diff --git a/.github/workflows/loopvc.yml b/.github/workflows/loopvc.yml new file mode 100644 index 00000000..dd4ce5e2 --- /dev/null +++ b/.github/workflows/loopvc.yml @@ -0,0 +1,64 @@ +name: loopvc + +# Generated loop obligations (Verify/Infer/loopvc): regenerates the pinned exports from the +# exported loop edges, discharges them with Verify/Discharge/discharge.sh and checks that a wrong +# invariant is rejected with a counterexample. + +on: + push: + branches: [main, "alpharush/loopvc-*"] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: loopvc-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + loopvc: + name: Loop obligations + runs-on: ubuntu-latest + timeout-minutes: 90 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install elan + run: | + curl -fsSL -o elan-init.sh \ + https://raw.githubusercontent.com/leanprover/elan/227caca133724d5516bee25c2aeb3e609478f2d8/elan-init.sh + sh elan-init.sh -y --default-toolchain none + rm elan-init.sh + echo "$HOME/.elan/bin" >> "$GITHUB_PATH" + + - name: Install z3 + run: | + curl -fsSL -o z3.zip \ + https://github.com/Z3Prover/z3/releases/download/z3-4.13.4/z3-4.13.4-x64-glibc-2.35.zip + echo "93f91f9c6f4a00a041c19fc7a74adc1f441c8244ce70d486e19abcd89c6a014b z3.zip" | sha256sum -c - + unzip -q z3.zip + mkdir -p "$HOME/.local/bin" + cp z3-4.13.4-x64-glibc-2.35/bin/z3 "$HOME/.local/bin/" + rm -rf z3.zip z3-4.13.4-x64-glibc-2.35 + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + + - name: Restore the discharge library build + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: Verify/Discharge/Reconstruct/.lake + key: loopvc-reconstruct-${{ hashFiles('Verify/Discharge/Reconstruct/lean-toolchain', 'Verify/Discharge/Reconstruct/lake-manifest.json', 'Verify/Discharge/Reconstruct/lakefile.lean', 'Verify/Obligation/**', 'Verify/Discharge/**/*.lean') }} + restore-keys: loopvc-reconstruct- + + - name: Build the discharge library + env: + LEAN_NUM_THREADS: "2" + run: cd Verify/Discharge/Reconstruct && lake build -KleanMemory=3000 + + - name: Check the generated loop obligations + env: + LEAN_NUM_THREADS: "1" + run: bash Verify/Infer/loopvc/check.sh "$RUNNER_TEMP/loopvc" diff --git a/.github/workflows/refinement.yml b/.github/workflows/refinement.yml new file mode 100644 index 00000000..792061d6 --- /dev/null +++ b/.github/workflows/refinement.yml @@ -0,0 +1,157 @@ +name: refinement + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: refinement-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + refinement: + name: Refinement + runs-on: ubuntu-latest + timeout-minutes: 240 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install elan + run: | + curl -fsSL -o elan-init.sh \ + https://raw.githubusercontent.com/leanprover/elan/227caca133724d5516bee25c2aeb3e609478f2d8/elan-init.sh + sh elan-init.sh -y --default-toolchain none + rm elan-init.sh + echo "$HOME/.elan/bin" >> "$GITHUB_PATH" + + - name: Cache solar, solc and Z3 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .cache + key: refinement-tools-${{ hashFiles('scripts/refinement/solar-rev', 'scripts/verify/uniswap_v2_spec-solar-rev', 'scripts/verify/uniswap_v2_stages-solar-rev', 'scripts/refinement/gen.sh', 'scripts/refinement/prove-rev', 'scripts/refinement/facts.sh') }} + + # Restored here and saved after the builds even when one fails or the runner stops, so a + # later run resumes where this one got to (the native objects of Mathlib and EthLib, which + # EthLib's precompiled modules need, take most of a cold build). + - name: Restore the Lake build + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .lake + key: refinement-lake-${{ hashFiles('lean-toolchain', 'lake-manifest.json') }}-${{ github.sha }} + restore-keys: refinement-lake-${{ hashFiles('lean-toolchain', 'lake-manifest.json') }}- + + # SolarTV and solar's generated stages and proofs live in this repository (tv/, Certified/), + # so the milestones build here with no solar checkout. solar's certify job regenerates + # Certified/ against a pinned commit of this repository and fails on any difference. + # In stages, two jobs at a time and each Lean process capped, so that the 16 GB runner does + # not run out of memory. + - name: Build SolarTV and the dependencies + env: + LEAN_NUM_THREADS: "2" + run: | + lake exe cache get || true + lake build -KleanMemory=3000 EvmRules SolarTV W1Proofs + + # Contracts.VerifyCounter.Source's kernel_rfl copies the type checker's closure; with the + # create2 additions its peak is about 2.9 GB, at the 3000 MB cap, so it builds first alone. + - name: Build the Certified contracts + env: + LEAN_NUM_THREADS: "2" + run: | + lake build -KleanMemory=4500 Contracts.VerifyCounter.Source + lake build -KleanMemory=3000 W1 counter w4 masks bank c4 mulx events reader verify_token verify_counter callsqrt arraymax + + - name: Build the verification libraries and Contracts + env: + LEAN_NUM_THREADS: "2" + run: | + lake build -KleanMemory=6000 Loom Verify VerifySpec VerifySpecTrustedBase VerifyLoom VerifyDischarge VerifyVC ContractsVC ContractsCounter ContractsArrayMaxVault ContractsVerifyCounter ContractsCallSqrt ContractsToken ContractsCallFamilies ContractsShapes ContractsCallSqrt + + # The Uniswap V2 port's sources and checked cores are generated from the pinned port, not + # committed (v2-core is GPL-3.0), so they are generated here before their build. + - name: Generate and check the Uniswap V2 port + env: + LEAN_NUM_THREADS: "2" + run: | + scripts/verify/uniswap_v2_gen.sh + lake build -KleanMemory=6000 ContractsUniswapV2 + # UniswapV2Pair's source acceptance in 22 generated stage modules; the largest (swap's + # lowering) peaks at 5.98 GB under -M 6000, so this step has little memory margin. + lake build -KleanMemory=6000 ContractsUniswapV2Pair + lake build -KleanMemory=6000 ContractsUniswapV2Factory + + # The ERC20 specs' connection needs solar-verify and solar's spec tooling + # (crates/verify/uniswap-v2, tools/certify/spec_connect.py) at the commit pinned in + # scripts/verify/uniswap_v2_spec-solar-rev. Its modules are generated, not committed, so + # they are generated here and then checked. + - name: Connect and check the Uniswap V2 ERC20 specs + env: + LEAN_NUM_THREADS: "2" + run: | + rev="$(tr -d '[:space:]' < scripts/verify/uniswap_v2_spec-solar-rev)" + dir=.cache/solar-spec + if [[ ! -x "$dir/target/release/solar-verify" || "$(git -C "$dir" rev-parse HEAD 2>/dev/null)" != "$rev" ]]; then + rm -rf "$dir"; git init -q "$dir" + git -C "$dir" remote add origin https://github.com/paradigmxyz/solar.git + git -C "$dir" fetch -q --depth 1 origin "$rev" + git -C "$dir" checkout -q --detach "$rev" + cargo build --release --locked --manifest-path "$dir/Cargo.toml" --bin solar-verify + fi + SOLAR_DIR="$dir" SOLAR_VERIFY="$dir/target/release/solar-verify" scripts/verify/uniswap_v2_spec.sh + lake build -KleanMemory=6000 ContractsUniswapV2ERC20Spec + + # UniswapV2ERC20.transfer's slice (docs/CERTIFICATION_TARGET.md): the source stage (E3), the + # backend stages for transfer's calls (E4), the bytes and gas certificates (E5, E8). The stages + # and certificates are compiled from the port by solar at the commit pinned in + # scripts/verify/uniswap_v2_stages-solar-rev, with its tools/certify, and checked here; they are + # not committed (the port is GPL-3.0). Every module is checked within 6 GB. + - name: Generate and check UniswapV2ERC20.transfer's slice + env: + LEAN_NUM_THREADS: "2" + run: | + scripts/verify/uniswap_v2_stages.sh + lake build -KleanMemory=6000 uv2_erc20 ContractsUniswapV2ERC20SourceMir + + # UniswapV2ERC20's approve and transferFrom: the source stage (E3) of each against the same + # stage0, its refused mutants and the slot-level posts. The trees, like the stages, come from the + # GPL-3.0 port and are generated here. Every module is checked within 6 GB. + - name: Generate and check UniswapV2ERC20's approve and transferFrom + env: + LEAN_NUM_THREADS: "2" + run: | + python3 scripts/verify/uniswap_v2_stage0_mutants.py + python3 scripts/verify/uniswap_v2_trees.py + lake build -KleanMemory=6000 uv2_erc20 ContractsUniswapV2ERC20Nested + + - name: Build SolidCore's refinement milestones + env: + LEAN_NUM_THREADS: "2" + run: | + lake build -KleanMemory=7000 SolidCore SolidCoreSolarW4 SolidCoreSolarC4 SolidCoreSolarMulX SolidCoreSolarBank SolidCoreSolarBankSource SolidCoreSolarTotality SolidCoreSolarAssemblyEnv SolidCoreSolarRunOracle SolidCoreSolarRevert SolidCoreSolarCreate ContractsC4Spec SolidCore.Refinement.Axioms.Audit SolidCore.Refinement.Axioms.Main SolidCore.Refinement.Axioms.C4 SolidCore.Refinement.Axioms.MulX SolidCore.Refinement.Axioms.W4 SolidCore.Refinement.Axioms.CounterGeneric SolidCore.Refinement.Axioms.Contracts SolidCore.Refinement.Axioms.Token SolidCore.Refinement.Axioms.VerifyCounter SolidCore.Refinement.Axioms.Lanes + + - name: Save the Lake build + if: always() + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .lake + key: refinement-lake-${{ hashFiles('lean-toolchain', 'lake-manifest.json') }}-${{ github.sha }} + + # Every headline's #print axioms, the sweep over their modules and the closure grep for + # sorry, native_decide, bv_decide and ofReduceBool. + - name: Audit the headlines' axioms + env: + AXIOM_MEMORY: "6000" + run: scripts/refinement/axiom-audit.sh + + - name: Check the refinement proofs and analysis facts + env: + # Each Z3 process may use up to 8 GB; the runner has 16 GB. + FACTS_JOBS: 1 + run: scripts/refinement/check.sh diff --git a/.gitignore b/.gitignore index e83fbcdf..1988fc45 100644 --- a/.gitignore +++ b/.gitignore @@ -7,9 +7,23 @@ tests/.foundry-suites/ *.olean *.ilean *.c +!vendor/evmyul/EvmYul/FFI/ffi.c *.o *.so *.dylib __pycache__/ tests/forge-harness/*/out/ tests/forge-harness/*/cache/ +/.cache/ + +# UniswapV2ERC20 gas slice: generated from the GPL-3.0 port (scripts/verify/uniswap_v2_gas.sh) +/Certified/uv2_erc20/gen/ +/Certified/uv2_erc20/uv2_erc20.sol +/Certified/uv2_erc20/CtxGas.lean +/Certified/uv2_erc20/ProofsT/ +/Certified/uv2_erc20/ProofsT.lean +/Certified/uv2_erc20/Ctx.lean +/Certified/uv2_erc20/CtxNeg.lean + +/Contracts/UniswapV2/ERC20/Runtime.lean +/Contracts/UniswapV2/ERC20/Nested/Trees.lean diff --git a/Certified/README.md b/Certified/README.md new file mode 100644 index 00000000..19e0ea39 --- /dev/null +++ b/Certified/README.md @@ -0,0 +1,14 @@ +# Certified: generated per-contract stages and proofs + +Each directory is one contract that solar's certify driver exported and proved, laid out as the +driver writes it: `/.sol` (the source), `options` (the compiler options), +`bytecode.hex`, `gen//*.lean` (the exported stages, modules `.gen..*`) +and `Proofs.lean`, `Proofs/**` (the backend proofs, modules `.Proofs.*`). `w1/` also holds +the `W1` checks of w1's stages. The `srcDir` of each library is `Certified`, so module names carry +no `Certified` prefix, as the solidity-lean refinement proofs import them. + +Only the contracts a headline theorem or milestone check here imports are committed: w1, w4, +counter, masks, c4, mulx, bank, events, reader, verify_token, verify_counter and callsqrt +(Uniswap v2-core's Math.sqrt loop entered through internal calls from two functions; its record +is MIR to EVM IR proved and the bytecode decoded, not end to end). Regenerate one with solar's certify +driver against this commit (solar's pin file names it); it rewrites the directory in place. diff --git a/Certified/abi_hash/Final.lean b/Certified/abi_hash/Final.lean new file mode 100644 index 00000000..60c9ab7c --- /dev/null +++ b/Certified/abi_hash/Final.lean @@ -0,0 +1,11 @@ +import abi_hash.Statement +import abi_hash.Shape + +-- Generated by solar's tools/certify/final.py; do not edit. The statement is +-- Certified.abi_hash.Final.Statement of abi_hash.Statement, which does not import the proof +-- module; the driver's checker requires `final`'s type to be exactly that constant. + +theorem Certified.abi_hash.Final.final : _root_.Certified.abi_hash.Final.Statement := + ⟨_root_.Certified.abi_hash.Final.bound, Certified.abi_hash.Shape.published⟩ + +#print axioms Certified.abi_hash.Final.final diff --git a/Certified/abi_hash/Proofs.lean b/Certified/abi_hash/Proofs.lean new file mode 100644 index 00000000..1b64098f --- /dev/null +++ b/Certified/abi_hash/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import abi_hash.Proofs.Stages +import abi_hash.Proofs.Assembly diff --git a/Certified/abi_hash/Proofs/Assembly.lean b/Certified/abi_hash/Proofs/Assembly.lean new file mode 100644 index 00000000..83b304d2 --- /dev/null +++ b/Certified/abi_hash/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Items +import abi_hash.gen.AbiHash.Evm4 +import abi_hash.gen.AbiHash.Bytecode + +/-! The final EVM IR of `AbiHash` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.AbiHash + +open SolarTV.Assembly SolarTV.Export.AbiHash SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm4).getD [] + +theorem items_eq : itemsOf evm4 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x2f else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.AbiHash.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.AbiHash.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms decodes + +end SolarTV.Milestone.AbiHash diff --git a/Certified/abi_hash/Proofs/Runs/Evm1.lean b/Certified/abi_hash/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..1a83bf86 --- /dev/null +++ b/Certified/abi_hash/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import abi_hash.gen.AbiHash.Evm1 +import abi_hash.gen.AbiHash.Sched + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.AbiHash + +open Machine SolarTV.Export.AbiHash SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 7 = EVM.Program.run o evm1 call 4 := by + sym_exec + +/-- info: 'SolarTV.Milestone.AbiHash.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.AbiHash diff --git a/Certified/abi_hash/Proofs/Runs/Evm2.lean b/Certified/abi_hash/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..d7bd7501 --- /dev/null +++ b/Certified/abi_hash/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import abi_hash.gen.AbiHash.Evm2 +import abi_hash.gen.AbiHash.Evm1 + +/-! `share-reverts`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.AbiHash + +open Machine SolarTV.Export.AbiHash SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 4 = EVM.Program.run o evm2 call 4 := by + sym_exec + +/-- info: 'SolarTV.Milestone.AbiHash.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.AbiHash diff --git a/Certified/abi_hash/Proofs/Runs/Evm3.lean b/Certified/abi_hash/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..3ab53834 --- /dev/null +++ b/Certified/abi_hash/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import abi_hash.gen.AbiHash.Evm3 +import abi_hash.gen.AbiHash.Evm2 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.AbiHash + +open Machine SolarTV.Export.AbiHash SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 4 = EVM.Program.run o evm3 call 4 := by + sym_exec + +/-- info: 'SolarTV.Milestone.AbiHash.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.AbiHash diff --git a/Certified/abi_hash/Proofs/Runs/Evm4.lean b/Certified/abi_hash/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..033ec4f5 --- /dev/null +++ b/Certified/abi_hash/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import abi_hash.gen.AbiHash.Evm4 +import abi_hash.gen.AbiHash.Evm3 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.AbiHash + +open Machine SolarTV.Export.AbiHash SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 4 = EVM.Program.run o evm4 call 2 := by + sym_exec + +/-- info: 'SolarTV.Milestone.AbiHash.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.AbiHash diff --git a/Certified/abi_hash/Proofs/Runs/Mir1.lean b/Certified/abi_hash/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..d9f77402 --- /dev/null +++ b/Certified/abi_hash/Proofs/Runs/Mir1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import abi_hash.gen.AbiHash.Mir1 +import abi_hash.gen.AbiHash.Stage0 + +/-! `evm-inst-schedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.AbiHash + +open Machine SolarTV.Export.AbiHash SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir1_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 7 = MIR.Lowered.Module.run o mir1 call 7 := by + sym_exec + +/-- info: 'SolarTV.Milestone.AbiHash.mir1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_run + +end SolarTV.Milestone.AbiHash diff --git a/Certified/abi_hash/Proofs/Runs/Sched.lean b/Certified/abi_hash/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..32a814bf --- /dev/null +++ b/Certified/abi_hash/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import abi_hash.gen.AbiHash.Sched +import abi_hash.gen.AbiHash.Mir1 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.AbiHash + +open Machine SolarTV.Export.AbiHash SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir1 call 7 = EVM.Program.run o sched call 7 := by + sym_exec + +/-- info: 'SolarTV.Milestone.AbiHash.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.AbiHash diff --git a/Certified/abi_hash/Proofs/Runs/Stage0.lean b/Certified/abi_hash/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..951fcd06 --- /dev/null +++ b/Certified/abi_hash/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import abi_hash.gen.AbiHash.Stage0 + +/-! The first lowered MIR ends on every call within 7 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.AbiHash + +open Machine SolarTV.Export.AbiHash SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 7).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.AbiHash.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.AbiHash diff --git a/Certified/abi_hash/Proofs/Stages.lean b/Certified/abi_hash/Proofs/Stages.lean new file mode 100644 index 00000000..60474588 --- /dev/null +++ b/Certified/abi_hash/Proofs/Stages.lean @@ -0,0 +1,115 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import abi_hash.Proofs.Runs.Stage0 +import abi_hash.Proofs.Runs.Mir1 +import abi_hash.Proofs.Runs.Sched +import abi_hash.Proofs.Runs.Evm1 +import abi_hash.Proofs.Runs.Evm2 +import abi_hash.Proofs.Runs.Evm3 +import abi_hash.Proofs.Runs.Evm4 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `AbiHash`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm4`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.AbiHash + +open Machine SolarTV.Export.AbiHash SolarTV.Milestone.W1 + +/-- `evm-inst-schedule`: stage0 to mir1. -/ +theorem stage_mir1 (o : Oracle) : Stage (mirSem o) (mirSem o) stage0 mir1 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 7 7 (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +theorem mir1_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir1 call 7).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := stage0) (q := mir1) (n := 7) (m := 7) (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +/-- `stack-schedule`: mir1 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) mir1 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 7 7 (mir1_ends o) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 7).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := mir1) (q := sched) (n := 7) (m := 7) (mir1_ends o) + (fun call _ => sched_run o call) + +/-- `cfg-simplify-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 7 4 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 4).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 7) (m := 4) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `share-reverts`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 4 4 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 4).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 4) (m := 4) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `terminal-dedup`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 4 4 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 4).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 4) (m := 4) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `cfg-simplify-early`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 4 2 (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1], sched, [evm1, evm2, evm3, evm4]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem abi_hash_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm4 anyCall := + mir_to_evmir o anyCall compilation ⟨stage_mir1 o, trivial⟩ (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.AbiHash.stage_mir1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir1 + +/-- info: 'SolarTV.Milestone.AbiHash.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.AbiHash.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.AbiHash.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.AbiHash.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.AbiHash.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.AbiHash.abi_hash_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms abi_hash_mir_to_evmir + +end SolarTV.Milestone.AbiHash diff --git a/Certified/abi_hash/Shape.lean b/Certified/abi_hash/Shape.lean new file mode 100644 index 00000000..d9995e19 --- /dev/null +++ b/Certified/abi_hash/Shape.lean @@ -0,0 +1,109 @@ +import Verify.ShapeGeneric +import SolidCore.Refinement.Solar.AbiHash.Lowering +import abi_hash.Proofs.Stages +import abi_hash.gen.AbiHash.Bytecode + +-- Generated by solar's tools/certify/shape_gen.py from abi_hash/shape.json and this run's export; +-- do not edit. Untrusted data and composition: the kernel re-derives every claim. + +/-! +# AbiHash: the proof of the published statement + +`published` applies `SolidCore.Refinement.Shapes.compiled` to the source check of `SolidCore.Refinement.Solar.AbiHash`, solar-tv's backend +stages to `evm4` (`SolarTV.Milestone.AbiHash.abi_hash_mir_to_evmir`), the final EVM IR's run within 2 blocks on every +call (the last stage's fuel) and the loop checker on the exact bytecode, with the certificate +tools/certify/asm_cert.py inferred. The gas bound is `gasBoundL cert 2` = 22100 · (2 · 32) + 6 += 1414406, at most the statement's 10000000. +-/ + +namespace Certified.abi_hash.Shape + +open SolidCore.Refinement SolidCore.Refinement.Solar SolarTV + +/-- The exported runtime bytecode. -/ +def code : ByteArray := ⟨(SolarTV.Export.AbiHash.bytecode.map UInt8.ofNat).toArray⟩ + +/-- The loop checker's certificate (tools/certify/asm_cert.py). -/ +def cert : SolidCore.Refinement.Solar.Assemble.Cert := + { offsets := [0x0, 0x2f], + needs := [0, 0], + top := 64, + turned := [], + costs := [32, 3], + types := [[], + []], + rets := [], + env := true, + reads := false } + +/-- The highest stack each block is entered with. -/ +def maxs : List Nat := [0, 1] + +set_option maxRecDepth 100000 in +theorem walk_ok : (SolarTV.Assembly.walk (SolidCore.Refinement.Solar.Assemble.bytesOf code) cert.offset 0 + (SolidCore.Refinement.Solar.Assemble.lower SolarTV.Export.AbiHash.evm4 cert)).isSome = true := by + have hw := SolidCore.Refinement.Solar.Assemble.walkS_drop (SolidCore.Refinement.Solar.Assemble.bytesOf code) cert.offset (SolidCore.Refinement.Solar.Assemble.lower SolarTV.Export.AbiHash.evm4 cert) 0 + (Nat.zero_le _) + rw [List.drop_zero] at hw + rw [← hw] + decide +kernel + +set_option maxRecDepth 100000 in +theorem blocks_ok : SolidCore.Refinement.Solar.AssembleLoop.blocksOkL SolarTV.Export.AbiHash.evm4 cert maxs 0 SolarTV.Export.AbiHash.evm4.blocks = true := by + decide +kernel + +theorem labels_ok : SolidCore.Refinement.Solar.Assemble.labelsValid SolarTV.Export.AbiHash.evm4 cert code = true := + SolidCore.Refinement.Solar.Assemble.labelsValid_of_walk walk_ok + +theorem size_ok : code.size < 2 ^ 32 := by decide +kernel + +/-- The checker of code with loops accepts the exact bytecode for the final EVM IR. -/ +theorem check_ok : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.AbiHash.evm4 code cert maxs = true := by + simp only [SolidCore.Refinement.Solar.AssembleLoop.checkL, walk_ok, blocks_ok, labels_ok, decide_eq_true size_ok, Bool.and_true, + Bool.true_and] + decide + +/-- The final EVM IR ends within 2 blocks on every call, under the bytecode's oracle. -/ +theorem ends (call : Call) : (EVM.Program.run SolidCore.Refinement.Shapes.oracle SolarTV.Export.AbiHash.evm4 call 2).isSome = true := + SolarTV.Milestone.W1.ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := SolidCore.Refinement.Shapes.oracle) (p := SolarTV.Export.AbiHash.evm3) (q := SolarTV.Export.AbiHash.evm4) (n := 4) (m := 2) + (SolarTV.Milestone.AbiHash.evm3_ends SolidCore.Refinement.Shapes.oracle) (fun call _ => SolarTV.Milestone.AbiHash.evm4_run SolidCore.Refinement.Shapes.oracle call) call trivial + +/-- The bytecode with byte `i` replaced by `b`. -/ +def mutant (i b : Nat) : ByteArray := ⟨((SolarTV.Export.AbiHash.bytecode.set i b).map UInt8.ofNat).toArray⟩ + +set_option maxRecDepth 100000 in +/-- The checker rejects the bytecode with a jump target moved (byte 2). -/ +theorem rejects_jump : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.AbiHash.evm4 (mutant 2 48) cert maxs = false := by + decide +kernel + +theorem gas_lt : SolidCore.Refinement.Solar.AssembleLoop.gasBoundL cert 2 < 2 ^ 64 := by decide +kernel + +theorem gas_le : SolidCore.Refinement.Solar.AssembleLoop.gasBoundL cert 2 ≤ 10000000 := by decide +kernel + +/-- SolidCore type checks the contract. -/ +theorem contract_ok : ∃ c, SolidCore.Refinement.Solar.AbiHash.contract? = .ok c := by + have h := SolidCore.Refinement.Solar.AbiHash.shape_eq + unfold SolidCore.Refinement.Solar.AbiHash.shape? at h + split at h + · next c hc => exact ⟨c, hc⟩ + · simp at h + + +/-- **What the published statement asks of this module.** -/ +theorem published : ∃ c, SolidCore.Refinement.Solar.AbiHash.contract? = .ok c ∧ + SolidCore.Refinement.Shapes.Compiled (solidCore SolidCore.Refinement.Solar.AbiHash.fuel) c code (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.AbiHash.fns) ([])) (fun _ => 10000000) := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, d, hd⟩ := SolidCore.Refinement.Solar.AbiHash.deployed_of hc + have hchk := SolidCore.Refinement.Solar.AbiHash.check_stage0 + rw [← hk] at hchk + have hval := SolidCore.Refinement.Solar.AbiHash.checkValue_stage0 + rw [← hk] at hval + exact ⟨c, hc, (SolidCore.Refinement.Shapes.compiled hd hchk hval (SolidCore.Refinement.Shapes.genericValid_inhabited _ _ _) + (SolarTV.Milestone.AbiHash.abi_hash_mir_to_evmir SolidCore.Refinement.Shapes.oracle) (fun _ _ => trivial) ends check_ok gas_lt).mono_gas (fun _ => gas_le) (fun _ => by decide)⟩ + +/-- info: 'Certified.abi_hash.Shape.published' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms published + +end Certified.abi_hash.Shape diff --git a/Certified/abi_hash/Statement.lean b/Certified/abi_hash/Statement.lean new file mode 100644 index 00000000..251c47ff --- /dev/null +++ b/Certified/abi_hash/Statement.lean @@ -0,0 +1,43 @@ +import Verify.Shapes +import Verify.ShapeGeneric +import abi_hash.gen.AbiHash.Bytecode +import SolidCore.Refinement.Solar.AbiHash.Lowering + +-- Generated by solar's tools/certify/final.py from abi_hash/shape.json and the bytecode the +-- driver compiled in this run; do not edit. This module never imports the proof module. + +/-! +# AbiHash: the published statement + +`Statement` binds the exact runtime bytecode (`runtimeHex`, from the driver's own compile) and +states _root_.SolidCore.Refinement.Shapes.Compiled of it against the checked source on the declared valid calls. +-/ + +namespace Certified.abi_hash.Final + +/-- The runtime bytecode the pinned solar emitted in this run, as hex (for the reader). -/ +def runtimeHex : String := + "34602f575f3560e01c806366d82b2b03602f5760443610602f576004355f5260243560205260405f205f5260205ff35b5f5ffd" + +/-- The same bytes, as numbers: what the statement binds. -/ +def runtimeBytes : List Nat := + [0x34, 0x60, 0x2f, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x66, 0xd8, 0x2b, 0x2b, 0x3, + 0x60, 0x2f, 0x57, 0x60, 0x44, 0x36, 0x10, 0x60, 0x2f, 0x57, 0x60, 0x4, 0x35, 0x5f, 0x52, 0x60, + 0x24, 0x35, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, + 0x5f, 0x5f, 0xfd] + +/-- The freshly exported bytecode the obligations speak of. -/ +def code : ByteArray := ⟨(_root_.SolarTV.Export.AbiHash.bytecode.map UInt8.ofNat).toArray⟩ + +/-- **The published statement.** -/ +def Statement : Prop := + _root_.Certified.abi_hash.Final.code.data.toList.map (·.toNat) = _root_.Certified.abi_hash.Final.runtimeBytes ∧ + (∃ c, SolidCore.Refinement.Solar.AbiHash.contract? = .ok c ∧ + _root_.SolidCore.Refinement.Shapes.Compiled (_root_.SolidCore.Refinement.solidCore (SolidCore.Refinement.Solar.AbiHash.fuel)) c _root_.Certified.abi_hash.Final.code + (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.AbiHash.fns) ([])) (fun _ => 10000000)) + +set_option maxRecDepth 100000 in +theorem bound : _root_.Certified.abi_hash.Final.code.data.toList.map (·.toNat) = _root_.Certified.abi_hash.Final.runtimeBytes := + @of_decide_eq_true _ (instDecidableEqList _ _) (by decide +kernel) + +end Certified.abi_hash.Final diff --git a/Certified/abi_hash/abi_hash.sol b/Certified/abi_hash/abi_hash.sol new file mode 100644 index 00000000..f8d44f88 --- /dev/null +++ b/Certified/abi_hash/abi_hash.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +contract AbiHash { + function hashPair(uint256 a, uint256 b) external pure returns (uint256) { + return uint256(keccak256(abi.encode(a, b))); + } +} diff --git a/Certified/abi_hash/bytecode.hex b/Certified/abi_hash/bytecode.hex new file mode 100644 index 00000000..3f13f5e8 --- /dev/null +++ b/Certified/abi_hash/bytecode.hex @@ -0,0 +1 @@ +34602f575f3560e01c806366d82b2b03602f5760443610602f576004355f5260243560205260405f205f5260205ff35b5f5ffd diff --git a/Certified/abi_hash/gen/AbiHash/Bytecode.lean b/Certified/abi_hash/gen/AbiHash/Bytecode.lean new file mode 100644 index 00000000..97a8a4dc --- /dev/null +++ b/Certified/abi_hash/gen/AbiHash/Bytecode.lean @@ -0,0 +1,17 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `AbiHash`; do not edit. -/ + +namespace SolarTV.Export.AbiHash + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x2f, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x66, 0xd8, 0x2b, 0x2b, 0x03, + 0x60, 0x2f, 0x57, 0x60, 0x44, 0x36, 0x10, 0x60, 0x2f, 0x57, 0x60, 0x04, 0x35, 0x5f, 0x52, 0x60, + 0x24, 0x35, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, + 0x5f, 0x5f, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "34602f575f3560e01c806366d82b2b03602f5760443610602f576004355f5260243560205260405f205f5260205ff35b5f5ffd" + +end SolarTV.Export.AbiHash diff --git a/Certified/abi_hash/gen/AbiHash/Evm1.lean b/Certified/abi_hash/gen/AbiHash/Evm1.lean new file mode 100644 index 00000000..0a9740bc --- /dev/null +++ b/Certified/abi_hash/gen/AbiHash/Evm1.lean @@ -0,0 +1,53 @@ +-- solar-lean-stage: kind=evm index=1 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `AbiHash`; do not edit. -/ + +namespace SolarTV.Export.AbiHash + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x66d82b2b)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb6 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.AbiHash diff --git a/Certified/abi_hash/gen/AbiHash/Evm2.lean b/Certified/abi_hash/gen/AbiHash/Evm2.lean new file mode 100644 index 00000000..83b59f28 --- /dev/null +++ b/Certified/abi_hash/gen/AbiHash/Evm2.lean @@ -0,0 +1,53 @@ +-- solar-lean-stage: kind=evm index=2 pass=share-reverts +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `AbiHash`; do not edit. -/ + +namespace SolarTV.Export.AbiHash + +/-- The runtime EVM IR after `share-reverts`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x66d82b2b)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb6 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.AbiHash diff --git a/Certified/abi_hash/gen/AbiHash/Evm3.lean b/Certified/abi_hash/gen/AbiHash/Evm3.lean new file mode 100644 index 00000000..03fe1295 --- /dev/null +++ b/Certified/abi_hash/gen/AbiHash/Evm3.lean @@ -0,0 +1,51 @@ +-- solar-lean-stage: kind=evm index=3 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `AbiHash`; do not edit. -/ + +namespace SolarTV.Export.AbiHash + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x66d82b2b)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb6 + [.jump 1]] } + +end SolarTV.Export.AbiHash diff --git a/Certified/abi_hash/gen/AbiHash/Evm4.lean b/Certified/abi_hash/gen/AbiHash/Evm4.lean new file mode 100644 index 00000000..3fd96ebe --- /dev/null +++ b/Certified/abi_hash/gen/AbiHash/Evm4.lean @@ -0,0 +1,47 @@ +-- solar-lean-stage: kind=evm index=4 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `AbiHash`; do not edit. -/ + +namespace SolarTV.Export.AbiHash + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x66d82b2b)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.AbiHash diff --git a/Certified/abi_hash/gen/AbiHash/Manifest.lean b/Certified/abi_hash/gen/AbiHash/Manifest.lean new file mode 100644 index 00000000..1431f4c3 --- /dev/null +++ b/Certified/abi_hash/gen/AbiHash/Manifest.lean @@ -0,0 +1,42 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `AbiHash`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.AbiHash.Manifest + +def sources : List (String × String) := + [("Certified/abi_hash/abi_hash.sol", "330f02c0291e970c20831975c0a05fa106ef10e8a8fda640f42b703aa47059a5")] + +def compiler : String := "0.8.38+commit.38b5232a.solar.0.3.0-dev" + +def arguments : List String := + ["Certified/abi_hash/abi_hash.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/abi_hash/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "ad37dc2c35b0f3fbe955e35bd8863587fc94881f2071557c6eda360f380450a5"), + ("Mir1", "mir1", "evm-inst-schedule", "5a3e6459f69279bac88f2b3833ba833542d074453423fc3d6a35452a6d1891cf"), + ("Sched", "sched", "stack-schedule", "6d9327f0240ff6e6550603675fac64a6582e2499ab328f62fa5277311b521305"), + ("Evm1", "evm1", "cfg-simplify-early", "4929e76ced8a279f12fdf31c1a21023beaf43d366656288a3b3988c8849dc54c"), + ("Evm2", "evm2", "share-reverts", "511632cd6e447d01f682069e3ff88568d8846325c2c763f151da22bf3c4c21cf"), + ("Evm3", "evm3", "terminal-dedup", "84eafe240fc117c8aaec8a238c5333b7f89dc6140c0e8ff3d4b1ffef274b8aa2"), + ("Evm4", "evm4", "cfg-simplify-early", "9fa4f065aa12373d79e10fded303e284d8b83e5ecc5f99bcf6a424fffa05df94"), + ("Bytecode", "bytecode", "assemble", "d3114e9ecdb0e711442668f42b64d8feb2e30bff4fa9528f9e243e0d0a934105")] + +def bytecodeHex : String := + "34602f575f3560e01c806366d82b2b03602f5760443610602f576004355f5260243560205260405f205f5260205ff35b5f5ffd" + +def bytecodeSha256 : String := "4ebf12dcd2d28ab92d3b72bb17f68f6da9eb5f46b8b6deba620d0fda68a3f31f" + +end SolarTV.Export.AbiHash.Manifest diff --git a/Certified/abi_hash/gen/AbiHash/Mir1.lean b/Certified/abi_hash/gen/AbiHash/Mir1.lean new file mode 100644 index 00000000..6d615d6c --- /dev/null +++ b/Certified/abi_hash/gen/AbiHash/Mir1.lean @@ -0,0 +1,55 @@ +-- solar-lean-stage: kind=mir index=1 pass=evm-inst-schedule +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `AbiHash`; do not edit. -/ + +namespace SolarTV.Export.AbiHash + +/-- The lowered MIR module after `evm-inst-schedule`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @hashPair + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 14) .calldatasize [], + .pure 16 .lt [.value 14, .const 68]], + .branch (.value 16) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 20) .calldataload [.const 36], + .effect (some 18) .calldataload [.const 4], + .effect none .mstore [.const 0, .value 18], + .effect none .mstore [.const 32, .value 20], + .effect (some 12) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 12]], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x66d82b2b, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.AbiHash diff --git a/Certified/abi_hash/gen/AbiHash/Sched.lean b/Certified/abi_hash/gen/AbiHash/Sched.lean new file mode 100644 index 00000000..3bf518ee --- /dev/null +++ b/Certified/abi_hash/gen/AbiHash/Sched.lean @@ -0,0 +1,59 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `AbiHash`; do not edit. -/ + +namespace SolarTV.Export.AbiHash + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 3, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x66d82b2b)), + .op (.stack .eq), + .jumpi 2, + .jump 3], + -- bb2 + [.jump 4], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 6, + .jump 5], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb6 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.AbiHash diff --git a/Certified/abi_hash/gen/AbiHash/Schedule.json b/Certified/abi_hash/gen/AbiHash/Schedule.json new file mode 100644 index 00000000..7a6c4a9f --- /dev/null +++ b/Certified/abi_hash/gen/AbiHash/Schedule.json @@ -0,0 +1,17 @@ +{ + "functions": [ + {"function": 1, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [3, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 0, "entry": 4, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [4, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [6, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [5, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]} + ] +} diff --git a/Certified/abi_hash/gen/AbiHash/Stage0.lean b/Certified/abi_hash/gen/AbiHash/Stage0.lean new file mode 100644 index 00000000..edbe4f40 --- /dev/null +++ b/Certified/abi_hash/gen/AbiHash/Stage0.lean @@ -0,0 +1,55 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `AbiHash`; do not edit. -/ + +namespace SolarTV.Export.AbiHash + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @hashPair + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 14) .calldatasize [], + .pure 16 .lt [.value 14, .const 68]], + .branch (.value 16) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 18) .calldataload [.const 4], + .effect (some 20) .calldataload [.const 36], + .effect none .mstore [.const 0, .value 18], + .effect none .mstore [.const 32, .value 20], + .effect (some 12) .keccak256 [.const 0, .const 64], + .effect none .mstore [.const 0, .value 12]], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x66d82b2b, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.AbiHash diff --git a/Certified/abi_hash/gen/AbiHash/manifest.json b/Certified/abi_hash/gen/AbiHash/manifest.json new file mode 100644 index 00000000..e957bb2f --- /dev/null +++ b/Certified/abi_hash/gen/AbiHash/manifest.json @@ -0,0 +1,89 @@ +{ + "arguments": [ + "Certified/abi_hash/abi_hash.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/abi_hash/gen" + ], + "bytecode": "34602f575f3560e01c806366d82b2b03602f5760443610602f576004355f5260243560205260405f205f5260205ff35b5f5ffd", + "bytecode_sha256": "4ebf12dcd2d28ab92d3b72bb17f68f6da9eb5f46b8b6deba620d0fda68a3f31f", + "compiler": "0.8.38+commit.38b5232a.solar.0.3.0-dev", + "contract": "AbiHash", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"Certified/abi_hash/abi_hash.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/abi_hash/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/abi_hash/gen\"), keep_asts: false, forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "Certified/abi_hash/abi_hash.sol", + "sha256": "330f02c0291e970c20831975c0a05fa106ef10e8a8fda640f42b703aa47059a5" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "ad37dc2c35b0f3fbe955e35bd8863587fc94881f2071557c6eda360f380450a5" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "evm-inst-schedule", + "sha256": "5a3e6459f69279bac88f2b3833ba833542d074453423fc3d6a35452a6d1891cf" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "6d9327f0240ff6e6550603675fac64a6582e2499ab328f62fa5277311b521305" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "4929e76ced8a279f12fdf31c1a21023beaf43d366656288a3b3988c8849dc54c" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "share-reverts", + "sha256": "511632cd6e447d01f682069e3ff88568d8846325c2c763f151da22bf3c4c21cf" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "84eafe240fc117c8aaec8a238c5333b7f89dc6140c0e8ff3d4b1ffef274b8aa2" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "9fa4f065aa12373d79e10fded303e284d8b83e5ecc5f99bcf6a424fffa05df94" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "d3114e9ecdb0e711442668f42b64d8feb2e30bff4fa9528f9e243e0d0a934105" + } + ] +} diff --git a/Certified/abi_hash/options b/Certified/abi_hash/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/abi_hash/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/abi_hash/record.json b/Certified/abi_hash/record.json new file mode 100644 index 00000000..16c84901 --- /dev/null +++ b/Certified/abi_hash/record.json @@ -0,0 +1,111 @@ +{ + "contract": "AbiHash", + "name": "abi_hash", + "source": "Certified/abi_hash/abi_hash.sol", + "bytecode": "34602f575f3560e01c806366d82b2b03602f5760443610602f576004355f5260243560205260405f205f5260205ff35b5f5ffd", + "solar": "38b5232add998cd34a311c8cecf5737d38f9cce6", + "solidity_lean": "5d51a4c04354aa2e44f65d475a376aac693fc12c", + "mir_to_evmir": "proved: SolarTV.Milestone.AbiHash.abi_hash_mir_to_evmir", + "assembly": "executed: inside the published statement Certified.abi_hash.Final.final (Shapes.Equiv and Resources over Target.runWith of the exact bytes); Proofs/: decoded only: abi_hash.Proofs.Assembly (the bytecode decodes to the final EVM IR's instructions; no execution theorem)", + "vc": "exported to .lake/certify/abi_hash/VC.lean", + "end_to_end": "not proved", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, a field of Shapes.Compiled)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with any status (no specification declares the allowed ones); the bytecode too, at gas from the bound on", + "spec": "none: solar-verify has no specification of abi_hash", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result", + "vacuity": "not applicable (no specification)", + "assumptions": "none beyond the statement's scope", + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "hash: the bytecode's KECCAK256 is EthLib's Keccak-256 (the statement's oracle), the same function SolidCore applies to the ABI encoding; no injectivity or separation is assumed", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: hashPair(uint256,uint256) ABI-encoded with clean argument words, any value below 2^256 (not payable: the value reverts on both sides), any storage; other call data is outside the statement", + "spec: none (solar-verify has no specification of abi_hash): equivalence, termination and resources only" + ], + "environment": "fixed, not quantified: one frame, caller 0x2000, the contract at 0x1000, the block and transaction of Target.message", + "provenance": "the solidity-lean checkout is not its commit: changed: lakefile.lean;untracked or ignored: .cache/solc-0.8.35;untracked or ignored: Certified/abi_hash/Proofs.lean;untracked or ignored: Certified/abi_hash/abi_hash.sol;untracked or ignored: Certified/abi_hash/bytecode.hex;; the starting build directory is trusted, not rebuilt from source (CERTIFY_CLEAN_BUILD=1)", + "strongest": false, + "source": "SolidCore/Refinement/Source/AbiHash.lean is the front end's AST of AbiHash in Certified/abi_hash/abi_hash.sol (solc 0.8.35)" + }, + "final": { + "module": "abi_hash.Final", + "statement_module": "abi_hash.Statement", + "theorem": "Certified.abi_hash.Final.final", + "kind": "compiled", + "statement": "_root_.Certified.abi_hash.Final.code.data.toList.map (·.toNat) = _root_.Certified.abi_hash.Final.runtimeBytes ∧ (∃ c, SolidCore.Refinement.Solar.AbiHash.contract? = .ok c ∧ _root_.SolidCore.Refinement.Shapes.Compiled (_root_.SolidCore.Refinement.solidCore (SolidCore.Refinement.Solar.AbiHash.fuel)) c _root_.Certified.abi_hash.Final.code (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.AbiHash.fns) ([])) (fun _ => 10000000))", + "nonvacuous": null, + "vacuity": null, + "allowed_vacuity": null, + "spec_bound_to_export": null, + "assumptions": [], + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "hash: the bytecode's KECCAK256 is EthLib's Keccak-256 (the statement's oracle), the same function SolidCore applies to the ABI encoding; no injectivity or separation is assumed", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: hashPair(uint256,uint256) ABI-encoded with clean argument words, any value below 2^256 (not payable: the value reverts on both sides), any storage; other call data is outside the statement", + "spec: none (solar-verify has no specification of abi_hash): equivalence, termination and resources only" + ], + "spec": "none: solar-verify has no specification of abi_hash", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, a field of Shapes.Compiled)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with any status (no specification declares the allowed ones); the bytecode too, at gas from the bound on", + "spec": "none: solar-verify has no specification of abi_hash", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result", + "vacuity": "not applicable (no specification)" + }, + "strongest": false + }, + "end_to_end_statement": {}, + "binding": {}, + "hypotheses": {}, + "refused": [], + "vacuous": "not applicable (no specification)", + "vc_vacuous": "not checked", + "source_ast": "SolidCore/Refinement/Source/AbiHash.lean is the front end's AST of AbiHash in Certified/abi_hash/abi_hash.sol (solc 0.8.35)", + "assembly_statement": null, + "assembly_hypotheses": null, + "negative_tests": true, + "caveats": [ + "solidity-lean at 5d51a4c04354aa2e44f65d475a376aac693fc12c, not the pinned 7aedd6330678291a0d13a465ddd398a7990de3a3", + "provenance: the solidity-lean checkout is not its commit: changed: lakefile.lean;untracked or ignored: .cache/solc-0.8.35;untracked or ignored: Certified/abi_hash/Proofs.lean;untracked or ignored: Certified/abi_hash/abi_hash.sol;untracked or ignored: Certified/abi_hash/bytecode.hex;", + "provenance: the starting build directory is trusted, not rebuilt from source (CERTIFY_CLEAN_BUILD=1)", + "not end to end: solidity-lean states no source or spec theorem for abi_hash" + ], + "backend": { + "theorem": { + "module": "abi_hash.Final", + "statement_module": "abi_hash.Statement", + "theorem": "Certified.abi_hash.Final.final", + "kind": "compiled", + "statement": "_root_.Certified.abi_hash.Final.code.data.toList.map (·.toNat) = _root_.Certified.abi_hash.Final.runtimeBytes ∧ (∃ c, SolidCore.Refinement.Solar.AbiHash.contract? = .ok c ∧ _root_.SolidCore.Refinement.Shapes.Compiled (_root_.SolidCore.Refinement.solidCore (SolidCore.Refinement.Solar.AbiHash.fuel)) c _root_.Certified.abi_hash.Final.code (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.AbiHash.fns) ([])) (fun _ => 10000000))", + "nonvacuous": null, + "vacuity": null, + "allowed_vacuity": null, + "spec_bound_to_export": null, + "assumptions": [], + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "hash: the bytecode's KECCAK256 is EthLib's Keccak-256 (the statement's oracle), the same function SolidCore applies to the ABI encoding; no injectivity or separation is assumed", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: hashPair(uint256,uint256) ABI-encoded with clean argument words, any value below 2^256 (not payable: the value reverts on both sides), any storage; other call data is outside the statement", + "spec: none (solar-verify has no specification of abi_hash): equivalence, termination and resources only" + ], + "spec": "none: solar-verify has no specification of abi_hash", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, a field of Shapes.Compiled)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with any status (no specification declares the allowed ones); the bytecode too, at gas from the bound on", + "spec": "none: solar-verify has no specification of abi_hash", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result", + "vacuity": "not applicable (no specification)" + }, + "strongest": false + } + } +} diff --git a/Certified/abi_hash/shape.json b/Certified/abi_hash/shape.json new file mode 100644 index 00000000..1214998b --- /dev/null +++ b/Certified/abi_hash/shape.json @@ -0,0 +1,38 @@ +{ + "kind": "compiled", + "contract": "SolidCore.Refinement.Solar.AbiHash.contract?", + "fuel": "SolidCore.Refinement.Solar.AbiHash.fuel", + "valid": "SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.AbiHash.fns) ([])", + "gas": "fun _ => 10000000", + "env": [], + "spec": "none: solar-verify has no specification of abi_hash", + "spec_modules": [ + "SolidCore.Refinement.Solar.AbiHash.Lowering", + "Verify.ShapeGeneric" + ], + "proof_module": "abi_hash.Shape", + "proof": "Certified.abi_hash.Shape.published", + "generic": { + "lowering": "SolidCore.Refinement.Solar.AbiHash.Lowering", + "ns": "SolidCore.Refinement.Solar.AbiHash", + "style": "core", + "check": "check_stage0", + "check_value": "checkValue_stage0", + "fns": "SolidCore.Refinement.Solar.AbiHash.fns", + "storage": "[]" + }, + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "hash: the bytecode's KECCAK256 is EthLib's Keccak-256 (the statement's oracle), the same function SolidCore applies to the ABI encoding; no injectivity or separation is assumed", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: hashPair(uint256,uint256) ABI-encoded with clean argument words, any value below 2^256 (not payable: the value reverts on both sides), any storage; other call data is outside the statement", + "spec: none (solar-verify has no specification of abi_hash): equivalence, termination and resources only" + ], + "source_ast": { + "file": "SolidCore/Refinement/Source/AbiHash.lean", + "namespace": "SolidCore.Refinement.Source.AbiHash", + "contract": "AbiHash" + } +} diff --git a/Certified/arraymax/Proofs.lean b/Certified/arraymax/Proofs.lean new file mode 100644 index 00000000..b9da08a8 --- /dev/null +++ b/Certified/arraymax/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import arraymax.Proofs.Stages +import arraymax.Proofs.Assembly diff --git a/Certified/arraymax/Proofs/Assembly.lean b/Certified/arraymax/Proofs/Assembly.lean new file mode 100644 index 00000000..d076d2e0 --- /dev/null +++ b/Certified/arraymax/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Items +import arraymax.gen.ArrayMaxEntry.Evm15 +import arraymax.gen.ArrayMaxEntry.Bytecode + +/-! The final EVM IR of `ArrayMaxEntry` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.Arraymax + +open SolarTV.Assembly SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm15).getD [] + +theorem items_eq : itemsOf evm15 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x13 else if label = 2 then 0x17 else if label = 3 then 0x2c else if label = 4 then 0xbc else if label = 5 then 0xed else if label = 6 then 0x10e else if label = 7 then 0x124 else if label = 8 then 0x13c else if label = 9 then 0x151 else if label = 10 then 0x16c else if label = 11 then 0x181 else if label = 12 then 0x1b6 else if label = 13 then 0x1d0 else if label = 14 then 0x1e8 else if label = 15 then 0x1ff else if label = 16 then 0x219 else if label = 17 then 0x236 else if label = 18 then 0x253 else if label = 19 then 0x268 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.Arraymax.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.Arraymax.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms decodes + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Evm1.lean b/Certified/arraymax/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..fc949627 --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Evm1.lean @@ -0,0 +1,101 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Evm1 +import arraymax.gen.ArrayMaxEntry.Sched + +/-! `peephole-early`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm1_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 14 + +theorem evm1_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm1_cutA (b, st, s) = (b == 14) := rfl + +def evm1_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 14 + +theorem evm1_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm1_cutB (b, st, s) = (b == 14) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm1_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State), x = (14, [w0, w1, w2, w3, w4, w5, w6], s) ∧ x' = (14, [w0, w1, w2, w3, w4, w5, w6], s)] + +theorem evm1_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (14, [w0, w1, w2, w3, w4, w5, w6], s)) : + ∃ Q ∈ evm1_rels call, Q (14, [w0, w1, w2, w3, w4, w5, w6], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm1_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm1_rels call, Q y y') + (seg (EVM.Program.block o call sched) evm1_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm1) evm1_cutB k' (0, [], State.initial call)) := by + refine ⟨44, 44, ?_⟩ + sym_seg [evm1_cutA_mk, evm1_cutB_mk] [evm1_mk1] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm1_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm1_rels call, Q y y') + (seg (EVM.Program.block o call sched) evm1_cutA k (14, [w0, w1, w2, w3, w4, w5, w6], s)) + (seg (EVM.Program.block o call evm1) evm1_cutB k' (14, [w0, w1, w2, w3, w4, w5, w6], s)) := by + refine ⟨44, 44, ?_⟩ + sym_seg [evm1_cutA_mk, evm1_cutB_mk] [evm1_mk1] + +theorem evm1_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm1_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm1_rels call, Q y y') + (seg (EVM.Program.block o call sched) evm1_cutA k x) + (seg (EVM.Program.block o call evm1) evm1_cutB k' x') := by + intro P mem x x' holds + simp only [evm1_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm1_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, rfl⟩ := holds + exact evm1_seg1 o call w0 w1 w2 w3 w4 w5 w6 s + +/-- `sched` and `evm1` simulated through their cut points on every call. -/ +def evm1_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o sched evm1 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call sched + step' call := EVM.Program.block o call evm1 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm1_cutA + cut' := evm1_cutB + Rel call := fun x x' => ∃ P ∈ evm1_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm1_segments o call) + +/-- Every end of `sched` on a call is matched by an agreeing end of `evm1`. -/ +theorem evm1_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o sched evm1 anyCall := + (evm1_sim o).certified + +/-- Every end of `evm1` on a call is matched by an agreeing end of `sched`. -/ +theorem evm1_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm1 sched anyCall := + (evm1_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.evm1_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_certified + +/-- info: 'SolarTV.Milestone.Arraymax.evm1_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Evm10.lean b/Certified/arraymax/Proofs/Runs/Evm10.lean new file mode 100644 index 00000000..302f6eb9 --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Evm10.lean @@ -0,0 +1,101 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Evm10 +import arraymax.gen.ArrayMaxEntry.Evm9 + +/-! `cfg-simplify-early`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm10_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm10_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm10_cutA (b, st, s) = (b == 3) := rfl + +def evm10_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm10_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm10_cutB (b, st, s) = (b == 3) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm10_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State), x = (3, [w0, w1, w2, w3, w4, w5, w6], s) ∧ x' = (3, [w0, w1, w2, w3, w4, w5, w6], s)] + +theorem evm10_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (3, [w0, w1, w2, w3, w4, w5, w6], s)) : + ∃ Q ∈ evm10_rels call, Q (3, [w0, w1, w2, w3, w4, w5, w6], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm10_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm10_rels call, Q y y') + (seg (EVM.Program.block o call evm9) evm10_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm10) evm10_cutB k' (0, [], State.initial call)) := by + refine ⟨23, 22, ?_⟩ + sym_seg [evm10_cutA_mk, evm10_cutB_mk] [evm10_mk1] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm10_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm10_rels call, Q y y') + (seg (EVM.Program.block o call evm9) evm10_cutA k (3, [w0, w1, w2, w3, w4, w5, w6], s)) + (seg (EVM.Program.block o call evm10) evm10_cutB k' (3, [w0, w1, w2, w3, w4, w5, w6], s)) := by + refine ⟨23, 22, ?_⟩ + sym_seg [evm10_cutA_mk, evm10_cutB_mk] [evm10_mk1] + +theorem evm10_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm10_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm10_rels call, Q y y') + (seg (EVM.Program.block o call evm9) evm10_cutA k x) + (seg (EVM.Program.block o call evm10) evm10_cutB k' x') := by + intro P mem x x' holds + simp only [evm10_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm10_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, rfl⟩ := holds + exact evm10_seg1 o call w0 w1 w2 w3 w4 w5 w6 s + +/-- `evm9` and `evm10` simulated through their cut points on every call. -/ +def evm10_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm9 evm10 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm9 + step' call := EVM.Program.block o call evm10 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm10_cutA + cut' := evm10_cutB + Rel call := fun x x' => ∃ P ∈ evm10_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm10_segments o call) + +/-- Every end of `evm9` on a call is matched by an agreeing end of `evm10`. -/ +theorem evm10_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm9 evm10 anyCall := + (evm10_sim o).certified + +/-- Every end of `evm10` on a call is matched by an agreeing end of `evm9`. -/ +theorem evm10_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm10 evm9 anyCall := + (evm10_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.evm10_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm10_certified + +/-- info: 'SolarTV.Milestone.Arraymax.evm10_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm10_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Evm11.lean b/Certified/arraymax/Proofs/Runs/Evm11.lean new file mode 100644 index 00000000..303d95b7 --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Evm11.lean @@ -0,0 +1,101 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Evm11 +import arraymax.gen.ArrayMaxEntry.Evm10 + +/-! `stack-reschedule`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm11_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm11_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm11_cutA (b, st, s) = (b == 3) := rfl + +def evm11_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm11_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm11_cutB (b, st, s) = (b == 3) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm11_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State), x = (3, [w0, w1, w2, w3, w4, w5, w6], s) ∧ x' = (3, [w0, w1, w2, w3, w4, w5, w6], s)] + +theorem evm11_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (3, [w0, w1, w2, w3, w4, w5, w6], s)) : + ∃ Q ∈ evm11_rels call, Q (3, [w0, w1, w2, w3, w4, w5, w6], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm11_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm11_rels call, Q y y') + (seg (EVM.Program.block o call evm10) evm11_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm11) evm11_cutB k' (0, [], State.initial call)) := by + refine ⟨22, 22, ?_⟩ + sym_seg [evm11_cutA_mk, evm11_cutB_mk] [evm11_mk1] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm11_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm11_rels call, Q y y') + (seg (EVM.Program.block o call evm10) evm11_cutA k (3, [w0, w1, w2, w3, w4, w5, w6], s)) + (seg (EVM.Program.block o call evm11) evm11_cutB k' (3, [w0, w1, w2, w3, w4, w5, w6], s)) := by + refine ⟨22, 22, ?_⟩ + sym_seg [evm11_cutA_mk, evm11_cutB_mk] [evm11_mk1] + +theorem evm11_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm11_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm11_rels call, Q y y') + (seg (EVM.Program.block o call evm10) evm11_cutA k x) + (seg (EVM.Program.block o call evm11) evm11_cutB k' x') := by + intro P mem x x' holds + simp only [evm11_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm11_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, rfl⟩ := holds + exact evm11_seg1 o call w0 w1 w2 w3 w4 w5 w6 s + +/-- `evm10` and `evm11` simulated through their cut points on every call. -/ +def evm11_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm10 evm11 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm10 + step' call := EVM.Program.block o call evm11 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm11_cutA + cut' := evm11_cutB + Rel call := fun x x' => ∃ P ∈ evm11_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm11_segments o call) + +/-- Every end of `evm10` on a call is matched by an agreeing end of `evm11`. -/ +theorem evm11_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm10 evm11 anyCall := + (evm11_sim o).certified + +/-- Every end of `evm11` on a call is matched by an agreeing end of `evm10`. -/ +theorem evm11_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm11 evm10 anyCall := + (evm11_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.evm11_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm11_certified + +/-- info: 'SolarTV.Milestone.Arraymax.evm11_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm11_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Evm12.lean b/Certified/arraymax/Proofs/Runs/Evm12.lean new file mode 100644 index 00000000..db8e7642 --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Evm12.lean @@ -0,0 +1,101 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Evm12 +import arraymax.gen.ArrayMaxEntry.Evm11 + +/-! `copy-loop-blocks`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm12_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm12_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm12_cutA (b, st, s) = (b == 3) := rfl + +def evm12_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm12_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm12_cutB (b, st, s) = (b == 3) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm12_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State), x = (3, [w0, w1, w2, w3, w4, w5, w6], s) ∧ x' = (3, [w0, w1, w2, w3, w4, w5, w6], s)] + +theorem evm12_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (3, [w0, w1, w2, w3, w4, w5, w6], s)) : + ∃ Q ∈ evm12_rels call, Q (3, [w0, w1, w2, w3, w4, w5, w6], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm12_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm12_rels call, Q y y') + (seg (EVM.Program.block o call evm11) evm12_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm12) evm12_cutB k' (0, [], State.initial call)) := by + refine ⟨22, 22, ?_⟩ + sym_seg [evm12_cutA_mk, evm12_cutB_mk] [evm12_mk1] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm12_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm12_rels call, Q y y') + (seg (EVM.Program.block o call evm11) evm12_cutA k (3, [w0, w1, w2, w3, w4, w5, w6], s)) + (seg (EVM.Program.block o call evm12) evm12_cutB k' (3, [w0, w1, w2, w3, w4, w5, w6], s)) := by + refine ⟨22, 22, ?_⟩ + sym_seg [evm12_cutA_mk, evm12_cutB_mk] [evm12_mk1] + +theorem evm12_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm12_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm12_rels call, Q y y') + (seg (EVM.Program.block o call evm11) evm12_cutA k x) + (seg (EVM.Program.block o call evm12) evm12_cutB k' x') := by + intro P mem x x' holds + simp only [evm12_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm12_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, rfl⟩ := holds + exact evm12_seg1 o call w0 w1 w2 w3 w4 w5 w6 s + +/-- `evm11` and `evm12` simulated through their cut points on every call. -/ +def evm12_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm11 evm12 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm11 + step' call := EVM.Program.block o call evm12 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm12_cutA + cut' := evm12_cutB + Rel call := fun x x' => ∃ P ∈ evm12_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm12_segments o call) + +/-- Every end of `evm11` on a call is matched by an agreeing end of `evm12`. -/ +theorem evm12_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm11 evm12 anyCall := + (evm12_sim o).certified + +/-- Every end of `evm12` on a call is matched by an agreeing end of `evm11`. -/ +theorem evm12_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm12 evm11 anyCall := + (evm12_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.evm12_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm12_certified + +/-- info: 'SolarTV.Milestone.Arraymax.evm12_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm12_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Evm13.lean b/Certified/arraymax/Proofs/Runs/Evm13.lean new file mode 100644 index 00000000..79e0111b --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Evm13.lean @@ -0,0 +1,101 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Evm13 +import arraymax.gen.ArrayMaxEntry.Evm12 + +/-! `cfg-simplify`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm13_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm13_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm13_cutA (b, st, s) = (b == 3) := rfl + +def evm13_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm13_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm13_cutB (b, st, s) = (b == 3) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm13_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State), x = (3, [w0, w1, w2, w3, w4, w5, w6], s) ∧ x' = (3, [w0, w1, w2, w3, w4, w5, w6], s)] + +theorem evm13_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (3, [w0, w1, w2, w3, w4, w5, w6], s)) : + ∃ Q ∈ evm13_rels call, Q (3, [w0, w1, w2, w3, w4, w5, w6], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm13_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm13_rels call, Q y y') + (seg (EVM.Program.block o call evm12) evm13_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm13) evm13_cutB k' (0, [], State.initial call)) := by + refine ⟨22, 21, ?_⟩ + sym_seg [evm13_cutA_mk, evm13_cutB_mk] [evm13_mk1] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm13_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm13_rels call, Q y y') + (seg (EVM.Program.block o call evm12) evm13_cutA k (3, [w0, w1, w2, w3, w4, w5, w6], s)) + (seg (EVM.Program.block o call evm13) evm13_cutB k' (3, [w0, w1, w2, w3, w4, w5, w6], s)) := by + refine ⟨22, 21, ?_⟩ + sym_seg [evm13_cutA_mk, evm13_cutB_mk] [evm13_mk1] + +theorem evm13_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm13_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm13_rels call, Q y y') + (seg (EVM.Program.block o call evm12) evm13_cutA k x) + (seg (EVM.Program.block o call evm13) evm13_cutB k' x') := by + intro P mem x x' holds + simp only [evm13_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm13_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, rfl⟩ := holds + exact evm13_seg1 o call w0 w1 w2 w3 w4 w5 w6 s + +/-- `evm12` and `evm13` simulated through their cut points on every call. -/ +def evm13_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm12 evm13 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm12 + step' call := EVM.Program.block o call evm13 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm13_cutA + cut' := evm13_cutB + Rel call := fun x x' => ∃ P ∈ evm13_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm13_segments o call) + +/-- Every end of `evm12` on a call is matched by an agreeing end of `evm13`. -/ +theorem evm13_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm12 evm13 anyCall := + (evm13_sim o).certified + +/-- Every end of `evm13` on a call is matched by an agreeing end of `evm12`. -/ +theorem evm13_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm13 evm12 anyCall := + (evm13_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.evm13_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm13_certified + +/-- info: 'SolarTV.Milestone.Arraymax.evm13_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm13_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Evm14.lean b/Certified/arraymax/Proofs/Runs/Evm14.lean new file mode 100644 index 00000000..648bffbc --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Evm14.lean @@ -0,0 +1,101 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Evm14 +import arraymax.gen.ArrayMaxEntry.Evm13 + +/-! `loop-layout`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm14_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm14_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm14_cutA (b, st, s) = (b == 3) := rfl + +def evm14_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 5 + +theorem evm14_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm14_cutB (b, st, s) = (b == 5) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm14_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State), x = (3, [w0, w1, w2, w3, w4, w5, w6], s) ∧ x' = (5, [w0, w1, w2, w3, w4, w5, w6], s)] + +theorem evm14_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (5, [w0, w1, w2, w3, w4, w5, w6], s)) : + ∃ Q ∈ evm14_rels call, Q (3, [w0, w1, w2, w3, w4, w5, w6], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm14_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm14_rels call, Q y y') + (seg (EVM.Program.block o call evm13) evm14_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm14) evm14_cutB k' (0, [], State.initial call)) := by + refine ⟨21, 21, ?_⟩ + sym_seg [evm14_cutA_mk, evm14_cutB_mk] [evm14_mk1] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm14_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm14_rels call, Q y y') + (seg (EVM.Program.block o call evm13) evm14_cutA k (3, [w0, w1, w2, w3, w4, w5, w6], s)) + (seg (EVM.Program.block o call evm14) evm14_cutB k' (5, [w0, w1, w2, w3, w4, w5, w6], s)) := by + refine ⟨21, 21, ?_⟩ + sym_seg [evm14_cutA_mk, evm14_cutB_mk] [evm14_mk1] + +theorem evm14_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm14_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm14_rels call, Q y y') + (seg (EVM.Program.block o call evm13) evm14_cutA k x) + (seg (EVM.Program.block o call evm14) evm14_cutB k' x') := by + intro P mem x x' holds + simp only [evm14_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm14_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, rfl⟩ := holds + exact evm14_seg1 o call w0 w1 w2 w3 w4 w5 w6 s + +/-- `evm13` and `evm14` simulated through their cut points on every call. -/ +def evm14_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm13 evm14 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm13 + step' call := EVM.Program.block o call evm14 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm14_cutA + cut' := evm14_cutB + Rel call := fun x x' => ∃ P ∈ evm14_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm14_segments o call) + +/-- Every end of `evm13` on a call is matched by an agreeing end of `evm14`. -/ +theorem evm14_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm13 evm14 anyCall := + (evm14_sim o).certified + +/-- Every end of `evm14` on a call is matched by an agreeing end of `evm13`. -/ +theorem evm14_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm14 evm13 anyCall := + (evm14_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.evm14_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm14_certified + +/-- info: 'SolarTV.Milestone.Arraymax.evm14_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm14_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Evm15.lean b/Certified/arraymax/Proofs/Runs/Evm15.lean new file mode 100644 index 00000000..d63c0dc5 --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Evm15.lean @@ -0,0 +1,101 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Evm15 +import arraymax.gen.ArrayMaxEntry.Evm14 + +/-! `reorder-expressions`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm15_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 5 + +theorem evm15_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm15_cutA (b, st, s) = (b == 5) := rfl + +def evm15_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 5 + +theorem evm15_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm15_cutB (b, st, s) = (b == 5) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm15_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State), x = (5, [w0, w1, w2, w3, w4, w5, w6], s) ∧ x' = (5, [w0, w1, w2, w3, w4, w5, w6], s)] + +theorem evm15_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (5, [w0, w1, w2, w3, w4, w5, w6], s)) : + ∃ Q ∈ evm15_rels call, Q (5, [w0, w1, w2, w3, w4, w5, w6], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm15_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm15_rels call, Q y y') + (seg (EVM.Program.block o call evm14) evm15_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm15) evm15_cutB k' (0, [], State.initial call)) := by + refine ⟨21, 21, ?_⟩ + sym_seg [evm15_cutA_mk, evm15_cutB_mk] [evm15_mk1] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm15_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm15_rels call, Q y y') + (seg (EVM.Program.block o call evm14) evm15_cutA k (5, [w0, w1, w2, w3, w4, w5, w6], s)) + (seg (EVM.Program.block o call evm15) evm15_cutB k' (5, [w0, w1, w2, w3, w4, w5, w6], s)) := by + refine ⟨21, 21, ?_⟩ + sym_seg [evm15_cutA_mk, evm15_cutB_mk] [evm15_mk1] + +theorem evm15_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm15_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm15_rels call, Q y y') + (seg (EVM.Program.block o call evm14) evm15_cutA k x) + (seg (EVM.Program.block o call evm15) evm15_cutB k' x') := by + intro P mem x x' holds + simp only [evm15_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm15_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, rfl⟩ := holds + exact evm15_seg1 o call w0 w1 w2 w3 w4 w5 w6 s + +/-- `evm14` and `evm15` simulated through their cut points on every call. -/ +def evm15_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm14 evm15 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm14 + step' call := EVM.Program.block o call evm15 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm15_cutA + cut' := evm15_cutB + Rel call := fun x x' => ∃ P ∈ evm15_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm15_segments o call) + +/-- Every end of `evm14` on a call is matched by an agreeing end of `evm15`. -/ +theorem evm15_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm14 evm15 anyCall := + (evm15_sim o).certified + +/-- Every end of `evm15` on a call is matched by an agreeing end of `evm14`. -/ +theorem evm15_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm15 evm14 anyCall := + (evm15_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.evm15_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm15_certified + +/-- info: 'SolarTV.Milestone.Arraymax.evm15_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm15_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Evm2.lean b/Certified/arraymax/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..a6840ce2 --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Evm2.lean @@ -0,0 +1,101 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Evm2 +import arraymax.gen.ArrayMaxEntry.Evm1 + +/-! `cfg-simplify-early`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm2_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 14 + +theorem evm2_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm2_cutA (b, st, s) = (b == 14) := rfl + +def evm2_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm2_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm2_cutB (b, st, s) = (b == 3) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm2_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State), x = (14, [w0, w1, w2, w3, w4, w5, w6], s) ∧ x' = (3, [w0, w1, w2, w3, w4, w5, w6], s)] + +theorem evm2_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (3, [w0, w1, w2, w3, w4, w5, w6], s)) : + ∃ Q ∈ evm2_rels call, Q (14, [w0, w1, w2, w3, w4, w5, w6], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm2_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm2_rels call, Q y y') + (seg (EVM.Program.block o call evm1) evm2_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm2) evm2_cutB k' (0, [], State.initial call)) := by + refine ⟨44, 24, ?_⟩ + sym_seg [evm2_cutA_mk, evm2_cutB_mk] [evm2_mk1] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm2_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm2_rels call, Q y y') + (seg (EVM.Program.block o call evm1) evm2_cutA k (14, [w0, w1, w2, w3, w4, w5, w6], s)) + (seg (EVM.Program.block o call evm2) evm2_cutB k' (3, [w0, w1, w2, w3, w4, w5, w6], s)) := by + refine ⟨44, 24, ?_⟩ + sym_seg [evm2_cutA_mk, evm2_cutB_mk] [evm2_mk1] + +theorem evm2_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm2_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm2_rels call, Q y y') + (seg (EVM.Program.block o call evm1) evm2_cutA k x) + (seg (EVM.Program.block o call evm2) evm2_cutB k' x') := by + intro P mem x x' holds + simp only [evm2_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm2_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, rfl⟩ := holds + exact evm2_seg1 o call w0 w1 w2 w3 w4 w5 w6 s + +/-- `evm1` and `evm2` simulated through their cut points on every call. -/ +def evm2_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm1 evm2 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm1 + step' call := EVM.Program.block o call evm2 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm2_cutA + cut' := evm2_cutB + Rel call := fun x x' => ∃ P ∈ evm2_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm2_segments o call) + +/-- Every end of `evm1` on a call is matched by an agreeing end of `evm2`. -/ +theorem evm2_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm1 evm2 anyCall := + (evm2_sim o).certified + +/-- Every end of `evm2` on a call is matched by an agreeing end of `evm1`. -/ +theorem evm2_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm2 evm1 anyCall := + (evm2_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.evm2_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_certified + +/-- info: 'SolarTV.Milestone.Arraymax.evm2_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Evm3.lean b/Certified/arraymax/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..02407372 --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Evm3.lean @@ -0,0 +1,101 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Evm3 +import arraymax.gen.ArrayMaxEntry.Evm2 + +/-! `compact-pushes`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm3_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm3_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm3_cutA (b, st, s) = (b == 3) := rfl + +def evm3_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm3_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm3_cutB (b, st, s) = (b == 3) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm3_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State), x = (3, [w0, w1, w2, w3, w4, w5, w6], s) ∧ x' = (3, [w0, w1, w2, w3, w4, w5, w6], s)] + +theorem evm3_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (3, [w0, w1, w2, w3, w4, w5, w6], s)) : + ∃ Q ∈ evm3_rels call, Q (3, [w0, w1, w2, w3, w4, w5, w6], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm3_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm3_rels call, Q y y') + (seg (EVM.Program.block o call evm2) evm3_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm3) evm3_cutB k' (0, [], State.initial call)) := by + refine ⟨24, 24, ?_⟩ + sym_seg [evm3_cutA_mk, evm3_cutB_mk] [evm3_mk1] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm3_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm3_rels call, Q y y') + (seg (EVM.Program.block o call evm2) evm3_cutA k (3, [w0, w1, w2, w3, w4, w5, w6], s)) + (seg (EVM.Program.block o call evm3) evm3_cutB k' (3, [w0, w1, w2, w3, w4, w5, w6], s)) := by + refine ⟨24, 24, ?_⟩ + sym_seg [evm3_cutA_mk, evm3_cutB_mk] [evm3_mk1] + +theorem evm3_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm3_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm3_rels call, Q y y') + (seg (EVM.Program.block o call evm2) evm3_cutA k x) + (seg (EVM.Program.block o call evm3) evm3_cutB k' x') := by + intro P mem x x' holds + simp only [evm3_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm3_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, rfl⟩ := holds + exact evm3_seg1 o call w0 w1 w2 w3 w4 w5 w6 s + +/-- `evm2` and `evm3` simulated through their cut points on every call. -/ +def evm3_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm2 evm3 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm2 + step' call := EVM.Program.block o call evm3 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm3_cutA + cut' := evm3_cutB + Rel call := fun x x' => ∃ P ∈ evm3_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm3_segments o call) + +/-- Every end of `evm2` on a call is matched by an agreeing end of `evm3`. -/ +theorem evm3_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm2 evm3 anyCall := + (evm3_sim o).certified + +/-- Every end of `evm3` on a call is matched by an agreeing end of `evm2`. -/ +theorem evm3_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm3 evm2 anyCall := + (evm3_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.evm3_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_certified + +/-- info: 'SolarTV.Milestone.Arraymax.evm3_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Evm4.lean b/Certified/arraymax/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..0d14de81 --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Evm4.lean @@ -0,0 +1,101 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Evm4 +import arraymax.gen.ArrayMaxEntry.Evm3 + +/-! `block-layout`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm4_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm4_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm4_cutA (b, st, s) = (b == 3) := rfl + +def evm4_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 4 + +theorem evm4_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm4_cutB (b, st, s) = (b == 4) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm4_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State), x = (3, [w0, w1, w2, w3, w4, w5, w6], s) ∧ x' = (4, [w0, w1, w2, w3, w4, w5, w6], s)] + +theorem evm4_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (4, [w0, w1, w2, w3, w4, w5, w6], s)) : + ∃ Q ∈ evm4_rels call, Q (3, [w0, w1, w2, w3, w4, w5, w6], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm4_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm4_rels call, Q y y') + (seg (EVM.Program.block o call evm3) evm4_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm4) evm4_cutB k' (0, [], State.initial call)) := by + refine ⟨24, 24, ?_⟩ + sym_seg [evm4_cutA_mk, evm4_cutB_mk] [evm4_mk1] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm4_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm4_rels call, Q y y') + (seg (EVM.Program.block o call evm3) evm4_cutA k (3, [w0, w1, w2, w3, w4, w5, w6], s)) + (seg (EVM.Program.block o call evm4) evm4_cutB k' (4, [w0, w1, w2, w3, w4, w5, w6], s)) := by + refine ⟨24, 24, ?_⟩ + sym_seg [evm4_cutA_mk, evm4_cutB_mk] [evm4_mk1] + +theorem evm4_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm4_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm4_rels call, Q y y') + (seg (EVM.Program.block o call evm3) evm4_cutA k x) + (seg (EVM.Program.block o call evm4) evm4_cutB k' x') := by + intro P mem x x' holds + simp only [evm4_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm4_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, rfl⟩ := holds + exact evm4_seg1 o call w0 w1 w2 w3 w4 w5 w6 s + +/-- `evm3` and `evm4` simulated through their cut points on every call. -/ +def evm4_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm3 evm4 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm3 + step' call := EVM.Program.block o call evm4 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm4_cutA + cut' := evm4_cutB + Rel call := fun x x' => ∃ P ∈ evm4_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm4_segments o call) + +/-- Every end of `evm3` on a call is matched by an agreeing end of `evm4`. -/ +theorem evm4_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm3 evm4 anyCall := + (evm4_sim o).certified + +/-- Every end of `evm4` on a call is matched by an agreeing end of `evm3`. -/ +theorem evm4_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm4 evm3 anyCall := + (evm4_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.evm4_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_certified + +/-- info: 'SolarTV.Milestone.Arraymax.evm4_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Evm5.lean b/Certified/arraymax/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..af7e0788 --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Evm5.lean @@ -0,0 +1,101 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Evm5 +import arraymax.gen.ArrayMaxEntry.Evm4 + +/-! `terminal-dedup`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm5_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 4 + +theorem evm5_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm5_cutA (b, st, s) = (b == 4) := rfl + +def evm5_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 4 + +theorem evm5_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm5_cutB (b, st, s) = (b == 4) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm5_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State), x = (4, [w0, w1, w2, w3, w4, w5, w6], s) ∧ x' = (4, [w0, w1, w2, w3, w4, w5, w6], s)] + +theorem evm5_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (4, [w0, w1, w2, w3, w4, w5, w6], s)) : + ∃ Q ∈ evm5_rels call, Q (4, [w0, w1, w2, w3, w4, w5, w6], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm5_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm5_rels call, Q y y') + (seg (EVM.Program.block o call evm4) evm5_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm5) evm5_cutB k' (0, [], State.initial call)) := by + refine ⟨24, 24, ?_⟩ + sym_seg [evm5_cutA_mk, evm5_cutB_mk] [evm5_mk1] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm5_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm5_rels call, Q y y') + (seg (EVM.Program.block o call evm4) evm5_cutA k (4, [w0, w1, w2, w3, w4, w5, w6], s)) + (seg (EVM.Program.block o call evm5) evm5_cutB k' (4, [w0, w1, w2, w3, w4, w5, w6], s)) := by + refine ⟨24, 24, ?_⟩ + sym_seg [evm5_cutA_mk, evm5_cutB_mk] [evm5_mk1] + +theorem evm5_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm5_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm5_rels call, Q y y') + (seg (EVM.Program.block o call evm4) evm5_cutA k x) + (seg (EVM.Program.block o call evm5) evm5_cutB k' x') := by + intro P mem x x' holds + simp only [evm5_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm5_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, rfl⟩ := holds + exact evm5_seg1 o call w0 w1 w2 w3 w4 w5 w6 s + +/-- `evm4` and `evm5` simulated through their cut points on every call. -/ +def evm5_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm4 evm5 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm4 + step' call := EVM.Program.block o call evm5 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm5_cutA + cut' := evm5_cutB + Rel call := fun x x' => ∃ P ∈ evm5_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm5_segments o call) + +/-- Every end of `evm4` on a call is matched by an agreeing end of `evm5`. -/ +theorem evm5_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm4 evm5 anyCall := + (evm5_sim o).certified + +/-- Every end of `evm5` on a call is matched by an agreeing end of `evm4`. -/ +theorem evm5_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm5 evm4 anyCall := + (evm5_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.evm5_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_certified + +/-- info: 'SolarTV.Milestone.Arraymax.evm5_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Evm6.lean b/Certified/arraymax/Proofs/Runs/Evm6.lean new file mode 100644 index 00000000..96cd5d45 --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Evm6.lean @@ -0,0 +1,101 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Evm6 +import arraymax.gen.ArrayMaxEntry.Evm5 + +/-! `cfg-simplify-early`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm6_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 4 + +theorem evm6_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm6_cutA (b, st, s) = (b == 4) := rfl + +def evm6_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm6_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm6_cutB (b, st, s) = (b == 3) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm6_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State), x = (4, [w0, w1, w2, w3, w4, w5, w6], s) ∧ x' = (3, [w0, w1, w2, w3, w4, w5, w6], s)] + +theorem evm6_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (3, [w0, w1, w2, w3, w4, w5, w6], s)) : + ∃ Q ∈ evm6_rels call, Q (4, [w0, w1, w2, w3, w4, w5, w6], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm6_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm6_rels call, Q y y') + (seg (EVM.Program.block o call evm5) evm6_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm6) evm6_cutB k' (0, [], State.initial call)) := by + refine ⟨24, 23, ?_⟩ + sym_seg [evm6_cutA_mk, evm6_cutB_mk] [evm6_mk1] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm6_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm6_rels call, Q y y') + (seg (EVM.Program.block o call evm5) evm6_cutA k (4, [w0, w1, w2, w3, w4, w5, w6], s)) + (seg (EVM.Program.block o call evm6) evm6_cutB k' (3, [w0, w1, w2, w3, w4, w5, w6], s)) := by + refine ⟨24, 23, ?_⟩ + sym_seg [evm6_cutA_mk, evm6_cutB_mk] [evm6_mk1] + +theorem evm6_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm6_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm6_rels call, Q y y') + (seg (EVM.Program.block o call evm5) evm6_cutA k x) + (seg (EVM.Program.block o call evm6) evm6_cutB k' x') := by + intro P mem x x' holds + simp only [evm6_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm6_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, rfl⟩ := holds + exact evm6_seg1 o call w0 w1 w2 w3 w4 w5 w6 s + +/-- `evm5` and `evm6` simulated through their cut points on every call. -/ +def evm6_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm5 evm6 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm5 + step' call := EVM.Program.block o call evm6 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm6_cutA + cut' := evm6_cutB + Rel call := fun x x' => ∃ P ∈ evm6_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm6_segments o call) + +/-- Every end of `evm5` on a call is matched by an agreeing end of `evm6`. -/ +theorem evm6_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm5 evm6 anyCall := + (evm6_sim o).certified + +/-- Every end of `evm6` on a call is matched by an agreeing end of `evm5`. -/ +theorem evm6_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm6 evm5 anyCall := + (evm6_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.evm6_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_certified + +/-- info: 'SolarTV.Milestone.Arraymax.evm6_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Evm7.lean b/Certified/arraymax/Proofs/Runs/Evm7.lean new file mode 100644 index 00000000..13430fee --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Evm7.lean @@ -0,0 +1,101 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Evm7 +import arraymax.gen.ArrayMaxEntry.Evm6 + +/-! `reorder-pushes`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm7_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm7_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm7_cutA (b, st, s) = (b == 3) := rfl + +def evm7_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm7_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm7_cutB (b, st, s) = (b == 3) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm7_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State), x = (3, [w0, w1, w2, w3, w4, w5, w6], s) ∧ x' = (3, [w0, w1, w2, w3, w4, w5, w6], s)] + +theorem evm7_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (3, [w0, w1, w2, w3, w4, w5, w6], s)) : + ∃ Q ∈ evm7_rels call, Q (3, [w0, w1, w2, w3, w4, w5, w6], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm7_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm7_rels call, Q y y') + (seg (EVM.Program.block o call evm6) evm7_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm7) evm7_cutB k' (0, [], State.initial call)) := by + refine ⟨23, 23, ?_⟩ + sym_seg [evm7_cutA_mk, evm7_cutB_mk] [evm7_mk1] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm7_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm7_rels call, Q y y') + (seg (EVM.Program.block o call evm6) evm7_cutA k (3, [w0, w1, w2, w3, w4, w5, w6], s)) + (seg (EVM.Program.block o call evm7) evm7_cutB k' (3, [w0, w1, w2, w3, w4, w5, w6], s)) := by + refine ⟨23, 23, ?_⟩ + sym_seg [evm7_cutA_mk, evm7_cutB_mk] [evm7_mk1] + +theorem evm7_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm7_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm7_rels call, Q y y') + (seg (EVM.Program.block o call evm6) evm7_cutA k x) + (seg (EVM.Program.block o call evm7) evm7_cutB k' x') := by + intro P mem x x' holds + simp only [evm7_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm7_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, rfl⟩ := holds + exact evm7_seg1 o call w0 w1 w2 w3 w4 w5 w6 s + +/-- `evm6` and `evm7` simulated through their cut points on every call. -/ +def evm7_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm6 evm7 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm6 + step' call := EVM.Program.block o call evm7 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm7_cutA + cut' := evm7_cutB + Rel call := fun x x' => ∃ P ∈ evm7_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm7_segments o call) + +/-- Every end of `evm6` on a call is matched by an agreeing end of `evm7`. -/ +theorem evm7_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm6 evm7 anyCall := + (evm7_sim o).certified + +/-- Every end of `evm7` on a call is matched by an agreeing end of `evm6`. -/ +theorem evm7_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm7 evm6 anyCall := + (evm7_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.evm7_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm7_certified + +/-- info: 'SolarTV.Milestone.Arraymax.evm7_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm7_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Evm8.lean b/Certified/arraymax/Proofs/Runs/Evm8.lean new file mode 100644 index 00000000..fc65d3d7 --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Evm8.lean @@ -0,0 +1,101 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Evm8 +import arraymax.gen.ArrayMaxEntry.Evm7 + +/-! `block-cse`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm8_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm8_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm8_cutA (b, st, s) = (b == 3) := rfl + +def evm8_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm8_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm8_cutB (b, st, s) = (b == 3) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm8_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State), x = (3, [w0, w1, w2, w3, w4, w5, w6], s) ∧ x' = (3, [w0, w1, w2, w3, w4, w5, w6], s)] + +theorem evm8_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (3, [w0, w1, w2, w3, w4, w5, w6], s)) : + ∃ Q ∈ evm8_rels call, Q (3, [w0, w1, w2, w3, w4, w5, w6], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm8_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm8_rels call, Q y y') + (seg (EVM.Program.block o call evm7) evm8_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm8) evm8_cutB k' (0, [], State.initial call)) := by + refine ⟨23, 23, ?_⟩ + sym_seg [evm8_cutA_mk, evm8_cutB_mk] [evm8_mk1] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm8_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm8_rels call, Q y y') + (seg (EVM.Program.block o call evm7) evm8_cutA k (3, [w0, w1, w2, w3, w4, w5, w6], s)) + (seg (EVM.Program.block o call evm8) evm8_cutB k' (3, [w0, w1, w2, w3, w4, w5, w6], s)) := by + refine ⟨23, 23, ?_⟩ + sym_seg [evm8_cutA_mk, evm8_cutB_mk] [evm8_mk1] + +theorem evm8_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm8_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm8_rels call, Q y y') + (seg (EVM.Program.block o call evm7) evm8_cutA k x) + (seg (EVM.Program.block o call evm8) evm8_cutB k' x') := by + intro P mem x x' holds + simp only [evm8_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm8_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, rfl⟩ := holds + exact evm8_seg1 o call w0 w1 w2 w3 w4 w5 w6 s + +/-- `evm7` and `evm8` simulated through their cut points on every call. -/ +def evm8_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm7 evm8 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm7 + step' call := EVM.Program.block o call evm8 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm8_cutA + cut' := evm8_cutB + Rel call := fun x x' => ∃ P ∈ evm8_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm8_segments o call) + +/-- Every end of `evm7` on a call is matched by an agreeing end of `evm8`. -/ +theorem evm8_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm7 evm8 anyCall := + (evm8_sim o).certified + +/-- Every end of `evm8` on a call is matched by an agreeing end of `evm7`. -/ +theorem evm8_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm8 evm7 anyCall := + (evm8_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.evm8_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm8_certified + +/-- info: 'SolarTV.Milestone.Arraymax.evm8_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm8_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Evm9.lean b/Certified/arraymax/Proofs/Runs/Evm9.lean new file mode 100644 index 00000000..1b92e50d --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Evm9.lean @@ -0,0 +1,101 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Evm9 +import arraymax.gen.ArrayMaxEntry.Evm8 + +/-! `stack-normalize`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm9_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm9_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm9_cutA (b, st, s) = (b == 3) := rfl + +def evm9_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 3 + +theorem evm9_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm9_cutB (b, st, s) = (b == 3) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm9_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State), x = (3, [w0, w1, w2, w3, w4, w5, w6], s) ∧ x' = (3, [w0, w1, w2, w3, w4, w5, w6], s)] + +theorem evm9_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (3, [w0, w1, w2, w3, w4, w5, w6], s)) : + ∃ Q ∈ evm9_rels call, Q (3, [w0, w1, w2, w3, w4, w5, w6], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm9_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm9_rels call, Q y y') + (seg (EVM.Program.block o call evm8) evm9_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm9) evm9_cutB k' (0, [], State.initial call)) := by + refine ⟨23, 23, ?_⟩ + sym_seg [evm9_cutA_mk, evm9_cutB_mk] [evm9_mk1] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem evm9_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 w6 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm9_rels call, Q y y') + (seg (EVM.Program.block o call evm8) evm9_cutA k (3, [w0, w1, w2, w3, w4, w5, w6], s)) + (seg (EVM.Program.block o call evm9) evm9_cutB k' (3, [w0, w1, w2, w3, w4, w5, w6], s)) := by + refine ⟨23, 23, ?_⟩ + sym_seg [evm9_cutA_mk, evm9_cutB_mk] [evm9_mk1] + +theorem evm9_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm9_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm9_rels call, Q y y') + (seg (EVM.Program.block o call evm8) evm9_cutA k x) + (seg (EVM.Program.block o call evm9) evm9_cutB k' x') := by + intro P mem x x' holds + simp only [evm9_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm9_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, w6, s, rfl, rfl⟩ := holds + exact evm9_seg1 o call w0 w1 w2 w3 w4 w5 w6 s + +/-- `evm8` and `evm9` simulated through their cut points on every call. -/ +def evm9_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm8 evm9 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm8 + step' call := EVM.Program.block o call evm9 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm9_cutA + cut' := evm9_cutB + Rel call := fun x x' => ∃ P ∈ evm9_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm9_segments o call) + +/-- Every end of `evm8` on a call is matched by an agreeing end of `evm9`. -/ +theorem evm9_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm8 evm9 anyCall := + (evm9_sim o).certified + +/-- Every end of `evm9` on a call is matched by an agreeing end of `evm8`. -/ +theorem evm9_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm9 evm8 anyCall := + (evm9_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.evm9_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm9_certified + +/-- info: 'SolarTV.Milestone.Arraymax.evm9_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm9_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Mir1.lean b/Certified/arraymax/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..e8084f10 --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Mir1.lean @@ -0,0 +1,168 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Mir1 +import arraymax.gen.ArrayMaxEntry.Stage0 + +/-! `spell-width-tests`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def mir1_cutA : MIR.Lowered.Frame → Bool := fun x => + match x.2.1 with + | .enter f _ b => (f == 0 && b == 2) + | .resume .. => false + +theorem mir1_cutA_enter (rs : List MIR.Lowered.Return) (f p b : Nat) (env : MIR.Lowered.Env) (s : State) : + mir1_cutA (rs, .enter f p b, env, s) = ((f == 0 && b == 2)) := rfl + +theorem mir1_cutA_resume (rs : List MIR.Lowered.Return) (f b : Nat) (is : List MIR.Lowered.Inst) (t : MIR.Lowered.Terminator) (env : MIR.Lowered.Env) (s : State) : + mir1_cutA (rs, .resume f b is t, env, s) = false := rfl + +def mir1_cutB : MIR.Lowered.Frame → Bool := fun x => + match x.2.1 with + | .enter f _ b => (f == 0 && b == 2) + | .resume .. => false + +theorem mir1_cutB_enter (rs : List MIR.Lowered.Return) (f p b : Nat) (env : MIR.Lowered.Env) (s : State) : + mir1_cutB (rs, .enter f p b, env, s) = ((f == 0 && b == 2)) := rfl + +theorem mir1_cutB_resume (rs : List MIR.Lowered.Return) (f b : Nat) (is : List MIR.Lowered.Inst) (t : MIR.Lowered.Terminator) (env : MIR.Lowered.Env) (s : State) : + mir1_cutB (rs, .resume f b is t, env, s) = false := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def mir1_rels (call : Call) : List (MIR.Lowered.Frame → MIR.Lowered.Frame → Prop) := + [fun x x' => x = ([], .enter stage0.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState stage0 (State.initial call)) ∧ x' = ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call)), + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env), x = ([], MIR.Lowered.Pos.enter 0 5 2, env, s) ∧ x' = ([], MIR.Lowered.Pos.enter 0 5 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 50 = env 50 ∧ env' 51 = env 51 ∧ env' 129 = env 129 ∧ env 12 = (0 : EvmRules.Word) ∧ env' 12 = (0 : EvmRules.Word), + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env), x = ([], MIR.Lowered.Pos.enter 0 5 2, env, s) ∧ x' = ([], MIR.Lowered.Pos.enter 0 10 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 37 = env 50 ∧ (1 : EvmRules.Word) = env 51 ∧ env' 126 = env 129 ∧ env 12 = (0 : EvmRules.Word) ∧ env' 12 = (0 : EvmRules.Word), + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env), x = ([], MIR.Lowered.Pos.enter 0 10 2, env, s) ∧ x' = ([], MIR.Lowered.Pos.enter 0 5 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 50 = env 37 ∧ env' 51 = (1 : EvmRules.Word) ∧ env' 129 = env 126 ∧ env 12 = (0 : EvmRules.Word) ∧ env' 12 = (0 : EvmRules.Word), + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env), x = ([], MIR.Lowered.Pos.enter 0 10 2, env, s) ∧ x' = ([], MIR.Lowered.Pos.enter 0 10 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 37 = env 37 ∧ env' 126 = env 126 ∧ env 12 = (0 : EvmRules.Word) ∧ env' 12 = (0 : EvmRules.Word)] + +theorem mir1_mk1 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' : MIR.Lowered.Env), y = ([], MIR.Lowered.Pos.enter 0 5 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 50 = env 50 ∧ env' 51 = env 51 ∧ env' 129 = env 129 ∧ env 12 = (0 : EvmRules.Word) ∧ env' 12 = (0 : EvmRules.Word)) : + ∃ Q ∈ mir1_rels call, Q ([], MIR.Lowered.Pos.enter 0 5 2, env, s) y := by + obtain ⟨env', h0, h1, h2, h3, h4, h5, h6, h7, h8⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨env, s, env', rfl, h0, h1, h2, h3, h4, h5, h6, h7, h8⟩ + +theorem mir1_mk2 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' : MIR.Lowered.Env), y = ([], MIR.Lowered.Pos.enter 0 10 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 37 = env 50 ∧ (1 : EvmRules.Word) = env 51 ∧ env' 126 = env 129 ∧ env 12 = (0 : EvmRules.Word) ∧ env' 12 = (0 : EvmRules.Word)) : + ∃ Q ∈ mir1_rels call, Q ([], MIR.Lowered.Pos.enter 0 5 2, env, s) y := by + obtain ⟨env', h0, h1, h2, h3, h4, h5, h6, h7, h8⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨env, s, env', rfl, h0, h1, h2, h3, h4, h5, h6, h7, h8⟩ + +theorem mir1_mk3 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' : MIR.Lowered.Env), y = ([], MIR.Lowered.Pos.enter 0 5 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 50 = env 37 ∧ env' 51 = (1 : EvmRules.Word) ∧ env' 129 = env 126 ∧ env 12 = (0 : EvmRules.Word) ∧ env' 12 = (0 : EvmRules.Word)) : + ∃ Q ∈ mir1_rels call, Q ([], MIR.Lowered.Pos.enter 0 10 2, env, s) y := by + obtain ⟨env', h0, h1, h2, h3, h4, h5, h6, h7, h8⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _)))) ⟨env, s, env', rfl, h0, h1, h2, h3, h4, h5, h6, h7, h8⟩ + +theorem mir1_mk4 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' : MIR.Lowered.Env), y = ([], MIR.Lowered.Pos.enter 0 10 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 37 = env 37 ∧ env' 126 = env 126 ∧ env 12 = (0 : EvmRules.Word) ∧ env' 12 = (0 : EvmRules.Word)) : + ∃ Q ∈ mir1_rels call, Q ([], MIR.Lowered.Pos.enter 0 10 2, env, s) y := by + obtain ⟨env', h0, h1, h2, h3, h4, h5, h6, h7⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))))) ⟨env, s, env', rfl, h0, h1, h2, h3, h4, h5, h6, h7⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem mir1_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([], .enter stage0.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState stage0 (State.initial call))) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB k' ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call))) := by + refine ⟨17, 17, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2, mir1_mk3, mir1_mk4] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem mir1_seg1 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env) (h0 : env' 12 = env 12) (h1 : env' 91 = env 91) (h2 : env' 119 = env 119) (h3 : env' 50 = env 50) (h4 : env' 51 = env 51) (h5 : env' 129 = env 129) (h6 : env 12 = (0 : EvmRules.Word)) (h7 : env' 12 = (0 : EvmRules.Word)) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([], MIR.Lowered.Pos.enter 0 5 2, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB k' ([], MIR.Lowered.Pos.enter 0 5 2, env', s)) := by + refine ⟨17, 17, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2, mir1_mk3, mir1_mk4] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem mir1_seg2 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env) (h0 : env' 12 = env 12) (h1 : env' 91 = env 91) (h2 : env' 119 = env 119) (h3 : env' 37 = env 50) (h4 : (1 : EvmRules.Word) = env 51) (h5 : env' 126 = env 129) (h6 : env 12 = (0 : EvmRules.Word)) (h7 : env' 12 = (0 : EvmRules.Word)) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([], MIR.Lowered.Pos.enter 0 5 2, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB k' ([], MIR.Lowered.Pos.enter 0 10 2, env', s)) := by + refine ⟨17, 17, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2, mir1_mk3, mir1_mk4] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem mir1_seg3 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env) (h0 : env' 12 = env 12) (h1 : env' 91 = env 91) (h2 : env' 119 = env 119) (h3 : env' 50 = env 37) (h4 : env' 51 = (1 : EvmRules.Word)) (h5 : env' 129 = env 126) (h6 : env 12 = (0 : EvmRules.Word)) (h7 : env' 12 = (0 : EvmRules.Word)) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([], MIR.Lowered.Pos.enter 0 10 2, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB k' ([], MIR.Lowered.Pos.enter 0 5 2, env', s)) := by + refine ⟨17, 17, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2, mir1_mk3, mir1_mk4] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem mir1_seg4 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env) (h0 : env' 12 = env 12) (h1 : env' 91 = env 91) (h2 : env' 119 = env 119) (h3 : env' 37 = env 37) (h4 : env' 126 = env 126) (h5 : env 12 = (0 : EvmRules.Word)) (h6 : env' 12 = (0 : EvmRules.Word)) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([], MIR.Lowered.Pos.enter 0 10 2, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB k' ([], MIR.Lowered.Pos.enter 0 10 2, env', s)) := by + refine ⟨17, 17, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2, mir1_mk3, mir1_mk4] + +theorem mir1_segments (o : Oracle) (call : Call) : + ∀ P ∈ mir1_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k x) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB k' x') := by + intro P mem x x' holds + simp only [mir1_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact mir1_seg0 o call + · obtain ⟨env, s, env', rfl, rfl, h0, h1, h2, h3, h4, h5, h6, h7⟩ := holds + exact mir1_seg1 o call env s env' h0 h1 h2 h3 h4 h5 h6 h7 + · obtain ⟨env, s, env', rfl, rfl, h0, h1, h2, h3, h4, h5, h6, h7⟩ := holds + exact mir1_seg2 o call env s env' h0 h1 h2 h3 h4 h5 h6 h7 + · obtain ⟨env, s, env', rfl, rfl, h0, h1, h2, h3, h4, h5, h6, h7⟩ := holds + exact mir1_seg3 o call env s env' h0 h1 h2 h3 h4 h5 h6 h7 + · obtain ⟨env, s, env', rfl, rfl, h0, h1, h2, h3, h4, h5, h6⟩ := holds + exact mir1_seg4 o call env s env' h0 h1 h2 h3 h4 h5 h6 + +/-- `stage0` and `mir1` simulated through their cut points on every call. -/ +def mir1_sim (o : Oracle) : + CutPoint.LayerSim MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o stage0 mir1 anyCall where + σ := MIR.Lowered.Frame + τ := MIR.Lowered.Frame + step call := MIR.Lowered.moduleBlock o call stage0 + step' call := MIR.Lowered.moduleBlock o call mir1 + init call := ([], .enter stage0.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState stage0 (State.initial call)) + init' call := ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call)) + runs _ _ := rfl + runs' _ _ := rfl + cut := mir1_cutA + cut' := mir1_cutB + Rel call := fun x x' => ∃ P ∈ mir1_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (mir1_segments o call) + +/-- Every end of `stage0` on a call is matched by an agreeing end of `mir1`. -/ +theorem mir1_certified (o : Oracle) : + Certified MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o stage0 mir1 anyCall := + (mir1_sim o).certified + +/-- Every end of `mir1` on a call is matched by an agreeing end of `stage0`. -/ +theorem mir1_certified_back (o : Oracle) : + Certified MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o mir1 stage0 anyCall := + (mir1_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.mir1_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_certified + +/-- info: 'SolarTV.Milestone.Arraymax.mir1_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Mir2.lean b/Certified/arraymax/Proofs/Runs/Mir2.lean new file mode 100644 index 00000000..d7be59f2 --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Mir2.lean @@ -0,0 +1,168 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Mir2 +import arraymax.gen.ArrayMaxEntry.Mir1 + +/-! `lower-assumes`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def mir2_cutA : MIR.Lowered.Frame → Bool := fun x => + match x.2.1 with + | .enter f _ b => (f == 0 && b == 2) + | .resume .. => false + +theorem mir2_cutA_enter (rs : List MIR.Lowered.Return) (f p b : Nat) (env : MIR.Lowered.Env) (s : State) : + mir2_cutA (rs, .enter f p b, env, s) = ((f == 0 && b == 2)) := rfl + +theorem mir2_cutA_resume (rs : List MIR.Lowered.Return) (f b : Nat) (is : List MIR.Lowered.Inst) (t : MIR.Lowered.Terminator) (env : MIR.Lowered.Env) (s : State) : + mir2_cutA (rs, .resume f b is t, env, s) = false := rfl + +def mir2_cutB : MIR.Lowered.Frame → Bool := fun x => + match x.2.1 with + | .enter f _ b => (f == 0 && b == 2) + | .resume .. => false + +theorem mir2_cutB_enter (rs : List MIR.Lowered.Return) (f p b : Nat) (env : MIR.Lowered.Env) (s : State) : + mir2_cutB (rs, .enter f p b, env, s) = ((f == 0 && b == 2)) := rfl + +theorem mir2_cutB_resume (rs : List MIR.Lowered.Return) (f b : Nat) (is : List MIR.Lowered.Inst) (t : MIR.Lowered.Terminator) (env : MIR.Lowered.Env) (s : State) : + mir2_cutB (rs, .resume f b is t, env, s) = false := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def mir2_rels (call : Call) : List (MIR.Lowered.Frame → MIR.Lowered.Frame → Prop) := + [fun x x' => x = ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call)) ∧ x' = ([], .enter mir2.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir2 (State.initial call)), + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env), x = ([], MIR.Lowered.Pos.enter 0 5 2, env, s) ∧ x' = ([], MIR.Lowered.Pos.enter 0 28 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 50 = env 50 ∧ env' 51 = env 51 ∧ env' 129 = env 129 ∧ env 12 = (0 : EvmRules.Word), + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env), x = ([], MIR.Lowered.Pos.enter 0 5 2, env, s) ∧ x' = ([], MIR.Lowered.Pos.enter 0 38 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 37 = env 50 ∧ (1 : EvmRules.Word) = env 51 ∧ env' 126 = env 129 ∧ env 12 = (0 : EvmRules.Word), + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env), x = ([], MIR.Lowered.Pos.enter 0 10 2, env, s) ∧ x' = ([], MIR.Lowered.Pos.enter 0 28 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 50 = env 37 ∧ env' 51 = (1 : EvmRules.Word) ∧ env' 129 = env 126 ∧ env 12 = (0 : EvmRules.Word), + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env), x = ([], MIR.Lowered.Pos.enter 0 10 2, env, s) ∧ x' = ([], MIR.Lowered.Pos.enter 0 38 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 37 = env 37 ∧ env' 126 = env 126 ∧ env 12 = (0 : EvmRules.Word)] + +theorem mir2_mk1 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' : MIR.Lowered.Env), y = ([], MIR.Lowered.Pos.enter 0 28 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 50 = env 50 ∧ env' 51 = env 51 ∧ env' 129 = env 129 ∧ env 12 = (0 : EvmRules.Word)) : + ∃ Q ∈ mir2_rels call, Q ([], MIR.Lowered.Pos.enter 0 5 2, env, s) y := by + obtain ⟨env', h0, h1, h2, h3, h4, h5, h6, h7⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨env, s, env', rfl, h0, h1, h2, h3, h4, h5, h6, h7⟩ + +theorem mir2_mk2 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' : MIR.Lowered.Env), y = ([], MIR.Lowered.Pos.enter 0 38 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 37 = env 50 ∧ (1 : EvmRules.Word) = env 51 ∧ env' 126 = env 129 ∧ env 12 = (0 : EvmRules.Word)) : + ∃ Q ∈ mir2_rels call, Q ([], MIR.Lowered.Pos.enter 0 5 2, env, s) y := by + obtain ⟨env', h0, h1, h2, h3, h4, h5, h6, h7⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨env, s, env', rfl, h0, h1, h2, h3, h4, h5, h6, h7⟩ + +theorem mir2_mk3 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' : MIR.Lowered.Env), y = ([], MIR.Lowered.Pos.enter 0 28 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 50 = env 37 ∧ env' 51 = (1 : EvmRules.Word) ∧ env' 129 = env 126 ∧ env 12 = (0 : EvmRules.Word)) : + ∃ Q ∈ mir2_rels call, Q ([], MIR.Lowered.Pos.enter 0 10 2, env, s) y := by + obtain ⟨env', h0, h1, h2, h3, h4, h5, h6, h7⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _)))) ⟨env, s, env', rfl, h0, h1, h2, h3, h4, h5, h6, h7⟩ + +theorem mir2_mk4 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' : MIR.Lowered.Env), y = ([], MIR.Lowered.Pos.enter 0 38 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 37 = env 37 ∧ env' 126 = env 126 ∧ env 12 = (0 : EvmRules.Word)) : + ∃ Q ∈ mir2_rels call, Q ([], MIR.Lowered.Pos.enter 0 10 2, env, s) y := by + obtain ⟨env', h0, h1, h2, h3, h4, h5, h6⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))))) ⟨env, s, env', rfl, h0, h1, h2, h3, h4, h5, h6⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem mir2_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir2_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir1) mir2_cutA k ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call))) + (seg (MIR.Lowered.moduleBlock o call mir2) mir2_cutB k' ([], .enter mir2.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir2 (State.initial call))) := by + refine ⟨17, 44, ?_⟩ + sym_seg [mir2_cutA_enter, mir2_cutA_resume, mir2_cutB_enter, mir2_cutB_resume] [mir2_mk1, mir2_mk2, mir2_mk3, mir2_mk4] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem mir2_seg1 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env) (h0 : env' 12 = env 12) (h1 : env' 91 = env 91) (h2 : env' 119 = env 119) (h3 : env' 50 = env 50) (h4 : env' 51 = env 51) (h5 : env' 129 = env 129) (h6 : env 12 = (0 : EvmRules.Word)) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir2_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir1) mir2_cutA k ([], MIR.Lowered.Pos.enter 0 5 2, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir2) mir2_cutB k' ([], MIR.Lowered.Pos.enter 0 28 2, env', s)) := by + refine ⟨17, 44, ?_⟩ + sym_seg [mir2_cutA_enter, mir2_cutA_resume, mir2_cutB_enter, mir2_cutB_resume] [mir2_mk1, mir2_mk2, mir2_mk3, mir2_mk4] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem mir2_seg2 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env) (h0 : env' 12 = env 12) (h1 : env' 91 = env 91) (h2 : env' 119 = env 119) (h3 : env' 37 = env 50) (h4 : (1 : EvmRules.Word) = env 51) (h5 : env' 126 = env 129) (h6 : env 12 = (0 : EvmRules.Word)) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir2_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir1) mir2_cutA k ([], MIR.Lowered.Pos.enter 0 5 2, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir2) mir2_cutB k' ([], MIR.Lowered.Pos.enter 0 38 2, env', s)) := by + refine ⟨17, 44, ?_⟩ + sym_seg [mir2_cutA_enter, mir2_cutA_resume, mir2_cutB_enter, mir2_cutB_resume] [mir2_mk1, mir2_mk2, mir2_mk3, mir2_mk4] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem mir2_seg3 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env) (h0 : env' 12 = env 12) (h1 : env' 91 = env 91) (h2 : env' 119 = env 119) (h3 : env' 50 = env 37) (h4 : env' 51 = (1 : EvmRules.Word)) (h5 : env' 129 = env 126) (h6 : env 12 = (0 : EvmRules.Word)) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir2_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir1) mir2_cutA k ([], MIR.Lowered.Pos.enter 0 10 2, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir2) mir2_cutB k' ([], MIR.Lowered.Pos.enter 0 28 2, env', s)) := by + refine ⟨17, 44, ?_⟩ + sym_seg [mir2_cutA_enter, mir2_cutA_resume, mir2_cutB_enter, mir2_cutB_resume] [mir2_mk1, mir2_mk2, mir2_mk3, mir2_mk4] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem mir2_seg4 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env) (h0 : env' 12 = env 12) (h1 : env' 91 = env 91) (h2 : env' 119 = env 119) (h3 : env' 37 = env 37) (h4 : env' 126 = env 126) (h5 : env 12 = (0 : EvmRules.Word)) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir2_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir1) mir2_cutA k ([], MIR.Lowered.Pos.enter 0 10 2, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir2) mir2_cutB k' ([], MIR.Lowered.Pos.enter 0 38 2, env', s)) := by + refine ⟨17, 44, ?_⟩ + sym_seg [mir2_cutA_enter, mir2_cutA_resume, mir2_cutB_enter, mir2_cutB_resume] [mir2_mk1, mir2_mk2, mir2_mk3, mir2_mk4] + +theorem mir2_segments (o : Oracle) (call : Call) : + ∀ P ∈ mir2_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir2_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir1) mir2_cutA k x) + (seg (MIR.Lowered.moduleBlock o call mir2) mir2_cutB k' x') := by + intro P mem x x' holds + simp only [mir2_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact mir2_seg0 o call + · obtain ⟨env, s, env', rfl, rfl, h0, h1, h2, h3, h4, h5, h6⟩ := holds + exact mir2_seg1 o call env s env' h0 h1 h2 h3 h4 h5 h6 + · obtain ⟨env, s, env', rfl, rfl, h0, h1, h2, h3, h4, h5, h6⟩ := holds + exact mir2_seg2 o call env s env' h0 h1 h2 h3 h4 h5 h6 + · obtain ⟨env, s, env', rfl, rfl, h0, h1, h2, h3, h4, h5, h6⟩ := holds + exact mir2_seg3 o call env s env' h0 h1 h2 h3 h4 h5 h6 + · obtain ⟨env, s, env', rfl, rfl, h0, h1, h2, h3, h4, h5⟩ := holds + exact mir2_seg4 o call env s env' h0 h1 h2 h3 h4 h5 + +/-- `mir1` and `mir2` simulated through their cut points on every call. -/ +def mir2_sim (o : Oracle) : + CutPoint.LayerSim MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o mir1 mir2 anyCall where + σ := MIR.Lowered.Frame + τ := MIR.Lowered.Frame + step call := MIR.Lowered.moduleBlock o call mir1 + step' call := MIR.Lowered.moduleBlock o call mir2 + init call := ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call)) + init' call := ([], .enter mir2.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir2 (State.initial call)) + runs _ _ := rfl + runs' _ _ := rfl + cut := mir2_cutA + cut' := mir2_cutB + Rel call := fun x x' => ∃ P ∈ mir2_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (mir2_segments o call) + +/-- Every end of `mir1` on a call is matched by an agreeing end of `mir2`. -/ +theorem mir2_certified (o : Oracle) : + Certified MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o mir1 mir2 anyCall := + (mir2_sim o).certified + +/-- Every end of `mir2` on a call is matched by an agreeing end of `mir1`. -/ +theorem mir2_certified_back (o : Oracle) : + Certified MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o mir2 mir1 anyCall := + (mir2_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.mir2_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir2_certified + +/-- info: 'SolarTV.Milestone.Arraymax.mir2_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir2_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Mir3.lean b/Certified/arraymax/Proofs/Runs/Mir3.lean new file mode 100644 index 00000000..99a81fd9 --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Mir3.lean @@ -0,0 +1,168 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Mir3 +import arraymax.gen.ArrayMaxEntry.Mir2 + +/-! `evm-inst-schedule`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def mir3_cutA : MIR.Lowered.Frame → Bool := fun x => + match x.2.1 with + | .enter f _ b => (f == 0 && b == 2) + | .resume .. => false + +theorem mir3_cutA_enter (rs : List MIR.Lowered.Return) (f p b : Nat) (env : MIR.Lowered.Env) (s : State) : + mir3_cutA (rs, .enter f p b, env, s) = ((f == 0 && b == 2)) := rfl + +theorem mir3_cutA_resume (rs : List MIR.Lowered.Return) (f b : Nat) (is : List MIR.Lowered.Inst) (t : MIR.Lowered.Terminator) (env : MIR.Lowered.Env) (s : State) : + mir3_cutA (rs, .resume f b is t, env, s) = false := rfl + +def mir3_cutB : MIR.Lowered.Frame → Bool := fun x => + match x.2.1 with + | .enter f _ b => (f == 0 && b == 2) + | .resume .. => false + +theorem mir3_cutB_enter (rs : List MIR.Lowered.Return) (f p b : Nat) (env : MIR.Lowered.Env) (s : State) : + mir3_cutB (rs, .enter f p b, env, s) = ((f == 0 && b == 2)) := rfl + +theorem mir3_cutB_resume (rs : List MIR.Lowered.Return) (f b : Nat) (is : List MIR.Lowered.Inst) (t : MIR.Lowered.Terminator) (env : MIR.Lowered.Env) (s : State) : + mir3_cutB (rs, .resume f b is t, env, s) = false := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def mir3_rels (call : Call) : List (MIR.Lowered.Frame → MIR.Lowered.Frame → Prop) := + [fun x x' => x = ([], .enter mir2.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir2 (State.initial call)) ∧ x' = ([], .enter mir3.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir3 (State.initial call)), + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env), x = ([], MIR.Lowered.Pos.enter 0 28 2, env, s) ∧ x' = ([], MIR.Lowered.Pos.enter 0 28 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 50 = env 50 ∧ env' 51 = env 51 ∧ env' 129 = env 129, + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env), x = ([], MIR.Lowered.Pos.enter 0 28 2, env, s) ∧ x' = ([], MIR.Lowered.Pos.enter 0 38 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 37 = env 50 ∧ (1 : EvmRules.Word) = env 51 ∧ env' 126 = env 129, + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env), x = ([], MIR.Lowered.Pos.enter 0 38 2, env, s) ∧ x' = ([], MIR.Lowered.Pos.enter 0 28 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 50 = env 37 ∧ env' 51 = (1 : EvmRules.Word) ∧ env' 129 = env 126, + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env), x = ([], MIR.Lowered.Pos.enter 0 38 2, env, s) ∧ x' = ([], MIR.Lowered.Pos.enter 0 38 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 37 = env 37 ∧ env' 126 = env 126] + +theorem mir3_mk1 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' : MIR.Lowered.Env), y = ([], MIR.Lowered.Pos.enter 0 28 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 50 = env 50 ∧ env' 51 = env 51 ∧ env' 129 = env 129) : + ∃ Q ∈ mir3_rels call, Q ([], MIR.Lowered.Pos.enter 0 28 2, env, s) y := by + obtain ⟨env', h0, h1, h2, h3, h4, h5, h6⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨env, s, env', rfl, h0, h1, h2, h3, h4, h5, h6⟩ + +theorem mir3_mk2 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' : MIR.Lowered.Env), y = ([], MIR.Lowered.Pos.enter 0 38 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 37 = env 50 ∧ (1 : EvmRules.Word) = env 51 ∧ env' 126 = env 129) : + ∃ Q ∈ mir3_rels call, Q ([], MIR.Lowered.Pos.enter 0 28 2, env, s) y := by + obtain ⟨env', h0, h1, h2, h3, h4, h5, h6⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨env, s, env', rfl, h0, h1, h2, h3, h4, h5, h6⟩ + +theorem mir3_mk3 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' : MIR.Lowered.Env), y = ([], MIR.Lowered.Pos.enter 0 28 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 50 = env 37 ∧ env' 51 = (1 : EvmRules.Word) ∧ env' 129 = env 126) : + ∃ Q ∈ mir3_rels call, Q ([], MIR.Lowered.Pos.enter 0 38 2, env, s) y := by + obtain ⟨env', h0, h1, h2, h3, h4, h5, h6⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _)))) ⟨env, s, env', rfl, h0, h1, h2, h3, h4, h5, h6⟩ + +theorem mir3_mk4 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' : MIR.Lowered.Env), y = ([], MIR.Lowered.Pos.enter 0 38 2, env', s) ∧ env' 12 = env 12 ∧ env' 91 = env 91 ∧ env' 119 = env 119 ∧ env' 37 = env 37 ∧ env' 126 = env 126) : + ∃ Q ∈ mir3_rels call, Q ([], MIR.Lowered.Pos.enter 0 38 2, env, s) y := by + obtain ⟨env', h0, h1, h2, h3, h4, h5⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))))) ⟨env, s, env', rfl, h0, h1, h2, h3, h4, h5⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem mir3_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir3_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir2) mir3_cutA k ([], .enter mir2.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir2 (State.initial call))) + (seg (MIR.Lowered.moduleBlock o call mir3) mir3_cutB k' ([], .enter mir3.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir3 (State.initial call))) := by + refine ⟨44, 44, ?_⟩ + sym_seg [mir3_cutA_enter, mir3_cutA_resume, mir3_cutB_enter, mir3_cutB_resume] [mir3_mk1, mir3_mk2, mir3_mk3, mir3_mk4] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem mir3_seg1 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env) (h0 : env' 12 = env 12) (h1 : env' 91 = env 91) (h2 : env' 119 = env 119) (h3 : env' 50 = env 50) (h4 : env' 51 = env 51) (h5 : env' 129 = env 129) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir3_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir2) mir3_cutA k ([], MIR.Lowered.Pos.enter 0 28 2, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir3) mir3_cutB k' ([], MIR.Lowered.Pos.enter 0 28 2, env', s)) := by + refine ⟨44, 44, ?_⟩ + sym_seg [mir3_cutA_enter, mir3_cutA_resume, mir3_cutB_enter, mir3_cutB_resume] [mir3_mk1, mir3_mk2, mir3_mk3, mir3_mk4] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem mir3_seg2 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env) (h0 : env' 12 = env 12) (h1 : env' 91 = env 91) (h2 : env' 119 = env 119) (h3 : env' 37 = env 50) (h4 : (1 : EvmRules.Word) = env 51) (h5 : env' 126 = env 129) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir3_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir2) mir3_cutA k ([], MIR.Lowered.Pos.enter 0 28 2, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir3) mir3_cutB k' ([], MIR.Lowered.Pos.enter 0 38 2, env', s)) := by + refine ⟨44, 44, ?_⟩ + sym_seg [mir3_cutA_enter, mir3_cutA_resume, mir3_cutB_enter, mir3_cutB_resume] [mir3_mk1, mir3_mk2, mir3_mk3, mir3_mk4] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem mir3_seg3 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env) (h0 : env' 12 = env 12) (h1 : env' 91 = env 91) (h2 : env' 119 = env 119) (h3 : env' 50 = env 37) (h4 : env' 51 = (1 : EvmRules.Word)) (h5 : env' 129 = env 126) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir3_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir2) mir3_cutA k ([], MIR.Lowered.Pos.enter 0 38 2, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir3) mir3_cutB k' ([], MIR.Lowered.Pos.enter 0 28 2, env', s)) := by + refine ⟨44, 44, ?_⟩ + sym_seg [mir3_cutA_enter, mir3_cutA_resume, mir3_cutB_enter, mir3_cutB_resume] [mir3_mk1, mir3_mk2, mir3_mk3, mir3_mk4] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem mir3_seg4 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env) (h0 : env' 12 = env 12) (h1 : env' 91 = env 91) (h2 : env' 119 = env 119) (h3 : env' 37 = env 37) (h4 : env' 126 = env 126) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir3_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir2) mir3_cutA k ([], MIR.Lowered.Pos.enter 0 38 2, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir3) mir3_cutB k' ([], MIR.Lowered.Pos.enter 0 38 2, env', s)) := by + refine ⟨44, 44, ?_⟩ + sym_seg [mir3_cutA_enter, mir3_cutA_resume, mir3_cutB_enter, mir3_cutB_resume] [mir3_mk1, mir3_mk2, mir3_mk3, mir3_mk4] + +theorem mir3_segments (o : Oracle) (call : Call) : + ∀ P ∈ mir3_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir3_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir2) mir3_cutA k x) + (seg (MIR.Lowered.moduleBlock o call mir3) mir3_cutB k' x') := by + intro P mem x x' holds + simp only [mir3_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact mir3_seg0 o call + · obtain ⟨env, s, env', rfl, rfl, h0, h1, h2, h3, h4, h5⟩ := holds + exact mir3_seg1 o call env s env' h0 h1 h2 h3 h4 h5 + · obtain ⟨env, s, env', rfl, rfl, h0, h1, h2, h3, h4, h5⟩ := holds + exact mir3_seg2 o call env s env' h0 h1 h2 h3 h4 h5 + · obtain ⟨env, s, env', rfl, rfl, h0, h1, h2, h3, h4, h5⟩ := holds + exact mir3_seg3 o call env s env' h0 h1 h2 h3 h4 h5 + · obtain ⟨env, s, env', rfl, rfl, h0, h1, h2, h3, h4⟩ := holds + exact mir3_seg4 o call env s env' h0 h1 h2 h3 h4 + +/-- `mir2` and `mir3` simulated through their cut points on every call. -/ +def mir3_sim (o : Oracle) : + CutPoint.LayerSim MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o mir2 mir3 anyCall where + σ := MIR.Lowered.Frame + τ := MIR.Lowered.Frame + step call := MIR.Lowered.moduleBlock o call mir2 + step' call := MIR.Lowered.moduleBlock o call mir3 + init call := ([], .enter mir2.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir2 (State.initial call)) + init' call := ([], .enter mir3.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir3 (State.initial call)) + runs _ _ := rfl + runs' _ _ := rfl + cut := mir3_cutA + cut' := mir3_cutB + Rel call := fun x x' => ∃ P ∈ mir3_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (mir3_segments o call) + +/-- Every end of `mir2` on a call is matched by an agreeing end of `mir3`. -/ +theorem mir3_certified (o : Oracle) : + Certified MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o mir2 mir3 anyCall := + (mir3_sim o).certified + +/-- Every end of `mir3` on a call is matched by an agreeing end of `mir2`. -/ +theorem mir3_certified_back (o : Oracle) : + Certified MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o mir3 mir2 anyCall := + (mir3_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.mir3_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir3_certified + +/-- info: 'SolarTV.Milestone.Arraymax.mir3_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir3_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Runs/Sched.lean b/Certified/arraymax/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..9473c1de --- /dev/null +++ b/Certified/arraymax/Proofs/Runs/Sched.lean @@ -0,0 +1,126 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import arraymax.gen.ArrayMaxEntry.Sched +import arraymax.gen.ArrayMaxEntry.Mir3 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def sched_cutA : MIR.Lowered.Frame → Bool := fun x => + match x.2.1 with + | .enter f _ b => (f == 0 && b == 2) + | .resume .. => false + +theorem sched_cutA_enter (rs : List MIR.Lowered.Return) (f p b : Nat) (env : MIR.Lowered.Env) (s : State) : + sched_cutA (rs, .enter f p b, env, s) = ((f == 0 && b == 2)) := rfl + +theorem sched_cutA_resume (rs : List MIR.Lowered.Return) (f b : Nat) (is : List MIR.Lowered.Inst) (t : MIR.Lowered.Terminator) (env : MIR.Lowered.Env) (s : State) : + sched_cutA (rs, .resume f b is t, env, s) = false := rfl + +def sched_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 14 + +theorem sched_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + sched_cutB (b, st, s) = (b == 14) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def sched_rels (call : Call) : List (MIR.Lowered.Frame → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = ([], .enter mir3.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir3 (State.initial call)) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (j0 : EvmRules.Word), x = ([], MIR.Lowered.Pos.enter 0 28 2, env, s) ∧ x' = (14, [env 51, env 129, env 50, env 119, env 12, env 91, j0], s), + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (j0 : EvmRules.Word), x = ([], MIR.Lowered.Pos.enter 0 38 2, env, s) ∧ x' = (14, [(1 : EvmRules.Word), env 126, env 37, env 119, env 12, env 91, j0], s)] + +theorem sched_mk1 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : Nat × EVM.Stack × State} + (h : ∃ (j0 : EvmRules.Word), y = (14, [env 51, env 129, env 50, env 119, env 12, env 91, j0], s)) : + ∃ Q ∈ sched_rels call, Q ([], MIR.Lowered.Pos.enter 0 28 2, env, s) y := by + obtain ⟨j0, h0⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨env, s, j0, rfl, h0⟩ + +theorem sched_mk2 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : Nat × EVM.Stack × State} + (h : ∃ (j0 : EvmRules.Word), y = (14, [(1 : EvmRules.Word), env 126, env 37, env 119, env 12, env 91, j0], s)) : + ∃ Q ∈ sched_rels call, Q ([], MIR.Lowered.Pos.enter 0 38 2, env, s) y := by + obtain ⟨j0, h0⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨env, s, j0, rfl, h0⟩ + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem sched_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ sched_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir3) sched_cutA k ([], .enter mir3.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir3 (State.initial call))) + (seg (EVM.Program.block o call sched) sched_cutB k' (0, [], State.initial call)) := by + refine ⟨44, 44, ?_⟩ + sym_seg [sched_cutA_enter, sched_cutA_resume, sched_cutB_mk] [sched_mk1, sched_mk2] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem sched_seg1 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (j0 : EvmRules.Word) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ sched_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir3) sched_cutA k ([], MIR.Lowered.Pos.enter 0 28 2, env, s)) + (seg (EVM.Program.block o call sched) sched_cutB k' (14, [env 51, env 129, env 50, env 119, env 12, env 91, j0], s)) := by + refine ⟨44, 44, ?_⟩ + sym_seg [sched_cutA_enter, sched_cutA_resume, sched_cutB_mk] [sched_mk1, sched_mk2] + +set_option maxHeartbeats 2000000 in +set_option maxRecDepth 20000 in +theorem sched_seg2 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (j0 : EvmRules.Word) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ sched_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir3) sched_cutA k ([], MIR.Lowered.Pos.enter 0 38 2, env, s)) + (seg (EVM.Program.block o call sched) sched_cutB k' (14, [(1 : EvmRules.Word), env 126, env 37, env 119, env 12, env 91, j0], s)) := by + refine ⟨44, 44, ?_⟩ + sym_seg [sched_cutA_enter, sched_cutA_resume, sched_cutB_mk] [sched_mk1, sched_mk2] + +theorem sched_segments (o : Oracle) (call : Call) : + ∀ P ∈ sched_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ sched_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir3) sched_cutA k x) + (seg (EVM.Program.block o call sched) sched_cutB k' x') := by + intro P mem x x' holds + simp only [sched_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact sched_seg0 o call + · obtain ⟨env, s, j0, rfl, rfl⟩ := holds + exact sched_seg1 o call env s j0 + · obtain ⟨env, s, j0, rfl, rfl⟩ := holds + exact sched_seg2 o call env s j0 + +/-- `mir3` and `sched` simulated through their cut points on every call. -/ +def sched_sim (o : Oracle) : + CutPoint.LayerSim MIR.Lowered.moduleLayer EVM.Program.layer o mir3 sched anyCall where + σ := MIR.Lowered.Frame + τ := Nat × EVM.Stack × State + step call := MIR.Lowered.moduleBlock o call mir3 + step' call := EVM.Program.block o call sched + init call := ([], .enter mir3.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir3 (State.initial call)) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := sched_cutA + cut' := sched_cutB + Rel call := fun x x' => ∃ P ∈ sched_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (sched_segments o call) + +/-- Every end of `mir3` on a call is matched by an agreeing end of `sched`. -/ +theorem sched_certified (o : Oracle) : + Certified MIR.Lowered.moduleLayer EVM.Program.layer o mir3 sched anyCall := + (sched_sim o).certified + +/-- Every end of `sched` on a call is matched by an agreeing end of `mir3`. -/ +theorem sched_certified_back (o : Oracle) : + Certified EVM.Program.layer MIR.Lowered.moduleLayer o sched mir3 anyCall := + (sched_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Arraymax.sched_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_certified + +/-- info: 'SolarTV.Milestone.Arraymax.sched_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/Proofs/Stages.lean b/Certified/arraymax/Proofs/Stages.lean new file mode 100644 index 00000000..6ca574a2 --- /dev/null +++ b/Certified/arraymax/Proofs/Stages.lean @@ -0,0 +1,61 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import arraymax.Proofs.Runs.Mir1 +import arraymax.Proofs.Runs.Mir2 +import arraymax.Proofs.Runs.Mir3 +import arraymax.Proofs.Runs.Sched +import arraymax.Proofs.Runs.Evm1 +import arraymax.Proofs.Runs.Evm2 +import arraymax.Proofs.Runs.Evm3 +import arraymax.Proofs.Runs.Evm4 +import arraymax.Proofs.Runs.Evm5 +import arraymax.Proofs.Runs.Evm6 +import arraymax.Proofs.Runs.Evm7 +import arraymax.Proofs.Runs.Evm8 +import arraymax.Proofs.Runs.Evm9 +import arraymax.Proofs.Runs.Evm10 +import arraymax.Proofs.Runs.Evm11 +import arraymax.Proofs.Runs.Evm12 +import arraymax.Proofs.Runs.Evm13 +import arraymax.Proofs.Runs.Evm14 +import arraymax.Proofs.Runs.Evm15 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `ArrayMaxEntry`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle through cut points, whatever number of times its loops run, and chained from the first lowered MIR `stage0` to the final EVM IR `evm15`, both ways. -/ + +namespace SolarTV.Milestone.Arraymax + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1, mir2, mir3], sched, [evm1, evm2, evm3, evm4, evm5, evm6, evm7, evm8, evm9, evm10, evm11, evm12, evm13, evm14, evm15]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, each through cut points, chained by the library's composition, on every call. -/ +theorem arraymax_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm15 anyCall := + mir_to_evmir_certified o anyCall compilation ⟨mir1_certified o, mir2_certified o, mir3_certified o, trivial⟩ (sched_certified o) + ⟨evm1_certified o, evm2_certified o, evm3_certified o, evm4_certified o, evm5_certified o, evm6_certified o, evm7_certified o, evm8_certified o, evm9_certified o, evm10_certified o, evm11_certified o, evm12_certified o, evm13_certified o, evm14_certified o, evm15_certified o, trivial⟩ + +/-- Every end of the first lowered MIR is matched by an agreeing end of the final EVM IR, on every call. -/ +theorem arraymax_certified (o : Oracle) : + Certified MIR.Lowered.moduleLayer EVM.Program.layer o stage0 evm15 anyCall := + ((((((((((((((((((mir1_certified o).trans (mir2_certified o)).trans (mir3_certified o)).trans (sched_certified o)).trans (evm1_certified o)).trans (evm2_certified o)).trans (evm3_certified o)).trans (evm4_certified o)).trans (evm5_certified o)).trans (evm6_certified o)).trans (evm7_certified o)).trans (evm8_certified o)).trans (evm9_certified o)).trans (evm10_certified o)).trans (evm11_certified o)).trans (evm12_certified o)).trans (evm13_certified o)).trans (evm14_certified o)).trans (evm15_certified o) + +/-- Every end of the final EVM IR is matched by an agreeing end of the first lowered MIR, on every call: one ends exactly when the other does. -/ +theorem arraymax_certified_back (o : Oracle) : + Certified EVM.Program.layer MIR.Lowered.moduleLayer o evm15 stage0 anyCall := + ((((((((((((((((((evm15_certified_back o).trans (evm14_certified_back o)).trans (evm13_certified_back o)).trans (evm12_certified_back o)).trans (evm11_certified_back o)).trans (evm10_certified_back o)).trans (evm9_certified_back o)).trans (evm8_certified_back o)).trans (evm7_certified_back o)).trans (evm6_certified_back o)).trans (evm5_certified_back o)).trans (evm4_certified_back o)).trans (evm3_certified_back o)).trans (evm2_certified_back o)).trans (evm1_certified_back o)).trans (sched_certified_back o)).trans (mir3_certified_back o)).trans (mir2_certified_back o)).trans (mir1_certified_back o) + +/-- info: 'SolarTV.Milestone.Arraymax.arraymax_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms arraymax_mir_to_evmir + +/-- info: 'SolarTV.Milestone.Arraymax.arraymax_certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms arraymax_certified + +/-- info: 'SolarTV.Milestone.Arraymax.arraymax_certified_back' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms arraymax_certified_back + +end SolarTV.Milestone.Arraymax diff --git a/Certified/arraymax/arraymax.sol b/Certified/arraymax/arraymax.sol new file mode 100644 index 00000000..b796b9dd --- /dev/null +++ b/Certified/arraymax/arraymax.sol @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +library ArrayMax { + /// @custom:requires xs.length > 0 + /// @custom:ensures forall uint256 j :: j < xs.length ==> xs[j] <= m + /// @custom:ensures exists uint256 j :: j < xs.length && xs[j] == m + function max(uint256[] memory xs) internal pure returns (uint256 m) { + m = xs[0]; + for (uint256 i = 1; i < xs.length; i++) { + if (xs[i] > m) { + m = xs[i]; + } + } + } + + /// @custom:ensures r <= n + function clamp(uint256 x, uint256 n) internal pure returns (uint256 r) { + r = x > n ? n : x; + } +} + +/// ArrayMax.max behind an external entry point, so that the loop is in the runtime bytecode +/// (an internal library function compiles to none). +contract ArrayMaxEntry { + /// @custom:ensures forall uint256 j :: j < xs.length ==> xs[j] <= result + /// @custom:ensures exists uint256 j :: j < xs.length && xs[j] == result + function max(uint256[] calldata xs) external pure returns (uint256) { + require(xs.length > 0); + return ArrayMax.max(xs); + } +} diff --git a/Certified/arraymax/bytecode.hex b/Certified/arraymax/bytecode.hex new file mode 100644 index 00000000..0ec2b60e --- /dev/null +++ b/Certified/arraymax/bytecode.hex @@ -0,0 +1 @@ +346013575f3560e01c80633bf6de9614602c575b5f5ffd5b6d01020000000000000005000000285f610124565b6080604052600435602436106004820191602436031017813591602001803603918260051c841117601357825f1080156013578360051b8460fb1c5f109381138480610253575060135760208101602081106102685760800160405260808086815260a0928584378051925160c0888003610236578885036102195785156101ff576001935093509350935060ed565b855184518087108a83036101515783801561016c575061018157505050506001810191602001905f19148060175750905b835186821087820361010e578060bc57505050505f52508061013c5760205ff35b5090506d010300000000000000020000001b9091955b906020529060405260605263ed572b275f526064601cfd5b6d01020000000000000001000000065f610124565b505090506d010300000000000000030000001d909197610124565b6d020200000000000000030000001c5f610124565b875186518b82036101b6578281036101d057505082156101e85795505050506001810191602001905f191480601757509060ed565b5090506d0103000000000000000400000023909199610124565b90506d01030000000000000004000000249091610124565b50506d020200000000000000040000001c5f610124565b50505050506d0202000000000000000a000000015f610124565b5050505090506d0103000000000000000a00000015909193610124565b50505050505050506d0103000000000000000a0000003181610124565b6d01020000000000000007000000065f610124565b6041602052634e487b715f526024601cfd diff --git a/Certified/arraymax/gen/ArrayMax/Bytecode.lean b/Certified/arraymax/gen/ArrayMax/Bytecode.lean new file mode 100644 index 00000000..89953a96 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMax/Bytecode.lean @@ -0,0 +1,14 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMax`; do not edit. -/ + +namespace SolarTV.Export.ArrayMax + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x5f, 0x5f, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "5f5ffd" + +end SolarTV.Export.ArrayMax diff --git a/Certified/arraymax/gen/ArrayMax/Manifest.lean b/Certified/arraymax/gen/ArrayMax/Manifest.lean new file mode 100644 index 00000000..7734f465 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMax/Manifest.lean @@ -0,0 +1,37 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMax`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.ArrayMax.Manifest + +def sources : List (String × String) := + [("Certified/arraymax/arraymax.sol", "904535ac694498a9823f530ca158ee0c762fd1adcc56f3e7b73ca0e457e61f4a")] + +def compiler : String := "0.8.38+commit.6c3ba965.solar.0.3.0-dev" + +def arguments : List String := + ["Certified/arraymax/arraymax.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/arraymax/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "970a12c27f9a7b0195a24ca17d792e46e3ac58ea1c64a09267150f45184361cd"), + ("Sched", "sched", "stack-schedule", "ecad6bab39684acc2ac1f3d099a35219f4f6d088eb1540820e5f1c95158d819c"), + ("Bytecode", "bytecode", "assemble", "1bc24224a60b6ae6809449b0fbd8fda894e04356ddad0406c2350d2a97b2f9f3")] + +def bytecodeHex : String := + "5f5ffd" + +def bytecodeSha256 : String := "fb46926419d6c8a637fd12b52e23f698ba5ad6bfe5afec13d064f59f7adcca4f" + +end SolarTV.Export.ArrayMax.Manifest diff --git a/Certified/arraymax/gen/ArrayMax/Sched.lean b/Certified/arraymax/gen/ArrayMax/Sched.lean new file mode 100644 index 00000000..12d965bb --- /dev/null +++ b/Certified/arraymax/gen/ArrayMax/Sched.lean @@ -0,0 +1,16 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMax`; do not edit. -/ + +namespace SolarTV.Export.ArrayMax + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.ArrayMax diff --git a/Certified/arraymax/gen/ArrayMax/Schedule.json b/Certified/arraymax/gen/ArrayMax/Schedule.json new file mode 100644 index 00000000..a791afcb --- /dev/null +++ b/Certified/arraymax/gen/ArrayMax/Schedule.json @@ -0,0 +1,7 @@ +{ + "functions": [ + {"function": 0, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null} + ]} + ] +} diff --git a/Certified/arraymax/gen/ArrayMax/Stage0.lean b/Certified/arraymax/gen/ArrayMax/Stage0.lean new file mode 100644 index 00000000..313c2f60 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMax/Stage0.lean @@ -0,0 +1,20 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMax`; do not edit. -/ + +namespace SolarTV.Export.ArrayMax + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 0, + functions := [ + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.ArrayMax diff --git a/Certified/arraymax/gen/ArrayMax/manifest.json b/Certified/arraymax/gen/ArrayMax/manifest.json new file mode 100644 index 00000000..b82f8908 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMax/manifest.json @@ -0,0 +1,49 @@ +{ + "arguments": [ + "Certified/arraymax/arraymax.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/arraymax/gen" + ], + "bytecode": "5f5ffd", + "bytecode_sha256": "fb46926419d6c8a637fd12b52e23f698ba5ad6bfe5afec13d064f59f7adcca4f", + "compiler": "0.8.38+commit.6c3ba965.solar.0.3.0-dev", + "contract": "ArrayMax", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"Certified/arraymax/arraymax.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/arraymax/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/arraymax/gen\"), keep_asts: false, forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "Certified/arraymax/arraymax.sol", + "sha256": "904535ac694498a9823f530ca158ee0c762fd1adcc56f3e7b73ca0e457e61f4a" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "970a12c27f9a7b0195a24ca17d792e46e3ac58ea1c64a09267150f45184361cd" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "ecad6bab39684acc2ac1f3d099a35219f4f6d088eb1540820e5f1c95158d819c" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "1bc24224a60b6ae6809449b0fbd8fda894e04356ddad0406c2350d2a97b2f9f3" + } + ] +} diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Bytecode.lean b/Certified/arraymax/gen/ArrayMaxEntry/Bytecode.lean new file mode 100644 index 00000000..c4248dc0 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Bytecode.lean @@ -0,0 +1,53 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x13, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x3b, 0xf6, 0xde, 0x96, 0x14, + 0x60, 0x2c, 0x57, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x6d, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x28, 0x5f, 0x61, 0x01, 0x24, 0x56, 0x5b, 0x60, 0x80, 0x60, + 0x40, 0x52, 0x60, 0x04, 0x35, 0x60, 0x24, 0x36, 0x10, 0x60, 0x04, 0x82, 0x01, 0x91, 0x60, 0x24, + 0x36, 0x03, 0x10, 0x17, 0x81, 0x35, 0x91, 0x60, 0x20, 0x01, 0x80, 0x36, 0x03, 0x91, 0x82, 0x60, + 0x05, 0x1c, 0x84, 0x11, 0x17, 0x60, 0x13, 0x57, 0x82, 0x5f, 0x10, 0x80, 0x15, 0x60, 0x13, 0x57, + 0x83, 0x60, 0x05, 0x1b, 0x84, 0x60, 0xfb, 0x1c, 0x5f, 0x10, 0x93, 0x81, 0x13, 0x84, 0x80, 0x61, + 0x02, 0x53, 0x57, 0x50, 0x60, 0x13, 0x57, 0x60, 0x20, 0x81, 0x01, 0x60, 0x20, 0x81, 0x10, 0x61, + 0x02, 0x68, 0x57, 0x60, 0x80, 0x01, 0x60, 0x40, 0x52, 0x60, 0x80, 0x80, 0x86, 0x81, 0x52, 0x60, + 0xa0, 0x92, 0x85, 0x84, 0x37, 0x80, 0x51, 0x92, 0x51, 0x60, 0xc0, 0x88, 0x80, 0x03, 0x61, 0x02, + 0x36, 0x57, 0x88, 0x85, 0x03, 0x61, 0x02, 0x19, 0x57, 0x85, 0x15, 0x61, 0x01, 0xff, 0x57, 0x60, + 0x01, 0x93, 0x50, 0x93, 0x50, 0x93, 0x50, 0x93, 0x50, 0x60, 0xed, 0x56, 0x5b, 0x85, 0x51, 0x84, + 0x51, 0x80, 0x87, 0x10, 0x8a, 0x83, 0x03, 0x61, 0x01, 0x51, 0x57, 0x83, 0x80, 0x15, 0x61, 0x01, + 0x6c, 0x57, 0x50, 0x61, 0x01, 0x81, 0x57, 0x50, 0x50, 0x50, 0x50, 0x60, 0x01, 0x81, 0x01, 0x91, + 0x60, 0x20, 0x01, 0x90, 0x5f, 0x19, 0x14, 0x80, 0x60, 0x17, 0x57, 0x50, 0x90, 0x5b, 0x83, 0x51, + 0x86, 0x82, 0x10, 0x87, 0x82, 0x03, 0x61, 0x01, 0x0e, 0x57, 0x80, 0x60, 0xbc, 0x57, 0x50, 0x50, + 0x50, 0x50, 0x5f, 0x52, 0x50, 0x80, 0x61, 0x01, 0x3c, 0x57, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x50, + 0x90, 0x50, 0x6d, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x1b, 0x90, 0x91, 0x95, 0x5b, 0x90, 0x60, 0x20, 0x52, 0x90, 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, + 0x63, 0xed, 0x57, 0x2b, 0x27, 0x5f, 0x52, 0x60, 0x64, 0x60, 0x1c, 0xfd, 0x5b, 0x6d, 0x01, 0x02, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x5f, 0x61, 0x01, 0x24, + 0x56, 0x5b, 0x50, 0x50, 0x90, 0x50, 0x6d, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x03, 0x00, 0x00, 0x00, 0x1d, 0x90, 0x91, 0x97, 0x61, 0x01, 0x24, 0x56, 0x5b, 0x6d, 0x02, 0x02, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x1c, 0x5f, 0x61, 0x01, 0x24, + 0x56, 0x5b, 0x87, 0x51, 0x86, 0x51, 0x8b, 0x82, 0x03, 0x61, 0x01, 0xb6, 0x57, 0x82, 0x81, 0x03, + 0x61, 0x01, 0xd0, 0x57, 0x50, 0x50, 0x82, 0x15, 0x61, 0x01, 0xe8, 0x57, 0x95, 0x50, 0x50, 0x50, + 0x50, 0x60, 0x01, 0x81, 0x01, 0x91, 0x60, 0x20, 0x01, 0x90, 0x5f, 0x19, 0x14, 0x80, 0x60, 0x17, + 0x57, 0x50, 0x90, 0x60, 0xed, 0x56, 0x5b, 0x50, 0x90, 0x50, 0x6d, 0x01, 0x03, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x23, 0x90, 0x91, 0x99, 0x61, 0x01, 0x24, 0x56, + 0x5b, 0x90, 0x50, 0x6d, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, + 0x00, 0x24, 0x90, 0x91, 0x61, 0x01, 0x24, 0x56, 0x5b, 0x50, 0x50, 0x6d, 0x02, 0x02, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x1c, 0x5f, 0x61, 0x01, 0x24, 0x56, 0x5b, + 0x50, 0x50, 0x50, 0x50, 0x50, 0x6d, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, + 0x00, 0x00, 0x00, 0x01, 0x5f, 0x61, 0x01, 0x24, 0x56, 0x5b, 0x50, 0x50, 0x50, 0x50, 0x90, 0x50, + 0x6d, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x15, 0x90, + 0x91, 0x93, 0x61, 0x01, 0x24, 0x56, 0x5b, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x50, 0x6d, + 0x01, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x31, 0x81, 0x61, + 0x01, 0x24, 0x56, 0x5b, 0x6d, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, + 0x00, 0x00, 0x06, 0x5f, 0x61, 0x01, 0x24, 0x56, 0x5b, 0x60, 0x41, 0x60, 0x20, 0x52, 0x63, 0x4e, + 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, 0x60, 0x1c, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "346013575f3560e01c80633bf6de9614602c575b5f5ffd5b6d01020000000000000005000000285f610124565b6080604052600435602436106004820191602436031017813591602001803603918260051c841117601357825f1080156013578360051b8460fb1c5f109381138480610253575060135760208101602081106102685760800160405260808086815260a0928584378051925160c0888003610236578885036102195785156101ff576001935093509350935060ed565b855184518087108a83036101515783801561016c575061018157505050506001810191602001905f19148060175750905b835186821087820361010e578060bc57505050505f52508061013c5760205ff35b5090506d010300000000000000020000001b9091955b906020529060405260605263ed572b275f526064601cfd5b6d01020000000000000001000000065f610124565b505090506d010300000000000000030000001d909197610124565b6d020200000000000000030000001c5f610124565b875186518b82036101b6578281036101d057505082156101e85795505050506001810191602001905f191480601757509060ed565b5090506d0103000000000000000400000023909199610124565b90506d01030000000000000004000000249091610124565b50506d020200000000000000040000001c5f610124565b50505050506d0202000000000000000a000000015f610124565b5050505090506d0103000000000000000a00000015909193610124565b50505050505050506d0103000000000000000a0000003181610124565b6d01020000000000000007000000065f610124565b6041602052634e487b715f526024601cfd" + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Evm1.lean b/Certified/arraymax/gen/ArrayMaxEntry/Evm1.lean new file mode 100644 index 00000000..a014885a --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Evm1.lean @@ -0,0 +1,392 @@ +-- solar-lean-stage: kind=evm index=1 pass=peephole-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime EVM IR after `peephole-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 3, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x3bf6de96)), + .op (.stack .eq), + .jumpi 2, + .jump 3], + -- bb2 + [.jump 4], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.swap 0)), + .op (.stack (.push 4)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack (.push 5)), + .op (.stack .shr), + .op (.stack (.dup 4)), + .op (.stack .gt), + .op (.stack .or), + .jumpi 42, + .jump 5], + -- bb5 + [.op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 42, + .jump 6], + -- bb6 + [.op (.stack (.dup 3)), + .op (.stack (.push 5)), + .op (.stack .shl), + .op (.stack (.dup 4)), + .op (.stack (.push 251)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 3)), + .op (.stack (.dup 1)), + .op (.stack .sgt), + .op (.stack (.dup 4)), + .op (.stack (.dup 0)), + .jumpi 40, + .jump 7], + -- bb7 + [.op (.stack .pop), + .jumpi 42, + .jump 8], + -- bb8 + [.op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 39, + .jump 9], + -- bb9 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .load, + .op (.stack (.swap 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.dup 6)), + .op (.stack (.dup 1)), + .op .store, + .op (.stack (.push 160)), + .op (.stack (.swap 2)), + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .effect .calldatacopy 3, + .op (.stack (.dup 0)), + .op .load, + .op (.stack (.swap 2)), + .op .load, + .op (.stack (.push 192)), + .op (.stack (.dup 3)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 38, + .jump 10], + -- bb10 + [.op (.stack (.dup 8)), + .op (.stack (.dup 0)), + .op (.stack .sub), + .jumpi 37, + .jump 11], + -- bb11 + [.op (.stack (.dup 8)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 36, + .jump 12], + -- bb12 + [.op (.stack (.dup 5)), + .op (.stack .iszero), + .jumpi 35, + .jump 13], + -- bb13 + [.op (.stack (.push 1)), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .jump 14], + -- bb14 + [.op (.stack (.dup 3)), + .op .load, + .op (.stack (.dup 6)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.dup 7)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 16, + .jump 15], + -- bb15 + [.op (.stack (.dup 0)), + .jumpi 20, + .jump 17], + -- bb16 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000020000001b)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 5)), + .jump 41], + -- bb17 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.dup 0)), + .jumpi 19, + .jump 18], + -- bb18 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb19 + [.op (.stack (.push 0x102000000000000000100000006)), + .op (.stack (.push 0)), + .jump 41], + -- bb20 + [.op (.stack (.dup 5)), + .op .load, + .op (.stack (.dup 4)), + .op .load, + .op (.stack (.dup 0)), + .op (.stack (.dup 7)), + .op (.stack .lt), + .op (.stack (.dup 10)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 23, + .jump 21], + -- bb21 + [.op (.stack (.dup 3)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 24, + .jump 22], + -- bb22 + [.op (.stack .pop), + .jumpi 25, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .jump 32], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000030000001d)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 7)), + .jump 41], + -- bb24 + [.op (.stack (.push 0x20200000000000000030000001c)), + .op (.stack (.push 0)), + .jump 41], + -- bb25 + [.op (.stack (.dup 7)), + .op .load, + .op (.stack (.dup 6)), + .op .load, + .op (.stack (.dup 11)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 29, + .jump 26], + -- bb26 + [.op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 30, + .jump 27], + -- bb27 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .jumpi 31, + .jump 28], + -- bb28 + [.op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .jump 32], + -- bb29 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000023)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 9)), + .jump 41], + -- bb30 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000024)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 41], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x20200000000000000040000001c)), + .op (.stack (.push 0)), + .jump 41], + -- bb32 + [.op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 34, + .jump 33], + -- bb33 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .jump 14], + -- bb34 + [.op (.stack (.push 0x102000000000000000500000028)), + .op (.stack (.push 0)), + .jump 41], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x202000000000000000a00000001)), + .op (.stack (.push 0)), + .jump 41], + -- bb36 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000015)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 41], + -- bb37 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack (.push 0x103000000000000000a00000031)), + .op (.stack (.swap 0)), + .jump 41], + -- bb38 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x112000000000000000a00000043)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 41], + -- bb39 + [.op (.stack (.push 65)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb40 + [.op (.stack (.push 0x102000000000000000700000006)), + .op (.stack (.push 0)), + .jump 41], + -- bb41 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb42 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Evm10.lean b/Certified/arraymax/gen/ArrayMaxEntry/Evm10.lean new file mode 100644 index 00000000..3ab3c849 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Evm10.lean @@ -0,0 +1,335 @@ +-- solar-lean-stage: kind=evm index=10 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm10 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x3bf6de96)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.swap 0)), + .op (.stack (.push 4)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack (.push 5)), + .op (.stack .shr), + .op (.stack (.dup 4)), + .op (.stack .gt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 1, + .op (.stack (.dup 3)), + .op (.stack (.push 5)), + .op (.stack .shl), + .op (.stack (.dup 4)), + .op (.stack (.push 251)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 3)), + .op (.stack (.dup 1)), + .op (.stack .sgt), + .op (.stack (.dup 4)), + .op (.stack (.dup 0)), + .jumpi 19, + .op (.stack .pop), + .jumpi 1, + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 20, + .op (.stack (.push 128)), + .op (.stack (.dup 0)), + .op (.stack (.swap 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.dup 6)), + .op (.stack (.dup 1)), + .op .store, + .op (.stack (.push 160)), + .op (.stack (.swap 2)), + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .effect .calldatacopy 3, + .op (.stack (.dup 0)), + .op .load, + .op (.stack (.swap 2)), + .op .load, + .op (.stack (.push 192)), + .op (.stack (.dup 8)), + .op (.stack (.dup 0)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.dup 8)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.dup 5)), + .op (.stack .iszero), + .jumpi 16, + .op (.stack (.push 1)), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .jump 3], + -- bb14 + [.op (.stack (.dup 3)), + .op .load, + .op (.stack (.dup 6)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.dup 7)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 4, + .op (.stack (.dup 0)), + .jumpi 7, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.dup 0)), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000020000001b)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 5)), + .jump 5], + -- bb41 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb19 + [.op (.stack (.push 0x102000000000000000100000006)), + .op (.stack (.push 0)), + .jump 5], + -- bb20 + [.op (.stack (.dup 5)), + .op .load, + .op (.stack (.dup 4)), + .op .load, + .op (.stack (.dup 0)), + .op (.stack (.dup 7)), + .op (.stack .lt), + .op (.stack (.dup 10)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.dup 3)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 10, + .op (.stack .pop), + .jumpi 11, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .jump 8], + -- bb32 + [.op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 3], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000030000001d)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 7)), + .jump 5], + -- bb24 + [.op (.stack (.push 0x20200000000000000030000001c)), + .op (.stack (.push 0)), + .jump 5], + -- bb25 + [.op (.stack (.dup 7)), + .op .load, + .op (.stack (.dup 6)), + .op .load, + .op (.stack (.dup 11)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 12, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 13, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.swap 5)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .jump 8], + -- bb29 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000023)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 9)), + .jump 5], + -- bb30 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000024)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 5], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x20200000000000000040000001c)), + .op (.stack (.push 0)), + .jump 5], + -- bb34 + [.op (.stack (.push 0x102000000000000000500000028)), + .op (.stack (.push 0)), + .jump 5], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x202000000000000000a00000001)), + .op (.stack (.push 0)), + .jump 5], + -- bb36 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000015)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 5], + -- bb37 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000031)), + .op (.stack (.dup 1)), + .jump 5], + -- bb40 + [.op (.stack (.push 0x102000000000000000700000006)), + .op (.stack (.push 0)), + .jump 5], + -- bb39 + [.op (.stack (.push 65)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Evm11.lean b/Certified/arraymax/gen/ArrayMaxEntry/Evm11.lean new file mode 100644 index 00000000..909dbad5 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Evm11.lean @@ -0,0 +1,334 @@ +-- solar-lean-stage: kind=evm index=11 pass=stack-reschedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime EVM IR after `stack-reschedule`. -/ +def evm11 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x3bf6de96)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.swap 0)), + .op (.stack (.push 4)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack (.push 5)), + .op (.stack .shr), + .op (.stack (.dup 4)), + .op (.stack .gt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 1, + .op (.stack (.dup 3)), + .op (.stack (.push 5)), + .op (.stack .shl), + .op (.stack (.dup 4)), + .op (.stack (.push 251)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 3)), + .op (.stack (.dup 1)), + .op (.stack .sgt), + .op (.stack (.dup 4)), + .op (.stack (.dup 0)), + .jumpi 19, + .op (.stack .pop), + .jumpi 1, + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 20, + .op (.stack (.push 128)), + .op (.stack .add), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 128)), + .op (.stack (.dup 0)), + .op (.stack (.dup 6)), + .op (.stack (.dup 1)), + .op .store, + .op (.stack (.push 160)), + .op (.stack (.swap 2)), + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .effect .calldatacopy 3, + .op (.stack (.dup 0)), + .op .load, + .op (.stack (.swap 2)), + .op .load, + .op (.stack (.push 192)), + .op (.stack (.dup 8)), + .op (.stack (.dup 0)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.dup 8)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.dup 5)), + .op (.stack .iszero), + .jumpi 16, + .op (.stack (.push 1)), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .jump 3], + -- bb14 + [.op (.stack (.dup 3)), + .op .load, + .op (.stack (.dup 6)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.dup 7)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 4, + .op (.stack (.dup 0)), + .jumpi 7, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.dup 0)), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000020000001b)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 5)), + .jump 5], + -- bb41 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb19 + [.op (.stack (.push 0x102000000000000000100000006)), + .op (.stack (.push 0)), + .jump 5], + -- bb20 + [.op (.stack (.dup 5)), + .op .load, + .op (.stack (.dup 4)), + .op .load, + .op (.stack (.dup 0)), + .op (.stack (.dup 7)), + .op (.stack .lt), + .op (.stack (.dup 10)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.dup 3)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 10, + .op (.stack .pop), + .jumpi 11, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .jump 8], + -- bb32 + [.op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 3], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000030000001d)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 7)), + .jump 5], + -- bb24 + [.op (.stack (.push 0x20200000000000000030000001c)), + .op (.stack (.push 0)), + .jump 5], + -- bb25 + [.op (.stack (.dup 7)), + .op .load, + .op (.stack (.dup 6)), + .op .load, + .op (.stack (.dup 11)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 12, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 13, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.swap 5)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .jump 8], + -- bb29 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000023)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 9)), + .jump 5], + -- bb30 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000024)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 5], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x20200000000000000040000001c)), + .op (.stack (.push 0)), + .jump 5], + -- bb34 + [.op (.stack (.push 0x102000000000000000500000028)), + .op (.stack (.push 0)), + .jump 5], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x202000000000000000a00000001)), + .op (.stack (.push 0)), + .jump 5], + -- bb36 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000015)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 5], + -- bb37 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000031)), + .op (.stack (.dup 1)), + .jump 5], + -- bb40 + [.op (.stack (.push 0x102000000000000000700000006)), + .op (.stack (.push 0)), + .jump 5], + -- bb39 + [.op (.stack (.push 65)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Evm12.lean b/Certified/arraymax/gen/ArrayMaxEntry/Evm12.lean new file mode 100644 index 00000000..02eab9ad --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Evm12.lean @@ -0,0 +1,348 @@ +-- solar-lean-stage: kind=evm index=12 pass=copy-loop-blocks +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime EVM IR after `copy-loop-blocks`. -/ +def evm12 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x3bf6de96)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.swap 0)), + .op (.stack (.push 4)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack (.push 5)), + .op (.stack .shr), + .op (.stack (.dup 4)), + .op (.stack .gt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 1, + .op (.stack (.dup 3)), + .op (.stack (.push 5)), + .op (.stack .shl), + .op (.stack (.dup 4)), + .op (.stack (.push 251)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 3)), + .op (.stack (.dup 1)), + .op (.stack .sgt), + .op (.stack (.dup 4)), + .op (.stack (.dup 0)), + .jumpi 19, + .op (.stack .pop), + .jumpi 1, + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 20, + .op (.stack (.push 128)), + .op (.stack .add), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 128)), + .op (.stack (.dup 0)), + .op (.stack (.dup 6)), + .op (.stack (.dup 1)), + .op .store, + .op (.stack (.push 160)), + .op (.stack (.swap 2)), + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .effect .calldatacopy 3, + .op (.stack (.dup 0)), + .op .load, + .op (.stack (.swap 2)), + .op .load, + .op (.stack (.push 192)), + .op (.stack (.dup 8)), + .op (.stack (.dup 0)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.dup 8)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.dup 5)), + .op (.stack .iszero), + .jumpi 16, + .op (.stack (.push 1)), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .jump 3], + -- bb14 + [.op (.stack (.dup 3)), + .op .load, + .op (.stack (.dup 6)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.dup 7)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 4, + .op (.stack (.dup 0)), + .jumpi 7, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.dup 0)), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000020000001b)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 5)), + .jump 5], + -- bb41 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb19 + [.op (.stack (.push 0x102000000000000000100000006)), + .op (.stack (.push 0)), + .jump 5], + -- bb20 + [.op (.stack (.dup 5)), + .op .load, + .op (.stack (.dup 4)), + .op .load, + .op (.stack (.dup 0)), + .op (.stack (.dup 7)), + .op (.stack .lt), + .op (.stack (.dup 10)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.dup 3)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 10, + .op (.stack .pop), + .jumpi 11, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .jump 8], + -- bb32 + [.op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 3], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000030000001d)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 7)), + .jump 5], + -- bb24 + [.op (.stack (.push 0x20200000000000000030000001c)), + .op (.stack (.push 0)), + .jump 5], + -- bb25 + [.op (.stack (.dup 7)), + .op .load, + .op (.stack (.dup 6)), + .op .load, + .op (.stack (.dup 11)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 12, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 13, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.swap 5)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 3], + -- bb29 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000023)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 9)), + .jump 5], + -- bb30 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000024)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 5], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x20200000000000000040000001c)), + .op (.stack (.push 0)), + .jump 5], + -- bb34 + [.op (.stack (.push 0x102000000000000000500000028)), + .op (.stack (.push 0)), + .jump 5], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x202000000000000000a00000001)), + .op (.stack (.push 0)), + .jump 5], + -- bb36 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000015)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 5], + -- bb37 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000031)), + .op (.stack (.dup 1)), + .jump 5], + -- bb40 + [.op (.stack (.push 0x102000000000000000700000006)), + .op (.stack (.push 0)), + .jump 5], + -- bb39 + [.op (.stack (.push 65)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Evm13.lean b/Certified/arraymax/gen/ArrayMaxEntry/Evm13.lean new file mode 100644 index 00000000..6e026ade --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Evm13.lean @@ -0,0 +1,346 @@ +-- solar-lean-stage: kind=evm index=13 pass=cfg-simplify +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime EVM IR after `cfg-simplify`. -/ +def evm13 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x3bf6de96)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.swap 0)), + .op (.stack (.push 4)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack (.push 5)), + .op (.stack .shr), + .op (.stack (.dup 4)), + .op (.stack .gt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 1, + .op (.stack (.dup 3)), + .op (.stack (.push 5)), + .op (.stack .shl), + .op (.stack (.dup 4)), + .op (.stack (.push 251)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 3)), + .op (.stack (.dup 1)), + .op (.stack .sgt), + .op (.stack (.dup 4)), + .op (.stack (.dup 0)), + .jumpi 18, + .op (.stack .pop), + .jumpi 1, + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 19, + .op (.stack (.push 128)), + .op (.stack .add), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 128)), + .op (.stack (.dup 0)), + .op (.stack (.dup 6)), + .op (.stack (.dup 1)), + .op .store, + .op (.stack (.push 160)), + .op (.stack (.swap 2)), + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .effect .calldatacopy 3, + .op (.stack (.dup 0)), + .op .load, + .op (.stack (.swap 2)), + .op .load, + .op (.stack (.push 192)), + .op (.stack (.dup 8)), + .op (.stack (.dup 0)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.dup 8)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 16, + .op (.stack (.dup 5)), + .op (.stack .iszero), + .jumpi 15, + .op (.stack (.push 1)), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .jump 3], + -- bb14 + [.op (.stack (.dup 3)), + .op .load, + .op (.stack (.dup 6)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.dup 7)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 4, + .op (.stack (.dup 0)), + .jumpi 7, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.dup 0)), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000020000001b)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 5)), + .jump 5], + -- bb41 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb19 + [.op (.stack (.push 0x102000000000000000100000006)), + .op (.stack (.push 0)), + .jump 5], + -- bb20 + [.op (.stack (.dup 5)), + .op .load, + .op (.stack (.dup 4)), + .op .load, + .op (.stack (.dup 0)), + .op (.stack (.dup 7)), + .op (.stack .lt), + .op (.stack (.dup 10)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 8, + .op (.stack (.dup 3)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 9, + .op (.stack .pop), + .jumpi 10, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 14, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 3], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000030000001d)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 7)), + .jump 5], + -- bb24 + [.op (.stack (.push 0x20200000000000000030000001c)), + .op (.stack (.push 0)), + .jump 5], + -- bb25 + [.op (.stack (.dup 7)), + .op .load, + .op (.stack (.dup 6)), + .op .load, + .op (.stack (.dup 11)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 11, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 12, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .jumpi 13, + .op (.stack (.swap 5)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 14, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 3], + -- bb29 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000023)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 9)), + .jump 5], + -- bb30 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000024)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 5], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x20200000000000000040000001c)), + .op (.stack (.push 0)), + .jump 5], + -- bb34 + [.op (.stack (.push 0x102000000000000000500000028)), + .op (.stack (.push 0)), + .jump 5], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x202000000000000000a00000001)), + .op (.stack (.push 0)), + .jump 5], + -- bb36 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000015)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 5], + -- bb37 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000031)), + .op (.stack (.dup 1)), + .jump 5], + -- bb40 + [.op (.stack (.push 0x102000000000000000700000006)), + .op (.stack (.push 0)), + .jump 5], + -- bb39 + [.op (.stack (.push 65)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Evm14.lean b/Certified/arraymax/gen/ArrayMaxEntry/Evm14.lean new file mode 100644 index 00000000..fd78c88d --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Evm14.lean @@ -0,0 +1,346 @@ +-- solar-lean-stage: kind=evm index=14 pass=loop-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime EVM IR after `loop-layout`. -/ +def evm14 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x3bf6de96)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 0x102000000000000000500000028)), + .op (.stack (.push 0)), + .jump 7], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.swap 0)), + .op (.stack (.push 4)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack (.push 5)), + .op (.stack .shr), + .op (.stack (.dup 4)), + .op (.stack .gt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 1, + .op (.stack (.dup 3)), + .op (.stack (.push 5)), + .op (.stack .shl), + .op (.stack (.dup 4)), + .op (.stack (.push 251)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 3)), + .op (.stack (.dup 1)), + .op (.stack .sgt), + .op (.stack (.dup 4)), + .op (.stack (.dup 0)), + .jumpi 18, + .op (.stack .pop), + .jumpi 1, + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 19, + .op (.stack (.push 128)), + .op (.stack .add), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 128)), + .op (.stack (.dup 0)), + .op (.stack (.dup 6)), + .op (.stack (.dup 1)), + .op .store, + .op (.stack (.push 160)), + .op (.stack (.swap 2)), + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .effect .calldatacopy 3, + .op (.stack (.dup 0)), + .op .load, + .op (.stack (.swap 2)), + .op .load, + .op (.stack (.push 192)), + .op (.stack (.dup 8)), + .op (.stack (.dup 0)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.dup 8)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 16, + .op (.stack (.dup 5)), + .op (.stack .iszero), + .jumpi 15, + .op (.stack (.push 1)), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .jump 5], + -- bb20 + [.op (.stack (.dup 5)), + .op .load, + .op (.stack (.dup 4)), + .op .load, + .op (.stack (.dup 0)), + .op (.stack (.dup 7)), + .op (.stack .lt), + .op (.stack (.dup 10)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.dup 3)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 10, + .op (.stack .pop), + .jumpi 11, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 2, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 5], + -- bb14 + [.op (.stack (.dup 3)), + .op .load, + .op (.stack (.dup 6)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.dup 7)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 6, + .op (.stack (.dup 0)), + .jumpi 4, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.dup 0)), + .jumpi 8, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000020000001b)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 5)), + .jump 7], + -- bb41 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb19 + [.op (.stack (.push 0x102000000000000000100000006)), + .op (.stack (.push 0)), + .jump 7], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000030000001d)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 7)), + .jump 7], + -- bb24 + [.op (.stack (.push 0x20200000000000000030000001c)), + .op (.stack (.push 0)), + .jump 7], + -- bb25 + [.op (.stack (.dup 7)), + .op .load, + .op (.stack (.dup 6)), + .op .load, + .op (.stack (.dup 11)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 12, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 13, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.swap 5)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 2, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 5], + -- bb29 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000023)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 9)), + .jump 7], + -- bb30 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000024)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 7], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x20200000000000000040000001c)), + .op (.stack (.push 0)), + .jump 7], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x202000000000000000a00000001)), + .op (.stack (.push 0)), + .jump 7], + -- bb36 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000015)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 7], + -- bb37 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000031)), + .op (.stack (.dup 1)), + .jump 7], + -- bb40 + [.op (.stack (.push 0x102000000000000000700000006)), + .op (.stack (.push 0)), + .jump 7], + -- bb39 + [.op (.stack (.push 65)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Evm15.lean b/Certified/arraymax/gen/ArrayMaxEntry/Evm15.lean new file mode 100644 index 00000000..8fe0bac4 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Evm15.lean @@ -0,0 +1,345 @@ +-- solar-lean-stage: kind=evm index=15 pass=reorder-expressions +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime EVM IR after `reorder-expressions`. -/ +def evm15 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x3bf6de96)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 0x102000000000000000500000028)), + .op (.stack (.push 0)), + .jump 7], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 4)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack (.push 5)), + .op (.stack .shr), + .op (.stack (.dup 4)), + .op (.stack .gt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 1, + .op (.stack (.dup 3)), + .op (.stack (.push 5)), + .op (.stack .shl), + .op (.stack (.dup 4)), + .op (.stack (.push 251)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 3)), + .op (.stack (.dup 1)), + .op (.stack .sgt), + .op (.stack (.dup 4)), + .op (.stack (.dup 0)), + .jumpi 18, + .op (.stack .pop), + .jumpi 1, + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 19, + .op (.stack (.push 128)), + .op (.stack .add), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 128)), + .op (.stack (.dup 0)), + .op (.stack (.dup 6)), + .op (.stack (.dup 1)), + .op .store, + .op (.stack (.push 160)), + .op (.stack (.swap 2)), + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .effect .calldatacopy 3, + .op (.stack (.dup 0)), + .op .load, + .op (.stack (.swap 2)), + .op .load, + .op (.stack (.push 192)), + .op (.stack (.dup 8)), + .op (.stack (.dup 0)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.dup 8)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 16, + .op (.stack (.dup 5)), + .op (.stack .iszero), + .jumpi 15, + .op (.stack (.push 1)), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .jump 5], + -- bb20 + [.op (.stack (.dup 5)), + .op .load, + .op (.stack (.dup 4)), + .op .load, + .op (.stack (.dup 0)), + .op (.stack (.dup 7)), + .op (.stack .lt), + .op (.stack (.dup 10)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.dup 3)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 10, + .op (.stack .pop), + .jumpi 11, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 2, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 5], + -- bb14 + [.op (.stack (.dup 3)), + .op .load, + .op (.stack (.dup 6)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.dup 7)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 6, + .op (.stack (.dup 0)), + .jumpi 4, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.dup 0)), + .jumpi 8, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000020000001b)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 5)), + .jump 7], + -- bb41 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb19 + [.op (.stack (.push 0x102000000000000000100000006)), + .op (.stack (.push 0)), + .jump 7], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000030000001d)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 7)), + .jump 7], + -- bb24 + [.op (.stack (.push 0x20200000000000000030000001c)), + .op (.stack (.push 0)), + .jump 7], + -- bb25 + [.op (.stack (.dup 7)), + .op .load, + .op (.stack (.dup 6)), + .op .load, + .op (.stack (.dup 11)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 12, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 13, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.swap 5)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 2, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 5], + -- bb29 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000023)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 9)), + .jump 7], + -- bb30 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000024)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 7], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x20200000000000000040000001c)), + .op (.stack (.push 0)), + .jump 7], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x202000000000000000a00000001)), + .op (.stack (.push 0)), + .jump 7], + -- bb36 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000015)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 7], + -- bb37 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000031)), + .op (.stack (.dup 1)), + .jump 7], + -- bb40 + [.op (.stack (.push 0x102000000000000000700000006)), + .op (.stack (.push 0)), + .jump 7], + -- bb39 + [.op (.stack (.push 65)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Evm2.lean b/Certified/arraymax/gen/ArrayMaxEntry/Evm2.lean new file mode 100644 index 00000000..50675f31 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Evm2.lean @@ -0,0 +1,352 @@ +-- solar-lean-stage: kind=evm index=2 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x3bf6de96)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.swap 0)), + .op (.stack (.push 4)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack (.push 5)), + .op (.stack .shr), + .op (.stack (.dup 4)), + .op (.stack .gt), + .op (.stack .or), + .jumpi 22, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 22, + .op (.stack (.dup 3)), + .op (.stack (.push 5)), + .op (.stack .shl), + .op (.stack (.dup 4)), + .op (.stack (.push 251)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 3)), + .op (.stack (.dup 1)), + .op (.stack .sgt), + .op (.stack (.dup 4)), + .op (.stack (.dup 0)), + .jumpi 20, + .op (.stack .pop), + .jumpi 22, + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 19, + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .load, + .op (.stack (.swap 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.dup 6)), + .op (.stack (.dup 1)), + .op .store, + .op (.stack (.push 160)), + .op (.stack (.swap 2)), + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .effect .calldatacopy 3, + .op (.stack (.dup 0)), + .op .load, + .op (.stack (.swap 2)), + .op .load, + .op (.stack (.push 192)), + .op (.stack (.dup 3)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.dup 8)), + .op (.stack (.dup 0)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.dup 8)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 16, + .op (.stack (.dup 5)), + .op (.stack .iszero), + .jumpi 15, + .op (.stack (.push 1)), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .jump 3], + -- bb14 + [.op (.stack (.dup 3)), + .op .load, + .op (.stack (.dup 6)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.dup 7)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 4, + .op (.stack (.dup 0)), + .jumpi 6, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.dup 0)), + .jumpi 5, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000020000001b)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 5)), + .jump 21], + -- bb19 + [.op (.stack (.push 0x102000000000000000100000006)), + .op (.stack (.push 0)), + .jump 21], + -- bb20 + [.op (.stack (.dup 5)), + .op .load, + .op (.stack (.dup 4)), + .op .load, + .op (.stack (.dup 0)), + .op (.stack (.dup 7)), + .op (.stack .lt), + .op (.stack (.dup 10)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 7, + .op (.stack (.dup 3)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 8, + .op (.stack .pop), + .jumpi 9, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .jump 13], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000030000001d)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 7)), + .jump 21], + -- bb24 + [.op (.stack (.push 0x20200000000000000030000001c)), + .op (.stack (.push 0)), + .jump 21], + -- bb25 + [.op (.stack (.dup 7)), + .op .load, + .op (.stack (.dup 6)), + .op .load, + .op (.stack (.dup 11)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 10, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 11, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .jumpi 12, + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .jump 13], + -- bb29 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000023)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 9)), + .jump 21], + -- bb30 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000024)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 21], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x20200000000000000040000001c)), + .op (.stack (.push 0)), + .jump 21], + -- bb32 + [.op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 14, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 3], + -- bb34 + [.op (.stack (.push 0x102000000000000000500000028)), + .op (.stack (.push 0)), + .jump 21], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x202000000000000000a00000001)), + .op (.stack (.push 0)), + .jump 21], + -- bb36 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000015)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 21], + -- bb37 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack (.push 0x103000000000000000a00000031)), + .op (.stack (.swap 0)), + .jump 21], + -- bb38 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x112000000000000000a00000043)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 21], + -- bb39 + [.op (.stack (.push 65)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb40 + [.op (.stack (.push 0x102000000000000000700000006)), + .op (.stack (.push 0)), + .jump 21], + -- bb41 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb42 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Evm3.lean b/Certified/arraymax/gen/ArrayMaxEntry/Evm3.lean new file mode 100644 index 00000000..add97dfc --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Evm3.lean @@ -0,0 +1,353 @@ +-- solar-lean-stage: kind=evm index=3 pass=compact-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime EVM IR after `compact-pushes`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x3bf6de96)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.swap 0)), + .op (.stack (.push 4)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack (.push 5)), + .op (.stack .shr), + .op (.stack (.dup 4)), + .op (.stack .gt), + .op (.stack .or), + .jumpi 22, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 22, + .op (.stack (.dup 3)), + .op (.stack (.push 5)), + .op (.stack .shl), + .op (.stack (.dup 4)), + .op (.stack (.push 251)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 3)), + .op (.stack (.dup 1)), + .op (.stack .sgt), + .op (.stack (.dup 4)), + .op (.stack (.dup 0)), + .jumpi 20, + .op (.stack .pop), + .jumpi 22, + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 19, + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .load, + .op (.stack (.swap 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.dup 6)), + .op (.stack (.dup 1)), + .op .store, + .op (.stack (.push 160)), + .op (.stack (.swap 2)), + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .effect .calldatacopy 3, + .op (.stack (.dup 0)), + .op .load, + .op (.stack (.swap 2)), + .op .load, + .op (.stack (.push 192)), + .op (.stack (.dup 3)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.dup 8)), + .op (.stack (.dup 0)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.dup 8)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 16, + .op (.stack (.dup 5)), + .op (.stack .iszero), + .jumpi 15, + .op (.stack (.push 1)), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .jump 3], + -- bb14 + [.op (.stack (.dup 3)), + .op .load, + .op (.stack (.dup 6)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.dup 7)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 4, + .op (.stack (.dup 0)), + .jumpi 6, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.dup 0)), + .jumpi 5, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000020000001b)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 5)), + .jump 21], + -- bb19 + [.op (.stack (.push 0x102000000000000000100000006)), + .op (.stack (.push 0)), + .jump 21], + -- bb20 + [.op (.stack (.dup 5)), + .op .load, + .op (.stack (.dup 4)), + .op .load, + .op (.stack (.dup 0)), + .op (.stack (.dup 7)), + .op (.stack .lt), + .op (.stack (.dup 10)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 7, + .op (.stack (.dup 3)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 8, + .op (.stack .pop), + .jumpi 9, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .jump 13], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000030000001d)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 7)), + .jump 21], + -- bb24 + [.op (.stack (.push 0x20200000000000000030000001c)), + .op (.stack (.push 0)), + .jump 21], + -- bb25 + [.op (.stack (.dup 7)), + .op .load, + .op (.stack (.dup 6)), + .op .load, + .op (.stack (.dup 11)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 10, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 11, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .jumpi 12, + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .jump 13], + -- bb29 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000023)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 9)), + .jump 21], + -- bb30 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000024)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 21], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x20200000000000000040000001c)), + .op (.stack (.push 0)), + .jump 21], + -- bb32 + [.op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 14, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 3], + -- bb34 + [.op (.stack (.push 0x102000000000000000500000028)), + .op (.stack (.push 0)), + .jump 21], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x202000000000000000a00000001)), + .op (.stack (.push 0)), + .jump 21], + -- bb36 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000015)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 21], + -- bb37 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack (.push 0x103000000000000000a00000031)), + .op (.stack (.swap 0)), + .jump 21], + -- bb38 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x112000000000000000a00000043)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 21], + -- bb39 + [.op (.stack (.push 65)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb40 + [.op (.stack (.push 0x102000000000000000700000006)), + .op (.stack (.push 0)), + .jump 21], + -- bb41 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb42 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Evm4.lean b/Certified/arraymax/gen/ArrayMaxEntry/Evm4.lean new file mode 100644 index 00000000..023c5939 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Evm4.lean @@ -0,0 +1,353 @@ +-- solar-lean-stage: kind=evm index=4 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime EVM IR after `block-layout`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x3bf6de96)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb42 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.swap 0)), + .op (.stack (.push 4)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack (.push 5)), + .op (.stack .shr), + .op (.stack (.dup 4)), + .op (.stack .gt), + .op (.stack .or), + .jumpi 2, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 2, + .op (.stack (.dup 3)), + .op (.stack (.push 5)), + .op (.stack .shl), + .op (.stack (.dup 4)), + .op (.stack (.push 251)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 3)), + .op (.stack (.dup 1)), + .op (.stack .sgt), + .op (.stack (.dup 4)), + .op (.stack (.dup 0)), + .jumpi 21, + .op (.stack .pop), + .jumpi 2, + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 22, + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .load, + .op (.stack (.swap 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.dup 6)), + .op (.stack (.dup 1)), + .op .store, + .op (.stack (.push 160)), + .op (.stack (.swap 2)), + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .effect .calldatacopy 3, + .op (.stack (.dup 0)), + .op .load, + .op (.stack (.swap 2)), + .op .load, + .op (.stack (.push 192)), + .op (.stack (.dup 3)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 20, + .op (.stack (.dup 8)), + .op (.stack (.dup 0)), + .op (.stack .sub), + .jumpi 19, + .op (.stack (.dup 8)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.dup 5)), + .op (.stack .iszero), + .jumpi 17, + .op (.stack (.push 1)), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .jump 4], + -- bb14 + [.op (.stack (.dup 3)), + .op .load, + .op (.stack (.dup 6)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.dup 7)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 5, + .op (.stack (.dup 0)), + .jumpi 8, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.dup 0)), + .jumpi 7, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000020000001b)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 5)), + .jump 6], + -- bb41 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb19 + [.op (.stack (.push 0x102000000000000000100000006)), + .op (.stack (.push 0)), + .jump 6], + -- bb20 + [.op (.stack (.dup 5)), + .op .load, + .op (.stack (.dup 4)), + .op .load, + .op (.stack (.dup 0)), + .op (.stack (.dup 7)), + .op (.stack .lt), + .op (.stack (.dup 10)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 10, + .op (.stack (.dup 3)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 11, + .op (.stack .pop), + .jumpi 12, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .jump 9], + -- bb32 + [.op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 16, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 4], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000030000001d)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 7)), + .jump 6], + -- bb24 + [.op (.stack (.push 0x20200000000000000030000001c)), + .op (.stack (.push 0)), + .jump 6], + -- bb25 + [.op (.stack (.dup 7)), + .op .load, + .op (.stack (.dup 6)), + .op .load, + .op (.stack (.dup 11)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 13, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 14, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .jumpi 15, + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .jump 9], + -- bb29 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000023)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 9)), + .jump 6], + -- bb30 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000024)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 6], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x20200000000000000040000001c)), + .op (.stack (.push 0)), + .jump 6], + -- bb34 + [.op (.stack (.push 0x102000000000000000500000028)), + .op (.stack (.push 0)), + .jump 6], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x202000000000000000a00000001)), + .op (.stack (.push 0)), + .jump 6], + -- bb36 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000015)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 6], + -- bb37 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack (.push 0x103000000000000000a00000031)), + .op (.stack (.swap 0)), + .jump 6], + -- bb38 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x112000000000000000a00000043)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 6], + -- bb40 + [.op (.stack (.push 0x102000000000000000700000006)), + .op (.stack (.push 0)), + .jump 6], + -- bb39 + [.op (.stack (.push 65)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Evm5.lean b/Certified/arraymax/gen/ArrayMaxEntry/Evm5.lean new file mode 100644 index 00000000..2f303306 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Evm5.lean @@ -0,0 +1,351 @@ +-- solar-lean-stage: kind=evm index=5 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x3bf6de96)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb42 + [.jump 1], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.swap 0)), + .op (.stack (.push 4)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack (.push 5)), + .op (.stack .shr), + .op (.stack (.dup 4)), + .op (.stack .gt), + .op (.stack .or), + .jumpi 2, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 2, + .op (.stack (.dup 3)), + .op (.stack (.push 5)), + .op (.stack .shl), + .op (.stack (.dup 4)), + .op (.stack (.push 251)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 3)), + .op (.stack (.dup 1)), + .op (.stack .sgt), + .op (.stack (.dup 4)), + .op (.stack (.dup 0)), + .jumpi 21, + .op (.stack .pop), + .jumpi 2, + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 22, + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .load, + .op (.stack (.swap 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.dup 6)), + .op (.stack (.dup 1)), + .op .store, + .op (.stack (.push 160)), + .op (.stack (.swap 2)), + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .effect .calldatacopy 3, + .op (.stack (.dup 0)), + .op .load, + .op (.stack (.swap 2)), + .op .load, + .op (.stack (.push 192)), + .op (.stack (.dup 3)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 20, + .op (.stack (.dup 8)), + .op (.stack (.dup 0)), + .op (.stack .sub), + .jumpi 19, + .op (.stack (.dup 8)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.dup 5)), + .op (.stack .iszero), + .jumpi 17, + .op (.stack (.push 1)), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .jump 4], + -- bb14 + [.op (.stack (.dup 3)), + .op .load, + .op (.stack (.dup 6)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.dup 7)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 5, + .op (.stack (.dup 0)), + .jumpi 8, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.dup 0)), + .jumpi 7, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000020000001b)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 5)), + .jump 6], + -- bb41 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb19 + [.op (.stack (.push 0x102000000000000000100000006)), + .op (.stack (.push 0)), + .jump 6], + -- bb20 + [.op (.stack (.dup 5)), + .op .load, + .op (.stack (.dup 4)), + .op .load, + .op (.stack (.dup 0)), + .op (.stack (.dup 7)), + .op (.stack .lt), + .op (.stack (.dup 10)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 10, + .op (.stack (.dup 3)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 11, + .op (.stack .pop), + .jumpi 12, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .jump 9], + -- bb32 + [.op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 16, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 4], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000030000001d)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 7)), + .jump 6], + -- bb24 + [.op (.stack (.push 0x20200000000000000030000001c)), + .op (.stack (.push 0)), + .jump 6], + -- bb25 + [.op (.stack (.dup 7)), + .op .load, + .op (.stack (.dup 6)), + .op .load, + .op (.stack (.dup 11)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 13, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 14, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .jumpi 15, + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .jump 9], + -- bb29 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000023)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 9)), + .jump 6], + -- bb30 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000024)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 6], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x20200000000000000040000001c)), + .op (.stack (.push 0)), + .jump 6], + -- bb34 + [.op (.stack (.push 0x102000000000000000500000028)), + .op (.stack (.push 0)), + .jump 6], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x202000000000000000a00000001)), + .op (.stack (.push 0)), + .jump 6], + -- bb36 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000015)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 6], + -- bb37 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack (.push 0x103000000000000000a00000031)), + .op (.stack (.swap 0)), + .jump 6], + -- bb38 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x112000000000000000a00000043)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 6], + -- bb40 + [.op (.stack (.push 0x102000000000000000700000006)), + .op (.stack (.push 0)), + .jump 6], + -- bb39 + [.op (.stack (.push 65)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Evm6.lean b/Certified/arraymax/gen/ArrayMaxEntry/Evm6.lean new file mode 100644 index 00000000..c45ee2c9 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Evm6.lean @@ -0,0 +1,349 @@ +-- solar-lean-stage: kind=evm index=6 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm6 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x3bf6de96)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.swap 0)), + .op (.stack (.push 4)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack (.push 5)), + .op (.stack .shr), + .op (.stack (.dup 4)), + .op (.stack .gt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 1, + .op (.stack (.dup 3)), + .op (.stack (.push 5)), + .op (.stack .shl), + .op (.stack (.dup 4)), + .op (.stack (.push 251)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 3)), + .op (.stack (.dup 1)), + .op (.stack .sgt), + .op (.stack (.dup 4)), + .op (.stack (.dup 0)), + .jumpi 20, + .op (.stack .pop), + .jumpi 1, + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 21, + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .load, + .op (.stack (.swap 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.dup 6)), + .op (.stack (.dup 1)), + .op .store, + .op (.stack (.push 160)), + .op (.stack (.swap 2)), + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .effect .calldatacopy 3, + .op (.stack (.dup 0)), + .op .load, + .op (.stack (.swap 2)), + .op .load, + .op (.stack (.push 192)), + .op (.stack (.dup 3)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 19, + .op (.stack (.dup 8)), + .op (.stack (.dup 0)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.dup 8)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.dup 5)), + .op (.stack .iszero), + .jumpi 16, + .op (.stack (.push 1)), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .jump 3], + -- bb14 + [.op (.stack (.dup 3)), + .op .load, + .op (.stack (.dup 6)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.dup 7)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 4, + .op (.stack (.dup 0)), + .jumpi 7, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.dup 0)), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000020000001b)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 5)), + .jump 5], + -- bb41 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb19 + [.op (.stack (.push 0x102000000000000000100000006)), + .op (.stack (.push 0)), + .jump 5], + -- bb20 + [.op (.stack (.dup 5)), + .op .load, + .op (.stack (.dup 4)), + .op .load, + .op (.stack (.dup 0)), + .op (.stack (.dup 7)), + .op (.stack .lt), + .op (.stack (.dup 10)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.dup 3)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 10, + .op (.stack .pop), + .jumpi 11, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .jump 8], + -- bb32 + [.op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 3], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000030000001d)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 7)), + .jump 5], + -- bb24 + [.op (.stack (.push 0x20200000000000000030000001c)), + .op (.stack (.push 0)), + .jump 5], + -- bb25 + [.op (.stack (.dup 7)), + .op .load, + .op (.stack (.dup 6)), + .op .load, + .op (.stack (.dup 11)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 12, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 13, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .jump 8], + -- bb29 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000023)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 9)), + .jump 5], + -- bb30 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000024)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 5], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x20200000000000000040000001c)), + .op (.stack (.push 0)), + .jump 5], + -- bb34 + [.op (.stack (.push 0x102000000000000000500000028)), + .op (.stack (.push 0)), + .jump 5], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x202000000000000000a00000001)), + .op (.stack (.push 0)), + .jump 5], + -- bb36 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000015)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 5], + -- bb37 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack (.push 0x103000000000000000a00000031)), + .op (.stack (.swap 0)), + .jump 5], + -- bb38 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x112000000000000000a00000043)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 5], + -- bb40 + [.op (.stack (.push 0x102000000000000000700000006)), + .op (.stack (.push 0)), + .jump 5], + -- bb39 + [.op (.stack (.push 65)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Evm7.lean b/Certified/arraymax/gen/ArrayMaxEntry/Evm7.lean new file mode 100644 index 00000000..0d9614c9 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Evm7.lean @@ -0,0 +1,348 @@ +-- solar-lean-stage: kind=evm index=7 pass=reorder-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime EVM IR after `reorder-pushes`. -/ +def evm7 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x3bf6de96)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.swap 0)), + .op (.stack (.push 4)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack (.push 5)), + .op (.stack .shr), + .op (.stack (.dup 4)), + .op (.stack .gt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 1, + .op (.stack (.dup 3)), + .op (.stack (.push 5)), + .op (.stack .shl), + .op (.stack (.dup 4)), + .op (.stack (.push 251)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 3)), + .op (.stack (.dup 1)), + .op (.stack .sgt), + .op (.stack (.dup 4)), + .op (.stack (.dup 0)), + .jumpi 20, + .op (.stack .pop), + .jumpi 1, + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 21, + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .load, + .op (.stack (.swap 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.dup 6)), + .op (.stack (.dup 1)), + .op .store, + .op (.stack (.push 160)), + .op (.stack (.swap 2)), + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .effect .calldatacopy 3, + .op (.stack (.dup 0)), + .op .load, + .op (.stack (.swap 2)), + .op .load, + .op (.stack (.push 192)), + .op (.stack (.dup 3)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 19, + .op (.stack (.dup 8)), + .op (.stack (.dup 0)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.dup 8)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.dup 5)), + .op (.stack .iszero), + .jumpi 16, + .op (.stack (.push 1)), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .jump 3], + -- bb14 + [.op (.stack (.dup 3)), + .op .load, + .op (.stack (.dup 6)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.dup 7)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 4, + .op (.stack (.dup 0)), + .jumpi 7, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.dup 0)), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000020000001b)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 5)), + .jump 5], + -- bb41 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb19 + [.op (.stack (.push 0x102000000000000000100000006)), + .op (.stack (.push 0)), + .jump 5], + -- bb20 + [.op (.stack (.dup 5)), + .op .load, + .op (.stack (.dup 4)), + .op .load, + .op (.stack (.dup 0)), + .op (.stack (.dup 7)), + .op (.stack .lt), + .op (.stack (.dup 10)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.dup 3)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 10, + .op (.stack .pop), + .jumpi 11, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .jump 8], + -- bb32 + [.op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 3], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000030000001d)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 7)), + .jump 5], + -- bb24 + [.op (.stack (.push 0x20200000000000000030000001c)), + .op (.stack (.push 0)), + .jump 5], + -- bb25 + [.op (.stack (.dup 7)), + .op .load, + .op (.stack (.dup 6)), + .op .load, + .op (.stack (.dup 11)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 12, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 13, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .jump 8], + -- bb29 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000023)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 9)), + .jump 5], + -- bb30 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000024)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 5], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x20200000000000000040000001c)), + .op (.stack (.push 0)), + .jump 5], + -- bb34 + [.op (.stack (.push 0x102000000000000000500000028)), + .op (.stack (.push 0)), + .jump 5], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x202000000000000000a00000001)), + .op (.stack (.push 0)), + .jump 5], + -- bb36 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000015)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 5], + -- bb37 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000031)), + .op (.stack (.dup 1)), + .jump 5], + -- bb38 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x112000000000000000a00000043)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 5], + -- bb40 + [.op (.stack (.push 0x102000000000000000700000006)), + .op (.stack (.push 0)), + .jump 5], + -- bb39 + [.op (.stack (.push 65)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Evm8.lean b/Certified/arraymax/gen/ArrayMaxEntry/Evm8.lean new file mode 100644 index 00000000..c8bc7cbf --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Evm8.lean @@ -0,0 +1,343 @@ +-- solar-lean-stage: kind=evm index=8 pass=block-cse +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime EVM IR after `block-cse`. -/ +def evm8 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x3bf6de96)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.swap 0)), + .op (.stack (.push 4)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack (.push 5)), + .op (.stack .shr), + .op (.stack (.dup 4)), + .op (.stack .gt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 1, + .op (.stack (.dup 3)), + .op (.stack (.push 5)), + .op (.stack .shl), + .op (.stack (.dup 4)), + .op (.stack (.push 251)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 3)), + .op (.stack (.dup 1)), + .op (.stack .sgt), + .op (.stack (.dup 4)), + .op (.stack (.dup 0)), + .jumpi 20, + .op (.stack .pop), + .jumpi 1, + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 21, + .op (.stack (.push 128)), + .op (.stack (.dup 0)), + .op (.stack (.swap 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.dup 6)), + .op (.stack (.dup 1)), + .op .store, + .op (.stack (.push 160)), + .op (.stack (.swap 2)), + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .effect .calldatacopy 3, + .op (.stack (.dup 0)), + .op .load, + .op (.stack (.swap 2)), + .op .load, + .op (.stack (.push 192)), + .op (.stack (.dup 8)), + .op (.stack (.dup 0)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.dup 8)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.dup 5)), + .op (.stack .iszero), + .jumpi 16, + .op (.stack (.push 1)), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .jump 3], + -- bb14 + [.op (.stack (.dup 3)), + .op .load, + .op (.stack (.dup 6)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.dup 7)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 4, + .op (.stack (.dup 0)), + .jumpi 7, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.dup 0)), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000020000001b)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 5)), + .jump 5], + -- bb41 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb19 + [.op (.stack (.push 0x102000000000000000100000006)), + .op (.stack (.push 0)), + .jump 5], + -- bb20 + [.op (.stack (.dup 5)), + .op .load, + .op (.stack (.dup 4)), + .op .load, + .op (.stack (.dup 0)), + .op (.stack (.dup 7)), + .op (.stack .lt), + .op (.stack (.dup 10)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.dup 3)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 10, + .op (.stack .pop), + .jumpi 11, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .jump 8], + -- bb32 + [.op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 3], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000030000001d)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 7)), + .jump 5], + -- bb24 + [.op (.stack (.push 0x20200000000000000030000001c)), + .op (.stack (.push 0)), + .jump 5], + -- bb25 + [.op (.stack (.dup 7)), + .op .load, + .op (.stack (.dup 6)), + .op .load, + .op (.stack (.dup 11)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 12, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 13, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .jump 8], + -- bb29 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000023)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 9)), + .jump 5], + -- bb30 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000024)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 5], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x20200000000000000040000001c)), + .op (.stack (.push 0)), + .jump 5], + -- bb34 + [.op (.stack (.push 0x102000000000000000500000028)), + .op (.stack (.push 0)), + .jump 5], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x202000000000000000a00000001)), + .op (.stack (.push 0)), + .jump 5], + -- bb36 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000015)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 5], + -- bb37 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000031)), + .op (.stack (.dup 1)), + .jump 5], + -- bb38 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x112000000000000000a00000043)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 5], + -- bb40 + [.op (.stack (.push 0x102000000000000000700000006)), + .op (.stack (.push 0)), + .jump 5], + -- bb39 + [.op (.stack (.push 65)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Evm9.lean b/Certified/arraymax/gen/ArrayMaxEntry/Evm9.lean new file mode 100644 index 00000000..d0cc1ae6 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Evm9.lean @@ -0,0 +1,342 @@ +-- solar-lean-stage: kind=evm index=9 pass=stack-normalize +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime EVM IR after `stack-normalize`. -/ +def evm9 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x3bf6de96)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.swap 0)), + .op (.stack (.push 4)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack (.push 5)), + .op (.stack .shr), + .op (.stack (.dup 4)), + .op (.stack .gt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 1, + .op (.stack (.dup 3)), + .op (.stack (.push 5)), + .op (.stack .shl), + .op (.stack (.dup 4)), + .op (.stack (.push 251)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 3)), + .op (.stack (.dup 1)), + .op (.stack .sgt), + .op (.stack (.dup 4)), + .op (.stack (.dup 0)), + .jumpi 20, + .op (.stack .pop), + .jumpi 1, + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 21, + .op (.stack (.push 128)), + .op (.stack (.dup 0)), + .op (.stack (.swap 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.dup 6)), + .op (.stack (.dup 1)), + .op .store, + .op (.stack (.push 160)), + .op (.stack (.swap 2)), + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .effect .calldatacopy 3, + .op (.stack (.dup 0)), + .op .load, + .op (.stack (.swap 2)), + .op .load, + .op (.stack (.push 192)), + .op (.stack (.dup 8)), + .op (.stack (.dup 0)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.dup 8)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.dup 5)), + .op (.stack .iszero), + .jumpi 16, + .op (.stack (.push 1)), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .jump 3], + -- bb14 + [.op (.stack (.dup 3)), + .op .load, + .op (.stack (.dup 6)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.dup 7)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 4, + .op (.stack (.dup 0)), + .jumpi 7, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.dup 0)), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000020000001b)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 5)), + .jump 5], + -- bb41 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb19 + [.op (.stack (.push 0x102000000000000000100000006)), + .op (.stack (.push 0)), + .jump 5], + -- bb20 + [.op (.stack (.dup 5)), + .op .load, + .op (.stack (.dup 4)), + .op .load, + .op (.stack (.dup 0)), + .op (.stack (.dup 7)), + .op (.stack .lt), + .op (.stack (.dup 10)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.dup 3)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 10, + .op (.stack .pop), + .jumpi 11, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .jump 8], + -- bb32 + [.op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 3], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000030000001d)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 7)), + .jump 5], + -- bb24 + [.op (.stack (.push 0x20200000000000000030000001c)), + .op (.stack (.push 0)), + .jump 5], + -- bb25 + [.op (.stack (.dup 7)), + .op .load, + .op (.stack (.dup 6)), + .op .load, + .op (.stack (.dup 11)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 12, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 13, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.swap 5)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .jump 8], + -- bb29 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000023)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 9)), + .jump 5], + -- bb30 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000024)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 5], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x20200000000000000040000001c)), + .op (.stack (.push 0)), + .jump 5], + -- bb34 + [.op (.stack (.push 0x102000000000000000500000028)), + .op (.stack (.push 0)), + .jump 5], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x202000000000000000a00000001)), + .op (.stack (.push 0)), + .jump 5], + -- bb36 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000015)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 5], + -- bb37 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000031)), + .op (.stack (.dup 1)), + .jump 5], + -- bb38 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x112000000000000000a00000043)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 5], + -- bb40 + [.op (.stack (.push 0x102000000000000000700000006)), + .op (.stack (.push 0)), + .jump 5], + -- bb39 + [.op (.stack (.push 65)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Manifest.lean b/Certified/arraymax/gen/ArrayMaxEntry/Manifest.lean new file mode 100644 index 00000000..288f5c19 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Manifest.lean @@ -0,0 +1,55 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.ArrayMaxEntry.Manifest + +def sources : List (String × String) := + [("Certified/arraymax/arraymax.sol", "904535ac694498a9823f530ca158ee0c762fd1adcc56f3e7b73ca0e457e61f4a")] + +def compiler : String := "0.8.38+commit.6c3ba965.solar.0.3.0-dev" + +def arguments : List String := + ["Certified/arraymax/arraymax.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/arraymax/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "2ab103c66098e0cbff43e9d16f844b9fc8f2178914b597de6fa486e8f338e04c"), + ("Mir1", "mir1", "spell-width-tests", "f14623bbb30c8a5e512477e2a06889160586717851645b4e4781261147f7b5ce"), + ("Mir2", "mir2", "lower-assumes", "b55fbef1d487415cd25806ffb905d134474a6e7344a9adc7b0381d87ba5f1606"), + ("Mir3", "mir3", "evm-inst-schedule", "f581ebc8a44a5751048aa9d5e3579be194f28a7ae43b324c05ba4174f05bbf70"), + ("Sched", "sched", "stack-schedule", "8faa6cf13e13f298634ce462803284a497f59d430e3e70ad5ebc1bf5f4e73a9b"), + ("Evm1", "evm1", "peephole-early", "d95c9c8f0d475b1f35ee80699231413b1310781faaba552a14cfbc03a0a7e53b"), + ("Evm2", "evm2", "cfg-simplify-early", "ed72735eb66fbc15a592a9955f4c255b968d1370f089658e1e908f6fe779663a"), + ("Evm3", "evm3", "compact-pushes", "494c9e25b5e6c67aec0914bea37cf7485a6d970cdf91174459ce815de6986224"), + ("Evm4", "evm4", "block-layout", "c7558e4e7760306023d76956fcb6f3cf0d7f92359feb2cfcf2d9638e26675ee4"), + ("Evm5", "evm5", "terminal-dedup", "4afdad9262ef7af05ec2b06e8aa697bf65ca0a7eb56c74705f02c275ad97d606"), + ("Evm6", "evm6", "cfg-simplify-early", "da150428e0c6d3f9109dc3bb4e912f6d315e61c369c7e6df4bfab1f3160d1107"), + ("Evm7", "evm7", "reorder-pushes", "64b694dd38e060ad399efef56b4a31a076f9765307c5ae52e67363cee1304485"), + ("Evm8", "evm8", "block-cse", "ef86fb9e88ff3e15275cf0b5288bb254053d11c0186e84eba05cfb3d07b97446"), + ("Evm9", "evm9", "stack-normalize", "1116b6d7d727966921e1e2710770c4f88b968b700f6ff83f019e83fc40930212"), + ("Evm10", "evm10", "cfg-simplify-early", "6ca82ae248233de9a028fc16e6b0da94d6042e9e761fb7720605b3caf8b3e3cd"), + ("Evm11", "evm11", "stack-reschedule", "1402c1eee6398954770f2fad457499ac4ea22372cacaded73c998fb04250cafe"), + ("Evm12", "evm12", "copy-loop-blocks", "e05ca1ab37fef8cb2650f2c4e210e91767b5d9c7908c5c55bbc3e455dc32fba7"), + ("Evm13", "evm13", "cfg-simplify", "38c56172c0491a9a3c30e457c47944d8fcdf0a3ab629fd979e482478d077f20a"), + ("Evm14", "evm14", "loop-layout", "bf5bc78e7083cea04133c049d5a141d683d7ba02c07854748c3b61ce83ff9369"), + ("Evm15", "evm15", "reorder-expressions", "1251a3ee3b2814803caea0da5de814008093817ef21fac4a96930718ca0fc832"), + ("Bytecode", "bytecode", "assemble", "dd9122080d9e308dfd9936f661b54b24678f7ade95bc4a106c43f313a342483e")] + +def bytecodeHex : String := + "346013575f3560e01c80633bf6de9614602c575b5f5ffd5b6d01020000000000000005000000285f610124565b6080604052600435602436106004820191602436031017813591602001803603918260051c841117601357825f1080156013578360051b8460fb1c5f109381138480610253575060135760208101602081106102685760800160405260808086815260a0928584378051925160c0888003610236578885036102195785156101ff576001935093509350935060ed565b855184518087108a83036101515783801561016c575061018157505050506001810191602001905f19148060175750905b835186821087820361010e578060bc57505050505f52508061013c5760205ff35b5090506d010300000000000000020000001b9091955b906020529060405260605263ed572b275f526064601cfd5b6d01020000000000000001000000065f610124565b505090506d010300000000000000030000001d909197610124565b6d020200000000000000030000001c5f610124565b875186518b82036101b6578281036101d057505082156101e85795505050506001810191602001905f191480601757509060ed565b5090506d0103000000000000000400000023909199610124565b90506d01030000000000000004000000249091610124565b50506d020200000000000000040000001c5f610124565b50505050506d0202000000000000000a000000015f610124565b5050505090506d0103000000000000000a00000015909193610124565b50505050505050506d0103000000000000000a0000003181610124565b6d01020000000000000007000000065f610124565b6041602052634e487b715f526024601cfd" + +def bytecodeSha256 : String := "83ee403925f2dbc4df58c6c27466204e0a28e1ecaadb0dd8760a3eba3f1a2e2d" + +end SolarTV.Export.ArrayMaxEntry.Manifest diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Mir1.lean b/Certified/arraymax/gen/ArrayMaxEntry/Mir1.lean new file mode 100644 index 00000000..d9e9e974 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Mir1.lean @@ -0,0 +1,131 @@ +-- solar-lean-stage: kind=mir index=1 pass=spell-width-tests +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The lowered MIR module after `spell-width-tests`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @max.0 + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 79) .calldatasize [], + .pure 81 .lt [.value 79, .const 36], + .effect (some 84) .calldataload [.const 4], + .pure 85 .add [.value 84, .const 4], + .pure 88 .sub [.value 79, .const 36], + .pure 89 .lt [.value 88, .value 84], + .pure 131 .or [.value 81, .value 89], + .effect (some 91) .calldataload [.value 85], + .pure 93 .add [.value 85, .const 32], + .pure 94 .sub [.value 79, .value 93], + .pure 96 .shr [.const 5, .value 94], + .pure 97 .lt [.value 96, .value 91], + .pure 132 .or [.value 131, .value 97]], + .branch (.value 132) 6 11⟩, + -- bb1 + ⟨[], + [.assume false .eq [.value 12, .const 0], + .effect none .mstore [.const 0, .value 38]], + .ret (.const 0) (.const 32)⟩, + -- bb2 + ⟨[(38, [(10, .value 37), (5, .value 50)]), (39, [(10, .const 1), (5, .value 51)]), (127, [(10, .value 126), (5, .value 129)])], + [.effect (some 40) .mload [.value 119], + .pure 41 .lt [.value 39, .value 91], + .assume false .eq [.value 40, .value 91]], + .branch (.value 41) 3 1⟩, + -- bb3 + ⟨[], + [.effect (some 42) .mload [.value 119], + .effect (some 46) .mload [.value 127], + .pure 47 .lt [.value 38, .value 46], + .assume false .eq [.value 42, .value 91], + .assume true .eq [.value 41, .const 0]], + .branch (.value 47) 4 5⟩, + -- bb4 + ⟨[], + [.effect (some 48) .mload [.value 119], + .effect (some 49) .mload [.value 127], + .assume false .eq [.value 48, .value 91], + .assume false .eq [.value 49, .value 46], + .assume true .eq [.value 41, .const 0]], + .jump 5⟩, + -- bb5 + ⟨[(50, [(4, .value 46), (3, .value 38)])], + [.pure 51 .add [.value 39, .const 1], + .pure 53 .eq [.value 39, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 53, .const 0], + .pure 129 .add [.value 127, .const 32]], + .jump 2⟩, + -- bb6 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb7 + ⟨[], + [.pure 10 .shl [.const 5, .value 91], + .pure 134 .shr [.const 251, .value 91], + .ne 12 (.value 134) (.const 0), + .assume false .eq [.value 12, .const 0], + .pure 16 .slt [.value 94, .value 10]], + .branch (.value 16) 6 9⟩, + -- bb8 + ⟨[], + [.effect none .mstore [.const 32, .const 65], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb9 + ⟨[], + [.pure 21 .add [.value 10, .const 32], + .pure 22 .lt [.value 21, .const 32]], + .branch (.value 22) 8 10⟩, + -- bb10 + ⟨[], + [.heapFloor 119 128, + .effect (some 121) .mload [.const 64], + .assume false .eq [.value 119, .value 121], + .pure 122 .add [.value 119, .value 21], + .effect none .mstore [.const 64, .value 122], + .effect none .mstore [.value 119, .value 91], + .pure 112 .add [.value 119, .const 32], + .effect none .calldatacopy [.value 112, .value 93, .value 10], + .effect (some 34) .mload [.value 119], + .assume false .eq [.value 91, .value 91], + .assume false .eq [.value 34, .value 91], + .assume true .eq [.value 3, .const 0], + .effect (some 37) .mload [.value 112], + .pure 126 .add [.value 119, .const 64]], + .jump 2⟩, + -- bb11 + ⟨[], + [.ne 3 (.value 91) (.const 0)], + .branch (.value 3) 7 6⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x3bf6de96, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Mir2.lean b/Certified/arraymax/gen/ArrayMaxEntry/Mir2.lean new file mode 100644 index 00000000..b1100b69 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Mir2.lean @@ -0,0 +1,242 @@ +-- solar-lean-stage: kind=mir index=2 pass=lower-assumes +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The lowered MIR module after `lower-assumes`. -/ +def mir2 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @max.0 + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 79) .calldatasize [], + .pure 81 .lt [.value 79, .const 36], + .effect (some 84) .calldataload [.const 4], + .pure 85 .add [.value 84, .const 4], + .pure 88 .sub [.value 79, .const 36], + .pure 89 .lt [.value 88, .value 84], + .pure 131 .or [.value 81, .value 89], + .effect (some 91) .calldataload [.value 85], + .pure 93 .add [.value 85, .const 32], + .pure 94 .sub [.value 79, .value 93], + .pure 96 .shr [.const 5, .value 94], + .pure 97 .lt [.value 96, .value 91], + .pure 132 .or [.value 131, .value 97]], + .branch (.value 132) 6 11⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 0, .value 38], + .word 137 (.value 12), + .ne 139 (.value 137) (.const 0)], + .branch (.value 139) 13 14⟩, + -- bb2 + ⟨[(38, [(38, .value 37), (28, .value 50)]), (39, [(38, .const 1), (28, .value 51)]), (127, [(38, .value 126), (28, .value 129)])], + [.effect (some 40) .mload [.value 119], + .pure 41 .lt [.value 39, .value 91], + .ne 141 (.value 40) (.value 91)], + .branch (.value 141) 15 16⟩, + -- bb3 + ⟨[], + [.effect (some 42) .mload [.value 119], + .effect (some 46) .mload [.value 127], + .pure 47 .lt [.value 38, .value 46], + .ne 143 (.value 42) (.value 91)], + .branch (.value 143) 17 18⟩, + -- bb4 + ⟨[], + [.effect (some 48) .mload [.value 119], + .effect (some 49) .mload [.value 127], + .ne 149 (.value 48) (.value 91)], + .branch (.value 149) 21 22⟩, + -- bb5 + ⟨[(50, [(26, .value 46), (20, .value 38)])], + [.pure 51 .add [.value 39, .const 1], + .pure 53 .eq [.value 39, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff], + .pure 129 .add [.value 127, .const 32], + .word 157 (.value 53), + .ne 159 (.value 157) (.const 0)], + .branch (.value 159) 27 28⟩, + -- bb6 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb7 + ⟨[], + [.pure 10 .shl [.const 5, .value 91], + .pure 134 .shr [.const 251, .value 91], + .ne 12 (.value 134) (.const 0), + .pure 16 .slt [.value 94, .value 10], + .word 161 (.value 12), + .ne 163 (.value 161) (.const 0)], + .branch (.value 163) 29 30⟩, + -- bb8 + ⟨[], + [.effect none .mstore [.const 32, .const 65], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb9 + ⟨[], + [.pure 21 .add [.value 10, .const 32], + .pure 22 .lt [.value 21, .const 32]], + .branch (.value 22) 8 10⟩, + -- bb10 + ⟨[], + [.heapFloor 119 128, + .effect (some 121) .mload [.const 64], + .pure 122 .add [.value 119, .value 21], + .effect none .mstore [.const 64, .value 122], + .effect none .mstore [.value 119, .value 91], + .pure 112 .add [.value 119, .const 32], + .effect none .calldatacopy [.value 112, .value 93, .value 10], + .effect (some 34) .mload [.value 119], + .effect (some 37) .mload [.value 112], + .pure 126 .add [.value 119, .const 64], + .ne 165 (.value 119) (.value 121)], + .branch (.value 165) 31 32⟩, + -- bb11 + ⟨[], + [.ne 3 (.value 91) (.const 0)], + .branch (.value 3) 7 6⟩, + -- bb12 + ⟨[(175, [(13, .const 0x102000000000000000100000006), (15, .const 0x10300000000000000020000001b), (17, .const 0x10300000000000000030000001d), (19, .const 0x20200000000000000030000001c), (21, .const 0x103000000000000000400000023), (23, .const 0x103000000000000000400000024), (25, .const 0x20200000000000000040000001c), (27, .const 0x102000000000000000500000028), (29, .const 0x102000000000000000700000006), (31, .const 0x112000000000000000a00000043), (33, .const 0x103000000000000000a00000031), (35, .const 0x103000000000000000a00000015), (37, .const 0x202000000000000000a00000001)]), (176, [(13, .value 137), (15, .value 40), (17, .value 42), (19, .value 145), (21, .value 48), (23, .value 49), (25, .value 153), (27, .value 157), (29, .value 161), (31, .value 119), (33, .value 91), (35, .value 34), (37, .value 171)]), (177, [(13, .const 0), (15, .value 91), (17, .value 91), (19, .const 0), (21, .value 91), (23, .value 46), (25, .const 0), (27, .const 0), (29, .const 0), (31, .value 121), (33, .value 91), (35, .value 91), (37, .const 0)])], + [.effect none .mstore [.const 32, .value 175], + .effect none .mstore [.const 64, .value 176], + .effect none .mstore [.const 96, .value 177], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb13 + ⟨[], + [], + .jump 12⟩, + -- bb14 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩, + -- bb15 + ⟨[], + [], + .jump 12⟩, + -- bb16 + ⟨[], + [], + .branch (.value 41) 3 1⟩, + -- bb17 + ⟨[], + [], + .jump 12⟩, + -- bb18 + ⟨[], + [.word 145 (.value 41), + .pure 147 .eq [.value 145, .const 0]], + .branch (.value 147) 19 20⟩, + -- bb19 + ⟨[], + [], + .jump 12⟩, + -- bb20 + ⟨[], + [], + .branch (.value 47) 4 5⟩, + -- bb21 + ⟨[], + [], + .jump 12⟩, + -- bb22 + ⟨[], + [.ne 151 (.value 49) (.value 46)], + .branch (.value 151) 23 24⟩, + -- bb23 + ⟨[], + [], + .jump 12⟩, + -- bb24 + ⟨[], + [.word 153 (.value 41), + .pure 155 .eq [.value 153, .const 0]], + .branch (.value 155) 25 26⟩, + -- bb25 + ⟨[], + [], + .jump 12⟩, + -- bb26 + ⟨[], + [], + .jump 5⟩, + -- bb27 + ⟨[], + [], + .jump 12⟩, + -- bb28 + ⟨[], + [], + .jump 2⟩, + -- bb29 + ⟨[], + [], + .jump 12⟩, + -- bb30 + ⟨[], + [], + .branch (.value 16) 6 9⟩, + -- bb31 + ⟨[], + [], + .jump 12⟩, + -- bb32 + ⟨[], + [.ne 167 (.value 91) (.value 91)], + .branch (.value 167) 33 34⟩, + -- bb33 + ⟨[], + [], + .jump 12⟩, + -- bb34 + ⟨[], + [.ne 169 (.value 34) (.value 91)], + .branch (.value 169) 35 36⟩, + -- bb35 + ⟨[], + [], + .jump 12⟩, + -- bb36 + ⟨[], + [.word 171 (.value 3), + .pure 173 .eq [.value 171, .const 0]], + .branch (.value 173) 37 38⟩, + -- bb37 + ⟨[], + [], + .jump 12⟩, + -- bb38 + ⟨[], + [], + .jump 2⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x3bf6de96, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Mir3.lean b/Certified/arraymax/gen/ArrayMaxEntry/Mir3.lean new file mode 100644 index 00000000..f42c4587 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Mir3.lean @@ -0,0 +1,242 @@ +-- solar-lean-stage: kind=mir index=3 pass=evm-inst-schedule +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The lowered MIR module after `evm-inst-schedule`. -/ +def mir3 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @max.0 + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 79) .calldatasize [], + .pure 81 .lt [.value 79, .const 36], + .effect (some 84) .calldataload [.const 4], + .pure 85 .add [.value 84, .const 4], + .pure 88 .sub [.value 79, .const 36], + .pure 89 .lt [.value 88, .value 84], + .pure 131 .or [.value 81, .value 89], + .effect (some 91) .calldataload [.value 85], + .pure 93 .add [.value 85, .const 32], + .pure 94 .sub [.value 79, .value 93], + .pure 96 .shr [.const 5, .value 94], + .pure 97 .lt [.value 96, .value 91], + .pure 132 .or [.value 131, .value 97]], + .branch (.value 132) 6 11⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 0, .value 38], + .word 137 (.value 12), + .ne 139 (.value 137) (.const 0)], + .branch (.value 139) 13 14⟩, + -- bb2 + ⟨[(38, [(38, .value 37), (28, .value 50)]), (39, [(38, .const 1), (28, .value 51)]), (127, [(38, .value 126), (28, .value 129)])], + [.effect (some 40) .mload [.value 119], + .pure 41 .lt [.value 39, .value 91], + .ne 141 (.value 40) (.value 91)], + .branch (.value 141) 15 16⟩, + -- bb3 + ⟨[], + [.effect (some 42) .mload [.value 119], + .effect (some 46) .mload [.value 127], + .pure 47 .lt [.value 38, .value 46], + .ne 143 (.value 42) (.value 91)], + .branch (.value 143) 17 18⟩, + -- bb4 + ⟨[], + [.effect (some 48) .mload [.value 119], + .effect (some 49) .mload [.value 127], + .ne 149 (.value 48) (.value 91)], + .branch (.value 149) 21 22⟩, + -- bb5 + ⟨[(50, [(26, .value 46), (20, .value 38)])], + [.pure 51 .add [.value 39, .const 1], + .pure 129 .add [.value 127, .const 32], + .pure 53 .eq [.value 39, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff], + .word 157 (.value 53), + .ne 159 (.value 157) (.const 0)], + .branch (.value 159) 27 28⟩, + -- bb6 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb7 + ⟨[], + [.pure 10 .shl [.const 5, .value 91], + .pure 134 .shr [.const 251, .value 91], + .ne 12 (.value 134) (.const 0), + .pure 16 .slt [.value 94, .value 10], + .word 161 (.value 12), + .ne 163 (.value 161) (.const 0)], + .branch (.value 163) 29 30⟩, + -- bb8 + ⟨[], + [.effect none .mstore [.const 32, .const 65], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb9 + ⟨[], + [.pure 21 .add [.value 10, .const 32], + .pure 22 .lt [.value 21, .const 32]], + .branch (.value 22) 8 10⟩, + -- bb10 + ⟨[], + [.heapFloor 119 128, + .effect (some 121) .mload [.const 64], + .pure 122 .add [.value 119, .value 21], + .effect none .mstore [.const 64, .value 122], + .effect none .mstore [.value 119, .value 91], + .pure 112 .add [.value 119, .const 32], + .effect none .calldatacopy [.value 112, .value 93, .value 10], + .effect (some 34) .mload [.value 119], + .effect (some 37) .mload [.value 112], + .pure 126 .add [.value 119, .const 64], + .ne 165 (.value 119) (.value 121)], + .branch (.value 165) 31 32⟩, + -- bb11 + ⟨[], + [.ne 3 (.value 91) (.const 0)], + .branch (.value 3) 7 6⟩, + -- bb12 + ⟨[(175, [(13, .const 0x102000000000000000100000006), (15, .const 0x10300000000000000020000001b), (17, .const 0x10300000000000000030000001d), (19, .const 0x20200000000000000030000001c), (21, .const 0x103000000000000000400000023), (23, .const 0x103000000000000000400000024), (25, .const 0x20200000000000000040000001c), (27, .const 0x102000000000000000500000028), (29, .const 0x102000000000000000700000006), (31, .const 0x112000000000000000a00000043), (33, .const 0x103000000000000000a00000031), (35, .const 0x103000000000000000a00000015), (37, .const 0x202000000000000000a00000001)]), (176, [(13, .value 137), (15, .value 40), (17, .value 42), (19, .value 145), (21, .value 48), (23, .value 49), (25, .value 153), (27, .value 157), (29, .value 161), (31, .value 119), (33, .value 91), (35, .value 34), (37, .value 171)]), (177, [(13, .const 0), (15, .value 91), (17, .value 91), (19, .const 0), (21, .value 91), (23, .value 46), (25, .const 0), (27, .const 0), (29, .const 0), (31, .value 121), (33, .value 91), (35, .value 91), (37, .const 0)])], + [.effect none .mstore [.const 32, .value 175], + .effect none .mstore [.const 64, .value 176], + .effect none .mstore [.const 96, .value 177], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb13 + ⟨[], + [], + .jump 12⟩, + -- bb14 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩, + -- bb15 + ⟨[], + [], + .jump 12⟩, + -- bb16 + ⟨[], + [], + .branch (.value 41) 3 1⟩, + -- bb17 + ⟨[], + [], + .jump 12⟩, + -- bb18 + ⟨[], + [.word 145 (.value 41), + .pure 147 .eq [.value 145, .const 0]], + .branch (.value 147) 19 20⟩, + -- bb19 + ⟨[], + [], + .jump 12⟩, + -- bb20 + ⟨[], + [], + .branch (.value 47) 4 5⟩, + -- bb21 + ⟨[], + [], + .jump 12⟩, + -- bb22 + ⟨[], + [.ne 151 (.value 49) (.value 46)], + .branch (.value 151) 23 24⟩, + -- bb23 + ⟨[], + [], + .jump 12⟩, + -- bb24 + ⟨[], + [.word 153 (.value 41), + .pure 155 .eq [.value 153, .const 0]], + .branch (.value 155) 25 26⟩, + -- bb25 + ⟨[], + [], + .jump 12⟩, + -- bb26 + ⟨[], + [], + .jump 5⟩, + -- bb27 + ⟨[], + [], + .jump 12⟩, + -- bb28 + ⟨[], + [], + .jump 2⟩, + -- bb29 + ⟨[], + [], + .jump 12⟩, + -- bb30 + ⟨[], + [], + .branch (.value 16) 6 9⟩, + -- bb31 + ⟨[], + [], + .jump 12⟩, + -- bb32 + ⟨[], + [.ne 167 (.value 91) (.value 91)], + .branch (.value 167) 33 34⟩, + -- bb33 + ⟨[], + [], + .jump 12⟩, + -- bb34 + ⟨[], + [.ne 169 (.value 34) (.value 91)], + .branch (.value 169) 35 36⟩, + -- bb35 + ⟨[], + [], + .jump 12⟩, + -- bb36 + ⟨[], + [.word 171 (.value 3), + .pure 173 .eq [.value 171, .const 0]], + .branch (.value 173) 37 38⟩, + -- bb37 + ⟨[], + [], + .jump 12⟩, + -- bb38 + ⟨[], + [], + .jump 2⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x3bf6de96, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Sched.lean b/Certified/arraymax/gen/ArrayMaxEntry/Sched.lean new file mode 100644 index 00000000..714358fe --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Sched.lean @@ -0,0 +1,405 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 3, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x3bf6de96)), + .op (.stack .eq), + .jumpi 2, + .jump 3], + -- bb2 + [.jump 4], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.swap 0)), + .op (.stack (.push 4)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack .lt), + .op (.stack .or), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .calldatasize), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack (.push 5)), + .op (.stack .shr), + .op (.stack (.dup 4)), + .op (.stack .gt), + .op (.stack .or), + .jumpi 42, + .jump 5], + -- bb5 + [.op (.stack (.dup 2)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 42, + .jump 6], + -- bb6 + [.op (.stack (.dup 3)), + .op (.stack (.push 5)), + .op (.stack .shl), + .op (.stack (.dup 4)), + .op (.stack (.push 251)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 3)), + .op (.stack (.dup 1)), + .op (.stack .sgt), + .op (.stack (.dup 4)), + .op (.stack (.dup 0)), + .jumpi 40, + .jump 7], + -- bb7 + [.op (.stack .pop), + .jumpi 42, + .jump 8], + -- bb8 + [.op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 39, + .jump 9], + -- bb9 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .load, + .op (.stack (.swap 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.dup 6)), + .op (.stack (.dup 1)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 2)), + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .effect .calldatacopy 3, + .op (.stack (.dup 0)), + .op .load, + .op (.stack (.swap 2)), + .op .load, + .op (.stack (.push 64)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.dup 3)), + .op (.stack (.dup 3)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 38, + .jump 10], + -- bb10 + [.op (.stack (.dup 8)), + .op (.stack (.dup 0)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 37, + .jump 11], + -- bb11 + [.op (.stack (.dup 8)), + .op (.stack (.dup 5)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 36, + .jump 12], + -- bb12 + [.op (.stack (.dup 5)), + .op (.stack .iszero), + .jumpi 35, + .jump 13], + -- bb13 + [.op (.stack (.push 1)), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .jump 14], + -- bb14 + [.op (.stack (.dup 3)), + .op .load, + .op (.stack (.dup 6)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.dup 7)), + .op (.stack (.dup 2)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 16, + .jump 15], + -- bb15 + [.op (.stack (.dup 0)), + .jumpi 20, + .jump 17], + -- bb16 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000020000001b)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 5)), + .jump 41], + -- bb17 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.dup 0)), + .jumpi 19, + .jump 18], + -- bb18 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb19 + [.op (.stack (.push 0x102000000000000000100000006)), + .op (.stack (.push 0)), + .jump 41], + -- bb20 + [.op (.stack (.dup 5)), + .op .load, + .op (.stack (.dup 4)), + .op .load, + .op (.stack (.dup 0)), + .op (.stack (.dup 7)), + .op (.stack .lt), + .op (.stack (.dup 10)), + .op (.stack (.dup 3)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 23, + .jump 21], + -- bb21 + [.op (.stack (.dup 3)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 24, + .jump 22], + -- bb22 + [.op (.stack .pop), + .jumpi 25, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .jump 32], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10300000000000000030000001d)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 7)), + .jump 41], + -- bb24 + [.op (.stack (.push 0x20200000000000000030000001c)), + .op (.stack (.push 0)), + .jump 41], + -- bb25 + [.op (.stack (.dup 7)), + .op .load, + .op (.stack (.dup 6)), + .op .load, + .op (.stack (.dup 11)), + .op (.stack (.dup 2)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 29, + .jump 26], + -- bb26 + [.op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 30, + .jump 27], + -- bb27 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .jumpi 31, + .jump 28], + -- bb28 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .jump 32], + -- bb29 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000023)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 9)), + .jump 41], + -- bb30 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000400000024)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 41], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x20200000000000000040000001c)), + .op (.stack (.push 0)), + .jump 41], + -- bb32 + [.op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 34, + .jump 33], + -- bb33 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .jump 14], + -- bb34 + [.op (.stack (.push 0x102000000000000000500000028)), + .op (.stack (.push 0)), + .jump 41], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x202000000000000000a00000001)), + .op (.stack (.push 0)), + .jump 41], + -- bb36 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x103000000000000000a00000015)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 41], + -- bb37 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack (.push 0x103000000000000000a00000031)), + .op (.stack (.swap 0)), + .jump 41], + -- bb38 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x112000000000000000a00000043)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 41], + -- bb39 + [.op (.stack (.push 65)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb40 + [.op (.stack (.push 0x102000000000000000700000006)), + .op (.stack (.push 0)), + .jump 41], + -- bb41 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb42 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Schedule.json b/Certified/arraymax/gen/ArrayMaxEntry/Schedule.json new file mode 100644 index 00000000..3a8cac8d --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Schedule.json @@ -0,0 +1,51 @@ +{ + "functions": [ + {"function": 1, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [3, 0], "layout": [], "floating": true, "continues": null} + ]}, + {"function": 0, "entry": 4, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [4, 3], "layout": [], "floating": false, "continues": null}, + {"block": 1, "start": [17, 0], "layout": ["v12", "junk", "v38", "junk", "junk", "junk", "junk"], "floating": true, "continues": null}, + {"block": 2, "start": [14, 0], "layout": ["v91", "v12", "v119", "v38", "v127", "v39"], "floating": false, "continues": null}, + {"block": 3, "start": [20, 0], "layout": ["v91", "v12", "v119", "v38", "v127", "v39", "junk", "v41"], "floating": false, "continues": null}, + {"block": 4, "start": [25, 0], "layout": ["v91", "v12", "v119", "junk", "v127", "v39", "junk", "v41", "junk", "v46"], "floating": false, "continues": null}, + {"block": 5, "start": [32, 0], "layout": ["v91", "v12", "v119", "v50", "v127", "v39"], "floating": false, "continues": null}, + {"block": 6, "start": [42, 0], "layout": [], "floating": true, "continues": null}, + {"block": 7, "start": [6, 0], "layout": ["v91", "v94", "v93", "v3"], "floating": false, "continues": null}, + {"block": 8, "start": [39, 0], "layout": [], "floating": true, "continues": null}, + {"block": 9, "start": [8, 0], "layout": ["v91", "v12", "v93", "v3", "v10"], "floating": false, "continues": null}, + {"block": 10, "start": [9, 0], "layout": ["v91", "v12", "v93", "v3", "v10", "v21"], "floating": false, "continues": null}, + {"block": 11, "start": [5, 0], "layout": ["v91", "v94", "v93"], "floating": false, "continues": null}, + {"block": 12, "start": [41, 0], "layout": ["v176", "v175", "v177"], "floating": true, "continues": null}, + {"block": 13, "start": [19, 0], "layout": ["v137"], "floating": true, "continues": null}, + {"block": 14, "start": [18, 0], "layout": [], "floating": true, "continues": null}, + {"block": 15, "start": [16, 0], "layout": ["v91", "junk", "junk", "junk", "junk", "junk", "v40", "junk"], "floating": true, "continues": null}, + {"block": 16, "start": [15, 0], "layout": ["v91", "v12", "v119", "v38", "v127", "v39", "junk", "v41"], "floating": false, "continues": null}, + {"block": 17, "start": [23, 0], "layout": ["v91", "junk", "junk", "junk", "junk", "junk", "junk", "junk", "v42", "junk", "junk"], "floating": true, "continues": null}, + {"block": 18, "start": [21, 0], "layout": ["v91", "v12", "v119", "v38", "v127", "v39", "junk", "v41", "junk", "v46", "v47"], "floating": false, "continues": null}, + {"block": 19, "start": [24, 0], "layout": ["v145"], "floating": true, "continues": null}, + {"block": 20, "start": [22, 0], "layout": ["v91", "v12", "v119", "v38", "v127", "v39", "junk", "v41", "junk", "v46", "v47", "junk"], "floating": false, "continues": null}, + {"block": 21, "start": [29, 0], "layout": ["v91", "junk", "junk", "junk", "junk", "junk", "junk", "junk", "junk", "junk", "v48", "junk"], "floating": true, "continues": null}, + {"block": 22, "start": [26, 0], "layout": ["v91", "v12", "v119", "junk", "v127", "v39", "junk", "v41", "junk", "v46", "junk", "v49"], "floating": false, "continues": null}, + {"block": 23, "start": [30, 0], "layout": ["v46", "junk", "v49"], "floating": true, "continues": null}, + {"block": 24, "start": [27, 0], "layout": ["v91", "v12", "v119", "junk", "v127", "v39", "junk", "v41", "junk", "v46", "junk", "junk"], "floating": false, "continues": null}, + {"block": 25, "start": [31, 0], "layout": ["v153", "junk", "junk"], "floating": true, "continues": null}, + {"block": 26, "start": [28, 0], "layout": ["v91", "v12", "v119", "junk", "v127", "v39", "junk", "junk", "junk", "v46"], "floating": false, "continues": null}, + {"block": 27, "start": [34, 0], "layout": ["v157"], "floating": true, "continues": null}, + {"block": 28, "start": [33, 0], "layout": ["v91", "v12", "v119", "v50", "v51", "v129", "junk"], "floating": false, "continues": null}, + {"block": 29, "start": [40, 0], "layout": ["v161"], "floating": true, "continues": null}, + {"block": 30, "start": [7, 0], "layout": ["v91", "v12", "v93", "v3", "v10", "v16", "junk"], "floating": false, "continues": null}, + {"block": 31, "start": [38, 0], "layout": ["v121", "v119", "junk", "junk"], "floating": true, "continues": null}, + {"block": 32, "start": [10, 0], "layout": ["v91", "v12", "junk", "v3", "v34", "junk", "v119", "v37", "v126"], "floating": false, "continues": null}, + {"block": 33, "start": [37, 0], "layout": ["v91", "junk", "junk", "junk", "junk", "junk", "junk", "junk", "junk"], "floating": true, "continues": null}, + {"block": 34, "start": [11, 0], "layout": ["v91", "v12", "junk", "v3", "v34", "junk", "v119", "v37", "v126"], "floating": false, "continues": null}, + {"block": 35, "start": [36, 0], "layout": ["v91", "junk", "junk", "junk", "v34", "junk", "junk", "junk", "junk"], "floating": true, "continues": null}, + {"block": 36, "start": [12, 0], "layout": ["v91", "v12", "junk", "v3", "junk", "junk", "v119", "v37", "v126"], "floating": false, "continues": null}, + {"block": 37, "start": [35, 0], "layout": ["v171", "junk", "junk", "junk", "junk", "junk"], "floating": true, "continues": null}, + {"block": 38, "start": [13, 0], "layout": ["v91", "v12", "junk", "junk", "junk", "junk", "v119", "v37", "v126"], "floating": false, "continues": null} + ]} + ] +} diff --git a/Certified/arraymax/gen/ArrayMaxEntry/Stage0.lean b/Certified/arraymax/gen/ArrayMaxEntry/Stage0.lean new file mode 100644 index 00000000..3e95d037 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/Stage0.lean @@ -0,0 +1,130 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `ArrayMaxEntry`; do not edit. -/ + +namespace SolarTV.Export.ArrayMaxEntry + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @max.0 + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 79) .calldatasize [], + .pure 81 .lt [.value 79, .const 36], + .effect (some 84) .calldataload [.const 4], + .pure 85 .add [.value 84, .const 4], + .pure 88 .sub [.value 79, .const 36], + .pure 89 .lt [.value 88, .value 84], + .pure 131 .or [.value 81, .value 89], + .effect (some 91) .calldataload [.value 85], + .pure 93 .add [.value 85, .const 32], + .pure 94 .sub [.value 79, .value 93], + .pure 96 .shr [.const 5, .value 94], + .pure 97 .lt [.value 96, .value 91], + .pure 132 .or [.value 131, .value 97]], + .branch (.value 132) 6 11⟩, + -- bb1 + ⟨[], + [.assume false .eq [.value 12, .const 0], + .effect none .mstore [.const 0, .value 38]], + .ret (.const 0) (.const 32)⟩, + -- bb2 + ⟨[(38, [(10, .value 37), (5, .value 50)]), (39, [(10, .const 1), (5, .value 51)]), (127, [(10, .value 126), (5, .value 129)])], + [.effect (some 40) .mload [.value 119], + .pure 41 .lt [.value 39, .value 91], + .assume false .eq [.value 40, .value 91]], + .branch (.value 41) 3 1⟩, + -- bb3 + ⟨[], + [.effect (some 42) .mload [.value 119], + .effect (some 46) .mload [.value 127], + .pure 47 .lt [.value 38, .value 46], + .assume false .eq [.value 42, .value 91], + .assume true .eq [.value 41, .const 0]], + .branch (.value 47) 4 5⟩, + -- bb4 + ⟨[], + [.effect (some 48) .mload [.value 119], + .effect (some 49) .mload [.value 127], + .assume false .eq [.value 48, .value 91], + .assume false .eq [.value 49, .value 46], + .assume true .eq [.value 41, .const 0]], + .jump 5⟩, + -- bb5 + ⟨[(50, [(4, .value 46), (3, .value 38)])], + [.pure 51 .add [.value 39, .const 1], + .pure 53 .eq [.value 39, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 53, .const 0], + .pure 129 .add [.value 127, .const 32]], + .jump 2⟩, + -- bb6 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb7 + ⟨[], + [.pure 10 .shl [.const 5, .value 91], + .pure 12 .gt [.value 91, .const 0x7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 12, .const 0], + .pure 16 .slt [.value 94, .value 10]], + .branch (.value 16) 6 9⟩, + -- bb8 + ⟨[], + [.effect none .mstore [.const 32, .const 65], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb9 + ⟨[], + [.pure 21 .add [.value 10, .const 32], + .pure 22 .lt [.value 21, .const 32]], + .branch (.value 22) 8 10⟩, + -- bb10 + ⟨[], + [.heapFloor 119 128, + .effect (some 121) .mload [.const 64], + .assume false .eq [.value 119, .value 121], + .pure 122 .add [.value 119, .value 21], + .effect none .mstore [.const 64, .value 122], + .effect none .mstore [.value 119, .value 91], + .pure 112 .add [.value 119, .const 32], + .effect none .calldatacopy [.value 112, .value 93, .value 10], + .effect (some 34) .mload [.value 119], + .assume false .eq [.value 91, .value 91], + .assume false .eq [.value 34, .value 91], + .assume true .eq [.value 3, .const 0], + .effect (some 37) .mload [.value 112], + .pure 126 .add [.value 119, .const 64]], + .jump 2⟩, + -- bb11 + ⟨[], + [.ne 3 (.value 91) (.const 0)], + .branch (.value 3) 7 6⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x3bf6de96, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.ArrayMaxEntry diff --git a/Certified/arraymax/gen/ArrayMaxEntry/manifest.json b/Certified/arraymax/gen/ArrayMaxEntry/manifest.json new file mode 100644 index 00000000..e01faa90 --- /dev/null +++ b/Certified/arraymax/gen/ArrayMaxEntry/manifest.json @@ -0,0 +1,193 @@ +{ + "arguments": [ + "Certified/arraymax/arraymax.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/arraymax/gen" + ], + "bytecode": "346013575f3560e01c80633bf6de9614602c575b5f5ffd5b6d01020000000000000005000000285f610124565b6080604052600435602436106004820191602436031017813591602001803603918260051c841117601357825f1080156013578360051b8460fb1c5f109381138480610253575060135760208101602081106102685760800160405260808086815260a0928584378051925160c0888003610236578885036102195785156101ff576001935093509350935060ed565b855184518087108a83036101515783801561016c575061018157505050506001810191602001905f19148060175750905b835186821087820361010e578060bc57505050505f52508061013c5760205ff35b5090506d010300000000000000020000001b9091955b906020529060405260605263ed572b275f526064601cfd5b6d01020000000000000001000000065f610124565b505090506d010300000000000000030000001d909197610124565b6d020200000000000000030000001c5f610124565b875186518b82036101b6578281036101d057505082156101e85795505050506001810191602001905f191480601757509060ed565b5090506d0103000000000000000400000023909199610124565b90506d01030000000000000004000000249091610124565b50506d020200000000000000040000001c5f610124565b50505050506d0202000000000000000a000000015f610124565b5050505090506d0103000000000000000a00000015909193610124565b50505050505050506d0103000000000000000a0000003181610124565b6d01020000000000000007000000065f610124565b6041602052634e487b715f526024601cfd", + "bytecode_sha256": "83ee403925f2dbc4df58c6c27466204e0a28e1ecaadb0dd8760a3eba3f1a2e2d", + "compiler": "0.8.38+commit.6c3ba965.solar.0.3.0-dev", + "contract": "ArrayMaxEntry", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"Certified/arraymax/arraymax.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/arraymax/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/arraymax/gen\"), keep_asts: false, forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "Certified/arraymax/arraymax.sol", + "sha256": "904535ac694498a9823f530ca158ee0c762fd1adcc56f3e7b73ca0e457e61f4a" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "2ab103c66098e0cbff43e9d16f844b9fc8f2178914b597de6fa486e8f338e04c" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "spell-width-tests", + "sha256": "f14623bbb30c8a5e512477e2a06889160586717851645b4e4781261147f7b5ce" + }, + { + "definition": "mir2", + "file": "Mir2.lean", + "index": 2, + "kind": "mir", + "pass": "lower-assumes", + "sha256": "b55fbef1d487415cd25806ffb905d134474a6e7344a9adc7b0381d87ba5f1606" + }, + { + "definition": "mir3", + "file": "Mir3.lean", + "index": 3, + "kind": "mir", + "pass": "evm-inst-schedule", + "sha256": "f581ebc8a44a5751048aa9d5e3579be194f28a7ae43b324c05ba4174f05bbf70" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "8faa6cf13e13f298634ce462803284a497f59d430e3e70ad5ebc1bf5f4e73a9b" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "peephole-early", + "sha256": "d95c9c8f0d475b1f35ee80699231413b1310781faaba552a14cfbc03a0a7e53b" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "ed72735eb66fbc15a592a9955f4c255b968d1370f089658e1e908f6fe779663a" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "compact-pushes", + "sha256": "494c9e25b5e6c67aec0914bea37cf7485a6d970cdf91174459ce815de6986224" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "block-layout", + "sha256": "c7558e4e7760306023d76956fcb6f3cf0d7f92359feb2cfcf2d9638e26675ee4" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "4afdad9262ef7af05ec2b06e8aa697bf65ca0a7eb56c74705f02c275ad97d606" + }, + { + "definition": "evm6", + "file": "Evm6.lean", + "index": 6, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "da150428e0c6d3f9109dc3bb4e912f6d315e61c369c7e6df4bfab1f3160d1107" + }, + { + "definition": "evm7", + "file": "Evm7.lean", + "index": 7, + "kind": "evm", + "pass": "reorder-pushes", + "sha256": "64b694dd38e060ad399efef56b4a31a076f9765307c5ae52e67363cee1304485" + }, + { + "definition": "evm8", + "file": "Evm8.lean", + "index": 8, + "kind": "evm", + "pass": "block-cse", + "sha256": "ef86fb9e88ff3e15275cf0b5288bb254053d11c0186e84eba05cfb3d07b97446" + }, + { + "definition": "evm9", + "file": "Evm9.lean", + "index": 9, + "kind": "evm", + "pass": "stack-normalize", + "sha256": "1116b6d7d727966921e1e2710770c4f88b968b700f6ff83f019e83fc40930212" + }, + { + "definition": "evm10", + "file": "Evm10.lean", + "index": 10, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "6ca82ae248233de9a028fc16e6b0da94d6042e9e761fb7720605b3caf8b3e3cd" + }, + { + "definition": "evm11", + "file": "Evm11.lean", + "index": 11, + "kind": "evm", + "pass": "stack-reschedule", + "sha256": "1402c1eee6398954770f2fad457499ac4ea22372cacaded73c998fb04250cafe" + }, + { + "definition": "evm12", + "file": "Evm12.lean", + "index": 12, + "kind": "evm", + "pass": "copy-loop-blocks", + "sha256": "e05ca1ab37fef8cb2650f2c4e210e91767b5d9c7908c5c55bbc3e455dc32fba7" + }, + { + "definition": "evm13", + "file": "Evm13.lean", + "index": 13, + "kind": "evm", + "pass": "cfg-simplify", + "sha256": "38c56172c0491a9a3c30e457c47944d8fcdf0a3ab629fd979e482478d077f20a" + }, + { + "definition": "evm14", + "file": "Evm14.lean", + "index": 14, + "kind": "evm", + "pass": "loop-layout", + "sha256": "bf5bc78e7083cea04133c049d5a141d683d7ba02c07854748c3b61ce83ff9369" + }, + { + "definition": "evm15", + "file": "Evm15.lean", + "index": 15, + "kind": "evm", + "pass": "reorder-expressions", + "sha256": "1251a3ee3b2814803caea0da5de814008093817ef21fac4a96930718ca0fc832" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "dd9122080d9e308dfd9936f661b54b24678f7ade95bc4a106c43f313a342483e" + } + ] +} diff --git a/Certified/arraymax/options b/Certified/arraymax/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/arraymax/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/arraymax/recdepth b/Certified/arraymax/recdepth new file mode 100644 index 00000000..b92677ed --- /dev/null +++ b/Certified/arraymax/recdepth @@ -0,0 +1 @@ +20000 diff --git a/Certified/bank/Final.lean b/Certified/bank/Final.lean new file mode 100644 index 00000000..268410d9 --- /dev/null +++ b/Certified/bank/Final.lean @@ -0,0 +1,77 @@ +import Verify.Shapes +import Verify.ShapeGeneric +import bank.gen.Bank.Bytecode +import SolidCore.Refinement.Solar.Bank.Lowering +import bank.Shape + +-- Generated by solar's tools/certify/final.py from bank/shape.json and the bytecode the +-- driver compiled in this run; do not edit. The statement is fixed by the driver; the proof +-- module only supplies a term the kernel checks against it. + +/-! +# Bank: the published statement + +`Statement` binds the exact runtime bytecode (`runtimeHex`, from the driver's own compile) and +states Shapes.Compiled of it against the checked source on the declared valid calls. +-/ + +namespace Certified.bank.Final + +open SolidCore.Refinement + +/-- The runtime bytecode the pinned solar emitted in this run, as hex (for the reader). -/ +def runtimeHex : String := + "346028575f3560e01c80632f4f21e21460f857806370a0823114610161578063b6b55f2514603e575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243610602857600435803360875b815f525f60205260405f2080548481019081105f1960601c85116101a657602c578155600154938401938410602c57926001559154905090565b905f52337fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c60205fa25f525f1960601c331160cb575f1960601c331160cb5760205ff35b690417000000010000000260201b335f1960601c915b6020525b60405260605263ed572b275f526064601cfd5b60043560a01c60443610176028576004355f1960601c81166024358261011b604d565b5f525f1960601c8211610147578181036101345760205ff35b6d010200000002000000020000000760e1565b505f1960601c906d041700000002000000020000000960e1565b60043560a01c60243610176028576004355f1960601c8116815f525f60205260405f20545f528181036101935760205ff35b6d010200000003000000020000000960e1565b505050505f1960601c6d04170000000000000000800000006020529060e556" + +/-- The same bytes, as numbers: what the statement binds. -/ +def runtimeBytes : List Nat := + [0x34, 0x60, 0x28, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x2f, 0x4f, 0x21, 0xe2, 0x14, + 0x60, 0xf8, 0x57, 0x80, 0x63, 0x70, 0xa0, 0x82, 0x31, 0x14, 0x61, 0x1, 0x61, 0x57, 0x80, 0x63, + 0xb6, 0xb5, 0x5f, 0x25, 0x14, 0x60, 0x3e, 0x57, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x60, 0x11, 0x60, + 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, 0x60, 0x1c, 0xfd, 0x5b, 0x60, + 0x24, 0x36, 0x10, 0x60, 0x28, 0x57, 0x60, 0x4, 0x35, 0x80, 0x33, 0x60, 0x87, 0x5b, 0x81, 0x5f, + 0x52, 0x5f, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x80, 0x54, 0x84, 0x81, 0x1, 0x90, 0x81, + 0x10, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x85, 0x11, 0x61, 0x1, 0xa6, 0x57, 0x60, 0x2c, 0x57, 0x81, + 0x55, 0x60, 0x1, 0x54, 0x93, 0x84, 0x1, 0x93, 0x84, 0x10, 0x60, 0x2c, 0x57, 0x92, 0x60, 0x1, + 0x55, 0x91, 0x54, 0x90, 0x50, 0x90, 0x56, 0x5b, 0x90, 0x5f, 0x52, 0x33, 0x7f, 0xe1, 0xff, 0xfc, + 0xc4, 0x92, 0x3d, 0x4, 0xb5, 0x59, 0xf4, 0xd2, 0x9a, 0x8b, 0xfc, 0x6c, 0xda, 0x4, 0xeb, 0x5b, + 0xd, 0x3c, 0x46, 0x7, 0x51, 0xc2, 0x40, 0x2c, 0x5c, 0x5c, 0xc9, 0x10, 0x9c, 0x60, 0x20, 0x5f, + 0xa2, 0x5f, 0x52, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x33, 0x11, 0x60, 0xcb, 0x57, 0x5f, 0x19, 0x60, + 0x60, 0x1c, 0x33, 0x11, 0x60, 0xcb, 0x57, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x69, 0x4, 0x17, 0x0, + 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x2, 0x60, 0x20, 0x1b, 0x33, 0x5f, 0x19, 0x60, 0x60, 0x1c, + 0x91, 0x5b, 0x60, 0x20, 0x52, 0x5b, 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, 0x63, 0xed, 0x57, 0x2b, + 0x27, 0x5f, 0x52, 0x60, 0x64, 0x60, 0x1c, 0xfd, 0x5b, 0x60, 0x4, 0x35, 0x60, 0xa0, 0x1c, 0x60, + 0x44, 0x36, 0x10, 0x17, 0x60, 0x28, 0x57, 0x60, 0x4, 0x35, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x81, + 0x16, 0x60, 0x24, 0x35, 0x82, 0x61, 0x1, 0x1b, 0x60, 0x4d, 0x56, 0x5b, 0x5f, 0x52, 0x5f, 0x19, + 0x60, 0x60, 0x1c, 0x82, 0x11, 0x61, 0x1, 0x47, 0x57, 0x81, 0x81, 0x3, 0x61, 0x1, 0x34, 0x57, + 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x6d, 0x1, 0x2, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x2, + 0x0, 0x0, 0x0, 0x7, 0x60, 0xe1, 0x56, 0x5b, 0x50, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x90, 0x6d, + 0x4, 0x17, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x9, 0x60, 0xe1, + 0x56, 0x5b, 0x60, 0x4, 0x35, 0x60, 0xa0, 0x1c, 0x60, 0x24, 0x36, 0x10, 0x17, 0x60, 0x28, 0x57, + 0x60, 0x4, 0x35, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x81, 0x16, 0x81, 0x5f, 0x52, 0x5f, 0x60, 0x20, + 0x52, 0x60, 0x40, 0x5f, 0x20, 0x54, 0x5f, 0x52, 0x81, 0x81, 0x3, 0x61, 0x1, 0x93, 0x57, 0x60, + 0x20, 0x5f, 0xf3, 0x5b, 0x6d, 0x1, 0x2, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x2, 0x0, + 0x0, 0x0, 0x9, 0x60, 0xe1, 0x56, 0x5b, 0x50, 0x50, 0x50, 0x50, 0x5f, 0x19, 0x60, 0x60, 0x1c, + 0x6d, 0x4, 0x17, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x0, 0x0, 0x0, 0x60, + 0x20, 0x52, 0x90, 0x60, 0xe5, 0x56] + +/-- The freshly exported bytecode the obligations speak of. -/ +def code : ByteArray := ⟨(SolarTV.Export.Bank.bytecode.map UInt8.ofNat).toArray⟩ + +/-- **The published statement.** -/ +def Statement : Prop := + code.data.toList.map (·.toNat) = runtimeBytes ∧ + (∃ c, SolidCore.Refinement.Solar.Bank.contract? = .ok c ∧ + Shapes.Compiled (solidCore (SolidCore.Refinement.Solar.Bank.fuel)) c code + (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.Bank.fns) ([])) (fun _ => 155937612)) + +set_option maxRecDepth 100000 in +theorem bound : code.data.toList.map (·.toNat) = runtimeBytes := + @of_decide_eq_true _ (instDecidableEqList _ _) (by decide +kernel) + +theorem final : Statement := + ⟨bound, Certified.bank.Shape.published⟩ + +#print axioms final + +end Certified.bank.Final diff --git a/Certified/bank/Proofs.lean b/Certified/bank/Proofs.lean new file mode 100644 index 00000000..763927f7 --- /dev/null +++ b/Certified/bank/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import bank.Proofs.Stages +import bank.Proofs.Assembly diff --git a/Certified/bank/Proofs/Assembly.lean b/Certified/bank/Proofs/Assembly.lean new file mode 100644 index 00000000..dee64448 --- /dev/null +++ b/Certified/bank/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Items +import bank.gen.Bank.Evm11 +import bank.gen.Bank.Bytecode + +/-! The final EVM IR of `Bank` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.Bank + +open SolarTV.Assembly SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm11).getD [] + +theorem items_eq : itemsOf evm11 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x28 else if label = 2 then 0x2c else if label = 3 then 0x3e else if label = 4 then 0x4d else if label = 5 then 0x87 else if label = 6 then 0xcb else if label = 7 then 0xe1 else if label = 8 then 0xe5 else if label = 9 then 0xf8 else if label = 10 then 0x11b else if label = 11 then 0x134 else if label = 12 then 0x147 else if label = 13 then 0x161 else if label = 14 then 0x193 else if label = 15 then 0x1a6 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.Bank.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.Bank.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms decodes + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm1.lean b/Certified/bank/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..ef5d66d6 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm1 +import bank.gen.Bank.Sched + +/-! `peephole-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 333 = EVM.Program.run o evm1 call 333 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm10.lean b/Certified/bank/Proofs/Runs/Evm10.lean new file mode 100644 index 00000000..54d647bc --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm10.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm10 +import bank.gen.Bank.Evm9 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm10_run (o : Oracle) (call : Call) : + EVM.Program.run o evm9 call 144 = EVM.Program.run o evm10 call 144 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm10_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm10_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm11.lean b/Certified/bank/Proofs/Runs/Evm11.lean new file mode 100644 index 00000000..2efcab59 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm11.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm11 +import bank.gen.Bank.Evm10 + +/-! `stack-reschedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm11_run (o : Oracle) (call : Call) : + EVM.Program.run o evm10 call 144 = EVM.Program.run o evm11 call 144 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm11_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm11_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm2.lean b/Certified/bank/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..fbca6035 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm2 +import bank.gen.Bank.Evm1 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 333 = EVM.Program.run o evm2 call 180 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm3.lean b/Certified/bank/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..041aa8f4 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm3 +import bank.gen.Bank.Evm2 + +/-! `compact-pushes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 180 = EVM.Program.run o evm3 call 180 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm4.lean b/Certified/bank/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..e5a0d2f3 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm4 +import bank.gen.Bank.Evm3 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 180 = EVM.Program.run o evm4 call 180 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm5.lean b/Certified/bank/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..3a8fae1b --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm5.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm5 +import bank.gen.Bank.Evm4 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 180 = EVM.Program.run o evm5 call 180 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm6.lean b/Certified/bank/Proofs/Runs/Evm6.lean new file mode 100644 index 00000000..dc18c1c9 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm6.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm6 +import bank.gen.Bank.Evm5 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm6_run (o : Oracle) (call : Call) : + EVM.Program.run o evm5 call 180 = EVM.Program.run o evm6 call 135 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm6_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm7.lean b/Certified/bank/Proofs/Runs/Evm7.lean new file mode 100644 index 00000000..077839ee --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm7.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm7 +import bank.gen.Bank.Evm6 + +/-! `tail-merge`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm7_run (o : Oracle) (call : Call) : + EVM.Program.run o evm6 call 135 = EVM.Program.run o evm7 call 153 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm7_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm7_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm8.lean b/Certified/bank/Proofs/Runs/Evm8.lean new file mode 100644 index 00000000..4632acfc --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm8.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm8 +import bank.gen.Bank.Evm7 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm8_run (o : Oracle) (call : Call) : + EVM.Program.run o evm7 call 153 = EVM.Program.run o evm8 call 144 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm8_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm8_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Evm9.lean b/Certified/bank/Proofs/Runs/Evm9.lean new file mode 100644 index 00000000..a2cad2ac --- /dev/null +++ b/Certified/bank/Proofs/Runs/Evm9.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Evm9 +import bank.gen.Bank.Evm8 + +/-! `reorder-pushes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm9_run (o : Oracle) (call : Call) : + EVM.Program.run o evm8 call 144 = EVM.Program.run o evm9 call 144 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.evm9_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm9_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Mir1.lean b/Certified/bank/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..e3104b39 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Mir1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Mir1 +import bank.gen.Bank.Stage0 + +/-! `place-reads`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir1_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 171 = MIR.Lowered.Module.run o mir1 call 171 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.mir1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Mir2.lean b/Certified/bank/Proofs/Runs/Mir2.lean new file mode 100644 index 00000000..3639fa98 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Mir2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Mir2 +import bank.gen.Bank.Mir1 + +/-! `spell-width-tests`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir2_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir1 call 171 = MIR.Lowered.Module.run o mir2 call 171 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.mir2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir2_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Mir3.lean b/Certified/bank/Proofs/Runs/Mir3.lean new file mode 100644 index 00000000..feb75f59 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Mir3.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Mir3 +import bank.gen.Bank.Mir2 + +/-! `lower-assumes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir3_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir2 call 171 = MIR.Lowered.Module.run o mir3 call 315 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.mir3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir3_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Mir4.lean b/Certified/bank/Proofs/Runs/Mir4.lean new file mode 100644 index 00000000..9799d1e8 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Mir4.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Mir4 +import bank.gen.Bank.Mir3 + +/-! `evm-inst-schedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir4_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir3 call 315 = MIR.Lowered.Module.run o mir4 call 315 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.mir4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir4_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Sched.lean b/Certified/bank/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..134c4694 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Sched +import bank.gen.Bank.Mir4 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir4 call 315 = EVM.Program.run o sched call 333 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Runs/Stage0.lean b/Certified/bank/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..028bee66 --- /dev/null +++ b/Certified/bank/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import bank.gen.Bank.Stage0 + +/-! The first lowered MIR ends on every call within 171 blocks, its block count times the square of one more than its call sites. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 171).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.Bank.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Proofs/Stages.lean b/Certified/bank/Proofs/Stages.lean new file mode 100644 index 00000000..99eb536b --- /dev/null +++ b/Certified/bank/Proofs/Stages.lean @@ -0,0 +1,275 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import bank.Proofs.Runs.Stage0 +import bank.Proofs.Runs.Mir1 +import bank.Proofs.Runs.Mir2 +import bank.Proofs.Runs.Mir3 +import bank.Proofs.Runs.Mir4 +import bank.Proofs.Runs.Sched +import bank.Proofs.Runs.Evm1 +import bank.Proofs.Runs.Evm2 +import bank.Proofs.Runs.Evm3 +import bank.Proofs.Runs.Evm4 +import bank.Proofs.Runs.Evm5 +import bank.Proofs.Runs.Evm6 +import bank.Proofs.Runs.Evm7 +import bank.Proofs.Runs.Evm8 +import bank.Proofs.Runs.Evm9 +import bank.Proofs.Runs.Evm10 +import bank.Proofs.Runs.Evm11 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Bank`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm11`. Fuels are the programs' block counts times the square of one more than their call sites. -/ + +namespace SolarTV.Milestone.Bank + +open Machine SolarTV.Export.Bank SolarTV.Milestone.W1 + +/-- `place-reads`: stage0 to mir1. -/ +theorem stage_mir1 (o : Oracle) : Stage (mirSem o) (mirSem o) stage0 mir1 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 171 171 (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +theorem mir1_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir1 call 171).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := stage0) (q := mir1) (n := 171) (m := 171) (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +/-- `spell-width-tests`: mir1 to mir2. -/ +theorem stage_mir2 (o : Oracle) : Stage (mirSem o) (mirSem o) mir1 mir2 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 171 171 (mir1_ends o) + (fun call _ => mir2_run o call) + +theorem mir2_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir2 call 171).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir1) (q := mir2) (n := 171) (m := 171) (mir1_ends o) + (fun call _ => mir2_run o call) + +/-- `lower-assumes`: mir2 to mir3. -/ +theorem stage_mir3 (o : Oracle) : Stage (mirSem o) (mirSem o) mir2 mir3 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 171 315 (mir2_ends o) + (fun call _ => mir3_run o call) + +theorem mir3_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir3 call 315).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir2) (q := mir3) (n := 171) (m := 315) (mir2_ends o) + (fun call _ => mir3_run o call) + +/-- `evm-inst-schedule`: mir3 to mir4. -/ +theorem stage_mir4 (o : Oracle) : Stage (mirSem o) (mirSem o) mir3 mir4 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 315 315 (mir3_ends o) + (fun call _ => mir4_run o call) + +theorem mir4_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir4 call 315).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir3) (q := mir4) (n := 315) (m := 315) (mir3_ends o) + (fun call _ => mir4_run o call) + +/-- `stack-schedule`: mir4 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) mir4 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 315 333 (mir4_ends o) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 333).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := mir4) (q := sched) (n := 315) (m := 333) (mir4_ends o) + (fun call _ => sched_run o call) + +/-- `peephole-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 333 333 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 333).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 333) (m := 333) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `cfg-simplify-early`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 333 180 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 180).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 333) (m := 180) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `compact-pushes`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 180 180 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 180).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 180) (m := 180) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `block-layout`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 180 180 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 180).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 180) (m := 180) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `terminal-dedup`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 180 180 (evm4_ends o) + (fun call _ => evm5_run o call) + +theorem evm5_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm5 call 180).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm4) (q := evm5) (n := 180) (m := 180) (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- `cfg-simplify-early`: evm5 to evm6. -/ +theorem stage_evm6 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm5 evm6 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 180 135 (evm5_ends o) + (fun call _ => evm6_run o call) + +theorem evm6_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm6 call 135).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm5) (q := evm6) (n := 180) (m := 135) (evm5_ends o) + (fun call _ => evm6_run o call) + +/-- `tail-merge`: evm6 to evm7. -/ +theorem stage_evm7 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm6 evm7 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 135 153 (evm6_ends o) + (fun call _ => evm7_run o call) + +theorem evm7_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm7 call 153).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm6) (q := evm7) (n := 135) (m := 153) (evm6_ends o) + (fun call _ => evm7_run o call) + +/-- `cfg-simplify-early`: evm7 to evm8. -/ +theorem stage_evm8 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm7 evm8 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 153 144 (evm7_ends o) + (fun call _ => evm8_run o call) + +theorem evm8_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm8 call 144).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm7) (q := evm8) (n := 153) (m := 144) (evm7_ends o) + (fun call _ => evm8_run o call) + +/-- `reorder-pushes`: evm8 to evm9. -/ +theorem stage_evm9 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm8 evm9 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 144 144 (evm8_ends o) + (fun call _ => evm9_run o call) + +theorem evm9_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm9 call 144).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm8) (q := evm9) (n := 144) (m := 144) (evm8_ends o) + (fun call _ => evm9_run o call) + +/-- `block-layout`: evm9 to evm10. -/ +theorem stage_evm10 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm9 evm10 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 144 144 (evm9_ends o) + (fun call _ => evm10_run o call) + +theorem evm10_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm10 call 144).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm9) (q := evm10) (n := 144) (m := 144) (evm9_ends o) + (fun call _ => evm10_run o call) + +/-- `stack-reschedule`: evm10 to evm11. -/ +theorem stage_evm11 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm10 evm11 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 144 144 (evm10_ends o) + (fun call _ => evm11_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1, mir2, mir3, mir4], sched, [evm1, evm2, evm3, evm4, evm5, evm6, evm7, evm8, evm9, evm10, evm11]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem bank_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm11 anyCall := + mir_to_evmir o anyCall compilation ⟨stage_mir1 o, stage_mir2 o, stage_mir3 o, stage_mir4 o, trivial⟩ (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, stage_evm6 o, stage_evm7 o, stage_evm8 o, stage_evm9 o, stage_evm10 o, stage_evm11 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.Bank.stage_mir1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir1 + +/-- info: 'SolarTV.Milestone.Bank.stage_mir2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir2 + +/-- info: 'SolarTV.Milestone.Bank.stage_mir3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir3 + +/-- info: 'SolarTV.Milestone.Bank.stage_mir4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir4 + +/-- info: 'SolarTV.Milestone.Bank.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.Bank.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm6' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm6 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm7' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm7 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm8' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm8 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm9' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm9 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm10' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm10 + +/-- info: 'SolarTV.Milestone.Bank.stage_evm11' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm11 + +/-- info: 'SolarTV.Milestone.Bank.bank_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bank_mir_to_evmir + +end SolarTV.Milestone.Bank diff --git a/Certified/bank/Shape.lean b/Certified/bank/Shape.lean new file mode 100644 index 00000000..6c658608 --- /dev/null +++ b/Certified/bank/Shape.lean @@ -0,0 +1,133 @@ +import Verify.ShapeGeneric +import SolidCore.Refinement.Solar.Bank.Lowering +import bank.Proofs.Stages +import bank.gen.Bank.Bytecode + +-- Generated by solar's tools/certify/shape_gen.py from bank/shape.json and this run's export; +-- do not edit. Untrusted data and composition: the kernel re-derives every claim. + +/-! +# Bank: the proof of the published statement + +`published` applies `SolidCore.Refinement.Shapes.compiled` to the source check of `SolidCore.Refinement.Solar.Bank`, solar-tv's backend +stages to `evm11` (`SolarTV.Milestone.Bank.bank_mir_to_evmir`), the final EVM IR's run within 144 blocks on every +call (the last stage's fuel) and the loop checker on the exact bytecode, with the certificate +tools/certify/asm_cert.py inferred. The gas bound is `gasBoundL cert 144` = 22100 · (144 · 49) + 12 += 155937612, at most the statement's 155937612. +-/ + +namespace Certified.bank.Shape + +open SolidCore.Refinement SolidCore.Refinement.Solar SolarTV + +/-- The exported runtime bytecode. -/ +def code : ByteArray := ⟨(SolarTV.Export.Bank.bytecode.map UInt8.ofNat).toArray⟩ + +/-- The loop checker's certificate (tools/certify/asm_cert.py). -/ +def cert : SolidCore.Refinement.Solar.Assemble.Cert := + { offsets := [0x0, 0x28, 0x2c, 0x3e, 0x4d, 0x87, 0xcb, 0xe1, 0xe5, 0xf8, 0x11b, 0x134, 0x147, 0x161, 0x193, 0x1a6], + needs := [0, 0, 6, 1, 5, 3, 1, 3, 2, 1, 3, 2, 2, 1, 3, 8], + top := 128, + turned := [], + costs := [22, 3, 9, 11, 49, 29, 10, 3, 10, 25, 18, 4, 10, 38, 4, 15], + types := [[], + [], + [some false, none, none, some false, some false, some false], + [some false], + [some true, some false, some false, some false, some false], + [some false, some false, some false], + [some false], + [some false, some false, some false], + [some false, some false], + [some false], + [some false, some false, some false], + [some false, some false], + [some false, some false], + [some false], + [some false, some false, some false], + [some false, some false, some false, some true, some false, some false, some false, some false]], + rets := [5, 10], + env := true, + reads := false } + +/-- The highest stack each block is entered with. -/ +def maxs : List Nat := [0, 1, 8, 1, 6, 4, 2, 5, 6, 1, 4, 3, 3, 1, 3, 9] + +set_option maxRecDepth 100000 in +theorem walk_ok : (SolarTV.Assembly.walk (SolidCore.Refinement.Solar.Assemble.bytesOf code) cert.offset 0 + (SolidCore.Refinement.Solar.Assemble.lower SolarTV.Export.Bank.evm11 cert)).isSome = true := by + have hw := SolidCore.Refinement.Solar.Assemble.walkS_drop (SolidCore.Refinement.Solar.Assemble.bytesOf code) cert.offset (SolidCore.Refinement.Solar.Assemble.lower SolarTV.Export.Bank.evm11 cert) 0 + (Nat.zero_le _) + rw [List.drop_zero] at hw + rw [← hw] + decide +kernel + +set_option maxRecDepth 100000 in +theorem blocks_ok : SolidCore.Refinement.Solar.AssembleLoop.blocksOkL SolarTV.Export.Bank.evm11 cert maxs 0 SolarTV.Export.Bank.evm11.blocks = true := by + decide +kernel + +theorem labels_ok : SolidCore.Refinement.Solar.Assemble.labelsValid SolarTV.Export.Bank.evm11 cert code = true := + SolidCore.Refinement.Solar.Assemble.labelsValid_of_walk walk_ok + +theorem size_ok : code.size < 2 ^ 32 := by decide +kernel + +/-- The checker of code with loops accepts the exact bytecode for the final EVM IR. -/ +theorem check_ok : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.Bank.evm11 code cert maxs = true := by + simp only [SolidCore.Refinement.Solar.AssembleLoop.checkL, walk_ok, blocks_ok, labels_ok, decide_eq_true size_ok, Bool.and_true, + Bool.true_and] + decide + +/-- The final EVM IR ends within 144 blocks on every call, under the bytecode's oracle. -/ +theorem ends (call : Call) : (EVM.Program.run SolidCore.Refinement.Shapes.oracle SolarTV.Export.Bank.evm11 call 144).isSome = true := + SolarTV.Milestone.W1.ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := SolidCore.Refinement.Shapes.oracle) (p := SolarTV.Export.Bank.evm10) (q := SolarTV.Export.Bank.evm11) (n := 144) (m := 144) + (SolarTV.Milestone.Bank.evm10_ends SolidCore.Refinement.Shapes.oracle) (fun call _ => SolarTV.Milestone.Bank.evm11_run SolidCore.Refinement.Shapes.oracle call) call trivial + +/-- The bytecode with byte `i` replaced by `b`. -/ +def mutant (i b : Nat) : ByteArray := ⟨((SolarTV.Export.Bank.bytecode.set i b).map UInt8.ofNat).toArray⟩ + +set_option maxRecDepth 100000 in +/-- The checker rejects the bytecode with a jump target moved (byte 2). -/ +theorem rejects_jump : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.Bank.evm11 (mutant 2 41) cert maxs = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The checker rejects the bytecode with an SSTORE dropped (as POP) (byte 112). -/ +theorem rejects_sstore : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.Bank.evm11 (mutant 112 80) cert maxs = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The checker rejects the bytecode with an opcode outside the fragment (CREATE) for an SSTORE (byte 112). -/ +theorem rejects_opcode : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.Bank.evm11 (mutant 112 240) cert maxs = false := by + decide +kernel + +theorem gas_lt : SolidCore.Refinement.Solar.AssembleLoop.gasBoundL cert 144 < 2 ^ 64 := by decide +kernel + +theorem gas_le : SolidCore.Refinement.Solar.AssembleLoop.gasBoundL cert 144 ≤ 155937612 := by decide +kernel + +/-- SolidCore type checks the contract. -/ +theorem contract_ok : ∃ c, SolidCore.Refinement.Solar.Bank.contract? = .ok c := by + have h := SolidCore.Refinement.Solar.Bank.shape_eq + unfold SolidCore.Refinement.Solar.Bank.shape? at h + split at h + · next c hc => exact ⟨c, hc⟩ + · simp at h + + +/-- **What the published statement asks of this module.** -/ +theorem published : ∃ c, SolidCore.Refinement.Solar.Bank.contract? = .ok c ∧ + SolidCore.Refinement.Shapes.Compiled (solidCore SolidCore.Refinement.Solar.Bank.fuel) c code (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.Bank.fns) ([])) (fun _ => 155937612) := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, d, hd⟩ := SolidCore.Refinement.Solar.Bank.deployed_of hc + have hchk := SolidCore.Refinement.Solar.Bank.check_stage0 + rw [← hk] at hchk + have hval := SolidCore.Refinement.Solar.Bank.checkValue_stage0 + rw [← hk] at hval + exact ⟨c, hc, (SolidCore.Refinement.Shapes.compiled hd hchk hval (SolidCore.Refinement.Shapes.genericValid_inhabited _ _ _) + (SolarTV.Milestone.Bank.bank_mir_to_evmir SolidCore.Refinement.Shapes.oracle) (fun _ _ => trivial) ends check_ok gas_lt).mono_gas (fun _ => gas_le) (fun _ => by decide)⟩ + +/-- info: 'Certified.bank.Shape.published' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms published + +end Certified.bank.Shape diff --git a/Certified/bank/bank.sol b/Certified/bank/bank.sol new file mode 100644 index 00000000..7d449f0d --- /dev/null +++ b/Certified/bank/bank.sol @@ -0,0 +1,40 @@ +contract Bank { + mapping(address => uint256) balances; + uint256 total; + + event Deposit(address indexed who, uint256 amount); + + function credit(address who, uint256 amount) internal returns (uint256) { + balances[who] += amount; + total += amount; + return balances[who]; + } + + /// @custom:succeeds-if msg.value == 0 && (balances[msg.sender] + amount < 2 ** 256 && total + amount < 2 ** 256) + /// @custom:ensures balances[msg.sender] == old(balances[msg.sender]) + amount + /// @custom:ensures total == old(total) + amount + /// @custom:ensures result == balances[msg.sender] + /// @custom:ensures forall address a :: a != msg.sender ==> balances[a] == old(balances[a]) + function deposit(uint256 amount) external returns (uint256) { + uint256 b = credit(msg.sender, amount); + emit Deposit(msg.sender, amount); + return b; + } + + /// @custom:succeeds-if msg.value == 0 && (balances[who] + amount < 2 ** 256 && total + amount < 2 ** 256) + /// @custom:ensures balances[who] == old(balances[who]) + amount + /// @custom:ensures total == old(total) + amount + /// @custom:ensures result == balances[who] + /// @custom:ensures forall address a :: a != who ==> balances[a] == old(balances[a]) + function depositFor(address who, uint256 amount) external returns (uint256) { + return credit(who, amount); + } + + /// @custom:succeeds-if msg.value == 0 + /// @custom:ensures result == balances[who] + /// @custom:ensures total == old(total) + /// @custom:ensures forall address a :: balances[a] == old(balances[a]) + function balanceOf(address who) external view returns (uint256) { + return balances[who]; + } +} diff --git a/Certified/bank/bytecode.hex b/Certified/bank/bytecode.hex new file mode 100644 index 00000000..6c899e5b --- /dev/null +++ b/Certified/bank/bytecode.hex @@ -0,0 +1 @@ +346028575f3560e01c80632f4f21e21460f857806370a0823114610161578063b6b55f2514603e575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243610602857600435803360875b815f525f60205260405f2080548481019081105f1960601c85116101a657602c578155600154938401938410602c57926001559154905090565b905f52337fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c60205fa25f525f1960601c331160cb575f1960601c331160cb5760205ff35b690417000000010000000260201b335f1960601c915b6020525b60405260605263ed572b275f526064601cfd5b60043560a01c60443610176028576004355f1960601c81166024358261011b604d565b5f525f1960601c8211610147578181036101345760205ff35b6d010200000002000000020000000760e1565b505f1960601c906d041700000002000000020000000960e1565b60043560a01c60243610176028576004355f1960601c8116815f525f60205260405f20545f528181036101935760205ff35b6d010200000003000000020000000960e1565b505050505f1960601c6d04170000000000000000800000006020529060e556 diff --git a/Certified/bank/gen/Bank/Bytecode.lean b/Certified/bank/gen/Bank/Bytecode.lean new file mode 100644 index 00000000..1ae1df5e --- /dev/null +++ b/Certified/bank/gen/Bank/Bytecode.lean @@ -0,0 +1,42 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x28, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x2f, 0x4f, 0x21, 0xe2, 0x14, + 0x60, 0xf8, 0x57, 0x80, 0x63, 0x70, 0xa0, 0x82, 0x31, 0x14, 0x61, 0x01, 0x61, 0x57, 0x80, 0x63, + 0xb6, 0xb5, 0x5f, 0x25, 0x14, 0x60, 0x3e, 0x57, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x60, 0x11, 0x60, + 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, 0x60, 0x1c, 0xfd, 0x5b, 0x60, + 0x24, 0x36, 0x10, 0x60, 0x28, 0x57, 0x60, 0x04, 0x35, 0x80, 0x33, 0x60, 0x87, 0x5b, 0x81, 0x5f, + 0x52, 0x5f, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x80, 0x54, 0x84, 0x81, 0x01, 0x90, 0x81, + 0x10, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x85, 0x11, 0x61, 0x01, 0xa6, 0x57, 0x60, 0x2c, 0x57, 0x81, + 0x55, 0x60, 0x01, 0x54, 0x93, 0x84, 0x01, 0x93, 0x84, 0x10, 0x60, 0x2c, 0x57, 0x92, 0x60, 0x01, + 0x55, 0x91, 0x54, 0x90, 0x50, 0x90, 0x56, 0x5b, 0x90, 0x5f, 0x52, 0x33, 0x7f, 0xe1, 0xff, 0xfc, + 0xc4, 0x92, 0x3d, 0x04, 0xb5, 0x59, 0xf4, 0xd2, 0x9a, 0x8b, 0xfc, 0x6c, 0xda, 0x04, 0xeb, 0x5b, + 0x0d, 0x3c, 0x46, 0x07, 0x51, 0xc2, 0x40, 0x2c, 0x5c, 0x5c, 0xc9, 0x10, 0x9c, 0x60, 0x20, 0x5f, + 0xa2, 0x5f, 0x52, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x33, 0x11, 0x60, 0xcb, 0x57, 0x5f, 0x19, 0x60, + 0x60, 0x1c, 0x33, 0x11, 0x60, 0xcb, 0x57, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x69, 0x04, 0x17, 0x00, + 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x60, 0x20, 0x1b, 0x33, 0x5f, 0x19, 0x60, 0x60, 0x1c, + 0x91, 0x5b, 0x60, 0x20, 0x52, 0x5b, 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, 0x63, 0xed, 0x57, 0x2b, + 0x27, 0x5f, 0x52, 0x60, 0x64, 0x60, 0x1c, 0xfd, 0x5b, 0x60, 0x04, 0x35, 0x60, 0xa0, 0x1c, 0x60, + 0x44, 0x36, 0x10, 0x17, 0x60, 0x28, 0x57, 0x60, 0x04, 0x35, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x81, + 0x16, 0x60, 0x24, 0x35, 0x82, 0x61, 0x01, 0x1b, 0x60, 0x4d, 0x56, 0x5b, 0x5f, 0x52, 0x5f, 0x19, + 0x60, 0x60, 0x1c, 0x82, 0x11, 0x61, 0x01, 0x47, 0x57, 0x81, 0x81, 0x03, 0x61, 0x01, 0x34, 0x57, + 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x6d, 0x01, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, + 0x00, 0x00, 0x00, 0x07, 0x60, 0xe1, 0x56, 0x5b, 0x50, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x90, 0x6d, + 0x04, 0x17, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x09, 0x60, 0xe1, + 0x56, 0x5b, 0x60, 0x04, 0x35, 0x60, 0xa0, 0x1c, 0x60, 0x24, 0x36, 0x10, 0x17, 0x60, 0x28, 0x57, + 0x60, 0x04, 0x35, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x81, 0x16, 0x81, 0x5f, 0x52, 0x5f, 0x60, 0x20, + 0x52, 0x60, 0x40, 0x5f, 0x20, 0x54, 0x5f, 0x52, 0x81, 0x81, 0x03, 0x61, 0x01, 0x93, 0x57, 0x60, + 0x20, 0x5f, 0xf3, 0x5b, 0x6d, 0x01, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, + 0x00, 0x00, 0x09, 0x60, 0xe1, 0x56, 0x5b, 0x50, 0x50, 0x50, 0x50, 0x5f, 0x19, 0x60, 0x60, 0x1c, + 0x6d, 0x04, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x60, + 0x20, 0x52, 0x90, 0x60, 0xe5, 0x56] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "346028575f3560e01c80632f4f21e21460f857806370a0823114610161578063b6b55f2514603e575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243610602857600435803360875b815f525f60205260405f2080548481019081105f1960601c85116101a657602c578155600154938401938410602c57926001559154905090565b905f52337fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c60205fa25f525f1960601c331160cb575f1960601c331160cb5760205ff35b690417000000010000000260201b335f1960601c915b6020525b60405260605263ed572b275f526064601cfd5b60043560a01c60443610176028576004355f1960601c81166024358261011b604d565b5f525f1960601c8211610147578181036101345760205ff35b6d010200000002000000020000000760e1565b505f1960601c906d041700000002000000020000000960e1565b60043560a01c60243610176028576004355f1960601c8116815f525f60205260405f20545f528181036101935760205ff35b6d010200000003000000020000000960e1565b505050505f1960601c6d04170000000000000000800000006020529060e556" + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm1.lean b/Certified/bank/gen/Bank/Evm1.lean new file mode 100644 index 00000000..dd2044f5 --- /dev/null +++ b/Certified/bank/gen/Bank/Evm1.lean @@ -0,0 +1,319 @@ +-- solar-lean-stage: kind=evm index=1 pass=peephole-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `peephole-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 5, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 2, + .jump 5], + -- bb2 + [.jump 6], + -- bb3 + [.jump 24], + -- bb4 + [.jump 15], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 14, + .jump 7], + -- bb7 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 8, + .jump 30], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 12, + .jump 9], + -- bb9 + [.op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 11, + .jump 10], + -- bb10 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x417000000010000000200000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 13], + -- bb12 + [.op (.stack (.push 0x417000000010000000200000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 13], + -- bb13 + [.op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 23, + .jump 16], + -- bb16 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 17, + .jump 30], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 21, + .jump 18], + -- bb18 + [.op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 20, + .jump 19], + -- bb19 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 22], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 22], + -- bb22 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb23 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 29, + .jump 25], + -- bb25 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 27, + .jump 26], + -- bb26 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .jump 28], + -- bb28 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb29 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 35, + .jump 31], + -- bb31 + [.jumpi 34, + .jump 32], + -- bb32 + [.op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 34, + .jump 33], + -- bb33 + [.op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 36], + -- bb36 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm10.lean b/Certified/bank/gen/Bank/Evm10.lean new file mode 100644 index 00000000..d52d203a --- /dev/null +++ b/Certified/bank/gen/Bank/Evm10.lean @@ -0,0 +1,265 @@ +-- solar-lean-stage: kind=evm index=10 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `block-layout`. -/ +def evm10 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 9, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 13, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 5, + .jump 4], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 15, + .jumpi 2, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .jump 7], + -- bb37 + [.op (.stack (.push 32)), + .op .store, + .jump 8], + -- bb36 + [.op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 10, + .jump 4], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 12, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 11, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 7], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 7], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 14, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .jump 7], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .jump 8]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm11.lean b/Certified/bank/gen/Bank/Evm11.lean new file mode 100644 index 00000000..00f7ad58 --- /dev/null +++ b/Certified/bank/gen/Bank/Evm11.lean @@ -0,0 +1,263 @@ +-- solar-lean-stage: kind=evm index=11 pass=stack-reschedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `stack-reschedule`. -/ +def evm11 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 9, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 13, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 5, + .jump 4], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 15, + .jumpi 2, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .jump 7], + -- bb37 + [.op (.stack (.push 32)), + .op .store, + .jump 8], + -- bb36 + [.op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 10, + .jump 4], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 12, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 11, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 7], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.push 0x417000000020000000200000009)), + .jump 7], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 14, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .jump 7], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .jump 8]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm2.lean b/Certified/bank/gen/Bank/Evm2.lean new file mode 100644 index 00000000..986c3065 --- /dev/null +++ b/Certified/bank/gen/Bank/Evm2.lean @@ -0,0 +1,285 @@ +-- solar-lean-stage: kind=evm index=2 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 8, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 14, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 7, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 3, + .jump 17], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 5, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 4, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x417000000010000000200000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 6], + -- bb12 + [.op (.stack (.push 0x417000000010000000200000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 6], + -- bb13 + [.op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 13, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 9, + .jump 17], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 11, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 10, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 12], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 12], + -- bb22 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb23 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 16, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 15, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb29 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 19, + .jumpi 18, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 18, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm3.lean b/Certified/bank/gen/Bank/Evm3.lean new file mode 100644 index 00000000..ca797f6d --- /dev/null +++ b/Certified/bank/gen/Bank/Evm3.lean @@ -0,0 +1,319 @@ +-- solar-lean-stage: kind=evm index=3 pass=compact-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `compact-pushes`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 8, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 14, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 7, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 3, + .jump 17], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 5, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 4, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 6], + -- bb12 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 6], + -- bb13 + [.op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 13, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 9, + .jump 17], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 11, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 10, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 12], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 12], + -- bb22 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb23 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 16, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 15, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb29 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 19, + .jumpi 18, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 18, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm4.lean b/Certified/bank/gen/Bank/Evm4.lean new file mode 100644 index 00000000..3c4875ec --- /dev/null +++ b/Certified/bank/gen/Bank/Evm4.lean @@ -0,0 +1,319 @@ +-- solar-lean-stage: kind=evm index=4 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `block-layout`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 9, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 14, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 15, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 5, + .jump 4], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 19, + .jumpi 2, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 8, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 7], + -- bb13 + [.op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb12 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 7], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 16, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 10, + .jump 4], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 13, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 11, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 12], + -- bb22 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 12], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 18, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb23 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb29 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm5.lean b/Certified/bank/gen/Bank/Evm5.lean new file mode 100644 index 00000000..5423cb76 --- /dev/null +++ b/Certified/bank/gen/Bank/Evm5.lean @@ -0,0 +1,305 @@ +-- solar-lean-stage: kind=evm index=5 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 9, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 14, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 15, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 5, + .jump 4], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 19, + .jumpi 2, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 8, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 7], + -- bb13 + [.op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb12 + [.jump 6], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 16, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 10, + .jump 4], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 13, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 11, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 12], + -- bb22 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 12], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 18, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb14 + [.jump 1], + -- bb23 + [.jump 1], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb29 + [.jump 1], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm6.lean b/Certified/bank/gen/Bank/Evm6.lean new file mode 100644 index 00000000..42377488 --- /dev/null +++ b/Certified/bank/gen/Bank/Evm6.lean @@ -0,0 +1,295 @@ +-- solar-lean-stage: kind=evm index=6 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm6 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 5, + .jump 4], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 14, + .jumpi 2, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 8, + .jump 4], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 11, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 10], + -- bb22 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 10], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 13, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm7.lean b/Certified/bank/gen/Bank/Evm7.lean new file mode 100644 index 00000000..7317023c --- /dev/null +++ b/Certified/bank/gen/Bank/Evm7.lean @@ -0,0 +1,268 @@ +-- solar-lean-stage: kind=evm index=7 pass=tail-merge +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `tail-merge`. -/ +def evm7 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 5, + .jump 4], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 14, + .jumpi 2, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .jump 16], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 8, + .jump 4], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 11, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 10], + -- bb22 + [.jump 16], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 10], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 13, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .jump 16], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .jump 15], + -- bb36 + [.op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb37 + [.op (.stack (.push 32)), + .op .store, + .jump 15]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm8.lean b/Certified/bank/gen/Bank/Evm8.lean new file mode 100644 index 00000000..7e222cff --- /dev/null +++ b/Certified/bank/gen/Bank/Evm8.lean @@ -0,0 +1,266 @@ +-- solar-lean-stage: kind=evm index=8 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm8 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 11, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 5, + .jump 4], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 13, + .jumpi 2, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .jump 15], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 8, + .jump 4], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 10, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 15], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 15], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 12, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .jump 15], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .jump 14], + -- bb36 + [.op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb37 + [.op (.stack (.push 32)), + .op .store, + .jump 14]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Evm9.lean b/Certified/bank/gen/Bank/Evm9.lean new file mode 100644 index 00000000..b12b86ce --- /dev/null +++ b/Certified/bank/gen/Bank/Evm9.lean @@ -0,0 +1,265 @@ +-- solar-lean-stage: kind=evm index=9 pass=reorder-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR after `reorder-pushes`. -/ +def evm9 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 11, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 5, + .jump 4], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 13, + .jumpi 2, + .op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 6, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x4170000000100000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .jump 15], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 8, + .jump 4], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 10, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 9, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 15], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 15], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 12, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .jump 15], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .jump 14], + -- bb36 + [.op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb37 + [.op (.stack (.push 32)), + .op .store, + .jump 14]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Manifest.lean b/Certified/bank/gen/Bank/Manifest.lean new file mode 100644 index 00000000..be171804 --- /dev/null +++ b/Certified/bank/gen/Bank/Manifest.lean @@ -0,0 +1,52 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Bank.Manifest + +def sources : List (String × String) := + [("Certified/bank/bank.sol", "2a29919999674ac221097e3f50ed43bcddf094d19a08da5f5c9704a0dd099d03")] + +def compiler : String := "0.8.38+commit.52e2060e.solar.0.3.0-dev" + +def arguments : List String := + ["Certified/bank/bank.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/bank/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "7d145b2998661cb5c4592a5374f9cc79d94794bba2f6f17b3dfdd0e2a87e0fcc"), + ("Mir1", "mir1", "place-reads", "fc18b9f9f61ef53c23dcf6f6799dee7c57a15ca47bb4da2255c633f82b1308ab"), + ("Mir2", "mir2", "spell-width-tests", "706bb5ac9ec0a0d67f08496e91c62af4ae17405eb912f83decf45e9a8292b2c0"), + ("Mir3", "mir3", "lower-assumes", "aedcd4a2b80c765f6e037a756d6db7b1fab1a2447bdf0ca62eda37ae64185e34"), + ("Mir4", "mir4", "evm-inst-schedule", "6f68722b113a0f8f2cda66280547c0601f97b443d416806a6803322a38ae51b9"), + ("Sched", "sched", "stack-schedule", "7867a2d8d7a8605c655c1bc038b5cee9a7e714d6c152c9e267afc6dcfd8f9586"), + ("Evm1", "evm1", "peephole-early", "92adb3e54ee739c60d8e69961ba9619245df9ae42f1dca9df06fa352fd35f652"), + ("Evm2", "evm2", "cfg-simplify-early", "357042975eaf869a3c7f3a65ee4fc68bf6ef1cbb39d2c129c7aa730ac4ce95c7"), + ("Evm3", "evm3", "compact-pushes", "95b583b99ae08080b2753dc74b9a3d0f0921e23147a0419959612ea9afb91025"), + ("Evm4", "evm4", "block-layout", "5c18eab01a900c5e39d0cac1415ad8339a52ba78c43649f4e3fbfb8cb380e6e1"), + ("Evm5", "evm5", "terminal-dedup", "6ebad5531b56a0b055f247364e211b2ed1882f40858c9d75ce5b15ffcd5d9ea2"), + ("Evm6", "evm6", "cfg-simplify-early", "5f9a29c13202ce893fa142487c112f530321e5ac8041c28597d23504b278b7f8"), + ("Evm7", "evm7", "tail-merge", "baa56a2fc6e55d128e88f34ce5e6bcfdf7e4cbb78a0a907bf7ddcea3a8502bfa"), + ("Evm8", "evm8", "cfg-simplify-early", "b954ed58f56daec2d604a03ac02aa0ef3e543767b4a5d0bb13f68ea7f74fead6"), + ("Evm9", "evm9", "reorder-pushes", "43597405f5bd81147174381637469732e796aa4056f192d37311c7b21f95b65c"), + ("Evm10", "evm10", "block-layout", "0153e265384d5fa0bb56bbcddac12cb7724b905dafbd698d03461bba22095730"), + ("Evm11", "evm11", "stack-reschedule", "d55f0c281937953166c7fe2d2176bcb62145f1e1a597546d95ae4e3d903329aa"), + ("Bytecode", "bytecode", "assemble", "48ec986cf2d82ee746b044677549cc626376293bd6701e44e04d9b1e8e93bd8a")] + +def bytecodeHex : String := + "346028575f3560e01c80632f4f21e21460f857806370a0823114610161578063b6b55f2514603e575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243610602857600435803360875b815f525f60205260405f2080548481019081105f1960601c85116101a657602c578155600154938401938410602c57926001559154905090565b905f52337fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c60205fa25f525f1960601c331160cb575f1960601c331160cb5760205ff35b690417000000010000000260201b335f1960601c915b6020525b60405260605263ed572b275f526064601cfd5b60043560a01c60443610176028576004355f1960601c81166024358261011b604d565b5f525f1960601c8211610147578181036101345760205ff35b6d010200000002000000020000000760e1565b505f1960601c906d041700000002000000020000000960e1565b60043560a01c60243610176028576004355f1960601c8116815f525f60205260405f20545f528181036101935760205ff35b6d010200000003000000020000000960e1565b505050505f1960601c6d04170000000000000000800000006020529060e556" + +def bytecodeSha256 : String := "bff0578068ce4ab4a041f226e4e960c13d358c8b430718fefe9ce3a22d760543" + +end SolarTV.Export.Bank.Manifest diff --git a/Certified/bank/gen/Bank/Mir1.lean b/Certified/bank/gen/Bank/Mir1.lean new file mode 100644 index 00000000..4c74b5a8 --- /dev/null +++ b/Certified/bank/gen/Bank/Mir1.lean @@ -0,0 +1,146 @@ +-- solar-lean-stage: kind=mir index=1 pass=place-reads +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The lowered MIR module after `place-reads`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 4, + functions := [ + -- @credit + { params := [0, 30, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 0, .value 0], + .effect none .mstore [.const 32, .const 0], + .effect (some 29) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 29], + .pure 15 .add [.value 5, .value 1], + .pure 16 .lt [.value 15, .value 5], + .assume true .gt [.value 30, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 16) 1 2⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.value 29, .value 15], + .effect (some 8) .sload [.const 1], + .pure 23 .add [.value 8, .value 1], + .pure 24 .lt [.value 23, .value 8]], + .branch (.value 24) 1 3⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 1, .value 23], + .effect (some 14) .sload [.value 29]], + .leave [.value 14]⟩] }, + -- @deposit + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 11) .calldatasize [], + .pure 13 .lt [.value 11, .const 36]], + .branch (.value 13) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 15) .calldataload [.const 4], + .effect (some 1) .caller [], + .call (some 2) 0 [.value 1, .value 1, .value 15], + .effect none .mstore [.const 0, .value 15], + .effect none (.log 2) [.const 0, .const 32, .const 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c, .value 1], + .effect none .mstore [.const 0, .value 2], + .assume true .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume true .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .ret (.const 0) (.const 32)⟩] }, + -- @depositFor + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 5) .calldatasize [], + .pure 7 .lt [.value 5, .const 68], + .effect (some 9) .calldataload [.const 4], + .pure 11 .gt [.value 9, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 21 .or [.value 7, .value 11]], + .branch (.value 21) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 22) .calldataload [.const 4], + .effect (some 13) .calldataload [.const 36], + .pure 19 .and [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff], + .call (some 3) 0 [.value 22, .value 22, .value 13], + .effect none .mstore [.const 0, .value 3], + .assume true .gt [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 19, .value 22]], + .ret (.const 0) (.const 32)⟩] }, + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 13 .gt [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 25 .or [.value 9, .value 13]], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .pure 24 .and [.value 26, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5], + .assume false .eq [.value 24, .value 26]], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 5 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 5 [(.const 0x2f4f21e2, 2), (.const 0x70a08231, 3), (.const 0xb6b55f25, 4)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Mir2.lean b/Certified/bank/gen/Bank/Mir2.lean new file mode 100644 index 00000000..4e159ef1 --- /dev/null +++ b/Certified/bank/gen/Bank/Mir2.lean @@ -0,0 +1,150 @@ +-- solar-lean-stage: kind=mir index=2 pass=spell-width-tests +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The lowered MIR module after `spell-width-tests`. -/ +def mir2 : MIR.Lowered.Module := + { entry := 4, + functions := [ + -- @credit + { params := [0, 30, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 0, .value 0], + .effect none .mstore [.const 32, .const 0], + .effect (some 29) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 29], + .pure 15 .add [.value 5, .value 1], + .pure 16 .lt [.value 15, .value 5], + .assume true .gt [.value 30, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 16) 1 2⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.value 29, .value 15], + .effect (some 8) .sload [.const 1], + .pure 23 .add [.value 8, .value 1], + .pure 24 .lt [.value 23, .value 8]], + .branch (.value 24) 1 3⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 1, .value 23], + .effect (some 14) .sload [.value 29]], + .leave [.value 14]⟩] }, + -- @deposit + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 11) .calldatasize [], + .pure 13 .lt [.value 11, .const 36]], + .branch (.value 13) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 15) .calldataload [.const 4], + .effect (some 1) .caller [], + .call (some 2) 0 [.value 1, .value 1, .value 15], + .effect none .mstore [.const 0, .value 15], + .effect none (.log 2) [.const 0, .const 32, .const 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c, .value 1], + .effect none .mstore [.const 0, .value 2], + .assume true .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume true .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .ret (.const 0) (.const 32)⟩] }, + -- @depositFor + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 5) .calldatasize [], + .pure 7 .lt [.value 5, .const 68], + .effect (some 9) .calldataload [.const 4], + .pure 24 .shr [.const 160, .value 9], + .word 27 (.value 7), + .pure 28 .or [.value 24, .value 27], + .ne 21 (.value 28) (.const 0)], + .branch (.value 21) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 22) .calldataload [.const 4], + .effect (some 13) .calldataload [.const 36], + .pure 19 .and [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff], + .call (some 3) 0 [.value 22, .value 22, .value 13], + .effect none .mstore [.const 0, .value 3], + .assume true .gt [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 19, .value 22]], + .ret (.const 0) (.const 32)⟩] }, + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 28 .shr [.const 160, .value 11], + .word 31 (.value 9), + .pure 32 .or [.value 28, .value 31], + .ne 25 (.value 32) (.const 0)], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .pure 24 .and [.value 26, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5], + .assume false .eq [.value 24, .value 26]], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 5 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 5 [(.const 0x2f4f21e2, 2), (.const 0x70a08231, 3), (.const 0xb6b55f25, 4)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Mir3.lean b/Certified/bank/gen/Bank/Mir3.lean new file mode 100644 index 00000000..6f8c95c5 --- /dev/null +++ b/Certified/bank/gen/Bank/Mir3.lean @@ -0,0 +1,224 @@ +-- solar-lean-stage: kind=mir index=3 pass=lower-assumes +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The lowered MIR module after `lower-assumes`. -/ +def mir3 : MIR.Lowered.Module := + { entry := 4, + functions := [ + -- @credit + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 0, .value 0], + .effect none .mstore [.const 32, .const 0], + .effect (some 29) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 29], + .pure 15 .add [.value 5, .value 1], + .pure 16 .lt [.value 15, .value 5], + .pure 32 .gt [.value 0, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 32) 5 6⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.value 29, .value 15], + .effect (some 8) .sload [.const 1], + .pure 23 .add [.value 8, .value 1], + .pure 24 .lt [.value 23, .value 8]], + .branch (.value 24) 1 3⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 1, .value 23], + .effect (some 14) .sload [.value 29]], + .leave [.value 14]⟩, + -- bb4 + ⟨[(34, [(5, .const 0x417000000000000000080000000)]), (35, [(5, .value 0)]), (36, [(5, .const 0xffffffffffffffffffffffffffffffffffffffff)])], + [.effect none .mstore [.const 32, .value 34], + .effect none .mstore [.const 64, .value 35], + .effect none .mstore [.const 96, .value 36], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb5 + ⟨[], + [], + .jump 4⟩, + -- bb6 + ⟨[], + [], + .branch (.value 16) 1 2⟩] }, + -- @deposit + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 11) .calldatasize [], + .pure 13 .lt [.value 11, .const 36]], + .branch (.value 13) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 15) .calldataload [.const 4], + .effect (some 1) .caller [], + .call (some 2) 0 [.value 1, .value 15], + .effect none .mstore [.const 0, .value 15], + .effect none (.log 2) [.const 0, .const 32, .const 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c, .value 1], + .effect none .mstore [.const 0, .value 2], + .pure 21 .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 21) 4 5⟩, + -- bb3 + ⟨[(25, [(4, .const 0x417000000010000000200000000), (6, .const 0x417000000010000000200000000)]), (26, [(4, .value 1), (6, .value 1)]), (27, [(4, .const 0xffffffffffffffffffffffffffffffffffffffff), (6, .const 0xffffffffffffffffffffffffffffffffffffffff)])], + [.effect none .mstore [.const 32, .value 25], + .effect none .mstore [.const 64, .value 26], + .effect none .mstore [.const 96, .value 27], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [.pure 23 .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 23) 6 7⟩, + -- bb6 + ⟨[], + [], + .jump 3⟩, + -- bb7 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩] }, + -- @depositFor + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 5) .calldatasize [], + .pure 7 .lt [.value 5, .const 68], + .effect (some 9) .calldataload [.const 4], + .pure 24 .shr [.const 160, .value 9], + .word 27 (.value 7), + .pure 28 .or [.value 24, .value 27], + .ne 21 (.value 28) (.const 0)], + .branch (.value 21) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 22) .calldataload [.const 4], + .effect (some 13) .calldataload [.const 36], + .pure 19 .and [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff], + .call (some 3) 0 [.value 22, .value 13], + .effect none .mstore [.const 0, .value 3], + .pure 31 .gt [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 31) 4 5⟩, + -- bb3 + ⟨[(35, [(4, .const 0x417000000020000000200000009), (6, .const 0x102000000020000000200000007)]), (36, [(4, .value 22), (6, .value 19)]), (37, [(4, .const 0xffffffffffffffffffffffffffffffffffffffff), (6, .value 22)])], + [.effect none .mstore [.const 32, .value 35], + .effect none .mstore [.const 64, .value 36], + .effect none .mstore [.const 96, .value 37], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [.ne 33 (.value 19) (.value 22)], + .branch (.value 33) 6 7⟩, + -- bb6 + ⟨[], + [], + .jump 3⟩, + -- bb7 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩] }, + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 28 .shr [.const 160, .value 11], + .word 31 (.value 9), + .pure 32 .or [.value 28, .value 31], + .ne 25 (.value 32) (.const 0)], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .pure 24 .and [.value 26, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5], + .ne 35 (.value 24) (.value 26)], + .branch (.value 35) 4 5⟩, + -- bb3 + ⟨[(37, [(4, .const 0x102000000030000000200000009)]), (38, [(4, .value 24)]), (39, [(4, .value 26)])], + [.effect none .mstore [.const 32, .value 37], + .effect none .mstore [.const 64, .value 38], + .effect none .mstore [.const 96, .value 39], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 5 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 5 [(.const 0x2f4f21e2, 2), (.const 0x70a08231, 3), (.const 0xb6b55f25, 4)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Mir4.lean b/Certified/bank/gen/Bank/Mir4.lean new file mode 100644 index 00000000..b1d640e5 --- /dev/null +++ b/Certified/bank/gen/Bank/Mir4.lean @@ -0,0 +1,224 @@ +-- solar-lean-stage: kind=mir index=4 pass=evm-inst-schedule +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The lowered MIR module after `evm-inst-schedule`. -/ +def mir4 : MIR.Lowered.Module := + { entry := 4, + functions := [ + -- @credit + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 0, .value 0], + .effect none .mstore [.const 32, .const 0], + .effect (some 29) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 29], + .pure 15 .add [.value 5, .value 1], + .pure 16 .lt [.value 15, .value 5], + .pure 32 .gt [.value 0, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 32) 5 6⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.value 29, .value 15], + .effect (some 8) .sload [.const 1], + .pure 23 .add [.value 8, .value 1], + .pure 24 .lt [.value 23, .value 8]], + .branch (.value 24) 1 3⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 1, .value 23], + .effect (some 14) .sload [.value 29]], + .leave [.value 14]⟩, + -- bb4 + ⟨[(34, [(5, .const 0x417000000000000000080000000)]), (35, [(5, .value 0)]), (36, [(5, .const 0xffffffffffffffffffffffffffffffffffffffff)])], + [.effect none .mstore [.const 32, .value 34], + .effect none .mstore [.const 64, .value 35], + .effect none .mstore [.const 96, .value 36], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb5 + ⟨[], + [], + .jump 4⟩, + -- bb6 + ⟨[], + [], + .branch (.value 16) 1 2⟩] }, + -- @deposit + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 11) .calldatasize [], + .pure 13 .lt [.value 11, .const 36]], + .branch (.value 13) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 15) .calldataload [.const 4], + .effect (some 1) .caller [], + .call (some 2) 0 [.value 1, .value 15], + .effect none .mstore [.const 0, .value 15], + .effect none (.log 2) [.const 0, .const 32, .const 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c, .value 1], + .effect none .mstore [.const 0, .value 2], + .pure 21 .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 21) 4 5⟩, + -- bb3 + ⟨[(25, [(4, .const 0x417000000010000000200000000), (6, .const 0x417000000010000000200000000)]), (26, [(4, .value 1), (6, .value 1)]), (27, [(4, .const 0xffffffffffffffffffffffffffffffffffffffff), (6, .const 0xffffffffffffffffffffffffffffffffffffffff)])], + [.effect none .mstore [.const 32, .value 25], + .effect none .mstore [.const 64, .value 26], + .effect none .mstore [.const 96, .value 27], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [.pure 23 .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 23) 6 7⟩, + -- bb6 + ⟨[], + [], + .jump 3⟩, + -- bb7 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩] }, + -- @depositFor + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 9) .calldataload [.const 4], + .pure 24 .shr [.const 160, .value 9], + .effect (some 5) .calldatasize [], + .pure 7 .lt [.value 5, .const 68], + .word 27 (.value 7), + .pure 28 .or [.value 24, .value 27], + .ne 21 (.value 28) (.const 0)], + .branch (.value 21) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 22) .calldataload [.const 4], + .effect (some 13) .calldataload [.const 36], + .pure 19 .and [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff], + .call (some 3) 0 [.value 22, .value 13], + .effect none .mstore [.const 0, .value 3], + .pure 31 .gt [.value 22, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 31) 4 5⟩, + -- bb3 + ⟨[(35, [(4, .const 0x417000000020000000200000009), (6, .const 0x102000000020000000200000007)]), (36, [(4, .value 22), (6, .value 19)]), (37, [(4, .const 0xffffffffffffffffffffffffffffffffffffffff), (6, .value 22)])], + [.effect none .mstore [.const 32, .value 35], + .effect none .mstore [.const 64, .value 36], + .effect none .mstore [.const 96, .value 37], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [.ne 33 (.value 19) (.value 22)], + .branch (.value 33) 6 7⟩, + -- bb6 + ⟨[], + [], + .jump 3⟩, + -- bb7 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩] }, + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 11) .calldataload [.const 4], + .pure 28 .shr [.const 160, .value 11], + .effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .word 31 (.value 9), + .pure 32 .or [.value 28, .value 31], + .ne 25 (.value 32) (.const 0)], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .pure 24 .and [.value 26, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5], + .ne 35 (.value 24) (.value 26)], + .branch (.value 35) 4 5⟩, + -- bb3 + ⟨[(37, [(4, .const 0x102000000030000000200000009)]), (38, [(4, .value 24)]), (39, [(4, .value 26)])], + [.effect none .mstore [.const 32, .value 37], + .effect none .mstore [.const 64, .value 38], + .effect none .mstore [.const 96, .value 39], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 5 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 5 [(.const 0x2f4f21e2, 2), (.const 0x70a08231, 3), (.const 0xb6b55f25, 4)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Sched.lean b/Certified/bank/gen/Bank/Sched.lean new file mode 100644 index 00000000..1133f424 --- /dev/null +++ b/Certified/bank/gen/Bank/Sched.lean @@ -0,0 +1,321 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 5, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2f4f21e2)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb6b55f25)), + .op (.stack .eq), + .jumpi 2, + .jump 5], + -- bb2 + [.jump 6], + -- bb3 + [.jump 24], + -- bb4 + [.jump 15], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 14, + .jump 7], + -- bb7 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .effect .caller 0, + .pushLabel 8, + .jump 30], + -- bb8 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .effect .caller 0, + .op (.stack (.push 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 2) 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 12, + .jump 9], + -- bb9 + [.op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 11, + .jump 10], + -- bb10 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 0x417000000010000000200000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 13], + -- bb12 + [.op (.stack (.push 0x417000000010000000200000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 13], + -- bb13 + [.op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 23, + .jump 16], + -- bb16 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .pushLabel 17, + .jump 30], + -- bb17 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 21, + .jump 18], + -- bb18 + [.op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 20, + .jump 19], + -- bb19 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb20 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 22], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.push 0x417000000020000000200000009)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 22], + -- bb22 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb23 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb24 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 29, + .jump 25], + -- bb25 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 27, + .jump 26], + -- bb26 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb27 + [.op (.stack (.push 0x102000000030000000200000009)), + .jump 28], + -- bb28 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb29 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb30 + [.op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 4)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 5)), + .op (.stack .gt), + .jumpi 35, + .jump 31], + -- bb31 + [.jumpi 34, + .jump 32], + -- bb32 + [.op (.stack (.dup 1)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.swap 3)), + .op (.stack (.dup 4)), + .op (.stack .lt), + .jumpi 34, + .jump 33], + -- bb33 + [.op (.stack (.swap 2)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 1)), + .effect .sload 1, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb34 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb35 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0x417000000000000000080000000)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 36], + -- bb36 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/Schedule.json b/Certified/bank/gen/Bank/Schedule.json new file mode 100644 index 00000000..9c002f43 --- /dev/null +++ b/Certified/bank/gen/Bank/Schedule.json @@ -0,0 +1,56 @@ +{ + "functions": [ + {"function": 4, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [4, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [3, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 5, "start": [5, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 1, "entry": 6, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [6, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [14, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [7, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [13, 0], "layout": ["v25", "v26", "v27"], "floating": true, "continues": null}, + {"block": 4, "start": [12, 0], "layout": [], "floating": true, "continues": null}, + {"block": 5, "start": [9, 0], "layout": [], "floating": true, "continues": null}, + {"block": 6, "start": [11, 0], "layout": [], "floating": true, "continues": null}, + {"block": 7, "start": [10, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + {"block": 2, "return": 8, "below": ["v15"]} + ]}, + {"function": 2, "entry": 15, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [15, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [23, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [16, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [22, 0], "layout": ["v37", "v36", "v35"], "floating": true, "continues": null}, + {"block": 4, "start": [21, 0], "layout": ["v22", "junk"], "floating": true, "continues": null}, + {"block": 5, "start": [18, 0], "layout": ["v22", "v19"], "floating": true, "continues": null}, + {"block": 6, "start": [20, 0], "layout": ["v22", "v19"], "floating": true, "continues": null}, + {"block": 7, "start": [19, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + {"block": 2, "return": 17, "below": ["v22", "v19"]} + ]}, + {"function": 3, "entry": 24, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [24, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [29, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [25, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [28, 0], "layout": ["v39", "v38", "v37"], "floating": true, "continues": null}, + {"block": 4, "start": [27, 0], "layout": ["v26", "v24"], "floating": true, "continues": null}, + {"block": 5, "start": [26, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 0, "entry": 30, "returns": true, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [30, 0], "layout": ["v1", "v0", "ret"], "floating": false, "continues": null}, + {"block": 1, "start": [34, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [32, 0], "layout": ["v1", "junk", "ret", "v29", "v15"], "floating": false, "continues": null}, + {"block": 3, "start": [33, 0], "layout": ["v23", "junk", "ret", "v29"], "floating": false, "continues": null}, + {"block": 4, "start": [36, 0], "layout": ["v35", "v34", "v36"], "floating": true, "continues": null}, + {"block": 5, "start": [35, 0], "layout": ["v0", "junk", "junk", "junk", "junk"], "floating": true, "continues": null}, + {"block": 6, "start": [31, 0], "layout": ["v1", "junk", "ret", "v29", "v15", "v16"], "floating": false, "continues": null} + ], "calls": [ + ]} + ] +} diff --git a/Certified/bank/gen/Bank/Stage0.lean b/Certified/bank/gen/Bank/Stage0.lean new file mode 100644 index 00000000..1cb02230 --- /dev/null +++ b/Certified/bank/gen/Bank/Stage0.lean @@ -0,0 +1,144 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Bank`; do not edit. -/ + +namespace SolarTV.Export.Bank + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 4, + functions := [ + -- @credit + { params := [0, 30, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 0, .value 0], + .effect none .mstore [.const 32, .const 0], + .effect (some 29) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 29], + .pure 15 .add [.value 5, .value 1], + .pure 16 .lt [.value 15, .value 5], + .assume true .gt [.value 30, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 16) 1 2⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.value 29, .value 15], + .effect (some 8) .sload [.const 1], + .pure 23 .add [.value 8, .value 1], + .pure 24 .lt [.value 23, .value 8]], + .branch (.value 24) 1 3⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 1, .value 23], + .effect (some 14) .sload [.value 29]], + .leave [.value 14]⟩] }, + -- @deposit + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 11) .calldatasize [], + .pure 13 .lt [.value 11, .const 36]], + .branch (.value 13) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 15) .calldataload [.const 4], + .effect (some 1) .caller [], + .call (some 2) 0 [.value 1, .value 1, .value 15], + .effect none .mstore [.const 0, .value 15], + .effect none (.log 2) [.const 0, .const 32, .const 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c, .value 1], + .effect none .mstore [.const 0, .value 2], + .assume true .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume true .gt [.value 1, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .ret (.const 0) (.const 32)⟩] }, + -- @depositFor + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 5) .calldatasize [], + .pure 7 .lt [.value 5, .const 68], + .effect (some 9) .calldataload [.const 4], + .pure 11 .gt [.value 9, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 21 .or [.value 7, .value 11]], + .branch (.value 21) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 13) .calldataload [.const 36], + .pure 19 .and [.value 9, .const 0xffffffffffffffffffffffffffffffffffffffff], + .call (some 3) 0 [.value 9, .value 9, .value 13], + .effect none .mstore [.const 0, .value 3], + .assume true .gt [.value 9, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 19, .value 9]], + .ret (.const 0) (.const 32)⟩] }, + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 13 .gt [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 25 .or [.value 9, .value 13]], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.pure 24 .and [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 11], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5], + .assume false .eq [.value 24, .value 11]], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 5 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 5 [(.const 0x2f4f21e2, 2), (.const 0x70a08231, 3), (.const 0xb6b55f25, 4)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Bank diff --git a/Certified/bank/gen/Bank/manifest.json b/Certified/bank/gen/Bank/manifest.json new file mode 100644 index 00000000..9c8c0e75 --- /dev/null +++ b/Certified/bank/gen/Bank/manifest.json @@ -0,0 +1,169 @@ +{ + "arguments": [ + "Certified/bank/bank.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/bank/gen" + ], + "bytecode": "346028575f3560e01c80632f4f21e21460f857806370a0823114610161578063b6b55f2514603e575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243610602857600435803360875b815f525f60205260405f2080548481019081105f1960601c85116101a657602c578155600154938401938410602c57926001559154905090565b905f52337fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c60205fa25f525f1960601c331160cb575f1960601c331160cb5760205ff35b690417000000010000000260201b335f1960601c915b6020525b60405260605263ed572b275f526064601cfd5b60043560a01c60443610176028576004355f1960601c81166024358261011b604d565b5f525f1960601c8211610147578181036101345760205ff35b6d010200000002000000020000000760e1565b505f1960601c906d041700000002000000020000000960e1565b60043560a01c60243610176028576004355f1960601c8116815f525f60205260405f20545f528181036101935760205ff35b6d010200000003000000020000000960e1565b505050505f1960601c6d04170000000000000000800000006020529060e556", + "bytecode_sha256": "bff0578068ce4ab4a041f226e4e960c13d358c8b430718fefe9ce3a22d760543", + "compiler": "0.8.38+commit.52e2060e.solar.0.3.0-dev", + "contract": "Bank", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"Certified/bank/bank.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/bank/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/bank/gen\"), keep_asts: false, forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "Certified/bank/bank.sol", + "sha256": "2a29919999674ac221097e3f50ed43bcddf094d19a08da5f5c9704a0dd099d03" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "7d145b2998661cb5c4592a5374f9cc79d94794bba2f6f17b3dfdd0e2a87e0fcc" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "place-reads", + "sha256": "fc18b9f9f61ef53c23dcf6f6799dee7c57a15ca47bb4da2255c633f82b1308ab" + }, + { + "definition": "mir2", + "file": "Mir2.lean", + "index": 2, + "kind": "mir", + "pass": "spell-width-tests", + "sha256": "706bb5ac9ec0a0d67f08496e91c62af4ae17405eb912f83decf45e9a8292b2c0" + }, + { + "definition": "mir3", + "file": "Mir3.lean", + "index": 3, + "kind": "mir", + "pass": "lower-assumes", + "sha256": "aedcd4a2b80c765f6e037a756d6db7b1fab1a2447bdf0ca62eda37ae64185e34" + }, + { + "definition": "mir4", + "file": "Mir4.lean", + "index": 4, + "kind": "mir", + "pass": "evm-inst-schedule", + "sha256": "6f68722b113a0f8f2cda66280547c0601f97b443d416806a6803322a38ae51b9" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "7867a2d8d7a8605c655c1bc038b5cee9a7e714d6c152c9e267afc6dcfd8f9586" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "peephole-early", + "sha256": "92adb3e54ee739c60d8e69961ba9619245df9ae42f1dca9df06fa352fd35f652" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "357042975eaf869a3c7f3a65ee4fc68bf6ef1cbb39d2c129c7aa730ac4ce95c7" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "compact-pushes", + "sha256": "95b583b99ae08080b2753dc74b9a3d0f0921e23147a0419959612ea9afb91025" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "block-layout", + "sha256": "5c18eab01a900c5e39d0cac1415ad8339a52ba78c43649f4e3fbfb8cb380e6e1" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "6ebad5531b56a0b055f247364e211b2ed1882f40858c9d75ce5b15ffcd5d9ea2" + }, + { + "definition": "evm6", + "file": "Evm6.lean", + "index": 6, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "5f9a29c13202ce893fa142487c112f530321e5ac8041c28597d23504b278b7f8" + }, + { + "definition": "evm7", + "file": "Evm7.lean", + "index": 7, + "kind": "evm", + "pass": "tail-merge", + "sha256": "baa56a2fc6e55d128e88f34ce5e6bcfdf7e4cbb78a0a907bf7ddcea3a8502bfa" + }, + { + "definition": "evm8", + "file": "Evm8.lean", + "index": 8, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "b954ed58f56daec2d604a03ac02aa0ef3e543767b4a5d0bb13f68ea7f74fead6" + }, + { + "definition": "evm9", + "file": "Evm9.lean", + "index": 9, + "kind": "evm", + "pass": "reorder-pushes", + "sha256": "43597405f5bd81147174381637469732e796aa4056f192d37311c7b21f95b65c" + }, + { + "definition": "evm10", + "file": "Evm10.lean", + "index": 10, + "kind": "evm", + "pass": "block-layout", + "sha256": "0153e265384d5fa0bb56bbcddac12cb7724b905dafbd698d03461bba22095730" + }, + { + "definition": "evm11", + "file": "Evm11.lean", + "index": 11, + "kind": "evm", + "pass": "stack-reschedule", + "sha256": "d55f0c281937953166c7fe2d2176bcb62145f1e1a597546d95ae4e3d903329aa" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "48ec986cf2d82ee746b044677549cc626376293bd6701e44e04d9b1e8e93bd8a" + } + ] +} diff --git a/Certified/bank/options b/Certified/bank/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/bank/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/bank/record.json b/Certified/bank/record.json new file mode 100644 index 00000000..64040b55 --- /dev/null +++ b/Certified/bank/record.json @@ -0,0 +1,89 @@ +{ + "contract": "Bank", + "name": "bank", + "source": "Certified/bank/bank.sol", + "bytecode": "346028575f3560e01c80632f4f21e21460f857806370a0823114610161578063b6b55f2514603e575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243610602857600435803360875b815f525f60205260405f2080548481019081105f1960601c85116101a657602c578155600154938401938410602c57926001559154905090565b905f52337fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c60205fa25f525f1960601c331160cb575f1960601c331160cb5760205ff35b690417000000010000000260201b335f1960601c915b6020525b60405260605263ed572b275f526064601cfd5b60043560a01c60443610176028576004355f1960601c81166024358261011b604d565b5f525f1960601c8211610147578181036101345760205ff35b6d010200000002000000020000000760e1565b505f1960601c906d041700000002000000020000000960e1565b60043560a01c60243610176028576004355f1960601c8116815f525f60205260405f20545f528181036101935760205ff35b6d010200000003000000020000000960e1565b505050505f1960601c6d04170000000000000000800000006020529060e556", + "solar": "cb5053ab39adfd59820913b336d346389ce1b8d9", + "solidity_lean": "11fb9334142fbb8ded0b1d699015a978cdc3ed52", + "mir_to_evmir": "proved: SolarTV.Milestone.Bank.bank_mir_to_evmir", + "assembly": "decoded only: bank.Proofs.Assembly (the bytecode decodes to the final EVM IR's instructions; no execution theorem)", + "vc": "exported to .lake/certify/bank/VC.lean", + "end_to_end": "not proved", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, a field of Shapes.Compiled)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with any status (no specification declares the allowed ones); the bytecode too, at gas from the bound on", + "spec": "none: solar-verify has no specification of bank", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result", + "assumptions": "none beyond the statement's scope", + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: deposit(uint256), depositFor(address,uint256) and balanceOf(address) ABI-encoded with clean argument words, any value below 2^256 (no function is payable: the value reverts on both sides), any storage; other call data is outside the statement", + "spec: none (solar-verify has no specification of bank): equivalence, termination and resources only" + ], + "strongest": false + }, + "final": { + "module": "bank.Final", + "theorem": "Certified.bank.Final.final", + "kind": "compiled", + "statement": "code.data.toList.map (·.toNat) = runtimeBytes ∧ (∃ c, SolidCore.Refinement.Solar.Bank.contract? = .ok c ∧ Shapes.Compiled (solidCore (SolidCore.Refinement.Solar.Bank.fuel)) c code (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.Bank.fns) ([])) (fun _ => 155937612))", + "assumptions": [], + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: deposit(uint256), depositFor(address,uint256) and balanceOf(address) ABI-encoded with clean argument words, any value below 2^256 (no function is payable: the value reverts on both sides), any storage; other call data is outside the statement", + "spec: none (solar-verify has no specification of bank): equivalence, termination and resources only" + ], + "spec": "none: solar-verify has no specification of bank", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, a field of Shapes.Compiled)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with any status (no specification declares the allowed ones); the bytecode too, at gas from the bound on", + "spec": "none: solar-verify has no specification of bank", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result" + } + }, + "end_to_end_statement": {}, + "binding": {}, + "hypotheses": {}, + "refused": [], + "vacuous": "not checked", + "assembly_statement": null, + "assembly_hypotheses": null, + "negative_tests": false, + "caveats": [ + "solidity-lean at 11fb9334142fbb8ded0b1d699015a978cdc3ed52, not the pinned 95ebfd5f178b93b42d498a124104fc92bfc6b74f", + "solar cb5053ab39adfd59820913b336d346389ce1b8d9, not built from this checkout's compiler sources", + "assembly decoded, not executed", + "not end to end: solidity-lean states no source or spec theorem for bank", + "negative tests skipped" + ], + "backend": { + "theorem": { + "module": "bank.Final", + "theorem": "Certified.bank.Final.final", + "kind": "compiled", + "statement": "code.data.toList.map (·.toNat) = runtimeBytes ∧ (∃ c, SolidCore.Refinement.Solar.Bank.contract? = .ok c ∧ Shapes.Compiled (solidCore (SolidCore.Refinement.Solar.Bank.fuel)) c code (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.Bank.fns) ([])) (fun _ => 155937612))", + "assumptions": [], + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: deposit(uint256), depositFor(address,uint256) and balanceOf(address) ABI-encoded with clean argument words, any value below 2^256 (no function is payable: the value reverts on both sides), any storage; other call data is outside the statement", + "spec: none (solar-verify has no specification of bank): equivalence, termination and resources only" + ], + "spec": "none: solar-verify has no specification of bank", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, a field of Shapes.Compiled)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with any status (no specification declares the allowed ones); the bytecode too, at gas from the bound on", + "spec": "none: solar-verify has no specification of bank", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result" + } + } + } +} diff --git a/Certified/bank/shape.json b/Certified/bank/shape.json new file mode 100644 index 00000000..3948890e --- /dev/null +++ b/Certified/bank/shape.json @@ -0,0 +1,55 @@ +{ + "kind": "certified", + "contract": "SolidCore.Refinement.Solar.Bank.contract?", + "fuel": "SolidCore.Refinement.Solar.Bank.fuel", + "valid": "SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.Bank.fns) ([])", + "allowed_export": true, + "spec_export": { + "ctx": "SolidCore.Refinement.Shapes.ctxOfCall", + "step": "SolidCore.Refinement.Shapes.idStep" + }, + "nonvacuous": "Certified.bank.Shape.nonvacuous", + "gas": "fun _ => 155937612", + "env": [ + "SolidCore.Spec.MapSlotsSeparated [0]" + ], + "spec": "solar-verify's export of bank.sol in this run (Certified.bank.gen.Bank.Spec.Bank): deposit and depositFor add the amount to the balance and the total, return the new balance and leave every other balance, and succeed-if msg.value == 0 and neither sum overflows; balanceOf returns the balance and changes nothing, and succeeds-if msg.value == 0. The postcondition (bundlePost) and the allowed statuses (bundleAllowed) are both read off that export", + "spec_modules": [ + "SolidCore.Refinement.Solar.Bank.Lowering", + "Verify.ShapeGeneric", + "Verify.Spec.TreeMap", + "Verify.ShapeSpecExport" + ], + "proof_module": "bank.Shape", + "proof": "Certified.bank.Shape.published", + "generic": { + "lowering": "SolidCore.Refinement.Solar.Bank.Lowering", + "ns": "SolidCore.Refinement.Solar.Bank", + "style": "core", + "check": "check_stage0", + "check_value": "checkValue_stage0", + "fns": "SolidCore.Refinement.Solar.Bank.fns", + "storage": "[]", + "spec_connect": { + "witness": "deposit", + "ghost_fixed": true, + "using": [ + "SolidCore.Refinement.Solar.Bank.digest_eq" + ] + } + }, + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: deposit(uint256), depositFor(address,uint256) and balanceOf(address) ABI-encoded with clean argument words, any value below 2^256 (no function is payable: the value reverts on both sides), any storage; other call data is outside the statement", + "spec: solar-verify's exported spec of deposit, depositFor and balanceOf, with their succeeds-if conditions; the Deposit event is not in the spec language, and is covered by equivalence (the bytecode's log is SolidCore's)", + "assumption SolidCore.Spec.MapSlotsSeparated [0] (keccak256 as an uninterpreted function: injective on the preimages of balances[a], with images at least 2^128, apart from the scalar slots), a named premise of the statement, not proved; it stands in for the KeccakModel premise" + ], + "source_ast": { + "file": "SolidCore/Refinement/Source/Bank.lean", + "namespace": "SolidCore.Refinement.Source.Bank", + "contract": "Bank" + } +} diff --git a/Certified/c4/Proofs.lean b/Certified/c4/Proofs.lean new file mode 100644 index 00000000..0166581d --- /dev/null +++ b/Certified/c4/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import c4.Proofs.Stages +import c4.Proofs.Assembly diff --git a/Certified/c4/Proofs/Assembly.lean b/Certified/c4/Proofs/Assembly.lean new file mode 100644 index 00000000..ea4bf3e7 --- /dev/null +++ b/Certified/c4/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Items +import c4.gen.Main.Evm5 +import c4.gen.Main.Bytecode + +/-! The final EVM IR of `Main` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.C4 + +open SolarTV.Assembly SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm5).getD [] + +theorem items_eq : itemsOf evm5 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x55 else if label = 2 then 0x59 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.C4.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.C4.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms decodes + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Evm1.lean b/Certified/c4/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..cc48770f --- /dev/null +++ b/Certified/c4/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Evm1 +import c4.gen.Main.Sched + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 9 = EVM.Program.run o evm1 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Evm2.lean b/Certified/c4/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..4d360647 --- /dev/null +++ b/Certified/c4/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Evm2 +import c4.gen.Main.Evm1 + +/-! `compact-pushes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 5 = EVM.Program.run o evm2 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Evm3.lean b/Certified/c4/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..9c3c08a1 --- /dev/null +++ b/Certified/c4/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Evm3 +import c4.gen.Main.Evm2 + +/-! `share-reverts`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 5 = EVM.Program.run o evm3 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Evm4.lean b/Certified/c4/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..b56776e1 --- /dev/null +++ b/Certified/c4/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Evm4 +import c4.gen.Main.Evm3 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 5 = EVM.Program.run o evm4 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Evm5.lean b/Certified/c4/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..0043a221 --- /dev/null +++ b/Certified/c4/Proofs/Runs/Evm5.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Evm5 +import c4.gen.Main.Evm4 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 5 = EVM.Program.run o evm5 call 3 := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Mir1.lean b/Certified/c4/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..b3d9d612 --- /dev/null +++ b/Certified/c4/Proofs/Runs/Mir1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Mir1 +import c4.gen.Main.Stage0 + +/-! `place-reads`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir1_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 9 = MIR.Lowered.Module.run o mir1 call 9 := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.mir1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_run + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Mir2.lean b/Certified/c4/Proofs/Runs/Mir2.lean new file mode 100644 index 00000000..ec549d08 --- /dev/null +++ b/Certified/c4/Proofs/Runs/Mir2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Mir2 +import c4.gen.Main.Mir1 + +/-! `evm-inst-schedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir2_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir1 call 9 = MIR.Lowered.Module.run o mir2 call 9 := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.mir2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir2_run + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Sched.lean b/Certified/c4/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..8ecd9cbe --- /dev/null +++ b/Certified/c4/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Sched +import c4.gen.Main.Mir2 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir2 call 9 = EVM.Program.run o sched call 9 := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Runs/Stage0.lean b/Certified/c4/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..9aac8097 --- /dev/null +++ b/Certified/c4/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import c4.gen.Main.Stage0 + +/-! The first lowered MIR ends on every call within 9 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 9).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.C4.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/Proofs/Stages.lean b/Certified/c4/Proofs/Stages.lean new file mode 100644 index 00000000..7018150a --- /dev/null +++ b/Certified/c4/Proofs/Stages.lean @@ -0,0 +1,147 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import c4.Proofs.Runs.Stage0 +import c4.Proofs.Runs.Mir1 +import c4.Proofs.Runs.Mir2 +import c4.Proofs.Runs.Sched +import c4.Proofs.Runs.Evm1 +import c4.Proofs.Runs.Evm2 +import c4.Proofs.Runs.Evm3 +import c4.Proofs.Runs.Evm4 +import c4.Proofs.Runs.Evm5 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Main`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm5`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.C4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +/-- `place-reads`: stage0 to mir1. -/ +theorem stage_mir1 (o : Oracle) : Stage (mirSem o) (mirSem o) stage0 mir1 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 9 9 (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +theorem mir1_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir1 call 9).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := stage0) (q := mir1) (n := 9) (m := 9) (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +/-- `evm-inst-schedule`: mir1 to mir2. -/ +theorem stage_mir2 (o : Oracle) : Stage (mirSem o) (mirSem o) mir1 mir2 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 9 9 (mir1_ends o) + (fun call _ => mir2_run o call) + +theorem mir2_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir2 call 9).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir1) (q := mir2) (n := 9) (m := 9) (mir1_ends o) + (fun call _ => mir2_run o call) + +/-- `stack-schedule`: mir2 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) mir2 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 9 9 (mir2_ends o) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 9).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := mir2) (q := sched) (n := 9) (m := 9) (mir2_ends o) + (fun call _ => sched_run o call) + +/-- `cfg-simplify-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 9 5 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 9) (m := 5) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `compact-pushes`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 5) (m := 5) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `share-reverts`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 5) (m := 5) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `terminal-dedup`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 5) (m := 5) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `cfg-simplify-early`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 3 (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1, mir2], sched, [evm1, evm2, evm3, evm4, evm5]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem c4_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm5 anyCall := + mir_to_evmir o anyCall compilation ⟨stage_mir1 o, stage_mir2 o, trivial⟩ (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.C4.stage_mir1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir1 + +/-- info: 'SolarTV.Milestone.C4.stage_mir2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir2 + +/-- info: 'SolarTV.Milestone.C4.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.C4.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.C4.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.C4.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.C4.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.C4.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.C4.c4_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms c4_mir_to_evmir + +end SolarTV.Milestone.C4 diff --git a/Certified/c4/bytecode.hex b/Certified/c4/bytecode.hex new file mode 100644 index 00000000..fc159c91 --- /dev/null +++ b/Certified/c4/bytecode.hex @@ -0,0 +1 @@ +346055575f3560e01c806302067e6a036055576024361060ff60043511176055576004355f5460ff8116820160ff81116059579060ff1916179081601e1a1860081b9061ff00191617805f5560ff165f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd diff --git a/Certified/c4/c4.sol b/Certified/c4/c4.sol new file mode 100644 index 00000000..44d5fc4f --- /dev/null +++ b/Certified/c4/c4.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { uint8 v; uint8 w = 7; function add(uint8 x) external returns (uint8) { v += x; w ^= x; return v; } } diff --git a/Certified/c4/gen/Main/Bytecode.lean b/Certified/c4/gen/Main/Bytecode.lean new file mode 100644 index 00000000..a05abfcf --- /dev/null +++ b/Certified/c4/gen/Main/Bytecode.lean @@ -0,0 +1,20 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x55, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x02, 0x06, 0x7e, 0x6a, 0x03, + 0x60, 0x55, 0x57, 0x60, 0x24, 0x36, 0x10, 0x60, 0xff, 0x60, 0x04, 0x35, 0x11, 0x17, 0x60, 0x55, + 0x57, 0x60, 0x04, 0x35, 0x5f, 0x54, 0x60, 0xff, 0x81, 0x16, 0x82, 0x01, 0x60, 0xff, 0x81, 0x11, + 0x60, 0x59, 0x57, 0x90, 0x60, 0xff, 0x19, 0x16, 0x17, 0x90, 0x81, 0x60, 0x1e, 0x1a, 0x18, 0x60, + 0x08, 0x1b, 0x90, 0x61, 0xff, 0x00, 0x19, 0x16, 0x17, 0x80, 0x5f, 0x55, 0x60, 0xff, 0x16, 0x5f, + 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, + 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, 0x60, 0x1c, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "346055575f3560e01c806302067e6a036055576024361060ff60043511176055576004355f5460ff8116820160ff81116059579060ff1916179081601e1a1860081b9061ff00191617805f5560ff165f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd" + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Evm1.lean b/Certified/c4/gen/Main/Evm1.lean new file mode 100644 index 00000000..cd1ead6a --- /dev/null +++ b/Certified/c4/gen/Main/Evm1.lean @@ -0,0 +1,90 @@ +-- solar-lean-stage: kind=evm index=1 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2067e6a)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .jumpi 3, + .op (.stack (.swap 0)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00)), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack (.push 30)), + .op (.stack .byte), + .op (.stack .xor), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack (.swap 0)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff)), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Evm2.lean b/Certified/c4/gen/Main/Evm2.lean new file mode 100644 index 00000000..ba01cae0 --- /dev/null +++ b/Certified/c4/gen/Main/Evm2.lean @@ -0,0 +1,92 @@ +-- solar-lean-stage: kind=evm index=2 pass=compact-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `compact-pushes`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2067e6a)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .jumpi 3, + .op (.stack (.swap 0)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack (.push 30)), + .op (.stack .byte), + .op (.stack .xor), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack (.swap 0)), + .op (.stack (.push 65280)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Evm3.lean b/Certified/c4/gen/Main/Evm3.lean new file mode 100644 index 00000000..f46f65c5 --- /dev/null +++ b/Certified/c4/gen/Main/Evm3.lean @@ -0,0 +1,92 @@ +-- solar-lean-stage: kind=evm index=3 pass=share-reverts +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `share-reverts`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2067e6a)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .jumpi 3, + .op (.stack (.swap 0)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack (.push 30)), + .op (.stack .byte), + .op (.stack .xor), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack (.swap 0)), + .op (.stack (.push 65280)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Evm4.lean b/Certified/c4/gen/Main/Evm4.lean new file mode 100644 index 00000000..3254f449 --- /dev/null +++ b/Certified/c4/gen/Main/Evm4.lean @@ -0,0 +1,90 @@ +-- solar-lean-stage: kind=evm index=4 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2067e6a)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .jumpi 3, + .op (.stack (.swap 0)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack (.push 30)), + .op (.stack .byte), + .op (.stack .xor), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack (.swap 0)), + .op (.stack (.push 65280)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.jump 1]] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Evm5.lean b/Certified/c4/gen/Main/Evm5.lean new file mode 100644 index 00000000..d2dab63e --- /dev/null +++ b/Certified/c4/gen/Main/Evm5.lean @@ -0,0 +1,86 @@ +-- solar-lean-stage: kind=evm index=5 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2067e6a)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .jumpi 2, + .op (.stack (.swap 0)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack (.push 30)), + .op (.stack .byte), + .op (.stack .xor), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack (.swap 0)), + .op (.stack (.push 65280)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Manifest.lean b/Certified/c4/gen/Main/Manifest.lean new file mode 100644 index 00000000..04b0d50c --- /dev/null +++ b/Certified/c4/gen/Main/Manifest.lean @@ -0,0 +1,42 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Main.Manifest + +def sources : List (String × String) := + [("Certified/c4/c4.sol", "31c39cd4e9c5cba0f78aff3a986d69be40c5f68cdb36fbf05ad3d0a5e950e858")] + +def compiler : String := "0.8.38+commit.cb5053ab.solar.0.3.0-dev" + +def arguments : List String := + ["Certified/c4/c4.sol", + "-Zcheck-analyses=false", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/c4/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "fc9bd372cfa93042b6948b6b52ce83f8c868b0832c2cd076bdd4bf4c481b521a"), + ("Mir1", "mir1", "place-reads", "0e5c81b03404896a8f12b5e1df4636f4922bc80cef6e06f297fa024a3965ecb9"), + ("Mir2", "mir2", "evm-inst-schedule", "b50596a2f7dc4831a1789f42dd5d0502e13b266ca9e5f7567e1292c450b94af4"), + ("Sched", "sched", "stack-schedule", "fdf061032cfc51bfca74d7977cb5944bdb0af4147d7048cb86e77fa7d4742160"), + ("Evm1", "evm1", "cfg-simplify-early", "b10980301296d4887ba4322567653012d670c2a5441dcba1f4044ffb40d1d1d8"), + ("Evm2", "evm2", "compact-pushes", "512034f050a4fe708788f1c7e7db6c570432aedfd9fdd308c3a993849ba8c28c"), + ("Evm3", "evm3", "share-reverts", "955fa46e2c6701e3644da10a0129e72c06cdf0624a7bd4fa4f7faae7f71be222"), + ("Evm4", "evm4", "terminal-dedup", "4009d1232a8b5bc57afbbe5ac64c2fde908da9b958d007f9f9759078bdf9093b"), + ("Evm5", "evm5", "cfg-simplify-early", "1309fae9f4a8d9561fe138c69b13b7c6e57a71404ed92f861c9a7370738fc7bc"), + ("Bytecode", "bytecode", "assemble", "7d5d01d3952b98c24d030dfd189808f507cdd5e523b997b80aa4baff836df2af")] + +def bytecodeHex : String := + "346055575f3560e01c806302067e6a036055576024361060ff60043511176055576004355f5460ff8116820160ff81116059579060ff1916179081601e1a1860081b9061ff00191617805f5560ff165f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd" + +def bytecodeSha256 : String := "8a21bc207d9dd8be48d921a717eda3ecb7e5bfcb5397850bc3d64a29037fac47" + +end SolarTV.Export.Main.Manifest diff --git a/Certified/c4/gen/Main/Mir1.lean b/Certified/c4/gen/Main/Mir1.lean new file mode 100644 index 00000000..0c3e9059 --- /dev/null +++ b/Certified/c4/gen/Main/Mir1.lean @@ -0,0 +1,77 @@ +-- solar-lean-stage: kind=mir index=1 pass=place-reads +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The lowered MIR module after `place-reads`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 2, + functions := [ + -- @add + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 45) .calldatasize [], + .pure 47 .lt [.value 45, .const 36], + .effect (some 49) .calldataload [.const 4], + .pure 51 .gt [.value 49, .const 255], + .pure 71 .or [.value 47, .value 51]], + .branch (.value 71) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00], + .pure 11 .or [.value 8, .value 34], + .pure 60 .byte [.const 30, .value 11], + .pure 61 .xor [.value 60, .value 72], + .pure 23 .and [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff], + .pure 26 .shl [.const 8, .value 61], + .pure 27 .or [.value 23, .value 26], + .effect none .sstore [.const 0, .value 27], + .pure 65 .and [.value 27, .const 255], + .effect none .mstore [.const 0, .value 65]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 72) .calldataload [.const 4], + .effect (some 2) .sload [.const 0], + .pure 69 .and [.value 2, .const 255], + .pure 34 .add [.value 69, .value 72], + .pure 36 .gt [.value 34, .const 255]], + .branch (.value 36) 1 2⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x2067e6a, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Mir2.lean b/Certified/c4/gen/Main/Mir2.lean new file mode 100644 index 00000000..47615e5f --- /dev/null +++ b/Certified/c4/gen/Main/Mir2.lean @@ -0,0 +1,77 @@ +-- solar-lean-stage: kind=mir index=2 pass=evm-inst-schedule +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The lowered MIR module after `evm-inst-schedule`. -/ +def mir2 : MIR.Lowered.Module := + { entry := 2, + functions := [ + -- @add + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 45) .calldatasize [], + .pure 47 .lt [.value 45, .const 36], + .effect (some 49) .calldataload [.const 4], + .pure 51 .gt [.value 49, .const 255], + .pure 71 .or [.value 47, .value 51]], + .branch (.value 71) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00], + .pure 11 .or [.value 8, .value 34], + .pure 60 .byte [.const 30, .value 11], + .pure 61 .xor [.value 60, .value 72], + .pure 26 .shl [.const 8, .value 61], + .pure 23 .and [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff], + .pure 27 .or [.value 23, .value 26], + .effect none .sstore [.const 0, .value 27], + .pure 65 .and [.value 27, .const 255], + .effect none .mstore [.const 0, .value 65]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 72) .calldataload [.const 4], + .effect (some 2) .sload [.const 0], + .pure 69 .and [.value 2, .const 255], + .pure 34 .add [.value 69, .value 72], + .pure 36 .gt [.value 34, .const 255]], + .branch (.value 36) 1 2⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x2067e6a, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Sched.lean b/Certified/c4/gen/Main/Sched.lean new file mode 100644 index 00000000..0d041c9a --- /dev/null +++ b/Certified/c4/gen/Main/Sched.lean @@ -0,0 +1,98 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 3, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x2067e6a)), + .op (.stack .eq), + .jumpi 2, + .jump 3], + -- bb2 + [.jump 4], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 8, + .jump 5], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .jumpi 7, + .jump 6], + -- bb6 + [.op (.stack (.swap 0)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00)), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack (.push 30)), + .op (.stack .byte), + .op (.stack .xor), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack (.swap 0)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff)), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.push 255)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/Schedule.json b/Certified/c4/gen/Main/Schedule.json new file mode 100644 index 00000000..e2c8750e --- /dev/null +++ b/Certified/c4/gen/Main/Schedule.json @@ -0,0 +1,19 @@ +{ + "functions": [ + {"function": 2, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [3, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 0, "entry": 4, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [4, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [7, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [6, 0], "layout": ["v72", "v2", "v34"], "floating": true, "continues": null}, + {"block": 3, "start": [8, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [5, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]} + ] +} diff --git a/Certified/c4/gen/Main/Stage0.lean b/Certified/c4/gen/Main/Stage0.lean new file mode 100644 index 00000000..e758272d --- /dev/null +++ b/Certified/c4/gen/Main/Stage0.lean @@ -0,0 +1,76 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 2, + functions := [ + -- @add + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 45) .calldatasize [], + .pure 47 .lt [.value 45, .const 36], + .effect (some 49) .calldataload [.const 4], + .pure 51 .gt [.value 49, .const 255], + .pure 71 .or [.value 47, .value 51]], + .branch (.value 71) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00], + .pure 11 .or [.value 8, .value 34], + .pure 60 .byte [.const 30, .value 11], + .pure 61 .xor [.value 60, .value 49], + .pure 23 .and [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff], + .pure 26 .shl [.const 8, .value 61], + .pure 27 .or [.value 23, .value 26], + .effect none .sstore [.const 0, .value 27], + .pure 65 .and [.value 27, .const 255], + .effect none .mstore [.const 0, .value 65]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 2) .sload [.const 0], + .pure 69 .and [.value 2, .const 255], + .pure 34 .add [.value 69, .value 49], + .pure 36 .gt [.value 34, .const 255]], + .branch (.value 36) 1 2⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x2067e6a, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/c4/gen/Main/manifest.json b/Certified/c4/gen/Main/manifest.json new file mode 100644 index 00000000..ff21ac1f --- /dev/null +++ b/Certified/c4/gen/Main/manifest.json @@ -0,0 +1,103 @@ +{ + "arguments": [ + "Certified/c4/c4.sol", + "-Zcheck-analyses=false", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/c4/gen" + ], + "bytecode": "346055575f3560e01c806302067e6a036055576024361060ff60043511176055576004355f5460ff8116820160ff81116059579060ff1916179081601e1a1860081b9061ff00191617805f5560ff165f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd", + "bytecode_sha256": "8a21bc207d9dd8be48d921a717eda3ecb7e5bfcb5397850bc3d64a29037fac47", + "compiler": "0.8.38+commit.cb5053ab.solar.0.3.0-dev", + "contract": "Main", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"Certified/c4/c4.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"check-analyses=false\", \"emit-lean-stages=Certified/c4/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: Some(false), prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/c4/gen\"), keep_asts: false, forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "Certified/c4/c4.sol", + "sha256": "31c39cd4e9c5cba0f78aff3a986d69be40c5f68cdb36fbf05ad3d0a5e950e858" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "fc9bd372cfa93042b6948b6b52ce83f8c868b0832c2cd076bdd4bf4c481b521a" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "place-reads", + "sha256": "0e5c81b03404896a8f12b5e1df4636f4922bc80cef6e06f297fa024a3965ecb9" + }, + { + "definition": "mir2", + "file": "Mir2.lean", + "index": 2, + "kind": "mir", + "pass": "evm-inst-schedule", + "sha256": "b50596a2f7dc4831a1789f42dd5d0502e13b266ca9e5f7567e1292c450b94af4" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "fdf061032cfc51bfca74d7977cb5944bdb0af4147d7048cb86e77fa7d4742160" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "b10980301296d4887ba4322567653012d670c2a5441dcba1f4044ffb40d1d1d8" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "compact-pushes", + "sha256": "512034f050a4fe708788f1c7e7db6c570432aedfd9fdd308c3a993849ba8c28c" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "share-reverts", + "sha256": "955fa46e2c6701e3644da10a0129e72c06cdf0624a7bd4fa4f7faae7f71be222" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "4009d1232a8b5bc57afbbe5ac64c2fde908da9b958d007f9f9759078bdf9093b" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "1309fae9f4a8d9561fe138c69b13b7c6e57a71404ed92f861c9a7370738fc7bc" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "7d5d01d3952b98c24d030dfd189808f507cdd5e523b997b80aa4baff836df2af" + } + ] +} diff --git a/Certified/c4/options b/Certified/c4/options new file mode 100644 index 00000000..55fc63cf --- /dev/null +++ b/Certified/c4/options @@ -0,0 +1 @@ +-Zcheck-analyses=false diff --git a/Certified/c4/record.json b/Certified/c4/record.json new file mode 100644 index 00000000..cb0f7a3b --- /dev/null +++ b/Certified/c4/record.json @@ -0,0 +1,36 @@ +{ + "contract": "Main", + "name": "c4", + "source": "Certified/c4/c4.sol", + "bytecode": "346055575f3560e01c806302067e6a036055576024361060ff60043511176055576004355f5460ff8116820160ff81116059579060ff1916179081601e1a1860081b9061ff00191617805f5560ff165f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd", + "solar": "cb5053ab39adfd59820913b336d346389ce1b8d9", + "solidity_lean": "696df0a81602fc416fabec7b892073e15e8920de", + "mir_to_evmir": "proved: SolarTV.Milestone.C4.c4_mir_to_evmir", + "assembly": "decoded only: c4.Proofs.Assembly (the bytecode decodes to the final EVM IR's instructions; no execution theorem)", + "vc": "exported to .lake/certify/c4/VC.lean", + "end_to_end": "not proved", + "end_to_end_statement": {}, + "hypotheses": {}, + "refused": [ + { + "function": "Main.add", + "reason": "undeclared symbol: |w@18#bv8|", + "status": "refused (unproved)" + } + ], + "vacuous": "not checked", + "assembly_statement": null, + "assembly_hypotheses": null, + "negative_tests": false, + "caveats": [ + "solidity-lean at 696df0a81602fc416fabec7b892073e15e8920de, not the pinned 813949dc3556d3c3f1c129e8254a4eead78bac87", + "solar cb5053ab39adfd59820913b336d346389ce1b8d9, not built from this checkout's compiler sources", + "assembly decoded, not executed", + "1 spec function(s) refused, unproved", + "not end to end: solidity-lean states no source or spec theorem for c4", + "negative tests skipped" + ], + "backend": { + "theorem": "SolarTV.Milestone.C4.c4_mir_to_evmir" + } +} diff --git a/Certified/callsqrt/Proofs.lean b/Certified/callsqrt/Proofs.lean new file mode 100644 index 00000000..30379516 --- /dev/null +++ b/Certified/callsqrt/Proofs.lean @@ -0,0 +1,4 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import callsqrt.Proofs.Stages +import callsqrt.Proofs.Assembly +import callsqrt.Proofs.Execution diff --git a/Certified/callsqrt/Proofs/Assembly.lean b/Certified/callsqrt/Proofs/Assembly.lean new file mode 100644 index 00000000..3b947256 --- /dev/null +++ b/Certified/callsqrt/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Items +import callsqrt.gen.CallSqrt.Evm13 +import callsqrt.gen.CallSqrt.Bytecode + +/-! The final EVM IR of `CallSqrt` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.Callsqrt + +open SolarTV.Assembly SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm13).getD [] + +theorem items_eq : itemsOf evm13 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x22 else if label = 2 then 0x26 else if label = 3 then 0x2c else if label = 4 then 0x39 else if label = 5 then 0x48 else if label = 6 then 0x54 else if label = 7 then 0x5b else if label = 8 then 0x7a else if label = 9 then 0x9b else if label = 10 then 0x9e else if label = 11 then 0xae else if label = 12 then 0xb4 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.Callsqrt.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.Callsqrt.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms decodes + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Execution.lean b/Certified/callsqrt/Proofs/Execution.lean new file mode 100644 index 00000000..cd760fa9 --- /dev/null +++ b/Certified/callsqrt/Proofs/Execution.lean @@ -0,0 +1,110 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import callsqrt.Proofs.Stages +import callsqrt.gen.CallSqrt.Bytecode +import SolidCore.Refinement.Solar.AssembleFast +import SolidCore.Refinement.Solar.EndToEnd +import SolidCore.Refinement.Solar.RunOracle + +/-! The bytecode of `CallSqrt` runs as its final EVM IR does, at every gas, by the assembly checker for code with loops on an inferred certificate the kernel's evaluation of the checker re-derives; with the backend stages read backwards, every result of the bytecode at any gas is the first lowered MIR's or a failure that changes nothing. -/ + +namespace SolarTV.Milestone.Callsqrt + +open SolarTV SolarTV.Export.CallSqrt + +/-- The runtime bytecode, as bytes. -/ +def code : ByteArray := ⟨(bytecode.map UInt8.ofNat).toArray⟩ + +/-- The checker's certificate (tools/certify/asm_cert.py): each labelled block's offset, each block's lowest +entry height and entry words, its budget, the memory bound, the turned branches, the pushed labels and +whether the program reads CALLER or hashes. -/ +def cert : SolidCore.Refinement.Solar.Assemble.Cert := + { offsets := [0x0, 0x22, 0x26, 0x2c, 0x39, 0x48, 0x54, 0x5b, 0x7a, 0x9b, 0x9e, 0xae, 0xb4], + needs := [0, 0, 1, 3, 2, 1, 2, 3, 5, 2, 3, 4, 5], + top := 128, + turned := [], + costs := [21, 3, 4, 11, 11, 8, 5, 27, 29, 2, 8, 4, 16], + types := [[], + [], + [some false], + [some true, some false, some false], + [some false, some false], + [some false], + [some false, some false], + [some true, some false, some false], + [some false, some false, some true, some false, some false], + [some false, some false], + [some false, some false, none], + [some false, some true, some false, some false], + [some false, some false, some true, some false, some false]], + rets := [4, 6], + env := false, + reads := false } + +/-- The highest stack each block is entered with. -/ +def maxs : List Nat := [0, 1, 1, 3, 2, 1, 2, 3, 5, 5, 6, 4, 5] + +set_option maxRecDepth 100000 in +/-- The code's linear decoding is the lowered program at the layout. -/ +theorem walk_ok : (SolarTV.Assembly.walk (SolidCore.Refinement.Solar.Assemble.bytesOf code) cert.offset 0 + (SolidCore.Refinement.Solar.Assemble.lower evm13 cert)).isSome = true := by + have hw := SolidCore.Refinement.Solar.Assemble.walkS_drop (SolidCore.Refinement.Solar.Assemble.bytesOf code) cert.offset (SolidCore.Refinement.Solar.Assemble.lower evm13 cert) 0 + (Nat.zero_le _) + rw [List.drop_zero] at hw + rw [← hw] + decide +kernel + +set_option maxRecDepth 100000 in +/-- Every block checks within its budget and stack bounds. -/ +theorem blocks_ok : SolidCore.Refinement.Solar.AssembleLoop.blocksOkL evm13 cert maxs 0 evm13.blocks = true := by + decide +kernel + +theorem labels_ok : SolidCore.Refinement.Solar.Assemble.labelsValid evm13 cert code = true := + SolidCore.Refinement.Solar.Assemble.labelsValid_of_walk walk_ok + +theorem size_ok : code.size < 2 ^ 32 := by decide +kernel + +/-- The checker of code with loops accepts the bytecode for the final EVM IR. -/ +theorem check_ok : SolidCore.Refinement.Solar.AssembleLoop.checkL evm13 code cert maxs = true := by + simp only [SolidCore.Refinement.Solar.AssembleLoop.checkL, walk_ok, blocks_ok, labels_ok, decide_eq_true size_ok, Bool.and_true, + Bool.true_and] + decide + +/-- **The assembly stage at every gas.** -/ +theorem assembly (o : Machine.Oracle) (ho : cert.env = true → SolidCore.Refinement.Solar.Assemble.OracleOk o) + (he : cert.reads = true → SolidCore.Refinement.Solar.Assemble.EnvOk o) (scope : Call → Prop) (gas : Nat) : + SolidCore.Refinement.Final.Within (evmirSem o) (SolidCore.Refinement.Final.ethLibWith gas) + evm13 code scope := + SolidCore.Refinement.Solar.AssembleLoop.within_of_checkL check_ok o ho scope gas he + +/-- **The first lowered MIR to the exact bytecode at every gas**: every result of the bytecode, on every call, is +the first lowered MIR's or a failure that changes nothing. -/ +theorem callsqrt_bytecode (o : Machine.Oracle) (ho : cert.env = true → SolidCore.Refinement.Solar.Assemble.OracleOk o) + (he : cert.reads = true → SolidCore.Refinement.Solar.Assemble.EnvOk o) (gas : Nat) : + SolidCore.Refinement.Final.Within (mirSem o) (SolidCore.Refinement.Final.ethLibWith gas) + stage0 code anyCall := + SolidCore.Refinement.Solar.EndToEnd.within_of_checkL (callsqrt_certified_back o) + (fun _ _ => trivial) check_ok ho gas he + +/-- **The first lowered MIR to the exact bytecode, run by run**: for every gas and every call there is an oracle, +meeting the certificate's constraints (CertOk), under which every result of the bytecode is the first +lowered MIR's or a failure that changes nothing; it composes with specifications proved for every +oracle (RunOracle.holds_of_withinRun). -/ +theorem callsqrt_bytecode_run : + SolidCore.Refinement.Solar.RunOracle.WithinRun mirSem (fun _ => stage0) code anyCall + (SolidCore.Refinement.Solar.RunOracle.CertOk cert) := + SolidCore.Refinement.Solar.RunOracle.withinRun_mir_of_checkL callsqrt_certified_back + (fun _ _ => trivial) check_ok + +/-- info: 'SolarTV.Milestone.Callsqrt.check_ok' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms check_ok + +/-- info: 'SolarTV.Milestone.Callsqrt.callsqrt_bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms callsqrt_bytecode + +/-- info: 'SolarTV.Milestone.Callsqrt.callsqrt_bytecode_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms callsqrt_bytecode_run + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Runs/Evm1.lean b/Certified/callsqrt/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..af4cdb89 --- /dev/null +++ b/Certified/callsqrt/Proofs/Runs/Evm1.lean @@ -0,0 +1,115 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import callsqrt.gen.CallSqrt.Evm1 +import callsqrt.gen.CallSqrt.Sched + +/-! `cfg-simplify-early`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Callsqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm1_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 15 + +theorem evm1_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm1_cutA (b, st, s) = (b == 15) := rfl + +def evm1_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm1_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm1_cutB (b, st, s) = (b == 9) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm1_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (15, [w0, w1, (BitVec.ofNat 256 10), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (15, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 3), w3, w4], s)] + +theorem evm1_mk1 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s)) : + ∃ Q ∈ evm1_rels call, Q (15, [w0, w1, (BitVec.ofNat 256 10), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +theorem evm1_mk2 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 3), w3, w4], s)) : + ∃ Q ∈ evm1_rels call, Q (15, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm1_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm1_rels call, Q y y') + (seg (EVM.Program.block o call sched) evm1_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm1) evm1_cutB k' (0, [], State.initial call)) := by + refine ⟨39, 25, ?_⟩ + sym_seg [evm1_cutA_mk, evm1_cutB_mk] [evm1_mk1, evm1_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm1_seg1 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm1_rels call, Q y y') + (seg (EVM.Program.block o call sched) evm1_cutA k (15, [w0, w1, (BitVec.ofNat 256 10), w3, w4], s)) + (seg (EVM.Program.block o call evm1) evm1_cutB k' (9, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s)) := by + refine ⟨39, 25, ?_⟩ + sym_seg [evm1_cutA_mk, evm1_cutB_mk] [evm1_mk1, evm1_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm1_seg2 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm1_rels call, Q y y') + (seg (EVM.Program.block o call sched) evm1_cutA k (15, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s)) + (seg (EVM.Program.block o call evm1) evm1_cutB k' (9, [w0, w1, (BitVec.ofNat 256 3), w3, w4], s)) := by + refine ⟨39, 25, ?_⟩ + sym_seg [evm1_cutA_mk, evm1_cutB_mk] [evm1_mk1, evm1_mk2] + +theorem evm1_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm1_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm1_rels call, Q y y') + (seg (EVM.Program.block o call sched) evm1_cutA k x) + (seg (EVM.Program.block o call evm1) evm1_cutB k' x') := by + intro P mem x x' holds + simp only [evm1_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm1_seg0 o call + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm1_seg1 o call w0 w1 w3 w4 s + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm1_seg2 o call w0 w1 w3 w4 s + +/-- `sched` and `evm1` simulated through their cut points on every call. -/ +def evm1_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o sched evm1 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call sched + step' call := EVM.Program.block o call evm1 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm1_cutA + cut' := evm1_cutB + Rel call := fun x x' => ∃ P ∈ evm1_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm1_segments o call) + +/-- Every end of `sched` on a call is matched by an agreeing end of `evm1`. -/ +theorem evm1_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o sched evm1 anyCall := + (evm1_sim o).certified + +/-- Every end of `evm1` on a call is matched by an agreeing end of `sched`. -/ +theorem evm1_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm1 sched anyCall := + (evm1_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Callsqrt.evm1_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_certified + +/-- info: 'SolarTV.Milestone.Callsqrt.evm1_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_certified_back + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Runs/Evm10.lean b/Certified/callsqrt/Proofs/Runs/Evm10.lean new file mode 100644 index 00000000..50ba1ed5 --- /dev/null +++ b/Certified/callsqrt/Proofs/Runs/Evm10.lean @@ -0,0 +1,115 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import callsqrt.gen.CallSqrt.Evm10 +import callsqrt.gen.CallSqrt.Evm9 + +/-! `stack-reschedule`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Callsqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm10_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm10_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm10_cutA (b, st, s) = (b == 9) := rfl + +def evm10_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm10_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm10_cutB (b, st, s) = (b == 9) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm10_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)] + +theorem evm10_mk1 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) : + ∃ Q ∈ evm10_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +theorem evm10_mk2 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) : + ∃ Q ∈ evm10_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm10_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm10_rels call, Q y y') + (seg (EVM.Program.block o call evm9) evm10_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm10) evm10_cutB k' (0, [], State.initial call)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm10_cutA_mk, evm10_cutB_mk] [evm10_mk1, evm10_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm10_seg1 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm10_rels call, Q y y') + (seg (EVM.Program.block o call evm9) evm10_cutA k (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) + (seg (EVM.Program.block o call evm10) evm10_cutB k' (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm10_cutA_mk, evm10_cutB_mk] [evm10_mk1, evm10_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm10_seg2 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm10_rels call, Q y y') + (seg (EVM.Program.block o call evm9) evm10_cutA k (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) + (seg (EVM.Program.block o call evm10) evm10_cutB k' (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm10_cutA_mk, evm10_cutB_mk] [evm10_mk1, evm10_mk2] + +theorem evm10_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm10_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm10_rels call, Q y y') + (seg (EVM.Program.block o call evm9) evm10_cutA k x) + (seg (EVM.Program.block o call evm10) evm10_cutB k' x') := by + intro P mem x x' holds + simp only [evm10_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm10_seg0 o call + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm10_seg1 o call w0 w1 w3 w4 s + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm10_seg2 o call w0 w1 w3 w4 s + +/-- `evm9` and `evm10` simulated through their cut points on every call. -/ +def evm10_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm9 evm10 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm9 + step' call := EVM.Program.block o call evm10 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm10_cutA + cut' := evm10_cutB + Rel call := fun x x' => ∃ P ∈ evm10_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm10_segments o call) + +/-- Every end of `evm9` on a call is matched by an agreeing end of `evm10`. -/ +theorem evm10_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm9 evm10 anyCall := + (evm10_sim o).certified + +/-- Every end of `evm10` on a call is matched by an agreeing end of `evm9`. -/ +theorem evm10_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm10 evm9 anyCall := + (evm10_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Callsqrt.evm10_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm10_certified + +/-- info: 'SolarTV.Milestone.Callsqrt.evm10_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm10_certified_back + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Runs/Evm11.lean b/Certified/callsqrt/Proofs/Runs/Evm11.lean new file mode 100644 index 00000000..1b516db2 --- /dev/null +++ b/Certified/callsqrt/Proofs/Runs/Evm11.lean @@ -0,0 +1,115 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import callsqrt.gen.CallSqrt.Evm11 +import callsqrt.gen.CallSqrt.Evm10 + +/-! `inline-returns`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Callsqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm11_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm11_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm11_cutA (b, st, s) = (b == 9) := rfl + +def evm11_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm11_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm11_cutB (b, st, s) = (b == 9) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm11_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)] + +theorem evm11_mk1 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) : + ∃ Q ∈ evm11_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +theorem evm11_mk2 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) : + ∃ Q ∈ evm11_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm11_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm11_rels call, Q y y') + (seg (EVM.Program.block o call evm10) evm11_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm11) evm11_cutB k' (0, [], State.initial call)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm11_cutA_mk, evm11_cutB_mk] [evm11_mk1, evm11_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm11_seg1 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm11_rels call, Q y y') + (seg (EVM.Program.block o call evm10) evm11_cutA k (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) + (seg (EVM.Program.block o call evm11) evm11_cutB k' (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm11_cutA_mk, evm11_cutB_mk] [evm11_mk1, evm11_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm11_seg2 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm11_rels call, Q y y') + (seg (EVM.Program.block o call evm10) evm11_cutA k (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) + (seg (EVM.Program.block o call evm11) evm11_cutB k' (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm11_cutA_mk, evm11_cutB_mk] [evm11_mk1, evm11_mk2] + +theorem evm11_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm11_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm11_rels call, Q y y') + (seg (EVM.Program.block o call evm10) evm11_cutA k x) + (seg (EVM.Program.block o call evm11) evm11_cutB k' x') := by + intro P mem x x' holds + simp only [evm11_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm11_seg0 o call + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm11_seg1 o call w0 w1 w3 w4 s + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm11_seg2 o call w0 w1 w3 w4 s + +/-- `evm10` and `evm11` simulated through their cut points on every call. -/ +def evm11_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm10 evm11 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm10 + step' call := EVM.Program.block o call evm11 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm11_cutA + cut' := evm11_cutB + Rel call := fun x x' => ∃ P ∈ evm11_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm11_segments o call) + +/-- Every end of `evm10` on a call is matched by an agreeing end of `evm11`. -/ +theorem evm11_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm10 evm11 anyCall := + (evm11_sim o).certified + +/-- Every end of `evm11` on a call is matched by an agreeing end of `evm10`. -/ +theorem evm11_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm11 evm10 anyCall := + (evm11_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Callsqrt.evm11_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm11_certified + +/-- info: 'SolarTV.Milestone.Callsqrt.evm11_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm11_certified_back + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Runs/Evm12.lean b/Certified/callsqrt/Proofs/Runs/Evm12.lean new file mode 100644 index 00000000..8289c601 --- /dev/null +++ b/Certified/callsqrt/Proofs/Runs/Evm12.lean @@ -0,0 +1,115 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import callsqrt.gen.CallSqrt.Evm12 +import callsqrt.gen.CallSqrt.Evm11 + +/-! `copy-loop-blocks`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Callsqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm12_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 10 + +theorem evm12_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm12_cutA (b, st, s) = (b == 10) := rfl + +def evm12_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 10 + +theorem evm12_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm12_cutB (b, st, s) = (b == 10) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm12_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (10, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) ∧ x' = (10, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (10, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) ∧ x' = (10, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)] + +theorem evm12_mk1 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (10, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) : + ∃ Q ∈ evm12_rels call, Q (10, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +theorem evm12_mk2 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (10, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) : + ∃ Q ∈ evm12_rels call, Q (10, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm12_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm12_rels call, Q y y') + (seg (EVM.Program.block o call evm11) evm12_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm12) evm12_cutB k' (0, [], State.initial call)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm12_cutA_mk, evm12_cutB_mk] [evm12_mk1, evm12_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm12_seg1 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm12_rels call, Q y y') + (seg (EVM.Program.block o call evm11) evm12_cutA k (10, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) + (seg (EVM.Program.block o call evm12) evm12_cutB k' (10, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm12_cutA_mk, evm12_cutB_mk] [evm12_mk1, evm12_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm12_seg2 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm12_rels call, Q y y') + (seg (EVM.Program.block o call evm11) evm12_cutA k (10, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) + (seg (EVM.Program.block o call evm12) evm12_cutB k' (10, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm12_cutA_mk, evm12_cutB_mk] [evm12_mk1, evm12_mk2] + +theorem evm12_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm12_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm12_rels call, Q y y') + (seg (EVM.Program.block o call evm11) evm12_cutA k x) + (seg (EVM.Program.block o call evm12) evm12_cutB k' x') := by + intro P mem x x' holds + simp only [evm12_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm12_seg0 o call + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm12_seg1 o call w0 w1 w3 w4 s + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm12_seg2 o call w0 w1 w3 w4 s + +/-- `evm11` and `evm12` simulated through their cut points on every call. -/ +def evm12_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm11 evm12 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm11 + step' call := EVM.Program.block o call evm12 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm12_cutA + cut' := evm12_cutB + Rel call := fun x x' => ∃ P ∈ evm12_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm12_segments o call) + +/-- Every end of `evm11` on a call is matched by an agreeing end of `evm12`. -/ +theorem evm12_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm11 evm12 anyCall := + (evm12_sim o).certified + +/-- Every end of `evm12` on a call is matched by an agreeing end of `evm11`. -/ +theorem evm12_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm12 evm11 anyCall := + (evm12_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Callsqrt.evm12_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm12_certified + +/-- info: 'SolarTV.Milestone.Callsqrt.evm12_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm12_certified_back + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Runs/Evm13.lean b/Certified/callsqrt/Proofs/Runs/Evm13.lean new file mode 100644 index 00000000..cf958346 --- /dev/null +++ b/Certified/callsqrt/Proofs/Runs/Evm13.lean @@ -0,0 +1,115 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import callsqrt.gen.CallSqrt.Evm13 +import callsqrt.gen.CallSqrt.Evm12 + +/-! `cfg-simplify`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Callsqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm13_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 10 + +theorem evm13_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm13_cutA (b, st, s) = (b == 10) := rfl + +def evm13_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 8 + +theorem evm13_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm13_cutB (b, st, s) = (b == 8) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm13_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (10, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) ∧ x' = (8, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (10, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) ∧ x' = (8, [w0, w1, (BitVec.ofNat 256 4), w3, w4], s)] + +theorem evm13_mk1 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (8, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s)) : + ∃ Q ∈ evm13_rels call, Q (10, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +theorem evm13_mk2 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (8, [w0, w1, (BitVec.ofNat 256 4), w3, w4], s)) : + ∃ Q ∈ evm13_rels call, Q (10, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm13_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm13_rels call, Q y y') + (seg (EVM.Program.block o call evm12) evm13_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm13) evm13_cutB k' (0, [], State.initial call)) := by + refine ⟨30, 26, ?_⟩ + sym_seg [evm13_cutA_mk, evm13_cutB_mk] [evm13_mk1, evm13_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm13_seg1 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm13_rels call, Q y y') + (seg (EVM.Program.block o call evm12) evm13_cutA k (10, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) + (seg (EVM.Program.block o call evm13) evm13_cutB k' (8, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s)) := by + refine ⟨30, 26, ?_⟩ + sym_seg [evm13_cutA_mk, evm13_cutB_mk] [evm13_mk1, evm13_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm13_seg2 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm13_rels call, Q y y') + (seg (EVM.Program.block o call evm12) evm13_cutA k (10, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) + (seg (EVM.Program.block o call evm13) evm13_cutB k' (8, [w0, w1, (BitVec.ofNat 256 4), w3, w4], s)) := by + refine ⟨30, 26, ?_⟩ + sym_seg [evm13_cutA_mk, evm13_cutB_mk] [evm13_mk1, evm13_mk2] + +theorem evm13_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm13_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm13_rels call, Q y y') + (seg (EVM.Program.block o call evm12) evm13_cutA k x) + (seg (EVM.Program.block o call evm13) evm13_cutB k' x') := by + intro P mem x x' holds + simp only [evm13_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm13_seg0 o call + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm13_seg1 o call w0 w1 w3 w4 s + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm13_seg2 o call w0 w1 w3 w4 s + +/-- `evm12` and `evm13` simulated through their cut points on every call. -/ +def evm13_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm12 evm13 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm12 + step' call := EVM.Program.block o call evm13 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm13_cutA + cut' := evm13_cutB + Rel call := fun x x' => ∃ P ∈ evm13_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm13_segments o call) + +/-- Every end of `evm12` on a call is matched by an agreeing end of `evm13`. -/ +theorem evm13_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm12 evm13 anyCall := + (evm13_sim o).certified + +/-- Every end of `evm13` on a call is matched by an agreeing end of `evm12`. -/ +theorem evm13_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm13 evm12 anyCall := + (evm13_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Callsqrt.evm13_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm13_certified + +/-- info: 'SolarTV.Milestone.Callsqrt.evm13_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm13_certified_back + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Runs/Evm2.lean b/Certified/callsqrt/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..c4a4ec70 --- /dev/null +++ b/Certified/callsqrt/Proofs/Runs/Evm2.lean @@ -0,0 +1,115 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import callsqrt.gen.CallSqrt.Evm2 +import callsqrt.gen.CallSqrt.Evm1 + +/-! `compact-pushes`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Callsqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm2_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm2_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm2_cutA (b, st, s) = (b == 9) := rfl + +def evm2_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm2_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm2_cutB (b, st, s) = (b == 9) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm2_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 3), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 3), w3, w4], s)] + +theorem evm2_mk1 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s)) : + ∃ Q ∈ evm2_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +theorem evm2_mk2 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 3), w3, w4], s)) : + ∃ Q ∈ evm2_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 3), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm2_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm2_rels call, Q y y') + (seg (EVM.Program.block o call evm1) evm2_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm2) evm2_cutB k' (0, [], State.initial call)) := by + refine ⟨25, 25, ?_⟩ + sym_seg [evm2_cutA_mk, evm2_cutB_mk] [evm2_mk1, evm2_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm2_seg1 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm2_rels call, Q y y') + (seg (EVM.Program.block o call evm1) evm2_cutA k (9, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s)) + (seg (EVM.Program.block o call evm2) evm2_cutB k' (9, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s)) := by + refine ⟨25, 25, ?_⟩ + sym_seg [evm2_cutA_mk, evm2_cutB_mk] [evm2_mk1, evm2_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm2_seg2 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm2_rels call, Q y y') + (seg (EVM.Program.block o call evm1) evm2_cutA k (9, [w0, w1, (BitVec.ofNat 256 3), w3, w4], s)) + (seg (EVM.Program.block o call evm2) evm2_cutB k' (9, [w0, w1, (BitVec.ofNat 256 3), w3, w4], s)) := by + refine ⟨25, 25, ?_⟩ + sym_seg [evm2_cutA_mk, evm2_cutB_mk] [evm2_mk1, evm2_mk2] + +theorem evm2_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm2_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm2_rels call, Q y y') + (seg (EVM.Program.block o call evm1) evm2_cutA k x) + (seg (EVM.Program.block o call evm2) evm2_cutB k' x') := by + intro P mem x x' holds + simp only [evm2_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm2_seg0 o call + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm2_seg1 o call w0 w1 w3 w4 s + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm2_seg2 o call w0 w1 w3 w4 s + +/-- `evm1` and `evm2` simulated through their cut points on every call. -/ +def evm2_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm1 evm2 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm1 + step' call := EVM.Program.block o call evm2 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm2_cutA + cut' := evm2_cutB + Rel call := fun x x' => ∃ P ∈ evm2_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm2_segments o call) + +/-- Every end of `evm1` on a call is matched by an agreeing end of `evm2`. -/ +theorem evm2_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm1 evm2 anyCall := + (evm2_sim o).certified + +/-- Every end of `evm2` on a call is matched by an agreeing end of `evm1`. -/ +theorem evm2_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm2 evm1 anyCall := + (evm2_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Callsqrt.evm2_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_certified + +/-- info: 'SolarTV.Milestone.Callsqrt.evm2_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_certified_back + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Runs/Evm3.lean b/Certified/callsqrt/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..422bed9d --- /dev/null +++ b/Certified/callsqrt/Proofs/Runs/Evm3.lean @@ -0,0 +1,115 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import callsqrt.gen.CallSqrt.Evm3 +import callsqrt.gen.CallSqrt.Evm2 + +/-! `block-layout`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Callsqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm3_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm3_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm3_cutA (b, st, s) = (b == 9) := rfl + +def evm3_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm3_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm3_cutB (b, st, s) = (b == 9) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm3_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 3), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)] + +theorem evm3_mk1 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) : + ∃ Q ∈ evm3_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +theorem evm3_mk2 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) : + ∃ Q ∈ evm3_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 3), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm3_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm3_rels call, Q y y') + (seg (EVM.Program.block o call evm2) evm3_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm3) evm3_cutB k' (0, [], State.initial call)) := by + refine ⟨25, 25, ?_⟩ + sym_seg [evm3_cutA_mk, evm3_cutB_mk] [evm3_mk1, evm3_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm3_seg1 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm3_rels call, Q y y') + (seg (EVM.Program.block o call evm2) evm3_cutA k (9, [w0, w1, (BitVec.ofNat 256 6), w3, w4], s)) + (seg (EVM.Program.block o call evm3) evm3_cutB k' (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) := by + refine ⟨25, 25, ?_⟩ + sym_seg [evm3_cutA_mk, evm3_cutB_mk] [evm3_mk1, evm3_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm3_seg2 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm3_rels call, Q y y') + (seg (EVM.Program.block o call evm2) evm3_cutA k (9, [w0, w1, (BitVec.ofNat 256 3), w3, w4], s)) + (seg (EVM.Program.block o call evm3) evm3_cutB k' (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) := by + refine ⟨25, 25, ?_⟩ + sym_seg [evm3_cutA_mk, evm3_cutB_mk] [evm3_mk1, evm3_mk2] + +theorem evm3_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm3_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm3_rels call, Q y y') + (seg (EVM.Program.block o call evm2) evm3_cutA k x) + (seg (EVM.Program.block o call evm3) evm3_cutB k' x') := by + intro P mem x x' holds + simp only [evm3_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm3_seg0 o call + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm3_seg1 o call w0 w1 w3 w4 s + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm3_seg2 o call w0 w1 w3 w4 s + +/-- `evm2` and `evm3` simulated through their cut points on every call. -/ +def evm3_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm2 evm3 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm2 + step' call := EVM.Program.block o call evm3 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm3_cutA + cut' := evm3_cutB + Rel call := fun x x' => ∃ P ∈ evm3_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm3_segments o call) + +/-- Every end of `evm2` on a call is matched by an agreeing end of `evm3`. -/ +theorem evm3_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm2 evm3 anyCall := + (evm3_sim o).certified + +/-- Every end of `evm3` on a call is matched by an agreeing end of `evm2`. -/ +theorem evm3_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm3 evm2 anyCall := + (evm3_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Callsqrt.evm3_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_certified + +/-- info: 'SolarTV.Milestone.Callsqrt.evm3_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_certified_back + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Runs/Evm4.lean b/Certified/callsqrt/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..133a6083 --- /dev/null +++ b/Certified/callsqrt/Proofs/Runs/Evm4.lean @@ -0,0 +1,115 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import callsqrt.gen.CallSqrt.Evm4 +import callsqrt.gen.CallSqrt.Evm3 + +/-! `terminal-dedup`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Callsqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm4_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm4_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm4_cutA (b, st, s) = (b == 9) := rfl + +def evm4_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm4_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm4_cutB (b, st, s) = (b == 9) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm4_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)] + +theorem evm4_mk1 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) : + ∃ Q ∈ evm4_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +theorem evm4_mk2 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) : + ∃ Q ∈ evm4_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm4_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm4_rels call, Q y y') + (seg (EVM.Program.block o call evm3) evm4_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm4) evm4_cutB k' (0, [], State.initial call)) := by + refine ⟨25, 27, ?_⟩ + sym_seg [evm4_cutA_mk, evm4_cutB_mk] [evm4_mk1, evm4_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm4_seg1 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm4_rels call, Q y y') + (seg (EVM.Program.block o call evm3) evm4_cutA k (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) + (seg (EVM.Program.block o call evm4) evm4_cutB k' (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) := by + refine ⟨25, 27, ?_⟩ + sym_seg [evm4_cutA_mk, evm4_cutB_mk] [evm4_mk1, evm4_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm4_seg2 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm4_rels call, Q y y') + (seg (EVM.Program.block o call evm3) evm4_cutA k (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) + (seg (EVM.Program.block o call evm4) evm4_cutB k' (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) := by + refine ⟨25, 27, ?_⟩ + sym_seg [evm4_cutA_mk, evm4_cutB_mk] [evm4_mk1, evm4_mk2] + +theorem evm4_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm4_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm4_rels call, Q y y') + (seg (EVM.Program.block o call evm3) evm4_cutA k x) + (seg (EVM.Program.block o call evm4) evm4_cutB k' x') := by + intro P mem x x' holds + simp only [evm4_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm4_seg0 o call + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm4_seg1 o call w0 w1 w3 w4 s + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm4_seg2 o call w0 w1 w3 w4 s + +/-- `evm3` and `evm4` simulated through their cut points on every call. -/ +def evm4_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm3 evm4 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm3 + step' call := EVM.Program.block o call evm4 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm4_cutA + cut' := evm4_cutB + Rel call := fun x x' => ∃ P ∈ evm4_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm4_segments o call) + +/-- Every end of `evm3` on a call is matched by an agreeing end of `evm4`. -/ +theorem evm4_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm3 evm4 anyCall := + (evm4_sim o).certified + +/-- Every end of `evm4` on a call is matched by an agreeing end of `evm3`. -/ +theorem evm4_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm4 evm3 anyCall := + (evm4_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Callsqrt.evm4_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_certified + +/-- info: 'SolarTV.Milestone.Callsqrt.evm4_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_certified_back + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Runs/Evm5.lean b/Certified/callsqrt/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..28ff4011 --- /dev/null +++ b/Certified/callsqrt/Proofs/Runs/Evm5.lean @@ -0,0 +1,115 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import callsqrt.gen.CallSqrt.Evm5 +import callsqrt.gen.CallSqrt.Evm4 + +/-! `cfg-simplify-early`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Callsqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm5_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm5_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm5_cutA (b, st, s) = (b == 9) := rfl + +def evm5_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm5_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm5_cutB (b, st, s) = (b == 9) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm5_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)] + +theorem evm5_mk1 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) : + ∃ Q ∈ evm5_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +theorem evm5_mk2 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) : + ∃ Q ∈ evm5_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm5_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm5_rels call, Q y y') + (seg (EVM.Program.block o call evm4) evm5_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm5) evm5_cutB k' (0, [], State.initial call)) := by + refine ⟨27, 25, ?_⟩ + sym_seg [evm5_cutA_mk, evm5_cutB_mk] [evm5_mk1, evm5_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm5_seg1 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm5_rels call, Q y y') + (seg (EVM.Program.block o call evm4) evm5_cutA k (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) + (seg (EVM.Program.block o call evm5) evm5_cutB k' (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) := by + refine ⟨27, 25, ?_⟩ + sym_seg [evm5_cutA_mk, evm5_cutB_mk] [evm5_mk1, evm5_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm5_seg2 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm5_rels call, Q y y') + (seg (EVM.Program.block o call evm4) evm5_cutA k (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) + (seg (EVM.Program.block o call evm5) evm5_cutB k' (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) := by + refine ⟨27, 25, ?_⟩ + sym_seg [evm5_cutA_mk, evm5_cutB_mk] [evm5_mk1, evm5_mk2] + +theorem evm5_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm5_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm5_rels call, Q y y') + (seg (EVM.Program.block o call evm4) evm5_cutA k x) + (seg (EVM.Program.block o call evm5) evm5_cutB k' x') := by + intro P mem x x' holds + simp only [evm5_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm5_seg0 o call + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm5_seg1 o call w0 w1 w3 w4 s + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm5_seg2 o call w0 w1 w3 w4 s + +/-- `evm4` and `evm5` simulated through their cut points on every call. -/ +def evm5_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm4 evm5 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm4 + step' call := EVM.Program.block o call evm5 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm5_cutA + cut' := evm5_cutB + Rel call := fun x x' => ∃ P ∈ evm5_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm5_segments o call) + +/-- Every end of `evm4` on a call is matched by an agreeing end of `evm5`. -/ +theorem evm5_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm4 evm5 anyCall := + (evm5_sim o).certified + +/-- Every end of `evm5` on a call is matched by an agreeing end of `evm4`. -/ +theorem evm5_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm5 evm4 anyCall := + (evm5_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Callsqrt.evm5_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_certified + +/-- info: 'SolarTV.Milestone.Callsqrt.evm5_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_certified_back + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Runs/Evm6.lean b/Certified/callsqrt/Proofs/Runs/Evm6.lean new file mode 100644 index 00000000..0e31ab08 --- /dev/null +++ b/Certified/callsqrt/Proofs/Runs/Evm6.lean @@ -0,0 +1,115 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import callsqrt.gen.CallSqrt.Evm6 +import callsqrt.gen.CallSqrt.Evm5 + +/-! `tail-merge`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Callsqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm6_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm6_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm6_cutA (b, st, s) = (b == 9) := rfl + +def evm6_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm6_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm6_cutB (b, st, s) = (b == 9) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm6_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)] + +theorem evm6_mk1 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) : + ∃ Q ∈ evm6_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +theorem evm6_mk2 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) : + ∃ Q ∈ evm6_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm6_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm6_rels call, Q y y') + (seg (EVM.Program.block o call evm5) evm6_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm6) evm6_cutB k' (0, [], State.initial call)) := by + refine ⟨25, 30, ?_⟩ + sym_seg [evm6_cutA_mk, evm6_cutB_mk] [evm6_mk1, evm6_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm6_seg1 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm6_rels call, Q y y') + (seg (EVM.Program.block o call evm5) evm6_cutA k (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) + (seg (EVM.Program.block o call evm6) evm6_cutB k' (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) := by + refine ⟨25, 30, ?_⟩ + sym_seg [evm6_cutA_mk, evm6_cutB_mk] [evm6_mk1, evm6_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm6_seg2 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm6_rels call, Q y y') + (seg (EVM.Program.block o call evm5) evm6_cutA k (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) + (seg (EVM.Program.block o call evm6) evm6_cutB k' (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) := by + refine ⟨25, 30, ?_⟩ + sym_seg [evm6_cutA_mk, evm6_cutB_mk] [evm6_mk1, evm6_mk2] + +theorem evm6_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm6_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm6_rels call, Q y y') + (seg (EVM.Program.block o call evm5) evm6_cutA k x) + (seg (EVM.Program.block o call evm6) evm6_cutB k' x') := by + intro P mem x x' holds + simp only [evm6_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm6_seg0 o call + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm6_seg1 o call w0 w1 w3 w4 s + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm6_seg2 o call w0 w1 w3 w4 s + +/-- `evm5` and `evm6` simulated through their cut points on every call. -/ +def evm6_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm5 evm6 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm5 + step' call := EVM.Program.block o call evm6 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm6_cutA + cut' := evm6_cutB + Rel call := fun x x' => ∃ P ∈ evm6_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm6_segments o call) + +/-- Every end of `evm5` on a call is matched by an agreeing end of `evm6`. -/ +theorem evm6_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm5 evm6 anyCall := + (evm6_sim o).certified + +/-- Every end of `evm6` on a call is matched by an agreeing end of `evm5`. -/ +theorem evm6_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm6 evm5 anyCall := + (evm6_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Callsqrt.evm6_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_certified + +/-- info: 'SolarTV.Milestone.Callsqrt.evm6_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_certified_back + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Runs/Evm7.lean b/Certified/callsqrt/Proofs/Runs/Evm7.lean new file mode 100644 index 00000000..3bb248e7 --- /dev/null +++ b/Certified/callsqrt/Proofs/Runs/Evm7.lean @@ -0,0 +1,115 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import callsqrt.gen.CallSqrt.Evm7 +import callsqrt.gen.CallSqrt.Evm6 + +/-! `reorder-pushes`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Callsqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm7_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm7_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm7_cutA (b, st, s) = (b == 9) := rfl + +def evm7_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm7_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm7_cutB (b, st, s) = (b == 9) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm7_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)] + +theorem evm7_mk1 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) : + ∃ Q ∈ evm7_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +theorem evm7_mk2 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) : + ∃ Q ∈ evm7_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm7_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm7_rels call, Q y y') + (seg (EVM.Program.block o call evm6) evm7_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm7) evm7_cutB k' (0, [], State.initial call)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm7_cutA_mk, evm7_cutB_mk] [evm7_mk1, evm7_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm7_seg1 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm7_rels call, Q y y') + (seg (EVM.Program.block o call evm6) evm7_cutA k (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) + (seg (EVM.Program.block o call evm7) evm7_cutB k' (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm7_cutA_mk, evm7_cutB_mk] [evm7_mk1, evm7_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm7_seg2 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm7_rels call, Q y y') + (seg (EVM.Program.block o call evm6) evm7_cutA k (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) + (seg (EVM.Program.block o call evm7) evm7_cutB k' (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm7_cutA_mk, evm7_cutB_mk] [evm7_mk1, evm7_mk2] + +theorem evm7_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm7_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm7_rels call, Q y y') + (seg (EVM.Program.block o call evm6) evm7_cutA k x) + (seg (EVM.Program.block o call evm7) evm7_cutB k' x') := by + intro P mem x x' holds + simp only [evm7_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm7_seg0 o call + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm7_seg1 o call w0 w1 w3 w4 s + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm7_seg2 o call w0 w1 w3 w4 s + +/-- `evm6` and `evm7` simulated through their cut points on every call. -/ +def evm7_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm6 evm7 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm6 + step' call := EVM.Program.block o call evm7 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm7_cutA + cut' := evm7_cutB + Rel call := fun x x' => ∃ P ∈ evm7_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm7_segments o call) + +/-- Every end of `evm6` on a call is matched by an agreeing end of `evm7`. -/ +theorem evm7_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm6 evm7 anyCall := + (evm7_sim o).certified + +/-- Every end of `evm7` on a call is matched by an agreeing end of `evm6`. -/ +theorem evm7_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm7 evm6 anyCall := + (evm7_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Callsqrt.evm7_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm7_certified + +/-- info: 'SolarTV.Milestone.Callsqrt.evm7_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm7_certified_back + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Runs/Evm8.lean b/Certified/callsqrt/Proofs/Runs/Evm8.lean new file mode 100644 index 00000000..061d7ee7 --- /dev/null +++ b/Certified/callsqrt/Proofs/Runs/Evm8.lean @@ -0,0 +1,115 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import callsqrt.gen.CallSqrt.Evm8 +import callsqrt.gen.CallSqrt.Evm7 + +/-! `stack-normalize`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Callsqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm8_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm8_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm8_cutA (b, st, s) = (b == 9) := rfl + +def evm8_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm8_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm8_cutB (b, st, s) = (b == 9) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm8_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)] + +theorem evm8_mk1 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) : + ∃ Q ∈ evm8_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +theorem evm8_mk2 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) : + ∃ Q ∈ evm8_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm8_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm8_rels call, Q y y') + (seg (EVM.Program.block o call evm7) evm8_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm8) evm8_cutB k' (0, [], State.initial call)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm8_cutA_mk, evm8_cutB_mk] [evm8_mk1, evm8_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm8_seg1 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm8_rels call, Q y y') + (seg (EVM.Program.block o call evm7) evm8_cutA k (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) + (seg (EVM.Program.block o call evm8) evm8_cutB k' (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm8_cutA_mk, evm8_cutB_mk] [evm8_mk1, evm8_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm8_seg2 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm8_rels call, Q y y') + (seg (EVM.Program.block o call evm7) evm8_cutA k (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) + (seg (EVM.Program.block o call evm8) evm8_cutB k' (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm8_cutA_mk, evm8_cutB_mk] [evm8_mk1, evm8_mk2] + +theorem evm8_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm8_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm8_rels call, Q y y') + (seg (EVM.Program.block o call evm7) evm8_cutA k x) + (seg (EVM.Program.block o call evm8) evm8_cutB k' x') := by + intro P mem x x' holds + simp only [evm8_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm8_seg0 o call + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm8_seg1 o call w0 w1 w3 w4 s + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm8_seg2 o call w0 w1 w3 w4 s + +/-- `evm7` and `evm8` simulated through their cut points on every call. -/ +def evm8_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm7 evm8 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm7 + step' call := EVM.Program.block o call evm8 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm8_cutA + cut' := evm8_cutB + Rel call := fun x x' => ∃ P ∈ evm8_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm8_segments o call) + +/-- Every end of `evm7` on a call is matched by an agreeing end of `evm8`. -/ +theorem evm8_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm7 evm8 anyCall := + (evm8_sim o).certified + +/-- Every end of `evm8` on a call is matched by an agreeing end of `evm7`. -/ +theorem evm8_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm8 evm7 anyCall := + (evm8_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Callsqrt.evm8_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm8_certified + +/-- info: 'SolarTV.Milestone.Callsqrt.evm8_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm8_certified_back + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Runs/Evm9.lean b/Certified/callsqrt/Proofs/Runs/Evm9.lean new file mode 100644 index 00000000..4b0b6a26 --- /dev/null +++ b/Certified/callsqrt/Proofs/Runs/Evm9.lean @@ -0,0 +1,115 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import callsqrt.gen.CallSqrt.Evm9 +import callsqrt.gen.CallSqrt.Evm8 + +/-! `block-layout`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Callsqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm9_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm9_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm9_cutA (b, st, s) = (b == 9) := rfl + +def evm9_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 9 + +theorem evm9_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm9_cutB (b, st, s) = (b == 9) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm9_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s), + fun x x' => ∃ (w0 w1 w3 w4 : EvmRules.Word) (s : State), x = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) ∧ x' = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)] + +theorem evm9_mk1 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) : + ∃ Q ∈ evm9_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +theorem evm9_mk2 {call : Call} {w0 w1 w3 w4 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) : + ∃ Q ∈ evm9_rels call, Q (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s) y := + rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨w0, w1, w3, w4, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm9_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm9_rels call, Q y y') + (seg (EVM.Program.block o call evm8) evm9_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm9) evm9_cutB k' (0, [], State.initial call)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm9_cutA_mk, evm9_cutB_mk] [evm9_mk1, evm9_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm9_seg1 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm9_rels call, Q y y') + (seg (EVM.Program.block o call evm8) evm9_cutA k (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) + (seg (EVM.Program.block o call evm9) evm9_cutB k' (9, [w0, w1, (BitVec.ofNat 256 7), w3, w4], s)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm9_cutA_mk, evm9_cutB_mk] [evm9_mk1, evm9_mk2] + +set_option maxHeartbeats 2000000 in +theorem evm9_seg2 (o : Oracle) (call : Call) (w0 w1 w3 w4 : EvmRules.Word) (s : State) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm9_rels call, Q y y') + (seg (EVM.Program.block o call evm8) evm9_cutA k (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) + (seg (EVM.Program.block o call evm9) evm9_cutB k' (9, [w0, w1, (BitVec.ofNat 256 5), w3, w4], s)) := by + refine ⟨30, 30, ?_⟩ + sym_seg [evm9_cutA_mk, evm9_cutB_mk] [evm9_mk1, evm9_mk2] + +theorem evm9_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm9_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ evm9_rels call, Q y y') + (seg (EVM.Program.block o call evm8) evm9_cutA k x) + (seg (EVM.Program.block o call evm9) evm9_cutB k' x') := by + intro P mem x x' holds + simp only [evm9_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm9_seg0 o call + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm9_seg1 o call w0 w1 w3 w4 s + · obtain ⟨w0, w1, w3, w4, s, rfl, rfl⟩ := holds + exact evm9_seg2 o call w0 w1 w3 w4 s + +/-- `evm8` and `evm9` simulated through their cut points on every call. -/ +def evm9_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm8 evm9 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm8 + step' call := EVM.Program.block o call evm9 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm9_cutA + cut' := evm9_cutB + Rel call := fun x x' => ∃ P ∈ evm9_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (evm9_segments o call) + +/-- Every end of `evm8` on a call is matched by an agreeing end of `evm9`. -/ +theorem evm9_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm8 evm9 anyCall := + (evm9_sim o).certified + +/-- Every end of `evm9` on a call is matched by an agreeing end of `evm8`. -/ +theorem evm9_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm9 evm8 anyCall := + (evm9_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Callsqrt.evm9_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm9_certified + +/-- info: 'SolarTV.Milestone.Callsqrt.evm9_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm9_certified_back + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Runs/Mir1.lean b/Certified/callsqrt/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..33438c16 --- /dev/null +++ b/Certified/callsqrt/Proofs/Runs/Mir1.lean @@ -0,0 +1,231 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import callsqrt.gen.CallSqrt.Mir1 +import callsqrt.gen.CallSqrt.Stage0 + +/-! `lower-assumes`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Callsqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def mir1_cutA : MIR.Lowered.Frame → Bool := fun x => + match x.2.1 with + | .enter f _ b => (f == 2 && b == 4) + | .resume .. => false + +theorem mir1_cutA_enter (rs : List MIR.Lowered.Return) (f p b : Nat) (env : MIR.Lowered.Env) (s : State) : + mir1_cutA (rs, .enter f p b, env, s) = ((f == 2 && b == 4)) := rfl + +theorem mir1_cutA_resume (rs : List MIR.Lowered.Return) (f b : Nat) (is : List MIR.Lowered.Inst) (t : MIR.Lowered.Terminator) (env : MIR.Lowered.Env) (s : State) : + mir1_cutA (rs, .resume f b is t, env, s) = false := rfl + +def mir1_cutB : MIR.Lowered.Frame → Bool := fun x => + match x.2.1 with + | .enter f _ b => (f == 2 && b == 4) + | .resume .. => false + +theorem mir1_cutB_enter (rs : List MIR.Lowered.Return) (f p b : Nat) (env : MIR.Lowered.Env) (s : State) : + mir1_cutB (rs, .enter f p b, env, s) = ((f == 2 && b == 4)) := rfl + +theorem mir1_cutB_resume (rs : List MIR.Lowered.Return) (f b : Nat) (is : List MIR.Lowered.Inst) (t : MIR.Lowered.Terminator) (env : MIR.Lowered.Env) (s : State) : + mir1_cutB (rs, .resume f b is t, env, s) = false := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def mir1_rels (call : Call) : List (MIR.Lowered.Frame → MIR.Lowered.Frame → Prop) := + [fun x x' => x = ([], .enter stage0.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState stage0 (State.initial call)) ∧ x' = ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call)), + fun x x' => ∃ (env c0 : MIR.Lowered.Env) (s : State) (env' c0' : MIR.Lowered.Env), x = ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 1 4, env, s) ∧ x' = ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0', [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env', s) ∧ env' 0 = env 0 ∧ env' 10 = env 0 ∧ env' 15 = env 30, + fun x x' => ∃ (env c0 : MIR.Lowered.Env) (s : State) (env' c0' : MIR.Lowered.Env), x = ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 1 4, env, s) ∧ x' = ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0', [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env', s) ∧ env' 0 = env 0 ∧ env' 10 = env 0 ∧ env' 15 = env 30, + fun x x' => ∃ (env c0 : MIR.Lowered.Env) (s : State) (env' c0' : MIR.Lowered.Env), x = ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 1 4, env, s) ∧ x' = ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0', [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env', s) ∧ env' 0 = env 0 ∧ env' 0 = env 0 ∧ env' 30 = env 30, + fun x x' => ∃ (env c0 : MIR.Lowered.Env) (s : State) (env' c0' : MIR.Lowered.Env), x = ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 1 4, env, s) ∧ x' = ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0', [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env', s) ∧ env' 0 = env 0 ∧ env' 0 = env 0 ∧ env' 30 = env 30, + fun x x' => ∃ (env c0 : MIR.Lowered.Env) (s : State) (env' c0' : MIR.Lowered.Env), x = ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s) ∧ x' = ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0', [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env', s) ∧ env' 0 = env 0 ∧ env' 10 = env 10 ∧ env' 15 = env 15, + fun x x' => ∃ (env c0 : MIR.Lowered.Env) (s : State) (env' c0' : MIR.Lowered.Env), x = ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s) ∧ x' = ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0', [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env', s) ∧ env' 0 = env 0 ∧ env' 10 = env 10 ∧ env' 15 = env 15, + fun x x' => ∃ (env c0 : MIR.Lowered.Env) (s : State) (env' c0' : MIR.Lowered.Env), x = ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s) ∧ x' = ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0', [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env', s) ∧ env' 0 = env 0 ∧ env' 0 = env 10 ∧ env' 30 = env 15, + fun x x' => ∃ (env c0 : MIR.Lowered.Env) (s : State) (env' c0' : MIR.Lowered.Env), x = ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s) ∧ x' = ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0', [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env', s) ∧ env' 0 = env 0 ∧ env' 0 = env 10 ∧ env' 30 = env 15] + +theorem mir1_mk1 {call : Call} {env c0 : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' c0' : MIR.Lowered.Env), y = ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0', [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env', s) ∧ env' 0 = env 0 ∧ env' 10 = env 0 ∧ env' 15 = env 30) : + ∃ Q ∈ mir1_rels call, Q ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 1 4, env, s) y := by + obtain ⟨env', c0', h0, h1, h2, h3⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨env, c0, s, env', c0', rfl, h0, h1, h2, h3⟩ + +theorem mir1_mk2 {call : Call} {env c0 : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' c0' : MIR.Lowered.Env), y = ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0', [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env', s) ∧ env' 0 = env 0 ∧ env' 10 = env 0 ∧ env' 15 = env 30) : + ∃ Q ∈ mir1_rels call, Q ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 1 4, env, s) y := by + obtain ⟨env', c0', h0, h1, h2, h3⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨env, c0, s, env', c0', rfl, h0, h1, h2, h3⟩ + +theorem mir1_mk3 {call : Call} {env c0 : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' c0' : MIR.Lowered.Env), y = ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0', [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env', s) ∧ env' 0 = env 0 ∧ env' 0 = env 0 ∧ env' 30 = env 30) : + ∃ Q ∈ mir1_rels call, Q ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 1 4, env, s) y := by + obtain ⟨env', c0', h0, h1, h2, h3⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _)))) ⟨env, c0, s, env', c0', rfl, h0, h1, h2, h3⟩ + +theorem mir1_mk4 {call : Call} {env c0 : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' c0' : MIR.Lowered.Env), y = ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0', [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env', s) ∧ env' 0 = env 0 ∧ env' 0 = env 0 ∧ env' 30 = env 30) : + ∃ Q ∈ mir1_rels call, Q ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 1 4, env, s) y := by + obtain ⟨env', c0', h0, h1, h2, h3⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))))) ⟨env, c0, s, env', c0', rfl, h0, h1, h2, h3⟩ + +theorem mir1_mk5 {call : Call} {env c0 : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' c0' : MIR.Lowered.Env), y = ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0', [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env', s) ∧ env' 0 = env 0 ∧ env' 10 = env 10 ∧ env' 15 = env 15) : + ∃ Q ∈ mir1_rels call, Q ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s) y := by + obtain ⟨env', c0', h0, h1, h2, h3⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _)))))) ⟨env, c0, s, env', c0', rfl, h0, h1, h2, h3⟩ + +theorem mir1_mk6 {call : Call} {env c0 : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' c0' : MIR.Lowered.Env), y = ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0', [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env', s) ∧ env' 0 = env 0 ∧ env' 10 = env 10 ∧ env' 15 = env 15) : + ∃ Q ∈ mir1_rels call, Q ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s) y := by + obtain ⟨env', c0', h0, h1, h2, h3⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))))))) ⟨env, c0, s, env', c0', rfl, h0, h1, h2, h3⟩ + +theorem mir1_mk7 {call : Call} {env c0 : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' c0' : MIR.Lowered.Env), y = ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0', [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env', s) ∧ env' 0 = env 0 ∧ env' 0 = env 10 ∧ env' 30 = env 15) : + ∃ Q ∈ mir1_rels call, Q ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s) y := by + obtain ⟨env', c0', h0, h1, h2, h3⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _)))))))) ⟨env, c0, s, env', c0', rfl, h0, h1, h2, h3⟩ + +theorem mir1_mk8 {call : Call} {env c0 : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' c0' : MIR.Lowered.Env), y = ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0', [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env', s) ∧ env' 0 = env 0 ∧ env' 0 = env 10 ∧ env' 30 = env 15) : + ∃ Q ∈ mir1_rels call, Q ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s) y := by + obtain ⟨env', c0', h0, h1, h2, h3⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))))))))) ⟨env, c0, s, env', c0', rfl, h0, h1, h2, h3⟩ + +set_option maxHeartbeats 2000000 in +theorem mir1_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([], .enter stage0.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState stage0 (State.initial call))) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB k' ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call))) := by + refine ⟨60, 69, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2, mir1_mk3, mir1_mk4, mir1_mk5, mir1_mk6, mir1_mk7, mir1_mk8] + +set_option maxHeartbeats 2000000 in +theorem mir1_seg1 (o : Oracle) (call : Call) (env c0 : MIR.Lowered.Env) (s : State) (env' c0' : MIR.Lowered.Env) (h0 : env' 0 = env 0) (h1 : env' 10 = env 0) (h2 : env' 15 = env 30) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 1 4, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB k' ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0', [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env', s)) := by + refine ⟨60, 69, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2, mir1_mk3, mir1_mk4, mir1_mk5, mir1_mk6, mir1_mk7, mir1_mk8] + +set_option maxHeartbeats 2000000 in +theorem mir1_seg2 (o : Oracle) (call : Call) (env c0 : MIR.Lowered.Env) (s : State) (env' c0' : MIR.Lowered.Env) (h0 : env' 0 = env 0) (h1 : env' 10 = env 0) (h2 : env' 15 = env 30) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 1 4, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB k' ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0', [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env', s)) := by + refine ⟨60, 69, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2, mir1_mk3, mir1_mk4, mir1_mk5, mir1_mk6, mir1_mk7, mir1_mk8] + +set_option maxHeartbeats 2000000 in +theorem mir1_seg3 (o : Oracle) (call : Call) (env c0 : MIR.Lowered.Env) (s : State) (env' c0' : MIR.Lowered.Env) (h0 : env' 0 = env 0) (h1 : env' 0 = env 0) (h2 : env' 30 = env 30) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 1 4, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB k' ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0', [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env', s)) := by + refine ⟨60, 69, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2, mir1_mk3, mir1_mk4, mir1_mk5, mir1_mk6, mir1_mk7, mir1_mk8] + +set_option maxHeartbeats 2000000 in +theorem mir1_seg4 (o : Oracle) (call : Call) (env c0 : MIR.Lowered.Env) (s : State) (env' c0' : MIR.Lowered.Env) (h0 : env' 0 = env 0) (h1 : env' 0 = env 0) (h2 : env' 30 = env 30) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 1 4, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB k' ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0', [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env', s)) := by + refine ⟨60, 69, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2, mir1_mk3, mir1_mk4, mir1_mk5, mir1_mk6, mir1_mk7, mir1_mk8] + +set_option maxHeartbeats 2000000 in +theorem mir1_seg5 (o : Oracle) (call : Call) (env c0 : MIR.Lowered.Env) (s : State) (env' c0' : MIR.Lowered.Env) (h0 : env' 0 = env 0) (h1 : env' 10 = env 10) (h2 : env' 15 = env 15) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB k' ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0', [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env', s)) := by + refine ⟨60, 69, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2, mir1_mk3, mir1_mk4, mir1_mk5, mir1_mk6, mir1_mk7, mir1_mk8] + +set_option maxHeartbeats 2000000 in +theorem mir1_seg6 (o : Oracle) (call : Call) (env c0 : MIR.Lowered.Env) (s : State) (env' c0' : MIR.Lowered.Env) (h0 : env' 0 = env 0) (h1 : env' 10 = env 10) (h2 : env' 15 = env 15) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB k' ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0', [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env', s)) := by + refine ⟨60, 69, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2, mir1_mk3, mir1_mk4, mir1_mk5, mir1_mk6, mir1_mk7, mir1_mk8] + +set_option maxHeartbeats 2000000 in +theorem mir1_seg7 (o : Oracle) (call : Call) (env c0 : MIR.Lowered.Env) (s : State) (env' c0' : MIR.Lowered.Env) (h0 : env' 0 = env 0) (h1 : env' 0 = env 10) (h2 : env' 30 = env 15) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB k' ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0', [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env', s)) := by + refine ⟨60, 69, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2, mir1_mk3, mir1_mk4, mir1_mk5, mir1_mk6, mir1_mk7, mir1_mk8] + +set_option maxHeartbeats 2000000 in +theorem mir1_seg8 (o : Oracle) (call : Call) (env c0 : MIR.Lowered.Env) (s : State) (env' c0' : MIR.Lowered.Env) (h0 : env' 0 = env 0) (h1 : env' 0 = env 10) (h2 : env' 30 = env 15) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB k' ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0', [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env', s)) := by + refine ⟨60, 69, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2, mir1_mk3, mir1_mk4, mir1_mk5, mir1_mk6, mir1_mk7, mir1_mk8] + +theorem mir1_segments (o : Oracle) (call : Call) : + ∀ P ∈ mir1_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k x) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB k' x') := by + intro P mem x x' holds + simp only [mir1_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact mir1_seg0 o call + · obtain ⟨env, c0, s, env', c0', rfl, rfl, h0, h1, h2⟩ := holds + exact mir1_seg1 o call env c0 s env' c0' h0 h1 h2 + · obtain ⟨env, c0, s, env', c0', rfl, rfl, h0, h1, h2⟩ := holds + exact mir1_seg2 o call env c0 s env' c0' h0 h1 h2 + · obtain ⟨env, c0, s, env', c0', rfl, rfl, h0, h1, h2⟩ := holds + exact mir1_seg3 o call env c0 s env' c0' h0 h1 h2 + · obtain ⟨env, c0, s, env', c0', rfl, rfl, h0, h1, h2⟩ := holds + exact mir1_seg4 o call env c0 s env' c0' h0 h1 h2 + · obtain ⟨env, c0, s, env', c0', rfl, rfl, h0, h1, h2⟩ := holds + exact mir1_seg5 o call env c0 s env' c0' h0 h1 h2 + · obtain ⟨env, c0, s, env', c0', rfl, rfl, h0, h1, h2⟩ := holds + exact mir1_seg6 o call env c0 s env' c0' h0 h1 h2 + · obtain ⟨env, c0, s, env', c0', rfl, rfl, h0, h1, h2⟩ := holds + exact mir1_seg7 o call env c0 s env' c0' h0 h1 h2 + · obtain ⟨env, c0, s, env', c0', rfl, rfl, h0, h1, h2⟩ := holds + exact mir1_seg8 o call env c0 s env' c0' h0 h1 h2 + +/-- `stage0` and `mir1` simulated through their cut points on every call. -/ +def mir1_sim (o : Oracle) : + CutPoint.LayerSim MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o stage0 mir1 anyCall where + σ := MIR.Lowered.Frame + τ := MIR.Lowered.Frame + step call := MIR.Lowered.moduleBlock o call stage0 + step' call := MIR.Lowered.moduleBlock o call mir1 + init call := ([], .enter stage0.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState stage0 (State.initial call)) + init' call := ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call)) + runs _ _ := rfl + runs' _ _ := rfl + cut := mir1_cutA + cut' := mir1_cutB + Rel call := fun x x' => ∃ P ∈ mir1_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (mir1_segments o call) + +/-- Every end of `stage0` on a call is matched by an agreeing end of `mir1`. -/ +theorem mir1_certified (o : Oracle) : + Certified MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o stage0 mir1 anyCall := + (mir1_sim o).certified + +/-- Every end of `mir1` on a call is matched by an agreeing end of `stage0`. -/ +theorem mir1_certified_back (o : Oracle) : + Certified MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o mir1 stage0 anyCall := + (mir1_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Callsqrt.mir1_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_certified + +/-- info: 'SolarTV.Milestone.Callsqrt.mir1_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_certified_back + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Runs/Sched.lean b/Certified/callsqrt/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..a76aa7bf --- /dev/null +++ b/Certified/callsqrt/Proofs/Runs/Sched.lean @@ -0,0 +1,157 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import callsqrt.gen.CallSqrt.Sched +import callsqrt.gen.CallSqrt.Mir1 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.Callsqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def sched_cutA : MIR.Lowered.Frame → Bool := fun x => + match x.2.1 with + | .enter f _ b => (f == 2 && b == 4) + | .resume .. => false + +theorem sched_cutA_enter (rs : List MIR.Lowered.Return) (f p b : Nat) (env : MIR.Lowered.Env) (s : State) : + sched_cutA (rs, .enter f p b, env, s) = ((f == 2 && b == 4)) := rfl + +theorem sched_cutA_resume (rs : List MIR.Lowered.Return) (f b : Nat) (is : List MIR.Lowered.Inst) (t : MIR.Lowered.Terminator) (env : MIR.Lowered.Env) (s : State) : + sched_cutA (rs, .resume f b is t, env, s) = false := rfl + +def sched_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 15 + +theorem sched_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + sched_cutB (b, st, s) = (b == 15) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def sched_rels (call : Call) : List (MIR.Lowered.Frame → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call)) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (env c0 : MIR.Lowered.Env) (s : State) (j0 : EvmRules.Word), x = ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s) ∧ x' = (15, [env 10, env 15, (BitVec.ofNat 256 6), env 0, j0], s), + fun x x' => ∃ (env c0 : MIR.Lowered.Env) (s : State) (j0 : EvmRules.Word), x = ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env, s) ∧ x' = (15, [env 0, env 30, (BitVec.ofNat 256 6), env 0, j0], s), + fun x x' => ∃ (env c0 : MIR.Lowered.Env) (s : State) (j0 : EvmRules.Word), x = ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s) ∧ x' = (15, [env 10, env 15, (BitVec.ofNat 256 10), env 0, j0], s), + fun x x' => ∃ (env c0 : MIR.Lowered.Env) (s : State) (j0 : EvmRules.Word), x = ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env, s) ∧ x' = (15, [env 0, env 30, (BitVec.ofNat 256 10), env 0, j0], s)] + +theorem sched_mk1 {call : Call} {env c0 : MIR.Lowered.Env} {s : State} {y : Nat × EVM.Stack × State} + (h : ∃ (j0 : EvmRules.Word), y = (15, [env 10, env 15, (BitVec.ofNat 256 6), env 0, j0], s)) : + ∃ Q ∈ sched_rels call, Q ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s) y := by + obtain ⟨j0, h0⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨env, c0, s, j0, rfl, h0⟩ + +theorem sched_mk2 {call : Call} {env c0 : MIR.Lowered.Env} {s : State} {y : Nat × EVM.Stack × State} + (h : ∃ (j0 : EvmRules.Word), y = (15, [env 0, env 30, (BitVec.ofNat 256 6), env 0, j0], s)) : + ∃ Q ∈ sched_rels call, Q ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env, s) y := by + obtain ⟨j0, h0⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨env, c0, s, j0, rfl, h0⟩ + +theorem sched_mk3 {call : Call} {env c0 : MIR.Lowered.Env} {s : State} {y : Nat × EVM.Stack × State} + (h : ∃ (j0 : EvmRules.Word), y = (15, [env 10, env 15, (BitVec.ofNat 256 10), env 0, j0], s)) : + ∃ Q ∈ sched_rels call, Q ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s) y := by + obtain ⟨j0, h0⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _)))) ⟨env, c0, s, j0, rfl, h0⟩ + +theorem sched_mk4 {call : Call} {env c0 : MIR.Lowered.Env} {s : State} {y : Nat × EVM.Stack × State} + (h : ∃ (j0 : EvmRules.Word), y = (15, [env 0, env 30, (BitVec.ofNat 256 10), env 0, j0], s)) : + ∃ Q ∈ sched_rels call, Q ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env, s) y := by + obtain ⟨j0, h0⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))))) ⟨env, c0, s, j0, rfl, h0⟩ + +set_option maxHeartbeats 2000000 in +theorem sched_seg0 (o : Oracle) (call : Call) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ sched_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir1) sched_cutA k ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call))) + (seg (EVM.Program.block o call sched) sched_cutB k' (0, [], State.initial call)) := by + refine ⟨69, 39, ?_⟩ + sym_seg [sched_cutA_enter, sched_cutA_resume, sched_cutB_mk] [sched_mk1, sched_mk2, sched_mk3, sched_mk4] + +set_option maxHeartbeats 2000000 in +theorem sched_seg1 (o : Oracle) (call : Call) (env c0 : MIR.Lowered.Env) (s : State) (j0 : EvmRules.Word) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ sched_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir1) sched_cutA k ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s)) + (seg (EVM.Program.block o call sched) sched_cutB k' (15, [env 10, env 15, (BitVec.ofNat 256 6), env 0, j0], s)) := by + refine ⟨69, 39, ?_⟩ + sym_seg [sched_cutA_enter, sched_cutA_resume, sched_cutB_mk] [sched_mk1, sched_mk2, sched_mk3, sched_mk4] + +set_option maxHeartbeats 2000000 in +theorem sched_seg2 (o : Oracle) (call : Call) (env c0 : MIR.Lowered.Env) (s : State) (j0 : EvmRules.Word) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ sched_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir1) sched_cutA k ([⟨0, 0, (some 2), [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]], .branch (.value 6) 1 2, c0, [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env, s)) + (seg (EVM.Program.block o call sched) sched_cutB k' (15, [env 0, env 30, (BitVec.ofNat 256 6), env 0, j0], s)) := by + refine ⟨69, 39, ?_⟩ + sym_seg [sched_cutA_enter, sched_cutA_resume, sched_cutB_mk] [sched_mk1, sched_mk2, sched_mk3, sched_mk4] + +set_option maxHeartbeats 2000000 in +theorem sched_seg3 (o : Oracle) (call : Call) (env c0 : MIR.Lowered.Env) (s : State) (j0 : EvmRules.Word) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ sched_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir1) sched_cutA k ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 9 4, env, s)) + (seg (EVM.Program.block o call sched) sched_cutB k' (15, [env 10, env 15, (BitVec.ofNat 256 10), env 0, j0], s)) := by + refine ⟨69, 39, ?_⟩ + sym_seg [sched_cutA_enter, sched_cutA_resume, sched_cutB_mk] [sched_mk1, sched_mk2, sched_mk3, sched_mk4] + +set_option maxHeartbeats 2000000 in +theorem sched_seg4 (o : Oracle) (call : Call) (env c0 : MIR.Lowered.Env) (s : State) (j0 : EvmRules.Word) : + ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ sched_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir1) sched_cutA k ([⟨1, 0, (some 4), [.effect none .mstore [.const 0, .value 4]], .ret (.const 0) (.const 32), c0, [], none⟩], MIR.Lowered.Pos.enter 2 12 4, env, s)) + (seg (EVM.Program.block o call sched) sched_cutB k' (15, [env 0, env 30, (BitVec.ofNat 256 10), env 0, j0], s)) := by + refine ⟨69, 39, ?_⟩ + sym_seg [sched_cutA_enter, sched_cutA_resume, sched_cutB_mk] [sched_mk1, sched_mk2, sched_mk3, sched_mk4] + +theorem sched_segments (o : Oracle) (call : Call) : + ∀ P ∈ sched_rels call, ∀ x x', P x x' → ∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ sched_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir1) sched_cutA k x) + (seg (EVM.Program.block o call sched) sched_cutB k' x') := by + intro P mem x x' holds + simp only [sched_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact sched_seg0 o call + · obtain ⟨env, c0, s, j0, rfl, rfl⟩ := holds + exact sched_seg1 o call env c0 s j0 + · obtain ⟨env, c0, s, j0, rfl, rfl⟩ := holds + exact sched_seg2 o call env c0 s j0 + · obtain ⟨env, c0, s, j0, rfl, rfl⟩ := holds + exact sched_seg3 o call env c0 s j0 + · obtain ⟨env, c0, s, j0, rfl, rfl⟩ := holds + exact sched_seg4 o call env c0 s j0 + +/-- `mir1` and `sched` simulated through their cut points on every call. -/ +def sched_sim (o : Oracle) : + CutPoint.LayerSim MIR.Lowered.moduleLayer EVM.Program.layer o mir1 sched anyCall where + σ := MIR.Lowered.Frame + τ := Nat × EVM.Stack × State + step call := MIR.Lowered.moduleBlock o call mir1 + step' call := EVM.Program.block o call sched + init call := ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call)) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := sched_cutA + cut' := sched_cutB + Rel call := fun x x' => ∃ P ∈ sched_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each (sched_segments o call) + +/-- Every end of `mir1` on a call is matched by an agreeing end of `sched`. -/ +theorem sched_certified (o : Oracle) : + Certified MIR.Lowered.moduleLayer EVM.Program.layer o mir1 sched anyCall := + (sched_sim o).certified + +/-- Every end of `sched` on a call is matched by an agreeing end of `mir1`. -/ +theorem sched_certified_back (o : Oracle) : + Certified EVM.Program.layer MIR.Lowered.moduleLayer o sched mir1 anyCall := + (sched_sim o).certified_back + +/-- info: 'SolarTV.Milestone.Callsqrt.sched_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_certified + +/-- info: 'SolarTV.Milestone.Callsqrt.sched_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_certified_back + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/Proofs/Stages.lean b/Certified/callsqrt/Proofs/Stages.lean new file mode 100644 index 00000000..e975b7e3 --- /dev/null +++ b/Certified/callsqrt/Proofs/Stages.lean @@ -0,0 +1,57 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import callsqrt.Proofs.Runs.Mir1 +import callsqrt.Proofs.Runs.Sched +import callsqrt.Proofs.Runs.Evm1 +import callsqrt.Proofs.Runs.Evm2 +import callsqrt.Proofs.Runs.Evm3 +import callsqrt.Proofs.Runs.Evm4 +import callsqrt.Proofs.Runs.Evm5 +import callsqrt.Proofs.Runs.Evm6 +import callsqrt.Proofs.Runs.Evm7 +import callsqrt.Proofs.Runs.Evm8 +import callsqrt.Proofs.Runs.Evm9 +import callsqrt.Proofs.Runs.Evm10 +import callsqrt.Proofs.Runs.Evm11 +import callsqrt.Proofs.Runs.Evm12 +import callsqrt.Proofs.Runs.Evm13 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `CallSqrt`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle through cut points, whatever number of times its loops run, and chained from the first lowered MIR `stage0` to the final EVM IR `evm13`, both ways. -/ + +namespace SolarTV.Milestone.Callsqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1], sched, [evm1, evm2, evm3, evm4, evm5, evm6, evm7, evm8, evm9, evm10, evm11, evm12, evm13]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, each through cut points, chained by the library's composition, on every call. -/ +theorem callsqrt_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm13 anyCall := + mir_to_evmir_certified o anyCall compilation ⟨mir1_certified o, trivial⟩ (sched_certified o) + ⟨evm1_certified o, evm2_certified o, evm3_certified o, evm4_certified o, evm5_certified o, evm6_certified o, evm7_certified o, evm8_certified o, evm9_certified o, evm10_certified o, evm11_certified o, evm12_certified o, evm13_certified o, trivial⟩ + +/-- Every end of the first lowered MIR is matched by an agreeing end of the final EVM IR, on every call. -/ +theorem callsqrt_certified (o : Oracle) : + Certified MIR.Lowered.moduleLayer EVM.Program.layer o stage0 evm13 anyCall := + ((((((((((((((mir1_certified o).trans (sched_certified o)).trans (evm1_certified o)).trans (evm2_certified o)).trans (evm3_certified o)).trans (evm4_certified o)).trans (evm5_certified o)).trans (evm6_certified o)).trans (evm7_certified o)).trans (evm8_certified o)).trans (evm9_certified o)).trans (evm10_certified o)).trans (evm11_certified o)).trans (evm12_certified o)).trans (evm13_certified o) + +/-- Every end of the final EVM IR is matched by an agreeing end of the first lowered MIR, on every call: one ends exactly when the other does. -/ +theorem callsqrt_certified_back (o : Oracle) : + Certified EVM.Program.layer MIR.Lowered.moduleLayer o evm13 stage0 anyCall := + ((((((((((((((evm13_certified_back o).trans (evm12_certified_back o)).trans (evm11_certified_back o)).trans (evm10_certified_back o)).trans (evm9_certified_back o)).trans (evm8_certified_back o)).trans (evm7_certified_back o)).trans (evm6_certified_back o)).trans (evm5_certified_back o)).trans (evm4_certified_back o)).trans (evm3_certified_back o)).trans (evm2_certified_back o)).trans (evm1_certified_back o)).trans (sched_certified_back o)).trans (mir1_certified_back o) + +/-- info: 'SolarTV.Milestone.Callsqrt.callsqrt_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms callsqrt_mir_to_evmir + +/-- info: 'SolarTV.Milestone.Callsqrt.callsqrt_certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms callsqrt_certified + +/-- info: 'SolarTV.Milestone.Callsqrt.callsqrt_certified_back' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms callsqrt_certified_back + +end SolarTV.Milestone.Callsqrt diff --git a/Certified/callsqrt/bytecode.hex b/Certified/callsqrt/bytecode.hex new file mode 100644 index 00000000..8b37ffdf --- /dev/null +++ b/Certified/callsqrt/bytecode.hex @@ -0,0 +1 @@ +6024361034176022575f3560e01c8063b3de648b146026578063e420264a146048575b5f5ffd5b60043560395b60038211605b57905f1090565b6001018015609b575f5260205ff35b60043560011c6054602c565b5f5260205ff35b8160011c600181015f1982101560b45783915090808210607a57925050565b50801560ae57808304818101908110609b5760011c90808210607a57925050565b60115b602052634e487b715f526024601cfd5b6012609e565b506d03080000000200000001000000016020526040525f1960605263ed572b275f526064601cfd diff --git a/Certified/callsqrt/callsqrt.sol b/Certified/callsqrt/callsqrt.sol new file mode 100644 index 00000000..20edef32 --- /dev/null +++ b/Certified/callsqrt/callsqrt.sol @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-3.0 +// Uniswap/v2-core@6a9e7c9 contracts/libraries/Math.sol as solar-tv/uniswap-v2/port.py writes it, then an entry point. +pragma solidity ^0.8.0; + +// a library for performing various math operations + +library Math { + function min(uint x, uint y) internal pure returns (uint z) { + z = x < y ? x : y; + } + + // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) + function sqrt(uint y) internal pure returns (uint z) { + if (y > 3) { + z = y; + uint x = y / 2 + 1; + while (x < z) { + z = x; + x = (y / x + x) / 2; + } + } else if (y != 0) { + z = 1; + } + } +} + +/// Math.sqrt called from two entry points, so that it stays an internal function whose loop +/// the calls enter. +contract CallSqrt { + function f(uint256 y) external pure returns (uint256) { + return Math.sqrt(y) + 1; + } + + function g(uint256 a) external pure returns (uint256) { + return Math.sqrt(a >> 1); + } +} diff --git a/Certified/callsqrt/gen/CallSqrt/Bytecode.lean b/Certified/callsqrt/gen/CallSqrt/Bytecode.lean new file mode 100644 index 00000000..b0685305 --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Bytecode.lean @@ -0,0 +1,27 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x60, 0x24, 0x36, 0x10, 0x34, 0x17, 0x60, 0x22, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, + 0xb3, 0xde, 0x64, 0x8b, 0x14, 0x60, 0x26, 0x57, 0x80, 0x63, 0xe4, 0x20, 0x26, 0x4a, 0x14, 0x60, + 0x48, 0x57, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x60, 0x04, 0x35, 0x60, 0x39, 0x5b, 0x60, 0x03, 0x82, + 0x11, 0x60, 0x5b, 0x57, 0x90, 0x5f, 0x10, 0x90, 0x56, 0x5b, 0x60, 0x01, 0x01, 0x80, 0x15, 0x60, + 0x9b, 0x57, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x04, 0x35, 0x60, 0x01, 0x1c, 0x60, + 0x54, 0x60, 0x2c, 0x56, 0x5b, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x81, 0x60, 0x01, 0x1c, + 0x60, 0x01, 0x81, 0x01, 0x5f, 0x19, 0x82, 0x10, 0x15, 0x60, 0xb4, 0x57, 0x83, 0x91, 0x50, 0x90, + 0x80, 0x82, 0x10, 0x60, 0x7a, 0x57, 0x92, 0x50, 0x50, 0x56, 0x5b, 0x50, 0x80, 0x15, 0x60, 0xae, + 0x57, 0x80, 0x83, 0x04, 0x81, 0x81, 0x01, 0x90, 0x81, 0x10, 0x60, 0x9b, 0x57, 0x60, 0x01, 0x1c, + 0x90, 0x80, 0x82, 0x10, 0x60, 0x7a, 0x57, 0x92, 0x50, 0x50, 0x56, 0x5b, 0x60, 0x11, 0x5b, 0x60, + 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, 0x60, 0x1c, 0xfd, 0x5b, 0x60, + 0x12, 0x60, 0x9e, 0x56, 0x5b, 0x50, 0x6d, 0x03, 0x08, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0x01, 0x60, 0x20, 0x52, 0x60, 0x40, 0x52, 0x5f, 0x19, 0x60, 0x60, 0x52, + 0x63, 0xed, 0x57, 0x2b, 0x27, 0x5f, 0x52, 0x60, 0x64, 0x60, 0x1c, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "6024361034176022575f3560e01c8063b3de648b146026578063e420264a146048575b5f5ffd5b60043560395b60038211605b57905f1090565b6001018015609b575f5260205ff35b60043560011c6054602c565b5f5260205ff35b8160011c600181015f1982101560b45783915090808210607a57925050565b50801560ae57808304818101908110609b5760011c90808210607a57925050565b60115b602052634e487b715f526024601cfd5b6012609e565b506d03080000000200000001000000016020526040525f1960605263ed572b275f526064601cfd" + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/Evm1.lean b/Certified/callsqrt/gen/CallSqrt/Evm1.lean new file mode 100644 index 00000000..c35687f7 --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Evm1.lean @@ -0,0 +1,172 @@ +-- solar-lean-stage: kind=evm index=1 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .effect .callvalue 0, + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xb3de648b)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe420264a)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .pushLabel 3, + .jump 7], + -- bb6 + [.op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .op (.stack .shr), + .pushLabel 6, + .jump 7], + -- bb10 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 3)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 8, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .lt), + .jump 10], + -- bb13 + [.op (.stack (.dup 1)), + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.dup 3)), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 9], + -- bb15 + [.op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 11, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 10], + -- bb16 + [.op (.stack (.swap 0)), + .jumpDyn], + -- bb17 + [.op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 13, + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .jump 9], + -- bb20 + [.op (.stack (.push 18)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb21 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb22 + [.op (.stack .pop), + .op (.stack (.push 0x308000000020000000100000001)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/Evm10.lean b/Certified/callsqrt/gen/CallSqrt/Evm10.lean new file mode 100644 index 00000000..9e81cc1d --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Evm10.lean @@ -0,0 +1,156 @@ +-- solar-lean-stage: kind=evm index=10 pass=stack-reschedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The runtime EVM IR after `stack-reschedule`. -/ +def evm10 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .effect .callvalue 0, + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xb3de648b)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe420264a)), + .op (.stack .eq), + .jumpi 6, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .pushLabel 5, + .jump 3], + -- bb11 + [.op (.stack (.push 3)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 8, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .lt), + .jump 4], + -- bb16 + [.op (.stack (.swap 0)), + .jumpDyn], + -- bb6 + [.op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 11, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .op (.stack .shr), + .pushLabel 7, + .jump 3], + -- bb10 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.dup 1)), + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.dup 3)), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 9], + -- bb15 + [.op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 10, + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 4], + -- bb17 + [.op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 13, + .op (.stack (.dup 0)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 11, + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .jump 9], + -- bb8 + [.op (.stack (.push 17)), + .jump 12], + -- bb23 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb20 + [.op (.stack (.push 18)), + .jump 12], + -- bb22 + [.op (.stack .pop), + .op (.stack (.push 0x308000000020000000100000001)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/Evm11.lean b/Certified/callsqrt/gen/CallSqrt/Evm11.lean new file mode 100644 index 00000000..0a58ef7c --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Evm11.lean @@ -0,0 +1,155 @@ +-- solar-lean-stage: kind=evm index=11 pass=inline-returns +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The runtime EVM IR after `inline-returns`. -/ +def evm11 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .effect .callvalue 0, + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xb3de648b)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe420264a)), + .op (.stack .eq), + .jumpi 6, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .pushLabel 5, + .jump 3], + -- bb11 + [.op (.stack (.push 3)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 8, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .lt), + .jump 4], + -- bb16 + [.op (.stack (.swap 0)), + .jumpDyn], + -- bb6 + [.op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 11, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .op (.stack .shr), + .pushLabel 7, + .jump 3], + -- bb10 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.dup 1)), + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.dup 3)), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 9], + -- bb15 + [.op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 10, + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack .pop), + .jumpDyn], + -- bb17 + [.op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 13, + .op (.stack (.dup 0)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 11, + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .jump 9], + -- bb8 + [.op (.stack (.push 17)), + .jump 12], + -- bb23 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb20 + [.op (.stack (.push 18)), + .jump 12], + -- bb22 + [.op (.stack .pop), + .op (.stack (.push 0x308000000020000000100000001)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/Evm12.lean b/Certified/callsqrt/gen/CallSqrt/Evm12.lean new file mode 100644 index 00000000..ff8b5e6b --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Evm12.lean @@ -0,0 +1,162 @@ +-- solar-lean-stage: kind=evm index=12 pass=copy-loop-blocks +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The runtime EVM IR after `copy-loop-blocks`. -/ +def evm12 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .effect .callvalue 0, + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xb3de648b)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe420264a)), + .op (.stack .eq), + .jumpi 6, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .pushLabel 5, + .jump 3], + -- bb11 + [.op (.stack (.push 3)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 8, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .lt), + .jump 4], + -- bb16 + [.op (.stack (.swap 0)), + .jumpDyn], + -- bb6 + [.op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 11, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .op (.stack .shr), + .pushLabel 7, + .jump 3], + -- bb10 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.dup 1)), + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.dup 3)), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 9], + -- bb15 + [.op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 10, + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack .pop), + .jumpDyn], + -- bb17 + [.op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 13, + .op (.stack (.dup 0)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 11, + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 10, + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack .pop), + .jumpDyn], + -- bb8 + [.op (.stack (.push 17)), + .jump 12], + -- bb23 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb20 + [.op (.stack (.push 18)), + .jump 12], + -- bb22 + [.op (.stack .pop), + .op (.stack (.push 0x308000000020000000100000001)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/Evm13.lean b/Certified/callsqrt/gen/CallSqrt/Evm13.lean new file mode 100644 index 00000000..070c6fd0 --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Evm13.lean @@ -0,0 +1,158 @@ +-- solar-lean-stage: kind=evm index=13 pass=cfg-simplify +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The runtime EVM IR after `cfg-simplify`. -/ +def evm13 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .effect .callvalue 0, + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xb3de648b)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe420264a)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .pushLabel 4, + .jump 3], + -- bb11 + [.op (.stack (.push 3)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 7, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.swap 0)), + .jumpDyn], + -- bb6 + [.op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 9, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .op (.stack .shr), + .pushLabel 6, + .jump 3], + -- bb10 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.dup 1)), + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack .iszero), + .jumpi 12, + .op (.stack (.dup 3)), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 8, + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack .pop), + .jumpDyn], + -- bb17 + [.op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 11, + .op (.stack (.dup 0)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 9, + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 8, + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack .pop), + .jumpDyn], + -- bb8 + [.op (.stack (.push 17)), + .jump 10], + -- bb23 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb20 + [.op (.stack (.push 18)), + .jump 10], + -- bb22 + [.op (.stack .pop), + .op (.stack (.push 0x308000000020000000100000001)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/Evm2.lean b/Certified/callsqrt/gen/CallSqrt/Evm2.lean new file mode 100644 index 00000000..a8d5202d --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Evm2.lean @@ -0,0 +1,174 @@ +-- solar-lean-stage: kind=evm index=2 pass=compact-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The runtime EVM IR after `compact-pushes`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .effect .callvalue 0, + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xb3de648b)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe420264a)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .pushLabel 3, + .jump 7], + -- bb6 + [.op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .op (.stack .shr), + .pushLabel 6, + .jump 7], + -- bb10 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 3)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 8, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .lt), + .jump 10], + -- bb13 + [.op (.stack (.dup 1)), + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.dup 3)), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 9], + -- bb15 + [.op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 11, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 10], + -- bb16 + [.op (.stack (.swap 0)), + .jumpDyn], + -- bb17 + [.op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 13, + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .jump 9], + -- bb20 + [.op (.stack (.push 18)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb21 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb22 + [.op (.stack .pop), + .op (.stack (.push 0x308000000020000000100000001)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/Evm3.lean b/Certified/callsqrt/gen/CallSqrt/Evm3.lean new file mode 100644 index 00000000..45eb1da3 --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Evm3.lean @@ -0,0 +1,174 @@ +-- solar-lean-stage: kind=evm index=3 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The runtime EVM IR after `block-layout`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .effect .callvalue 0, + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xb3de648b)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe420264a)), + .op (.stack .eq), + .jumpi 6, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .pushLabel 5, + .jump 3], + -- bb11 + [.op (.stack (.push 3)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 8, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .lt), + .jump 4], + -- bb16 + [.op (.stack (.swap 0)), + .jumpDyn], + -- bb6 + [.op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 11, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .op (.stack .shr), + .pushLabel 7, + .jump 3], + -- bb10 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.dup 1)), + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.dup 3)), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 9], + -- bb15 + [.op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 10, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 4], + -- bb17 + [.op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 13, + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .jump 9], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb20 + [.op (.stack (.push 18)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb21 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb22 + [.op (.stack .pop), + .op (.stack (.push 0x308000000020000000100000001)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/Evm4.lean b/Certified/callsqrt/gen/CallSqrt/Evm4.lean new file mode 100644 index 00000000..ab885dab --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Evm4.lean @@ -0,0 +1,166 @@ +-- solar-lean-stage: kind=evm index=4 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .effect .callvalue 0, + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xb3de648b)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe420264a)), + .op (.stack .eq), + .jumpi 6, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .pushLabel 5, + .jump 3], + -- bb11 + [.op (.stack (.push 3)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 8, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .lt), + .jump 4], + -- bb16 + [.op (.stack (.swap 0)), + .jumpDyn], + -- bb6 + [.op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 11, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .op (.stack .shr), + .pushLabel 7, + .jump 3], + -- bb10 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.dup 1)), + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.dup 3)), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 9], + -- bb15 + [.op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 10, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 4], + -- bb17 + [.op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 13, + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .jump 9], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb20 + [.op (.stack (.push 18)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb21 + [.jump 11], + -- bb22 + [.op (.stack .pop), + .op (.stack (.push 0x308000000020000000100000001)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/Evm5.lean b/Certified/callsqrt/gen/CallSqrt/Evm5.lean new file mode 100644 index 00000000..262554dc --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Evm5.lean @@ -0,0 +1,164 @@ +-- solar-lean-stage: kind=evm index=5 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .effect .callvalue 0, + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xb3de648b)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe420264a)), + .op (.stack .eq), + .jumpi 6, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .pushLabel 5, + .jump 3], + -- bb11 + [.op (.stack (.push 3)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 8, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .lt), + .jump 4], + -- bb16 + [.op (.stack (.swap 0)), + .jumpDyn], + -- bb6 + [.op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 11, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .op (.stack .shr), + .pushLabel 7, + .jump 3], + -- bb10 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.dup 1)), + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack .iszero), + .jumpi 13, + .op (.stack (.dup 3)), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 9], + -- bb15 + [.op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 10, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 4], + -- bb17 + [.op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 11, + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .jump 9], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb20 + [.op (.stack (.push 18)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb22 + [.op (.stack .pop), + .op (.stack (.push 0x308000000020000000100000001)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/Evm6.lean b/Certified/callsqrt/gen/CallSqrt/Evm6.lean new file mode 100644 index 00000000..798148c8 --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Evm6.lean @@ -0,0 +1,159 @@ +-- solar-lean-stage: kind=evm index=6 pass=tail-merge +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The runtime EVM IR after `tail-merge`. -/ +def evm6 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .effect .callvalue 0, + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xb3de648b)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe420264a)), + .op (.stack .eq), + .jumpi 6, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .pushLabel 5, + .jump 3], + -- bb11 + [.op (.stack (.push 3)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 8, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .lt), + .jump 4], + -- bb16 + [.op (.stack (.swap 0)), + .jumpDyn], + -- bb6 + [.op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 11, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .op (.stack .shr), + .pushLabel 7, + .jump 3], + -- bb10 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.dup 1)), + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack .iszero), + .jumpi 13, + .op (.stack (.dup 3)), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 9], + -- bb15 + [.op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 10, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 4], + -- bb17 + [.op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 11, + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .jump 9], + -- bb8 + [.op (.stack (.push 17)), + .jump 14], + -- bb20 + [.op (.stack (.push 18)), + .jump 14], + -- bb22 + [.op (.stack .pop), + .op (.stack (.push 0x308000000020000000100000001)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb23 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/Evm7.lean b/Certified/callsqrt/gen/CallSqrt/Evm7.lean new file mode 100644 index 00000000..b62becd9 --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Evm7.lean @@ -0,0 +1,158 @@ +-- solar-lean-stage: kind=evm index=7 pass=reorder-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The runtime EVM IR after `reorder-pushes`. -/ +def evm7 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .effect .callvalue 0, + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xb3de648b)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe420264a)), + .op (.stack .eq), + .jumpi 6, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .pushLabel 5, + .jump 3], + -- bb11 + [.op (.stack (.push 3)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 8, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .lt), + .jump 4], + -- bb16 + [.op (.stack (.swap 0)), + .jumpDyn], + -- bb6 + [.op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 11, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .op (.stack .shr), + .pushLabel 7, + .jump 3], + -- bb10 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.dup 1)), + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack .iszero), + .jumpi 13, + .op (.stack (.dup 3)), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 9], + -- bb15 + [.op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 10, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 4], + -- bb17 + [.op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 11, + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .jump 9], + -- bb8 + [.op (.stack (.push 17)), + .jump 14], + -- bb20 + [.op (.stack (.push 18)), + .jump 14], + -- bb22 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 0x308000000020000000100000001)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb23 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/Evm8.lean b/Certified/callsqrt/gen/CallSqrt/Evm8.lean new file mode 100644 index 00000000..7ef86884 --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Evm8.lean @@ -0,0 +1,157 @@ +-- solar-lean-stage: kind=evm index=8 pass=stack-normalize +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The runtime EVM IR after `stack-normalize`. -/ +def evm8 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .effect .callvalue 0, + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xb3de648b)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe420264a)), + .op (.stack .eq), + .jumpi 6, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .pushLabel 5, + .jump 3], + -- bb11 + [.op (.stack (.push 3)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 8, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .lt), + .jump 4], + -- bb16 + [.op (.stack (.swap 0)), + .jumpDyn], + -- bb6 + [.op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 11, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .op (.stack .shr), + .pushLabel 7, + .jump 3], + -- bb10 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.dup 1)), + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack .iszero), + .jumpi 13, + .op (.stack (.dup 3)), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 9], + -- bb15 + [.op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 10, + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 4], + -- bb17 + [.op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 12, + .op (.stack (.dup 0)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 11, + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .jump 9], + -- bb8 + [.op (.stack (.push 17)), + .jump 14], + -- bb20 + [.op (.stack (.push 18)), + .jump 14], + -- bb22 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 0x308000000020000000100000001)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb23 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/Evm9.lean b/Certified/callsqrt/gen/CallSqrt/Evm9.lean new file mode 100644 index 00000000..09589fbc --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Evm9.lean @@ -0,0 +1,157 @@ +-- solar-lean-stage: kind=evm index=9 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The runtime EVM IR after `block-layout`. -/ +def evm9 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .effect .callvalue 0, + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xb3de648b)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe420264a)), + .op (.stack .eq), + .jumpi 6, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .pushLabel 5, + .jump 3], + -- bb11 + [.op (.stack (.push 3)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 8, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .lt), + .jump 4], + -- bb16 + [.op (.stack (.swap 0)), + .jumpDyn], + -- bb6 + [.op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 11, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .op (.stack .shr), + .pushLabel 7, + .jump 3], + -- bb10 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.dup 1)), + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack .iszero), + .jumpi 14, + .op (.stack (.dup 3)), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 9], + -- bb15 + [.op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 10, + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 4], + -- bb17 + [.op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 13, + .op (.stack (.dup 0)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 11, + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .jump 9], + -- bb8 + [.op (.stack (.push 17)), + .jump 12], + -- bb23 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb20 + [.op (.stack (.push 18)), + .jump 12], + -- bb22 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 0x308000000020000000100000001)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/Manifest.lean b/Certified/callsqrt/gen/CallSqrt/Manifest.lean new file mode 100644 index 00000000..9e4675f6 --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Manifest.lean @@ -0,0 +1,51 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.CallSqrt.Manifest + +def sources : List (String × String) := + [("Certified/callsqrt/callsqrt.sol", "de1e97d3782481740b78753f4a9933eec66d15c015397a55b59255f9d56906d9")] + +def compiler : String := "0.8.38+commit.cb5053ab.solar.0.3.0-dev" + +def arguments : List String := + ["Certified/callsqrt/callsqrt.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/callsqrt/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "d957e4a9da2372b09f85b01a61aeb2cb18d23635520f34af608650df94a40846"), + ("Mir1", "mir1", "lower-assumes", "0f53c878c78d96eb51eb7b6d7f3e150725313c1db1d37376d77c9f61eba07295"), + ("Sched", "sched", "stack-schedule", "05e0cfec95d0970608f020da9efc3b1b9822776c587a1e053ee859e00adc82d5"), + ("Evm1", "evm1", "cfg-simplify-early", "123b70a54cd8d9a4e7ff9e7631c54e89e68ab665f26daf5e51f2cd928c2aa182"), + ("Evm2", "evm2", "compact-pushes", "b72cab1cbec9ba8609e2612062694106f129fed7794ab17958041a7ab1c2841f"), + ("Evm3", "evm3", "block-layout", "d87d8457a298d827ea00786d7b5e4b8f6b747c50cf06801a92acb43d132bae24"), + ("Evm4", "evm4", "terminal-dedup", "88fbc79ab09942584024e0b083cb61f95d2f10b04c76b39e2c661b724bf6fda4"), + ("Evm5", "evm5", "cfg-simplify-early", "cdea2f26fef17ec876b9b586f1d793072f64c6b8a1d66c37a8d3956b69dae161"), + ("Evm6", "evm6", "tail-merge", "a6140ae089622007a504fbcca937cdbdc7986e352aded3375ffcc2044a7d5fff"), + ("Evm7", "evm7", "reorder-pushes", "a08cef8ac57be384174353ab1039a5d48cfd883563eb7dc45dae2981be10698f"), + ("Evm8", "evm8", "stack-normalize", "ebc56f0092441ffad9ad87e3a961cd006a246ffecb16361662c9eb76fdd93449"), + ("Evm9", "evm9", "block-layout", "2344131c89411b0f4ff8e53be092bdbb62b864294bd5fc0c8ff864dd4ec125ef"), + ("Evm10", "evm10", "stack-reschedule", "d1859481d702db01d5db6f77c46ec8521c1dd72d237c110b975088b8f5e6028d"), + ("Evm11", "evm11", "inline-returns", "d3548ca976ebdd9ed3f28c962a5c10139f4128e76091f211d330a78fec14492c"), + ("Evm12", "evm12", "copy-loop-blocks", "ed33e32f2d052486c226fea45686fbbcfadd0d4a42c11317ced0b9a157bf95f2"), + ("Evm13", "evm13", "cfg-simplify", "c26441f33f94ab60033e1fde5b25a22ebf92b1a4e6c18ac1d7bceb113c2327c2"), + ("Bytecode", "bytecode", "assemble", "8161b3b0e3ddff3e02f5fcde0acbc91debabf4cb6cdebb20cfe0ee3f6b7de33c")] + +def bytecodeHex : String := + "6024361034176022575f3560e01c8063b3de648b146026578063e420264a146048575b5f5ffd5b60043560395b60038211605b57905f1090565b6001018015609b575f5260205ff35b60043560011c6054602c565b5f5260205ff35b8160011c600181015f1982101560b45783915090808210607a57925050565b50801560ae57808304818101908110609b5760011c90808210607a57925050565b60115b602052634e487b715f526024601cfd5b6012609e565b506d03080000000200000001000000016020526040525f1960605263ed572b275f526064601cfd" + +def bytecodeSha256 : String := "8d899f9ae46a785487daac251bee8ac1db72cded3c47a473a12115d82328fe32" + +end SolarTV.Export.CallSqrt.Manifest diff --git a/Certified/callsqrt/gen/CallSqrt/Mir1.lean b/Certified/callsqrt/gen/CallSqrt/Mir1.lean new file mode 100644 index 00000000..60740610 --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Mir1.lean @@ -0,0 +1,137 @@ +-- solar-lean-stage: kind=mir index=1 pass=lower-assumes +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The lowered MIR module after `lower-assumes`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 3, + functions := [ + -- @f + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 20) .calldataload [.const 4], + .call (some 2) 2 [.value 20], + .pure 5 .add [.value 2, .const 1], + .pure 6 .eq [.value 5, .const 0]], + .branch (.value 6) 1 2⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 5]], + .ret (.const 0) (.const 32)⟩] }, + -- @g + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 10) .calldataload [.const 4], + .pure 3 .shr [.const 1, .value 10], + .call (some 4) 2 [.value 3], + .effect none .mstore [.const 0, .value 4]], + .ret (.const 0) (.const 32)⟩] }, + -- @sqrt + { params := [0], + blocks := [ + -- bb0 + ⟨[], + [.pure 2 .gt [.value 0, .const 3]], + .branch (.value 2) 1 2⟩, + -- bb1 + ⟨[], + [.pure 5 .shr [.const 1, .value 0], + .pure 30 .add [.value 5, .const 1], + .pure 68 .lt [.value 5, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff], + .pure 70 .eq [.value 68, .const 0]], + .branch (.value 70) 11 12⟩, + -- bb2 + ⟨[], + [.ne 17 (.value 0) (.const 0), + .word 66 (.value 17)], + .jump 3⟩, + -- bb3 + ⟨[(21, [(4, .value 9), (2, .value 66)])], + [], + .leave [.value 21]⟩, + -- bb4 + ⟨[(9, [(12, .value 0), (9, .value 10)]), (10, [(12, .value 30), (9, .value 15)])], + [.pure 11 .lt [.value 10, .value 9]], + .branch (.value 11) 5 3⟩, + -- bb5 + ⟨[], + [.ne 39 (.value 10) (.const 0)], + .branch (.value 39) 7 6⟩, + -- bb6 + ⟨[], + [.effect none .mstore [.const 32, .const 18], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb7 + ⟨[], + [.pure 46 .div [.value 0, .value 10], + .pure 47 .add [.value 46, .value 10], + .pure 48 .lt [.value 47, .value 46]], + .branch (.value 48) 8 9⟩, + -- bb8 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb9 + ⟨[], + [.pure 15 .shr [.const 1, .value 47]], + .jump 4⟩, + -- bb10 + ⟨[(72, [(11, .const 0x308000000020000000100000001)]), (73, [(11, .value 5)]), (74, [(11, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)])], + [.effect none .mstore [.const 32, .value 72], + .effect none .mstore [.const 64, .value 73], + .effect none .mstore [.const 96, .value 74], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb11 + ⟨[], + [], + .jump 10⟩, + -- bb12 + ⟨[], + [], + .jump 4⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .effect (some 1) .calldatasize [], + .pure 3 .lt [.value 1, .const 36], + .word 4 (.value 3), + .pure 5 .or [.value 0, .value 4], + .ne 7 (.value 5) (.const 0)], + .branch (.value 7) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 9) .calldataload [.const 0], + .pure 11 .shr [.const 224, .value 9]], + .switch (.value 11) 1 [(.const 0xb3de648b, 3), (.const 0xe420264a, 4)]⟩, + -- bb3 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 1 []⟩] }] } + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/Sched.lean b/Certified/callsqrt/gen/CallSqrt/Sched.lean new file mode 100644 index 00000000..5ace7de2 --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Sched.lean @@ -0,0 +1,190 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .effect .callvalue 0, + .op (.stack .or), + .jumpi 4, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xb3de648b)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0xe420264a)), + .op (.stack .eq), + .jumpi 2, + .jump 4], + -- bb2 + [.jump 9], + -- bb3 + [.jump 5], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .pushLabel 6, + .jump 11], + -- bb6 + [.op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 8, + .jump 7], + -- bb7 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .op (.stack .shr), + .pushLabel 10, + .jump 11], + -- bb10 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb11 + [.op (.stack (.push 3)), + .op (.stack (.dup 2)), + .op (.stack .gt), + .jumpi 13, + .jump 12], + -- bb12 + [.op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op (.stack .lt), + .jump 16], + -- bb13 + [.op (.stack (.dup 1)), + .op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack .iszero), + .jumpi 22, + .jump 14], + -- bb14 + [.op (.stack (.dup 3)), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 15], + -- bb15 + [.op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 17, + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 1)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .jump 16], + -- bb16 + [.op (.stack (.swap 0)), + .jumpDyn], + -- bb17 + [.op (.stack .pop), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 20, + .jump 18], + -- bb18 + [.op (.stack (.dup 0)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 21, + .jump 19], + -- bb19 + [.op (.stack (.push 1)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .jump 15], + -- bb20 + [.op (.stack (.push 18)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb21 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb22 + [.op (.stack .pop), + .op (.stack (.push 0x308000000020000000100000001)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)), + .jump 23], + -- bb23 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/Schedule.json b/Certified/callsqrt/gen/CallSqrt/Schedule.json new file mode 100644 index 00000000..cb3a4eb4 --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Schedule.json @@ -0,0 +1,40 @@ +{ + "functions": [ + {"function": 3, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [4, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [3, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [2, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 0, "entry": 5, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [5, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [8, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [7, 0], "layout": ["v5"], "floating": true, "continues": null} + ], "calls": [ + {"block": 0, "return": 6, "below": []} + ]}, + {"function": 1, "entry": 9, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [9, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + {"block": 0, "return": 10, "below": []} + ]}, + {"function": 2, "entry": 11, "returns": true, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [11, 0], "layout": ["v0", "ret"], "floating": false, "continues": null}, + {"block": 1, "start": [13, 0], "layout": ["v0", "ret"], "floating": false, "continues": null}, + {"block": 2, "start": [12, 0], "layout": ["v0", "ret"], "floating": false, "continues": null}, + {"block": 3, "start": [16, 0], "layout": ["ret", "v21"], "floating": false, "continues": null}, + {"block": 4, "start": [15, 0], "layout": ["v0", "ret", "v10", "v9"], "floating": false, "continues": null}, + {"block": 5, "start": [17, 0], "layout": ["v0", "ret", "v10", "junk"], "floating": false, "continues": null}, + {"block": 6, "start": [20, 0], "layout": [], "floating": true, "continues": null}, + {"block": 7, "start": [18, 0], "layout": ["v0", "ret", "v10"], "floating": false, "continues": null}, + {"block": 8, "start": [21, 0], "layout": [], "floating": true, "continues": null}, + {"block": 9, "start": [19, 0], "layout": ["v0", "ret", "v10", "v47"], "floating": false, "continues": null}, + {"block": 10, "start": [23, 0], "layout": ["v73", "v72", "v74"], "floating": true, "continues": null}, + {"block": 11, "start": [22, 0], "layout": ["v5", "junk"], "floating": true, "continues": null}, + {"block": 12, "start": [14, 0], "layout": ["v0", "ret", "junk", "v30"], "floating": false, "continues": null} + ], "calls": [ + ]} + ] +} diff --git a/Certified/callsqrt/gen/CallSqrt/Stage0.lean b/Certified/callsqrt/gen/CallSqrt/Stage0.lean new file mode 100644 index 00000000..12f4ea08 --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/Stage0.lean @@ -0,0 +1,124 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `CallSqrt`; do not edit. -/ + +namespace SolarTV.Export.CallSqrt + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 3, + functions := [ + -- @f + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 20) .calldataload [.const 4], + .call (some 2) 2 [.value 20], + .pure 5 .add [.value 2, .const 1], + .pure 6 .eq [.value 5, .const 0]], + .branch (.value 6) 1 2⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 5]], + .ret (.const 0) (.const 32)⟩] }, + -- @g + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 10) .calldataload [.const 4], + .pure 3 .shr [.const 1, .value 10], + .call (some 4) 2 [.value 3], + .effect none .mstore [.const 0, .value 4]], + .ret (.const 0) (.const 32)⟩] }, + -- @sqrt + { params := [0], + blocks := [ + -- bb0 + ⟨[], + [.pure 2 .gt [.value 0, .const 3]], + .branch (.value 2) 1 2⟩, + -- bb1 + ⟨[], + [.pure 5 .shr [.const 1, .value 0], + .pure 30 .add [.value 5, .const 1], + .assume false .lt [.value 5, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.const 0, .const 0], + .assume false .eq [.const 0, .const 0]], + .jump 4⟩, + -- bb2 + ⟨[], + [.ne 17 (.value 0) (.const 0), + .word 66 (.value 17)], + .jump 3⟩, + -- bb3 + ⟨[(21, [(4, .value 9), (2, .value 66)])], + [], + .leave [.value 21]⟩, + -- bb4 + ⟨[(9, [(1, .value 0), (9, .value 10)]), (10, [(1, .value 30), (9, .value 15)])], + [.pure 11 .lt [.value 10, .value 9]], + .branch (.value 11) 5 3⟩, + -- bb5 + ⟨[], + [.ne 39 (.value 10) (.const 0)], + .branch (.value 39) 7 6⟩, + -- bb6 + ⟨[], + [.effect none .mstore [.const 32, .const 18], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb7 + ⟨[], + [.pure 46 .div [.value 0, .value 10], + .pure 47 .add [.value 46, .value 10], + .pure 48 .lt [.value 47, .value 46]], + .branch (.value 48) 8 9⟩, + -- bb8 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb9 + ⟨[], + [.pure 15 .shr [.const 1, .value 47], + .assume false .eq [.const 0, .const 0]], + .jump 4⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .effect (some 1) .calldatasize [], + .pure 3 .lt [.value 1, .const 36], + .word 4 (.value 3), + .pure 5 .or [.value 0, .value 4], + .ne 7 (.value 5) (.const 0)], + .branch (.value 7) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 9) .calldataload [.const 0], + .pure 11 .shr [.const 224, .value 9]], + .switch (.value 11) 1 [(.const 0xb3de648b, 3), (.const 0xe420264a, 4)]⟩, + -- bb3 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 1 []⟩] }] } + +end SolarTV.Export.CallSqrt diff --git a/Certified/callsqrt/gen/CallSqrt/manifest.json b/Certified/callsqrt/gen/CallSqrt/manifest.json new file mode 100644 index 00000000..e3d99ea0 --- /dev/null +++ b/Certified/callsqrt/gen/CallSqrt/manifest.json @@ -0,0 +1,161 @@ +{ + "arguments": [ + "Certified/callsqrt/callsqrt.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/callsqrt/gen" + ], + "bytecode": "6024361034176022575f3560e01c8063b3de648b146026578063e420264a146048575b5f5ffd5b60043560395b60038211605b57905f1090565b6001018015609b575f5260205ff35b60043560011c6054602c565b5f5260205ff35b8160011c600181015f1982101560b45783915090808210607a57925050565b50801560ae57808304818101908110609b5760011c90808210607a57925050565b60115b602052634e487b715f526024601cfd5b6012609e565b506d03080000000200000001000000016020526040525f1960605263ed572b275f526064601cfd", + "bytecode_sha256": "8d899f9ae46a785487daac251bee8ac1db72cded3c47a473a12115d82328fe32", + "compiler": "0.8.38+commit.cb5053ab.solar.0.3.0-dev", + "contract": "CallSqrt", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"Certified/callsqrt/callsqrt.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/callsqrt/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/callsqrt/gen\"), keep_asts: false, forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "Certified/callsqrt/callsqrt.sol", + "sha256": "de1e97d3782481740b78753f4a9933eec66d15c015397a55b59255f9d56906d9" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "d957e4a9da2372b09f85b01a61aeb2cb18d23635520f34af608650df94a40846" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "lower-assumes", + "sha256": "0f53c878c78d96eb51eb7b6d7f3e150725313c1db1d37376d77c9f61eba07295" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "05e0cfec95d0970608f020da9efc3b1b9822776c587a1e053ee859e00adc82d5" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "123b70a54cd8d9a4e7ff9e7631c54e89e68ab665f26daf5e51f2cd928c2aa182" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "compact-pushes", + "sha256": "b72cab1cbec9ba8609e2612062694106f129fed7794ab17958041a7ab1c2841f" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "block-layout", + "sha256": "d87d8457a298d827ea00786d7b5e4b8f6b747c50cf06801a92acb43d132bae24" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "88fbc79ab09942584024e0b083cb61f95d2f10b04c76b39e2c661b724bf6fda4" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "cdea2f26fef17ec876b9b586f1d793072f64c6b8a1d66c37a8d3956b69dae161" + }, + { + "definition": "evm6", + "file": "Evm6.lean", + "index": 6, + "kind": "evm", + "pass": "tail-merge", + "sha256": "a6140ae089622007a504fbcca937cdbdc7986e352aded3375ffcc2044a7d5fff" + }, + { + "definition": "evm7", + "file": "Evm7.lean", + "index": 7, + "kind": "evm", + "pass": "reorder-pushes", + "sha256": "a08cef8ac57be384174353ab1039a5d48cfd883563eb7dc45dae2981be10698f" + }, + { + "definition": "evm8", + "file": "Evm8.lean", + "index": 8, + "kind": "evm", + "pass": "stack-normalize", + "sha256": "ebc56f0092441ffad9ad87e3a961cd006a246ffecb16361662c9eb76fdd93449" + }, + { + "definition": "evm9", + "file": "Evm9.lean", + "index": 9, + "kind": "evm", + "pass": "block-layout", + "sha256": "2344131c89411b0f4ff8e53be092bdbb62b864294bd5fc0c8ff864dd4ec125ef" + }, + { + "definition": "evm10", + "file": "Evm10.lean", + "index": 10, + "kind": "evm", + "pass": "stack-reschedule", + "sha256": "d1859481d702db01d5db6f77c46ec8521c1dd72d237c110b975088b8f5e6028d" + }, + { + "definition": "evm11", + "file": "Evm11.lean", + "index": 11, + "kind": "evm", + "pass": "inline-returns", + "sha256": "d3548ca976ebdd9ed3f28c962a5c10139f4128e76091f211d330a78fec14492c" + }, + { + "definition": "evm12", + "file": "Evm12.lean", + "index": 12, + "kind": "evm", + "pass": "copy-loop-blocks", + "sha256": "ed33e32f2d052486c226fea45686fbbcfadd0d4a42c11317ced0b9a157bf95f2" + }, + { + "definition": "evm13", + "file": "Evm13.lean", + "index": 13, + "kind": "evm", + "pass": "cfg-simplify", + "sha256": "c26441f33f94ab60033e1fde5b25a22ebf92b1a4e6c18ac1d7bceb113c2327c2" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "8161b3b0e3ddff3e02f5fcde0acbc91debabf4cb6cdebb20cfe0ee3f6b7de33c" + } + ] +} diff --git a/Certified/callsqrt/gen/Math/Bytecode.lean b/Certified/callsqrt/gen/Math/Bytecode.lean new file mode 100644 index 00000000..49ae30ac --- /dev/null +++ b/Certified/callsqrt/gen/Math/Bytecode.lean @@ -0,0 +1,14 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Math`; do not edit. -/ + +namespace SolarTV.Export.Math + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x5f, 0x5f, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "5f5ffd" + +end SolarTV.Export.Math diff --git a/Certified/callsqrt/gen/Math/Manifest.lean b/Certified/callsqrt/gen/Math/Manifest.lean new file mode 100644 index 00000000..1402daaa --- /dev/null +++ b/Certified/callsqrt/gen/Math/Manifest.lean @@ -0,0 +1,37 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Math`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Math.Manifest + +def sources : List (String × String) := + [("Certified/callsqrt/callsqrt.sol", "de1e97d3782481740b78753f4a9933eec66d15c015397a55b59255f9d56906d9")] + +def compiler : String := "0.8.38+commit.cb5053ab.solar.0.3.0-dev" + +def arguments : List String := + ["Certified/callsqrt/callsqrt.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/callsqrt/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "4418130ce11c713000811dec515565de47ebcf948b6e2a03b80d3266b068eef4"), + ("Sched", "sched", "stack-schedule", "40a0c2d17dca2bd5f923f2934f23d31c60175fef28cf1e6adbe8613716c5bbb3"), + ("Bytecode", "bytecode", "assemble", "a466ac991a6191547f6c3d5420f86ca8b95aabe6b84d87078aa6d3c142fcfe8a")] + +def bytecodeHex : String := + "5f5ffd" + +def bytecodeSha256 : String := "fb46926419d6c8a637fd12b52e23f698ba5ad6bfe5afec13d064f59f7adcca4f" + +end SolarTV.Export.Math.Manifest diff --git a/Certified/callsqrt/gen/Math/Sched.lean b/Certified/callsqrt/gen/Math/Sched.lean new file mode 100644 index 00000000..89204bb0 --- /dev/null +++ b/Certified/callsqrt/gen/Math/Sched.lean @@ -0,0 +1,16 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Math`; do not edit. -/ + +namespace SolarTV.Export.Math + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Math diff --git a/Certified/callsqrt/gen/Math/Schedule.json b/Certified/callsqrt/gen/Math/Schedule.json new file mode 100644 index 00000000..614051c2 --- /dev/null +++ b/Certified/callsqrt/gen/Math/Schedule.json @@ -0,0 +1,8 @@ +{ + "functions": [ + {"function": 0, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]} + ] +} diff --git a/Certified/callsqrt/gen/Math/Stage0.lean b/Certified/callsqrt/gen/Math/Stage0.lean new file mode 100644 index 00000000..bdfc48af --- /dev/null +++ b/Certified/callsqrt/gen/Math/Stage0.lean @@ -0,0 +1,20 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Math`; do not edit. -/ + +namespace SolarTV.Export.Math + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 0, + functions := [ + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Math diff --git a/Certified/callsqrt/gen/Math/manifest.json b/Certified/callsqrt/gen/Math/manifest.json new file mode 100644 index 00000000..55ba406f --- /dev/null +++ b/Certified/callsqrt/gen/Math/manifest.json @@ -0,0 +1,49 @@ +{ + "arguments": [ + "Certified/callsqrt/callsqrt.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/callsqrt/gen" + ], + "bytecode": "5f5ffd", + "bytecode_sha256": "fb46926419d6c8a637fd12b52e23f698ba5ad6bfe5afec13d064f59f7adcca4f", + "compiler": "0.8.38+commit.cb5053ab.solar.0.3.0-dev", + "contract": "Math", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"Certified/callsqrt/callsqrt.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/callsqrt/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/callsqrt/gen\"), keep_asts: false, forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "Certified/callsqrt/callsqrt.sol", + "sha256": "de1e97d3782481740b78753f4a9933eec66d15c015397a55b59255f9d56906d9" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "4418130ce11c713000811dec515565de47ebcf948b6e2a03b80d3266b068eef4" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "40a0c2d17dca2bd5f923f2934f23d31c60175fef28cf1e6adbe8613716c5bbb3" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "a466ac991a6191547f6c3d5420f86ca8b95aabe6b84d87078aa6d3c142fcfe8a" + } + ] +} diff --git a/Certified/callsqrt/options b/Certified/callsqrt/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/callsqrt/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/callsqrt/record.json b/Certified/callsqrt/record.json new file mode 100644 index 00000000..7b640a63 --- /dev/null +++ b/Certified/callsqrt/record.json @@ -0,0 +1,50 @@ +{ + "contract": "CallSqrt", + "name": "callsqrt", + "source": "Certified/callsqrt/callsqrt.sol", + "bytecode": "6024361034176022575f3560e01c8063b3de648b146026578063e420264a146048575b5f5ffd5b60043560395b60038211605b57905f1090565b6001018015609b575f5260205ff35b60043560011c6054602c565b5f5260205ff35b8160011c600181015f1982101560b45783915090808210607a57925050565b50801560ae57808304818101908110609b5760011c90808210607a57925050565b60115b602052634e487b715f526024601cfd5b6012609e565b506d03080000000200000001000000016020526040525f1960605263ed572b275f526064601cfd", + "solar": "cb5053ab39adfd59820913b336d346389ce1b8d9", + "solidity_lean": "696df0a81602fc416fabec7b892073e15e8920de", + "mir_to_evmir": "proved: SolarTV.Milestone.Callsqrt.callsqrt_mir_to_evmir", + "assembly": "executed: SolarTV.Milestone.Callsqrt.callsqrt_bytecode", + "vc": "exported to .lake/certify/callsqrt/VC.lean", + "end_to_end": "not proved", + "end_to_end_statement": {}, + "hypotheses": {}, + "refused": [ + { + "function": "Math.sqrt", + "reason": "command outside the Lean fragment: (set-option :timeout 0)", + "status": "refused (unproved)" + }, + { + "function": "CallSqrt.f", + "reason": "command outside the Lean fragment: (set-option :timeout 0)", + "status": "refused (unproved)" + }, + { + "function": "CallSqrt.g", + "reason": "command outside the Lean fragment: (set-option :timeout 0)", + "status": "refused (unproved)" + } + ], + "vacuous": "not checked", + "assembly_statement": "∀ {anyCall : SolarTV.Call → Prop} (o : SolarTV.Machine.Oracle), (SolarTV.Milestone.Callsqrt.cert.env = true → SolidCore.Refinement.Solar.Assemble.OracleOk o) → (SolarTV.Milestone.Callsqrt.cert.reads = true → SolidCore.Refinement.Solar.Assemble.EnvOk o) → ∀ (gas : ℕ), SolidCore.Refinement.Final.Within (SolarTV.mirSem o) (SolidCore.Refinement.Final.ethLibWith gas) SolarTV.Export.CallSqrt.stage0 SolarTV.Milestone.Callsqrt.code anyCall", + "assembly_hypotheses": [ + "anyCall : SolarTV.Call → Prop", + "o : SolarTV.Machine.Oracle", + "(SolarTV.Milestone.Callsqrt.cert.env = true → SolidCore.Refinement.Solar.Assemble.OracleOk o)", + "(SolarTV.Milestone.Callsqrt.cert.reads = true → SolidCore.Refinement.Solar.Assemble.EnvOk o)" + ], + "negative_tests": false, + "caveats": [ + "solidity-lean at 696df0a81602fc416fabec7b892073e15e8920de, not the pinned 813949dc3556d3c3f1c129e8254a4eead78bac87", + "solar cb5053ab39adfd59820913b336d346389ce1b8d9, not built from this checkout's compiler sources", + "3 spec function(s) refused, unproved", + "not end to end: solidity-lean states no source or spec theorem for callsqrt", + "negative tests skipped" + ], + "backend": { + "theorem": "SolarTV.Milestone.Callsqrt.callsqrt_mir_to_evmir" + } +} diff --git a/Certified/counter/Final.lean b/Certified/counter/Final.lean new file mode 100644 index 00000000..09a1149a --- /dev/null +++ b/Certified/counter/Final.lean @@ -0,0 +1,53 @@ +import Verify.Shapes +import counter.gen.Counter.Bytecode +import Contracts.Counter.ShapeSpec +import Contracts.Counter.Shape + +-- Generated by solar's tools/certify/final.py from counter/shape.json and the bytecode the +-- driver compiled in this run; do not edit. The statement is fixed by the driver; the proof +-- module only supplies a term the kernel checks against it. + +/-! +# Counter: the published statement + +`Statement` binds the exact runtime bytecode (`runtimeHex`, from the driver's own compile) and +states Shapes.Certified of it against the checked source on the declared valid calls. +-/ + +namespace Certified.counter.Final + +open SolidCore.Refinement + +/-- The runtime bytecode the pinned solar emitted in this run, as hex (for the reader). -/ +def runtimeHex : String := + "346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd" + +/-- The same bytes, as numbers: what the statement binds. -/ +def runtimeBytes : List Nat := + [0x34, 0x60, 0x34, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x6d, 0x4c, 0xe6, 0x3c, 0x14, + 0x60, 0x38, 0x57, 0x80, 0x63, 0x81, 0x26, 0x0, 0xdf, 0x3, 0x60, 0x34, 0x57, 0x60, 0x24, 0x36, + 0x10, 0x60, 0x34, 0x57, 0x5f, 0x54, 0x60, 0x4, 0x35, 0x81, 0x1, 0x90, 0x81, 0x10, 0x60, 0x41, + 0x57, 0x5f, 0x55, 0x0, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x5f, 0x54, 0x5f, 0x52, 0x60, 0x20, 0x5f, + 0xf3, 0x5b, 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, + 0x60, 0x1c, 0xfd] + +/-- The freshly exported bytecode the obligations speak of. -/ +def code : ByteArray := ⟨(SolarTV.Export.Counter.bytecode.map UInt8.ofNat).toArray⟩ + +/-- **The published statement.** -/ +def Statement : Prop := + code.data.toList.map (·.toNat) = runtimeBytes ∧ + (∃ c, SolidCore.Refinement.Solar.Counter.contract? = .ok c ∧ + Shapes.Certified (solidCore (SolidCore.Refinement.Solar.Counter.fuel)) c code + (SolidCore.Refinement.Solar.Counter.ShapeSpec.cspec.Calls) (SolidCore.Refinement.Solar.Counter.ShapeSpec.allowed) (SolidCore.Refinement.Shapes.specPost SolidCore.Refinement.Solar.Counter.ShapeSpec.cspec) (SolidCore.Refinement.Solar.Counter.ShapeSpec.gasBound)) + +set_option maxRecDepth 100000 in +theorem bound : code.data.toList.map (·.toNat) = runtimeBytes := + @of_decide_eq_true _ (instDecidableEqList _ _) (by decide +kernel) + +theorem final : Statement := + ⟨bound, SolidCore.Refinement.Solar.Counter.Shape.published⟩ + +#print axioms final + +end Certified.counter.Final diff --git a/Certified/counter/Proofs.lean b/Certified/counter/Proofs.lean new file mode 100644 index 00000000..701668e1 --- /dev/null +++ b/Certified/counter/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import counter.Proofs.Stages +import counter.Proofs.Assembly diff --git a/Certified/counter/Proofs/Assembly.lean b/Certified/counter/Proofs/Assembly.lean new file mode 100644 index 00000000..3e244e68 --- /dev/null +++ b/Certified/counter/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Items +import counter.gen.Counter.Evm5 +import counter.gen.Counter.Bytecode + +/-! The final EVM IR of `Counter` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.Counter + +open SolarTV.Assembly SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm5).getD [] + +theorem items_eq : itemsOf evm5 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x34 else if label = 2 then 0x38 else if label = 3 then 0x41 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.Counter.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.Counter.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms decodes + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/Proofs/Runs/Evm1.lean b/Certified/counter/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..3713dac3 --- /dev/null +++ b/Certified/counter/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import counter.gen.Counter.Evm1 +import counter.gen.Counter.Sched + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Counter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 11 = EVM.Program.run o evm1 call 6 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Counter.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/Proofs/Runs/Evm2.lean b/Certified/counter/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..93a4bccb --- /dev/null +++ b/Certified/counter/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import counter.gen.Counter.Evm2 +import counter.gen.Counter.Evm1 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Counter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 6 = EVM.Program.run o evm2 call 6 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Counter.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/Proofs/Runs/Evm3.lean b/Certified/counter/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..bfbfb0c8 --- /dev/null +++ b/Certified/counter/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import counter.gen.Counter.Evm3 +import counter.gen.Counter.Evm2 + +/-! `share-reverts`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Counter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 6 = EVM.Program.run o evm3 call 6 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Counter.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/Proofs/Runs/Evm4.lean b/Certified/counter/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..9105ddf9 --- /dev/null +++ b/Certified/counter/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import counter.gen.Counter.Evm4 +import counter.gen.Counter.Evm3 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Counter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 6 = EVM.Program.run o evm4 call 6 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Counter.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/Proofs/Runs/Evm5.lean b/Certified/counter/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..52b3db31 --- /dev/null +++ b/Certified/counter/Proofs/Runs/Evm5.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import counter.gen.Counter.Evm5 +import counter.gen.Counter.Evm4 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Counter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 6 = EVM.Program.run o evm5 call 4 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Counter.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/Proofs/Runs/Sched.lean b/Certified/counter/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..4c21fb61 --- /dev/null +++ b/Certified/counter/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import counter.gen.Counter.Sched +import counter.gen.Counter.Stage0 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.Counter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 11 = EVM.Program.run o sched call 11 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Counter.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/Proofs/Runs/Stage0.lean b/Certified/counter/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..a95eccf4 --- /dev/null +++ b/Certified/counter/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import counter.gen.Counter.Stage0 + +/-! The first lowered MIR ends on every call within 11 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.Counter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 11).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.Counter.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/Proofs/Stages.lean b/Certified/counter/Proofs/Stages.lean new file mode 100644 index 00000000..2e2c0138 --- /dev/null +++ b/Certified/counter/Proofs/Stages.lean @@ -0,0 +1,115 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import counter.Proofs.Runs.Stage0 +import counter.Proofs.Runs.Sched +import counter.Proofs.Runs.Evm1 +import counter.Proofs.Runs.Evm2 +import counter.Proofs.Runs.Evm3 +import counter.Proofs.Runs.Evm4 +import counter.Proofs.Runs.Evm5 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Counter`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm5`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.Counter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +/-- `stack-schedule`: stage0 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 11 11 (fun call _ => stage0_ends o call) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 11).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := stage0) (q := sched) (n := 11) (m := 11) (fun call _ => stage0_ends o call) + (fun call _ => sched_run o call) + +/-- `cfg-simplify-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 11 6 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 6).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 11) (m := 6) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `block-layout`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 6 6 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 6).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 6) (m := 6) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `share-reverts`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 6 6 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 6).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 6) (m := 6) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `terminal-dedup`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 6 6 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 6).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 6) (m := 6) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `cfg-simplify-early`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 6 4 (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [], sched, [evm1, evm2, evm3, evm4, evm5]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem counter_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm5 anyCall := + mir_to_evmir o anyCall compilation trivial (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.Counter.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.Counter.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.Counter.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.Counter.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.Counter.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.Counter.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.Counter.counter_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms counter_mir_to_evmir + +end SolarTV.Milestone.Counter diff --git a/Certified/counter/bytecode.hex b/Certified/counter/bytecode.hex new file mode 100644 index 00000000..158c777c --- /dev/null +++ b/Certified/counter/bytecode.hex @@ -0,0 +1 @@ +346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd diff --git a/Certified/counter/counter.sol b/Certified/counter/counter.sol new file mode 100644 index 00000000..5a7a17e3 --- /dev/null +++ b/Certified/counter/counter.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Counter { + uint256 x; + /// @custom:ensures x == old(x) + d + function inc(uint256 d) external { x += d; } + function get() external view returns (uint256) { return x; } +} diff --git a/Certified/counter/gen/Counter/Bytecode.lean b/Certified/counter/gen/Counter/Bytecode.lean new file mode 100644 index 00000000..37f4d190 --- /dev/null +++ b/Certified/counter/gen/Counter/Bytecode.lean @@ -0,0 +1,19 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x34, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x6d, 0x4c, 0xe6, 0x3c, 0x14, + 0x60, 0x38, 0x57, 0x80, 0x63, 0x81, 0x26, 0x00, 0xdf, 0x03, 0x60, 0x34, 0x57, 0x60, 0x24, 0x36, + 0x10, 0x60, 0x34, 0x57, 0x5f, 0x54, 0x60, 0x04, 0x35, 0x81, 0x01, 0x90, 0x81, 0x10, 0x60, 0x41, + 0x57, 0x5f, 0x55, 0x00, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x5f, 0x54, 0x5f, 0x52, 0x60, 0x20, 0x5f, + 0xf3, 0x5b, 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, + 0x60, 0x1c, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd" + +end SolarTV.Export.Counter diff --git a/Certified/counter/gen/Counter/Evm1.lean b/Certified/counter/gen/Counter/Evm1.lean new file mode 100644 index 00000000..7d53247b --- /dev/null +++ b/Certified/counter/gen/Counter/Evm1.lean @@ -0,0 +1,72 @@ +-- solar-lean-stage: kind=evm index=1 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret]] } + +end SolarTV.Export.Counter diff --git a/Certified/counter/gen/Counter/Evm2.lean b/Certified/counter/gen/Counter/Evm2.lean new file mode 100644 index 00000000..6d229db0 --- /dev/null +++ b/Certified/counter/gen/Counter/Evm2.lean @@ -0,0 +1,72 @@ +-- solar-lean-stage: kind=evm index=2 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `block-layout`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Counter diff --git a/Certified/counter/gen/Counter/Evm3.lean b/Certified/counter/gen/Counter/Evm3.lean new file mode 100644 index 00000000..bae9066e --- /dev/null +++ b/Certified/counter/gen/Counter/Evm3.lean @@ -0,0 +1,72 @@ +-- solar-lean-stage: kind=evm index=3 pass=share-reverts +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `share-reverts`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Counter diff --git a/Certified/counter/gen/Counter/Evm4.lean b/Certified/counter/gen/Counter/Evm4.lean new file mode 100644 index 00000000..b3a24bd5 --- /dev/null +++ b/Certified/counter/gen/Counter/Evm4.lean @@ -0,0 +1,70 @@ +-- solar-lean-stage: kind=evm index=4 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.jump 1]] } + +end SolarTV.Export.Counter diff --git a/Certified/counter/gen/Counter/Evm5.lean b/Certified/counter/gen/Counter/Evm5.lean new file mode 100644 index 00000000..97dc193a --- /dev/null +++ b/Certified/counter/gen/Counter/Evm5.lean @@ -0,0 +1,66 @@ +-- solar-lean-stage: kind=evm index=5 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Counter diff --git a/Certified/counter/gen/Counter/Manifest.lean b/Certified/counter/gen/Counter/Manifest.lean new file mode 100644 index 00000000..e937d906 --- /dev/null +++ b/Certified/counter/gen/Counter/Manifest.lean @@ -0,0 +1,42 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Counter.Manifest + +def sources : List (String × String) := + [("Certified/counter/counter.sol", "28af3c6bf35e4bde0636e2861c1f3eb6a5791d6f944a96af70b00fa46df54ad5")] + +def compiler : String := "0.8.38+commit.cb5053ab.solar.0.3.0-dev" + +def arguments : List String := + ["Certified/counter/counter.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/counter/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "455c5c9bc1edc79a8525008cafaa56bfbed84a0af77282cb1d60aacf04d52045"), + ("Sched", "sched", "stack-schedule", "18e30c45562a1863be5c810b37b374c8376cb5f093ab3ee3d2663947f1346011"), + ("Evm1", "evm1", "cfg-simplify-early", "31c90cb533b38c43aca3259f29283b635ecb2fd484be8e383b0dfe97a2a3f475"), + ("Evm2", "evm2", "block-layout", "8d28ef5f0d949d948a1a0f5f1dfd859c0fecbea894cf62a009a9345ff37fd5af"), + ("Evm3", "evm3", "share-reverts", "8171f571ac99ad077dc819ff7bd8fd5c4b1c08b0b3bf77e97a8e3a61924542d1"), + ("Evm4", "evm4", "terminal-dedup", "f840c77ead93175f074b51c9a550a287db6e86ed2cbb2218afeae7331d4badfa"), + ("Evm5", "evm5", "cfg-simplify-early", "8bf84a55156ac80e2af70c987aecdb04f40b38fd962516c466b2d601c3e89f09"), + ("Bytecode", "bytecode", "assemble", "5e1da0f07568e12e2177a30c1ed98662ce5e731e153644472bdfcfa38203b0e5")] + +def bytecodeHex : String := + "346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd" + +def bytecodeSha256 : String := "daed21b0c790bb2c08bcf999c9ebc6fea950c213ea0a799418552aa14c18f6ec" + +end SolarTV.Export.Counter.Manifest diff --git a/Certified/counter/gen/Counter/Sched.lean b/Certified/counter/gen/Counter/Sched.lean new file mode 100644 index 00000000..e7359f24 --- /dev/null +++ b/Certified/counter/gen/Counter/Sched.lean @@ -0,0 +1,82 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 4, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .eq), + .jumpi 2, + .jump 4], + -- bb2 + [.jump 5], + -- bb3 + [.jump 10], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 9, + .jump 6], + -- bb6 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 8, + .jump 7], + -- bb7 + [.op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret]] } + +end SolarTV.Export.Counter diff --git a/Certified/counter/gen/Counter/Schedule.json b/Certified/counter/gen/Counter/Schedule.json new file mode 100644 index 00000000..8b632099 --- /dev/null +++ b/Certified/counter/gen/Counter/Schedule.json @@ -0,0 +1,24 @@ +{ + "functions": [ + {"function": 2, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [3, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [4, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 0, "entry": 5, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [5, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [8, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [7, 0], "layout": ["v4"], "floating": true, "continues": null}, + {"block": 3, "start": [9, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [6, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 1, "entry": 10, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [10, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]} + ] +} diff --git a/Certified/counter/gen/Counter/Stage0.lean b/Certified/counter/gen/Counter/Stage0.lean new file mode 100644 index 00000000..fc30c311 --- /dev/null +++ b/Certified/counter/gen/Counter/Stage0.lean @@ -0,0 +1,74 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 2, + functions := [ + -- @inc + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 36]], + .branch (.value 15) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 0, .value 4]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 17) .calldataload [.const 4], + .effect (some 2) .sload [.const 0], + .pure 4 .add [.value 2, .value 17], + .pure 5 .lt [.value 4, .value 2]], + .branch (.value 5) 1 2⟩] }, + -- @get + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 0], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 4 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 4 [(.const 0x6d4ce63c, 2), (.const 0x812600df, 3)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Counter diff --git a/Certified/counter/gen/Counter/manifest.json b/Certified/counter/gen/Counter/manifest.json new file mode 100644 index 00000000..6679c72c --- /dev/null +++ b/Certified/counter/gen/Counter/manifest.json @@ -0,0 +1,89 @@ +{ + "arguments": [ + "Certified/counter/counter.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/counter/gen" + ], + "bytecode": "346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd", + "bytecode_sha256": "daed21b0c790bb2c08bcf999c9ebc6fea950c213ea0a799418552aa14c18f6ec", + "compiler": "0.8.38+commit.cb5053ab.solar.0.3.0-dev", + "contract": "Counter", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"Certified/counter/counter.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/counter/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/counter/gen\"), keep_asts: false, forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "Certified/counter/counter.sol", + "sha256": "28af3c6bf35e4bde0636e2861c1f3eb6a5791d6f944a96af70b00fa46df54ad5" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "455c5c9bc1edc79a8525008cafaa56bfbed84a0af77282cb1d60aacf04d52045" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "18e30c45562a1863be5c810b37b374c8376cb5f093ab3ee3d2663947f1346011" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "31c90cb533b38c43aca3259f29283b635ecb2fd484be8e383b0dfe97a2a3f475" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "block-layout", + "sha256": "8d28ef5f0d949d948a1a0f5f1dfd859c0fecbea894cf62a009a9345ff37fd5af" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "share-reverts", + "sha256": "8171f571ac99ad077dc819ff7bd8fd5c4b1c08b0b3bf77e97a8e3a61924542d1" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "f840c77ead93175f074b51c9a550a287db6e86ed2cbb2218afeae7331d4badfa" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "8bf84a55156ac80e2af70c987aecdb04f40b38fd962516c466b2d601c3e89f09" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "5e1da0f07568e12e2177a30c1ed98662ce5e731e153644472bdfcfa38203b0e5" + } + ] +} diff --git a/Certified/counter/headline b/Certified/counter/headline new file mode 100644 index 00000000..89502ff6 --- /dev/null +++ b/Certified/counter/headline @@ -0,0 +1,5 @@ +Contracts.Counter.Headline SolidCore.Refinement.Solar.Counter.Headline.spec_holds_of_bytecode +Contracts.Counter.Headline SolidCore.Refinement.Solar.Counter.Headline.wrong_fails +Contracts.Counter.EndToEnd SolidCore.Refinement.Solar.Counter.EndToEnd.inc_spec_bytecode +Contracts.Counter.EndToEnd SolidCore.Refinement.Solar.Counter.EndToEnd.get_spec_bytecode +Contracts.Counter.Deploy SolidCore.Refinement.Solar.Counter.Deploy.initcode_runs diff --git a/Certified/counter/options b/Certified/counter/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/counter/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/counter/record.json b/Certified/counter/record.json new file mode 100644 index 00000000..96afda23 --- /dev/null +++ b/Certified/counter/record.json @@ -0,0 +1,106 @@ +{ + "contract": "Counter", + "name": "counter", + "source": "Certified/counter/counter.sol", + "bytecode": "346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd", + "solar": "cb5053ab39adfd59820913b336d346389ce1b8d9", + "solidity_lean": "11fb9334142fbb8ded0b1d699015a978cdc3ed52", + "mir_to_evmir": "proved: SolarTV.Milestone.Counter.counter_mir_to_evmir", + "assembly": "decoded only: counter.Proofs.Assembly (the bytecode decodes to the final EVM IR's instructions; no execution theorem)", + "vc": "exported to .lake/certify/counter/VC.lean", + "end_to_end": "proved (contract-specific): SolidCore.Refinement.Solar.Counter.Headline.spec_holds_of_bytecode, SolidCore.Refinement.Solar.Counter.Headline.wrong_fails, SolidCore.Refinement.Solar.Counter.EndToEnd.inc_spec_bytecode, SolidCore.Refinement.Solar.Counter.EndToEnd.get_spec_bytecode, SolidCore.Refinement.Solar.Counter.Deploy.initcode_runs", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, Shapes.Certified.equivG)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with an allowed status; the bytecode too, at gas from the bound on", + "spec": "proved (published statement, Shapes.Meets): the specification of every source result on a valid call, hence of every bytecode result that is not an inert failure", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result", + "assumptions": "none beyond the statement's scope", + "excluded": [ + "gas: the bound is 1,281,806 for every valid call (the straight-line checker's bound, 22100 per item plus memory), coarse; below it the bytecode may run out of gas, which equivalence admits as a failure that changes nothing", + "deployment: the init code is not covered by this statement (Contracts.Counter.Deploy.initcode_runs proves it separately)", + "source model trusted: SolidCore's checked Counter (SolidCore.Refinement.Solar.Counter.contract?) is the meaning of counter.sol (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; valid calls are inc(uint256) and get() ABI-encoded with clean arguments, any value below 2^256, any storage; other call data is outside the statement", + "below the gas bound, equivalence admits any failure that changes nothing (out of gas or a revert, whatever its data)" + ], + "strongest": true + }, + "final": { + "module": "counter.Final", + "theorem": "Certified.counter.Final.final", + "kind": "certified", + "statement": "code.data.toList.map (·.toNat) = runtimeBytes ∧ (∃ c, SolidCore.Refinement.Solar.Counter.contract? = .ok c ∧ Shapes.Certified (solidCore (SolidCore.Refinement.Solar.Counter.fuel)) c code (SolidCore.Refinement.Solar.Counter.ShapeSpec.cspec.Calls) (SolidCore.Refinement.Solar.Counter.ShapeSpec.allowed) (SolidCore.Refinement.Shapes.specPost SolidCore.Refinement.Solar.Counter.ShapeSpec.cspec) (SolidCore.Refinement.Solar.Counter.ShapeSpec.gasBound))", + "assumptions": [], + "excluded": [ + "gas: the bound is 1,281,806 for every valid call (the straight-line checker's bound, 22100 per item plus memory), coarse; below it the bytecode may run out of gas, which equivalence admits as a failure that changes nothing", + "deployment: the init code is not covered by this statement (Contracts.Counter.Deploy.initcode_runs proves it separately)", + "source model trusted: SolidCore's checked Counter (SolidCore.Refinement.Solar.Counter.contract?) is the meaning of counter.sol (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; valid calls are inc(uint256) and get() ABI-encoded with clean arguments, any value below 2^256, any storage; other call data is outside the statement", + "below the gas bound, equivalence admits any failure that changes nothing (out of gas or a revert, whatever its data)" + ], + "spec": null, + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, Shapes.Certified.equivG)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with an allowed status; the bytecode too, at gas from the bound on", + "spec": "proved (published statement, Shapes.Meets): the specification of every source result on a valid call, hence of every bytecode result that is not an inert failure", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result" + } + }, + "end_to_end_statement": { + "SolidCore.Refinement.Solar.Counter.Headline.spec_holds_of_bytecode": "SolidCore.Spec.Export.Counter.manifest.bytecodeSha256 = SolidCore.Refinement.Solar.Counter.Final.manifest.runtimeSha256 ∧ SolidCore.Refinement.Final.Bound SolidCore.Refinement.Solar.Counter.Final.manifest SolidCore.Refinement.Solar.Counter.code ∧ SolidCore.Refinement.Final.FrameLocal SolidCore.Refinement.Solar.Counter.code = true ∧ ∃ c, SolidCore.Refinement.Solar.Counter.contract? = Except.ok c ∧ SolidCore.Refinement.Final.Agree (SolidCore.Refinement.solidCore SolidCore.Refinement.Solar.Counter.fuel) SolidCore.Refinement.ethLib c SolidCore.Refinement.Solar.Counter.code SolidCore.Refinement.Solar.Counter.scopeEvery ∧ SolidCore.Spec.Holds SolidCore.Refinement.ethLib SolidCore.Refinement.Solar.Counter.code SolidCore.Refinement.Solar.Counter.scopeEvery SolidCore.Refinement.Solar.Counter.Headline.spec SolidCore.Refinement.Solar.Counter.Headline.ctxOf SolidCore.Refinement.Solar.Counter.Headline.step ∧ (∀ (call : SolarTV.Call), SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnInc [] call → ∃ obs, SolidCore.Refinement.Target.run SolidCore.Refinement.Solar.Counter.code call = some obs ∧ SolidCore.Verify.VC.Counter.incPost call obs) ∧ (∀ (call : SolarTV.Call), SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnGet [] call → ∃ obs, SolidCore.Refinement.Target.run SolidCore.Refinement.Solar.Counter.code call = some obs ∧ SolidCore.Verify.VC.Counter.getPost call obs) ∧ SolidCore.Refinement.Target.run SolidCore.Refinement.Solar.Counter.Deploy.initcode SolidCore.Refinement.Solar.Counter.Deploy.deployCall = some SolidCore.Refinement.Solar.Counter.Deploy.deployed", + "SolidCore.Refinement.Solar.Counter.Headline.wrong_fails": "¬SolidCore.Spec.Holds SolidCore.Refinement.ethLib SolidCore.Refinement.Solar.Counter.code SolidCore.Refinement.Solar.Counter.scopeEvery SolidCore.Spec.Export.CounterSpecMut.Counter SolidCore.Refinement.Solar.Counter.Headline.ctxOf SolidCore.Refinement.Solar.Counter.Headline.step", + "SolidCore.Refinement.Solar.Counter.EndToEnd.inc_spec_bytecode": "SolidCore.Refinement.Final.Bound SolidCore.Refinement.Solar.Counter.Final.manifest SolidCore.Refinement.Solar.Counter.code ∧ SolidCore.Refinement.Final.FrameLocal SolidCore.Refinement.Solar.Counter.code = true ∧ ∀ (call : SolarTV.Call), SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnInc [] call → ∃ obs, SolidCore.Refinement.Target.run SolidCore.Refinement.Solar.Counter.code call = some obs ∧ SolidCore.Verify.VC.Counter.incPost call obs", + "SolidCore.Refinement.Solar.Counter.EndToEnd.get_spec_bytecode": "SolidCore.Refinement.Final.Bound SolidCore.Refinement.Solar.Counter.Final.manifest SolidCore.Refinement.Solar.Counter.code ∧ SolidCore.Refinement.Final.FrameLocal SolidCore.Refinement.Solar.Counter.code = true ∧ ∀ (call : SolarTV.Call), SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnGet [] call → ∃ obs, SolidCore.Refinement.Target.run SolidCore.Refinement.Solar.Counter.code call = some obs ∧ SolidCore.Verify.VC.Counter.getPost call obs", + "SolidCore.Refinement.Solar.Counter.Deploy.initcode_runs": "SolidCore.Refinement.Target.run SolidCore.Refinement.Solar.Counter.Deploy.initcode SolidCore.Refinement.Solar.Counter.Deploy.deployCall = some SolidCore.Refinement.Solar.Counter.Deploy.deployed" + }, + "binding": { + "SolidCore.Refinement.Solar.Counter.Headline.spec_holds_of_bytecode": "statement reaches the fresh export", + "SolidCore.Refinement.Solar.Counter.Headline.wrong_fails": "proof reaches the fresh export, statement does not", + "SolidCore.Refinement.Solar.Counter.EndToEnd.inc_spec_bytecode": "statement reaches the fresh export", + "SolidCore.Refinement.Solar.Counter.EndToEnd.get_spec_bytecode": "statement reaches the fresh export", + "SolidCore.Refinement.Solar.Counter.Deploy.initcode_runs": "never reaches the fresh export" + }, + "hypotheses": { + "SolidCore.Refinement.Solar.Counter.Headline.spec_holds_of_bytecode": [], + "SolidCore.Refinement.Solar.Counter.Headline.wrong_fails": [], + "SolidCore.Refinement.Solar.Counter.EndToEnd.inc_spec_bytecode": [ + "SolidCore.Refinement.Final.Bound SolidCore.Refinement.Solar.Counter.Final.manifest SolidCore.Refinement.Solar.Counter.code ∧ SolidCore.Refinement.Final.FrameLocal SolidCore.Refinement.Solar.Counter.code = true ∧ ∀ (call : SolarTV.Call), SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnInc [] call" + ], + "SolidCore.Refinement.Solar.Counter.EndToEnd.get_spec_bytecode": [ + "SolidCore.Refinement.Final.Bound SolidCore.Refinement.Solar.Counter.Final.manifest SolidCore.Refinement.Solar.Counter.code ∧ SolidCore.Refinement.Final.FrameLocal SolidCore.Refinement.Solar.Counter.code = true ∧ ∀ (call : SolarTV.Call), SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnGet [] call" + ], + "SolidCore.Refinement.Solar.Counter.Deploy.initcode_runs": [] + }, + "refused": [], + "vacuous": "not checked", + "assembly_statement": null, + "assembly_hypotheses": null, + "negative_tests": true, + "caveats": [ + "solidity-lean at 11fb9334142fbb8ded0b1d699015a978cdc3ed52, not the pinned 534f2d9d7dce4ea16478bd4a6b8e97021425874d", + "solar cb5053ab39adfd59820913b336d346389ce1b8d9, not built from this checkout's compiler sources", + "assembly decoded, not executed" + ], + "backend": { + "theorem": { + "module": "counter.Final", + "theorem": "Certified.counter.Final.final", + "kind": "certified", + "statement": "code.data.toList.map (·.toNat) = runtimeBytes ∧ (∃ c, SolidCore.Refinement.Solar.Counter.contract? = .ok c ∧ Shapes.Certified (solidCore (SolidCore.Refinement.Solar.Counter.fuel)) c code (SolidCore.Refinement.Solar.Counter.ShapeSpec.cspec.Calls) (SolidCore.Refinement.Solar.Counter.ShapeSpec.allowed) (SolidCore.Refinement.Shapes.specPost SolidCore.Refinement.Solar.Counter.ShapeSpec.cspec) (SolidCore.Refinement.Solar.Counter.ShapeSpec.gasBound))", + "assumptions": [], + "excluded": [ + "gas: the bound is 1,281,806 for every valid call (the straight-line checker's bound, 22100 per item plus memory), coarse; below it the bytecode may run out of gas, which equivalence admits as a failure that changes nothing", + "deployment: the init code is not covered by this statement (Contracts.Counter.Deploy.initcode_runs proves it separately)", + "source model trusted: SolidCore's checked Counter (SolidCore.Refinement.Solar.Counter.contract?) is the meaning of counter.sol (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; valid calls are inc(uint256) and get() ABI-encoded with clean arguments, any value below 2^256, any storage; other call data is outside the statement", + "below the gas bound, equivalence admits any failure that changes nothing (out of gas or a revert, whatever its data)" + ], + "spec": null, + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, Shapes.Certified.equivG)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with an allowed status; the bytecode too, at gas from the bound on", + "spec": "proved (published statement, Shapes.Meets): the specification of every source result on a valid call, hence of every bytecode result that is not an inert failure", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result" + } + } + } +} diff --git a/Certified/counter/shape.json b/Certified/counter/shape.json new file mode 100644 index 00000000..21eba841 --- /dev/null +++ b/Certified/counter/shape.json @@ -0,0 +1,33 @@ +{ + "kind": "certified", + "contract": "SolidCore.Refinement.Solar.Counter.contract?", + "fuel": "SolidCore.Refinement.Solar.Counter.fuel", + "valid": "SolidCore.Refinement.Solar.Counter.ShapeSpec.cspec.Calls", + "allowed": "SolidCore.Refinement.Solar.Counter.ShapeSpec.allowed", + "spec_export": { + "ctx": "SolidCore.Refinement.Solar.Counter.Headline.ctxOf", + "step": "SolidCore.Refinement.Solar.Counter.Headline.step" + }, + "nonvacuous": "SolidCore.Refinement.Solar.Counter.ShapeExport.nonvacuous", + "gas": "SolidCore.Refinement.Solar.Counter.ShapeSpec.gasBound", + "env": [], + "spec": "solar-verify's export of counter.sol in this run: inc(d) ensures x == old(x) + d (no succeeds-if, so no claim that it succeeds); get() has no spec", + "spec_modules": [ + "Contracts.Counter.ShapeSpec", + "Contracts.Counter.Headline" + ], + "proof_module": "Contracts.Counter.ShapeExport", + "proof": "SolidCore.Refinement.Solar.Counter.ShapeExport.published", + "excluded": [ + "gas: the bound is 1,281,806 for every valid call (the straight-line checker's bound, 22100 per item plus memory), coarse; below it the bytecode may run out of gas, which equivalence admits as a failure that changes nothing", + "deployment: the init code is not covered by this statement (Contracts.Counter.Deploy.initcode_runs proves it separately)", + "source model trusted: SolidCore's checked Counter (SolidCore.Refinement.Solar.Counter.contract?) is the meaning of counter.sol (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; valid calls are inc(uint256) and get() ABI-encoded with clean arguments, any value below 2^256, any storage; other call data is outside the statement", + "below the gas bound, equivalence admits any failure that changes nothing (out of gas or a revert, whatever its data)" + ], + "source_ast": { + "file": "SolidCore/Refinement/Solar/Counter/Source.lean", + "namespace": "SolidCore.Refinement.Source.Counter", + "contract": "Counter" + } +} diff --git a/Certified/event_words/Final.lean b/Certified/event_words/Final.lean new file mode 100644 index 00000000..8c4c6d14 --- /dev/null +++ b/Certified/event_words/Final.lean @@ -0,0 +1,11 @@ +import event_words.Statement +import event_words.Shape + +-- Generated by solar's tools/certify/final.py; do not edit. The statement is +-- Certified.event_words.Final.Statement of event_words.Statement, which does not import the proof +-- module; the driver's checker requires `final`'s type to be exactly that constant. + +theorem Certified.event_words.Final.final : _root_.Certified.event_words.Final.Statement := + ⟨_root_.Certified.event_words.Final.bound, Certified.event_words.Shape.published⟩ + +#print axioms Certified.event_words.Final.final diff --git a/Certified/event_words/Proofs.lean b/Certified/event_words/Proofs.lean new file mode 100644 index 00000000..59cb5eb9 --- /dev/null +++ b/Certified/event_words/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import event_words.Proofs.Stages +import event_words.Proofs.Assembly diff --git a/Certified/event_words/Proofs/Assembly.lean b/Certified/event_words/Proofs/Assembly.lean new file mode 100644 index 00000000..002a69bc --- /dev/null +++ b/Certified/event_words/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Items +import event_words.gen.EventWords.Evm8 +import event_words.gen.EventWords.Bytecode + +/-! The final EVM IR of `EventWords` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.EventWords + +open SolarTV.Assembly SolarTV.Export.EventWords SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm8).getD [] + +theorem items_eq : itemsOf evm8 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x89 else if label = 2 then 0x8d else if label = 3 then 0x9d else if label = 4 then 0xb3 else if label = 5 then 0xcb else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.EventWords.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.EventWords.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms decodes + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Proofs/Runs/Evm1.lean b/Certified/event_words/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..29d09143 --- /dev/null +++ b/Certified/event_words/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import event_words.gen.EventWords.Evm1 +import event_words.gen.EventWords.Sched + +/-! `peephole-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.EventWords + +open Machine SolarTV.Export.EventWords SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 14 = EVM.Program.run o evm1 call 14 := by + sym_exec + +/-- info: 'SolarTV.Milestone.EventWords.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Proofs/Runs/Evm2.lean b/Certified/event_words/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..da8fa617 --- /dev/null +++ b/Certified/event_words/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import event_words.gen.EventWords.Evm2 +import event_words.gen.EventWords.Evm1 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.EventWords + +open Machine SolarTV.Export.EventWords SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 14 = EVM.Program.run o evm2 call 8 := by + sym_exec + +/-- info: 'SolarTV.Milestone.EventWords.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Proofs/Runs/Evm3.lean b/Certified/event_words/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..8077a979 --- /dev/null +++ b/Certified/event_words/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import event_words.gen.EventWords.Evm3 +import event_words.gen.EventWords.Evm2 + +/-! `compact-pushes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.EventWords + +open Machine SolarTV.Export.EventWords SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 8 = EVM.Program.run o evm3 call 8 := by + sym_exec + +/-- info: 'SolarTV.Milestone.EventWords.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Proofs/Runs/Evm4.lean b/Certified/event_words/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..de2c235a --- /dev/null +++ b/Certified/event_words/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import event_words.gen.EventWords.Evm4 +import event_words.gen.EventWords.Evm3 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.EventWords + +open Machine SolarTV.Export.EventWords SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 8 = EVM.Program.run o evm4 call 8 := by + sym_exec + +/-- info: 'SolarTV.Milestone.EventWords.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Proofs/Runs/Evm5.lean b/Certified/event_words/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..84011d81 --- /dev/null +++ b/Certified/event_words/Proofs/Runs/Evm5.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import event_words.gen.EventWords.Evm5 +import event_words.gen.EventWords.Evm4 + +/-! `share-reverts`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.EventWords + +open Machine SolarTV.Export.EventWords SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 8 = EVM.Program.run o evm5 call 8 := by + sym_exec + +/-- info: 'SolarTV.Milestone.EventWords.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Proofs/Runs/Evm6.lean b/Certified/event_words/Proofs/Runs/Evm6.lean new file mode 100644 index 00000000..94023316 --- /dev/null +++ b/Certified/event_words/Proofs/Runs/Evm6.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import event_words.gen.EventWords.Evm6 +import event_words.gen.EventWords.Evm5 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.EventWords + +open Machine SolarTV.Export.EventWords SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm6_run (o : Oracle) (call : Call) : + EVM.Program.run o evm5 call 8 = EVM.Program.run o evm6 call 8 := by + sym_exec + +/-- info: 'SolarTV.Milestone.EventWords.evm6_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_run + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Proofs/Runs/Evm7.lean b/Certified/event_words/Proofs/Runs/Evm7.lean new file mode 100644 index 00000000..1cddce6f --- /dev/null +++ b/Certified/event_words/Proofs/Runs/Evm7.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import event_words.gen.EventWords.Evm7 +import event_words.gen.EventWords.Evm6 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.EventWords + +open Machine SolarTV.Export.EventWords SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm7_run (o : Oracle) (call : Call) : + EVM.Program.run o evm6 call 8 = EVM.Program.run o evm7 call 6 := by + sym_exec + +/-- info: 'SolarTV.Milestone.EventWords.evm7_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm7_run + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Proofs/Runs/Evm8.lean b/Certified/event_words/Proofs/Runs/Evm8.lean new file mode 100644 index 00000000..9fc6c97b --- /dev/null +++ b/Certified/event_words/Proofs/Runs/Evm8.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import event_words.gen.EventWords.Evm8 +import event_words.gen.EventWords.Evm7 + +/-! `block-cse`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.EventWords + +open Machine SolarTV.Export.EventWords SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm8_run (o : Oracle) (call : Call) : + EVM.Program.run o evm7 call 6 = EVM.Program.run o evm8 call 6 := by + sym_exec + +/-- info: 'SolarTV.Milestone.EventWords.evm8_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm8_run + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Proofs/Runs/Mir1.lean b/Certified/event_words/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..03c3b411 --- /dev/null +++ b/Certified/event_words/Proofs/Runs/Mir1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import event_words.gen.EventWords.Mir1 +import event_words.gen.EventWords.Stage0 + +/-! `place-reads`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.EventWords + +open Machine SolarTV.Export.EventWords SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir1_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 7 = MIR.Lowered.Module.run o mir1 call 7 := by + sym_exec + +/-- info: 'SolarTV.Milestone.EventWords.mir1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_run + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Proofs/Runs/Mir2.lean b/Certified/event_words/Proofs/Runs/Mir2.lean new file mode 100644 index 00000000..75db835e --- /dev/null +++ b/Certified/event_words/Proofs/Runs/Mir2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import event_words.gen.EventWords.Mir2 +import event_words.gen.EventWords.Mir1 + +/-! `dce`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.EventWords + +open Machine SolarTV.Export.EventWords SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir2_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir1 call 7 = MIR.Lowered.Module.run o mir2 call 7 := by + sym_exec + +/-- info: 'SolarTV.Milestone.EventWords.mir2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir2_run + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Proofs/Runs/Mir3.lean b/Certified/event_words/Proofs/Runs/Mir3.lean new file mode 100644 index 00000000..7a0ae4a9 --- /dev/null +++ b/Certified/event_words/Proofs/Runs/Mir3.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import event_words.gen.EventWords.Mir3 +import event_words.gen.EventWords.Mir2 + +/-! `spell-width-tests`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.EventWords + +open Machine SolarTV.Export.EventWords SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir3_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir2 call 7 = MIR.Lowered.Module.run o mir3 call 7 := by + sym_exec + +/-- info: 'SolarTV.Milestone.EventWords.mir3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir3_run + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Proofs/Runs/Mir4.lean b/Certified/event_words/Proofs/Runs/Mir4.lean new file mode 100644 index 00000000..2ae78d18 --- /dev/null +++ b/Certified/event_words/Proofs/Runs/Mir4.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import event_words.gen.EventWords.Mir4 +import event_words.gen.EventWords.Mir3 + +/-! `lower-assumes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.EventWords + +open Machine SolarTV.Export.EventWords SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir4_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir3 call 7 = MIR.Lowered.Module.run o mir4 call 14 := by + sym_exec + +/-- info: 'SolarTV.Milestone.EventWords.mir4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir4_run + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Proofs/Runs/Mir5.lean b/Certified/event_words/Proofs/Runs/Mir5.lean new file mode 100644 index 00000000..26efae78 --- /dev/null +++ b/Certified/event_words/Proofs/Runs/Mir5.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import event_words.gen.EventWords.Mir5 +import event_words.gen.EventWords.Mir4 + +/-! `evm-inst-schedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.EventWords + +open Machine SolarTV.Export.EventWords SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir5_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir4 call 14 = MIR.Lowered.Module.run o mir5 call 14 := by + sym_exec + +/-- info: 'SolarTV.Milestone.EventWords.mir5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir5_run + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Proofs/Runs/Sched.lean b/Certified/event_words/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..653227ef --- /dev/null +++ b/Certified/event_words/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import event_words.gen.EventWords.Sched +import event_words.gen.EventWords.Mir5 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.EventWords + +open Machine SolarTV.Export.EventWords SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir5 call 14 = EVM.Program.run o sched call 14 := by + sym_exec + +/-- info: 'SolarTV.Milestone.EventWords.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Proofs/Runs/Stage0.lean b/Certified/event_words/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..da55aafe --- /dev/null +++ b/Certified/event_words/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import event_words.gen.EventWords.Stage0 + +/-! The first lowered MIR ends on every call within 7 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.EventWords + +open Machine SolarTV.Export.EventWords SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 7).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.EventWords.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Proofs/Stages.lean b/Certified/event_words/Proofs/Stages.lean new file mode 100644 index 00000000..521ee113 --- /dev/null +++ b/Certified/event_words/Proofs/Stages.lean @@ -0,0 +1,243 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import event_words.Proofs.Runs.Stage0 +import event_words.Proofs.Runs.Mir1 +import event_words.Proofs.Runs.Mir2 +import event_words.Proofs.Runs.Mir3 +import event_words.Proofs.Runs.Mir4 +import event_words.Proofs.Runs.Mir5 +import event_words.Proofs.Runs.Sched +import event_words.Proofs.Runs.Evm1 +import event_words.Proofs.Runs.Evm2 +import event_words.Proofs.Runs.Evm3 +import event_words.Proofs.Runs.Evm4 +import event_words.Proofs.Runs.Evm5 +import event_words.Proofs.Runs.Evm6 +import event_words.Proofs.Runs.Evm7 +import event_words.Proofs.Runs.Evm8 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `EventWords`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm8`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.EventWords + +open Machine SolarTV.Export.EventWords SolarTV.Milestone.W1 + +/-- `place-reads`: stage0 to mir1. -/ +theorem stage_mir1 (o : Oracle) : Stage (mirSem o) (mirSem o) stage0 mir1 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 7 7 (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +theorem mir1_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir1 call 7).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := stage0) (q := mir1) (n := 7) (m := 7) (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +/-- `dce`: mir1 to mir2. -/ +theorem stage_mir2 (o : Oracle) : Stage (mirSem o) (mirSem o) mir1 mir2 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 7 7 (mir1_ends o) + (fun call _ => mir2_run o call) + +theorem mir2_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir2 call 7).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir1) (q := mir2) (n := 7) (m := 7) (mir1_ends o) + (fun call _ => mir2_run o call) + +/-- `spell-width-tests`: mir2 to mir3. -/ +theorem stage_mir3 (o : Oracle) : Stage (mirSem o) (mirSem o) mir2 mir3 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 7 7 (mir2_ends o) + (fun call _ => mir3_run o call) + +theorem mir3_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir3 call 7).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir2) (q := mir3) (n := 7) (m := 7) (mir2_ends o) + (fun call _ => mir3_run o call) + +/-- `lower-assumes`: mir3 to mir4. -/ +theorem stage_mir4 (o : Oracle) : Stage (mirSem o) (mirSem o) mir3 mir4 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 7 14 (mir3_ends o) + (fun call _ => mir4_run o call) + +theorem mir4_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir4 call 14).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir3) (q := mir4) (n := 7) (m := 14) (mir3_ends o) + (fun call _ => mir4_run o call) + +/-- `evm-inst-schedule`: mir4 to mir5. -/ +theorem stage_mir5 (o : Oracle) : Stage (mirSem o) (mirSem o) mir4 mir5 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 14 14 (mir4_ends o) + (fun call _ => mir5_run o call) + +theorem mir5_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir5 call 14).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir4) (q := mir5) (n := 14) (m := 14) (mir4_ends o) + (fun call _ => mir5_run o call) + +/-- `stack-schedule`: mir5 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) mir5 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 14 14 (mir5_ends o) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 14).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := mir5) (q := sched) (n := 14) (m := 14) (mir5_ends o) + (fun call _ => sched_run o call) + +/-- `peephole-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 14 14 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 14).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 14) (m := 14) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `cfg-simplify-early`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 14 8 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 8).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 14) (m := 8) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `compact-pushes`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 8 8 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 8).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 8) (m := 8) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `block-layout`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 8 8 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 8).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 8) (m := 8) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `share-reverts`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 8 8 (evm4_ends o) + (fun call _ => evm5_run o call) + +theorem evm5_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm5 call 8).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm4) (q := evm5) (n := 8) (m := 8) (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- `terminal-dedup`: evm5 to evm6. -/ +theorem stage_evm6 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm5 evm6 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 8 8 (evm5_ends o) + (fun call _ => evm6_run o call) + +theorem evm6_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm6 call 8).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm5) (q := evm6) (n := 8) (m := 8) (evm5_ends o) + (fun call _ => evm6_run o call) + +/-- `cfg-simplify-early`: evm6 to evm7. -/ +theorem stage_evm7 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm6 evm7 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 8 6 (evm6_ends o) + (fun call _ => evm7_run o call) + +theorem evm7_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm7 call 6).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm6) (q := evm7) (n := 8) (m := 6) (evm6_ends o) + (fun call _ => evm7_run o call) + +/-- `block-cse`: evm7 to evm8. -/ +theorem stage_evm8 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm7 evm8 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 6 6 (evm7_ends o) + (fun call _ => evm8_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1, mir2, mir3, mir4, mir5], sched, [evm1, evm2, evm3, evm4, evm5, evm6, evm7, evm8]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem event_words_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm8 anyCall := + mir_to_evmir o anyCall compilation ⟨stage_mir1 o, stage_mir2 o, stage_mir3 o, stage_mir4 o, stage_mir5 o, trivial⟩ (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, stage_evm6 o, stage_evm7 o, stage_evm8 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.EventWords.stage_mir1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir1 + +/-- info: 'SolarTV.Milestone.EventWords.stage_mir2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir2 + +/-- info: 'SolarTV.Milestone.EventWords.stage_mir3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir3 + +/-- info: 'SolarTV.Milestone.EventWords.stage_mir4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir4 + +/-- info: 'SolarTV.Milestone.EventWords.stage_mir5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir5 + +/-- info: 'SolarTV.Milestone.EventWords.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.EventWords.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.EventWords.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.EventWords.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.EventWords.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.EventWords.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.EventWords.stage_evm6' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm6 + +/-- info: 'SolarTV.Milestone.EventWords.stage_evm7' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm7 + +/-- info: 'SolarTV.Milestone.EventWords.stage_evm8' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm8 + +/-- info: 'SolarTV.Milestone.EventWords.event_words_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms event_words_mir_to_evmir + +end SolarTV.Milestone.EventWords diff --git a/Certified/event_words/Shape.lean b/Certified/event_words/Shape.lean new file mode 100644 index 00000000..d15b4ab4 --- /dev/null +++ b/Certified/event_words/Shape.lean @@ -0,0 +1,113 @@ +import Verify.ShapeGeneric +import SolidCore.Refinement.Solar.EventWords.Lowering +import event_words.Proofs.Stages +import event_words.gen.EventWords.Bytecode + +-- Generated by solar's tools/certify/shape_gen.py from event_words/shape.json and this run's export; +-- do not edit. Untrusted data and composition: the kernel re-derives every claim. + +/-! +# EventWords: the proof of the published statement + +`published` applies `SolidCore.Refinement.Shapes.compiled` to the source check of `SolidCore.Refinement.Solar.EventWords`, solar-tv's backend +stages to `evm8` (`SolarTV.Milestone.EventWords.event_words_mir_to_evmir`), the final EVM IR's run within 6 blocks on every +call (the last stage's fuel) and the loop checker on the exact bytecode, with the certificate +tools/certify/asm_cert.py inferred. The gas bound is `gasBoundL cert 6` = 22100 · (6 · 77) + 24 += 10210224, at most the statement's 10210224. +-/ + +namespace Certified.event_words.Shape + +open SolidCore.Refinement SolidCore.Refinement.Solar SolarTV + +/-- The exported runtime bytecode. -/ +def code : ByteArray := ⟨(SolarTV.Export.EventWords.bytecode.map UInt8.ofNat).toArray⟩ + +/-- The loop checker's certificate (tools/certify/asm_cert.py). -/ +def cert : SolidCore.Refinement.Solar.Assemble.Cert := + { offsets := [0x0, 0x89, 0x8d, 0x9d, 0xb3, 0xcb], + needs := [0, 0, 3, 4, 3, 5], + top := 256, + turned := [], + costs := [77, 3, 2, 12, 11, 7], + types := [[], + [], + [some false, some false, some false], + [some false, some false, some false, some false], + [some false, some false, some false], + [some false, some false, some false, some false, some false]], + rets := [], + env := true, + reads := false } + +/-- The highest stack each block is entered with. -/ +def maxs : List Nat := [0, 1, 3, 6, 3, 5] + +set_option maxRecDepth 100000 in +theorem walk_ok : (SolarTV.Assembly.walk (SolidCore.Refinement.Solar.Assemble.bytesOf code) cert.offset 0 + (SolidCore.Refinement.Solar.Assemble.lower SolarTV.Export.EventWords.evm8 cert)).isSome = true := by + have hw := SolidCore.Refinement.Solar.Assemble.walkS_drop (SolidCore.Refinement.Solar.Assemble.bytesOf code) cert.offset (SolidCore.Refinement.Solar.Assemble.lower SolarTV.Export.EventWords.evm8 cert) 0 + (Nat.zero_le _) + rw [List.drop_zero] at hw + rw [← hw] + decide +kernel + +set_option maxRecDepth 100000 in +theorem blocks_ok : SolidCore.Refinement.Solar.AssembleLoop.blocksOkL SolarTV.Export.EventWords.evm8 cert maxs 0 SolarTV.Export.EventWords.evm8.blocks = true := by + decide +kernel + +theorem labels_ok : SolidCore.Refinement.Solar.Assemble.labelsValid SolarTV.Export.EventWords.evm8 cert code = true := + SolidCore.Refinement.Solar.Assemble.labelsValid_of_walk walk_ok + +theorem size_ok : code.size < 2 ^ 32 := by decide +kernel + +/-- The checker of code with loops accepts the exact bytecode for the final EVM IR. -/ +theorem check_ok : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.EventWords.evm8 code cert maxs = true := by + simp only [SolidCore.Refinement.Solar.AssembleLoop.checkL, walk_ok, blocks_ok, labels_ok, decide_eq_true size_ok, Bool.and_true, + Bool.true_and] + decide + +/-- The final EVM IR ends within 6 blocks on every call, under the bytecode's oracle. -/ +theorem ends (call : Call) : (EVM.Program.run SolidCore.Refinement.Shapes.oracle SolarTV.Export.EventWords.evm8 call 6).isSome = true := + SolarTV.Milestone.W1.ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := SolidCore.Refinement.Shapes.oracle) (p := SolarTV.Export.EventWords.evm7) (q := SolarTV.Export.EventWords.evm8) (n := 6) (m := 6) + (SolarTV.Milestone.EventWords.evm7_ends SolidCore.Refinement.Shapes.oracle) (fun call _ => SolarTV.Milestone.EventWords.evm8_run SolidCore.Refinement.Shapes.oracle call) call trivial + +/-- The bytecode with byte `i` replaced by `b`. -/ +def mutant (i b : Nat) : ByteArray := ⟨((SolarTV.Export.EventWords.bytecode.set i b).map UInt8.ofNat).toArray⟩ + +set_option maxRecDepth 100000 in +/-- The checker rejects the bytecode with a jump target moved (byte 2). -/ +theorem rejects_jump : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.EventWords.evm8 (mutant 2 138) cert maxs = false := by + decide +kernel + +theorem gas_lt : SolidCore.Refinement.Solar.AssembleLoop.gasBoundL cert 6 < 2 ^ 64 := by decide +kernel + +theorem gas_le : SolidCore.Refinement.Solar.AssembleLoop.gasBoundL cert 6 ≤ 10210224 := by decide +kernel + +/-- SolidCore type checks the contract. -/ +theorem contract_ok : ∃ c, SolidCore.Refinement.Solar.EventWords.contract? = .ok c := by + have h := SolidCore.Refinement.Solar.EventWords.shape_eq + unfold SolidCore.Refinement.Solar.EventWords.shape? at h + split at h + · next c hc => exact ⟨c, hc⟩ + · simp at h + + +/-- **What the published statement asks of this module.** -/ +theorem published : ∃ c, SolidCore.Refinement.Solar.EventWords.contract? = .ok c ∧ + SolidCore.Refinement.Shapes.Compiled (solidCore SolidCore.Refinement.Solar.EventWords.fuel) c code (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.EventWords.fns) ([])) (fun _ => 10210224) := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, d, hd⟩ := SolidCore.Refinement.Solar.EventWords.deployed_of hc + have hchk := SolidCore.Refinement.Solar.EventWords.check_stage0 + rw [← hk] at hchk + have hval := SolidCore.Refinement.Solar.EventWords.checkValue_stage0 + rw [← hk] at hval + exact ⟨c, hc, (SolidCore.Refinement.Shapes.compiled hd hchk hval (SolidCore.Refinement.Shapes.genericValid_inhabited _ _ _) + (SolarTV.Milestone.EventWords.event_words_mir_to_evmir SolidCore.Refinement.Shapes.oracle) (fun _ _ => trivial) ends check_ok gas_lt).mono_gas (fun _ => gas_le) (fun _ => by decide)⟩ + +/-- info: 'Certified.event_words.Shape.published' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms published + +end Certified.event_words.Shape diff --git a/Certified/event_words/Statement.lean b/Certified/event_words/Statement.lean new file mode 100644 index 00000000..6aefd112 --- /dev/null +++ b/Certified/event_words/Statement.lean @@ -0,0 +1,54 @@ +import Verify.Shapes +import Verify.ShapeGeneric +import event_words.gen.EventWords.Bytecode +import SolidCore.Refinement.Solar.EventWords.Lowering + +-- Generated by solar's tools/certify/final.py from event_words/shape.json and the bytecode the +-- driver compiled in this run; do not edit. This module never imports the proof module. + +/-! +# EventWords: the published statement + +`Statement` binds the exact runtime bytecode (`runtimeHex`, from the driver's own compile) and +states _root_.SolidCore.Refinement.Shapes.Compiled of it against the checked source on the declared valid calls. +-/ + +namespace Certified.event_words.Final + +/-- The runtime bytecode the pinned solar emitted in this run, as hex (for the reader). -/ +def runtimeHex : String := + "346089575f3560e01c8063562e19df03608957608060405260843560a01c60a43610176089576084355f1960601c8116608080600435825260243560a05260443560c05260643560e05283337fd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d8228385a380820360cb5750505f1960601c331160b357818103608d57005b5f5ffd5b6d010200000000000000020000001b5b60205260405260605263ed572b275f526064601cfd5b5f1960601c33690417000000000000000260201b609d565b6d0112000000000000000200000019919091609d56" + +/-- The same bytes, as numbers: what the statement binds. -/ +def runtimeBytes : List Nat := + [0x34, 0x60, 0x89, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x56, 0x2e, 0x19, 0xdf, 0x3, + 0x60, 0x89, 0x57, 0x60, 0x80, 0x60, 0x40, 0x52, 0x60, 0x84, 0x35, 0x60, 0xa0, 0x1c, 0x60, 0xa4, + 0x36, 0x10, 0x17, 0x60, 0x89, 0x57, 0x60, 0x84, 0x35, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x81, 0x16, + 0x60, 0x80, 0x80, 0x60, 0x4, 0x35, 0x82, 0x52, 0x60, 0x24, 0x35, 0x60, 0xa0, 0x52, 0x60, 0x44, + 0x35, 0x60, 0xc0, 0x52, 0x60, 0x64, 0x35, 0x60, 0xe0, 0x52, 0x83, 0x33, 0x7f, 0xd7, 0x8a, 0xd9, + 0x5f, 0xa4, 0x6c, 0x99, 0x4b, 0x65, 0x51, 0xd0, 0xda, 0x85, 0xfc, 0x27, 0x5f, 0xe6, 0x13, 0xce, + 0x37, 0x65, 0x7f, 0xb8, 0xd5, 0xe3, 0xd1, 0x30, 0x84, 0x1, 0x59, 0xd8, 0x22, 0x83, 0x85, 0xa3, + 0x80, 0x82, 0x3, 0x60, 0xcb, 0x57, 0x50, 0x50, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x33, 0x11, 0x60, + 0xb3, 0x57, 0x81, 0x81, 0x3, 0x60, 0x8d, 0x57, 0x0, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x6d, 0x1, + 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x1b, 0x5b, 0x60, 0x20, + 0x52, 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, 0x63, 0xed, 0x57, 0x2b, 0x27, 0x5f, 0x52, 0x60, 0x64, + 0x60, 0x1c, 0xfd, 0x5b, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x33, 0x69, 0x4, 0x17, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x2, 0x60, 0x20, 0x1b, 0x60, 0x9d, 0x56, 0x5b, 0x6d, 0x1, 0x12, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x19, 0x91, 0x90, 0x91, 0x60, 0x9d, + 0x56] + +/-- The freshly exported bytecode the obligations speak of. -/ +def code : ByteArray := ⟨(_root_.SolarTV.Export.EventWords.bytecode.map UInt8.ofNat).toArray⟩ + +/-- **The published statement.** -/ +def Statement : Prop := + _root_.Certified.event_words.Final.code.data.toList.map (·.toNat) = _root_.Certified.event_words.Final.runtimeBytes ∧ + (∃ c, SolidCore.Refinement.Solar.EventWords.contract? = .ok c ∧ + _root_.SolidCore.Refinement.Shapes.Compiled (_root_.SolidCore.Refinement.solidCore (SolidCore.Refinement.Solar.EventWords.fuel)) c _root_.Certified.event_words.Final.code + (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.EventWords.fns) ([])) (fun _ => 10210224)) + +set_option maxRecDepth 100000 in +theorem bound : _root_.Certified.event_words.Final.code.data.toList.map (·.toNat) = _root_.Certified.event_words.Final.runtimeBytes := + @of_decide_eq_true _ (instDecidableEqList _ _) (by decide +kernel) + +end Certified.event_words.Final diff --git a/Certified/event_words/bytecode.hex b/Certified/event_words/bytecode.hex new file mode 100644 index 00000000..27513110 --- /dev/null +++ b/Certified/event_words/bytecode.hex @@ -0,0 +1 @@ +346089575f3560e01c8063562e19df03608957608060405260843560a01c60a43610176089576084355f1960601c8116608080600435825260243560a05260443560c05260643560e05283337fd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d8228385a380820360cb5750505f1960601c331160b357818103608d57005b5f5ffd5b6d010200000000000000020000001b5b60205260405260605263ed572b275f526064601cfd5b5f1960601c33690417000000000000000260201b609d565b6d0112000000000000000200000019919091609d56 diff --git a/Certified/event_words/event_words.sol b/Certified/event_words/event_words.sol new file mode 100644 index 00000000..6d401dd3 --- /dev/null +++ b/Certified/event_words/event_words.sol @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +contract EventWords { + event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to); + + function swap(uint256 a0, uint256 a1, uint256 b0, uint256 b1, address to) external { + emit Swap(msg.sender, a0, a1, b0, b1, to); + } +} diff --git a/Certified/event_words/gen/EventWords/Bytecode.lean b/Certified/event_words/gen/EventWords/Bytecode.lean new file mode 100644 index 00000000..05241ce3 --- /dev/null +++ b/Certified/event_words/gen/EventWords/Bytecode.lean @@ -0,0 +1,28 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. -/ + +namespace SolarTV.Export.EventWords + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x89, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x56, 0x2e, 0x19, 0xdf, 0x03, + 0x60, 0x89, 0x57, 0x60, 0x80, 0x60, 0x40, 0x52, 0x60, 0x84, 0x35, 0x60, 0xa0, 0x1c, 0x60, 0xa4, + 0x36, 0x10, 0x17, 0x60, 0x89, 0x57, 0x60, 0x84, 0x35, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x81, 0x16, + 0x60, 0x80, 0x80, 0x60, 0x04, 0x35, 0x82, 0x52, 0x60, 0x24, 0x35, 0x60, 0xa0, 0x52, 0x60, 0x44, + 0x35, 0x60, 0xc0, 0x52, 0x60, 0x64, 0x35, 0x60, 0xe0, 0x52, 0x83, 0x33, 0x7f, 0xd7, 0x8a, 0xd9, + 0x5f, 0xa4, 0x6c, 0x99, 0x4b, 0x65, 0x51, 0xd0, 0xda, 0x85, 0xfc, 0x27, 0x5f, 0xe6, 0x13, 0xce, + 0x37, 0x65, 0x7f, 0xb8, 0xd5, 0xe3, 0xd1, 0x30, 0x84, 0x01, 0x59, 0xd8, 0x22, 0x83, 0x85, 0xa3, + 0x80, 0x82, 0x03, 0x60, 0xcb, 0x57, 0x50, 0x50, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x33, 0x11, 0x60, + 0xb3, 0x57, 0x81, 0x81, 0x03, 0x60, 0x8d, 0x57, 0x00, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x6d, 0x01, + 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x1b, 0x5b, 0x60, 0x20, + 0x52, 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, 0x63, 0xed, 0x57, 0x2b, 0x27, 0x5f, 0x52, 0x60, 0x64, + 0x60, 0x1c, 0xfd, 0x5b, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x33, 0x69, 0x04, 0x17, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x02, 0x60, 0x20, 0x1b, 0x60, 0x9d, 0x56, 0x5b, 0x6d, 0x01, 0x12, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x19, 0x91, 0x90, 0x91, 0x60, 0x9d, + 0x56] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "346089575f3560e01c8063562e19df03608957608060405260843560a01c60a43610176089576084355f1960601c8116608080600435825260243560a05260443560c05260643560e05283337fd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d8228385a380820360cb5750505f1960601c331160b357818103608d57005b5f5ffd5b6d010200000000000000020000001b5b60205260405260605263ed572b275f526064601cfd5b5f1960601c33690417000000000000000260201b609d565b6d0112000000000000000200000019919091609d56" + +end SolarTV.Export.EventWords diff --git a/Certified/event_words/gen/EventWords/Evm1.lean b/Certified/event_words/gen/EventWords/Evm1.lean new file mode 100644 index 00000000..55781d59 --- /dev/null +++ b/Certified/event_words/gen/EventWords/Evm1.lean @@ -0,0 +1,129 @@ +-- solar-lean-stage: kind=evm index=1 pass=peephole-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. -/ + +namespace SolarTV.Export.EventWords + +/-- The runtime EVM IR after `peephole-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 3, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x562e19df)), + .op (.stack .eq), + .jumpi 2, + .jump 3], + -- bb2 + [.jump 4], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 164)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 13, + .jump 5], + -- bb5 + [.op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .load, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .op .store, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 192)), + .op .store, + .op (.stack (.push 100)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op .store, + .op (.stack (.dup 3)), + .effect .caller 0, + .op (.stack (.push 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822)), + .op (.stack (.push 128)), + .op (.stack (.dup 5)), + .effect (.log 3) 5, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 11, + .jump 6], + -- bb6 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 10, + .jump 7], + -- bb7 + [.op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 9, + .jump 8], + -- bb8 + [.stop], + -- bb9 + [.op (.stack (.push 0x10200000000000000020000001b)), + .jump 12], + -- bb10 + [.op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack (.push 0x417000000000000000200000000)), + .jump 12], + -- bb11 + [.op (.stack (.push 0x112000000000000000200000019)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 12], + -- bb12 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb13 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.EventWords diff --git a/Certified/event_words/gen/EventWords/Evm2.lean b/Certified/event_words/gen/EventWords/Evm2.lean new file mode 100644 index 00000000..3dc0752c --- /dev/null +++ b/Certified/event_words/gen/EventWords/Evm2.lean @@ -0,0 +1,117 @@ +-- solar-lean-stage: kind=evm index=2 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. -/ + +namespace SolarTV.Export.EventWords + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x562e19df)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 164)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 7, + .op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .load, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .op .store, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 192)), + .op .store, + .op (.stack (.push 100)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op .store, + .op (.stack (.dup 3)), + .effect .caller 0, + .op (.stack (.push 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822)), + .op (.stack (.push 128)), + .op (.stack (.dup 5)), + .effect (.log 3) 5, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 5, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 4, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 3, + .stop], + -- bb9 + [.op (.stack (.push 0x10200000000000000020000001b)), + .jump 6], + -- bb10 + [.op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack (.push 0x417000000000000000200000000)), + .jump 6], + -- bb11 + [.op (.stack (.push 0x112000000000000000200000019)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 6], + -- bb12 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb13 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.EventWords diff --git a/Certified/event_words/gen/EventWords/Evm3.lean b/Certified/event_words/gen/EventWords/Evm3.lean new file mode 100644 index 00000000..80000e9e --- /dev/null +++ b/Certified/event_words/gen/EventWords/Evm3.lean @@ -0,0 +1,128 @@ +-- solar-lean-stage: kind=evm index=3 pass=compact-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. -/ + +namespace SolarTV.Export.EventWords + +/-- The runtime EVM IR after `compact-pushes`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x562e19df)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 164)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 7, + .op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .load, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .op .store, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 192)), + .op .store, + .op (.stack (.push 100)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op .store, + .op (.stack (.dup 3)), + .effect .caller 0, + .op (.stack (.push 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822)), + .op (.stack (.push 128)), + .op (.stack (.dup 5)), + .effect (.log 3) 5, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 5, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 4, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 3, + .stop], + -- bb9 + [.op (.stack (.push 0x10200000000000000020000001b)), + .jump 6], + -- bb10 + [.op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack (.push 0x4170000000000000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .jump 6], + -- bb11 + [.op (.stack (.push 0x112000000000000000200000019)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 6], + -- bb12 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb13 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.EventWords diff --git a/Certified/event_words/gen/EventWords/Evm4.lean b/Certified/event_words/gen/EventWords/Evm4.lean new file mode 100644 index 00000000..f8bc8b20 --- /dev/null +++ b/Certified/event_words/gen/EventWords/Evm4.lean @@ -0,0 +1,128 @@ +-- solar-lean-stage: kind=evm index=4 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. -/ + +namespace SolarTV.Export.EventWords + +/-- The runtime EVM IR after `block-layout`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x562e19df)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 164)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 7, + .op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .load, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .op .store, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 192)), + .op .store, + .op (.stack (.push 100)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op .store, + .op (.stack (.dup 3)), + .effect .caller 0, + .op (.stack (.push 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822)), + .op (.stack (.push 128)), + .op (.stack (.dup 5)), + .effect (.log 3) 5, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 6, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 5, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 3, + .stop], + -- bb9 + [.op (.stack (.push 0x10200000000000000020000001b)), + .jump 4], + -- bb12 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack (.push 0x4170000000000000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .jump 4], + -- bb11 + [.op (.stack (.push 0x112000000000000000200000019)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 4], + -- bb13 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.EventWords diff --git a/Certified/event_words/gen/EventWords/Evm5.lean b/Certified/event_words/gen/EventWords/Evm5.lean new file mode 100644 index 00000000..c163d12a --- /dev/null +++ b/Certified/event_words/gen/EventWords/Evm5.lean @@ -0,0 +1,128 @@ +-- solar-lean-stage: kind=evm index=5 pass=share-reverts +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. -/ + +namespace SolarTV.Export.EventWords + +/-- The runtime EVM IR after `share-reverts`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x562e19df)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 164)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 7, + .op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .load, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .op .store, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 192)), + .op .store, + .op (.stack (.push 100)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op .store, + .op (.stack (.dup 3)), + .effect .caller 0, + .op (.stack (.push 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822)), + .op (.stack (.push 128)), + .op (.stack (.dup 5)), + .effect (.log 3) 5, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 6, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 5, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 3, + .stop], + -- bb9 + [.op (.stack (.push 0x10200000000000000020000001b)), + .jump 4], + -- bb12 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack (.push 0x4170000000000000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .jump 4], + -- bb11 + [.op (.stack (.push 0x112000000000000000200000019)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 4], + -- bb13 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.EventWords diff --git a/Certified/event_words/gen/EventWords/Evm6.lean b/Certified/event_words/gen/EventWords/Evm6.lean new file mode 100644 index 00000000..fab51d7a --- /dev/null +++ b/Certified/event_words/gen/EventWords/Evm6.lean @@ -0,0 +1,126 @@ +-- solar-lean-stage: kind=evm index=6 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. -/ + +namespace SolarTV.Export.EventWords + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm6 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x562e19df)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 164)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 7, + .op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .load, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .op .store, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 192)), + .op .store, + .op (.stack (.push 100)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op .store, + .op (.stack (.dup 3)), + .effect .caller 0, + .op (.stack (.push 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822)), + .op (.stack (.push 128)), + .op (.stack (.dup 5)), + .effect (.log 3) 5, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 6, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 5, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 3, + .stop], + -- bb9 + [.op (.stack (.push 0x10200000000000000020000001b)), + .jump 4], + -- bb12 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack (.push 0x4170000000000000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .jump 4], + -- bb11 + [.op (.stack (.push 0x112000000000000000200000019)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 4], + -- bb13 + [.jump 1]] } + +end SolarTV.Export.EventWords diff --git a/Certified/event_words/gen/EventWords/Evm7.lean b/Certified/event_words/gen/EventWords/Evm7.lean new file mode 100644 index 00000000..1bdd141e --- /dev/null +++ b/Certified/event_words/gen/EventWords/Evm7.lean @@ -0,0 +1,122 @@ +-- solar-lean-stage: kind=evm index=7 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. -/ + +namespace SolarTV.Export.EventWords + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm7 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x562e19df)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 164)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .load, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .op .store, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 192)), + .op .store, + .op (.stack (.push 100)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op .store, + .op (.stack (.dup 3)), + .effect .caller 0, + .op (.stack (.push 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822)), + .op (.stack (.push 128)), + .op (.stack (.dup 5)), + .effect (.log 3) 5, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 5, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 4, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 2, + .stop], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb9 + [.op (.stack (.push 0x10200000000000000020000001b)), + .jump 3], + -- bb12 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack (.push 0x4170000000000000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .jump 3], + -- bb11 + [.op (.stack (.push 0x112000000000000000200000019)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 3]] } + +end SolarTV.Export.EventWords diff --git a/Certified/event_words/gen/EventWords/Evm8.lean b/Certified/event_words/gen/EventWords/Evm8.lean new file mode 100644 index 00000000..efa1da18 --- /dev/null +++ b/Certified/event_words/gen/EventWords/Evm8.lean @@ -0,0 +1,121 @@ +-- solar-lean-stage: kind=evm index=8 pass=block-cse +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. -/ + +namespace SolarTV.Export.EventWords + +/-- The runtime EVM IR after `block-cse`. -/ +def evm8 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x562e19df)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 164)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 128)), + .op (.stack (.dup 0)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .op .store, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 192)), + .op .store, + .op (.stack (.push 100)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op .store, + .op (.stack (.dup 3)), + .effect .caller 0, + .op (.stack (.push 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822)), + .op (.stack (.dup 3)), + .op (.stack (.dup 5)), + .effect (.log 3) 5, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 5, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 4, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 2, + .stop], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb9 + [.op (.stack (.push 0x10200000000000000020000001b)), + .jump 3], + -- bb12 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack (.push 0x4170000000000000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .jump 3], + -- bb11 + [.op (.stack (.push 0x112000000000000000200000019)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 3]] } + +end SolarTV.Export.EventWords diff --git a/Certified/event_words/gen/EventWords/Manifest.lean b/Certified/event_words/gen/EventWords/Manifest.lean new file mode 100644 index 00000000..8e73e0a7 --- /dev/null +++ b/Certified/event_words/gen/EventWords/Manifest.lean @@ -0,0 +1,50 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.EventWords.Manifest + +def sources : List (String × String) := + [("Certified/event_words/event_words.sol", "b049dde6594516d1014c39022c6d2250234f3afc5cb71118e9e6e60ddfef43a9")] + +def compiler : String := "0.8.38+commit.38b5232a.solar.0.3.0-dev" + +def arguments : List String := + ["Certified/event_words/event_words.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/event_words/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "384da7bfc188221dd38d208139332f9c70b36879889764faf7e2fe8b12803d4a"), + ("Mir1", "mir1", "place-reads", "626760ccbc67935ac0b9cabf6e31886d4905ce3ceff57e7a6db042f89de96ed9"), + ("Mir2", "mir2", "dce", "c68a86ca7cd863664484b6b6107e9eac916d8ab6a3951d957606e26d360feb9f"), + ("Mir3", "mir3", "spell-width-tests", "cf00b6d959980e22eb7322c7a74155fda5c53075cdd1989e127cf6643d5c69e9"), + ("Mir4", "mir4", "lower-assumes", "bafddc49951ce8114532bc3b9fba33f0e57f77b4f768d0ee13ec1cd56e30ebc5"), + ("Mir5", "mir5", "evm-inst-schedule", "3e29dfd9fc358541980333fb78cfc4eed270ca5e8dcd89e4fd18a90ecc956d59"), + ("Sched", "sched", "stack-schedule", "07fafd4068a421cb4a19386abd1869dd6c98f081e305983aa367623e33d75a41"), + ("Evm1", "evm1", "peephole-early", "438868a34636004336afa6902bc44dc659b5ea176bbc977d24ff3a85ce8aa922"), + ("Evm2", "evm2", "cfg-simplify-early", "e8728dfdf3bf6600f5d1eb27a2b8068ac12a73d80b3c8cb116aa42847ff46614"), + ("Evm3", "evm3", "compact-pushes", "43d92bb5e723289a899bf4501781ab8579f4ce87f7eec2dde270c18ab312b106"), + ("Evm4", "evm4", "block-layout", "69644fa13497ed1ce4bcff16ff583ecdc9ff036471d8d704f65104924dee2ebf"), + ("Evm5", "evm5", "share-reverts", "768892d917de9ce4687e5c9d2abfa257fff04c5f18230cf760516eb43b14c0b9"), + ("Evm6", "evm6", "terminal-dedup", "bc60c204eb865eb988c1f1c45e83af5c5fe330a3158f1f2e5a1b062cb6e0e00f"), + ("Evm7", "evm7", "cfg-simplify-early", "d1c2725dbb9cd8cc253a8f46471a3abc0ce97547843f3665788b62cfb800412c"), + ("Evm8", "evm8", "block-cse", "fc2b7223ca3950b3a7ae20bdbd1bd7fc02a771bf385d11f4696d0995b0ffad2d"), + ("Bytecode", "bytecode", "assemble", "1c5a9dcfa4ce625fe8aefac4edc1dc12f9e705619d5323f1c90118b020dac702")] + +def bytecodeHex : String := + "346089575f3560e01c8063562e19df03608957608060405260843560a01c60a43610176089576084355f1960601c8116608080600435825260243560a05260443560c05260643560e05283337fd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d8228385a380820360cb5750505f1960601c331160b357818103608d57005b5f5ffd5b6d010200000000000000020000001b5b60205260405260605263ed572b275f526064601cfd5b5f1960601c33690417000000000000000260201b609d565b6d0112000000000000000200000019919091609d56" + +def bytecodeSha256 : String := "7913fabebc485079bd90fbab5a4b2ae172c9915254a24e52fff8755366fa612e" + +end SolarTV.Export.EventWords.Manifest diff --git a/Certified/event_words/gen/EventWords/Mir1.lean b/Certified/event_words/gen/EventWords/Mir1.lean new file mode 100644 index 00000000..5e084b4e --- /dev/null +++ b/Certified/event_words/gen/EventWords/Mir1.lean @@ -0,0 +1,77 @@ +-- solar-lean-stage: kind=mir index=1 pass=place-reads +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. -/ + +namespace SolarTV.Export.EventWords + +/-- The lowered MIR module after `place-reads`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @swap + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 164], + .effect (some 17) .calldataload [.const 4], + .effect (some 19) .calldataload [.const 36], + .effect (some 21) .calldataload [.const 68], + .effect (some 23) .calldataload [.const 100], + .effect (some 25) .calldataload [.const 132], + .pure 27 .gt [.value 25, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 51 .or [.value 15, .value 27]], + .branch (.value 51) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 56) .calldataload [.const 132], + .effect (some 55) .calldataload [.const 100], + .effect (some 54) .calldataload [.const 68], + .effect (some 53) .calldataload [.const 36], + .effect (some 52) .calldataload [.const 4], + .pure 49 .and [.value 56, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 6) .caller [], + .heapFloor 45 128, + .effect (some 47) .mload [.const 64], + .assume false .eq [.value 45, .value 47], + .effect none .mstore [.value 45, .value 52], + .pure 33 .add [.value 45, .const 32], + .effect none .mstore [.value 33, .value 53], + .pure 36 .add [.value 45, .const 64], + .effect none .mstore [.value 36, .value 54], + .pure 39 .add [.value 45, .const 96], + .effect none .mstore [.value 39, .value 55], + .effect none (.log 3) [.value 45, .const 128, .const 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822, .value 6, .value 56], + .assume true .gt [.value 6, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 49, .value 56]], + .stop⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x562e19df, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.EventWords diff --git a/Certified/event_words/gen/EventWords/Mir2.lean b/Certified/event_words/gen/EventWords/Mir2.lean new file mode 100644 index 00000000..d6271a98 --- /dev/null +++ b/Certified/event_words/gen/EventWords/Mir2.lean @@ -0,0 +1,73 @@ +-- solar-lean-stage: kind=mir index=2 pass=dce +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. -/ + +namespace SolarTV.Export.EventWords + +/-- The lowered MIR module after `dce`. -/ +def mir2 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @swap + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 164], + .effect (some 25) .calldataload [.const 132], + .pure 27 .gt [.value 25, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 51 .or [.value 15, .value 27]], + .branch (.value 51) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 56) .calldataload [.const 132], + .effect (some 55) .calldataload [.const 100], + .effect (some 54) .calldataload [.const 68], + .effect (some 53) .calldataload [.const 36], + .effect (some 52) .calldataload [.const 4], + .pure 49 .and [.value 56, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 6) .caller [], + .heapFloor 45 128, + .effect (some 47) .mload [.const 64], + .assume false .eq [.value 45, .value 47], + .effect none .mstore [.value 45, .value 52], + .pure 33 .add [.value 45, .const 32], + .effect none .mstore [.value 33, .value 53], + .pure 36 .add [.value 45, .const 64], + .effect none .mstore [.value 36, .value 54], + .pure 39 .add [.value 45, .const 96], + .effect none .mstore [.value 39, .value 55], + .effect none (.log 3) [.value 45, .const 128, .const 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822, .value 6, .value 56], + .assume true .gt [.value 6, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 49, .value 56]], + .stop⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x562e19df, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.EventWords diff --git a/Certified/event_words/gen/EventWords/Mir3.lean b/Certified/event_words/gen/EventWords/Mir3.lean new file mode 100644 index 00000000..96801eb5 --- /dev/null +++ b/Certified/event_words/gen/EventWords/Mir3.lean @@ -0,0 +1,75 @@ +-- solar-lean-stage: kind=mir index=3 pass=spell-width-tests +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. -/ + +namespace SolarTV.Export.EventWords + +/-- The lowered MIR module after `spell-width-tests`. -/ +def mir3 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @swap + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 164], + .effect (some 25) .calldataload [.const 132], + .pure 58 .shr [.const 160, .value 25], + .word 61 (.value 15), + .pure 62 .or [.value 58, .value 61], + .ne 51 (.value 62) (.const 0)], + .branch (.value 51) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 56) .calldataload [.const 132], + .effect (some 55) .calldataload [.const 100], + .effect (some 54) .calldataload [.const 68], + .effect (some 53) .calldataload [.const 36], + .effect (some 52) .calldataload [.const 4], + .pure 49 .and [.value 56, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 6) .caller [], + .heapFloor 45 128, + .effect (some 47) .mload [.const 64], + .assume false .eq [.value 45, .value 47], + .effect none .mstore [.value 45, .value 52], + .pure 33 .add [.value 45, .const 32], + .effect none .mstore [.value 33, .value 53], + .pure 36 .add [.value 45, .const 64], + .effect none .mstore [.value 36, .value 54], + .pure 39 .add [.value 45, .const 96], + .effect none .mstore [.value 39, .value 55], + .effect none (.log 3) [.value 45, .const 128, .const 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822, .value 6, .value 56], + .assume true .gt [.value 6, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 49, .value 56]], + .stop⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x562e19df, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.EventWords diff --git a/Certified/event_words/gen/EventWords/Mir4.lean b/Certified/event_words/gen/EventWords/Mir4.lean new file mode 100644 index 00000000..b6edfbad --- /dev/null +++ b/Certified/event_words/gen/EventWords/Mir4.lean @@ -0,0 +1,104 @@ +-- solar-lean-stage: kind=mir index=4 pass=lower-assumes +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. -/ + +namespace SolarTV.Export.EventWords + +/-- The lowered MIR module after `lower-assumes`. -/ +def mir4 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @swap + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 164], + .effect (some 25) .calldataload [.const 132], + .pure 58 .shr [.const 160, .value 25], + .word 61 (.value 15), + .pure 62 .or [.value 58, .value 61], + .ne 51 (.value 62) (.const 0)], + .branch (.value 51) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 56) .calldataload [.const 132], + .effect (some 55) .calldataload [.const 100], + .effect (some 54) .calldataload [.const 68], + .effect (some 53) .calldataload [.const 36], + .effect (some 52) .calldataload [.const 4], + .pure 49 .and [.value 56, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 6) .caller [], + .heapFloor 45 128, + .effect (some 47) .mload [.const 64], + .effect none .mstore [.value 45, .value 52], + .pure 33 .add [.value 45, .const 32], + .effect none .mstore [.value 33, .value 53], + .pure 36 .add [.value 45, .const 64], + .effect none .mstore [.value 36, .value 54], + .pure 39 .add [.value 45, .const 96], + .effect none .mstore [.value 39, .value 55], + .effect none (.log 3) [.value 45, .const 128, .const 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822, .value 6, .value 56], + .ne 65 (.value 45) (.value 47)], + .branch (.value 65) 4 5⟩, + -- bb3 + ⟨[(71, [(4, .const 0x112000000000000000200000019), (6, .const 0x417000000000000000200000000), (8, .const 0x10200000000000000020000001b)]), (72, [(4, .value 45), (6, .value 6), (8, .value 49)]), (73, [(4, .value 47), (6, .const 0xffffffffffffffffffffffffffffffffffffffff), (8, .value 56)])], + [.effect none .mstore [.const 32, .value 71], + .effect none .mstore [.const 64, .value 72], + .effect none .mstore [.const 96, .value 73], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [.pure 67 .gt [.value 6, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 67) 6 7⟩, + -- bb6 + ⟨[], + [], + .jump 3⟩, + -- bb7 + ⟨[], + [.ne 69 (.value 49) (.value 56)], + .branch (.value 69) 8 9⟩, + -- bb8 + ⟨[], + [], + .jump 3⟩, + -- bb9 + ⟨[], + [], + .stop⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x562e19df, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.EventWords diff --git a/Certified/event_words/gen/EventWords/Mir5.lean b/Certified/event_words/gen/EventWords/Mir5.lean new file mode 100644 index 00000000..36ed2658 --- /dev/null +++ b/Certified/event_words/gen/EventWords/Mir5.lean @@ -0,0 +1,104 @@ +-- solar-lean-stage: kind=mir index=5 pass=evm-inst-schedule +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. -/ + +namespace SolarTV.Export.EventWords + +/-- The lowered MIR module after `evm-inst-schedule`. -/ +def mir5 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @swap + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 25) .calldataload [.const 132], + .pure 58 .shr [.const 160, .value 25], + .effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 164], + .word 61 (.value 15), + .pure 62 .or [.value 58, .value 61], + .ne 51 (.value 62) (.const 0)], + .branch (.value 51) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 56) .calldataload [.const 132], + .effect (some 55) .calldataload [.const 100], + .effect (some 54) .calldataload [.const 68], + .effect (some 53) .calldataload [.const 36], + .effect (some 52) .calldataload [.const 4], + .pure 49 .and [.value 56, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 6) .caller [], + .heapFloor 45 128, + .effect (some 47) .mload [.const 64], + .effect none .mstore [.value 45, .value 52], + .pure 33 .add [.value 45, .const 32], + .effect none .mstore [.value 33, .value 53], + .pure 36 .add [.value 45, .const 64], + .effect none .mstore [.value 36, .value 54], + .pure 39 .add [.value 45, .const 96], + .effect none .mstore [.value 39, .value 55], + .effect none (.log 3) [.value 45, .const 128, .const 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822, .value 6, .value 56], + .ne 65 (.value 45) (.value 47)], + .branch (.value 65) 4 5⟩, + -- bb3 + ⟨[(71, [(4, .const 0x112000000000000000200000019), (6, .const 0x417000000000000000200000000), (8, .const 0x10200000000000000020000001b)]), (72, [(4, .value 45), (6, .value 6), (8, .value 49)]), (73, [(4, .value 47), (6, .const 0xffffffffffffffffffffffffffffffffffffffff), (8, .value 56)])], + [.effect none .mstore [.const 32, .value 71], + .effect none .mstore [.const 64, .value 72], + .effect none .mstore [.const 96, .value 73], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [.pure 67 .gt [.value 6, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 67) 6 7⟩, + -- bb6 + ⟨[], + [], + .jump 3⟩, + -- bb7 + ⟨[], + [.ne 69 (.value 49) (.value 56)], + .branch (.value 69) 8 9⟩, + -- bb8 + ⟨[], + [], + .jump 3⟩, + -- bb9 + ⟨[], + [], + .stop⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x562e19df, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.EventWords diff --git a/Certified/event_words/gen/EventWords/Sched.lean b/Certified/event_words/gen/EventWords/Sched.lean new file mode 100644 index 00000000..4298229c --- /dev/null +++ b/Certified/event_words/gen/EventWords/Sched.lean @@ -0,0 +1,137 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. -/ + +namespace SolarTV.Export.EventWords + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 3, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x562e19df)), + .op (.stack .eq), + .jumpi 2, + .jump 3], + -- bb2 + [.jump 4], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 164)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 13, + .jump 5], + -- bb5 + [.op (.stack (.push 132)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .load, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 2)), + .op .store, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 32)), + .op (.stack (.dup 3)), + .op (.stack .add), + .op .store, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 64)), + .op (.stack (.dup 3)), + .op (.stack .add), + .op .store, + .op (.stack (.push 100)), + .effect .calldataload 1, + .op (.stack (.push 96)), + .op (.stack (.dup 3)), + .op (.stack .add), + .op .store, + .op (.stack (.dup 3)), + .effect .caller 0, + .op (.stack (.push 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822)), + .op (.stack (.push 128)), + .op (.stack (.dup 5)), + .effect (.log 3) 5, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 11, + .jump 6], + -- bb6 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 10, + .jump 7], + -- bb7 + [.op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 9, + .jump 8], + -- bb8 + [.stop], + -- bb9 + [.op (.stack (.push 0x10200000000000000020000001b)), + .jump 12], + -- bb10 + [.op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack (.push 0x417000000000000000200000000)), + .jump 12], + -- bb11 + [.op (.stack (.push 0x112000000000000000200000019)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 12], + -- bb12 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb13 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.EventWords diff --git a/Certified/event_words/gen/EventWords/Schedule.json b/Certified/event_words/gen/EventWords/Schedule.json new file mode 100644 index 00000000..d24540a3 --- /dev/null +++ b/Certified/event_words/gen/EventWords/Schedule.json @@ -0,0 +1,24 @@ +{ + "functions": [ + {"function": 1, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [3, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 0, "entry": 4, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [4, 3], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [13, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [5, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [12, 0], "layout": ["v73", "v72", "v71"], "floating": true, "continues": null}, + {"block": 4, "start": [11, 0], "layout": ["v45", "v47"], "floating": true, "continues": null}, + {"block": 5, "start": [6, 0], "layout": ["v56", "v49", "junk", "junk"], "floating": true, "continues": null}, + {"block": 6, "start": [10, 0], "layout": [], "floating": true, "continues": null}, + {"block": 7, "start": [7, 0], "layout": ["v56", "v49"], "floating": true, "continues": null}, + {"block": 8, "start": [9, 0], "layout": ["v56", "v49"], "floating": true, "continues": null}, + {"block": 9, "start": [8, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]} + ] +} diff --git a/Certified/event_words/gen/EventWords/Stage0.lean b/Certified/event_words/gen/EventWords/Stage0.lean new file mode 100644 index 00000000..2b67fb1d --- /dev/null +++ b/Certified/event_words/gen/EventWords/Stage0.lean @@ -0,0 +1,72 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `EventWords`; do not edit. -/ + +namespace SolarTV.Export.EventWords + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @swap + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 164], + .effect (some 17) .calldataload [.const 4], + .effect (some 19) .calldataload [.const 36], + .effect (some 21) .calldataload [.const 68], + .effect (some 23) .calldataload [.const 100], + .effect (some 25) .calldataload [.const 132], + .pure 27 .gt [.value 25, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 51 .or [.value 15, .value 27]], + .branch (.value 51) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.pure 49 .and [.value 25, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 6) .caller [], + .heapFloor 45 128, + .effect (some 47) .mload [.const 64], + .assume false .eq [.value 45, .value 47], + .effect none .mstore [.value 45, .value 17], + .pure 33 .add [.value 45, .const 32], + .effect none .mstore [.value 33, .value 19], + .pure 36 .add [.value 45, .const 64], + .effect none .mstore [.value 36, .value 21], + .pure 39 .add [.value 45, .const 96], + .effect none .mstore [.value 39, .value 23], + .effect none (.log 3) [.value 45, .const 128, .const 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822, .value 6, .value 25], + .assume true .gt [.value 6, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 49, .value 25]], + .stop⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x562e19df, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.EventWords diff --git a/Certified/event_words/gen/EventWords/manifest.json b/Certified/event_words/gen/EventWords/manifest.json new file mode 100644 index 00000000..dad7f5b9 --- /dev/null +++ b/Certified/event_words/gen/EventWords/manifest.json @@ -0,0 +1,153 @@ +{ + "arguments": [ + "Certified/event_words/event_words.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/event_words/gen" + ], + "bytecode": "346089575f3560e01c8063562e19df03608957608060405260843560a01c60a43610176089576084355f1960601c8116608080600435825260243560a05260443560c05260643560e05283337fd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d8228385a380820360cb5750505f1960601c331160b357818103608d57005b5f5ffd5b6d010200000000000000020000001b5b60205260405260605263ed572b275f526064601cfd5b5f1960601c33690417000000000000000260201b609d565b6d0112000000000000000200000019919091609d56", + "bytecode_sha256": "7913fabebc485079bd90fbab5a4b2ae172c9915254a24e52fff8755366fa612e", + "compiler": "0.8.38+commit.38b5232a.solar.0.3.0-dev", + "contract": "EventWords", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"Certified/event_words/event_words.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/event_words/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/event_words/gen\"), keep_asts: false, forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "Certified/event_words/event_words.sol", + "sha256": "b049dde6594516d1014c39022c6d2250234f3afc5cb71118e9e6e60ddfef43a9" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "384da7bfc188221dd38d208139332f9c70b36879889764faf7e2fe8b12803d4a" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "place-reads", + "sha256": "626760ccbc67935ac0b9cabf6e31886d4905ce3ceff57e7a6db042f89de96ed9" + }, + { + "definition": "mir2", + "file": "Mir2.lean", + "index": 2, + "kind": "mir", + "pass": "dce", + "sha256": "c68a86ca7cd863664484b6b6107e9eac916d8ab6a3951d957606e26d360feb9f" + }, + { + "definition": "mir3", + "file": "Mir3.lean", + "index": 3, + "kind": "mir", + "pass": "spell-width-tests", + "sha256": "cf00b6d959980e22eb7322c7a74155fda5c53075cdd1989e127cf6643d5c69e9" + }, + { + "definition": "mir4", + "file": "Mir4.lean", + "index": 4, + "kind": "mir", + "pass": "lower-assumes", + "sha256": "bafddc49951ce8114532bc3b9fba33f0e57f77b4f768d0ee13ec1cd56e30ebc5" + }, + { + "definition": "mir5", + "file": "Mir5.lean", + "index": 5, + "kind": "mir", + "pass": "evm-inst-schedule", + "sha256": "3e29dfd9fc358541980333fb78cfc4eed270ca5e8dcd89e4fd18a90ecc956d59" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "07fafd4068a421cb4a19386abd1869dd6c98f081e305983aa367623e33d75a41" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "peephole-early", + "sha256": "438868a34636004336afa6902bc44dc659b5ea176bbc977d24ff3a85ce8aa922" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "e8728dfdf3bf6600f5d1eb27a2b8068ac12a73d80b3c8cb116aa42847ff46614" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "compact-pushes", + "sha256": "43d92bb5e723289a899bf4501781ab8579f4ce87f7eec2dde270c18ab312b106" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "block-layout", + "sha256": "69644fa13497ed1ce4bcff16ff583ecdc9ff036471d8d704f65104924dee2ebf" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "share-reverts", + "sha256": "768892d917de9ce4687e5c9d2abfa257fff04c5f18230cf760516eb43b14c0b9" + }, + { + "definition": "evm6", + "file": "Evm6.lean", + "index": 6, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "bc60c204eb865eb988c1f1c45e83af5c5fe330a3158f1f2e5a1b062cb6e0e00f" + }, + { + "definition": "evm7", + "file": "Evm7.lean", + "index": 7, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "d1c2725dbb9cd8cc253a8f46471a3abc0ce97547843f3665788b62cfb800412c" + }, + { + "definition": "evm8", + "file": "Evm8.lean", + "index": 8, + "kind": "evm", + "pass": "block-cse", + "sha256": "fc2b7223ca3950b3a7ae20bdbd1bd7fc02a771bf385d11f4696d0995b0ffad2d" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "1c5a9dcfa4ce625fe8aefac4edc1dc12f9e705619d5323f1c90118b020dac702" + } + ] +} diff --git a/Certified/event_words/options b/Certified/event_words/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/event_words/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/event_words/shape.json b/Certified/event_words/shape.json new file mode 100644 index 00000000..ce781d0f --- /dev/null +++ b/Certified/event_words/shape.json @@ -0,0 +1,38 @@ +{ + "kind": "compiled", + "contract": "SolidCore.Refinement.Solar.EventWords.contract?", + "fuel": "SolidCore.Refinement.Solar.EventWords.fuel", + "valid": "SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.EventWords.fns) ([])", + "gas": "fun _ => 10210224", + "env": [], + "spec": "none: solar-verify has no specification of event_words", + "spec_modules": [ + "SolidCore.Refinement.Solar.EventWords.Lowering", + "Verify.ShapeGeneric" + ], + "proof_module": "event_words.Shape", + "proof": "Certified.event_words.Shape.published", + "generic": { + "lowering": "SolidCore.Refinement.Solar.EventWords.Lowering", + "ns": "SolidCore.Refinement.Solar.EventWords", + "style": "core", + "check": "check_stage0", + "check_value": "checkValue_stage0", + "fns": "SolidCore.Refinement.Solar.EventWords.fns", + "storage": "[]" + }, + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "memory: the entry heap and heap floor are the constant words codegen placed (0x80); the event data is ABI-encoded at the free memory pointer", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: the function of EventWords.fns ABI-encoded with clean argument words (the address below 2^160), any value below 2^256, any storage; other call data is outside the statement", + "spec: none (solar-verify has no specification of event_words): equivalence, termination and resources only" + ], + "source_ast": { + "file": "SolidCore/Refinement/Source/EventWords.lean", + "namespace": "SolidCore.Refinement.Source.EventWords", + "contract": "EventWords" + } +} diff --git a/Certified/events/Final.lean b/Certified/events/Final.lean new file mode 100644 index 00000000..b74caf0f --- /dev/null +++ b/Certified/events/Final.lean @@ -0,0 +1,11 @@ +import events.Statement +import events.Shape + +-- Generated by solar's tools/certify/final.py; do not edit. The statement is +-- Certified.events.Final.Statement of events.Statement, which does not import the proof +-- module; the driver's checker requires `final`'s type to be exactly that constant. + +theorem Certified.events.Final.final : _root_.Certified.events.Final.Statement := + ⟨_root_.Certified.events.Final.bound, Certified.events.Shape.nonvacuous, Certified.events.Shape.published⟩ + +#print axioms Certified.events.Final.final diff --git a/Certified/events/Proofs.lean b/Certified/events/Proofs.lean new file mode 100644 index 00000000..6f3fcc7a --- /dev/null +++ b/Certified/events/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import events.Proofs.Stages +import events.Proofs.Assembly diff --git a/Certified/events/Proofs/Assembly.lean b/Certified/events/Proofs/Assembly.lean new file mode 100644 index 00000000..4bc3c936 --- /dev/null +++ b/Certified/events/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Items +import events.gen.Events.Evm5 +import events.gen.Events.Bytecode + +/-! The final EVM IR of `Events` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.Events + +open SolarTV.Assembly SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm5).getD [] + +theorem items_eq : itemsOf evm5 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x53 else if label = 2 then 0x57 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.Events.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.Events.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms decodes + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Runs/Evm1.lean b/Certified/events/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..bb9b9852 --- /dev/null +++ b/Certified/events/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import events.gen.Events.Evm1 +import events.gen.Events.Sched + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 10 = EVM.Program.run o evm1 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Events.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Runs/Evm2.lean b/Certified/events/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..c5b0b495 --- /dev/null +++ b/Certified/events/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import events.gen.Events.Evm2 +import events.gen.Events.Evm1 + +/-! `compact-pushes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 5 = EVM.Program.run o evm2 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Events.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Runs/Evm3.lean b/Certified/events/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..4cce876c --- /dev/null +++ b/Certified/events/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import events.gen.Events.Evm3 +import events.gen.Events.Evm2 + +/-! `share-reverts`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 5 = EVM.Program.run o evm3 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Events.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Runs/Evm4.lean b/Certified/events/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..012cdb84 --- /dev/null +++ b/Certified/events/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import events.gen.Events.Evm4 +import events.gen.Events.Evm3 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 5 = EVM.Program.run o evm4 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Events.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Runs/Evm5.lean b/Certified/events/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..78777881 --- /dev/null +++ b/Certified/events/Proofs/Runs/Evm5.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import events.gen.Events.Evm5 +import events.gen.Events.Evm4 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 5 = EVM.Program.run o evm5 call 3 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Events.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Runs/Mir1.lean b/Certified/events/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..623ccc1e --- /dev/null +++ b/Certified/events/Proofs/Runs/Mir1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import events.gen.Events.Mir1 +import events.gen.Events.Stage0 + +/-! `lower-assumes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir1_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 7 = MIR.Lowered.Module.run o mir1 call 10 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Events.mir1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_run + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Runs/Sched.lean b/Certified/events/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..0464b86e --- /dev/null +++ b/Certified/events/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import events.gen.Events.Sched +import events.gen.Events.Mir1 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir1 call 10 = EVM.Program.run o sched call 10 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Events.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Runs/Stage0.lean b/Certified/events/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..d3a1da5f --- /dev/null +++ b/Certified/events/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import events.gen.Events.Stage0 + +/-! The first lowered MIR ends on every call within 7 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 7).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.Events.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.Events diff --git a/Certified/events/Proofs/Stages.lean b/Certified/events/Proofs/Stages.lean new file mode 100644 index 00000000..3872816a --- /dev/null +++ b/Certified/events/Proofs/Stages.lean @@ -0,0 +1,131 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import events.Proofs.Runs.Stage0 +import events.Proofs.Runs.Mir1 +import events.Proofs.Runs.Sched +import events.Proofs.Runs.Evm1 +import events.Proofs.Runs.Evm2 +import events.Proofs.Runs.Evm3 +import events.Proofs.Runs.Evm4 +import events.Proofs.Runs.Evm5 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Events`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm5`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.Events + +open Machine SolarTV.Export.Events SolarTV.Milestone.W1 + +/-- `lower-assumes`: stage0 to mir1. -/ +theorem stage_mir1 (o : Oracle) : Stage (mirSem o) (mirSem o) stage0 mir1 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 7 10 (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +theorem mir1_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir1 call 10).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := stage0) (q := mir1) (n := 7) (m := 10) (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +/-- `stack-schedule`: mir1 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) mir1 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 10 10 (mir1_ends o) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 10).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := mir1) (q := sched) (n := 10) (m := 10) (mir1_ends o) + (fun call _ => sched_run o call) + +/-- `cfg-simplify-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 10 5 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 10) (m := 5) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `compact-pushes`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 5) (m := 5) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `share-reverts`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 5) (m := 5) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `terminal-dedup`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 5) (m := 5) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `cfg-simplify-early`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 3 (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1], sched, [evm1, evm2, evm3, evm4, evm5]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem events_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm5 anyCall := + mir_to_evmir o anyCall compilation ⟨stage_mir1 o, trivial⟩ (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.Events.stage_mir1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir1 + +/-- info: 'SolarTV.Milestone.Events.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.Events.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.Events.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.Events.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.Events.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.Events.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.Events.events_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms events_mir_to_evmir + +end SolarTV.Milestone.Events diff --git a/Certified/events/Shape.lean b/Certified/events/Shape.lean new file mode 100644 index 00000000..7f88415f --- /dev/null +++ b/Certified/events/Shape.lean @@ -0,0 +1,144 @@ +import Verify.ShapeGeneric +import SolidCore.Refinement.Solar.Events.Lowering +import events.Proofs.Stages +import events.gen.Events.Bytecode +import Verify.ShapeSpecExport +import events.SpecConnect + +-- Generated by solar's tools/certify/shape_gen.py from events/shape.json and this run's export; +-- do not edit. Untrusted data and composition: the kernel re-derives every claim. + +/-! +# Events: the proof of the published statement + +`published` applies `SolidCore.Refinement.Shapes.compiled` to the source check of `SolidCore.Refinement.Solar.Events`, solar-tv's backend +stages to `evm5` (`SolarTV.Milestone.Events.events_mir_to_evmir`), the final EVM IR's run within 3 blocks on every +call (the last stage's fuel) and the loop checker on the exact bytecode, with the certificate +tools/certify/asm_cert.py inferred. The gas bound is `gasBoundL cert 3` = 22100 · (3 · 36) + 12 += 2386812, at most the statement's 2386812. +-/ + +namespace Certified.events.Shape + +open SolidCore.Refinement SolidCore.Refinement.Solar SolarTV + +/-- The exported runtime bytecode. -/ +def code : ByteArray := ⟨(SolarTV.Export.Events.bytecode.map UInt8.ofNat).toArray⟩ + +/-- The loop checker's certificate (tools/certify/asm_cert.py). -/ +def cert : SolidCore.Refinement.Solar.Assemble.Cert := + { offsets := [0x0, 0x53, 0x57], + needs := [0, 0, 1], + top := 128, + turned := [], + costs := [36, 3, 21], + types := [[], + [], + [some false]], + rets := [], + env := true, + reads := false } + +/-- The highest stack each block is entered with. -/ +def maxs : List Nat := [0, 1, 1] + +set_option maxRecDepth 100000 in +theorem walk_ok : (SolarTV.Assembly.walk (SolidCore.Refinement.Solar.Assemble.bytesOf code) cert.offset 0 + (SolidCore.Refinement.Solar.Assemble.lower SolarTV.Export.Events.evm5 cert)).isSome = true := by + have hw := SolidCore.Refinement.Solar.Assemble.walkS_drop (SolidCore.Refinement.Solar.Assemble.bytesOf code) cert.offset (SolidCore.Refinement.Solar.Assemble.lower SolarTV.Export.Events.evm5 cert) 0 + (Nat.zero_le _) + rw [List.drop_zero] at hw + rw [← hw] + decide +kernel + +set_option maxRecDepth 100000 in +theorem blocks_ok : SolidCore.Refinement.Solar.AssembleLoop.blocksOkL SolarTV.Export.Events.evm5 cert maxs 0 SolarTV.Export.Events.evm5.blocks = true := by + decide +kernel + +theorem labels_ok : SolidCore.Refinement.Solar.Assemble.labelsValid SolarTV.Export.Events.evm5 cert code = true := + SolidCore.Refinement.Solar.Assemble.labelsValid_of_walk walk_ok + +theorem size_ok : code.size < 2 ^ 32 := by decide +kernel + +/-- The checker of code with loops accepts the exact bytecode for the final EVM IR. -/ +theorem check_ok : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.Events.evm5 code cert maxs = true := by + simp only [SolidCore.Refinement.Solar.AssembleLoop.checkL, walk_ok, blocks_ok, labels_ok, decide_eq_true size_ok, Bool.and_true, + Bool.true_and] + decide + +/-- The final EVM IR ends within 3 blocks on every call, under the bytecode's oracle. -/ +theorem ends (call : Call) : (EVM.Program.run SolidCore.Refinement.Shapes.oracle SolarTV.Export.Events.evm5 call 3).isSome = true := + SolarTV.Milestone.W1.ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := SolidCore.Refinement.Shapes.oracle) (p := SolarTV.Export.Events.evm4) (q := SolarTV.Export.Events.evm5) (n := 5) (m := 3) + (SolarTV.Milestone.Events.evm4_ends SolidCore.Refinement.Shapes.oracle) (fun call _ => SolarTV.Milestone.Events.evm5_run SolidCore.Refinement.Shapes.oracle call) call trivial + +/-- The bytecode with byte `i` replaced by `b`. -/ +def mutant (i b : Nat) : ByteArray := ⟨((SolarTV.Export.Events.bytecode.set i b).map UInt8.ofNat).toArray⟩ + +set_option maxRecDepth 100000 in +/-- The checker rejects the bytecode with a jump target moved (byte 2). -/ +theorem rejects_jump : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.Events.evm5 (mutant 2 84) cert maxs = false := by + decide +kernel + +theorem gas_lt : SolidCore.Refinement.Solar.AssembleLoop.gasBoundL cert 3 < 2 ^ 64 := by decide +kernel + +theorem gas_le : SolidCore.Refinement.Solar.AssembleLoop.gasBoundL cert 3 ≤ 2386812 := by decide +kernel + +/-- SolidCore type checks the contract. -/ +theorem contract_ok : ∃ c, SolidCore.Refinement.Solar.Events.contract? = .ok c := by + have h := SolidCore.Refinement.Solar.Events.shape_eq + unfold SolidCore.Refinement.Solar.Events.shape? at h + split at h + · next c hc => exact ⟨c, hc⟩ + · simp at h + + +/-- **What the published statement asks of this module.** -/ +theorem published : ∃ c, SolidCore.Refinement.Solar.Events.contract? = .ok c ∧ + SolidCore.Refinement.Shapes.Certified (solidCore SolidCore.Refinement.Solar.Events.fuel) c code (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.Events.fns) ([])) (SolidCore.Refinement.Shapes.bundleAllowed Certified.events.gen.Events.Spec.Events SolidCore.Refinement.Shapes.ctxOfCall) (SolidCore.Refinement.Shapes.bundlePost Certified.events.gen.Events.Spec.Events SolidCore.Refinement.Shapes.ctxOfCall SolidCore.Refinement.Shapes.idStep) (fun _ => 2386812) := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, d, hd⟩ := SolidCore.Refinement.Solar.Events.deployed_of hc + have hchk := SolidCore.Refinement.Solar.Events.check_stage0 + rw [← hk] at hchk + have hval := SolidCore.Refinement.Solar.Events.checkValue_stage0 + rw [← hk] at hval + have hholds : SolidCore.Spec.Holds (solidCore SolidCore.Refinement.Solar.Events.fuel) c (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.Events.fns) ([])) Certified.events.gen.Events.Spec.Events SolidCore.Refinement.Shapes.ctxOfCall SolidCore.Refinement.Shapes.idStep := by + refine SolidCore.Refinement.Shapes.holds_of_getElem ?_ + intro i hi + rcases i with _ | i + · exact SolidCore.Refinement.Shapes.holdsFn_genericValid hd hchk hval (fun _ => rfl) + (by first | exact Or.inl rfl | exact Or.inr (by simp [SolidCore.Refinement.Shapes.valueGuarded, SolidCore.Refinement.Shapes.valueZero, Certified.events.gen.Events.Spec.Events])) + (fn := events.SpecConnect.fn_transfer) (by rfl) (by decide) (events.SpecConnect.transfer_holds hc SolidCore.Refinement.Shapes.idStep) + · simp [Certified.events.gen.Events.Spec.Events] at hi + exact ⟨c, hc, ((SolidCore.Refinement.Shapes.compiled hd hchk hval (SolidCore.Refinement.Shapes.genericValid_inhabited _ _ _) + (SolarTV.Milestone.Events.events_mir_to_evmir SolidCore.Refinement.Shapes.oracle) (fun _ _ => trivial) ends check_ok gas_lt).mono_gas (fun _ => gas_le) (fun _ => by decide)).certified_of_holds + (fun _ h => h) hholds⟩ + +/-- info: 'Certified.events.Shape.published' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms published + +/-- **Non-vacuity**: `transfer` on zero words with no value, from the constructor's slots written with 0, +meets its precondition and its succeeds-if conditions, so the spec requires it to succeed: the same call +reverting is rejected by the exported postcondition and by the exported allowed statuses. -/ +theorem nonvacuous : + (∃ (call : SolarTV.Call) (obs : SolarTV.Observable), (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.Events.fns) ([])) call ∧ ¬ (SolidCore.Refinement.Shapes.bundlePost Certified.events.gen.Events.Spec.Events SolidCore.Refinement.Shapes.ctxOfCall SolidCore.Refinement.Shapes.idStep) call obs) ∧ + (∃ (call : SolarTV.Call) (obs : SolarTV.Observable), (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.Events.fns) ([])) call ∧ obs.success = false ∧ + ¬ (SolidCore.Refinement.Shapes.bundleAllowed Certified.events.gen.Events.Spec.Events SolidCore.Refinement.Shapes.ctxOfCall) call obs) := by + let wcall : SolarTV.Call := { calldata := SolidCore.Refinement.Abi.calldata 217554442 (List.replicate 2 0), callvalue := 0, storage := SolidCore.Refinement.Shapes.zeros ([]) } + have hpre : SolidCore.Spec.Pre Certified.events.gen.Events.Spec.Events ((Certified.events.gen.Events.Spec.Events).spec.specs[0]'(by decide)) + (SolidCore.Refinement.Shapes.ctxOfCall wcall) ⟨fun _ => 0, SolidCore.Spec.Ghost.zero, 0⟩ wcall (List.replicate 2 0) := by + refine ⟨SolidCore.Refinement.Shapes.decodes_zero (by decide) (by rfl) (by first | rfl | decide | simp [Certified.events.gen.Events.Spec.Events, SolidCore.Spec.decodeWords, SolidCore.Spec.Ty.ofWord]) 0 _, + (SolidCore.Refinement.Shapes.slotValue_zeros _).symm, by simp [SolidCore.Refinement.Shapes.ctxOfCall], ?_, ?_⟩ <;> + simp [SolidCore.Spec.Bundle.satAll, Certified.events.gen.Events.Spec.Events] + refine SolidCore.Refinement.Shapes.nonvacuous_of_succeeds (SolidCore.Refinement.Shapes.valid_of_find (SolidCore.Refinement.Shapes.covers_zeros _) (by decide)) + (List.getElem_mem _) hpre (by simp [Certified.events.gen.Events.Spec.Events]) ?_ + simp [SolidCore.Spec.Bundle.satAll, SolidCore.Spec.Bundle.sat, Certified.events.gen.Events.Spec.Events, SolidCore.Spec.eval, + SolidCore.Spec.BinOp.apply, SolidCore.Spec.mkEnv, SolidCore.Spec.Env.cur, SolidCore.Spec.ofProp, + SolidCore.Spec.slotOf, SolidCore.Spec.Ty.ofBits, SolidCore.Spec.toWord, SolidCore.Refinement.Shapes.ctxOfCall] + +/-- info: 'Certified.events.Shape.nonvacuous' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms nonvacuous + +end Certified.events.Shape diff --git a/Certified/events/SpecConnect.lean b/Certified/events/SpecConnect.lean new file mode 100644 index 00000000..a7c51773 --- /dev/null +++ b/Certified/events/SpecConnect.lean @@ -0,0 +1,111 @@ +-- Generated by solar's tools/certify/spec_connect.py. Do not edit. +import SolidCore.Refinement.Solar.Events.Lowering +import events.gen.Events.Spec +import Verify.Spec.Tree +import Verify.Spec.TreeMap +import Verify.Spec.TreeMapNested +import Verify.Spec.TreeIn +import Verify.Spec.TreeSucceeds +import Verify.VC.KernelIdx +import SolidCore.Refinement.KernelRfl + +/-! +# Certified.events.gen.Events.Spec.Events, of SolidCore's checked contract, from the erased trees + +For each function of the exported spec: the generic source stage's tree (`_erase_eq`, `deploy_eq`), +the spec of the tree (`_meets`) and the spec of SolidCore's contract on the stage's calls +(`_holds`, `SolidCore.Spec.holdsFn_of_tree`). See tools/certify/spec_connect.py. +-/ + +namespace events.SpecConnect + +open SolidCore.Spec SolidCore.Refinement SolidCore.Refinement.Generic + +/-- The exported spec. -/ +abbrev spec : Bundle := Certified.events.gen.Events.Spec.Events + +/-- The call context of the stage's calls (no value), as SolidCore's runs see it. -/ +def ctx : Ctx := { sender := 0x2000, value := 0, timestamp := 1, self := 0x1000 } + +/-- The call context of every call: `ctx` with the call's value. -/ +def ctxOf (call : SolarTV.Call) : Ctx := { ctx with value := call.callvalue } + +/-- The storage the constructor leaves. -/ +def deployed : List (Nat × Nat) := [] + +/-- Whether the contract deploys with that storage and no logs. -/ +def deploy? : Bool := + match SolidCore.Refinement.Solar.Events.contract? with + | .ok c => Wide.deployedAt SolidCore.Refinement.Solar.Events.fuel c deployed + | .error _ => false + +kernel_rfl deploy_eq deploy? true using SolidCore.Refinement.Solar.Events.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Refinement.Solar.Events.digest_eq + +/-- `Events.transfer` as the stage's ABI sees it (only the number of its parameters matters). -/ +def fn_transfer : SolidCore.Refinement.Abi.Fn := ⟨217554442, List.replicate 2 (.uint 256)⟩ + +/-- The generic source stage's erasure of `Events.transfer`. -/ +def transfer_tree : Tree := + SolidCore.Refinement.Generic.Tree.halt true [] [] [{ topics := [SolidCore.Refinement.Generic.WExpr.lit 57743509088182381206199446994789903859235539828100749539486038820882091805673, SolidCore.Refinement.Generic.WExpr.lit 8192, SolidCore.Refinement.Generic.WExpr.arg 0], data := [SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 0, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 1, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 2, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 3, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 4, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 5, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 6, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 7, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 8, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 9, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 10, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 11, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 12, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 13, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 14, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 15, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 16, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 17, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 18, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 19, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 20, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 21, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 22, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 23, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 24, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 25, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 26, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 27, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 28, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 29, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 30, SolidCore.Refinement.Generic.OByte.byteOf (SolidCore.Refinement.Generic.WExpr.arg 1) 31] }] + +/-- How SolidCore dispatches and the stage erases `Events.transfer`. -/ +def transfer_erase? : Option (Nat × Option Tree) := + match SolidCore.Refinement.Solar.Events.contract? with + | .ok c => (c.core.findFunctionBySelector? 217554442).map fun f => (f.params.length, eraseFn (envOf c.core) SolidCore.Refinement.Solar.Events.fuel f) + | .error _ => none + +kernel_rfl transfer_erase_eq transfer_erase? (some (2, some transfer_tree)) using SolidCore.Refinement.Solar.Events.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Refinement.Solar.Events.digest_eq + +/-- `Events.transfer`'s exported spec. -/ +def transfer_spec : FnSpec := spec.spec.specs[0]'(by decide) + +set_option maxHeartbeats 4000000 in +/-- `transfer`'s spec without its succeeds-if conditions holds of its erased tree. -/ +theorem transfer_meets0 : TreeMeets spec transfer_spec.noSucc ctx 2 transfer_tree := by + tree_meets [transfer_tree, transfer_spec, SolidCore.Spec.FnSpec.noSucc, spec, Certified.events.gen.Events.Spec.Events] + +set_option maxHeartbeats 4000000 in +/-- From a pre-state meeting `transfer`'s succeeds-if conditions, its erased tree succeeds. -/ +theorem transfer_succeeds : TreeSucceeds spec transfer_spec ctx 2 transfer_tree := by + tree_succeeds [transfer_tree, transfer_spec, events.SpecConnect.spec, Certified.events.gen.Events.Spec.Events, events.SpecConnect.ctx] + +/-- `transfer`'s spec holds of its erased tree. -/ +theorem transfer_meets : TreeMeets spec transfer_spec ctx 2 transfer_tree := + treeMeets_of_succeeds (transfer_meets0) (transfer_succeeds) + +/-- **`Events.transfer`'s spec holds of SolidCore's checked contract** on the stage's calls of it. -/ +theorem transfer_holds {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : SolidCore.Refinement.Solar.Events.contract? = .ok c) + (step : GhostStep) : + HoldsFn (solidCore SolidCore.Refinement.Solar.Events.fuel) c (SolidCore.Verify.VC.stageScope fn_transfer deployed) spec ctxOf step transfer_spec := by + have hdep := deploy_eq + simp only [deploy?, hc] at hdep + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + have hmap := transfer_erase_eq + simp only [transfer_erase?, hc, Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + exact holdsFn_of_tree (fn := fn_transfer) (ctx := ctx) hdd (by decide) hf (by simpa [fn_transfer] using hlen) hT + (fun call h => by simp [ctxOf, ctx, h]) (by simpa [fn_transfer] using transfer_meets) + +/-- **`Events.transfer`'s spec holds of SolidCore's checked contract in every world `W`** on the +stage's calls of it (the function calls out nowhere, so its tree is its run in any world). -/ +theorem transfer_holds_in (W : SolidCore.Refinement.World) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Refinement.Solar.Events.contract? = .ok c) (step : GhostStep) : + HoldsFn (solidCoreIn W SolidCore.Refinement.Solar.Events.fuel) c (SolidCore.Verify.VC.stageScope fn_transfer deployed) spec ctxOf step transfer_spec := by + have hdep := deploy_eq + simp only [deploy?, hc] at hdep + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + have hmap := transfer_erase_eq + simp only [transfer_erase?, hc, Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + exact holdsFn_of_tree_in W (fn := fn_transfer) (ctx := ctx) hdd (by decide) hf (by simpa [fn_transfer] using hlen) hT + (fun call h => by simp [ctxOf, ctx, h]) (by simpa [fn_transfer] using transfer_meets) + +/-- info: 'events.SpecConnect.transfer_holds_in' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms transfer_holds_in + +/-- info: 'events.SpecConnect.transfer_holds' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms transfer_holds + +end events.SpecConnect diff --git a/Certified/events/Statement.lean b/Certified/events/Statement.lean new file mode 100644 index 00000000..9c1432d7 --- /dev/null +++ b/Certified/events/Statement.lean @@ -0,0 +1,59 @@ +import Verify.Shapes +import Verify.ShapeBundle +import events.gen.Events.Spec +import Verify.ShapeSpecExport +import events.gen.Events.Bytecode +import SolidCore.Refinement.Solar.Events.Lowering +import Verify.ShapeGeneric + +-- Generated by solar's tools/certify/final.py from events/shape.json and the bytecode the +-- driver compiled in this run; do not edit. This module never imports the proof module. + +/-! +# Events: the published statement + +`Statement` binds the exact runtime bytecode (`runtimeHex`, from the driver's own compile) and +states _root_.SolidCore.Refinement.Shapes.Certified of it against the checked source on the declared valid calls. +-/ + +namespace Certified.events.Final + +/-- The runtime bytecode the pinned solar emitted in this run, as hex (for the reader). -/ +def runtimeHex : String := + "346053575f3560e01c80630cf79e0a03605357604436106053576024355f52600435337f7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be960205fa35f1960601c3311605757005b5f5ffd5b690417000000000000000260201b335f1960601c9160205260405260605263ed572b275f526064601cfd" + +/-- The same bytes, as numbers: what the statement binds. -/ +def runtimeBytes : List Nat := + [0x34, 0x60, 0x53, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0xc, 0xf7, 0x9e, 0xa, 0x3, + 0x60, 0x53, 0x57, 0x60, 0x44, 0x36, 0x10, 0x60, 0x53, 0x57, 0x60, 0x24, 0x35, 0x5f, 0x52, 0x60, + 0x4, 0x35, 0x33, 0x7f, 0x7f, 0xa9, 0xaa, 0xfe, 0xb8, 0xbb, 0x80, 0x3d, 0x77, 0xde, 0x5d, 0x84, + 0xbc, 0x2f, 0x2e, 0xdb, 0xd8, 0x42, 0xca, 0x91, 0xb2, 0xc, 0xd5, 0x2, 0xa, 0xa2, 0x1d, 0xfe, + 0x26, 0xab, 0xb, 0xe9, 0x60, 0x20, 0x5f, 0xa3, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x33, 0x11, 0x60, + 0x57, 0x57, 0x0, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x69, 0x4, 0x17, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x2, 0x60, 0x20, 0x1b, 0x33, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x91, 0x60, 0x20, 0x52, + 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, 0x63, 0xed, 0x57, 0x2b, 0x27, 0x5f, 0x52, 0x60, 0x64, 0x60, + 0x1c, 0xfd] + +/-- The freshly exported bytecode the obligations speak of. -/ +def code : ByteArray := ⟨(_root_.SolarTV.Export.Events.bytecode.map UInt8.ofNat).toArray⟩ + +/-- The specification and the allowed statuses are not vacuous: some valid call has a result the +specification rejects, and some valid call has a revert the allowed statuses reject. -/ +def NonVacuous : Prop := + (∃ (call : _root_.SolarTV.Call) (obs : _root_.SolarTV.Observable), (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.Events.fns) ([])) call ∧ ¬ (_root_.SolidCore.Refinement.Shapes.bundlePost _root_.Certified.events.gen.Events.Spec.Events (SolidCore.Refinement.Shapes.ctxOfCall) (SolidCore.Refinement.Shapes.idStep)) call obs) ∧ + (∃ (call : _root_.SolarTV.Call) (obs : _root_.SolarTV.Observable), (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.Events.fns) ([])) call ∧ obs.success = false ∧ + ¬ (_root_.SolidCore.Refinement.Shapes.bundleAllowed _root_.Certified.events.gen.Events.Spec.Events (SolidCore.Refinement.Shapes.ctxOfCall)) call obs) + +/-- **The published statement.** -/ +def Statement : Prop := + _root_.Certified.events.Final.code.data.toList.map (·.toNat) = _root_.Certified.events.Final.runtimeBytes ∧ + _root_.Certified.events.Final.NonVacuous ∧ + (∃ c, SolidCore.Refinement.Solar.Events.contract? = .ok c ∧ + _root_.SolidCore.Refinement.Shapes.Certified (_root_.SolidCore.Refinement.solidCore (SolidCore.Refinement.Solar.Events.fuel)) c _root_.Certified.events.Final.code + (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.Events.fns) ([])) (_root_.SolidCore.Refinement.Shapes.bundleAllowed _root_.Certified.events.gen.Events.Spec.Events (SolidCore.Refinement.Shapes.ctxOfCall)) (_root_.SolidCore.Refinement.Shapes.bundlePost _root_.Certified.events.gen.Events.Spec.Events (SolidCore.Refinement.Shapes.ctxOfCall) (SolidCore.Refinement.Shapes.idStep)) (fun _ => 2386812)) + +set_option maxRecDepth 100000 in +theorem bound : _root_.Certified.events.Final.code.data.toList.map (·.toNat) = _root_.Certified.events.Final.runtimeBytes := + @of_decide_eq_true _ (instDecidableEqList _ _) (by decide +kernel) + +end Certified.events.Final diff --git a/Certified/events/bytecode.hex b/Certified/events/bytecode.hex new file mode 100644 index 00000000..2b4036d4 --- /dev/null +++ b/Certified/events/bytecode.hex @@ -0,0 +1 @@ +346053575f3560e01c80630cf79e0a03605357604436106053576024355f52600435337f7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be960205fa35f1960601c3311605757005b5f5ffd5b690417000000000000000260201b335f1960601c9160205260405260605263ed572b275f526064601cfd diff --git a/Certified/events/events.sol b/Certified/events/events.sol new file mode 100644 index 00000000..0e0af982 --- /dev/null +++ b/Certified/events/events.sol @@ -0,0 +1,8 @@ +contract Events { + event Transfer(address indexed from, uint256 indexed id, uint256 value); + + /// @custom:succeeds-if msg.value == 0 + function transfer(uint256 id, uint256 value) external { + emit Transfer(msg.sender, id, value); + } +} diff --git a/Certified/events/gen/Events/Bytecode.lean b/Certified/events/gen/Events/Bytecode.lean new file mode 100644 index 00000000..620b7eab --- /dev/null +++ b/Certified/events/gen/Events/Bytecode.lean @@ -0,0 +1,22 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x53, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x0c, 0xf7, 0x9e, 0x0a, 0x03, + 0x60, 0x53, 0x57, 0x60, 0x44, 0x36, 0x10, 0x60, 0x53, 0x57, 0x60, 0x24, 0x35, 0x5f, 0x52, 0x60, + 0x04, 0x35, 0x33, 0x7f, 0x7f, 0xa9, 0xaa, 0xfe, 0xb8, 0xbb, 0x80, 0x3d, 0x77, 0xde, 0x5d, 0x84, + 0xbc, 0x2f, 0x2e, 0xdb, 0xd8, 0x42, 0xca, 0x91, 0xb2, 0x0c, 0xd5, 0x02, 0x0a, 0xa2, 0x1d, 0xfe, + 0x26, 0xab, 0x0b, 0xe9, 0x60, 0x20, 0x5f, 0xa3, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x33, 0x11, 0x60, + 0x57, 0x57, 0x00, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x69, 0x04, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x02, 0x60, 0x20, 0x1b, 0x33, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x91, 0x60, 0x20, 0x52, + 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, 0x63, 0xed, 0x57, 0x2b, 0x27, 0x5f, 0x52, 0x60, 0x64, 0x60, + 0x1c, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "346053575f3560e01c80630cf79e0a03605357604436106053576024355f52600435337f7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be960205fa35f1960601c3311605757005b5f5ffd5b690417000000000000000260201b335f1960601c9160205260405260605263ed572b275f526064601cfd" + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/Evm1.lean b/Certified/events/gen/Events/Evm1.lean new file mode 100644 index 00000000..171dc29e --- /dev/null +++ b/Certified/events/gen/Events/Evm1.lean @@ -0,0 +1,70 @@ +-- solar-lean-stage: kind=evm index=1 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xcf79e0a)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 3, + .stop], + -- bb7 + [.op (.stack (.push 0x417000000000000000200000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/Evm2.lean b/Certified/events/gen/Events/Evm2.lean new file mode 100644 index 00000000..a0988c3d --- /dev/null +++ b/Certified/events/gen/Events/Evm2.lean @@ -0,0 +1,78 @@ +-- solar-lean-stage: kind=evm index=2 pass=compact-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The runtime EVM IR after `compact-pushes`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xcf79e0a)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 3, + .stop], + -- bb7 + [.op (.stack (.push 0x4170000000000000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/Evm3.lean b/Certified/events/gen/Events/Evm3.lean new file mode 100644 index 00000000..dae18f7f --- /dev/null +++ b/Certified/events/gen/Events/Evm3.lean @@ -0,0 +1,78 @@ +-- solar-lean-stage: kind=evm index=3 pass=share-reverts +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The runtime EVM IR after `share-reverts`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xcf79e0a)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 3, + .stop], + -- bb7 + [.op (.stack (.push 0x4170000000000000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/Evm4.lean b/Certified/events/gen/Events/Evm4.lean new file mode 100644 index 00000000..422a8ed5 --- /dev/null +++ b/Certified/events/gen/Events/Evm4.lean @@ -0,0 +1,76 @@ +-- solar-lean-stage: kind=evm index=4 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xcf79e0a)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 3, + .stop], + -- bb7 + [.op (.stack (.push 0x4170000000000000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.jump 1]] } + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/Evm5.lean b/Certified/events/gen/Events/Evm5.lean new file mode 100644 index 00000000..b8236ef6 --- /dev/null +++ b/Certified/events/gen/Events/Evm5.lean @@ -0,0 +1,72 @@ +-- solar-lean-stage: kind=evm index=5 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xcf79e0a)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 2, + .stop], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb7 + [.op (.stack (.push 0x4170000000000000002)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/Manifest.lean b/Certified/events/gen/Events/Manifest.lean new file mode 100644 index 00000000..cae96901 --- /dev/null +++ b/Certified/events/gen/Events/Manifest.lean @@ -0,0 +1,43 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Events.Manifest + +def sources : List (String × String) := + [("Certified/events/events.sol", "c935cf243f303a252e4ee0bb10c9c75130eef92ca6c4a954830e67af9a939214")] + +def compiler : String := "0.8.38+commit.9aea5229.solar.0.3.0-dev" + +def arguments : List String := + ["Certified/events/events.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/events/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "68677a695510baf2870afd0103eb47704edc8ef3364bd447b4adca68bbae9872"), + ("Mir1", "mir1", "lower-assumes", "2d42087e761656008220641508b6b751973cea26f4fe9cd5c0c03dd904852144"), + ("Sched", "sched", "stack-schedule", "929791fc4e57353df07b33d8162fea62bb0c2e2b4813e1931736baecd9699549"), + ("Evm1", "evm1", "cfg-simplify-early", "e326484f2b9d99b6b5c1d840ac3b1fb9c839a16a52bbf0a2aae10cc92d2a8919"), + ("Evm2", "evm2", "compact-pushes", "b86a90a2aaddfe85d8fb1cfe30fe9c326001fb6bb3901e81c624c90168f3df6b"), + ("Evm3", "evm3", "share-reverts", "34129f64acafdee66806e77d9771942beaed85ab32da0e25a4432541413a4235"), + ("Evm4", "evm4", "terminal-dedup", "3644c7996119ff8509849b1a3dbc32429efe7c7088c8920cc0a11675feb223e2"), + ("Evm5", "evm5", "cfg-simplify-early", "7fd8518f82d6a049aac367739d04580b006674baba38f47b193be4950cb2b082"), + ("Bytecode", "bytecode", "assemble", "c598af1c73cf0b943d5ee96c6a76400d8f34e2df60f4f818ca582f427da9acf1")] + +def bytecodeHex : String := + "346053575f3560e01c80630cf79e0a03605357604436106053576024355f52600435337f7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be960205fa35f1960601c3311605757005b5f5ffd5b690417000000000000000260201b335f1960601c9160205260405260605263ed572b275f526064601cfd" + +def bytecodeSha256 : String := "5ad38c8bca24e0ca8c4a5e95f1f07bf993aad9a02ac3bc0872fc41fab8a6298b" + +end SolarTV.Export.Events.Manifest diff --git a/Certified/events/gen/Events/Mir1.lean b/Certified/events/gen/Events/Mir1.lean new file mode 100644 index 00000000..0c224421 --- /dev/null +++ b/Certified/events/gen/Events/Mir1.lean @@ -0,0 +1,70 @@ +-- solar-lean-stage: kind=mir index=1 pass=lower-assumes +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The lowered MIR module after `lower-assumes`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @transfer + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 9) .calldatasize [], + .pure 11 .lt [.value 9, .const 68]], + .branch (.value 11) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 13) .calldataload [.const 4], + .effect (some 15) .calldataload [.const 36], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 15], + .effect none (.log 3) [.const 0, .const 32, .const 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9, .value 3, .value 13], + .pure 18 .gt [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 18) 4 5⟩, + -- bb3 + ⟨[(20, [(4, .const 0x417000000000000000200000000)]), (21, [(4, .value 3)]), (22, [(4, .const 0xffffffffffffffffffffffffffffffffffffffff)])], + [.effect none .mstore [.const 32, .value 20], + .effect none .mstore [.const 64, .value 21], + .effect none .mstore [.const 96, .value 22], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [], + .stop⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0xcf79e0a, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/Sched.lean b/Certified/events/gen/Events/Sched.lean new file mode 100644 index 00000000..86e1db31 --- /dev/null +++ b/Certified/events/gen/Events/Sched.lean @@ -0,0 +1,80 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 3, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xcf79e0a)), + .op (.stack .eq), + .jumpi 2, + .jump 3], + -- bb2 + [.jump 4], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 9, + .jump 5], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9)), + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .effect (.log 3) 5, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 7, + .jump 6], + -- bb6 + [.stop], + -- bb7 + [.op (.stack (.push 0x417000000000000000200000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 8], + -- bb8 + [.op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/Schedule.json b/Certified/events/gen/Events/Schedule.json new file mode 100644 index 00000000..85fa6c48 --- /dev/null +++ b/Certified/events/gen/Events/Schedule.json @@ -0,0 +1,20 @@ +{ + "functions": [ + {"function": 1, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [3, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 0, "entry": 4, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [4, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [9, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [5, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [8, 0], "layout": ["v20", "v21", "v22"], "floating": true, "continues": null}, + {"block": 4, "start": [7, 0], "layout": [], "floating": true, "continues": null}, + {"block": 5, "start": [6, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]} + ] +} diff --git a/Certified/events/gen/Events/Spec.lean b/Certified/events/gen/Events/Spec.lean new file mode 100644 index 00000000..10a0dcdc --- /dev/null +++ b/Certified/events/gen/Events/Spec.lean @@ -0,0 +1,48 @@ +import Verify.Spec.Contract + +/-! +Specs of `Certified/events/events.sol`, exported by solar-verify 0.3.0 with `--emit-lean-spec`. +Generated: do not edit. +-/ + +namespace Certified.events.gen.Events.Spec + +open SolidCore.Spec + +/-- What the specs were exported from and are about. -/ +def manifest : Manifest := + { source := "Certified/events/events.sol", + sourceSha256 := "c935cf243f303a252e4ee0bb10c9c75130eef92ca6c4a954830e67af9a939214", + compiler := "", + options := [], + bytecodeSha256 := "" } + +/-- The specs of `Events`. -/ +def Events : Bundle where + fuel := 0 + spec := + { name := "Events", + fns := [ + ], + invariants := [ + ], + ghosts := [], + specs := [ + { name := "Events.transfer", + selector := 0x0cf79e0a, + params := [(.uint 256), (.uint 256)], + rets := [], + payable := false, + requires := [], + ensures := [], + succeedsIf := [ + (.bin .eq (.env .value) (.lit 0))] }] } + +/-- Every spec function call resolves and nests within the fuel. -/ +theorem Events_wf : Events.WF = true := by decide +kernel + +/-- Trusted-base items these specs' proofs rely on beyond the verdict +(`SolidCore.Spec.Assumptions`). -/ +def trusted : List String := [] + +end Certified.events.gen.Events.Spec diff --git a/Certified/events/gen/Events/Stage0.lean b/Certified/events/gen/Events/Stage0.lean new file mode 100644 index 00000000..a0a7e03b --- /dev/null +++ b/Certified/events/gen/Events/Stage0.lean @@ -0,0 +1,55 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Events`; do not edit. -/ + +namespace SolarTV.Export.Events + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @transfer + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 9) .calldatasize [], + .pure 11 .lt [.value 9, .const 68]], + .branch (.value 11) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 13) .calldataload [.const 4], + .effect (some 15) .calldataload [.const 36], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 15], + .effect none (.log 3) [.const 0, .const 32, .const 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9, .value 3, .value 13], + .assume true .gt [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .stop⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0xcf79e0a, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Events diff --git a/Certified/events/gen/Events/manifest.json b/Certified/events/gen/Events/manifest.json new file mode 100644 index 00000000..37f45cfa --- /dev/null +++ b/Certified/events/gen/Events/manifest.json @@ -0,0 +1,97 @@ +{ + "arguments": [ + "Certified/events/events.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/events/gen" + ], + "bytecode": "346053575f3560e01c80630cf79e0a03605357604436106053576024355f52600435337f7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be960205fa35f1960601c3311605757005b5f5ffd5b690417000000000000000260201b335f1960601c9160205260405260605263ed572b275f526064601cfd", + "bytecode_sha256": "5ad38c8bca24e0ca8c4a5e95f1f07bf993aad9a02ac3bc0872fc41fab8a6298b", + "compiler": "0.8.38+commit.9aea5229.solar.0.3.0-dev", + "contract": "Events", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"Certified/events/events.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/events/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/events/gen\"), keep_asts: false, forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "Certified/events/events.sol", + "sha256": "c935cf243f303a252e4ee0bb10c9c75130eef92ca6c4a954830e67af9a939214" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "68677a695510baf2870afd0103eb47704edc8ef3364bd447b4adca68bbae9872" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "lower-assumes", + "sha256": "2d42087e761656008220641508b6b751973cea26f4fe9cd5c0c03dd904852144" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "929791fc4e57353df07b33d8162fea62bb0c2e2b4813e1931736baecd9699549" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "e326484f2b9d99b6b5c1d840ac3b1fb9c839a16a52bbf0a2aae10cc92d2a8919" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "compact-pushes", + "sha256": "b86a90a2aaddfe85d8fb1cfe30fe9c326001fb6bb3901e81c624c90168f3df6b" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "share-reverts", + "sha256": "34129f64acafdee66806e77d9771942beaed85ab32da0e25a4432541413a4235" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "3644c7996119ff8509849b1a3dbc32429efe7c7088c8920cc0a11675feb223e2" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "7fd8518f82d6a049aac367739d04580b006674baba38f47b193be4950cb2b082" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "c598af1c73cf0b943d5ee96c6a76400d8f34e2df60f4f818ca582f427da9acf1" + } + ] +} diff --git a/Certified/events/options b/Certified/events/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/events/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/events/record.json b/Certified/events/record.json new file mode 100644 index 00000000..2964baf8 --- /dev/null +++ b/Certified/events/record.json @@ -0,0 +1,107 @@ +{ + "contract": "Events", + "name": "events", + "source": "Certified/events/events.sol", + "bytecode": "346053575f3560e01c80630cf79e0a03605357604436106053576024355f52600435337f7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be960205fa35f1960601c3311605757005b5f5ffd5b690417000000000000000260201b335f1960601c9160205260405260605263ed572b275f526064601cfd", + "solar": "9aea52293a7b53ce980c99da99c7486983ed6ae9", + "solidity_lean": "b6d85507ee67f6ae15835e3bc595857c6e1b0781", + "mir_to_evmir": "proved: SolarTV.Milestone.Events.events_mir_to_evmir", + "assembly": "executed: inside the published statement Certified.events.Final.final (Shapes.Equiv and Resources over Target.runWith of the exact bytes); Proofs/: decoded only: events.Proofs.Assembly (the bytecode decodes to the final EVM IR's instructions; no execution theorem)", + "vc": "exported to .lake/certify/events/VC.lean", + "end_to_end": "not proved", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, Shapes.Certified.equivG)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with an allowed status; the bytecode too, at gas from the bound on", + "spec": "proved (published statement, Shapes.Meets of Shapes.bundlePost of the specification solar-verify exported in this run, NonVacuous in the statement): the specification of every source result on a valid call, hence of every bytecode result that is not an inert failure", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result", + "vacuity": "proved non-vacuous (NonVacuous in the statement)", + "assumptions": "none beyond the statement's scope", + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: the functions of Events.fns ABI-encoded with clean argument words, any value below 2^256, any storage; other call data is outside the statement", + "spec: the exported spec states when transfer succeeds (no value) and nothing of its log, which solar-verify's spec language cannot name; the log is covered by equivalence (the bytecode's log is SolidCore's), not by the spec" + ], + "environment": "fixed, not quantified: one frame, caller 0x2000, the contract at 0x1000, the block and transaction of Target.message", + "provenance": "clean", + "strongest": true, + "source": "SolidCore/Refinement/Source/Events.lean is the front end's AST of Events in Certified/events/events.sol (solc 0.8.35)" + }, + "final": { + "module": "events.Final", + "statement_module": "events.Statement", + "theorem": "Certified.events.Final.final", + "kind": "certified", + "statement": "_root_.Certified.events.Final.code.data.toList.map (·.toNat) = _root_.Certified.events.Final.runtimeBytes ∧ _root_.Certified.events.Final.NonVacuous ∧ (∃ c, SolidCore.Refinement.Solar.Events.contract? = .ok c ∧ _root_.SolidCore.Refinement.Shapes.Certified (_root_.SolidCore.Refinement.solidCore (SolidCore.Refinement.Solar.Events.fuel)) c _root_.Certified.events.Final.code (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.Events.fns) ([])) (_root_.SolidCore.Refinement.Shapes.bundleAllowed _root_.Certified.events.gen.Events.Spec.Events (SolidCore.Refinement.Shapes.ctxOfCall)) (_root_.SolidCore.Refinement.Shapes.bundlePost _root_.Certified.events.gen.Events.Spec.Events (SolidCore.Refinement.Shapes.ctxOfCall) (SolidCore.Refinement.Shapes.idStep)) (fun _ => 2386812))", + "nonvacuous": "Certified.events.Final.NonVacuous", + "vacuity": null, + "allowed_vacuity": null, + "spec_bound_to_export": "Certified.events.gen.Events.Spec.Events", + "allowed_bound_to_export": true, + "assumptions": [], + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: the functions of Events.fns ABI-encoded with clean argument words, any value below 2^256, any storage; other call data is outside the statement", + "spec: the exported spec states when transfer succeeds (no value) and nothing of its log, which solar-verify's spec language cannot name; the log is covered by equivalence (the bytecode's log is SolidCore's), not by the spec" + ], + "spec": "solar-verify's export of events.sol in this run (Certified.events.gen.Events.Spec.Events): transfer(id, value) succeeds-if msg.value == 0, so it must succeed on every valid call without a value; the postcondition (bundlePost) and the allowed statuses (bundleAllowed: success, or a call with a value) are both read off that export", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, Shapes.Certified.equivG)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with an allowed status; the bytecode too, at gas from the bound on", + "spec": "proved (published statement, Shapes.Meets of Shapes.bundlePost of the specification solar-verify exported in this run, NonVacuous in the statement): the specification of every source result on a valid call, hence of every bytecode result that is not an inert failure", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result", + "vacuity": "proved non-vacuous (NonVacuous in the statement)" + }, + "strongest": true + }, + "end_to_end_statement": {}, + "binding": {}, + "hypotheses": {}, + "refused": [], + "vacuous": "proved non-vacuous (NonVacuous in the statement)", + "vc_vacuous": "not checked", + "source_ast": "SolidCore/Refinement/Source/Events.lean is the front end's AST of Events in Certified/events/events.sol (solc 0.8.35)", + "assembly_statement": null, + "assembly_hypotheses": null, + "negative_tests": true, + "caveats": [ + "not end to end: solidity-lean states no source or spec theorem for events" + ], + "backend": { + "theorem": { + "module": "events.Final", + "statement_module": "events.Statement", + "theorem": "Certified.events.Final.final", + "kind": "certified", + "statement": "_root_.Certified.events.Final.code.data.toList.map (·.toNat) = _root_.Certified.events.Final.runtimeBytes ∧ _root_.Certified.events.Final.NonVacuous ∧ (∃ c, SolidCore.Refinement.Solar.Events.contract? = .ok c ∧ _root_.SolidCore.Refinement.Shapes.Certified (_root_.SolidCore.Refinement.solidCore (SolidCore.Refinement.Solar.Events.fuel)) c _root_.Certified.events.Final.code (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.Events.fns) ([])) (_root_.SolidCore.Refinement.Shapes.bundleAllowed _root_.Certified.events.gen.Events.Spec.Events (SolidCore.Refinement.Shapes.ctxOfCall)) (_root_.SolidCore.Refinement.Shapes.bundlePost _root_.Certified.events.gen.Events.Spec.Events (SolidCore.Refinement.Shapes.ctxOfCall) (SolidCore.Refinement.Shapes.idStep)) (fun _ => 2386812))", + "nonvacuous": "Certified.events.Final.NonVacuous", + "vacuity": null, + "allowed_vacuity": null, + "spec_bound_to_export": "Certified.events.gen.Events.Spec.Events", + "allowed_bound_to_export": true, + "assumptions": [], + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: the functions of Events.fns ABI-encoded with clean argument words, any value below 2^256, any storage; other call data is outside the statement", + "spec: the exported spec states when transfer succeeds (no value) and nothing of its log, which solar-verify's spec language cannot name; the log is covered by equivalence (the bytecode's log is SolidCore's), not by the spec" + ], + "spec": "solar-verify's export of events.sol in this run (Certified.events.gen.Events.Spec.Events): transfer(id, value) succeeds-if msg.value == 0, so it must succeed on every valid call without a value; the postcondition (bundlePost) and the allowed statuses (bundleAllowed: success, or a call with a value) are both read off that export", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, Shapes.Certified.equivG)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with an allowed status; the bytecode too, at gas from the bound on", + "spec": "proved (published statement, Shapes.Meets of Shapes.bundlePost of the specification solar-verify exported in this run, NonVacuous in the statement): the specification of every source result on a valid call, hence of every bytecode result that is not an inert failure", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result", + "vacuity": "proved non-vacuous (NonVacuous in the statement)" + }, + "strongest": true + } + } +} diff --git a/Certified/events/shape.json b/Certified/events/shape.json new file mode 100644 index 00000000..4ba51401 --- /dev/null +++ b/Certified/events/shape.json @@ -0,0 +1,50 @@ +{ + "kind": "certified", + "contract": "SolidCore.Refinement.Solar.Events.contract?", + "fuel": "SolidCore.Refinement.Solar.Events.fuel", + "valid": "SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.Events.fns) ([])", + "allowed_export": true, + "spec_export": { + "ctx": "SolidCore.Refinement.Shapes.ctxOfCall", + "step": "SolidCore.Refinement.Shapes.idStep" + }, + "nonvacuous": "Certified.events.Shape.nonvacuous", + "gas": "fun _ => 2386812", + "env": [], + "spec": "solar-verify's export of events.sol in this run (Certified.events.gen.Events.Spec.Events): transfer(id, value) succeeds-if msg.value == 0, so it must succeed on every valid call without a value; the postcondition (bundlePost) and the allowed statuses (bundleAllowed: success, or a call with a value) are both read off that export", + "spec_modules": [ + "SolidCore.Refinement.Solar.Events.Lowering", + "Verify.ShapeGeneric", + "Verify.ShapeSpecExport" + ], + "proof_module": "events.Shape", + "proof": "Certified.events.Shape.published", + "generic": { + "lowering": "SolidCore.Refinement.Solar.Events.Lowering", + "ns": "SolidCore.Refinement.Solar.Events", + "style": "core", + "check": "check_stage0", + "check_value": "checkValue_stage0", + "fns": "SolidCore.Refinement.Solar.Events.fns", + "storage": "[]", + "spec_connect": { + "witness": "transfer", + "using": [ + "SolidCore.Refinement.Solar.Events.digest_eq" + ] + } + }, + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: the functions of Events.fns ABI-encoded with clean argument words, any value below 2^256, any storage; other call data is outside the statement", + "spec: the exported spec states when transfer succeeds (no value) and nothing of its log, which solar-verify's spec language cannot name; the log is covered by equivalence (the bytecode's log is SolidCore's), not by the spec" + ], + "source_ast": { + "file": "SolidCore/Refinement/Source/Events.lean", + "namespace": "SolidCore.Refinement.Source.Events", + "contract": "Events" + } +} diff --git a/Certified/masks/Proofs.lean b/Certified/masks/Proofs.lean new file mode 100644 index 00000000..1b901319 --- /dev/null +++ b/Certified/masks/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import masks.Proofs.Stages +import masks.Proofs.Assembly diff --git a/Certified/masks/Proofs/Assembly.lean b/Certified/masks/Proofs/Assembly.lean new file mode 100644 index 00000000..4b901ba5 --- /dev/null +++ b/Certified/masks/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Items +import masks.gen.Masks.Evm6 +import masks.gen.Masks.Bytecode + +/-! The final EVM IR of `Masks` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.Masks + +open SolarTV.Assembly SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm6).getD [] + +theorem items_eq : itemsOf evm6 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x3e else if label = 2 then 0x42 else if label = 3 then 0x4b else if label = 4 then 0x71 else if label = 5 then 0x83 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.Masks.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.Masks.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms decodes + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Evm1.lean b/Certified/masks/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..5f919b07 --- /dev/null +++ b/Certified/masks/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Evm1 +import masks.gen.Masks.Sched + +/-! `peephole-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 18 = EVM.Program.run o evm1 call 18 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Evm2.lean b/Certified/masks/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..ba010a04 --- /dev/null +++ b/Certified/masks/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Evm2 +import masks.gen.Masks.Evm1 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 18 = EVM.Program.run o evm2 call 9 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Evm3.lean b/Certified/masks/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..28c54a8e --- /dev/null +++ b/Certified/masks/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Evm3 +import masks.gen.Masks.Evm2 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 9 = EVM.Program.run o evm3 call 9 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Evm4.lean b/Certified/masks/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..91af1354 --- /dev/null +++ b/Certified/masks/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Evm4 +import masks.gen.Masks.Evm3 + +/-! `share-reverts`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 9 = EVM.Program.run o evm4 call 9 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Evm5.lean b/Certified/masks/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..2fe64ff4 --- /dev/null +++ b/Certified/masks/Proofs/Runs/Evm5.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Evm5 +import masks.gen.Masks.Evm4 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 9 = EVM.Program.run o evm5 call 9 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Evm6.lean b/Certified/masks/Proofs/Runs/Evm6.lean new file mode 100644 index 00000000..eee09728 --- /dev/null +++ b/Certified/masks/Proofs/Runs/Evm6.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Evm6 +import masks.gen.Masks.Evm5 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm6_run (o : Oracle) (call : Call) : + EVM.Program.run o evm5 call 9 = EVM.Program.run o evm6 call 6 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.evm6_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Mir1.lean b/Certified/masks/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..51875c1d --- /dev/null +++ b/Certified/masks/Proofs/Runs/Mir1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Mir1 +import masks.gen.Masks.Stage0 + +/-! `place-reads`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir1_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 15 = MIR.Lowered.Module.run o mir1 call 15 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.mir1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Mir2.lean b/Certified/masks/Proofs/Runs/Mir2.lean new file mode 100644 index 00000000..ae2c7827 --- /dev/null +++ b/Certified/masks/Proofs/Runs/Mir2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Mir2 +import masks.gen.Masks.Mir1 + +/-! `lower-assumes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir2_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir1 call 15 = MIR.Lowered.Module.run o mir2 call 18 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.mir2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir2_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Sched.lean b/Certified/masks/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..fdd354df --- /dev/null +++ b/Certified/masks/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Sched +import masks.gen.Masks.Mir2 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir2 call 18 = EVM.Program.run o sched call 18 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Runs/Stage0.lean b/Certified/masks/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..9c63848e --- /dev/null +++ b/Certified/masks/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import masks.gen.Masks.Stage0 + +/-! The first lowered MIR ends on every call within 15 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 15).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.Masks.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/Proofs/Stages.lean b/Certified/masks/Proofs/Stages.lean new file mode 100644 index 00000000..801ee8f7 --- /dev/null +++ b/Certified/masks/Proofs/Stages.lean @@ -0,0 +1,163 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import masks.Proofs.Runs.Stage0 +import masks.Proofs.Runs.Mir1 +import masks.Proofs.Runs.Mir2 +import masks.Proofs.Runs.Sched +import masks.Proofs.Runs.Evm1 +import masks.Proofs.Runs.Evm2 +import masks.Proofs.Runs.Evm3 +import masks.Proofs.Runs.Evm4 +import masks.Proofs.Runs.Evm5 +import masks.Proofs.Runs.Evm6 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Masks`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm6`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.Masks + +open Machine SolarTV.Export.Masks SolarTV.Milestone.W1 + +/-- `place-reads`: stage0 to mir1. -/ +theorem stage_mir1 (o : Oracle) : Stage (mirSem o) (mirSem o) stage0 mir1 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 15 15 (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +theorem mir1_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir1 call 15).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := stage0) (q := mir1) (n := 15) (m := 15) (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +/-- `lower-assumes`: mir1 to mir2. -/ +theorem stage_mir2 (o : Oracle) : Stage (mirSem o) (mirSem o) mir1 mir2 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 15 18 (mir1_ends o) + (fun call _ => mir2_run o call) + +theorem mir2_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir2 call 18).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir1) (q := mir2) (n := 15) (m := 18) (mir1_ends o) + (fun call _ => mir2_run o call) + +/-- `stack-schedule`: mir2 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) mir2 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 18 18 (mir2_ends o) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 18).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := mir2) (q := sched) (n := 18) (m := 18) (mir2_ends o) + (fun call _ => sched_run o call) + +/-- `peephole-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 18 18 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 18).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 18) (m := 18) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `cfg-simplify-early`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 18 9 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 9).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 18) (m := 9) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `block-layout`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 9 9 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 9).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 9) (m := 9) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `share-reverts`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 9 9 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 9).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 9) (m := 9) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `terminal-dedup`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 9 9 (evm4_ends o) + (fun call _ => evm5_run o call) + +theorem evm5_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm5 call 9).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm4) (q := evm5) (n := 9) (m := 9) (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- `cfg-simplify-early`: evm5 to evm6. -/ +theorem stage_evm6 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm5 evm6 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 9 6 (evm5_ends o) + (fun call _ => evm6_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1, mir2], sched, [evm1, evm2, evm3, evm4, evm5, evm6]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem masks_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm6 anyCall := + mir_to_evmir o anyCall compilation ⟨stage_mir1 o, stage_mir2 o, trivial⟩ (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, stage_evm6 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.Masks.stage_mir1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir1 + +/-- info: 'SolarTV.Milestone.Masks.stage_mir2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir2 + +/-- info: 'SolarTV.Milestone.Masks.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.Masks.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.Masks.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.Masks.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.Masks.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.Masks.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.Masks.stage_evm6' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm6 + +/-- info: 'SolarTV.Milestone.Masks.masks_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms masks_mir_to_evmir + +end SolarTV.Milestone.Masks diff --git a/Certified/masks/bytecode.hex b/Certified/masks/bytecode.hex new file mode 100644 index 00000000..65beef34 --- /dev/null +++ b/Certified/masks/bytecode.hex @@ -0,0 +1 @@ +34603e575f3560e01c806341fa8d2d14604b5780636d4ce63c146042578063812600df03603e5760243610603e575f5460043581019081106071575f55005b5f5ffd5b5f545f5260205ff35b6024361060ff6004351117603e5760043560ff8116600f82165f5281810360835760205ff35b6011602052634e487b715f526024601cfd5b6d010200000002000000020000000760205260405260605263ed572b275f526064601cfd diff --git a/Certified/masks/gen/Masks/Bytecode.lean b/Certified/masks/gen/Masks/Bytecode.lean new file mode 100644 index 00000000..a347b183 --- /dev/null +++ b/Certified/masks/gen/Masks/Bytecode.lean @@ -0,0 +1,24 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x3e, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x41, 0xfa, 0x8d, 0x2d, 0x14, + 0x60, 0x4b, 0x57, 0x80, 0x63, 0x6d, 0x4c, 0xe6, 0x3c, 0x14, 0x60, 0x42, 0x57, 0x80, 0x63, 0x81, + 0x26, 0x00, 0xdf, 0x03, 0x60, 0x3e, 0x57, 0x60, 0x24, 0x36, 0x10, 0x60, 0x3e, 0x57, 0x5f, 0x54, + 0x60, 0x04, 0x35, 0x81, 0x01, 0x90, 0x81, 0x10, 0x60, 0x71, 0x57, 0x5f, 0x55, 0x00, 0x5b, 0x5f, + 0x5f, 0xfd, 0x5b, 0x5f, 0x54, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x24, 0x36, 0x10, + 0x60, 0xff, 0x60, 0x04, 0x35, 0x11, 0x17, 0x60, 0x3e, 0x57, 0x60, 0x04, 0x35, 0x60, 0xff, 0x81, + 0x16, 0x60, 0x0f, 0x82, 0x16, 0x5f, 0x52, 0x81, 0x81, 0x03, 0x60, 0x83, 0x57, 0x60, 0x20, 0x5f, + 0xf3, 0x5b, 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, + 0x60, 0x1c, 0xfd, 0x5b, 0x6d, 0x01, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, + 0x00, 0x00, 0x07, 0x60, 0x20, 0x52, 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, 0x63, 0xed, 0x57, 0x2b, + 0x27, 0x5f, 0x52, 0x60, 0x64, 0x60, 0x1c, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "34603e575f3560e01c806341fa8d2d14604b5780636d4ce63c146042578063812600df03603e5760243610603e575f5460043581019081106071575f55005b5f5ffd5b5f545f5260205ff35b6024361060ff6004351117603e5760043560ff8116600f82165f5281810360835760205ff35b6011602052634e487b715f526024601cfd5b6d010200000002000000020000000760205260405260605263ed572b275f526064601cfd" + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Evm1.lean b/Certified/masks/gen/Masks/Evm1.lean new file mode 100644 index 00000000..902102a1 --- /dev/null +++ b/Certified/masks/gen/Masks/Evm1.lean @@ -0,0 +1,139 @@ +-- solar-lean-stage: kind=evm index=1 pass=peephole-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The runtime EVM IR after `peephole-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 5, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x41fa8d2d)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .eq), + .jumpi 2, + .jump 5], + -- bb2 + [.jump 6], + -- bb3 + [.jump 11], + -- bb4 + [.jump 12], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 10, + .jump 7], + -- bb7 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 9, + .jump 8], + -- bb8 + [.op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb9 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb11 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 17, + .jump 13], + -- bb13 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 15)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 15, + .jump 14], + -- bb14 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 16], + -- bb16 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Evm2.lean b/Certified/masks/gen/Masks/Evm2.lean new file mode 100644 index 00000000..c272319c --- /dev/null +++ b/Certified/masks/gen/Masks/Evm2.lean @@ -0,0 +1,121 @@ +-- solar-lean-stage: kind=evm index=2 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x41fa8d2d)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb9 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb11 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 8, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 15)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 7, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 0x102000000020000000200000007)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Evm3.lean b/Certified/masks/gen/Masks/Evm3.lean new file mode 100644 index 00000000..b2a00fed --- /dev/null +++ b/Certified/masks/gen/Masks/Evm3.lean @@ -0,0 +1,121 @@ +-- solar-lean-stage: kind=evm index=3 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The runtime EVM IR after `block-layout`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x41fa8d2d)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 6, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb11 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 8, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 15)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 7, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 0x102000000020000000200000007)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Evm4.lean b/Certified/masks/gen/Masks/Evm4.lean new file mode 100644 index 00000000..97bd42b8 --- /dev/null +++ b/Certified/masks/gen/Masks/Evm4.lean @@ -0,0 +1,121 @@ +-- solar-lean-stage: kind=evm index=4 pass=share-reverts +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The runtime EVM IR after `share-reverts`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x41fa8d2d)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 6, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb11 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 8, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 15)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 7, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 0x102000000020000000200000007)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Evm5.lean b/Certified/masks/gen/Masks/Evm5.lean new file mode 100644 index 00000000..6953fbe3 --- /dev/null +++ b/Certified/masks/gen/Masks/Evm5.lean @@ -0,0 +1,117 @@ +-- solar-lean-stage: kind=evm index=5 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x41fa8d2d)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 6, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb11 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 8, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 15)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 7, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.jump 1], + -- bb15 + [.op (.stack (.push 0x102000000020000000200000007)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb17 + [.jump 1]] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Evm6.lean b/Certified/masks/gen/Masks/Evm6.lean new file mode 100644 index 00000000..491c9dc0 --- /dev/null +++ b/Certified/masks/gen/Masks/Evm6.lean @@ -0,0 +1,111 @@ +-- solar-lean-stage: kind=evm index=6 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm6 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x41fa8d2d)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb11 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 15)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 5, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb15 + [.op (.stack (.push 0x102000000020000000200000007)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Manifest.lean b/Certified/masks/gen/Masks/Manifest.lean new file mode 100644 index 00000000..611d5f39 --- /dev/null +++ b/Certified/masks/gen/Masks/Manifest.lean @@ -0,0 +1,45 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Masks.Manifest + +def sources : List (String × String) := + [("Certified/masks/masks.sol", "07aea44de99801385666f8de90ffb4edfba9f7ce9c874a89392f7d19fcd34d8e")] + +def compiler : String := "0.8.38+commit.cb5053ab.solar.0.3.0-dev" + +def arguments : List String := + ["Certified/masks/masks.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/masks/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "f2ac4b40da1be05e27ff460d855b8469c615cb90e23ed4139c5bae770ff392a6"), + ("Mir1", "mir1", "place-reads", "7e81d3e6e02f5b7189eef395a33abdbb0ddc9ab401f45e3f6e295a8e13b2767e"), + ("Mir2", "mir2", "lower-assumes", "35d0dd1e7e4afcc9a8a678114e8fca543da1b45cc2c6d229dd50f65269fc7d5b"), + ("Sched", "sched", "stack-schedule", "8566264d5747d0e0f9b124d30e112b2e4fb6634bf30f8901c8dc5314aa5e6b29"), + ("Evm1", "evm1", "peephole-early", "45f1839dac2612d414827e908263089e616b479f5ae0fa3b5508a0390ebd0f1f"), + ("Evm2", "evm2", "cfg-simplify-early", "1107efe81108adac52babb7c8ea8ccf956dc728be4c423ebe7a1a8d6fe969694"), + ("Evm3", "evm3", "block-layout", "b874dab5e2fd397b3cdb4078ce26400188307e4edca63b6c052da46c5015bf3c"), + ("Evm4", "evm4", "share-reverts", "1605fd858459857f03b1f6082f5992ec5f89bbac6dc80c39250c6e5a7ab723eb"), + ("Evm5", "evm5", "terminal-dedup", "cae48f97a155f2f2ac01ac680ac86f1674ad292b3fce1150bfe04be45931918b"), + ("Evm6", "evm6", "cfg-simplify-early", "4a76d0ff6a898e1dfbfc1acdab9d6fd29b5ccae1d45008fa06df18a932378cfd"), + ("Bytecode", "bytecode", "assemble", "1d90f37bbc86f39a55f34258e7f04d1806cf26bed44399f55c57260a5c7d3d2f")] + +def bytecodeHex : String := + "34603e575f3560e01c806341fa8d2d14604b5780636d4ce63c146042578063812600df03603e5760243610603e575f5460043581019081106071575f55005b5f5ffd5b5f545f5260205ff35b6024361060ff6004351117603e5760043560ff8116600f82165f5281810360835760205ff35b6011602052634e487b715f526024601cfd5b6d010200000002000000020000000760205260405260605263ed572b275f526064601cfd" + +def bytecodeSha256 : String := "43bd25ba9b579f0623a2d7181e6cf0f1094c31f96143a747470cd125d735dfe7" + +end SolarTV.Export.Masks.Manifest diff --git a/Certified/masks/gen/Masks/Mir1.lean b/Certified/masks/gen/Masks/Mir1.lean new file mode 100644 index 00000000..39fb6354 --- /dev/null +++ b/Certified/masks/gen/Masks/Mir1.lean @@ -0,0 +1,101 @@ +-- solar-lean-stage: kind=mir index=1 pass=place-reads +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The lowered MIR module after `place-reads`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 3, + functions := [ + -- @inc + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 36]], + .branch (.value 15) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 0, .value 4]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 17) .calldataload [.const 4], + .effect (some 2) .sload [.const 0], + .pure 4 .add [.value 2, .value 17], + .pure 5 .lt [.value 4, .value 2]], + .branch (.value 5) 1 2⟩] }, + -- @get + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 0], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @low + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 6) .calldatasize [], + .pure 8 .lt [.value 6, .const 36], + .effect (some 10) .calldataload [.const 4], + .pure 12 .gt [.value 10, .const 255], + .pure 23 .or [.value 8, .value 12]], + .branch (.value 23) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 24) .calldataload [.const 4], + .pure 19 .and [.value 24, .const 255], + .pure 20 .and [.value 24, .const 15], + .effect none .mstore [.const 0, .value 20], + .assume false .eq [.value 19, .value 24]], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 5 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 5 [(.const 0x41fa8d2d, 2), (.const 0x6d4ce63c, 3), (.const 0x812600df, 4)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Mir2.lean b/Certified/masks/gen/Masks/Mir2.lean new file mode 100644 index 00000000..0737f92f --- /dev/null +++ b/Certified/masks/gen/Masks/Mir2.lean @@ -0,0 +1,116 @@ +-- solar-lean-stage: kind=mir index=2 pass=lower-assumes +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The lowered MIR module after `lower-assumes`. -/ +def mir2 : MIR.Lowered.Module := + { entry := 3, + functions := [ + -- @inc + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 36]], + .branch (.value 15) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 0, .value 4]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 17) .calldataload [.const 4], + .effect (some 2) .sload [.const 0], + .pure 4 .add [.value 2, .value 17], + .pure 5 .lt [.value 4, .value 2]], + .branch (.value 5) 1 2⟩] }, + -- @get + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 0], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @low + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 6) .calldatasize [], + .pure 8 .lt [.value 6, .const 36], + .effect (some 10) .calldataload [.const 4], + .pure 12 .gt [.value 10, .const 255], + .pure 23 .or [.value 8, .value 12]], + .branch (.value 23) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 24) .calldataload [.const 4], + .pure 19 .and [.value 24, .const 255], + .pure 20 .and [.value 24, .const 15], + .effect none .mstore [.const 0, .value 20], + .ne 25 (.value 19) (.value 24)], + .branch (.value 25) 4 5⟩, + -- bb3 + ⟨[(27, [(4, .const 0x102000000020000000200000007)]), (28, [(4, .value 19)]), (29, [(4, .value 24)])], + [.effect none .mstore [.const 32, .value 27], + .effect none .mstore [.const 64, .value 28], + .effect none .mstore [.const 96, .value 29], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 5 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 5 [(.const 0x41fa8d2d, 2), (.const 0x6d4ce63c, 3), (.const 0x812600df, 4)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Sched.lean b/Certified/masks/gen/Masks/Sched.lean new file mode 100644 index 00000000..c1b17dea --- /dev/null +++ b/Certified/masks/gen/Masks/Sched.lean @@ -0,0 +1,140 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 5, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x41fa8d2d)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d4ce63c)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x812600df)), + .op (.stack .eq), + .jumpi 2, + .jump 5], + -- bb2 + [.jump 6], + -- bb3 + [.jump 11], + -- bb4 + [.jump 12], + -- bb5 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb6 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 10, + .jump 7], + -- bb7 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 9, + .jump 8], + -- bb8 + [.op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb9 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb11 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .jumpi 17, + .jump 13], + -- bb13 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 15)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 15, + .jump 14], + -- bb14 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 0x102000000020000000200000007)), + .jump 16], + -- bb16 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/Schedule.json b/Certified/masks/gen/Masks/Schedule.json new file mode 100644 index 00000000..816a205e --- /dev/null +++ b/Certified/masks/gen/Masks/Schedule.json @@ -0,0 +1,34 @@ +{ + "functions": [ + {"function": 3, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [4, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [3, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 5, "start": [5, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 0, "entry": 6, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [6, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [9, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [8, 0], "layout": ["v4"], "floating": true, "continues": null}, + {"block": 3, "start": [10, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [7, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 1, "entry": 11, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [11, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 2, "entry": 12, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [12, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [17, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [13, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [16, 0], "layout": ["v29", "v28", "v27"], "floating": true, "continues": null}, + {"block": 4, "start": [15, 0], "layout": ["v24", "v19"], "floating": true, "continues": null}, + {"block": 5, "start": [14, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]} + ] +} diff --git a/Certified/masks/gen/Masks/Stage0.lean b/Certified/masks/gen/Masks/Stage0.lean new file mode 100644 index 00000000..5b7cf0a4 --- /dev/null +++ b/Certified/masks/gen/Masks/Stage0.lean @@ -0,0 +1,100 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Masks`; do not edit. -/ + +namespace SolarTV.Export.Masks + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 3, + functions := [ + -- @inc + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 36]], + .branch (.value 15) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 0, .value 4]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 17) .calldataload [.const 4], + .effect (some 2) .sload [.const 0], + .pure 4 .add [.value 2, .value 17], + .pure 5 .lt [.value 4, .value 2]], + .branch (.value 5) 1 2⟩] }, + -- @get + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 0], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @low + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 6) .calldatasize [], + .pure 8 .lt [.value 6, .const 36], + .effect (some 10) .calldataload [.const 4], + .pure 12 .gt [.value 10, .const 255], + .pure 23 .or [.value 8, .value 12]], + .branch (.value 23) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.pure 19 .and [.value 10, .const 255], + .pure 20 .and [.value 10, .const 15], + .effect none .mstore [.const 0, .value 20], + .assume false .eq [.value 19, .value 10]], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 5 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 5 [(.const 0x41fa8d2d, 2), (.const 0x6d4ce63c, 3), (.const 0x812600df, 4)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Masks diff --git a/Certified/masks/gen/Masks/manifest.json b/Certified/masks/gen/Masks/manifest.json new file mode 100644 index 00000000..66f4091f --- /dev/null +++ b/Certified/masks/gen/Masks/manifest.json @@ -0,0 +1,113 @@ +{ + "arguments": [ + "Certified/masks/masks.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/masks/gen" + ], + "bytecode": "34603e575f3560e01c806341fa8d2d14604b5780636d4ce63c146042578063812600df03603e5760243610603e575f5460043581019081106071575f55005b5f5ffd5b5f545f5260205ff35b6024361060ff6004351117603e5760043560ff8116600f82165f5281810360835760205ff35b6011602052634e487b715f526024601cfd5b6d010200000002000000020000000760205260405260605263ed572b275f526064601cfd", + "bytecode_sha256": "43bd25ba9b579f0623a2d7181e6cf0f1094c31f96143a747470cd125d735dfe7", + "compiler": "0.8.38+commit.cb5053ab.solar.0.3.0-dev", + "contract": "Masks", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"Certified/masks/masks.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/masks/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/masks/gen\"), keep_asts: false, forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "Certified/masks/masks.sol", + "sha256": "07aea44de99801385666f8de90ffb4edfba9f7ce9c874a89392f7d19fcd34d8e" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "f2ac4b40da1be05e27ff460d855b8469c615cb90e23ed4139c5bae770ff392a6" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "place-reads", + "sha256": "7e81d3e6e02f5b7189eef395a33abdbb0ddc9ab401f45e3f6e295a8e13b2767e" + }, + { + "definition": "mir2", + "file": "Mir2.lean", + "index": 2, + "kind": "mir", + "pass": "lower-assumes", + "sha256": "35d0dd1e7e4afcc9a8a678114e8fca543da1b45cc2c6d229dd50f65269fc7d5b" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "8566264d5747d0e0f9b124d30e112b2e4fb6634bf30f8901c8dc5314aa5e6b29" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "peephole-early", + "sha256": "45f1839dac2612d414827e908263089e616b479f5ae0fa3b5508a0390ebd0f1f" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "1107efe81108adac52babb7c8ea8ccf956dc728be4c423ebe7a1a8d6fe969694" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "block-layout", + "sha256": "b874dab5e2fd397b3cdb4078ce26400188307e4edca63b6c052da46c5015bf3c" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "share-reverts", + "sha256": "1605fd858459857f03b1f6082f5992ec5f89bbac6dc80c39250c6e5a7ab723eb" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "cae48f97a155f2f2ac01ac680ac86f1674ad292b3fce1150bfe04be45931918b" + }, + { + "definition": "evm6", + "file": "Evm6.lean", + "index": 6, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "4a76d0ff6a898e1dfbfc1acdab9d6fd29b5ccae1d45008fa06df18a932378cfd" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "1d90f37bbc86f39a55f34258e7f04d1806cf26bed44399f55c57260a5c7d3d2f" + } + ] +} diff --git a/Certified/masks/masks.sol b/Certified/masks/masks.sol new file mode 100644 index 00000000..9fcb7994 --- /dev/null +++ b/Certified/masks/masks.sol @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Masks { + uint256 x; + function inc(uint256 d) external { + x += d; + } + function get() external view returns (uint256) { + return x; + } + function low(uint8 a) external pure returns (uint8) { + return a & 0x0f; + } +} diff --git a/Certified/masks/options b/Certified/masks/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/masks/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/masks/record.json b/Certified/masks/record.json new file mode 100644 index 00000000..6cc49e20 --- /dev/null +++ b/Certified/masks/record.json @@ -0,0 +1,36 @@ +{ + "contract": "Masks", + "name": "masks", + "source": "Certified/masks/masks.sol", + "bytecode": "34603e575f3560e01c806341fa8d2d14604b5780636d4ce63c146042578063812600df03603e5760243610603e575f5460043581019081106071575f55005b5f5ffd5b5f545f5260205ff35b6024361060ff6004351117603e5760043560ff8116600f82165f5281810360835760205ff35b6011602052634e487b715f526024601cfd5b6d010200000002000000020000000760205260405260605263ed572b275f526064601cfd", + "solar": "cb5053ab39adfd59820913b336d346389ce1b8d9", + "solidity_lean": "696df0a81602fc416fabec7b892073e15e8920de", + "mir_to_evmir": "proved: SolarTV.Milestone.Masks.masks_mir_to_evmir", + "assembly": "decoded only: masks.Proofs.Assembly (the bytecode decodes to the final EVM IR's instructions; no execution theorem)", + "vc": "exported to .lake/certify/masks/VC.lean", + "end_to_end": "not proved", + "end_to_end_statement": {}, + "hypotheses": {}, + "refused": [ + { + "function": "Masks.low", + "reason": "undeclared symbol: |a@20#bv8|", + "status": "refused (unproved)" + } + ], + "vacuous": "not checked", + "assembly_statement": null, + "assembly_hypotheses": null, + "negative_tests": false, + "caveats": [ + "solidity-lean at 696df0a81602fc416fabec7b892073e15e8920de, not the pinned 813949dc3556d3c3f1c129e8254a4eead78bac87", + "solar cb5053ab39adfd59820913b336d346389ce1b8d9, not built from this checkout's compiler sources", + "assembly decoded, not executed", + "1 spec function(s) refused, unproved", + "not end to end: solidity-lean states no source or spec theorem for masks", + "negative tests skipped" + ], + "backend": { + "theorem": "SolarTV.Milestone.Masks.masks_mir_to_evmir" + } +} diff --git a/Certified/mulx/Final.lean b/Certified/mulx/Final.lean new file mode 100644 index 00000000..7e8fd79f --- /dev/null +++ b/Certified/mulx/Final.lean @@ -0,0 +1,60 @@ +import Verify.Shapes +import Verify.ShapeGeneric +import mulx.gen.Main.Bytecode +import SolidCore.Refinement.Solar.MulX.Lowering +import mulx.Shape + +-- Generated by solar's tools/certify/final.py from mulx/shape.json and the bytecode the +-- driver compiled in this run; do not edit. The statement is fixed by the driver; the proof +-- module only supplies a term the kernel checks against it. + +/-! +# Main: the published statement + +`Statement` binds the exact runtime bytecode (`runtimeHex`, from the driver's own compile) and +states Shapes.Compiled of it against the checked source on the declared valid calls. +-/ + +namespace Certified.mulx.Final + +open SolidCore.Refinement + +/-- The runtime bytecode the pinned solar emitted in this run, as hex (for the reader). -/ +def runtimeHex : String := + "34601d575f3560e01c806316ea58cb14606d5780639db20e58146033575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243560101c6064361060ff600435111717601d576004602435604435913502808280159202928304141715602157806001555f5260205ff35b60243560101c6044361060ff600435111717601d575f5460ff81166004350260ff81119160ff1916178060081c61ffff16602435028060101c90921760215762ffff0019169060081b175f55" + +/-- The same bytes, as numbers: what the statement binds. -/ +def runtimeBytes : List Nat := + [0x34, 0x60, 0x1d, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x16, 0xea, 0x58, 0xcb, 0x14, + 0x60, 0x6d, 0x57, 0x80, 0x63, 0x9d, 0xb2, 0xe, 0x58, 0x14, 0x60, 0x33, 0x57, 0x5b, 0x5f, 0x5f, + 0xfd, 0x5b, 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, + 0x60, 0x1c, 0xfd, 0x5b, 0x60, 0x24, 0x35, 0x60, 0x10, 0x1c, 0x60, 0x64, 0x36, 0x10, 0x60, 0xff, + 0x60, 0x4, 0x35, 0x11, 0x17, 0x17, 0x60, 0x1d, 0x57, 0x60, 0x4, 0x60, 0x24, 0x35, 0x60, 0x44, + 0x35, 0x91, 0x35, 0x2, 0x80, 0x82, 0x80, 0x15, 0x92, 0x2, 0x92, 0x83, 0x4, 0x14, 0x17, 0x15, + 0x60, 0x21, 0x57, 0x80, 0x60, 0x1, 0x55, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x24, + 0x35, 0x60, 0x10, 0x1c, 0x60, 0x44, 0x36, 0x10, 0x60, 0xff, 0x60, 0x4, 0x35, 0x11, 0x17, 0x17, + 0x60, 0x1d, 0x57, 0x5f, 0x54, 0x60, 0xff, 0x81, 0x16, 0x60, 0x4, 0x35, 0x2, 0x60, 0xff, 0x81, + 0x11, 0x91, 0x60, 0xff, 0x19, 0x16, 0x17, 0x80, 0x60, 0x8, 0x1c, 0x61, 0xff, 0xff, 0x16, 0x60, + 0x24, 0x35, 0x2, 0x80, 0x60, 0x10, 0x1c, 0x90, 0x92, 0x17, 0x60, 0x21, 0x57, 0x62, 0xff, 0xff, + 0x0, 0x19, 0x16, 0x90, 0x60, 0x8, 0x1b, 0x17, 0x5f, 0x55] + +/-- The freshly exported bytecode the obligations speak of. -/ +def code : ByteArray := ⟨(SolarTV.Export.Main.bytecode.map UInt8.ofNat).toArray⟩ + +/-- **The published statement.** -/ +def Statement : Prop := + code.data.toList.map (·.toNat) = runtimeBytes ∧ + (∃ c, SolidCore.Refinement.Solar.MulX.contract? = .ok c ∧ + Shapes.Compiled (solidCore (SolidCore.Refinement.Solar.MulX.fuel)) c code + (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.MulX.fns) (SolidCore.Refinement.Solar.MulX.deployed)) (fun _ => 6298506)) + +set_option maxRecDepth 100000 in +theorem bound : code.data.toList.map (·.toNat) = runtimeBytes := + @of_decide_eq_true _ (instDecidableEqList _ _) (by decide +kernel) + +theorem final : Statement := + ⟨bound, Certified.mulx.Shape.published⟩ + +#print axioms final + +end Certified.mulx.Final diff --git a/Certified/mulx/Proofs.lean b/Certified/mulx/Proofs.lean new file mode 100644 index 00000000..ff615c87 --- /dev/null +++ b/Certified/mulx/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import mulx.Proofs.Stages +import mulx.Proofs.Assembly diff --git a/Certified/mulx/Proofs/Assembly.lean b/Certified/mulx/Proofs/Assembly.lean new file mode 100644 index 00000000..1729b6b9 --- /dev/null +++ b/Certified/mulx/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Items +import mulx.gen.Main.Evm8 +import mulx.gen.Main.Bytecode + +/-! The final EVM IR of `Main` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.Mulx + +open SolarTV.Assembly SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm8).getD [] + +theorem items_eq : itemsOf evm8 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x1d else if label = 2 then 0x21 else if label = 3 then 0x33 else if label = 4 then 0x6d else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.Mulx.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.Mulx.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms decodes + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Evm1.lean b/Certified/mulx/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..6db1ec4d --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Evm1 +import mulx.gen.Main.Sched + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 15 = EVM.Program.run o evm1 call 8 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Evm2.lean b/Certified/mulx/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..50a946d9 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Evm2 +import mulx.gen.Main.Evm1 + +/-! `compact-pushes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 8 = EVM.Program.run o evm2 call 8 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Evm3.lean b/Certified/mulx/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..e5d3e22e --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Evm3 +import mulx.gen.Main.Evm2 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 8 = EVM.Program.run o evm3 call 8 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Evm4.lean b/Certified/mulx/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..d3932d18 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Evm4 +import mulx.gen.Main.Evm3 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 8 = EVM.Program.run o evm4 call 8 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Evm5.lean b/Certified/mulx/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..bb92f5b6 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Evm5.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Evm5 +import mulx.gen.Main.Evm4 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 8 = EVM.Program.run o evm5 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Evm6.lean b/Certified/mulx/Proofs/Runs/Evm6.lean new file mode 100644 index 00000000..6f035447 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Evm6.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Evm6 +import mulx.gen.Main.Evm5 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm6_run (o : Oracle) (call : Call) : + EVM.Program.run o evm5 call 5 = EVM.Program.run o evm6 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.evm6_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Evm7.lean b/Certified/mulx/Proofs/Runs/Evm7.lean new file mode 100644 index 00000000..abfcfae9 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Evm7.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Evm7 +import mulx.gen.Main.Evm6 + +/-! `stack-reschedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm7_run (o : Oracle) (call : Call) : + EVM.Program.run o evm6 call 5 = EVM.Program.run o evm7 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.evm7_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm7_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Evm8.lean b/Certified/mulx/Proofs/Runs/Evm8.lean new file mode 100644 index 00000000..5ef159d6 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Evm8.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Evm8 +import mulx.gen.Main.Evm7 + +/-! `terminal-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm8_run (o : Oracle) (call : Call) : + EVM.Program.run o evm7 call 5 = EVM.Program.run o evm8 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.evm8_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm8_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Mir1.lean b/Certified/mulx/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..41bf84c4 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Mir1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Mir1 +import mulx.gen.Main.Stage0 + +/-! `place-reads`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir1_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 15 = MIR.Lowered.Module.run o mir1 call 15 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.mir1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Mir2.lean b/Certified/mulx/Proofs/Runs/Mir2.lean new file mode 100644 index 00000000..a5ef4485 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Mir2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Mir2 +import mulx.gen.Main.Mir1 + +/-! `spell-width-tests`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir2_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir1 call 15 = MIR.Lowered.Module.run o mir2 call 15 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.mir2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir2_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Mir3.lean b/Certified/mulx/Proofs/Runs/Mir3.lean new file mode 100644 index 00000000..5f062332 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Mir3.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Mir3 +import mulx.gen.Main.Mir2 + +/-! `evm-inst-schedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem mir3_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir2 call 15 = MIR.Lowered.Module.run o mir3 call 15 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.mir3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir3_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Sched.lean b/Certified/mulx/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..ef4a673c --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Sched +import mulx.gen.Main.Mir3 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir3 call 15 = EVM.Program.run o sched call 15 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Runs/Stage0.lean b/Certified/mulx/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..dea977a2 --- /dev/null +++ b/Certified/mulx/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import mulx.gen.Main.Stage0 + +/-! The first lowered MIR ends on every call within 15 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 15).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.Mulx.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Proofs/Stages.lean b/Certified/mulx/Proofs/Stages.lean new file mode 100644 index 00000000..59122ee1 --- /dev/null +++ b/Certified/mulx/Proofs/Stages.lean @@ -0,0 +1,211 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import mulx.Proofs.Runs.Stage0 +import mulx.Proofs.Runs.Mir1 +import mulx.Proofs.Runs.Mir2 +import mulx.Proofs.Runs.Mir3 +import mulx.Proofs.Runs.Sched +import mulx.Proofs.Runs.Evm1 +import mulx.Proofs.Runs.Evm2 +import mulx.Proofs.Runs.Evm3 +import mulx.Proofs.Runs.Evm4 +import mulx.Proofs.Runs.Evm5 +import mulx.Proofs.Runs.Evm6 +import mulx.Proofs.Runs.Evm7 +import mulx.Proofs.Runs.Evm8 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Main`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm8`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.Mulx + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +/-- `place-reads`: stage0 to mir1. -/ +theorem stage_mir1 (o : Oracle) : Stage (mirSem o) (mirSem o) stage0 mir1 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 15 15 (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +theorem mir1_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir1 call 15).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := stage0) (q := mir1) (n := 15) (m := 15) (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +/-- `spell-width-tests`: mir1 to mir2. -/ +theorem stage_mir2 (o : Oracle) : Stage (mirSem o) (mirSem o) mir1 mir2 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 15 15 (mir1_ends o) + (fun call _ => mir2_run o call) + +theorem mir2_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir2 call 15).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir1) (q := mir2) (n := 15) (m := 15) (mir1_ends o) + (fun call _ => mir2_run o call) + +/-- `evm-inst-schedule`: mir2 to mir3. -/ +theorem stage_mir3 (o : Oracle) : Stage (mirSem o) (mirSem o) mir2 mir3 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 15 15 (mir2_ends o) + (fun call _ => mir3_run o call) + +theorem mir3_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir3 call 15).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir2) (q := mir3) (n := 15) (m := 15) (mir2_ends o) + (fun call _ => mir3_run o call) + +/-- `stack-schedule`: mir3 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) mir3 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 15 15 (mir3_ends o) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 15).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := mir3) (q := sched) (n := 15) (m := 15) (mir3_ends o) + (fun call _ => sched_run o call) + +/-- `cfg-simplify-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 15 8 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 8).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 15) (m := 8) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `compact-pushes`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 8 8 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 8).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 8) (m := 8) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `block-layout`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 8 8 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 8).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 8) (m := 8) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `terminal-dedup`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 8 8 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 8).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 8) (m := 8) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `cfg-simplify-early`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 8 5 (evm4_ends o) + (fun call _ => evm5_run o call) + +theorem evm5_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm5 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm4) (q := evm5) (n := 8) (m := 5) (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- `block-layout`: evm5 to evm6. -/ +theorem stage_evm6 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm5 evm6 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm5_ends o) + (fun call _ => evm6_run o call) + +theorem evm6_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm6 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm5) (q := evm6) (n := 5) (m := 5) (evm5_ends o) + (fun call _ => evm6_run o call) + +/-- `stack-reschedule`: evm6 to evm7. -/ +theorem stage_evm7 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm6 evm7 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm6_ends o) + (fun call _ => evm7_run o call) + +theorem evm7_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm7 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm6) (q := evm7) (n := 5) (m := 5) (evm6_ends o) + (fun call _ => evm7_run o call) + +/-- `terminal-layout`: evm7 to evm8. -/ +theorem stage_evm8 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm7 evm8 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm7_ends o) + (fun call _ => evm8_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1, mir2, mir3], sched, [evm1, evm2, evm3, evm4, evm5, evm6, evm7, evm8]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem mulx_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm8 anyCall := + mir_to_evmir o anyCall compilation ⟨stage_mir1 o, stage_mir2 o, stage_mir3 o, trivial⟩ (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, stage_evm6 o, stage_evm7 o, stage_evm8 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.Mulx.stage_mir1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir1 + +/-- info: 'SolarTV.Milestone.Mulx.stage_mir2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir2 + +/-- info: 'SolarTV.Milestone.Mulx.stage_mir3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir3 + +/-- info: 'SolarTV.Milestone.Mulx.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.Mulx.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.Mulx.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.Mulx.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.Mulx.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.Mulx.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.Mulx.stage_evm6' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm6 + +/-- info: 'SolarTV.Milestone.Mulx.stage_evm7' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm7 + +/-- info: 'SolarTV.Milestone.Mulx.stage_evm8' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm8 + +/-- info: 'SolarTV.Milestone.Mulx.mulx_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms mulx_mir_to_evmir + +end SolarTV.Milestone.Mulx diff --git a/Certified/mulx/Shape.lean b/Certified/mulx/Shape.lean new file mode 100644 index 00000000..43d195f5 --- /dev/null +++ b/Certified/mulx/Shape.lean @@ -0,0 +1,122 @@ +import Verify.ShapeGeneric +import SolidCore.Refinement.Solar.MulX.Lowering +import mulx.Proofs.Stages +import mulx.gen.Main.Bytecode + +-- Generated by solar's tools/certify/shape_gen.py from mulx/shape.json and this run's export; +-- do not edit. Untrusted data and composition: the kernel re-derives every claim. + +/-! +# Main: the proof of the published statement + +`published` applies `SolidCore.Refinement.Shapes.compiled` to the source check of `SolidCore.Refinement.Solar.MulX`, solar-tv's backend +stages to `evm8` (`SolarTV.Milestone.Mulx.mulx_mir_to_evmir`), the final EVM IR's run within 5 blocks on every +call (the last stage's fuel) and the loop checker on the exact bytecode, with the certificate +tools/certify/asm_cert.py inferred. The gas bound is `gasBoundL cert 5` = 22100 · (5 · 57) + 6 += 6298506, at most the statement's 6298506. +-/ + +namespace Certified.mulx.Shape + +open SolidCore.Refinement SolidCore.Refinement.Solar SolarTV + +/-- The exported runtime bytecode. -/ +def code : ByteArray := ⟨(SolarTV.Export.Main.bytecode.map UInt8.ofNat).toArray⟩ + +/-- The loop checker's certificate (tools/certify/asm_cert.py). -/ +def cert : SolidCore.Refinement.Solar.Assemble.Cert := + { offsets := [0x0, 0x1d, 0x21, 0x33, 0x6d], + needs := [0, 0, 2, 1, 1], + top := 64, + turned := [], + costs := [17, 3, 9, 45, 57], + types := [[], + [], + [some false, some false], + [some false], + [some false]], + rets := [], + env := false, + reads := false } + +/-- The highest stack each block is entered with. -/ +def maxs : List Nat := [0, 1, 3, 1, 1] + +set_option maxRecDepth 100000 in +theorem walk_ok : (SolarTV.Assembly.walk (SolidCore.Refinement.Solar.Assemble.bytesOf code) cert.offset 0 + (SolidCore.Refinement.Solar.Assemble.lower SolarTV.Export.Main.evm8 cert)).isSome = true := by + have hw := SolidCore.Refinement.Solar.Assemble.walkS_drop (SolidCore.Refinement.Solar.Assemble.bytesOf code) cert.offset (SolidCore.Refinement.Solar.Assemble.lower SolarTV.Export.Main.evm8 cert) 0 + (Nat.zero_le _) + rw [List.drop_zero] at hw + rw [← hw] + decide +kernel + +set_option maxRecDepth 100000 in +theorem blocks_ok : SolidCore.Refinement.Solar.AssembleLoop.blocksOkL SolarTV.Export.Main.evm8 cert maxs 0 SolarTV.Export.Main.evm8.blocks = true := by + decide +kernel + +theorem labels_ok : SolidCore.Refinement.Solar.Assemble.labelsValid SolarTV.Export.Main.evm8 cert code = true := + SolidCore.Refinement.Solar.Assemble.labelsValid_of_walk walk_ok + +theorem size_ok : code.size < 2 ^ 32 := by decide +kernel + +/-- The checker of code with loops accepts the exact bytecode for the final EVM IR. -/ +theorem check_ok : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.Main.evm8 code cert maxs = true := by + simp only [SolidCore.Refinement.Solar.AssembleLoop.checkL, walk_ok, blocks_ok, labels_ok, decide_eq_true size_ok, Bool.and_true, + Bool.true_and] + decide + +/-- The final EVM IR ends within 5 blocks on every call, under the bytecode's oracle. -/ +theorem ends (call : Call) : (EVM.Program.run SolidCore.Refinement.Shapes.oracle SolarTV.Export.Main.evm8 call 5).isSome = true := + SolarTV.Milestone.W1.ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := SolidCore.Refinement.Shapes.oracle) (p := SolarTV.Export.Main.evm7) (q := SolarTV.Export.Main.evm8) (n := 5) (m := 5) + (SolarTV.Milestone.Mulx.evm7_ends SolidCore.Refinement.Shapes.oracle) (fun call _ => SolarTV.Milestone.Mulx.evm8_run SolidCore.Refinement.Shapes.oracle call) call trivial + +/-- The bytecode with byte `i` replaced by `b`. -/ +def mutant (i b : Nat) : ByteArray := ⟨((SolarTV.Export.Main.bytecode.set i b).map UInt8.ofNat).toArray⟩ + +set_option maxRecDepth 100000 in +/-- The checker rejects the bytecode with a jump target moved (byte 2). -/ +theorem rejects_jump : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.Main.evm8 (mutant 2 30) cert maxs = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The checker rejects the bytecode with an SSTORE dropped (as POP) (byte 102). -/ +theorem rejects_sstore : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.Main.evm8 (mutant 102 80) cert maxs = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The checker rejects the bytecode with an opcode outside the fragment (CREATE) for an SSTORE (byte 102). -/ +theorem rejects_opcode : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.Main.evm8 (mutant 102 240) cert maxs = false := by + decide +kernel + +theorem gas_lt : SolidCore.Refinement.Solar.AssembleLoop.gasBoundL cert 5 < 2 ^ 64 := by decide +kernel + +theorem gas_le : SolidCore.Refinement.Solar.AssembleLoop.gasBoundL cert 5 ≤ 6298506 := by decide +kernel + +/-- SolidCore type checks the contract. -/ +theorem contract_ok : ∃ c, SolidCore.Refinement.Solar.MulX.contract? = .ok c := by + have h := SolidCore.Refinement.Solar.MulX.shape_eq + unfold SolidCore.Refinement.Solar.MulX.shape? at h + split at h + · next c hc => exact ⟨c, hc⟩ + · simp at h + + +/-- **What the published statement asks of this module.** -/ +theorem published : ∃ c, SolidCore.Refinement.Solar.MulX.contract? = .ok c ∧ + SolidCore.Refinement.Shapes.Compiled (solidCore SolidCore.Refinement.Solar.MulX.fuel) c code (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.MulX.fns) (SolidCore.Refinement.Solar.MulX.deployed)) (fun _ => 6298506) := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, d, hd⟩ := SolidCore.Refinement.Solar.MulX.deployed_of hc + have hchk := SolidCore.Refinement.Solar.MulX.check_stage0 + rw [← hk] at hchk + have hval := SolidCore.Refinement.Solar.MulX.checkValue_stage0 + rw [← hk] at hval + exact ⟨c, hc, (SolidCore.Refinement.Shapes.compiled hd hchk hval (SolidCore.Refinement.Shapes.genericValid_inhabited _ _ _) + (SolarTV.Milestone.Mulx.mulx_mir_to_evmir SolidCore.Refinement.Shapes.oracle) (fun _ _ => trivial) ends check_ok gas_lt).mono_gas (fun _ => gas_le) (fun _ => by decide)⟩ + +/-- info: 'Certified.mulx.Shape.published' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms published + +end Certified.mulx.Shape diff --git a/Certified/mulx/bytecode.hex b/Certified/mulx/bytecode.hex new file mode 100644 index 00000000..1e570744 --- /dev/null +++ b/Certified/mulx/bytecode.hex @@ -0,0 +1 @@ +34601d575f3560e01c806316ea58cb14606d5780639db20e58146033575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243560101c6064361060ff600435111717601d576004602435604435913502808280159202928304141715602157806001555f5260205ff35b60243560101c6044361060ff600435111717601d575f5460ff81166004350260ff81119160ff1916178060081c61ffff16602435028060101c90921760215762ffff0019169060081b175f55 diff --git a/Certified/mulx/gen/Main/Bytecode.lean b/Certified/mulx/gen/Main/Bytecode.lean new file mode 100644 index 00000000..7f0a5991 --- /dev/null +++ b/Certified/mulx/gen/Main/Bytecode.lean @@ -0,0 +1,25 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x1d, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x16, 0xea, 0x58, 0xcb, 0x14, + 0x60, 0x6d, 0x57, 0x80, 0x63, 0x9d, 0xb2, 0x0e, 0x58, 0x14, 0x60, 0x33, 0x57, 0x5b, 0x5f, 0x5f, + 0xfd, 0x5b, 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, + 0x60, 0x1c, 0xfd, 0x5b, 0x60, 0x24, 0x35, 0x60, 0x10, 0x1c, 0x60, 0x64, 0x36, 0x10, 0x60, 0xff, + 0x60, 0x04, 0x35, 0x11, 0x17, 0x17, 0x60, 0x1d, 0x57, 0x60, 0x04, 0x60, 0x24, 0x35, 0x60, 0x44, + 0x35, 0x91, 0x35, 0x02, 0x80, 0x82, 0x80, 0x15, 0x92, 0x02, 0x92, 0x83, 0x04, 0x14, 0x17, 0x15, + 0x60, 0x21, 0x57, 0x80, 0x60, 0x01, 0x55, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x24, + 0x35, 0x60, 0x10, 0x1c, 0x60, 0x44, 0x36, 0x10, 0x60, 0xff, 0x60, 0x04, 0x35, 0x11, 0x17, 0x17, + 0x60, 0x1d, 0x57, 0x5f, 0x54, 0x60, 0xff, 0x81, 0x16, 0x60, 0x04, 0x35, 0x02, 0x60, 0xff, 0x81, + 0x11, 0x91, 0x60, 0xff, 0x19, 0x16, 0x17, 0x80, 0x60, 0x08, 0x1c, 0x61, 0xff, 0xff, 0x16, 0x60, + 0x24, 0x35, 0x02, 0x80, 0x60, 0x10, 0x1c, 0x90, 0x92, 0x17, 0x60, 0x21, 0x57, 0x62, 0xff, 0xff, + 0x00, 0x19, 0x16, 0x90, 0x60, 0x08, 0x1b, 0x17, 0x5f, 0x55] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "34601d575f3560e01c806316ea58cb14606d5780639db20e58146033575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243560101c6064361060ff600435111717601d576004602435604435913502808280159202928304141715602157806001555f5260205ff35b60243560101c6044361060ff600435111717601d575f5460ff81166004350260ff81119160ff1916178060081c61ffff16602435028060101c90921760215762ffff0019169060081b175f55" + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Evm1.lean b/Certified/mulx/gen/Main/Evm1.lean new file mode 100644 index 00000000..a248e82f --- /dev/null +++ b/Certified/mulx/gen/Main/Evm1.lean @@ -0,0 +1,159 @@ +-- solar-lean-stage: kind=evm index=1 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00)), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 3, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000ff)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 7, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .mul), + .op (.stack (.swap 0)), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack (.dup 2)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Evm2.lean b/Certified/mulx/gen/Main/Evm2.lean new file mode 100644 index 00000000..7162fb24 --- /dev/null +++ b/Certified/mulx/gen/Main/Evm2.lean @@ -0,0 +1,161 @@ +-- solar-lean-stage: kind=evm index=2 pass=compact-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `compact-pushes`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 3, + .op (.stack (.push 0xffff00)), + .op (.stack .not), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 7, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .mul), + .op (.stack (.swap 0)), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack (.dup 2)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Evm3.lean b/Certified/mulx/gen/Main/Evm3.lean new file mode 100644 index 00000000..aeb68699 --- /dev/null +++ b/Certified/mulx/gen/Main/Evm3.lean @@ -0,0 +1,161 @@ +-- solar-lean-stage: kind=evm index=3 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `block-layout`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 0xffff00)), + .op (.stack .not), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 7, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .mul), + .op (.stack (.swap 0)), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack (.dup 2)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb13 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Evm4.lean b/Certified/mulx/gen/Main/Evm4.lean new file mode 100644 index 00000000..7de7c98f --- /dev/null +++ b/Certified/mulx/gen/Main/Evm4.lean @@ -0,0 +1,149 @@ +-- solar-lean-stage: kind=evm index=4 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 0xffff00)), + .op (.stack .not), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 7, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .mul), + .op (.stack (.swap 0)), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack (.dup 2)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.jump 1], + -- bb13 + [.jump 4], + -- bb14 + [.jump 1]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Evm5.lean b/Certified/mulx/gen/Main/Evm5.lean new file mode 100644 index 00000000..78037090 --- /dev/null +++ b/Certified/mulx/gen/Main/Evm5.lean @@ -0,0 +1,143 @@ +-- solar-lean-stage: kind=evm index=5 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 0xffff00)), + .op (.stack .not), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .mul), + .op (.stack (.swap 0)), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack (.dup 2)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Evm6.lean b/Certified/mulx/gen/Main/Evm6.lean new file mode 100644 index 00000000..8aadee35 --- /dev/null +++ b/Certified/mulx/gen/Main/Evm6.lean @@ -0,0 +1,143 @@ +-- solar-lean-stage: kind=evm index=6 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `block-layout`. -/ +def evm6 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 4, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 2, + .op (.stack (.push 0xffff00)), + .op (.stack .not), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .mul), + .op (.stack (.swap 0)), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack (.dup 2)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Evm7.lean b/Certified/mulx/gen/Main/Evm7.lean new file mode 100644 index 00000000..1e6bfb62 --- /dev/null +++ b/Certified/mulx/gen/Main/Evm7.lean @@ -0,0 +1,142 @@ +-- solar-lean-stage: kind=evm index=7 pass=stack-reschedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `stack-reschedule`. -/ +def evm7 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 4, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 2, + .op (.stack (.push 0xffff00)), + .op (.stack .not), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack .mul), + .op (.stack (.swap 2)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Evm8.lean b/Certified/mulx/gen/Main/Evm8.lean new file mode 100644 index 00000000..9317e0b3 --- /dev/null +++ b/Certified/mulx/gen/Main/Evm8.lean @@ -0,0 +1,142 @@ +-- solar-lean-stage: kind=evm index=8 pass=terminal-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `terminal-layout`. -/ +def evm8 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.swap 1)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack .mul), + .op (.stack (.swap 2)), + .op (.stack (.dup 3)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 255)), + .op (.stack .not), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 2, + .op (.stack (.push 0xffff00)), + .op (.stack .not), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Manifest.lean b/Certified/mulx/gen/Main/Manifest.lean new file mode 100644 index 00000000..61992274 --- /dev/null +++ b/Certified/mulx/gen/Main/Manifest.lean @@ -0,0 +1,46 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Main.Manifest + +def sources : List (String × String) := + [("Certified/mulx/mulx.sol", "c0dd0ad4558b8273ffd8b9e9abd7431eb429a29524df0b7cbe931076e0eb46d1")] + +def compiler : String := "0.8.38+commit.52e2060e.solar.0.3.0-dev" + +def arguments : List String := + ["Certified/mulx/mulx.sol", + "-Zcheck-analyses=false", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/mulx/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "2b9c8cec1601216327fccf673b46da96524d9a9f370a59ba48c0e8c681ab04d3"), + ("Mir1", "mir1", "place-reads", "00bc7419a9e8986262cab286f3b645a02372d763fb479aab53fd441540de293d"), + ("Mir2", "mir2", "spell-width-tests", "c968bd712214b6bee13301512125f77a4a78009ac4645f67c33973bb547da5d5"), + ("Mir3", "mir3", "evm-inst-schedule", "56851b5379010bdddc4322c96d0cf71074a5e03799692441f19bcec896c1f405"), + ("Sched", "sched", "stack-schedule", "65427f39b7dccd0532eea820dcf87913d159dd38432341d3a6eab343af58b1f5"), + ("Evm1", "evm1", "cfg-simplify-early", "0c8207918da2ec50f56ce74e53a462ec5439a64d172ac23415638e4030f18859"), + ("Evm2", "evm2", "compact-pushes", "59aa616e5814a8851865724e044fcc404b09cefa0301b05f3ada06cd397ba4ae"), + ("Evm3", "evm3", "block-layout", "3387cc09f143955e7a4a04c724d47b76f32c50a63b6c62a0d78d3c4f15586cb3"), + ("Evm4", "evm4", "terminal-dedup", "316cd3f9f0b49901c3e2b9a40e25148bfb2865742e41d560f3b5e3984bce857c"), + ("Evm5", "evm5", "cfg-simplify-early", "035c602fd240c7669f4cf04aecffc4d0c92710118d0ed62a04318db45c83adcd"), + ("Evm6", "evm6", "block-layout", "93fd2e565351cdc932aed3af2866ce507178d92df687db5f6073455723ca5081"), + ("Evm7", "evm7", "stack-reschedule", "0944bb89f3c09191c3f4a4f9f93921ba7e046e8b98f170ec37399164b47ade9d"), + ("Evm8", "evm8", "terminal-layout", "cbde24c2d1aca6c969d32bcb0bdfa778c1422db4507b1ee17cc2b85ffc7579bc"), + ("Bytecode", "bytecode", "assemble", "3e3d39a7bf6aea74f26053fb78ffd63c5e14743483a63449fccbf3bffc8eb6e3")] + +def bytecodeHex : String := + "34601d575f3560e01c806316ea58cb14606d5780639db20e58146033575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243560101c6064361060ff600435111717601d576004602435604435913502808280159202928304141715602157806001555f5260205ff35b60243560101c6044361060ff600435111717601d575f5460ff81166004350260ff81119160ff1916178060081c61ffff16602435028060101c90921760215762ffff0019169060081b175f55" + +def bytecodeSha256 : String := "42ecdc71b09d339299d2b7ce61e121c77b141c5386eb9cbf18792a9ba9ca4cfe" + +end SolarTV.Export.Main.Manifest diff --git a/Certified/mulx/gen/Main/Mir1.lean b/Certified/mulx/gen/Main/Mir1.lean new file mode 100644 index 00000000..be9c25bc --- /dev/null +++ b/Certified/mulx/gen/Main/Mir1.lean @@ -0,0 +1,126 @@ +-- solar-lean-stage: kind=mir index=1 pass=place-reads +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The lowered MIR module after `place-reads`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 3, + functions := [ + -- @m + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 48) .calldatasize [], + .pure 50 .lt [.value 48, .const 68], + .effect (some 52) .calldataload [.const 4], + .pure 54 .gt [.value 52, .const 255], + .pure 74 .or [.value 50, .value 54], + .effect (some 56) .calldataload [.const 36], + .pure 58 .gt [.value 56, .const 65535], + .pure 75 .or [.value 74, .value 58]], + .branch (.value 75) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.pure 24 .and [.value 12, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000ff], + .pure 27 .shl [.const 8, .value 43], + .pure 28 .or [.value 24, .value 27], + .effect none .sstore [.const 0, .value 28]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 78) .calldataload [.const 36], + .effect (some 77) .calldataload [.const 4], + .effect (some 3) .sload [.const 0], + .pure 73 .and [.value 3, .const 255], + .pure 31 .mul [.value 73, .value 77], + .pure 33 .gt [.value 31, .const 255], + .pure 9 .and [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00], + .pure 12 .or [.value 9, .value 31], + .pure 16 .shr [.const 8, .value 12], + .pure 65 .and [.value 16, .const 65535], + .pure 43 .mul [.value 65, .value 78], + .pure 45 .gt [.value 43, .const 65535], + .pure 76 .or [.value 33, .value 45]], + .branch (.value 76) 1 2⟩] }, + -- @n + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 29) .calldatasize [], + .pure 31 .lt [.value 29, .const 100], + .effect (some 33) .calldataload [.const 4], + .pure 35 .gt [.value 33, .const 255], + .pure 51 .or [.value 31, .value 35], + .effect (some 37) .calldataload [.const 36], + .pure 39 .gt [.value 37, .const 65535], + .pure 52 .or [.value 51, .value 39]], + .branch (.value 52) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 1, .value 11], + .effect none .mstore [.const 0, .value 11]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 54) .calldataload [.const 36], + .effect (some 53) .calldataload [.const 4], + .effect (some 41) .calldataload [.const 68], + .pure 5 .mul [.value 53, .value 54], + .pure 11 .mul [.value 5, .value 41], + .pure 13 .eq [.value 41, .const 0], + .pure 14 .div [.value 11, .value 41], + .pure 15 .eq [.value 14, .value 5], + .pure 16 .or [.value 13, .value 15]], + .branch (.value 16) 2 1⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 4 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 4 [(.const 0x16ea58cb, 2), (.const 0x9db20e58, 3)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Mir2.lean b/Certified/mulx/gen/Main/Mir2.lean new file mode 100644 index 00000000..604d6be2 --- /dev/null +++ b/Certified/mulx/gen/Main/Mir2.lean @@ -0,0 +1,132 @@ +-- solar-lean-stage: kind=mir index=2 pass=spell-width-tests +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The lowered MIR module after `spell-width-tests`. -/ +def mir2 : MIR.Lowered.Module := + { entry := 3, + functions := [ + -- @m + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 48) .calldatasize [], + .pure 50 .lt [.value 48, .const 68], + .effect (some 52) .calldataload [.const 4], + .pure 54 .gt [.value 52, .const 255], + .pure 74 .or [.value 50, .value 54], + .effect (some 56) .calldataload [.const 36], + .pure 80 .shr [.const 16, .value 56], + .word 83 (.value 74), + .pure 84 .or [.value 80, .value 83], + .ne 75 (.value 84) (.const 0)], + .branch (.value 75) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.pure 24 .and [.value 12, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000ff], + .pure 27 .shl [.const 8, .value 43], + .pure 28 .or [.value 24, .value 27], + .effect none .sstore [.const 0, .value 28]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 78) .calldataload [.const 36], + .effect (some 77) .calldataload [.const 4], + .effect (some 3) .sload [.const 0], + .pure 73 .and [.value 3, .const 255], + .pure 31 .mul [.value 73, .value 77], + .pure 33 .gt [.value 31, .const 255], + .pure 9 .and [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00], + .pure 12 .or [.value 9, .value 31], + .pure 16 .shr [.const 8, .value 12], + .pure 65 .and [.value 16, .const 65535], + .pure 43 .mul [.value 65, .value 78], + .pure 88 .shr [.const 16, .value 43], + .word 91 (.value 33), + .pure 92 .or [.value 88, .value 91], + .ne 76 (.value 92) (.const 0)], + .branch (.value 76) 1 2⟩] }, + -- @n + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 29) .calldatasize [], + .pure 31 .lt [.value 29, .const 100], + .effect (some 33) .calldataload [.const 4], + .pure 35 .gt [.value 33, .const 255], + .pure 51 .or [.value 31, .value 35], + .effect (some 37) .calldataload [.const 36], + .pure 56 .shr [.const 16, .value 37], + .word 59 (.value 51), + .pure 60 .or [.value 56, .value 59], + .ne 52 (.value 60) (.const 0)], + .branch (.value 52) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 1, .value 11], + .effect none .mstore [.const 0, .value 11]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 54) .calldataload [.const 36], + .effect (some 53) .calldataload [.const 4], + .effect (some 41) .calldataload [.const 68], + .pure 5 .mul [.value 53, .value 54], + .pure 11 .mul [.value 5, .value 41], + .pure 13 .eq [.value 41, .const 0], + .pure 14 .div [.value 11, .value 41], + .pure 15 .eq [.value 14, .value 5], + .pure 16 .or [.value 13, .value 15]], + .branch (.value 16) 2 1⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 4 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 4 [(.const 0x16ea58cb, 2), (.const 0x9db20e58, 3)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Mir3.lean b/Certified/mulx/gen/Main/Mir3.lean new file mode 100644 index 00000000..51d13904 --- /dev/null +++ b/Certified/mulx/gen/Main/Mir3.lean @@ -0,0 +1,132 @@ +-- solar-lean-stage: kind=mir index=3 pass=evm-inst-schedule +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The lowered MIR module after `evm-inst-schedule`. -/ +def mir3 : MIR.Lowered.Module := + { entry := 3, + functions := [ + -- @m + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 56) .calldataload [.const 36], + .pure 80 .shr [.const 16, .value 56], + .effect (some 48) .calldatasize [], + .pure 50 .lt [.value 48, .const 68], + .effect (some 52) .calldataload [.const 4], + .pure 54 .gt [.value 52, .const 255], + .pure 74 .or [.value 50, .value 54], + .word 83 (.value 74), + .pure 84 .or [.value 80, .value 83], + .ne 75 (.value 84) (.const 0)], + .branch (.value 75) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.pure 24 .and [.value 12, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000ff], + .pure 27 .shl [.const 8, .value 43], + .pure 28 .or [.value 24, .value 27], + .effect none .sstore [.const 0, .value 28]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 78) .calldataload [.const 36], + .effect (some 77) .calldataload [.const 4], + .effect (some 3) .sload [.const 0], + .pure 73 .and [.value 3, .const 255], + .pure 31 .mul [.value 73, .value 77], + .pure 33 .gt [.value 31, .const 255], + .pure 9 .and [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00], + .pure 12 .or [.value 9, .value 31], + .pure 16 .shr [.const 8, .value 12], + .pure 65 .and [.value 16, .const 65535], + .pure 43 .mul [.value 65, .value 78], + .pure 88 .shr [.const 16, .value 43], + .word 91 (.value 33), + .pure 92 .or [.value 88, .value 91], + .ne 76 (.value 92) (.const 0)], + .branch (.value 76) 1 2⟩] }, + -- @n + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 37) .calldataload [.const 36], + .pure 56 .shr [.const 16, .value 37], + .effect (some 29) .calldatasize [], + .pure 31 .lt [.value 29, .const 100], + .effect (some 33) .calldataload [.const 4], + .pure 35 .gt [.value 33, .const 255], + .pure 51 .or [.value 31, .value 35], + .word 59 (.value 51), + .pure 60 .or [.value 56, .value 59], + .ne 52 (.value 60) (.const 0)], + .branch (.value 52) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 1, .value 11], + .effect none .mstore [.const 0, .value 11]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 54) .calldataload [.const 36], + .effect (some 53) .calldataload [.const 4], + .effect (some 41) .calldataload [.const 68], + .pure 5 .mul [.value 53, .value 54], + .pure 11 .mul [.value 5, .value 41], + .pure 13 .eq [.value 41, .const 0], + .pure 14 .div [.value 11, .value 41], + .pure 15 .eq [.value 14, .value 5], + .pure 16 .or [.value 13, .value 15]], + .branch (.value 16) 2 1⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 4 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 4 [(.const 0x16ea58cb, 2), (.const 0x9db20e58, 3)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Sched.lean b/Certified/mulx/gen/Main/Sched.lean new file mode 100644 index 00000000..38398b2d --- /dev/null +++ b/Certified/mulx/gen/Main/Sched.lean @@ -0,0 +1,173 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 4, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x16ea58cb)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x9db20e58)), + .op (.stack .eq), + .jumpi 2, + .jump 4], + -- bb2 + [.jump 10], + -- bb3 + [.jump 5], + -- bb4 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb5 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 9, + .jump 6], + -- bb6 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.push 255)), + .op (.stack (.dup 1)), + .op (.stack .gt), + .op (.stack (.swap 1)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00)), + .op (.stack .and), + .op (.stack .or), + .op (.stack (.dup 0)), + .op (.stack (.push 8)), + .op (.stack .shr), + .op (.stack (.push 65535)), + .op (.stack .and), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 0)), + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.swap 0)), + .op (.stack (.swap 2)), + .op (.stack .or), + .jumpi 8, + .jump 7], + -- bb7 + [.op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000ff)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 8)), + .op (.stack .shl), + .op (.stack .or), + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb8 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 16)), + .op (.stack .shr), + .op (.stack (.push 100)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack (.push 255)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .gt), + .op (.stack .or), + .op (.stack .or), + .jumpi 14, + .jump 11], + -- bb11 + [.op (.stack (.push 68)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack .mul), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .mul), + .op (.stack (.swap 0)), + .op (.stack (.dup 2)), + .op (.stack .iszero), + .op (.stack (.swap 2)), + .op (.stack (.dup 2)), + .op (.stack .div), + .op (.stack .eq), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .or), + .op (.stack .iszero), + .jumpi 13, + .jump 12], + -- bb12 + [.op (.stack (.dup 0)), + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb13 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/Schedule.json b/Certified/mulx/gen/Main/Schedule.json new file mode 100644 index 00000000..cd1b57d3 --- /dev/null +++ b/Certified/mulx/gen/Main/Schedule.json @@ -0,0 +1,28 @@ +{ + "functions": [ + {"function": 3, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [3, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [4, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 0, "entry": 5, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [5, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [8, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [7, 0], "layout": ["v43", "v12"], "floating": true, "continues": null}, + {"block": 3, "start": [9, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [6, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 1, "entry": 10, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [10, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [13, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [12, 0], "layout": ["v11"], "floating": true, "continues": null}, + {"block": 3, "start": [14, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [11, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]} + ] +} diff --git a/Certified/mulx/gen/Main/Stage0.lean b/Certified/mulx/gen/Main/Stage0.lean new file mode 100644 index 00000000..b240a5bc --- /dev/null +++ b/Certified/mulx/gen/Main/Stage0.lean @@ -0,0 +1,122 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 3, + functions := [ + -- @m + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 48) .calldatasize [], + .pure 50 .lt [.value 48, .const 68], + .effect (some 52) .calldataload [.const 4], + .pure 54 .gt [.value 52, .const 255], + .pure 74 .or [.value 50, .value 54], + .effect (some 56) .calldataload [.const 36], + .pure 58 .gt [.value 56, .const 65535], + .pure 75 .or [.value 74, .value 58]], + .branch (.value 75) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.pure 24 .and [.value 12, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000ff], + .pure 27 .shl [.const 8, .value 43], + .pure 28 .or [.value 24, .value 27], + .effect none .sstore [.const 0, .value 28]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 3) .sload [.const 0], + .pure 73 .and [.value 3, .const 255], + .pure 31 .mul [.value 73, .value 52], + .pure 33 .gt [.value 31, .const 255], + .pure 9 .and [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00], + .pure 12 .or [.value 9, .value 31], + .pure 16 .shr [.const 8, .value 12], + .pure 65 .and [.value 16, .const 65535], + .pure 43 .mul [.value 65, .value 56], + .pure 45 .gt [.value 43, .const 65535], + .pure 76 .or [.value 33, .value 45]], + .branch (.value 76) 1 2⟩] }, + -- @n + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 29) .calldatasize [], + .pure 31 .lt [.value 29, .const 100], + .effect (some 33) .calldataload [.const 4], + .pure 35 .gt [.value 33, .const 255], + .pure 51 .or [.value 31, .value 35], + .effect (some 37) .calldataload [.const 36], + .pure 39 .gt [.value 37, .const 65535], + .pure 52 .or [.value 51, .value 39]], + .branch (.value 52) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 1, .value 11], + .effect none .mstore [.const 0, .value 11]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 41) .calldataload [.const 68], + .pure 5 .mul [.value 33, .value 37], + .pure 11 .mul [.value 5, .value 41], + .pure 13 .eq [.value 41, .const 0], + .pure 14 .div [.value 11, .value 41], + .pure 15 .eq [.value 14, .value 5], + .pure 16 .or [.value 13, .value 15]], + .branch (.value 16) 2 1⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 4 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 4 [(.const 0x16ea58cb, 2), (.const 0x9db20e58, 3)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/mulx/gen/Main/manifest.json b/Certified/mulx/gen/Main/manifest.json new file mode 100644 index 00000000..c61125ba --- /dev/null +++ b/Certified/mulx/gen/Main/manifest.json @@ -0,0 +1,135 @@ +{ + "arguments": [ + "Certified/mulx/mulx.sol", + "-Zcheck-analyses=false", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/mulx/gen" + ], + "bytecode": "34601d575f3560e01c806316ea58cb14606d5780639db20e58146033575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243560101c6064361060ff600435111717601d576004602435604435913502808280159202928304141715602157806001555f5260205ff35b60243560101c6044361060ff600435111717601d575f5460ff81166004350260ff81119160ff1916178060081c61ffff16602435028060101c90921760215762ffff0019169060081b175f55", + "bytecode_sha256": "42ecdc71b09d339299d2b7ce61e121c77b141c5386eb9cbf18792a9ba9ca4cfe", + "compiler": "0.8.38+commit.52e2060e.solar.0.3.0-dev", + "contract": "Main", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"Certified/mulx/mulx.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"check-analyses=false\", \"emit-lean-stages=Certified/mulx/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: Some(false), prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/mulx/gen\"), keep_asts: false, forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "Certified/mulx/mulx.sol", + "sha256": "c0dd0ad4558b8273ffd8b9e9abd7431eb429a29524df0b7cbe931076e0eb46d1" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "2b9c8cec1601216327fccf673b46da96524d9a9f370a59ba48c0e8c681ab04d3" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "place-reads", + "sha256": "00bc7419a9e8986262cab286f3b645a02372d763fb479aab53fd441540de293d" + }, + { + "definition": "mir2", + "file": "Mir2.lean", + "index": 2, + "kind": "mir", + "pass": "spell-width-tests", + "sha256": "c968bd712214b6bee13301512125f77a4a78009ac4645f67c33973bb547da5d5" + }, + { + "definition": "mir3", + "file": "Mir3.lean", + "index": 3, + "kind": "mir", + "pass": "evm-inst-schedule", + "sha256": "56851b5379010bdddc4322c96d0cf71074a5e03799692441f19bcec896c1f405" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "65427f39b7dccd0532eea820dcf87913d159dd38432341d3a6eab343af58b1f5" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "0c8207918da2ec50f56ce74e53a462ec5439a64d172ac23415638e4030f18859" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "compact-pushes", + "sha256": "59aa616e5814a8851865724e044fcc404b09cefa0301b05f3ada06cd397ba4ae" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "block-layout", + "sha256": "3387cc09f143955e7a4a04c724d47b76f32c50a63b6c62a0d78d3c4f15586cb3" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "316cd3f9f0b49901c3e2b9a40e25148bfb2865742e41d560f3b5e3984bce857c" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "035c602fd240c7669f4cf04aecffc4d0c92710118d0ed62a04318db45c83adcd" + }, + { + "definition": "evm6", + "file": "Evm6.lean", + "index": 6, + "kind": "evm", + "pass": "block-layout", + "sha256": "93fd2e565351cdc932aed3af2866ce507178d92df687db5f6073455723ca5081" + }, + { + "definition": "evm7", + "file": "Evm7.lean", + "index": 7, + "kind": "evm", + "pass": "stack-reschedule", + "sha256": "0944bb89f3c09191c3f4a4f9f93921ba7e046e8b98f170ec37399164b47ade9d" + }, + { + "definition": "evm8", + "file": "Evm8.lean", + "index": 8, + "kind": "evm", + "pass": "terminal-layout", + "sha256": "cbde24c2d1aca6c969d32bcb0bdfa778c1422db4507b1ee17cc2b85ffc7579bc" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "3e3d39a7bf6aea74f26053fb78ffd63c5e14743483a63449fccbf3bffc8eb6e3" + } + ] +} diff --git a/Certified/mulx/mulx.sol b/Certified/mulx/mulx.sol new file mode 100644 index 00000000..23f7b978 --- /dev/null +++ b/Certified/mulx/mulx.sol @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + uint8 x8; + uint16 y16 = 3; + uint256 z; + /// @custom:succeeds-if msg.value == 0 && (x8 * a < 256 && y16 * b < 65536) + /// @custom:ensures x8 == old(x8) * a + /// @custom:ensures y16 == old(y16) * b + /// @custom:ensures z == old(z) + function m(uint8 a, uint16 b) external { x8 *= a; y16 *= b; } + /// @custom:succeeds-if msg.value == 0 && (a * b * c < 2 ** 256) + /// @custom:ensures z == a * b * c + /// @custom:ensures result == a * b * c + /// @custom:ensures x8 == old(x8) && y16 == old(y16) + function n(uint8 a, uint16 b, uint256 c) external returns (uint256) { z = uint256(a) * b * c; return z; } +} diff --git a/Certified/mulx/options b/Certified/mulx/options new file mode 100644 index 00000000..55fc63cf --- /dev/null +++ b/Certified/mulx/options @@ -0,0 +1 @@ +-Zcheck-analyses=false diff --git a/Certified/mulx/record.json b/Certified/mulx/record.json new file mode 100644 index 00000000..02a9cc9d --- /dev/null +++ b/Certified/mulx/record.json @@ -0,0 +1,89 @@ +{ + "contract": "Main", + "name": "mulx", + "source": "Certified/mulx/mulx.sol", + "bytecode": "34601d575f3560e01c806316ea58cb14606d5780639db20e58146033575b5f5ffd5b6011602052634e487b715f526024601cfd5b60243560101c6064361060ff600435111717601d576004602435604435913502808280159202928304141715602157806001555f5260205ff35b60243560101c6044361060ff600435111717601d575f5460ff81166004350260ff81119160ff1916178060081c61ffff16602435028060101c90921760215762ffff0019169060081b175f55", + "solar": "cb5053ab39adfd59820913b336d346389ce1b8d9", + "solidity_lean": "11fb9334142fbb8ded0b1d699015a978cdc3ed52", + "mir_to_evmir": "proved: SolarTV.Milestone.Mulx.mulx_mir_to_evmir", + "assembly": "decoded only: mulx.Proofs.Assembly (the bytecode decodes to the final EVM IR's instructions; no execution theorem)", + "vc": "exported to .lake/certify/mulx/VC.lean", + "end_to_end": "not proved", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, a field of Shapes.Compiled)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with any status (no specification declares the allowed ones); the bytecode too, at gas from the bound on", + "spec": "none: solar-verify has no specification of mulx", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result", + "assumptions": "none beyond the statement's scope", + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: m(uint8,uint16) and n(uint8,uint16,uint256) ABI-encoded with clean argument words, any value below 2^256, from any storage that writes slot 0; other call data is outside the statement", + "spec: none (solar-verify has no specification of mulx): equivalence, termination and resources only" + ], + "strongest": false + }, + "final": { + "module": "mulx.Final", + "theorem": "Certified.mulx.Final.final", + "kind": "compiled", + "statement": "code.data.toList.map (·.toNat) = runtimeBytes ∧ (∃ c, SolidCore.Refinement.Solar.MulX.contract? = .ok c ∧ Shapes.Compiled (solidCore (SolidCore.Refinement.Solar.MulX.fuel)) c code (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.MulX.fns) (SolidCore.Refinement.Solar.MulX.deployed)) (fun _ => 6298506))", + "assumptions": [], + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: m(uint8,uint16) and n(uint8,uint16,uint256) ABI-encoded with clean argument words, any value below 2^256, from any storage that writes slot 0; other call data is outside the statement", + "spec: none (solar-verify has no specification of mulx): equivalence, termination and resources only" + ], + "spec": "none: solar-verify has no specification of mulx", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, a field of Shapes.Compiled)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with any status (no specification declares the allowed ones); the bytecode too, at gas from the bound on", + "spec": "none: solar-verify has no specification of mulx", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result" + } + }, + "end_to_end_statement": {}, + "binding": {}, + "hypotheses": {}, + "refused": [], + "vacuous": "not checked", + "assembly_statement": null, + "assembly_hypotheses": null, + "negative_tests": false, + "caveats": [ + "solidity-lean at 11fb9334142fbb8ded0b1d699015a978cdc3ed52, not the pinned 95ebfd5f178b93b42d498a124104fc92bfc6b74f", + "solar cb5053ab39adfd59820913b336d346389ce1b8d9, not built from this checkout's compiler sources", + "assembly decoded, not executed", + "not end to end: solidity-lean states no source or spec theorem for mulx", + "negative tests skipped" + ], + "backend": { + "theorem": { + "module": "mulx.Final", + "theorem": "Certified.mulx.Final.final", + "kind": "compiled", + "statement": "code.data.toList.map (·.toNat) = runtimeBytes ∧ (∃ c, SolidCore.Refinement.Solar.MulX.contract? = .ok c ∧ Shapes.Compiled (solidCore (SolidCore.Refinement.Solar.MulX.fuel)) c code (SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.MulX.fns) (SolidCore.Refinement.Solar.MulX.deployed)) (fun _ => 6298506))", + "assumptions": [], + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: m(uint8,uint16) and n(uint8,uint16,uint256) ABI-encoded with clean argument words, any value below 2^256, from any storage that writes slot 0; other call data is outside the statement", + "spec: none (solar-verify has no specification of mulx): equivalence, termination and resources only" + ], + "spec": "none: solar-verify has no specification of mulx", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, a field of Shapes.Compiled)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with any status (no specification declares the allowed ones); the bytecode too, at gas from the bound on", + "spec": "none: solar-verify has no specification of mulx", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result" + } + } + } +} diff --git a/Certified/mulx/shape.json b/Certified/mulx/shape.json new file mode 100644 index 00000000..ca3eb824 --- /dev/null +++ b/Certified/mulx/shape.json @@ -0,0 +1,47 @@ +{ + "kind": "certified", + "contract": "SolidCore.Refinement.Solar.MulX.contract?", + "fuel": "SolidCore.Refinement.Solar.MulX.fuel", + "valid": "SolidCore.Refinement.Shapes.genericValid (SolidCore.Refinement.Solar.MulX.fns) (SolidCore.Refinement.Solar.MulX.deployed)", + "allowed_export": true, + "spec_export": { + "ctx": "SolidCore.Refinement.Shapes.ctxOfCall", + "step": "SolidCore.Refinement.Shapes.idStep" + }, + "nonvacuous": "Certified.mulx.Shape.nonvacuous", + "gas": "fun _ => 6298506", + "env": [], + "spec": "solar-verify's export of mulx.sol in this run (Certified.mulx.gen.Main.Spec.Main): m(a, b) ensures x8 == old(x8) * a, y16 == old(y16) * b and z unchanged, and succeeds-if msg.value == 0 and both products fit their widths; n(a, b, c) ensures z == a * b * c and returns it, x8 and y16 unchanged, and succeeds-if msg.value == 0 and a * b * c < 2^256. The postcondition (bundlePost) and the allowed statuses (bundleAllowed) are both read off that export", + "spec_modules": [ + "SolidCore.Refinement.Solar.MulX.Lowering", + "Verify.ShapeGeneric", + "Verify.ShapeSpecExport" + ], + "proof_module": "mulx.Shape", + "proof": "Certified.mulx.Shape.published", + "generic": { + "lowering": "SolidCore.Refinement.Solar.MulX.Lowering", + "ns": "SolidCore.Refinement.Solar.MulX", + "style": "core", + "check": "check_stage0", + "check_value": "checkValue_stage0", + "fns": "SolidCore.Refinement.Solar.MulX.fns", + "storage": "SolidCore.Refinement.Solar.MulX.deployed", + "spec_connect": { + "witness": "m" + } + }, + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: m(uint8,uint16) and n(uint8,uint16,uint256) ABI-encoded with clean argument words, any value below 2^256, from any storage that writes slot 0; other call data is outside the statement", + "spec: solar-verify's exported spec of m and n, with their succeeds-if conditions: every revert the statement allows is one from which no succeeds-if condition requires success (an overflow, or a call with a value)" + ], + "source_ast": { + "file": "SolidCore/Refinement/Source/MulX.lean", + "namespace": "SolidCore.Refinement.Source.MulX", + "contract": "Main" + } +} diff --git a/Certified/reader/Proofs.lean b/Certified/reader/Proofs.lean new file mode 100644 index 00000000..33ee215c --- /dev/null +++ b/Certified/reader/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import reader.Proofs.Stages +import reader.Proofs.Assembly diff --git a/Certified/reader/Proofs/Assembly.lean b/Certified/reader/Proofs/Assembly.lean new file mode 100644 index 00000000..bc7db8fa --- /dev/null +++ b/Certified/reader/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Items +import reader.gen.Reader.Evm7 +import reader.gen.Reader.Bytecode + +/-! The final EVM IR of `Reader` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.Reader + +open SolarTV.Assembly SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm7).getD [] + +theorem items_eq : itemsOf evm7 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x53 else if label = 2 then 0x57 else if label = 3 then 0x5f else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.Reader.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.Reader.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms decodes + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Evm1.lean b/Certified/reader/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..a4ea4817 --- /dev/null +++ b/Certified/reader/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Evm1 +import reader.gen.Reader.Sched + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 48 = EVM.Program.run o evm1 call 24 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Evm2.lean b/Certified/reader/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..9df61b91 --- /dev/null +++ b/Certified/reader/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Evm2 +import reader.gen.Reader.Evm1 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 24 = EVM.Program.run o evm2 call 24 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Evm3.lean b/Certified/reader/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..5082a9eb --- /dev/null +++ b/Certified/reader/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Evm3 +import reader.gen.Reader.Evm2 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 24 = EVM.Program.run o evm3 call 24 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Evm4.lean b/Certified/reader/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..32b0d6c9 --- /dev/null +++ b/Certified/reader/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Evm4 +import reader.gen.Reader.Evm3 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 24 = EVM.Program.run o evm4 call 20 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Evm5.lean b/Certified/reader/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..27bcf7a1 --- /dev/null +++ b/Certified/reader/Proofs/Runs/Evm5.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Evm5 +import reader.gen.Reader.Evm4 + +/-! `block-cse`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 20 = EVM.Program.run o evm5 call 20 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Evm6.lean b/Certified/reader/Proofs/Runs/Evm6.lean new file mode 100644 index 00000000..3b5f6f1c --- /dev/null +++ b/Certified/reader/Proofs/Runs/Evm6.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Evm6 +import reader.gen.Reader.Evm5 + +/-! `share-reverts`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm6_run (o : Oracle) (call : Call) : + EVM.Program.run o evm5 call 20 = EVM.Program.run o evm6 call 20 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.evm6_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Evm7.lean b/Certified/reader/Proofs/Runs/Evm7.lean new file mode 100644 index 00000000..a91013f3 --- /dev/null +++ b/Certified/reader/Proofs/Runs/Evm7.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Evm7 +import reader.gen.Reader.Evm6 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm7_run (o : Oracle) (call : Call) : + EVM.Program.run o evm6 call 20 = EVM.Program.run o evm7 call 16 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.evm7_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm7_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Mir1.lean b/Certified/reader/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..bda91c4e --- /dev/null +++ b/Certified/reader/Proofs/Runs/Mir1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Mir1 +import reader.gen.Reader.Stage0 + +/-! `place-reads`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir1_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 48 = MIR.Lowered.Module.run o mir1 call 48 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.mir1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Mir2.lean b/Certified/reader/Proofs/Runs/Mir2.lean new file mode 100644 index 00000000..383de90c --- /dev/null +++ b/Certified/reader/Proofs/Runs/Mir2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Mir2 +import reader.gen.Reader.Mir1 + +/-! `spell-width-tests`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir2_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir1 call 48 = MIR.Lowered.Module.run o mir2 call 48 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.mir2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir2_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Mir3.lean b/Certified/reader/Proofs/Runs/Mir3.lean new file mode 100644 index 00000000..15d9688e --- /dev/null +++ b/Certified/reader/Proofs/Runs/Mir3.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Mir3 +import reader.gen.Reader.Mir2 + +/-! `evm-inst-schedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir3_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir2 call 48 = MIR.Lowered.Module.run o mir3 call 48 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.mir3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir3_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Sched.lean b/Certified/reader/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..7e4cda57 --- /dev/null +++ b/Certified/reader/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Sched +import reader.gen.Reader.Mir3 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir3 call 48 = EVM.Program.run o sched call 48 := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Runs/Stage0.lean b/Certified/reader/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..a20b4226 --- /dev/null +++ b/Certified/reader/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import reader.gen.Reader.Stage0 + +/-! The first lowered MIR ends on every call within 48 blocks, its block count times the square of one more than its call sites. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 48).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.Reader.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/Proofs/Stages.lean b/Certified/reader/Proofs/Stages.lean new file mode 100644 index 00000000..65e43185 --- /dev/null +++ b/Certified/reader/Proofs/Stages.lean @@ -0,0 +1,195 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import reader.Proofs.Runs.Stage0 +import reader.Proofs.Runs.Mir1 +import reader.Proofs.Runs.Mir2 +import reader.Proofs.Runs.Mir3 +import reader.Proofs.Runs.Sched +import reader.Proofs.Runs.Evm1 +import reader.Proofs.Runs.Evm2 +import reader.Proofs.Runs.Evm3 +import reader.Proofs.Runs.Evm4 +import reader.Proofs.Runs.Evm5 +import reader.Proofs.Runs.Evm6 +import reader.Proofs.Runs.Evm7 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Reader`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm7`. Fuels are the programs' block counts times the square of one more than their call sites. -/ + +namespace SolarTV.Milestone.Reader + +open Machine SolarTV.Export.Reader SolarTV.Milestone.W1 + +/-- `place-reads`: stage0 to mir1. -/ +theorem stage_mir1 (o : Oracle) : Stage (mirSem o) (mirSem o) stage0 mir1 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 48 48 (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +theorem mir1_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir1 call 48).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := stage0) (q := mir1) (n := 48) (m := 48) (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +/-- `spell-width-tests`: mir1 to mir2. -/ +theorem stage_mir2 (o : Oracle) : Stage (mirSem o) (mirSem o) mir1 mir2 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 48 48 (mir1_ends o) + (fun call _ => mir2_run o call) + +theorem mir2_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir2 call 48).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir1) (q := mir2) (n := 48) (m := 48) (mir1_ends o) + (fun call _ => mir2_run o call) + +/-- `evm-inst-schedule`: mir2 to mir3. -/ +theorem stage_mir3 (o : Oracle) : Stage (mirSem o) (mirSem o) mir2 mir3 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 48 48 (mir2_ends o) + (fun call _ => mir3_run o call) + +theorem mir3_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir3 call 48).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir2) (q := mir3) (n := 48) (m := 48) (mir2_ends o) + (fun call _ => mir3_run o call) + +/-- `stack-schedule`: mir3 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) mir3 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 48 48 (mir3_ends o) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 48).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := mir3) (q := sched) (n := 48) (m := 48) (mir3_ends o) + (fun call _ => sched_run o call) + +/-- `cfg-simplify-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 48 24 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 24).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 48) (m := 24) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `block-layout`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 24 24 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 24).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 24) (m := 24) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `terminal-dedup`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 24 24 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 24).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 24) (m := 24) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `cfg-simplify-early`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 24 20 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 20).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 24) (m := 20) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `block-cse`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 20 20 (evm4_ends o) + (fun call _ => evm5_run o call) + +theorem evm5_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm5 call 20).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm4) (q := evm5) (n := 20) (m := 20) (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- `share-reverts`: evm5 to evm6. -/ +theorem stage_evm6 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm5 evm6 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 20 20 (evm5_ends o) + (fun call _ => evm6_run o call) + +theorem evm6_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm6 call 20).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm5) (q := evm6) (n := 20) (m := 20) (evm5_ends o) + (fun call _ => evm6_run o call) + +/-- `cfg-simplify-early`: evm6 to evm7. -/ +theorem stage_evm7 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm6 evm7 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 20 16 (evm6_ends o) + (fun call _ => evm7_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1, mir2, mir3], sched, [evm1, evm2, evm3, evm4, evm5, evm6, evm7]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem reader_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm7 anyCall := + mir_to_evmir o anyCall compilation ⟨stage_mir1 o, stage_mir2 o, stage_mir3 o, trivial⟩ (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, stage_evm6 o, stage_evm7 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.Reader.stage_mir1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir1 + +/-- info: 'SolarTV.Milestone.Reader.stage_mir2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir2 + +/-- info: 'SolarTV.Milestone.Reader.stage_mir3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir3 + +/-- info: 'SolarTV.Milestone.Reader.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.Reader.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.Reader.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.Reader.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.Reader.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.Reader.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.Reader.stage_evm6' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm6 + +/-- info: 'SolarTV.Milestone.Reader.stage_evm7' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm7 + +/-- info: 'SolarTV.Milestone.Reader.reader_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms reader_mir_to_evmir + +end SolarTV.Milestone.Reader diff --git a/Certified/reader/bytecode.hex b/Certified/reader/bytecode.hex new file mode 100644 index 00000000..38cf9e30 --- /dev/null +++ b/Certified/reader/bytecode.hex @@ -0,0 +1 @@ +346053575f3560e01c8063a087a87e03605357608060405260043560a01c602436101760535763a035b1fe5f5260205f6004601c81355afa156057573d6020116053575f516001018015605f575f5260205ff35b5f5ffd5b3d5f5f3e3d5ffd5b6011602052634e487b715f526024601cfd diff --git a/Certified/reader/gen/Reader/Bytecode.lean b/Certified/reader/gen/Reader/Bytecode.lean new file mode 100644 index 00000000..fdf8bb18 --- /dev/null +++ b/Certified/reader/gen/Reader/Bytecode.lean @@ -0,0 +1,21 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x53, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0xa0, 0x87, 0xa8, 0x7e, 0x03, + 0x60, 0x53, 0x57, 0x60, 0x80, 0x60, 0x40, 0x52, 0x60, 0x04, 0x35, 0x60, 0xa0, 0x1c, 0x60, 0x24, + 0x36, 0x10, 0x17, 0x60, 0x53, 0x57, 0x63, 0xa0, 0x35, 0xb1, 0xfe, 0x5f, 0x52, 0x60, 0x20, 0x5f, + 0x60, 0x04, 0x60, 0x1c, 0x81, 0x35, 0x5a, 0xfa, 0x15, 0x60, 0x57, 0x57, 0x3d, 0x60, 0x20, 0x11, + 0x60, 0x53, 0x57, 0x5f, 0x51, 0x60, 0x01, 0x01, 0x80, 0x15, 0x60, 0x5f, 0x57, 0x5f, 0x52, 0x60, + 0x20, 0x5f, 0xf3, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x3d, 0x5f, 0x5f, 0x3e, 0x3d, 0x5f, 0xfd, 0x5b, + 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, 0x60, 0x1c, + 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "346053575f3560e01c8063a087a87e03605357608060405260043560a01c602436101760535763a035b1fe5f5260205f6004601c81355afa156057573d6020116053575f516001018015605f575f5260205ff35b5f5ffd5b3d5f5f3e3d5ffd5b6011602052634e487b715f526024601cfd" + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Evm1.lean b/Certified/reader/gen/Reader/Evm1.lean new file mode 100644 index 00000000..89e56944 --- /dev/null +++ b/Certified/reader/gen/Reader/Evm1.lean @@ -0,0 +1,92 @@ +-- solar-lean-stage: kind=evm index=1 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xa087a87e)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 5, + .op (.stack (.push 0xa035b1fe)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .op (.stack (.push 4)), + .op (.stack (.push 28)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .gas 0, + .effect (.call .staticcall) 6, + .op (.stack .iszero), + .jumpi 3, + .op (.stack .returndatasize), + .op (.stack (.push 32)), + .op (.stack .gt), + .jumpi 5, + .op (.stack (.push 0)), + .op .load, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack .returndatasize), + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .effect .returndatacopy 3, + .op (.stack .returndatasize), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Evm2.lean b/Certified/reader/gen/Reader/Evm2.lean new file mode 100644 index 00000000..de6983b7 --- /dev/null +++ b/Certified/reader/gen/Reader/Evm2.lean @@ -0,0 +1,92 @@ +-- solar-lean-stage: kind=evm index=2 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime EVM IR after `block-layout`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xa087a87e)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 2, + .op (.stack (.push 0xa035b1fe)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .op (.stack (.push 4)), + .op (.stack (.push 28)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .gas 0, + .effect (.call .staticcall) 6, + .op (.stack .iszero), + .jumpi 4, + .op (.stack .returndatasize), + .op (.stack (.push 32)), + .op (.stack .gt), + .jumpi 2, + .op (.stack (.push 0)), + .op .load, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 5, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack .returndatasize), + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .effect .returndatacopy 3, + .op (.stack .returndatasize), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Evm3.lean b/Certified/reader/gen/Reader/Evm3.lean new file mode 100644 index 00000000..fcfc5566 --- /dev/null +++ b/Certified/reader/gen/Reader/Evm3.lean @@ -0,0 +1,90 @@ +-- solar-lean-stage: kind=evm index=3 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xa087a87e)), + .op (.stack .eq), + .jumpi 3, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb11 + [.jump 1], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 2, + .op (.stack (.push 0xa035b1fe)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .op (.stack (.push 4)), + .op (.stack (.push 28)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .gas 0, + .effect (.call .staticcall) 6, + .op (.stack .iszero), + .jumpi 4, + .op (.stack .returndatasize), + .op (.stack (.push 32)), + .op (.stack .gt), + .jumpi 2, + .op (.stack (.push 0)), + .op .load, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 5, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack .returndatasize), + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .effect .returndatacopy 3, + .op (.stack .returndatasize), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Evm4.lean b/Certified/reader/gen/Reader/Evm4.lean new file mode 100644 index 00000000..547ef996 --- /dev/null +++ b/Certified/reader/gen/Reader/Evm4.lean @@ -0,0 +1,88 @@ +-- solar-lean-stage: kind=evm index=4 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xa087a87e)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0xa035b1fe)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .op (.stack (.push 4)), + .op (.stack (.push 28)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .gas 0, + .effect (.call .staticcall) 6, + .op (.stack .iszero), + .jumpi 3, + .op (.stack .returndatasize), + .op (.stack (.push 32)), + .op (.stack .gt), + .jumpi 1, + .op (.stack (.push 0)), + .op .load, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack .returndatasize), + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .effect .returndatacopy 3, + .op (.stack .returndatasize), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Evm5.lean b/Certified/reader/gen/Reader/Evm5.lean new file mode 100644 index 00000000..8b20556d --- /dev/null +++ b/Certified/reader/gen/Reader/Evm5.lean @@ -0,0 +1,88 @@ +-- solar-lean-stage: kind=evm index=5 pass=block-cse +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime EVM IR after `block-cse`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xa087a87e)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0xa035b1fe)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .op (.stack (.push 4)), + .op (.stack (.push 28)), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .effect .gas 0, + .effect (.call .staticcall) 6, + .op (.stack .iszero), + .jumpi 3, + .op (.stack .returndatasize), + .op (.stack (.push 32)), + .op (.stack .gt), + .jumpi 1, + .op (.stack (.push 0)), + .op .load, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack .returndatasize), + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .effect .returndatacopy 3, + .op (.stack .returndatasize), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Evm6.lean b/Certified/reader/gen/Reader/Evm6.lean new file mode 100644 index 00000000..e63faf9b --- /dev/null +++ b/Certified/reader/gen/Reader/Evm6.lean @@ -0,0 +1,88 @@ +-- solar-lean-stage: kind=evm index=6 pass=share-reverts +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime EVM IR after `share-reverts`. -/ +def evm6 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xa087a87e)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0xa035b1fe)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .op (.stack (.push 4)), + .op (.stack (.push 28)), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .effect .gas 0, + .effect (.call .staticcall) 6, + .op (.stack .iszero), + .jumpi 3, + .op (.stack .returndatasize), + .op (.stack (.push 32)), + .op (.stack .gt), + .jumpi 1, + .op (.stack (.push 0)), + .op .load, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 4, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack .returndatasize), + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .effect .returndatacopy 3, + .op (.stack .returndatasize), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Evm7.lean b/Certified/reader/gen/Reader/Evm7.lean new file mode 100644 index 00000000..98970e1a --- /dev/null +++ b/Certified/reader/gen/Reader/Evm7.lean @@ -0,0 +1,86 @@ +-- solar-lean-stage: kind=evm index=7 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm7 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xa087a87e)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 0xa035b1fe)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .op (.stack (.push 4)), + .op (.stack (.push 28)), + .op (.stack (.dup 1)), + .effect .calldataload 1, + .effect .gas 0, + .effect (.call .staticcall) 6, + .op (.stack .iszero), + .jumpi 2, + .op (.stack .returndatasize), + .op (.stack (.push 32)), + .op (.stack .gt), + .jumpi 1, + .op (.stack (.push 0)), + .op .load, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 3, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb9 + [.op (.stack .returndatasize), + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .effect .returndatacopy 3, + .op (.stack .returndatasize), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Manifest.lean b/Certified/reader/gen/Reader/Manifest.lean new file mode 100644 index 00000000..7ee331ad --- /dev/null +++ b/Certified/reader/gen/Reader/Manifest.lean @@ -0,0 +1,47 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Reader.Manifest + +def sources : List (String × String) := + [("Certified/reader/reader.sol", "bff96eb4b5b33ebc37c3dd379d4d55388525e9787dd991afa41cc0b809b89a7e")] + +def compiler : String := "0.8.38+commit.cb5053ab.solar.0.3.0-dev" + +def arguments : List String := + ["Certified/reader/reader.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/reader/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "c18d3ee3fbe18467c367f0b868bfa6f93511e86bbecab095a1e288d8497f85a2"), + ("Mir1", "mir1", "place-reads", "84085542c96e416459e21e878019f8af37c807d8a7cefd56afaa4238a26029d8"), + ("Mir2", "mir2", "spell-width-tests", "805f70ac294e93760f04edc04a2eaf36b89430d26dc2d4959309a53b0597d114"), + ("Mir3", "mir3", "evm-inst-schedule", "11a9ae1838d817aa69640ad29b7050cbc70b05b56c1ecf54329f5c816a2d4581"), + ("Sched", "sched", "stack-schedule", "f618618c81f32246f89af8bf5a44f7d5407b420836ba4a2527bd07677cb4b153"), + ("Evm1", "evm1", "cfg-simplify-early", "f351e61c85551e0385e65007fff190c72592edd3dad4981277769a3760514ebf"), + ("Evm2", "evm2", "block-layout", "e52785df1aca97d96814a14e02da72c28095e1f81b8e6bd9ca046109cdb22ccd"), + ("Evm3", "evm3", "terminal-dedup", "ceee2fd40bcbe7eb8e855e299c41f8bc03fab804b0fdeb0d7f6f8877ab2f0c23"), + ("Evm4", "evm4", "cfg-simplify-early", "3b74cb48e673f40e6c712cb3139a2c45b5f1acd06512ae9f4dac74d32f65f1c9"), + ("Evm5", "evm5", "block-cse", "fc489b656954d811b262210a2fc8fc512ed285a96cc07841b8ddae9a9139160a"), + ("Evm6", "evm6", "share-reverts", "ba632cf5e20581d34c5ec93d168d8d802d08c52f081a0f19be6323423d8d095b"), + ("Evm7", "evm7", "cfg-simplify-early", "a0bdf8538b97a7dfb6e452bfad93e70f2238db07643497d48ab2aad1bd7b36e7"), + ("Bytecode", "bytecode", "assemble", "ce5b93ef146d00753003f24db5c08fa70ca8cf43dfe6b38f62dfc0f23271af13")] + +def bytecodeHex : String := + "346053575f3560e01c8063a087a87e03605357608060405260043560a01c602436101760535763a035b1fe5f5260205f6004601c81355afa156057573d6020116053575f516001018015605f575f5260205ff35b5f5ffd5b3d5f5f3e3d5ffd5b6011602052634e487b715f526024601cfd" + +def bytecodeSha256 : String := "7e4fced8401133d842f58d3d310e8b78a32039960170ea5d8ad75a53a7b36626" + +end SolarTV.Export.Reader.Manifest diff --git a/Certified/reader/gen/Reader/Mir1.lean b/Certified/reader/gen/Reader/Mir1.lean new file mode 100644 index 00000000..cbc35f7e --- /dev/null +++ b/Certified/reader/gen/Reader/Mir1.lean @@ -0,0 +1,83 @@ +-- solar-lean-stage: kind=mir index=1 pass=place-reads +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The lowered MIR module after `place-reads`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @read + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 33) .calldatasize [], + .pure 35 .lt [.value 33, .const 36], + .effect (some 37) .calldataload [.const 4], + .pure 39 .gt [.value 37, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 47 .or [.value 35, .value 39]], + .branch (.value 47) 3 7⟩, + -- bb1 + ⟨[], + [.effect (some 30) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 30], + .effect (some 31) .returndatasize []], + .revert (.const 0) (.value 31)⟩, + -- bb2 + ⟨[], + [.effect (some 13) .returndatasize [], + .pure 14 .lt [.value 13, .const 32]], + .branch (.value 14) 3 4⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 15) .mload [.const 0], + .pure 19 .add [.value 15, .const 1], + .pure 20 .eq [.value 19, .const 0]], + .branch (.value 20) 5 6⟩, + -- bb5 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb6 + ⟨[], + [.effect none .mstore [.const 0, .value 19]], + .ret (.const 0) (.const 32)⟩, + -- bb7 + ⟨[], + [.effect (some 48) .calldataload [.const 4], + .effect (some 3) .gas [], + .effect none .mstore [.const 0, .const 0xa035b1fe], + .effect (some 11) (.call .staticcall) [.value 3, .value 48, .const 28, .const 4, .const 0, .const 32]], + .branch (.value 11) 2 1⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0xa087a87e, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Mir2.lean b/Certified/reader/gen/Reader/Mir2.lean new file mode 100644 index 00000000..6ce5ea16 --- /dev/null +++ b/Certified/reader/gen/Reader/Mir2.lean @@ -0,0 +1,85 @@ +-- solar-lean-stage: kind=mir index=2 pass=spell-width-tests +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The lowered MIR module after `spell-width-tests`. -/ +def mir2 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @read + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 33) .calldatasize [], + .pure 35 .lt [.value 33, .const 36], + .effect (some 37) .calldataload [.const 4], + .pure 50 .shr [.const 160, .value 37], + .word 53 (.value 35), + .pure 54 .or [.value 50, .value 53], + .ne 47 (.value 54) (.const 0)], + .branch (.value 47) 3 7⟩, + -- bb1 + ⟨[], + [.effect (some 30) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 30], + .effect (some 31) .returndatasize []], + .revert (.const 0) (.value 31)⟩, + -- bb2 + ⟨[], + [.effect (some 13) .returndatasize [], + .pure 14 .lt [.value 13, .const 32]], + .branch (.value 14) 3 4⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 15) .mload [.const 0], + .pure 19 .add [.value 15, .const 1], + .pure 20 .eq [.value 19, .const 0]], + .branch (.value 20) 5 6⟩, + -- bb5 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb6 + ⟨[], + [.effect none .mstore [.const 0, .value 19]], + .ret (.const 0) (.const 32)⟩, + -- bb7 + ⟨[], + [.effect (some 48) .calldataload [.const 4], + .effect (some 3) .gas [], + .effect none .mstore [.const 0, .const 0xa035b1fe], + .effect (some 11) (.call .staticcall) [.value 3, .value 48, .const 28, .const 4, .const 0, .const 32]], + .branch (.value 11) 2 1⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0xa087a87e, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Mir3.lean b/Certified/reader/gen/Reader/Mir3.lean new file mode 100644 index 00000000..95c1a657 --- /dev/null +++ b/Certified/reader/gen/Reader/Mir3.lean @@ -0,0 +1,85 @@ +-- solar-lean-stage: kind=mir index=3 pass=evm-inst-schedule +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The lowered MIR module after `evm-inst-schedule`. -/ +def mir3 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @read + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 37) .calldataload [.const 4], + .pure 50 .shr [.const 160, .value 37], + .effect (some 33) .calldatasize [], + .pure 35 .lt [.value 33, .const 36], + .word 53 (.value 35), + .pure 54 .or [.value 50, .value 53], + .ne 47 (.value 54) (.const 0)], + .branch (.value 47) 3 7⟩, + -- bb1 + ⟨[], + [.effect (some 30) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 30], + .effect (some 31) .returndatasize []], + .revert (.const 0) (.value 31)⟩, + -- bb2 + ⟨[], + [.effect (some 13) .returndatasize [], + .pure 14 .lt [.value 13, .const 32]], + .branch (.value 14) 3 4⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 15) .mload [.const 0], + .pure 19 .add [.value 15, .const 1], + .pure 20 .eq [.value 19, .const 0]], + .branch (.value 20) 5 6⟩, + -- bb5 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb6 + ⟨[], + [.effect none .mstore [.const 0, .value 19]], + .ret (.const 0) (.const 32)⟩, + -- bb7 + ⟨[], + [.effect (some 48) .calldataload [.const 4], + .effect (some 3) .gas [], + .effect none .mstore [.const 0, .const 0xa035b1fe], + .effect (some 11) (.call .staticcall) [.value 3, .value 48, .const 28, .const 4, .const 0, .const 32]], + .branch (.value 11) 2 1⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0xa087a87e, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Sched.lean b/Certified/reader/gen/Reader/Sched.lean new file mode 100644 index 00000000..7903d1cd --- /dev/null +++ b/Certified/reader/gen/Reader/Sched.lean @@ -0,0 +1,104 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 3, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0xa087a87e)), + .op (.stack .eq), + .jumpi 2, + .jump 3], + -- bb2 + [.jump 4], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 128)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 11, + .jump 5], + -- bb5 + [.op (.stack (.push 0xa035b1fe)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .op (.stack (.push 4)), + .op (.stack (.push 28)), + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .gas 0, + .effect (.call .staticcall) 6, + .op (.stack .iszero), + .jumpi 9, + .jump 6], + -- bb6 + [.op (.stack .returndatasize), + .op (.stack (.push 32)), + .op (.stack .gt), + .jumpi 11, + .jump 7], + -- bb7 + [.op (.stack (.push 0)), + .op .load, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 10, + .jump 8], + -- bb8 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack .returndatasize), + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .effect .returndatacopy 3, + .op (.stack .returndatasize), + .op (.stack (.push 0)), + .revert], + -- bb10 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb11 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/Schedule.json b/Certified/reader/gen/Reader/Schedule.json new file mode 100644 index 00000000..8248e221 --- /dev/null +++ b/Certified/reader/gen/Reader/Schedule.json @@ -0,0 +1,22 @@ +{ + "functions": [ + {"function": 1, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [3, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 0, "entry": 4, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [4, 3], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [9, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [6, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [11, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [7, 0], "layout": [], "floating": true, "continues": null}, + {"block": 5, "start": [10, 0], "layout": [], "floating": true, "continues": null}, + {"block": 6, "start": [8, 0], "layout": ["v19"], "floating": true, "continues": null}, + {"block": 7, "start": [5, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]} + ] +} diff --git a/Certified/reader/gen/Reader/Stage0.lean b/Certified/reader/gen/Reader/Stage0.lean new file mode 100644 index 00000000..150af153 --- /dev/null +++ b/Certified/reader/gen/Reader/Stage0.lean @@ -0,0 +1,82 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Reader`; do not edit. -/ + +namespace SolarTV.Export.Reader + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @read + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 33) .calldatasize [], + .pure 35 .lt [.value 33, .const 36], + .effect (some 37) .calldataload [.const 4], + .pure 39 .gt [.value 37, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 47 .or [.value 35, .value 39]], + .branch (.value 47) 3 7⟩, + -- bb1 + ⟨[], + [.effect (some 30) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 30], + .effect (some 31) .returndatasize []], + .revert (.const 0) (.value 31)⟩, + -- bb2 + ⟨[], + [.effect (some 13) .returndatasize [], + .pure 14 .lt [.value 13, .const 32]], + .branch (.value 14) 3 4⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 15) .mload [.const 0], + .pure 19 .add [.value 15, .const 1], + .pure 20 .eq [.value 19, .const 0]], + .branch (.value 20) 5 6⟩, + -- bb5 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb6 + ⟨[], + [.effect none .mstore [.const 0, .value 19]], + .ret (.const 0) (.const 32)⟩, + -- bb7 + ⟨[], + [.effect (some 3) .gas [], + .effect none .mstore [.const 0, .const 0xa035b1fe], + .effect (some 11) (.call .staticcall) [.value 3, .value 37, .const 28, .const 4, .const 0, .const 32]], + .branch (.value 11) 2 1⟩], + entryHeap := some 128 }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0xa087a87e, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Reader diff --git a/Certified/reader/gen/Reader/manifest.json b/Certified/reader/gen/Reader/manifest.json new file mode 100644 index 00000000..703ad4c1 --- /dev/null +++ b/Certified/reader/gen/Reader/manifest.json @@ -0,0 +1,129 @@ +{ + "arguments": [ + "Certified/reader/reader.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/reader/gen" + ], + "bytecode": "346053575f3560e01c8063a087a87e03605357608060405260043560a01c602436101760535763a035b1fe5f5260205f6004601c81355afa156057573d6020116053575f516001018015605f575f5260205ff35b5f5ffd5b3d5f5f3e3d5ffd5b6011602052634e487b715f526024601cfd", + "bytecode_sha256": "7e4fced8401133d842f58d3d310e8b78a32039960170ea5d8ad75a53a7b36626", + "compiler": "0.8.38+commit.cb5053ab.solar.0.3.0-dev", + "contract": "Reader", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"Certified/reader/reader.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/reader/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/reader/gen\"), keep_asts: false, forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "Certified/reader/reader.sol", + "sha256": "bff96eb4b5b33ebc37c3dd379d4d55388525e9787dd991afa41cc0b809b89a7e" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "c18d3ee3fbe18467c367f0b868bfa6f93511e86bbecab095a1e288d8497f85a2" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "place-reads", + "sha256": "84085542c96e416459e21e878019f8af37c807d8a7cefd56afaa4238a26029d8" + }, + { + "definition": "mir2", + "file": "Mir2.lean", + "index": 2, + "kind": "mir", + "pass": "spell-width-tests", + "sha256": "805f70ac294e93760f04edc04a2eaf36b89430d26dc2d4959309a53b0597d114" + }, + { + "definition": "mir3", + "file": "Mir3.lean", + "index": 3, + "kind": "mir", + "pass": "evm-inst-schedule", + "sha256": "11a9ae1838d817aa69640ad29b7050cbc70b05b56c1ecf54329f5c816a2d4581" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "f618618c81f32246f89af8bf5a44f7d5407b420836ba4a2527bd07677cb4b153" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "f351e61c85551e0385e65007fff190c72592edd3dad4981277769a3760514ebf" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "block-layout", + "sha256": "e52785df1aca97d96814a14e02da72c28095e1f81b8e6bd9ca046109cdb22ccd" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "ceee2fd40bcbe7eb8e855e299c41f8bc03fab804b0fdeb0d7f6f8877ab2f0c23" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "3b74cb48e673f40e6c712cb3139a2c45b5f1acd06512ae9f4dac74d32f65f1c9" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "block-cse", + "sha256": "fc489b656954d811b262210a2fc8fc512ed285a96cc07841b8ddae9a9139160a" + }, + { + "definition": "evm6", + "file": "Evm6.lean", + "index": 6, + "kind": "evm", + "pass": "share-reverts", + "sha256": "ba632cf5e20581d34c5ec93d168d8d802d08c52f081a0f19be6323423d8d095b" + }, + { + "definition": "evm7", + "file": "Evm7.lean", + "index": 7, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "a0bdf8538b97a7dfb6e452bfad93e70f2238db07643497d48ab2aad1bd7b36e7" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "ce5b93ef146d00753003f24db5c08fa70ca8cf43dfe6b38f62dfc0f23271af13" + } + ] +} diff --git a/Certified/reader/options b/Certified/reader/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/reader/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/reader/reader.sol b/Certified/reader/reader.sol new file mode 100644 index 00000000..a5e80afe --- /dev/null +++ b/Certified/reader/reader.sol @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +interface IOracle { + function price() external view returns (uint256); +} + +contract Reader { + function read(IOracle o) external view returns (uint256) { + return o.price() + 1; + } +} + diff --git a/Certified/reader/record.json b/Certified/reader/record.json new file mode 100644 index 00000000..f77e020d --- /dev/null +++ b/Certified/reader/record.json @@ -0,0 +1,36 @@ +{ + "contract": "Reader", + "name": "reader", + "source": "Certified/reader/reader.sol", + "bytecode": "346053575f3560e01c8063a087a87e03605357608060405260043560a01c602436101760535763a035b1fe5f5260205f6004601c81355afa156057573d6020116053575f516001018015605f575f5260205ff35b5f5ffd5b3d5f5f3e3d5ffd5b6011602052634e487b715f526024601cfd", + "solar": "cb5053ab39adfd59820913b336d346389ce1b8d9", + "solidity_lean": "696df0a81602fc416fabec7b892073e15e8920de", + "mir_to_evmir": "proved: SolarTV.Milestone.Reader.reader_mir_to_evmir", + "assembly": "decoded only: reader.Proofs.Assembly (the bytecode decodes to the final EVM IR's instructions; no execution theorem)", + "vc": "exported to .lake/certify/reader/VC.lean", + "end_to_end": "not proved", + "end_to_end_statement": {}, + "hypotheses": {}, + "refused": [ + { + "function": "Reader.read", + "reason": "declare-fun outside the Lean fragment: (declare-fun |sv_world (Array Int Int) Int| ((Array Int Int) Int) Int)", + "status": "refused (unproved)" + } + ], + "vacuous": "not checked", + "assembly_statement": null, + "assembly_hypotheses": null, + "negative_tests": false, + "caveats": [ + "solidity-lean at 696df0a81602fc416fabec7b892073e15e8920de, not the pinned 813949dc3556d3c3f1c129e8254a4eead78bac87", + "solar cb5053ab39adfd59820913b336d346389ce1b8d9, not built from this checkout's compiler sources", + "assembly decoded, not executed", + "1 spec function(s) refused, unproved", + "not end to end: solidity-lean states no source or spec theorem for reader", + "negative tests skipped" + ], + "backend": { + "theorem": "SolarTV.Milestone.Reader.reader_mir_to_evmir" + } +} diff --git a/Certified/uv2_erc20/.gitignore b/Certified/uv2_erc20/.gitignore new file mode 100644 index 00000000..4a021da5 --- /dev/null +++ b/Certified/uv2_erc20/.gitignore @@ -0,0 +1,2 @@ +# Exported by scripts/verify/uniswap_v2_erc20_stages.sh from the GPL-3.0 v2-core port; not committed. +gen/ diff --git a/Certified/uv2_erc20/AnyCaller.lean b/Certified/uv2_erc20/AnyCaller.lean new file mode 100644 index 00000000..ace92d4e --- /dev/null +++ b/Certified/uv2_erc20/AnyCaller.lean @@ -0,0 +1,90 @@ +import uv2_erc20.Gas +import uv2_erc20.ProofsT.Stages + +-- Untrusted proof script: the kernel checks it. + +/-! +# UniswapV2ERC20.transfer's backend stages from any caller (E4, E4∘E5) + +The backend stages (`uv2_erc20_transfer_mir_to_evmir`, E4) hold under every oracle, and the machine +reads CALLER from the oracle (`Oracle.caller`), so E4 is a statement about every caller: its proofs +execute `CALLER` as an unknown 160-bit word, never as `0x2000`. This module states that for the +calls of `transfer` and composes it with the gas edge (E5, `CtxGas.gas_edge`, also from any +caller) down to EthLib's run of the exact bytes: + +* `stages_from`: E4 under the oracle of a call from any account `a` (`oracleFrom a`). +* `backend_any_caller`: from every caller `a` (below `2 ^ 160`, not the contract), under every + oracle whose CALLER is `a` and whose Keccak-256 is EthLib's, every result the first lowered MIR + `stage0` gives on a call of `transfer` is EthLib's result on the exact runtime bytes, at every + gas from `G` = 8199112 on. +* `resources_any_caller`: `Shapes.ResourcesFrom` for any source semantics per caller, from a source + stage per caller into `stage0` (E3 with a symbolic caller, the hypothesis `source`) and its + totality: what E3 must give for the whole chain to hold from any caller. +* `any_caller_inhabited`: the premises hold of a caller other than `0x2000` (`0x3000`). + +The negative control that a stage hardcoding the caller is refused is by execution, outside +Lean's build (the slice-stages RESULT: `CALLER` replaced by `PUSH 0x2000` in `evm11`). +-/ + +namespace SolarTV.Export.UniswapV2ERC20.AnyCaller + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Shapes SolidCore.Refinement.Solar +open SolarTV.Milestone.Uv2Erc20T (scope uv2_erc20_transfer_mir_to_evmir) +open SolarTV.Export.UniswapV2ERC20.CtxGas (G code prog TransferCall gas_edge resources) + +/-- A call of `transfer` is in the stages' scope: its selector is none of the excluded ones. -/ +theorem transfer_scope {call : Call} (h : TransferCall call) : scope call := by + unfold TransferCall at h + simp only [scope, h] + decide + +/-- **E4 from any caller**: the backend stages under the oracle of a call from `a`. -/ +theorem stages_from (a : Nat) : + Stage (mirSem (oracleFrom a)) (evmirSem (oracleFrom a)) stage0 evm11 scope := + uv2_erc20_transfer_mir_to_evmir (oracleFrom a) + +/-- **E4∘E5 from any caller**: the first lowered MIR's result on a call of `transfer` is EthLib's +result on the exact runtime bytes, from every caller, at every gas from `G` on. -/ +theorem backend_any_caller : ∀ a, a < 2 ^ 160 → a ≠ selfAddress → ∀ o, AssembleLoop.OracleOkAt a o → + ∀ call, TransferCall call → ∀ obs, (mirSem o).run stage0 call = some obs → + ∀ gas, G ≤ gas → Final.Target.runWithFrom a gas code call = some obs := by + intro a ha hne o ho call hc obs hrun gas hg + have h4 := uv2_erc20_transfer_mir_to_evmir o call (transfer_scope hc) obs hrun + obtain ⟨obs', hq, hb⟩ := gas_edge a ha hne o ho call hc gas hg + rw [show (evmirSem o).run prog call = (evmirSem o).run evm11 call from rfl, h4] at hq + cases hq + exact hb + +/-- **Resources from any caller, from a source stage per caller into `stage0`** (E3 with a symbolic +caller as the hypothesis `source`, with its totality `total`). -/ +theorem resources_any_caller {Valid : Call → Prop} {run : Nat → Call → Option Observable} + (hv : ∀ call, Valid call → TransferCall call) + (total : ∀ a, a < 2 ^ 160 → a ≠ selfAddress → ∀ call, Valid call → ∃ obs, run a call = some obs) + (source : ∀ a, a < 2 ^ 160 → a ≠ selfAddress → ∀ call, Valid call → ∀ obs, run a call = some obs → + (mirSem (oracleFrom a)).run stage0 call = some obs) : + ResourcesFrom run code Valid (fun _ => G) := + resources hv total fun a _ _ call hc obs h => + stages_from a call (transfer_scope (hv call hc)) obs (source a ‹_› ‹_› call hc obs h) + +/-- The premises of `backend_any_caller` hold of a caller other than `0x2000`. -/ +theorem any_caller_inhabited : + ∃ a o, a ≠ callerAddress ∧ a < 2 ^ 160 ∧ a ≠ selfAddress ∧ AssembleLoop.OracleOkAt a o := + ⟨0x3000, oracleFrom 0x3000, by decide, by decide, by decide, oracleFrom_ok (by decide)⟩ + +/-- info: 'SolarTV.Export.UniswapV2ERC20.AnyCaller.stages_from' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stages_from + +/-- info: 'SolarTV.Export.UniswapV2ERC20.AnyCaller.backend_any_caller' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms backend_any_caller + +/-- info: 'SolarTV.Export.UniswapV2ERC20.AnyCaller.resources_any_caller' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms resources_any_caller + +/-- info: 'SolarTV.Export.UniswapV2ERC20.AnyCaller.any_caller_inhabited' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms any_caller_inhabited + +end SolarTV.Export.UniswapV2ERC20.AnyCaller diff --git a/Certified/uv2_erc20/Gas.lean b/Certified/uv2_erc20/Gas.lean new file mode 100644 index 00000000..5b30ecf5 --- /dev/null +++ b/Certified/uv2_erc20/Gas.lean @@ -0,0 +1,110 @@ +import Verify.ShapeCtxGasFrom +import uv2_erc20.GasGuard + +-- Untrusted proof script: the kernel checks it. The certificate and the guarded program are +-- generated data (CtxGas.lean); the theorems below state what they give. + +/-! +# UniswapV2ERC20.transfer: a proved gas bound on the exact runtime bytes (E8) + +`G` = `gasBoundL cx.base N` = 22100 · (7 · 53) + 12 = 8199112: seven blocks (the most a call of +`transfer` runs, `GasGuard.N`), each of at most 53 items of the lowered program (the dispatcher's, +the largest block such a call runs), each charged 22100 gas, plus the memory up to 128 bytes. +22100 is at least the price of every instruction the checker admits under EIP-2929 and EIP-2200, +whatever the call finds warm or cold: an SSTORE that sets a zero slot it reads cold (20000 + 2100), +a cold SLOAD (2100), a KECCAK256 of 64 bytes, a LOG3 of 32 bytes. EthLib's interpreter meters the +accesses the run actually makes (its access sets start with the caller, the contract and the +precompiles warm, per EIP-2929), so the theorem holds of the real warm and cold slots, not of a +model of them. + +* `gas_edge`: from every caller `a` (below `2 ^ 160`, not the contract itself), on every call of + `transfer`'s selector, under every oracle whose CALLER is `a` and whose Keccak-256 is EthLib's, + at every gas from `G` on, EthLib runs the exact bytes to exactly the final EVM IR's result + (success, return data, revert data, logs, storage). Its only inputs are the kernel's checks of + generated programs: `check_ok` (the checker with contexts and gas on the exact bytes against + `evm11`) and the guard stage (`guard_ends`, `guard_run`). No premise mentions gas. +* `resources`: `Shapes.ResourcesFrom` for any valid-call predicate inside `transfer`'s selector and + any source semantics per caller, from the functional stage from that source to `evm11` (E3∘E4: + the hypothesis `stage`) and its totality (`total`). At `callerAddress` it is `Shapes.Resources` + (`resources_at`). +* Negative controls: the checker refuses the bytes with the dispatcher's first jump target moved + and with transfer's debit SSTORE dropped. +-/ + +namespace SolarTV.Export.UniswapV2ERC20.CtxGas + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Shapes SolidCore.Refinement.Solar + +/-- **The proved gas bound** of a call of `transfer`. -/ +def G : Nat := AssembleLoop.gasBoundL cx.base N + +theorem G_eq : G = 8199112 := by decide +kernel + +theorem G_lt : G < 2 ^ 64 := by rw [G_eq]; decide + +theorem reads_false : cx.base.reads = false := rfl + +/-- **The gas edge of UniswapV2ERC20.transfer on its exact runtime bytes, from any caller.** -/ +theorem gas_edge : ∀ a, a < 2 ^ 160 → a ≠ selfAddress → ∀ o, AssembleLoop.OracleOkAt a o → + ∀ call, TransferCall call → ∀ gas, G ≤ gas → + ∃ obs, (evmirSem o).run prog call = some obs ∧ + Final.Target.runWithFrom a gas code call = some obs := by + intro a ha hne o ho call hc gas hg + obtain ⟨obs, hq, hb⟩ := gasEdge_ofXL check_ok reads_false (fun o call h => guard_ends o call h) + (fun o call h => guard_run o call h) a ha hne o ho call hc gas hg + exact ⟨obs, (AssembleCtx.sem_norm o prog call).symm.trans hq, hb⟩ + +/-- **Resources of UniswapV2ERC20.transfer from any caller**, from the functional stage. -/ +theorem resources {Valid : Call → Prop} {run : Nat → Call → Option Observable} + (hv : ∀ call, Valid call → TransferCall call) + (total : ∀ a, a < 2 ^ 160 → a ≠ selfAddress → ∀ call, Valid call → ∃ obs, run a call = some obs) + (stage : ∀ a, a < 2 ^ 160 → a ≠ selfAddress → ∀ call, Valid call → ∀ obs, run a call = some obs → + (evmirSem (oracleFrom a)).run prog call = some obs) : + ResourcesFrom run code Valid (fun _ => G) := + resourcesFrom_ofXL total + (fun a ha hne call hc obs h => (AssembleCtx.sem_norm _ prog call).trans (stage a ha hne call hc obs h)) + check_ok reads_false + (fun o call h => guard_ends o call (hv call h)) (fun o call h => guard_run o call (hv call h)) G_lt + +/-- At `callerAddress`: `Shapes.Resources` of a source semantics. -/ +theorem resources_at {S : Sem} {p : S.Prog} {Valid : Call → Prop} + {run : Nat → Call → Option Observable} (hrun : run callerAddress = S.run p) + (hv : ∀ call, Valid call → TransferCall call) + (total : ∀ a, a < 2 ^ 160 → a ≠ selfAddress → ∀ call, Valid call → ∃ obs, run a call = some obs) + (stage : ∀ a, a < 2 ^ 160 → a ≠ selfAddress → ∀ call, Valid call → ∀ obs, run a call = some obs → + (evmirSem (oracleFrom a)).run prog call = some obs) : + Resources S p code Valid (fun _ => G) := + (resources hv total stage).resources hrun + +/-- The bytes with byte `i` replaced by `b`. -/ +def mutant (i b : Nat) : ByteArray := ⟨((bytes.set i b).map UInt8.ofNat).toArray⟩ + +/-- A checker run whose walk of the bytes against the program fails refuses the bytes. -/ +theorem refuses_of_walk {code' : ByteArray} + (h : Assemble.walkS cx.base.offset (Assemble.bytesOf code') 0 + (Assemble.lower (AssembleCtx.norm prog) cx.base) = false) : + AssembleCtxGas.checkXL F (AssembleCtx.norm prog) code' cx = false := by + have hw := Assemble.walkS_drop (Assemble.bytesOf code') cx.base.offset + (Assemble.lower (AssembleCtx.norm prog) cx.base) 0 (Nat.zero_le _) + rw [List.drop_zero, h] at hw + simp only [AssembleCtxGas.checkXL, ← hw, Bool.false_and] + +set_option maxRecDepth 100000 in +/-- The checker refuses the bytes with the dispatcher's first jump target moved (byte 7). -/ +theorem rejects_jump : AssembleCtxGas.checkXL F (AssembleCtx.norm prog) (mutant 7 0x64) cx = false := + refuses_of_walk (by decide +kernel) + +set_option maxRecDepth 100000 in +/-- The checker refuses the bytes with transfer's debit SSTORE dropped, as POP (byte 0x427). -/ +theorem rejects_sstore : AssembleCtxGas.checkXL F (AssembleCtx.norm prog) (mutant 0x427 0x50) cx = false := + refuses_of_walk (by decide +kernel) + +/-- info: 'SolarTV.Export.UniswapV2ERC20.CtxGas.gas_edge' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms gas_edge + +/-- info: 'SolarTV.Export.UniswapV2ERC20.CtxGas.resources' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms resources + +end SolarTV.Export.UniswapV2ERC20.CtxGas diff --git a/Certified/uv2_erc20/GasGuard.lean b/Certified/uv2_erc20/GasGuard.lean new file mode 100644 index 00000000..00d3ee02 --- /dev/null +++ b/Certified/uv2_erc20/GasGuard.lean @@ -0,0 +1,68 @@ +import W1Proofs.Tactic +import W1Proofs.Axioms +import uv2_erc20.CtxGas + +-- Untrusted proof script: the kernel checks it. The statement speaks only of the generated +-- program and its guarded copy. + +/-! +# UniswapV2ERC20.transfer: the guard stage + +On every call whose selector is `transfer(address,uint256)`'s, under every oracle, the final EVM +IR `evm11` and `CtxGas.guarded` (each block of `CtxGas.F`, the blocks of the other functions, a +jump to itself) end within `N` blocks in the same result: no such call enters a block the checker +with contexts and gas leaves unchecked. Symbolic execution (`sym_exec`) over a symbolic call and +oracle: the calldata, the storage and the oracle stay opaque. +-/ + +namespace SolarTV.Export.UniswapV2ERC20.CtxGas + +open SolarTV SolarTV.Machine SolarTV.Milestone.W1 + +/-- The blocks a call of transfer runs, at most: dispatch, entry, the balance read, the checked +subtraction, the credit, and the return or the revert. -/ +def N : Nat := 7 + +/-- A call of transfer: its first calldata word's top four bytes are the selector `0xa9059cbb`. -/ +def TransferCall (call : Call) : Prop := + EvmRules.Evm.shr 224 (calldataWord call 0) = 0xa9059cbb + +set_option maxHeartbeats 8000000 in +theorem guarded_run7 (o : Oracle) (call : Call) + (hsel : EvmRules.Evm.shr 224 (calldataWord call 0) = 0xa9059cbb) : + EVM.Program.run o SolarTV.Export.UniswapV2ERC20.evm11 call 7 = EVM.Program.run o guarded call 7 := by + sym_exec + +set_option maxHeartbeats 8000000 in +theorem guarded_ends7 (o : Oracle) (call : Call) + (hsel : EvmRules.Evm.shr 224 (calldataWord call 0) = 0xa9059cbb) : + (EVM.Program.run o guarded call 7).isSome = true := by + sym_exec + +/-- The run of the final EVM IR (with RETURNDATASIZE in effect form, the same runs) is the guarded +program's on a call of transfer. -/ +theorem guard_run (o : Oracle) (call : Call) (h : TransferCall call) : + EVM.Program.run o (SolidCore.Refinement.Solar.AssembleCtx.norm prog) call N = + EVM.Program.run o + (SolidCore.Refinement.Solar.AssembleCtxGas.guard F (SolidCore.Refinement.Solar.AssembleCtx.norm prog)) + call N := by + rw [guarded_eq, SolidCore.Refinement.Solar.AssembleCtx.run_norm] + exact guarded_run7 o call h + +/-- The guarded program ends within `N` blocks on a call of transfer. -/ +theorem guard_ends (o : Oracle) (call : Call) (h : TransferCall call) : + (EVM.Program.run o + (SolidCore.Refinement.Solar.AssembleCtxGas.guard F (SolidCore.Refinement.Solar.AssembleCtx.norm prog)) + call N).isSome = true := by + rw [guarded_eq] + exact guarded_ends7 o call h + +/-- info: 'SolarTV.Export.UniswapV2ERC20.CtxGas.guard_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within guard_ends + +/-- info: 'SolarTV.Export.UniswapV2ERC20.CtxGas.guard_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within guard_run + +end SolarTV.Export.UniswapV2ERC20.CtxGas diff --git a/Certified/uv2_erc20/options b/Certified/uv2_erc20/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/uv2_erc20/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/verify_counter/Final.lean b/Certified/verify_counter/Final.lean new file mode 100644 index 00000000..1443178c --- /dev/null +++ b/Certified/verify_counter/Final.lean @@ -0,0 +1,11 @@ +import verify_counter.Statement +import Contracts.VerifyCounter.ShapeExport + +-- Generated by solar's tools/certify/final.py; do not edit. The statement is +-- Certified.verify_counter.Final.Statement of verify_counter.Statement, which does not import the proof +-- module; the driver's checker requires `final`'s type to be exactly that constant. + +theorem Certified.verify_counter.Final.final : _root_.Certified.verify_counter.Final.Statement := + ⟨_root_.Certified.verify_counter.Final.bound, Contracts.VerifyCounter.ShapeExport.nonvacuous, Contracts.VerifyCounter.ShapeExport.published⟩ + +#print axioms Certified.verify_counter.Final.final diff --git a/Certified/verify_counter/Proofs.lean b/Certified/verify_counter/Proofs.lean new file mode 100644 index 00000000..24680d01 --- /dev/null +++ b/Certified/verify_counter/Proofs.lean @@ -0,0 +1,4 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import verify_counter.Proofs.Stages +import verify_counter.Proofs.Assembly +import verify_counter.Proofs.Execution diff --git a/Certified/verify_counter/Proofs/Assembly.lean b/Certified/verify_counter/Proofs/Assembly.lean new file mode 100644 index 00000000..5c201f86 --- /dev/null +++ b/Certified/verify_counter/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Items +import verify_counter.gen.Counter.Evm11 +import verify_counter.gen.Counter.Bytecode + +/-! The final EVM IR of `Counter` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.VerifyCounter + +open SolarTV.Assembly SolarTV.Export.Counter SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm11).getD [] + +theorem items_eq : itemsOf evm11 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x3c else if label = 2 then 0x40 else if label = 3 then 0x52 else if label = 4 then 0x5b else if label = 5 then 0x65 else if label = 6 then 0x73 else if label = 7 then 0xaa else if label = 8 then 0xdb else if label = 9 then 0x10f else if label = 10 then 0x111 else if label = 11 then 0x127 else if label = 12 then 0x136 else if label = 13 then 0x13e else if label = 14 then 0x152 else if label = 15 then 0x167 else if label = 16 then 0x182 else if label = 17 then 0x19a else if label = 18 then 0x1af else if label = 19 then 0x1cb else if label = 20 then 0x1d2 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.VerifyCounter.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.VerifyCounter.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms decodes + +end SolarTV.Milestone.VerifyCounter diff --git a/Certified/verify_counter/Proofs/Execution.lean b/Certified/verify_counter/Proofs/Execution.lean new file mode 100644 index 00000000..5ab2e838 --- /dev/null +++ b/Certified/verify_counter/Proofs/Execution.lean @@ -0,0 +1,118 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import verify_counter.Proofs.Stages +import verify_counter.gen.Counter.Bytecode +import SolidCore.Refinement.Solar.AssembleFast +import SolidCore.Refinement.Solar.EndToEnd +import SolidCore.Refinement.Solar.RunOracle + +/-! The bytecode of `Counter` runs as its final EVM IR does, at every gas, by the assembly checker for code with loops on an inferred certificate the kernel's evaluation of the checker re-derives; with the backend stages read backwards, every result of the bytecode at any gas is the first lowered MIR's or a failure that changes nothing. -/ + +namespace SolarTV.Milestone.VerifyCounter + +open SolarTV SolarTV.Export.Counter + +/-- The runtime bytecode, as bytes. -/ +def code : ByteArray := ⟨(bytecode.map UInt8.ofNat).toArray⟩ + +/-- The checker's certificate (tools/certify/asm_cert.py): each labelled block's offset, each block's lowest +entry height and entry words, its budget, the memory bound, the turned branches, the pushed labels and +whether the program reads CALLER or hashes. -/ +def cert : SolidCore.Refinement.Solar.Assemble.Cert := + { offsets := [0x0, 0x3c, 0x40, 0x52, 0x5b, 0x65, 0x73, 0xaa, 0xdb, 0x10f, 0x111, 0x127, 0x136, 0x13e, 0x152, 0x167, 0x182, 0x19a, 0x1af, 0x1cb, 0x1d2], + needs := [0, 0, 2, 1, 1, 1, 1, 6, 6, 4, 8, 5, 3, 4, 8, 8, 8, 5, 1, 3, 3], + top := 192, + turned := [], + costs := [32, 3, 9, 7, 7, 11, 43, 37, 41, 1, 8, 8, 5, 4, 5, 11, 8, 5, 20, 5, 15], + types := [[], + [], + [some false, some false], + [some false], + [some false], + [some false], + [some false], + [some false, some false, some false, some false, some false, some false], + [some false, some false, some false, some false, some false, some false], + [some false, some false, some false, some false], + [some false, some false, some false, some false, some false, some false, some false, some false], + [some false, some false, some false, some false, some false], + [some false, some false, some false], + [some false, some false, some false, some false], + [some false, some false, some false, some false, some false, some false, some false, some false], + [some false, some false, some false, some false, some false, some false, some false, some false], + [some false, some false, some false, some false, some false, some false, some false, some false], + [some false, some false, some false, some false, some false], + [some false], + [some false, some false, some false], + [some false, some false, some false]], + rets := [], + env := false, + reads := false } + +/-- The highest stack each block is entered with. -/ +def maxs : List Nat := [0, 1, 7, 1, 1, 1, 1, 6, 6, 7, 8, 10, 8, 4, 8, 8, 8, 5, 1, 3, 3] + +set_option maxRecDepth 100000 in +/-- The code's linear decoding is the lowered program at the layout. -/ +theorem walk_ok : (SolarTV.Assembly.walk (SolidCore.Refinement.Solar.Assemble.bytesOf code) cert.offset 0 + (SolidCore.Refinement.Solar.Assemble.lower evm11 cert)).isSome = true := by + have hw := SolidCore.Refinement.Solar.Assemble.walkS_drop (SolidCore.Refinement.Solar.Assemble.bytesOf code) cert.offset (SolidCore.Refinement.Solar.Assemble.lower evm11 cert) 0 + (Nat.zero_le _) + rw [List.drop_zero] at hw + rw [← hw] + decide +kernel + +set_option maxRecDepth 100000 in +/-- Every block checks within its budget and stack bounds. -/ +theorem blocks_ok : SolidCore.Refinement.Solar.AssembleLoop.blocksOkL evm11 cert maxs 0 evm11.blocks = true := by + decide +kernel + +theorem labels_ok : SolidCore.Refinement.Solar.Assemble.labelsValid evm11 cert code = true := + SolidCore.Refinement.Solar.Assemble.labelsValid_of_walk walk_ok + +theorem size_ok : code.size < 2 ^ 32 := by decide +kernel + +/-- The checker of code with loops accepts the bytecode for the final EVM IR. -/ +theorem check_ok : SolidCore.Refinement.Solar.AssembleLoop.checkL evm11 code cert maxs = true := by + simp only [SolidCore.Refinement.Solar.AssembleLoop.checkL, walk_ok, blocks_ok, labels_ok, decide_eq_true size_ok, Bool.and_true, + Bool.true_and] + decide + +/-- **The assembly stage at every gas.** -/ +theorem assembly (o : Machine.Oracle) (ho : cert.env = true → SolidCore.Refinement.Solar.Assemble.OracleOk o) + (he : cert.reads = true → SolidCore.Refinement.Solar.Assemble.EnvOk o) (scope : Call → Prop) (gas : Nat) : + SolidCore.Refinement.Final.Within (evmirSem o) (SolidCore.Refinement.Final.ethLibWith gas) + evm11 code scope := + SolidCore.Refinement.Solar.AssembleLoop.within_of_checkL check_ok o ho scope gas he + +/-- **The first lowered MIR to the exact bytecode at every gas**: every result of the bytecode, on every call, is +the first lowered MIR's or a failure that changes nothing. -/ +theorem verify_counter_bytecode (o : Machine.Oracle) (ho : cert.env = true → SolidCore.Refinement.Solar.Assemble.OracleOk o) + (he : cert.reads = true → SolidCore.Refinement.Solar.Assemble.EnvOk o) (gas : Nat) : + SolidCore.Refinement.Final.Within (mirSem o) (SolidCore.Refinement.Final.ethLibWith gas) + stage0 code anyCall := + SolidCore.Refinement.Solar.EndToEnd.within_of_checkL (verify_counter_certified_back o) + (fun _ _ => trivial) check_ok ho gas he + +/-- **The first lowered MIR to the exact bytecode, run by run**: for every gas and every call there is an oracle, +meeting the certificate's constraints (CertOk), under which every result of the bytecode is the first +lowered MIR's or a failure that changes nothing; it composes with specifications proved for every +oracle (RunOracle.holds_of_withinRun). -/ +theorem verify_counter_bytecode_run : + SolidCore.Refinement.Solar.RunOracle.WithinRun mirSem (fun _ => stage0) code anyCall + (SolidCore.Refinement.Solar.RunOracle.CertOk cert) := + SolidCore.Refinement.Solar.RunOracle.withinRun_mir_of_checkL verify_counter_certified_back + (fun _ _ => trivial) check_ok + +/-- info: 'SolarTV.Milestone.VerifyCounter.check_ok' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms check_ok + +/-- info: 'SolarTV.Milestone.VerifyCounter.verify_counter_bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms verify_counter_bytecode + +/-- info: 'SolarTV.Milestone.VerifyCounter.verify_counter_bytecode_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms verify_counter_bytecode_run + +end SolarTV.Milestone.VerifyCounter diff --git a/Certified/verify_counter/Proofs/Runs/Evm1.lean b/Certified/verify_counter/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..34f24bc5 --- /dev/null +++ b/Certified/verify_counter/Proofs/Runs/Evm1.lean @@ -0,0 +1,109 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import SolarTV.Termination +import verify_counter.gen.Counter.Evm1 +import verify_counter.gen.Counter.Sched + +/-! `peephole-early`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.VerifyCounter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm1_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 18 + +theorem evm1_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm1_cutA (b, st, s) = (b == 18) := rfl + +def evm1_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 18 + +theorem evm1_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm1_cutB (b, st, s) = (b == 18) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm1_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State), x = (18, [w0, w1, w2, w3, w4, w5], s) ∧ x' = (18, [w0, w1, w2, w3, w4, w5], s)] + +theorem evm1_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (18, [w0, w1, w2, w3, w4, w5], s)) : + ∃ Q ∈ evm1_rels call, Q (18, [w0, w1, w2, w3, w4, w5], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm1_seg0 (o : Oracle) (call : Call) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm1_rels call, Q y y') + (seg (EVM.Program.block o call sched) evm1_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm1) evm1_cutB 45 (0, [], State.initial call)) := by + refine ⟨45, ?_⟩ + sym_seg [evm1_cutA_mk, evm1_cutB_mk] [evm1_mk1] + +set_option maxHeartbeats 2000000 in +theorem evm1_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm1_rels call, Q y y') + (seg (EVM.Program.block o call sched) evm1_cutA k (18, [w0, w1, w2, w3, w4, w5], s)) + (seg (EVM.Program.block o call evm1) evm1_cutB 45 (18, [w0, w1, w2, w3, w4, w5], s)) := by + refine ⟨45, ?_⟩ + sym_seg [evm1_cutA_mk, evm1_cutB_mk] [evm1_mk1] + +theorem evm1_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm1_rels call, ∀ x x', P x x' → ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm1_rels call, Q y y') + (seg (EVM.Program.block o call sched) evm1_cutA k x) + (seg (EVM.Program.block o call evm1) evm1_cutB 45 x') := by + intro P mem x x' holds + simp only [evm1_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm1_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, s, rfl, rfl⟩ := holds + exact evm1_seg1 o call w0 w1 w2 w3 w4 w5 s + +/-- `sched` and `evm1` simulated through their cut points on every call. -/ +def evm1_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o sched evm1 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call sched + step' call := EVM.Program.block o call evm1 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm1_cutA + cut' := evm1_cutB + Rel call := fun x x' => ∃ P ∈ evm1_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each fun P m x x' h => + match evm1_segments o call P m x x' h with | ⟨k, s⟩ => ⟨k, 45, s⟩ + +/-- Every segment of `evm1` takes at most 45 steps: the bound that carries a loop's +ranking certificate on `sched` to a step bound on `evm1` (`CutPoint.ends_within_sim_start`). -/ +theorem evm1_bounded (o : Oracle) (call : Call) : + CutPoint.BoundedSim (EVM.Program.block o call sched) evm1_cutA + (EVM.Program.block o call evm1) evm1_cutB Agree + (fun x x' => ∃ P ∈ evm1_rels call, P x x') 45 := + fun x x' ⟨P, m, h⟩ => evm1_segments o call P m x x' h + +/-- Every end of `sched` on a call is matched by an agreeing end of `evm1`. -/ +theorem evm1_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o sched evm1 anyCall := + (evm1_sim o).certified + +/-- Every end of `evm1` on a call is matched by an agreeing end of `sched`. -/ +theorem evm1_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm1 sched anyCall := + (evm1_sim o).certified_back + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm1_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_certified + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm1_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_certified_back + +end SolarTV.Milestone.VerifyCounter diff --git a/Certified/verify_counter/Proofs/Runs/Evm10.lean b/Certified/verify_counter/Proofs/Runs/Evm10.lean new file mode 100644 index 00000000..00d58cc3 --- /dev/null +++ b/Certified/verify_counter/Proofs/Runs/Evm10.lean @@ -0,0 +1,109 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import SolarTV.Termination +import verify_counter.gen.Counter.Evm10 +import verify_counter.gen.Counter.Evm9 + +/-! `block-layout`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.VerifyCounter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm10_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm10_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm10_cutA (b, st, s) = (b == 7) := rfl + +def evm10_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm10_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm10_cutB (b, st, s) = (b == 7) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm10_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State), x = (7, [w0, w1, w2, w3, w4, w5], s) ∧ x' = (7, [w0, w1, w2, w3, w4, w5], s)] + +theorem evm10_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (7, [w0, w1, w2, w3, w4, w5], s)) : + ∃ Q ∈ evm10_rels call, Q (7, [w0, w1, w2, w3, w4, w5], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm10_seg0 (o : Oracle) (call : Call) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm10_rels call, Q y y') + (seg (EVM.Program.block o call evm9) evm10_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm10) evm10_cutB 22 (0, [], State.initial call)) := by + refine ⟨22, ?_⟩ + sym_seg [evm10_cutA_mk, evm10_cutB_mk] [evm10_mk1] + +set_option maxHeartbeats 2000000 in +theorem evm10_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm10_rels call, Q y y') + (seg (EVM.Program.block o call evm9) evm10_cutA k (7, [w0, w1, w2, w3, w4, w5], s)) + (seg (EVM.Program.block o call evm10) evm10_cutB 22 (7, [w0, w1, w2, w3, w4, w5], s)) := by + refine ⟨22, ?_⟩ + sym_seg [evm10_cutA_mk, evm10_cutB_mk] [evm10_mk1] + +theorem evm10_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm10_rels call, ∀ x x', P x x' → ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm10_rels call, Q y y') + (seg (EVM.Program.block o call evm9) evm10_cutA k x) + (seg (EVM.Program.block o call evm10) evm10_cutB 22 x') := by + intro P mem x x' holds + simp only [evm10_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm10_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, s, rfl, rfl⟩ := holds + exact evm10_seg1 o call w0 w1 w2 w3 w4 w5 s + +/-- `evm9` and `evm10` simulated through their cut points on every call. -/ +def evm10_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm9 evm10 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm9 + step' call := EVM.Program.block o call evm10 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm10_cutA + cut' := evm10_cutB + Rel call := fun x x' => ∃ P ∈ evm10_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each fun P m x x' h => + match evm10_segments o call P m x x' h with | ⟨k, s⟩ => ⟨k, 22, s⟩ + +/-- Every segment of `evm10` takes at most 22 steps: the bound that carries a loop's +ranking certificate on `evm9` to a step bound on `evm10` (`CutPoint.ends_within_sim_start`). -/ +theorem evm10_bounded (o : Oracle) (call : Call) : + CutPoint.BoundedSim (EVM.Program.block o call evm9) evm10_cutA + (EVM.Program.block o call evm10) evm10_cutB Agree + (fun x x' => ∃ P ∈ evm10_rels call, P x x') 22 := + fun x x' ⟨P, m, h⟩ => evm10_segments o call P m x x' h + +/-- Every end of `evm9` on a call is matched by an agreeing end of `evm10`. -/ +theorem evm10_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm9 evm10 anyCall := + (evm10_sim o).certified + +/-- Every end of `evm10` on a call is matched by an agreeing end of `evm9`. -/ +theorem evm10_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm10 evm9 anyCall := + (evm10_sim o).certified_back + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm10_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm10_certified + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm10_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm10_certified_back + +end SolarTV.Milestone.VerifyCounter diff --git a/Certified/verify_counter/Proofs/Runs/Evm11.lean b/Certified/verify_counter/Proofs/Runs/Evm11.lean new file mode 100644 index 00000000..a0257449 --- /dev/null +++ b/Certified/verify_counter/Proofs/Runs/Evm11.lean @@ -0,0 +1,109 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import SolarTV.Termination +import verify_counter.gen.Counter.Evm11 +import verify_counter.gen.Counter.Evm10 + +/-! `loop-layout`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.VerifyCounter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm11_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm11_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm11_cutA (b, st, s) = (b == 7) := rfl + +def evm11_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 8 + +theorem evm11_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm11_cutB (b, st, s) = (b == 8) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm11_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State), x = (7, [w0, w1, w2, w3, w4, w5], s) ∧ x' = (8, [w0, w1, w2, w3, w4, w5], s)] + +theorem evm11_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (8, [w0, w1, w2, w3, w4, w5], s)) : + ∃ Q ∈ evm11_rels call, Q (7, [w0, w1, w2, w3, w4, w5], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm11_seg0 (o : Oracle) (call : Call) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm11_rels call, Q y y') + (seg (EVM.Program.block o call evm10) evm11_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm11) evm11_cutB 22 (0, [], State.initial call)) := by + refine ⟨22, ?_⟩ + sym_seg [evm11_cutA_mk, evm11_cutB_mk] [evm11_mk1] + +set_option maxHeartbeats 2000000 in +theorem evm11_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm11_rels call, Q y y') + (seg (EVM.Program.block o call evm10) evm11_cutA k (7, [w0, w1, w2, w3, w4, w5], s)) + (seg (EVM.Program.block o call evm11) evm11_cutB 22 (8, [w0, w1, w2, w3, w4, w5], s)) := by + refine ⟨22, ?_⟩ + sym_seg [evm11_cutA_mk, evm11_cutB_mk] [evm11_mk1] + +theorem evm11_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm11_rels call, ∀ x x', P x x' → ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm11_rels call, Q y y') + (seg (EVM.Program.block o call evm10) evm11_cutA k x) + (seg (EVM.Program.block o call evm11) evm11_cutB 22 x') := by + intro P mem x x' holds + simp only [evm11_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm11_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, s, rfl, rfl⟩ := holds + exact evm11_seg1 o call w0 w1 w2 w3 w4 w5 s + +/-- `evm10` and `evm11` simulated through their cut points on every call. -/ +def evm11_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm10 evm11 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm10 + step' call := EVM.Program.block o call evm11 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm11_cutA + cut' := evm11_cutB + Rel call := fun x x' => ∃ P ∈ evm11_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each fun P m x x' h => + match evm11_segments o call P m x x' h with | ⟨k, s⟩ => ⟨k, 22, s⟩ + +/-- Every segment of `evm11` takes at most 22 steps: the bound that carries a loop's +ranking certificate on `evm10` to a step bound on `evm11` (`CutPoint.ends_within_sim_start`). -/ +theorem evm11_bounded (o : Oracle) (call : Call) : + CutPoint.BoundedSim (EVM.Program.block o call evm10) evm11_cutA + (EVM.Program.block o call evm11) evm11_cutB Agree + (fun x x' => ∃ P ∈ evm11_rels call, P x x') 22 := + fun x x' ⟨P, m, h⟩ => evm11_segments o call P m x x' h + +/-- Every end of `evm10` on a call is matched by an agreeing end of `evm11`. -/ +theorem evm11_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm10 evm11 anyCall := + (evm11_sim o).certified + +/-- Every end of `evm11` on a call is matched by an agreeing end of `evm10`. -/ +theorem evm11_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm11 evm10 anyCall := + (evm11_sim o).certified_back + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm11_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm11_certified + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm11_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm11_certified_back + +end SolarTV.Milestone.VerifyCounter diff --git a/Certified/verify_counter/Proofs/Runs/Evm2.lean b/Certified/verify_counter/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..6a8cb0be --- /dev/null +++ b/Certified/verify_counter/Proofs/Runs/Evm2.lean @@ -0,0 +1,109 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import SolarTV.Termination +import verify_counter.gen.Counter.Evm2 +import verify_counter.gen.Counter.Evm1 + +/-! `cfg-simplify-early`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.VerifyCounter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm2_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 18 + +theorem evm2_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm2_cutA (b, st, s) = (b == 18) := rfl + +def evm2_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm2_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm2_cutB (b, st, s) = (b == 7) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm2_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State), x = (18, [w0, w1, w2, w3, w4, w5], s) ∧ x' = (7, [w0, w1, w2, w3, w4, w5], s)] + +theorem evm2_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (7, [w0, w1, w2, w3, w4, w5], s)) : + ∃ Q ∈ evm2_rels call, Q (18, [w0, w1, w2, w3, w4, w5], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm2_seg0 (o : Oracle) (call : Call) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm2_rels call, Q y y') + (seg (EVM.Program.block o call evm1) evm2_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm2) evm2_cutB 24 (0, [], State.initial call)) := by + refine ⟨45, ?_⟩ + sym_seg [evm2_cutA_mk, evm2_cutB_mk] [evm2_mk1] + +set_option maxHeartbeats 2000000 in +theorem evm2_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm2_rels call, Q y y') + (seg (EVM.Program.block o call evm1) evm2_cutA k (18, [w0, w1, w2, w3, w4, w5], s)) + (seg (EVM.Program.block o call evm2) evm2_cutB 24 (7, [w0, w1, w2, w3, w4, w5], s)) := by + refine ⟨45, ?_⟩ + sym_seg [evm2_cutA_mk, evm2_cutB_mk] [evm2_mk1] + +theorem evm2_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm2_rels call, ∀ x x', P x x' → ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm2_rels call, Q y y') + (seg (EVM.Program.block o call evm1) evm2_cutA k x) + (seg (EVM.Program.block o call evm2) evm2_cutB 24 x') := by + intro P mem x x' holds + simp only [evm2_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm2_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, s, rfl, rfl⟩ := holds + exact evm2_seg1 o call w0 w1 w2 w3 w4 w5 s + +/-- `evm1` and `evm2` simulated through their cut points on every call. -/ +def evm2_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm1 evm2 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm1 + step' call := EVM.Program.block o call evm2 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm2_cutA + cut' := evm2_cutB + Rel call := fun x x' => ∃ P ∈ evm2_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each fun P m x x' h => + match evm2_segments o call P m x x' h with | ⟨k, s⟩ => ⟨k, 24, s⟩ + +/-- Every segment of `evm2` takes at most 24 steps: the bound that carries a loop's +ranking certificate on `evm1` to a step bound on `evm2` (`CutPoint.ends_within_sim_start`). -/ +theorem evm2_bounded (o : Oracle) (call : Call) : + CutPoint.BoundedSim (EVM.Program.block o call evm1) evm2_cutA + (EVM.Program.block o call evm2) evm2_cutB Agree + (fun x x' => ∃ P ∈ evm2_rels call, P x x') 24 := + fun x x' ⟨P, m, h⟩ => evm2_segments o call P m x x' h + +/-- Every end of `evm1` on a call is matched by an agreeing end of `evm2`. -/ +theorem evm2_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm1 evm2 anyCall := + (evm2_sim o).certified + +/-- Every end of `evm2` on a call is matched by an agreeing end of `evm1`. -/ +theorem evm2_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm2 evm1 anyCall := + (evm2_sim o).certified_back + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm2_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_certified + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm2_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_certified_back + +end SolarTV.Milestone.VerifyCounter diff --git a/Certified/verify_counter/Proofs/Runs/Evm3.lean b/Certified/verify_counter/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..7ec57cb1 --- /dev/null +++ b/Certified/verify_counter/Proofs/Runs/Evm3.lean @@ -0,0 +1,109 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import SolarTV.Termination +import verify_counter.gen.Counter.Evm3 +import verify_counter.gen.Counter.Evm2 + +/-! `compact-pushes`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.VerifyCounter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm3_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm3_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm3_cutA (b, st, s) = (b == 7) := rfl + +def evm3_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm3_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm3_cutB (b, st, s) = (b == 7) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm3_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State), x = (7, [w0, w1, w2, w3, w4, w5], s) ∧ x' = (7, [w0, w1, w2, w3, w4, w5], s)] + +theorem evm3_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (7, [w0, w1, w2, w3, w4, w5], s)) : + ∃ Q ∈ evm3_rels call, Q (7, [w0, w1, w2, w3, w4, w5], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm3_seg0 (o : Oracle) (call : Call) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm3_rels call, Q y y') + (seg (EVM.Program.block o call evm2) evm3_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm3) evm3_cutB 24 (0, [], State.initial call)) := by + refine ⟨24, ?_⟩ + sym_seg [evm3_cutA_mk, evm3_cutB_mk] [evm3_mk1] + +set_option maxHeartbeats 2000000 in +theorem evm3_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm3_rels call, Q y y') + (seg (EVM.Program.block o call evm2) evm3_cutA k (7, [w0, w1, w2, w3, w4, w5], s)) + (seg (EVM.Program.block o call evm3) evm3_cutB 24 (7, [w0, w1, w2, w3, w4, w5], s)) := by + refine ⟨24, ?_⟩ + sym_seg [evm3_cutA_mk, evm3_cutB_mk] [evm3_mk1] + +theorem evm3_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm3_rels call, ∀ x x', P x x' → ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm3_rels call, Q y y') + (seg (EVM.Program.block o call evm2) evm3_cutA k x) + (seg (EVM.Program.block o call evm3) evm3_cutB 24 x') := by + intro P mem x x' holds + simp only [evm3_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm3_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, s, rfl, rfl⟩ := holds + exact evm3_seg1 o call w0 w1 w2 w3 w4 w5 s + +/-- `evm2` and `evm3` simulated through their cut points on every call. -/ +def evm3_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm2 evm3 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm2 + step' call := EVM.Program.block o call evm3 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm3_cutA + cut' := evm3_cutB + Rel call := fun x x' => ∃ P ∈ evm3_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each fun P m x x' h => + match evm3_segments o call P m x x' h with | ⟨k, s⟩ => ⟨k, 24, s⟩ + +/-- Every segment of `evm3` takes at most 24 steps: the bound that carries a loop's +ranking certificate on `evm2` to a step bound on `evm3` (`CutPoint.ends_within_sim_start`). -/ +theorem evm3_bounded (o : Oracle) (call : Call) : + CutPoint.BoundedSim (EVM.Program.block o call evm2) evm3_cutA + (EVM.Program.block o call evm3) evm3_cutB Agree + (fun x x' => ∃ P ∈ evm3_rels call, P x x') 24 := + fun x x' ⟨P, m, h⟩ => evm3_segments o call P m x x' h + +/-- Every end of `evm2` on a call is matched by an agreeing end of `evm3`. -/ +theorem evm3_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm2 evm3 anyCall := + (evm3_sim o).certified + +/-- Every end of `evm3` on a call is matched by an agreeing end of `evm2`. -/ +theorem evm3_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm3 evm2 anyCall := + (evm3_sim o).certified_back + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm3_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_certified + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm3_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_certified_back + +end SolarTV.Milestone.VerifyCounter diff --git a/Certified/verify_counter/Proofs/Runs/Evm4.lean b/Certified/verify_counter/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..6c4fb3ba --- /dev/null +++ b/Certified/verify_counter/Proofs/Runs/Evm4.lean @@ -0,0 +1,109 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import SolarTV.Termination +import verify_counter.gen.Counter.Evm4 +import verify_counter.gen.Counter.Evm3 + +/-! `block-layout`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.VerifyCounter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm4_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm4_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm4_cutA (b, st, s) = (b == 7) := rfl + +def evm4_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm4_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm4_cutB (b, st, s) = (b == 7) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm4_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State), x = (7, [w0, w1, w2, w3, w4, w5], s) ∧ x' = (7, [w0, w1, w2, w3, w4, w5], s)] + +theorem evm4_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (7, [w0, w1, w2, w3, w4, w5], s)) : + ∃ Q ∈ evm4_rels call, Q (7, [w0, w1, w2, w3, w4, w5], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm4_seg0 (o : Oracle) (call : Call) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm4_rels call, Q y y') + (seg (EVM.Program.block o call evm3) evm4_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm4) evm4_cutB 24 (0, [], State.initial call)) := by + refine ⟨24, ?_⟩ + sym_seg [evm4_cutA_mk, evm4_cutB_mk] [evm4_mk1] + +set_option maxHeartbeats 2000000 in +theorem evm4_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm4_rels call, Q y y') + (seg (EVM.Program.block o call evm3) evm4_cutA k (7, [w0, w1, w2, w3, w4, w5], s)) + (seg (EVM.Program.block o call evm4) evm4_cutB 24 (7, [w0, w1, w2, w3, w4, w5], s)) := by + refine ⟨24, ?_⟩ + sym_seg [evm4_cutA_mk, evm4_cutB_mk] [evm4_mk1] + +theorem evm4_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm4_rels call, ∀ x x', P x x' → ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm4_rels call, Q y y') + (seg (EVM.Program.block o call evm3) evm4_cutA k x) + (seg (EVM.Program.block o call evm4) evm4_cutB 24 x') := by + intro P mem x x' holds + simp only [evm4_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm4_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, s, rfl, rfl⟩ := holds + exact evm4_seg1 o call w0 w1 w2 w3 w4 w5 s + +/-- `evm3` and `evm4` simulated through their cut points on every call. -/ +def evm4_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm3 evm4 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm3 + step' call := EVM.Program.block o call evm4 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm4_cutA + cut' := evm4_cutB + Rel call := fun x x' => ∃ P ∈ evm4_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each fun P m x x' h => + match evm4_segments o call P m x x' h with | ⟨k, s⟩ => ⟨k, 24, s⟩ + +/-- Every segment of `evm4` takes at most 24 steps: the bound that carries a loop's +ranking certificate on `evm3` to a step bound on `evm4` (`CutPoint.ends_within_sim_start`). -/ +theorem evm4_bounded (o : Oracle) (call : Call) : + CutPoint.BoundedSim (EVM.Program.block o call evm3) evm4_cutA + (EVM.Program.block o call evm4) evm4_cutB Agree + (fun x x' => ∃ P ∈ evm4_rels call, P x x') 24 := + fun x x' ⟨P, m, h⟩ => evm4_segments o call P m x x' h + +/-- Every end of `evm3` on a call is matched by an agreeing end of `evm4`. -/ +theorem evm4_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm3 evm4 anyCall := + (evm4_sim o).certified + +/-- Every end of `evm4` on a call is matched by an agreeing end of `evm3`. -/ +theorem evm4_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm4 evm3 anyCall := + (evm4_sim o).certified_back + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm4_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_certified + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm4_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_certified_back + +end SolarTV.Milestone.VerifyCounter diff --git a/Certified/verify_counter/Proofs/Runs/Evm5.lean b/Certified/verify_counter/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..425d4c88 --- /dev/null +++ b/Certified/verify_counter/Proofs/Runs/Evm5.lean @@ -0,0 +1,109 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import SolarTV.Termination +import verify_counter.gen.Counter.Evm5 +import verify_counter.gen.Counter.Evm4 + +/-! `terminal-dedup`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.VerifyCounter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm5_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm5_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm5_cutA (b, st, s) = (b == 7) := rfl + +def evm5_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm5_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm5_cutB (b, st, s) = (b == 7) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm5_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State), x = (7, [w0, w1, w2, w3, w4, w5], s) ∧ x' = (7, [w0, w1, w2, w3, w4, w5], s)] + +theorem evm5_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (7, [w0, w1, w2, w3, w4, w5], s)) : + ∃ Q ∈ evm5_rels call, Q (7, [w0, w1, w2, w3, w4, w5], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm5_seg0 (o : Oracle) (call : Call) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm5_rels call, Q y y') + (seg (EVM.Program.block o call evm4) evm5_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm5) evm5_cutB 24 (0, [], State.initial call)) := by + refine ⟨24, ?_⟩ + sym_seg [evm5_cutA_mk, evm5_cutB_mk] [evm5_mk1] + +set_option maxHeartbeats 2000000 in +theorem evm5_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm5_rels call, Q y y') + (seg (EVM.Program.block o call evm4) evm5_cutA k (7, [w0, w1, w2, w3, w4, w5], s)) + (seg (EVM.Program.block o call evm5) evm5_cutB 24 (7, [w0, w1, w2, w3, w4, w5], s)) := by + refine ⟨24, ?_⟩ + sym_seg [evm5_cutA_mk, evm5_cutB_mk] [evm5_mk1] + +theorem evm5_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm5_rels call, ∀ x x', P x x' → ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm5_rels call, Q y y') + (seg (EVM.Program.block o call evm4) evm5_cutA k x) + (seg (EVM.Program.block o call evm5) evm5_cutB 24 x') := by + intro P mem x x' holds + simp only [evm5_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm5_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, s, rfl, rfl⟩ := holds + exact evm5_seg1 o call w0 w1 w2 w3 w4 w5 s + +/-- `evm4` and `evm5` simulated through their cut points on every call. -/ +def evm5_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm4 evm5 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm4 + step' call := EVM.Program.block o call evm5 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm5_cutA + cut' := evm5_cutB + Rel call := fun x x' => ∃ P ∈ evm5_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each fun P m x x' h => + match evm5_segments o call P m x x' h with | ⟨k, s⟩ => ⟨k, 24, s⟩ + +/-- Every segment of `evm5` takes at most 24 steps: the bound that carries a loop's +ranking certificate on `evm4` to a step bound on `evm5` (`CutPoint.ends_within_sim_start`). -/ +theorem evm5_bounded (o : Oracle) (call : Call) : + CutPoint.BoundedSim (EVM.Program.block o call evm4) evm5_cutA + (EVM.Program.block o call evm5) evm5_cutB Agree + (fun x x' => ∃ P ∈ evm5_rels call, P x x') 24 := + fun x x' ⟨P, m, h⟩ => evm5_segments o call P m x x' h + +/-- Every end of `evm4` on a call is matched by an agreeing end of `evm5`. -/ +theorem evm5_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm4 evm5 anyCall := + (evm5_sim o).certified + +/-- Every end of `evm5` on a call is matched by an agreeing end of `evm4`. -/ +theorem evm5_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm5 evm4 anyCall := + (evm5_sim o).certified_back + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm5_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_certified + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm5_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_certified_back + +end SolarTV.Milestone.VerifyCounter diff --git a/Certified/verify_counter/Proofs/Runs/Evm6.lean b/Certified/verify_counter/Proofs/Runs/Evm6.lean new file mode 100644 index 00000000..5ee0b613 --- /dev/null +++ b/Certified/verify_counter/Proofs/Runs/Evm6.lean @@ -0,0 +1,109 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import SolarTV.Termination +import verify_counter.gen.Counter.Evm6 +import verify_counter.gen.Counter.Evm5 + +/-! `cfg-simplify-early`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.VerifyCounter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm6_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm6_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm6_cutA (b, st, s) = (b == 7) := rfl + +def evm6_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm6_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm6_cutB (b, st, s) = (b == 7) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm6_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State), x = (7, [w0, w1, w2, w3, w4, w5], s) ∧ x' = (7, [w0, w1, w2, w3, w4, w5], s)] + +theorem evm6_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (7, [w0, w1, w2, w3, w4, w5], s)) : + ∃ Q ∈ evm6_rels call, Q (7, [w0, w1, w2, w3, w4, w5], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm6_seg0 (o : Oracle) (call : Call) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm6_rels call, Q y y') + (seg (EVM.Program.block o call evm5) evm6_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm6) evm6_cutB 21 (0, [], State.initial call)) := by + refine ⟨24, ?_⟩ + sym_seg [evm6_cutA_mk, evm6_cutB_mk] [evm6_mk1] + +set_option maxHeartbeats 2000000 in +theorem evm6_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm6_rels call, Q y y') + (seg (EVM.Program.block o call evm5) evm6_cutA k (7, [w0, w1, w2, w3, w4, w5], s)) + (seg (EVM.Program.block o call evm6) evm6_cutB 21 (7, [w0, w1, w2, w3, w4, w5], s)) := by + refine ⟨24, ?_⟩ + sym_seg [evm6_cutA_mk, evm6_cutB_mk] [evm6_mk1] + +theorem evm6_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm6_rels call, ∀ x x', P x x' → ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm6_rels call, Q y y') + (seg (EVM.Program.block o call evm5) evm6_cutA k x) + (seg (EVM.Program.block o call evm6) evm6_cutB 21 x') := by + intro P mem x x' holds + simp only [evm6_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm6_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, s, rfl, rfl⟩ := holds + exact evm6_seg1 o call w0 w1 w2 w3 w4 w5 s + +/-- `evm5` and `evm6` simulated through their cut points on every call. -/ +def evm6_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm5 evm6 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm5 + step' call := EVM.Program.block o call evm6 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm6_cutA + cut' := evm6_cutB + Rel call := fun x x' => ∃ P ∈ evm6_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each fun P m x x' h => + match evm6_segments o call P m x x' h with | ⟨k, s⟩ => ⟨k, 21, s⟩ + +/-- Every segment of `evm6` takes at most 21 steps: the bound that carries a loop's +ranking certificate on `evm5` to a step bound on `evm6` (`CutPoint.ends_within_sim_start`). -/ +theorem evm6_bounded (o : Oracle) (call : Call) : + CutPoint.BoundedSim (EVM.Program.block o call evm5) evm6_cutA + (EVM.Program.block o call evm6) evm6_cutB Agree + (fun x x' => ∃ P ∈ evm6_rels call, P x x') 21 := + fun x x' ⟨P, m, h⟩ => evm6_segments o call P m x x' h + +/-- Every end of `evm5` on a call is matched by an agreeing end of `evm6`. -/ +theorem evm6_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm5 evm6 anyCall := + (evm6_sim o).certified + +/-- Every end of `evm6` on a call is matched by an agreeing end of `evm5`. -/ +theorem evm6_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm6 evm5 anyCall := + (evm6_sim o).certified_back + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm6_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_certified + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm6_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_certified_back + +end SolarTV.Milestone.VerifyCounter diff --git a/Certified/verify_counter/Proofs/Runs/Evm7.lean b/Certified/verify_counter/Proofs/Runs/Evm7.lean new file mode 100644 index 00000000..abedbb04 --- /dev/null +++ b/Certified/verify_counter/Proofs/Runs/Evm7.lean @@ -0,0 +1,109 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import SolarTV.Termination +import verify_counter.gen.Counter.Evm7 +import verify_counter.gen.Counter.Evm6 + +/-! `tail-merge`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.VerifyCounter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm7_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm7_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm7_cutA (b, st, s) = (b == 7) := rfl + +def evm7_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm7_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm7_cutB (b, st, s) = (b == 7) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm7_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State), x = (7, [w0, w1, w2, w3, w4, w5], s) ∧ x' = (7, [w0, w1, w2, w3, w4, w5], s)] + +theorem evm7_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (7, [w0, w1, w2, w3, w4, w5], s)) : + ∃ Q ∈ evm7_rels call, Q (7, [w0, w1, w2, w3, w4, w5], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm7_seg0 (o : Oracle) (call : Call) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm7_rels call, Q y y') + (seg (EVM.Program.block o call evm6) evm7_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm7) evm7_cutB 22 (0, [], State.initial call)) := by + refine ⟨21, ?_⟩ + sym_seg [evm7_cutA_mk, evm7_cutB_mk] [evm7_mk1] + +set_option maxHeartbeats 2000000 in +theorem evm7_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm7_rels call, Q y y') + (seg (EVM.Program.block o call evm6) evm7_cutA k (7, [w0, w1, w2, w3, w4, w5], s)) + (seg (EVM.Program.block o call evm7) evm7_cutB 22 (7, [w0, w1, w2, w3, w4, w5], s)) := by + refine ⟨21, ?_⟩ + sym_seg [evm7_cutA_mk, evm7_cutB_mk] [evm7_mk1] + +theorem evm7_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm7_rels call, ∀ x x', P x x' → ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm7_rels call, Q y y') + (seg (EVM.Program.block o call evm6) evm7_cutA k x) + (seg (EVM.Program.block o call evm7) evm7_cutB 22 x') := by + intro P mem x x' holds + simp only [evm7_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm7_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, s, rfl, rfl⟩ := holds + exact evm7_seg1 o call w0 w1 w2 w3 w4 w5 s + +/-- `evm6` and `evm7` simulated through their cut points on every call. -/ +def evm7_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm6 evm7 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm6 + step' call := EVM.Program.block o call evm7 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm7_cutA + cut' := evm7_cutB + Rel call := fun x x' => ∃ P ∈ evm7_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each fun P m x x' h => + match evm7_segments o call P m x x' h with | ⟨k, s⟩ => ⟨k, 22, s⟩ + +/-- Every segment of `evm7` takes at most 22 steps: the bound that carries a loop's +ranking certificate on `evm6` to a step bound on `evm7` (`CutPoint.ends_within_sim_start`). -/ +theorem evm7_bounded (o : Oracle) (call : Call) : + CutPoint.BoundedSim (EVM.Program.block o call evm6) evm7_cutA + (EVM.Program.block o call evm7) evm7_cutB Agree + (fun x x' => ∃ P ∈ evm7_rels call, P x x') 22 := + fun x x' ⟨P, m, h⟩ => evm7_segments o call P m x x' h + +/-- Every end of `evm6` on a call is matched by an agreeing end of `evm7`. -/ +theorem evm7_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm6 evm7 anyCall := + (evm7_sim o).certified + +/-- Every end of `evm7` on a call is matched by an agreeing end of `evm6`. -/ +theorem evm7_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm7 evm6 anyCall := + (evm7_sim o).certified_back + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm7_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm7_certified + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm7_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm7_certified_back + +end SolarTV.Milestone.VerifyCounter diff --git a/Certified/verify_counter/Proofs/Runs/Evm8.lean b/Certified/verify_counter/Proofs/Runs/Evm8.lean new file mode 100644 index 00000000..017decf7 --- /dev/null +++ b/Certified/verify_counter/Proofs/Runs/Evm8.lean @@ -0,0 +1,109 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import SolarTV.Termination +import verify_counter.gen.Counter.Evm8 +import verify_counter.gen.Counter.Evm7 + +/-! `block-cse`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.VerifyCounter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm8_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm8_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm8_cutA (b, st, s) = (b == 7) := rfl + +def evm8_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm8_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm8_cutB (b, st, s) = (b == 7) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm8_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State), x = (7, [w0, w1, w2, w3, w4, w5], s) ∧ x' = (7, [w0, w1, w2, w3, w4, w5], s)] + +theorem evm8_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (7, [w0, w1, w2, w3, w4, w5], s)) : + ∃ Q ∈ evm8_rels call, Q (7, [w0, w1, w2, w3, w4, w5], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm8_seg0 (o : Oracle) (call : Call) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm8_rels call, Q y y') + (seg (EVM.Program.block o call evm7) evm8_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm8) evm8_cutB 22 (0, [], State.initial call)) := by + refine ⟨22, ?_⟩ + sym_seg [evm8_cutA_mk, evm8_cutB_mk] [evm8_mk1] + +set_option maxHeartbeats 2000000 in +theorem evm8_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm8_rels call, Q y y') + (seg (EVM.Program.block o call evm7) evm8_cutA k (7, [w0, w1, w2, w3, w4, w5], s)) + (seg (EVM.Program.block o call evm8) evm8_cutB 22 (7, [w0, w1, w2, w3, w4, w5], s)) := by + refine ⟨22, ?_⟩ + sym_seg [evm8_cutA_mk, evm8_cutB_mk] [evm8_mk1] + +theorem evm8_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm8_rels call, ∀ x x', P x x' → ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm8_rels call, Q y y') + (seg (EVM.Program.block o call evm7) evm8_cutA k x) + (seg (EVM.Program.block o call evm8) evm8_cutB 22 x') := by + intro P mem x x' holds + simp only [evm8_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm8_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, s, rfl, rfl⟩ := holds + exact evm8_seg1 o call w0 w1 w2 w3 w4 w5 s + +/-- `evm7` and `evm8` simulated through their cut points on every call. -/ +def evm8_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm7 evm8 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm7 + step' call := EVM.Program.block o call evm8 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm8_cutA + cut' := evm8_cutB + Rel call := fun x x' => ∃ P ∈ evm8_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each fun P m x x' h => + match evm8_segments o call P m x x' h with | ⟨k, s⟩ => ⟨k, 22, s⟩ + +/-- Every segment of `evm8` takes at most 22 steps: the bound that carries a loop's +ranking certificate on `evm7` to a step bound on `evm8` (`CutPoint.ends_within_sim_start`). -/ +theorem evm8_bounded (o : Oracle) (call : Call) : + CutPoint.BoundedSim (EVM.Program.block o call evm7) evm8_cutA + (EVM.Program.block o call evm8) evm8_cutB Agree + (fun x x' => ∃ P ∈ evm8_rels call, P x x') 22 := + fun x x' ⟨P, m, h⟩ => evm8_segments o call P m x x' h + +/-- Every end of `evm7` on a call is matched by an agreeing end of `evm8`. -/ +theorem evm8_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm7 evm8 anyCall := + (evm8_sim o).certified + +/-- Every end of `evm8` on a call is matched by an agreeing end of `evm7`. -/ +theorem evm8_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm8 evm7 anyCall := + (evm8_sim o).certified_back + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm8_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm8_certified + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm8_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm8_certified_back + +end SolarTV.Milestone.VerifyCounter diff --git a/Certified/verify_counter/Proofs/Runs/Evm9.lean b/Certified/verify_counter/Proofs/Runs/Evm9.lean new file mode 100644 index 00000000..c6547cae --- /dev/null +++ b/Certified/verify_counter/Proofs/Runs/Evm9.lean @@ -0,0 +1,109 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import SolarTV.Termination +import verify_counter.gen.Counter.Evm9 +import verify_counter.gen.Counter.Evm8 + +/-! `stack-normalize`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.VerifyCounter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def evm9_cutA : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm9_cutA_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm9_cutA (b, st, s) = (b == 7) := rfl + +def evm9_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 7 + +theorem evm9_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + evm9_cutB (b, st, s) = (b == 7) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def evm9_rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State), x = (7, [w0, w1, w2, w3, w4, w5], s) ∧ x' = (7, [w0, w1, w2, w3, w4, w5], s)] + +theorem evm9_mk1 {call : Call} {w0 w1 w2 w3 w4 w5 : EvmRules.Word} {s : State} {y : Nat × EVM.Stack × State} + (h : y = (7, [w0, w1, w2, w3, w4, w5], s)) : + ∃ Q ∈ evm9_rels call, Q (7, [w0, w1, w2, w3, w4, w5], s) y := + rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨w0, w1, w2, w3, w4, w5, s, rfl, h⟩ + +set_option maxHeartbeats 2000000 in +theorem evm9_seg0 (o : Oracle) (call : Call) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm9_rels call, Q y y') + (seg (EVM.Program.block o call evm8) evm9_cutA k (0, [], State.initial call)) + (seg (EVM.Program.block o call evm9) evm9_cutB 22 (0, [], State.initial call)) := by + refine ⟨22, ?_⟩ + sym_seg [evm9_cutA_mk, evm9_cutB_mk] [evm9_mk1] + +set_option maxHeartbeats 2000000 in +theorem evm9_seg1 (o : Oracle) (call : Call) (w0 w1 w2 w3 w4 w5 : EvmRules.Word) (s : State) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm9_rels call, Q y y') + (seg (EVM.Program.block o call evm8) evm9_cutA k (7, [w0, w1, w2, w3, w4, w5], s)) + (seg (EVM.Program.block o call evm9) evm9_cutB 22 (7, [w0, w1, w2, w3, w4, w5], s)) := by + refine ⟨22, ?_⟩ + sym_seg [evm9_cutA_mk, evm9_cutB_mk] [evm9_mk1] + +theorem evm9_segments (o : Oracle) (call : Call) : + ∀ P ∈ evm9_rels call, ∀ x x', P x x' → ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ evm9_rels call, Q y y') + (seg (EVM.Program.block o call evm8) evm9_cutA k x) + (seg (EVM.Program.block o call evm9) evm9_cutB 22 x') := by + intro P mem x x' holds + simp only [evm9_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact evm9_seg0 o call + · obtain ⟨w0, w1, w2, w3, w4, w5, s, rfl, rfl⟩ := holds + exact evm9_seg1 o call w0 w1 w2 w3 w4 w5 s + +/-- `evm8` and `evm9` simulated through their cut points on every call. -/ +def evm9_sim (o : Oracle) : + CutPoint.LayerSim EVM.Program.layer EVM.Program.layer o evm8 evm9 anyCall where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := EVM.Program.block o call evm8 + step' call := EVM.Program.block o call evm9 + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := evm9_cutA + cut' := evm9_cutB + Rel call := fun x x' => ∃ P ∈ evm9_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each fun P m x x' h => + match evm9_segments o call P m x x' h with | ⟨k, s⟩ => ⟨k, 22, s⟩ + +/-- Every segment of `evm9` takes at most 22 steps: the bound that carries a loop's +ranking certificate on `evm8` to a step bound on `evm9` (`CutPoint.ends_within_sim_start`). -/ +theorem evm9_bounded (o : Oracle) (call : Call) : + CutPoint.BoundedSim (EVM.Program.block o call evm8) evm9_cutA + (EVM.Program.block o call evm9) evm9_cutB Agree + (fun x x' => ∃ P ∈ evm9_rels call, P x x') 22 := + fun x x' ⟨P, m, h⟩ => evm9_segments o call P m x x' h + +/-- Every end of `evm8` on a call is matched by an agreeing end of `evm9`. -/ +theorem evm9_certified (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm8 evm9 anyCall := + (evm9_sim o).certified + +/-- Every end of `evm9` on a call is matched by an agreeing end of `evm8`. -/ +theorem evm9_certified_back (o : Oracle) : + Certified EVM.Program.layer EVM.Program.layer o evm9 evm8 anyCall := + (evm9_sim o).certified_back + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm9_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm9_certified + +/-- info: 'SolarTV.Milestone.VerifyCounter.evm9_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm9_certified_back + +end SolarTV.Milestone.VerifyCounter diff --git a/Certified/verify_counter/Proofs/Runs/Mir1.lean b/Certified/verify_counter/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..8a61305b --- /dev/null +++ b/Certified/verify_counter/Proofs/Runs/Mir1.lean @@ -0,0 +1,139 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import SolarTV.Termination +import verify_counter.gen.Counter.Mir1 +import verify_counter.gen.Counter.Stage0 + +/-! `lower-assumes`: its input and output simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.VerifyCounter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def mir1_cutA : MIR.Lowered.Frame → Bool := fun x => + match x.2.1 with + | .enter f _ b => (f == 4 && b == 1) + | .resume .. => false + +theorem mir1_cutA_enter (rs : List MIR.Lowered.Return) (f p b : Nat) (env : MIR.Lowered.Env) (s : State) : + mir1_cutA (rs, .enter f p b, env, s) = ((f == 4 && b == 1)) := rfl + +theorem mir1_cutA_resume (rs : List MIR.Lowered.Return) (f b : Nat) (is : List MIR.Lowered.Inst) (t : MIR.Lowered.Terminator) (env : MIR.Lowered.Env) (s : State) : + mir1_cutA (rs, .resume f b is t, env, s) = false := rfl + +def mir1_cutB : MIR.Lowered.Frame → Bool := fun x => + match x.2.1 with + | .enter f _ b => (f == 4 && b == 1) + | .resume .. => false + +theorem mir1_cutB_enter (rs : List MIR.Lowered.Return) (f p b : Nat) (env : MIR.Lowered.Env) (s : State) : + mir1_cutB (rs, .enter f p b, env, s) = ((f == 4 && b == 1)) := rfl + +theorem mir1_cutB_resume (rs : List MIR.Lowered.Return) (f b : Nat) (is : List MIR.Lowered.Inst) (t : MIR.Lowered.Terminator) (env : MIR.Lowered.Env) (s : State) : + mir1_cutB (rs, .resume f b is t, env, s) = false := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def mir1_rels (call : Call) : List (MIR.Lowered.Frame → MIR.Lowered.Frame → Prop) := + [fun x x' => x = ([], .enter stage0.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState stage0 (State.initial call)) ∧ x' = ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call)), + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env), x = ([], MIR.Lowered.Pos.enter 4 7 1, env, s) ∧ x' = ([], MIR.Lowered.Pos.enter 4 23 1, env', s) ∧ env' 30 = env 30 ∧ env' 62 = env 62 ∧ env' 2 = env 2 ∧ s.storage (0x0 : EvmRules.Word) = env 30 ∧ s.memory.load 128 = env 2 ∧ s.memory.load 160 = (0 : EvmRules.Word), + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env), x = ([], MIR.Lowered.Pos.enter 4 10 1, env, s) ∧ x' = ([], MIR.Lowered.Pos.enter 4 25 1, env', s) ∧ env' 30 = env 30 ∧ env' 62 = env 62 ∧ env' 20 = env 20 ∧ env' 43 = env 43 ∧ s.storage (0x0 : EvmRules.Word) = env 30 ∧ s.memory.load 128 = env 43 ∧ s.memory.load 160 = (1 : EvmRules.Word)] + +theorem mir1_mk1 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' : MIR.Lowered.Env), y = ([], MIR.Lowered.Pos.enter 4 23 1, env', s) ∧ env' 30 = env 30 ∧ env' 62 = env 62 ∧ env' 2 = env 2 ∧ s.storage (0x0 : EvmRules.Word) = env 30 ∧ s.memory.load 128 = env 2 ∧ s.memory.load 160 = (0 : EvmRules.Word)) : + ∃ Q ∈ mir1_rels call, Q ([], MIR.Lowered.Pos.enter 4 7 1, env, s) y := by + obtain ⟨env', h0, h1, h2, h3, h4, h5, h6⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨env, s, env', rfl, h0, h1, h2, h3, h4, h5, h6⟩ + +theorem mir1_mk2 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : MIR.Lowered.Frame} + (h : ∃ (env' : MIR.Lowered.Env), y = ([], MIR.Lowered.Pos.enter 4 25 1, env', s) ∧ env' 30 = env 30 ∧ env' 62 = env 62 ∧ env' 20 = env 20 ∧ env' 43 = env 43 ∧ s.storage (0x0 : EvmRules.Word) = env 30 ∧ s.memory.load 128 = env 43 ∧ s.memory.load 160 = (1 : EvmRules.Word)) : + ∃ Q ∈ mir1_rels call, Q ([], MIR.Lowered.Pos.enter 4 10 1, env, s) y := by + obtain ⟨env', h0, h1, h2, h3, h4, h5, h6, h7⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨env, s, env', rfl, h0, h1, h2, h3, h4, h5, h6, h7⟩ + +set_option maxHeartbeats 2000000 in +theorem mir1_seg0 (o : Oracle) (call : Call) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([], .enter stage0.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState stage0 (State.initial call))) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB 46 ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call))) := by + refine ⟨33, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2] + +set_option maxHeartbeats 2000000 in +theorem mir1_seg1 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env) (h0 : env' 30 = env 30) (h1 : env' 62 = env 62) (h2 : env' 2 = env 2) (h3 : s.storage (0x0 : EvmRules.Word) = env 30) (h4 : s.memory.load 128 = env 2) (h5 : s.memory.load 160 = (0 : EvmRules.Word)) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([], MIR.Lowered.Pos.enter 4 7 1, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB 46 ([], MIR.Lowered.Pos.enter 4 23 1, env', s)) := by + refine ⟨33, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2] + +set_option maxHeartbeats 2000000 in +theorem mir1_seg2 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (env' : MIR.Lowered.Env) (h0 : env' 30 = env 30) (h1 : env' 62 = env 62) (h2 : env' 20 = env 20) (h3 : env' 43 = env 43) (h4 : s.storage (0x0 : EvmRules.Word) = env 30) (h5 : s.memory.load 128 = env 43) (h6 : s.memory.load 160 = (1 : EvmRules.Word)) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k ([], MIR.Lowered.Pos.enter 4 10 1, env, s)) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB 46 ([], MIR.Lowered.Pos.enter 4 25 1, env', s)) := by + refine ⟨33, ?_⟩ + sym_seg [mir1_cutA_enter, mir1_cutA_resume, mir1_cutB_enter, mir1_cutB_resume] [mir1_mk1, mir1_mk2] + +theorem mir1_segments (o : Oracle) (call : Call) : + ∀ P ∈ mir1_rels call, ∀ x x', P x x' → ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ mir1_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call stage0) mir1_cutA k x) + (seg (MIR.Lowered.moduleBlock o call mir1) mir1_cutB 46 x') := by + intro P mem x x' holds + simp only [mir1_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact mir1_seg0 o call + · obtain ⟨env, s, env', rfl, rfl, h0, h1, h2, h3, h4, h5⟩ := holds + exact mir1_seg1 o call env s env' h0 h1 h2 h3 h4 h5 + · obtain ⟨env, s, env', rfl, rfl, h0, h1, h2, h3, h4, h5, h6⟩ := holds + exact mir1_seg2 o call env s env' h0 h1 h2 h3 h4 h5 h6 + +/-- `stage0` and `mir1` simulated through their cut points on every call. -/ +def mir1_sim (o : Oracle) : + CutPoint.LayerSim MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o stage0 mir1 anyCall where + σ := MIR.Lowered.Frame + τ := MIR.Lowered.Frame + step call := MIR.Lowered.moduleBlock o call stage0 + step' call := MIR.Lowered.moduleBlock o call mir1 + init call := ([], .enter stage0.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState stage0 (State.initial call)) + init' call := ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call)) + runs _ _ := rfl + runs' _ _ := rfl + cut := mir1_cutA + cut' := mir1_cutB + Rel call := fun x x' => ∃ P ∈ mir1_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each fun P m x x' h => + match mir1_segments o call P m x x' h with | ⟨k, s⟩ => ⟨k, 46, s⟩ + +/-- Every segment of `mir1` takes at most 46 steps: the bound that carries a loop's +ranking certificate on `stage0` to a step bound on `mir1` (`CutPoint.ends_within_sim_start`). -/ +theorem mir1_bounded (o : Oracle) (call : Call) : + CutPoint.BoundedSim (MIR.Lowered.moduleBlock o call stage0) mir1_cutA + (MIR.Lowered.moduleBlock o call mir1) mir1_cutB Agree + (fun x x' => ∃ P ∈ mir1_rels call, P x x') 46 := + fun x x' ⟨P, m, h⟩ => mir1_segments o call P m x x' h + +/-- Every end of `stage0` on a call is matched by an agreeing end of `mir1`. -/ +theorem mir1_certified (o : Oracle) : + Certified MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o stage0 mir1 anyCall := + (mir1_sim o).certified + +/-- Every end of `mir1` on a call is matched by an agreeing end of `stage0`. -/ +theorem mir1_certified_back (o : Oracle) : + Certified MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o mir1 stage0 anyCall := + (mir1_sim o).certified_back + +/-- info: 'SolarTV.Milestone.VerifyCounter.mir1_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_certified + +/-- info: 'SolarTV.Milestone.VerifyCounter.mir1_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_certified_back + +end SolarTV.Milestone.VerifyCounter diff --git a/Certified/verify_counter/Proofs/Runs/Sched.lean b/Certified/verify_counter/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..bb1efce6 --- /dev/null +++ b/Certified/verify_counter/Proofs/Runs/Sched.lean @@ -0,0 +1,133 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Segment +import W1Proofs.Stage +import W1Proofs.Axioms +import SolarTV.Termination +import verify_counter.gen.Counter.Sched +import verify_counter.gen.Counter.Mir1 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR simulated through cut points on every call: from every pair of configurations the relations derived from the compiler relate, the two loop-free segments end alike (`sym_seg`), so their runs end in agreeing results for any number of loop iterations, both ways. -/ + +namespace SolarTV.Milestone.VerifyCounter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +open SolarTV.CutPoint (seg SegRel) + +def sched_cutA : MIR.Lowered.Frame → Bool := fun x => + match x.2.1 with + | .enter f _ b => (f == 4 && b == 1) + | .resume .. => false + +theorem sched_cutA_enter (rs : List MIR.Lowered.Return) (f p b : Nat) (env : MIR.Lowered.Env) (s : State) : + sched_cutA (rs, .enter f p b, env, s) = ((f == 4 && b == 1)) := rfl + +theorem sched_cutA_resume (rs : List MIR.Lowered.Return) (f b : Nat) (is : List MIR.Lowered.Inst) (t : MIR.Lowered.Terminator) (env : MIR.Lowered.Env) (s : State) : + sched_cutA (rs, .resume f b is t, env, s) = false := rfl + +def sched_cutB : Nat × EVM.Stack × State → Bool := fun x => x.1 == 18 + +theorem sched_cutB_mk (b : Nat) (st : EVM.Stack) (s : State) : + sched_cutB (b, st, s) = (b == 18) := rfl + +/-- The relations at the first configurations and at each pair of cut points, from what the compiler kept across the pass. -/ +def sched_rels (call : Call) : List (MIR.Lowered.Frame → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call)) ∧ x' = (0, [], State.initial call), + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (j0 : EvmRules.Word), x = ([], MIR.Lowered.Pos.enter 4 23 1, env, s) ∧ x' = (18, [(0 : EvmRules.Word), (0 : EvmRules.Word), env 30, env 2, env 62, j0], s), + fun x x' => ∃ (env : MIR.Lowered.Env) (s : State) (j0 : EvmRules.Word), x = ([], MIR.Lowered.Pos.enter 4 25 1, env, s) ∧ x' = (18, [(1 : EvmRules.Word), env 20, env 30, env 43, env 62, j0], s)] + +theorem sched_mk1 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : Nat × EVM.Stack × State} + (h : ∃ (j0 : EvmRules.Word), y = (18, [(0 : EvmRules.Word), (0 : EvmRules.Word), env 30, env 2, env 62, j0], s)) : + ∃ Q ∈ sched_rels call, Q ([], MIR.Lowered.Pos.enter 4 23 1, env, s) y := by + obtain ⟨j0, h0⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.head _)) ⟨env, s, j0, rfl, h0⟩ + +theorem sched_mk2 {call : Call} {env : MIR.Lowered.Env} {s : State} {y : Nat × EVM.Stack × State} + (h : ∃ (j0 : EvmRules.Word), y = (18, [(1 : EvmRules.Word), env 20, env 30, env 43, env 62, j0], s)) : + ∃ Q ∈ sched_rels call, Q ([], MIR.Lowered.Pos.enter 4 25 1, env, s) y := by + obtain ⟨j0, h0⟩ := h + exact rel_mem (List.Mem.tail _ (List.Mem.tail _ (List.Mem.head _))) ⟨env, s, j0, rfl, h0⟩ + +set_option maxHeartbeats 2000000 in +theorem sched_seg0 (o : Oracle) (call : Call) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ sched_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir1) sched_cutA k ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call))) + (seg (EVM.Program.block o call sched) sched_cutB 45 (0, [], State.initial call)) := by + refine ⟨46, ?_⟩ + sym_seg [sched_cutA_enter, sched_cutA_resume, sched_cutB_mk] [sched_mk1, sched_mk2] + +set_option maxHeartbeats 2000000 in +theorem sched_seg1 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (j0 : EvmRules.Word) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ sched_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir1) sched_cutA k ([], MIR.Lowered.Pos.enter 4 23 1, env, s)) + (seg (EVM.Program.block o call sched) sched_cutB 45 (18, [(0 : EvmRules.Word), (0 : EvmRules.Word), env 30, env 2, env 62, j0], s)) := by + refine ⟨46, ?_⟩ + sym_seg [sched_cutA_enter, sched_cutA_resume, sched_cutB_mk] [sched_mk1, sched_mk2] + +set_option maxHeartbeats 2000000 in +theorem sched_seg2 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) (j0 : EvmRules.Word) : + ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ sched_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir1) sched_cutA k ([], MIR.Lowered.Pos.enter 4 25 1, env, s)) + (seg (EVM.Program.block o call sched) sched_cutB 45 (18, [(1 : EvmRules.Word), env 20, env 30, env 43, env 62, j0], s)) := by + refine ⟨46, ?_⟩ + sym_seg [sched_cutA_enter, sched_cutA_resume, sched_cutB_mk] [sched_mk1, sched_mk2] + +theorem sched_segments (o : Oracle) (call : Call) : + ∀ P ∈ sched_rels call, ∀ x x', P x x' → ∃ k, SegRel Agree (fun y y' => ∃ Q ∈ sched_rels call, Q y y') + (seg (MIR.Lowered.moduleBlock o call mir1) sched_cutA k x) + (seg (EVM.Program.block o call sched) sched_cutB 45 x') := by + intro P mem x x' holds + simp only [sched_rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + exact sched_seg0 o call + · obtain ⟨env, s, j0, rfl, rfl⟩ := holds + exact sched_seg1 o call env s j0 + · obtain ⟨env, s, j0, rfl, rfl⟩ := holds + exact sched_seg2 o call env s j0 + +/-- `mir1` and `sched` simulated through their cut points on every call. -/ +def sched_sim (o : Oracle) : + CutPoint.LayerSim MIR.Lowered.moduleLayer EVM.Program.layer o mir1 sched anyCall where + σ := MIR.Lowered.Frame + τ := Nat × EVM.Stack × State + step call := MIR.Lowered.moduleBlock o call mir1 + step' call := EVM.Program.block o call sched + init call := ([], .enter mir1.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState mir1 (State.initial call)) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := sched_cutA + cut' := sched_cutB + Rel call := fun x x' => ∃ P ∈ sched_rels call, P x x' + start _ _ := ⟨_, List.Mem.head _, rfl, rfl⟩ + sim call _ := CutPoint.Sim.of_each fun P m x x' h => + match sched_segments o call P m x x' h with | ⟨k, s⟩ => ⟨k, 45, s⟩ + +/-- Every segment of `sched` takes at most 45 steps: the bound that carries a loop's +ranking certificate on `mir1` to a step bound on `sched` (`CutPoint.ends_within_sim_start`). -/ +theorem sched_bounded (o : Oracle) (call : Call) : + CutPoint.BoundedSim (MIR.Lowered.moduleBlock o call mir1) sched_cutA + (EVM.Program.block o call sched) sched_cutB Agree + (fun x x' => ∃ P ∈ sched_rels call, P x x') 45 := + fun x x' ⟨P, m, h⟩ => sched_segments o call P m x x' h + +/-- Every end of `mir1` on a call is matched by an agreeing end of `sched`. -/ +theorem sched_certified (o : Oracle) : + Certified MIR.Lowered.moduleLayer EVM.Program.layer o mir1 sched anyCall := + (sched_sim o).certified + +/-- Every end of `sched` on a call is matched by an agreeing end of `mir1`. -/ +theorem sched_certified_back (o : Oracle) : + Certified EVM.Program.layer MIR.Lowered.moduleLayer o sched mir1 anyCall := + (sched_sim o).certified_back + +/-- info: 'SolarTV.Milestone.VerifyCounter.sched_certified' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_certified + +/-- info: 'SolarTV.Milestone.VerifyCounter.sched_certified_back' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_certified_back + +end SolarTV.Milestone.VerifyCounter diff --git a/Certified/verify_counter/Proofs/Stages.lean b/Certified/verify_counter/Proofs/Stages.lean new file mode 100644 index 00000000..5ae95e78 --- /dev/null +++ b/Certified/verify_counter/Proofs/Stages.lean @@ -0,0 +1,55 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import verify_counter.Proofs.Runs.Mir1 +import verify_counter.Proofs.Runs.Sched +import verify_counter.Proofs.Runs.Evm1 +import verify_counter.Proofs.Runs.Evm2 +import verify_counter.Proofs.Runs.Evm3 +import verify_counter.Proofs.Runs.Evm4 +import verify_counter.Proofs.Runs.Evm5 +import verify_counter.Proofs.Runs.Evm6 +import verify_counter.Proofs.Runs.Evm7 +import verify_counter.Proofs.Runs.Evm8 +import verify_counter.Proofs.Runs.Evm9 +import verify_counter.Proofs.Runs.Evm10 +import verify_counter.Proofs.Runs.Evm11 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Counter`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle through cut points, whatever number of times its loops run, and chained from the first lowered MIR `stage0` to the final EVM IR `evm11`, both ways. -/ + +namespace SolarTV.Milestone.VerifyCounter + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1], sched, [evm1, evm2, evm3, evm4, evm5, evm6, evm7, evm8, evm9, evm10, evm11]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, each through cut points, chained by the library's composition, on every call. -/ +theorem verify_counter_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm11 anyCall := + mir_to_evmir_certified o anyCall compilation ⟨mir1_certified o, trivial⟩ (sched_certified o) + ⟨evm1_certified o, evm2_certified o, evm3_certified o, evm4_certified o, evm5_certified o, evm6_certified o, evm7_certified o, evm8_certified o, evm9_certified o, evm10_certified o, evm11_certified o, trivial⟩ + +/-- Every end of the first lowered MIR is matched by an agreeing end of the final EVM IR, on every call. -/ +theorem verify_counter_certified (o : Oracle) : + Certified MIR.Lowered.moduleLayer EVM.Program.layer o stage0 evm11 anyCall := + ((((((((((((mir1_certified o).trans (sched_certified o)).trans (evm1_certified o)).trans (evm2_certified o)).trans (evm3_certified o)).trans (evm4_certified o)).trans (evm5_certified o)).trans (evm6_certified o)).trans (evm7_certified o)).trans (evm8_certified o)).trans (evm9_certified o)).trans (evm10_certified o)).trans (evm11_certified o) + +/-- Every end of the final EVM IR is matched by an agreeing end of the first lowered MIR, on every call: one ends exactly when the other does. -/ +theorem verify_counter_certified_back (o : Oracle) : + Certified EVM.Program.layer MIR.Lowered.moduleLayer o evm11 stage0 anyCall := + ((((((((((((evm11_certified_back o).trans (evm10_certified_back o)).trans (evm9_certified_back o)).trans (evm8_certified_back o)).trans (evm7_certified_back o)).trans (evm6_certified_back o)).trans (evm5_certified_back o)).trans (evm4_certified_back o)).trans (evm3_certified_back o)).trans (evm2_certified_back o)).trans (evm1_certified_back o)).trans (sched_certified_back o)).trans (mir1_certified_back o) + +/-- info: 'SolarTV.Milestone.VerifyCounter.verify_counter_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms verify_counter_mir_to_evmir + +/-- info: 'SolarTV.Milestone.VerifyCounter.verify_counter_certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms verify_counter_certified + +/-- info: 'SolarTV.Milestone.VerifyCounter.verify_counter_certified_back' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms verify_counter_certified_back + +end SolarTV.Milestone.VerifyCounter diff --git a/Certified/verify_counter/Statement.lean b/Certified/verify_counter/Statement.lean new file mode 100644 index 00000000..61dc803a --- /dev/null +++ b/Certified/verify_counter/Statement.lean @@ -0,0 +1,81 @@ +import Verify.Shapes +import Verify.ShapeBundle +import verify_counter.gen.Counter.Spec +import verify_counter.gen.Counter.Bytecode +import Contracts.VerifyCounter.ShapeSource +import Contracts.VerifyCounter.Gas +import Verify.ShapeSpecExport + +-- Generated by solar's tools/certify/final.py from verify_counter/shape.json and the bytecode the +-- driver compiled in this run; do not edit. This module never imports the proof module. + +/-! +# Counter: the published statement + +`Statement` binds the exact runtime bytecode (`runtimeHex`, from the driver's own compile) and +states _root_.SolidCore.Refinement.Shapes.Certified of it against the checked source on the declared valid calls. +-/ + +namespace Certified.verify_counter.Final + +/-- The runtime bytecode the pinned solar emitted in this run, as hex (for the reader). -/ +def runtimeHex : String := + "34603c575f3560e01c806306661abd1460525780636d5433e6146101af578063a4d66daf14605b578063b20eb4c4146073578063d09de08a146065575b5f5ffd5b6011602052634e487b715f526024601cfd5b5f545f5260205ff35b6001545f5260205ff35b5f5460010180156040575f55005b60243610603c576004355f54818101818110604057600154106101d25780816080525f60a0528082820361019a575f5f91925060db565b506080516001840180158583036101675760405780608052600160a05260018301925f191480610182575093505060015b8482105f54808503610111575060aa5760a051815f10828203610152571561010f5750505050608051815f5581810361013e575b005b90506d011100000004000000010000000f939091935b60205260405260605263ed572b275b5f526064601cfd5b6d012100000004000000050000000e610127565b506d012100000004000000040000000c610127565b505090506d0121000000040000000300000008929192610127565b5f6d0102000000040000000a00000012919091610127565b506d010300000004000000070000000b610127565b60443610603c576004356024358082106101cb57505f5260205ff35b5f5260205ff35b636f76657260e01b6004602080526040526060526308c379a061013656" + +/-- The same bytes, as numbers: what the statement binds. -/ +def runtimeBytes : List Nat := + [0x34, 0x60, 0x3c, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x6, 0x66, 0x1a, 0xbd, 0x14, + 0x60, 0x52, 0x57, 0x80, 0x63, 0x6d, 0x54, 0x33, 0xe6, 0x14, 0x61, 0x1, 0xaf, 0x57, 0x80, 0x63, + 0xa4, 0xd6, 0x6d, 0xaf, 0x14, 0x60, 0x5b, 0x57, 0x80, 0x63, 0xb2, 0xe, 0xb4, 0xc4, 0x14, 0x60, + 0x73, 0x57, 0x80, 0x63, 0xd0, 0x9d, 0xe0, 0x8a, 0x14, 0x60, 0x65, 0x57, 0x5b, 0x5f, 0x5f, 0xfd, + 0x5b, 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, 0x60, + 0x1c, 0xfd, 0x5b, 0x5f, 0x54, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x1, 0x54, 0x5f, + 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x5f, 0x54, 0x60, 0x1, 0x1, 0x80, 0x15, 0x60, 0x40, 0x57, + 0x5f, 0x55, 0x0, 0x5b, 0x60, 0x24, 0x36, 0x10, 0x60, 0x3c, 0x57, 0x60, 0x4, 0x35, 0x5f, 0x54, + 0x81, 0x81, 0x1, 0x81, 0x81, 0x10, 0x60, 0x40, 0x57, 0x60, 0x1, 0x54, 0x10, 0x61, 0x1, 0xd2, + 0x57, 0x80, 0x81, 0x60, 0x80, 0x52, 0x5f, 0x60, 0xa0, 0x52, 0x80, 0x82, 0x82, 0x3, 0x61, 0x1, + 0x9a, 0x57, 0x5f, 0x5f, 0x91, 0x92, 0x50, 0x60, 0xdb, 0x56, 0x5b, 0x50, 0x60, 0x80, 0x51, 0x60, + 0x1, 0x84, 0x1, 0x80, 0x15, 0x85, 0x83, 0x3, 0x61, 0x1, 0x67, 0x57, 0x60, 0x40, 0x57, 0x80, + 0x60, 0x80, 0x52, 0x60, 0x1, 0x60, 0xa0, 0x52, 0x60, 0x1, 0x83, 0x1, 0x92, 0x5f, 0x19, 0x14, + 0x80, 0x61, 0x1, 0x82, 0x57, 0x50, 0x93, 0x50, 0x50, 0x60, 0x1, 0x5b, 0x84, 0x82, 0x10, 0x5f, + 0x54, 0x80, 0x85, 0x3, 0x61, 0x1, 0x11, 0x57, 0x50, 0x60, 0xaa, 0x57, 0x60, 0xa0, 0x51, 0x81, + 0x5f, 0x10, 0x82, 0x82, 0x3, 0x61, 0x1, 0x52, 0x57, 0x15, 0x61, 0x1, 0xf, 0x57, 0x50, 0x50, + 0x50, 0x50, 0x60, 0x80, 0x51, 0x81, 0x5f, 0x55, 0x81, 0x81, 0x3, 0x61, 0x1, 0x3e, 0x57, 0x5b, + 0x0, 0x5b, 0x90, 0x50, 0x6d, 0x1, 0x11, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x1, 0x0, + 0x0, 0x0, 0xf, 0x93, 0x90, 0x91, 0x93, 0x5b, 0x60, 0x20, 0x52, 0x60, 0x40, 0x52, 0x60, 0x60, + 0x52, 0x63, 0xed, 0x57, 0x2b, 0x27, 0x5b, 0x5f, 0x52, 0x60, 0x64, 0x60, 0x1c, 0xfd, 0x5b, 0x6d, + 0x1, 0x21, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x5, 0x0, 0x0, 0x0, 0xe, 0x61, 0x1, + 0x27, 0x56, 0x5b, 0x50, 0x6d, 0x1, 0x21, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x4, 0x0, + 0x0, 0x0, 0xc, 0x61, 0x1, 0x27, 0x56, 0x5b, 0x50, 0x50, 0x90, 0x50, 0x6d, 0x1, 0x21, 0x0, + 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x8, 0x92, 0x91, 0x92, 0x61, 0x1, + 0x27, 0x56, 0x5b, 0x5f, 0x6d, 0x1, 0x2, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0xa, 0x0, + 0x0, 0x0, 0x12, 0x91, 0x90, 0x91, 0x61, 0x1, 0x27, 0x56, 0x5b, 0x50, 0x6d, 0x1, 0x3, 0x0, + 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x7, 0x0, 0x0, 0x0, 0xb, 0x61, 0x1, 0x27, 0x56, 0x5b, + 0x60, 0x44, 0x36, 0x10, 0x60, 0x3c, 0x57, 0x60, 0x4, 0x35, 0x60, 0x24, 0x35, 0x80, 0x82, 0x10, + 0x61, 0x1, 0xcb, 0x57, 0x50, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x5f, 0x52, 0x60, 0x20, + 0x5f, 0xf3, 0x5b, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x60, 0xe0, 0x1b, 0x60, 0x4, 0x60, 0x20, 0x80, + 0x52, 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, 0x63, 0x8, 0xc3, 0x79, 0xa0, 0x61, 0x1, 0x36, 0x56] + +/-- The freshly exported bytecode the obligations speak of. -/ +def code : ByteArray := ⟨(_root_.SolarTV.Export.Counter.bytecode.map UInt8.ofNat).toArray⟩ + +/-- The specification and the allowed statuses are not vacuous: some valid call has a result the +specification rejects, and some valid call has a revert the allowed statuses reject. -/ +def NonVacuous : Prop := + (∃ (call : _root_.SolarTV.Call) (obs : _root_.SolarTV.Observable), (Contracts.VerifyCounter.ShapeSource.ValidS) call ∧ ¬ (_root_.SolidCore.Refinement.Shapes.bundlePost _root_.Certified.verify_counter.gen.Counter.Spec.Counter (SolidCore.Refinement.Shapes.ctxOfCall) (SolidCore.Refinement.Shapes.idStep)) call obs) ∧ + (∃ (call : _root_.SolarTV.Call) (obs : _root_.SolarTV.Observable), (Contracts.VerifyCounter.ShapeSource.ValidS) call ∧ obs.success = false ∧ + ¬ (Contracts.VerifyCounter.ShapeSource.Allowed) call obs) + +/-- **The published statement.** -/ +def Statement : Prop := + _root_.Certified.verify_counter.Final.code.data.toList.map (·.toNat) = _root_.Certified.verify_counter.Final.runtimeBytes ∧ + _root_.Certified.verify_counter.Final.NonVacuous ∧ + (∃ c, Contracts.VerifyCounter.Source.contract? = .ok c ∧ + _root_.SolidCore.Refinement.Shapes.Certified (_root_.SolidCore.Refinement.Generic.Loop.solidCoreRuntime (Contracts.VerifyCounter.Source.fuel)) c _root_.Certified.verify_counter.Final.code + (Contracts.VerifyCounter.ShapeSource.ValidS) (Contracts.VerifyCounter.ShapeSource.Allowed) (_root_.SolidCore.Refinement.Shapes.bundlePost _root_.Certified.verify_counter.gen.Counter.Spec.Counter (SolidCore.Refinement.Shapes.ctxOfCall) (SolidCore.Refinement.Shapes.idStep)) (SolarTV.Milestone.VerifyCounter.Bump.gasBound)) + +set_option maxRecDepth 100000 in +theorem bound : _root_.Certified.verify_counter.Final.code.data.toList.map (·.toNat) = _root_.Certified.verify_counter.Final.runtimeBytes := + @of_decide_eq_true _ (instDecidableEqList _ _) (by decide +kernel) + +end Certified.verify_counter.Final diff --git a/Certified/verify_counter/bytecode.hex b/Certified/verify_counter/bytecode.hex new file mode 100644 index 00000000..47e8dcc2 --- /dev/null +++ b/Certified/verify_counter/bytecode.hex @@ -0,0 +1 @@ +34603c575f3560e01c806306661abd1460525780636d5433e6146101af578063a4d66daf14605b578063b20eb4c4146073578063d09de08a146065575b5f5ffd5b6011602052634e487b715f526024601cfd5b5f545f5260205ff35b6001545f5260205ff35b5f5460010180156040575f55005b60243610603c576004355f54818101818110604057600154106101d25780816080525f60a0528082820361019a575f5f91925060db565b506080516001840180158583036101675760405780608052600160a05260018301925f191480610182575093505060015b8482105f54808503610111575060aa5760a051815f10828203610152571561010f5750505050608051815f5581810361013e575b005b90506d011100000004000000010000000f939091935b60205260405260605263ed572b275b5f526064601cfd5b6d012100000004000000050000000e610127565b506d012100000004000000040000000c610127565b505090506d0121000000040000000300000008929192610127565b5f6d0102000000040000000a00000012919091610127565b506d010300000004000000070000000b610127565b60443610603c576004356024358082106101cb57505f5260205ff35b5f5260205ff35b636f76657260e01b6004602080526040526060526308c379a061013656 diff --git a/Certified/verify_counter/gen/Counter/Bytecode.lean b/Certified/verify_counter/gen/Counter/Bytecode.lean new file mode 100644 index 00000000..dab23e9a --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Bytecode.lean @@ -0,0 +1,44 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x3c, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x06, 0x66, 0x1a, 0xbd, 0x14, + 0x60, 0x52, 0x57, 0x80, 0x63, 0x6d, 0x54, 0x33, 0xe6, 0x14, 0x61, 0x01, 0xaf, 0x57, 0x80, 0x63, + 0xa4, 0xd6, 0x6d, 0xaf, 0x14, 0x60, 0x5b, 0x57, 0x80, 0x63, 0xb2, 0x0e, 0xb4, 0xc4, 0x14, 0x60, + 0x73, 0x57, 0x80, 0x63, 0xd0, 0x9d, 0xe0, 0x8a, 0x14, 0x60, 0x65, 0x57, 0x5b, 0x5f, 0x5f, 0xfd, + 0x5b, 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, 0x60, + 0x1c, 0xfd, 0x5b, 0x5f, 0x54, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x01, 0x54, 0x5f, + 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x5f, 0x54, 0x60, 0x01, 0x01, 0x80, 0x15, 0x60, 0x40, 0x57, + 0x5f, 0x55, 0x00, 0x5b, 0x60, 0x24, 0x36, 0x10, 0x60, 0x3c, 0x57, 0x60, 0x04, 0x35, 0x5f, 0x54, + 0x81, 0x81, 0x01, 0x81, 0x81, 0x10, 0x60, 0x40, 0x57, 0x60, 0x01, 0x54, 0x10, 0x61, 0x01, 0xd2, + 0x57, 0x80, 0x81, 0x60, 0x80, 0x52, 0x5f, 0x60, 0xa0, 0x52, 0x80, 0x82, 0x82, 0x03, 0x61, 0x01, + 0x9a, 0x57, 0x5f, 0x5f, 0x91, 0x92, 0x50, 0x60, 0xdb, 0x56, 0x5b, 0x50, 0x60, 0x80, 0x51, 0x60, + 0x01, 0x84, 0x01, 0x80, 0x15, 0x85, 0x83, 0x03, 0x61, 0x01, 0x67, 0x57, 0x60, 0x40, 0x57, 0x80, + 0x60, 0x80, 0x52, 0x60, 0x01, 0x60, 0xa0, 0x52, 0x60, 0x01, 0x83, 0x01, 0x92, 0x5f, 0x19, 0x14, + 0x80, 0x61, 0x01, 0x82, 0x57, 0x50, 0x93, 0x50, 0x50, 0x60, 0x01, 0x5b, 0x84, 0x82, 0x10, 0x5f, + 0x54, 0x80, 0x85, 0x03, 0x61, 0x01, 0x11, 0x57, 0x50, 0x60, 0xaa, 0x57, 0x60, 0xa0, 0x51, 0x81, + 0x5f, 0x10, 0x82, 0x82, 0x03, 0x61, 0x01, 0x52, 0x57, 0x15, 0x61, 0x01, 0x0f, 0x57, 0x50, 0x50, + 0x50, 0x50, 0x60, 0x80, 0x51, 0x81, 0x5f, 0x55, 0x81, 0x81, 0x03, 0x61, 0x01, 0x3e, 0x57, 0x5b, + 0x00, 0x5b, 0x90, 0x50, 0x6d, 0x01, 0x11, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, + 0x00, 0x00, 0x0f, 0x93, 0x90, 0x91, 0x93, 0x5b, 0x60, 0x20, 0x52, 0x60, 0x40, 0x52, 0x60, 0x60, + 0x52, 0x63, 0xed, 0x57, 0x2b, 0x27, 0x5b, 0x5f, 0x52, 0x60, 0x64, 0x60, 0x1c, 0xfd, 0x5b, 0x6d, + 0x01, 0x21, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x0e, 0x61, 0x01, + 0x27, 0x56, 0x5b, 0x50, 0x6d, 0x01, 0x21, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, + 0x00, 0x00, 0x0c, 0x61, 0x01, 0x27, 0x56, 0x5b, 0x50, 0x50, 0x90, 0x50, 0x6d, 0x01, 0x21, 0x00, + 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x08, 0x92, 0x91, 0x92, 0x61, 0x01, + 0x27, 0x56, 0x5b, 0x5f, 0x6d, 0x01, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x0a, 0x00, + 0x00, 0x00, 0x12, 0x91, 0x90, 0x91, 0x61, 0x01, 0x27, 0x56, 0x5b, 0x50, 0x6d, 0x01, 0x03, 0x00, + 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x0b, 0x61, 0x01, 0x27, 0x56, 0x5b, + 0x60, 0x44, 0x36, 0x10, 0x60, 0x3c, 0x57, 0x60, 0x04, 0x35, 0x60, 0x24, 0x35, 0x80, 0x82, 0x10, + 0x61, 0x01, 0xcb, 0x57, 0x50, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x5f, 0x52, 0x60, 0x20, + 0x5f, 0xf3, 0x5b, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x60, 0xe0, 0x1b, 0x60, 0x04, 0x60, 0x20, 0x80, + 0x52, 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, 0x63, 0x08, 0xc3, 0x79, 0xa0, 0x61, 0x01, 0x36, 0x56] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "34603c575f3560e01c806306661abd1460525780636d5433e6146101af578063a4d66daf14605b578063b20eb4c4146073578063d09de08a146065575b5f5ffd5b6011602052634e487b715f526024601cfd5b5f545f5260205ff35b6001545f5260205ff35b5f5460010180156040575f55005b60243610603c576004355f54818101818110604057600154106101d25780816080525f60a0528082820361019a575f5f91925060db565b506080516001840180158583036101675760405780608052600160a05260018301925f191480610182575093505060015b8482105f54808503610111575060aa5760a051815f10828203610152571561010f5750505050608051815f5581810361013e575b005b90506d011100000004000000010000000f939091935b60205260405260605263ed572b275b5f526064601cfd5b6d012100000004000000050000000e610127565b506d012100000004000000040000000c610127565b505090506d0121000000040000000300000008929192610127565b5f6d0102000000040000000a00000012919091610127565b506d010300000004000000070000000b610127565b60443610603c576004356024358082106101cb57505f5260205ff35b5f5260205ff35b636f76657260e01b6004602080526040526060526308c379a061013656" + +end SolarTV.Export.Counter diff --git a/Certified/verify_counter/gen/Counter/Evm1.lean b/Certified/verify_counter/gen/Counter/Evm1.lean new file mode 100644 index 00000000..39f1bf47 --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Evm1.lean @@ -0,0 +1,347 @@ +-- solar-lean-stage: kind=evm index=1 pass=peephole-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `peephole-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 7, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6661abd)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d5433e6)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa4d66daf)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb20eb4c4)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0xd09de08a)), + .op (.stack .eq), + .jumpi 2, + .jump 7], + -- bb2 + [.jump 10], + -- bb3 + [.jump 13], + -- bb4 + [.jump 9], + -- bb5 + [.jump 38], + -- bb6 + [.jump 8], + -- bb7 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 12, + .jump 11], + -- bb11 + [.op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb12 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb13 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 37, + .jump 14], + -- bb14 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 36, + .jump 15], + -- bb15 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack .lt), + .jumpi 35, + .jump 16], + -- bb16 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 33, + .jump 17], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 18], + -- bb18 + [.op (.stack (.dup 4)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 20, + .jump 19], + -- bb19 + [.op (.stack .pop), + .jumpi 27, + .jump 21], + -- bb20 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x11100000004000000010000000f)), + .op (.stack (.swap 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 34], + -- bb21 + [.op (.stack (.push 160)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 26, + .jump 22], + -- bb22 + [.op (.stack .iszero), + .jumpi 24, + .jump 23], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 25, + .jump 24], + -- bb24 + [.stop], + -- bb25 + [.op (.stack (.push 0x12100000004000000050000000e)), + .jump 34], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x12100000004000000040000000c)), + .jump 34], + -- bb27 + [.op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.push 1)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .op (.stack (.dup 5)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 31, + .jump 28], + -- bb28 + [.jumpi 36, + .jump 29], + -- bb29 + [.op (.stack (.dup 0)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.dup 3)), + .op (.stack .add), + .op (.stack (.swap 2)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 32, + .jump 30], + -- bb30 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.push 1)), + .jump 18], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x121000000040000000300000008)), + .op (.stack (.swap 2)), + .op (.stack (.swap 1)), + .op (.stack (.swap 2)), + .jump 34], + -- bb32 + [.op (.stack (.push 0)), + .op (.stack (.push 0x102000000040000000a00000012)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 34], + -- bb33 + [.op (.stack .pop), + .op (.stack (.push 0x10300000004000000070000000b)), + .jump 34], + -- bb34 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb35 + [.op (.stack (.push 0x6f76657200000000000000000000000000000000000000000000000000000000)), + .op (.stack (.push 4)), + .jump 43], + -- bb36 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb37 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb38 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 42, + .jump 39], + -- bb39 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 41, + .jump 40], + -- bb40 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb41 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb42 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb43 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Counter diff --git a/Certified/verify_counter/gen/Counter/Evm10.lean b/Certified/verify_counter/gen/Counter/Evm10.lean new file mode 100644 index 00000000..578f0096 --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Evm10.lean @@ -0,0 +1,284 @@ +-- solar-lean-stage: kind=evm index=10 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `block-layout`. -/ +def evm10 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6661abd)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d5433e6)), + .op (.stack .eq), + .jumpi 18, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa4d66daf)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb20eb4c4)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0xd09de08a)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb7 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb36 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 2, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb13 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack .lt), + .jumpi 20, + .op (.stack (.dup 0)), + .op (.stack (.dup 1)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 2)), + .op (.stack .pop), + .jump 7], + -- bb18 + [.op (.stack (.dup 4)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 9, + .op (.stack .pop), + .jumpi 14, + .op (.stack (.push 160)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 13, + .op (.stack .iszero), + .jumpi 8, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 12, + .jump 8], + -- bb24 + [.stop], + -- bb20 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x11100000004000000010000000f)), + .op (.stack (.swap 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 10], + -- bb34 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .jump 11], + -- bb42 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb25 + [.op (.stack (.push 0x12100000004000000050000000e)), + .jump 10], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x12100000004000000040000000c)), + .jump 10], + -- bb27 + [.op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.push 1)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .op (.stack (.dup 5)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 15, + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.dup 3)), + .op (.stack .add), + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 16, + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 1)), + .jump 7], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x121000000040000000300000008)), + .op (.stack (.swap 2)), + .op (.stack (.swap 1)), + .op (.stack (.swap 2)), + .jump 10], + -- bb32 + [.op (.stack (.push 0)), + .op (.stack (.push 0x102000000040000000a00000012)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 10], + -- bb33 + [.op (.stack .pop), + .op (.stack (.push 0x10300000004000000070000000b)), + .jump 10], + -- bb38 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 19, + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb41 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb35 + [.op (.stack (.push 0x6f766572)), + .op (.stack (.push 224)), + .op (.stack .shl), + .op (.stack (.push 4)), + .op (.stack (.push 32)), + .op (.stack (.dup 0)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .jump 11]] } + +end SolarTV.Export.Counter diff --git a/Certified/verify_counter/gen/Counter/Evm11.lean b/Certified/verify_counter/gen/Counter/Evm11.lean new file mode 100644 index 00000000..2888a442 --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Evm11.lean @@ -0,0 +1,284 @@ +-- solar-lean-stage: kind=evm index=11 pass=loop-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `loop-layout`. -/ +def evm11 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6661abd)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d5433e6)), + .op (.stack .eq), + .jumpi 18, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa4d66daf)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb20eb4c4)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0xd09de08a)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb7 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb36 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 2, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb13 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack .lt), + .jumpi 20, + .op (.stack (.dup 0)), + .op (.stack (.dup 1)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 2)), + .op (.stack .pop), + .jump 8], + -- bb27 + [.op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.push 1)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .op (.stack (.dup 5)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 15, + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.dup 3)), + .op (.stack .add), + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 16, + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 1)), + .jump 8], + -- bb18 + [.op (.stack (.dup 4)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 10, + .op (.stack .pop), + .jumpi 7, + .op (.stack (.push 160)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 14, + .op (.stack .iszero), + .jumpi 9, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 13, + .jump 9], + -- bb24 + [.stop], + -- bb20 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x11100000004000000010000000f)), + .op (.stack (.swap 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 11], + -- bb34 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .jump 12], + -- bb42 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb25 + [.op (.stack (.push 0x12100000004000000050000000e)), + .jump 11], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x12100000004000000040000000c)), + .jump 11], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x121000000040000000300000008)), + .op (.stack (.swap 2)), + .op (.stack (.swap 1)), + .op (.stack (.swap 2)), + .jump 11], + -- bb32 + [.op (.stack (.push 0)), + .op (.stack (.push 0x102000000040000000a00000012)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 11], + -- bb33 + [.op (.stack .pop), + .op (.stack (.push 0x10300000004000000070000000b)), + .jump 11], + -- bb38 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 19, + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb41 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb35 + [.op (.stack (.push 0x6f766572)), + .op (.stack (.push 224)), + .op (.stack .shl), + .op (.stack (.push 4)), + .op (.stack (.push 32)), + .op (.stack (.dup 0)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .jump 12]] } + +end SolarTV.Export.Counter diff --git a/Certified/verify_counter/gen/Counter/Evm2.lean b/Certified/verify_counter/gen/Counter/Evm2.lean new file mode 100644 index 00000000..39564e93 --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Evm2.lean @@ -0,0 +1,305 @@ +-- solar-lean-stage: kind=evm index=2 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6661abd)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d5433e6)), + .op (.stack .eq), + .jumpi 20, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa4d66daf)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb20eb4c4)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0xd09de08a)), + .op (.stack .eq), + .jumpi 4, + .jump 1], + -- bb7 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb12 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb13 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 19, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 18, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack .lt), + .jumpi 17, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 15, + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 7], + -- bb18 + [.op (.stack (.dup 4)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 8, + .op (.stack .pop), + .jumpi 12, + .op (.stack (.push 160)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 11, + .op (.stack .iszero), + .jumpi 9, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 10, + .jump 9], + -- bb20 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x11100000004000000010000000f)), + .op (.stack (.swap 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 16], + -- bb24 + [.stop], + -- bb25 + [.op (.stack (.push 0x12100000004000000050000000e)), + .jump 16], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x12100000004000000040000000c)), + .jump 16], + -- bb27 + [.op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.push 1)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .op (.stack (.dup 5)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 13, + .jumpi 18, + .op (.stack (.dup 0)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.dup 3)), + .op (.stack .add), + .op (.stack (.swap 2)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 14, + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.push 1)), + .jump 7], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x121000000040000000300000008)), + .op (.stack (.swap 2)), + .op (.stack (.swap 1)), + .op (.stack (.swap 2)), + .jump 16], + -- bb32 + [.op (.stack (.push 0)), + .op (.stack (.push 0x102000000040000000a00000012)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 16], + -- bb33 + [.op (.stack .pop), + .op (.stack (.push 0x10300000004000000070000000b)), + .jump 16], + -- bb34 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb35 + [.op (.stack (.push 0x6f76657200000000000000000000000000000000000000000000000000000000)), + .op (.stack (.push 4)), + .op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb36 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb37 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb38 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 22, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 21, + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb41 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb42 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Counter diff --git a/Certified/verify_counter/gen/Counter/Evm3.lean b/Certified/verify_counter/gen/Counter/Evm3.lean new file mode 100644 index 00000000..54638d2f --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Evm3.lean @@ -0,0 +1,308 @@ +-- solar-lean-stage: kind=evm index=3 pass=compact-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `compact-pushes`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6661abd)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d5433e6)), + .op (.stack .eq), + .jumpi 20, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa4d66daf)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb20eb4c4)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0xd09de08a)), + .op (.stack .eq), + .jumpi 4, + .jump 1], + -- bb7 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 5, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb12 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb13 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 19, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 18, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack .lt), + .jumpi 17, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 15, + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 7], + -- bb18 + [.op (.stack (.dup 4)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 8, + .op (.stack .pop), + .jumpi 12, + .op (.stack (.push 160)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 11, + .op (.stack .iszero), + .jumpi 9, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 10, + .jump 9], + -- bb20 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x11100000004000000010000000f)), + .op (.stack (.swap 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 16], + -- bb24 + [.stop], + -- bb25 + [.op (.stack (.push 0x12100000004000000050000000e)), + .jump 16], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x12100000004000000040000000c)), + .jump 16], + -- bb27 + [.op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.push 1)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .op (.stack (.dup 5)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 13, + .jumpi 18, + .op (.stack (.dup 0)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.dup 3)), + .op (.stack .add), + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 14, + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.push 1)), + .jump 7], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x121000000040000000300000008)), + .op (.stack (.swap 2)), + .op (.stack (.swap 1)), + .op (.stack (.swap 2)), + .jump 16], + -- bb32 + [.op (.stack (.push 0)), + .op (.stack (.push 0x102000000040000000a00000012)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 16], + -- bb33 + [.op (.stack .pop), + .op (.stack (.push 0x10300000004000000070000000b)), + .jump 16], + -- bb34 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb35 + [.op (.stack (.push 0x6f766572)), + .op (.stack (.push 224)), + .op (.stack .shl), + .op (.stack (.push 4)), + .op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb36 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb37 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb38 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 22, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 21, + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb41 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb42 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Counter diff --git a/Certified/verify_counter/gen/Counter/Evm4.lean b/Certified/verify_counter/gen/Counter/Evm4.lean new file mode 100644 index 00000000..4e596fd1 --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Evm4.lean @@ -0,0 +1,308 @@ +-- solar-lean-stage: kind=evm index=4 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `block-layout`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6661abd)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d5433e6)), + .op (.stack .eq), + .jumpi 17, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa4d66daf)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb20eb4c4)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0xd09de08a)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb7 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb36 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 19, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb13 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 21, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack .lt), + .jumpi 20, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 16, + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 7], + -- bb18 + [.op (.stack (.dup 4)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 9, + .op (.stack .pop), + .jumpi 13, + .op (.stack (.push 160)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 12, + .op (.stack .iszero), + .jumpi 8, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 11, + .jump 8], + -- bb24 + [.stop], + -- bb20 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x11100000004000000010000000f)), + .op (.stack (.swap 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 10], + -- bb34 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb25 + [.op (.stack (.push 0x12100000004000000050000000e)), + .jump 10], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x12100000004000000040000000c)), + .jump 10], + -- bb27 + [.op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.push 1)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .op (.stack (.dup 5)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 14, + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.dup 3)), + .op (.stack .add), + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.push 1)), + .jump 7], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x121000000040000000300000008)), + .op (.stack (.swap 2)), + .op (.stack (.swap 1)), + .op (.stack (.swap 2)), + .jump 10], + -- bb32 + [.op (.stack (.push 0)), + .op (.stack (.push 0x102000000040000000a00000012)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 10], + -- bb33 + [.op (.stack .pop), + .op (.stack (.push 0x10300000004000000070000000b)), + .jump 10], + -- bb38 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 22, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 18, + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb41 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb35 + [.op (.stack (.push 0x6f766572)), + .op (.stack (.push 224)), + .op (.stack .shl), + .op (.stack (.push 4)), + .op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb37 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb42 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Counter diff --git a/Certified/verify_counter/gen/Counter/Evm5.lean b/Certified/verify_counter/gen/Counter/Evm5.lean new file mode 100644 index 00000000..32a427ed --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Evm5.lean @@ -0,0 +1,296 @@ +-- solar-lean-stage: kind=evm index=5 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6661abd)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d5433e6)), + .op (.stack .eq), + .jumpi 17, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa4d66daf)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb20eb4c4)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0xd09de08a)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb7 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb36 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 19, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb13 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 21, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack .lt), + .jumpi 20, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 16, + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 7], + -- bb18 + [.op (.stack (.dup 4)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 9, + .op (.stack .pop), + .jumpi 13, + .op (.stack (.push 160)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 12, + .op (.stack .iszero), + .jumpi 8, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 11, + .jump 8], + -- bb24 + [.stop], + -- bb20 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x11100000004000000010000000f)), + .op (.stack (.swap 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 10], + -- bb34 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb25 + [.op (.stack (.push 0x12100000004000000050000000e)), + .jump 10], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x12100000004000000040000000c)), + .jump 10], + -- bb27 + [.op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.push 1)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .op (.stack (.dup 5)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 14, + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.dup 3)), + .op (.stack .add), + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.push 1)), + .jump 7], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x121000000040000000300000008)), + .op (.stack (.swap 2)), + .op (.stack (.swap 1)), + .op (.stack (.swap 2)), + .jump 10], + -- bb32 + [.op (.stack (.push 0)), + .op (.stack (.push 0x102000000040000000a00000012)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 10], + -- bb33 + [.op (.stack .pop), + .op (.stack (.push 0x10300000004000000070000000b)), + .jump 10], + -- bb38 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 22, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 18, + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb41 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.jump 2], + -- bb35 + [.op (.stack (.push 0x6f766572)), + .op (.stack (.push 224)), + .op (.stack .shl), + .op (.stack (.push 4)), + .op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb37 + [.jump 1], + -- bb42 + [.jump 1]] } + +end SolarTV.Export.Counter diff --git a/Certified/verify_counter/gen/Counter/Evm6.lean b/Certified/verify_counter/gen/Counter/Evm6.lean new file mode 100644 index 00000000..913f69e5 --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Evm6.lean @@ -0,0 +1,290 @@ +-- solar-lean-stage: kind=evm index=6 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm6 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6661abd)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d5433e6)), + .op (.stack .eq), + .jumpi 17, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa4d66daf)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb20eb4c4)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0xd09de08a)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb7 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb36 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 2, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb13 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack .lt), + .jumpi 19, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 16, + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 7], + -- bb18 + [.op (.stack (.dup 4)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 9, + .op (.stack .pop), + .jumpi 13, + .op (.stack (.push 160)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 12, + .op (.stack .iszero), + .jumpi 8, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 11, + .jump 8], + -- bb24 + [.stop], + -- bb20 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x11100000004000000010000000f)), + .op (.stack (.swap 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 10], + -- bb34 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb25 + [.op (.stack (.push 0x12100000004000000050000000e)), + .jump 10], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x12100000004000000040000000c)), + .jump 10], + -- bb27 + [.op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.push 1)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .op (.stack (.dup 5)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 14, + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.dup 3)), + .op (.stack .add), + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.push 1)), + .jump 7], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x121000000040000000300000008)), + .op (.stack (.swap 2)), + .op (.stack (.swap 1)), + .op (.stack (.swap 2)), + .jump 10], + -- bb32 + [.op (.stack (.push 0)), + .op (.stack (.push 0x102000000040000000a00000012)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 10], + -- bb33 + [.op (.stack .pop), + .op (.stack (.push 0x10300000004000000070000000b)), + .jump 10], + -- bb38 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 18, + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb41 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb35 + [.op (.stack (.push 0x6f766572)), + .op (.stack (.push 224)), + .op (.stack .shl), + .op (.stack (.push 4)), + .op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Counter diff --git a/Certified/verify_counter/gen/Counter/Evm7.lean b/Certified/verify_counter/gen/Counter/Evm7.lean new file mode 100644 index 00000000..f88d6dae --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Evm7.lean @@ -0,0 +1,288 @@ +-- solar-lean-stage: kind=evm index=7 pass=tail-merge +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `tail-merge`. -/ +def evm7 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6661abd)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d5433e6)), + .op (.stack .eq), + .jumpi 17, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa4d66daf)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb20eb4c4)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0xd09de08a)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb7 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb36 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 2, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb13 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack .lt), + .jumpi 19, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 16, + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 7], + -- bb18 + [.op (.stack (.dup 4)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 9, + .op (.stack .pop), + .jumpi 13, + .op (.stack (.push 160)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 12, + .op (.stack .iszero), + .jumpi 8, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 11, + .jump 8], + -- bb24 + [.stop], + -- bb20 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x11100000004000000010000000f)), + .op (.stack (.swap 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 10], + -- bb34 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .jump 20], + -- bb25 + [.op (.stack (.push 0x12100000004000000050000000e)), + .jump 10], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x12100000004000000040000000c)), + .jump 10], + -- bb27 + [.op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.push 1)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .op (.stack (.dup 5)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 14, + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.dup 3)), + .op (.stack .add), + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.push 1)), + .jump 7], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x121000000040000000300000008)), + .op (.stack (.swap 2)), + .op (.stack (.swap 1)), + .op (.stack (.swap 2)), + .jump 10], + -- bb32 + [.op (.stack (.push 0)), + .op (.stack (.push 0x102000000040000000a00000012)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 10], + -- bb33 + [.op (.stack .pop), + .op (.stack (.push 0x10300000004000000070000000b)), + .jump 10], + -- bb38 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 18, + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb41 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb35 + [.op (.stack (.push 0x6f766572)), + .op (.stack (.push 224)), + .op (.stack .shl), + .op (.stack (.push 4)), + .op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .jump 20], + -- bb42 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Counter diff --git a/Certified/verify_counter/gen/Counter/Evm8.lean b/Certified/verify_counter/gen/Counter/Evm8.lean new file mode 100644 index 00000000..5dc8338a --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Evm8.lean @@ -0,0 +1,286 @@ +-- solar-lean-stage: kind=evm index=8 pass=block-cse +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `block-cse`. -/ +def evm8 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6661abd)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d5433e6)), + .op (.stack .eq), + .jumpi 17, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa4d66daf)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb20eb4c4)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0xd09de08a)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb7 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb36 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 2, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb13 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack .lt), + .jumpi 19, + .op (.stack (.dup 0)), + .op (.stack (.dup 1)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 16, + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 7], + -- bb18 + [.op (.stack (.dup 4)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 9, + .op (.stack .pop), + .jumpi 13, + .op (.stack (.push 160)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 12, + .op (.stack .iszero), + .jumpi 8, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 11, + .jump 8], + -- bb24 + [.stop], + -- bb20 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x11100000004000000010000000f)), + .op (.stack (.swap 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 10], + -- bb34 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .jump 20], + -- bb25 + [.op (.stack (.push 0x12100000004000000050000000e)), + .jump 10], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x12100000004000000040000000c)), + .jump 10], + -- bb27 + [.op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.push 1)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .op (.stack (.dup 5)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 14, + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.dup 3)), + .op (.stack .add), + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.push 1)), + .jump 7], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x121000000040000000300000008)), + .op (.stack (.swap 2)), + .op (.stack (.swap 1)), + .op (.stack (.swap 2)), + .jump 10], + -- bb32 + [.op (.stack (.push 0)), + .op (.stack (.push 0x102000000040000000a00000012)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 10], + -- bb33 + [.op (.stack .pop), + .op (.stack (.push 0x10300000004000000070000000b)), + .jump 10], + -- bb38 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 18, + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb41 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb35 + [.op (.stack (.push 0x6f766572)), + .op (.stack (.push 224)), + .op (.stack .shl), + .op (.stack (.push 4)), + .op (.stack (.push 32)), + .op (.stack (.dup 0)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .jump 20], + -- bb42 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Counter diff --git a/Certified/verify_counter/gen/Counter/Evm9.lean b/Certified/verify_counter/gen/Counter/Evm9.lean new file mode 100644 index 00000000..512b2c74 --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Evm9.lean @@ -0,0 +1,284 @@ +-- solar-lean-stage: kind=evm index=9 pass=stack-normalize +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR after `stack-normalize`. -/ +def evm9 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6661abd)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d5433e6)), + .op (.stack .eq), + .jumpi 17, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa4d66daf)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb20eb4c4)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0xd09de08a)), + .op (.stack .eq), + .jumpi 5, + .jump 1], + -- bb7 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb36 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 2, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb13 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack .lt), + .jumpi 19, + .op (.stack (.dup 0)), + .op (.stack (.dup 1)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 16, + .op (.stack (.push 0)), + .op (.stack (.push 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 2)), + .op (.stack .pop), + .jump 7], + -- bb18 + [.op (.stack (.dup 4)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 5)), + .op (.stack .sub), + .jumpi 9, + .op (.stack .pop), + .jumpi 13, + .op (.stack (.push 160)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 12, + .op (.stack .iszero), + .jumpi 8, + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 11, + .jump 8], + -- bb24 + [.stop], + -- bb20 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x11100000004000000010000000f)), + .op (.stack (.swap 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 10], + -- bb34 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .jump 20], + -- bb25 + [.op (.stack (.push 0x12100000004000000050000000e)), + .jump 10], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x12100000004000000040000000c)), + .jump 10], + -- bb27 + [.op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.push 1)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .op (.stack (.dup 5)), + .op (.stack (.dup 3)), + .op (.stack .sub), + .jumpi 14, + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.dup 3)), + .op (.stack .add), + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack .pop), + .op (.stack (.swap 3)), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 1)), + .jump 7], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x121000000040000000300000008)), + .op (.stack (.swap 2)), + .op (.stack (.swap 1)), + .op (.stack (.swap 2)), + .jump 10], + -- bb32 + [.op (.stack (.push 0)), + .op (.stack (.push 0x102000000040000000a00000012)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 10], + -- bb33 + [.op (.stack .pop), + .op (.stack (.push 0x10300000004000000070000000b)), + .jump 10], + -- bb38 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 18, + .op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb41 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb35 + [.op (.stack (.push 0x6f766572)), + .op (.stack (.push 224)), + .op (.stack .shl), + .op (.stack (.push 4)), + .op (.stack (.push 32)), + .op (.stack (.dup 0)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .jump 20], + -- bb42 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Counter diff --git a/Certified/verify_counter/gen/Counter/Manifest.lean b/Certified/verify_counter/gen/Counter/Manifest.lean new file mode 100644 index 00000000..1aba141f --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Manifest.lean @@ -0,0 +1,49 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Counter.Manifest + +def sources : List (String × String) := + [("Certified/verify_counter/verify_counter.sol", "f1c87a334b8db31fc8f80541febeaf8617318d20b685634f44e26c74146ad326")] + +def compiler : String := "0.8.38+commit.9aea5229.solar.0.3.0-dev" + +def arguments : List String := + ["Certified/verify_counter/verify_counter.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/verify_counter/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "656d00f214539eeaa141a32cf03260162058e19bb0ba268dd260f06ee750b8f0"), + ("Mir1", "mir1", "lower-assumes", "4148e76c786c2c789fa6406554802afb17396a9b4c64cac88c222d0ef473e2ec"), + ("Sched", "sched", "stack-schedule", "9c786268ecfa4bcfb528b33ba84078ab3bb149731c437ff049174efd08a6efa8"), + ("Evm1", "evm1", "peephole-early", "eeb77872db3bfb3ba5d70ecf0ad642c5f3b07365141022dca569643df4e3a64c"), + ("Evm2", "evm2", "cfg-simplify-early", "2dadc7ece271f11f114461bbf5e86129a29d6437aa12a6fc419cd94b0781fea2"), + ("Evm3", "evm3", "compact-pushes", "992a3c13079318558dda80965d13feba69246a1eb80d8f3b217608b9a5502d3f"), + ("Evm4", "evm4", "block-layout", "712fb37d047bc02661cd67cbbf0687bb75d27d18e90a975b034383f5718b5c42"), + ("Evm5", "evm5", "terminal-dedup", "c6f7e76d48ebf1ec8e5540dc28c466f5748eab1dd843bf19c5586a8c1e08b6d3"), + ("Evm6", "evm6", "cfg-simplify-early", "99964e04dc786304a3edca4025dea0676d283c64efed12cdc2d6300a0c940e72"), + ("Evm7", "evm7", "tail-merge", "03b4a54e4df8a3afde11cd80577df69f48cfcddc72a81099ac31139e01383a20"), + ("Evm8", "evm8", "block-cse", "77171ebac3ccb7b05c885642afe4a874a679302f2691ce170c3cc7c156faab51"), + ("Evm9", "evm9", "stack-normalize", "90cfd88740d3f5279b2750f2184f001e75bc15e7fad84a0609336768478fca59"), + ("Evm10", "evm10", "block-layout", "8fb28ec686a5e55940778cccff0d8c8f4c3bd4fc7adcad5a177e4bad2472cd85"), + ("Evm11", "evm11", "loop-layout", "f70f678e80e80283f0ca6de824d88793e77f0688e62a8205818b280fd06085b7"), + ("Bytecode", "bytecode", "assemble", "fc71a0161d4f5d4951d881a578f3b44966305a115e6ec32c226a58f588fe5345")] + +def bytecodeHex : String := + "34603c575f3560e01c806306661abd1460525780636d5433e6146101af578063a4d66daf14605b578063b20eb4c4146073578063d09de08a146065575b5f5ffd5b6011602052634e487b715f526024601cfd5b5f545f5260205ff35b6001545f5260205ff35b5f5460010180156040575f55005b60243610603c576004355f54818101818110604057600154106101d25780816080525f60a0528082820361019a575f5f91925060db565b506080516001840180158583036101675760405780608052600160a05260018301925f191480610182575093505060015b8482105f54808503610111575060aa5760a051815f10828203610152571561010f5750505050608051815f5581810361013e575b005b90506d011100000004000000010000000f939091935b60205260405260605263ed572b275b5f526064601cfd5b6d012100000004000000050000000e610127565b506d012100000004000000040000000c610127565b505090506d0121000000040000000300000008929192610127565b5f6d0102000000040000000a00000012919091610127565b506d010300000004000000070000000b610127565b60443610603c576004356024358082106101cb57505f5260205ff35b5f5260205ff35b636f76657260e01b6004602080526040526060526308c379a061013656" + +def bytecodeSha256 : String := "d74a847b897f855f93daf2805937efe40aec636c2ec3ca0c2d4ca6d21f214cc1" + +end SolarTV.Export.Counter.Manifest diff --git a/Certified/verify_counter/gen/Counter/Mir1.lean b/Certified/verify_counter/gen/Counter/Mir1.lean new file mode 100644 index 00000000..ad05b6f2 --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Mir1.lean @@ -0,0 +1,256 @@ +-- solar-lean-stage: kind=mir index=1 pass=lower-assumes +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The lowered MIR module after `lower-assumes`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 7, + functions := [ + -- @count + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 0], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @limit + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 1], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @increment + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 0], + .pure 4 .add [.value 2, .const 1], + .pure 5 .eq [.value 4, .const 0]], + .branch (.value 5) 1 2⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 0, .value 4]], + .stop⟩] }, + -- @bump + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 58) .calldatasize [], + .pure 60 .lt [.value 58, .const 36]], + .branch (.value 60) 11 12⟩, + -- bb1 + ⟨[(13, [(23, .const 0), (25, .value 20)]), (55, [(23, .value 2), (25, .value 43)]), (56, [(23, .const 0), (25, .const 1)])], + [.pure 14 .lt [.value 13, .value 62], + .effect (some 31) .sload [.const 0], + .ne 67 (.value 30) (.value 31)], + .branch (.value 67) 14 15⟩, + -- bb2 + ⟨[], + [], + .stop⟩, + -- bb3 + ⟨[], + [.effect (some 16) .mload [.const 128], + .pure 43 .add [.value 55, .const 1], + .pure 44 .eq [.value 43, .const 0], + .ne 69 (.value 16) (.value 55)], + .branch (.value 69) 16 17⟩, + -- bb4 + ⟨[], + [.effect (some 26) .mload [.const 160], + .ne 28 (.value 56) (.const 0), + .ne 71 (.value 26) (.value 56)], + .branch (.value 71) 18 19⟩, + -- bb5 + ⟨[], + [.effect (some 29) .mload [.const 128], + .effect none .sstore [.const 0, .value 55], + .ne 73 (.value 29) (.value 55)], + .branch (.value 73) 20 21⟩, + -- bb6 + ⟨[], + [], + .tailCall 6 [.const 4, .const 0x6f76657200000000000000000000000000000000000000000000000000000000]⟩, + -- bb7 + ⟨[], + [.effect (some 24) .sload [.const 0], + .effect none .mstore [.const 128, .value 2], + .effect none .mstore [.const 160, .const 0], + .effect (some 30) .sload [.const 0], + .ne 75 (.value 24) (.value 2)], + .branch (.value 75) 22 23⟩, + -- bb8 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb9 + ⟨[], + [.effect (some 5) .sload [.const 1], + .pure 6 .lt [.value 5, .value 35]], + .branch (.value 6) 6 7⟩, + -- bb10 + ⟨[], + [.effect none .mstore [.const 128, .value 43], + .effect none .mstore [.const 160, .const 1], + .pure 20 .add [.value 13, .const 1], + .pure 33 .eq [.value 13, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff], + .word 77 (.value 33), + .ne 79 (.value 77) (.const 0)], + .branch (.value 79) 24 25⟩, + -- bb11 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb12 + ⟨[], + [.effect (some 62) .calldataload [.const 4], + .effect (some 2) .sload [.const 0], + .pure 35 .add [.value 2, .value 62], + .pure 36 .lt [.value 35, .value 2]], + .branch (.value 36) 8 9⟩, + -- bb13 + ⟨[(81, [(14, .const 0x11100000004000000010000000f), (16, .const 0x121000000040000000300000008), (18, .const 0x12100000004000000040000000c), (20, .const 0x12100000004000000050000000e), (22, .const 0x10300000004000000070000000b), (24, .const 0x102000000040000000a00000012)]), (82, [(14, .value 30), (16, .value 16), (18, .value 26), (20, .value 29), (22, .value 24), (24, .value 77)]), (83, [(14, .value 31), (16, .value 55), (18, .value 56), (20, .value 55), (22, .value 2), (24, .const 0)])], + [.effect none .mstore [.const 32, .value 81], + .effect none .mstore [.const 64, .value 82], + .effect none .mstore [.const 96, .value 83], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb14 + ⟨[], + [], + .jump 13⟩, + -- bb15 + ⟨[], + [], + .branch (.value 14) 3 4⟩, + -- bb16 + ⟨[], + [], + .jump 13⟩, + -- bb17 + ⟨[], + [], + .branch (.value 44) 8 10⟩, + -- bb18 + ⟨[], + [], + .jump 13⟩, + -- bb19 + ⟨[], + [], + .branch (.value 28) 5 2⟩, + -- bb20 + ⟨[], + [], + .jump 13⟩, + -- bb21 + ⟨[], + [], + .jump 2⟩, + -- bb22 + ⟨[], + [], + .jump 13⟩, + -- bb23 + ⟨[], + [], + .jump 1⟩, + -- bb24 + ⟨[], + [], + .jump 13⟩, + -- bb25 + ⟨[], + [], + .jump 1⟩] }, + -- @max + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 68]], + .branch (.value 9) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 0, .value 11]], + .ret (.const 0) (.const 32)⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 13]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 11) .calldataload [.const 4], + .effect (some 13) .calldataload [.const 36], + .pure 2 .lt [.value 11, .value 13]], + .branch (.value 2) 2 1⟩] }, + -- @revert_error + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 32, .const 32], + .effect none .mstore [.const 64, .value 0], + .effect none .mstore [.const 96, .value 1], + .effect none .mstore [.const 0, .const 0x8c379a0]], + .revert (.const 28) (.const 100)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 7 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 7 [(.const 0x6661abd, 2), (.const 0x6d5433e6, 3), (.const 0xa4d66daf, 4), (.const 0xb20eb4c4, 5), (.const 0xd09de08a, 6)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 5 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb5 + ⟨[], + [], + .tailCall 4 []⟩, + -- bb6 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb7 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Counter diff --git a/Certified/verify_counter/gen/Counter/Sched.lean b/Certified/verify_counter/gen/Counter/Sched.lean new file mode 100644 index 00000000..e28f5779 --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Sched.lean @@ -0,0 +1,352 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 7, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x6661abd)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0x6d5433e6)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa4d66daf)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0xb20eb4c4)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0xd09de08a)), + .op (.stack .eq), + .jumpi 2, + .jump 7], + -- bb2 + [.jump 10], + -- bb3 + [.jump 13], + -- bb4 + [.jump 9], + -- bb5 + [.jump 38], + -- bb6 + [.jump 8], + -- bb7 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb9 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb10 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.push 1)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 12, + .jump 11], + -- bb11 + [.op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb12 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb13 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 37, + .jump 14], + -- bb14 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 36, + .jump 15], + -- bb15 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack .lt), + .jumpi 35, + .jump 16], + -- bb16 + [.op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 33, + .jump 17], + -- bb17 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 18], + -- bb18 + [.op (.stack (.dup 4)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .op (.stack (.push 0)), + .effect .sload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 5)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 20, + .jump 19], + -- bb19 + [.op (.stack .pop), + .jumpi 27, + .jump 21], + -- bb20 + [.op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x11100000004000000010000000f)), + .op (.stack (.swap 3)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack (.swap 3)), + .jump 34], + -- bb21 + [.op (.stack (.push 160)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op (.stack .lt), + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 26, + .jump 22], + -- bb22 + [.op (.stack .iszero), + .jumpi 24, + .jump 23], + -- bb23 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .effect .sstore 2, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 25, + .jump 24], + -- bb24 + [.stop], + -- bb25 + [.op (.stack (.push 0x12100000004000000050000000e)), + .jump 34], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x12100000004000000040000000c)), + .jump 34], + -- bb27 + [.op (.stack .pop), + .op (.stack (.push 128)), + .op .load, + .op (.stack (.push 1)), + .op (.stack (.dup 4)), + .op (.stack .add), + .op (.stack (.dup 0)), + .op (.stack .iszero), + .op (.stack (.dup 5)), + .op (.stack (.dup 3)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 31, + .jump 28], + -- bb28 + [.jumpi 36, + .jump 29], + -- bb29 + [.op (.stack (.dup 0)), + .op (.stack (.push 128)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.push 160)), + .op .store, + .op (.stack (.push 1)), + .op (.stack (.dup 3)), + .op (.stack .add), + .op (.stack (.swap 2)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)), + .op (.stack .eq), + .op (.stack (.dup 0)), + .jumpi 32, + .jump 30], + -- bb30 + [.op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.swap 2)), + .op (.stack .pop), + .op (.stack (.push 1)), + .jump 18], + -- bb31 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x121000000040000000300000008)), + .op (.stack (.swap 2)), + .op (.stack (.swap 1)), + .op (.stack (.swap 2)), + .jump 34], + -- bb32 + [.op (.stack (.push 0)), + .op (.stack (.push 0x102000000040000000a00000012)), + .op (.stack (.swap 1)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 34], + -- bb33 + [.op (.stack .pop), + .op (.stack (.push 0x10300000004000000070000000b)), + .jump 34], + -- bb34 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb35 + [.op (.stack (.push 0x6f76657200000000000000000000000000000000000000000000000000000000)), + .op (.stack (.push 4)), + .jump 43], + -- bb36 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb37 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb38 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 42, + .jump 39], + -- bb39 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 41, + .jump 40], + -- bb40 + [.op (.stack .pop), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb41 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb42 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb43 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Counter diff --git a/Certified/verify_counter/gen/Counter/Schedule.json b/Certified/verify_counter/gen/Counter/Schedule.json new file mode 100644 index 00000000..69806a09 --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Schedule.json @@ -0,0 +1,70 @@ +{ + "functions": [ + {"function": 7, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [6, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [5, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [4, 0], "layout": [], "floating": true, "continues": null}, + {"block": 5, "start": [3, 0], "layout": [], "floating": true, "continues": null}, + {"block": 6, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 7, "start": [7, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 0, "entry": 8, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [8, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 1, "entry": 9, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [9, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 3, "entry": 10, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [10, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [12, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [11, 0], "layout": ["v4"], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 4, "entry": 13, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [13, 0], "layout": [], "floating": false, "continues": null}, + {"block": 1, "start": [18, 0], "layout": ["v62", "v55", "v30", "v13", "v56"], "floating": false, "continues": null}, + {"block": 2, "start": [24, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [27, 0], "layout": ["v62", "v55", "v30", "v13", "junk"], "floating": false, "continues": null}, + {"block": 4, "start": [21, 0], "layout": ["v55", "junk", "junk", "v56"], "floating": true, "continues": null}, + {"block": 5, "start": [23, 0], "layout": ["v55", "junk", "junk", "junk", "junk"], "floating": true, "continues": null}, + {"block": 6, "start": [35, 0], "layout": [], "floating": true, "continues": null}, + {"block": 7, "start": [16, 0], "layout": ["v62", "v2"], "floating": false, "continues": null}, + {"block": 8, "start": [36, 0], "layout": [], "floating": true, "continues": null}, + {"block": 9, "start": [15, 0], "layout": ["v62", "v2", "v35"], "floating": false, "continues": null}, + {"block": 10, "start": [29, 0], "layout": ["v62", "junk", "v30", "v13", "junk", "v43"], "floating": false, "continues": null}, + {"block": 11, "start": [37, 0], "layout": [], "floating": true, "continues": null}, + {"block": 12, "start": [14, 0], "layout": [], "floating": false, "continues": null}, + {"block": 13, "start": [34, 0], "layout": ["v83", "v82", "v81"], "floating": true, "continues": null}, + {"block": 14, "start": [20, 0], "layout": ["v30", "junk", "junk", "junk", "v31"], "floating": true, "continues": null}, + {"block": 15, "start": [19, 0], "layout": ["v62", "v55", "v30", "v13", "v56", "v14", "junk"], "floating": false, "continues": null}, + {"block": 16, "start": [31, 0], "layout": ["v55", "junk", "junk", "v16", "junk", "junk"], "floating": true, "continues": null}, + {"block": 17, "start": [28, 0], "layout": ["v62", "junk", "v30", "v13", "junk", "v43", "v44"], "floating": false, "continues": null}, + {"block": 18, "start": [26, 0], "layout": ["v56", "v26", "junk"], "floating": true, "continues": null}, + {"block": 19, "start": [22, 0], "layout": ["v55", "junk", "junk", "junk", "junk", "v28"], "floating": true, "continues": null}, + {"block": 20, "start": [25, 0], "layout": ["v55", "v29"], "floating": true, "continues": null}, + {"block": 21, "start": null, "layout": [], "floating": true, "continues": 2}, + {"block": 22, "start": [33, 0], "layout": ["v2", "v24", "junk"], "floating": true, "continues": null}, + {"block": 23, "start": [17, 0], "layout": ["v62", "v2", "junk", "v30"], "floating": false, "continues": null}, + {"block": 24, "start": [32, 0], "layout": ["v77"], "floating": true, "continues": null}, + {"block": 25, "start": [30, 0], "layout": ["v62", "junk", "v30", "v20", "junk", "v43", "junk"], "floating": false, "continues": null} + ], "calls": [ + ]}, + {"function": 5, "entry": 38, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [38, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [40, 0], "layout": ["v11", "junk"], "floating": true, "continues": null}, + {"block": 2, "start": [41, 0], "layout": ["v13"], "floating": true, "continues": null}, + {"block": 3, "start": [42, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [39, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 6, "entry": 43, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [43, 0], "layout": ["v1", "v0"], "floating": true, "continues": null} + ], "calls": [ + ]} + ] +} diff --git a/Certified/verify_counter/gen/Counter/Spec.lean b/Certified/verify_counter/gen/Counter/Spec.lean new file mode 100644 index 00000000..738b6e07 --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Spec.lean @@ -0,0 +1,68 @@ +import Verify.Spec.Contract + +/-! +Specs of `Certified/verify_counter/verify_counter.sol`, exported by solar-verify 0.3.0 with `--emit-lean-spec`. +Generated: do not edit. +-/ + +namespace Certified.verify_counter.gen.Counter.Spec + +open SolidCore.Spec + +/-- What the specs were exported from and are about. -/ +def manifest : Manifest := + { source := "Certified/verify_counter/verify_counter.sol", + sourceSha256 := "f1c87a334b8db31fc8f80541febeaf8617318d20b685634f44e26c74146ad326", + compiler := "", + options := [], + bytecodeSha256 := "" } + +/-- The specs of `Counter`. -/ +def Counter : Bundle where + fuel := 0 + spec := + { name := "Counter", + fns := [ + ], + invariants := [ + (.bin .le (.load (.slot 0) (.lit 0) 32 (.uint 256)) (.load (.slot 1) (.lit 0) 32 (.uint 256)))], + ghosts := [], + specs := [ + { name := "Counter.increment", + selector := 0xd09de08a, + params := [], + rets := [], + payable := false, + requires := [ + (.bin .lt (.load (.slot 0) (.lit 0) 32 (.uint 256)) (.load (.slot 1) (.lit 0) 32 (.uint 256)))], + ensures := [ + (.bin .eq (.load (.slot 0) (.lit 0) 32 (.uint 256)) (.bin .add (.old (.load (.slot 0) (.lit 0) 32 (.uint 256))) (.lit 1)))], + succeedsIf := [] }, + { name := "Counter.bump", + selector := 0xb20eb4c4, + params := [(.uint 256)], + rets := [], + payable := false, + requires := [], + ensures := [ + (.bin .eq (.load (.slot 0) (.lit 0) 32 (.uint 256)) (.bin .add (.old (.load (.slot 0) (.lit 0) 32 (.uint 256))) (.arg 0)))], + succeedsIf := [] }, + { name := "Counter.max", + selector := 0x6d5433e6, + params := [(.uint 256), (.uint 256)], + rets := [(.uint 256)], + payable := false, + requires := [], + ensures := [ + (.bin .eq (.ret 0) (.ite (.bin .ge (.arg 0) (.arg 1)) (.arg 0) (.arg 1))), + (.bin .and (.bin .ge (.ret 0) (.arg 0)) (.bin .ge (.ret 0) (.arg 1)))], + succeedsIf := [] }] } + +/-- Every spec function call resolves and nests within the fuel. -/ +theorem Counter_wf : Counter.WF = true := by decide +kernel + +/-- Trusted-base items these specs' proofs rely on beyond the verdict +(`SolidCore.Spec.Assumptions`). -/ +def trusted : List String := [] + +end Certified.verify_counter.gen.Counter.Spec diff --git a/Certified/verify_counter/gen/Counter/Stage0.lean b/Certified/verify_counter/gen/Counter/Stage0.lean new file mode 100644 index 00000000..c8ce2588 --- /dev/null +++ b/Certified/verify_counter/gen/Counter/Stage0.lean @@ -0,0 +1,200 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Counter`; do not edit. -/ + +namespace SolarTV.Export.Counter + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 7, + functions := [ + -- @count + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 0], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @limit + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 1], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @increment + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 0], + .pure 4 .add [.value 2, .const 1], + .pure 5 .eq [.value 4, .const 0]], + .branch (.value 5) 1 2⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 0, .value 4]], + .stop⟩] }, + -- @bump + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 58) .calldatasize [], + .pure 60 .lt [.value 58, .const 36]], + .branch (.value 60) 11 12⟩, + -- bb1 + ⟨[(13, [(7, .const 0), (10, .value 20)]), (55, [(7, .value 2), (10, .value 43)]), (56, [(7, .const 0), (10, .const 1)])], + [.pure 14 .lt [.value 13, .value 62], + .effect (some 31) .sload [.const 0], + .assume false .eq [.value 30, .value 31]], + .branch (.value 14) 3 4⟩, + -- bb2 + ⟨[], + [], + .stop⟩, + -- bb3 + ⟨[], + [.effect (some 16) .mload [.const 128], + .pure 43 .add [.value 55, .const 1], + .pure 44 .eq [.value 43, .const 0], + .assume false .eq [.value 16, .value 55]], + .branch (.value 44) 8 10⟩, + -- bb4 + ⟨[], + [.effect (some 26) .mload [.const 160], + .ne 28 (.value 56) (.const 0), + .assume false .eq [.value 26, .value 56]], + .branch (.value 28) 5 2⟩, + -- bb5 + ⟨[], + [.effect (some 29) .mload [.const 128], + .effect none .sstore [.const 0, .value 55], + .assume false .eq [.value 29, .value 55]], + .jump 2⟩, + -- bb6 + ⟨[], + [], + .tailCall 6 [.const 4, .const 0x6f76657200000000000000000000000000000000000000000000000000000000]⟩, + -- bb7 + ⟨[], + [.effect (some 24) .sload [.const 0], + .effect none .mstore [.const 128, .value 2], + .effect none .mstore [.const 160, .const 0], + .effect (some 30) .sload [.const 0], + .assume false .eq [.value 24, .value 2]], + .jump 1⟩, + -- bb8 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb9 + ⟨[], + [.effect (some 5) .sload [.const 1], + .pure 6 .lt [.value 5, .value 35]], + .branch (.value 6) 6 7⟩, + -- bb10 + ⟨[], + [.effect none .mstore [.const 128, .value 43], + .effect none .mstore [.const 160, .const 1], + .pure 20 .add [.value 13, .const 1], + .pure 33 .eq [.value 13, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 33, .const 0]], + .jump 1⟩, + -- bb11 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb12 + ⟨[], + [.effect (some 62) .calldataload [.const 4], + .effect (some 2) .sload [.const 0], + .pure 35 .add [.value 2, .value 62], + .pure 36 .lt [.value 35, .value 2]], + .branch (.value 36) 8 9⟩] }, + -- @max + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 68]], + .branch (.value 9) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 0, .value 11]], + .ret (.const 0) (.const 32)⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 13]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 11) .calldataload [.const 4], + .effect (some 13) .calldataload [.const 36], + .pure 2 .lt [.value 11, .value 13]], + .branch (.value 2) 2 1⟩] }, + -- @revert_error + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 32, .const 32], + .effect none .mstore [.const 64, .value 0], + .effect none .mstore [.const 96, .value 1], + .effect none .mstore [.const 0, .const 0x8c379a0]], + .revert (.const 28) (.const 100)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 7 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 7 [(.const 0x6661abd, 2), (.const 0x6d5433e6, 3), (.const 0xa4d66daf, 4), (.const 0xb20eb4c4, 5), (.const 0xd09de08a, 6)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 5 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb5 + ⟨[], + [], + .tailCall 4 []⟩, + -- bb6 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb7 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Counter diff --git a/Certified/verify_counter/gen/Counter/manifest.json b/Certified/verify_counter/gen/Counter/manifest.json new file mode 100644 index 00000000..3122e3b6 --- /dev/null +++ b/Certified/verify_counter/gen/Counter/manifest.json @@ -0,0 +1,145 @@ +{ + "arguments": [ + "Certified/verify_counter/verify_counter.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/verify_counter/gen" + ], + "bytecode": "34603c575f3560e01c806306661abd1460525780636d5433e6146101af578063a4d66daf14605b578063b20eb4c4146073578063d09de08a146065575b5f5ffd5b6011602052634e487b715f526024601cfd5b5f545f5260205ff35b6001545f5260205ff35b5f5460010180156040575f55005b60243610603c576004355f54818101818110604057600154106101d25780816080525f60a0528082820361019a575f5f91925060db565b506080516001840180158583036101675760405780608052600160a05260018301925f191480610182575093505060015b8482105f54808503610111575060aa5760a051815f10828203610152571561010f5750505050608051815f5581810361013e575b005b90506d011100000004000000010000000f939091935b60205260405260605263ed572b275b5f526064601cfd5b6d012100000004000000050000000e610127565b506d012100000004000000040000000c610127565b505090506d0121000000040000000300000008929192610127565b5f6d0102000000040000000a00000012919091610127565b506d010300000004000000070000000b610127565b60443610603c576004356024358082106101cb57505f5260205ff35b5f5260205ff35b636f76657260e01b6004602080526040526060526308c379a061013656", + "bytecode_sha256": "d74a847b897f855f93daf2805937efe40aec636c2ec3ca0c2d4ca6d21f214cc1", + "compiler": "0.8.38+commit.9aea5229.solar.0.3.0-dev", + "contract": "Counter", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"Certified/verify_counter/verify_counter.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/verify_counter/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/verify_counter/gen\"), keep_asts: false, forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "Certified/verify_counter/verify_counter.sol", + "sha256": "f1c87a334b8db31fc8f80541febeaf8617318d20b685634f44e26c74146ad326" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "656d00f214539eeaa141a32cf03260162058e19bb0ba268dd260f06ee750b8f0" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "lower-assumes", + "sha256": "4148e76c786c2c789fa6406554802afb17396a9b4c64cac88c222d0ef473e2ec" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "9c786268ecfa4bcfb528b33ba84078ab3bb149731c437ff049174efd08a6efa8" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "peephole-early", + "sha256": "eeb77872db3bfb3ba5d70ecf0ad642c5f3b07365141022dca569643df4e3a64c" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "2dadc7ece271f11f114461bbf5e86129a29d6437aa12a6fc419cd94b0781fea2" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "compact-pushes", + "sha256": "992a3c13079318558dda80965d13feba69246a1eb80d8f3b217608b9a5502d3f" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "block-layout", + "sha256": "712fb37d047bc02661cd67cbbf0687bb75d27d18e90a975b034383f5718b5c42" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "c6f7e76d48ebf1ec8e5540dc28c466f5748eab1dd843bf19c5586a8c1e08b6d3" + }, + { + "definition": "evm6", + "file": "Evm6.lean", + "index": 6, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "99964e04dc786304a3edca4025dea0676d283c64efed12cdc2d6300a0c940e72" + }, + { + "definition": "evm7", + "file": "Evm7.lean", + "index": 7, + "kind": "evm", + "pass": "tail-merge", + "sha256": "03b4a54e4df8a3afde11cd80577df69f48cfcddc72a81099ac31139e01383a20" + }, + { + "definition": "evm8", + "file": "Evm8.lean", + "index": 8, + "kind": "evm", + "pass": "block-cse", + "sha256": "77171ebac3ccb7b05c885642afe4a874a679302f2691ce170c3cc7c156faab51" + }, + { + "definition": "evm9", + "file": "Evm9.lean", + "index": 9, + "kind": "evm", + "pass": "stack-normalize", + "sha256": "90cfd88740d3f5279b2750f2184f001e75bc15e7fad84a0609336768478fca59" + }, + { + "definition": "evm10", + "file": "Evm10.lean", + "index": 10, + "kind": "evm", + "pass": "block-layout", + "sha256": "8fb28ec686a5e55940778cccff0d8c8f4c3bd4fc7adcad5a177e4bad2472cd85" + }, + { + "definition": "evm11", + "file": "Evm11.lean", + "index": 11, + "kind": "evm", + "pass": "loop-layout", + "sha256": "f70f678e80e80283f0ca6de824d88793e77f0688e62a8205818b280fd06085b7" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "fc71a0161d4f5d4951d881a578f3b44966305a115e6ec32c226a58f588fe5345" + } + ] +} diff --git a/Certified/verify_counter/headline b/Certified/verify_counter/headline new file mode 100644 index 00000000..320c8da1 --- /dev/null +++ b/Certified/verify_counter/headline @@ -0,0 +1 @@ +Contracts.VerifyCounter.Bytecode SolidCore.Refinement.Solar.VerifyCounter.spec_holds_of_bytecode diff --git a/Certified/verify_counter/options b/Certified/verify_counter/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/verify_counter/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/verify_counter/record.json b/Certified/verify_counter/record.json new file mode 100644 index 00000000..19358e9d --- /dev/null +++ b/Certified/verify_counter/record.json @@ -0,0 +1,126 @@ +{ + "contract": "Counter", + "name": "verify_counter", + "source": "Certified/verify_counter/verify_counter.sol", + "bytecode": "34603c575f3560e01c806306661abd1460525780636d5433e6146101af578063a4d66daf14605b578063b20eb4c4146073578063d09de08a146065575b5f5ffd5b6011602052634e487b715f526024601cfd5b5f545f5260205ff35b6001545f5260205ff35b5f5460010180156040575f55005b60243610603c576004355f54818101818110604057600154106101d25780816080525f60a0528082820361019a575f5f91925060db565b506080516001840180158583036101675760405780608052600160a05260018301925f191480610182575093505060015b8482105f54808503610111575060aa5760a051815f10828203610152571561010f5750505050608051815f5581810361013e575b005b90506d011100000004000000010000000f939091935b60205260405260605263ed572b275b5f526064601cfd5b6d012100000004000000050000000e610127565b506d012100000004000000040000000c610127565b505090506d0121000000040000000300000008929192610127565b5f6d0102000000040000000a00000012919091610127565b506d010300000004000000070000000b610127565b60443610603c576004356024358082106101cb57505f5260205ff35b5f5260205ff35b636f76657260e01b6004602080526040526060526308c379a061013656", + "solar": "9aea52293a7b53ce980c99da99c7486983ed6ae9", + "solidity_lean": "f962c2abbee427aaf97e6c80daa54840da04ee6f", + "mir_to_evmir": "proved: SolarTV.Milestone.VerifyCounter.verify_counter_mir_to_evmir", + "assembly": "executed: inside the published statement Certified.verify_counter.Final.final (Shapes.Equiv and Resources over Target.runWith of the exact bytes); Proofs/: executed: SolarTV.Milestone.VerifyCounter.verify_counter_bytecode", + "vc": "exported to .lake/certify/verify_counter/VC.lean", + "end_to_end": "proved (contract-specific): SolidCore.Refinement.Solar.VerifyCounter.spec_holds_of_bytecode", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, Shapes.Certified.equivG)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with an allowed status; the bytecode too, at gas from the bound on", + "spec": "proved (published statement, Shapes.Meets of Shapes.bundlePost of the specification solar-verify exported in this run, NonVacuous in the statement): the specification of every source result on a valid call, hence of every bytecode result that is not an inert failure", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result", + "vacuity": "proved non-vacuous (NonVacuous in the statement)", + "assumptions": "none beyond the statement's scope", + "excluded": [ + "source model trusted: SolidCore's checked Counter (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "source to MIR: SolidCore's runtime run equals solar's first lowered MIR on every valid call (Contracts.VerifyCounter.StageSource.mir_eq, from the generic erasure of bump with the loop's kernel-checked ranking certificate); the backend from MIR to the bytes is Contracts.VerifyCounter.Shape.functional and resources", + "deployment: the init code is not covered; runtime bytecode from any storage", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message", + "valid calls: bump(uint256) with ABI call data, no value, any storage, argument n < 2^32 (where the gas bound stays below 2^64); count(), limit(), increment() and max() are outside this statement", + "resources: gas bound Bump.gasBound call, linear in n, coarse (22100 gas per item)" + ], + "environment": "fixed, not quantified: one frame, caller 0x2000, the contract at 0x1000, the block and transaction of Target.message", + "provenance": "clean", + "strongest": true, + "source": "Contracts/VerifyCounter/SourceAst.lean is the front end's AST of Counter in Certified/verify_counter/verify_counter.sol (solc 0.8.35)" + }, + "final": { + "module": "verify_counter.Final", + "statement_module": "verify_counter.Statement", + "theorem": "Certified.verify_counter.Final.final", + "kind": "certified", + "statement": "_root_.Certified.verify_counter.Final.code.data.toList.map (·.toNat) = _root_.Certified.verify_counter.Final.runtimeBytes ∧ _root_.Certified.verify_counter.Final.NonVacuous ∧ (∃ c, Contracts.VerifyCounter.Source.contract? = .ok c ∧ _root_.SolidCore.Refinement.Shapes.Certified (_root_.SolidCore.Refinement.Generic.Loop.solidCoreRuntime (Contracts.VerifyCounter.Source.fuel)) c _root_.Certified.verify_counter.Final.code (Contracts.VerifyCounter.ShapeSource.ValidS) (Contracts.VerifyCounter.ShapeSource.Allowed) (_root_.SolidCore.Refinement.Shapes.bundlePost _root_.Certified.verify_counter.gen.Counter.Spec.Counter (SolidCore.Refinement.Shapes.ctxOfCall) (SolidCore.Refinement.Shapes.idStep)) (SolarTV.Milestone.VerifyCounter.Bump.gasBound))", + "nonvacuous": "Certified.verify_counter.Final.NonVacuous", + "vacuity": null, + "allowed_vacuity": null, + "spec_bound_to_export": "Certified.verify_counter.gen.Counter.Spec.Counter", + "allowed_bound_to_export": false, + "assumptions": [], + "excluded": [ + "source model trusted: SolidCore's checked Counter (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "source to MIR: SolidCore's runtime run equals solar's first lowered MIR on every valid call (Contracts.VerifyCounter.StageSource.mir_eq, from the generic erasure of bump with the loop's kernel-checked ranking certificate); the backend from MIR to the bytes is Contracts.VerifyCounter.Shape.functional and resources", + "deployment: the init code is not covered; runtime bytecode from any storage", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message", + "valid calls: bump(uint256) with ABI call data, no value, any storage, argument n < 2^32 (where the gas bound stays below 2^64); count(), limit(), increment() and max() are outside this statement", + "resources: gas bound Bump.gasBound call, linear in n, coarse (22100 gas per item)" + ], + "spec": "solar-verify's export of verify_counter.sol in this run (Certified.verify_counter.gen.Counter.Spec.Counter): bump(n) ensures count == old(count) + n and the invariant count <= limit, read by Shapes.bundlePost; increment and max are in the export and do not apply to the valid calls (other selectors). Allowed statuses: success, Panic(0x11) or Error(\"over\") (ShapeSource.Allowed)", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, Shapes.Certified.equivG)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with an allowed status; the bytecode too, at gas from the bound on", + "spec": "proved (published statement, Shapes.Meets of Shapes.bundlePost of the specification solar-verify exported in this run, NonVacuous in the statement): the specification of every source result on a valid call, hence of every bytecode result that is not an inert failure", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result", + "vacuity": "proved non-vacuous (NonVacuous in the statement)" + }, + "strongest": true + }, + "end_to_end_statement": { + "SolidCore.Refinement.Solar.VerifyCounter.spec_holds_of_bytecode": "∀ (gas : ℕ), SolidCore.Refinement.Final.Holds (SolidCore.Refinement.Final.ethLibWith gas) SolidCore.Refinement.Solar.VerifyCounter.code SolidCore.Refinement.Solar.VerifyCounter.spec" + }, + "binding": { + "SolidCore.Refinement.Solar.VerifyCounter.spec_holds_of_bytecode": "proof reaches the fresh export, statement does not" + }, + "hypotheses": { + "SolidCore.Refinement.Solar.VerifyCounter.spec_holds_of_bytecode": [ + "gas : ℕ" + ] + }, + "refused": [ + { + "function": "Counter.bump", + "reason": "command outside the Lean fragment: (set-option :timeout 0)", + "status": "refused (unproved)" + } + ], + "vacuous": "proved non-vacuous (NonVacuous in the statement)", + "vc_vacuous": "not checked", + "source_ast": "Contracts/VerifyCounter/SourceAst.lean is the front end's AST of Counter in Certified/verify_counter/verify_counter.sol (solc 0.8.35)", + "assembly_statement": "∀ {anyCall : SolarTV.Call → Prop} (o : SolarTV.Machine.Oracle), (SolarTV.Milestone.VerifyCounter.cert.env = true → SolidCore.Refinement.Solar.Assemble.OracleOk o) → (SolarTV.Milestone.VerifyCounter.cert.reads = true → SolidCore.Refinement.Solar.Assemble.EnvOk o) → ∀ (gas : ℕ), SolidCore.Refinement.Final.Within (SolarTV.mirSem o) (SolidCore.Refinement.Final.ethLibWith gas) SolarTV.Export.Counter.stage0 SolarTV.Milestone.VerifyCounter.code anyCall", + "assembly_hypotheses": [ + "anyCall : SolarTV.Call → Prop", + "o : SolarTV.Machine.Oracle", + "(SolarTV.Milestone.VerifyCounter.cert.env = true → SolidCore.Refinement.Solar.Assemble.OracleOk o)", + "(SolarTV.Milestone.VerifyCounter.cert.reads = true → SolidCore.Refinement.Solar.Assemble.EnvOk o)" + ], + "negative_tests": true, + "caveats": [ + "1 spec function(s) refused, unproved" + ], + "backend": { + "theorem": { + "module": "verify_counter.Final", + "statement_module": "verify_counter.Statement", + "theorem": "Certified.verify_counter.Final.final", + "kind": "certified", + "statement": "_root_.Certified.verify_counter.Final.code.data.toList.map (·.toNat) = _root_.Certified.verify_counter.Final.runtimeBytes ∧ _root_.Certified.verify_counter.Final.NonVacuous ∧ (∃ c, Contracts.VerifyCounter.Source.contract? = .ok c ∧ _root_.SolidCore.Refinement.Shapes.Certified (_root_.SolidCore.Refinement.Generic.Loop.solidCoreRuntime (Contracts.VerifyCounter.Source.fuel)) c _root_.Certified.verify_counter.Final.code (Contracts.VerifyCounter.ShapeSource.ValidS) (Contracts.VerifyCounter.ShapeSource.Allowed) (_root_.SolidCore.Refinement.Shapes.bundlePost _root_.Certified.verify_counter.gen.Counter.Spec.Counter (SolidCore.Refinement.Shapes.ctxOfCall) (SolidCore.Refinement.Shapes.idStep)) (SolarTV.Milestone.VerifyCounter.Bump.gasBound))", + "nonvacuous": "Certified.verify_counter.Final.NonVacuous", + "vacuity": null, + "allowed_vacuity": null, + "spec_bound_to_export": "Certified.verify_counter.gen.Counter.Spec.Counter", + "allowed_bound_to_export": false, + "assumptions": [], + "excluded": [ + "source model trusted: SolidCore's checked Counter (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "source to MIR: SolidCore's runtime run equals solar's first lowered MIR on every valid call (Contracts.VerifyCounter.StageSource.mir_eq, from the generic erasure of bump with the loop's kernel-checked ranking certificate); the backend from MIR to the bytes is Contracts.VerifyCounter.Shape.functional and resources", + "deployment: the init code is not covered; runtime bytecode from any storage", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message", + "valid calls: bump(uint256) with ABI call data, no value, any storage, argument n < 2^32 (where the gas bound stays below 2^64); count(), limit(), increment() and max() are outside this statement", + "resources: gas bound Bump.gasBound call, linear in n, coarse (22100 gas per item)" + ], + "spec": "solar-verify's export of verify_counter.sol in this run (Certified.verify_counter.gen.Counter.Spec.Counter): bump(n) ensures count == old(count) + n and the invariant count <= limit, read by Shapes.bundlePost; increment and max are in the export and do not apply to the valid calls (other selectors). Allowed statuses: success, Panic(0x11) or Error(\"over\") (ShapeSource.Allowed)", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, Shapes.Certified.equivG)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with an allowed status; the bytecode too, at gas from the bound on", + "spec": "proved (published statement, Shapes.Meets of Shapes.bundlePost of the specification solar-verify exported in this run, NonVacuous in the statement): the specification of every source result on a valid call, hence of every bytecode result that is not an inert failure", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result", + "vacuity": "proved non-vacuous (NonVacuous in the statement)" + }, + "strongest": true + } + } +} diff --git a/Certified/verify_counter/shape.json b/Certified/verify_counter/shape.json new file mode 100644 index 00000000..574432bf --- /dev/null +++ b/Certified/verify_counter/shape.json @@ -0,0 +1,36 @@ +{ + "kind": "certified", + "contract": "Contracts.VerifyCounter.Source.contract?", + "fuel": "Contracts.VerifyCounter.Source.fuel", + "source_sem": "SolidCore.Refinement.Generic.Loop.solidCoreRuntime", + "valid": "Contracts.VerifyCounter.ShapeSource.ValidS", + "allowed": "Contracts.VerifyCounter.ShapeSource.Allowed", + "spec_export": { + "ctx": "SolidCore.Refinement.Shapes.ctxOfCall", + "step": "SolidCore.Refinement.Shapes.idStep" + }, + "nonvacuous": "Contracts.VerifyCounter.ShapeExport.nonvacuous", + "gas": "SolarTV.Milestone.VerifyCounter.Bump.gasBound", + "env": [], + "spec": "solar-verify's export of verify_counter.sol in this run (Certified.verify_counter.gen.Counter.Spec.Counter): bump(n) ensures count == old(count) + n and the invariant count <= limit, read by Shapes.bundlePost; increment and max are in the export and do not apply to the valid calls (other selectors). Allowed statuses: success, Panic(0x11) or Error(\"over\") (ShapeSource.Allowed)", + "spec_modules": [ + "Contracts.VerifyCounter.ShapeSource", + "Contracts.VerifyCounter.Gas", + "Verify.ShapeSpecExport" + ], + "proof_module": "Contracts.VerifyCounter.ShapeExport", + "proof": "Contracts.VerifyCounter.ShapeExport.published", + "excluded": [ + "source model trusted: SolidCore's checked Counter (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "source to MIR: SolidCore's runtime run equals solar's first lowered MIR on every valid call (Contracts.VerifyCounter.StageSource.mir_eq, from the generic erasure of bump with the loop's kernel-checked ranking certificate); the backend from MIR to the bytes is Contracts.VerifyCounter.Shape.functional and resources", + "deployment: the init code is not covered; runtime bytecode from any storage", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message", + "valid calls: bump(uint256) with ABI call data, no value, any storage, argument n < 2^32 (where the gas bound stays below 2^64); count(), limit(), increment() and max() are outside this statement", + "resources: gas bound Bump.gasBound call, linear in n, coarse (22100 gas per item)" + ], + "source_ast": { + "file": "Contracts/VerifyCounter/SourceAst.lean", + "namespace": "SolidCore.Refinement.Source.VerifyCounter", + "contract": "Counter" + } +} diff --git a/Certified/verify_counter/verify_counter.sol b/Certified/verify_counter/verify_counter.sol new file mode 100644 index 00000000..c27e1c20 --- /dev/null +++ b/Certified/verify_counter/verify_counter.sol @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +/// @custom:invariant count <= limit +contract Counter { + uint256 public count; + uint256 public limit; + + /// @custom:ensures limit == _limit && count == 0 + constructor(uint256 _limit) { + limit = _limit; + } + + /// @custom:requires count < limit + /// @custom:ensures count == old(count) + 1 + function increment() external { + count += 1; + } + + /// @custom:ensures count == old(count) + n + function bump(uint256 n) external { + require(count + n <= limit, "over"); + /// @custom:invariant i <= n + /// @custom:invariant count == old(count) + i + /// @custom:decreases n - i + for (uint256 i = 0; i < n; i++) { + count++; + } + } + + /// @custom:ensures result == (a >= b ? a : b) + /// @custom:ensures result >= a && result >= b + function max(uint256 a, uint256 b) public pure returns (uint256) { + if (a >= b) return a; + return b; + } +} diff --git a/Certified/verify_token/Final.lean b/Certified/verify_token/Final.lean new file mode 100644 index 00000000..016a2587 --- /dev/null +++ b/Certified/verify_token/Final.lean @@ -0,0 +1,94 @@ +import Verify.Shapes +import verify_token.gen.Token.Bytecode +import Contracts.Token.Lowering +import Contracts.Token.VC.Burn +import Contracts.Token.VC.Transfer +import Verify.ShapeGeneric +import verify_token.Shape + +-- Generated by solar's tools/certify/final.py from verify_token/shape.json and the bytecode the +-- driver compiled in this run; do not edit. The statement is fixed by the driver; the proof +-- module only supplies a term the kernel checks against it. + +/-! +# Token: the published statement + +`Statement` binds the exact runtime bytecode (`runtimeHex`, from the driver's own compile) and +states Shapes.Certified of it against the checked source on the declared valid calls. +-/ + +namespace Certified.verify_token.Final + +open SolidCore.Refinement + +/-- The runtime bytecode the pinned solar emitted in this run, as hex (for the reader). -/ +def runtimeHex : String := + "346047575f3560e01c806318160ddd14608f57806340c10f191460a957806342966c681461024357806370a0823114605d5780638da5cb5b146099578063a9059cbb14610172575b5f5ffd5b6011602052634e487b715f526024601cfd5b60043560a01c60243610176047576004355f1960601c8116815f525f60205260405f20545f5281810361027f5760205ff35b6001545f5260205ff35b60025460601b60601c5f5260205ff35b60043560a01c60443610176047576004355f1960601c808216906002541633145f1960601c331161015957828203610134571561010c5750602435600154818101908110604b57600155905f525f60205260405f208054918201918210604b5755005b686e6f74206f776e657260b81b60095b602080526040526060526308c379a05b5f526064601cfd5b506d01020000000400000007000000155b6020525b60405260605263ed572b2761012c565b5f1960601c33690417000000040000000760201b610145565b60043560a01c60443610176047576004356024355f1960601c8216335f525f60205260405f2080548381105f1960601c331161022a5785840361020f57806101f85784909103909155925f525060405f208054918201918210604b575560015f52806101dd5760205ff35b6d01020000000500000004000000045f5b9060205290610149565b6b696e73756666696369656e7460a01b600c61011c565b50505090506d010200000005000000060000001c90916101ee565b33690417000000050000000660201b5f1960601c6101ee565b60243610604757600435335f525f60205260405f2080548281039083115f1960601c331161029357604b579055600154818110604b5703600155005b6d0102000000000000000200000009610145565b690417000000060000000560201b335f1960601c9161014556" + +/-- The same bytes, as numbers: what the statement binds. -/ +def runtimeBytes : List Nat := + [0x34, 0x60, 0x47, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x18, 0x16, 0xd, 0xdd, 0x14, + 0x60, 0x8f, 0x57, 0x80, 0x63, 0x40, 0xc1, 0xf, 0x19, 0x14, 0x60, 0xa9, 0x57, 0x80, 0x63, 0x42, + 0x96, 0x6c, 0x68, 0x14, 0x61, 0x2, 0x43, 0x57, 0x80, 0x63, 0x70, 0xa0, 0x82, 0x31, 0x14, 0x60, + 0x5d, 0x57, 0x80, 0x63, 0x8d, 0xa5, 0xcb, 0x5b, 0x14, 0x60, 0x99, 0x57, 0x80, 0x63, 0xa9, 0x5, + 0x9c, 0xbb, 0x14, 0x61, 0x1, 0x72, 0x57, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x60, 0x11, 0x60, 0x20, + 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, 0x60, 0x1c, 0xfd, 0x5b, 0x60, 0x4, + 0x35, 0x60, 0xa0, 0x1c, 0x60, 0x24, 0x36, 0x10, 0x17, 0x60, 0x47, 0x57, 0x60, 0x4, 0x35, 0x5f, + 0x19, 0x60, 0x60, 0x1c, 0x81, 0x16, 0x81, 0x5f, 0x52, 0x5f, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, + 0x20, 0x54, 0x5f, 0x52, 0x81, 0x81, 0x3, 0x61, 0x2, 0x7f, 0x57, 0x60, 0x20, 0x5f, 0xf3, 0x5b, + 0x60, 0x1, 0x54, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x2, 0x54, 0x60, 0x60, 0x1b, + 0x60, 0x60, 0x1c, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x4, 0x35, 0x60, 0xa0, 0x1c, + 0x60, 0x44, 0x36, 0x10, 0x17, 0x60, 0x47, 0x57, 0x60, 0x4, 0x35, 0x5f, 0x19, 0x60, 0x60, 0x1c, + 0x80, 0x82, 0x16, 0x90, 0x60, 0x2, 0x54, 0x16, 0x33, 0x14, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x33, + 0x11, 0x61, 0x1, 0x59, 0x57, 0x82, 0x82, 0x3, 0x61, 0x1, 0x34, 0x57, 0x15, 0x61, 0x1, 0xc, + 0x57, 0x50, 0x60, 0x24, 0x35, 0x60, 0x1, 0x54, 0x81, 0x81, 0x1, 0x90, 0x81, 0x10, 0x60, 0x4b, + 0x57, 0x60, 0x1, 0x55, 0x90, 0x5f, 0x52, 0x5f, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x80, + 0x54, 0x91, 0x82, 0x1, 0x91, 0x82, 0x10, 0x60, 0x4b, 0x57, 0x55, 0x0, 0x5b, 0x68, 0x6e, 0x6f, + 0x74, 0x20, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x60, 0xb8, 0x1b, 0x60, 0x9, 0x5b, 0x60, 0x20, 0x80, + 0x52, 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, 0x63, 0x8, 0xc3, 0x79, 0xa0, 0x5b, 0x5f, 0x52, 0x60, + 0x64, 0x60, 0x1c, 0xfd, 0x5b, 0x50, 0x6d, 0x1, 0x2, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, + 0x7, 0x0, 0x0, 0x0, 0x15, 0x5b, 0x60, 0x20, 0x52, 0x5b, 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, + 0x63, 0xed, 0x57, 0x2b, 0x27, 0x61, 0x1, 0x2c, 0x56, 0x5b, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x33, + 0x69, 0x4, 0x17, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x7, 0x60, 0x20, 0x1b, 0x61, 0x1, + 0x45, 0x56, 0x5b, 0x60, 0x4, 0x35, 0x60, 0xa0, 0x1c, 0x60, 0x44, 0x36, 0x10, 0x17, 0x60, 0x47, + 0x57, 0x60, 0x4, 0x35, 0x60, 0x24, 0x35, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x82, 0x16, 0x33, 0x5f, + 0x52, 0x5f, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x80, 0x54, 0x83, 0x81, 0x10, 0x5f, 0x19, + 0x60, 0x60, 0x1c, 0x33, 0x11, 0x61, 0x2, 0x2a, 0x57, 0x85, 0x84, 0x3, 0x61, 0x2, 0xf, 0x57, + 0x80, 0x61, 0x1, 0xf8, 0x57, 0x84, 0x90, 0x91, 0x3, 0x90, 0x91, 0x55, 0x92, 0x5f, 0x52, 0x50, + 0x60, 0x40, 0x5f, 0x20, 0x80, 0x54, 0x91, 0x82, 0x1, 0x91, 0x82, 0x10, 0x60, 0x4b, 0x57, 0x55, + 0x60, 0x1, 0x5f, 0x52, 0x80, 0x61, 0x1, 0xdd, 0x57, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x6d, 0x1, + 0x2, 0x0, 0x0, 0x0, 0x5, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x4, 0x5f, 0x5b, 0x90, + 0x60, 0x20, 0x52, 0x90, 0x61, 0x1, 0x49, 0x56, 0x5b, 0x6b, 0x69, 0x6e, 0x73, 0x75, 0x66, 0x66, + 0x69, 0x63, 0x69, 0x65, 0x6e, 0x74, 0x60, 0xa0, 0x1b, 0x60, 0xc, 0x61, 0x1, 0x1c, 0x56, 0x5b, + 0x50, 0x50, 0x50, 0x90, 0x50, 0x6d, 0x1, 0x2, 0x0, 0x0, 0x0, 0x5, 0x0, 0x0, 0x0, 0x6, + 0x0, 0x0, 0x0, 0x1c, 0x90, 0x91, 0x61, 0x1, 0xee, 0x56, 0x5b, 0x33, 0x69, 0x4, 0x17, 0x0, + 0x0, 0x0, 0x5, 0x0, 0x0, 0x0, 0x6, 0x60, 0x20, 0x1b, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x61, + 0x1, 0xee, 0x56, 0x5b, 0x60, 0x24, 0x36, 0x10, 0x60, 0x47, 0x57, 0x60, 0x4, 0x35, 0x33, 0x5f, + 0x52, 0x5f, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x80, 0x54, 0x82, 0x81, 0x3, 0x90, 0x83, + 0x11, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x33, 0x11, 0x61, 0x2, 0x93, 0x57, 0x60, 0x4b, 0x57, 0x90, + 0x55, 0x60, 0x1, 0x54, 0x81, 0x81, 0x10, 0x60, 0x4b, 0x57, 0x3, 0x60, 0x1, 0x55, 0x0, 0x5b, + 0x6d, 0x1, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x9, 0x61, + 0x1, 0x45, 0x56, 0x5b, 0x69, 0x4, 0x17, 0x0, 0x0, 0x0, 0x6, 0x0, 0x0, 0x0, 0x5, 0x60, + 0x20, 0x1b, 0x33, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x91, 0x61, 0x1, 0x45, 0x56] + +/-- The freshly exported bytecode the obligations speak of. -/ +def code : ByteArray := ⟨(SolarTV.Export.Token.bytecode.map UInt8.ofNat).toArray⟩ + +/-- **The published statement.** -/ +def Statement : Prop := + code.data.toList.map (·.toNat) = runtimeBytes ∧ + ((SolidCore.Verify.VC.Token.HashInj) → + ∃ c, SolidCore.Verify.VC.Token.contract? = .ok c ∧ + Shapes.Certified (solidCore (SolidCore.Verify.VC.Token.fuel)) c code + (SolidCore.Refinement.Shapes.genericValid0 ([SolidCore.Verify.VC.Token.fnTransfer, SolidCore.Verify.VC.Token.fnBurn, SolidCore.Refinement.Solar.VerifyTokenSource.fnMint, SolidCore.Refinement.Solar.VerifyTokenSource.fnTotalSupply, SolidCore.Refinement.Solar.VerifyTokenSource.fnOwner]) ([(2, 4096)])) (fun _ _ => True) (fun call obs => (SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Token.fnTransfer [(2, 4096)] call → SolidCore.Verify.VC.Token.trPost call obs) ∧ (SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Token.fnBurn [(2, 4096)] call → SolidCore.Verify.VC.Token.burnPost call obs)) (fun _ => 42697212)) + +set_option maxRecDepth 100000 in +theorem bound : code.data.toList.map (·.toNat) = runtimeBytes := + @of_decide_eq_true _ (instDecidableEqList _ _) (by decide +kernel) + +theorem final : Statement := + ⟨bound, fun _h0 => Certified.verify_token.Shape.published _h0⟩ + +#print axioms final + +end Certified.verify_token.Final diff --git a/Certified/verify_token/Proofs.lean b/Certified/verify_token/Proofs.lean new file mode 100644 index 00000000..3062549d --- /dev/null +++ b/Certified/verify_token/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import verify_token.Proofs.Stages +import verify_token.Proofs.Assembly diff --git a/Certified/verify_token/Proofs/Assembly.lean b/Certified/verify_token/Proofs/Assembly.lean new file mode 100644 index 00000000..fbc6600b --- /dev/null +++ b/Certified/verify_token/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Items +import verify_token.gen.Token.Evm12 +import verify_token.gen.Token.Bytecode + +/-! The final EVM IR of `Token` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.VerifyToken + +open SolarTV.Assembly SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm12).getD [] + +theorem items_eq : itemsOf evm12 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x47 else if label = 2 then 0x4b else if label = 3 then 0x5d else if label = 4 then 0x8f else if label = 5 then 0x99 else if label = 6 then 0xa9 else if label = 7 then 0x10c else if label = 8 then 0x11c else if label = 9 then 0x12c else if label = 10 then 0x134 else if label = 11 then 0x145 else if label = 12 then 0x149 else if label = 13 then 0x159 else if label = 14 then 0x172 else if label = 15 then 0x1dd else if label = 16 then 0x1ee else if label = 17 then 0x1f8 else if label = 18 then 0x20f else if label = 19 then 0x22a else if label = 20 then 0x243 else if label = 21 then 0x27f else if label = 22 then 0x293 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.VerifyToken.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.VerifyToken.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms decodes + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Evm1.lean b/Certified/verify_token/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..40b09095 --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Evm1 +import verify_token.gen.Token.Sched + +/-! `peephole-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 54 = EVM.Program.run o evm1 call 54 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Evm10.lean b/Certified/verify_token/Proofs/Runs/Evm10.lean new file mode 100644 index 00000000..621e40d7 --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Evm10.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Evm10 +import verify_token.gen.Token.Evm9 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm10_run (o : Oracle) (call : Call) : + EVM.Program.run o evm9 call 23 = EVM.Program.run o evm10 call 23 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.evm10_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm10_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Evm11.lean b/Certified/verify_token/Proofs/Runs/Evm11.lean new file mode 100644 index 00000000..27650c31 --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Evm11.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Evm11 +import verify_token.gen.Token.Evm10 + +/-! `stack-reschedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm11_run (o : Oracle) (call : Call) : + EVM.Program.run o evm10 call 23 = EVM.Program.run o evm11 call 23 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.evm11_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm11_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Evm12.lean b/Certified/verify_token/Proofs/Runs/Evm12.lean new file mode 100644 index 00000000..362b835f --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Evm12.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Evm12 +import verify_token.gen.Token.Evm11 + +/-! `late-word`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm12_run (o : Oracle) (call : Call) : + EVM.Program.run o evm11 call 23 = EVM.Program.run o evm12 call 23 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.evm12_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm12_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Evm2.lean b/Certified/verify_token/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..97337af2 --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Evm2 +import verify_token.gen.Token.Evm1 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 54 = EVM.Program.run o evm2 call 27 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Evm3.lean b/Certified/verify_token/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..af46cd27 --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Evm3 +import verify_token.gen.Token.Evm2 + +/-! `compact-pushes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 27 = EVM.Program.run o evm3 call 27 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Evm4.lean b/Certified/verify_token/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..81ea43d1 --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Evm4 +import verify_token.gen.Token.Evm3 + +/-! `block-layout`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 27 = EVM.Program.run o evm4 call 27 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Evm5.lean b/Certified/verify_token/Proofs/Runs/Evm5.lean new file mode 100644 index 00000000..8ecd90f2 --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Evm5.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Evm5 +import verify_token.gen.Token.Evm4 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm5_run (o : Oracle) (call : Call) : + EVM.Program.run o evm4 call 27 = EVM.Program.run o evm5 call 27 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.evm5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm5_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Evm6.lean b/Certified/verify_token/Proofs/Runs/Evm6.lean new file mode 100644 index 00000000..f4de3959 --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Evm6.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Evm6 +import verify_token.gen.Token.Evm5 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm6_run (o : Oracle) (call : Call) : + EVM.Program.run o evm5 call 27 = EVM.Program.run o evm6 call 21 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.evm6_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm6_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Evm7.lean b/Certified/verify_token/Proofs/Runs/Evm7.lean new file mode 100644 index 00000000..25a42ce1 --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Evm7.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Evm7 +import verify_token.gen.Token.Evm6 + +/-! `tail-merge`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm7_run (o : Oracle) (call : Call) : + EVM.Program.run o evm6 call 21 = EVM.Program.run o evm7 call 24 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.evm7_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm7_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Evm8.lean b/Certified/verify_token/Proofs/Runs/Evm8.lean new file mode 100644 index 00000000..4771badb --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Evm8.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Evm8 +import verify_token.gen.Token.Evm7 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm8_run (o : Oracle) (call : Call) : + EVM.Program.run o evm7 call 24 = EVM.Program.run o evm8 call 23 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.evm8_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm8_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Evm9.lean b/Certified/verify_token/Proofs/Runs/Evm9.lean new file mode 100644 index 00000000..ba4eb1ed --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Evm9.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Evm9 +import verify_token.gen.Token.Evm8 + +/-! `block-cse`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem evm9_run (o : Oracle) (call : Call) : + EVM.Program.run o evm8 call 23 = EVM.Program.run o evm9 call 23 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.evm9_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm9_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Mir1.lean b/Certified/verify_token/Proofs/Runs/Mir1.lean new file mode 100644 index 00000000..5a841088 --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Mir1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Mir1 +import verify_token.gen.Token.Stage0 + +/-! `place-reads`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir1_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 36 = MIR.Lowered.Module.run o mir1 call 36 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.mir1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir1_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Mir2.lean b/Certified/verify_token/Proofs/Runs/Mir2.lean new file mode 100644 index 00000000..64f9e746 --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Mir2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Mir2 +import verify_token.gen.Token.Mir1 + +/-! `dce`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir2_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir1 call 36 = MIR.Lowered.Module.run o mir2 call 36 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.mir2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir2_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Mir3.lean b/Certified/verify_token/Proofs/Runs/Mir3.lean new file mode 100644 index 00000000..2c93c9c0 --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Mir3.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Mir3 +import verify_token.gen.Token.Mir2 + +/-! `spell-width-tests`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir3_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir2 call 36 = MIR.Lowered.Module.run o mir3 call 36 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.mir3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir3_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Mir4.lean b/Certified/verify_token/Proofs/Runs/Mir4.lean new file mode 100644 index 00000000..aa1fc774 --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Mir4.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Mir4 +import verify_token.gen.Token.Mir3 + +/-! `lower-assumes`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir4_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir3 call 36 = MIR.Lowered.Module.run o mir4 call 54 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.mir4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir4_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Mir5.lean b/Certified/verify_token/Proofs/Runs/Mir5.lean new file mode 100644 index 00000000..61159b0b --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Mir5.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Mir5 +import verify_token.gen.Token.Mir4 + +/-! `evm-inst-schedule`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem mir5_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir4 call 54 = MIR.Lowered.Module.run o mir5 call 54 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.mir5_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within mir5_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Sched.lean b/Certified/verify_token/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..e1c12581 --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Sched +import verify_token.gen.Token.Mir5 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o mir5 call 54 = EVM.Program.run o sched call 54 := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Runs/Stage0.lean b/Certified/verify_token/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..0948c8c3 --- /dev/null +++ b/Certified/verify_token/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import verify_token.gen.Token.Stage0 + +/-! The first lowered MIR ends on every call within 36 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +set_option maxHeartbeats 8000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 36).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.VerifyToken.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Proofs/Stages.lean b/Certified/verify_token/Proofs/Stages.lean new file mode 100644 index 00000000..c6c71f2c --- /dev/null +++ b/Certified/verify_token/Proofs/Stages.lean @@ -0,0 +1,307 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import verify_token.Proofs.Runs.Stage0 +import verify_token.Proofs.Runs.Mir1 +import verify_token.Proofs.Runs.Mir2 +import verify_token.Proofs.Runs.Mir3 +import verify_token.Proofs.Runs.Mir4 +import verify_token.Proofs.Runs.Mir5 +import verify_token.Proofs.Runs.Sched +import verify_token.Proofs.Runs.Evm1 +import verify_token.Proofs.Runs.Evm2 +import verify_token.Proofs.Runs.Evm3 +import verify_token.Proofs.Runs.Evm4 +import verify_token.Proofs.Runs.Evm5 +import verify_token.Proofs.Runs.Evm6 +import verify_token.Proofs.Runs.Evm7 +import verify_token.Proofs.Runs.Evm8 +import verify_token.Proofs.Runs.Evm9 +import verify_token.Proofs.Runs.Evm10 +import verify_token.Proofs.Runs.Evm11 +import verify_token.Proofs.Runs.Evm12 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Token`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm12`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.VerifyToken + +open Machine SolarTV.Export.Token SolarTV.Milestone.W1 + +/-- `place-reads`: stage0 to mir1. -/ +theorem stage_mir1 (o : Oracle) : Stage (mirSem o) (mirSem o) stage0 mir1 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 36 36 (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +theorem mir1_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir1 call 36).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := stage0) (q := mir1) (n := 36) (m := 36) (fun call _ => stage0_ends o call) + (fun call _ => mir1_run o call) + +/-- `dce`: mir1 to mir2. -/ +theorem stage_mir2 (o : Oracle) : Stage (mirSem o) (mirSem o) mir1 mir2 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 36 36 (mir1_ends o) + (fun call _ => mir2_run o call) + +theorem mir2_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir2 call 36).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir1) (q := mir2) (n := 36) (m := 36) (mir1_ends o) + (fun call _ => mir2_run o call) + +/-- `spell-width-tests`: mir2 to mir3. -/ +theorem stage_mir3 (o : Oracle) : Stage (mirSem o) (mirSem o) mir2 mir3 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 36 36 (mir2_ends o) + (fun call _ => mir3_run o call) + +theorem mir3_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir3 call 36).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir2) (q := mir3) (n := 36) (m := 36) (mir2_ends o) + (fun call _ => mir3_run o call) + +/-- `lower-assumes`: mir3 to mir4. -/ +theorem stage_mir4 (o : Oracle) : Stage (mirSem o) (mirSem o) mir3 mir4 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 36 54 (mir3_ends o) + (fun call _ => mir4_run o call) + +theorem mir4_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir4 call 54).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir3) (q := mir4) (n := 36) (m := 54) (mir3_ends o) + (fun call _ => mir4_run o call) + +/-- `evm-inst-schedule`: mir4 to mir5. -/ +theorem stage_mir5 (o : Oracle) : Stage (mirSem o) (mirSem o) mir4 mir5 anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) 54 54 (mir4_ends o) + (fun call _ => mir5_run o call) + +theorem mir5_ends (o : Oracle) : ∀ call, anyCall call → + (MIR.Lowered.Module.run o mir5 call 54).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := MIR.Lowered.moduleLayer) + (o := o) (p := mir4) (q := mir5) (n := 54) (m := 54) (mir4_ends o) + (fun call _ => mir5_run o call) + +/-- `stack-schedule`: mir5 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) mir5 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 54 54 (mir5_ends o) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 54).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := mir5) (q := sched) (n := 54) (m := 54) (mir5_ends o) + (fun call _ => sched_run o call) + +/-- `peephole-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 54 54 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 54).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 54) (m := 54) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `cfg-simplify-early`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 54 27 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 27).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 54) (m := 27) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `compact-pushes`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 27 27 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 27).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 27) (m := 27) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `block-layout`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 27 27 (evm3_ends o) + (fun call _ => evm4_run o call) + +theorem evm4_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm4 call 27).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm3) (q := evm4) (n := 27) (m := 27) (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- `terminal-dedup`: evm4 to evm5. -/ +theorem stage_evm5 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm4 evm5 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 27 27 (evm4_ends o) + (fun call _ => evm5_run o call) + +theorem evm5_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm5 call 27).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm4) (q := evm5) (n := 27) (m := 27) (evm4_ends o) + (fun call _ => evm5_run o call) + +/-- `cfg-simplify-early`: evm5 to evm6. -/ +theorem stage_evm6 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm5 evm6 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 27 21 (evm5_ends o) + (fun call _ => evm6_run o call) + +theorem evm6_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm6 call 21).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm5) (q := evm6) (n := 27) (m := 21) (evm5_ends o) + (fun call _ => evm6_run o call) + +/-- `tail-merge`: evm6 to evm7. -/ +theorem stage_evm7 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm6 evm7 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 21 24 (evm6_ends o) + (fun call _ => evm7_run o call) + +theorem evm7_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm7 call 24).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm6) (q := evm7) (n := 21) (m := 24) (evm6_ends o) + (fun call _ => evm7_run o call) + +/-- `cfg-simplify-early`: evm7 to evm8. -/ +theorem stage_evm8 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm7 evm8 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 24 23 (evm7_ends o) + (fun call _ => evm8_run o call) + +theorem evm8_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm8 call 23).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm7) (q := evm8) (n := 24) (m := 23) (evm7_ends o) + (fun call _ => evm8_run o call) + +/-- `block-cse`: evm8 to evm9. -/ +theorem stage_evm9 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm8 evm9 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 23 23 (evm8_ends o) + (fun call _ => evm9_run o call) + +theorem evm9_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm9 call 23).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm8) (q := evm9) (n := 23) (m := 23) (evm8_ends o) + (fun call _ => evm9_run o call) + +/-- `block-layout`: evm9 to evm10. -/ +theorem stage_evm10 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm9 evm10 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 23 23 (evm9_ends o) + (fun call _ => evm10_run o call) + +theorem evm10_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm10 call 23).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm9) (q := evm10) (n := 23) (m := 23) (evm9_ends o) + (fun call _ => evm10_run o call) + +/-- `stack-reschedule`: evm10 to evm11. -/ +theorem stage_evm11 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm10 evm11 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 23 23 (evm10_ends o) + (fun call _ => evm11_run o call) + +theorem evm11_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm11 call 23).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm10) (q := evm11) (n := 23) (m := 23) (evm10_ends o) + (fun call _ => evm11_run o call) + +/-- `late-word`: evm11 to evm12. -/ +theorem stage_evm12 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm11 evm12 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 23 23 (evm11_ends o) + (fun call _ => evm12_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [mir1, mir2, mir3, mir4, mir5], sched, [evm1, evm2, evm3, evm4, evm5, evm6, evm7, evm8, evm9, evm10, evm11, evm12]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem verify_token_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm12 anyCall := + mir_to_evmir o anyCall compilation ⟨stage_mir1 o, stage_mir2 o, stage_mir3 o, stage_mir4 o, stage_mir5 o, trivial⟩ (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, stage_evm5 o, stage_evm6 o, stage_evm7 o, stage_evm8 o, stage_evm9 o, stage_evm10 o, stage_evm11 o, stage_evm12 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_mir1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir1 + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_mir2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir2 + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_mir3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir3 + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_mir4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir4 + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_mir5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_mir5 + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_evm5' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm5 + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_evm6' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm6 + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_evm7' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm7 + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_evm8' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm8 + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_evm9' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm9 + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_evm10' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm10 + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_evm11' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm11 + +/-- info: 'SolarTV.Milestone.VerifyToken.stage_evm12' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm12 + +/-- info: 'SolarTV.Milestone.VerifyToken.verify_token_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms verify_token_mir_to_evmir + +end SolarTV.Milestone.VerifyToken diff --git a/Certified/verify_token/Shape.lean b/Certified/verify_token/Shape.lean new file mode 100644 index 00000000..7c828838 --- /dev/null +++ b/Certified/verify_token/Shape.lean @@ -0,0 +1,140 @@ +import Verify.ShapeGeneric +import Contracts.Token.Lowering +import verify_token.Proofs.Stages +import verify_token.gen.Token.Bytecode +import Contracts.Token.Discharge + +-- Generated by solar's tools/certify/shape_gen.py from verify_token/shape.json and this run's export; +-- do not edit. Untrusted data and composition: the kernel re-derives every claim. + +/-! +# Token: the proof of the published statement + +`published` applies `SolidCore.Refinement.Shapes.compiled0` to the source check of `SolidCore.Refinement.Solar.VerifyTokenSource`, solar-tv's backend +stages to `evm12` (`SolarTV.Milestone.VerifyToken.verify_token_mir_to_evmir`), the final EVM IR's run within 23 blocks on every +call (the last stage's fuel) and the loop checker on the exact bytecode, with the certificate +tools/certify/asm_cert.py inferred. The gas bound is `gasBoundL cert 23` = 22100 · (23 · 84) + 12 += 42697212, at most the statement's 42697212. +-/ + +namespace Certified.verify_token.Shape + +open SolidCore.Refinement SolidCore.Refinement.Solar SolarTV + +/-- The exported runtime bytecode. -/ +def code : ByteArray := ⟨(SolarTV.Export.Token.bytecode.map UInt8.ofNat).toArray⟩ + +/-- The loop checker's certificate (tools/certify/asm_cert.py). -/ +def cert : SolidCore.Refinement.Solar.Assemble.Cert := + { offsets := [0x0, 0x47, 0x4b, 0x5d, 0x8f, 0x99, 0xa9, 0x10c, 0x11c, 0x12c, 0x134, 0x145, 0x149, 0x159, 0x172, 0x1dd, 0x1ee, 0x1f8, 0x20f, 0x22a, 0x243, 0x27f, 0x293], + needs := [0, 0, 3, 1, 1, 1, 1, 3, 5, 2, 4, 4, 3, 4, 1, 2, 4, 7, 7, 7, 1, 3, 5], + top := 128, + turned := [], + costs := [37, 3, 9, 38, 7, 11, 77, 5, 9, 5, 3, 3, 8, 11, 84, 3, 7, 7, 11, 11, 47, 4, 12], + types := [[], + [], + [some false, some false, some false], + [some false], + [some false], + [some false], + [some false], + [some false, some false, some false], + [some false, some false, some false, some false, some false], + [some false, some false], + [some false, some false, some false, some false], + [some false, some false, some false, some false], + [some false, some false, some false], + [some false, some false, some false, some false], + [some false], + [some false, some false], + [some false, some false, some false, some false], + [some false, some false, some false, some false, some false, some false, some false], + [some false, some false, some false, some false, some false, some false, some false], + [some false, some false, some false, some false, some false, some false, some false], + [some false], + [some false, some false, some false], + [some false, some false, some false, some false, some false]], + rets := [], + env := true, + reads := false } + +/-- The highest stack each block is entered with. -/ +def maxs : List Nat := [0, 1, 4, 1, 1, 1, 1, 3, 9, 8, 4, 8, 9, 4, 1, 2, 10, 7, 7, 7, 1, 3, 5] + +set_option maxRecDepth 100000 in +theorem walk_ok : (SolarTV.Assembly.walk (SolidCore.Refinement.Solar.Assemble.bytesOf code) cert.offset 0 + (SolidCore.Refinement.Solar.Assemble.lower SolarTV.Export.Token.evm12 cert)).isSome = true := by + have hw := SolidCore.Refinement.Solar.Assemble.walkS_drop (SolidCore.Refinement.Solar.Assemble.bytesOf code) cert.offset (SolidCore.Refinement.Solar.Assemble.lower SolarTV.Export.Token.evm12 cert) 0 + (Nat.zero_le _) + rw [List.drop_zero] at hw + rw [← hw] + decide +kernel + +set_option maxRecDepth 100000 in +theorem blocks_ok : SolidCore.Refinement.Solar.AssembleLoop.blocksOkL SolarTV.Export.Token.evm12 cert maxs 0 SolarTV.Export.Token.evm12.blocks = true := by + decide +kernel + +theorem labels_ok : SolidCore.Refinement.Solar.Assemble.labelsValid SolarTV.Export.Token.evm12 cert code = true := + SolidCore.Refinement.Solar.Assemble.labelsValid_of_walk walk_ok + +theorem size_ok : code.size < 2 ^ 32 := by decide +kernel + +/-- The checker of code with loops accepts the exact bytecode for the final EVM IR. -/ +theorem check_ok : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.Token.evm12 code cert maxs = true := by + simp only [SolidCore.Refinement.Solar.AssembleLoop.checkL, walk_ok, blocks_ok, labels_ok, decide_eq_true size_ok, Bool.and_true, + Bool.true_and] + decide + +/-- The final EVM IR ends within 23 blocks on every call, under the bytecode's oracle. -/ +theorem ends (call : Call) : (EVM.Program.run SolidCore.Refinement.Shapes.oracle SolarTV.Export.Token.evm12 call 23).isSome = true := + SolarTV.Milestone.W1.ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := SolidCore.Refinement.Shapes.oracle) (p := SolarTV.Export.Token.evm11) (q := SolarTV.Export.Token.evm12) (n := 23) (m := 23) + (SolarTV.Milestone.VerifyToken.evm11_ends SolidCore.Refinement.Shapes.oracle) (fun call _ => SolarTV.Milestone.VerifyToken.evm12_run SolidCore.Refinement.Shapes.oracle call) call trivial + +/-- The bytecode with byte `i` replaced by `b`. -/ +def mutant (i b : Nat) : ByteArray := ⟨((SolarTV.Export.Token.bytecode.set i b).map UInt8.ofNat).toArray⟩ + +set_option maxRecDepth 100000 in +/-- The checker rejects the bytecode with a jump target moved (byte 2). -/ +theorem rejects_jump : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.Token.evm12 (mutant 2 72) cert maxs = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The checker rejects the bytecode with an SSTORE dropped (as POP) (byte 243). -/ +theorem rejects_sstore : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.Token.evm12 (mutant 243 80) cert maxs = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The checker rejects the bytecode with an opcode outside the fragment (CREATE) for an SSTORE (byte 243). -/ +theorem rejects_opcode : SolidCore.Refinement.Solar.AssembleLoop.checkL SolarTV.Export.Token.evm12 (mutant 243 240) cert maxs = false := by + decide +kernel + +theorem gas_lt : SolidCore.Refinement.Solar.AssembleLoop.gasBoundL cert 23 < 2 ^ 64 := by decide +kernel + +theorem gas_le : SolidCore.Refinement.Solar.AssembleLoop.gasBoundL cert 23 ≤ 42697212 := by decide +kernel + + +/-- **What the published statement asks of this module.** -/ +theorem published : (SolidCore.Verify.VC.Token.HashInj) → + ∃ c, SolidCore.Verify.VC.Token.contract? = .ok c ∧ + SolidCore.Refinement.Shapes.Certified (solidCore SolidCore.Verify.VC.Token.fuel) c code (SolidCore.Refinement.Shapes.genericValid0 ([SolidCore.Verify.VC.Token.fnTransfer, SolidCore.Verify.VC.Token.fnBurn, SolidCore.Refinement.Solar.VerifyTokenSource.fnMint, SolidCore.Refinement.Solar.VerifyTokenSource.fnTotalSupply, SolidCore.Refinement.Solar.VerifyTokenSource.fnOwner]) ([(2, 4096)])) (fun _ _ => True) (fun call obs => (SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Token.fnTransfer [(2, 4096)] call → SolidCore.Verify.VC.Token.trPost call obs) ∧ (SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Token.fnBurn [(2, 4096)] call → SolidCore.Verify.VC.Token.burnPost call obs)) (fun _ => 42697212) := by + intro _h0 + obtain ⟨c, hc⟩ := SolidCore.Refinement.Solar.VerifyTokenSource.contract_ok + obtain ⟨d, hd⟩ := SolidCore.Refinement.Solar.VerifyTokenSource.deployed hc + have h0 := SolidCore.Refinement.Solar.VerifyTokenSource.check_of hc SolidCore.Refinement.Solar.VerifyTokenSource.check_transfer_eq + have h1 := SolidCore.Refinement.Solar.VerifyTokenSource.check_of hc SolidCore.Refinement.Solar.VerifyTokenSource.check_burn_eq + have h2 := SolidCore.Refinement.Solar.VerifyTokenSource.check_of hc SolidCore.Refinement.Solar.VerifyTokenSource.check_mint_eq + have h3 := SolidCore.Refinement.Solar.VerifyTokenSource.check_of hc SolidCore.Refinement.Solar.VerifyTokenSource.check_totalSupply_eq + have h4 := SolidCore.Refinement.Solar.VerifyTokenSource.check_of hc SolidCore.Refinement.Solar.VerifyTokenSource.check_owner_eq + have hchk : Generic.check SolidCore.Verify.VC.Token.fuel SolidCore.Refinement.Solar.VerifyTokenSource.mirFuel c.core SolarTV.Export.Token.stage0 ([SolidCore.Verify.VC.Token.fnTransfer, SolidCore.Verify.VC.Token.fnBurn, SolidCore.Refinement.Solar.VerifyTokenSource.fnMint, SolidCore.Refinement.Solar.VerifyTokenSource.fnTotalSupply, SolidCore.Refinement.Solar.VerifyTokenSource.fnOwner]) .all = true := by + simp only [Generic.check, List.all_cons, List.all_nil, Bool.and_true] at h0 h1 h2 h3 h4 ⊢ + simp only [h0, h1, h2, h3, h4, Bool.and_self] + exact ⟨c, hc, ((SolidCore.Refinement.Shapes.compiled0 hd hchk (SolidCore.Refinement.Shapes.genericValid0_inhabited _ _ _) + (SolarTV.Milestone.VerifyToken.verify_token_mir_to_evmir SolidCore.Refinement.Shapes.oracle) (fun _ _ => trivial) ends check_ok gas_lt).mono_gas (fun _ => gas_le) (fun _ => by decide)).certified + (fun _ _ _ _ => trivial) (SolidCore.Refinement.Shapes.Meets.and (SolidCore.Refinement.Shapes.meets_of_triple (SolidCore.Verify.VC.Token.transfer_triple_discharged _h0 hc)) (SolidCore.Refinement.Shapes.meets_of_triple (SolidCore.Verify.VC.Token.burn_triple hc)))⟩ + +/-- info: 'Certified.verify_token.Shape.published' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms published + +end Certified.verify_token.Shape diff --git a/Certified/verify_token/bytecode.hex b/Certified/verify_token/bytecode.hex new file mode 100644 index 00000000..19611d40 --- /dev/null +++ b/Certified/verify_token/bytecode.hex @@ -0,0 +1 @@ +346047575f3560e01c806318160ddd14608f57806340c10f191460a957806342966c681461024357806370a0823114605d5780638da5cb5b146099578063a9059cbb14610172575b5f5ffd5b6011602052634e487b715f526024601cfd5b60043560a01c60243610176047576004355f1960601c8116815f525f60205260405f20545f5281810361027f5760205ff35b6001545f5260205ff35b60025460601b60601c5f5260205ff35b60043560a01c60443610176047576004355f1960601c808216906002541633145f1960601c331161015957828203610134571561010c5750602435600154818101908110604b57600155905f525f60205260405f208054918201918210604b5755005b686e6f74206f776e657260b81b60095b602080526040526060526308c379a05b5f526064601cfd5b506d01020000000400000007000000155b6020525b60405260605263ed572b2761012c565b5f1960601c33690417000000040000000760201b610145565b60043560a01c60443610176047576004356024355f1960601c8216335f525f60205260405f2080548381105f1960601c331161022a5785840361020f57806101f85784909103909155925f525060405f208054918201918210604b575560015f52806101dd5760205ff35b6d01020000000500000004000000045f5b9060205290610149565b6b696e73756666696369656e7460a01b600c61011c565b50505090506d010200000005000000060000001c90916101ee565b33690417000000050000000660201b5f1960601c6101ee565b60243610604757600435335f525f60205260405f2080548281039083115f1960601c331161029357604b579055600154818110604b5703600155005b6d0102000000000000000200000009610145565b690417000000060000000560201b335f1960601c9161014556 diff --git a/Certified/verify_token/gen/Token/Bytecode.lean b/Certified/verify_token/gen/Token/Bytecode.lean new file mode 100644 index 00000000..ecb3f5f7 --- /dev/null +++ b/Certified/verify_token/gen/Token/Bytecode.lean @@ -0,0 +1,56 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x47, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x18, 0x16, 0x0d, 0xdd, 0x14, + 0x60, 0x8f, 0x57, 0x80, 0x63, 0x40, 0xc1, 0x0f, 0x19, 0x14, 0x60, 0xa9, 0x57, 0x80, 0x63, 0x42, + 0x96, 0x6c, 0x68, 0x14, 0x61, 0x02, 0x43, 0x57, 0x80, 0x63, 0x70, 0xa0, 0x82, 0x31, 0x14, 0x60, + 0x5d, 0x57, 0x80, 0x63, 0x8d, 0xa5, 0xcb, 0x5b, 0x14, 0x60, 0x99, 0x57, 0x80, 0x63, 0xa9, 0x05, + 0x9c, 0xbb, 0x14, 0x61, 0x01, 0x72, 0x57, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x60, 0x11, 0x60, 0x20, + 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, 0x60, 0x1c, 0xfd, 0x5b, 0x60, 0x04, + 0x35, 0x60, 0xa0, 0x1c, 0x60, 0x24, 0x36, 0x10, 0x17, 0x60, 0x47, 0x57, 0x60, 0x04, 0x35, 0x5f, + 0x19, 0x60, 0x60, 0x1c, 0x81, 0x16, 0x81, 0x5f, 0x52, 0x5f, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, + 0x20, 0x54, 0x5f, 0x52, 0x81, 0x81, 0x03, 0x61, 0x02, 0x7f, 0x57, 0x60, 0x20, 0x5f, 0xf3, 0x5b, + 0x60, 0x01, 0x54, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x02, 0x54, 0x60, 0x60, 0x1b, + 0x60, 0x60, 0x1c, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x04, 0x35, 0x60, 0xa0, 0x1c, + 0x60, 0x44, 0x36, 0x10, 0x17, 0x60, 0x47, 0x57, 0x60, 0x04, 0x35, 0x5f, 0x19, 0x60, 0x60, 0x1c, + 0x80, 0x82, 0x16, 0x90, 0x60, 0x02, 0x54, 0x16, 0x33, 0x14, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x33, + 0x11, 0x61, 0x01, 0x59, 0x57, 0x82, 0x82, 0x03, 0x61, 0x01, 0x34, 0x57, 0x15, 0x61, 0x01, 0x0c, + 0x57, 0x50, 0x60, 0x24, 0x35, 0x60, 0x01, 0x54, 0x81, 0x81, 0x01, 0x90, 0x81, 0x10, 0x60, 0x4b, + 0x57, 0x60, 0x01, 0x55, 0x90, 0x5f, 0x52, 0x5f, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x80, + 0x54, 0x91, 0x82, 0x01, 0x91, 0x82, 0x10, 0x60, 0x4b, 0x57, 0x55, 0x00, 0x5b, 0x68, 0x6e, 0x6f, + 0x74, 0x20, 0x6f, 0x77, 0x6e, 0x65, 0x72, 0x60, 0xb8, 0x1b, 0x60, 0x09, 0x5b, 0x60, 0x20, 0x80, + 0x52, 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, 0x63, 0x08, 0xc3, 0x79, 0xa0, 0x5b, 0x5f, 0x52, 0x60, + 0x64, 0x60, 0x1c, 0xfd, 0x5b, 0x50, 0x6d, 0x01, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, + 0x07, 0x00, 0x00, 0x00, 0x15, 0x5b, 0x60, 0x20, 0x52, 0x5b, 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, + 0x63, 0xed, 0x57, 0x2b, 0x27, 0x61, 0x01, 0x2c, 0x56, 0x5b, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x33, + 0x69, 0x04, 0x17, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x07, 0x60, 0x20, 0x1b, 0x61, 0x01, + 0x45, 0x56, 0x5b, 0x60, 0x04, 0x35, 0x60, 0xa0, 0x1c, 0x60, 0x44, 0x36, 0x10, 0x17, 0x60, 0x47, + 0x57, 0x60, 0x04, 0x35, 0x60, 0x24, 0x35, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x82, 0x16, 0x33, 0x5f, + 0x52, 0x5f, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x80, 0x54, 0x83, 0x81, 0x10, 0x5f, 0x19, + 0x60, 0x60, 0x1c, 0x33, 0x11, 0x61, 0x02, 0x2a, 0x57, 0x85, 0x84, 0x03, 0x61, 0x02, 0x0f, 0x57, + 0x80, 0x61, 0x01, 0xf8, 0x57, 0x84, 0x90, 0x91, 0x03, 0x90, 0x91, 0x55, 0x92, 0x5f, 0x52, 0x50, + 0x60, 0x40, 0x5f, 0x20, 0x80, 0x54, 0x91, 0x82, 0x01, 0x91, 0x82, 0x10, 0x60, 0x4b, 0x57, 0x55, + 0x60, 0x01, 0x5f, 0x52, 0x80, 0x61, 0x01, 0xdd, 0x57, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x6d, 0x01, + 0x02, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x5f, 0x5b, 0x90, + 0x60, 0x20, 0x52, 0x90, 0x61, 0x01, 0x49, 0x56, 0x5b, 0x6b, 0x69, 0x6e, 0x73, 0x75, 0x66, 0x66, + 0x69, 0x63, 0x69, 0x65, 0x6e, 0x74, 0x60, 0xa0, 0x1b, 0x60, 0x0c, 0x61, 0x01, 0x1c, 0x56, 0x5b, + 0x50, 0x50, 0x50, 0x90, 0x50, 0x6d, 0x01, 0x02, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, + 0x00, 0x00, 0x00, 0x1c, 0x90, 0x91, 0x61, 0x01, 0xee, 0x56, 0x5b, 0x33, 0x69, 0x04, 0x17, 0x00, + 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x60, 0x20, 0x1b, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x61, + 0x01, 0xee, 0x56, 0x5b, 0x60, 0x24, 0x36, 0x10, 0x60, 0x47, 0x57, 0x60, 0x04, 0x35, 0x33, 0x5f, + 0x52, 0x5f, 0x60, 0x20, 0x52, 0x60, 0x40, 0x5f, 0x20, 0x80, 0x54, 0x82, 0x81, 0x03, 0x90, 0x83, + 0x11, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x33, 0x11, 0x61, 0x02, 0x93, 0x57, 0x60, 0x4b, 0x57, 0x90, + 0x55, 0x60, 0x01, 0x54, 0x81, 0x81, 0x10, 0x60, 0x4b, 0x57, 0x03, 0x60, 0x01, 0x55, 0x00, 0x5b, + 0x6d, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x09, 0x61, + 0x01, 0x45, 0x56, 0x5b, 0x69, 0x04, 0x17, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x05, 0x60, + 0x20, 0x1b, 0x33, 0x5f, 0x19, 0x60, 0x60, 0x1c, 0x91, 0x61, 0x01, 0x45, 0x56] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "346047575f3560e01c806318160ddd14608f57806340c10f191460a957806342966c681461024357806370a0823114605d5780638da5cb5b146099578063a9059cbb14610172575b5f5ffd5b6011602052634e487b715f526024601cfd5b60043560a01c60243610176047576004355f1960601c8116815f525f60205260405f20545f5281810361027f5760205ff35b6001545f5260205ff35b60025460601b60601c5f5260205ff35b60043560a01c60443610176047576004355f1960601c808216906002541633145f1960601c331161015957828203610134571561010c5750602435600154818101908110604b57600155905f525f60205260405f208054918201918210604b5755005b686e6f74206f776e657260b81b60095b602080526040526060526308c379a05b5f526064601cfd5b506d01020000000400000007000000155b6020525b60405260605263ed572b2761012c565b5f1960601c33690417000000040000000760201b610145565b60043560a01c60443610176047576004356024355f1960601c8216335f525f60205260405f2080548381105f1960601c331161022a5785840361020f57806101f85784909103909155925f525060405f208054918201918210604b575560015f52806101dd5760205ff35b6d01020000000500000004000000045f5b9060205290610149565b6b696e73756666696369656e7460a01b600c61011c565b50505090506d010200000005000000060000001c90916101ee565b33690417000000050000000660201b5f1960601c6101ee565b60243610604757600435335f525f60205260405f2080548281039083115f1960601c331161029357604b579055600154818110604b5703600155005b6d0102000000000000000200000009610145565b690417000000060000000560201b335f1960601c9161014556" + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Evm1.lean b/Certified/verify_token/gen/Token/Evm1.lean new file mode 100644 index 00000000..3fa24dca --- /dev/null +++ b/Certified/verify_token/gen/Token/Evm1.lean @@ -0,0 +1,493 @@ +-- solar-lean-stage: kind=evm index=1 pass=peephole-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `peephole-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 8, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x18160ddd)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0x40c10f19)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0x42966c68)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8da5cb5b)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 2, + .jump 8], + -- bb2 + [.jump 30], + -- bb3 + [.jump 16], + -- bb4 + [.jump 9], + -- bb5 + [.jump 44], + -- bb6 + [.jump 17], + -- bb7 + [.jump 15], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 14, + .jump 10], + -- bb10 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 12, + .jump 11], + -- bb11 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 0x102000000000000000200000009)), + .jump 13], + -- bb13 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack (.push 2)), + .effect .sload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 29, + .jump 18], + -- bb18 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 2)), + .effect .sload 1, + .op (.stack .and), + .effect .caller 0, + .op (.stack .eq), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 27, + .jump 19], + -- bb19 + [.op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 26, + .jump 20], + -- bb20 + [.op (.stack .iszero), + .jumpi 24, + .jump 21], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 25, + .jump 22], + -- bb22 + [.op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 25, + .jump 23], + -- bb23 + [.effect .sstore 2, + .stop], + -- bb24 + [.op (.stack (.push 0x6e6f74206f776e65720000000000000000000000000000000000000000000000)), + .op (.stack (.push 9)), + .jump 53], + -- bb25 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x102000000040000000700000015)), + .jump 28], + -- bb27 + [.op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack (.push 0x417000000040000000700000000)), + .jump 28], + -- bb28 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb29 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb30 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 43, + .jump 31], + -- bb31 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 2)), + .op (.stack .and), + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 41, + .jump 32], + -- bb32 + [.op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .op (.stack .sub), + .jumpi 40, + .jump 33], + -- bb33 + [.op (.stack (.dup 0)), + .jumpi 39, + .jump 34], + -- bb34 + [.op (.stack (.dup 4)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 38, + .jump 35], + -- bb35 + [.effect .sstore 2, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 0)), + .jumpi 37, + .jump 36], + -- bb36 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 0x102000000050000000400000004)), + .op (.stack (.push 0)), + .jump 42], + -- bb38 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb39 + [.op (.stack (.push 0x696e73756666696369656e740000000000000000000000000000000000000000)), + .op (.stack (.push 12)), + .jump 53], + -- bb40 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10200000005000000060000001c)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 42], + -- bb41 + [.effect .caller 0, + .op (.stack (.push 0x417000000050000000600000000)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 42], + -- bb42 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb43 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb44 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 52, + .jump 45], + -- bb45 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.dup 3)), + .op (.stack .gt), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 50, + .jump 46], + -- bb46 + [.jumpi 49, + .jump 47], + -- bb47 + [.op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack .gt), + .jumpi 49, + .jump 48], + -- bb48 + [.op (.stack (.push 1)), + .effect .sstore 2, + .stop], + -- bb49 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb50 + [.op (.stack (.push 0x417000000060000000500000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 51], + -- bb51 + [.op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb52 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb53 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Evm10.lean b/Certified/verify_token/gen/Token/Evm10.lean new file mode 100644 index 00000000..0852be41 --- /dev/null +++ b/Certified/verify_token/gen/Token/Evm10.lean @@ -0,0 +1,409 @@ +-- solar-lean-stage: kind=evm index=10 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `block-layout`. -/ +def evm10 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x18160ddd)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x40c10f19)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0x42966c68)), + .op (.stack .eq), + .jumpi 20, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8da5cb5b)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 14, + .jump 1], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb25 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 21, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack (.push 2)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 2)), + .effect .sload 1, + .op (.stack .and), + .effect .caller 0, + .op (.stack .eq), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 13, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 10, + .op (.stack .iszero), + .jumpi 7, + .op (.stack .pop), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 2, + .effect .sstore 2, + .stop], + -- bb24 + [.op (.stack (.push 0x6e6f74206f776e6572)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 8], + -- bb53 + [.op (.stack (.push 32)), + .op (.stack (.dup 0)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .jump 9], + -- bb54 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x102000000040000000700000015)), + .jump 11], + -- bb56 + [.op (.stack (.push 32)), + .op .store, + .jump 12], + -- bb55 + [.op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .jump 9], + -- bb27 + [.op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack (.push 0x4170000000400000007)), + .op (.stack (.push 32)), + .op (.stack .shl), + .jump 11], + -- bb30 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .and), + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 19, + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.dup 0)), + .jumpi 17, + .op (.stack (.dup 4)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 2, + .effect .sstore 2, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 0x102000000050000000400000004)), + .op (.stack (.push 0)), + .jump 16], + -- bb42 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .jump 12], + -- bb39 + [.op (.stack (.push 0x696e73756666696369656e74)), + .op (.stack (.push 160)), + .op (.stack .shl), + .op (.stack (.push 12)), + .jump 8], + -- bb40 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10200000005000000060000001c)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 16], + -- bb41 + [.effect .caller 0, + .op (.stack (.push 0x4170000000500000006)), + .op (.stack (.push 32)), + .op (.stack .shl), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 16], + -- bb44 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.dup 3)), + .op (.stack .gt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 22, + .jumpi 2, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack .gt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sstore 2, + .stop], + -- bb12 + [.op (.stack (.push 0x102000000000000000200000009)), + .jump 11], + -- bb50 + [.op (.stack (.push 0x4170000000600000005)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .jump 11]] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Evm11.lean b/Certified/verify_token/gen/Token/Evm11.lean new file mode 100644 index 00000000..4c4ac217 --- /dev/null +++ b/Certified/verify_token/gen/Token/Evm11.lean @@ -0,0 +1,408 @@ +-- solar-lean-stage: kind=evm index=11 pass=stack-reschedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `stack-reschedule`. -/ +def evm11 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x18160ddd)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x40c10f19)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0x42966c68)), + .op (.stack .eq), + .jumpi 20, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8da5cb5b)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 14, + .jump 1], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb25 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 21, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack (.push 2)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 2)), + .effect .sload 1, + .op (.stack .and), + .effect .caller 0, + .op (.stack .eq), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 13, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 10, + .op (.stack .iszero), + .jumpi 7, + .op (.stack .pop), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 2, + .effect .sstore 2, + .stop], + -- bb24 + [.op (.stack (.push 0x6e6f74206f776e6572)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 8], + -- bb53 + [.op (.stack (.push 32)), + .op (.stack (.dup 0)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .jump 9], + -- bb54 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x102000000040000000700000015)), + .jump 11], + -- bb56 + [.op (.stack (.push 32)), + .op .store, + .jump 12], + -- bb55 + [.op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .jump 9], + -- bb27 + [.op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack (.push 0x4170000000400000007)), + .op (.stack (.push 32)), + .op (.stack .shl), + .jump 11], + -- bb30 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .and), + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 19, + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.dup 0)), + .jumpi 17, + .op (.stack (.dup 4)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 2, + .effect .sstore 2, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 0x102000000050000000400000004)), + .op (.stack (.push 0)), + .jump 16], + -- bb42 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .jump 12], + -- bb39 + [.op (.stack (.push 0x696e73756666696369656e74)), + .op (.stack (.push 160)), + .op (.stack .shl), + .op (.stack (.push 12)), + .jump 8], + -- bb40 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10200000005000000060000001c)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 16], + -- bb41 + [.effect .caller 0, + .op (.stack (.push 0x4170000000500000006)), + .op (.stack (.push 32)), + .op (.stack .shl), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 16], + -- bb44 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.dup 3)), + .op (.stack .gt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 22, + .jumpi 2, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack .sub), + .op (.stack (.push 1)), + .effect .sstore 2, + .stop], + -- bb12 + [.op (.stack (.push 0x102000000000000000200000009)), + .jump 11], + -- bb50 + [.op (.stack (.push 0x4170000000600000005)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .jump 11]] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Evm12.lean b/Certified/verify_token/gen/Token/Evm12.lean new file mode 100644 index 00000000..0d0ceab0 --- /dev/null +++ b/Certified/verify_token/gen/Token/Evm12.lean @@ -0,0 +1,407 @@ +-- solar-lean-stage: kind=evm index=12 pass=late-word +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `late-word`. -/ +def evm12 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x18160ddd)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x40c10f19)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0x42966c68)), + .op (.stack .eq), + .jumpi 20, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8da5cb5b)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 14, + .jump 1], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb25 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 21, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack (.push 2)), + .effect .sload 1, + .op (.stack (.push 96)), + .op (.stack .shl), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 2)), + .effect .sload 1, + .op (.stack .and), + .effect .caller 0, + .op (.stack .eq), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 13, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 10, + .op (.stack .iszero), + .jumpi 7, + .op (.stack .pop), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 2, + .effect .sstore 2, + .stop], + -- bb24 + [.op (.stack (.push 0x6e6f74206f776e6572)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 8], + -- bb53 + [.op (.stack (.push 32)), + .op (.stack (.dup 0)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .jump 9], + -- bb54 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x102000000040000000700000015)), + .jump 11], + -- bb56 + [.op (.stack (.push 32)), + .op .store, + .jump 12], + -- bb55 + [.op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .jump 9], + -- bb27 + [.op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack (.push 0x4170000000400000007)), + .op (.stack (.push 32)), + .op (.stack .shl), + .jump 11], + -- bb30 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .and), + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 19, + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.dup 0)), + .jumpi 17, + .op (.stack (.dup 4)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 2, + .effect .sstore 2, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 0x102000000050000000400000004)), + .op (.stack (.push 0)), + .jump 16], + -- bb42 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .jump 12], + -- bb39 + [.op (.stack (.push 0x696e73756666696369656e74)), + .op (.stack (.push 160)), + .op (.stack .shl), + .op (.stack (.push 12)), + .jump 8], + -- bb40 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10200000005000000060000001c)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 16], + -- bb41 + [.effect .caller 0, + .op (.stack (.push 0x4170000000500000006)), + .op (.stack (.push 32)), + .op (.stack .shl), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 16], + -- bb44 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.dup 3)), + .op (.stack .gt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 22, + .jumpi 2, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack .sub), + .op (.stack (.push 1)), + .effect .sstore 2, + .stop], + -- bb12 + [.op (.stack (.push 0x102000000000000000200000009)), + .jump 11], + -- bb50 + [.op (.stack (.push 0x4170000000600000005)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .jump 11]] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Evm2.lean b/Certified/verify_token/gen/Token/Evm2.lean new file mode 100644 index 00000000..fcb4a8c9 --- /dev/null +++ b/Certified/verify_token/gen/Token/Evm2.lean @@ -0,0 +1,439 @@ +-- solar-lean-stage: kind=evm index=2 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x18160ddd)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0x40c10f19)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0x42966c68)), + .op (.stack .eq), + .jumpi 22, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8da5cb5b)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 14, + .jump 1], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 3, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 0x102000000000000000200000009)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack (.push 2)), + .effect .sload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 13, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 2)), + .effect .sload 1, + .op (.stack .and), + .effect .caller 0, + .op (.stack .eq), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 11, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 10, + .op (.stack .iszero), + .jumpi 8, + .op (.stack .pop), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 9, + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 9, + .effect .sstore 2, + .stop], + -- bb24 + [.op (.stack (.push 0x6e6f74206f776e65720000000000000000000000000000000000000000000000)), + .op (.stack (.push 9)), + .jump 26], + -- bb25 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x102000000040000000700000015)), + .jump 12], + -- bb27 + [.op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack (.push 0x417000000040000000700000000)), + .jump 12], + -- bb28 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb29 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb30 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 21, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 2)), + .op (.stack .and), + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 19, + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.dup 0)), + .jumpi 17, + .op (.stack (.dup 4)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 16, + .effect .sstore 2, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 0x102000000050000000400000004)), + .op (.stack (.push 0)), + .jump 20], + -- bb38 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb39 + [.op (.stack (.push 0x696e73756666696369656e740000000000000000000000000000000000000000)), + .op (.stack (.push 12)), + .jump 26], + -- bb40 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10200000005000000060000001c)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 20], + -- bb41 + [.effect .caller 0, + .op (.stack (.push 0x417000000050000000600000000)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 20], + -- bb42 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb43 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb44 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 25, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.dup 3)), + .op (.stack .gt), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 24, + .jumpi 23, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack .gt), + .jumpi 23, + .op (.stack (.push 1)), + .effect .sstore 2, + .stop], + -- bb49 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb50 + [.op (.stack (.push 0x417000000060000000500000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb52 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb53 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Evm3.lean b/Certified/verify_token/gen/Token/Evm3.lean new file mode 100644 index 00000000..087d8071 --- /dev/null +++ b/Certified/verify_token/gen/Token/Evm3.lean @@ -0,0 +1,479 @@ +-- solar-lean-stage: kind=evm index=3 pass=compact-pushes +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `compact-pushes`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x18160ddd)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0x40c10f19)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0x42966c68)), + .op (.stack .eq), + .jumpi 22, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 2, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8da5cb5b)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 14, + .jump 1], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 3, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 0x102000000000000000200000009)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack (.push 2)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 13, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 2)), + .effect .sload 1, + .op (.stack .and), + .effect .caller 0, + .op (.stack .eq), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 11, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 10, + .op (.stack .iszero), + .jumpi 8, + .op (.stack .pop), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 9, + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 9, + .effect .sstore 2, + .stop], + -- bb24 + [.op (.stack (.push 0x6e6f74206f776e6572)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 26], + -- bb25 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x102000000040000000700000015)), + .jump 12], + -- bb27 + [.op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack (.push 0x4170000000400000007)), + .op (.stack (.push 32)), + .op (.stack .shl), + .jump 12], + -- bb28 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb29 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb30 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 21, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .and), + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 19, + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.dup 0)), + .jumpi 17, + .op (.stack (.dup 4)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 16, + .effect .sstore 2, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 0x102000000050000000400000004)), + .op (.stack (.push 0)), + .jump 20], + -- bb38 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb39 + [.op (.stack (.push 0x696e73756666696369656e74)), + .op (.stack (.push 160)), + .op (.stack .shl), + .op (.stack (.push 12)), + .jump 26], + -- bb40 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10200000005000000060000001c)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 20], + -- bb41 + [.effect .caller 0, + .op (.stack (.push 0x4170000000500000006)), + .op (.stack (.push 32)), + .op (.stack .shl), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 20], + -- bb42 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb43 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb44 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 25, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.dup 3)), + .op (.stack .gt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 24, + .jumpi 23, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack .gt), + .jumpi 23, + .op (.stack (.push 1)), + .effect .sstore 2, + .stop], + -- bb49 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb50 + [.op (.stack (.push 0x4170000000600000005)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb52 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb53 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Evm4.lean b/Certified/verify_token/gen/Token/Evm4.lean new file mode 100644 index 00000000..7e87de84 --- /dev/null +++ b/Certified/verify_token/gen/Token/Evm4.lean @@ -0,0 +1,479 @@ +-- solar-lean-stage: kind=evm index=4 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `block-layout`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x18160ddd)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0x40c10f19)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0x42966c68)), + .op (.stack .eq), + .jumpi 19, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8da5cb5b)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 13, + .jump 1], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb25 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb49 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 21, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 20, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack (.push 2)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 22, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 2)), + .effect .sload 1, + .op (.stack .and), + .effect .caller 0, + .op (.stack .eq), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 12, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 10, + .op (.stack .iszero), + .jumpi 8, + .op (.stack .pop), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 2, + .effect .sstore 2, + .stop], + -- bb24 + [.op (.stack (.push 0x6e6f74206f776e6572)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 9], + -- bb53 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x102000000040000000700000015)), + .jump 11], + -- bb28 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb27 + [.op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack (.push 0x4170000000400000007)), + .op (.stack (.push 32)), + .op (.stack .shl), + .jump 11], + -- bb30 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 24, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .and), + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 18, + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.dup 0)), + .jumpi 16, + .op (.stack (.dup 4)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 23, + .effect .sstore 2, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 0)), + .jumpi 14, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 0x102000000050000000400000004)), + .op (.stack (.push 0)), + .jump 15], + -- bb42 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb39 + [.op (.stack (.push 0x696e73756666696369656e74)), + .op (.stack (.push 160)), + .op (.stack .shl), + .op (.stack (.push 12)), + .jump 9], + -- bb40 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10200000005000000060000001c)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 15], + -- bb41 + [.effect .caller 0, + .op (.stack (.push 0x4170000000500000006)), + .op (.stack (.push 32)), + .op (.stack .shl), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 15], + -- bb44 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 26, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.dup 3)), + .op (.stack .gt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 25, + .jumpi 3, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack .gt), + .jumpi 3, + .op (.stack (.push 1)), + .effect .sstore 2, + .stop], + -- bb12 + [.op (.stack (.push 0x102000000000000000200000009)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb29 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb38 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb43 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb50 + [.op (.stack (.push 0x4170000000600000005)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb52 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Evm5.lean b/Certified/verify_token/gen/Token/Evm5.lean new file mode 100644 index 00000000..500db7ec --- /dev/null +++ b/Certified/verify_token/gen/Token/Evm5.lean @@ -0,0 +1,455 @@ +-- solar-lean-stage: kind=evm index=5 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm5 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x18160ddd)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0x40c10f19)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0x42966c68)), + .op (.stack .eq), + .jumpi 19, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8da5cb5b)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 13, + .jump 1], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb25 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb49 + [.jump 2], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 21, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 20, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack (.push 2)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 22, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 2)), + .effect .sload 1, + .op (.stack .and), + .effect .caller 0, + .op (.stack .eq), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 12, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 10, + .op (.stack .iszero), + .jumpi 8, + .op (.stack .pop), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 2, + .effect .sstore 2, + .stop], + -- bb24 + [.op (.stack (.push 0x6e6f74206f776e6572)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 9], + -- bb53 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x102000000040000000700000015)), + .jump 11], + -- bb28 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb27 + [.op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack (.push 0x4170000000400000007)), + .op (.stack (.push 32)), + .op (.stack .shl), + .jump 11], + -- bb30 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 24, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .and), + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 18, + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .op (.stack .sub), + .jumpi 17, + .op (.stack (.dup 0)), + .jumpi 16, + .op (.stack (.dup 4)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 23, + .effect .sstore 2, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 0)), + .jumpi 14, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 0x102000000050000000400000004)), + .op (.stack (.push 0)), + .jump 15], + -- bb42 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb39 + [.op (.stack (.push 0x696e73756666696369656e74)), + .op (.stack (.push 160)), + .op (.stack .shl), + .op (.stack (.push 12)), + .jump 9], + -- bb40 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10200000005000000060000001c)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 15], + -- bb41 + [.effect .caller 0, + .op (.stack (.push 0x4170000000500000006)), + .op (.stack (.push 32)), + .op (.stack .shl), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 15], + -- bb44 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 26, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.dup 3)), + .op (.stack .gt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 25, + .jumpi 3, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack .gt), + .jumpi 3, + .op (.stack (.push 1)), + .effect .sstore 2, + .stop], + -- bb12 + [.op (.stack (.push 0x102000000000000000200000009)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.jump 1], + -- bb29 + [.jump 1], + -- bb38 + [.jump 2], + -- bb43 + [.jump 1], + -- bb50 + [.op (.stack (.push 0x4170000000600000005)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb52 + [.jump 1]] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Evm6.lean b/Certified/verify_token/gen/Token/Evm6.lean new file mode 100644 index 00000000..1c916ba7 --- /dev/null +++ b/Certified/verify_token/gen/Token/Evm6.lean @@ -0,0 +1,443 @@ +-- solar-lean-stage: kind=evm index=6 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm6 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x18160ddd)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x40c10f19)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0x42966c68)), + .op (.stack .eq), + .jumpi 18, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8da5cb5b)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 12, + .jump 1], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb25 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 19, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack (.push 2)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 2)), + .effect .sload 1, + .op (.stack .and), + .effect .caller 0, + .op (.stack .eq), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 11, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 9, + .op (.stack .iszero), + .jumpi 7, + .op (.stack .pop), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 2, + .effect .sstore 2, + .stop], + -- bb24 + [.op (.stack (.push 0x6e6f74206f776e6572)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 8], + -- bb53 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x102000000040000000700000015)), + .jump 10], + -- bb28 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb27 + [.op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack (.push 0x4170000000400000007)), + .op (.stack (.push 32)), + .op (.stack .shl), + .jump 10], + -- bb30 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .and), + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 17, + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .op (.stack .sub), + .jumpi 16, + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack (.dup 4)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 2, + .effect .sstore 2, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 0)), + .jumpi 13, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 0x102000000050000000400000004)), + .op (.stack (.push 0)), + .jump 14], + -- bb42 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb39 + [.op (.stack (.push 0x696e73756666696369656e74)), + .op (.stack (.push 160)), + .op (.stack .shl), + .op (.stack (.push 12)), + .jump 8], + -- bb40 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10200000005000000060000001c)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 14], + -- bb41 + [.effect .caller 0, + .op (.stack (.push 0x4170000000500000006)), + .op (.stack (.push 32)), + .op (.stack .shl), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 14], + -- bb44 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.dup 3)), + .op (.stack .gt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 20, + .jumpi 2, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack .gt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sstore 2, + .stop], + -- bb12 + [.op (.stack (.push 0x102000000000000000200000009)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb50 + [.op (.stack (.push 0x4170000000600000005)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Evm7.lean b/Certified/verify_token/gen/Token/Evm7.lean new file mode 100644 index 00000000..c5c5cef5 --- /dev/null +++ b/Certified/verify_token/gen/Token/Evm7.lean @@ -0,0 +1,414 @@ +-- solar-lean-stage: kind=evm index=7 pass=tail-merge +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `tail-merge`. -/ +def evm7 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x18160ddd)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x40c10f19)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0x42966c68)), + .op (.stack .eq), + .jumpi 18, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8da5cb5b)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 12, + .jump 1], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb25 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 19, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack (.push 2)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 2)), + .effect .sload 1, + .op (.stack .and), + .effect .caller 0, + .op (.stack .eq), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 11, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 9, + .op (.stack .iszero), + .jumpi 7, + .op (.stack .pop), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 2, + .effect .sstore 2, + .stop], + -- bb24 + [.op (.stack (.push 0x6e6f74206f776e6572)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 8], + -- bb53 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .jump 21], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x102000000040000000700000015)), + .jump 10], + -- bb28 + [.jump 23], + -- bb27 + [.op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack (.push 0x4170000000400000007)), + .op (.stack (.push 32)), + .op (.stack .shl), + .jump 10], + -- bb30 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .and), + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 17, + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .op (.stack .sub), + .jumpi 16, + .op (.stack (.dup 0)), + .jumpi 15, + .op (.stack (.dup 4)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 2, + .effect .sstore 2, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 0)), + .jumpi 13, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 0x102000000050000000400000004)), + .op (.stack (.push 0)), + .jump 14], + -- bb42 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .jump 22], + -- bb39 + [.op (.stack (.push 0x696e73756666696369656e74)), + .op (.stack (.push 160)), + .op (.stack .shl), + .op (.stack (.push 12)), + .jump 8], + -- bb40 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10200000005000000060000001c)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 14], + -- bb41 + [.effect .caller 0, + .op (.stack (.push 0x4170000000500000006)), + .op (.stack (.push 32)), + .op (.stack .shl), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 14], + -- bb44 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.dup 3)), + .op (.stack .gt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 20, + .jumpi 2, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack .gt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sstore 2, + .stop], + -- bb12 + [.op (.stack (.push 0x102000000000000000200000009)), + .jump 23], + -- bb50 + [.op (.stack (.push 0x4170000000600000005)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .jump 23], + -- bb54 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb55 + [.op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .jump 21], + -- bb56 + [.op (.stack (.push 32)), + .op .store, + .jump 22]] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Evm8.lean b/Certified/verify_token/gen/Token/Evm8.lean new file mode 100644 index 00000000..b8b1a812 --- /dev/null +++ b/Certified/verify_token/gen/Token/Evm8.lean @@ -0,0 +1,412 @@ +-- solar-lean-stage: kind=evm index=8 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm8 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x18160ddd)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x40c10f19)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0x42966c68)), + .op (.stack .eq), + .jumpi 17, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8da5cb5b)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 11, + .jump 1], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb25 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack (.push 2)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 2)), + .effect .sload 1, + .op (.stack .and), + .effect .caller 0, + .op (.stack .eq), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 10, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 9, + .op (.stack .iszero), + .jumpi 7, + .op (.stack .pop), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 2, + .effect .sstore 2, + .stop], + -- bb24 + [.op (.stack (.push 0x6e6f74206f776e6572)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 8], + -- bb53 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .jump 20], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x102000000040000000700000015)), + .jump 22], + -- bb27 + [.op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack (.push 0x4170000000400000007)), + .op (.stack (.push 32)), + .op (.stack .shl), + .jump 22], + -- bb30 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .and), + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 16, + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .op (.stack .sub), + .jumpi 15, + .op (.stack (.dup 0)), + .jumpi 14, + .op (.stack (.dup 4)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 2, + .effect .sstore 2, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 0)), + .jumpi 12, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 0x102000000050000000400000004)), + .op (.stack (.push 0)), + .jump 13], + -- bb42 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .jump 21], + -- bb39 + [.op (.stack (.push 0x696e73756666696369656e74)), + .op (.stack (.push 160)), + .op (.stack .shl), + .op (.stack (.push 12)), + .jump 8], + -- bb40 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10200000005000000060000001c)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 13], + -- bb41 + [.effect .caller 0, + .op (.stack (.push 0x4170000000500000006)), + .op (.stack (.push 32)), + .op (.stack .shl), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 13], + -- bb44 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.dup 3)), + .op (.stack .gt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 19, + .jumpi 2, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack .gt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sstore 2, + .stop], + -- bb12 + [.op (.stack (.push 0x102000000000000000200000009)), + .jump 22], + -- bb50 + [.op (.stack (.push 0x4170000000600000005)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .jump 22], + -- bb54 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb55 + [.op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .jump 20], + -- bb56 + [.op (.stack (.push 32)), + .op .store, + .jump 21]] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Evm9.lean b/Certified/verify_token/gen/Token/Evm9.lean new file mode 100644 index 00000000..693217bc --- /dev/null +++ b/Certified/verify_token/gen/Token/Evm9.lean @@ -0,0 +1,409 @@ +-- solar-lean-stage: kind=evm index=9 pass=block-cse +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR after `block-cse`. -/ +def evm9 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x18160ddd)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x40c10f19)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0x42966c68)), + .op (.stack .eq), + .jumpi 17, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8da5cb5b)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 11, + .jump 1], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb25 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .jumpi 18, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb15 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack (.push 2)), + .effect .sload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 2)), + .effect .sload 1, + .op (.stack .and), + .effect .caller 0, + .op (.stack .eq), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 10, + .op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .sub), + .jumpi 9, + .op (.stack .iszero), + .jumpi 7, + .op (.stack .pop), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 2, + .effect .sstore 2, + .stop], + -- bb24 + [.op (.stack (.push 0x6e6f74206f776e6572)), + .op (.stack (.push 184)), + .op (.stack .shl), + .op (.stack (.push 9)), + .jump 8], + -- bb53 + [.op (.stack (.push 32)), + .op (.stack (.dup 0)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .jump 20], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x102000000040000000700000015)), + .jump 22], + -- bb27 + [.op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack (.push 0x4170000000400000007)), + .op (.stack (.push 32)), + .op (.stack .shl), + .jump 22], + -- bb30 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.dup 2)), + .op (.stack .and), + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 16, + .op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .op (.stack .sub), + .jumpi 15, + .op (.stack (.dup 0)), + .jumpi 14, + .op (.stack (.dup 4)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 2, + .effect .sstore 2, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 0)), + .jumpi 12, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 0x102000000050000000400000004)), + .op (.stack (.push 0)), + .jump 13], + -- bb42 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .jump 21], + -- bb39 + [.op (.stack (.push 0x696e73756666696369656e74)), + .op (.stack (.push 160)), + .op (.stack .shl), + .op (.stack (.push 12)), + .jump 8], + -- bb40 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10200000005000000060000001c)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 13], + -- bb41 + [.effect .caller 0, + .op (.stack (.push 0x4170000000500000006)), + .op (.stack (.push 32)), + .op (.stack .shl), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .jump 13], + -- bb44 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.dup 3)), + .op (.stack .gt), + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .effect .caller 0, + .op (.stack .gt), + .jumpi 19, + .jumpi 2, + .op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack .gt), + .jumpi 2, + .op (.stack (.push 1)), + .effect .sstore 2, + .stop], + -- bb12 + [.op (.stack (.push 0x102000000000000000200000009)), + .jump 22], + -- bb50 + [.op (.stack (.push 0x4170000000600000005)), + .op (.stack (.push 32)), + .op (.stack .shl), + .effect .caller 0, + .op (.stack (.push 0)), + .op (.stack .not), + .op (.stack (.push 96)), + .op (.stack .shr), + .op (.stack (.swap 1)), + .jump 22], + -- bb54 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb55 + [.op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .jump 20], + -- bb56 + [.op (.stack (.push 32)), + .op .store, + .jump 21]] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Manifest.lean b/Certified/verify_token/gen/Token/Manifest.lean new file mode 100644 index 00000000..54968a8f --- /dev/null +++ b/Certified/verify_token/gen/Token/Manifest.lean @@ -0,0 +1,54 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Token.Manifest + +def sources : List (String × String) := + [("Certified/verify_token/verify_token.sol", "273bfc34729a2a7e3301fc37589096b7efb80480b17636e8ba09b295e537b4a6")] + +def compiler : String := "0.8.38+commit.52e2060e.solar.0.3.0-dev" + +def arguments : List String := + ["Certified/verify_token/verify_token.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/verify_token/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "e8789b9f290cf1dcf806246c20cdddaf6a539bdaac5ab952f735ed8e7842d221"), + ("Mir1", "mir1", "place-reads", "34eb46ed987217db0b8a46f9efffc1d9ef6b6d264a70d38f985b0432c55c92b8"), + ("Mir2", "mir2", "dce", "c69ef3285ed9327c54cbd261bc553f1e30833b5c7d969e5f7d561d51b5d4c800"), + ("Mir3", "mir3", "spell-width-tests", "a0e14bcc6ce3ad310520d0dc83a6ed41a810a05f840b0b1b1242bb6fe43991b4"), + ("Mir4", "mir4", "lower-assumes", "fec78fb4db8520c8556d947523c1c3946fa41cff1627243265d7a7d56a018368"), + ("Mir5", "mir5", "evm-inst-schedule", "d28ef0680a9dab917b735eefa03f82c9c1924c16c886be5734af42b4aeaa4bd6"), + ("Sched", "sched", "stack-schedule", "d22ec9081823db64a1f7dd98e2bb1c86a94014950cac8018f4a148297c74f1c1"), + ("Evm1", "evm1", "peephole-early", "b00ae7c65ba72e834ad9f0aed64d99876cfbabd1de5f936d84648404e6e78e9b"), + ("Evm2", "evm2", "cfg-simplify-early", "c5a63cf9ae35b8ea608781cb478588333d2066ccdbd4c38579abbd86bb841dbf"), + ("Evm3", "evm3", "compact-pushes", "d0272052cc08017a83c2d70a45869065bd0cd73a2d4685f6c680d036c09f61e9"), + ("Evm4", "evm4", "block-layout", "8bb5bfaefd46e5b0e6e01d28581a8a1495d1f3f130dc2837d93e5b400ca64374"), + ("Evm5", "evm5", "terminal-dedup", "fef2e6afb3153d43b289fdc6d7d0ab65f759463de55fa419d324cdf04a008594"), + ("Evm6", "evm6", "cfg-simplify-early", "141f48924b6099305576b3d2785c606c47568b3aee54cf2d9beef2d502c2e0f0"), + ("Evm7", "evm7", "tail-merge", "bdbd21d572ee88d8811a0ab1e1c62f8e09f989347857b9fe0dfcf4963ca5a52d"), + ("Evm8", "evm8", "cfg-simplify-early", "8aae0f7860f60999f0b2eac914ea0f905416fca0770939abc4b14d665d630654"), + ("Evm9", "evm9", "block-cse", "185ba3cdb5c0bd63899660731e7adbed98d62c3f945398db1b18bdc102678aad"), + ("Evm10", "evm10", "block-layout", "87bf65504eccd67ed8061ee984d6aea1dca316d4a6e2c31f68ce688f1d83f1c1"), + ("Evm11", "evm11", "stack-reschedule", "4163c93e749e6c4ddee937f27969e096cf3159573b94bd25af76e52b786bb55b"), + ("Evm12", "evm12", "late-word", "978a10bca872c7a80170961e26234fc7506e4f54d600b571331c34662345d557"), + ("Bytecode", "bytecode", "assemble", "96965b9ad064acc1d154bfc6cfce634b2eac138d9bab75c124b3d9f6959be68d")] + +def bytecodeHex : String := + "346047575f3560e01c806318160ddd14608f57806340c10f191460a957806342966c681461024357806370a0823114605d5780638da5cb5b146099578063a9059cbb14610172575b5f5ffd5b6011602052634e487b715f526024601cfd5b60043560a01c60243610176047576004355f1960601c8116815f525f60205260405f20545f5281810361027f5760205ff35b6001545f5260205ff35b60025460601b60601c5f5260205ff35b60043560a01c60443610176047576004355f1960601c808216906002541633145f1960601c331161015957828203610134571561010c5750602435600154818101908110604b57600155905f525f60205260405f208054918201918210604b5755005b686e6f74206f776e657260b81b60095b602080526040526060526308c379a05b5f526064601cfd5b506d01020000000400000007000000155b6020525b60405260605263ed572b2761012c565b5f1960601c33690417000000040000000760201b610145565b60043560a01c60443610176047576004356024355f1960601c8216335f525f60205260405f2080548381105f1960601c331161022a5785840361020f57806101f85784909103909155925f525060405f208054918201918210604b575560015f52806101dd5760205ff35b6d01020000000500000004000000045f5b9060205290610149565b6b696e73756666696369656e7460a01b600c61011c565b50505090506d010200000005000000060000001c90916101ee565b33690417000000050000000660201b5f1960601c6101ee565b60243610604757600435335f525f60205260405f2080548281039083115f1960601c331161029357604b579055600154818110604b5703600155005b6d0102000000000000000200000009610145565b690417000000060000000560201b335f1960601c9161014556" + +def bytecodeSha256 : String := "dc9b316028e6184a20b02cf865e2b5fa72a87eb066dc745e9a75d5da5fb252d7" + +end SolarTV.Export.Token.Manifest diff --git a/Certified/verify_token/gen/Token/Mir1.lean b/Certified/verify_token/gen/Token/Mir1.lean new file mode 100644 index 00000000..05570253 --- /dev/null +++ b/Certified/verify_token/gen/Token/Mir1.lean @@ -0,0 +1,261 @@ +-- solar-lean-stage: kind=mir index=1 pass=place-reads +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The lowered MIR module after `place-reads`. -/ +def mir1 : MIR.Lowered.Module := + { entry := 8, + functions := [ + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 13 .gt [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 25 .or [.value 9, .value 13]], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .pure 24 .and [.value 26, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5], + .assume false .eq [.value 24, .value 26]], + .ret (.const 0) (.const 32)⟩] }, + -- @totalSupply + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 1], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @owner + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 2], + .pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @mint + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 28) .calldatasize [], + .pure 30 .lt [.value 28, .const 68], + .effect (some 32) .calldataload [.const 4], + .pure 34 .gt [.value 32, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 49 .or [.value 30, .value 34]], + .branch (.value 49) 6 7⟩, + -- bb1 + ⟨[], + [], + .tailCall 7 [.const 9, .const 0x6e6f74206f776e65720000000000000000000000000000000000000000000000]⟩, + -- bb2 + ⟨[], + [.effect (some 51) .calldataload [.const 36], + .effect (some 10) .sload [.const 1], + .pure 17 .add [.value 10, .value 51], + .pure 18 .lt [.value 17, .value 10]], + .branch (.value 18) 3 4⟩, + -- bb3 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb4 + ⟨[], + [.effect none .sstore [.const 1, .value 17], + .effect none .mstore [.const 0, .value 50], + .effect none .mstore [.const 32, .const 0], + .effect (some 43) .keccak256 [.const 0, .const 64], + .effect (some 15) .sload [.value 43], + .pure 25 .add [.value 15, .value 51], + .pure 26 .lt [.value 25, .value 15]], + .branch (.value 26) 3 5⟩, + -- bb5 + ⟨[], + [.effect none .sstore [.value 43, .value 25]], + .stop⟩, + -- bb6 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb7 + ⟨[], + [.effect (some 50) .calldataload [.const 4], + .effect (some 36) .calldataload [.const 36], + .pure 45 .and [.value 50, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 2) .caller [], + .effect (some 4) .sload [.const 2], + .pure 47 .and [.value 4, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 6 .eq [.value 2, .value 47], + .assume true .gt [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 45, .value 50]], + .branch (.value 6) 2 1⟩] }, + -- @transfer + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 36) .calldatasize [], + .pure 38 .lt [.value 36, .const 68], + .effect (some 40) .calldataload [.const 4], + .pure 42 .gt [.value 40, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 67 .or [.value 38, .value 42]], + .branch (.value 67) 5 6⟩, + -- bb1 + ⟨[], + [], + .tailCall 7 [.const 12, .const 0x696e73756666696369656e740000000000000000000000000000000000000000]⟩, + -- bb2 + ⟨[], + [.pure 12 .sub [.value 6, .value 44], + .effect none .sstore [.value 63, .value 12], + .effect none .mstore [.const 0, .value 68], + .effect none .mstore [.const 32, .const 0], + .effect (some 58) .keccak256 [.const 0, .const 64], + .effect (some 20) .sload [.value 58], + .pure 27 .add [.value 20, .value 44], + .pure 28 .lt [.value 27, .value 20]], + .branch (.value 28) 3 4⟩, + -- bb3 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb4 + ⟨[], + [.effect none .sstore [.value 58, .value 27], + .assume false .eq [.value 7, .const 0], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb6 + ⟨[], + [.effect (some 68) .calldataload [.const 4], + .effect (some 44) .calldataload [.const 36], + .pure 65 .and [.value 68, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 0], + .effect (some 63) .keccak256 [.const 0, .const 64], + .effect (some 6) .sload [.value 63], + .pure 7 .lt [.value 6, .value 44], + .assume true .gt [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 65, .value 68]], + .branch (.value 7) 1 2⟩] }, + -- @burn + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 21) .calldatasize [], + .pure 23 .lt [.value 21, .const 36]], + .branch (.value 23) 4 5⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.value 31, .value 10], + .effect (some 8) .sload [.const 1], + .pure 18 .sub [.value 8, .value 25], + .pure 19 .lt [.value 8, .value 25]], + .branch (.value 19) 1 3⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 1, .value 18]], + .stop⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb5 + ⟨[], + [.effect (some 25) .calldataload [.const 4], + .effect (some 2) .caller [], + .effect none .mstore [.const 0, .value 2], + .effect none .mstore [.const 32, .const 0], + .effect (some 31) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 31], + .pure 10 .sub [.value 5, .value 25], + .pure 11 .lt [.value 5, .value 25], + .assume true .gt [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 11) 1 2⟩] }, + -- @revert_error + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 32, .const 32], + .effect none .mstore [.const 64, .value 0], + .effect none .mstore [.const 96, .value 1], + .effect none .mstore [.const 0, .const 0x8c379a0]], + .revert (.const 28) (.const 100)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 8 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 8 [(.const 0x18160ddd, 2), (.const 0x40c10f19, 3), (.const 0x42966c68, 4), (.const 0x70a08231, 5), (.const 0x8da5cb5b, 6), (.const 0xa9059cbb, 7)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 4 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 6 []⟩, + -- bb5 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb6 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb7 + ⟨[], + [], + .tailCall 5 []⟩, + -- bb8 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Mir2.lean b/Certified/verify_token/gen/Token/Mir2.lean new file mode 100644 index 00000000..2064a169 --- /dev/null +++ b/Certified/verify_token/gen/Token/Mir2.lean @@ -0,0 +1,260 @@ +-- solar-lean-stage: kind=mir index=2 pass=dce +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The lowered MIR module after `dce`. -/ +def mir2 : MIR.Lowered.Module := + { entry := 8, + functions := [ + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 13 .gt [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 25 .or [.value 9, .value 13]], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .pure 24 .and [.value 26, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5], + .assume false .eq [.value 24, .value 26]], + .ret (.const 0) (.const 32)⟩] }, + -- @totalSupply + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 1], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @owner + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 2], + .pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @mint + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 28) .calldatasize [], + .pure 30 .lt [.value 28, .const 68], + .effect (some 32) .calldataload [.const 4], + .pure 34 .gt [.value 32, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 49 .or [.value 30, .value 34]], + .branch (.value 49) 6 7⟩, + -- bb1 + ⟨[], + [], + .tailCall 7 [.const 9, .const 0x6e6f74206f776e65720000000000000000000000000000000000000000000000]⟩, + -- bb2 + ⟨[], + [.effect (some 51) .calldataload [.const 36], + .effect (some 10) .sload [.const 1], + .pure 17 .add [.value 10, .value 51], + .pure 18 .lt [.value 17, .value 10]], + .branch (.value 18) 3 4⟩, + -- bb3 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb4 + ⟨[], + [.effect none .sstore [.const 1, .value 17], + .effect none .mstore [.const 0, .value 50], + .effect none .mstore [.const 32, .const 0], + .effect (some 43) .keccak256 [.const 0, .const 64], + .effect (some 15) .sload [.value 43], + .pure 25 .add [.value 15, .value 51], + .pure 26 .lt [.value 25, .value 15]], + .branch (.value 26) 3 5⟩, + -- bb5 + ⟨[], + [.effect none .sstore [.value 43, .value 25]], + .stop⟩, + -- bb6 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb7 + ⟨[], + [.effect (some 50) .calldataload [.const 4], + .pure 45 .and [.value 50, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 2) .caller [], + .effect (some 4) .sload [.const 2], + .pure 47 .and [.value 4, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 6 .eq [.value 2, .value 47], + .assume true .gt [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 45, .value 50]], + .branch (.value 6) 2 1⟩] }, + -- @transfer + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 36) .calldatasize [], + .pure 38 .lt [.value 36, .const 68], + .effect (some 40) .calldataload [.const 4], + .pure 42 .gt [.value 40, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 67 .or [.value 38, .value 42]], + .branch (.value 67) 5 6⟩, + -- bb1 + ⟨[], + [], + .tailCall 7 [.const 12, .const 0x696e73756666696369656e740000000000000000000000000000000000000000]⟩, + -- bb2 + ⟨[], + [.pure 12 .sub [.value 6, .value 44], + .effect none .sstore [.value 63, .value 12], + .effect none .mstore [.const 0, .value 68], + .effect none .mstore [.const 32, .const 0], + .effect (some 58) .keccak256 [.const 0, .const 64], + .effect (some 20) .sload [.value 58], + .pure 27 .add [.value 20, .value 44], + .pure 28 .lt [.value 27, .value 20]], + .branch (.value 28) 3 4⟩, + -- bb3 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb4 + ⟨[], + [.effect none .sstore [.value 58, .value 27], + .assume false .eq [.value 7, .const 0], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb6 + ⟨[], + [.effect (some 68) .calldataload [.const 4], + .effect (some 44) .calldataload [.const 36], + .pure 65 .and [.value 68, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 0], + .effect (some 63) .keccak256 [.const 0, .const 64], + .effect (some 6) .sload [.value 63], + .pure 7 .lt [.value 6, .value 44], + .assume true .gt [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 65, .value 68]], + .branch (.value 7) 1 2⟩] }, + -- @burn + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 21) .calldatasize [], + .pure 23 .lt [.value 21, .const 36]], + .branch (.value 23) 4 5⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.value 31, .value 10], + .effect (some 8) .sload [.const 1], + .pure 18 .sub [.value 8, .value 25], + .pure 19 .lt [.value 8, .value 25]], + .branch (.value 19) 1 3⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 1, .value 18]], + .stop⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb5 + ⟨[], + [.effect (some 25) .calldataload [.const 4], + .effect (some 2) .caller [], + .effect none .mstore [.const 0, .value 2], + .effect none .mstore [.const 32, .const 0], + .effect (some 31) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 31], + .pure 10 .sub [.value 5, .value 25], + .pure 11 .lt [.value 5, .value 25], + .assume true .gt [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 11) 1 2⟩] }, + -- @revert_error + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 32, .const 32], + .effect none .mstore [.const 64, .value 0], + .effect none .mstore [.const 96, .value 1], + .effect none .mstore [.const 0, .const 0x8c379a0]], + .revert (.const 28) (.const 100)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 8 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 8 [(.const 0x18160ddd, 2), (.const 0x40c10f19, 3), (.const 0x42966c68, 4), (.const 0x70a08231, 5), (.const 0x8da5cb5b, 6), (.const 0xa9059cbb, 7)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 4 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 6 []⟩, + -- bb5 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb6 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb7 + ⟨[], + [], + .tailCall 5 []⟩, + -- bb8 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Mir3.lean b/Certified/verify_token/gen/Token/Mir3.lean new file mode 100644 index 00000000..f6c36da9 --- /dev/null +++ b/Certified/verify_token/gen/Token/Mir3.lean @@ -0,0 +1,266 @@ +-- solar-lean-stage: kind=mir index=3 pass=spell-width-tests +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The lowered MIR module after `spell-width-tests`. -/ +def mir3 : MIR.Lowered.Module := + { entry := 8, + functions := [ + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 28 .shr [.const 160, .value 11], + .word 31 (.value 9), + .pure 32 .or [.value 28, .value 31], + .ne 25 (.value 32) (.const 0)], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .pure 24 .and [.value 26, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5], + .assume false .eq [.value 24, .value 26]], + .ret (.const 0) (.const 32)⟩] }, + -- @totalSupply + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 1], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @owner + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 2], + .pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @mint + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 28) .calldatasize [], + .pure 30 .lt [.value 28, .const 68], + .effect (some 32) .calldataload [.const 4], + .pure 53 .shr [.const 160, .value 32], + .word 56 (.value 30), + .pure 57 .or [.value 53, .value 56], + .ne 49 (.value 57) (.const 0)], + .branch (.value 49) 6 7⟩, + -- bb1 + ⟨[], + [], + .tailCall 7 [.const 9, .const 0x6e6f74206f776e65720000000000000000000000000000000000000000000000]⟩, + -- bb2 + ⟨[], + [.effect (some 51) .calldataload [.const 36], + .effect (some 10) .sload [.const 1], + .pure 17 .add [.value 10, .value 51], + .pure 18 .lt [.value 17, .value 10]], + .branch (.value 18) 3 4⟩, + -- bb3 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb4 + ⟨[], + [.effect none .sstore [.const 1, .value 17], + .effect none .mstore [.const 0, .value 50], + .effect none .mstore [.const 32, .const 0], + .effect (some 43) .keccak256 [.const 0, .const 64], + .effect (some 15) .sload [.value 43], + .pure 25 .add [.value 15, .value 51], + .pure 26 .lt [.value 25, .value 15]], + .branch (.value 26) 3 5⟩, + -- bb5 + ⟨[], + [.effect none .sstore [.value 43, .value 25]], + .stop⟩, + -- bb6 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb7 + ⟨[], + [.effect (some 50) .calldataload [.const 4], + .pure 45 .and [.value 50, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 2) .caller [], + .effect (some 4) .sload [.const 2], + .pure 47 .and [.value 4, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 6 .eq [.value 2, .value 47], + .assume true .gt [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 45, .value 50]], + .branch (.value 6) 2 1⟩] }, + -- @transfer + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 36) .calldatasize [], + .pure 38 .lt [.value 36, .const 68], + .effect (some 40) .calldataload [.const 4], + .pure 70 .shr [.const 160, .value 40], + .word 73 (.value 38), + .pure 74 .or [.value 70, .value 73], + .ne 67 (.value 74) (.const 0)], + .branch (.value 67) 5 6⟩, + -- bb1 + ⟨[], + [], + .tailCall 7 [.const 12, .const 0x696e73756666696369656e740000000000000000000000000000000000000000]⟩, + -- bb2 + ⟨[], + [.pure 12 .sub [.value 6, .value 44], + .effect none .sstore [.value 63, .value 12], + .effect none .mstore [.const 0, .value 68], + .effect none .mstore [.const 32, .const 0], + .effect (some 58) .keccak256 [.const 0, .const 64], + .effect (some 20) .sload [.value 58], + .pure 27 .add [.value 20, .value 44], + .pure 28 .lt [.value 27, .value 20]], + .branch (.value 28) 3 4⟩, + -- bb3 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb4 + ⟨[], + [.effect none .sstore [.value 58, .value 27], + .assume false .eq [.value 7, .const 0], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb6 + ⟨[], + [.effect (some 68) .calldataload [.const 4], + .effect (some 44) .calldataload [.const 36], + .pure 65 .and [.value 68, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 0], + .effect (some 63) .keccak256 [.const 0, .const 64], + .effect (some 6) .sload [.value 63], + .pure 7 .lt [.value 6, .value 44], + .assume true .gt [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 65, .value 68]], + .branch (.value 7) 1 2⟩] }, + -- @burn + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 21) .calldatasize [], + .pure 23 .lt [.value 21, .const 36]], + .branch (.value 23) 4 5⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.value 31, .value 10], + .effect (some 8) .sload [.const 1], + .pure 18 .sub [.value 8, .value 25], + .pure 19 .lt [.value 8, .value 25]], + .branch (.value 19) 1 3⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 1, .value 18]], + .stop⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb5 + ⟨[], + [.effect (some 25) .calldataload [.const 4], + .effect (some 2) .caller [], + .effect none .mstore [.const 0, .value 2], + .effect none .mstore [.const 32, .const 0], + .effect (some 31) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 31], + .pure 10 .sub [.value 5, .value 25], + .pure 11 .lt [.value 5, .value 25], + .assume true .gt [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 11) 1 2⟩] }, + -- @revert_error + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 32, .const 32], + .effect none .mstore [.const 64, .value 0], + .effect none .mstore [.const 96, .value 1], + .effect none .mstore [.const 0, .const 0x8c379a0]], + .revert (.const 28) (.const 100)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 8 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 8 [(.const 0x18160ddd, 2), (.const 0x40c10f19, 3), (.const 0x42966c68, 4), (.const 0x70a08231, 5), (.const 0x8da5cb5b, 6), (.const 0xa9059cbb, 7)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 4 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 6 []⟩, + -- bb5 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb6 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb7 + ⟨[], + [], + .tailCall 5 []⟩, + -- bb8 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Mir4.lean b/Certified/verify_token/gen/Token/Mir4.lean new file mode 100644 index 00000000..e5f70c08 --- /dev/null +++ b/Certified/verify_token/gen/Token/Mir4.lean @@ -0,0 +1,349 @@ +-- solar-lean-stage: kind=mir index=4 pass=lower-assumes +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The lowered MIR module after `lower-assumes`. -/ +def mir4 : MIR.Lowered.Module := + { entry := 8, + functions := [ + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 28 .shr [.const 160, .value 11], + .word 31 (.value 9), + .pure 32 .or [.value 28, .value 31], + .ne 25 (.value 32) (.const 0)], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .pure 24 .and [.value 26, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5], + .ne 35 (.value 24) (.value 26)], + .branch (.value 35) 4 5⟩, + -- bb3 + ⟨[(37, [(4, .const 0x102000000000000000200000009)]), (38, [(4, .value 24)]), (39, [(4, .value 26)])], + [.effect none .mstore [.const 32, .value 37], + .effect none .mstore [.const 64, .value 38], + .effect none .mstore [.const 96, .value 39], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩] }, + -- @totalSupply + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 1], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @owner + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 2], + .pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @mint + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 28) .calldatasize [], + .pure 30 .lt [.value 28, .const 68], + .effect (some 32) .calldataload [.const 4], + .pure 53 .shr [.const 160, .value 32], + .word 56 (.value 30), + .pure 57 .or [.value 53, .value 56], + .ne 49 (.value 57) (.const 0)], + .branch (.value 49) 6 7⟩, + -- bb1 + ⟨[], + [], + .tailCall 7 [.const 9, .const 0x6e6f74206f776e65720000000000000000000000000000000000000000000000]⟩, + -- bb2 + ⟨[], + [.effect (some 51) .calldataload [.const 36], + .effect (some 10) .sload [.const 1], + .pure 17 .add [.value 10, .value 51], + .pure 18 .lt [.value 17, .value 10]], + .branch (.value 18) 3 4⟩, + -- bb3 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb4 + ⟨[], + [.effect none .sstore [.const 1, .value 17], + .effect none .mstore [.const 0, .value 50], + .effect none .mstore [.const 32, .const 0], + .effect (some 43) .keccak256 [.const 0, .const 64], + .effect (some 15) .sload [.value 43], + .pure 25 .add [.value 15, .value 51], + .pure 26 .lt [.value 25, .value 15]], + .branch (.value 26) 3 5⟩, + -- bb5 + ⟨[], + [.effect none .sstore [.value 43, .value 25]], + .stop⟩, + -- bb6 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb7 + ⟨[], + [.effect (some 50) .calldataload [.const 4], + .pure 45 .and [.value 50, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 2) .caller [], + .effect (some 4) .sload [.const 2], + .pure 47 .and [.value 4, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 6 .eq [.value 2, .value 47], + .pure 60 .gt [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 60) 9 10⟩, + -- bb8 + ⟨[(64, [(9, .const 0x417000000040000000700000000), (11, .const 0x102000000040000000700000015)]), (65, [(9, .value 2), (11, .value 45)]), (66, [(9, .const 0xffffffffffffffffffffffffffffffffffffffff), (11, .value 50)])], + [.effect none .mstore [.const 32, .value 64], + .effect none .mstore [.const 64, .value 65], + .effect none .mstore [.const 96, .value 66], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb9 + ⟨[], + [], + .jump 8⟩, + -- bb10 + ⟨[], + [.ne 62 (.value 45) (.value 50)], + .branch (.value 62) 11 12⟩, + -- bb11 + ⟨[], + [], + .jump 8⟩, + -- bb12 + ⟨[], + [], + .branch (.value 6) 2 1⟩] }, + -- @transfer + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 36) .calldatasize [], + .pure 38 .lt [.value 36, .const 68], + .effect (some 40) .calldataload [.const 4], + .pure 70 .shr [.const 160, .value 40], + .word 73 (.value 38), + .pure 74 .or [.value 70, .value 73], + .ne 67 (.value 74) (.const 0)], + .branch (.value 67) 5 6⟩, + -- bb1 + ⟨[], + [], + .tailCall 7 [.const 12, .const 0x696e73756666696369656e740000000000000000000000000000000000000000]⟩, + -- bb2 + ⟨[], + [.pure 12 .sub [.value 6, .value 44], + .effect none .sstore [.value 63, .value 12], + .effect none .mstore [.const 0, .value 68], + .effect none .mstore [.const 32, .const 0], + .effect (some 58) .keccak256 [.const 0, .const 64], + .effect (some 20) .sload [.value 58], + .pure 27 .add [.value 20, .value 44], + .pure 28 .lt [.value 27, .value 20]], + .branch (.value 28) 3 4⟩, + -- bb3 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb4 + ⟨[], + [.effect none .sstore [.value 58, .value 27], + .effect none .mstore [.const 0, .const 1], + .word 77 (.value 7), + .ne 79 (.value 77) (.const 0)], + .branch (.value 79) 8 9⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb6 + ⟨[], + [.effect (some 68) .calldataload [.const 4], + .effect (some 44) .calldataload [.const 36], + .pure 65 .and [.value 68, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 0], + .effect (some 63) .keccak256 [.const 0, .const 64], + .effect (some 6) .sload [.value 63], + .pure 7 .lt [.value 6, .value 44], + .pure 81 .gt [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 81) 10 11⟩, + -- bb7 + ⟨[(85, [(8, .const 0x102000000050000000400000004), (10, .const 0x417000000050000000600000000), (12, .const 0x10200000005000000060000001c)]), (86, [(8, .value 77), (10, .value 3), (12, .value 65)]), (87, [(8, .const 0), (10, .const 0xffffffffffffffffffffffffffffffffffffffff), (12, .value 68)])], + [.effect none .mstore [.const 32, .value 85], + .effect none .mstore [.const 64, .value 86], + .effect none .mstore [.const 96, .value 87], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb8 + ⟨[], + [], + .jump 7⟩, + -- bb9 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩, + -- bb10 + ⟨[], + [], + .jump 7⟩, + -- bb11 + ⟨[], + [.ne 83 (.value 65) (.value 68)], + .branch (.value 83) 12 13⟩, + -- bb12 + ⟨[], + [], + .jump 7⟩, + -- bb13 + ⟨[], + [], + .branch (.value 7) 1 2⟩] }, + -- @burn + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 21) .calldatasize [], + .pure 23 .lt [.value 21, .const 36]], + .branch (.value 23) 4 5⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.value 31, .value 10], + .effect (some 8) .sload [.const 1], + .pure 18 .sub [.value 8, .value 25], + .pure 19 .lt [.value 8, .value 25]], + .branch (.value 19) 1 3⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 1, .value 18]], + .stop⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb5 + ⟨[], + [.effect (some 25) .calldataload [.const 4], + .effect (some 2) .caller [], + .effect none .mstore [.const 0, .value 2], + .effect none .mstore [.const 32, .const 0], + .effect (some 31) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 31], + .pure 10 .sub [.value 5, .value 25], + .pure 11 .lt [.value 5, .value 25], + .pure 33 .gt [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 33) 7 8⟩, + -- bb6 + ⟨[(35, [(7, .const 0x417000000060000000500000000)]), (36, [(7, .value 2)]), (37, [(7, .const 0xffffffffffffffffffffffffffffffffffffffff)])], + [.effect none .mstore [.const 32, .value 35], + .effect none .mstore [.const 64, .value 36], + .effect none .mstore [.const 96, .value 37], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb7 + ⟨[], + [], + .jump 6⟩, + -- bb8 + ⟨[], + [], + .branch (.value 11) 1 2⟩] }, + -- @revert_error + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 32, .const 32], + .effect none .mstore [.const 64, .value 0], + .effect none .mstore [.const 96, .value 1], + .effect none .mstore [.const 0, .const 0x8c379a0]], + .revert (.const 28) (.const 100)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 8 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 8 [(.const 0x18160ddd, 2), (.const 0x40c10f19, 3), (.const 0x42966c68, 4), (.const 0x70a08231, 5), (.const 0x8da5cb5b, 6), (.const 0xa9059cbb, 7)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 4 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 6 []⟩, + -- bb5 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb6 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb7 + ⟨[], + [], + .tailCall 5 []⟩, + -- bb8 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Mir5.lean b/Certified/verify_token/gen/Token/Mir5.lean new file mode 100644 index 00000000..864718b2 --- /dev/null +++ b/Certified/verify_token/gen/Token/Mir5.lean @@ -0,0 +1,349 @@ +-- solar-lean-stage: kind=mir index=5 pass=evm-inst-schedule +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The lowered MIR module after `evm-inst-schedule`. -/ +def mir5 : MIR.Lowered.Module := + { entry := 8, + functions := [ + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 11) .calldataload [.const 4], + .pure 28 .shr [.const 160, .value 11], + .effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .word 31 (.value 9), + .pure 32 .or [.value 28, .value 31], + .ne 25 (.value 32) (.const 0)], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 26) .calldataload [.const 4], + .pure 24 .and [.value 26, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 26], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5], + .ne 35 (.value 24) (.value 26)], + .branch (.value 35) 4 5⟩, + -- bb3 + ⟨[(37, [(4, .const 0x102000000000000000200000009)]), (38, [(4, .value 24)]), (39, [(4, .value 26)])], + [.effect none .mstore [.const 32, .value 37], + .effect none .mstore [.const 64, .value 38], + .effect none .mstore [.const 96, .value 39], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb4 + ⟨[], + [], + .jump 3⟩, + -- bb5 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩] }, + -- @totalSupply + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 1], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @owner + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 2], + .pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @mint + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 32) .calldataload [.const 4], + .pure 53 .shr [.const 160, .value 32], + .effect (some 28) .calldatasize [], + .pure 30 .lt [.value 28, .const 68], + .word 56 (.value 30), + .pure 57 .or [.value 53, .value 56], + .ne 49 (.value 57) (.const 0)], + .branch (.value 49) 6 7⟩, + -- bb1 + ⟨[], + [], + .tailCall 7 [.const 9, .const 0x6e6f74206f776e65720000000000000000000000000000000000000000000000]⟩, + -- bb2 + ⟨[], + [.effect (some 51) .calldataload [.const 36], + .effect (some 10) .sload [.const 1], + .pure 17 .add [.value 10, .value 51], + .pure 18 .lt [.value 17, .value 10]], + .branch (.value 18) 3 4⟩, + -- bb3 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb4 + ⟨[], + [.effect none .sstore [.const 1, .value 17], + .effect none .mstore [.const 0, .value 50], + .effect none .mstore [.const 32, .const 0], + .effect (some 43) .keccak256 [.const 0, .const 64], + .effect (some 15) .sload [.value 43], + .pure 25 .add [.value 15, .value 51], + .pure 26 .lt [.value 25, .value 15]], + .branch (.value 26) 3 5⟩, + -- bb5 + ⟨[], + [.effect none .sstore [.value 43, .value 25]], + .stop⟩, + -- bb6 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb7 + ⟨[], + [.effect (some 50) .calldataload [.const 4], + .pure 45 .and [.value 50, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 2) .caller [], + .effect (some 4) .sload [.const 2], + .pure 47 .and [.value 4, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 6 .eq [.value 2, .value 47], + .pure 60 .gt [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 60) 9 10⟩, + -- bb8 + ⟨[(64, [(9, .const 0x417000000040000000700000000), (11, .const 0x102000000040000000700000015)]), (65, [(9, .value 2), (11, .value 45)]), (66, [(9, .const 0xffffffffffffffffffffffffffffffffffffffff), (11, .value 50)])], + [.effect none .mstore [.const 32, .value 64], + .effect none .mstore [.const 64, .value 65], + .effect none .mstore [.const 96, .value 66], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb9 + ⟨[], + [], + .jump 8⟩, + -- bb10 + ⟨[], + [.ne 62 (.value 45) (.value 50)], + .branch (.value 62) 11 12⟩, + -- bb11 + ⟨[], + [], + .jump 8⟩, + -- bb12 + ⟨[], + [], + .branch (.value 6) 2 1⟩] }, + -- @transfer + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 40) .calldataload [.const 4], + .pure 70 .shr [.const 160, .value 40], + .effect (some 36) .calldatasize [], + .pure 38 .lt [.value 36, .const 68], + .word 73 (.value 38), + .pure 74 .or [.value 70, .value 73], + .ne 67 (.value 74) (.const 0)], + .branch (.value 67) 5 6⟩, + -- bb1 + ⟨[], + [], + .tailCall 7 [.const 12, .const 0x696e73756666696369656e740000000000000000000000000000000000000000]⟩, + -- bb2 + ⟨[], + [.pure 12 .sub [.value 6, .value 44], + .effect none .sstore [.value 63, .value 12], + .effect none .mstore [.const 0, .value 68], + .effect none .mstore [.const 32, .const 0], + .effect (some 58) .keccak256 [.const 0, .const 64], + .effect (some 20) .sload [.value 58], + .pure 27 .add [.value 20, .value 44], + .pure 28 .lt [.value 27, .value 20]], + .branch (.value 28) 3 4⟩, + -- bb3 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb4 + ⟨[], + [.effect none .sstore [.value 58, .value 27], + .effect none .mstore [.const 0, .const 1], + .word 77 (.value 7), + .ne 79 (.value 77) (.const 0)], + .branch (.value 79) 8 9⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb6 + ⟨[], + [.effect (some 68) .calldataload [.const 4], + .effect (some 44) .calldataload [.const 36], + .pure 65 .and [.value 68, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 0], + .effect (some 63) .keccak256 [.const 0, .const 64], + .effect (some 6) .sload [.value 63], + .pure 7 .lt [.value 6, .value 44], + .pure 81 .gt [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 81) 10 11⟩, + -- bb7 + ⟨[(85, [(8, .const 0x102000000050000000400000004), (10, .const 0x417000000050000000600000000), (12, .const 0x10200000005000000060000001c)]), (86, [(8, .value 77), (10, .value 3), (12, .value 65)]), (87, [(8, .const 0), (10, .const 0xffffffffffffffffffffffffffffffffffffffff), (12, .value 68)])], + [.effect none .mstore [.const 32, .value 85], + .effect none .mstore [.const 64, .value 86], + .effect none .mstore [.const 96, .value 87], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb8 + ⟨[], + [], + .jump 7⟩, + -- bb9 + ⟨[], + [], + .ret (.const 0) (.const 32)⟩, + -- bb10 + ⟨[], + [], + .jump 7⟩, + -- bb11 + ⟨[], + [.ne 83 (.value 65) (.value 68)], + .branch (.value 83) 12 13⟩, + -- bb12 + ⟨[], + [], + .jump 7⟩, + -- bb13 + ⟨[], + [], + .branch (.value 7) 1 2⟩] }, + -- @burn + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 21) .calldatasize [], + .pure 23 .lt [.value 21, .const 36]], + .branch (.value 23) 4 5⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.value 31, .value 10], + .effect (some 8) .sload [.const 1], + .pure 18 .sub [.value 8, .value 25], + .pure 19 .lt [.value 8, .value 25]], + .branch (.value 19) 1 3⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 1, .value 18]], + .stop⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb5 + ⟨[], + [.effect (some 25) .calldataload [.const 4], + .effect (some 2) .caller [], + .effect none .mstore [.const 0, .value 2], + .effect none .mstore [.const 32, .const 0], + .effect (some 31) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 31], + .pure 10 .sub [.value 5, .value 25], + .pure 11 .lt [.value 5, .value 25], + .pure 33 .gt [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 33) 7 8⟩, + -- bb6 + ⟨[(35, [(7, .const 0x417000000060000000500000000)]), (36, [(7, .value 2)]), (37, [(7, .const 0xffffffffffffffffffffffffffffffffffffffff)])], + [.effect none .mstore [.const 32, .value 35], + .effect none .mstore [.const 64, .value 36], + .effect none .mstore [.const 96, .value 37], + .effect none .mstore [.const 0, .const 0xed572b27]], + .revert (.const 28) (.const 100)⟩, + -- bb7 + ⟨[], + [], + .jump 6⟩, + -- bb8 + ⟨[], + [], + .branch (.value 11) 1 2⟩] }, + -- @revert_error + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 32, .const 32], + .effect none .mstore [.const 64, .value 0], + .effect none .mstore [.const 96, .value 1], + .effect none .mstore [.const 0, .const 0x8c379a0]], + .revert (.const 28) (.const 100)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 8 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 8 [(.const 0x18160ddd, 2), (.const 0x40c10f19, 3), (.const 0x42966c68, 4), (.const 0x70a08231, 5), (.const 0x8da5cb5b, 6), (.const 0xa9059cbb, 7)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 4 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 6 []⟩, + -- bb5 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb6 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb7 + ⟨[], + [], + .tailCall 5 []⟩, + -- bb8 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Sched.lean b/Certified/verify_token/gen/Token/Sched.lean new file mode 100644 index 00000000..6c2d527e --- /dev/null +++ b/Certified/verify_token/gen/Token/Sched.lean @@ -0,0 +1,496 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 8, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x18160ddd)), + .op (.stack .eq), + .jumpi 7, + .op (.stack (.dup 0)), + .op (.stack (.push 0x40c10f19)), + .op (.stack .eq), + .jumpi 6, + .op (.stack (.dup 0)), + .op (.stack (.push 0x42966c68)), + .op (.stack .eq), + .jumpi 5, + .op (.stack (.dup 0)), + .op (.stack (.push 0x70a08231)), + .op (.stack .eq), + .jumpi 4, + .op (.stack (.dup 0)), + .op (.stack (.push 0x8da5cb5b)), + .op (.stack .eq), + .jumpi 3, + .op (.stack (.dup 0)), + .op (.stack (.push 0xa9059cbb)), + .op (.stack .eq), + .jumpi 2, + .jump 8], + -- bb2 + [.jump 30], + -- bb3 + [.jump 16], + -- bb4 + [.jump 9], + -- bb5 + [.jump 44], + -- bb6 + [.jump 17], + -- bb7 + [.jump 15], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb9 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 14, + .jump 10], + -- bb10 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 1)), + .op (.stack .and), + .op (.stack (.dup 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 12, + .jump 11], + -- bb11 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb12 + [.op (.stack (.push 0x102000000000000000200000009)), + .jump 13], + -- bb13 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb14 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb15 + [.op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb16 + [.op (.stack (.push 2)), + .effect .sload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack .and), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb17 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 29, + .jump 18], + -- bb18 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 0)), + .op (.stack (.dup 2)), + .op (.stack .and), + .op (.stack (.swap 0)), + .op (.stack (.push 2)), + .effect .sload 1, + .op (.stack .and), + .effect .caller 0, + .op (.stack .eq), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 27, + .jump 19], + -- bb19 + [.op (.stack (.dup 2)), + .op (.stack (.dup 2)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 26, + .jump 20], + -- bb20 + [.op (.stack .iszero), + .jumpi 24, + .jump 21], + -- bb21 + [.op (.stack .pop), + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 25, + .jump 22], + -- bb22 + [.op (.stack (.push 1)), + .effect .sstore 2, + .op (.stack (.swap 0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 25, + .jump 23], + -- bb23 + [.effect .sstore 2, + .stop], + -- bb24 + [.op (.stack (.push 0x6e6f74206f776e65720000000000000000000000000000000000000000000000)), + .op (.stack (.push 9)), + .jump 53], + -- bb25 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb26 + [.op (.stack .pop), + .op (.stack (.push 0x102000000040000000700000015)), + .jump 28], + -- bb27 + [.op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack (.push 0x417000000040000000700000000)), + .jump 28], + -- bb28 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb29 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb30 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 160)), + .op (.stack .shr), + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .op (.stack .or), + .jumpi 43, + .jump 31], + -- bb31 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .op (.stack (.dup 2)), + .op (.stack .and), + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 3)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 41, + .jump 32], + -- bb32 + [.op (.stack (.dup 5)), + .op (.stack (.dup 4)), + .op (.stack .eq), + .op (.stack .iszero), + .jumpi 40, + .jump 33], + -- bb33 + [.op (.stack (.dup 0)), + .jumpi 39, + .jump 34], + -- bb34 + [.op (.stack (.dup 4)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .effect .sstore 2, + .op (.stack (.swap 2)), + .op (.stack (.push 0)), + .op .store, + .op (.stack .pop), + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .add), + .op (.stack (.swap 1)), + .op (.stack (.dup 2)), + .op (.stack .lt), + .jumpi 38, + .jump 35], + -- bb35 + [.effect .sstore 2, + .op (.stack (.push 1)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.dup 0)), + .jumpi 37, + .jump 36], + -- bb36 + [.op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb37 + [.op (.stack (.push 0x102000000050000000400000004)), + .op (.stack (.push 0)), + .jump 42], + -- bb38 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb39 + [.op (.stack (.push 0x696e73756666696369656e740000000000000000000000000000000000000000)), + .op (.stack (.push 12)), + .jump 53], + -- bb40 + [.op (.stack .pop), + .op (.stack .pop), + .op (.stack .pop), + .op (.stack (.swap 0)), + .op (.stack .pop), + .op (.stack (.push 0x10200000005000000060000001c)), + .op (.stack (.swap 0)), + .op (.stack (.swap 1)), + .jump 42], + -- bb41 + [.effect .caller 0, + .op (.stack (.push 0x417000000050000000600000000)), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 42], + -- bb42 + [.op (.stack (.swap 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.swap 0)), + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb43 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb44 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 52, + .jump 45], + -- bb45 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .effect .caller 0, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 0)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op (.stack (.push 0)), + .effect .keccak256 2, + .op (.stack (.dup 0)), + .effect .sload 1, + .op (.stack (.dup 2)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 0)), + .op (.stack (.dup 3)), + .op (.stack .gt), + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .effect .caller 0, + .op (.stack .gt), + .jumpi 50, + .jump 46], + -- bb46 + [.jumpi 49, + .jump 47], + -- bb47 + [.op (.stack (.swap 0)), + .effect .sstore 2, + .op (.stack (.push 1)), + .effect .sload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .sub), + .op (.stack (.swap 1)), + .op (.stack .gt), + .jumpi 49, + .jump 48], + -- bb48 + [.op (.stack (.push 1)), + .effect .sstore 2, + .stop], + -- bb49 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb50 + [.op (.stack (.push 0x417000000060000000500000000)), + .effect .caller 0, + .op (.stack (.push 0xffffffffffffffffffffffffffffffffffffffff)), + .jump 51], + -- bb51 + [.op (.stack (.swap 1)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0xed572b27)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert], + -- bb52 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb53 + [.op (.stack (.push 32)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 64)), + .op .store, + .op (.stack (.push 96)), + .op .store, + .op (.stack (.push 0x8c379a0)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 100)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/Schedule.json b/Certified/verify_token/gen/Token/Schedule.json new file mode 100644 index 00000000..c545115a --- /dev/null +++ b/Certified/verify_token/gen/Token/Schedule.json @@ -0,0 +1,82 @@ +{ + "functions": [ + {"function": 8, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [7, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [6, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [5, 0], "layout": [], "floating": true, "continues": null}, + {"block": 5, "start": [4, 0], "layout": [], "floating": true, "continues": null}, + {"block": 6, "start": [3, 0], "layout": [], "floating": true, "continues": null}, + {"block": 7, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 8, "start": [8, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 0, "entry": 9, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [9, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [14, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [10, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [13, 0], "layout": ["v39", "v38", "v37"], "floating": true, "continues": null}, + {"block": 4, "start": [12, 0], "layout": ["v26", "v24"], "floating": true, "continues": null}, + {"block": 5, "start": [11, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 1, "entry": 15, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [15, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 2, "entry": 16, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [16, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 4, "entry": 17, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [17, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [24, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [21, 0], "layout": ["v50", "junk"], "floating": true, "continues": null}, + {"block": 3, "start": [25, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [22, 0], "layout": ["v50", "v51", "v17"], "floating": true, "continues": null}, + {"block": 5, "start": [23, 0], "layout": ["v25", "v43"], "floating": true, "continues": null}, + {"block": 6, "start": [29, 0], "layout": [], "floating": true, "continues": null}, + {"block": 7, "start": [18, 0], "layout": [], "floating": true, "continues": null}, + {"block": 8, "start": [28, 0], "layout": ["v66", "v65", "v64"], "floating": true, "continues": null}, + {"block": 9, "start": [27, 0], "layout": [], "floating": true, "continues": null}, + {"block": 10, "start": [19, 0], "layout": ["v50", "v45", "v6"], "floating": true, "continues": null}, + {"block": 11, "start": [26, 0], "layout": ["v50", "v45", "junk"], "floating": true, "continues": null}, + {"block": 12, "start": [20, 0], "layout": ["v50", "junk", "v6"], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 5, "entry": 30, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [30, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [39, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [34, 0], "layout": ["v68", "v44", "junk", "v63", "v6", "v7"], "floating": true, "continues": null}, + {"block": 3, "start": [38, 0], "layout": [], "floating": true, "continues": null}, + {"block": 4, "start": [35, 0], "layout": ["v7", "v27", "v58"], "floating": true, "continues": null}, + {"block": 5, "start": [43, 0], "layout": [], "floating": true, "continues": null}, + {"block": 6, "start": [31, 0], "layout": [], "floating": true, "continues": null}, + {"block": 7, "start": [42, 0], "layout": ["v86", "v85", "v87"], "floating": true, "continues": null}, + {"block": 8, "start": [37, 0], "layout": ["v77"], "floating": true, "continues": null}, + {"block": 9, "start": [36, 0], "layout": [], "floating": true, "continues": null}, + {"block": 10, "start": [41, 0], "layout": [], "floating": true, "continues": null}, + {"block": 11, "start": [32, 0], "layout": ["v68", "v44", "v65", "v63", "v6", "v7"], "floating": true, "continues": null}, + {"block": 12, "start": [40, 0], "layout": ["v68", "junk", "v65", "junk", "junk", "junk"], "floating": true, "continues": null}, + {"block": 13, "start": [33, 0], "layout": ["v68", "v44", "junk", "v63", "v6", "v7"], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 6, "entry": 44, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [44, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [49, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [47, 0], "layout": ["v25", "v31", "v10"], "floating": true, "continues": null}, + {"block": 3, "start": [48, 0], "layout": ["v18"], "floating": true, "continues": null}, + {"block": 4, "start": [52, 0], "layout": [], "floating": true, "continues": null}, + {"block": 5, "start": [45, 0], "layout": [], "floating": true, "continues": null}, + {"block": 6, "start": [51, 0], "layout": ["v35", "v36", "v37"], "floating": true, "continues": null}, + {"block": 7, "start": [50, 0], "layout": [], "floating": true, "continues": null}, + {"block": 8, "start": [46, 0], "layout": ["v25", "v31", "v10", "v11"], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 7, "entry": 53, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [53, 0], "layout": ["v1", "v0"], "floating": true, "continues": null} + ], "calls": [ + ]} + ] +} diff --git a/Certified/verify_token/gen/Token/Stage0.lean b/Certified/verify_token/gen/Token/Stage0.lean new file mode 100644 index 00000000..b515b565 --- /dev/null +++ b/Certified/verify_token/gen/Token/Stage0.lean @@ -0,0 +1,257 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Token`; do not edit. -/ + +namespace SolarTV.Export.Token + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 8, + functions := [ + -- @balanceOf + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 7) .calldatasize [], + .pure 9 .lt [.value 7, .const 36], + .effect (some 11) .calldataload [.const 4], + .pure 13 .gt [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 25 .or [.value 9, .value 13]], + .branch (.value 25) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.pure 24 .and [.value 11, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 11], + .effect none .mstore [.const 32, .const 0], + .effect (some 22) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 22], + .effect none .mstore [.const 0, .value 5], + .assume false .eq [.value 24, .value 11]], + .ret (.const 0) (.const 32)⟩] }, + -- @totalSupply + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 1], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @owner + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 2], + .pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @constructor: not reachable from the runtime entry, so it has no blocks here + { blocks := [] }, + -- @mint + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 28) .calldatasize [], + .pure 30 .lt [.value 28, .const 68], + .effect (some 32) .calldataload [.const 4], + .pure 34 .gt [.value 32, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 49 .or [.value 30, .value 34]], + .branch (.value 49) 6 7⟩, + -- bb1 + ⟨[], + [], + .tailCall 7 [.const 9, .const 0x6e6f74206f776e65720000000000000000000000000000000000000000000000]⟩, + -- bb2 + ⟨[], + [.effect (some 10) .sload [.const 1], + .pure 17 .add [.value 10, .value 36], + .pure 18 .lt [.value 17, .value 10]], + .branch (.value 18) 3 4⟩, + -- bb3 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb4 + ⟨[], + [.effect none .sstore [.const 1, .value 17], + .effect none .mstore [.const 0, .value 32], + .effect none .mstore [.const 32, .const 0], + .effect (some 43) .keccak256 [.const 0, .const 64], + .effect (some 15) .sload [.value 43], + .pure 25 .add [.value 15, .value 36], + .pure 26 .lt [.value 25, .value 15]], + .branch (.value 26) 3 5⟩, + -- bb5 + ⟨[], + [.effect none .sstore [.value 43, .value 25]], + .stop⟩, + -- bb6 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb7 + ⟨[], + [.effect (some 36) .calldataload [.const 36], + .pure 45 .and [.value 32, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 2) .caller [], + .effect (some 4) .sload [.const 2], + .pure 47 .and [.value 4, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 6 .eq [.value 2, .value 47], + .assume true .gt [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 45, .value 32]], + .branch (.value 6) 2 1⟩] }, + -- @transfer + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 36) .calldatasize [], + .pure 38 .lt [.value 36, .const 68], + .effect (some 40) .calldataload [.const 4], + .pure 42 .gt [.value 40, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 67 .or [.value 38, .value 42]], + .branch (.value 67) 5 6⟩, + -- bb1 + ⟨[], + [], + .tailCall 7 [.const 12, .const 0x696e73756666696369656e740000000000000000000000000000000000000000]⟩, + -- bb2 + ⟨[], + [.pure 12 .sub [.value 6, .value 44], + .effect none .sstore [.value 63, .value 12], + .effect none .mstore [.const 0, .value 40], + .effect none .mstore [.const 32, .const 0], + .effect (some 58) .keccak256 [.const 0, .const 64], + .effect (some 20) .sload [.value 58], + .pure 27 .add [.value 20, .value 44], + .pure 28 .lt [.value 27, .value 20]], + .branch (.value 28) 3 4⟩, + -- bb3 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb4 + ⟨[], + [.effect none .sstore [.value 58, .value 27], + .assume false .eq [.value 7, .const 0], + .effect none .mstore [.const 0, .const 1]], + .ret (.const 0) (.const 32)⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb6 + ⟨[], + [.effect (some 44) .calldataload [.const 36], + .pure 65 .and [.value 40, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 3) .caller [], + .effect none .mstore [.const 0, .value 3], + .effect none .mstore [.const 32, .const 0], + .effect (some 63) .keccak256 [.const 0, .const 64], + .effect (some 6) .sload [.value 63], + .pure 7 .lt [.value 6, .value 44], + .assume true .gt [.value 3, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 65, .value 40]], + .branch (.value 7) 1 2⟩] }, + -- @burn + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 21) .calldatasize [], + .pure 23 .lt [.value 21, .const 36]], + .branch (.value 23) 4 5⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.value 31, .value 10], + .effect (some 8) .sload [.const 1], + .pure 18 .sub [.value 8, .value 25], + .pure 19 .lt [.value 8, .value 25]], + .branch (.value 19) 1 3⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 1, .value 18]], + .stop⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb5 + ⟨[], + [.effect (some 25) .calldataload [.const 4], + .effect (some 2) .caller [], + .effect none .mstore [.const 0, .value 2], + .effect none .mstore [.const 32, .const 0], + .effect (some 31) .keccak256 [.const 0, .const 64], + .effect (some 5) .sload [.value 31], + .pure 10 .sub [.value 5, .value 25], + .pure 11 .lt [.value 5, .value 25], + .assume true .gt [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 11) 1 2⟩] }, + -- @revert_error + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 32, .const 32], + .effect none .mstore [.const 64, .value 0], + .effect none .mstore [.const 96, .value 1], + .effect none .mstore [.const 0, .const 0x8c379a0]], + .revert (.const 28) (.const 100)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 8 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 8 [(.const 0x18160ddd, 2), (.const 0x40c10f19, 3), (.const 0x42966c68, 4), (.const 0x70a08231, 5), (.const 0x8da5cb5b, 6), (.const 0xa9059cbb, 7)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 4 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 6 []⟩, + -- bb5 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb6 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb7 + ⟨[], + [], + .tailCall 5 []⟩, + -- bb8 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Token diff --git a/Certified/verify_token/gen/Token/manifest.json b/Certified/verify_token/gen/Token/manifest.json new file mode 100644 index 00000000..51e76a5b --- /dev/null +++ b/Certified/verify_token/gen/Token/manifest.json @@ -0,0 +1,185 @@ +{ + "arguments": [ + "Certified/verify_token/verify_token.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/verify_token/gen" + ], + "bytecode": "346047575f3560e01c806318160ddd14608f57806340c10f191460a957806342966c681461024357806370a0823114605d5780638da5cb5b146099578063a9059cbb14610172575b5f5ffd5b6011602052634e487b715f526024601cfd5b60043560a01c60243610176047576004355f1960601c8116815f525f60205260405f20545f5281810361027f5760205ff35b6001545f5260205ff35b60025460601b60601c5f5260205ff35b60043560a01c60443610176047576004355f1960601c808216906002541633145f1960601c331161015957828203610134571561010c5750602435600154818101908110604b57600155905f525f60205260405f208054918201918210604b5755005b686e6f74206f776e657260b81b60095b602080526040526060526308c379a05b5f526064601cfd5b506d01020000000400000007000000155b6020525b60405260605263ed572b2761012c565b5f1960601c33690417000000040000000760201b610145565b60043560a01c60443610176047576004356024355f1960601c8216335f525f60205260405f2080548381105f1960601c331161022a5785840361020f57806101f85784909103909155925f525060405f208054918201918210604b575560015f52806101dd5760205ff35b6d01020000000500000004000000045f5b9060205290610149565b6b696e73756666696369656e7460a01b600c61011c565b50505090506d010200000005000000060000001c90916101ee565b33690417000000050000000660201b5f1960601c6101ee565b60243610604757600435335f525f60205260405f2080548281039083115f1960601c331161029357604b579055600154818110604b5703600155005b6d0102000000000000000200000009610145565b690417000000060000000560201b335f1960601c9161014556", + "bytecode_sha256": "dc9b316028e6184a20b02cf865e2b5fa72a87eb066dc745e9a75d5da5fb252d7", + "compiler": "0.8.38+commit.52e2060e.solar.0.3.0-dev", + "contract": "Token", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"Certified/verify_token/verify_token.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/verify_token/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/verify_token/gen\"), keep_asts: false, forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "Certified/verify_token/verify_token.sol", + "sha256": "273bfc34729a2a7e3301fc37589096b7efb80480b17636e8ba09b295e537b4a6" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "e8789b9f290cf1dcf806246c20cdddaf6a539bdaac5ab952f735ed8e7842d221" + }, + { + "definition": "mir1", + "file": "Mir1.lean", + "index": 1, + "kind": "mir", + "pass": "place-reads", + "sha256": "34eb46ed987217db0b8a46f9efffc1d9ef6b6d264a70d38f985b0432c55c92b8" + }, + { + "definition": "mir2", + "file": "Mir2.lean", + "index": 2, + "kind": "mir", + "pass": "dce", + "sha256": "c69ef3285ed9327c54cbd261bc553f1e30833b5c7d969e5f7d561d51b5d4c800" + }, + { + "definition": "mir3", + "file": "Mir3.lean", + "index": 3, + "kind": "mir", + "pass": "spell-width-tests", + "sha256": "a0e14bcc6ce3ad310520d0dc83a6ed41a810a05f840b0b1b1242bb6fe43991b4" + }, + { + "definition": "mir4", + "file": "Mir4.lean", + "index": 4, + "kind": "mir", + "pass": "lower-assumes", + "sha256": "fec78fb4db8520c8556d947523c1c3946fa41cff1627243265d7a7d56a018368" + }, + { + "definition": "mir5", + "file": "Mir5.lean", + "index": 5, + "kind": "mir", + "pass": "evm-inst-schedule", + "sha256": "d28ef0680a9dab917b735eefa03f82c9c1924c16c886be5734af42b4aeaa4bd6" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "d22ec9081823db64a1f7dd98e2bb1c86a94014950cac8018f4a148297c74f1c1" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "peephole-early", + "sha256": "b00ae7c65ba72e834ad9f0aed64d99876cfbabd1de5f936d84648404e6e78e9b" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "c5a63cf9ae35b8ea608781cb478588333d2066ccdbd4c38579abbd86bb841dbf" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "compact-pushes", + "sha256": "d0272052cc08017a83c2d70a45869065bd0cd73a2d4685f6c680d036c09f61e9" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "block-layout", + "sha256": "8bb5bfaefd46e5b0e6e01d28581a8a1495d1f3f130dc2837d93e5b400ca64374" + }, + { + "definition": "evm5", + "file": "Evm5.lean", + "index": 5, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "fef2e6afb3153d43b289fdc6d7d0ab65f759463de55fa419d324cdf04a008594" + }, + { + "definition": "evm6", + "file": "Evm6.lean", + "index": 6, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "141f48924b6099305576b3d2785c606c47568b3aee54cf2d9beef2d502c2e0f0" + }, + { + "definition": "evm7", + "file": "Evm7.lean", + "index": 7, + "kind": "evm", + "pass": "tail-merge", + "sha256": "bdbd21d572ee88d8811a0ab1e1c62f8e09f989347857b9fe0dfcf4963ca5a52d" + }, + { + "definition": "evm8", + "file": "Evm8.lean", + "index": 8, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "8aae0f7860f60999f0b2eac914ea0f905416fca0770939abc4b14d665d630654" + }, + { + "definition": "evm9", + "file": "Evm9.lean", + "index": 9, + "kind": "evm", + "pass": "block-cse", + "sha256": "185ba3cdb5c0bd63899660731e7adbed98d62c3f945398db1b18bdc102678aad" + }, + { + "definition": "evm10", + "file": "Evm10.lean", + "index": 10, + "kind": "evm", + "pass": "block-layout", + "sha256": "87bf65504eccd67ed8061ee984d6aea1dca316d4a6e2c31f68ce688f1d83f1c1" + }, + { + "definition": "evm11", + "file": "Evm11.lean", + "index": 11, + "kind": "evm", + "pass": "stack-reschedule", + "sha256": "4163c93e749e6c4ddee937f27969e096cf3159573b94bd25af76e52b786bb55b" + }, + { + "definition": "evm12", + "file": "Evm12.lean", + "index": 12, + "kind": "evm", + "pass": "late-word", + "sha256": "978a10bca872c7a80170961e26234fc7506e4f54d600b571331c34662345d557" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "96965b9ad064acc1d154bfc6cfce634b2eac138d9bab75c124b3d9f6959be68d" + } + ] +} diff --git a/Certified/verify_token/headline b/Certified/verify_token/headline new file mode 100644 index 00000000..def2f22a --- /dev/null +++ b/Certified/verify_token/headline @@ -0,0 +1 @@ +Contracts.Token.EndToEnd Contracts.Token.spec_holds_of_bytecode diff --git a/Certified/verify_token/heartbeats b/Certified/verify_token/heartbeats new file mode 100644 index 00000000..d8a0d1ed --- /dev/null +++ b/Certified/verify_token/heartbeats @@ -0,0 +1 @@ +8000000 diff --git a/Certified/verify_token/options b/Certified/verify_token/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/verify_token/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/verify_token/record.json b/Certified/verify_token/record.json new file mode 100644 index 00000000..560366e1 --- /dev/null +++ b/Certified/verify_token/record.json @@ -0,0 +1,106 @@ +{ + "contract": "Token", + "name": "verify_token", + "source": "Certified/verify_token/verify_token.sol", + "bytecode": "346047575f3560e01c806318160ddd14608f57806340c10f191460a957806342966c681461024357806370a0823114605d5780638da5cb5b146099578063a9059cbb14610172575b5f5ffd5b6011602052634e487b715f526024601cfd5b60043560a01c60243610176047576004355f1960601c8116815f525f60205260405f20545f5281810361027f5760205ff35b6001545f5260205ff35b60025460601b60601c5f5260205ff35b60043560a01c60443610176047576004355f1960601c808216906002541633145f1960601c331161015957828203610134571561010c5750602435600154818101908110604b57600155905f525f60205260405f208054918201918210604b5755005b686e6f74206f776e657260b81b60095b602080526040526060526308c379a05b5f526064601cfd5b506d01020000000400000007000000155b6020525b60405260605263ed572b2761012c565b5f1960601c33690417000000040000000760201b610145565b60043560a01c60443610176047576004356024355f1960601c8216335f525f60205260405f2080548381105f1960601c331161022a5785840361020f57806101f85784909103909155925f525060405f208054918201918210604b575560015f52806101dd5760205ff35b6d01020000000500000004000000045f5b9060205290610149565b6b696e73756666696369656e7460a01b600c61011c565b50505090506d010200000005000000060000001c90916101ee565b33690417000000050000000660201b5f1960601c6101ee565b60243610604757600435335f525f60205260405f2080548281039083115f1960601c331161029357604b579055600154818110604b5703600155005b6d0102000000000000000200000009610145565b690417000000060000000560201b335f1960601c9161014556", + "solar": "cb5053ab39adfd59820913b336d346389ce1b8d9", + "solidity_lean": "11fb9334142fbb8ded0b1d699015a978cdc3ed52", + "mir_to_evmir": "proved: SolarTV.Milestone.VerifyToken.verify_token_mir_to_evmir", + "assembly": "decoded only: verify_token.Proofs.Assembly (the bytecode decodes to the final EVM IR's instructions; no execution theorem)", + "vc": "exported to .lake/certify/verify_token/VC.lean", + "end_to_end": "proved (contract-specific): Contracts.Token.spec_holds_of_bytecode", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, Shapes.Certified.equivG)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with an allowed status; the bytecode too, at gas from the bound on", + "spec": "proved (published statement, Shapes.Meets): the specification of every source result on a valid call, hence of every bytecode result that is not an inert failure", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result", + "assumptions": [ + "SolidCore.Verify.VC.Token.HashInj" + ], + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: transfer, burn, mint, totalSupply and owner ABI-encoded with clean argument words, no value, from any storage that writes slot 2 (owner); balanceOf (a public mapping getter outside the generic stage's fragment) and calls with value are outside the statement", + "spec: transfer's three ensures clauses on distinct addresses (trPost) and burn's (burnPost), on success only; mint, totalSupply and owner have none; the spec declares no revert condition, so every status is allowed (Allowed is True): a revert meets the statement", + "assumption HashInj: keccak256 of (address, 0) is injective on addresses (the mapping's slots), a premise of the statement, not proved" + ], + "strongest": true + }, + "final": { + "module": "verify_token.Final", + "theorem": "Certified.verify_token.Final.final", + "kind": "certified", + "statement": "code.data.toList.map (·.toNat) = runtimeBytes ∧ ((SolidCore.Verify.VC.Token.HashInj) → ∃ c, SolidCore.Verify.VC.Token.contract? = .ok c ∧ Shapes.Certified (solidCore (SolidCore.Verify.VC.Token.fuel)) c code (SolidCore.Refinement.Shapes.genericValid0 ([SolidCore.Verify.VC.Token.fnTransfer, SolidCore.Verify.VC.Token.fnBurn, SolidCore.Refinement.Solar.VerifyTokenSource.fnMint, SolidCore.Refinement.Solar.VerifyTokenSource.fnTotalSupply, SolidCore.Refinement.Solar.VerifyTokenSource.fnOwner]) ([(2, 4096)])) (fun _ _ => True) (fun call obs => (SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Token.fnTransfer [(2, 4096)] call → SolidCore.Verify.VC.Token.trPost call obs) ∧ (SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Token.fnBurn [(2, 4096)] call → SolidCore.Verify.VC.Token.burnPost call obs)) (fun _ => 42697212))", + "assumptions": [ + "SolidCore.Verify.VC.Token.HashInj" + ], + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: transfer, burn, mint, totalSupply and owner ABI-encoded with clean argument words, no value, from any storage that writes slot 2 (owner); balanceOf (a public mapping getter outside the generic stage's fragment) and calls with value are outside the statement", + "spec: transfer's three ensures clauses on distinct addresses (trPost) and burn's (burnPost), on success only; mint, totalSupply and owner have none; the spec declares no revert condition, so every status is allowed (Allowed is True): a revert meets the statement", + "assumption HashInj: keccak256 of (address, 0) is injective on addresses (the mapping's slots), a premise of the statement, not proved" + ], + "spec": "solar-verify's Token spec (scripts/verify/Token.sol): transfer's three ensures clauses on distinct addresses (trPost) and burn's (burnPost), on success; the discharged obligations Contracts.Token.Discharge / VC.Burn", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, Shapes.Certified.equivG)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with an allowed status; the bytecode too, at gas from the bound on", + "spec": "proved (published statement, Shapes.Meets): the specification of every source result on a valid call, hence of every bytecode result that is not an inert failure", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result" + } + }, + "end_to_end_statement": { + "Contracts.Token.spec_holds_of_bytecode": "SolidCore.Verify.VC.Token.HashInj → (∀ (call : SolarTV.Call), SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Token.fnTransfer [(2, 4096)] call → ∃ obs, SolidCore.Refinement.Target.run SolidCore.Refinement.Solar.VerifyTokenAsm.code call = some obs ∧ SolidCore.Verify.VC.Token.trPost call obs) ∧ ∀ (call : SolarTV.Call), SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Token.fnBurn [(2, 4096)] call → ∃ obs, SolidCore.Refinement.Target.run SolidCore.Refinement.Solar.VerifyTokenAsm.code call = some obs ∧ SolidCore.Verify.VC.Token.burnPost call obs" + }, + "binding": { + "Contracts.Token.spec_holds_of_bytecode": "statement reaches the fresh export" + }, + "hypotheses": { + "Contracts.Token.spec_holds_of_bytecode": [ + "SolidCore.Verify.VC.Token.HashInj", + "(∀ (call : SolarTV.Call), SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Token.fnTransfer [(2, 4096)] call → ∃ obs, SolidCore.Refinement.Target.run SolidCore.Refinement.Solar.VerifyTokenAsm.code call = some obs ∧ SolidCore.Verify.VC.Token.trPost call obs) ∧ ∀ (call : SolarTV.Call), SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Token.fnBurn [(2, 4096)] call" + ] + }, + "refused": [], + "vacuous": "not checked", + "assembly_statement": null, + "assembly_hypotheses": null, + "negative_tests": false, + "caveats": [ + "solidity-lean at 11fb9334142fbb8ded0b1d699015a978cdc3ed52, not the pinned 95ebfd5f178b93b42d498a124104fc92bfc6b74f", + "solar cb5053ab39adfd59820913b336d346389ce1b8d9, not built from this checkout's compiler sources", + "assembly decoded, not executed", + "negative tests skipped" + ], + "backend": { + "theorem": { + "module": "verify_token.Final", + "theorem": "Certified.verify_token.Final.final", + "kind": "certified", + "statement": "code.data.toList.map (·.toNat) = runtimeBytes ∧ ((SolidCore.Verify.VC.Token.HashInj) → ∃ c, SolidCore.Verify.VC.Token.contract? = .ok c ∧ Shapes.Certified (solidCore (SolidCore.Verify.VC.Token.fuel)) c code (SolidCore.Refinement.Shapes.genericValid0 ([SolidCore.Verify.VC.Token.fnTransfer, SolidCore.Verify.VC.Token.fnBurn, SolidCore.Refinement.Solar.VerifyTokenSource.fnMint, SolidCore.Refinement.Solar.VerifyTokenSource.fnTotalSupply, SolidCore.Refinement.Solar.VerifyTokenSource.fnOwner]) ([(2, 4096)])) (fun _ _ => True) (fun call obs => (SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Token.fnTransfer [(2, 4096)] call → SolidCore.Verify.VC.Token.trPost call obs) ∧ (SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Token.fnBurn [(2, 4096)] call → SolidCore.Verify.VC.Token.burnPost call obs)) (fun _ => 42697212))", + "assumptions": [ + "SolidCore.Verify.VC.Token.HashInj" + ], + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: transfer, burn, mint, totalSupply and owner ABI-encoded with clean argument words, no value, from any storage that writes slot 2 (owner); balanceOf (a public mapping getter outside the generic stage's fragment) and calls with value are outside the statement", + "spec: transfer's three ensures clauses on distinct addresses (trPost) and burn's (burnPost), on success only; mint, totalSupply and owner have none; the spec declares no revert condition, so every status is allowed (Allowed is True): a revert meets the statement", + "assumption HashInj: keccak256 of (address, 0) is injective on addresses (the mapping's slots), a premise of the statement, not proved" + ], + "spec": "solar-verify's Token spec (scripts/verify/Token.sol): transfer's three ensures clauses on distinct addresses (trPost) and burn's (burnPost), on success; the discharged obligations Contracts.Token.Discharge / VC.Burn", + "statuses": { + "equivalence": "proved (published statement, Shapes.Equiv): at every gas below 2^256 every result of the exact bytecode on a valid call is the source's, or a failure that changes nothing (out of gas or a revert, whatever its data); such a failure only below the gas bound, and from the bound on exactly the source's, revert data included (Shapes.EquivG, Shapes.Certified.equivG)", + "termination": "proved (published statement, Shapes.Terminates): the source ends on every valid call with an allowed status; the bytecode too, at gas from the bound on", + "spec": "proved (published statement, Shapes.Meets): the specification of every source result on a valid call, hence of every bytecode result that is not an inert failure", + "resources": "proved (published statement, Shapes.Resources): from the gas bound on, below 2^64, the bytecode gives the source's result" + } + } + } +} diff --git a/Certified/verify_token/shape.json b/Certified/verify_token/shape.json new file mode 100644 index 00000000..edc4b3ba --- /dev/null +++ b/Certified/verify_token/shape.json @@ -0,0 +1,78 @@ +{ + "kind": "certified", + "contract": "SolidCore.Verify.VC.Token.contract?", + "fuel": "SolidCore.Verify.VC.Token.fuel", + "valid": "SolidCore.Refinement.Shapes.genericValid0 ([SolidCore.Verify.VC.Token.fnTransfer, SolidCore.Verify.VC.Token.fnBurn, SolidCore.Refinement.Solar.VerifyTokenSource.fnMint, SolidCore.Refinement.Solar.VerifyTokenSource.fnTotalSupply, SolidCore.Refinement.Solar.VerifyTokenSource.fnOwner]) ([(2, 4096)])", + "allowed_export": true, + "spec_export": { + "ctx": "SolidCore.Refinement.Shapes.ctxOfCall", + "step": "SolidCore.Refinement.Shapes.idStep" + }, + "nonvacuous": "Certified.verify_token.Shape.nonvacuous", + "gas": "fun _ => 42697212", + "env": [ + "SolidCore.Spec.MapSlotsSeparated [0]" + ], + "spec": "solar-verify's export of verify_token.sol in this run (Certified.verify_token.gen.Token.Spec.Token): mint, transfer and burn with their ensures (balances, totalSupply, frame of every other balance, transfer's return) and succeeds-if conditions (msg.value == 0; mint: the sender is the owner and neither sum overflows; transfer: the sender's balance covers the amount and the recipient's does not overflow; burn: the balance and the supply cover the amount). The postcondition (bundlePost) and the allowed statuses (bundleAllowed) are both read off that export", + "spec_modules": [ + "Contracts.Token.Lowering", + "Verify.ShapeGeneric", + "Verify.Spec.TreeMap", + "Verify.ShapeSpecExport" + ], + "proof_module": "verify_token.Shape", + "proof": "Certified.verify_token.Shape.published", + "generic": { + "lowering": "Contracts.Token.Lowering", + "imports": [], + "ns": "SolidCore.Refinement.Solar.VerifyTokenSource", + "source_ns": "SolidCore.Verify.VC.Token", + "style": "checked", + "contract_ok": "SolidCore.Refinement.Solar.VerifyTokenSource.contract_ok", + "checks": [ + [ + "transfer", + "SolidCore.Refinement.Solar.VerifyTokenSource.check_transfer_eq" + ], + [ + "burn", + "SolidCore.Refinement.Solar.VerifyTokenSource.check_burn_eq" + ], + [ + "mint", + "SolidCore.Refinement.Solar.VerifyTokenSource.check_mint_eq" + ], + [ + "totalSupply", + "SolidCore.Refinement.Solar.VerifyTokenSource.check_totalSupply_eq" + ], + [ + "owner", + "SolidCore.Refinement.Solar.VerifyTokenSource.check_owner_eq" + ] + ], + "fns": "[SolidCore.Verify.VC.Token.fnTransfer, SolidCore.Verify.VC.Token.fnBurn, SolidCore.Refinement.Solar.VerifyTokenSource.fnMint, SolidCore.Refinement.Solar.VerifyTokenSource.fnTotalSupply, SolidCore.Refinement.Solar.VerifyTokenSource.fnOwner]", + "storage": "[(2, 4096)]", + "spec_connect": { + "witness": "transfer", + "ghost_fixed": true, + "core": "Contracts.Token.VC.Burn", + "ns": "SolidCore.Verify.VC.Token" + } + }, + "excluded": [ + "deployment: the init code is not covered; the statement is about the runtime bytecode from any storage that writes the slots the constructor writes", + "source model trusted: SolidCore's checked contract (the solc AST through scripts/solc_ast_to_lean_source.py and the type checker) is the meaning of the source (frontend trust boundary)", + "calls: one frame, caller 0x2000, contract at 0x1000, the block and transaction of Target.message; no external calls, GAS reads or return data in the code (the loop checker's fragment)", + "gas: the bound is the loop checker's (22100 per item times the final EVM IR's block fuel, plus memory), coarse; below it the bytecode may fail without effects, which equivalence admits", + "valid calls: transfer, burn, mint, totalSupply and owner ABI-encoded with clean argument words, no value, from any storage that writes slot 2 (owner); balanceOf (a public mapping getter outside the generic stage's fragment) and calls with value are outside the statement", + "spec: solar-verify's exported spec of mint, transfer and burn, with their succeeds-if conditions; totalSupply and owner are public getters with no spec; the ghost sum of balances is not stated (spec_connect proves ghost-free specs only)", + "assumption SolidCore.Spec.MapSlotsSeparated [0] (keccak256 as an uninterpreted function: injective on the preimages of balanceOf[a], with images at least 2^128, apart from the scalar slots), a named premise of the statement, not proved; it stands in for the KeccakModel premise and replaces HashInj", + "sender: every call is from 0x2000 (the interface's one frame); the owner is whatever slot 2 holds, any value" + ], + "source_ast": { + "file": "Contracts/Token/VC/Source.lean", + "namespace": "SolidCore.Verify.VC.Source.Token", + "contract": "Token" + } +} diff --git a/Certified/verify_token/verify_token.sol b/Certified/verify_token/verify_token.sol new file mode 100644 index 00000000..de93aafc --- /dev/null +++ b/Certified/verify_token/verify_token.sol @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +/// A minimal token. +contract Token { + mapping(address => uint256) public balanceOf; + uint256 public totalSupply; + address public owner; + + modifier onlyOwner() { + require(msg.sender == owner, "not owner"); + _; + } + + /// @custom:ensures owner == msg.sender + constructor() { + owner = msg.sender; + } + + /// @custom:succeeds-if msg.value == 0 && (msg.sender == owner && totalSupply + amount < 2 ** 256 && balanceOf[to] + amount < 2 ** 256) + /// @custom:ensures balanceOf[to] == old(balanceOf[to]) + amount + /// @custom:ensures totalSupply == old(totalSupply) + amount + /// @custom:ensures forall address a :: a != to ==> balanceOf[a] == old(balanceOf[a]) + function mint(address to, uint256 amount) external onlyOwner { + totalSupply += amount; + balanceOf[to] += amount; + } + + /// @custom:succeeds-if msg.value == 0 && (balanceOf[msg.sender] >= amount && (msg.sender == to || balanceOf[to] + amount < 2 ** 256)) + /// @custom:ensures msg.sender != to ==> balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount + /// @custom:ensures msg.sender != to ==> balanceOf[to] == old(balanceOf[to]) + amount + /// @custom:ensures msg.sender == to ==> balanceOf[to] == old(balanceOf[to]) + /// @custom:ensures forall address a :: a != msg.sender && a != to ==> balanceOf[a] == old(balanceOf[a]) + /// @custom:ensures totalSupply == old(totalSupply) + /// @custom:ensures result == true + function transfer(address to, uint256 amount) external returns (bool) { + uint256 bal = balanceOf[msg.sender]; + require(bal >= amount, "insufficient"); + balanceOf[msg.sender] = bal - amount; + balanceOf[to] += amount; + return true; + } + + /// @custom:succeeds-if msg.value == 0 && (balanceOf[msg.sender] >= amount && totalSupply >= amount) + /// @custom:ensures balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount + /// @custom:ensures totalSupply == old(totalSupply) - amount + /// @custom:ensures forall address a :: a != msg.sender ==> balanceOf[a] == old(balanceOf[a]) + function burn(uint256 amount) external { + balanceOf[msg.sender] -= amount; + totalSupply -= amount; + } +} diff --git a/Certified/w1/W1.lean b/Certified/w1/W1.lean new file mode 100644 index 00000000..401f3b38 --- /dev/null +++ b/Certified/w1/W1.lean @@ -0,0 +1,2 @@ +import gen.Stages +import W1.Sanity diff --git a/Certified/w1/W1/Sanity.lean b/Certified/w1/W1/Sanity.lean new file mode 100644 index 00000000..bd070472 --- /dev/null +++ b/Certified/w1/W1/Sanity.lean @@ -0,0 +1,110 @@ +import gen.Stages + +/-! Each exported artifact of w1 run in Lean on concrete calls. + +Every artifact, from the first lowered MIR to the final EVM IR, observes the same result on +each call below: a valid addition returns the sum, an overflowing one reverts with +`Panic(0x11)`, a call with value, an unknown selector and short calldata revert empty. The +results are checked by the kernel (`decide +kernel`), with no native evaluation; the oracle is +irrelevant here, since w1 reads nothing from it. -/ + +namespace SolarTV.Milestone.W1.Sanity + +open SolarTV Machine EvmRules + +/-- An oracle that answers zero, for solidity-lean's test caller. -/ +def oracle : Oracle := + ⟨fun _ _ _ => 0, fun _ => 0, fun _ _ => 0, fun _ _ => 0, fun _ => 0, + BitVec.ofNat 160 environment.caller⟩ + +/-- The big-endian 32 bytes of a word. -/ +def word (n : Nat) : List UInt8 := (List.range 32).map fun i => UInt8.ofNat (n / 256 ^ (31 - i)) + +/-- A call of `f(a, b)`, selector `0x13d1aa2e`, with `value` wei and the selector `selector`. -/ +def call (a b : Nat) (value : Nat := 0) (selector : List UInt8 := [0x13, 0xd1, 0xaa, 0x2e]) : + Call := + ⟨⟨(selector ++ word a ++ word b).toArray⟩, value, []⟩ + +/-- A call whose calldata is only the selector and one argument. -/ +def short : Call := ⟨⟨([0x13, 0xd1, 0xaa, 0x2e] ++ word 1).toArray⟩, 0, []⟩ + +/-- Success and output of an end, as `observe` gives them. -/ +def outcome (c : Call) : Option (Halt × State) → Option (Bool × List Nat) + | some r => some ((observe c r.2 r.1).success, (observe c r.2 r.1).output) + | none => none + +def mir (m : MIR.Lowered.Module) (c : Call) : Option (Bool × List Nat) := + outcome c (MIR.Lowered.Module.run oracle m c 16) + +def evm (p : EVM.Program.Program) (c : Call) : Option (Bool × List Nat) := + outcome c (EVM.Program.run oracle p c 32) + +def sum : Option (Bool × List Nat) := some (true, List.replicate 31 0 ++ [3]) + +def panic : Option (Bool × List Nat) := + some (false, [0x4e, 0x48, 0x7b, 0x71] ++ List.replicate 31 0 ++ [0x11]) + +def empty : Option (Bool × List Nat) := some (false, []) + +def max : Nat := 2 ^ 256 - 1 + +/-! The first lowered MIR. -/ + +theorem stage0_sum : mir Export.Main.stage0 (call 1 2) = sum := by decide +kernel +theorem stage0_overflow : mir Export.Main.stage0 (call max 1) = panic := by decide +kernel +theorem stage0_value : mir Export.Main.stage0 (call 1 2 (value := 1)) = empty := by decide +kernel +theorem stage0_selector : + mir Export.Main.stage0 (call 1 2 (selector := [0, 0, 0, 0])) = empty := by decide +kernel +theorem stage0_short : mir Export.Main.stage0 short = empty := by decide +kernel + +/-! The scheduled EVM IR and the output of every EVM IR pass. -/ + +theorem sched_sum : evm Export.Main.sched (call 1 2) = sum := by decide +kernel +theorem sched_overflow : evm Export.Main.sched (call max 1) = panic := by decide +kernel +theorem sched_value : evm Export.Main.sched (call 1 2 (value := 1)) = empty := by decide +kernel +theorem sched_selector : + evm Export.Main.sched (call 1 2 (selector := [0, 0, 0, 0])) = empty := by decide +kernel +theorem sched_short : evm Export.Main.sched short = empty := by decide +kernel + +theorem evm1_sum : evm Export.Main.evm1 (call 1 2) = sum := by decide +kernel +theorem evm1_overflow : evm Export.Main.evm1 (call max 1) = panic := by decide +kernel +theorem evm2_sum : evm Export.Main.evm2 (call 1 2) = sum := by decide +kernel +theorem evm2_overflow : evm Export.Main.evm2 (call max 1) = panic := by decide +kernel +theorem evm3_sum : evm Export.Main.evm3 (call 1 2) = sum := by decide +kernel +theorem evm3_overflow : evm Export.Main.evm3 (call max 1) = panic := by decide +kernel +theorem evm4_sum : evm Export.Main.evm4 (call 1 2) = sum := by decide +kernel +theorem evm4_overflow : evm Export.Main.evm4 (call max 1) = panic := by decide +kernel +theorem evm4_value : evm Export.Main.evm4 (call 1 2 (value := 1)) = empty := by decide +kernel +theorem evm4_selector : + evm Export.Main.evm4 (call 1 2 (selector := [0, 0, 0, 0])) = empty := by decide +kernel +theorem evm4_short : evm Export.Main.evm4 short = empty := by decide +kernel + +/-! The checks tell programs apart: entering `@f` directly skips the value and selector +checks, and dropping the panic block makes an overflow stop with success instead. -/ + +/-- `stage0` entered at `@f` instead of the dispatcher. -/ +def withoutDispatch : MIR.Lowered.Module := { Export.Main.stage0 with entry := 0 } + +theorem withoutDispatch_value : mir withoutDispatch (call 1 2 (value := 1)) = sum := by + decide +kernel + +/-- `evm4` without its last block, the panic. -/ +def withoutPanic : EVM.Program.Program := ⟨Export.Main.evm4.blocks.take 2⟩ + +theorem withoutPanic_overflow : evm withoutPanic (call max 1) = some (true, []) := by + decide +kernel + +/-! The bytecode is the manifest's. -/ + +theorem bytecode_manifest : Export.Main.bytecodeHex = Export.Main.Manifest.bytecodeHex := rfl + +/-- info: 'SolarTV.Milestone.W1.Sanity.stage0_overflow' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms stage0_overflow + +/-- info: 'SolarTV.Milestone.W1.Sanity.evm4_overflow' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms evm4_overflow + +end SolarTV.Milestone.W1.Sanity + diff --git a/Certified/w1/gen/Main/Bytecode.lean b/Certified/w1/gen/Main/Bytecode.lean new file mode 100644 index 00000000..4308d748 --- /dev/null +++ b/Certified/w1/gen/Main/Bytecode.lean @@ -0,0 +1,18 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x2e, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x13, 0xd1, 0xaa, 0x2e, 0x03, + 0x60, 0x2e, 0x57, 0x60, 0x44, 0x36, 0x10, 0x60, 0x2e, 0x57, 0x60, 0x04, 0x35, 0x60, 0x24, 0x35, + 0x81, 0x01, 0x90, 0x81, 0x10, 0x60, 0x32, 0x57, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x5f, + 0x5f, 0xfd, 0x5b, 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, + 0x24, 0x60, 0x1c, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "34602e575f3560e01c806313d1aa2e03602e5760443610602e5760043560243581019081106032575f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd" + +end SolarTV.Export.Main diff --git a/Certified/w1/gen/Main/Evm1.lean b/Certified/w1/gen/Main/Evm1.lean new file mode 100644 index 00000000..ea4696ca --- /dev/null +++ b/Certified/w1/gen/Main/Evm1.lean @@ -0,0 +1,62 @@ +-- solar-lean-stage: kind=evm index=1 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x13d1aa2e)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/w1/gen/Main/Evm2.lean b/Certified/w1/gen/Main/Evm2.lean new file mode 100644 index 00000000..ebf688d4 --- /dev/null +++ b/Certified/w1/gen/Main/Evm2.lean @@ -0,0 +1,62 @@ +-- solar-lean-stage: kind=evm index=2 pass=share-reverts +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `share-reverts`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x13d1aa2e)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/w1/gen/Main/Evm3.lean b/Certified/w1/gen/Main/Evm3.lean new file mode 100644 index 00000000..62217667 --- /dev/null +++ b/Certified/w1/gen/Main/Evm3.lean @@ -0,0 +1,60 @@ +-- solar-lean-stage: kind=evm index=3 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x13d1aa2e)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.jump 1]] } + +end SolarTV.Export.Main diff --git a/Certified/w1/gen/Main/Evm4.lean b/Certified/w1/gen/Main/Evm4.lean new file mode 100644 index 00000000..2c9e6e8f --- /dev/null +++ b/Certified/w1/gen/Main/Evm4.lean @@ -0,0 +1,56 @@ +-- solar-lean-stage: kind=evm index=4 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x13d1aa2e)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 2, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/w1/gen/Main/Manifest.lean b/Certified/w1/gen/Main/Manifest.lean new file mode 100644 index 00000000..3c6b5e67 --- /dev/null +++ b/Certified/w1/gen/Main/Manifest.lean @@ -0,0 +1,41 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Main.Manifest + +def sources : List (String × String) := + [("solar-tv/milestone/w1/w1.sol", "e117e9ffe35bad0e8f1c0968146f9f99c8a4e5822787334f2591f0b1f6a46947")] + +def compiler : String := "0.8.38+commit.3ca8f483.solar.0.3.0-dev" + +def arguments : List String := + ["solar-tv/milestone/w1/w1.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/w1/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "fdf061c02c61572edabc120fbbae3199153ef03ff8dd1ba8f595732d915b2393"), + ("Sched", "sched", "stack-schedule", "c71694c03284f20688a387320b8274e1170d77e0144f942367063144aaf99b1c"), + ("Evm1", "evm1", "cfg-simplify-early", "9e2485b2fe109ce18c3a766cf61c72feb289ad77047d412a52c547f593851894"), + ("Evm2", "evm2", "share-reverts", "d48b6f1604cfa19d47510ea36cc03a0d6aab015d3116b3a2d876997018d9276a"), + ("Evm3", "evm3", "terminal-dedup", "67e313735720516f937146b9c9e6ac89ef731521eb34d66410a0945ac815bf43"), + ("Evm4", "evm4", "cfg-simplify-early", "6b1aace8993d2a8e277f8a60f7a9053df13f8d86e2e1b4416b639bbac7647529"), + ("Bytecode", "bytecode", "assemble", "d3e9cc2eda568f223b58d3c4cb380fc2929a0c0fb4dfa2277f570cf65c35b50a")] + +def bytecodeHex : String := + "34602e575f3560e01c806313d1aa2e03602e5760443610602e5760043560243581019081106032575f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd" + +def bytecodeSha256 : String := "24d2438e4d77b39b2530aac7af63774b10576eabc3c093d282620ab44403778b" + +end SolarTV.Export.Main.Manifest diff --git a/Certified/w1/gen/Main/Sched.lean b/Certified/w1/gen/Main/Sched.lean new file mode 100644 index 00000000..7aa00560 --- /dev/null +++ b/Certified/w1/gen/Main/Sched.lean @@ -0,0 +1,70 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 3, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x13d1aa2e)), + .op (.stack .eq), + .jumpi 2, + .jump 3], + -- bb2 + [.jump 4], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 8, + .jump 5], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 7, + .jump 6], + -- bb6 + [.op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb7 + [.op (.stack (.push 17)), + .op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb8 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/w1/gen/Main/Stage0.lean b/Certified/w1/gen/Main/Stage0.lean new file mode 100644 index 00000000..0f88c77c --- /dev/null +++ b/Certified/w1/gen/Main/Stage0.lean @@ -0,0 +1,62 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @f + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 68]], + .branch (.value 15) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 4]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 17) .calldataload [.const 4], + .effect (some 19) .calldataload [.const 36], + .pure 4 .add [.value 17, .value 19], + .pure 5 .lt [.value 4, .value 17]], + .branch (.value 5) 1 2⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x13d1aa2e, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/w1/gen/Main/manifest.json b/Certified/w1/gen/Main/manifest.json new file mode 100644 index 00000000..54e35418 --- /dev/null +++ b/Certified/w1/gen/Main/manifest.json @@ -0,0 +1,81 @@ +{ + "arguments": [ + "solar-tv/milestone/w1/w1.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=solar-tv/milestone/w1/gen" + ], + "bytecode": "34602e575f3560e01c806313d1aa2e03602e5760443610602e5760043560243581019081106032575f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd", + "bytecode_sha256": "24d2438e4d77b39b2530aac7af63774b10576eabc3c093d282620ab44403778b", + "compiler": "0.8.38+commit.3ca8f483.solar.0.3.0-dev", + "contract": "Main", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"solar-tv/milestone/w1/w1.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=solar-tv/milestone/w1/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"solar-tv/milestone/w1/gen\"), forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "solar-tv/milestone/w1/w1.sol", + "sha256": "e117e9ffe35bad0e8f1c0968146f9f99c8a4e5822787334f2591f0b1f6a46947" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "fdf061c02c61572edabc120fbbae3199153ef03ff8dd1ba8f595732d915b2393" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "c71694c03284f20688a387320b8274e1170d77e0144f942367063144aaf99b1c" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "9e2485b2fe109ce18c3a766cf61c72feb289ad77047d412a52c547f593851894" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "share-reverts", + "sha256": "d48b6f1604cfa19d47510ea36cc03a0d6aab015d3116b3a2d876997018d9276a" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "67e313735720516f937146b9c9e6ac89ef731521eb34d66410a0945ac815bf43" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "6b1aace8993d2a8e277f8a60f7a9053df13f8d86e2e1b4416b639bbac7647529" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "d3e9cc2eda568f223b58d3c4cb380fc2929a0c0fb4dfa2277f570cf65c35b50a" + } + ] +} diff --git a/Certified/w1/gen/Stages.lean b/Certified/w1/gen/Stages.lean new file mode 100644 index 00000000..f319dccc --- /dev/null +++ b/Certified/w1/gen/Stages.lean @@ -0,0 +1,9 @@ +-- Generated by gen.sh from Main/manifest.json; do not edit. +import gen.Main.Stage0 +import gen.Main.Sched +import gen.Main.Evm1 +import gen.Main.Evm2 +import gen.Main.Evm3 +import gen.Main.Evm4 +import gen.Main.Bytecode +import gen.Main.Manifest diff --git a/Certified/w1/w1.sol b/Certified/w1/w1.sol new file mode 100644 index 00000000..1b9e73ed --- /dev/null +++ b/Certified/w1/w1.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { function f(uint256 a, uint256 b) external pure returns (uint256) { return a + b; } } diff --git a/Certified/w4/Proofs.lean b/Certified/w4/Proofs.lean new file mode 100644 index 00000000..95899ba8 --- /dev/null +++ b/Certified/w4/Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import w4.Proofs.Stages +import w4.Proofs.Assembly diff --git a/Certified/w4/Proofs/Assembly.lean b/Certified/w4/Proofs/Assembly.lean new file mode 100644 index 00000000..d9d5858c --- /dev/null +++ b/Certified/w4/Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Items +import w4.gen.Main.Evm4 +import w4.gen.Main.Bytecode + +/-! The final EVM IR of `Main` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.W4 + +open SolarTV.Assembly SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm4).getD [] + +theorem items_eq : itemsOf evm4 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x20 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.W4.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.W4.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms decodes + +end SolarTV.Milestone.W4 diff --git a/Certified/w4/Proofs/Runs/Evm1.lean b/Certified/w4/Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..8e249712 --- /dev/null +++ b/Certified/w4/Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import w4.gen.Main.Evm1 +import w4.gen.Main.Sched + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.W4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 7 = EVM.Program.run o evm1 call 4 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W4.evm1_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm1_run + +end SolarTV.Milestone.W4 diff --git a/Certified/w4/Proofs/Runs/Evm2.lean b/Certified/w4/Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..da59e059 --- /dev/null +++ b/Certified/w4/Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import w4.gen.Main.Evm2 +import w4.gen.Main.Evm1 + +/-! `share-reverts`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.W4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 4 = EVM.Program.run o evm2 call 4 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W4.evm2_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm2_run + +end SolarTV.Milestone.W4 diff --git a/Certified/w4/Proofs/Runs/Evm3.lean b/Certified/w4/Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..17a01a5f --- /dev/null +++ b/Certified/w4/Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import w4.gen.Main.Evm3 +import w4.gen.Main.Evm2 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.W4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 4 = EVM.Program.run o evm3 call 4 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W4.evm3_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm3_run + +end SolarTV.Milestone.W4 diff --git a/Certified/w4/Proofs/Runs/Evm4.lean b/Certified/w4/Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..9b5a46e6 --- /dev/null +++ b/Certified/w4/Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import w4.gen.Main.Evm4 +import w4.gen.Main.Evm3 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.W4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 4 = EVM.Program.run o evm4 call 2 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W4.evm4_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within evm4_run + +end SolarTV.Milestone.W4 diff --git a/Certified/w4/Proofs/Runs/Sched.lean b/Certified/w4/Proofs/Runs/Sched.lean new file mode 100644 index 00000000..1ea10de8 --- /dev/null +++ b/Certified/w4/Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import w4.gen.Main.Sched +import w4.gen.Main.Stage0 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.W4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 7 = EVM.Program.run o sched call 7 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W4.sched_run' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within sched_run + +end SolarTV.Milestone.W4 diff --git a/Certified/w4/Proofs/Runs/Stage0.lean b/Certified/w4/Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..a41a3be8 --- /dev/null +++ b/Certified/w4/Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import w4.gen.Main.Stage0 + +/-! The first lowered MIR ends on every call within 7 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.W4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxHeartbeats 2000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 7).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.W4.stage0_ends' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within stage0_ends + +end SolarTV.Milestone.W4 diff --git a/Certified/w4/Proofs/Stages.lean b/Certified/w4/Proofs/Stages.lean new file mode 100644 index 00000000..db71737a --- /dev/null +++ b/Certified/w4/Proofs/Stages.lean @@ -0,0 +1,99 @@ +-- Generated by solar's tools/certify/certify.py; do not edit. +import w4.Proofs.Runs.Stage0 +import w4.Proofs.Runs.Sched +import w4.Proofs.Runs.Evm1 +import w4.Proofs.Runs.Evm2 +import w4.Proofs.Runs.Evm3 +import w4.Proofs.Runs.Evm4 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Main`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm4`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.W4 + +open Machine SolarTV.Export.Main SolarTV.Milestone.W1 + +/-- `stack-schedule`: stage0 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 7 7 (fun call _ => stage0_ends o call) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 7).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := stage0) (q := sched) (n := 7) (m := 7) (fun call _ => stage0_ends o call) + (fun call _ => sched_run o call) + +/-- `cfg-simplify-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 7 4 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 4).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 7) (m := 4) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `share-reverts`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 4 4 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 4).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 4) (m := 4) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `terminal-dedup`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 4 4 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 4).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 4) (m := 4) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `cfg-simplify-early`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 4 2 (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [], sched, [evm1, evm2, evm3, evm4]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem w4_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm4 anyCall := + mir_to_evmir o anyCall compilation trivial (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.W4.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.W4.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.W4.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.W4.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.W4.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.W4.w4_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms w4_mir_to_evmir + +end SolarTV.Milestone.W4 diff --git a/Certified/w4/bytecode.hex b/Certified/w4/bytecode.hex new file mode 100644 index 00000000..da2948a4 --- /dev/null +++ b/Certified/w4/bytecode.hex @@ -0,0 +1 @@ +346020575f3560e01c806360fe47b103602057602436106020576004355f55005b5f5ffd diff --git a/Certified/w4/gen/Main/Bytecode.lean b/Certified/w4/gen/Main/Bytecode.lean new file mode 100644 index 00000000..4e7384ba --- /dev/null +++ b/Certified/w4/gen/Main/Bytecode.lean @@ -0,0 +1,16 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x20, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x60, 0xfe, 0x47, 0xb1, 0x03, + 0x60, 0x20, 0x57, 0x60, 0x24, 0x36, 0x10, 0x60, 0x20, 0x57, 0x60, 0x04, 0x35, 0x5f, 0x55, 0x00, + 0x5b, 0x5f, 0x5f, 0xfd] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "346020575f3560e01c806360fe47b103602057602436106020576004355f55005b5f5ffd" + +end SolarTV.Export.Main diff --git a/Certified/w4/gen/Main/Evm1.lean b/Certified/w4/gen/Main/Evm1.lean new file mode 100644 index 00000000..28f58e8a --- /dev/null +++ b/Certified/w4/gen/Main/Evm1.lean @@ -0,0 +1,42 @@ +-- solar-lean-stage: kind=evm index=1 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm1 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x60fe47b1)), + .op (.stack .eq), + .jumpi 2, + .jump 1], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb6 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/w4/gen/Main/Evm2.lean b/Certified/w4/gen/Main/Evm2.lean new file mode 100644 index 00000000..652f443a --- /dev/null +++ b/Certified/w4/gen/Main/Evm2.lean @@ -0,0 +1,42 @@ +-- solar-lean-stage: kind=evm index=2 pass=share-reverts +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `share-reverts`. -/ +def evm2 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x60fe47b1)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb6 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/w4/gen/Main/Evm3.lean b/Certified/w4/gen/Main/Evm3.lean new file mode 100644 index 00000000..49d91be3 --- /dev/null +++ b/Certified/w4/gen/Main/Evm3.lean @@ -0,0 +1,40 @@ +-- solar-lean-stage: kind=evm index=3 pass=terminal-dedup +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `terminal-dedup`. -/ +def evm3 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x60fe47b1)), + .op (.stack .sub), + .jumpi 1, + .jump 2], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb6 + [.jump 1]] } + +end SolarTV.Export.Main diff --git a/Certified/w4/gen/Main/Evm4.lean b/Certified/w4/gen/Main/Evm4.lean new file mode 100644 index 00000000..0c46121e --- /dev/null +++ b/Certified/w4/gen/Main/Evm4.lean @@ -0,0 +1,36 @@ +-- solar-lean-stage: kind=evm index=4 pass=cfg-simplify-early +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR after `cfg-simplify-early`. -/ +def evm4 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 1, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x60fe47b1)), + .op (.stack .sub), + .jumpi 1, + .op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 1, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/w4/gen/Main/Manifest.lean b/Certified/w4/gen/Main/Manifest.lean new file mode 100644 index 00000000..facc2728 --- /dev/null +++ b/Certified/w4/gen/Main/Manifest.lean @@ -0,0 +1,41 @@ +-- solar-lean-stage: kind=manifest index=0 pass=none +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. + +What the stages of this directory were compiled from and by. `stages` lists each +stage's file, its definition, the pass whose output it is, and the SHA-256 of the file. +-/ + +namespace SolarTV.Export.Main.Manifest + +def sources : List (String × String) := + [("Certified/w4/w4.sol", "942f34d659aeb6e6809054e007c8201ad58d6ddb4ac748444eb9442dc317f02d")] + +def compiler : String := "0.8.38+commit.cb5053ab.solar.0.3.0-dev" + +def arguments : List String := + ["Certified/w4/w4.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/w4/gen"] + +def evmVersion : String := "osaka" + +def optimization : String := "Gas" + +def stages : List (String × String × String × String) := + [("Stage0", "stage0", "lower-evm-shaped", "ad2808b449e47195d6e928b2f07d7345c6fd85e2e1f66c6e8a4d85be6e9aee01"), + ("Sched", "sched", "stack-schedule", "7f3aa6e29328784877d834249d0d9c4ca0b91a2ffa502b499cb54ee7079d7146"), + ("Evm1", "evm1", "cfg-simplify-early", "ba810a9908a18e0fab7fa8c84b8e468f71fc28872422e237e8f7c74ddb98123e"), + ("Evm2", "evm2", "share-reverts", "aaf0fa85179f3ee35481eaf6ebbbce3a9d55b10f568a398acdcd1ebba33d15df"), + ("Evm3", "evm3", "terminal-dedup", "c43f40fbc2bae9fa15dda374eddbc74ecc567d460eacb90eb8ec9dce3963aef6"), + ("Evm4", "evm4", "cfg-simplify-early", "e71c69daa0aa1e6b065784c4401c964795416ef7afb30a48723f2c97f369aabb"), + ("Bytecode", "bytecode", "assemble", "6752a6cf2de90dc563c1c70b55e2e5d1edf7940c357c651bb767a5f7d5d33e03")] + +def bytecodeHex : String := + "346020575f3560e01c806360fe47b103602057602436106020576004355f55005b5f5ffd" + +def bytecodeSha256 : String := "4ac6a427e10e54ab60dbae0bd734633543eafea6ea38440d53363c8fa50018ee" + +end SolarTV.Export.Main.Manifest diff --git a/Certified/w4/gen/Main/Sched.lean b/Certified/w4/gen/Main/Sched.lean new file mode 100644 index 00000000..6cc14795 --- /dev/null +++ b/Certified/w4/gen/Main/Sched.lean @@ -0,0 +1,48 @@ +-- solar-lean-stage: kind=sched index=0 pass=stack-schedule +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The runtime EVM IR as stack scheduling emits it. -/ +def sched : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 3, + .jump 1], + -- bb1 + [.op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x60fe47b1)), + .op (.stack .eq), + .jumpi 2, + .jump 3], + -- bb2 + [.jump 4], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb4 + [.op (.stack (.push 36)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 6, + .jump 5], + -- bb5 + [.op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.push 0)), + .effect .sstore 2, + .stop], + -- bb6 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert]] } + +end SolarTV.Export.Main diff --git a/Certified/w4/gen/Main/Schedule.json b/Certified/w4/gen/Main/Schedule.json new file mode 100644 index 00000000..7a6c4a9f --- /dev/null +++ b/Certified/w4/gen/Main/Schedule.json @@ -0,0 +1,17 @@ +{ + "functions": [ + {"function": 1, "entry": null, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [0, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [1, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [2, 0], "layout": [], "floating": true, "continues": null}, + {"block": 3, "start": [3, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]}, + {"function": 0, "entry": 4, "returns": false, "rebuilt": false, "unsupported": null, "blocks": [ + {"block": 0, "start": [4, 0], "layout": [], "floating": true, "continues": null}, + {"block": 1, "start": [6, 0], "layout": [], "floating": true, "continues": null}, + {"block": 2, "start": [5, 0], "layout": [], "floating": true, "continues": null} + ], "calls": [ + ]} + ] +} diff --git a/Certified/w4/gen/Main/Stage0.lean b/Certified/w4/gen/Main/Stage0.lean new file mode 100644 index 00000000..865b23ba --- /dev/null +++ b/Certified/w4/gen/Main/Stage0.lean @@ -0,0 +1,51 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Main`; do not edit. -/ + +namespace SolarTV.Export.Main + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @set + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 3) .calldatasize [], + .pure 5 .lt [.value 3, .const 36]], + .branch (.value 5) 1 2⟩, + -- bb1 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb2 + ⟨[], + [.effect (some 7) .calldataload [.const 4], + .effect none .sstore [.const 0, .value 7]], + .stop⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x60fe47b1, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Main diff --git a/Certified/w4/gen/Main/manifest.json b/Certified/w4/gen/Main/manifest.json new file mode 100644 index 00000000..0be508e5 --- /dev/null +++ b/Certified/w4/gen/Main/manifest.json @@ -0,0 +1,81 @@ +{ + "arguments": [ + "Certified/w4/w4.sol", + "-Ogas", + "--evm-version", + "osaka", + "--emit=bin-runtime", + "-Zemit-lean-stages=Certified/w4/gen" + ], + "bytecode": "346020575f3560e01c806360fe47b103602057602436106020576004355f55005b5f5ffd", + "bytecode_sha256": "4ac6a427e10e54ab60dbae0bd734633543eafea6ea38440d53363c8fa50018ee", + "compiler": "0.8.38+commit.cb5053ab.solar.0.3.0-dev", + "contract": "Main", + "evm_version": "osaka", + "optimization": "Gas", + "options": "CompileOpts { input: [\"Certified/w4/w4.sol\"], import_remappings: [], base_path: None, include_paths: [], allow_paths: [], no_import_callback: false, language: Solidity, threads: 4, evm_version: Osaka, stop_after: None, optimization: Gas, optimizer_runs: None, revert_strings: Default, libraries: [], out_dir: None, emit: [BinRuntime], standard_json: false, color: Auto, verbose: false, pretty_json: false, pretty_json_err: false, error_format: Human, error_format_human: Unicode, diagnostic_width: None, no_warnings: false, allow: [], _unstable: [\"emit-lean-stages=Certified/w4/gen\"], unstable: UnstableOpts { ui_testing: false, track_diagnostics: false, parse_yul: false, no_resolve_imports: false, recover_incomplete_input: false, dump: None, ast_stats: false, hir_stats: false, standard_json_stats: false, span_visitor: false, print_max_storage_sizes: false, print_natspec: false, mir_pipeline: None, evm_ir_pipeline: None, print_after_each: false, pass_diff: false, debugify: None, debugify_output: None, solar_tv: None, validate_ir: None, time_passes: false, codegen_all_functions: false, switch_lowering: Auto, switch_max_gas_code_growth: None, switch_max_bit_slice_gas_code_growth: None, tune: None, pack_wide_jump_tables: false, check_analyses: None, prove_analyses: None, validate_passes: None, validate_passes_fault: None, validate_backend: None, validate_backend_fault: None, validate_evm_ir_passes: None, validate_assembly: false, validate_assembly_fault: None, emit_lean_stages: Some(\"Certified/w4/gen\"), keep_asts: false, forget_gcx: true, help: (), _non_exhaustive: () }, _non_exhaustive: () }", + "sources": [ + { + "path": "Certified/w4/w4.sol", + "sha256": "942f34d659aeb6e6809054e007c8201ad58d6ddb4ac748444eb9442dc317f02d" + } + ], + "stages": [ + { + "definition": "stage0", + "file": "Stage0.lean", + "index": 0, + "kind": "mir", + "pass": "lower-evm-shaped", + "sha256": "ad2808b449e47195d6e928b2f07d7345c6fd85e2e1f66c6e8a4d85be6e9aee01" + }, + { + "definition": "sched", + "file": "Sched.lean", + "index": 0, + "kind": "sched", + "pass": "stack-schedule", + "sha256": "7f3aa6e29328784877d834249d0d9c4ca0b91a2ffa502b499cb54ee7079d7146" + }, + { + "definition": "evm1", + "file": "Evm1.lean", + "index": 1, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "ba810a9908a18e0fab7fa8c84b8e468f71fc28872422e237e8f7c74ddb98123e" + }, + { + "definition": "evm2", + "file": "Evm2.lean", + "index": 2, + "kind": "evm", + "pass": "share-reverts", + "sha256": "aaf0fa85179f3ee35481eaf6ebbbce3a9d55b10f568a398acdcd1ebba33d15df" + }, + { + "definition": "evm3", + "file": "Evm3.lean", + "index": 3, + "kind": "evm", + "pass": "terminal-dedup", + "sha256": "c43f40fbc2bae9fa15dda374eddbc74ecc567d460eacb90eb8ec9dce3963aef6" + }, + { + "definition": "evm4", + "file": "Evm4.lean", + "index": 4, + "kind": "evm", + "pass": "cfg-simplify-early", + "sha256": "e71c69daa0aa1e6b065784c4401c964795416ef7afb30a48723f2c97f369aabb" + }, + { + "definition": "bytecode", + "file": "Bytecode.lean", + "index": 0, + "kind": "bytecode", + "pass": "assemble", + "sha256": "6752a6cf2de90dc563c1c70b55e2e5d1edf7940c357c651bb767a5f7d5d33e03" + } + ] +} diff --git a/Certified/w4/options b/Certified/w4/options new file mode 100644 index 00000000..da38913c --- /dev/null +++ b/Certified/w4/options @@ -0,0 +1,3 @@ +-Ogas +--evm-version +osaka diff --git a/Certified/w4/record.json b/Certified/w4/record.json new file mode 100644 index 00000000..b19e4c50 --- /dev/null +++ b/Certified/w4/record.json @@ -0,0 +1,29 @@ +{ + "contract": "Main", + "name": "w4", + "source": "Certified/w4/w4.sol", + "bytecode": "346020575f3560e01c806360fe47b103602057602436106020576004355f55005b5f5ffd", + "solar": "cb5053ab39adfd59820913b336d346389ce1b8d9", + "solidity_lean": "696df0a81602fc416fabec7b892073e15e8920de", + "mir_to_evmir": "proved: SolarTV.Milestone.W4.w4_mir_to_evmir", + "assembly": "decoded only: w4.Proofs.Assembly (the bytecode decodes to the final EVM IR's instructions; no execution theorem)", + "vc": "exported to .lake/certify/w4/VC.lean", + "end_to_end": "not proved", + "end_to_end_statement": {}, + "hypotheses": {}, + "refused": [], + "vacuous": "not checked", + "assembly_statement": null, + "assembly_hypotheses": null, + "negative_tests": false, + "caveats": [ + "solidity-lean at 696df0a81602fc416fabec7b892073e15e8920de, not the pinned 813949dc3556d3c3f1c129e8254a4eead78bac87", + "solar cb5053ab39adfd59820913b336d346389ce1b8d9, not built from this checkout's compiler sources", + "assembly decoded, not executed", + "not end to end: solidity-lean states no source or spec theorem for w4", + "negative tests skipped" + ], + "backend": { + "theorem": "SolarTV.Milestone.W4.w4_mir_to_evmir" + } +} diff --git a/Certified/w4/w4.sol b/Certified/w4/w4.sol new file mode 100644 index 00000000..2451a811 --- /dev/null +++ b/Certified/w4/w4.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + uint256 x; + function set(uint256 v) external { + x = v; + } +} diff --git a/Contracts/ArrayMax/Audit.lean b/Contracts/ArrayMax/Audit.lean new file mode 100644 index 00000000..8f620e1b --- /dev/null +++ b/Contracts/ArrayMax/Audit.lean @@ -0,0 +1,22 @@ +import Contracts.ArrayMax.Proofs.ArrayMax.max +import Contracts.ArrayMax.Proofs.ArrayMax.clamp +import Contracts.ArrayMax.Proofs.ArrayMaxEntry.max + +/-! Fails unless every theorem under `Contracts.ArrayMax.max`, `Contracts.ArrayMax.clamp`, `Contracts.ArrayMaxEntry.max` uses no axiom but `propext`, +`Classical.choice` and `Quot.sound`, and prints how many it checked. -/ + +open Lean Elab Command in +#eval show CommandElabM Unit from do + let env ← getEnv + let roots : List Name := [`Contracts.ArrayMax.max, `Contracts.ArrayMax.clamp, `Contracts.ArrayMaxEntry.max] + let allowed : List Name := [`propext, `Classical.choice, `Quot.sound] + let mut n := 0 + for (name, info) in env.constants.toList do + unless roots.any (·.isPrefixOf name) do continue + unless info matches .thmInfo _ do continue + let axs ← Lean.collectAxioms name + for a in axs do + unless allowed.contains a do throwError "{name} uses axiom {a}" + n := n + 1 + if n == 0 then throwError "no theorems found" + IO.println s!"ArrayMax: {n} theorems, axioms within propext, Classical.choice, Quot.sound" diff --git a/Contracts/ArrayMax/Bounded.lean b/Contracts/ArrayMax/Bounded.lean new file mode 100644 index 00000000..3062e83a --- /dev/null +++ b/Contracts/ArrayMax/Bounded.lean @@ -0,0 +1,231 @@ +import Verify.Discharge + +/- +A bounded variant of `vc_search` (Verify.Discharge) for obligations whose hypotheses chain a loop +or path condition through many local Booleans, where the unbounded search times out or exhausts +memory (ArrayMax `max`'s preserved quantified invariants) or `vc_norm` exceeds the recursion +limit (Vault's reentrancy-lock obligations): + +1. definitions of local symbols are substituted away, and every remaining Boolean constant is + split into its two cases, so that Boolean formulas fold to literals before `vc_norm`; +2. quantified hypotheses are instantiated once, at the witnesses of existentials and at the + arguments of matching array reads, and never again; +3. a conditional whose condition has quantifiers (a path condition the context restates) is + proved from the context by `and_intros`, `assumption` and `omega`, and otherwise split; +4. each case clears its quantified hypotheses and is closed by `omega`; `vc_bounded_leaf` first + instantiates them once more at the leaf and, when `omega` fails, splits on whether a witness + equals another array index, adding the read's congruence (`congrArg`), at most four deep. + +Every step builds a proof term the kernel checks; a goal it cannot close fails, never passes. +-/ +open Lean Meta Elab Tactic SolarVerify.Discharge + +namespace Contracts.Bounded + +/-- Like the search's `splitIte`, but proves a quantified condition the context implies +directly in the tactic monad (so a failed attempt is an exception, never a logged error), with +enough depth for a path condition's left-nested conjunction. -/ +def splitIteB : TacticM Unit := withMainContext do + let some c ← findIteCond | throwError "no conditional" + let hcN ← mkFreshUserName `hc + let hcI := mkIdent hcN + if hasQuantifier c then + let s ← saveState + try + let m ← mkFreshExprSyntheticOpaqueMVar c + let main ← getMainGoal + setGoals [m.mvarId!] + evalTactic (← `(tactic| and_intros <;> first | assumption | omega)) + unless (← getGoals).isEmpty do throwError "condition not proved" + let m ← instantiateMVars m + if m.hasMVar then throwError "condition not proved" + let (_, g') ← (← main.assert hcN c m).intro1P + setGoals [g'] + simpCase (← `(tactic| simp only [↓reduceIte, SolarVerify.Discharge.ite_pos $hcI, SolarVerify.Discharge.qite_pos $hcI])) + return + catch _ => s.restore + evalTactic (← `(tactic| by_cases $hcI : $(← Term.exprToSyntax c))) + let gs ← getGoals + let mut out := [] + for (g, pos) in gs.zip [true, false] do + setGoals [g] + if pos then + simpCase (← `(tactic| simp only [↓reduceIte, SolarVerify.Discharge.ite_pos $hcI, SolarVerify.Discharge.qite_pos $hcI])) + else + simpCase (← `(tactic| simp only [↓reduceIte, SolarVerify.Discharge.ite_neg $hcI, SolarVerify.Discharge.qite_neg $hcI])) + out := out ++ (← getGoals) + setGoals out + +/-- Normalizes, splits hypotheses, then splits one conditional or propositional atom per level +(at most `fuel` levels) and closes each case with `omega`, without instantiating again. -/ +partial def boundedLeaf (fuel : Nat) : TacticM Unit := do + if fuel = 0 then throwError "bounded: depth exhausted" + for g in (← getGoals) do + setGoals [g] + evalTactic (← `(tactic| vc_norm)) + if (← getGoals).isEmpty then continue + splitHyps + for g in (← getGoals) do + setGoals [g] + if (← findIteCond).isSome then + splitIteB + boundedLeaf (fuel - 1) + else if let some p ← findPropAtom then + splitProp p + boundedLeaf (fuel - 1) + else + clearQuantified + evalTactic (← `(tactic| omega)) + setGoals [] + +/-- Substitutes definitions, normalizes, splits hypotheses and instantiates once. -/ +def boundedPre : TacticM Unit := do + evalTactic (← `(tactic| intros)) + iffToEq + evalTactic (← `(tactic| subst_vars)) + evalTactic (← `(tactic| vc_norm)) + splitHyps + let gs ← getGoals + let mut out := [] + for g in gs do + setGoals [g] + let _ ← instantiate (← witnesses) {} + out := out ++ (← getGoals) + setGoals out + +/-- Cases on every Boolean local variable (an SMT `Bool` constant), so that the Boolean +formulas over it fold to literals before `vc_norm` runs. -/ +partial def boolCases : TacticM Unit := withMainContext do + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail then continue + if (← instantiateMVars ldecl.type) == mkConst ``Bool then + let gs ← (← getMainGoal).cases ldecl.fvarId + let mut out := [] + for sg in gs do + setGoals [sg.mvarId] + boolCases + out := out ++ (← getGoals) + setGoals out + return + +/-- `boundedPre` with a case split on every Boolean constant before `vc_norm`. -/ +def boundedPreB : TacticM Unit := do + evalTactic (← `(tactic| intros)) + iffToEq + evalTactic (← `(tactic| subst_vars)) + boolCases + let gs ← getGoals + let mut out := [] + for g in gs do + setGoals [g] + evalTactic (← `(tactic| simp -failIfUnchanged only [Bool.true_and, Bool.and_true, Bool.false_and, Bool.and_false, Bool.not_true, Bool.not_false, Bool.true_or, Bool.or_true, Bool.false_or, Bool.or_false, Bool.false_eq_true, Bool.true_eq_false, false_and, and_false, not_true_eq_false] at *)) + unless (← getGoals).isEmpty do + evalTactic (← `(tactic| vc_norm)) + unless (← getGoals).isEmpty do + splitHyps + let gs' ← getGoals + for g' in gs' do + setGoals [g'] + let _ ← instantiate (← witnesses) {} + out := out ++ (← getGoals) + setGoals out + +end Contracts.Bounded + +open Contracts.Bounded + +/-- The bounded search on a goal `vc_valid_prep` left, without Boolean case splits. -/ +elab "vc_bounded" : tactic => do boundedPre; boundedLeaf 16 + +/-- The bounded search on a goal `vc_valid_prep` left, after splitting every Boolean constant. -/ +elab "vc_bounded_bool" : tactic => do boundedPreB; boundedLeaf 16 + +/-- `vc_valid_prep`, then the bounded search with Boolean case splits. -/ +macro "vc_bounded_valid" : tactic => `(tactic| (vc_valid_prep <;> vc_bounded_bool)) + +namespace Contracts.Bounded + +/-- The pairs of reads `f w`, `f t` of one local function of one integer argument where `w` is a +witness and `t` is not, witnesses in context order. -/ +def readPairs : TacticM (List (Expr × Expr)) := withMainContext do + let ws ← witnesses + let mut ground : Array Expr := #[] + for ldecl in (← getLCtx) do + if !ldecl.isImplementationDetail then + ground := localApps (← instantiateMVars ldecl.type) ground + let mut reads : Array Expr := #[] + for e in ground do + -- only reads over the goal's own locals (an instance may mention a cleared one) + if e.getAppNumArgs == 1 && !(reads.contains e) then + let lctx ← getLCtx + unless (Lean.collectFVars {} e).fvarIds.all lctx.contains do continue + if (← inferType (e.getArg! 0)) == mkConst `Int then reads := reads.push e + let mut out := #[] + for w in ws do + for a in reads do + unless a.getArg! 0 == w do continue + for b in reads do + if b.getAppFn == a.getAppFn && !(ws.contains (b.getArg! 0)) then out := out.push (a, b) + return out.toList + +/-- `omega`, and when it fails, a case split on whether the arguments of two reads are equal +(adding `f a = f b` by `congrArg` when they are), at most `fuel` deep. -/ +partial def congrOmega (pairs : List (Expr × Expr)) (fuel : Nat) : TacticM Unit := do + let s ← saveState + try + evalTactic (← `(tactic| omega)) + catch err => + s.restore + let (a, b) :: rest := pairs | throw err + if fuel = 0 then throw err + let g ← getMainGoal + let subs ← g.withContext do + let eq ← mkEq (a.getArg! 0) (b.getArg! 0) + let em ← mkAppM ``Classical.em #[eq] + let (fv, g1) ← (← g.assert (← mkFreshUserName `hem) (mkOr eq (mkNot eq)) em).intro1P + g1.cases fv + let [sp, sn] := subs.toList | throwError "congrOmega: cases" + let gp ← sp.mvarId.withContext do + let pf ← mkCongrArg a.getAppFn sp.fields[0]! + let (_, g') ← (← sp.mvarId.assert (← mkFreshUserName `cong) (← inferType pf) pf).intro1P + pure g' + setGoals [gp] + congrOmega rest (fuel - 1) + setGoals [sn.mvarId] + congrOmega rest (fuel - 1) + +/-- `boundedLeaf`, but each leaf instantiates its quantified hypotheses once more (at the +witnesses and array reads the case split exposed) before `omega`. -/ +partial def boundedLeaf2 (fuel : Nat) : TacticM Unit := do + if fuel = 0 then throwError "bounded: depth exhausted" + for g in (← getGoals) do + setGoals [g] + evalTactic (← `(tactic| vc_norm)) + if (← getGoals).isEmpty then continue + splitHyps + for g in (← getGoals) do + setGoals [g] + if (← findIteCond).isSome then + splitIteB + boundedLeaf2 (fuel - 1) + else if let some p ← findPropAtom then + splitProp p + boundedLeaf2 (fuel - 1) + else + let _ ← instantiate (← witnesses) {} + evalTactic (← `(tactic| vc_norm)) + for g in (← getGoals) do + setGoals [g] + splitHyps + for g in (← getGoals) do + setGoals [g] + clearQuantified + congrOmega (← readPairs) 4 + setGoals [] + +end Contracts.Bounded + +open Contracts.Bounded + +/-- The bounded search on a goal `vc_valid_prep` left, instantiating again at each leaf. -/ +elab "vc_bounded_leaf" : tactic => do boundedPre; boundedLeaf2 16 diff --git a/Contracts/ArrayMax/Entry.lean b/Contracts/ArrayMax/Entry.lean new file mode 100644 index 00000000..f4a14311 --- /dev/null +++ b/Contracts/ArrayMax/Entry.lean @@ -0,0 +1,76 @@ +import Contracts.ArrayMax.Entry.Loop +import Contracts.ArrayMax.Entry.Start + +/-! +# ArrayMaxEntry.max on solar's first lowered MIR, through one cut point + +solar inlines `ArrayMax.max` into `ArrayMaxEntry.max(uint256[] calldata)`: function 0 of +`stage0` decodes the array, copies it to memory at 128 (`calldatacopy`) and runs the loop with +its header at block 2. The header invariant is not written here: `Inferred.lean` is generated by +solar's `solar-tv/milestone/inferred.py` from what `solar-verify --show-inferred` inferred for the +loop (the quantified clauses over `xs` included), bound to the header's values, with the frame +the compiler keeps (the copy of the calldata array, the induction pointer) read off the MIR. +The segments below check every conjunct, so a wrong clause fails by mismatch. + +* `stage0_post`: every end of stage0 on a call of `max` meets `Post`: on success it returns one + word `m`, no element of the calldata array is above it, and one element equals it, whatever the + array's length (the loop runs `xs.length - 1` times). + +`CalldataFits`: the calldata is shorter than 2^64 bytes. Without it, offsets past 2^256 wrap in +the word arithmetic of the decoder, and the copy may land elsewhere; every call the EVM can pay +for meets it. +-/ + +namespace SolarTV.Milestone.ArrayMaxEntry + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 +open SolarTV.CutPoint (seg SegOk) + +/-! ## Every run -/ + +/-- **ArrayMaxEntry.max's spec of solar's first lowered MIR**: every end of stage0 on a call of +`max` meets `Post`, however many times the loop runs. -/ +theorem stage0_post (o : Oracle) (call : Call) (hsel : IsMax call) (fits : CalldataFits call) + (r : Halt × State) (e : MIR.Lowered.moduleLayer.Ends o stage0 call r) : Post call r := by + obtain ⟨n, e⟩ := e + change Machine.iterate _ n _ = some r at e + rw [CutPoint.iterate_eq] at e + exact CutPoint.post_of_start (seg0 o call hsel fits) (by + rintro x (⟨env, s, rfl, h⟩ | ⟨env, s, rfl, h⟩) + · exact seg5 o call env s h + · exact seg10 o call env s h) n r e + +/-- `Post` is read off what an observer sees. -/ +theorem Post.of_agree {call : Call} {r r' : Halt × State} (ag : Agree r r') (h : Post call r) : + Post call r' := by + obtain ⟨a, s⟩ := r + obtain ⟨b, t⟩ := r' + intro hb + have ha : a = .stop ∨ ∃ d, a = .ret d := by + rcases hb with hb | ⟨d, hb⟩ <;> simp only at hb <;> subst hb <;> cases a <;> simp_all [Agree] + obtain ⟨m, hm, h1, h2⟩ := h ha + simp only at hm + subst hm + refine ⟨m, ?_, h1, h2⟩ + rcases hb with hb | ⟨d, hb⟩ <;> simp only at hb <;> subst hb + · exact absurd (congrArg List.length ag.1) (by simp) + · simp only [Agree] at ag + simp [ag.1] + +/-- `Post` carried along any program whose every end is matched by an agreeing end of stage0. -/ +theorem post_of_certified {L : Layer} {p : L.Prog} (o : Oracle) + (cert : Certified L MIR.Lowered.moduleLayer o p stage0 anyCall) (call : Call) + (hsel : IsMax call) (fits : CalldataFits call) (r : Halt × State) (e : L.Ends o p call r) : + Post call r := by + obtain ⟨r0, e0, ag⟩ := cert call trivial r e + exact (stage0_post o call hsel fits r0 e0).of_agree (CutPoint.Agree.symm ag) + +/-- info: 'SolarTV.Milestone.ArrayMaxEntry.stage0_post' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage0_post + +/-- info: 'SolarTV.Milestone.ArrayMaxEntry.post_of_certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms post_of_certified + +end SolarTV.Milestone.ArrayMaxEntry diff --git a/Contracts/ArrayMax/Entry/Basic.lean b/Contracts/ArrayMax/Entry/Basic.lean new file mode 100644 index 00000000..1e05376c --- /dev/null +++ b/Contracts/ArrayMax/Entry/Basic.lean @@ -0,0 +1,219 @@ +import SolarTV.CutPointHoare +import W1Proofs.Segment +import W1Proofs.Stage +import Contracts.ArrayMax.Inferred + +/-! +# ArrayMaxEntry.max on solar's first lowered MIR, through one cut point + +solar inlines `ArrayMax.max` into `ArrayMaxEntry.max(uint256[] calldata)`: function 0 of +`stage0` decodes the array, copies it to memory at 128 (`calldatacopy`) and runs the loop with +its header at block 2. The header invariant is not written here: `Inferred.lean` is generated by +solar's `solar-tv/milestone/inferred.py` from what `solar-verify --show-inferred` inferred for the +loop (the quantified clauses over `xs` included), bound to the header's values, with the frame +the compiler keeps (the copy of the calldata array, the induction pointer) read off the MIR. +The segments below check every conjunct, so a wrong clause fails by mismatch. + +* `stage0_post`: every end of stage0 on a call of `max` meets `Post`: on success it returns one + word `m`, no element of the calldata array is above it, and one element equals it, whatever the + array's length (the loop runs `xs.length - 1` times). + +`CalldataFits`: the calldata is shorter than 2^64 bytes. Without it, offsets past 2^256 wrap in +the word arithmetic of the decoder, and the copy may land elsewhere; every call the EVM can pay +for meets it. +-/ + +namespace SolarTV.Milestone.ArrayMaxEntry + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 +open SolarTV.CutPoint (seg SegOk) + +abbrev W := EvmRules.Word + +def cut : MIR.Lowered.Frame → Bool := fun x => + match x.2.1 with + | .enter f _ b => (f == 0 && b == 2) + | .resume .. => false + +theorem cut_enter (rs : List MIR.Lowered.Return) (f p b : Nat) (env : MIR.Lowered.Env) (s : State) : + cut (rs, .enter f p b, env, s) = ((f == 0 && b == 2)) := rfl + +theorem cut_resume (rs : List MIR.Lowered.Return) (f b : Nat) (is : List MIR.Lowered.Inst) (t : MIR.Lowered.Terminator) (env : MIR.Lowered.Env) (s : State) : + cut (rs, .resume f b is t, env, s) = false := rfl + +/-- `max(uint256[])`'s selector. -/ +def IsMax (call : Call) : Prop := EvmRules.Evm.shr 224 (calldataWord call 0) = 0x3bf6de96 + +/-- Calldata shorter than 2^64 bytes. -/ +def CalldataFits (call : Call) : Prop := call.calldata.size < 2 ^ 64 + +/-- The array's length, as the ABI decoder reads it: the word at its offset (the first argument +word) past the selector. -/ +def len (call : Call) : W := calldataWord call (calldataWord call 4 + (4 : W)) + +/-- Element `j` of the array. -/ +def elem (call : Call) (j : W) : W := + calldataWord call (((calldataWord call 4 + (4 : W)) + (32 : W)) + 32 * j) + +/-- `ArrayMaxEntry.max`'s ensures clauses: a successful end returns one word `m`, no element is +above it and some element equals it. -/ +def Post (call : Call) (r : Halt × State) : Prop := + (r.1 = .stop ∨ ∃ d, r.1 = .ret d) → + ∃ m, r.1 = .ret (Mem.wordBytes m) ∧ (∀ j, j < len call → elem call j ≤ m) ∧ + ∃ j, j < len call ∧ elem call j = m + +/-! ## Words and memory -/ + +theorem shr5_toNat (x : W) : (EvmRules.Evm.shr 5 x).toNat = x.toNat / 32 := by + unfold EvmRules.Evm.shr + simp [BitVec.ult, Nat.shiftRight_eq_div_pow] + +theorem shl5_toNat (x : W) : (EvmRules.Evm.shl 5 x).toNat = x.toNat * 32 % 2 ^ 256 := by + unfold EvmRules.Evm.shl + simp [BitVec.ult, Nat.shiftLeft_eq] + +theorem byte_word (n : Nat) (h : n < 256) : (BitVec.ofNat 8 n).setWidth 256 = BitVec.ofNat 256 n := by + apply BitVec.eq_of_toNat_eq + simp only [BitVec.toNat_setWidth, BitVec.toNat_ofNat] + omega + +theorem foldl_ext' {α β : Type} {f g : β → α → β} : + ∀ (l : List α) (b : β), (∀ b a, a ∈ l → f b a = g b a) → l.foldl f b = l.foldl g b + | [], _, _ => rfl + | a :: l, b, h => by + simp only [List.foldl_cons] + rw [h b a (List.mem_cons_self ..)] + exact foldl_ext' l _ (fun b x hx => h b x (List.mem_cons_of_mem _ hx)) + +/-- A word inside a calldata copy is the calldata word at the same distance. -/ +theorem load_calldatacopy (m : Mem) (dst size srcN a : Nat) (call : Call) (w : W) + (lo : dst ≤ a) (hi : a + 32 ≤ dst + size) (hw : w.toNat = srcN + (a - dst)) : + (m.write dst size (fun i => calldataByte call (srcN + i))).load a = calldataWord call w := by + unfold Mem.load calldataWord + rw [Mem.read_write_inside m dst size _ a 32 lo hi, List.foldl_map] + apply foldl_ext' + intro acc i _ + unfold calldataByte + rw [byte_word _ (UInt8.toNat_lt _), hw] + congr 4 + omega + +theorem load_write_below (m : Mem) (dst size a : Nat) (src : Nat → Memory.Byte) (h : a + 32 ≤ dst) : + (m.write dst size src).load a = m.load a := by + unfold Mem.load + rw [Mem.read_write_disjoint m dst size src a 32 (Or.inl h)] + +theorem nums (O L J S : Nat) (hS : S < 2 ^ 64) (hO : O + 36 ≤ S) (hL : L ≤ (S - (O + 36)) / 32) + (hJ : J < L) : 160 + 32 * J + 32 ≤ 160 + L * 32 ∧ O + 36 + 32 * J < 2 ^ 256 ∧ 160 + 32 * J < 2 ^ 256 ∧ + 32 * J < 2 ^ 256 ∧ L * 32 < 2 ^ 256 := by + have : L * 32 ≤ S - (O + 36) := by + have := Nat.div_mul_le_self (S - (O + 36)) 32 + exact Nat.le_trans (Nat.mul_le_mul_right 32 hL) this + omega + +theorem facts (call : Call) (fits : call.calldata.size < 2 ^ 64) + (hA : ¬BitVec.ofNat 256 call.calldata.size < 36) + (hB : ¬BitVec.ofNat 256 call.calldata.size - 36 < calldataWord call 4) + (hC : ¬EvmRules.Evm.shr 5 (BitVec.ofNat 256 call.calldata.size - (calldataWord call 4 + 4 + 32)) < + calldataWord call (calldataWord call 4 + 4)) : + (calldataWord call 4).toNat + 36 ≤ call.calldata.size ∧ + (calldataWord call 4 + 4 + 32).toNat = (calldataWord call 4).toNat + 36 ∧ + (calldataWord call (calldataWord call 4 + 4)).toNat ≤ + (call.calldata.size - ((calldataWord call 4).toNat + 36)) / 32 := by + have hS : (BitVec.ofNat 256 call.calldata.size).toNat = call.calldata.size := + Nat.mod_eq_of_lt (by omega) + have n4 : (4 : W).toNat = 4 := rfl + have n32 : (32 : W).toNat = 32 := rfl + have n36 : (36 : W).toNat = 36 := rfl + have hO4 := (calldataWord call 4).isLt + rw [BitVec.lt_def, hS, n36] at hA + have h36 : (36 : W) ≤ BitVec.ofNat 256 call.calldata.size := by + rw [BitVec.le_def, hS, n36]; omega + rw [BitVec.lt_def, BitVec.toNat_sub_of_le h36, hS, n36] at hB + have e0 : (calldataWord call 4 + 4).toNat = (calldataWord call 4).toNat + 4 := by + rw [BitVec.toNat_add_of_lt] <;> rw [n4]; omega + have e1 : (calldataWord call 4 + 4 + 32).toNat = (calldataWord call 4).toNat + 36 := by + rw [BitVec.toNat_add_of_lt] <;> rw [e0, n32] <;> omega + have hle : calldataWord call 4 + 4 + 32 ≤ BitVec.ofNat 256 call.calldata.size := by + rw [BitVec.le_def, hS, e1]; omega + rw [BitVec.lt_def, shr5_toNat, BitVec.toNat_sub_of_le hle, hS, e1] at hC + exact ⟨by omega, e1, by omega⟩ + +/-- The words the decoder's copy wrote are the calldata array's, on a call whose checks passed. -/ +theorem copy_entry (call : Call) (m : Mem) (fits : call.calldata.size < 2 ^ 64) + (hA : ¬BitVec.ofNat 256 call.calldata.size < 36) + (hB : ¬BitVec.ofNat 256 call.calldata.size - 36 < calldataWord call 4) + (hC : ¬EvmRules.Evm.shr 5 (BitVec.ofNat 256 call.calldata.size - (calldataWord call 4 + 4 + 32)) < + calldataWord call (calldataWord call 4 + 4)) : + ∀ j : W, j < calldataWord call (calldataWord call 4 + 4) → + (m.write 160 (EvmRules.Evm.shl 5 (calldataWord call (calldataWord call 4 + 4))).toNat + (fun i => calldataByte call ((calldataWord call 4 + 4 + 32).toNat + i))).load + (128 + 32 + 32 * j : W).toNat = + calldataWord call (calldataWord call 4 + 4 + 32 + 32 * j) := by + obtain ⟨hO, e1, hL⟩ := facts call fits hA hB hC + intro j hj + rw [BitVec.lt_def] at hj + obtain ⟨n1, n2, n3, n4, n5⟩ := nums _ _ _ _ fits hO hL hj + have k32 : (32 : W).toNat = 32 := rfl + have k160 : (128 + 32 : W).toNat = 160 := rfl + have ea : (128 + 32 + 32 * j : W).toNat = 160 + 32 * j.toNat := by + rw [BitVec.toNat_add, k160, BitVec.toNat_mul, k32]; omega + have ew : (calldataWord call 4 + 4 + 32 + 32 * j).toNat = + (calldataWord call 4).toNat + 36 + 32 * j.toNat := by + rw [BitVec.toNat_add, e1, BitVec.toNat_mul, k32]; omega + rw [shl5_toNat, Nat.mod_eq_of_lt n5, e1, ea] + apply load_calldatacopy <;> omega + + +/-! ## The loop's steps -/ + +theorem fa_step (mem : Mem) (P i i' m m' : W) + (h : ∀ j, j < i → mem.load (P + 32 + 32 * j).toNat ≤ m) (hm : m ≤ m') + (hx : mem.load (P + 32 + 32 * i).toNat ≤ m') (hi : i' = i + 1) (ho : i + 1 ≠ 0) : + ∀ j, j < i' → mem.load (P + 32 + 32 * j).toNat ≤ m' := by + intro j hj + by_cases hji : j < i + · exact BitVec.le_trans (h j hji) hm + · have : j = i := by subst hi; bv_omega + subst this; exact hx + +theorem ex_keep (mem : Mem) (P B B' m : W) (h : ∃ j, j < B ∧ mem.load (P + 32 + 32 * j).toNat = m) + (hb : B ≤ B') : ∃ j, j < B' ∧ mem.load (P + 32 + 32 * j).toNat = m := by + obtain ⟨j, hj, e⟩ := h + exact ⟨j, by bv_omega, e⟩ + +theorem ex_new (mem : Mem) (P B i q m : W) (hq : P + 32 + 32 * i = q) (hi : i < B) + (e : mem.load q.toNat = m) : ∃ j, j < B ∧ mem.load (P + 32 + 32 * j).toNat = m := + ⟨i, hi, by rw [hq]; exact e⟩ + +theorem post_exit (call : Call) (mem mem' : Mem) (i m : W) (st : State) + (hi : ¬ i < len call) (hle : i ≤ len call) + (hfa : ∀ j, j < i → mem.load (128 + 32 + 32 * j).toNat ≤ m) + (hex : ∃ j, j < len call ∧ mem.load (128 + 32 + 32 * j).toNat = m) + (copy : ∀ j, j < len call → mem.load (128 + 32 + 32 * j).toNat = elem call j) : + Post call (Halt.ret ((mem'.store 0 m).read 0 32), st) := by + intro _ + refine ⟨m, by rw [Mem.read_store_same], ?_, ?_⟩ + · intro j hj + rw [← copy j hj] + exact hfa j (by bv_omega) + · obtain ⟨j, hj, e⟩ := hex + exact ⟨j, hj, (copy j hj) ▸ e⟩ + +/-- One conjunct of the invariant at the back edge. -/ +syntax "am_conj" : tactic +set_option hygiene false in +macro_rules + | `(tactic| am_conj) => `(tactic| first + | rfl + | assumption + | (refine fa_step _ _ _ _ _ _ ‹_› ?_ ?_ ?_ ?_ <;> + first | bv_omega | (rw [hptr]; first | exact BitVec.le_refl _ | bv_omega)) + | (refine ex_new _ _ _ _ _ _ hptr ?_ ?_ <;> first | bv_omega | rfl) + | (refine ex_keep _ _ _ _ _ ‹_› ?_; bv_omega) + | bv_omega) + +macro "rev_leaf" : tactic => `(tactic| + (unfold Post; dsimp only; intro h; rcases h with h | ⟨_, h⟩ <;> exact Halt.noConfusion h)) + +end SolarTV.Milestone.ArrayMaxEntry diff --git a/Contracts/ArrayMax/Entry/Loop.lean b/Contracts/ArrayMax/Entry/Loop.lean new file mode 100644 index 00000000..a45df6c1 --- /dev/null +++ b/Contracts/ArrayMax/Entry/Loop.lean @@ -0,0 +1,52 @@ +import Contracts.ArrayMax.Entry.Basic + +/-! ArrayMaxEntry.max: the loop's segments, from its header entered from its entry and from its back edge. -/ + +namespace SolarTV.Milestone.ArrayMaxEntry + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 +open SolarTV.CutPoint (seg SegOk) + +/-! ## The segments -/ + +set_option maxHeartbeats 4000000 in +theorem seg10 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) + (h : Inferred.at10 call env s) : + ∃ k, SegOk (Inferred.Inv call) (Post call) + (seg (MIR.Lowered.moduleBlock o call stage0) cut k ([], .enter 0 10 2, env, s)) := by + refine ⟨20, ?_⟩ + obtain ⟨-, -, a1, a2, fa, ex, exi, lpos, -, e37, e126, -, hst, e91, e119, e12, copy, hlen⟩ := h + simp only [e119, e37, e91] at fa ex exi hlen a2 + have hptr : (128 : W) + 32 + 32 * 1 = 128 + 64 := by decide + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + seg_norm [SegOk, cut_enter, cut_resume] + repeat' (split_cond <;> seg_norm [SegOk, cut_enter, cut_resume]) + all_goals first + | exact True.intro + | (apply post_exit (i := 1) <;> first | assumption | bv_omega) + | (refine Or.inl ⟨_, _, rfl, ?_⟩ + simp only [Inferred.at5, MIR.Lowered.Env.set, Mem.load_expand, ↓reduceIte, Nat.reduceEqDiff, + EvmRules.Evm.add, e119, e91] + and_intros <;> am_conj) + +set_option maxHeartbeats 4000000 in +theorem seg5 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) + (h : Inferred.at5 call env s) : + ∃ k, SegOk (Inferred.Inv call) (Post call) + (seg (MIR.Lowered.moduleBlock o call stage0) cut k ([], .enter 0 5 2, env, s)) := by + refine ⟨20, ?_⟩ + obtain ⟨a0, -, a1, a2, fa, ex, exi, lpos, ipos, e129, hst, e91, e119, e12, copy, hlen⟩ := h + simp only [e119, e91] at fa ex exi hlen + have hptr : (128 : W) + 32 + 32 * env 51 = 128 + 64 + 32 * (env 51 - 1) := by bv_omega + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + seg_norm [SegOk, cut_enter, cut_resume] + repeat' (split_cond <;> seg_norm [SegOk, cut_enter, cut_resume]) + all_goals first + | exact True.intro + | (apply post_exit (i := env 51) <;> first | assumption | bv_omega) + | (refine Or.inl ⟨_, _, rfl, ?_⟩ + simp only [Inferred.at5, MIR.Lowered.Env.set, Mem.load_expand, ↓reduceIte, Nat.reduceEqDiff, + EvmRules.Evm.add, e119, e91] + and_intros <;> am_conj) + +end SolarTV.Milestone.ArrayMaxEntry diff --git a/Contracts/ArrayMax/Entry/Start.lean b/Contracts/ArrayMax/Entry/Start.lean new file mode 100644 index 00000000..28948b39 --- /dev/null +++ b/Contracts/ArrayMax/Entry/Start.lean @@ -0,0 +1,49 @@ +import Contracts.ArrayMax.Entry.Basic + +/-! ArrayMaxEntry.max: the segment from the call's start to the loop's header. -/ + +namespace SolarTV.Milestone.ArrayMaxEntry + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 +open SolarTV.CutPoint (seg SegOk) + +/-- One conjunct of the invariant at the loop's entry. -/ +syntax "am_entry" : tactic +set_option hygiene false in +macro_rules + | `(tactic| am_entry) => `(tactic| first + | rfl + | assumption + | exact BitVec.le_refl _ + | (intro j hj; have : j = 0 := by bv_omega + subst this; exact BitVec.le_refl _) + | exact ⟨0, by bv_omega, rfl⟩ + | (obtain ⟨hC, hA, hB⟩ := ‹¬_ < _ ∧ ¬_ < _ ∧ ¬_ < _› + exact copy_entry call _ fits hA hB hC) + | (rw [show (128 : W).toNat = 128 from rfl, load_write_below _ _ _ _ _ (by decide), + Mem.load_store_same]) + | bv_omega + | (simp only [EvmRules.Evm.gt, BitVec.ult, Bool.cond_eq_ite, decide_eq_true_eq]; split <;> bv_omega)) + +set_option maxHeartbeats 8000000 in +theorem seg0 (o : Oracle) (call : Call) (hsel : IsMax call) (fits : CalldataFits call) : + ∃ k, SegOk (Inferred.Inv call) (Post call) + (seg (MIR.Lowered.moduleBlock o call stage0) cut k + ([], .enter stage0.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState stage0 (State.initial call))) := by + refine ⟨40, ?_⟩ + unfold IsMax at hsel + unfold CalldataFits at fits + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + seg_norm [SegOk, cut_enter, cut_resume] + repeat' (split_cond <;> seg_norm [SegOk, cut_enter, cut_resume]) + all_goals first + | exact True.intro + | rev_leaf + | (exfalso; simp_all only [↓reduceIte, Nat.reduceBEq, Bool.false_eq_true, + not_false_eq_true]; done) + | (refine Or.inr ⟨_, _, rfl, ?_⟩ + simp only [Inferred.at10, MIR.Lowered.Env.set, Mem.load_expand, ↓reduceIte, Nat.reduceEqDiff, + EvmRules.Evm.add, EvmRules.Evm.sub] at * + and_intros <;> am_entry) + +end SolarTV.Milestone.ArrayMaxEntry diff --git a/Contracts/ArrayMax/Entry/Total.lean b/Contracts/ArrayMax/Entry/Total.lean new file mode 100644 index 00000000..91600ac1 --- /dev/null +++ b/Contracts/ArrayMax/Entry/Total.lean @@ -0,0 +1,177 @@ +import SolarTV.Termination +import Contracts.ArrayMax.Entry.Basic + +/-! +# ArrayMaxEntry.max ends: the loop's ranking certificate, checked + +`Entry.stage0_post` is partial correctness: every end of the first lowered MIR on a call of +`max` meets `Post`. Here the same invariant, with the measure `xs.length - i` that +`inferred.py` emits from `solar-verify --show-inferred` (`Inferred.rank`), goes through the +generic termination checker `SolarTV.CutPoint.ends_within_start`: every segment must end in a +result meeting `Post` or at the header with the invariant and a lower rank, and none may be +stuck. So every call of `max` (with calldata the EVM can pay for, `CalldataFits`) ends within +`(xs.length + 2) * 40` blocks of the MIR, whatever the array's length, and meets `Post` +(`stage0_ends_within`), and a metered run from the header with `(xs.length + 1) * 40` units never +runs out (`stage0_gas`). +-/ + +namespace SolarTV.Milestone.ArrayMaxEntry + +open Machine SolarTV.Export.ArrayMaxEntry SolarTV.Milestone.W1 +open SolarTV.CutPoint (seg SegEnds) + +/-- The array's length, as the rank reads it. -/ +abbrev lenN (call : Call) : Nat := + (calldataWord call (calldataWord call 4 + (4 : EvmRules.Word))).toNat + +/-- What the decoder's length check gives: a length at most the words left, so at most +`2 ^ 251 - 1`, the bound the compiler assumes when it scales the length by 32. -/ +theorem le_of_not_shr5_lt {x y : EvmRules.Word} (h : ¬EvmRules.Evm.shr 5 x < y) : + y ≤ 3618502788666131106986593281521497120414687020801267626233049500247285301247 := by + have hs : EvmRules.Evm.shr 5 x ≤ 3618502788666131106986593281521497120414687020801267626233049500247285301247 := by + simp only [EvmRules.Evm.shr] + rw [show BitVec.ult (5 : EvmRules.Word) 256 = true by decide] + simp only [Bool.cond_true, BitVec.ushiftRight_eq', BitVec.le_def, BitVec.toNat_ushiftRight, + Nat.shiftRight_eq_div_pow] + rw [show (5 : EvmRules.Word).toNat = 5 from rfl, + show (3618502788666131106986593281521497120414687020801267626233049500247285301247 : EvmRules.Word).toNat = + 3618502788666131106986593281521497120414687020801267626233049500247285301247 from rfl] + have := x.isLt + omega + bv_omega + +/-- One conjunct of the invariant at the loop's entry. -/ +syntax "am_entry'" : tactic +set_option hygiene false in +macro_rules + | `(tactic| am_entry') => `(tactic| first + | rfl + | assumption + | exact BitVec.le_refl _ + | (intro j hj; have : j = 0 := by bv_omega + subst this; exact BitVec.le_refl _) + | exact ⟨0, by bv_omega, rfl⟩ + | (obtain ⟨hC, hA, hB⟩ := ‹¬_ < _ ∧ ¬_ < _ ∧ ¬_ < _› + exact copy_entry call _ fits hA hB hC) + | (rw [show (128 : W).toNat = 128 from rfl, load_write_below _ _ _ _ _ (by decide), + Mem.load_store_same]) + | bv_omega + | (simp only [EvmRules.Evm.gt, BitVec.ult, Bool.cond_eq_ite, decide_eq_true_eq]; split <;> bv_omega)) + +set_option maxHeartbeats 8000000 in +theorem tseg0 (o : Oracle) (call : Call) (hsel : IsMax call) (fits : CalldataFits call) : + SegEnds (Inferred.Inv call) (Post call) (fun _ => True) + (seg (MIR.Lowered.moduleBlock o call stage0) cut 40 + ([], .enter stage0.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState stage0 (State.initial call))) := by + unfold IsMax at hsel + unfold CalldataFits at fits + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + seg_norm [SegEnds, cut_enter, cut_resume] + repeat' (split_cond <;> seg_norm [SegEnds, cut_enter, cut_resume]) + all_goals first + | rev_leaf + | (exfalso; simp_all only [↓reduceIte, Nat.reduceBEq, Bool.false_eq_true, + not_false_eq_true]; done) + | bv_omega + | ((first | refine ⟨Or.inr ⟨_, _, rfl, ?_⟩, trivial⟩ | refine Or.inr ⟨_, _, rfl, ?_⟩) + simp only [Inferred.at10, MIR.Lowered.Env.set, Mem.load_expand, ↓reduceIte, Nat.reduceEqDiff, + EvmRules.Evm.add, EvmRules.Evm.sub] at * + and_intros <;> am_entry') + | (obtain ⟨h1, -, -⟩ := ‹¬_ < _ ∧ ¬_ < _ ∧ ¬_ < _› + have := le_of_not_shr5_lt h1 + bv_omega) + +set_option maxHeartbeats 4000000 in +theorem tseg10 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) + (h : Inferred.at10 call env s) : + SegEnds (Inferred.Inv call) (Post call) + (fun y => Inferred.rank call y < Inferred.rank call ([], .enter 0 10 2, env, s)) + (seg (MIR.Lowered.moduleBlock o call stage0) cut 40 ([], .enter 0 10 2, env, s)) := by + obtain ⟨-, -, a1, a2, fa, ex, exi, lpos, -, e37, e126, -, hst, e91, e119, e12, copy, hlen⟩ := h + simp only [e119, e37, e91] at fa ex exi hlen a2 + have hptr : (128 : W) + 32 + 32 * 1 = 128 + 64 := by decide + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + seg_norm [SegEnds, cut_enter, cut_resume] + repeat' (split_cond <;> seg_norm [SegEnds, cut_enter, cut_resume]) + all_goals first + | (apply post_exit (i := 1) <;> first | assumption | bv_omega) + | (constructor + · refine Or.inl ⟨_, _, rfl, ?_⟩ + simp only [Inferred.at5, MIR.Lowered.Env.set, Mem.load_expand, ↓reduceIte, Nat.reduceEqDiff, + EvmRules.Evm.add, e119, e91] + and_intros <;> am_conj + · simp only [Inferred.rank, MIR.Lowered.Env.set, ↓reduceIte, Nat.reduceEqDiff, + EvmRules.Evm.add] + bv_omega) + +set_option maxHeartbeats 4000000 in +theorem tseg5 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) + (h : Inferred.at5 call env s) : + SegEnds (Inferred.Inv call) (Post call) + (fun y => Inferred.rank call y < Inferred.rank call ([], .enter 0 5 2, env, s)) + (seg (MIR.Lowered.moduleBlock o call stage0) cut 40 ([], .enter 0 5 2, env, s)) := by + obtain ⟨a0, -, a1, a2, fa, ex, exi, lpos, ipos, e129, hst, e91, e119, e12, copy, hlen⟩ := h + simp only [e119, e91] at fa ex exi hlen + have hptr : (128 : W) + 32 + 32 * env 51 = 128 + 64 + 32 * (env 51 - 1) := by bv_omega + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + seg_norm [SegEnds, cut_enter, cut_resume] + repeat' (split_cond <;> seg_norm [SegEnds, cut_enter, cut_resume]) + all_goals first + | bv_omega + | (apply post_exit (i := env 51) <;> first | assumption | bv_omega) + | (constructor + · refine Or.inl ⟨_, _, rfl, ?_⟩ + simp only [Inferred.at5, MIR.Lowered.Env.set, Mem.load_expand, ↓reduceIte, Nat.reduceEqDiff, + EvmRules.Evm.add, e119, e91] + and_intros <;> am_conj + · simp only [Inferred.rank, MIR.Lowered.Env.set, ↓reduceIte, Nat.reduceEqDiff, + EvmRules.Evm.add] + bv_omega) + +/-- Every segment from a cut point of the certificate. -/ +theorem tseg (o : Oracle) (call : Call) : + ∀ x, Inferred.Inv call x → SegEnds (Inferred.Inv call) (Post call) + (fun y => Inferred.rank call y < Inferred.rank call x) + (seg (MIR.Lowered.moduleBlock o call stage0) cut 40 x) := by + rintro x (⟨env, s, rfl, h⟩ | ⟨env, s, rfl, h⟩) + · exact tseg5 o call env s h + · exact tseg10 o call env s h + +theorem rank_le (call : Call) : ∀ y, Inferred.Inv call y → Inferred.rank call y ≤ lenN call := by + rintro y (⟨env, s, rfl, h⟩ | ⟨env, s, rfl, h⟩) <;> simp only [Inferred.rank, lenN] <;> omega + +/-- **Every call of `max` ends within `(xs.length + 2) * 40` blocks of solar's first lowered MIR, +and meets `Post`**: the bound the ranking certificate gives, whatever the array's length. -/ +theorem stage0_ends_within (o : Oracle) (call : Call) (hsel : IsMax call) (fits : CalldataFits call) : + ∃ r, Machine.iterate (MIR.Lowered.moduleBlock o call stage0) ((lenN call + 2) * 40) + ([], .enter stage0.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState stage0 (State.initial call)) = + some r ∧ Post call r := by + obtain ⟨r, ran, post⟩ := CutPoint.ends_within_start (Inferred.rank call) 40 (lenN call) + (rank_le call) (tseg0 o call hsel fits) (tseg o call) + exact ⟨r, by rw [CutPoint.iterate_eq]; exact ran, post⟩ + +/-- Every call of `max` ends on the MIR, in an end meeting `Post`. -/ +theorem stage0_ends (o : Oracle) (call : Call) (hsel : IsMax call) (fits : CalldataFits call) : + ∃ r, MIR.Lowered.moduleLayer.Ends o stage0 call r ∧ Post call r := by + obtain ⟨r, ran, post⟩ := stage0_ends_within o call hsel fits + exact ⟨r, ⟨_, by change Machine.iterate _ _ _ = some r; exact ran⟩, post⟩ + +/-- **The resource form**: charging each block one unit, a metered run from the header with +`(xs.length + 1) * 40` units never runs out, and ends meeting `Post`. -/ +theorem stage0_gas (o : Oracle) (call : Call) (x : MIR.Lowered.Frame) (hx : Inferred.Inv call x) + (g : Nat) (hg : (lenN call + 1) * 40 ≤ g) : + ∃ n r left, CutPoint.runGas (MIR.Lowered.moduleBlock o call stage0) (fun _ => 1) n g x = + some (.done r left) ∧ Post call r := + CutPoint.gas_ends (cut := cut) (Inferred.rank call) 40 40 + (fun y hy => ⟨tseg o call y hy, CutPoint.segCost_one_le 40 y⟩) x hx g + (Nat.le_trans (Nat.mul_le_mul_right 40 (by have := rank_le call x hx; omega)) hg) + +/-- info: 'SolarTV.Milestone.ArrayMaxEntry.stage0_ends_within' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage0_ends_within + +/-- info: 'SolarTV.Milestone.ArrayMaxEntry.stage0_gas' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage0_gas + +end SolarTV.Milestone.ArrayMaxEntry diff --git a/Contracts/ArrayMax/Execution.lean b/Contracts/ArrayMax/Execution.lean new file mode 100644 index 00000000..49c9a58f --- /dev/null +++ b/Contracts/ArrayMax/Execution.lean @@ -0,0 +1,84 @@ +import SolidCore.Refinement.Solar.AssembleCut +import SolidCore.Refinement.Solar.AssembleFast +import arraymax.gen.ArrayMaxEntry.Evm15 +import arraymax.gen.ArrayMaxEntry.Bytecode + +/-! +# ArrayMaxEntry's bytecode runs as its final EVM IR + +solar's final EVM IR of `ArrayMaxEntry` (`evm15`) loads at computed offsets (the array's +elements in memory) and copies call data of the array's length; the checker with memory at any +offset (`AssembleCut.checkC`) accepts its bytecode, so at every gas below `2 ^ 256` every result +of the bytecode is the EVM IR's or a failure that changes nothing. The bytecode with CODECOPY in +place of its CALLDATACOPY (byte 148) is rejected by evaluation. +-/ + +namespace SolidCore.Refinement.Solar.ArrayMaxRun + +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCut SolarTV.Export.ArrayMaxEntry + +def code : ByteArray := ⟨(bytecode.map UInt8.ofNat).toArray⟩ + +/-- The same bytecode with CODECOPY (0x39) in place of the CALLDATACOPY at byte 148. -/ +def mutant : ByteArray := ⟨((bytecode.set 148 0x39).map UInt8.ofNat).toArray⟩ + +def cert : Cert := + { offsets := [0x0, 0x13, 0x17, 0x2c, 0xbc, 0xed, 0x10e, 0x124, 0x13c, 0x151, 0x16c, 0x181, 0x1b6, 0x1d0, 0x1e8, 0x1ff, 0x219, 0x236, 0x253, 0x268], + needs := [0, 0, 8, 1, 9, 7, 9, 4, 3, 12, 13, 11, 13, 13, 11, 10, 10, 10, 8, 7], + top := 2 ^ 140, + turned := [], + costs := [12, 3, 5, 112, 40, 26, 8, 14, 5, 11, 5, 43, 10, 8, 7, 10, 13, 13, 5, 9], + types := [[], [], + List.replicate 8 (some false), [some false], List.replicate 9 (some false), + List.replicate 7 (some false), List.replicate 9 (some false), List.replicate 4 (some false), + List.replicate 3 (some false), List.replicate 12 (some false), List.replicate 13 (some false), + List.replicate 11 (some false), List.replicate 13 (some false), List.replicate 13 (some false), + List.replicate 11 (some false), List.replicate 10 (some false), List.replicate 10 (some false), + List.replicate 10 (some false), List.replicate 8 (some false), List.replicate 7 (some false)], + rets := [], + env := false, + reads := false } + +def maxs : List Nat := [0, 6, 8, 1, 9, 7, 9, 15, 3, 12, 13, 11, 13, 13, 11, 10, 10, 10, 8, 7] + +set_option maxRecDepth 100000 in +theorem walk_ok : (SolarTV.Assembly.walk (bytesOf code) cert.offset 0 (lower evm15 cert)).isSome = + true := by + have hw := walkS_drop (bytesOf code) cert.offset (lower evm15 cert) 0 (Nat.zero_le _) + rw [List.drop_zero] at hw + rw [← hw] + decide +kernel + +set_option maxRecDepth 100000 in +theorem blocks_ok : blocksOkC evm15 cert maxs 0 evm15.blocks = true := by + decide +kernel + +theorem labels_ok : labelsValid evm15 cert code = true := + labelsValid_of_walk walk_ok + +theorem size_ok : code.size < 2 ^ 32 := by + decide +kernel + +theorem check_ok : checkC evm15 code cert maxs = true := by + simp only [checkC, walk_ok, blocks_ok, labels_ok, decide_eq_true size_ok, Bool.and_true, + Bool.true_and] + decide + +set_option maxRecDepth 100000 in +/-- The mutant fails the check by evaluation. -/ +theorem mutant_fails : checkC evm15 mutant cert maxs = false := by + decide +kernel + +/-- **ArrayMaxEntry's bytecode, run by run**: at every gas below `2 ^ 256` and every call, the +oracle of the run's table makes every result of the bytecode the final EVM IR's or a failure that +changes nothing. -/ +theorem bytecode_runs (scope : SolarTV.Call → Prop) : + WithinRunLt SolarTV.evmirSem (fun _ => evm15) code scope (RunOracle.CertOk cert) := + withinRun_of_checkC check_ok scope + +/-- info: 'SolidCore.Refinement.Solar.ArrayMaxRun.bytecode_runs' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecode_runs + +end SolidCore.Refinement.Solar.ArrayMaxRun diff --git a/Contracts/ArrayMax/Inferred.lean b/Contracts/ArrayMax/Inferred.lean new file mode 100644 index 00000000..c6b6db96 --- /dev/null +++ b/Contracts/ArrayMax/Inferred.lean @@ -0,0 +1,84 @@ +-- Generated by solar-tv/milestone/inferred.py from what solar-verify --show-inferred printed +-- (sha256 b5a802bde34f8e9b2a85671fbab3b613ff7ea9e8c46cf3741350387698a76887) and Stage0.lean (sha256 2ab103c66098e0cbff43e9d16f844b9fc8f2178914b597de6fa486e8f338e04c); do not edit. +import W1Proofs.Stage +import arraymax.gen.ArrayMaxEntry.Stage0 + +/-! +# The inferred invariant of `max`'s loop at its header + +solar-verify inferred, for the loop at line 10 of the source: + +* `i >= 1` (guard) +* `i >= entry(i)` (guard) +* `i <= xs.length` (guard) +* `m >= entry(m)` (guard) +* `forall uint256 j :: j < xs.length ==> xs[j] <= m [xs.length := i]` (spec) +* `exists uint256 j :: j < xs.length && xs[j] == m` (spec) +* `exists uint256 j :: j < xs.length && xs[j] == m [xs.length := i]` (spec) +* `xs.length > 0` (spec) +* `xs.length > 0 [xs.length := i]` (spec) +* the measure `xs.length - i` + +They are bound to bb2 of function 0 of the first lowered MIR as `i` to phi 39, `xs.length` to `calldataWord call (calldataWord call 4 + (4 : EvmRules.Word))`, `xs` to the memory array at 119, `m` to phi 38; the +frame (storage, the values the loop reads from before it, the branches before the loop and +the facts the header checks of memory) is read off the MIR. The cut-point proof checks every +conjunct on every segment; none is assumed. +-/ + +namespace SolarTV.Milestone.ArrayMaxEntry.Inferred + +open Machine SolarTV.Milestone.W1 + +/-- At bb2 entered from bb5 (the loop's back edge), before its phis bind. -/ +def at5 (call : Call) (env : MIR.Lowered.Env) (s : State) : Prop := + (1 : EvmRules.Word) ≤ env 51 ∧ + (1 : EvmRules.Word) ≤ env 51 ∧ + env 51 ≤ calldataWord call (calldataWord call 4 + (4 : EvmRules.Word)) ∧ + s.memory.load (((128 : EvmRules.Word) + (32 : EvmRules.Word))).toNat ≤ env 50 ∧ + (∀ j : EvmRules.Word, (j < env 51 → s.memory.load (env 119 + 32 + 32 * j).toNat ≤ env 50)) ∧ + (∃ j : EvmRules.Word, (j < calldataWord call (calldataWord call 4 + (4 : EvmRules.Word)) ∧ s.memory.load (env 119 + 32 + 32 * j).toNat = env 50)) ∧ + (∃ j : EvmRules.Word, (j < env 51 ∧ s.memory.load (env 119 + 32 + 32 * j).toNat = env 50)) ∧ + (0 : EvmRules.Word) < calldataWord call (calldataWord call 4 + (4 : EvmRules.Word)) ∧ + (0 : EvmRules.Word) < env 51 ∧ + env 129 = ((128 : EvmRules.Word) + (64 : EvmRules.Word)) + 32 * (env 51 - 1) ∧ + s.storage = (State.initial call).storage ∧ + env 91 = calldataWord call (calldataWord call 4 + (4 : EvmRules.Word)) ∧ + env 119 = (128 : EvmRules.Word) ∧ + env 12 = (0 : EvmRules.Word) ∧ + (∀ j : EvmRules.Word, j < calldataWord call (calldataWord call 4 + (4 : EvmRules.Word)) → s.memory.load (((128 : EvmRules.Word) + (32 : EvmRules.Word)) + 32 * j).toNat = calldataWord call (((calldataWord call 4 + (4 : EvmRules.Word)) + (32 : EvmRules.Word)) + 32 * j)) ∧ + s.memory.load (env 119).toNat = env 91 + +/-- At bb2 entered from bb10 (the loop's entry), before its phis bind. -/ +def at10 (call : Call) (env : MIR.Lowered.Env) (s : State) : Prop := + (1 : EvmRules.Word) ≤ (1 : EvmRules.Word) ∧ + (1 : EvmRules.Word) ≤ (1 : EvmRules.Word) ∧ + (1 : EvmRules.Word) ≤ calldataWord call (calldataWord call 4 + (4 : EvmRules.Word)) ∧ + s.memory.load (((128 : EvmRules.Word) + (32 : EvmRules.Word))).toNat ≤ env 37 ∧ + (∀ j : EvmRules.Word, (j < (1 : EvmRules.Word) → s.memory.load (env 119 + 32 + 32 * j).toNat ≤ env 37)) ∧ + (∃ j : EvmRules.Word, (j < calldataWord call (calldataWord call 4 + (4 : EvmRules.Word)) ∧ s.memory.load (env 119 + 32 + 32 * j).toNat = env 37)) ∧ + (∃ j : EvmRules.Word, (j < (1 : EvmRules.Word) ∧ s.memory.load (env 119 + 32 + 32 * j).toNat = env 37)) ∧ + (0 : EvmRules.Word) < calldataWord call (calldataWord call 4 + (4 : EvmRules.Word)) ∧ + (0 : EvmRules.Word) < (1 : EvmRules.Word) ∧ + env 37 = s.memory.load (((128 : EvmRules.Word) + (32 : EvmRules.Word))).toNat ∧ + env 126 = ((128 : EvmRules.Word) + (64 : EvmRules.Word)) ∧ + env 126 = ((128 : EvmRules.Word) + (64 : EvmRules.Word)) + 32 * ((1 : EvmRules.Word) - 1) ∧ + s.storage = (State.initial call).storage ∧ + env 91 = calldataWord call (calldataWord call 4 + (4 : EvmRules.Word)) ∧ + env 119 = (128 : EvmRules.Word) ∧ + env 12 = (0 : EvmRules.Word) ∧ + (∀ j : EvmRules.Word, j < calldataWord call (calldataWord call 4 + (4 : EvmRules.Word)) → s.memory.load (((128 : EvmRules.Word) + (32 : EvmRules.Word)) + 32 * j).toNat = calldataWord call (((calldataWord call 4 + (4 : EvmRules.Word)) + (32 : EvmRules.Word)) + 32 * j)) ∧ + s.memory.load (env 119).toNat = env 91 + +/-- The header invariant: the frame enters bb2 of function 0 from one of its predecessors, +and that predecessor's conjuncts hold. -/ +def Inv (call : Call) (x : MIR.Lowered.Frame) : Prop := + (∃ env s, x = ([], .enter 0 5 2, env, s) ∧ at5 call env s) ∨ + (∃ env s, x = ([], .enter 0 10 2, env, s) ∧ at10 call env s) + +/-- The measure `xs.length - i` at the header, in Nat. -/ +def rank (call : Call) : MIR.Lowered.Frame → Nat + | (_, .enter _ 5 _, env, _) => ((calldataWord call (calldataWord call 4 + (4 : EvmRules.Word))).toNat - (env 51).toNat) + | (_, .enter _ 10 _, _, _) => ((calldataWord call (calldataWord call 4 + (4 : EvmRules.Word))).toNat - ((1 : EvmRules.Word)).toNat) + | _ => 0 + +end SolarTV.Milestone.ArrayMaxEntry.Inferred diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/clamp.lean b/Contracts/ArrayMax/Proofs/ArrayMax/clamp.lean new file mode 100644 index 00000000..fe8a6774 --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/clamp.lean @@ -0,0 +1,16 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.clamp + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +/-! Kernel proofs of the required obligations of ArrayMax.clamp, as the frozen v1 export states them +(`Vc/ArrayMax/clamp.lean`). -/ + +namespace Contracts.ArrayMax.clamp + +/-- ArrayMax.clamp#1 (obligation): postcondition not satisfied: r <= n. -/ +theorem ob1 : SolarVerifyVc.ArrayMax.clamp.ob1.Valid := by + first | vc_bounded_valid | vc_valid + +end Contracts.ArrayMax.clamp diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max.lean new file mode 100644 index 00000000..a5ee0281 --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max.lean @@ -0,0 +1,18 @@ +import Contracts.ArrayMax.Proofs.ArrayMax.max.ob0 +import Contracts.ArrayMax.Proofs.ArrayMax.max.ob1 +import Contracts.ArrayMax.Proofs.ArrayMax.max.ob2 +import Contracts.ArrayMax.Proofs.ArrayMax.max.ob3 +import Contracts.ArrayMax.Proofs.ArrayMax.max.ob4 +import Contracts.ArrayMax.Proofs.ArrayMax.max.ob5 +import Contracts.ArrayMax.Proofs.ArrayMax.max.ob6 +import Contracts.ArrayMax.Proofs.ArrayMax.max.ob7 +import Contracts.ArrayMax.Proofs.ArrayMax.max.ob8 +import Contracts.ArrayMax.Proofs.ArrayMax.max.ob9 +import Contracts.ArrayMax.Proofs.ArrayMax.max.ob10 +import Contracts.ArrayMax.Proofs.ArrayMax.max.ob11 +import Contracts.ArrayMax.Proofs.ArrayMax.max.ob12 +import Contracts.ArrayMax.Proofs.ArrayMax.max.ob14 +import Contracts.ArrayMax.Proofs.ArrayMax.max.ob15 + +/-! Kernel proofs of the required obligations of ArrayMax.max, as the frozen v1 export states them +(`Vc/ArrayMax/max.lean`), one module per obligation so that no Lean process holds them all. -/ diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max/ob0.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob0.lean new file mode 100644 index 00000000..d7e691b5 --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob0.lean @@ -0,0 +1,13 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +namespace Contracts.ArrayMax.max + +/-- ArrayMax.max#0 (obligation): loop invariant not satisfied on entry: 1 <= i. -/ +theorem ob0 : SolarVerifyVc.ArrayMax.max.ob0.Valid := by + vc_valid + +end Contracts.ArrayMax.max diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max/ob1.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob1.lean new file mode 100644 index 00000000..24856ed5 --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob1.lean @@ -0,0 +1,13 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +namespace Contracts.ArrayMax.max + +/-- ArrayMax.max#1 (obligation): loop invariant not satisfied on entry: i <= xs.length. -/ +theorem ob1 : SolarVerifyVc.ArrayMax.max.ob1.Valid := by + vc_valid + +end Contracts.ArrayMax.max diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max/ob10.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob10.lean new file mode 100644 index 00000000..f052537c --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob10.lean @@ -0,0 +1,13 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +namespace Contracts.ArrayMax.max + +/-- ArrayMax.max#10 (obligation): loop invariant not preserved by the loop body: exists uint256 j :: j < xs.length && xs[j] == m. -/ +theorem ob10 : SolarVerifyVc.ArrayMax.max.ob10.Valid := by + vc_valid_prep <;> vc_bounded + +end Contracts.ArrayMax.max diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max/ob11.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob11.lean new file mode 100644 index 00000000..41541e8c --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob11.lean @@ -0,0 +1,13 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +namespace Contracts.ArrayMax.max + +/-- ArrayMax.max#11 (obligation): loop invariant not preserved by the loop body: xs.length > 0. -/ +theorem ob11 : SolarVerifyVc.ArrayMax.max.ob11.Valid := by + vc_valid + +end Contracts.ArrayMax.max diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max/ob12.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob12.lean new file mode 100644 index 00000000..434bce94 --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob12.lean @@ -0,0 +1,13 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +namespace Contracts.ArrayMax.max + +/-- ArrayMax.max#12 (obligation): loop does not terminate: decreases clause not decreased: (xs.length) - i. -/ +theorem ob12 : SolarVerifyVc.ArrayMax.max.ob12.Valid := by + vc_valid + +end Contracts.ArrayMax.max diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max/ob14.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob14.lean new file mode 100644 index 00000000..771b7879 --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob14.lean @@ -0,0 +1,13 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +namespace Contracts.ArrayMax.max + +/-- ArrayMax.max#14 (obligation): postcondition not satisfied: forall uint256 j :: j < xs.length ==> xs[j] <= m. -/ +theorem ob14 : SolarVerifyVc.ArrayMax.max.ob14.Valid := by + vc_bounded_valid + +end Contracts.ArrayMax.max diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max/ob15.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob15.lean new file mode 100644 index 00000000..0332264a --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob15.lean @@ -0,0 +1,13 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +namespace Contracts.ArrayMax.max + +/-- ArrayMax.max#15 (obligation): postcondition not satisfied: exists uint256 j :: j < xs.length && xs[j] == m. -/ +theorem ob15 : SolarVerifyVc.ArrayMax.max.ob15.Valid := by + vc_valid + +end Contracts.ArrayMax.max diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max/ob2.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob2.lean new file mode 100644 index 00000000..51f67365 --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob2.lean @@ -0,0 +1,13 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +namespace Contracts.ArrayMax.max + +/-- ArrayMax.max#2 (obligation): loop invariant not satisfied on entry: forall uint256 j :: j < i ==> xs[j] <= m. -/ +theorem ob2 : SolarVerifyVc.ArrayMax.max.ob2.Valid := by + vc_valid + +end Contracts.ArrayMax.max diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max/ob3.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob3.lean new file mode 100644 index 00000000..42bbe1ec --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob3.lean @@ -0,0 +1,13 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +namespace Contracts.ArrayMax.max + +/-- ArrayMax.max#3 (obligation): loop invariant not satisfied on entry: exists uint256 j :: j < i && xs[j] == m. -/ +theorem ob3 : SolarVerifyVc.ArrayMax.max.ob3.Valid := by + vc_valid + +end Contracts.ArrayMax.max diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max/ob4.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob4.lean new file mode 100644 index 00000000..23d98a1f --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob4.lean @@ -0,0 +1,13 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +namespace Contracts.ArrayMax.max + +/-- ArrayMax.max#4 (obligation): loop invariant not satisfied on entry: exists uint256 j :: j < xs.length && xs[j] == m. -/ +theorem ob4 : SolarVerifyVc.ArrayMax.max.ob4.Valid := by + vc_valid + +end Contracts.ArrayMax.max diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max/ob5.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob5.lean new file mode 100644 index 00000000..97a798e5 --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob5.lean @@ -0,0 +1,13 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +namespace Contracts.ArrayMax.max + +/-- ArrayMax.max#5 (obligation): loop invariant not satisfied on entry: xs.length > 0. -/ +theorem ob5 : SolarVerifyVc.ArrayMax.max.ob5.Valid := by + vc_valid + +end Contracts.ArrayMax.max diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max/ob6.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob6.lean new file mode 100644 index 00000000..a5ad05a0 --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob6.lean @@ -0,0 +1,13 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +namespace Contracts.ArrayMax.max + +/-- ArrayMax.max#6 (obligation): loop invariant not preserved by the loop body: 1 <= i. -/ +theorem ob6 : SolarVerifyVc.ArrayMax.max.ob6.Valid := by + vc_valid + +end Contracts.ArrayMax.max diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max/ob7.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob7.lean new file mode 100644 index 00000000..3ec1d337 --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob7.lean @@ -0,0 +1,13 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +namespace Contracts.ArrayMax.max + +/-- ArrayMax.max#7 (obligation): loop invariant not preserved by the loop body: i <= xs.length. -/ +theorem ob7 : SolarVerifyVc.ArrayMax.max.ob7.Valid := by + vc_valid + +end Contracts.ArrayMax.max diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max/ob8.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob8.lean new file mode 100644 index 00000000..7a67bc96 --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob8.lean @@ -0,0 +1,13 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +namespace Contracts.ArrayMax.max + +/-- ArrayMax.max#8 (obligation): loop invariant not preserved by the loop body: forall uint256 j :: j < i ==> xs[j] <= m. -/ +theorem ob8 : SolarVerifyVc.ArrayMax.max.ob8.Valid := by + vc_valid_prep <;> vc_bounded_leaf + +end Contracts.ArrayMax.max diff --git a/Contracts/ArrayMax/Proofs/ArrayMax/max/ob9.lean b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob9.lean new file mode 100644 index 00000000..a63b1a8e --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMax/max/ob9.lean @@ -0,0 +1,13 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMax.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +namespace Contracts.ArrayMax.max + +/-- ArrayMax.max#9 (obligation): loop invariant not preserved by the loop body: exists uint256 j :: j < i && xs[j] == m. -/ +theorem ob9 : SolarVerifyVc.ArrayMax.max.ob9.Valid := by + vc_bounded_valid + +end Contracts.ArrayMax.max diff --git a/Contracts/ArrayMax/Proofs/ArrayMaxEntry/max.lean b/Contracts/ArrayMax/Proofs/ArrayMaxEntry/max.lean new file mode 100644 index 00000000..635cffab --- /dev/null +++ b/Contracts/ArrayMax/Proofs/ArrayMaxEntry/max.lean @@ -0,0 +1,24 @@ +import Contracts.ArrayMax.Bounded +import Contracts.ArrayMax.Vc.ArrayMaxEntry.max + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +/-! Kernel proofs of the required obligations of ArrayMaxEntry.max, as the frozen v1 export states them +(`Vc/ArrayMaxEntry/max.lean`). -/ + +namespace Contracts.ArrayMaxEntry.max + +/-- ArrayMaxEntry.max#0 (obligation): precondition of 'max' not satisfied: xs.length > 0. -/ +theorem ob0 : SolarVerifyVc.ArrayMaxEntry.max.ob0.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMaxEntry.max#2 (obligation): postcondition not satisfied: forall uint256 j :: j < xs.length ==> xs[j] <= result. -/ +theorem ob2 : SolarVerifyVc.ArrayMaxEntry.max.ob2.Valid := by + first | vc_bounded_valid | vc_valid + +/-- ArrayMaxEntry.max#3 (obligation): postcondition not satisfied: exists uint256 j :: j < xs.length && xs[j] == result. -/ +theorem ob3 : SolarVerifyVc.ArrayMaxEntry.max.ob3.Valid := by + first | vc_bounded_valid | vc_valid + +end Contracts.ArrayMaxEntry.max diff --git a/Contracts/ArrayMax/README.md b/Contracts/ArrayMax/README.md new file mode 100644 index 00000000..5df24181 --- /dev/null +++ b/Contracts/ArrayMax/README.md @@ -0,0 +1,47 @@ +# ArrayMax: solar-verify's obligations in the Lean kernel + +`Vc/` holds the frozen v1 export of `crates/verify/examples/ArrayMax.sol` (paradigmxyz/solar +7f4e94e, `solar-verify --emit-lean`, z3 4.13.4, cvc5 1.3.1). Each module is the exporter's output +with one change: its first line `import SolarVerify` reads `import Verify.Obligation`, where the +same library now lives (the `VerifyDischarge` library). `Vc/frozen.sha256` is the lock of the unchanged export, which +`Vc/manifest.json` and the modules match before that rewrite. + +The loop of `ArrayMax.max` carries no written invariant: solar-verify infers it, and the inferred +clauses reach Lean only as the ordinary loop obligations (on entry, preserved, and the +postconditions they imply), which are proved here like any other. + +`Bounded.lean` is the search that closes the obligations the default `vc_valid` cannot +(`max`'s preserved quantified invariants, and Vault's reentrancy-lock obligations); it builds +proof terms only, and every theorem's axioms are checked to be `propext`, `Classical.choice` and +`Quot.sound`. + +## Inferred invariant and memory writes + +solar-verify's loop-invariant inference was later found to be unsound for loops around internal +calls that write a memory array the caller passed; solar now refuses those loops. ArrayMax is +outside that case: `max` only reads `xs`, calls nothing, and neither `ArrayMaxEntry.max` nor +`clamp` writes an array, so the inferred clauses checked here are unaffected. They are, in any +case, not trusted: each is re-proved here as an ordinary obligation. + +## Building + +`lake build ContractsArrayMaxVault` builds the exports, the proofs and `Audit.lean`, which fails +unless every theorem uses no axiom but `propext`, `Classical.choice` and `Quot.sound`. + +## ArrayMaxEntry.max on solar's code + +`Entry.lean` (with `Entry/{Basic,Loop,Start}.lean`) proves `ArrayMaxEntry.max`'s ensures clauses (every +element of the calldata array is at most the result, and one equals it) of solar's first lowered +MIR of this file (Certified/arraymax), on every call of `max(uint256[])`, whatever the array's +length: one cut point at the loop's header, where `Inferred.lean` is the invariant solar-verify +inferred for `ArrayMax.max`'s loop (its `forall` and `exists` clauses over `xs` included), carried to the +header by solar's `solar-tv/milestone/arraymax/inferred.sh`; it is generated, never written here, and +every conjunct is checked on every segment. One named hypothesis, `CalldataFits`: the calldata +is shorter than 2^64 bytes, without which the decoder's word arithmetic could wrap. +`Wrong.lean`: the kernel runs the code on `max([1, 7, 3])` to a return of 7, which refutes the mutant +spec "returns the first element". + +`Execution.lean`: the bytecode runs as the final EVM IR (`AssembleCut.checkC`, memory at any offset). +Not covered: Certified/arraymax's MIR stages (`Runs.Mir1` fails `sym_seg` on the ABI decoder's +checks, so the spec is not yet carried from the first lowered MIR to the final EVM IR), and the link from the VCs in `Vc/` (about solar-verify's +model of the source) to this code: the spec here is restated on the code. diff --git a/Contracts/ArrayMax/Vc/ArrayMax/clamp.lean b/Contracts/ArrayMax/Vc/ArrayMax/clamp.lean new file mode 100644 index 00000000..e83ea593 --- /dev/null +++ b/Contracts/ArrayMax/Vc/ArrayMax/clamp.lean @@ -0,0 +1,74 @@ +-- Generated by solar-verify --emit-lean (format 1); do not edit. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.ArrayMax.clamp +open SolarVerify.Smt SolarVerify.Vc + +/-- Script 0 of ArrayMax.clamp: the solver's assertion stack. -/ +def script0 : Script where + decls := [ + ⟨"|this@1|", [], .int⟩, + ⟨"|msg.sender@2|", [], .int⟩, + ⟨"|msg.value@3|", [], .int⟩, + ⟨"|block.timestamp@4|", [], .int⟩, + ⟨"|block.number@5|", [], .int⟩, + ⟨"|block.chainid@6|", [], .int⟩, + ⟨"|tx.origin@7|", [], .int⟩, + ⟨"|tx.gasprice@8|", [], .int⟩, + ⟨"|msg.sig@9|", [], .int⟩, + ⟨"|msg.data@10|", [], .int⟩, + ⟨"|block.basefee@11|", [], .int⟩, + ⟨"|block.blobbasefee@12|", [], .int⟩, + ⟨"|block.coinbase@13|", [], .int⟩, + ⟨"|block.prevrandao@14|", [], .int⟩, + ⟨"|block.difficulty@15|", [], .int⟩, + ⟨"|block.gaslimit@16|", [], .int⟩, + ⟨"|x@17|", [], .int⟩, + ⟨"|n@18|", [], .int⟩, + ⟨"|g@19|", [], .bool⟩, + ⟨"|g@20|", [], .bool⟩, + ⟨"|g@21|", [], .bool⟩, + ⟨"|r@22|", [], .int⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 16 []], .app .le [.fn 16 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 18 [], .app .and [.bool true, .app .gt [.fn 16 [], .fn 17 []]]], + .app .eq [.fn 19 [], .app .and [.bool true, .app .not [.app .gt [.fn 16 [], .fn 17 []]]]], + .app .eq [.fn 20 [], .app .or [.fn 18 [], .fn 19 []]], + .app .eq [.fn 21 [], .app .ite [.app .gt [.fn 16 [], .fn 17 []], .fn 17 [], .fn 16 []]] + ] + +/-- ArrayMax.clamp#0: a query only a warning reads (sat). -/ +def ob0 : Obligation where + script := script0 + upto := 22 + guard := .fn 20 [] + goal := .bool false + +/-- ArrayMax.clamp#1: postcondition not satisfied: `r <= n` (unsat). -/ +def ob1 : Obligation where + script := script0 + upto := 22 + guard := .fn 20 [] + goal := .app .le [.fn 21 [], .fn 17 []] + +end SolarVerifyVc.ArrayMax.clamp diff --git a/Contracts/ArrayMax/Vc/ArrayMax/max.lean b/Contracts/ArrayMax/Vc/ArrayMax/max.lean new file mode 100644 index 00000000..d903dbab --- /dev/null +++ b/Contracts/ArrayMax/Vc/ArrayMax/max.lean @@ -0,0 +1,210 @@ +-- Generated by solar-verify --emit-lean (format 1); do not edit. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.ArrayMax.max +open SolarVerify.Smt SolarVerify.Vc + +/-- Script 0 of ArrayMax.max: the solver's assertion stack. -/ +def script0 : Script where + decls := [ + ⟨"|this@1|", [], .int⟩, + ⟨"|msg.sender@2|", [], .int⟩, + ⟨"|msg.value@3|", [], .int⟩, + ⟨"|block.timestamp@4|", [], .int⟩, + ⟨"|block.number@5|", [], .int⟩, + ⟨"|block.chainid@6|", [], .int⟩, + ⟨"|tx.origin@7|", [], .int⟩, + ⟨"|tx.gasprice@8|", [], .int⟩, + ⟨"|msg.sig@9|", [], .int⟩, + ⟨"|msg.data@10|", [], .int⟩, + ⟨"|block.basefee@11|", [], .int⟩, + ⟨"|block.blobbasefee@12|", [], .int⟩, + ⟨"|block.coinbase@13|", [], .int⟩, + ⟨"|block.prevrandao@14|", [], .int⟩, + ⟨"|block.difficulty@15|", [], .int⟩, + ⟨"|block.gaslimit@16|", [], .int⟩, + ⟨"|xs@17|", [], (.array .int .int)⟩, + ⟨"|xs.length@18|", [], .int⟩, + ⟨"|g@19|", [], .bool⟩, + ⟨"|g@20|", [], .bool⟩, + ⟨"|m@21|", [], .int⟩, + ⟨"|i@28|", [], .int⟩, + ⟨"|m@29|", [], .int⟩, + ⟨"|g@30|", [], .bool⟩, + ⟨"|g@31|", [], .bool⟩, + ⟨"|g@33|", [], .bool⟩, + ⟨"|g@35|", [], .bool⟩, + ⟨"|g@37|", [], .bool⟩, + ⟨"|g@38|", [], .bool⟩, + ⟨"|g@39|", [], .bool⟩, + ⟨"|g@40|", [], .bool⟩, + ⟨"|g@41|", [], .bool⟩, + ⟨"|g@42|", [], .bool⟩, + ⟨"|m@43|", [], .int⟩, + ⟨"|g@44|", [], .bool⟩, + ⟨"|g@45|", [], .bool⟩, + ⟨"|m@46|", [], .int⟩, + ⟨"|arith@47|", [], .int⟩, + ⟨"|g@48|", [], .bool⟩, + ⟨"|g@52|", [], .bool⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 18 [], .app .and [.bool true, .app .gt [.fn 17 [], .int 0]]], + .app .eq [.fn 19 [], .app .and [.fn 18 [], .app .and [.app .le [.int 0, .int 0], .app .lt [.int 0, .fn 17 []]]]], + .app .and [.app .le [.int 0, .app .select [.fn 16 [], .int 0]], .app .le [.app .select [.fn 16 [], .int 0], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 20 [], .app .select [.fn 16 [], .int 0]], + .app .and [.app .le [.int 0, .fn 21 []], .app .le [.fn 21 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 22 []], .app .le [.fn 22 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 23 [], .app .and [.fn 19 [], .app .le [.int 1, .fn 21 []]]], + .app .eq [.fn 24 [], .app .and [.fn 23 [], .app .le [.fn 21 [], .fn 17 []]]], + .app .eq [.fn 25 [], .app .and [.fn 24 [], .«forall» [.int] (.app .implies [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .implies [.app .lt [.var 0, .fn 21 []], .app .le [.app .select [.fn 16 [], .var 0], .fn 22 []]]])]], + .app .eq [.fn 26 [], .app .and [.fn 25 [], .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .fn 21 []], .app .eq [.app .select [.fn 16 [], .var 0], .fn 22 []]]])]], + .app .eq [.fn 27 [], .app .and [.fn 26 [], .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .fn 17 []], .app .eq [.app .select [.fn 16 [], .var 0], .fn 22 []]]])]], + .app .eq [.fn 28 [], .app .and [.fn 27 [], .app .gt [.fn 17 [], .int 0]]], + .app .eq [.fn 29 [], .app .and [.fn 28 [], .app .lt [.fn 21 [], .fn 17 []]]], + .app .eq [.fn 30 [], .app .and [.fn 29 [], .app .and [.app .le [.int 0, .fn 21 []], .app .lt [.fn 21 [], .fn 17 []]]]], + .app .and [.app .le [.int 0, .app .select [.fn 16 [], .fn 21 []]], .app .le [.app .select [.fn 16 [], .fn 21 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 31 [], .app .and [.fn 30 [], .app .gt [.app .select [.fn 16 [], .fn 21 []], .fn 22 []]]], + .app .eq [.fn 32 [], .app .and [.fn 31 [], .app .and [.app .le [.int 0, .fn 21 []], .app .lt [.fn 21 [], .fn 17 []]]]], + .app .and [.app .le [.int 0, .app .select [.fn 16 [], .fn 21 []]], .app .le [.app .select [.fn 16 [], .fn 21 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 33 [], .app .select [.fn 16 [], .fn 21 []]], + .app .eq [.fn 34 [], .app .and [.fn 30 [], .app .not [.app .gt [.app .select [.fn 16 [], .fn 21 []], .fn 22 []]]]], + .app .eq [.fn 35 [], .app .or [.fn 32 [], .fn 34 []]], + .app .eq [.fn 36 [], .app .ite [.fn 32 [], .fn 33 [], .fn 22 []]], + .app .eq [.fn 37 [], .app .add [.fn 21 [], .int 1]], + .app .eq [.fn 38 [], .app .and [.fn 35 [], .app .and [.app .le [.int 0, .fn 37 []], .app .le [.fn 37 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 39 [], .app .and [.fn 28 [], .app .not [.app .lt [.fn 21 [], .fn 17 []]]]] + ] + +/-- ArrayMax.max#0: loop invariant not satisfied on entry: `1 <= i` (unsat). -/ +def ob0 : Obligation where + script := script0 + upto := 21 + guard := .fn 19 [] + goal := .app .le [.int 1, .int 1] + +/-- ArrayMax.max#1: loop invariant not satisfied on entry: `i <= xs.length` (unsat). -/ +def ob1 : Obligation where + script := script0 + upto := 21 + guard := .fn 19 [] + goal := .app .le [.int 1, .fn 17 []] + +/-- ArrayMax.max#2: loop invariant not satisfied on entry: `forall uint256 j :: j < i ==> xs[j] <= m` (unsat). -/ +def ob2 : Obligation where + script := script0 + upto := 21 + guard := .fn 19 [] + goal := .«forall» [.int] (.app .implies [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .implies [.app .lt [.var 0, .int 1], .app .le [.app .select [.fn 16 [], .var 0], .fn 20 []]]]) + +/-- ArrayMax.max#3: loop invariant not satisfied on entry: `exists uint256 j :: j < i && xs[j] == m` (unsat). -/ +def ob3 : Obligation where + script := script0 + upto := 21 + guard := .fn 19 [] + goal := .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .int 1], .app .eq [.app .select [.fn 16 [], .var 0], .fn 20 []]]]) + +/-- ArrayMax.max#4: loop invariant not satisfied on entry: `exists uint256 j :: j < xs.length && xs[j] == m` (unsat). -/ +def ob4 : Obligation where + script := script0 + upto := 21 + guard := .fn 19 [] + goal := .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .fn 17 []], .app .eq [.app .select [.fn 16 [], .var 0], .fn 20 []]]]) + +/-- ArrayMax.max#5: loop invariant not satisfied on entry: `xs.length > 0` (unsat). -/ +def ob5 : Obligation where + script := script0 + upto := 21 + guard := .fn 19 [] + goal := .app .gt [.fn 17 [], .int 0] + +/-- ArrayMax.max#6: loop invariant not preserved by the loop body: `1 <= i` (unsat). -/ +def ob6 : Obligation where + script := script0 + upto := 41 + guard := .fn 38 [] + goal := .app .le [.int 1, .fn 37 []] + +/-- ArrayMax.max#7: loop invariant not preserved by the loop body: `i <= xs.length` (unsat). -/ +def ob7 : Obligation where + script := script0 + upto := 41 + guard := .fn 38 [] + goal := .app .le [.fn 37 [], .fn 17 []] + +/-- ArrayMax.max#8: loop invariant not preserved by the loop body: `forall uint256 j :: j < i ==> xs[j] <= m` (unsat). -/ +def ob8 : Obligation where + script := script0 + upto := 41 + guard := .fn 38 [] + goal := .«forall» [.int] (.app .implies [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .implies [.app .lt [.var 0, .fn 37 []], .app .le [.app .select [.fn 16 [], .var 0], .fn 36 []]]]) + +/-- ArrayMax.max#9: loop invariant not preserved by the loop body: `exists uint256 j :: j < i && xs[j] == m` (unsat). -/ +def ob9 : Obligation where + script := script0 + upto := 41 + guard := .fn 38 [] + goal := .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .fn 37 []], .app .eq [.app .select [.fn 16 [], .var 0], .fn 36 []]]]) + +/-- ArrayMax.max#10: loop invariant not preserved by the loop body: `exists uint256 j :: j < xs.length && xs[j] == m` (unsat). -/ +def ob10 : Obligation where + script := script0 + upto := 41 + guard := .fn 38 [] + goal := .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .fn 17 []], .app .eq [.app .select [.fn 16 [], .var 0], .fn 36 []]]]) + +/-- ArrayMax.max#11: loop invariant not preserved by the loop body: `xs.length > 0` (unsat). -/ +def ob11 : Obligation where + script := script0 + upto := 41 + guard := .fn 38 [] + goal := .app .gt [.fn 17 [], .int 0] + +/-- ArrayMax.max#12: loop does not terminate: decreases clause not decreased: `(xs.length) - i` (unsat). -/ +def ob12 : Obligation where + script := script0 + upto := 41 + guard := .fn 38 [] + goal := .app .and [.app .le [.int 0, .app .sub [.fn 17 [], .fn 21 []]], .app .lt [.app .sub [.fn 17 [], .fn 37 []], .app .sub [.fn 17 [], .fn 21 []]]] + +/-- ArrayMax.max#13: a query only a warning reads (sat). -/ +def ob13 : Obligation where + script := script0 + upto := 42 + guard := .fn 39 [] + goal := .bool false + +/-- ArrayMax.max#14: postcondition not satisfied: `forall uint256 j :: j < xs.length ==> xs[j] <= m` (unsat). -/ +def ob14 : Obligation where + script := script0 + upto := 42 + guard := .fn 39 [] + goal := .«forall» [.int] (.app .implies [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .implies [.app .lt [.var 0, .fn 17 []], .app .le [.app .select [.fn 16 [], .var 0], .fn 22 []]]]) + +/-- ArrayMax.max#15: postcondition not satisfied: `exists uint256 j :: j < xs.length && xs[j] == m` (unsat). -/ +def ob15 : Obligation where + script := script0 + upto := 42 + guard := .fn 39 [] + goal := .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .fn 17 []], .app .eq [.app .select [.fn 16 [], .var 0], .fn 22 []]]]) + +end SolarVerifyVc.ArrayMax.max diff --git a/Contracts/ArrayMax/Vc/ArrayMaxEntry/constructor.lean b/Contracts/ArrayMax/Vc/ArrayMaxEntry/constructor.lean new file mode 100644 index 00000000..501038db --- /dev/null +++ b/Contracts/ArrayMax/Vc/ArrayMaxEntry/constructor.lean @@ -0,0 +1,60 @@ +-- Generated by solar-verify --emit-lean (format 1); do not edit. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.ArrayMaxEntry.constructor +open SolarVerify.Smt SolarVerify.Vc + +/-- Script 0 of ArrayMaxEntry.constructor: the solver's assertion stack. -/ +def script0 : Script where + decls := [ + ⟨"|this@1|", [], .int⟩, + ⟨"|msg.sender@2|", [], .int⟩, + ⟨"|msg.value@3|", [], .int⟩, + ⟨"|block.timestamp@4|", [], .int⟩, + ⟨"|block.number@5|", [], .int⟩, + ⟨"|block.chainid@6|", [], .int⟩, + ⟨"|tx.origin@7|", [], .int⟩, + ⟨"|tx.gasprice@8|", [], .int⟩, + ⟨"|msg.sig@9|", [], .int⟩, + ⟨"|msg.data@10|", [], .int⟩, + ⟨"|block.basefee@11|", [], .int⟩, + ⟨"|block.blobbasefee@12|", [], .int⟩, + ⟨"|block.coinbase@13|", [], .int⟩, + ⟨"|block.prevrandao@14|", [], .int⟩, + ⟨"|block.difficulty@15|", [], .int⟩, + ⟨"|block.gaslimit@16|", [], .int⟩, + ⟨"|__balance@17|", [], (.array .int .int)⟩, + ⟨"|__code_epoch@18|", [], .int⟩, + ⟨"|g@19|", [], .bool⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 18 [], .app .and [.bool true, .app .eq [.fn 2 [], .int 0]]] + ] + +/-- ArrayMaxEntry.constructor#0: a query only a warning reads (sat). -/ +def ob0 : Obligation where + script := script0 + upto := 18 + guard := .fn 18 [] + goal := .bool false + +end SolarVerifyVc.ArrayMaxEntry.constructor diff --git a/Contracts/ArrayMax/Vc/ArrayMaxEntry/max.lean b/Contracts/ArrayMax/Vc/ArrayMaxEntry/max.lean new file mode 100644 index 00000000..9ab295ed --- /dev/null +++ b/Contracts/ArrayMax/Vc/ArrayMaxEntry/max.lean @@ -0,0 +1,92 @@ +-- Generated by solar-verify --emit-lean (format 1); do not edit. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.ArrayMaxEntry.max +open SolarVerify.Smt SolarVerify.Vc + +/-- Script 0 of ArrayMaxEntry.max: the solver's assertion stack. -/ +def script0 : Script where + decls := [ + ⟨"|this@1|", [], .int⟩, + ⟨"|msg.sender@2|", [], .int⟩, + ⟨"|msg.value@3|", [], .int⟩, + ⟨"|block.timestamp@4|", [], .int⟩, + ⟨"|block.number@5|", [], .int⟩, + ⟨"|block.chainid@6|", [], .int⟩, + ⟨"|tx.origin@7|", [], .int⟩, + ⟨"|tx.gasprice@8|", [], .int⟩, + ⟨"|msg.sig@9|", [], .int⟩, + ⟨"|msg.data@10|", [], .int⟩, + ⟨"|block.basefee@11|", [], .int⟩, + ⟨"|block.blobbasefee@12|", [], .int⟩, + ⟨"|block.coinbase@13|", [], .int⟩, + ⟨"|block.prevrandao@14|", [], .int⟩, + ⟨"|block.difficulty@15|", [], .int⟩, + ⟨"|block.gaslimit@16|", [], .int⟩, + ⟨"|__balance@17|", [], (.array .int .int)⟩, + ⟨"|__code_epoch@18|", [], .int⟩, + ⟨"|xs@19|", [], (.array .int .int)⟩, + ⟨"|xs.length@20|", [], .int⟩, + ⟨"|g@21|", [], .bool⟩, + ⟨"|g@22|", [], .bool⟩, + ⟨"|m@23|", [], .int⟩, + ⟨"|g@25|", [], .bool⟩, + ⟨"|g@27|", [], .bool⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 19 []], .app .le [.fn 19 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 20 [], .app .and [.bool true, .app .eq [.fn 2 [], .int 0]]], + .app .eq [.fn 21 [], .app .and [.fn 20 [], .app .gt [.fn 19 [], .int 0]]], + .app .and [.app .le [.int 0, .fn 22 []], .app .le [.fn 22 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 23 [], .app .and [.fn 21 [], .«forall» [.int] (.app .implies [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .implies [.app .lt [.var 0, .fn 19 []], .app .le [.app .select [.fn 18 [], .var 0], .fn 22 []]]])]], + .app .eq [.fn 24 [], .app .and [.fn 23 [], .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .fn 19 []], .app .eq [.app .select [.fn 18 [], .var 0], .fn 22 []]]])]] + ] + +/-- ArrayMaxEntry.max#0: precondition of `max` not satisfied: `xs.length > 0` (unsat). -/ +def ob0 : Obligation where + script := script0 + upto := 20 + guard := .fn 21 [] + goal := .app .gt [.fn 19 [], .int 0] + +/-- ArrayMaxEntry.max#1: a query only a warning reads (sat). -/ +def ob1 : Obligation where + script := script0 + upto := 23 + guard := .fn 24 [] + goal := .bool false + +/-- ArrayMaxEntry.max#2: postcondition not satisfied: `forall uint256 j :: j < xs.length ==> xs[j] <= result` (unsat). -/ +def ob2 : Obligation where + script := script0 + upto := 23 + guard := .fn 24 [] + goal := .«forall» [.int] (.app .implies [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .implies [.app .lt [.var 0, .fn 19 []], .app .le [.app .select [.fn 18 [], .var 0], .fn 22 []]]]) + +/-- ArrayMaxEntry.max#3: postcondition not satisfied: `exists uint256 j :: j < xs.length && xs[j] == result` (unsat). -/ +def ob3 : Obligation where + script := script0 + upto := 23 + guard := .fn 24 [] + goal := .«exists» [.int] (.app .and [.app .and [.app .and [.app .le [.int 0, .var 0], .app .le [.var 0, .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]], .app .and [.app .lt [.var 0, .fn 19 []], .app .eq [.app .select [.fn 18 [], .var 0], .fn 22 []]]]) + +end SolarVerifyVc.ArrayMaxEntry.max diff --git a/Contracts/ArrayMax/Vc/frozen.sha256 b/Contracts/ArrayMax/Vc/frozen.sha256 new file mode 100644 index 00000000..62894797 --- /dev/null +++ b/Contracts/ArrayMax/Vc/frozen.sha256 @@ -0,0 +1,5 @@ +fd6ba812db32525b609d720b646fa1db1c6f847553ffe5689aa569c0a0213241 manifest.json +1a02fe322248251cb404d8f56ad9110bbf4ead96cf56ad1117976351eeca0f5a ArrayMax/clamp.lean +a39b2942dcd59cf63faa1ced3aa86bb2834f362bfa894d7be9878f0ba66a44c6 ArrayMax/max.lean +fdda1a5f2c6049ddb1b7136571217dc2d743845728edbd4bbc4cfe2256ef5bd9 ArrayMaxEntry/constructor.lean +9bd919a6e290d34c0723dd1529e9bd64004112cd5c1ba5c91d13425f080329ed ArrayMaxEntry/max.lean diff --git a/Contracts/ArrayMax/Vc/manifest.json b/Contracts/ArrayMax/Vc/manifest.json new file mode 100644 index 00000000..03459c9e --- /dev/null +++ b/Contracts/ArrayMax/Vc/manifest.json @@ -0,0 +1,760 @@ +{ + "arguments": [ + "--emit-lean", + "vc-exports/ArrayMax", + "crates/verify/examples/ArrayMax.sol" + ], + "compiler": "0.8.38+commit.7f4e94e0.solar.0.3.0-dev", + "errors": [], + "format": "solar-verify-lean", + "lean": { + "library": "SolarVerify", + "smt_sha256": "2c92f3bcd927369da89250662bd5a6174d3c06d0c3c38f5021509fe8810036e3", + "toolchain": "leanprover/lean4:v4.35.0", + "vc_sha256": "7275fa354f077a4826dd9fe56124cbffee2337d7a21975b477534fc5f45d7cfe" + }, + "options": { + "dry_run": false, + "only": null, + "strict": false, + "timeout_ms": 10000 + }, + "solvers": { + "bitwuzla": null, + "cvc5": "This is cvc5 version 1.3.1 [git ea1b484 on branch HEAD]", + "z3": "Z3 version 4.13.4 - 64 bit" + }, + "sources": [ + { + "path": "/home/hand/wt-inferred/crates/verify/examples/ArrayMax.sol", + "sha256": "904535ac694498a9823f530ca158ee0c762fd1adcc56f3e7b73ca0e457e61f4a" + } + ], + "units": [ + { + "module": "ArrayMax/max.lean", + "name": "ArrayMax.max", + "namespace": "SolarVerifyVc.ArrayMax.max", + "obligations": [ + { + "answer": "unsat", + "asserts": 21, + "commands": 42, + "goal": "(<= 1 1)", + "guard": "|g@20|", + "id": "ArrayMax.max#0", + "kind": "loop invariant not satisfied on entry", + "lean": "SolarVerifyVc.ArrayMax.max.ob0", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "5295b5100b304c78178c05e0648edf7b8c5c65328262f7ee8a78c53d8182ee89", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "1 <= i" + } + }, + { + "answer": "unsat", + "asserts": 21, + "commands": 42, + "goal": "(<= 1 |xs.length@18|)", + "guard": "|g@20|", + "id": "ArrayMax.max#1", + "kind": "loop invariant not satisfied on entry", + "lean": "SolarVerifyVc.ArrayMax.max.ob1", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "347c5f72952324b53f4727ba7bf3fb662d77ca67db931b9655ec59d710bb22c4", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "i <= xs.length" + } + }, + { + "answer": "unsat", + "asserts": 21, + "commands": 42, + "goal": "(forall ((|j!25| Int)) (=> (and (and (<= 0 |j!25|) (<= |j!25| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (=> (< |j!25| 1) (<= (select |xs@17| |j!25|) |m@21|))))", + "guard": "|g@20|", + "id": "ArrayMax.max#2", + "kind": "loop invariant not satisfied on entry", + "lean": "SolarVerifyVc.ArrayMax.max.ob2", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "f980a79aecb59738706917debadad336afdd06f91c4b5507757b75995f9fd2b9", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "forall uint256 j :: j < i ==> xs[j] <= m" + } + }, + { + "answer": "unsat", + "asserts": 21, + "commands": 42, + "goal": "(exists ((|j!26| Int)) (and (and (and (<= 0 |j!26|) (<= |j!26| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (and (< |j!26| 1) (= (select |xs@17| |j!26|) |m@21|))))", + "guard": "|g@20|", + "id": "ArrayMax.max#3", + "kind": "loop invariant not satisfied on entry", + "lean": "SolarVerifyVc.ArrayMax.max.ob3", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "5dbc71e2ea2e9f356ecb6b576ba70861bf6170313124b302aec223cc7503b697", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "exists uint256 j :: j < i && xs[j] == m" + } + }, + { + "answer": "unsat", + "asserts": 21, + "commands": 42, + "goal": "(exists ((|j!27| Int)) (and (and (and (<= 0 |j!27|) (<= |j!27| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (and (< |j!27| |xs.length@18|) (= (select |xs@17| |j!27|) |m@21|))))", + "guard": "|g@20|", + "id": "ArrayMax.max#4", + "kind": "loop invariant not satisfied on entry", + "lean": "SolarVerifyVc.ArrayMax.max.ob4", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "55ecfb69494a22d6e58ad91840bcbb0897fdf19bb2ad70583faf832f8056b227", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "exists uint256 j :: j < xs.length && xs[j] == m" + } + }, + { + "answer": "unsat", + "asserts": 21, + "commands": 42, + "goal": "(> |xs.length@18| 0)", + "guard": "|g@20|", + "id": "ArrayMax.max#5", + "kind": "loop invariant not satisfied on entry", + "lean": "SolarVerifyVc.ArrayMax.max.ob5", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "4dfac29473863b79f8e4b029a64e650a5062964c2a069706eaa080479282ff0e", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "xs.length > 0" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 80, + "goal": "(<= 1 |arith@47|)", + "guard": "|g@48|", + "id": "ArrayMax.max#6", + "kind": "loop invariant not preserved by the loop body", + "lean": "SolarVerifyVc.ArrayMax.max.ob6", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "b515578b67f66dd4eaa1bc5a770b54e58b64ce5a77460f54f931a02729f6ab19", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "1 <= i" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 80, + "goal": "(<= |arith@47| |xs.length@18|)", + "guard": "|g@48|", + "id": "ArrayMax.max#7", + "kind": "loop invariant not preserved by the loop body", + "lean": "SolarVerifyVc.ArrayMax.max.ob7", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "bf57c3c10ee62b1215acc86c6d35917fafe7b6d43f4e08e00d0e103e9d2af6ca", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "i <= xs.length" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 80, + "goal": "(forall ((|j!49| Int)) (=> (and (and (<= 0 |j!49|) (<= |j!49| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (=> (< |j!49| |arith@47|) (<= (select |xs@17| |j!49|) |m@46|))))", + "guard": "|g@48|", + "id": "ArrayMax.max#8", + "kind": "loop invariant not preserved by the loop body", + "lean": "SolarVerifyVc.ArrayMax.max.ob8", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "f25bff351a6ea08f2bcc9d638abb5bf7189a4968ac5e2a62576f42f2639ffd05", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "forall uint256 j :: j < i ==> xs[j] <= m" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 80, + "goal": "(exists ((|j!50| Int)) (and (and (and (<= 0 |j!50|) (<= |j!50| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (and (< |j!50| |arith@47|) (= (select |xs@17| |j!50|) |m@46|))))", + "guard": "|g@48|", + "id": "ArrayMax.max#9", + "kind": "loop invariant not preserved by the loop body", + "lean": "SolarVerifyVc.ArrayMax.max.ob9", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "b0fa429989bc9d610ac25c80224ea993b198f49fa116f7ddefde114a96eb7a01", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "exists uint256 j :: j < i && xs[j] == m" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 80, + "goal": "(exists ((|j!51| Int)) (and (and (and (<= 0 |j!51|) (<= |j!51| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (and (< |j!51| |xs.length@18|) (= (select |xs@17| |j!51|) |m@46|))))", + "guard": "|g@48|", + "id": "ArrayMax.max#10", + "kind": "loop invariant not preserved by the loop body", + "lean": "SolarVerifyVc.ArrayMax.max.ob10", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "dba88be31a4526edfb6ef423e6b08ecef7db4ca61f4b6abfcfc62407e049d851", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "exists uint256 j :: j < xs.length && xs[j] == m" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 80, + "goal": "(> |xs.length@18| 0)", + "guard": "|g@48|", + "id": "ArrayMax.max#11", + "kind": "loop invariant not preserved by the loop body", + "lean": "SolarVerifyVc.ArrayMax.max.ob11", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "934a80355bad5cc493fce7387db616006574e4727549114faa462f45b85f57c4", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "xs.length > 0" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 80, + "goal": "(and (<= 0 (- |xs.length@18| |i@28|)) (< (- |xs.length@18| |arith@47|) (- |xs.length@18| |i@28|)))", + "guard": "|g@48|", + "id": "ArrayMax.max#12", + "kind": "loop does not terminate: decreases clause not decreased", + "lean": "SolarVerifyVc.ArrayMax.max.ob12", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10 + }, + "smt_sha256": "ab98ca88f80753c5ac3991a7b6b4189cc5fe5b02ee4d7203111d9ec183c0ded7", + "solver": "z3", + "spec": { + "column": 9, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 10, + "text": "(xs.length) - i" + } + }, + { + "answer": "sat", + "asserts": 42, + "commands": 82, + "goal": "false", + "guard": "|g@52|", + "id": "ArrayMax.max#13", + "lean": "SolarVerifyVc.ArrayMax.max.ob13", + "required": false, + "role": "advisory", + "script": 0, + "smt_sha256": "f92d705bb601763d2dfb970f85c5c278b5c349e4bbe00aa2d4fa9b125314817d", + "solver": "z3" + }, + { + "answer": "unsat", + "asserts": 42, + "commands": 82, + "goal": "(forall ((|j!53| Int)) (=> (and (and (<= 0 |j!53|) (<= |j!53| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (=> (< |j!53| |xs.length@18|) (<= (select |xs@17| |j!53|) |m@29|))))", + "guard": "|g@52|", + "id": "ArrayMax.max#14", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.ArrayMax.max.ob14", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 6 + }, + "smt_sha256": "9eb45f23e4334f8efc8813e249422b90ce287a408a64ac239401e574fc219fd8", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 6, + "text": "forall uint256 j :: j < xs.length ==> xs[j] <= m" + } + }, + { + "answer": "unsat", + "asserts": 42, + "commands": 82, + "goal": "(exists ((|j!54| Int)) (and (and (and (<= 0 |j!54|) (<= |j!54| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (and (< |j!54| |xs.length@18|) (= (select |xs@17| |j!54|) |m@29|))))", + "guard": "|g@52|", + "id": "ArrayMax.max#15", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.ArrayMax.max.ob15", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 7 + }, + "smt_sha256": "e0e3e9b245cc79d0a181a12470b923c5f05bfbe4af657301137ae1344b42b2d4", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 7, + "text": "exists uint256 j :: j < xs.length && xs[j] == m" + } + } + ], + "scripts": [ + { + "commands": 82, + "decls": [ + "|this@1|", + "|msg.sender@2|", + "|msg.value@3|", + "|block.timestamp@4|", + "|block.number@5|", + "|block.chainid@6|", + "|tx.origin@7|", + "|tx.gasprice@8|", + "|msg.sig@9|", + "|msg.data@10|", + "|block.basefee@11|", + "|block.blobbasefee@12|", + "|block.coinbase@13|", + "|block.prevrandao@14|", + "|block.difficulty@15|", + "|block.gaslimit@16|", + "|xs@17|", + "|xs.length@18|", + "|g@19|", + "|g@20|", + "|m@21|", + "|i@28|", + "|m@29|", + "|g@30|", + "|g@31|", + "|g@33|", + "|g@35|", + "|g@37|", + "|g@38|", + "|g@39|", + "|g@40|", + "|g@41|", + "|g@42|", + "|m@43|", + "|g@44|", + "|g@45|", + "|m@46|", + "|arith@47|", + "|g@48|", + "|g@52|" + ], + "lean": "SolarVerifyVc.ArrayMax.max.script0", + "smt": "ArrayMax/max.script0.smt2" + } + ], + "status": "verified" + }, + { + "module": "ArrayMax/clamp.lean", + "name": "ArrayMax.clamp", + "namespace": "SolarVerifyVc.ArrayMax.clamp", + "obligations": [ + { + "answer": "sat", + "asserts": 22, + "commands": 44, + "goal": "false", + "guard": "|g@21|", + "id": "ArrayMax.clamp#0", + "lean": "SolarVerifyVc.ArrayMax.clamp.ob0", + "required": false, + "role": "advisory", + "script": 0, + "smt_sha256": "c669e10e759850f1b0ed3843c8440755652c2b706652835d7415a7dfef329df3", + "solver": "z3" + }, + { + "answer": "unsat", + "asserts": 22, + "commands": 44, + "goal": "(<= |r@22| |n@18|)", + "guard": "|g@21|", + "id": "ArrayMax.clamp#1", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.ArrayMax.clamp.ob1", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 17 + }, + "smt_sha256": "ae925b0907b4ef1737b19d4fc649c22775148b4351b0413901526e9c10bd82a7", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 17, + "text": "r <= n" + } + } + ], + "scripts": [ + { + "commands": 44, + "decls": [ + "|this@1|", + "|msg.sender@2|", + "|msg.value@3|", + "|block.timestamp@4|", + "|block.number@5|", + "|block.chainid@6|", + "|tx.origin@7|", + "|tx.gasprice@8|", + "|msg.sig@9|", + "|msg.data@10|", + "|block.basefee@11|", + "|block.blobbasefee@12|", + "|block.coinbase@13|", + "|block.prevrandao@14|", + "|block.difficulty@15|", + "|block.gaslimit@16|", + "|x@17|", + "|n@18|", + "|g@19|", + "|g@20|", + "|g@21|", + "|r@22|" + ], + "lean": "SolarVerifyVc.ArrayMax.clamp.script0", + "smt": "ArrayMax/clamp.script0.smt2" + } + ], + "status": "verified" + }, + { + "module": "ArrayMaxEntry/max.lean", + "name": "ArrayMaxEntry.max", + "namespace": "SolarVerifyVc.ArrayMaxEntry.max", + "obligations": [ + { + "answer": "unsat", + "asserts": 20, + "commands": 42, + "goal": "(> |xs.length@20| 0)", + "guard": "|g@22|", + "id": "ArrayMaxEntry.max#0", + "kind": "precondition of `max` not satisfied", + "lean": "SolarVerifyVc.ArrayMaxEntry.max.ob0", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 16, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 30 + }, + "smt_sha256": "250434d86bc1b5c4e45f2e3538f7c1e5123fa49df127e0943ff25a45ebd9e13f", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 5, + "text": "xs.length > 0" + } + }, + { + "answer": "sat", + "asserts": 23, + "commands": 48, + "goal": "false", + "guard": "|g@27|", + "id": "ArrayMaxEntry.max#1", + "lean": "SolarVerifyVc.ArrayMaxEntry.max.ob1", + "required": false, + "role": "advisory", + "script": 0, + "smt_sha256": "6a103618ebb3edca8d5011cb95b77f711994fef7c719df636741f80fa7f2e54e", + "solver": "z3" + }, + { + "answer": "unsat", + "asserts": 23, + "commands": 48, + "goal": "(forall ((|j!28| Int)) (=> (and (and (<= 0 |j!28|) (<= |j!28| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (=> (< |j!28| |xs.length@20|) (<= (select |xs@19| |j!28|) |m@23|))))", + "guard": "|g@27|", + "id": "ArrayMaxEntry.max#2", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.ArrayMaxEntry.max.ob2", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 26 + }, + "smt_sha256": "d1712d8397bf64d098f81b53f58d74d79369f8df7c7e83f1df197cf66c13530b", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 26, + "text": "forall uint256 j :: j < xs.length ==> xs[j] <= result" + } + }, + { + "answer": "unsat", + "asserts": 23, + "commands": 48, + "goal": "(exists ((|j!29| Int)) (and (and (and (<= 0 |j!29|) (<= |j!29| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) (and (< |j!29| |xs.length@20|) (= (select |xs@19| |j!29|) |m@23|))))", + "guard": "|g@27|", + "id": "ArrayMaxEntry.max#3", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.ArrayMaxEntry.max.ob3", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 27 + }, + "smt_sha256": "48dc434e3f17562a86578ff2efe8db9146ebef7af86cb3190c125e5c4e88f5e4", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/ArrayMax.sol", + "line": 27, + "text": "exists uint256 j :: j < xs.length && xs[j] == result" + } + } + ], + "scripts": [ + { + "commands": 48, + "decls": [ + "|this@1|", + "|msg.sender@2|", + "|msg.value@3|", + "|block.timestamp@4|", + "|block.number@5|", + "|block.chainid@6|", + "|tx.origin@7|", + "|tx.gasprice@8|", + "|msg.sig@9|", + "|msg.data@10|", + "|block.basefee@11|", + "|block.blobbasefee@12|", + "|block.coinbase@13|", + "|block.prevrandao@14|", + "|block.difficulty@15|", + "|block.gaslimit@16|", + "|__balance@17|", + "|__code_epoch@18|", + "|xs@19|", + "|xs.length@20|", + "|g@21|", + "|g@22|", + "|m@23|", + "|g@25|", + "|g@27|" + ], + "lean": "SolarVerifyVc.ArrayMaxEntry.max.script0", + "smt": "ArrayMaxEntry/max.script0.smt2" + } + ], + "status": "verified" + }, + { + "module": "ArrayMaxEntry/constructor.lean", + "name": "ArrayMaxEntry.constructor", + "namespace": "SolarVerifyVc.ArrayMaxEntry.constructor", + "obligations": [ + { + "answer": "sat", + "asserts": 18, + "commands": 37, + "goal": "false", + "guard": "|g@19|", + "id": "ArrayMaxEntry.constructor#0", + "lean": "SolarVerifyVc.ArrayMaxEntry.constructor.ob0", + "required": false, + "role": "advisory", + "script": 0, + "smt_sha256": "47045d9c3bc9bc2bb3756918d7c08545edc1433497ba6f34db2b2e3a5ba0fa43", + "solver": "z3" + } + ], + "scripts": [ + { + "commands": 37, + "decls": [ + "|this@1|", + "|msg.sender@2|", + "|msg.value@3|", + "|block.timestamp@4|", + "|block.number@5|", + "|block.chainid@6|", + "|tx.origin@7|", + "|tx.gasprice@8|", + "|msg.sig@9|", + "|msg.data@10|", + "|block.basefee@11|", + "|block.blobbasefee@12|", + "|block.coinbase@13|", + "|block.prevrandao@14|", + "|block.difficulty@15|", + "|block.gaslimit@16|", + "|__balance@17|", + "|__code_epoch@18|", + "|g@19|" + ], + "lean": "SolarVerifyVc.ArrayMaxEntry.constructor.script0", + "smt": "ArrayMaxEntry/constructor.script0.smt2" + } + ], + "status": "verified" + } + ], + "version": 1 +} diff --git a/Contracts/ArrayMax/Wrong.lean b/Contracts/ArrayMax/Wrong.lean new file mode 100644 index 00000000..bdb8296a --- /dev/null +++ b/Contracts/ArrayMax/Wrong.lean @@ -0,0 +1,71 @@ +import Contracts.ArrayMax.Entry + +/-! +# ArrayMaxEntry.max: a wrong spec fails on a concrete call + +`demo` is `max([1, 7, 3])`, ABI-encoded. The kernel runs solar's first lowered MIR on it to the +return of 7 (`demo_halt`), which meets `Post` and refutes the mutant spec "returns the first +element" (`wrong_fails`), by a mismatch of the returned word. +-/ + +namespace SolarTV.Milestone.ArrayMaxEntry + +open Machine SolarTV.Export.ArrayMaxEntry + +/-- The 32 big-endian bytes of a number. -/ +def word32 (n : Nat) : List UInt8 := (List.range 32).map fun i => UInt8.ofNat (n / 256 ^ (31 - i) % 256) + +/-- `max([1, 7, 3])`, ABI-encoded, with no value. -/ +def demo : Call := + { calldata := ⟨([0x3b, 0xf6, 0xde, 0x96] ++ word32 32 ++ word32 3 ++ word32 1 ++ word32 7 ++ + word32 3).toArray⟩, + callvalue := 0, storage := [] } + +/-- An oracle; the run reads none of it. -/ +def demoOracle : Oracle := ⟨fun _ _ _ => 0, fun _ => 0, fun _ _ => 0, fun _ _ => 0, fun _ => 0, 0⟩ + +theorem demo_isMax : IsMax demo := by unfold IsMax; decide +kernel + +theorem demo_fits : CalldataFits demo := by unfold CalldataFits; decide +kernel + +theorem demo_len : len demo = 3 := by decide +kernel + +theorem demo_elem0 : elem demo 0 = 1 := by decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's run of stage0 on `demo`: it returns the word 7. -/ +theorem demo_halt : (MIR.Lowered.Module.run demoOracle stage0 demo 40).map Prod.fst = + some (.ret (Mem.wordBytes 7)) := by + rfl + +/-- The mutant spec: a successful end returns the array's first element. -/ +def PostFirst (call : Call) (r : Halt × State) : Prop := + (r.1 = .stop ∨ ∃ d, r.1 = .ret d) → r.1 = .ret (Mem.wordBytes (elem call 0)) + +theorem wordBytes_ne : Mem.wordBytes (7 : W) ≠ Mem.wordBytes (1 : W) := by decide +kernel + +set_option maxRecDepth 100000 in +/-- **The mutant spec does not hold of stage0**: `demo`'s end returns 7, not its first element. -/ +theorem wrong_fails : + ¬∀ r, MIR.Lowered.moduleLayer.Ends demoOracle stage0 demo r → PostFirst demo r := by + intro h + obtain ⟨r, hr, h1⟩ := Option.map_eq_some_iff.1 demo_halt + have := h r ⟨40, hr⟩ (Or.inr ⟨_, h1⟩) + rw [h1] at this + have e := Halt.ret.inj this + rw [demo_elem0] at e + exact wordBytes_ne e + +/-- The true spec holds of that end. -/ +theorem demo_post : ∀ r, MIR.Lowered.moduleLayer.Ends demoOracle stage0 demo r → Post demo r := + fun r e => stage0_post demoOracle demo demo_isMax demo_fits r e + +/-- info: 'SolarTV.Milestone.ArrayMaxEntry.wrong_fails' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms wrong_fails + +/-- info: 'SolarTV.Milestone.ArrayMaxEntry.demo_post' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms demo_post + +end SolarTV.Milestone.ArrayMaxEntry diff --git a/Contracts/C4/Spec/Axioms.lean b/Contracts/C4/Spec/Axioms.lean new file mode 100644 index 00000000..522b56ee --- /dev/null +++ b/Contracts/C4/Spec/Axioms.lean @@ -0,0 +1,22 @@ +import Contracts.C4.Spec.Bytecode +import Verify.Spec.GhostFree + +/-! The axioms of the spec semantics' theorems: `propext`, `Classical.choice` and `Quot.sound` at +most, and no `sorry`, `native_decide` (`Lean.ofReduceBool`) or `bv_decide`. -/ + +#print axioms SolidCore.Spec.Ghost.sound +#print axioms SolidCore.Spec.Ghost.complete +#print axioms SolidCore.Spec.Ghost.spec_of_erased +#print axioms SolidCore.Spec.Ghost.spec_of_erased_real +#print axioms SolidCore.Spec.Ghost.ghostTotal_of_straight +#print axioms SolidCore.Spec.eval_ghostEquiv +#print axioms SolidCore.Spec.Bundle.sat_ghostEquiv +#print axioms SolidCore.Spec.Holds.of_stage +#print axioms SolidCore.Spec.spec_of_verdict +#print axioms SolidCore.Spec.Export.C4.Main_wf +#print axioms SolidCore.Spec.Solar.C4.post_of_postAt +#print axioms SolidCore.Spec.Solar.C4.holds_source +#print axioms SolidCore.Spec.Solar.C4.holds_bytecode +#print axioms SolidCore.Spec.Solar.C4.holds_bytecode_at +#print axioms SolidCore.Spec.Solar.C4.certified +#print axioms SolidCore.Spec.Solar.C4.wrong_fails diff --git a/Contracts/C4/Spec/Bytecode.lean b/Contracts/C4/Spec/Bytecode.lean new file mode 100644 index 00000000..6d13dd17 --- /dev/null +++ b/Contracts/C4/Spec/Bytecode.lean @@ -0,0 +1,260 @@ +import Contracts.C4.Spec.Export +import Contracts.C4.Spec.ExportWrong +import Verify.Spec.TrustedBase +import Verify.C4 +import SolidCore.Refinement.Corpus.C4 +import SolidCore.Refinement.Spec + +/-! +# c4: solar-verify's spec, proved of SolidCore and of solar's bytecode + +c4 (`scripts/refinement/corpus/c4.sol`) with specs written for solar-verify +(`scripts/refinement/spec/c4.sol`): + + contract Main { + uint8 v; + uint8 w = 7; + /// @custom:ensures result == old(v) + x + /// @custom:ensures v == old(v) + x + /// @custom:ensures w == (old(w) ^ x) + /// @custom:succeeds-if v + x < 256 + function add(uint8 x) external returns (uint8) { v += x; w ^= x; return v; } } + +`solar-verify --emit-lean` writes those specs as `Export.C4.Main`, whose meaning is +`SolidCore.Spec.Holds`: every call of `add` with a clean `uint8` argument finishes; when it succeeds +it returns a clean `uint8` equal to the old `v` plus `x`, `v` (the low byte of slot 0) is the old `v` +plus `x`, and `w` (the next byte) is the old `w` xor `x`; and when the old `v` plus `x` is below 256 +it succeeds. + +All of it is proved in Lean, with no trusted base: solar-verify's verdict, the one trusted item +of `spec_of_verdict`, is not used, since SolidCore's run of `add` is known exactly +(`Verify.C4.postAt`, by symbolic evaluation of SolidCore's interpreter from any storage that +writes slot 0). `post_of_postAt` reads that run through the spec's meaning. + +* `holds_source`: the spec of SolidCore's checked `Main`, from any storage that writes slot 0. +* `holds_bytecode`: the spec of solar's runtime bytecode on EthLib, from the deployed storage, + through the corpus's refinement (`Corpus.C4.refines_full`, solar 9688f215). +* `holds_bytecode_at`: from any storage that writes slot 0, given the stage from SolidCore to + the bytecode that solar-tv's c4 milestone certifies (`Solar.C4.certified_at`, whose + milestone proofs are outside this module's imports). +* `certified`: `holds_bytecode` bound to the export's manifest. +* `wrong_fails`: the negative test. With `result == old(v) + x + 1` + (`scripts/refinement/spec/c4_wrong.sol`, which solar-verify also rejects) the spec does not hold + of the bytecode, by a real mismatch: `add(0)` from the deployed storage returns 0. +-/ + +namespace SolidCore.Spec.Solar.C4 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Spec + +/-- The call context of SolidCore's and EthLib's interface (`Refinement.Statement`): sender +`0x2000`, the contract at `0x1000`, block timestamp 1. -/ +def ctxOf (call : Call) : Ctx := + { sender := 0x2000, value := call.callvalue, timestamp := 1, self := 0x1000 } + +/-- c4 has no ghost state. -/ +def step : GhostStep := fun _ g => g + +theorem bytesWord_map (l : List UInt8) : + bytesWord (l.map (·.toNat)) = EthLib.Base.bytesToNat l := by + simp [bytesWord, EthLib.Base.bytesToNat, List.foldl_map] + +theorem bytesWord_word {v : Nat} (h : v < 2 ^ 256) : bytesWord (Verify.word v) = v := by + rw [Verify.word, bytesWord_map, EthLib.Base.bytesToNat_natToBytes_of_lt] + simpa using h + +theorem length_word (v : Nat) : (Verify.word v).length = 32 := by + simp [Verify.word, EthLib.Base.natToBytes_length] + +theorem words_word {v : Nat} (h : v < 2 ^ 256) : words (Verify.word v) = [v] := by + simp only [words, length_word, Nat.reduceDiv, List.range_one, List.map_cons, List.map_nil, + Nat.mul_zero, List.drop_zero] + rw [List.take_of_length_le (by rw [length_word]), bytesWord_word h] + +/-- The argument bytes of one word are the word's bytes. -/ +theorem argBytes_one (a : Nat) : Dirty.argBytes [a] = Verify.word a := by + simp [Dirty.argBytes, Verify.word] + +/-- A call of the scope is `add` on one word `a` from a storage `σ`. -/ +theorem scopeAt_call {call : Call} (h : Verify.C4.scopeAt call) : + ∃ σ a, a < 2 ^ 256 ∧ call = Call.mk (Abi.calldata Bytecode.C4.Main.addSelector [a]) 0 σ := by + obtain ⟨σ, _, fn, hfn, args, hlen, hargs, rfl⟩ := h + simp only [Corpus.C4.fns, List.mem_singleton] at hfn + subst hfn + rcases args with _ | ⟨a, _ | _⟩ <;> simp at hlen + exact ⟨σ, a, hargs a (by simp), rfl⟩ + +/-- The argument words after the selector of such a call. -/ +theorem words_args (a : Nat) (ha : a < 2 ^ 256) : + words (((Abi.calldata Bytecode.C4.Main.addSelector [a]).data.toList.map (·.toNat)).drop 4) = + [a] := by + rw [Dirty.bytes_calldata, Wide.drop_selector, argBytes_one, words_word ha] + +/-- **SolidCore's run of `add`, read through the spec.** A call of the scope from a pre-state +meeting `Pre` that finishes as `Verify.C4.postAt` says finishes meeting `Post`. -/ +theorem post_of_postAt {call : Call} (hs : Verify.C4.scopeAt call) {fs : FnSpec} + (hfs : fs ∈ Export.C4.Main.spec.specs) {args : List Int} {pre : State} + (hpre : Pre Export.C4.Main fs (ctxOf call) pre call args) {obs : Observable} + (hpost : Verify.C4.postAt call obs) : + Post Export.C4.Main fs (ctxOf call) pre (step call pre.ghost) obs args := by + simp only [Export.C4.Main, List.mem_singleton] at hfs + subst hfs + obtain ⟨σ, a, ha, rfl⟩ := scopeAt_call hs + obtain ⟨⟨_, _, hdec⟩, hst, -, -, -⟩ := hpre + rw [words_args a ha] at hdec + simp only [decodeWords, Ty.ofWord, Nat.reducePow] at hdec + by_cases hx : a < 256 + swap + · simp [hx] at hdec + have hargs : args = [(a : Int)] := by + simp [hx, bind, pure] at hdec + exact hdec.symm + subst hargs + replace hx : a < 2 ^ 8 := hx + have haw : Verify.argWords 1 (Call.mk (Abi.calldata Bytecode.C4.Main.addSelector [a]) 0 σ) = + [a] := + Verify.argWords_calldata _ [a] (by simpa using ha) 0 σ + simp only [Verify.C4.postAt, haw, List.getD_cons_zero, hx, ite_true] at hpost + obtain ⟨hpost, -⟩ := hpost + have hs0lt : slotValue σ 0 < 2 ^ 256 := SolidCore.Refinement.Evm.Wide.slotValue_lt σ 0 + have hpre0 : pre.storage 0 = slotValue σ 0 := by rw [hst] + generalize slotValue σ 0 = s0 at hpost hs0lt hpre0 + by_cases hfit : s0 % 2 ^ 8 + a < 2 ^ 8 + · simp only [hfit, ite_true] at hpost + obtain ⟨hsucc, hout, hstore⟩ := hpost + have h0 := hstore 0 + simp only [Nat.zero_mod, ite_true] at h0 + have hy : s0 / 2 ^ 8 % 2 ^ 8 ^^^ a < 2 ^ 8 := Nat.xor_lt_two_pow (by omega) hx + refine ⟨fun _ => ⟨[((s0 % 2 ^ 8 + a : Nat) : Int)], ?_, ?_, ?_⟩, fun _ _ => hsucc⟩ + · rw [hout, words_word (by omega)] + simp [decodeWords, Ty.ofWord, show s0 % 256 + a < 256 by omega] + · simp [Bundle.satAll, Bundle.sat, eval, slotOf, mkEnv, Env.cur, BinOp.apply, + Ty.ofBits, toWord, hpre0, h0] + have e1 : ((s0 : Int) / 256 % 256 % + 115792089237316195423570985008687907853269984665640564039457584007913129639936).toNat = + s0 / 2 ^ 8 % 2 ^ 8 := by omega + have e2 : ((a : Int) % + 115792089237316195423570985008687907853269984665640564039457584007913129639936).toNat = + a := by omega + simp only [e1, e2] + generalize s0 / 2 ^ 8 % 2 ^ 8 ^^^ a = y at hy ⊢ + constructor <;> omega + · simp [Bundle.satAll, Export.C4.Main] + · simp only [hfit, ite_false] at hpost + refine ⟨fun h => by simp [hpost.1] at h, fun _ hsi => ?_⟩ + simp [Bundle.satAll, Bundle.sat, eval, slotOf, mkEnv, Env.cur, BinOp.apply, + Ty.ofBits, toWord, hpre0] at hsi + omega + +/-! ## The spec of SolidCore and of the bytecode -/ + +/-- **The spec of SolidCore's checked `Main`**, on every call of `add` from any storage that writes +slot 0. -/ +theorem holds_source : ∃ c, Corpus.C4.contract? = .ok c ∧ + Holds (solidCore Corpus.C4.fuel) c Verify.C4.scopeAt Export.C4.Main ctxOf step := by + obtain ⟨c, hc, hsat⟩ := Verify.C4.satisfiesAt + refine ⟨c, hc, fun fs hfs call hs args pre hpre => ?_⟩ + obtain ⟨obs, hrun, hpost⟩ := hsat call hs trivial + exact ⟨obs, hrun, post_of_postAt hs hfs hpre hpost⟩ + +/-- SolidCore's run of `add` from any storage, carried to the bytecode on the deployed storage by +the corpus refinement. -/ +theorem satisfies_bytecode : + Satisfies ethLib Corpus.C4.code Verify.C4.scope Verify.C4.pre Verify.C4.postAt := by + obtain ⟨c, hc, hsat⟩ := Verify.C4.satisfiesAt + obtain ⟨c', s, hc', hs', href⟩ := Corpus.C4.refines_full + rw [hc] at hc' + cases hc' + have hs : s = Verify.C4.deployed := by + rw [(Verify.C4.shape_of hc).2.1] at hs' + exact (Option.some.inj hs').symm + subst hs + exact bytecode_of_refines (fun call h hp => hsat call (Verify.C4.scopeAt_of_scope h) hp) href + +/-- **The spec of solar's runtime bytecode on EthLib**, on every call of `add` (any argument word, +no value) from the deployed storage. -/ +theorem holds_bytecode : + Holds ethLib Corpus.C4.code Verify.C4.scope Export.C4.Main ctxOf step := by + intro fs hfs call hs args pre hpre + obtain ⟨obs, hrun, hpost⟩ := satisfies_bytecode call hs trivial + exact ⟨obs, hrun, post_of_postAt (Verify.C4.scopeAt_of_scope hs) hfs hpre hpost⟩ + +/-- **The spec of the bytecode from any storage that writes slot 0**, given the stage from +SolidCore to the bytecode on that scope, which solar-tv's c4 milestone certifies +(`SolidCore.Refinement.Solar.C4.certified_at`). -/ +theorem holds_bytecode_at {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : Corpus.C4.contract? = .ok c) + (stage : Stage (solidCore Corpus.C4.fuel) ethLib c Corpus.C4.code Verify.C4.scopeAt) : + Holds ethLib Corpus.C4.code Verify.C4.scopeAt Export.C4.Main ctxOf step := by + obtain ⟨c', hc', h⟩ := holds_source + rw [hc] at hc' + cases hc' + exact h.of_stage stage + +/-- **c4's solar-verify spec, certified on solar's bytecode**, bound to the export's manifest: +the annotated source's sha256, the compiler that built the bytecode, the bytecode's sha256 (that +of `Bytecode.C4.Main.runtimeNat`'s 107 bytes, which `scripts/refinement/spec/check.sh` checks +outside the kernel, as solar's certify.sh does), the spec's well-formedness, and the spec. -/ +theorem certified : + Export.C4.manifest.sourceSha256 = + "f6a3a1d0280a07e6f5697b57489f426936b41078de11390f18fe62a313a495c9" ∧ + Export.C4.manifest.compiler = "solar 0.3.0-dev+commit.9688f215" ∧ + Bytecode.C4.solarRev = "9688f21581717743806cb7bf3afae2ac3c156a08" ∧ + Export.C4.manifest.bytecodeSha256 = + "8a21bc207d9dd8be48d921a717eda3ecb7e5bfcb5397850bc3d64a29037fac47" ∧ + Export.C4.Main.WF = true ∧ + Holds ethLib Corpus.C4.code Verify.C4.scope Export.C4.Main ctxOf step := + ⟨rfl, rfl, rfl, rfl, Export.C4.Main_wf, holds_bytecode⟩ + +/-! ## The negative test -/ + +/-- The call `add(0)` from the deployed storage. -/ +def call0 : Call := Call.mk (Abi.calldata Bytecode.C4.Main.addSelector [0]) 0 Verify.C4.deployed + +theorem selectorOf_calldata (sel : Nat) (hsel : sel < 2 ^ 32) (args : List Nat) : + selectorOf (Call.mk (Abi.calldata sel args) 0 []) = sel := by + simp only [selectorOf, Dirty.bytes_calldata] + rw [List.take_append_of_le_length (by simp [EthLib.Base.natToBytes_length]), + List.take_of_length_le (by simp [EthLib.Base.natToBytes_length]), bytesWord_map, + EthLib.Base.bytesToNat_natToBytes_of_lt (by simpa using hsel)] + +/-- **The wrong spec fails, by a mismatch.** `result == old(v) + x + 1` does not hold of the +bytecode: `add(0)` from the deployed storage returns 0, and the spec asks for 1. -/ +theorem wrong_fails : + ¬ Holds ethLib Corpus.C4.code Verify.C4.scope Export.C4Wrong.Main ctxOf step := by + intro h + have hs : Verify.C4.scope call0 := + ⟨_, List.mem_singleton_self _, [0], rfl, by simp, rfl⟩ + let pre : State := ⟨slotValue call0.storage, Ghost.zero, 0⟩ + have hfs := List.mem_singleton_self (Export.C4Wrong.Main.spec.specs.head (by simp [Export.C4Wrong.Main])) + have hdec : decodeWords [.uint 8] + (words ((call0.calldata.data.toList.map (·.toNat)).drop 4)) = some [0] := by + rw [call0, words_args 0 (by decide)] + simp [decodeWords, Ty.ofWord, bind, pure] + have hpre : Pre Export.C4Wrong.Main (Export.C4Wrong.Main.spec.specs.head (by simp [Export.C4Wrong.Main])) + (ctxOf call0) pre call0 [0] := by + refine ⟨⟨?_, ?_, ?_⟩, rfl, by simp [pre, ctxOf], ?_, ?_⟩ + · simp [call0, Abi.calldata, EthLib.Base.natToBytes_length, ByteArray.size] + · show selectorOf call0 = Bytecode.C4.Main.addSelector + have := selectorOf_calldata Bytecode.C4.Main.addSelector (by decide) [0] + exact this + · simpa [Export.C4Wrong.Main] using hdec + · simp [Bundle.satAll, Export.C4Wrong.Main] + · simp [Bundle.satAll, Export.C4Wrong.Main] + obtain ⟨obs, hrun, hpost⟩ := h _ (by simpa [Export.C4Wrong.Main] using hfs) call0 hs [0] pre hpre + obtain ⟨obs', hrun', hpost'⟩ := satisfies_bytecode call0 hs trivial + rw [hrun] at hrun' + cases hrun' + have haw : Verify.argWords 1 call0 = [0] := + Verify.argWords_calldata _ [0] (by simp) 0 Verify.C4.deployed + simp only [Verify.C4.postAt, haw] at hpost' + simp [call0, Verify.C4.deployed, slotValue] at hpost' + obtain ⟨⟨hsucc, hout, -⟩, -⟩ := hpost' + obtain ⟨rets, hrets, hens, -⟩ := hpost.1 hsucc + rw [hout, words_word (by decide)] at hrets + simp [decodeWords, Ty.ofWord, bind, pure, Export.C4Wrong.Main, List.head] at hrets + subst hrets + have := hens _ (by simp [Export.C4Wrong.Main, List.head]; exact Or.inl rfl) + simp [Bundle.sat, Export.C4Wrong.Main, eval, slotOf, mkEnv, Env.cur, BinOp.apply, Ty.ofBits, + toWord, pre, call0, Verify.C4.deployed, slotValue] at this + +end SolidCore.Spec.Solar.C4 diff --git a/Contracts/C4/Spec/Export.lean b/Contracts/C4/Spec/Export.lean new file mode 100644 index 00000000..7392ec3d --- /dev/null +++ b/Contracts/C4/Spec/Export.lean @@ -0,0 +1,51 @@ +import Verify.Spec.Contract + +/-! +Specs of `scripts/refinement/spec/c4.sol`, exported by solar-verify 0.3.0 with `--emit-lean-spec`. +Generated: do not edit. +-/ + +namespace SolidCore.Spec.Export.C4 + +open SolidCore.Spec + +/-- What the specs were exported from and are about. -/ +def manifest : Manifest := + { source := "scripts/refinement/spec/c4.sol", + sourceSha256 := "f6a3a1d0280a07e6f5697b57489f426936b41078de11390f18fe62a313a495c9", + compiler := "solar 0.3.0-dev+commit.9688f215", + options := [], + bytecodeSha256 := "8a21bc207d9dd8be48d921a717eda3ecb7e5bfcb5397850bc3d64a29037fac47" } + +/-- The specs of `Main`. -/ +def Main : Bundle where + fuel := 0 + spec := + { name := "Main", + fns := [ + ], + invariants := [ + ], + ghosts := [], + specs := [ + { name := "Main.add", + selector := 0x02067e6a, + params := [(.uint 8)], + rets := [(.uint 8)], + payable := false, + requires := [], + ensures := [ + (.bin .eq (.ret 0) (.bin .add (.old (.load (.slot 0) (.lit 0) 1 (.uint 8))) (.arg 0))), + (.bin .eq (.load (.slot 0) (.lit 0) 1 (.uint 8)) (.bin .add (.old (.load (.slot 0) (.lit 0) 1 (.uint 8))) (.arg 0))), + (.bin .eq (.load (.slot 0) (.lit 1) 1 (.uint 8)) (.bin .bxor (.old (.load (.slot 0) (.lit 1) 1 (.uint 8))) (.arg 0)))], + succeedsIf := [ + (.bin .lt (.bin .add (.load (.slot 0) (.lit 0) 1 (.uint 8)) (.arg 0)) (.lit 256))] }] } + +/-- Every spec function call resolves and nests within the fuel. -/ +theorem Main_wf : Main.WF = true := by decide +kernel + +/-- Trusted-base items these specs' proofs rely on beyond the verdict +(`SolidCore.Spec.Assumptions`). -/ +def trusted : List String := [] + +end SolidCore.Spec.Export.C4 diff --git a/Contracts/C4/Spec/ExportWrong.lean b/Contracts/C4/Spec/ExportWrong.lean new file mode 100644 index 00000000..f9d6984e --- /dev/null +++ b/Contracts/C4/Spec/ExportWrong.lean @@ -0,0 +1,51 @@ +import Verify.Spec.Contract + +/-! +Specs of `scripts/refinement/spec/c4_wrong.sol`, exported by solar-verify 0.3.0 with `--emit-lean-spec`. +Generated: do not edit. +-/ + +namespace SolidCore.Spec.Export.C4Wrong + +open SolidCore.Spec + +/-- What the specs were exported from and are about. -/ +def manifest : Manifest := + { source := "scripts/refinement/spec/c4_wrong.sol", + sourceSha256 := "2420cff959eb9497ee90798a5be2ea0bad65e9b79b10890c64815f4e4113875f", + compiler := "solar 0.3.0-dev+commit.9688f215", + options := [], + bytecodeSha256 := "8a21bc207d9dd8be48d921a717eda3ecb7e5bfcb5397850bc3d64a29037fac47" } + +/-- The specs of `Main`. -/ +def Main : Bundle where + fuel := 0 + spec := + { name := "Main", + fns := [ + ], + invariants := [ + ], + ghosts := [], + specs := [ + { name := "Main.add", + selector := 0x02067e6a, + params := [(.uint 8)], + rets := [(.uint 8)], + payable := false, + requires := [], + ensures := [ + (.bin .eq (.ret 0) (.bin .add (.bin .add (.old (.load (.slot 0) (.lit 0) 1 (.uint 8))) (.arg 0)) (.lit 1))), + (.bin .eq (.load (.slot 0) (.lit 0) 1 (.uint 8)) (.bin .add (.old (.load (.slot 0) (.lit 0) 1 (.uint 8))) (.arg 0))), + (.bin .eq (.load (.slot 0) (.lit 1) 1 (.uint 8)) (.bin .bxor (.old (.load (.slot 0) (.lit 1) 1 (.uint 8))) (.arg 0)))], + succeedsIf := [ + (.bin .lt (.bin .add (.load (.slot 0) (.lit 0) 1 (.uint 8)) (.arg 0)) (.lit 256))] }] } + +/-- Every spec function call resolves and nests within the fuel. -/ +theorem Main_wf : Main.WF = true := by decide +kernel + +/-- Trusted-base items these specs' proofs rely on beyond the verdict +(`SolidCore.Spec.Assumptions`). -/ +def trusted : List String := [] + +end SolidCore.Spec.Export.C4Wrong diff --git a/Contracts/CallFamilies/Calls.sol b/Contracts/CallFamilies/Calls.sol new file mode 100644 index 00000000..953e8069 --- /dev/null +++ b/Contracts/CallFamilies/Calls.sol @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +// The external-call families of a constant-product pair, written fresh: a token balance read +// (high-level STATICCALL behind the extcodesize guard), a factory read of the same kind, a token +// transfer through a low-level CALL whose return data must be empty or true, and a callback +// (high-level CALL with no return value). + +interface IBalance { + function balanceOf(address owner) external view returns (uint256); +} + +interface IFeeTo { + function feeTo() external view returns (address); +} + +interface ICallback { + function onFlash(address sender, uint256 amount, bytes calldata data) external; +} + +contract Calls { + bytes4 private constant TRANSFER = bytes4(keccak256(bytes("transfer(address,uint256)"))); + + address public factory; + address public token; + uint256 public reserve; + uint256 public kLast; + + function pay(address to, uint256 amount) private { + (bool ok, bytes memory ret) = token.call(abi.encodeWithSelector(TRANSFER, to, amount)); + require(ok && (ret.length == 0 || abi.decode(ret, (bool))), "TRANSFER_FAILED"); + } + + function sync() external { + reserve = IBalance(token).balanceOf(address(this)); + } + + function skim(address to) external { + pay(to, IBalance(token).balanceOf(address(this)) - reserve); + } + + function feeOn() external returns (bool on) { + on = IFeeTo(factory).feeTo() != address(0); + if (on) kLast = 1; + } + + function flash(address to, uint256 amount, bytes calldata data) external { + pay(to, amount); + if (data.length > 0) ICallback(to).onFlash(msg.sender, amount, data); + } +} diff --git a/Contracts/CallFamilies/Core.lean b/Contracts/CallFamilies/Core.lean new file mode 100644 index 00000000..40e41602 --- /dev/null +++ b/Contracts/CallFamilies/Core.lean @@ -0,0 +1,208 @@ +-- Generated from Contracts/CallFamilies/Calls.sol's signatures (solc 0.8.35 --hashes). Do not edit. + +import Contracts.CallFamilies.Source +import SolidCore.Refinement.KernelRfl +import Verify.VC.KernelIdx + +/-! +# SolidCore's checked `Calls` + +The kernel's type check of `Calls` (`contract_ok`), with the checker's +selectors from a table each of whose entries the kernel checks against Keccak-256 once +(`selector_eq`). +-/ + +namespace SolidCore.Verify.VC.Calls + +open SolidCore.Solidity SolidCore.Solidity.Source + +/-- The interpreter fuel of SolidCore's runs. -/ +def fuel : Nat := 4096 + +/-- SolidCore's checked `Calls`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract SolidCore.Verify.VC.Source.Calls.importedSourceUnit "Calls" + +/-- The selector of `balanceOf(address)`. -/ +abbrev balanceOfSel : Nat := 1889567281 + +/-- The selector of `balanceOf(address)`, by Keccak-256 of its signature. -/ +def selBalanceOf : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "balanceOf(address)" + +kernel_rfl selBalanceOf_eq selBalanceOf balanceOfSel + +/-- The selector of `factory()`. -/ +abbrev factorySel : Nat := 3294232917 + +/-- The selector of `factory()`, by Keccak-256 of its signature. -/ +def selFactory : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "factory()" + +kernel_rfl selFactory_eq selFactory factorySel + +/-- The selector of `feeOn()`. -/ +abbrev feeOnSel : Nat := 1328766218 + +/-- The selector of `feeOn()`, by Keccak-256 of its signature. -/ +def selFeeOn : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "feeOn()" + +kernel_rfl selFeeOn_eq selFeeOn feeOnSel + +/-- The selector of `feeTo()`. -/ +abbrev feeToSel : Nat := 25067096 + +/-- The selector of `feeTo()`, by Keccak-256 of its signature. -/ +def selFeeTo : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "feeTo()" + +kernel_rfl selFeeTo_eq selFeeTo feeToSel + +/-- The selector of `flash(address,uint256,bytes)`. -/ +abbrev flashSel : Nat := 4148228904 + +/-- The selector of `flash(address,uint256,bytes)`, by Keccak-256 of its signature. -/ +def selFlash : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "flash(address,uint256,bytes)" + +kernel_rfl selFlash_eq selFlash flashSel + +/-- The selector of `kLast()`. -/ +abbrev kLastSel : Nat := 1952775229 + +/-- The selector of `kLast()`, by Keccak-256 of its signature. -/ +def selKLast : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "kLast()" + +kernel_rfl selKLast_eq selKLast kLastSel + +/-- The selector of `onFlash(address,uint256,bytes)`. -/ +abbrev onFlashSel : Nat := 1971785435 + +/-- The selector of `onFlash(address,uint256,bytes)`, by Keccak-256 of its signature. -/ +def selOnFlash : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "onFlash(address,uint256,bytes)" + +kernel_rfl selOnFlash_eq selOnFlash onFlashSel + +/-- The selector of `reserve()`. -/ +abbrev reserveSel : Nat := 3442643934 + +/-- The selector of `reserve()`, by Keccak-256 of its signature. -/ +def selReserve : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "reserve()" + +kernel_rfl selReserve_eq selReserve reserveSel + +/-- The selector of `skim(address)`. -/ +abbrev skimSel : Nat := 3156594551 + +/-- The selector of `skim(address)`, by Keccak-256 of its signature. -/ +def selSkim : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "skim(address)" + +kernel_rfl selSkim_eq selSkim skimSel + +/-- The selector of `sync()`. -/ +abbrev syncSel : Nat := 4294363881 + +/-- The selector of `sync()`, by Keccak-256 of its signature. -/ +def selSync : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "sync()" + +kernel_rfl selSync_eq selSync syncSel + +/-- The selector of `token()`. -/ +abbrev tokenSel : Nat := 4228666474 + +/-- The selector of `token()`, by Keccak-256 of its signature. -/ +def selToken : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "token()" + +kernel_rfl selToken_eq selToken tokenSel + +/-- `ABI.selectorFromSignature`, with `Calls`'s selectors by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "balanceOf(address)" then balanceOfSel + else if s = "factory()" then factorySel + else if s = "feeOn()" then feeOnSel + else if s = "feeTo()" then feeToSel + else if s = "flash(address,uint256,bytes)" then flashSel + else if s = "kLast()" then kLastSel + else if s = "onFlash(address,uint256,bytes)" then onFlashSel + else if s = "reserve()" then reserveSel + else if s = "skim(address)" then skimSel + else if s = "sync()" then syncSel + else if s = "token()" then tokenSel + else SolidCore.Solidity.Source.ABI.selectorFromSignature s + +theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + by_cases h0 : s = "balanceOf(address)" + · rw [ite_eq_left h0, h0] + exact selBalanceOf_eq + rw [ite_eq_right h0] + by_cases h1 : s = "factory()" + · rw [ite_eq_left h1, h1] + exact selFactory_eq + rw [ite_eq_right h1] + by_cases h2 : s = "feeOn()" + · rw [ite_eq_left h2, h2] + exact selFeeOn_eq + rw [ite_eq_right h2] + by_cases h3 : s = "feeTo()" + · rw [ite_eq_left h3, h3] + exact selFeeTo_eq + rw [ite_eq_right h3] + by_cases h4 : s = "flash(address,uint256,bytes)" + · rw [ite_eq_left h4, h4] + exact selFlash_eq + rw [ite_eq_right h4] + by_cases h5 : s = "kLast()" + · rw [ite_eq_left h5, h5] + exact selKLast_eq + rw [ite_eq_right h5] + by_cases h6 : s = "onFlash(address,uint256,bytes)" + · rw [ite_eq_left h6, h6] + exact selOnFlash_eq + rw [ite_eq_right h6] + by_cases h7 : s = "reserve()" + · rw [ite_eq_left h7, h7] + exact selReserve_eq + rw [ite_eq_right h7] + by_cases h8 : s = "skim(address)" + · rw [ite_eq_left h8, h8] + exact selSkim_eq + rw [ite_eq_right h8] + by_cases h9 : s = "sync()" + · rw [ite_eq_left h9, h9] + exact selSync_eq + rw [ite_eq_right h9] + by_cases h10 : s = "token()" + · rw [ite_eq_left h10, h10] + exact selToken_eq + rw [ite_eq_right h10] + +/-- Whether SolidCore type checks the contract. -/ +def accepted : Bool := + match contract? with + | .ok _ => true + | .error _ => false + +kernel_rfl accepted_eq accepted true using selector_eq SolidCore.Verify.VC.mkIdx_eq + +/-- SolidCore type checks `Calls`. -/ +theorem contract_ok : ∃ c, contract? = .ok c := by + have h := accepted_eq + unfold accepted at h + split at h + · next c hc => exact ⟨c, hc⟩ + · simp at h + +/-- info: 'SolidCore.Verify.VC.Calls.contract_ok' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms contract_ok + +end SolidCore.Verify.VC.Calls diff --git a/Contracts/CallFamilies/FeeOnAgree.lean b/Contracts/CallFamilies/FeeOnAgree.lean new file mode 100644 index 00000000..bdf380c2 --- /dev/null +++ b/Contracts/CallFamilies/FeeOnAgree.lean @@ -0,0 +1,173 @@ +import Contracts.CallFamilies.FeeOnMir +import Contracts.CallFamilies.SyncAgree + +/-! +# `feeOn` in solar's MIR under the oracle hypothesis + +`mir_feeOn_agree`: under `CallsAgree o V`, when SolidCore's `feeOn()` asks `V` the call `FeeOnAsk` +describes (a `STATICCALL` of the factory in slot 0 with `feeTo()`'s selector) and `V` answers `a`, +solar's stage0 shows `obsOf σ a`: the callee's revert data, an empty revert for short return data +or a dirty address, else `true` with slot 3 set to 1 for a nonzero `feeTo`, or `false`. +-/ + +namespace SolidCore.Refinement.CallFamilies.FeeOn + +open SolarTV SolarTV.Machine SolarTV.MIR.Lowered SolidCore.Refinement +open SolidCore.Refinement.CallFamilies.Sync (retWord bytes_write bytes_expand lt_word callFlag_cases) +open EvmCompiler.Simulation +open SolidCore.Solidity.Source (addressToWord u256ToWord byteArrayToBytes) + +set_option linter.deprecated false + +/-- The 32 bytes of a returned word. -/ +def wordBytes (x : BitVec 256) : List Nat := (List.range 32).map fun i => (Memory.byte x i).toNat + +/-- What `feeOn()` shows when the factory answers `a`. -/ +def obsOf (σ : List (Nat × Nat)) (a : CallResponse) : Observable := + if a.success then + if a.returnData.size < 32 then ⟨false, [], [], slotValue σ⟩ + else if 2 ^ 160 ≤ (retWord a).toNat then ⟨false, [], [], slotValue σ⟩ + else if retWord a = 0 then + ⟨true, wordBytes 0, [], fun slot => ((State.initial (feeOnCall σ)).storage (BitVec.ofNat 256 slot)).toNat⟩ + else ⟨true, wordBytes 1, [], fun slot => + (update (State.initial (feeOnCall σ)).storage 3 1 (BitVec.ofNat 256 slot)).toNat⟩ + else ⟨false, (List.range a.returnData.size).map (fun j => (a.returnData.get! j).toNat), [], + slotValue σ⟩ + +/-- The call SolidCore's `feeOn()` asks `V`, with its answer. -/ +structure FeeOnAsk (σ : List (Nat × Nat)) (V : World) (world : SolidCore.Solidity.Shared.OpenWorld) + (request : CallRequest) (a : CallResponse) : Prop where + ans : V.ans [] (.external world (.call request)) = some a + kind : request.kind = .staticcall + callee : addressToWord request.codeAddress = slotValue σ 0 % 2 ^ 160 + value : u256ToWord request.transferValue = 0 + input : byteArrayToBytes request.calldata = input.map BitVec.toNat + storage : ∀ slot < 2 ^ 256, storageIn world slot = slotValue σ slot % 2 ^ 256 + transient : ∀ slot < 2 ^ 256, transientIn world slot = 0 + codes : ∀ x < 2 ^ 160, (codeIn world x).isEmpty = + (SolidCore.Solidity.Shared.Account.codeAt (V.codes.getD []) x).isEmpty + size : a.returnData.size < 2 ^ 256 + +theorem answer (o : Oracle) (V : World) (σ : List (Nat × Nat)) + (world : SolidCore.Solidity.Shared.OpenWorld) (request : CallRequest) (a : CallResponse) + (agree : CallsAgree o V) (hs : FeeOnAsk σ V world request a) : + ((callFlag o (W o σ) = 1) ↔ a.success = true) ∧ + (returndataSize o (W o σ)).toNat = a.returnData.size ∧ + ∀ j < a.returnData.size, (returndataByte o (W o σ) j).toNat = (a.returnData.get! j).toNat := by + have hcalls : machineCalls (W o σ) = + sourceCalls ([] ++ [⟨.external world (.call request), a⟩]) := by + simp only [W, machineCalls, sourceCalls, List.nil_append, hs.kind, hs.callee, hs.value, hs.input, + machineKind, List.getD] + simp + have hstore : ∀ slot < 2 ^ 256, + ((State.initial (feeOnCall σ)).storage (BitVec.ofNat 256 slot)).toNat = storageIn world slot ∧ + ((fun _ => (0 : BitVec 256)) (BitVec.ofNat 256 slot)).toNat = transientIn world slot := by + intro slot hslot + refine ⟨?_, ?_⟩ + · rw [hs.storage slot hslot] + simp only [State.initial, BitVec.toNat_ofNat] + rw [Nat.mod_eq_of_lt hslot] + rfl + · rw [hs.transient slot hslot]; rfl + have hcodes : CodesAgree o (W o σ).dropLast (codeIn world) := by + intro x hx + rw [hs.codes x hx] + exact agree.codes [.read "gas"] rfl x hx + obtain ⟨hflag, -, hrest⟩ := agree.calls [] world request a hs.ans (W o σ) .staticcall _ _ _ _ + rfl hcalls hstore hcodes + obtain ⟨hsz, hby, -⟩ := hrest [] rfl + simp only [List.append_nil] at hsz hby + refine ⟨hflag, ?_, fun j hj => hby j hj (Nat.lt_trans hj hs.size)⟩ + rw [hsz, Nat.mod_eq_of_lt hs.size] + +theorem gt_mask (v : BitVec 256) : EvmRules.Evm.gt v mask = if 2 ^ 160 ≤ v.toNat then 1 else 0 := by + change (bif mask.ult v then (1 : BitVec 256) else 0) = _ + rw [cond_eq_if] + have hm : mask.toNat = 2 ^ 160 - 1 := rfl + have hiff : (mask.ult v = true) ↔ 2 ^ 160 ≤ v.toNat := by + simp only [BitVec.ult, decide_eq_true_eq]; omega + by_cases h : 2 ^ 160 ≤ v.toNat + · rw [if_pos (hiff.mpr h), if_pos h] + · rw [if_neg (fun h' => h (hiff.mp h')), if_neg h] + +theorem ne_zero (v : BitVec 256) : EvmRules.Evm.ne v 0 = if v = 0 then 0 else 1 := by + unfold EvmRules.Evm.ne + by_cases h : v = 0 <;> simp [h] + +theorem read_store (m : Mem) (x : BitVec 256) : + ((m.store 0 x).expand 0 32).read 0 32 = (List.range 32).map fun i => Memory.byte x i := by + unfold Mem.read + apply List.map_congr_left + intro i hi + rw [List.mem_range] at hi + rw [bytes_expand] + unfold Mem.store + rw [bytes_expand] + simp [hi] + +/-- **feeOn's MIR under the oracle hypothesis.** -/ +theorem mir_feeOn_agree (o : Oracle) (V : World) (σ : List (Nat × Nat)) + (world : SolidCore.Solidity.Shared.OpenWorld) (request : CallRequest) (a : CallResponse) + (agree : CallsAgree o V) (hs : FeeOnAsk σ V world request a) : + (moduleSem o).run SolarTV.Export.Calls.stage0 (feeOnCall σ) = some (obsOf σ a) := by + obtain ⟨hflag, hsize, hbytes⟩ := answer o V σ world request a agree hs + rw [sem_feeOn] + congr 1 + unfold feeOnEnd obsOf + by_cases hsucc : a.success = true + · have hf : callFlag o (W o σ) ≠ 0 := by + intro h; have := hflag.mpr hsucc; rw [h] at this; exact absurd this (by decide) + rw [if_neg hf, if_pos hsucc, lt_word, hsize] + by_cases hlt : a.returnData.size < 32 + · have : ((if a.returnData.size < (32 : BitVec 256).toNat then (1 : BitVec 256) else 0) ≠ 0) := by + simp [hlt] + rw [if_pos this, if_pos hlt] + rfl + · have : ¬ ((if a.returnData.size < (32 : BitVec 256).toNat then (1 : BitVec 256) else 0) ≠ 0) := by + simp [hlt] + rw [if_neg this, if_neg hlt] + have hload : ret o σ = retWord a := by + unfold ret Mem.load Mem.read retWord + congr 1 + apply List.map_congr_left + intro i hi + rw [List.mem_range] at hi + have hmin : min 32 (returndataSize o (W o σ)).toNat = 32 := by rw [hsize]; omega + rw [M4, bytes_write, hmin] + simp only [Nat.zero_le, Nat.zero_add, hi, and_self, if_true, Nat.sub_zero] + apply BitVec.eq_of_toNat_eq + rw [hbytes i (by omega), BitVec.toNat_ofNat, Nat.mod_eq_of_lt (UInt8.toNat_lt _)] + rw [hload, gt_mask, ne_zero] + by_cases hd : 2 ^ 160 ≤ (retWord a).toNat + · rw [if_pos hd, if_pos (by decide), if_pos hd] + rfl + · rw [if_neg hd, if_neg (by decide), if_neg hd] + by_cases hz : retWord a = 0 + · rw [if_pos hz, if_pos rfl, if_pos hz] + simp only [halt, observe] + rfl + · rw [if_neg hz, if_neg (by decide), if_neg hz] + simp only [halt, observe] + rfl + · have hf : callFlag o (W o σ) = 0 := by + rcases callFlag_cases o (W o σ) with h | h + · exact h + · exact absurd (hflag.mp h) hsucc + rw [if_pos hf, if_neg hsucc] + simp only [halt, if_true, observe] + congr 1 + rw [hsize] + unfold Mem.read + rw [List.map_map] + apply List.map_congr_left + intro i hi + rw [List.mem_range] at hi + simp only [Function.comp, bytes_expand, bytes_write, Nat.zero_le, Nat.zero_add] + simp [hi] + exact hbytes i hi + +/-- info: 'SolidCore.Refinement.CallFamilies.FeeOn.mir_feeOn_agree' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms mir_feeOn_agree + +end SolidCore.Refinement.CallFamilies.FeeOn diff --git a/Contracts/CallFamilies/FeeOnMir.lean b/Contracts/CallFamilies/FeeOnMir.lean new file mode 100644 index 00000000..1dd6f60c --- /dev/null +++ b/Contracts/CallFamilies/FeeOnMir.lean @@ -0,0 +1,209 @@ +import Contracts.CallFamilies.SyncMir + +/-! +# `feeOn` in solar's first lowered MIR, for every oracle + +`sem_feeOn`: solar's stage0 runs `feeOn()` from the storage `σ` to `feeOnEnd o σ` under every +oracle `o`: it reads the factory (slot 0), makes one `STATICCALL` of `feeTo()` (world +`W o σ`), reverts with the callee's return data when the call fails, reverts with empty data when +it returned fewer than 32 bytes or a word above `2 ^ 160 - 1` (the address decoder's check), and +otherwise returns whether the word is not zero, after storing 1 in slot 3 when it is not. +-/ + +open SolidCore.Refinement.Kernel SolidCore.Refinement.CallFamilies.Sync +open SolarTV SolarTV.Machine SolarTV.MIR.Lowered + +namespace SolidCore.Refinement.CallFamilies.FeeOn + +set_option linter.deprecated false + +def feeOnCall (σ : List (Nat × Nat)) : Call := + { calldata := ⟨#[0x4f, 0x33, 0x5d, 0x0a]⟩, callvalue := 0, storage := σ } + +abbrev step (o : Oracle) (σ : List (Nat × Nat)) := moduleBlock o (feeOnCall σ) SolarTV.Export.Calls.stage0 + +def F0 (σ : List (Nat × Nat)) : Frame := ([], .enter 10 0 0, fun _ => 0, State.initial (feeOnCall σ)) +def F1 (o : Oracle) (σ : List (Nat × Nat)) : Frame := next (step o σ) (F0 σ) +def F2 (o : Oracle) (σ : List (Nat × Nat)) : Frame := next (step o σ) (F1 o σ) +def F3 (o : Oracle) (σ : List (Nat × Nat)) : Frame := next (step o σ) (F2 o σ) +def F4 (o : Oracle) (σ : List (Nat × Nat)) : Frame := next (step o σ) (F3 o σ) + +kernel_thm h0 : ∀ (o : Oracle) (σ : List (Nat × Nat)), step o σ (F0 σ) = some (.inr (F1 o σ)) +kernel_thm h1 : ∀ (o : Oracle) (σ : List (Nat × Nat)), step o σ (F1 o σ) = some (.inr (F2 o σ)) +kernel_thm h2 : ∀ (o : Oracle) (σ : List (Nat × Nat)), step o σ (F2 o σ) = some (.inr (F3 o σ)) +kernel_thm h3 : ∀ (o : Oracle) (σ : List (Nat × Nat)), step o σ (F3 o σ) = some (.inr (F4 o σ)) + +/-- Memory at the call: the free memory pointer and `feeTo()`'s selector. -/ +def mem1 : Mem := (Mem.initial.store 64 128).store 0 0x17e7e58 + +/-- The call's input: the selector's four bytes. -/ +def input : List Memory.Byte := ((mem1.expand 28 4).expand 0 32).read 28 4 + +/-- The world of the call. -/ +def W (o : Oracle) (σ : List (Nat × Nat)) : List Event := + [.read "gas", .call .staticcall [o.env "gas" [.read "gas"] [], BitVec.ofNat 256 (slotValue σ 0)] input + (State.initial (feeOnCall σ)).storage (fun _ => 0)] + +def M4 (o : Oracle) (σ : List (Nat × Nat)) : Mem := + ((mem1.expand 28 4).expand 0 32).write 0 (min 32 (returndataSize o (W o σ)).toNat) + (returndataByte o (W o σ)) + +def S4 (o : Oracle) (σ : List (Nat × Nat)) : State := + ⟨M4 o σ, (State.initial (feeOnCall σ)).storage, fun _ => 0, W o σ⟩ + +kernel_thm F4_eq : ∀ (o : Oracle) (σ : List (Nat × Nat)), F4 o σ = + ([], .enter 6 0 (if callFlag o (W o σ) = 0 then 1 else 2), (F4 o σ).2.2.1, S4 o σ) + +def G2 (o : Oracle) (σ : List (Nat × Nat)) (env : Env) : Frame := ([], .enter 6 0 2, env, S4 o σ) +def G2n (o : Oracle) (σ : List (Nat × Nat)) (env : Env) : Frame := next (step o σ) (G2 o σ env) + +kernel_thm g2 : ∀ (o : Oracle) (σ : List (Nat × Nat)) (env : Env), + step o σ (G2 o σ env) = some (.inr (G2n o σ env)) +kernel_thm G2n_eq : ∀ (o : Oracle) (σ : List (Nat × Nat)) (env : Env), G2n o σ env = + ([], .enter 6 2 (if EvmRules.Evm.lt (returndataSize o (W o σ)) 32 = 0 then 6 else 5), + (G2n o σ env).2.2.1, S4 o σ) + +kernel_thm g5 : ∀ (o : Oracle) (σ : List (Nat × Nat)) (p : Nat) (env : Env) (s : State), + step o σ ([], .enter 6 p 5, env, s) = some (.inl (halt s 0 0 true)) + +/-- The word the call returned, as `MLOAD` reads it. -/ +def ret (o : Oracle) (σ : List (Nat × Nat)) : BitVec 256 := (M4 o σ).load 0 + +def S6 (o : Oracle) (σ : List (Nat × Nat)) : State := { S4 o σ with memory := (M4 o σ).expand 0 32 } + +def G6 (o : Oracle) (σ : List (Nat × Nat)) (env : Env) : Frame := ([], .enter 6 2 6, env, S4 o σ) +def G6n (o : Oracle) (σ : List (Nat × Nat)) (env : Env) : Frame := next (step o σ) (G6 o σ env) + +kernel_thm g6 : ∀ (o : Oracle) (σ : List (Nat × Nat)) (env : Env), + step o σ (G6 o σ env) = some (.inr (G6n o σ env)) +kernel_thm G6n_eq : ∀ (o : Oracle) (σ : List (Nat × Nat)) (env : Env), G6n o σ env = + ([], .enter 6 6 (if EvmRules.Evm.gt (ret o σ) 0xffffffffffffffffffffffffffffffffffffffff = 0 then 7 else 5), + (G6n o σ env).2.2.1, S6 o σ) +kernel_thm G6n_env : ∀ (o : Oracle) (σ : List (Nat × Nat)) (env : Env), (G6n o σ env).2.2.1 16 = ret o σ + +def syncFn6 : Function := (SolarTV.Export.Calls.stage0.functions[6]?).getD ⟨[], [], none⟩ +kernel_thm fn6 : SolarTV.Export.Calls.stage0.functions[6]? = some syncFn6 +kernel_thm b1 : syncFn6.blocks[1]? = some ⟨[], + [.effect (some 26) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 26], + .effect (some 27) .returndatasize []], + .revert (.const 0) (.value 27)⟩ +kernel_thm b7 : syncFn6.blocks[7]? = some ⟨[], + [.pure 34 .and [.value 16, .const 0xffffffffffffffffffffffffffffffffffffffff], + .ne 21 (.value 16) (.const 0), + .assume false .eq [.value 34, .value 16]], + .branch (.value 21) 3 4⟩ +kernel_thm b3 : syncFn6.blocks[3]? = some ⟨[], [.effect none .sstore [.const 3, .const 1]], .jump 4⟩ +kernel_thm b4 : syncFn6.blocks[4]? = some ⟨[], + [.word 31 (.value 21), .effect none .mstore [.const 0, .value 31]], .ret (.const 0) (.const 32)⟩ + +theorem exec_b1 (o : Oracle) (call : Call) (env : Env) (s : State) : + execInsts o call [.effect (some 26) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 26], + .effect (some 27) .returndatasize []] env s = + some ((env.set 26 (returndataSize o s.world)).set 27 (returndataSize o s.world), + { s with memory := s.memory.write 0 (returndataSize o s.world).toNat (fun i => returndataByte o s.world (0 + i)) }) := by + simp only [execInsts, Effect.apply, List.map_cons, List.map_nil, Operand.eval] + have h : (env.set 26 (returndataSize o s.world)) 26 = returndataSize o s.world := by + simp [Env.set] + simp only [h, returndataSize] + simp + +theorem g1 (o : Oracle) (σ : List (Nat × Nat)) (env : Env) : + step o σ ([], .enter 6 0 1, env, S4 o σ) = some (.inl (halt + { S4 o σ with memory := (M4 o σ).write 0 (returndataSize o (W o σ)).toNat (fun i => returndataByte o (W o σ) (0 + i)) } 0 (returndataSize o (W o σ)) true)) := by + simp only [step, moduleBlock, fn6, b1, bindPhis, segment, splitCall, exec_b1] + simp [Operand.eval, Env.set, S4] + +/-- The address mask. -/ +abbrev mask : BitVec 256 := 0xffffffffffffffffffffffffffffffffffffffff + +theorem step_and (c) (a b : BitVec 256) : EVM.step c .and [a, b] = some [a &&& b] := rfl +theorem step_eq (c) (a b : BitVec 256) : + EVM.step c .eq [a, b] = some [if a = b then 1 else 0] := by + show some [EvmRules.Evm.eq a b] = _ + unfold EvmRules.Evm.eq + by_cases h : a = b <;> simp [h] + +theorem g7 (o : Oracle) (σ : List (Nat × Nat)) (env : Env) (hv : env 16 &&& mask = env 16) : + step o σ ([], .enter 6 6 7, env, S6 o σ) = some (.inr ([], .enter 6 7 + (if EvmRules.Evm.ne (env 16) 0 = 0 then 4 else 3), + ((env.set 34 (env 16 &&& mask)).set 21 (EvmRules.Evm.ne (env 16) 0)), S6 o σ)) := by + simp only [step, moduleBlock, fn6, b7, bindPhis, segment, splitCall, execInsts, List.map_cons, + List.map_nil, Operand.eval, evalPure] + simp only [step_and, step_eq, hv] + simp [Env.set] + +kernel_thm g3 : ∀ (o : Oracle) (σ : List (Nat × Nat)) (env : Env), + step o σ ([], .enter 6 7 3, env, S6 o σ) = + some (.inr ([], .enter 6 3 4, env, { S6 o σ with storage := update (S6 o σ).storage 3 1 })) + +kernel_thm g4 : ∀ (o : Oracle) (σ : List (Nat × Nat)) (p : Nat) (env : Env) (s : State), + step o σ ([], .enter 6 p 4, env, s) = + some (.inl (halt { s with memory := s.memory.store 0 (env 21) } 0 32 false)) + +theorem and_mask_of_gt (v : BitVec 256) (h : EvmRules.Evm.gt v mask = 0) : v &&& mask = v := by + have hle : v.toNat < 2 ^ 160 := by + change (bif mask.ult v then (1 : BitVec 256) else 0) = 0 at h + cases hu : mask.ult v with + | true => rw [hu] at h; exact absurd h (by decide) + | false => + simp only [BitVec.ult, decide_eq_false_iff_not, Nat.not_lt] at hu + have : mask.toNat = 2 ^ 160 - 1 := rfl + omega + apply BitVec.eq_of_toNat_eq + rw [BitVec.toNat_and, show mask.toNat = 2 ^ 160 - 1 from rfl, Nat.and_two_pow_sub_one_eq_mod, + Nat.mod_eq_of_lt hle] + +/-- The end of solar's stage0 on a call of `feeOn()`. -/ +def feeOnEnd (o : Oracle) (σ : List (Nat × Nat)) : Halt × State := + if callFlag o (W o σ) = 0 then + halt { S4 o σ with memory := (M4 o σ).write 0 (returndataSize o (W o σ)).toNat (fun i => returndataByte o (W o σ) (0 + i)) } 0 (returndataSize o (W o σ)) true + else if EvmRules.Evm.lt (returndataSize o (W o σ)) 32 ≠ 0 then halt (S4 o σ) 0 0 true + else if EvmRules.Evm.gt (ret o σ) mask ≠ 0 then halt (S6 o σ) 0 0 true + else if EvmRules.Evm.ne (ret o σ) 0 = 0 then + halt { S6 o σ with memory := (S6 o σ).memory.store 0 (EvmRules.Evm.ne (ret o σ) 0) } 0 32 false + else + halt { S6 o σ with storage := update (S6 o σ).storage 3 1, memory := (S6 o σ).memory.store 0 (EvmRules.Evm.ne (ret o σ) 0) } 0 32 false + +theorem run_feeOn (o : Oracle) (σ : List (Nat × Nat)) : + Module.run o SolarTV.Export.Calls.stage0 (feeOnCall σ) 10 = some (feeOnEnd o σ) := by + show iterate (step o σ) 10 (F0 σ) = _ + rw [iter_next (h0 o σ), iter_next (h1 o σ), iter_next (h2 o σ), iter_next (h3 o σ), F4_eq] + unfold feeOnEnd + by_cases hf : callFlag o (W o σ) = 0 + · rw [if_pos hf, if_pos hf, iter_end (g1 o σ _)] + rw [if_neg hf, if_neg hf] + rw [show (([], .enter 6 0 2, (F4 o σ).2.2.1, S4 o σ) : Frame) = G2 o σ (F4 o σ).2.2.1 from rfl, + iter_next (g2 o σ _), G2n_eq] + by_cases hl : EvmRules.Evm.lt (returndataSize o (W o σ)) 32 = 0 + · rw [if_pos hl, if_neg (fun h => h hl)] + generalize (G2n o σ (F4 o σ).2.2.1).2.2.1 = e2 + rw [show (([], .enter 6 2 6, e2, S4 o σ) : Frame) = G6 o σ e2 from rfl, iter_next (g6 o σ _), G6n_eq] + have henv := G6n_env o σ e2 + generalize (G6n o σ e2).2.2.1 = e6 at henv ⊢ + by_cases hg : EvmRules.Evm.gt (ret o σ) mask = 0 + · rw [if_pos hg, if_neg (fun h => h hg)] + have hv : e6 16 &&& mask = e6 16 := by rw [henv]; exact and_mask_of_gt _ hg + rw [iter_next (g7 o σ e6 hv), henv] + by_cases hn : EvmRules.Evm.ne (ret o σ) 0 = 0 + · rw [if_pos hn, if_pos hn, iter_end (g4 o σ _ _ _)] + simp [Env.set] + · rw [if_neg hn, if_neg hn, iter_next (g3 o σ _), iter_end (g4 o σ _ _ _)] + simp [Env.set] + · rw [if_neg hg, if_pos hg, iter_end (g5 o σ _ _ _)] + · rw [if_neg hl, if_pos hl, iter_end (g5 o σ _ _ _)] + +theorem sem_feeOn (o : Oracle) (σ : List (Nat × Nat)) : + (moduleSem o).run SolarTV.Export.Calls.stage0 (feeOnCall σ) = + some (observe (feeOnCall σ) (feeOnEnd o σ).2 (feeOnEnd o σ).1) := by + show (moduleLayer.result o _ _).map _ = _ + rw [moduleLayer.result_of_ends (show moduleLayer.Ends o SolarTV.Export.Calls.stage0 (feeOnCall σ) + (feeOnEnd o σ) from ⟨10, run_feeOn o σ⟩)] + rfl + +/-- info: 'SolidCore.Refinement.CallFamilies.FeeOn.sem_feeOn' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms sem_feeOn + +end SolidCore.Refinement.CallFamilies.FeeOn diff --git a/Contracts/CallFamilies/FeeOnSource.lean b/Contracts/CallFamilies/FeeOnSource.lean new file mode 100644 index 00000000..1a61c813 --- /dev/null +++ b/Contracts/CallFamilies/FeeOnSource.lean @@ -0,0 +1,515 @@ +import Contracts.CallFamilies.SyncSource + +/-! +# The source half of `feeOn` + +`feeOn_source`: SolidCore's run of `feeOn()` in a world `V` asks `V` the `STATICCALL` of +`feeTo()` the MIR makes, from the world the MIR sees, and shows `FeeOn.obsOf` of `V`'s answer +(`FeeOnSource`); `feeOn_stage_in` composes it with `mir_feeOn_agree` into the source stage of +`feeOn` under every oracle that agrees with `V`. +-/ + +namespace SolidCore.Refinement.CallFamilies + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Refinement.CallNode +open SolidCore.Solidity.Source EvmCompiler.Simulation + +/-- SolidCore's `feeOn()` of `Calls`, as the checker lowers it. -/ +def feeOnFn : FunctionDef := +{ name := "feeOn", + selector? := some 1328766218, + payable := false, + params := [], + paramAbiCleanups := [], + returns := [{ name := "on", ty := Ty.bool, isStorageRef := false }], + body := Stmt.block + [Stmt.skip, + Stmt.block + [Stmt.varDecl (Ty.address) "_sol_hoist_1" (some (Expr.word 0)), + Stmt.varDecl (Ty.address) "_sol_hoist_0" none, + Stmt.tryExternalCall + (SolidCore.Solidity.Shared.Call.ExternalCallKind.staticcall) + (Expr.storageRead (StorageReadMode.ref) "factory" []) + (Expr.encode (EncodeKind.withSelector) (some (Expr.word 25067096)) [] [] []) + (Expr.word 0) none false false + [{ name := "__ext0", ty := Ty.address, isStorageRef := false }] + [AbiCleanup.none] + (Stmt.assign (LValue.var "_sol_hoist_0") (Expr.var "__ext0")) + [], + Stmt.assign (LValue.var "on") + (Expr.binary (BinaryOp.ne) (Expr.var "_sol_hoist_0") (Expr.var "_sol_hoist_1")), + Stmt.ifElse (Expr.var "on") + (Stmt.assign (LValue.storage "kLast") (Expr.word 1)) + (Stmt.skip)]], + dispatchId? := none } + +theorem decode_addr (bs : List Byte) (h : 32 ≤ bs.length) : + abiDecodeValuesExcept? [Ty.address] bs = + if bytesToWordBE ((bs.map normByte).take 32) < 2 ^ 160 then + .ok [.word (bytesToWordBE ((bs.map normByte).take 32))] else .error .empty := by + have : ¬ bs.length < 32 := by omega + simp [abiDecodeValuesExcept?, Ty.listAbiHeadWords?, Ty.abiHeadWords?, abiDecodeOpt, bind, + Except.bind, pure, Except.pure, abiDecodeValuesAux?, abiDecodeValueAt?, + wordBytes_eq, this] + rw [show Ty.address.abiDecodeFuel = 1 from rfl] + simp [abiDecodeValueAtWithFuel?, readWord?, readBytes?, wordBytes_eq, h, this, abiDecodeOpt, + show (if Ty.address.isDynamicAbi = true then some 1 else Ty.address.staticAbiHeadWords?) = some 1 from rfl, + abiAddressFits] + have hv : bytesToWordBE (List.take 32 (List.map normByte bs)) < 2 ^ 256 := Nat.mod_lt _ (by decide) + generalize bytesToWordBE (List.take 32 (List.map normByte bs)) = v at hv ⊢ + have hn : SolidCore.Solidity.Shared.norm v = v := Nat.mod_eq_of_lt hv + by_cases hc : v < 2 ^ 160 + · have hc' : v < 1461501637330902918203684832716283019655932542976 := hc + simp [hn, hc', bind, Except.bind] + · have hc' : ¬ v < 1461501637330902918203684832716283019655932542976 := hc + simp [hn, hc', bind, Except.bind] + +theorem decode_short_addr (bs : List Byte) (h : bs.length < 32) : + abiDecodeValuesExcept? [Ty.address] bs = .error .empty := by + simp [abiDecodeValuesExcept?, Ty.listAbiHeadWords?, Ty.abiHeadWords?, abiDecodeOpt, bind, + Except.bind, pure, Except.pure, wordBytes_eq, h, + show (if Ty.address.isDynamicAbi = true then some 1 else Ty.address.staticAbiHeadWords?) = some 1 from rfl] + +theorem deref_word (rt : Runtime) (w : Word) : rt.derefMemoryValueDeep (.word w) = .ok (.word w) := by + unfold Runtime.derefMemoryValueDeep + rw [Runtime.derefMemoryValueWithFuel] + all_goals intros + all_goals contradiction + +theorem enc_feeTo (ctx : Context) (rt : Runtime) : + (Expr.encode (EncodeKind.withSelector) (some (Expr.word 25067096)) [] [] []).evalWithRuntimeByContext + ctx rt = .ok (.bytes [1, 126, 126, 88], rt) := by + simp only [Expr.evalWithRuntimeByContext, Expr.eval, Expr.orderFuel, Expr.evalFuel, + Expr.listEvalFuel, Expr.evalListFuel] + simp [Runtime.materializeForValueUseList, mat_word, bind, pure, liftM, monadLift, + MonadLift.monadLift, SolI.ofExcept, ipure_bind] + rfl + +theorem eval_varDecl_addr0 (n : Nat) (table : FunctionTable) (ctx : Context) (rt : Runtime) + (x : String) : + Stmt.eval (n + 1) table ctx rt (.varDecl Ty.address x (some (Expr.word 0))) = + pure (Result.normal (rt.declareLocal x (.word 0))) := by + rw [Stmt.eval] + simp [Expr.eval, Expr.evalFuel, Expr.orderFuel] + rfl + +theorem eval_skip (n : Nat) (table : FunctionTable) (ctx : Context) (rt : Runtime) : + Stmt.eval (n + 1) table ctx rt .skip = pure (Result.normal rt) := by + rw [Stmt.eval] + +/-- `Calls`'s `factory` field. -/ +def factoryField : StorageField := + { name := "factory", + slot := 0, + ty? := some Ty.address, + layout? := some (StorageLayout.scalar Ty.address), + transient := false, + packedOffset := 0, + packedBytes := 20, + packedSigned := false } + +theorem fac_eval (ctx : Context) (rt : Runtime) (hf : AddrFieldOk ctx "factory" factoryField) + (hw : rt.state.loadSlot factoryField.slot < Generic.wordSize) : + (Expr.storageRead .ref "factory" []).evalWithRuntimeByContext ctx rt = + .ok (.word (fieldValue (rt.state.loadSlot factoryField.slot) factoryField.packedOffset 20), rt) := by + simp only [Expr.evalWithRuntimeByContext, Expr.eval, Expr.orderFuel, Expr.evalFuel, + Expr.listEvalFuel] + simp only [load_addrField hf hw] + rfl + +theorem feeOnCall_eq (σ : List (Nat × Nat)) : + FeeOn.feeOnCall σ = Evm.Wide.callAt 1328766218 [] σ := rfl + +theorem feeOn_source (k : Nat) (V : World) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {d : SolidCore.Solidity.Source.State} (hd : Wide.DeployedAt (k + 5) c d []) + (hfind : c.core.findFunctionBySelector? 1328766218 = some feeOnFn) + (hfields : c.core.storageFields = callsFields) + (hstatic : StaticKeeps V) (hdt : d.transient.toList = []) (hde : d.envWorld? = none) + (hcb : c.core.context.accountBalances = []) (hch : c.core.context.accountCodehashes = []) + (hcc : c.core.context.accountCodes = []) (hkeys : ∀ p ∈ V.codes.getD [], p.1 < 2 ^ 160) + (hsize : ∀ h world request a, V.ans h (.external world (.call request)) = some a → + a.returnData.size < 2 ^ 256) (σ : List (Nat × Nat)) + (hself : slotValue σ 0 % 2 ^ 160 ≠ selfAddress) : FeeOnSource (k + 5) c V σ := by + have hlt := slotValue_lt σ + intro obs hrun + rw [feeOnCall_eq, runIn_eq_at V hd] at hrun + simp only [Source.ABI.Oracle.callCalldata, Dirty.readSelector_calldata _ (by decide : 1328766218 < 2 ^ 32), hfind] at hrun + simp only [show ABI.decodeFunctionArgs? feeOnFn (List.drop ABI.selectorBytes + (List.map (fun x => x.toNat) (EthLib.Base.natToBytes 4 1328766218) ++ + Dirty.argBytes (List.map (fun x => BitVec.toNat x) []))) = .ok [] from rfl, + show feeOnFn.acceptsValue 0 = true from rfl, ↓reduceIte] at hrun + generalize hctx : ABI.Contract.callContextAtWithBase c.core (ctxIn V c) selfAddress callerAddress 0 + (List.map (fun x => x.toNat) (EthLib.Base.natToBytes 4 1328766218) ++ + Dirty.argBytes (List.map (fun x => BitVec.toNat x) [])) = ctx at hrun + generalize hst : ({ d with storage := σ.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) d.storage } : + SolidCore.Solidity.Source.State) = st0 at hrun + have hctxv : ctx.value = 0 := by subst hctx; rfl + have hctxs : ctx.self = selfAddress := by subst hctx; rfl + simp only [Source.callAns, FunctionDef.call, FunctionDef.evalBodyEntry, hctxv, + show feeOnFn.acceptsValue 0 = true from rfl, ↓reduceIte, + show feeOnFn.initialFrame? [] = some [("on", Value.word 0)] by + simp [FunctionDef.initialFrame?, FunctionDef.returnDefaultBindings, BindingDecl.defaultBinding, + BindingDecl.bindArgs?, feeOnFn, Ty.defaultValue], Option.map_some, Option.bind_some] at hrun + generalize hrt0 : ({ state := { st0 with selfBalance := Solidity.Shared.addWord (Solidity.Shared.Account.balanceAt ctx.accountBalances ctx.self) 0, worldMutatedSinceAdoption := true }, locals := [[("on", Value.word 0)]] } : Runtime) = rt0 at hrun + rw [show feeOnFn.body = Stmt.block + [Stmt.skip, + Stmt.block + [Stmt.varDecl (Ty.address) "_sol_hoist_1" (some (Expr.word 0)), + Stmt.varDecl (Ty.address) "_sol_hoist_0" none, + Stmt.tryExternalCall + (SolidCore.Solidity.Shared.Call.ExternalCallKind.staticcall) + (Expr.storageRead (StorageReadMode.ref) "factory" []) + (Expr.encode (EncodeKind.withSelector) (some (Expr.word 25067096)) [] [] []) + (Expr.word 0) none false false + [{ name := "__ext0", ty := Ty.address, isStorageRef := false }] + [AbiCleanup.none] + (Stmt.assign (LValue.var "_sol_hoist_0") (Expr.var "__ext0")) + [], + Stmt.assign (LValue.var "on") + (Expr.binary (BinaryOp.ne) (Expr.var "_sol_hoist_0") (Expr.var "_sol_hoist_1")), + Stmt.ifElse (Expr.var "on") + (Stmt.assign (LValue.storage "kLast") (Expr.word 1)) + (Stmt.skip)]] from rfl] at hrun + simp only [eval_block, evalList_cons, eval_skip, sbind_pure, eval_varDecl_addr0, eval_varDecl_none] at hrun + rw [show k + 3 = (k + 2) + 1 from rfl] at hrun + have hctxf : ctx.storageFields = callsFields := by subst hctx; exact hfields + have hfx : AddrFieldOk ctx "factory" factoryField := + ⟨by simp [Context.storageField?, hctxf, callsFields, factoryField, tokenField], rfl, rfl, rfl, by decide, by decide⟩ + have hload : ∀ k, k < Generic.wordSize → st0.loadSlot k = slotValue σ k := by + intro k hk + have := getD_storage_cover hd (σ := σ) (by intro kv hkv; simp at hkv) k + subst hst + simp only [State.loadSlot, StorageMap.lookup?] + rw [← this] + simp only [SolidCore.Solidity.Shared.norm, modulus_eq, Std.HashMap.get?_eq_getElem?] + cases (List.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) d.storage σ)[k % Generic.wordSize]? <;> rfl + have hT : ((rt0.pushScope.pushScope.declareLocal "_sol_hoist_1" (Value.word 0)).declareLocal "_sol_hoist_0" Ty.address.defaultValue).state.loadSlot factoryField.slot = slotValue σ 0 := by + subst hrt0; exact hload 0 (by decide) + have ht := fac_eval ctx ((rt0.pushScope.pushScope.declareLocal "_sol_hoist_1" (Value.word 0)).declareLocal "_sol_hoist_0" Ty.address.defaultValue) hfx + (by rw [hT]; exact hlt 0) + rw [hT] at ht + have hne : wordEq (SolidCore.Solidity.Shared.norm (fieldValue (slotValue σ 0) factoryField.packedOffset 20)) ctx.self = false := by + rw [hctxs] + simp only [wordEq, fieldValue, factoryField, SolidCore.Solidity.Shared.norm] + simp + have h1 : slotValue σ 0 % 1461501637330902918203684832716283019655932542976 < Solidity.Shared.wordModulus := + lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (by decide) + rw [Nat.mod_eq_of_lt h1, Nat.mod_eq_of_lt (by decide : selfAddress < Solidity.Shared.wordModulus)] + exact hself + rw [eval_tryCall (k + 2) _ ctx _ _ _ _ _ false _ _ _ _ ht rfl (word0_eval ctx _) rfl (enc_feeTo ctx _) rfl hne] at hrun + generalize hW : snapshotWorld ctx ((rt0.pushScope.pushScope.declareLocal "_sol_hoist_1" (Value.word 0)).declareLocal "_sol_hoist_0" Ty.address.defaultValue).state = world at hrun + generalize hR : buildCallRequest ctx Solidity.Shared.Call.ExternalCallKind.staticcall + (Solidity.Shared.norm (fieldValue (slotValue σ 0) factoryField.packedOffset 20)) + (List.map normByte [1, 126, 126, 88]) (Solidity.Shared.norm 0) none = request at hrun + simp only [bind_request, map_request] at hrun + rw [foldAns_request] at hrun + cases hans : V.ans [] (Query.external world (ExternalRequest.call request)) with + | none => simp [hans] at hrun + | some a => + simp only [hans] at hrun + have hworld : ∀ slot < 2 ^ 256, storageIn world slot = slotValue σ slot % 2 ^ 256 := by + intro slot hslot + have hmut : ((rt0.pushScope.pushScope.declareLocal "_sol_hoist_1" (Value.word 0)).declareLocal "_sol_hoist_0" Ty.address.defaultValue).state.worldMutatedSinceAdoption = true := by + subst hrt0; rfl + have hwf : StorageMap.WF ((rt0.pushScope.pushScope.declareLocal "_sol_hoist_1" (Value.word 0)).declareLocal "_sol_hoist_0" Ty.address.defaultValue).state.storage := by + subst hrt0 hst + exact wf_foldl σ _ (wf_of_toList_nil _ hd.storage) + have hl := hload slot hslot + have hsto : ((rt0.pushScope.pushScope.declareLocal "_sol_hoist_1" (Value.word 0)).declareLocal "_sol_hoist_0" Ty.address.defaultValue).state.storage = st0.storage := by + subst hrt0; rfl + subst hW + unfold storageIn accountIn + rw [show wordToAddress selfAddress = wordToAddress ctx.self by rw [hctxs], + snapshotWorld_find_self ctx _ (Or.inr hmut)] + simp only [Option.getD_some, snapshotSelfAccount] + rw [lookup?_roundtrip _ hwf, hsto] + unfold State.loadSlot at hl + cases h : StorageMap.lookup? st0.storage slot with + | none => rw [h] at hl; simp [← hl] + | some v => rw [h] at hl; simp [← hl, SolidCore.Solidity.Shared.norm]; rfl + refine ⟨world, request, a, ?_, ?_⟩ + · refine ⟨hans, by subst hR; rfl, ?_, by subst hR; rfl, ?_, ?_, ?_, ?_, ?_⟩ + · subst hR + simp [buildCallRequest, addressToWord, wordToAddress, wordToU256, fieldValue, factoryField, + EvmYul.AccountAddress.ofUInt256, SolidCore.Solidity.Shared.norm] + have h1 : slotValue σ 0 % 1461501637330902918203684832716283019655932542976 < + Solidity.Shared.wordModulus := lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (by decide) + rw [Nat.mod_eq_of_lt h1] + simp [EvmYul.UInt256.ofNat, EvmYul.AccountAddress.size, Fin.ofNat, Id.run, EvmYul.UInt256.size] + · subst hR + show byteArrayToBytes (bytesToByteArray (List.map normByte [1, 126, 126, 88])) = List.map BitVec.toNat FeeOn.input + simp only [byteArrayToBytes, toList_eq_data, bytesToByteArray] + decide + · exact hworld + · intro slot hslot + have hmut : ((rt0.pushScope.pushScope.declareLocal "_sol_hoist_1" (Value.word 0)).declareLocal "_sol_hoist_0" Ty.address.defaultValue).state.worldMutatedSinceAdoption = true := by + subst hrt0; rfl + have htr : ((rt0.pushScope.pushScope.declareLocal "_sol_hoist_1" (Value.word 0)).declareLocal "_sol_hoist_0" Ty.address.defaultValue).state.transient = d.transient := by + subst hrt0 hst; rfl + subst hW + unfold transientIn accountIn + rw [show wordToAddress selfAddress = wordToAddress ctx.self by rw [hctxs], + snapshotWorld_find_self ctx _ (Or.inr hmut)] + simp only [Option.getD_some, snapshotSelfAccount] + rw [lookup?_roundtrip _ (by rw [htr]; exact wf_of_toList_nil _ hdt), htr] + have hnone : StorageMap.lookup? d.transient slot = none := by + unfold StorageMap.lookup? + rw [Std.HashMap.get?_eq_getElem?] + cases h : d.transient[SolidCore.Solidity.Shared.norm slot]? with + | none => rfl + | some v => + have := Std.HashMap.mem_toList_iff_getElem?_eq_some.mpr h + rw [hdt] at this; cases this + rw [hnone]; rfl + · intro x hx + have hacc : ctx.accountCodes = V.codes.getD [] := by + subst hctx + show V.codes.getD c.core.context.accountCodes = V.codes.getD [] + rw [hcc] + rw [← hacc] + subst hW + apply codeIn_snapshot + · subst hrt0 hst; exact hde + · subst hctx; exact hcb + · subst hctx; exact hch + · rw [hacc]; exact hkeys + · rw [hctxs]; decide + · exact hx + · exact hsize _ _ _ _ hans + · simp only [tryTail, decodeCallResponse] at hrun + cases hs : a.success + · simp only [hs, Bool.false_eq_true, ↓reduceIte, findMatch_nil] at hrun + simp only [sbind_pure, map_pure', foldAns_pure, Result.mapRuntime, FunctionDef.callBodyResult, + RevertData.fromRawBytes, normByte_bytes] at hrun + have hout : ∀ out, ABI.Contract.encodeRevertData? c.core + (if (byteArrayToBytes a.returnData == []) = true then SolidCore.Solidity.Source.RevertData.empty + else SolidCore.Solidity.Source.RevertData.raw (byteArrayToBytes a.returnData)).untagFixedBytes = some out → + out = byteArrayToBytes a.returnData := by + intro out h + split at h + · rename_i he + simp only [beq_iff_eq] at he + simp only [RevertData.untagFixedBytes, ABI.Contract.encodeRevertData?, Option.some.injEq] at h + rw [← h, he] + · simp only [RevertData.untagFixedBytes, ABI.Contract.encodeRevertData?, Option.some.injEq] at h + rw [← h] + exact normByte_bytes a.returnData + simp only [Option.bind_eq_bind, Option.map_bind] at hrun + obtain ⟨out, hout', hobs⟩ := Option.bind_eq_some_iff.mp hrun + rw [hout out hout'] at hobs + simp only [Function.comp, Option.map_some, Option.some.injEq] at hobs + rw [← hobs] + simp only [Source.observe, FeeOn.obsOf, hs, Bool.false_eq_true, ↓reduceIte, byteArrayToBytes_eq] + rfl + · simp only [hs, ↓reduceIte, normByte_bytes, List.map_cons, List.map_nil] at hrun + by_cases hlen : (byteArrayToBytes a.returnData).length < 32 + · rw [decode_short_addr _ hlen] at hrun + simp only [sbind_pure, map_pure', foldAns_pure, Result.mapRuntime, FunctionDef.callBodyResult, + RevertData.untagFixedBytes, ABI.Contract.encodeRevertData?, Option.bind_eq_bind, Option.bind_some, + Option.map_some, Option.some.injEq] at hrun + have hsz : a.returnData.size < 32 := by + rw [byteArrayToBytes_eq, List.length_map, List.length_range] at hlen; exact hlen + rw [← hrun] + simp only [Source.observe, FeeOn.obsOf, hs, ↓reduceIte, hsz, Bool.false_eq_true] + rfl + · rw [decode_addr _ (by omega)] at hrun + simp only [normByte_bytes] at hrun + generalize hw : bytesToWordBE (List.take 32 (byteArrayToBytes a.returnData)) = w at hrun + have hwlt : w < 2 ^ 256 := by rw [← hw]; exact Nat.mod_lt _ (by decide) + have hsz : 32 ≤ a.returnData.size := by + rw [byteArrayToBytes_eq, List.length_map, List.length_range] at hlen; omega + have hv : (Sync.retWord a).toNat = w := by rw [retWord_toNat a hsz, hw] + by_cases hc : w < 2 ^ 160 + · rw [if_pos hc] at hrun + have hbind : BindingDecl.bindArgs? [{ name := "__ext0", ty := Ty.address }] [Value.word w] = + some [("__ext0", Value.word w)] := by + simp [BindingDecl.bindArgs?, BindingDecl.bindArg?, Ty.coerceValue?, SolidCore.Solidity.Shared.norm, + Nat.mod_eq_of_lt hwlt] + simp only [show AbiCleanups.acceptOrUnspecified [AbiCleanup.none] [Value.word w] = true by + simp [AbiCleanups.acceptOrUnspecified, AbiCleanups.accept, AbiCleanup.accepts], + hbind, ↓reduceIte] at hrun + let ρ : Val := ⟨[], slotValue σ, solHash, SolidCore.Refinement.Generic.callerWord⟩ + let E : EraseEnv := { fields := callsFields, events := ctx.eventDecls, tbl := c.core.table } + let S1 : SymState := ⟨[[("__ext0", .lit w)], [("_sol_hoist_0", .lit 0), ("_sol_hoist_1", .lit 0)], [], [("on", .lit 0)]], [], [], .lit SolidCore.Refinement.Generic.callerWord⟩ + have hrel1 : StmtRel ρ E ctx (((({ state := adoptWorld a.postWorld ctx ((rt0.pushScope.pushScope.declareLocal "_sol_hoist_1" (Value.word 0)).declareLocal "_sol_hoist_0" Ty.address.defaultValue).state, locals := ((rt0.pushScope.pushScope.declareLocal "_sol_hoist_1" (Value.word 0)).declareLocal "_sol_hoist_0" Ty.address.defaultValue).locals, memory := ((rt0.pushScope.pushScope.declareLocal "_sol_hoist_1" (Value.word 0)).declareLocal "_sol_hoist_0" Ty.address.defaultValue).memory, nextMemory := ((rt0.pushScope.pushScope.declareLocal "_sol_hoist_1" (Value.word 0)).declareLocal "_sol_hoist_0" Ty.address.defaultValue).nextMemory, nextMemoryByte := ((rt0.pushScope.pushScope.declareLocal "_sol_hoist_1" (Value.word 0)).declareLocal "_sol_hoist_0" Ty.address.defaultValue).nextMemoryByte } : Runtime).recordExternalInteraction (ExternalInteraction.lowLevelCall { kind := Solidity.Shared.Call.ExternalCallKind.staticcall, target := Solidity.Shared.norm (fieldValue (slotValue σ 0) factoryField.packedOffset 20), calldata := [normByte 1, normByte 126, normByte 126, normByte 88], value := Solidity.Shared.norm 0, success := true, output := byteArrayToBytes a.returnData })).withFrame [("__ext0", Value.word w)])) S1 := + { fields := hctxf + events := rfl + checked := by subst hctx; rfl + sender := by subst hctx; rfl + hash := rfl + ok := slotValue_store σ + frames := by + subst hrt0 + simp [Runtime.withFrame, Runtime.recordExternalInteraction, Runtime.declareLocal, + Runtime.pushScope, frameOf, S1, WExpr.eval, Nat.mod_eq_of_lt hwlt] + simp [LocalEnv.declare, Ty.defaultValue] + store := by + intro j hj + show (adoptWorld a.postWorld ctx + ((rt0.pushScope.pushScope.declareLocal "_sol_hoist_1" (Value.word 0)).declareLocal "_sol_hoist_0" Ty.address.defaultValue).state).loadSlot j = slotValue σ j + have hadopt : ∀ X, (adoptWorld a.postWorld ctx X).loadSlot j = storageIn a.postWorld j := by + intro X + simp only [adoptWorld, State.loadSlot, storageIn, accountIn, hctxs] + cases StorageMap.lookup? _ j <;> rfl + rw [hadopt, hstatic _ _ _ _ hans (by subst hR; rfl) j, hworld j hj, Nat.mod_eq_of_lt (hlt j)] + logs := by + subst hrt0 hst + show List.map logOf d.events = List.map (Log.eval ρ) [] + rw [hd.events] + rfl + facts := by intro p hp; cases hp } + obtain ⟨r1, hr1, hl1⟩ := eval_stmt ρ E ctx (k + 2) (Stmt.assign (LValue.var "_sol_hoist_0") + (Expr.var "__ext0")) S1 _ rfl _ hrel1 + rw [hr1] at hrun + let S1' : SymState := ⟨[[("__ext0", .lit w)], [("_sol_hoist_0", .lit w), ("_sol_hoist_1", .lit 0)], [], [("on", .lit 0)]], [], [], .lit SolidCore.Refinement.Generic.callerWord⟩ + have hl1' : LeafRel ρ E ctx r1 (.normal S1') := hl1 + cases r1 with + | normal rt1 => + have hrel2 : StmtRel ρ E ctx rt1.popScope S1'.pop := StmtRel.popScope hl1' + obtain ⟨r2, hr2, hl2⟩ := eval_stmt ρ E ctx (k + 2 + 1) (Stmt.assign (LValue.var "on") + (Expr.binary BinaryOp.ne (Expr.var "_sol_hoist_0") (Expr.var "_sol_hoist_1"))) S1'.pop _ rfl _ hrel2 + simp only [done_bind', Result.mapRuntime, sbind_pure] at hrun + rw [hr2] at hrun + let ON : WExpr := .un .iszero (.bin .eq (.lit w) (.lit 0)) + let S3 : SymState := ⟨[[("_sol_hoist_0", .lit w), ("_sol_hoist_1", .lit 0)], [], [("on", ON)]], [], [], .lit SolidCore.Refinement.Generic.callerWord⟩ + have hl2' : LeafRel ρ E ctx r2 (.normal S3) := hl2 + cases r2 with + | normal rt2 => + obtain ⟨r3, hr3, hl3⟩ := eval_stmt ρ E ctx (k + 2 + 1) (Stmt.ifElse (Expr.var "on") + (Stmt.assign (LValue.storage "kLast") (Expr.word 1)) Stmt.skip) S3 _ rfl _ hl2' + simp only [done_bind', sbind_pure] at hrun + rw [hr3] at hrun + let S4 : SymState := ⟨S3.scopes, [(.lit 3, writeField (.init 3) (.lit 1) 0 32)], [], .lit SolidCore.Refinement.Generic.callerWord⟩ + have hl3' : LeafRel ρ E ctx r3 (if ON.eval ρ = 0 then .normal S3 else .normal S4) := hl3 + have hON : ON.eval ρ = if w = 0 then 0 else 1 := by + have hwlt' : w < 115792089237316195423570985008687907853269984665640564039457584007913129639936 := hwlt + simp [ON, WExpr.eval, UnOp.eval, BinOp.eval, Generic.wordSize, Nat.mod_eq_of_lt hwlt'] + by_cases hw0 : w = 0 <;> simp [hw0] + have hsz' : ¬ a.returnData.size < 32 := by omega + have hlo : ¬ 2 ^ 160 ≤ (Sync.retWord a).toNat := by rw [hv]; exact Nat.not_le_of_lt hc + by_cases hw0 : w = 0 + · rw [hON, if_pos hw0, if_pos rfl] at hl3' + cases r3 with + | normal rt3 => + have hrel3 : StmtRel ρ E ctx rt3 S3 := hl3' + simp only [done_bind', sbind_pure, evalList_nil, Result.mapRuntime, map_pure', foldAns_pure, + FunctionDef.callBodyResult] at hrun + have hloc : rt3.popScope.popScope.lookupLocal? "on" = some (Value.word 0) := by + simp [Runtime.popScope, Runtime.lookupLocal?, hrel3.frames, S3, S3, frameOf, LocalEnv.lookup?, + hON, hw0, Frame.lookup?] + have hcr : feeOnFn.collectReturns rt3.popScope.popScope = .ok [.word 0] := by + simp [FunctionDef.collectReturns, collectReturnBindings, collectReturnBindings.collect, feeOnFn, hloc, + deref_word, Ty.coerceValue?] + rfl + rw [hcr] at hrun + have henc : ABI.encodeValues? (List.map BindingDecl.ty feeOnFn.returns) [Value.word 0] = + some (FeeOn.wordBytes 0) := by decide + simp only [List.map_cons, List.map_nil, Value.untagFixedBytes, henc, Option.bind_eq_bind, + Option.bind_some, Option.map_some, Option.some.injEq] at hrun + have hev : rt3.state.events = [] := by + have := hrel3.logs + simp only [S3, S3, List.map_nil, List.map_eq_nil_iff] at this + exact this + rw [← hrun] + have hret : Sync.retWord a = 0 := BitVec.eq_of_toNat_eq (by rw [hv, hw0]; rfl) + simp only [Source.observe, FeeOn.obsOf, hs, ↓reduceIte, hsz', hlo, hret, Runtime.popScope, + State.logEntries, hev, List.map_nil] + rw [if_neg (by decide)] + congr 1 + funext slot + rw [loadSlot_eq rt3.state S3.writes ρ (slotValue_store σ) hrel3.store slot] + simp only [S3, Writes.store, Machine.State.initial, BitVec.toNat_ofNat] + show slotValue σ slot = _ + rw [← slotValue_store σ slot] + rfl + | _ => exact absurd hl3' id + · rw [hON, if_neg hw0, if_neg (by decide)] at hl3' + cases r3 with + | normal rt3 => + have hrel3 : StmtRel ρ E ctx rt3 S4 := hl3' + simp only [done_bind', sbind_pure, evalList_nil, Result.mapRuntime, map_pure', foldAns_pure, + FunctionDef.callBodyResult] at hrun + have hloc : rt3.popScope.popScope.lookupLocal? "on" = some (Value.word 1) := by + simp [Runtime.popScope, Runtime.lookupLocal?, hrel3.frames, S4, S3, frameOf, LocalEnv.lookup?, + hON, hw0, Frame.lookup?] + have hcr : feeOnFn.collectReturns rt3.popScope.popScope = .ok [.word 1] := by + simp [FunctionDef.collectReturns, collectReturnBindings, collectReturnBindings.collect, feeOnFn, hloc, + deref_word, Ty.coerceValue?] + rfl + rw [hcr] at hrun + have henc : ABI.encodeValues? (List.map BindingDecl.ty feeOnFn.returns) [Value.word 1] = + some (FeeOn.wordBytes 1) := by decide + simp only [List.map_cons, List.map_nil, Value.untagFixedBytes, henc, Option.bind_eq_bind, + Option.bind_some, Option.map_some, Option.some.injEq] at hrun + have hev : rt3.state.events = [] := by + have := hrel3.logs + simp only [S4, S3, List.map_nil, List.map_eq_nil_iff] at this + exact this + rw [← hrun] + have hret : ¬ Sync.retWord a = 0 := fun h => hw0 (by rw [← hv, h]; rfl) + simp only [Source.observe, FeeOn.obsOf, hs, ↓reduceIte, hsz', hlo, hret, Runtime.popScope, + State.logEntries, hev, List.map_nil] + congr 1 + funext slot + rw [loadSlot_eq rt3.state S4.writes ρ (slotValue_store σ) hrel3.store slot] + simp only [S4, Writes.store, Machine.update, Machine.State.initial] + rw [writeField_eval ρ _ _ (by decide) (by decide)] + by_cases h2 : slot % 2 ^ 256 = 3 + · have hb : BitVec.ofNat 256 slot = 3 := by + apply BitVec.eq_of_toNat_eq; simpa using h2 + rw [if_pos hb] + have h2' : slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 3 := h2 + simp [WExpr.eval, Generic.wordSize, h2', fieldWrite] + · have hb : BitVec.ofNat 256 slot ≠ 3 := by + intro h; apply h2; have := congrArg BitVec.toNat h; simpa using this + rw [if_neg hb] + have h2' : ¬ slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 3 := h2 + have hne : ¬ ((WExpr.lit 3).eval ρ = slot % Generic.wordSize) := by + intro h; apply h2'; simpa [WExpr.eval, Generic.wordSize] using h.symm + rw [if_neg hne] + simp only [BitVec.toNat_ofNat] + show slotValue σ slot = _ + rw [← slotValue_store σ slot] + rfl + | _ => exact absurd hl3' id + | _ => exact absurd hl2' id + | _ => exact absurd hl1' id + · rw [if_neg hc] at hrun + simp only [sbind_pure, map_pure', foldAns_pure, Result.mapRuntime, FunctionDef.callBodyResult, + RevertData.untagFixedBytes, ABI.Contract.encodeRevertData?, Option.bind_eq_bind, Option.bind_some, + Option.map_some, Option.some.injEq] at hrun + rw [← hrun] + have h1 : ¬ a.returnData.size < 32 := by omega + have h2 : 2 ^ 160 ≤ (Sync.retWord a).toNat := by rw [hv]; exact Nat.le_of_not_lt hc + simp only [Source.observe, FeeOn.obsOf, hs, ↓reduceIte, h1, h2, Bool.false_eq_true] + rfl + + +/-- info: 'SolidCore.Refinement.CallFamilies.feeOn_source' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms feeOn_source + +/-- **feeOn's source stage in the world V**: under every oracle that agrees with V +(CallsAgree o V), solar's stage0 runs feeOn() as SolidCore runs it in V, from every storage whose +factory is not the contract itself, with the hypotheses of sync_stage_in. -/ +theorem feeOn_stage_in (k : Nat) (V : World) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {d : SolidCore.Solidity.Source.State} (hd : Wide.DeployedAt (k + 5) c d []) + (hfind : c.core.findFunctionBySelector? 1328766218 = some feeOnFn) + (hfields : c.core.storageFields = callsFields) + (hdt : d.transient.toList = []) (hde : d.envWorld? = none) + (hcb : c.core.context.accountBalances = []) (hch : c.core.context.accountCodehashes = []) + (hcc : c.core.context.accountCodes = []) (hkeys : ∀ p ∈ V.codes.getD [], p.1 < 2 ^ 160) + (hsize : ∀ h world request a, V.ans h (.external world (.call request)) = some a → + a.returnData.size < 2 ^ 256) + (o : Machine.Oracle) (agree : CallsAgree o V) : + Stage (solidCoreIn V (k + 5)) (MIR.Lowered.moduleSem o) c SolarTV.Export.Calls.stage0 + (fun call => ∃ σ, slotValue σ 0 % 2 ^ 160 ≠ selfAddress ∧ call = FeeOn.feeOnCall σ) := + feeOn_stage (k + 5) c V _ (fun σ hσ => feeOn_source k V hd hfind hfields + (fun h w r a ha hk slot => (agree.static h w r a ha hk slot).1) hdt hde hcb hch hcc hkeys hsize σ hσ) + o agree + +/-- info: 'SolidCore.Refinement.CallFamilies.feeOn_stage_in' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms feeOn_stage_in + +end SolidCore.Refinement.CallFamilies diff --git a/Contracts/CallFamilies/NonVacuity.lean b/Contracts/CallFamilies/NonVacuity.lean new file mode 100644 index 00000000..ce61b0c1 --- /dev/null +++ b/Contracts/CallFamilies/NonVacuity.lean @@ -0,0 +1,184 @@ +import Contracts.CallFamilies.Core +import SolidCore.Refinement.SourceOracle + +/-! +# The external-call families run in an open world + +`Contracts/CallFamilies/Calls.sol` holds one function per external-call family of a constant-product pair +such as UniswapV2's: `sync` reads a token balance (a high-level `STATICCALL` behind solc's +`extcodesize` guard, as the pair's `sync`, `mint`, `burn` and `swap` do), `feeOn` reads the factory's +`feeTo` (the same kind of call, as `_mintFee` does), `skim` reads a balance and transfers tokens (a +low-level `CALL` whose return data must be empty or decode to `true`, as `_safeTransfer` in `skim`, +`burn` and `swap`), and `flash` transfers and then calls back (a high-level `CALL` with no return value, +as `swap`'s `uniswapV2Call`). + +In the closed world of `Source.run` none of them returns normally. This module proves that in an open +world each returns normally, so that a specification proved of SolidCore under every open world +(`World.Open`) is not vacuous on any of these families: + +* `witness`: an open world (`witness_open`) where the token, the factory and the callback have code, + every transfer succeeds and returns `true`, and every other call succeeds and returns the word + `balance`; +* `sync_returns`, `feeOn_returns`, `skim_returns`, `flash_returns`: run in `witness`, each returns + normally; +* `sync_closed`, `skim_closed`: in the closed world neither returns normally. + +Each run is the kernel's evaluation of SolidCore's interpreter (`kernel_rfl`, with the checker's +selectors from `Core`'s table), so the witnesses are proved, not tested. +-/ + +namespace SolidCore.Verify.VC.Calls.NonVacuity + +open SolidCore.Solidity SolidCore.Solidity.Source SolidCore.Refinement EvmCompiler.Simulation + +/-- The token's address in the witness. -/ +def token : Nat := 0xA0 +/-- The factory's address in the witness. -/ +def factory : Nat := 0xF0 +/-- The callback's address in the witness. -/ +def callback : Nat := 0xC0 + +/-- The word every call but a transfer returns: the token balance, the factory's `feeTo`. -/ +def balance : Nat := 1000000 + +/-- The selector of `transfer(address,uint256)`, as bytes. -/ +def transferSel : List Nat := [0xa9, 0x05, 0x9c, 0xbb] + +/-- The return data of a call: `true` for a transfer, else the word `balance`. -/ +def reply (request : CallRequest) : ByteArray := + if (byteArrayToBytes request.calldata).take 4 = transferSel then + bytesToByteArray (ABI.encodeWord 1) + else bytesToByteArray (ABI.encodeWord balance) + +/-- The witness's answers: precompiles and resources as SolidCore answers them, every other call +succeeds with `reply`, every creation fails, and the world after each is the world before it. -/ +def witnessAns : Ans := fun _ q => + match q with + | .resource r => some (Query.defaultAnswer (.resource r)) + | .external world (.call request) => + match precompileAnswerCall? world request with + | some a => some a + | none => + some (show CallResponse from + { success := true, returnData := reply request, postWorld := world, + returnedGas := EvmYul.UInt256.ofNat 0 }) + | .external world (.create request) => some (Query.defaultAnswer (.external world (.create request))) + +/-- The witness world: `witnessAns`, and code at the token, the factory and the callback. -/ +def witness : World := + { ans := witnessAns, codes := some [(token, [0]), (factory, [0]), (callback, [0])] } + +theorem witness_open : witness.Open where + calls h world request := by + simp only [witness, witnessAns] + split <;> rfl + creates _ _ _ := rfl + precompiles h world request a ha := by + simp only [witness, witnessAns, ha] + rfl + resources _ _ := rfl + codes := rfl + +/-- The contract's storage in the witness: the factory in slot 0 and the token in slot 1. -/ +def storage : List (Nat × Nat) := [(0, factory), (1, token)] + +/-- The call of the function with selector `sel` on the ABI-encoded arguments `args`. -/ +def callOf (sel : Nat) (args : List Nat) : Call := + { calldata := bytesToByteArray (ABI.wordToBytesBE 4 sel ++ args), callvalue := 0, storage } + +/-- `sync()`. -/ +def syncCall : Call := callOf syncSel [] +/-- `feeOn()`. -/ +def feeOnCall : Call := callOf feeOnSel [] +/-- `skim(callback)`. -/ +def skimCall : Call := callOf skimSel (ABI.encodeWord callback) +/-- `flash(callback, 5, hex"01")`. -/ +def flashCall : Call := + callOf flashSel (ABI.encodeWord callback ++ ABI.encodeWord 5 ++ ABI.encodeWord 96 ++ + ABI.encodeWord 1 ++ (1 :: List.replicate 31 0)) + +/-- Whether SolidCore's contract, run in `W` on `call`, returns normally. -/ +def returns (W : World) (call : Call) : Bool := + match contract? with + | .ok c => + match Source.runIn W fuel c call with + | some obs => obs.success + | none => false + | .error _ => false + +theorem returns_of {W : World} {call : Call} (h : returns W call = true) : + ∃ c, contract? = .ok c ∧ ∃ obs, Source.runIn W fuel c call = some obs ∧ obs.success = true := by + unfold returns at h + split at h + · next c hc => + refine ⟨c, hc, ?_⟩ + split at h + · next obs hobs => exact ⟨obs, hobs, h⟩ + · simp at h + · simp at h + +theorem not_returns_of {W : World} {call : Call} (h : returns W call = false) (c) + (hc : contract? = .ok c) : ∀ obs, Source.runIn W fuel c call = some obs → obs.success = false := by + intro obs hobs + unfold returns at h + rw [hc] at h + simp only [hobs] at h + exact h + +def syncReturns : Bool := returns witness syncCall +def feeOnReturns : Bool := returns witness feeOnCall +def skimReturns : Bool := returns witness skimCall +def flashReturns : Bool := returns witness flashCall +def syncClosed : Bool := returns World.closed syncCall +def skimClosed : Bool := returns World.closed skimCall + +kernel_rfl syncReturns_eq syncReturns true using selector_eq SolidCore.Verify.VC.mkIdx_eq +kernel_rfl feeOnReturns_eq feeOnReturns true using selector_eq SolidCore.Verify.VC.mkIdx_eq +kernel_rfl skimReturns_eq skimReturns true using selector_eq SolidCore.Verify.VC.mkIdx_eq +kernel_rfl flashReturns_eq flashReturns true using selector_eq SolidCore.Verify.VC.mkIdx_eq +kernel_rfl syncClosed_eq syncClosed false using selector_eq SolidCore.Verify.VC.mkIdx_eq +kernel_rfl skimClosed_eq skimClosed false using selector_eq SolidCore.Verify.VC.mkIdx_eq + +/-- **A token balance read returns in an open world**: `sync()` reaches `balanceOf` and stores it. -/ +theorem sync_returns : ∃ c, contract? = .ok c ∧ + ∃ obs, Source.runIn witness fuel c syncCall = some obs ∧ obs.success = true := + returns_of syncReturns_eq + +/-- **A factory read returns in an open world**: `feeOn()` reaches `feeTo`. -/ +theorem feeOn_returns : ∃ c, contract? = .ok c ∧ + ∃ obs, Source.runIn witness fuel c feeOnCall = some obs ∧ obs.success = true := + returns_of feeOnReturns_eq + +/-- **A transfer returns in an open world**: `skim(to)` reads the balance and transfers it. -/ +theorem skim_returns : ∃ c, contract? = .ok c ∧ + ∃ obs, Source.runIn witness fuel c skimCall = some obs ∧ obs.success = true := + returns_of skimReturns_eq + +/-- **A transfer and a callback return in an open world**: `flash` transfers, then calls back. -/ +theorem flash_returns : ∃ c, contract? = .ok c ∧ + ∃ obs, Source.runIn witness fuel c flashCall = some obs ∧ obs.success = true := + returns_of flashReturns_eq + +/-- In the closed world of `Source.run`, `sync()` never returns normally. -/ +theorem sync_closed : ∀ c, contract? = .ok c → + ∀ obs, Source.run fuel c syncCall = some obs → obs.success = false := by + intro c hc obs h + rw [← Source.runIn_closed] at h + exact not_returns_of syncClosed_eq c hc obs h + +/-- In the closed world of `Source.run`, `skim(to)` never returns normally. -/ +theorem skim_closed : ∀ c, contract? = .ok c → + ∀ obs, Source.run fuel c skimCall = some obs → obs.success = false := by + intro c hc obs h + rw [← Source.runIn_closed] at h + exact not_returns_of skimClosed_eq c hc obs h + +/-- info: 'SolidCore.Verify.VC.Calls.NonVacuity.flash_returns' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms flash_returns + +/-- info: 'SolidCore.Verify.VC.Calls.NonVacuity.sync_closed' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms sync_closed + +end SolidCore.Verify.VC.Calls.NonVacuity diff --git a/Contracts/CallFamilies/PayRun.lean b/Contracts/CallFamilies/PayRun.lean new file mode 100644 index 00000000..e5699928 --- /dev/null +++ b/Contracts/CallFamilies/PayRun.lean @@ -0,0 +1,277 @@ +import Contracts.CallFamilies.PaySource + +/-! +# pay's body in SolidCore, through its transfer call + +pay_run: from a frame binding to and amount (to below 2^160), with Calls' token field, outside +construction and with a token other than the contract itself, SolidCore's pay body is exactly one +request node, the low-level CALL of transfer(to, amount) (payInput) from the sent world, and for +every answer with return data shorter than 2^256 bytes it continues to payRes: success (no return +data, or a word equal to 1), Error("TRANSFER_FAILED") (a failed call, or a word equal to 0), or the +empty revert of a short or non-bool return word, in a runtime whose state is the adopted world with +the call recorded (payState). Covers the memoryVarDecl of ret, the tuple assignment of the call's +result, and the short-circuit require with the bool decode. +-/ + +namespace SolidCore.Refinement.CallFamilies + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Refinement.CallNode +open SolidCore.Solidity.Source EvmCompiler.Simulation + +/-- The runtime after (ok, ret) = the call's result. -/ +def wroteRt (R : Runtime) (w : Nat) (out : List Byte) (L : LocalEnv) : Runtime := + { state := R.state + locals := [("__solidcore_low_level_return", Value.tuple [Value.word w, Value.bytes out]), + ("ret", Value.memoryRef R.nextMemory), ("ok", Value.word w)] :: L + memory := R.memory.insertLoop R.nextMemory (Value.bytes out) + nextMemory := R.nextMemory + 1 + nextMemoryByte := R.nextMemoryByte + (Value.bytes out).memoryAllocationBytes } + +theorem write_ok_ret (ctx : Context) (R : Runtime) (w : Nat) (out : List Byte) (id : Nat) (L : LocalEnv) + (hl : R.locals = [("__solidcore_low_level_return", Value.tuple [Value.word w, Value.bytes out]), + ("ret", Value.memoryRef id), ("ok", Value.word 0)] :: L) : + LValues.writeTupleWithRuntime ctx R [some (LValue.var "ok"), some (LValue.var "ret")] + [Value.word w, Value.bytes out] = EvmCompiler.Simulation.Interaction.done (.ok (wroteRt R w out L)) := by + simp [LValues.writeTupleWithRuntime, LValues.resolveTupleWithRuntime, LValue.resolveWithRuntime, LValue.toExpr, + Expr.resolveLValue, Expr.resolveLValueFuel, Runtime.lookupStorageBase?, Runtime.lookupLocal?, hl, + LocalEnv.lookup?, Frame.lookup?, ResolvedLValue.freezeIndexedStoragePath, pure, bind, ipure_eq] + simp only [ResolvedLValue.asStoragePath?, dbind] + simp [LValues.writeResolvedRightToLeft, ResolvedLValue.write, Runtime.assignLocal?, Runtime.lookupLocal?, hl, + LocalEnv.lookup?, Frame.lookup?, Value.isMemoryObject, Runtime.memoryStoredValue, Runtime.allocMemory, + Runtime.assignLocalRaw?, LocalEnv.assign?, Frame.assign?, Value.coerceLike?, pure, bind, dbind, ipure_eq, wroteRt] + simp only [liftM, monadLift, MonadLift.monadLift, SolI.ofExcept, dbind] + simp [LocalEnv.lookup?, Frame.lookup?, Value.coerceLike?, LocalEnv.assign?, Frame.assign?, wroteRt] + done + +theorem throw_eq {α : Type} (e : SolidityFailure) : + (throw e : SolI α) = EvmCompiler.Simulation.Interaction.done (.error e) := rfl + +theorem tbind {α β : Type} (e : SolidityFailure) (f : α → SolI β) : + EvmCompiler.Simulation.Interaction.bind (EvmCompiler.Simulation.Interaction.done (.error e) : SolI α) f = + EvmCompiler.Simulation.Interaction.done (.error e) := rfl + +theorem caught_revert {α : Type} (e : SolidCore.Solidity.Source.RevertData) : + SolI.caught (EvmCompiler.Simulation.Interaction.done (.error (SolidityFailure.revert e)) : SolI α) = + EvmCompiler.Simulation.Interaction.done (.ok (.error e)) := rfl + +theorem headWords_bool : + (if Ty.bool.isDynamicAbi = true then some 1 else Ty.bool.staticAbiHeadWords?) = some 1 := rfl + +theorem decb_short (p : Nat) (bs : List Byte) (h : bs.length < 32) : + abiDecodeValuesWithCleanupsAtExcept? p [Ty.bool] [AbiCleanup.none] bs = .error .empty := by + simp [abiDecodeValuesWithCleanupsAtExcept?, Ty.listAbiHeadWords?, Ty.abiHeadWords?, abiDecodeOpt, bind, + Except.bind, pure, Except.pure, wordBytes_eq, headWords_bool, h] + +theorem decb_word (p : Nat) (bs : List Byte) (h : 32 ≤ bs.length) : + abiDecodeValuesWithCleanupsAtExcept? p [Ty.bool] [AbiCleanup.none] bs = + if bytesToWordBE ((bs.map normByte).take 32) ≤ 1 then + .ok [.word (bytesToWordBE ((bs.map normByte).take 32))] else .error .empty := by + have : ¬ bs.length < 32 := by omega + simp [abiDecodeValuesWithCleanupsAtExcept?, Ty.listAbiHeadWords?, Ty.abiHeadWords?, abiDecodeOpt, bind, + Except.bind, pure, Except.pure, abiDecodeValuesWithCleanupsAux?, abiDecodeValueAt?, wordBytes_eq, this, + abiCheckTopLevelAllocationAt?, headWords_bool] + rw [show Ty.bool.abiDecodeFuel = 1 from rfl] + simp [abiDecodeValueAtWithFuel?, readWord?, readBytes?, wordBytes_eq, h, abiDecodeOpt, AbiCleanup.accepts] + have hwlt : bytesToWordBE (List.take 32 (List.map normByte bs)) < 2 ^ 256 := Nat.mod_lt _ (by decide) + generalize bytesToWordBE (List.take 32 (List.map normByte bs)) = w at hwlt ⊢ + simp only [bind, Except.bind] + by_cases h0 : w = 0 + · subst h0; simp [wordEq] + by_cases h1 : w = 1 + · subst h1; simp [wordEq] + have h2 : ¬ w ≤ 1 := fun h => by + rcases Nat.le_one_iff_eq_zero_or_eq_one.mp h with h | h <;> contradiction + have hn : SolidCore.Solidity.Shared.norm w = w := Nat.mod_eq_of_lt hwlt + simp [wordEq, hn, h0, h1, h2, show SolidCore.Solidity.Shared.norm 0 = 0 from rfl, + show SolidCore.Solidity.Shared.norm 1 = 1 from rfl] + +/-- What pay's require condition evaluates to, by the call's success flag and return bytes. -/ +def condRes (R : Runtime) (b : Bool) (out : List Byte) : SolI (Value × Runtime) := + if b then + if out.length = 0 then .done (.ok (.word 1, R)) + else if out.length < 32 then .done (.error (.revert .empty)) + else if bytesToWordBE (((out.map normByte).map normByte).take 32) ≤ 1 then + .done (.ok (.word (bytesToWordBE (((out.map normByte).map normByte).take 32)), R)) + else .done (.error (.revert .empty)) + else .done (.ok (.word 0, R)) + +theorem cond_eval (ctx : Context) (R : Runtime) (b : Bool) (out : List Byte) (id : Nat) (L : LocalEnv) + (hl : R.locals = [("__solidcore_low_level_return", Value.tuple [Value.word (if b = true then 1 else 0), + Value.bytes out]), ("ret", Value.memoryRef id), ("ok", Value.word (if b = true then 1 else 0))] :: L) + (hm : R.memory[id]? = some (Value.bytes out)) (hlen : out.length < 2 ^ 256) : + Expr.eval ctx R payCond = condRes R b out := by + simp only [Expr.eval, payCond, Expr.orderFuel, Expr.listEvalFuel] + simp only [Expr.evalFuel] + cases b + · simp [Runtime.lookupStorageBase?, Runtime.lookupLocal?, hl, LocalEnv.lookup?, Frame.lookup?, + Runtime.derefMemoryValue, Value.expectWord, wordTruthy, liftM, monadLift, MonadLift.monadLift, SolI.ofExcept, + bind_done_ok, pure, SolidCore.Solidity.Shared.norm, condRes] + rfl + · simp [Runtime.lookupStorageBase?, Runtime.lookupLocal?, hl, LocalEnv.lookup?, Frame.lookup?, + Runtime.derefMemoryValue, Value.expectWord, wordTruthy, liftM, monadLift, MonadLift.monadLift, SolI.ofExcept, + Runtime.loadMemory?, MemoryMap.lookup?, hm, bind_done_ok, pure, SolidCore.Solidity.Shared.norm, ipure_eq, wm, + Value.length?, cleanup256, BinaryOp.apply, normWord] + by_cases hz : out.length = 0 + · simp only [hz, cleanup256 _ 0 (by decide)] + simp [Value.forceAbiLazy, BinaryOp.preservesFixedBytesWidth, bind_done_ok, ipure_eq, wm, wordEq, boolWord, bind, + Except.bind, pure, Except.pure, condRes] + intro h; exact absurd (List.length_eq_zero_iff.mp hz) h + · simp only [cleanup256 _ _ hlen] + simp [Value.forceAbiLazy, BinaryOp.preservesFixedBytesWidth, bind_done_ok, ipure_eq, wm, wordEq, boolWord, bind, + Except.bind, pure, Except.pure, hz, Runtime.lookupStorageBase?, Runtime.lookupLocal?, hl, LocalEnv.lookup?, + Frame.lookup?, Runtime.derefMemoryValue, Runtime.loadMemory?, MemoryMap.lookup?, hm, condRes] + have hn' : SolidCore.Solidity.Shared.norm out.length = out.length := Nat.mod_eq_of_lt hlen + have hz' : ¬ out = [] := fun h => hz (by rw [h]; rfl) + by_cases hs : out.length < 32 + · simp [decb_short _ (out.map normByte) (by simpa using hs), hs, hn', hz, hz', + show SolidCore.Solidity.Shared.norm 0 = 0 from rfl, Value.asBytes?] + rfl + · simp only [Value.asBytes?] + rw [decb_word _ (out.map normByte) (by simp; omega)] + simp only [List.map_map] + have hwlt : bytesToWordBE ((out.map (normByte ∘ normByte)).take 32) < 2 ^ 256 := Nat.mod_lt _ (by decide) + generalize bytesToWordBE ((out.map (normByte ∘ normByte)).take 32) = w at hwlt ⊢ + by_cases hw1 : w ≤ 1 + · have hn : w % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = w := + Nat.mod_eq_of_lt hwlt + rcases Nat.le_one_iff_eq_zero_or_eq_one.mp hw1 with h | h <;> subst h <;> + simp [hs, hn', hz, hz', show SolidCore.Solidity.Shared.norm 0 = 0 from rfl, Value.asBytes?, throw_eq, + tbind, dbind] <;> rfl + · simp [hw1, hs, hn', hz, hz', show SolidCore.Solidity.Shared.norm 0 = 0 from rfl, Value.asBytes?, throw_eq, + tbind, dbind] + done + +/-- The state pay leaves once the transfer answered: the adopted world, with the call recorded. -/ +def payState (ctx : Context) (st : State) (a : CallResponse) (D : LowLevelCallResult) : State := + { adoptWorld a.postWorld ctx st with + externalInteractions := (adoptWorld a.postWorld ctx st).externalInteractions ++ [ExternalInteraction.lowLevelCall D] } + +/-- pay's result, by the call's success flag and return bytes: success (no return data, or a true +word), Error("TRANSFER_FAILED") (a failed call or a false word), or the empty revert of a short or +non-bool return word. -/ +def payRes (b : Bool) (out : List Byte) (R : Runtime) : Result := + let w := bytesToWordBE ((out.map (normByte ∘ normByte)).take 32) + let r0 : Result := + if b then + if out.length = 0 then .normal R + else if out.length < 32 then .reverted R .empty + else if w ≤ 1 then (if w = 0 then .reverted R (.error "TRANSFER_FAILED") else .normal R) + else .reverted R .empty + else .reverted R (.error "TRANSFER_FAILED") + (r0.mapRuntime Runtime.popScope).mapRuntime Runtime.popScope + +set_option maxHeartbeats 300000 in +theorem pay_run (n : Nat) (tbl : FunctionTable) (ctx : Context) (rt : Runtime) (dst amt : Nat) + (hd : dst < 2 ^ 160) (ha : amt < 2 ^ 256) + (hl : rt.locals = [[("to", .word dst), ("amount", .word amt)]]) + (hf : AddrFieldOk ctx "token" tokenField) (hw : rt.state.loadSlot tokenField.slot < Generic.wordSize) + (hcons : ctx.construction = false) + (hself : wordEq (SolidCore.Solidity.Shared.norm (fieldValue (rt.state.loadSlot tokenField.slot) tokenField.packedOffset 20)) ctx.self = false) : + ∃ k, Stmt.eval (n + 3) tbl ctx rt payBody = + .request (.external (snapshotWorld ctx rt.state) + (.call (buildCallRequest ctx .call (SolidCore.Solidity.Shared.norm (fieldValue (rt.state.loadSlot tokenField.slot) tokenField.packedOffset 20)) + (List.map normByte (payInput dst amt)) (SolidCore.Solidity.Shared.norm 0) none))) k ∧ + ∀ a : CallResponse, a.returnData.size < 2 ^ 256 → ∃ R : Runtime, + R.state = payState ctx rt.state a (decodeCallResponse a .call + (SolidCore.Solidity.Shared.norm (fieldValue (rt.state.loadSlot tokenField.slot) tokenField.packedOffset 20)) + (List.map normByte (payInput dst amt)) (SolidCore.Solidity.Shared.norm 0) none) ∧ + k a = pure (payRes (decodeCallResponse a .call + (SolidCore.Solidity.Shared.norm (fieldValue (rt.state.loadSlot tokenField.slot) tokenField.packedOffset 20)) + (List.map normByte (payInput dst amt)) (SolidCore.Solidity.Shared.norm 0) none).success + (decodeCallResponse a .call + (SolidCore.Solidity.Shared.norm (fieldValue (rt.state.loadSlot tokenField.slot) tokenField.packedOffset 20)) + (List.map normByte (payInput dst amt)) (SolidCore.Solidity.Shared.norm 0) none).output R) := by + rw [payBody, eval_block, evalList_cons, show n + 2 = (n + 1) + 1 from rfl, eval_skip, sbind_pure] + dsimp only + rw [evalList_cons, pay_amount (n + 1) tbl ctx rt.pushScope dst amt ha (by simp [Runtime.pushScope, hl]), sbind_pure] + dsimp only + rw [evalList_cons, eval_block, payInner, evalList_cons, eval_varDecl_none, sbind_pure] + dsimp only + rw [evalList_cons, eval_memoryVarDecl_none, ret_decl] + dsimp only + rw [sbind_pure] + dsimp only + rw [evalList_cons, eval_varDecl_some] + rw [Expr.eval, show payCallE.orderFuel + 1 = 13 + 1 from rfl, payCallE, + eval_lowLevelCall 13 ctx _ _ _ _ false (tokF' 12 ctx _ rt hf ?hs hw) rfl (word0F 12 ctx _) rfl + (payEnc 7 ctx _ dst amt hd ha ?b1 ?l1 ?b2 ?l2) rfl hcons hself] + · simp only [caught_request, bind_request] + refine ⟨_, rfl, fun a ha => ?_⟩ + simp only [lowLevelTail, caught_done_ok, bind_done_ok, pure] + have hlen : (decodeCallResponse a LowLevelCallKind.call + (SolidCore.Solidity.Shared.norm (fieldValue (rt.state.loadSlot tokenField.slot) tokenField.packedOffset 20)) + (List.map normByte (payInput dst amt)) (SolidCore.Solidity.Shared.norm 0) none).output.length < 2 ^ 256 := by + simp only [decodeCallResponse, byteArrayToBytes_eq, List.length_map, List.length_range]; exact ha + generalize decodeCallResponse a LowLevelCallKind.call _ _ _ none = D at hlen ⊢ + simp only [ipure_eq, caught_done_ok, bind_done_ok] + generalize hR0 : retRt _ = R0 + have hR0l : R0.locals = [[("ret", Value.memoryRef rt.nextMemory), ("ok", Value.word 0)], [], + [("to", Value.word dst), ("amount", Value.word amt)]] := by + rw [← hR0]; simp [retRt, Runtime.declareLocal, Runtime.pushScope, LocalEnv.declare, Ty.defaultValue] + have hR0m : R0.memory = rt.memory.insertLoop rt.nextMemory (Value.bytes []) := by + rw [← hR0]; simp [retRt, Runtime.declareLocal, Runtime.pushScope] + have hR0n : R0.nextMemory = rt.nextMemory + 1 := by + rw [← hR0]; simp [retRt, Runtime.declareLocal, Runtime.pushScope] + have hR0s : R0.state = rt.state := by + rw [← hR0]; simp [retRt, Runtime.declareLocal, Runtime.pushScope] + clear hR0 + simp only [Ty.coerceTupleValues?, Ty.coerceValue?, boolWord] + have h01 : (wordEq (if D.success = true then 1 else 0) 0 || + wordEq (if D.success = true then 1 else 0) 1) = true := by + cases D.success <;> simp [wordEq] + simp only [h01, ↓reduceIte] + dsimp only [bind, Option.bind] + generalize hR1 : Runtime.declareLocal _ "__solidcore_low_level_return" _ = R1 + have hR1l : R1.locals = [[("__solidcore_low_level_return", Value.tuple [Value.word (if D.success = true then 1 else 0), + Value.bytes D.output]), ("ret", Value.memoryRef rt.nextMemory), ("ok", Value.word 0)], [], + [("to", Value.word dst), ("amount", Value.word amt)]] := by + rw [← hR1]; simp [Runtime.declareLocal, Runtime.recordExternalInteraction, LocalEnv.declare, hR0l] + have hR1s : R1.state = payState ctx rt.state a D := by + rw [← hR1, ← hR0s]; rfl + have hR1m : R1.memory = R0.memory := by + rw [← hR1]; simp [Runtime.declareLocal, Runtime.recordExternalInteraction] + have hR1n : R1.nextMemory = R0.nextMemory := by + rw [← hR1]; simp [Runtime.declareLocal, Runtime.recordExternalInteraction] + clear hR1 + rw [dbind]; dsimp only + rw [evalList_cons, Stmt.eval]; dsimp only + simp [Expr.eval, Expr.orderFuel, Expr.evalFuel, Runtime.lookupStorageBase?, Runtime.lookupLocal?, hR1l, + LocalEnv.lookup?, Frame.lookup?, Runtime.derefMemoryValue] + simp only [liftM, monadLift, MonadLift.monadLift, SolI.ofExcept, bind_done_ok, ipure_eq, caught_done_ok, pure] + try simp only [dbind] + rw [write_ok_ret ctx R1 _ D.output rt.nextMemory _ hR1l] + try simp only [caught_done_ok, dbind] + generalize hR2 : wroteRt R1 _ D.output _ = R2 + have hR2l : R2.locals = [("__solidcore_low_level_return", Value.tuple [Value.word (if D.success = true then 1 else 0), + Value.bytes D.output]), ("ret", Value.memoryRef R1.nextMemory), ("ok", Value.word (if D.success = true then 1 else 0))] :: + [[], [("to", Value.word dst), ("amount", Value.word amt)]] := by + rw [← hR2]; rfl + have hR2m : R2.memory = R1.memory.insertLoop R1.nextMemory (Value.bytes D.output) := by rw [← hR2]; rfl + have hR2s : R2.state = R1.state := by rw [← hR2]; rfl + clear hR2 + rw [bind_done_ok]; dsimp only + rw [bind_done_ok]; dsimp only + rw [evalList_cons, eval_require] + have hm : R2.memory[R1.nextMemory]? = some (Value.bytes D.output) := by + rw [hR2m]; simp [MemoryMap.insertLoop] + rw [cond_eval ctx R2 D.success D.output R1.nextMemory _ hR2l hm hlen] + refine ⟨R2, by rw [hR2s, hR1s], ?_⟩ + simp only [condRes, payRes] + simp only [List.map_map] + have hwm : SolidCore.Solidity.Shared.wordModulus = 2 ^ 256 := rfl + have hwlt : bytesToWordBE (List.take 32 (List.map (normByte ∘ normByte) D.output)) < 2 ^ 256 := + Nat.mod_lt _ (by decide) + have hwlt' : bytesToWordBE (List.take 32 (List.map (normByte ∘ normByte) D.output)) < + 115792089237316195423570985008687907853269984665640564039457584007913129639936 := hwlt + split_ifs <;> simp [caught_done_ok, bind_done_ok, dbind, tbind, ipure_eq, Value.expectWord, wordTruthy, + evalList_nil, pure, SolidCore.Solidity.Shared.norm, throw_eq, hwm, caught_revert, Nat.mod_eq_of_lt hwlt', + Result.mapRuntime, *] <;> done + · rfl + all_goals simp [Runtime.lookupStorageBase?, Runtime.lookupLocal?, retRt, Runtime.declareLocal, Runtime.pushScope, + LocalEnv.declare, LocalEnv.lookup?, Frame.lookup?] + +/-- info: 'SolidCore.Refinement.CallFamilies.pay_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms pay_run + +end SolidCore.Refinement.CallFamilies diff --git a/Contracts/CallFamilies/PaySource.lean b/Contracts/CallFamilies/PaySource.lean new file mode 100644 index 00000000..f4aac877 --- /dev/null +++ b/Contracts/CallFamilies/PaySource.lean @@ -0,0 +1,316 @@ +import Contracts.CallFamilies.SkimAgree +import Contracts.CallFamilies.SyncSource +import SolidCore.Refinement.KernelRfl + +namespace SolidCore.Refinement.CallFamilies + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Refinement.CallNode +open SolidCore.Solidity.Source EvmCompiler.Simulation + +/-- The selector expression of pay's transfer: bytes4(keccak256("transfer(address,uint256)")). -/ +def transferSelE : Expr := + Expr.castOp (CastKind.fixedBytes 32) 4 (Expr.keccak256 (Expr.byteArray + [116, 114, 97, 110, 115, 102, 101, 114, 40, 97, 100, 100, 114, 101, 115, 115, 44, 117, + 105, 110, 116, 50, 53, 54, 41])) + +theorem mat_bytes (ctx : Context) (rt : Runtime) (bs : List Byte) : + rt.materializeForValueUse ctx (.bytes bs) = .ok (.bytes bs) := by + unfold Runtime.materializeForValueUse + rw [Runtime.materializeForValueUseFuel] + all_goals intros + all_goals contradiction + +/-- The cast of the signature's Keccak-256 to its first four bytes. -/ +def selCast : Except SolidCore.Solidity.Source.RevertData Value := + fixedBytesCast? 4 32 (keccakWord ([116, 114, 97, 110, 115, 102, 101, 114, 40, 97, 100, 100, 114, 101, + 115, 115, 44, 117, 105, 110, 116, 50, 53, 54, 41].map normByte)) + +kernel_rfl selCast_eq selCast (Except.ok (Value.fixedBytes 4 + 2835717307)) + +/-- The selector cast as the interpreter computes it. -/ +def selCast2 : Except SolidCore.Solidity.Source.RevertData Value := + fixedBytesCast? 4 32 (SolidCore.Solidity.Shared.norm (keccakWord (List.map normByte (List.map normByte + [116, 114, 97, 110, 115, 102, 101, 114, 40, 97, 100, 100, 114, 101, + 115, 115, 44, 117, 105, 110, 116, 50, 53, 54, 41])))) + +kernel_rfl selCast2_eq selCast2 (Except.ok (Value.fixedBytes 4 2835717307)) + +/-- The selector of transfer, as SolidCore holds a bytes4 (right-aligned). -/ +abbrev transferWord : Nat := 2835717307 + +theorem dbind {ε α β : Type} (a : α) (f : α → Interaction ε β) : + (Interaction.done (Except.ok a)).bind f = f a := rfl + +theorem sel_eval (ctx : Context) (rt : Runtime) : + transferSelE.evalWithRuntimeByContext ctx rt = .ok (.fixedBytes 4 transferWord, rt) := by + simp only [transferSelE, Expr.evalWithRuntimeByContext, Expr.eval, Expr.orderFuel, Expr.evalFuel] + simp only [bind, pure, liftM, monadLift, MonadLift.monadLift, SolI.ofExcept, ipure_bind, mat_bytes] + have h := selCast_eq + unfold selCast at h + simp only [List.map_cons, List.map_nil] at h + rw [dbind] + simp only [Value.asBytes?, ipure_bind, Value.expectWord] + rw [dbind] + have h2 := selCast2_eq + unfold selCast2 at h2 + rw [h2] + rfl + +theorem selF (n : Nat) (ctx : Context) (rt : Runtime) : + Expr.evalFuel (n + 4) ctx rt transferSelE = pure (.fixedBytes 4 transferWord, rt) := by + simp only [transferSelE, Expr.evalFuel] + simp only [bind, pure, liftM, monadLift, MonadLift.monadLift, SolI.ofExcept, ipure_bind, mat_bytes] + rw [dbind] + simp only [Value.asBytes?, ipure_bind, Value.expectWord] + rw [dbind] + have h2 := selCast2_eq + unfold selCast2 at h2 + rw [h2] + rfl + +theorem varF (n : Nat) (ctx : Context) (rt : Runtime) (x : String) (w : Nat) + (hb : rt.lookupStorageBase? x = none) (hl : rt.lookupLocal? x = some (.word w)) : + Expr.evalFuel (n + 1) ctx rt (Expr.var x) = pure (.word w, rt) := by + simp only [Expr.evalFuel, hb, hl] + rfl + +def selBytes : List Nat := wordToBytesBE selectorBytes (SolidCore.Solidity.Shared.norm transferWord) + +kernel_rfl selBytes_eq selBytes [169, 5, 156, 187] + +theorem selBytes_eq' : wordToBytesBE selectorBytes (SolidCore.Solidity.Shared.norm transferWord) = + [169, 5, 156, 187] := selBytes_eq + +/-- The input pay sends: transfer(to, amount). -/ +def payInput (dst amt : Nat) : List Nat := + [169, 5, 156, 187] ++ wordToBytesBE Solidity.Source.wordBytes dst ++ wordToBytesBE Solidity.Source.wordBytes amt + +theorem enc2 (dst amt : Nat) (hd : dst < 2 ^ 160) (ha : amt < 2 ^ 256) : + abiEncodeValues? [Ty.address, Ty.uint256] [.word dst, .word amt] = + some (wordToBytesBE Solidity.Source.wordBytes dst ++ wordToBytesBE Solidity.Source.wordBytes amt) := by + simp only [abiEncodeValues?, abiEncodeValuesAux?, show Ty.address.isDynamicAbi = false from rfl, + show Ty.uint256.isDynamicAbi = false from rfl, Bool.false_eq_true, ↓reduceIte, + show Ty.listAbiHeadWords? [Ty.address, Ty.uint256] = some 2 from rfl, Option.bind_eq_bind, Option.bind_some] + simp only [abiEncodeStaticValue?, abiStaticBytes?] + have hf : abiAddressFits dst = true := by + simp only [abiAddressFits, SolidCore.Solidity.Shared.norm] + have h1 : dst % SolidCore.Solidity.Shared.wordModulus = dst := + Nat.mod_eq_of_lt (lt_of_lt_of_le hd (by decide)) + exact decide_eq_true (by rw [h1]; exact hd) + rw [if_pos hf] + simp only [List.append_nil] + +theorem payEnc (n : Nat) (ctx : Context) (rt : Runtime) (dst amt : Nat) (hd : dst < 2 ^ 160) + (ha : amt < 2 ^ 256) + (hb1 : rt.lookupStorageBase? "to" = none) (hl1 : rt.lookupLocal? "to" = some (.word dst)) + (hb2 : rt.lookupStorageBase? "amount" = none) (hl2 : rt.lookupLocal? "amount" = some (.word amt)) : + Expr.evalFuel (n + 6) ctx rt (Expr.encode (EncodeKind.withSelector) (some transferSelE) [] [Ty.address, Ty.uint256] + [Expr.var "to", Expr.var "amount"]) = pure (.bytes (payInput dst amt), rt) := by + rw [Expr.evalFuel] + simp only [Expr.evalListFuel] + rw [selF, sbind_pure, show n + 3 = (n + 2) + 1 from rfl, varF _ _ _ _ _ hb1 hl1, sbind_pure, + show n + 2 = (n + 1) + 1 from rfl, varF _ _ _ _ _ hb2 hl2, sbind_pure] + simp only [sbind_pure, Value.expectWord, liftM, monadLift, MonadLift.monadLift, SolI.ofExcept] + simp only [Runtime.materializeForValueUseList, mat_word, bind, Except.bind, dbind, pure] + rw [enc2 dst amt hd ha] + simp only [selBytes_eq', payInput, List.append_assoc] + +/-- The low-level call pay makes. -/ +def payCallE : Expr := + Expr.lowLevelCall (SolidCore.Solidity.Shared.Call.ExternalCallKind.call) + (Expr.storageRead (StorageReadMode.ref) "token" []) + (Expr.encode (EncodeKind.withSelector) (some transferSelE) [] [Ty.address, Ty.uint256] + [Expr.var "to", Expr.var "amount"]) + (Expr.word 0) none false + +/-- pay's require condition. -/ +def payCond : Expr := + Expr.binary BinaryOp.boolAnd (Expr.var "ok") + (Expr.binary BinaryOp.boolOr + (Expr.binary BinaryOp.eq (Expr.castOp CastKind.uintCleanup 256 (Expr.length (Expr.var "ret"))) + (Expr.word 0)) + (Expr.abiDecode [Ty.bool] [AbiCleanup.none] (Expr.var "ret"))) + +/-- The inner block of pay. -/ +def payInner : List Stmt := + [Stmt.varDecl Ty.bool "ok" none, + Stmt.memoryVarDecl Ty.bytesCalldata "ret" none, + Stmt.varDecl (Ty.tuple [Ty.bool, Ty.bytesCalldata]) "__solidcore_low_level_return" (some payCallE), + Stmt.assignTuple [some (LValue.var "ok"), some (LValue.var "ret")] (Expr.var "__solidcore_low_level_return"), + Stmt.requireStmt payCond (some "TRANSFER_FAILED")] + +/-- pay's body, as the checker lowers it. -/ +def payBody : Stmt := + Stmt.block [Stmt.skip, + Stmt.assign (LValue.var "amount") (Expr.castOp CastKind.uintCleanup 256 (Expr.var "amount")), + Stmt.block payInner] + +theorem eval_skip (n : Nat) (tbl : FunctionTable) (ctx : Context) (rt : Runtime) : + Stmt.eval (n + 1) tbl ctx rt .skip = pure (Result.normal rt) := by + rw [Stmt.eval] + +theorem eval_varDecl_some (n : Nat) (tbl : FunctionTable) (ctx : Context) (rt : Runtime) + (ty : Ty) (x : String) (e : Expr) : + Stmt.eval (n + 1) tbl ctx rt (.varDecl ty x (some e)) = + ((Expr.eval ctx rt e).caught >>= fun r => + match r with + | Except.ok (value, runtime') => + match ty.coerceValue? value with + | some coerced => pure (Result.normal (runtime'.declareLocal x coerced)) + | none => pure (Result.reverted rt RevertData.typeMismatch) + | Except.error err => pure (Result.reverted rt err)) := by + rw [Stmt.eval]; dsimp only; rfl + +theorem eval_memoryVarDecl_none (n : Nat) (tbl : FunctionTable) (ctx : Context) (rt : Runtime) + (ty : Ty) (x : String) : + Stmt.eval (n + 1) tbl ctx rt (.memoryVarDecl ty x none) = + match rt.declareMemoryLocal ty x ty.defaultValue with + | some updated => pure (Result.normal updated) + | none => pure (Result.reverted rt RevertData.typeMismatch) := by + rw [Stmt.eval]; dsimp only; rfl + +theorem eval_require (n : Nat) (tbl : FunctionTable) (ctx : Context) (rt : Runtime) + (c : Expr) (m : Option String) : + Stmt.eval (n + 1) tbl ctx rt (.requireStmt c m) = + ((Expr.eval ctx rt c).caught >>= fun r => + match r with + | Except.ok (value, runtime') => + match value.expectWord with + | Except.ok word => + if wordTruthy word then pure (Result.normal runtime') + else match m with + | some message => pure (Result.reverted runtime' (RevertData.error message)) + | none => pure (Result.reverted runtime' RevertData.empty) + | Except.error err => pure (Result.reverted runtime' err) + | Except.error err => pure (Result.reverted rt err)) := by + rw [Stmt.eval]; dsimp only; rfl + +theorem eval_assign_var (n : Nat) (tbl : FunctionTable) (ctx : Context) (rt : Runtime) + (x : String) (e : Expr) : + Stmt.eval (n + 1) tbl ctx rt (.assign (.var x) e) = Stmt.eval (n + 1) tbl ctx rt (.assign (.var x) e) := rfl + + +theorem cleanup256 (c : Bool) (w : Nat) (hw : w < 2 ^ 256) : + uintCleanup? c 256 (.word w) = .ok (.word w) := by + have hn : SolidCore.Solidity.Shared.norm w = w := Nat.mod_eq_of_lt hw + have h2 : w < 115792089237316195423570985008687907853269984665640564039457584007913129639936 := hw + simp [uintCleanup?, Value.forceAbiLazy, Value.asStorageWord?, uintCast?, hn, bind, Except.bind, + Nat.not_le.mpr h2, Nat.mod_eq_of_lt h2] + +theorem castVar_eval (ctx : Context) (rt : Runtime) (x : String) (w : Nat) (hw : w < 2 ^ 256) + (hb : rt.lookupStorageBase? x = none) (hl : rt.lookupLocal? x = some (.word w)) : + Expr.eval ctx rt (Expr.castOp CastKind.uintCleanup 256 (Expr.var x)) = + EvmCompiler.Simulation.Interaction.done (.ok (.word w, rt)) := by + simp only [Expr.eval, Expr.orderFuel] + rw [Expr.evalFuel] + rw [show 0 + 1 + (0 + 1) = 1 + 1 from rfl, varF 1 ctx rt x w hb hl, sbind_pure] + simp only [liftM, monadLift, MonadLift.monadLift, SolI.ofExcept, cleanup256 _ w hw] + rfl + +theorem resolve_var (ctx : Context) (rt : Runtime) (x : String) (v : Value) + (hb : rt.lookupStorageBase? x = none) (hl : rt.lookupLocal? x = some v) : + (LValue.var x).resolveWithRuntime ctx rt = + EvmCompiler.Simulation.Interaction.done (.ok (.local x, rt)) := by + simp only [LValue.resolveWithRuntime, LValue.toExpr, Expr.resolveLValue, Expr.orderFuel] + rw [Expr.resolveLValueFuel] + simp only [hb, hl] + rfl + +theorem pay_amount (n : Nat) (tbl : FunctionTable) (ctx : Context) (rt : Runtime) (dst amt : Nat) + (ha : amt < 2 ^ 256) + (hl : rt.locals = [[], [("to", .word dst), ("amount", .word amt)]]) : + Stmt.eval (n + 1) tbl ctx rt + (Stmt.assign (LValue.var "amount") (Expr.castOp CastKind.uintCleanup 256 (Expr.var "amount"))) = + pure (Result.normal { rt with locals := [[], [("to", .word dst), ("amount", .word amt)]] }) := by + rw [Stmt.eval]; dsimp only + simp [LValue.wantsMemoryRefRhs, Runtime.lookupMemoryRef?, Runtime.lookupLocal?, hl, LocalEnv.lookup?, + Frame.lookup?] + rw [castVar_eval ctx rt "amount" amt ha (by simp [Runtime.lookupStorageBase?, Runtime.lookupLocal?, hl, LocalEnv.lookup?, Frame.lookup?]) + (by simp [Runtime.lookupLocal?, hl, LocalEnv.lookup?, Frame.lookup?])] + have hr := resolve_var ctx rt "amount" (.word amt) + (by simp [Runtime.lookupStorageBase?, Runtime.lookupLocal?, hl, LocalEnv.lookup?, Frame.lookup?]) + (by simp [Runtime.lookupLocal?, hl, LocalEnv.lookup?, Frame.lookup?]) + simp only [caught_done_ok, bind_done_ok, hr] + simp [ResolvedLValue.write, Runtime.assignLocal?, Runtime.lookupLocal?, hl, LocalEnv.lookup?, + Frame.lookup?, LocalEnv.assign?, Value.coerceLike?, Frame.assign?] + done + +/-- The runtime after bytes memory ret. -/ +def retRt (rt : Runtime) : Runtime := + { state := rt.state + locals := rt.locals.declare "ret" (Value.memoryRef rt.nextMemory) + memory := rt.memory.insertLoop rt.nextMemory (Value.bytes []) + nextMemory := rt.nextMemory + 1 + nextMemoryByte := rt.nextMemoryByte + (Value.bytes []).memoryAllocationBytes } + +theorem ret_decl (rt : Runtime) : + rt.declareMemoryLocal Ty.bytesCalldata "ret" Ty.bytesCalldata.defaultValue = + some (retRt rt) := by + simp [Runtime.declareMemoryLocal, Ty.defaultValue, Ty.coerceValue?, Runtime.memoryStoredValue, + Runtime.allocMemory, Runtime.declareLocal, retRt] + +theorem tokF (n : Nat) (ctx : Context) (rt : Runtime) (hf : AddrFieldOk ctx "token" tokenField) + (hw : rt.state.loadSlot tokenField.slot < Generic.wordSize) : + Expr.evalFuel (n + 1) ctx rt (Expr.storageRead .ref "token" []) = + pure (.word (fieldValue (rt.state.loadSlot tokenField.slot) tokenField.packedOffset 20), rt) := by + simp only [Expr.evalFuel] + simp only [load_addrField hf hw] + rfl + + +theorem tokF' (n : Nat) (ctx : Context) (rt' rt : Runtime) (hf : AddrFieldOk ctx "token" tokenField) + (hs : rt'.state = rt.state) (hw : rt.state.loadSlot tokenField.slot < Generic.wordSize) : + Expr.evalFuel (n + 1) ctx rt' (Expr.storageRead .ref "token" []) = + pure (.word (fieldValue (rt.state.loadSlot tokenField.slot) tokenField.packedOffset 20), rt') := by + rw [← hs]; exact tokF n ctx rt' hf (hs ▸ hw) + +theorem caught_request {α : Type} (q : EvmCompiler.Simulation.Query) + (k : EvmCompiler.Simulation.Answer q → SolI α) : + SolI.caught (EvmCompiler.Simulation.Interaction.request q k) = + EvmCompiler.Simulation.Interaction.request q (fun a => SolI.caught (k a)) := rfl + +theorem ipure_eq {α : Type} (x : α) : + (EvmCompiler.Simulation.Interaction.pure x : SolI α) = EvmCompiler.Simulation.Interaction.done (.ok x) := rfl + +theorem word0F (m : Nat) (ctx : Context) (rt : Runtime) : + Expr.evalFuel (m + 1) ctx rt (Expr.word 0) = pure (.word 0, rt) := by + rw [Expr.evalFuel] + rfl + +set_option maxHeartbeats 300000 in +theorem pay_req (n : Nat) (tbl : FunctionTable) (ctx : Context) (rt : Runtime) (dst amt : Nat) + (hd : dst < 2 ^ 160) (ha : amt < 2 ^ 256) + (hl : rt.locals = [[("to", .word dst), ("amount", .word amt)]]) + (hf : AddrFieldOk ctx "token" tokenField) (hw : rt.state.loadSlot tokenField.slot < Generic.wordSize) + (hcons : ctx.construction = false) + (hself : wordEq (SolidCore.Solidity.Shared.norm (fieldValue (rt.state.loadSlot tokenField.slot) tokenField.packedOffset 20)) ctx.self = false) : + ∃ k, Stmt.eval (n + 3) tbl ctx rt payBody = + .request (.external (snapshotWorld ctx rt.state) + (.call (buildCallRequest ctx .call (SolidCore.Solidity.Shared.norm (fieldValue (rt.state.loadSlot tokenField.slot) tokenField.packedOffset 20)) + (List.map normByte (payInput dst amt)) (SolidCore.Solidity.Shared.norm 0) none))) k := by + rw [payBody, eval_block, evalList_cons, show n + 2 = (n + 1) + 1 from rfl, eval_skip, sbind_pure] + dsimp only + rw [evalList_cons, pay_amount (n + 1) tbl ctx rt.pushScope dst amt ha (by simp [Runtime.pushScope, hl]), sbind_pure] + dsimp only + rw [evalList_cons, eval_block, payInner, evalList_cons, eval_varDecl_none, sbind_pure] + dsimp only + rw [evalList_cons, eval_memoryVarDecl_none, ret_decl] + dsimp only + rw [sbind_pure] + dsimp only + rw [evalList_cons, eval_varDecl_some] + rw [Expr.eval, show payCallE.orderFuel + 1 = 13 + 1 from rfl, payCallE, + eval_lowLevelCall 13 ctx _ _ _ _ false (tokF' 12 ctx _ rt hf ?hs hw) rfl (word0F 12 ctx _) rfl + (payEnc 7 ctx _ dst amt hd ha ?b1 ?l1 ?b2 ?l2) rfl hcons hself] + · simp only [caught_request, bind_request] + exact ⟨_, rfl⟩ + · rfl + all_goals simp [Runtime.lookupStorageBase?, Runtime.lookupLocal?, retRt, Runtime.declareLocal, Runtime.pushScope, + LocalEnv.declare, LocalEnv.lookup?, Frame.lookup?] + +/-- info: 'SolidCore.Refinement.CallFamilies.pay_req' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms pay_req + +end SolidCore.Refinement.CallFamilies diff --git a/Contracts/CallFamilies/SkimAgree.lean b/Contracts/CallFamilies/SkimAgree.lean new file mode 100644 index 00000000..266a2f82 --- /dev/null +++ b/Contracts/CallFamilies/SkimAgree.lean @@ -0,0 +1,513 @@ +import Contracts.CallFamilies.SkimRun +import Contracts.CallFamilies.SyncAgree +import SolarTV.MemorySymbolic + +/-! +# skim in solar's MIR under the oracle hypothesis + +mir_skim_agree: under CallsAgree o V, when SolidCore's run of skim(dst) in the world V asks V the +token's balanceOf(address(this)) (SyncAsk, the same call sync makes) and, when the balance read +returned a word at least the reserve, then asks V the token's transfer(dst, balance - reserve) with +the first exchange as history (PayAsk), solar's stage0 shows what SkimObs says: the bubbled revert, +the empty revert of a short return, the Panic(0x11) revert of the subtraction, the +Error("TRANSFER_FAILED") revert, the empty revert of a short or non-bool return word, or success with +the storage the transfer's answer leaves. Each call's agreement comes from CallsAgree, the second with +the first exchange as its history. +-/ + +namespace SolidCore.Refinement.CallFamilies.Skim + +open SolarTV SolarTV.Machine SolarTV.MIR.Lowered SolidCore.Refinement +open EvmCompiler.Simulation +open SolidCore.Solidity.Source (addressToWord u256ToWord byteArrayToBytes) + +set_option linter.deprecated false + +/-- The 32 big-endian bytes of a word. -/ +def wordBE (n : Nat) : List Nat := (List.range 32).map (fun i => n / 256 ^ (31 - i) % 256) + +/-- The amount skim transfers: the balance word less the reserve, as the MIR subtracts. -/ +def amtW (σ : List (Nat × Nat)) (a1 : CallResponse) : BitVec 256 := + Sync.retWord a1 - BitVec.ofNat 256 (slotValue σ 2) + +/-- The input of transfer(dst, amount). -/ +def transferInput (σ : List (Nat × Nat)) (dst : Nat) (a1 : CallResponse) : List Nat := + [169, 5, 156, 187] ++ wordBE dst ++ wordBE (amtW σ a1).toNat + +/-- The second call SolidCore's skim asks V, after the balance read: pay's transfer. -/ +structure PayAsk (σ : List (Nat × Nat)) (dst : Nat) (V : World) + (world1 : SolidCore.Solidity.Shared.OpenWorld) (request1 : CallRequest) (a1 : CallResponse) + (world : SolidCore.Solidity.Shared.OpenWorld) (request : CallRequest) (a : CallResponse) : Prop where + ans : V.ans [⟨.external world1 (.call request1), a1⟩] (.external world (.call request)) = some a + kind : request.kind = .call + callee : addressToWord request.codeAddress = slotValue σ 1 % 2 ^ 160 + value : u256ToWord request.transferValue = 0 + input : byteArrayToBytes request.calldata = transferInput σ dst a1 + storage : ∀ slot < 2 ^ 256, storageIn world slot = slotValue σ slot % 2 ^ 256 + transient : ∀ slot < 2 ^ 256, transientIn world slot = 0 + codes : ∀ x < 2 ^ 160, (codeIn world x).isEmpty = (codeIn a1.postWorld x).isEmpty + size : a.returnData.size < 2 ^ 64 + +/-- The balance read ends skim before the transfer. -/ +def Early (σ : List (Nat × Nat)) (a1 : CallResponse) : Prop := + a1.success = false ∨ a1.returnData.size < 32 ∨ (Sync.retWord a1).toNat < slotValue σ 2 + +def failObs (σ : List (Nat × Nat)) (data : List Nat) : Observable := ⟨false, data, [], slotValue σ⟩ + +/-- Panic(0x11). -/ +def panicData : List Nat := [0x4e, 0x48, 0x7b, 0x71] ++ wordBE 17 + +/-- Error("TRANSFER_FAILED"). -/ +def errData : List Nat := [0x08, 0xc3, 0x79, 0xa0] ++ wordBE 32 ++ wordBE 15 ++ + wordBE 38139611465464413496808033184516339178673403987523396430313160281336026497024 + +def obsEarly (σ : List (Nat × Nat)) (a1 : CallResponse) : Observable := + if a1.success then + if a1.returnData.size < 32 then failObs σ [] else failObs σ panicData + else failObs σ ((List.range a1.returnData.size).map (fun j => (a1.returnData.get! j).toNat)) + +def okObs (a : CallResponse) : Observable := ⟨true, [], [], fun slot => storageIn a.postWorld (slot % 2 ^ 256)⟩ + +def obsLate (σ : List (Nat × Nat)) (a : CallResponse) : Observable := + if a.success then + if a.returnData.size = 0 then okObs a + else if a.returnData.size < 32 then failObs σ [] + else if 1 < (Sync.retWord a).toNat then failObs σ [] + else if (Sync.retWord a).toNat = 0 then failObs σ errData + else okObs a + else failObs σ errData + +/-- What SolidCore's skim(dst) in V shows, by the calls it asks. -/ +def SkimObs (σ : List (Nat × Nat)) (dst : Nat) (V : World) (obs : Observable) : Prop := + ∃ world1 request1 a1, Sync.SyncAsk σ V world1 request1 a1 ∧ (Early σ a1 → obs = obsEarly σ a1) ∧ + (¬ Early σ a1 → ∃ world request a, PayAsk σ dst V world1 request1 a1 world request a ∧ obs = obsLate σ a) + +theorem T_eq (o : Oracle) (σ : List (Nat × Nat)) (dst : Nat) : S7 o (S0' σ dst) = Sync.S4 o σ := rfl + +theorem W1_eq (o : Oracle) (σ : List (Nat × Nat)) (dst : Nat) : W1 o (S0' σ dst) = Sync.W o σ := rfl + + + +theorem bytes_store (m : Mem) (off : Nat) (v : BitVec 256) (i : Nat) : + (m.store off v).bytes i = if off ≤ i ∧ i < off + 32 then Memory.byte v (i - off) else m.bytes i := by + unfold Mem.store + rw [Sync.bytes_expand] + +theorem byte_toNat (v : BitVec 256) (k : Nat) (hk : k < 32) : + (Memory.byte v k).toNat = v.toNat / 256 ^ (31 - k) % 256 := by + unfold Memory.byte + rw [BitVec.toNat_setWidth, BitVec.toNat_ushiftRight, Nat.shiftRight_eq_div_pow] + rw [show 2 ^ (8 * (31 - k)) = 256 ^ (31 - k) by rw [pow_mul]; norm_num] + +theorem wordBytes_toNat (v : BitVec 256) : (Mem.wordBytes v).map BitVec.toNat = wordBE v.toNat := by + unfold Mem.wordBytes wordBE + rw [List.map_map] + apply List.map_congr_left + intro i hi + rw [List.mem_range] at hi + exact byte_toNat v i hi + +theorem read_expand (m : Mem) (o z a b : Nat) : (m.expand o z).read a b = m.read a b := by + simp only [Mem.read, Sync.bytes_expand] + +/-- The last four bytes of the word stored at 0, as a revert from 28 reads them. -/ +theorem read28 (m : Mem) (w : BitVec 256) : + ((m.store 0 w).read 28 4).map BitVec.toNat = + [w.toNat / 256 ^ 3 % 256, w.toNat / 256 ^ 2 % 256, w.toNat / 256 % 256, w.toNat % 256] := by + simp only [Mem.read, List.range_succ, List.range_zero, List.nil_append, List.map_cons, List.map_nil, bytes_store] + simp [byte_toNat] + +theorem read_split (m : Mem) (a k l n : Nat) (h : n = k + l) : m.read a n = m.read a k ++ m.read (a + k) l := by + subst h; exact Mem.read_append m a k l + +theorem err_data (s : State) : revertData (errHalt s).1 = errData := by + simp only [errHalt, halt, if_true, revertData, read_expand] + rw [show BitVec.toNat (28 : BitVec 256) = 28 from rfl, show BitVec.toNat (100 : BitVec 256) = 100 from rfl, + read_split _ 28 4 96 100 rfl, read_split _ 32 32 64 96 rfl, read_split _ 64 32 32 64 rfl] + simp only [List.map_append, read28] + rw [Mem.read_store_disjoint _ 0 _ 32 32 (Or.inr (by norm_num)), Mem.read_store_disjoint _ 96 _ 32 32 (Or.inl (by norm_num)), + Mem.read_store_disjoint _ 64 _ 32 32 (Or.inl (by norm_num)), Mem.read_store_same, + Mem.read_store_disjoint _ 0 _ 64 32 (Or.inr (by norm_num)), Mem.read_store_disjoint _ 96 _ 64 32 (Or.inl (by norm_num)), + Mem.read_store_same, + Mem.read_store_disjoint _ 0 _ 96 32 (Or.inr (by norm_num)), Mem.read_store_same] + simp only [wordBytes_toNat, errData, List.append_assoc] + rfl + +theorem panic_data (s : State) : + revertData (halt { s with memory := (s.memory.store 32 17#256).store 0 0x4e487b71#256 } 28 36 true).1 = panicData := by + simp only [halt, if_true, revertData, read_expand] + rw [show BitVec.toNat (28 : BitVec 256) = 28 from rfl, show BitVec.toNat (36 : BitVec 256) = 36 from rfl, + read_split _ 28 4 32 36 rfl] + simp only [List.map_append, read28] + rw [Mem.read_store_disjoint _ 0 _ 32 32 (Or.inr (by norm_num)), Mem.read_store_same] + simp only [wordBytes_toNat, panicData] + rfl + +theorem in2_eq (m : Mem) (a b : BitVec 256) : + (in2 m a b).map BitVec.toNat = [169, 5, 156, 187] ++ wordBE a.toNat ++ wordBE b.toNat := by + simp only [in2, PM, read_expand] + rw [read_split _ 160 4 64 68 rfl, read_split _ 164 32 32 64 rfl] + rw [Mem.read_store_same, Mem.read_store_disjoint _ 196 _ 164 32 (Or.inl (by norm_num)), Mem.read_store_same, + Mem.read_store_disjoint _ 196 _ 160 4 (Or.inl (by norm_num)), Mem.read_store_disjoint _ 164 _ 160 4 (Or.inl (by norm_num))] + simp only [List.map_append, wordBytes_toNat, List.append_assoc] + congr 1 + +theorem sem_skim (o : Oracle) (σ : List (Nat × Nat)) (dst : Nat) (hd : dst < 2 ^ 160) + (hr : callFlag o (W1 o (S0' σ dst)) ≠ 0#256 → + EvmRules.Evm.lt (o.env "returndatasize" (S7 o (S0' σ dst)).world []) 32#256 = 0#256 → + EvmRules.Evm.lt ((S7 o (S0' σ dst)).memory.load 0) ((S7 o (S0' σ dst)).storage 2#256) = 0#256 → + (rds2 o { S7 o (S0' σ dst) with memory := (S7 o (S0' σ dst)).memory.expand 0 32 } (BitVec.ofNat 256 dst) + (EvmRules.Evm.sub ((S7 o (S0' σ dst)).memory.load 0) ((S7 o (S0' σ dst)).storage 2#256))).toNat < 2 ^ 64) : + (moduleSem o).run SolarTV.Export.Calls.stage0 (skimCall σ dst) = + some (observe (skimCall σ dst) (mirEnd o σ dst).2 (mirEnd o σ dst).1) := by + show (moduleLayer.result o _ _).map _ = _ + rw [moduleLayer.result_of_ends (show moduleLayer.Ends o SolarTV.Export.Calls.stage0 (skimCall σ dst) (mirEnd o σ dst) + from ⟨20, run_skim o σ dst hd hr⟩)] + rfl + +/-- The first call's agreement, with the code the second call sees. -/ +theorem answer1 (o : Oracle) (V : World) (σ : List (Nat × Nat)) + (world : SolidCore.Solidity.Shared.OpenWorld) (request : CallRequest) (a : CallResponse) + (agree : CallsAgree o V) (hs : Sync.SyncAsk σ V world request a) : + CodesAgree o (Sync.W o σ ++ [.read "gas"]) (codeIn a.postWorld) := by + have hcalls : machineCalls (Sync.W o σ) = + sourceCalls ([] ++ [⟨.external world (.call request), a⟩]) := by + simp only [Sync.W, machineCalls, sourceCalls, List.nil_append, hs.kind, hs.callee, hs.value, hs.input, + machineKind, List.getD] + simp + have hstore : ∀ slot < 2 ^ 256, + ((State.initial (Sync.syncCall σ)).storage (BitVec.ofNat 256 slot)).toNat = storageIn world slot ∧ + ((fun _ => (0 : BitVec 256)) (BitVec.ofNat 256 slot)).toNat = transientIn world slot := by + intro slot hslot + refine ⟨?_, ?_⟩ + · rw [hs.storage slot hslot] + simp only [State.initial, BitVec.toNat_ofNat] + rw [Nat.mod_eq_of_lt hslot] + rfl + · rw [hs.transient slot hslot]; rfl + have hcodes : CodesAgree o (Sync.W o σ).dropLast (codeIn world) := by + intro x hx + rw [hs.codes x hx] + exact agree.codes [.read "gas"] rfl x hx + obtain ⟨-, -, hrest⟩ := agree.calls [] world request a hs.ans (Sync.W o σ) .staticcall _ _ _ _ + rfl hcalls hstore hcodes + obtain ⟨-, -, hc⟩ := hrest [.read "gas"] rfl + intro x hx + rw [hc x hx] + rfl + + +/-- The second call's agreement: pay's CALL of transfer, with the balance read as its history. -/ +theorem answer2 (o : Oracle) (V : World) (σ : List (Nat × Nat)) (dst : Nat) (hd : dst < 2 ^ 160) + (world1 : SolidCore.Solidity.Shared.OpenWorld) (request1 : CallRequest) (a1 : CallResponse) + (world : SolidCore.Solidity.Shared.OpenWorld) (request : CallRequest) (a : CallResponse) + (agree : CallsAgree o V) (hs : Sync.SyncAsk σ V world1 request1 a1) + (hp : PayAsk σ dst V world1 request1 a1 world request a) (s : State) + (hsw : s.world = Sync.W o σ) (hss : s.storage = (State.initial (Sync.syncCall σ)).storage) + (hst : s.transient = fun _ => 0) (amt : BitVec 256) (hamt : amt = amtW σ a1) : + ((callFlag o (W2 o s (BitVec.ofNat 256 dst) amt) = 1) ↔ a.success = true) ∧ + (∀ slot < 2 ^ 256, (o.storageAfter (W2 o s (BitVec.ofNat 256 dst) amt) (BitVec.ofNat 256 slot)).toNat = + storageIn a.postWorld slot) ∧ + (rds2 o s (BitVec.ofNat 256 dst) amt).toNat = a.returnData.size ∧ + ∀ j < a.returnData.size, + (returndataByte o (W2 o s (BitVec.ofNat 256 dst) amt) j).toNat = (a.returnData.get! j).toNat := by + have hd' : dst < 2 ^ 256 := by omega + have hin : (in2 s.memory (BitVec.ofNat 256 dst) amt).map BitVec.toNat = byteArrayToBytes request.calldata := by + rw [in2_eq, hp.input, transferInput, hamt, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hd'] + have hcalls : machineCalls (W2 o s (BitVec.ofNat 256 dst) amt) = + sourceCalls ([⟨.external world1 (.call request1), a1⟩] ++ [⟨.external world (.call request), a⟩]) := by + simp only [W2, hsw, Sync.W, List.cons_append, List.nil_append, machineCalls, sourceCalls, hs.kind, hs.callee, + hs.value, hs.input, hp.kind, hp.callee, hp.value, ← hin, machineKind, List.getD, hss] + simp [State.initial, Sync.syncCall] + have hstore : ∀ slot < 2 ^ 256, + (s.storage (BitVec.ofNat 256 slot)).toNat = storageIn world slot ∧ + (s.transient (BitVec.ofNat 256 slot)).toNat = transientIn world slot := by + intro slot hslot + refine ⟨?_, ?_⟩ + · rw [hp.storage slot hslot, hss] + simp only [State.initial, BitVec.toNat_ofNat] + rw [Nat.mod_eq_of_lt hslot] + rfl + · rw [hp.transient slot hslot, hst]; rfl + have hcodes : CodesAgree o (W2 o s (BitVec.ofNat 256 dst) amt).dropLast (codeIn world) := by + have h1 := answer1 o V σ world1 request1 a1 agree hs + have hdl : (W2 o s (BitVec.ofNat 256 dst) amt).dropLast = Sync.W o σ ++ [.read "gas"] := by + simp [W2, hsw] + rw [hdl] + intro x hx + rw [hp.codes x hx] + exact h1 x hx + obtain ⟨hflag, hsto, hrest⟩ := agree.calls [⟨.external world1 (.call request1), a1⟩] world request a hp.ans + (W2 o s (BitVec.ofNat 256 dst) amt) .call _ _ _ _ (by simp [W2]; exact ⟨rfl, rfl⟩) hcalls hstore hcodes + obtain ⟨hsz, hby, -⟩ := hrest [] rfl + simp only [List.append_nil] at hsz hby + have hsmall : a.returnData.size < 2 ^ 256 := lt_trans hp.size (by norm_num) + refine ⟨hflag, fun slot hslot => (hsto (by rw [hp.kind]; decide) slot hslot).1, ?_, fun j hj => hby j hj (lt_trans hj hsmall)⟩ + rw [rds2, ← returndataSize, hsz, Nat.mod_eq_of_lt hsmall] + + +theorem obs_empty (call : Call) (s : State) : + observe call (halt s 0 0 true).2 (halt s 0 0 true).1 = ⟨false, [], [], slotValue call.storage⟩ := by + simp [halt, observe, Mem.read] + +theorem obs_panic (call : Call) (s : State) : + observe call (halt { s with memory := (s.memory.store 32 17#256).store 0 0x4e487b71#256 } 28 36 true).2 + (halt { s with memory := (s.memory.store 32 17#256).store 0 0x4e487b71#256 } 28 36 true).1 = + ⟨false, panicData, [], slotValue call.storage⟩ := by + have h := panic_data s + simp only [halt, if_true, revertData] at h + simp only [halt, if_true, observe, h] + +theorem obs_err (call : Call) (s : State) : + observe call (errHalt s).2 (errHalt s).1 = ⟨false, errData, [], slotValue call.storage⟩ := by + have h := err_data s + simp only [errHalt, halt, if_true, revertData] at h + simp only [errHalt, halt, if_true, observe, h] + +theorem obs_panic' (call : Call) (m : Mem) (st tr : BitVec 256 → BitVec 256) (w : List Event) : + observe call (halt ⟨(m.store 32 17#256).store 0 0x4e487b71#256, st, tr, w⟩ 28 36 true).2 + (halt ⟨(m.store 32 17#256).store 0 0x4e487b71#256, st, tr, w⟩ 28 36 true).1 = + ⟨false, panicData, [], slotValue call.storage⟩ := + obs_panic call ⟨m, st, tr, w⟩ + +theorem slt_small (a b : BitVec 256) (ha : a.toNat < 2 ^ 255) (hb : b.toNat < 2 ^ 255) : + EvmRules.Evm.slt a b = EvmRules.Evm.lt a b := by + have hma : a.msb = false := by rw [BitVec.msb_eq_false_iff_two_mul_lt]; omega + have hmb : b.msb = false := by rw [BitVec.msb_eq_false_iff_two_mul_lt]; omega + simp only [EvmRules.Evm.slt, EvmRules.Evm.lt, BitVec.slt_eq_ult, hma, hmb] + simp + +theorem load288 (o : Oracle) (s : State) (a b : BitVec 256) (a2 : CallResponse) (h32 : 32 ≤ a2.returnData.size) + (hsz : (rds2 o s a b).toNat = a2.returnData.size) + (hby : ∀ j < a2.returnData.size, (returndataByte o (W2 o s a b) j).toNat = (a2.returnData.get! j).toNat) : + (((S8 o s a b).memory.expand 256 32).expand 256 32).load 288 = Sync.retWord a2 := by + unfold Mem.load Mem.read Sync.retWord + congr 1 + apply List.map_congr_left + intro i hi + rw [List.mem_range] at hi + rw [Sync.bytes_expand, Sync.bytes_expand] + simp only [S8] + rw [Sync.bytes_write, if_pos (by rw [hsz]; omega)] + apply BitVec.eq_of_toNat_eq + rw [show 0 + (288 + i - 288) = i by omega, hby i (by omega), BitVec.toNat_ofNat, Nat.mod_eq_of_lt (UInt8.toNat_lt _)] + +theorem logs_S8 (o : Oracle) (s : State) (a b : BitVec 256) (m : Mem) (hw : s.world = Sync.W o σ) : + logs { S8 o s a b with memory := m } = [] := by + simp [logs, S8, W2, hw, Sync.W] + +theorem storage_ok (o : Oracle) (W : List Event) (a2 : CallResponse) + (hsto : ∀ slot < 2 ^ 256, (o.storageAfter W (BitVec.ofNat 256 slot)).toNat = storageIn a2.postWorld slot) : + (fun slot => (o.storageAfter W (BitVec.ofNat 256 slot)).toNat) = fun slot => storageIn a2.postWorld (slot % 2 ^ 256) := by + funext slot + rw [← hsto (slot % 2 ^ 256) (Nat.mod_lt _ (by norm_num))] + congr 2 + apply BitVec.eq_of_toNat_eq + simp + + +/-- **skim's MIR under the oracle hypothesis.** -/ +theorem mir_skim_agree (o : Oracle) (V : World) (σ : List (Nat × Nat)) (dst : Nat) (hd : dst < 2 ^ 160) + (agree : CallsAgree o V) (obs : Observable) (h : SkimObs σ dst V obs) : + (moduleSem o).run SolarTV.Export.Calls.stage0 (skimCall σ dst) = some obs := by + obtain ⟨w1, r1, a1, hs1, hE, hL⟩ := h + obtain ⟨hflag1, hsize1, hbytes1⟩ := Sync.answer o V σ w1 r1 a1 agree hs1 + have hlt := SolidCore.Refinement.Evm.Wide.slotValue_lt σ + have hf0 : callFlag o (Sync.W o σ) = 0#256 ↔ a1.success = false := by + constructor + · intro h0 + cases hs : a1.success + · rfl + · have := hflag1.mpr hs; rw [h0] at this; exact absurd this (by decide) + · intro hf + rcases Sync.callFlag_cases o (Sync.W o σ) with h' | h' + · exact h' + · rw [hflag1.mp h'] at hf; cases hf + have hsz1 : (o.env "returndatasize" (Sync.S4 o σ).world []).toNat = a1.returnData.size := hsize1 + have hlt1 : EvmRules.Evm.lt (o.env "returndatasize" (Sync.S4 o σ).world []) 32#256 = 0#256 ↔ ¬ a1.returnData.size < 32 := by + rw [Sync.lt_word, hsz1] + by_cases hc : a1.returnData.size < 32 <;> simp [hc] + have hload1 : 32 ≤ a1.returnData.size → (Sync.M4 o σ).load 0 = Sync.retWord a1 := by + intro hge + unfold Mem.load Mem.read Sync.retWord + congr 1 + apply List.map_congr_left + intro i hi + rw [List.mem_range] at hi + have hmin : min 32 (returndataSize o (Sync.W o σ)).toNat = 32 := by rw [hsize1]; omega + rw [Sync.M4, Sync.bytes_write, hmin] + simp only [Nat.zero_le, Nat.zero_add, hi, and_self, if_true, Nat.sub_zero] + apply BitVec.eq_of_toNat_eq + rw [hbytes1 i (by omega), BitVec.toNat_ofNat, Nat.mod_eq_of_lt (UInt8.toNat_lt _)] + have hst2 : ((Sync.S4 o σ).storage 2#256).toNat = slotValue σ 2 := by + show (BitVec.ofNat 256 (slotValue σ (2#256).toNat)).toNat = slotValue σ 2 + rw [BitVec.toNat_ofNat]; exact Nat.mod_eq_of_lt (hlt 2) + have hlt2 : 32 ≤ a1.returnData.size → + (EvmRules.Evm.lt ((Sync.S4 o σ).memory.load 0) ((Sync.S4 o σ).storage 2#256) = 0#256 ↔ + ¬ (Sync.retWord a1).toNat < slotValue σ 2) := by + intro hge + rw [Sync.lt_word, show (Sync.S4 o σ).memory = Sync.M4 o σ from rfl, hload1 hge, hst2] + by_cases hc : (Sync.retWord a1).toNat < slotValue σ 2 <;> simp [hc] + have hamt : 32 ≤ a1.returnData.size → + EvmRules.Evm.sub ((Sync.S4 o σ).memory.load 0) ((Sync.S4 o σ).storage 2#256) = amtW σ a1 := by + intro hge + rw [show (Sync.S4 o σ).memory = Sync.M4 o σ from rfl, hload1 hge] + rfl + have late : ∀ (hsucc : a1.success = true) (hge : 32 ≤ a1.returnData.size) + (hres : ¬ (Sync.retWord a1).toNat < slotValue σ 2), ¬ Early σ a1 := by + intro hsucc hge hres he + rcases he with he | he | he + · rw [hsucc] at he; cases he + · omega + · exact hres he + have hr : callFlag o (W1 o (S0' σ dst)) ≠ 0#256 → + EvmRules.Evm.lt (o.env "returndatasize" (S7 o (S0' σ dst)).world []) 32#256 = 0#256 → + EvmRules.Evm.lt ((S7 o (S0' σ dst)).memory.load 0) ((S7 o (S0' σ dst)).storage 2#256) = 0#256 → + (rds2 o { S7 o (S0' σ dst) with memory := (S7 o (S0' σ dst)).memory.expand 0 32 } (BitVec.ofNat 256 dst) + (EvmRules.Evm.sub ((S7 o (S0' σ dst)).memory.load 0) ((S7 o (S0' σ dst)).storage 2#256))).toNat < 2 ^ 64 := by + rw [T_eq, W1_eq] + intro c1 c2 c4 + have hsucc : a1.success = true := by + cases hs : a1.success + · exact absurd (hf0.mpr hs) c1 + · rfl + have hge : 32 ≤ a1.returnData.size := by have := hlt1.mp c2; omega + have hres := (hlt2 hge).mp c4 + obtain ⟨w2, r2, a2, hp, -⟩ := hL (late hsucc hge hres) + obtain ⟨-, -, hsz2, -⟩ := answer2 o V σ dst hd w1 r1 a1 w2 r2 a2 agree hs1 hp + { Sync.S4 o σ with memory := (Sync.S4 o σ).memory.expand 0 32 } rfl rfl rfl _ (hamt hge) + rw [hsz2]; exact hp.size + rw [sem_skim o σ dst hd hr] + congr 1 + unfold mirEnd + rw [T_eq, W1_eq] + by_cases hsucc : a1.success = true + swap + · have hf : a1.success = false := by simpa using hsucc + rw [if_pos (hf0.mpr hf), hE (Or.inl hf)] + simp only [obsEarly, hsucc, if_false, failObs, halt, if_true, observe] + congr 1 + rw [hsz1] + unfold Mem.read + rw [List.map_map] + apply List.map_congr_left + intro i hi + rw [List.mem_range] at hi + simp only [Function.comp, Sync.bytes_expand, Sync.bytes_write, Nat.zero_le, Nat.zero_add] + simp [hi] + exact hbytes1 i hi + have c1 : ¬ callFlag o (Sync.W o σ) = 0#256 := fun h0 => by rw [hf0.mp h0] at hsucc; cases hsucc + rw [if_neg c1] + by_cases hsmall : a1.returnData.size < 32 + · rw [if_neg (fun c => hlt1.mp c hsmall), hE (Or.inr (Or.inl hsmall))] + simp only [obsEarly, hsucc, if_true, hsmall] + rw [obs_empty]; rfl + have hge : 32 ≤ a1.returnData.size := by omega + rw [if_pos (hlt1.mpr hsmall)] + by_cases hres : (Sync.retWord a1).toNat < slotValue σ 2 + · rw [if_neg (fun c => (hlt2 hge).mp c hres), hE (Or.inr (Or.inr hres))] + simp only [obsEarly, hsucc, if_true, hsmall, if_false] + rw [obs_panic']; rfl + rw [if_pos ((hlt2 hge).mpr hres)] + obtain ⟨w2, r2, a2, hp, hobs⟩ := hL (late hsucc hge hres) + rw [hobs] + obtain ⟨hflag2, hsto2, hsz2, hby2⟩ := answer2 o V σ dst hd w1 r1 a1 w2 r2 a2 agree hs1 hp + { Sync.S4 o σ with memory := (Sync.S4 o σ).memory.expand 0 32 } rfl rfl rfl _ (hamt hge) + by_cases hs2 : a2.success = true + swap + · have c5 : callFlag o (W2 o { Sync.S4 o σ with memory := (Sync.S4 o σ).memory.expand 0 32 } (BitVec.ofNat 256 dst) + (EvmRules.Evm.sub ((Sync.S4 o σ).memory.load 0) ((Sync.S4 o σ).storage 2#256))) = 0#256 := by + rcases Sync.callFlag_cases o (W2 o _ _ _) with h' | h' + · exact h' + · exact absurd (hflag2.mp h') hs2 + rw [if_pos c5] + simp only [obsLate, hs2, if_false] + rw [obs_err]; rfl + have c5 : ¬ callFlag o (W2 o { Sync.S4 o σ with memory := (Sync.S4 o σ).memory.expand 0 32 } (BitVec.ofNat 256 dst) + (EvmRules.Evm.sub ((Sync.S4 o σ).memory.load 0) ((Sync.S4 o σ).storage 2#256))) = 0#256 := by + intro h0; have := hflag2.mpr hs2; rw [h0] at this; exact absurd this (by decide) + rw [if_neg c5] + have hsmall2 := hp.size + have hok : ∀ m : Mem, observe (skimCall σ dst) + { S8 o { Sync.S4 o σ with memory := (Sync.S4 o σ).memory.expand 0 32 } (BitVec.ofNat 256 dst) + (EvmRules.Evm.sub ((Sync.S4 o σ).memory.load 0) ((Sync.S4 o σ).storage 2#256)) with memory := m } .stop = + okObs a2 := by + intro m + simp only [observe, okObs] + rw [logs_S8 (σ := σ) _ _ _ _ m rfl] + congr 1 + exact storage_ok o _ a2 hsto2 + by_cases hz : a2.returnData.size = 0 + · have c6 : ¬ EvmRules.Evm.eq (rds2 o { Sync.S4 o σ with memory := (Sync.S4 o σ).memory.expand 0 32 } + (BitVec.ofNat 256 dst) (EvmRules.Evm.sub ((Sync.S4 o σ).memory.load 0) ((Sync.S4 o σ).storage 2#256))) 0#256 + = 0#256 := by + have h0 : rds2 o { Sync.S4 o σ with memory := (Sync.S4 o σ).memory.expand 0 32 } (BitVec.ofNat 256 dst) + (EvmRules.Evm.sub ((Sync.S4 o σ).memory.load 0) ((Sync.S4 o σ).storage 2#256)) = 0#256 := by + apply BitVec.eq_of_toNat_eq; rw [hsz2, hz]; rfl + rw [h0, eq_self']; decide + rw [if_neg c6] + simp only [obsLate, hs2, if_true, hz] + rw [hok] + have c6 : EvmRules.Evm.eq (rds2 o { Sync.S4 o σ with memory := (Sync.S4 o σ).memory.expand 0 32 } + (BitVec.ofNat 256 dst) (EvmRules.Evm.sub ((Sync.S4 o σ).memory.load 0) ((Sync.S4 o σ).storage 2#256))) 0#256 + = 0#256 := by + simp only [EvmRules.Evm.eq] + have : ¬ (rds2 o { Sync.S4 o σ with memory := (Sync.S4 o σ).memory.expand 0 32 } (BitVec.ofNat 256 dst) + (EvmRules.Evm.sub ((Sync.S4 o σ).memory.load 0) ((Sync.S4 o σ).storage 2#256)) = 0#256) := by + intro h0; apply hz; rw [← hsz2, h0]; rfl + simp [this] + rw [if_pos c6] + have hslt : ∀ r : BitVec 256, r.toNat = a2.returnData.size → + (EvmRules.Evm.slt r 32#256 = 0#256 ↔ ¬ a2.returnData.size < 32) := by + intro r hr + rw [slt_small r 32#256 (by omega) (by decide), Sync.lt_word, hr] + by_cases hc : a2.returnData.size < 32 <;> simp [hc] + by_cases hsm2 : a2.returnData.size < 32 + · rw [if_neg (fun c => (hslt _ hsz2).mp c hsm2)] + simp only [obsLate, hs2, if_true, hz, if_false, hsm2] + rw [obs_empty]; rfl + rw [if_pos ((hslt _ hsz2).mpr hsm2)] + have hl288 := load288 o { Sync.S4 o σ with memory := (Sync.S4 o σ).memory.expand 0 32 } (BitVec.ofNat 256 dst) + (EvmRules.Evm.sub ((Sync.S4 o σ).memory.load 0) ((Sync.S4 o σ).storage 2#256)) a2 (by omega) hsz2 hby2 + simp only [hl288] + by_cases hgt : 1 < (Sync.retWord a2).toNat + · rw [if_neg (by simp [EvmRules.Evm.gt, BitVec.ult, hgt])] + simp only [obsLate, hs2, if_true, hz, if_false, hsm2, hgt] + rw [obs_empty]; rfl + rw [if_pos (by simp [EvmRules.Evm.gt, BitVec.ult, hgt])] + by_cases hz2 : (Sync.retWord a2).toNat = 0 + · have hw0 : Sync.retWord a2 = 0#256 := BitVec.eq_of_toNat_eq (by rw [hz2]; rfl) + rw [if_pos (by rw [hw0]; exact ne_self' _)] + simp only [obsLate, hs2, if_true, hz, if_false, hsm2, hgt, hz2] + rw [obs_err]; rfl + · have hw0 : Sync.retWord a2 ≠ 0#256 := fun h0 => hz2 (by rw [h0]; rfl) + rw [if_neg (by simp [EvmRules.Evm.ne, hw0])] + simp only [obsLate, hs2, if_true, hz, if_false, hsm2, hgt, hz2] + rw [hok] + +/-- info: 'SolidCore.Refinement.CallFamilies.Skim.mir_skim_agree' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms mir_skim_agree + + +/-- The source half of skim's stage in the world V from the storage σ, for the recipient dst: +SolidCore's run of skim(dst) asks V the calls SkimObs describes and shows what it says. -/ +def SkimSource (fuel : Nat) (c : SolidCore.Solidity.TypeCheck.CheckedContract) (V : World) + (σ : List (Nat × Nat)) (dst : Nat) : Prop := + ∀ obs, Source.runIn V fuel c (skimCall σ dst) = some obs → SkimObs σ dst V obs + +/-- **skim's source stage from its source half**, under every oracle that agrees with V. -/ +theorem skim_stage (fuel : Nat) (c : SolidCore.Solidity.TypeCheck.CheckedContract) (V : World) + (scope : List (Nat × Nat) → Nat → Prop) (hscope : ∀ σ dst, scope σ dst → dst < 2 ^ 160) + (src : ∀ σ dst, scope σ dst → SkimSource fuel c V σ dst) + (o : Oracle) (agree : CallsAgree o V) : + Stage (solidCoreIn V fuel) (moduleSem o) c SolarTV.Export.Calls.stage0 + (fun call => ∃ σ dst, scope σ dst ∧ call = skimCall σ dst) := by + rintro call ⟨σ, dst, hσ, rfl⟩ obs hrun + exact mir_skim_agree o V σ dst (hscope σ dst hσ) agree obs (src σ dst hσ obs hrun) + +/-- info: 'SolidCore.Refinement.CallFamilies.Skim.skim_stage' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms skim_stage + +end SolidCore.Refinement.CallFamilies.Skim diff --git a/Contracts/CallFamilies/SkimFacts.lean b/Contracts/CallFamilies/SkimFacts.lean new file mode 100644 index 00000000..c9e9bf43 --- /dev/null +++ b/Contracts/CallFamilies/SkimFacts.lean @@ -0,0 +1,50 @@ +import Contracts.CallFamilies.SourceFacts +import Contracts.CallFamilies.SkimSource + +/-! +# skim's source stage for Calls's checked core + +The hypotheses skim_stage_in takes of the checked contract hold of SolidCore's checked Calls: one +kernel_rfl of the type checker gives skim's body and pay's table entry (skimFn, payFn), the rest +comes from calls_facts. calls_skim_stage is the stage with only the world's hypotheses left: +CallsAgree o V, seeded code at addresses below 2 ^ 160, return data shorter than 2 ^ 64 bytes. +-/ + +namespace SolidCore.Refinement.CallFamilies + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Refinement.CallNode +open SolidCore.Solidity.Source EvmCompiler.Simulation +open SolidCore.Verify.VC.Calls (contract? fuel) + +/-- skim's and pay's entries in the checked Calls. -/ +def skimFacts : Option (Option FunctionDef × Option InternalFunction) := + match contract? with + | .ok c => some (c.core.findFunctionBySelector? 3156594551, c.core.table.lookup? payName) + | .error _ => none + +kernel_rfl skimFacts_eq skimFacts (some (some skimFn, some payFn)) using SolidCore.Verify.VC.Calls.selector_eq SolidCore.Verify.VC.mkIdx_eq + +/-- **skim's source stage for Calls**: SolidCore's checked Calls in a world V refines solar's stage0 +on skim(dst) under every oracle agreeing with V, for every recipient below 2 ^ 160 and every storage +whose token is not the contract itself. -/ +theorem calls_skim_stage : ∃ c, contract? = .ok c ∧ ∀ (V : World), + (∀ p ∈ V.codes.getD [], p.1 < 2 ^ 160) → + (∀ h world request a, V.ans h (.external world (.call request)) = some a → + a.returnData.size < 2 ^ 64) → + ∀ (o : Machine.Oracle), CallsAgree o V → + Stage (solidCoreIn V fuel) (MIR.Lowered.moduleSem o) c SolarTV.Export.Calls.stage0 + (fun call => ∃ σ dst, (dst < 2 ^ 160 ∧ slotValue σ 1 % 2 ^ 160 ≠ selfAddress) ∧ + call = Skim.skimCall σ dst) := by + obtain ⟨c, hc, -, -, h3, hb, hh, hcc, d, hd, hdt, hde⟩ := calls_facts + have h := skimFacts_eq + unfold skimFacts at h + rw [hc] at h + simp only [Option.some.injEq, Prod.mk.injEq] at h + exact ⟨c, hc, fun V hk hs o agree => + skim_stage_in 4088 V hd h.1 h.2 h3 hdt hde hb hh hcc hk hs o agree⟩ + +/-- info: 'SolidCore.Refinement.CallFamilies.calls_skim_stage' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms calls_skim_stage + +end SolidCore.Refinement.CallFamilies diff --git a/Contracts/CallFamilies/SkimMir.lean b/Contracts/CallFamilies/SkimMir.lean new file mode 100644 index 00000000..336aff75 --- /dev/null +++ b/Contracts/CallFamilies/SkimMir.lean @@ -0,0 +1,448 @@ +import Contracts.CallFamilies.SyncSource +import SolidCore.Refinement.KernelThm + +open SolidCore.Refinement.Kernel +open SolarTV SolarTV.Machine SolarTV.MIR.Lowered + +namespace SolidCore.Refinement.CallFamilies.Skim + +set_option linter.deprecated false + +def skimCall (σ : List (Nat × Nat)) (dst : Nat) : Call := + SolidCore.Refinement.Evm.Wide.callAt 0xbc25cf77 [BitVec.ofNat 256 dst] σ + +abbrev step (o : Oracle) (σ : List (Nat × Nat)) (dst : Nat) := + moduleBlock o (skimCall σ dst) SolarTV.Export.Calls.stage0 + +def fn5 : Function := (SolarTV.Export.Calls.stage0.functions[5]?).getD ⟨[], [], none⟩ +def fn8 : Function := (SolarTV.Export.Calls.stage0.functions[8]?).getD ⟨[], [], none⟩ +def fn9 : Function := (SolarTV.Export.Calls.stage0.functions[9]?).getD ⟨[], [], none⟩ +def fn10 : Function := (SolarTV.Export.Calls.stage0.functions[10]?).getD ⟨[], [], none⟩ +kernel_thm fn5_eq : SolarTV.Export.Calls.stage0.functions[5]? = some fn5 +kernel_thm fn8_eq : SolarTV.Export.Calls.stage0.functions[8]? = some fn8 +kernel_thm fn9_eq : SolarTV.Export.Calls.stage0.functions[9]? = some fn9 +kernel_thm fn10_eq : SolarTV.Export.Calls.stage0.functions[10]? = some fn10 +kernel_thm fn5_params : fn5.params = [] +kernel_thm fn8_params : fn8.params = [0, 100, 1] +kernel_thm fn9_params : fn9.params = [0, 1] +kernel_thm fn5_start : ∀ s, fn5.start s = { s with memory := s.memory.store 64 128 } +kernel_thm fn8_start : ∀ s, fn8.start s = s +kernel_thm fn9_start : ∀ s, fn9.start s = s +kernel_thm f5b0 : fn5.blocks[0]? = some ⟨[], + [.effect (some 37) .calldatasize [], + .pure 39 .lt [.value 37, .const 36], + .effect (some 41) .calldataload [.const 4], + .pure 43 .gt [.value 41, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 50 .or [.value 39, .value 43]], + .branch (.value 50) 3 7⟩ + +kernel_thm f5b1 : fn5.blocks[1]? = some ⟨[], + [.effect (some 34) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 34], + .effect (some 35) .returndatasize []], + .revert (.const 0) (.value 35)⟩ + +kernel_thm f5b2 : fn5.blocks[2]? = some ⟨[], + [.effect (some 18) .returndatasize [], + .pure 19 .lt [.value 18, .const 32]], + .branch (.value 19) 3 4⟩ + +kernel_thm f5b3 : fn5.blocks[3]? = some ⟨[], + [], + .revert (.const 0) (.const 0)⟩ + +kernel_thm f5b4 : fn5.blocks[4]? = some ⟨[], + [.effect (some 20) .mload [.const 0], + .effect (some 22) .sload [.const 2], + .pure 25 .sub [.value 20, .value 22], + .pure 26 .lt [.value 20, .value 22]], + .branch (.value 26) 5 6⟩ + +kernel_thm f5b5 : fn5.blocks[5]? = some ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩ + +kernel_thm f5b6 : fn5.blocks[6]? = some ⟨[], + [.call none 8 [.value 41, .value 41, .value 25], + .assume true .gt [.value 41, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .stop⟩ + +kernel_thm f5b7 : fn5.blocks[7]? = some ⟨[], + [.pure 47 .and [.value 41, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 2) .sload [.const 1], + .effect (some 5) .gas [], + .effect (some 6) .address [], + .effect none .mstore [.const 0, .const 0x70a08231], + .effect none .mstore [.const 32, .value 6], + .effect (some 16) (.call .staticcall) [.value 5, .value 2, .const 28, .const 36, .const 0, .const 32], + .assume true .gt [.value 6, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 47, .value 41]], + .branch (.value 16) 2 1⟩ + +kernel_thm f8b0 : fn8.blocks[0]? = some ⟨[], + [.effect (some 3) .sload [.const 1], + .effect (some 6) .gas [], + .heapFloor 91 128, + .effect (some 93) .mload [.const 64], + .assume false .eq [.value 91, .value 93], + .pure 94 .add [.value 91, .const 128], + .effect none .mstore [.const 64, .value 94], + .pure 82 .add [.value 91, .const 32], + .effect none .mstore [.value 82, .const 0xa9059cbb00000000000000000000000000000000000000000000000000000000], + .pure 84 .add [.value 91, .const 36], + .effect none .mstore [.value 84, .value 0], + .pure 79 .add [.value 84, .const 32], + .effect none .mstore [.value 79, .value 1], + .effect (some 27) (.call .call) [.value 6, .value 3, .const 0, .value 82, .const 68, .const 0, .const 0], + .effect (some 28) .returndatasize [], + .pure 105 .add [.value 28, .const 63], + .pure 34 .and [.value 105, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0], + .assume false .lt [.value 28, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc1], + .assume false .eq [.const 0, .const 0], + .pure 98 .add [.value 94, .value 34], + .effect none .mstore [.const 64, .value 98], + .effect none .mstore [.value 94, .value 28], + .pure 86 .add [.value 94, .const 32], + .effect none .returndatacopy [.value 86, .const 0, .value 28], + .assume true .gt [.value 100, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 27) 1 3⟩ + +kernel_thm f8b1 : fn8.blocks[1]? = some ⟨[], + [.effect (some 12) .mload [.value 94], + .pure 14 .eq [.value 28, .const 0], + .assume false .eq [.value 12, .value 28]], + .branch (.value 14) 4 2⟩ + +kernel_thm f8b2 : fn8.blocks[2]? = some ⟨[], + [.effect (some 56) .mload [.value 94], + .pure 60 .slt [.value 28, .const 32], + .assume false .eq [.value 56, .value 28]], + .branch (.value 60) 5 6⟩ + +kernel_thm f8b3 : fn8.blocks[3]? = some ⟨[], + [], + .tailCall 9 [.const 15, .const 0x5452414e534645525f4641494c45440000000000000000000000000000000000]⟩ + +kernel_thm f8b4 : fn8.blocks[4]? = some ⟨[], + [], + .leave []⟩ + +kernel_thm f8b5 : fn8.blocks[5]? = some ⟨[], + [], + .revert (.const 0) (.const 0)⟩ + +kernel_thm f8b6 : fn8.blocks[6]? = some ⟨[], + [.effect (some 63) .mload [.value 86], + .pure 65 .gt [.value 63, .const 1]], + .branch (.value 65) 5 7⟩ + +kernel_thm f8b7 : fn8.blocks[7]? = some ⟨[], + [.ne 69 (.value 63) (.const 0)], + .branch (.value 69) 4 3⟩ + +kernel_thm f9b0 : fn9.blocks[0]? = some ⟨[], + [.effect none .mstore [.const 32, .const 32], + .effect none .mstore [.const 64, .value 0], + .effect none .mstore [.const 96, .value 1], + .effect none .mstore [.const 0, .const 0x8c379a0]], + .revert (.const 28) (.const 100)⟩ + +kernel_thm f10b0 : fn10.blocks[0]? = some ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 10 1⟩ + +kernel_thm f10b1 : fn10.blocks[1]? = some ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 10 [(.const 0x4f335d0a, 2), (.const 0x7464fc3d, 3), (.const 0xbc25cf77, 4), (.const 0xc45a0155, 5), (.const 0xcd3293de, 6), (.const 0xf740f328, 7), (.const 0xfc0c546a, 8), (.const 0xfff6cae9, 9)]⟩ + +kernel_thm f10b2 : fn10.blocks[2]? = some ⟨[], + [], + .tailCall 6 []⟩ + +kernel_thm f10b3 : fn10.blocks[3]? = some ⟨[], + [], + .tailCall 3 []⟩ + +kernel_thm f10b4 : fn10.blocks[4]? = some ⟨[], + [], + .tailCall 5 []⟩ + +kernel_thm f10b5 : fn10.blocks[5]? = some ⟨[], + [], + .tailCall 0 []⟩ + +kernel_thm f10b6 : fn10.blocks[6]? = some ⟨[], + [], + .tailCall 2 []⟩ + +kernel_thm f10b7 : fn10.blocks[7]? = some ⟨[], + [], + .tailCall 7 []⟩ + +kernel_thm f10b8 : fn10.blocks[8]? = some ⟨[], + [], + .tailCall 1 []⟩ + +kernel_thm f10b9 : fn10.blocks[9]? = some ⟨[], + [], + .tailCall 4 []⟩ + +kernel_thm f10b10 : fn10.blocks[10]? = some ⟨[], + [], + .revert (.const 0) (.const 0)⟩ + +def mask : BitVec 256 := 0xffffffffffffffffffffffffffffffffffffffff + +/-- The values a step leaves, for a step that goes on. -/ +def envAfter (r : Option ((Halt × State) ⊕ Frame)) : Env := + match r with + | some (.inr f) => f.2.2.1 + | _ => fun _ => 0 + +theorem eq_self' (a : BitVec 256) : EvmRules.Evm.eq a a = 1 := by simp [EvmRules.Evm.eq] + +theorem ne_self' (a : BitVec 256) : EvmRules.Evm.ne a a = 0 := by simp [EvmRules.Evm.ne] + +macro "blk" : tactic => `(tactic| (simp only [step, moduleBlock, fn5_eq, fn8_eq, fn9_eq, fn10_eq, f5b0, f5b1, f5b2, f5b3, f5b4, + f5b5, f5b6, f5b7, f8b0, f8b1, f8b2, f8b3, f8b4, f8b5, f8b6, f8b7, f9b0, f10b0, f10b1, f10b4, f10b10, bindPhis, + segment, splitCall, execInsts, Effect.apply, List.map_cons, List.map_nil, Operand.eval, evalPure, EVM.step, + CallKind.shape, fn5_params, fn8_params, fn9_params, fn5_start, fn8_start, fn9_start, bindParams, envAfter])) + +theorem e0 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (env : Env) (s : State) : + step o σ dst ([], .enter 10 p 0, env, s) = + some (.inr ([], .enter 10 0 1, envAfter (step o σ dst ([], .enter 10 p 0, env, s)), s)) := by + blk; simp [Env.set, skimCall, Evm.Wide.callAt, ne_self'] + +theorem e1 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (env : Env) (s : State) + (hsel : EvmRules.Evm.shr (224#256) (calldataWord (skimCall σ dst) 0#256) = 3156594551#256) : + step o σ dst ([], .enter 10 p 1, env, s) = + some (.inr ([], .enter 10 1 4, envAfter (step o σ dst ([], .enter 10 p 1, env, s)), s)) := by + blk; simp [Env.set, hsel, switchTarget, Operand.eval] + +theorem e4 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (env : Env) (s : State) : + step o σ dst ([], .enter 10 p 4, env, s) = + some (.inr ([], .enter 5 0 0, fun _ => 0, { s with memory := s.memory.store 64 128 })) := by + blk + +theorem gt_mask (dst : Nat) (hd : dst < 2 ^ 160) : + EvmRules.Evm.gt (BitVec.ofNat 256 dst) 1461501637330902918203684832716283019655932542975#256 = 0#256 := by + have h1 : dst < 2 ^ 256 := by omega + simp only [EvmRules.Evm.gt, BitVec.ult, BitVec.toNat_ofNat, Nat.mod_eq_of_lt h1] + have : ¬ (1461501637330902918203684832716283019655932542975 < dst) := by omega + simp [this] + +theorem and_mask (dst : Nat) (hd : dst < 2 ^ 160) : + EvmRules.Evm.and (BitVec.ofNat 256 dst) 1461501637330902918203684832716283019655932542975#256 = + BitVec.ofNat 256 dst := by + apply BitVec.eq_of_toNat_eq + have h1 : dst < 2 ^ 256 := by omega + simp only [EvmRules.Evm.and, BitVec.toNat_and, BitVec.toNat_ofNat, Nat.mod_eq_of_lt h1] + rw [show (1461501637330902918203684832716283019655932542975 : Nat) % 2 ^ 256 = 2 ^ 160 - 1 by norm_num, + Nat.and_two_pow_sub_one_eq_mod, Nat.mod_eq_of_lt hd] + +theorem k0 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (env : Env) (s : State) + (hsz : (skimCall σ dst).calldata.size = 36) + (hw : calldataWord (skimCall σ dst) 4#256 = BitVec.ofNat 256 dst) (hd : dst < 2 ^ 160) : + step o σ dst ([], .enter 5 p 0, env, s) = + some (.inr ([], .enter 5 0 7, envAfter (step o σ dst ([], .enter 5 p 0, env, s)), s)) ∧ + envAfter (step o σ dst ([], .enter 5 p 0, env, s)) 41 = BitVec.ofNat 256 dst := by + constructor <;> (blk; simp [Env.set, hsz, hw, gt_mask dst hd, EvmRules.Evm.or, EvmRules.Evm.lt]) + +def mem7 (s : State) : Mem := (s.memory.store 0 1889567281#256).store 32 (BitVec.ofNat 256 environment.callee) + +def W1 (o : Oracle) (s : State) : List Event := + s.world ++ [.read "gas", .call .staticcall [o.env "gas" (s.world ++ [.read "gas"]) [], s.storage 1#256] + ((((mem7 s).expand 28 36).expand 0 32).read 28 36) s.storage s.transient] + +def S7 (o : Oracle) (s : State) : State := + called o .staticcall { s with memory := mem7 s, world := s.world ++ [.read "gas"] } + (((mem7 s).expand 28 36).expand 0 32) 0#256 32#256 (W1 o s) + +theorem k7 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (env : Env) (s : State) + (h41 : env 41 = BitVec.ofNat 256 dst) (hd : dst < 2 ^ 160) : + step o σ dst ([], .enter 5 p 7, env, s) = + some (.inr ([], .enter 5 7 (if callFlag o (W1 o s) = 0#256 then 1 else 2), + envAfter (step o σ dst ([], .enter 5 p 7, env, s)), S7 o s)) ∧ + envAfter (step o σ dst ([], .enter 5 p 7, env, s)) 41 = BitVec.ofNat 256 dst := by + have hc : EvmRules.Evm.gt (BitVec.ofNat 256 environment.callee) 1461501637330902918203684832716283019655932542975#256 = 0#256 := by + decide + constructor <;> (blk; simp [Env.set, h41, and_mask dst hd, eq_self', hc, W1, S7, mem7]) <;> rfl + +theorem k1 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (stack : List Return) (env : Env) (s : State) : + step o σ dst (stack, .enter 5 p 1, env, s) = + some (.inl (halt { s with memory := (s.memory.write 0 (o.env "returndatasize" s.world []).toNat + (fun i => returndataByte o s.world (0 + i))) } 0 (o.env "returndatasize" s.world []) true)) := by + blk; simp [Env.set, returndataSize] + +theorem k2 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (stack : List Return) (env : Env) (s : State) : + step o σ dst (stack, .enter 5 p 2, env, s) = + some (.inr (stack, .enter 5 2 (if EvmRules.Evm.lt (o.env "returndatasize" s.world []) 32#256 = 0#256 then 4 else 3), + envAfter (step o σ dst (stack, .enter 5 p 2, env, s)), s)) ∧ + envAfter (step o σ dst (stack, .enter 5 p 2, env, s)) 41 = env 41 := by + constructor <;> (blk; simp [Env.set]) + +theorem k3 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (stack : List Return) (env : Env) (s : State) : + step o σ dst (stack, .enter 5 p 3, env, s) = some (.inl (halt s 0 0 true)) := by + blk + +theorem k4 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (stack : List Return) (env : Env) (s : State) : + step o σ dst (stack, .enter 5 p 4, env, s) = + some (.inr (stack, .enter 5 4 (if EvmRules.Evm.lt (s.memory.load 0) (s.storage 2#256) = 0#256 then 6 else 5), + envAfter (step o σ dst (stack, .enter 5 p 4, env, s)), { s with memory := s.memory.expand 0 32 })) ∧ + envAfter (step o σ dst (stack, .enter 5 p 4, env, s)) 41 = env 41 ∧ + envAfter (step o σ dst (stack, .enter 5 p 4, env, s)) 25 = EvmRules.Evm.sub (s.memory.load 0) (s.storage 2#256) := by + refine ⟨?_, ?_, ?_⟩ <;> (blk; simp [Env.set]) + +theorem k5 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (stack : List Return) (env : Env) (s : State) : + step o σ dst (stack, .enter 5 p 5, env, s) = some (.inl (halt + { s with memory := (s.memory.store 32 17#256).store 0 0x4e487b71#256 } 28 36 true)) := by + blk; rfl + +/-- Where pay returns to in skim. -/ +def retSkim (env : Env) : Return := + ⟨5, 6, none, [.assume true .gt [.value 41, .const 0xffffffffffffffffffffffffffffffffffffffff]], .stop, env, [], none⟩ + +def payEnv (a b : BitVec 256) : Env := ((Env.set (fun _ => 0#256) 0 a).set 100 a).set 1 b + +theorem k6 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (env : Env) (s : State) : + step o σ dst ([], .enter 5 p 6, env, s) = + some (.inr ([retSkim env], .enter 8 0 0, payEnv (env 41) (env 25), s)) := by + blk; simp [retSkim, payEnv] + +/-- The transfer selector word solar's MIR stores. -/ +def selT : BitVec 256 := 76450787359836037641860180984291677749980919077056822294353438043884394381312#256 + +def PM (m : Mem) (a b : BitVec 256) : Mem := + ((((m.expand 64 32).store 64 256#256).store 160 selT).store 164 a).store 196 b + +def in2 (m : Mem) (a b : BitVec 256) : List Memory.Byte := (((PM m a b).expand 160 68).expand 0 0).read 160 68 + +def W2 (o : Oracle) (s : State) (a b : BitVec 256) : List Event := + s.world ++ [.read "gas", .call .call [o.env "gas" (s.world ++ [.read "gas"]) [], s.storage 1#256, 0#256] + (in2 s.memory a b) s.storage s.transient] + +def rds2 (o : Oracle) (s : State) (a b : BitVec 256) : BitVec 256 := o.env "returndatasize" (W2 o s a b) [] + +def mask31 : BitVec 256 := 115792089237316195423570985008687907853269984665640564039457584007913129639904#256 + +def S8 (o : Oracle) (s : State) (a b : BitVec 256) : State := + ⟨((((((PM s.memory a b).expand 160 68).expand 0 0).write 0 (min 0 (rds2 o s a b).toNat) + (returndataByte o (W2 o s a b))).store 64 (256#256 + EvmRules.Evm.and (rds2 o s a b + 63#256) mask31)).store 256 + (rds2 o s a b)).write 288 (rds2 o s a b).toNat (fun i => returndataByte o (W2 o s a b) (0 + i)), + o.storageAfter (W2 o s a b), o.transientAfter (W2 o s a b), W2 o s a b⟩ + +theorem lt_c1 (r : BitVec 256) (hr : r.toNat < 2 ^ 64) : + EvmRules.Evm.lt r 115792089237316195423570985008687907853269984665640564039457584007913129639873#256 = 1#256 := by + simp only [EvmRules.Evm.lt, BitVec.ult] + have : r.toNat < 115792089237316195423570985008687907853269984665640564039457584007913129639873 := by omega + simp [this] + +theorem p0 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (stack : List Return) (env : Env) (s : State) + (h64 : s.memory.load 64 = 128#256) (h100 : env 100 = BitVec.ofNat 256 dst) (hd : dst < 2 ^ 160) + (hr : (rds2 o s (env 0) (env 1)).toNat < 2 ^ 64) : + step o σ dst (stack, .enter 8 p 0, env, s) = + some (.inr (stack, .enter 8 0 (if callFlag o (W2 o s (env 0) (env 1)) = 0#256 then 3 else 1), + envAfter (step o σ dst (stack, .enter 8 p 0, env, s)), S8 o s (env 0) (env 1))) ∧ + envAfter (step o σ dst (stack, .enter 8 p 0, env, s)) 28 = rds2 o s (env 0) (env 1) ∧ + envAfter (step o σ dst (stack, .enter 8 p 0, env, s)) 94 = 256#256 ∧ + envAfter (step o σ dst (stack, .enter 8 p 0, env, s)) 86 = 288#256 := by + have hr' := lt_c1 _ hr + simp only [rds2, W2, in2, PM, selT] at hr' + refine ⟨?_, ?_, ?_, ?_⟩ <;> (blk; simp [Env.set, h64, h100, gt_mask dst hd, eq_self', EvmRules.Evm.add, hr', called, + S8, W2, rds2, in2, PM, selT, mask31]) <;> rfl + +theorem p3 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (stack : List Return) (env : Env) (s : State) : + step o σ dst (stack, .enter 8 p 3, env, s) = + some (.inr (stack, .enter 9 0 0, (Env.set (fun _ => 0#256) 0 15#256).set 1 38139611465464413496808033184516339178673403987523396430313160281336026497024#256, s)) := by + blk; rfl + + +theorem p1 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (stack : List Return) (env : Env) (s : State) + (h94 : env 94 = 256#256) (hm : s.memory.load 256 = env 28) : + step o σ dst (stack, .enter 8 p 1, env, s) = + some (.inr (stack, .enter 8 1 (if EvmRules.Evm.eq (env 28) 0#256 = 0#256 then 2 else 4), + envAfter (step o σ dst (stack, .enter 8 p 1, env, s)), { s with memory := s.memory.expand 256 32 })) ∧ + envAfter (step o σ dst (stack, .enter 8 p 1, env, s)) 28 = env 28 ∧ + envAfter (step o σ dst (stack, .enter 8 p 1, env, s)) 94 = env 94 ∧ + envAfter (step o σ dst (stack, .enter 8 p 1, env, s)) 86 = env 86 := by + refine ⟨?_, ?_, ?_, ?_⟩ <;> (blk; simp [Env.set, h94, hm, eq_self']) <;> rfl + +theorem p2 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (stack : List Return) (env : Env) (s : State) + (h94 : env 94 = 256#256) (hm : s.memory.load 256 = env 28) : + step o σ dst (stack, .enter 8 p 2, env, s) = + some (.inr (stack, .enter 8 2 (if EvmRules.Evm.slt (env 28) 32#256 = 0#256 then 6 else 5), + envAfter (step o σ dst (stack, .enter 8 p 2, env, s)), { s with memory := s.memory.expand 256 32 })) ∧ + envAfter (step o σ dst (stack, .enter 8 p 2, env, s)) 86 = env 86 := by + refine ⟨?_, ?_⟩ <;> (blk; simp [Env.set, h94, hm, eq_self']) <;> rfl + +theorem p5 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (stack : List Return) (env : Env) (s : State) : + step o σ dst (stack, .enter 8 p 5, env, s) = some (.inl (halt s 0 0 true)) := by + blk + +theorem p6 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (stack : List Return) (env : Env) (s : State) + (h86 : env 86 = 288#256) : + step o σ dst (stack, .enter 8 p 6, env, s) = + some (.inr (stack, .enter 8 6 (if EvmRules.Evm.gt (s.memory.load 288) 1#256 = 0#256 then 7 else 5), + envAfter (step o σ dst (stack, .enter 8 p 6, env, s)), { s with memory := s.memory.expand 288 32 })) ∧ + envAfter (step o σ dst (stack, .enter 8 p 6, env, s)) 63 = s.memory.load 288 := by + refine ⟨?_, ?_⟩ <;> (blk; simp [Env.set, h86]) <;> rfl + +theorem p7 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (stack : List Return) (env : Env) (s : State) : + step o σ dst (stack, .enter 8 p 7, env, s) = + some (.inr (stack, .enter 8 7 (if EvmRules.Evm.ne (env 63) 0#256 = 0#256 then 3 else 4), + envAfter (step o σ dst (stack, .enter 8 p 7, env, s)), s)) := by + blk; simp [Env.set] + +theorem p4 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (e env : Env) (s : State) : + step o σ dst ([retSkim e], .enter 8 p 4, env, s) = + some (.inr ([], .resume 5 6 [.assume true .gt [.value 41, .const 0xffffffffffffffffffffffffffffffffffffffff]] .stop, e, s)) := by + blk; simp [retSkim, bindResults, bindResult, publishResults] + +theorem rs (o : Oracle) (σ : List (Nat × Nat)) (dst : Nat) (e : Env) (s : State) + (h41 : e 41 = BitVec.ofNat 256 dst) (hd : dst < 2 ^ 160) : + step o σ dst ([], .resume 5 6 [.assume true .gt [.value 41, .const 0xffffffffffffffffffffffffffffffffffffffff]] .stop, e, s) = + some (.inl (.stop, s)) := by + blk; simp [h41, gt_mask dst hd] + +/-- The revert of \`Error("TRANSFER_FAILED")\`. -/ +theorem r0 (o : Oracle) (σ : List (Nat × Nat)) (dst p : Nat) (stack : List Return) (s : State) : + step o σ dst (stack, .enter 9 p 0, (Env.set (fun _ => 0#256) 0 15#256).set 1 38139611465464413496808033184516339178673403987523396430313160281336026497024#256, s) = + some (.inl (halt { s with memory := (((s.memory.store 32 32#256).store 64 15#256).store 96 + 38139611465464413496808033184516339178673403987523396430313160281336026497024#256).store 0 147028384#256 } 28 100 true)) := by + blk; simp [Env.set] + + +section calldata +open EthLib.Base EthLib.Execution EthLib.Execution.Evm SolidCore.Refinement SolidCore.Refinement.Evm + +theorem calldata_skim (σ : List (Nat × Nat)) (dst : Nat) : + (skimCall σ dst).calldata = cdOf (selectorOf 0xbc25cf77) [BitVec.ofNat 256 dst] := by + have := calldata_eq_cdOf 0xbc25cf77 [(BitVec.ofNat 256 dst).toNat] (by + intro y hy + simp only [List.mem_cons, List.mem_nil_iff, or_false] at hy + rcases hy with rfl + exact BitVec.isLt _) + rw [show (skimCall σ dst).calldata = Abi.calldata 0xbc25cf77 [(BitVec.ofNat 256 dst).toNat] from rfl, this] + simp only [List.map_cons, List.map_nil, BitVec.ofNat_toNat, BitVec.setWidth_eq] + +theorem skim_sel (σ : List (Nat × Nat)) (dst : Nat) : + EvmRules.Evm.shr (224#256) (calldataWord (skimCall σ dst) 0#256) = 3156594551#256 := by + rw [SolidCore.Refinement.Generic.calldataWord_eq, calldata_skim] + have := shr_cdOf_selectorOf 0xbc25cf77 [BitVec.ofNat 256 dst] (by decide) + simpa [EvmRules.Evm.shr, bitwiseShr] using this + +theorem skim_word4 (σ : List (Nat × Nat)) (dst : Nat) : + calldataWord (skimCall σ dst) 4#256 = BitVec.ofNat 256 dst := by + rw [SolidCore.Refinement.Generic.calldataWord_eq, calldata_skim] + exact loadWord_cdOf_getD _ [BitVec.ofNat 256 dst] 4 (by simp [size_selectorOf]) (by simp [size_selectorOf]) + (by simp [size_selectorOf]) + +theorem skim_size (σ : List (Nat × Nat)) (dst : Nat) : (skimCall σ dst).calldata.size = 36 := by + rw [calldata_skim, size_cdOf, size_selectorOf]; simp + +end calldata + +end SolidCore.Refinement.CallFamilies.Skim diff --git a/Contracts/CallFamilies/SkimRun.lean b/Contracts/CallFamilies/SkimRun.lean new file mode 100644 index 00000000..e9f6e61a --- /dev/null +++ b/Contracts/CallFamilies/SkimRun.lean @@ -0,0 +1,159 @@ +import Contracts.CallFamilies.SkimMir + +/-! +# skim in solar's first lowered MIR, for every oracle + +run_skim: solar's stage0 runs skim(dst) from the storage σ to mirEnd o σ dst under every oracle +o, for every address dst below 2 ^ 160 and every oracle whose second call returns fewer than +2 ^ 64 bytes: the token's balanceOf(address(this)) STATICCALL, its revert bubbling and short +return check, the checked subtraction of the reserve (panic 0x11), the internal call of pay with +the free-memory-pointer allocation of the transfer calldata and the return buffer, the low-level +CALL of transfer(dst, amount), and the decoding of its return data as empty or a bool word. +Each block step is a lemma of SkimMir over free values and state. +-/ + +open SolarTV SolarTV.Machine SolarTV.MIR.Lowered + +namespace SolidCore.Refinement.CallFamilies.Skim + +set_option linter.deprecated false + +set_option hygiene false in +local notation "tS0" => S0' σ dst + +/-- The state skim's body starts in: the free-memory pointer at 128. -/ +def S0' (σ : List (Nat × Nat)) (dst : Nat) : State := + { State.initial (skimCall σ dst) with memory := (State.initial (skimCall σ dst)).memory.store 64 128 } + +set_option hygiene false in +local notation "tT" => S7 o (S0' σ dst) +set_option hygiene false in +local notation "tT4" => ({ S7 o (S0' σ dst) with memory := (S7 o (S0' σ dst)).memory.expand 0 32 } : State) +set_option hygiene false in +local notation "tAmt" => EvmRules.Evm.sub ((S7 o (S0' σ dst)).memory.load 0) ((S7 o (S0' σ dst)).storage 2#256) +set_option hygiene false in +local notation "tU" => S8 o tT4 (BitVec.ofNat 256 dst) tAmt +set_option hygiene false in +local notation "tR" => rds2 o tT4 (BitVec.ofNat 256 dst) tAmt +set_option hygiene false in +local notation "tU1" => ({ tU with memory := (tU).memory.expand 256 32 } : State) +set_option hygiene false in +local notation "tU2" => ({ tU1 with memory := (tU1).memory.expand 256 32 } : State) +set_option hygiene false in +local notation "tU3" => ({ tU2 with memory := (tU2).memory.expand 288 32 } : State) + +/-- The revert of Error("TRANSFER_FAILED") from the state s. -/ +def errHalt (s : State) : Halt × State := + halt { s with memory := (((s.memory.store 32 32#256).store 64 15#256).store 96 + 38139611465464413496808033184516339178673403987523396430313160281336026497024#256).store 0 147028384#256 } 28 100 true + +/-- The end of solar's stage0 on a call of skim. -/ +def mirEnd (o : Oracle) (σ : List (Nat × Nat)) (dst : Nat) : Halt × State := + if callFlag o (W1 o tS0) = 0#256 then + halt { tT with memory := ((tT).memory.write 0 (o.env "returndatasize" (tT).world []).toNat + (fun i => returndataByte o (tT).world (0 + i))) } 0 (o.env "returndatasize" (tT).world []) true + else if EvmRules.Evm.lt (o.env "returndatasize" (tT).world []) 32#256 = 0#256 then + if EvmRules.Evm.lt ((tT).memory.load 0) ((tT).storage 2#256) = 0#256 then + if callFlag o (W2 o tT4 (BitVec.ofNat 256 dst) tAmt) = 0#256 then errHalt tU + else if EvmRules.Evm.eq tR 0#256 = 0#256 then + if EvmRules.Evm.slt tR 32#256 = 0#256 then + if EvmRules.Evm.gt ((tU2).memory.load 288) 1#256 = 0#256 then + if EvmRules.Evm.ne ((tU2).memory.load 288) 0#256 = 0#256 then errHalt tU3 + else (.stop, tU3) + else halt tU3 0 0 true + else halt tU2 0 0 true + else (.stop, tU1) + else halt { tT4 with memory := ((tT4).memory.store 32 17#256).store 0 0x4e487b71#256 } 28 36 true + else halt tT 0 0 true + +theorem load64 (o : Oracle) (σ : List (Nat × Nat)) (dst : Nat) : (tT4).memory.load 64 = 128#256 := by + simp only [S7, called, mem7, S0'] + have e0 : (0#256).toNat = 0 := rfl + have e32 : (32#256).toNat = 32 := rfl + rw [Mem.load_expand, Mem.load_write_of_disjoint _ _ _ _ _ (Or.inr (by rw [e0, e32]; omega)), Mem.load_expand, Mem.load_expand, + Mem.load_store_of_disjoint _ _ _ _ (Or.inr (by omega)), Mem.load_store_of_disjoint _ _ _ _ (Or.inr (by omega)), + Mem.load_store_same] + rfl + +theorem load256_S8 (o : Oracle) (s : State) (a b : BitVec 256) : (S8 o s a b).memory.load 256 = rds2 o s a b := by + simp only [S8] + rw [Mem.load_write_of_disjoint _ _ _ _ _ (Or.inl (by omega)), Mem.load_store_same] + +theorem payEnv_0 (a b : BitVec 256) : payEnv a b 0 = a := by simp [payEnv, Env.set] +theorem payEnv_1 (a b : BitVec 256) : payEnv a b 1 = b := by simp [payEnv, Env.set] +theorem payEnv_100 (a b : BitVec 256) : payEnv a b 100 = a := by simp [payEnv, Env.set] + +open SolidCore.Refinement.CallFamilies.Sync (iter_next iter_end) in +theorem run_skim (o : Oracle) (σ : List (Nat × Nat)) (dst : Nat) (hd : dst < 2 ^ 160) + (hr : callFlag o (W1 o tS0) ≠ 0#256 → + EvmRules.Evm.lt (o.env "returndatasize" (tT).world []) 32#256 = 0#256 → + EvmRules.Evm.lt ((tT).memory.load 0) ((tT).storage 2#256) = 0#256 → (tR).toNat < 2 ^ 64) : + Module.run o SolarTV.Export.Calls.stage0 (skimCall σ dst) 20 = some (mirEnd o σ dst) := by + show iterate (step o σ dst) 20 ([], .enter 10 0 0, fun _ => 0, State.initial (skimCall σ dst)) = _ + rw [iter_next (e0 o σ dst 0 _ _), iter_next (e1 o σ dst 0 _ _ (skim_sel σ dst)), iter_next (e4 o σ dst 1 _ _)] + rw [show ({ State.initial (skimCall σ dst) with memory := (State.initial (skimCall σ dst)).memory.store 64 128 } : State) = tS0 from rfl] + obtain ⟨h0, h0e⟩ := k0 o σ dst 0 (fun _ => 0) tS0 (skim_size σ dst) (skim_word4 σ dst) hd + rw [iter_next h0] + obtain ⟨h7, h7e⟩ := k7 o σ dst 0 _ tS0 h0e hd + rw [iter_next h7] + unfold mirEnd + by_cases c1 : callFlag o (W1 o tS0) = 0#256 + · rw [if_pos c1, if_pos c1, iter_end (k1 o σ dst 7 [] _ _)] + rw [if_neg c1, if_neg c1] + obtain ⟨h2, h2e⟩ := k2 o σ dst 7 [] _ tT + rw [iter_next h2] + by_cases c2 : EvmRules.Evm.lt (o.env "returndatasize" (tT).world []) 32#256 = 0#256 + swap + · rw [if_neg c2, if_neg c2, iter_end (k3 o σ dst 2 [] _ _)] + rw [if_pos c2, if_pos c2] + obtain ⟨h4, h4e, h4a⟩ := k4 o σ dst 2 [] _ tT + rw [iter_next h4] + by_cases c4 : EvmRules.Evm.lt ((tT).memory.load 0) ((tT).storage 2#256) = 0#256 + swap + · rw [if_neg c4, if_neg c4, iter_end (k5 o σ dst 4 [] _ _)] + rw [if_pos c4, if_pos c4, iter_next (k6 o σ dst 4 _ _)] + have h41 : envAfter (step o σ dst ([], .enter 5 2 4, envAfter (step o σ dst ([], .enter 5 7 2, + envAfter (step o σ dst ([], .enter 5 0 7, envAfter (step o σ dst ([], .enter 5 0 0, fun _ => 0, tS0)), tS0)), tT)), tT)) 41 = + BitVec.ofNat 256 dst := by rw [h4e, h2e, h7e] + rw [h41, h4a] + obtain ⟨hp, hp28, hp94, hp86⟩ := p0 o σ dst 0 _ (payEnv (BitVec.ofNat 256 dst) tAmt) tT4 (load64 o σ dst) + (payEnv_100 _ _) hd (by rw [payEnv_0, payEnv_1]; exact hr c1 c2 c4) + rw [payEnv_0, payEnv_1] at hp hp28 + rw [iter_next hp] + by_cases c5 : callFlag o (W2 o tT4 (BitVec.ofNat 256 dst) tAmt) = 0#256 + · rw [if_pos c5, if_pos c5, iter_next (p3 o σ dst 0 _ _ _), iter_end (r0 o σ dst 0 _ _)] + rfl + rw [if_neg c5, if_neg c5] + obtain ⟨hq, hq28, hq94, hq86⟩ := p1 o σ dst 0 _ _ tU hp94 (by rw [load256_S8, hp28]) + rw [hp28] at hq + rw [iter_next hq] + by_cases c6 : EvmRules.Evm.eq tR 0#256 = 0#256 + swap + · rw [if_neg c6, if_neg c6, iter_next (p4 o σ dst 1 _ _ _), + iter_end (rs o σ dst _ _ h41 hd)] + rw [if_pos c6, if_pos c6] + obtain ⟨hq2, hq2e⟩ := p2 o σ dst 1 _ _ tU1 (hq94.trans hp94) (by rw [Mem.load_expand, load256_S8, hq28, hp28]) + rw [hq28, hp28] at hq2 + rw [iter_next hq2] + by_cases c7 : EvmRules.Evm.slt tR 32#256 = 0#256 + swap + · rw [if_neg c7, if_neg c7, iter_end (p5 o σ dst 2 _ _ _)] + rw [if_pos c7, if_pos c7] + obtain ⟨hq6, hq6e⟩ := p6 o σ dst 2 _ _ tU2 (hq2e.trans (hq86.trans hp86)) + rw [iter_next hq6] + by_cases c8 : EvmRules.Evm.gt ((tU2).memory.load 288) 1#256 = 0#256 + swap + · rw [if_neg c8, if_neg c8, iter_end (p5 o σ dst 6 _ _ _)] + rw [if_pos c8, if_pos c8] + rw [iter_next (p7 o σ dst 6 _ _ _), hq6e] + by_cases c9 : EvmRules.Evm.ne ((tU2).memory.load 288) 0#256 = 0#256 + · rw [if_pos c9, if_pos c9, iter_next (p3 o σ dst 7 _ _ _), iter_end (r0 o σ dst 0 _ _)] + rfl + · rw [if_neg c9, if_neg c9, iter_next (p4 o σ dst 7 _ _ _), + iter_end (rs o σ dst _ _ h41 hd)] + +/-- info: 'SolidCore.Refinement.CallFamilies.Skim.run_skim' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms run_skim + +end SolidCore.Refinement.CallFamilies.Skim diff --git a/Contracts/CallFamilies/SkimSource.lean b/Contracts/CallFamilies/SkimSource.lean new file mode 100644 index 00000000..6c07a26a --- /dev/null +++ b/Contracts/CallFamilies/SkimSource.lean @@ -0,0 +1,660 @@ +import Contracts.CallFamilies.PayRun +import Contracts.CallFamilies.SkimAgree +import Contracts.CallFamilies.Core + +namespace SolidCore.Refinement.CallFamilies + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Refinement.CallNode +open SolidCore.Solidity.Source EvmCompiler.Simulation + +/-- The name of pay in Calls' function table. -/ +def payName : String := + "__internal_pay(address,uint256)#[SolidCore.Solidity.Ty.address false, SolidCore.Solidity.Ty.uint 256]" + +/-- pay, as the checker lowers it. -/ +def payFn : InternalFunction := + { name := payName, + params := [{ name := "to", ty := Ty.address, isStorageRef := false }, + { name := "amount", ty := Ty.uint256, isStorageRef := false }], + returns := [], + body := payBody } + +/-- The checked sub of skim: balance - reserve. -/ +def skimAmtE : Expr := + Expr.castOp CastKind.uintCleanup 256 (Expr.castOp CastKind.uintCleanup 256 + (Expr.binary BinaryOp.sub (Expr.castOp CastKind.uintCleanup 256 (Expr.var "_sol_hoist_0")) + (Expr.castOp CastKind.uintCleanup 256 (Expr.var "_sol_hoist_1")))) + +/-- skim's balance read. -/ +def skimTryS : Stmt := + Stmt.tryExternalCall (SolidCore.Solidity.Shared.Call.ExternalCallKind.staticcall) + (Expr.storageRead (StorageReadMode.ref) "token" []) + (Expr.encode (EncodeKind.withSelector) (some (Expr.word 1889567281)) [] [Ty.address] [Expr.self]) + (Expr.word 0) none false false + [{ name := "__ext0", ty := Ty.uint256, isStorageRef := false }] + [AbiCleanup.uint 256] + (Stmt.assign (LValue.var "_sol_hoist_0") (Expr.castOp (CastKind.uintCleanup) 256 (Expr.var "__ext0"))) + [] + +/-- skim's call of pay. -/ +def skimPayS : List Stmt := + [Stmt.varDecl Ty.address "_ic_arg_0" (some (Expr.var "_sol_hoist_2")), + Stmt.varDecl Ty.uint256 "_ic_arg_1" (some skimAmtE), + Stmt.captureReturn [] (Stmt.internalCall [] payName [Expr.var "_ic_arg_0", Expr.var "_ic_arg_1"])] + +/-- SolidCore's skim(address) of Calls, as the checker lowers it. -/ +def skimFn : FunctionDef := +{ name := "skim", + selector? := some 3156594551, + payable := false, + params := [{ name := "to", ty := Ty.address, isStorageRef := false }], + paramAbiCleanups := [AbiCleanup.none], + returns := [], + body := Stmt.block [Stmt.skip, Stmt.block + [Stmt.varDecl Ty.address "_sol_hoist_2" (some (Expr.var "to")), + Stmt.varDecl Ty.uint256 "_sol_hoist_1" + (some (Expr.castOp CastKind.uintCleanup 256 (Expr.storageRead StorageReadMode.ref "reserve" []))), + Stmt.varDecl Ty.uint256 "_sol_hoist_0" none, + skimTryS, + Stmt.block skimPayS]], + dispatchId? := none } + +/-- Calls's reserve field. -/ +def reserveField : StorageField := + { name := "reserve", slot := 2, ty? := some Ty.uint256, layout? := some (StorageLayout.scalar Ty.uint256), + transient := false, packedOffset := 0, packedBytes := 32, packedSigned := false } + +theorem reserve_eval (ctx : Context) (rt : Runtime) (hf : FieldOk ctx "reserve" reserveField) + (hw : rt.state.loadSlot reserveField.slot < Generic.wordSize) : + Expr.eval ctx rt (Expr.castOp CastKind.uintCleanup 256 (Expr.storageRead StorageReadMode.ref "reserve" [])) = + EvmCompiler.Simulation.Interaction.done (.ok (.word (fieldValue (rt.state.loadSlot reserveField.slot) 0 32), rt)) := by + simp only [Expr.eval, Expr.orderFuel] + rw [Expr.evalFuel] + simp only [Expr.evalFuel, load_field hf hw] + have hv : fieldValue (rt.state.loadSlot reserveField.slot) 0 32 < 2 ^ 256 := by + simp only [fieldValue]; split <;> omega + simp only [liftM, monadLift, MonadLift.monadLift, SolI.ofExcept, bind_done_ok, + show reserveField.packedOffset = 0 from rfl, show reserveField.packedBytes = 32 from rfl] + rw [sbind_pure]; dsimp only + rw [cleanup256 _ _ hv] + rfl + +theorem varE (ctx : Context) (rt : Runtime) (x : String) (w : Nat) + (hb : rt.lookupStorageBase? x = none) (hl : rt.lookupLocal? x = some (.word w)) : + Expr.eval ctx rt (Expr.var x) = EvmCompiler.Simulation.Interaction.done (.ok (.word w, rt)) := by + simp only [Expr.eval, Expr.orderFuel] + exact varF 1 ctx rt x w hb hl + +theorem assign_cast_var (n : Nat) (tbl : FunctionTable) (ctx : Context) (rt : Runtime) (x y : String) (w : Nat) + (hw : w < 2 ^ 256) (L : LocalEnv) + (hbx : rt.lookupStorageBase? x = none) (hmx : rt.lookupMemoryRef? x = none) + (hlx : ∃ v, rt.lookupLocal? x = some (.word v)) + (hby : rt.lookupStorageBase? y = none) (hly : rt.lookupLocal? y = some (.word w)) + (hL : LocalEnv.assign? rt.locals x (.word w) = some L) : + Stmt.eval (n + 1) tbl ctx rt (Stmt.assign (LValue.var x) (Expr.castOp CastKind.uintCleanup 256 (Expr.var y))) = + pure (Result.normal { rt with locals := L }) := by + obtain ⟨v, hv⟩ := hlx + rw [Stmt.eval]; dsimp only + simp only [LValue.wantsMemoryRefRhs, hmx, Option.isSome_none, Bool.false_eq_true, ↓reduceIte] + rw [castVar_eval ctx rt y w hw hby hly] + rw [caught_done_ok, bind_done_ok]; dsimp only + rw [resolve_var ctx rt x (.word v) hbx hv, caught_done_ok, bind_done_ok]; dsimp only + simp [ResolvedLValue.write, Runtime.assignLocal?, hv, Value.coerceLike?, hL] + done + +theorem amt_eval (ctx : Context) (rt : Runtime) (w r : Nat) (hw : w < 2 ^ 256) (hr : r < 2 ^ 256) + (hc : ctx.checked = true) + (hb0 : rt.lookupStorageBase? "_sol_hoist_0" = none) (hl0 : rt.lookupLocal? "_sol_hoist_0" = some (.word w)) + (hb1 : rt.lookupStorageBase? "_sol_hoist_1" = none) (hl1 : rt.lookupLocal? "_sol_hoist_1" = some (.word r)) : + Expr.eval ctx rt skimAmtE = + if w < r then EvmCompiler.Simulation.Interaction.done (.error (.revert .overflow)) + else EvmCompiler.Simulation.Interaction.done (.ok (.word (w - r), rt)) := by + simp only [Expr.eval, skimAmtE, Expr.orderFuel] + simp only [Expr.evalFuel] + simp [hb0, hl0, hb1, hl1, Runtime.derefMemoryValue, liftM, monadLift, MonadLift.monadLift, SolI.ofExcept, + bind_done_ok, ipure_eq, cleanup256 _ _ hw, cleanup256 _ _ hr, BinaryOp.apply, hc, sbind_pure, + Value.forceAbiLazy, BinaryOp.preservesFixedBytesWidth, BinaryOp.applyWord, checkedSub] + have hnw : SolidCore.Solidity.Shared.norm w = w := Nat.mod_eq_of_lt hw + have hnr : SolidCore.Solidity.Shared.norm r = r := Nat.mod_eq_of_lt hr + by_cases hlt : w < r + · simp [hnw, hnr, hlt, bind_done_ok, tbind, throw_eq, bind, Except.bind, pure, Except.pure] + done + · have hsub : SolidCore.Solidity.Shared.subWord w r = w - r := by + rw [subWord_eq w r hw hr] + have hge : r ≤ w := by omega + have : w + (Generic.wordSize - r) = (w - r) + Generic.wordSize := by + have : r < Generic.wordSize := hr + omega + rw [this, Nat.add_mod_right, Nat.mod_eq_of_lt (by have : w < Generic.wordSize := hw; omega)] + have hd : w - r < 2 ^ 256 := by omega + simp [hnw, hnr, hlt, hsub, bind_done_ok, cleanup256 _ _ hd, sbind_pure, ipure_eq, bind, Except.bind, pure, + Except.pure] + done + +theorem refArg_var (ctx : Context) (rt : Runtime) (x : String) (w : Nat) + (hb : rt.lookupStorageBase? x = none) (hm : rt.lookupMemoryRef? x = none) + (hl : rt.lookupLocal? x = some (.word w)) : + Expr.evalRefArg ctx rt (Expr.var x) = EvmCompiler.Simulation.Interaction.done (.ok (.word w, rt)) := by + simp only [Expr.evalRefArg, hb, hm] + exact varE ctx rt x w hb hl + +theorem refArgs2 (ctx : Context) (rt : Runtime) (x y : String) (v w : Nat) + (hbx : rt.lookupStorageBase? x = none) (hmx : rt.lookupMemoryRef? x = none) + (hlx : rt.lookupLocal? x = some (.word v)) + (hby : rt.lookupStorageBase? y = none) (hmy : rt.lookupMemoryRef? y = none) + (hly : rt.lookupLocal? y = some (.word w)) : + Expr.evalRefArgList ctx rt [Expr.var x, Expr.var y] = + EvmCompiler.Simulation.Interaction.done (.ok ([.word v, .word w], rt)) := by + simp only [Expr.evalRefArgList, Expr.listEvalFuel, Expr.orderFuel] + simp only [Expr.evalRefArgListFuel, refArg_var ctx rt x v hbx hmx hlx, refArg_var ctx rt y w hby hmy hly, + bind_done_ok] + rfl + +theorem pay_frame (v w : Nat) (hv : v < 2 ^ 160) (hw : w < 2 ^ 256) : + payFn.initialFrame? [.word v, .word w] = some [("to", .word v), ("amount", .word w)] := by + simp [InternalFunction.initialFrame?, payFn, BindingDecl.bindArgsRef?, BindingDecl.bindArgRef?, + InternalFunction.returnDefaultBindings, BindingDecl.bindArg?, coerce_param (Or.inr rfl) v, + coerce_param (Or.inl rfl) w] + +theorem bytes_roundtrip (l : List Nat) : byteArrayToBytes (bytesToByteArray l) = l.map (· % 256) := by + simp [byteArrayToBytes, bytesToByteArray, toList_eq_data] + done + +theorem srcBytesBE_eq : ∀ (n v : Nat), + wordToBytesBE n v = (List.range n).map fun i => v / 256 ^ (n - 1 - i) % 256 + | 0, _ => rfl + | n + 1, v => by + rw [wordToBytesBE, srcBytesBE_eq n (v / 256), List.range_succ, List.map_append] + congr 1 + · apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [Nat.div_div_eq_div_mul, ← Nat.pow_succ', show (n - 1 - i).succ = n + 1 - 1 - i by omega] + · simp [normByte, SolidCore.Solidity.Shared.Account.byte] + +theorem input_eq (σ : List (Nat × Nat)) (dst : Nat) (a : CallResponse) (w : Nat) + (hv : (Sync.retWord a).toNat = w) (hge : slotValue σ 2 ≤ w) : + List.map (fun x => x % 256) (List.map normByte (payInput dst (w - slotValue σ 2))) = + Skim.transferInput σ dst a := by + have hr : slotValue σ 2 < 2 ^ 256 := slotValue_lt σ 2 + have hamt : (Skim.amtW σ a).toNat = w - slotValue σ 2 := by + unfold Skim.amtW + rw [BitVec.toNat_sub_of_le (by rw [BitVec.le_def, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hr, hv]; exact hge), + BitVec.toNat_ofNat, Nat.mod_eq_of_lt hr, hv] + rw [Skim.transferInput, hamt, payInput, srcBytesBE_eq, srcBytesBE_eq] + simp [Skim.wordBE, normByte, SolidCore.Solidity.Shared.Account.byte, wordBytes_eq] + congr 1 <;> apply List.map_congr_left <;> intro i _ <;> simp [Function.comp, normByte, + SolidCore.Solidity.Shared.Account.byte, Nat.mod_mod] + +/-- SolidCore's Error("TRANSFER_FAILED") bytes. -/ +def errB : Option (List OByte) := errorBytes "TRANSFER_FAILED" + +kernel_rfl errB_eq errB (some (Skim.errData.map OByte.lit)) using SolidCore.Verify.VC.Calls.selector_eq + +theorem errB_eq' : errorBytes "TRANSFER_FAILED" = some (Skim.errData.map OByte.lit) := errB_eq + +theorem skimCall_eq (σ : List (Nat × Nat)) (dst : Nat) : + Skim.skimCall σ dst = Evm.Wide.callAt 3156594551 [BitVec.ofNat 256 dst] σ := rfl + +set_option maxHeartbeats 4000000 in +theorem skim_source (k : Nat) (V : World) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {d : SolidCore.Solidity.Source.State} (hd : Wide.DeployedAt (k + 8) c d []) + (hfind : c.core.findFunctionBySelector? 3156594551 = some skimFn) + (hpay : c.core.table.lookup? payName = some payFn) + (hfields : c.core.storageFields = callsFields) + (hstatic : StaticKeeps V) + (hstaticT : ∀ h world request a, V.ans h (.external world (.call request)) = some a → + request.kind = .staticcall → ∀ slot, transientIn a.postWorld slot = transientIn world slot) (hdt : d.transient.toList = []) (hde : d.envWorld? = none) + (hcb : c.core.context.accountBalances = []) (hch : c.core.context.accountCodehashes = []) + (hcc : c.core.context.accountCodes = []) (hkeys : ∀ p ∈ V.codes.getD [], p.1 < 2 ^ 160) + (hsize : ∀ h world request a, V.ans h (.external world (.call request)) = some a → + a.returnData.size < 2 ^ 256) + (hsize64 : ∀ h world request a, V.ans h (.external world (.call request)) = some a → + a.returnData.size < 2 ^ 64) (σ : List (Nat × Nat)) (dst : Nat) (hdst : dst < 2 ^ 160) + (hself : slotValue σ 1 % 2 ^ 160 ≠ selfAddress) : Skim.SkimSource (k + 8) c V σ dst := by + have hlt := slotValue_lt σ + intro obs hrun + rw [skimCall_eq, runIn_eq_at V hd] at hrun + simp only [Source.ABI.Oracle.callCalldata, Dirty.readSelector_calldata _ (by decide : 3156594551 < 2 ^ 32), hfind] at hrun + have hdst' : (BitVec.ofNat 256 dst).toNat = dst := by + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt (lt_trans hdst (by decide))] + simp only [List.map_cons, List.map_nil, hdst'] at hrun + rw [show List.drop ABI.selectorBytes (List.map (fun x => x.toNat) (EthLib.Base.natToBytes 4 3156594551) ++ + Dirty.argBytes [dst]) = Dirty.argBytes [dst] by simp [ABI.selectorBytes, EthLib.Base.natToBytes_length], + decode_args (ws := [160]) rfl [dst] rfl (by simp; exact lt_trans hdst (by decide))] at hrun + have hcl : argsClean [160] [dst] = true := by simp [argsClean]; omega + simp only [hcl, ↓reduceIte, show skimFn.acceptsValue 0 = true from rfl, List.map_cons, List.map_nil] at hrun + generalize hctx : ABI.Contract.callContextAtWithBase c.core (ctxIn V c) selfAddress callerAddress 0 + (List.map (fun x => x.toNat) (EthLib.Base.natToBytes 4 3156594551) ++ Dirty.argBytes [dst]) = ctx at hrun + generalize hst : ({ d with storage := σ.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) d.storage } : + SolidCore.Solidity.Source.State) = st0 at hrun + have hctxv : ctx.value = 0 := by subst hctx; rfl + have hctxs : ctx.self = selfAddress := by subst hctx; rfl + have hframe : skimFn.initialFrame? [Value.word dst] = some [("to", Value.word dst)] := by + simp [FunctionDef.initialFrame?, skimFn, BindingDecl.bindArgs?, BindingDecl.bindArg?, + coerce_param (Or.inr rfl) dst, FunctionDef.returnDefaultBindings] + simp only [Source.callAns, FunctionDef.call, FunctionDef.evalBodyEntry, hctxv, + show skimFn.acceptsValue 0 = true from rfl, ↓reduceIte, hframe, Option.map_some, Option.bind_some] at hrun + generalize hrt0 : ({ state := { st0 with selfBalance := Solidity.Shared.addWord (Solidity.Shared.Account.balanceAt ctx.accountBalances ctx.self) 0, worldMutatedSinceAdoption := true }, locals := [[("to", Value.word dst)]] } : Runtime) = rt0 at hrun + have hrt0l : rt0.locals = [[("to", Value.word dst)]] := by rw [← hrt0] + rw [show skimFn.body = Stmt.block [Stmt.skip, Stmt.block + [Stmt.varDecl Ty.address "_sol_hoist_2" (some (Expr.var "to")), + Stmt.varDecl Ty.uint256 "_sol_hoist_1" + (some (Expr.castOp CastKind.uintCleanup 256 (Expr.storageRead StorageReadMode.ref "reserve" []))), + Stmt.varDecl Ty.uint256 "_sol_hoist_0" none, + skimTryS, + Stmt.block skimPayS]] from rfl] at hrun + rw [eval_block, evalList_cons, eval_skip, sbind_pure] at hrun + dsimp only at hrun + rw [evalList_cons, eval_block, evalList_cons, eval_varDecl_some, + varE ctx _ "to" dst (by simp [Runtime.lookupStorageBase?, Runtime.lookupLocal?, Runtime.pushScope, hrt0l, + LocalEnv.lookup?, Frame.lookup?]) (by simp [Runtime.lookupLocal?, Runtime.pushScope, hrt0l, + LocalEnv.lookup?, Frame.lookup?]), caught_done_ok, bind_done_ok] at hrun + dsimp only at hrun + rw [coerce_param (Or.inr rfl) dst, sbind_pure] at hrun + dsimp only at hrun + have hctxf : ctx.storageFields = callsFields := by subst hctx; exact hfields + have hfr : FieldOk ctx "reserve" reserveField := + ⟨by simp [Context.storageField?, hctxf, callsFields, reserveField, tokenField], rfl, rfl, by decide, by decide, + by decide⟩ + have hfx : AddrFieldOk ctx "token" tokenField := + ⟨by simp [Context.storageField?, hctxf, callsFields, tokenField], rfl, rfl, rfl, by decide, by decide⟩ + have hload : ∀ k, k < Generic.wordSize → st0.loadSlot k = slotValue σ k := by + intro k hk + have := getD_storage_cover hd (σ := σ) (by intro kv hkv; simp at hkv) k + subst hst + simp only [State.loadSlot, StorageMap.lookup?] + rw [← this] + simp only [SolidCore.Solidity.Shared.norm, modulus_eq, Std.HashMap.get?_eq_getElem?] + cases (List.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) d.storage σ)[k % Generic.wordSize]? <;> rfl + have hst0 : (rt0.pushScope.pushScope.declareLocal "_sol_hoist_2" (Value.word dst)).state.loadSlot 2 = slotValue σ 2 := by + rw [← hrt0]; exact hload 2 (by decide) + rw [evalList_cons, eval_varDecl_some, reserve_eval ctx _ hfr (by rw [show reserveField.slot = 2 from rfl, hst0]; exact hlt 2), + caught_done_ok, bind_done_ok] at hrun + dsimp only at hrun + rw [coerce_param (Or.inl rfl), sbind_pure] at hrun + dsimp only at hrun + rw [evalList_cons, eval_varDecl_none, sbind_pure] at hrun + dsimp only at hrun + rw [evalList_cons, skimTryS] at hrun + generalize hR : Runtime.declareLocal _ "_sol_hoist_0" _ = R at hrun + have hRs : R.state = rt0.state := by rw [← hR]; rfl + have hRl : R.locals = [[("_sol_hoist_0", Value.word 0), + ("_sol_hoist_1", Value.word (fieldValue (slotValue σ 2) 0 32)), ("_sol_hoist_2", Value.word dst)], [], + [("to", Value.word dst)]] := by + rw [← hR, ← hst0]; simp [Runtime.declareLocal, Runtime.pushScope, LocalEnv.declare, hrt0l, Ty.defaultValue]; rfl + clear hR + have hT : R.state.loadSlot tokenField.slot = slotValue σ 1 := by + rw [hRs, ← hrt0]; exact hload 1 (by decide) + have ht := tok_eval ctx R hfx (by rw [hT]; exact hlt 1) + rw [hT] at ht + have hne : wordEq (SolidCore.Solidity.Shared.norm (fieldValue (slotValue σ 1) tokenField.packedOffset 20)) ctx.self = false := by + rw [hctxs] + simp only [wordEq, fieldValue, tokenField, SolidCore.Solidity.Shared.norm] + simp + have h1 : slotValue σ 1 % 1461501637330902918203684832716283019655932542976 < Solidity.Shared.wordModulus := + lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (by decide) + rw [Nat.mod_eq_of_lt h1, Nat.mod_eq_of_lt (by decide : selfAddress < Solidity.Shared.wordModulus)] + exact hself + rw [show k + 6 = (k + 5) + 1 from rfl, + eval_tryCall (k + 5) _ ctx _ _ _ _ _ false _ _ _ _ ht rfl (word0_eval ctx _) rfl (enc_eval ctx _ hctxs) rfl hne] at hrun + generalize hW : snapshotWorld ctx R.state = world at hrun + generalize hRq : buildCallRequest ctx Solidity.Shared.Call.ExternalCallKind.staticcall + (Solidity.Shared.norm (fieldValue (slotValue σ 1) tokenField.packedOffset 20)) + (List.map normByte encSync) (Solidity.Shared.norm 0) none = request at hrun + simp only [bind_request, map_request] at hrun + rw [foldAns_request] at hrun + have hmut : R.state.worldMutatedSinceAdoption = true := by rw [hRs, ← hrt0] + have hwf : StorageMap.WF R.state.storage := by + rw [hRs, ← hrt0, ← hst]; exact wf_foldl σ _ (wf_of_toList_nil _ hd.storage) + have hworld : ∀ slot < 2 ^ 256, storageIn world slot = slotValue σ slot % 2 ^ 256 := by + intro slot hslot + have hl := hload slot hslot + have hsto : R.state.storage = st0.storage := by rw [hRs, ← hrt0] + subst hW + unfold storageIn accountIn + rw [show wordToAddress selfAddress = wordToAddress ctx.self by rw [hctxs], + snapshotWorld_find_self ctx _ (Or.inr hmut)] + simp only [Option.getD_some, snapshotSelfAccount] + rw [lookup?_roundtrip _ hwf, hsto] + unfold State.loadSlot at hl + cases h : StorageMap.lookup? st0.storage slot with + | none => rw [h] at hl; simp [← hl] + | some v => rw [h] at hl; simp [← hl, SolidCore.Solidity.Shared.norm]; rfl + have htrans : ∀ slot < 2 ^ 256, transientIn world slot = 0 := by + intro slot hslot + have htr : R.state.transient = d.transient := by rw [hRs, ← hrt0, ← hst] + subst hW + unfold transientIn accountIn + rw [show wordToAddress selfAddress = wordToAddress ctx.self by rw [hctxs], + snapshotWorld_find_self ctx _ (Or.inr hmut)] + simp only [Option.getD_some, snapshotSelfAccount] + rw [lookup?_roundtrip _ (by rw [htr]; exact wf_of_toList_nil _ hdt), htr] + have hnone : StorageMap.lookup? d.transient slot = none := by + unfold StorageMap.lookup? + rw [Std.HashMap.get?_eq_getElem?] + cases h : d.transient[SolidCore.Solidity.Shared.norm slot]? with + | none => rfl + | some v => + have := Std.HashMap.mem_toList_iff_getElem?_eq_some.mpr h + rw [hdt] at this; cases this + rw [hnone]; rfl + have hacc : ctx.accountCodes = V.codes.getD [] := by + subst hctx + show V.codes.getD c.core.context.accountCodes = V.codes.getD [] + rw [hcc] + have hcodes : ∀ x < 2 ^ 160, (codeIn world x).isEmpty = + (SolidCore.Solidity.Shared.Account.codeAt (V.codes.getD []) x).isEmpty := by + intro x hx + rw [← hacc] + subst hW + apply codeIn_snapshot + · rw [hRs, ← hrt0, ← hst]; exact hde + · subst hctx; exact hcb + · subst hctx; exact hch + · rw [hacc]; exact hkeys + · rw [hctxs]; decide + · exact hx + cases hans : V.ans [] (Query.external world (ExternalRequest.call request)) with + | none => simp [hans] at hrun + | some a => + simp only [hans] at hrun + have hask : Sync.SyncAsk σ V world request a := by + refine ⟨hans, by subst hRq; rfl, ?_, by subst hRq; rfl, ?_, hworld, htrans, hcodes, hsize _ _ _ _ hans⟩ + · subst hRq + simp [buildCallRequest, addressToWord, wordToAddress, wordToU256, fieldValue, tokenField, + EvmYul.AccountAddress.ofUInt256, SolidCore.Solidity.Shared.norm] + have h1 : slotValue σ 1 % 1461501637330902918203684832716283019655932542976 < + Solidity.Shared.wordModulus := lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (by decide) + rw [Nat.mod_eq_of_lt h1] + simp [EvmYul.UInt256.ofNat, EvmYul.AccountAddress.size, Fin.ofNat, Id.run, EvmYul.UInt256.size] + · subst hRq + show byteArrayToBytes (bytesToByteArray (List.map normByte encSync)) = List.map BitVec.toNat Sync.input + simp only [byteArrayToBytes, toList_eq_data, bytesToByteArray] + decide + refine ⟨world, request, a, hask, ?_⟩ + simp only [tryTail, decodeCallResponse] at hrun + cases hs : a.success + · have hE : Skim.Early σ a := Or.inl hs + refine ⟨fun _ => ?_, fun h => absurd hE h⟩ + simp only [hs, Bool.false_eq_true, ↓reduceIte, findMatch_nil] at hrun + simp only [sbind_pure, map_pure', foldAns_pure, Result.mapRuntime, FunctionDef.callBodyResult, + RevertData.fromRawBytes, normByte_bytes] at hrun + have hout : ∀ out, ABI.Contract.encodeRevertData? c.core + (if (byteArrayToBytes a.returnData == []) = true then SolidCore.Solidity.Source.RevertData.empty + else SolidCore.Solidity.Source.RevertData.raw (byteArrayToBytes a.returnData)).untagFixedBytes = some out → + out = byteArrayToBytes a.returnData := by + intro out h + split at h + · rename_i he + simp only [beq_iff_eq] at he + simp only [RevertData.untagFixedBytes, ABI.Contract.encodeRevertData?, Option.some.injEq] at h + rw [← h, he] + · simp only [RevertData.untagFixedBytes, ABI.Contract.encodeRevertData?, Option.some.injEq] at h + rw [← h] + exact normByte_bytes a.returnData + simp only [Option.bind_eq_bind, Option.map_bind] at hrun + obtain ⟨out, hout', hobs⟩ := Option.bind_eq_some_iff.mp hrun + rw [hout out hout'] at hobs + simp only [Function.comp, Option.map_some, Option.some.injEq] at hobs + rw [← hobs] + simp only [Source.observe, Skim.obsEarly, Skim.failObs, hs, Bool.false_eq_true, ↓reduceIte, byteArrayToBytes_eq] + rfl + · simp only [hs, ↓reduceIte, normByte_bytes, List.map_cons, List.map_nil] at hrun + by_cases hlen : (byteArrayToBytes a.returnData).length < 32 + · have hsz : a.returnData.size < 32 := by + rw [byteArrayToBytes_eq, List.length_map, List.length_range] at hlen; exact hlen + have hE : Skim.Early σ a := Or.inr (Or.inl hsz) + refine ⟨fun _ => ?_, fun h => absurd hE h⟩ + rw [decode_short _ hlen] at hrun + simp only [sbind_pure, map_pure', foldAns_pure, Result.mapRuntime, FunctionDef.callBodyResult, + RevertData.untagFixedBytes, ABI.Contract.encodeRevertData?, Option.bind_eq_bind, Option.bind_some, + Option.map_some, Option.some.injEq] at hrun + rw [← hrun] + simp only [Source.observe, Skim.obsEarly, Skim.failObs, hs, ↓reduceIte, hsz] + rfl + · have hsz : 32 ≤ a.returnData.size := by + rw [byteArrayToBytes_eq, List.length_map, List.length_range] at hlen; omega + rw [decode_word _ (by omega)] at hrun + simp only [normByte_bytes] at hrun + have hv : (Sync.retWord a).toNat = bytesToWordBE (List.take 32 (byteArrayToBytes a.returnData)) := + retWord_toNat a hsz + generalize hw : bytesToWordBE (List.take 32 (byteArrayToBytes a.returnData)) = w at hrun hv + have hwlt : w < 2 ^ 256 := by rw [← hw]; exact Nat.mod_lt _ (by decide) + simp only [AbiCleanups.acceptOrUnspecified] at hrun + have hacc : AbiCleanups.accept [AbiCleanup.uint 256] [Value.word w] = true := by + simp [AbiCleanups.accept, AbiCleanup.accepts, SolidCore.Solidity.Shared.norm] + first + | exact decide_eq_true (Nat.mod_lt w (by decide : 0 < Solidity.Shared.wordModulus)) + | exact Nat.mod_lt w (by decide : 0 < Solidity.Shared.wordModulus) + have hbind : BindingDecl.bindArgs? [{ name := "__ext0", ty := Ty.uint256 }] [Value.word w] = + some [("__ext0", Value.word w)] := by + simp [BindingDecl.bindArgs?, BindingDecl.bindArg?, Ty.coerceValue?, SolidCore.Solidity.Shared.norm, + Nat.mod_eq_of_lt hwlt] + simp only [hacc, hbind, Bool.or_true, ↓reduceIte] at hrun + generalize hQ : Runtime.withFrame _ [("__ext0", Value.word w)] = Q at hrun + have hQl : Q.locals = [("__ext0", Value.word w)] :: R.locals := by rw [← hQ]; rfl + rw [hRl] at hQl + rw [show k + 5 = (k + 4) + 1 from rfl, assign_cast_var (k + 4) _ ctx Q "_sol_hoist_0" "__ext0" w hwlt + [[("__ext0", Value.word w)], [("_sol_hoist_0", Value.word w), + ("_sol_hoist_1", Value.word (fieldValue (slotValue σ 2) 0 32)), ("_sol_hoist_2", Value.word dst)], [], + [("to", Value.word dst)]] + (by simp [Runtime.lookupStorageBase?, Runtime.lookupLocal?, hQl, LocalEnv.lookup?, Frame.lookup?]) + (by simp [Runtime.lookupMemoryRef?, Runtime.lookupLocal?, hQl, LocalEnv.lookup?, Frame.lookup?]) + ⟨0, by simp [Runtime.lookupLocal?, hQl, LocalEnv.lookup?, Frame.lookup?]⟩ + (by simp [Runtime.lookupStorageBase?, Runtime.lookupLocal?, hQl, LocalEnv.lookup?, Frame.lookup?]) + (by simp [Runtime.lookupLocal?, hQl, LocalEnv.lookup?, Frame.lookup?]) + (by simp [hQl, LocalEnv.assign?, Frame.assign?])] at hrun + simp only [sbind_pure, Result.mapRuntime] at hrun + have hres : fieldValue (slotValue σ 2) 0 32 = slotValue σ 2 := by + have := hlt 2; simp [fieldValue]; done + rw [hres] at hrun + generalize hT : Runtime.popScope _ = T at hrun + have hTl : T.locals = [[("_sol_hoist_0", Value.word w), ("_sol_hoist_1", Value.word (slotValue σ 2)), + ("_sol_hoist_2", Value.word dst)], [], [("to", Value.word dst)]] := by rw [← hT]; rfl + rw [evalList_cons, eval_block, skimPayS, evalList_cons, eval_varDecl_some, + varE ctx _ "_sol_hoist_2" dst (by simp [Runtime.lookupStorageBase?, Runtime.lookupLocal?, Runtime.pushScope, hTl, + LocalEnv.lookup?, Frame.lookup?]) (by simp [Runtime.lookupLocal?, Runtime.pushScope, hTl, + LocalEnv.lookup?, Frame.lookup?]), caught_done_ok, bind_done_ok] at hrun + dsimp only at hrun + rw [coerce_param (Or.inr rfl), sbind_pure] at hrun + dsimp only at hrun + have hctxc : ctx.checked = true := by subst hctx; rfl + rw [evalList_cons, eval_varDecl_some, amt_eval ctx _ w (slotValue σ 2) hwlt (hlt 2) hctxc + (by simp [Runtime.lookupStorageBase?, Runtime.lookupLocal?, Runtime.pushScope, Runtime.declareLocal, hTl, + LocalEnv.declare, LocalEnv.lookup?, Frame.lookup?]) + (by simp [Runtime.lookupLocal?, Runtime.pushScope, Runtime.declareLocal, hTl, LocalEnv.declare, + LocalEnv.lookup?, Frame.lookup?]) + (by simp [Runtime.lookupStorageBase?, Runtime.lookupLocal?, Runtime.pushScope, Runtime.declareLocal, hTl, + LocalEnv.declare, LocalEnv.lookup?, Frame.lookup?]) + (by simp [Runtime.lookupLocal?, Runtime.pushScope, Runtime.declareLocal, hTl, LocalEnv.declare, + LocalEnv.lookup?, Frame.lookup?])] at hrun + by_cases hlw : w < slotValue σ 2 + · have hE : Skim.Early σ a := Or.inr (Or.inr (by rw [hv]; exact hlw)) + refine ⟨fun _ => ?_, fun h => absurd hE h⟩ + simp only [hlw, ↓reduceIte, caught_revert, bind_done_ok] at hrun + simp only [sbind_pure, Result.mapRuntime, map_pure', foldAns_pure, FunctionDef.callBodyResult] at hrun + have hpd : (panicBytes 17).map (OByte.eval ⟨[], fun _ => 0, solHash, SolidCore.Refinement.Generic.callerWord⟩) = Skim.panicData := by rfl + simp only [RevertData.overflow, RevertData.untagFixedBytes, encode_panic ⟨[], fun _ => 0, solHash, SolidCore.Refinement.Generic.callerWord⟩, hpd, Option.bind_some, + Option.map_some, Option.some.injEq] at hrun + simp only [bind, Option.bind, Option.map, Option.some.injEq] at hrun + subst hrun + have hns : ¬ a.returnData.size < 32 := by omega + simp only [Source.observe, Skim.obsEarly, Skim.failObs, hs, ↓reduceIte, hns] + rfl + have hnE : ¬ Skim.Early σ a := by + rintro (h | h | h) + · rw [hs] at h; cases h + · omega + · rw [hv] at h; exact hlw h + refine ⟨fun h => absurd h hnE, fun _ => ?_⟩ + simp only [hlw, ↓reduceIte, caught_done_ok, bind_done_ok] at hrun + try dsimp only at hrun + rw [coerce_param (Or.inl rfl), sbind_pure] at hrun + dsimp only at hrun + rw [evalList_cons, eval_captureReturn_nil] at hrun + generalize hU : Runtime.declareLocal _ "_ic_arg_1" _ = U at hrun + have hUl : U.locals = [[("_ic_arg_1", Value.word (w - slotValue σ 2)), ("_ic_arg_0", Value.word dst)], + [("_sol_hoist_0", Value.word w), ("_sol_hoist_1", Value.word (slotValue σ 2)), + ("_sol_hoist_2", Value.word dst)], [], [("to", Value.word dst)]] := by + rw [← hU]; simp [Runtime.declareLocal, Runtime.pushScope, LocalEnv.declare, hTl] + have hamt : w - slotValue σ 2 < 2 ^ 256 := lt_of_le_of_lt (Nat.sub_le _ _) hwlt + rw [show k + 4 = (k + 3) + 1 from rfl, eval_internalCall (k + 3) _ ctx U [] payName _ payFn _ U _ + (refArgs2 ctx U "_ic_arg_0" "_ic_arg_1" dst (w - slotValue σ 2) + (by simp [Runtime.lookupStorageBase?, Runtime.lookupLocal?, hUl, LocalEnv.lookup?, Frame.lookup?]) + (by simp [Runtime.lookupMemoryRef?, Runtime.lookupLocal?, hUl, LocalEnv.lookup?, Frame.lookup?]) + (by simp [Runtime.lookupLocal?, hUl, LocalEnv.lookup?, Frame.lookup?]) + (by simp [Runtime.lookupStorageBase?, Runtime.lookupLocal?, hUl, LocalEnv.lookup?, Frame.lookup?]) + (by simp [Runtime.lookupMemoryRef?, Runtime.lookupLocal?, hUl, LocalEnv.lookup?, Frame.lookup?]) + (by simp [Runtime.lookupLocal?, hUl, LocalEnv.lookup?, Frame.lookup?])) + hpay (pay_frame dst _ hdst hamt)] at hrun + have hUs : U.state.storage = (adoptWorld a.postWorld ctx R.state).storage := by + rw [← hU, ← hT, ← hQ]; rfl + have hadopt : ∀ j, (adoptWorld a.postWorld ctx R.state).loadSlot j = storageIn a.postWorld j := by + intro j + simp only [adoptWorld, State.loadSlot, storageIn, accountIn, hctxs] + cases StorageMap.lookup? _ j <;> rfl + have hpost : ∀ j < 2 ^ 256, storageIn a.postWorld j = slotValue σ j := by + intro j hj + rw [hstatic _ _ _ _ hans (by subst hRq; rfl) j, hworld j hj, Nat.mod_eq_of_lt (hlt j)] + have hU1 : U.state.loadSlot tokenField.slot = slotValue σ 1 := by + rw [show U.state.loadSlot tokenField.slot = (adoptWorld a.postWorld ctx R.state).loadSlot 1 by + unfold State.loadSlot; rw [hUs]; rfl, hadopt, hpost 1 (by decide)] + have hfx' : AddrFieldOk { ctx with checked := true } "token" tokenField := + ⟨by simp [Context.storageField?, hctxf, callsFields, tokenField], rfl, rfl, rfl, by decide, by decide⟩ + generalize hP : (⟨U.state, _, U.memory, U.nextMemory, U.nextMemoryByte⟩ : Runtime) = P at hrun + have hPs : P.state = U.state := by rw [← hP] + have hPl : P.locals = [[("to", Value.word dst), ("amount", Value.word (w - slotValue σ 2))]] := by rw [← hP] + obtain ⟨kk, hk, hkk⟩ := pay_run k _ { ctx with checked := true } P dst (w - slotValue σ 2) hdst hamt hPl hfx' + (by rw [hPs, hU1]; exact hlt 1) (by subst hctx; rfl) (by rw [hPs, hU1]; exact hne) + rw [show payFn.body = payBody from rfl, hk] at hrun + simp only [bind_request, map_request] at hrun + rw [foldAns_request] at hrun + have hUenv : U.state.envWorld? = some a.postWorld := by rw [← hU, ← hT, ← hQ]; rfl + have hUmut : U.state.worldMutatedSinceAdoption = false := by rw [← hU, ← hT, ← hQ]; rfl + have hW2 : snapshotWorld { ctx with checked := true } P.state = a.postWorld := by + rw [hPs]; simp [snapshotWorld, hUenv, hUmut] + rw [hW2] at hrun + generalize hRq2 : buildCallRequest { ctx with checked := true } LowLevelCallKind.call _ _ _ none = request2 at hrun + cases hans2 : V.ans ([] ++ [{ query := Query.external world (ExternalRequest.call request), answer := a }]) + (Query.external a.postWorld (ExternalRequest.call request2)) with + | none => rw [hans2] at hrun; simp at hrun + | some a2 => + simp only [hans2] at hrun + refine ⟨a.postWorld, request2, a2, ?_, ?_⟩ + · refine ⟨by rw [List.nil_append] at hans2; exact hans2, by subst hRq2; rfl, ?_, by subst hRq2; rfl, ?_, ?_, ?_, fun _ _ => rfl, ?_⟩ + · subst hRq2 + rw [hPs, hU1] + simp [buildCallRequest, addressToWord, wordToAddress, wordToU256, fieldValue, tokenField, + EvmYul.AccountAddress.ofUInt256, SolidCore.Solidity.Shared.norm] + have h1 : slotValue σ 1 % 1461501637330902918203684832716283019655932542976 < + Solidity.Shared.wordModulus := lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (by decide) + rw [Nat.mod_eq_of_lt h1] + simp [EvmYul.UInt256.ofNat, EvmYul.AccountAddress.size, Fin.ofNat, Id.run, EvmYul.UInt256.size] + · subst hRq2 + simp only [buildCallRequest, bytes_roundtrip] + exact input_eq σ dst a w hv (Nat.le_of_not_lt hlw) + · intro slot hslot + rw [hstatic _ _ _ _ hans (by subst hRq; rfl) slot, hworld slot hslot] + · intro slot hslot + rw [hstaticT _ _ _ _ hans (by subst hRq; rfl) slot, htrans slot hslot] + · exact hsize64 _ _ _ _ hans2 + · obtain ⟨R2, hR2s, hk2⟩ := hkk a2 (hsize _ _ _ _ hans2) + simp only [hk2, sbind_pure] at hrun + simp only [decodeCallResponse] at hrun hR2s + have hl2 : (byteArrayToBytes a2.returnData).length = a2.returnData.size := by + rw [byteArrayToBytes_eq, List.length_map, List.length_range] + have hwq : 32 ≤ a2.returnData.size → bytesToWordBE (List.take 32 (List.map (normByte ∘ normByte) + (byteArrayToBytes a2.returnData))) = (Sync.retWord a2).toNat := by + intro h32 + rw [← List.map_map, normByte_bytes, normByte_bytes, retWord_toNat a2 h32] + have hcr : ∀ r, skimFn.collectReturns r = .ok [] := fun _ => rfl + have hst2 : ∀ j, R2.state.loadSlot j = storageIn a2.postWorld (j % 2 ^ 256) := by + intro j + rw [hR2s] + simp only [payState, adoptWorld, State.loadSlot, storageIn, accountIn, hctxs] + simp only [StorageMap.lookup?, SolidCore.Solidity.Shared.norm, Std.HashMap.get?_eq_getElem?] + have hmm : j % 2 ^ 256 % SolidCore.Solidity.Shared.wordModulus = j % SolidCore.Solidity.Shared.wordModulus := + Nat.mod_mod j _ + rw [hmm] + cases (storageToWordMap _)[j % SolidCore.Solidity.Shared.wordModulus]? <;> rfl + have hev2 : R2.state.events = [] := by + rw [hR2s] + show P.state.events = [] + have hUe : U.state.events = R.state.events := by rw [← hU, ← hT, ← hQ]; rfl + rw [hPs, hUe, hRs, ← hrt0, ← hst] + exact hd.events + have hemp : ABI.Contract.encodeRevertData? c.core RevertData.empty = some [] := by + simp [ABI.Contract.encodeRevertData?] + have he : ABI.Contract.encodeRevertData? c.core (RevertData.error "TRANSFER_FAILED") = some Skim.errData := by + rw [encode_error ⟨[], fun _ => 0, solHash, SolidCore.Refinement.Generic.callerWord⟩ c.core errB_eq', List.map_map] + decide + simp only [payRes, hl2] at hrun + split_ifs at hrun with h1 h2 h3 h4 h5 + all_goals simp only [Result.mapRuntime, finish_reverted, finish_normal_nil payFn rfl, sbind_pure, + map_pure', foldAns_pure, FunctionDef.callBodyResult, evalList_nil] at hrun + all_goals simp only [hcr, List.map_nil, show ABI.encodeValues? (List.map BindingDecl.ty skimFn.returns) [] = some [] from rfl, + RevertData.untagFixedBytes, he, hemp, Option.bind_eq_bind, Option.bind_some, + Option.map_some, Option.some.injEq] at hrun + all_goals try subst hrun + all_goals simp only [Source.observe, Skim.obsLate, Skim.failObs, Skim.okObs] + · simp only [h1, h2, ↓reduceIte, if_true, Runtime.popScope, State.logEntries, hev2, List.map_nil] + congr 1 + funext slot + exact hst2 slot + · simp only [h1, h2, h3, ↓reduceIte] + rfl + · have h32 : 32 ≤ a2.returnData.size := by omega + rw [hwq h32] at h4 h5 + simp only [h1, h2, h3, ↓reduceIte, h5, show ¬ 1 < 0 by omega] + rfl + · have h32 : 32 ≤ a2.returnData.size := by omega + rw [hwq h32] at h4 h5 + simp only [h1, h2, h3, ↓reduceIte, h5, Nat.not_lt.mpr h4, if_true, + Runtime.popScope, State.logEntries, hev2, List.map_nil] + congr 1 + funext slot + exact hst2 slot + · have h32 : 32 ≤ a2.returnData.size := by omega + rw [hwq h32] at h4 + simp only [h1, h2, h3, ↓reduceIte, Nat.lt_of_not_le h4] + rfl + · simp only [h1, Bool.false_eq_true, ↓reduceIte] + rfl + +/-- info: 'SolidCore.Refinement.CallFamilies.skim_source' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms skim_source + +/-- **skim's source stage in the world V**: under every oracle that agrees with V (CallsAgree o V), +solar's stage0 runs skim(dst) as SolidCore runs it in V, for every recipient below 2 ^ 160 and every +storage whose token is not the contract itself. Hypotheses: the checked contract's skim, pay and +fields are skimFn, payFn and callsFields, its constructor leaves no storage, transient storage, +adopted world or seeded accounts; V's seeded code is at addresses below 2 ^ 160 and its answers' +return data is shorter than 2 ^ 64 bytes. -/ +theorem skim_stage_in (k : Nat) (V : World) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {d : SolidCore.Solidity.Source.State} (hd : Wide.DeployedAt (k + 8) c d []) + (hfind : c.core.findFunctionBySelector? 3156594551 = some skimFn) + (hpay : c.core.table.lookup? payName = some payFn) + (hfields : c.core.storageFields = callsFields) + (hdt : d.transient.toList = []) (hde : d.envWorld? = none) + (hcb : c.core.context.accountBalances = []) (hch : c.core.context.accountCodehashes = []) + (hcc : c.core.context.accountCodes = []) (hkeys : ∀ p ∈ V.codes.getD [], p.1 < 2 ^ 160) + (hsize64 : ∀ h world request a, V.ans h (.external world (.call request)) = some a → + a.returnData.size < 2 ^ 64) + (o : Machine.Oracle) (agree : CallsAgree o V) : + Stage (solidCoreIn V (k + 8)) (MIR.Lowered.moduleSem o) c SolarTV.Export.Calls.stage0 + (fun call => ∃ σ dst, (dst < 2 ^ 160 ∧ slotValue σ 1 % 2 ^ 160 ≠ selfAddress) ∧ call = Skim.skimCall σ dst) := + Skim.skim_stage (k + 8) c V _ (fun _ _ h => h.1) + (fun σ dst h => skim_source k V hd hfind hpay hfields + (fun h w r a ha hk slot => (agree.static h w r a ha hk slot).1) + (fun h w r a ha hk slot => (agree.static h w r a ha hk slot).2) + hdt hde hcb hch hcc hkeys + (fun h w r a ha => lt_trans (hsize64 h w r a ha) (by decide)) hsize64 σ dst h.1 h.2) + o agree + +/-- info: 'SolidCore.Refinement.CallFamilies.skim_stage_in' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms skim_stage_in + +end SolidCore.Refinement.CallFamilies diff --git a/Contracts/CallFamilies/Source.lean b/Contracts/CallFamilies/Source.lean new file mode 100644 index 00000000..0044bf63 --- /dev/null +++ b/Contracts/CallFamilies/Source.lean @@ -0,0 +1,169 @@ +-- Generated from Contracts/CallFamilies/Calls.sol with solc 0.8.35 by scripts/solc_ast_to_lean_source.py. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Verify +namespace VC +namespace Source +namespace Calls + +def importedSourceName : String := "Contracts/CallFamilies/Calls.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.interface + name := "IBalance" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "balanceOf", + visibility := some Visibility.external_, + mutability := StateMutability.view, + params := [{ name := some "owner", ty := Ty.address false, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := none })] } + +def importedContractDecl1 : ContractDecl := +{ kind := ContractKind.interface + name := "IFeeTo" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "feeTo", + visibility := some Visibility.external_, + mutability := StateMutability.view, + params := [], + returns := [{ name := none, ty := Ty.address false, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := none })] } + +def importedContractDecl2 : ContractDecl := +{ kind := ContractKind.interface + name := "ICallback" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "onFlash", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "sender", ty := Ty.address false, location := none }, { name := some "amount", ty := Ty.uint 256, location := none }, { name := some "data", ty := Ty.bytes, location := some DataLocation.calldata }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := none })] } + +def importedContractDecl3 : ContractDecl := +{ kind := ContractKind.contract + name := "Calls" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "TRANSFER", + ty := Ty.bytesN 4, + visibility := some Visibility.private_, + mutability := VarMutability.constant, + override? := none, + init := some (Expr.call (Expr.typeName (Ty.bytesN 4)) [Arg.positional (Expr.call (Expr.ident "keccak256") [Arg.positional (Expr.call (Expr.typeName (Ty.bytes)) [Arg.positional (Expr.literal (Literal.string "transfer(address,uint256)"))])])]) }), (ContractItem.stateVar + { name := "factory", + ty := Ty.address false, + visibility := some Visibility.public_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "token", + ty := Ty.address false, + visibility := some Visibility.public_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "reserve", + ty := Ty.uint 256, + visibility := some Visibility.public_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "kLast", + ty := Ty.uint 256, + visibility := some Visibility.public_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.function + { kind := FunctionKind.function, + name := some "pay", + visibility := some Visibility.private_, + mutability := StateMutability.nonpayable, + params := [{ name := some "to", ty := Ty.address false, location := none }, { name := some "amount", ty := Ty.uint 256, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.varDecl [{ name := some "ok", ty := Ty.bool, location := none }, { name := some "ret", ty := Ty.bytes, location := some DataLocation.memory }] (some (Expr.call (Expr.member (Expr.ident "token") "call") [Arg.positional (Expr.call (Expr.member (Expr.ident "abi") "encodeWithSelector") [Arg.positional (Expr.ident "TRANSFER"), Arg.positional (Expr.ident "to"), Arg.positional (Expr.ident "amount")])])), Stmt.expr (Expr.call (Expr.ident "require") [Arg.positional (Expr.binary BinaryOp.boolAnd (Expr.ident "ok") (Expr.binary BinaryOp.boolOr (Expr.binary BinaryOp.eq (Expr.member (Expr.ident "ret") "length") (Expr.literal (Literal.number "0"))) (Expr.call (Expr.member (Expr.ident "abi") "decode") [Arg.positional (Expr.ident "ret"), Arg.positional (Expr.tuple [TupleItem.value (Expr.typeName (Ty.bool))])]))), Arg.positional (Expr.literal (Literal.string "TRANSFER_FAILED"))])]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "sync", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "reserve") AssignOp.assign (Expr.call (Expr.member (Expr.call (Expr.typeName (Ty.user ({ segments := ["IBalance"] }))) [Arg.positional (Expr.ident "token")]) "balanceOf") [Arg.positional (Expr.call (Expr.typeName (Ty.address false)) [Arg.positional (Expr.ident "this")])]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "skim", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "to", ty := Ty.address false, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.ident "pay") [Arg.positional (Expr.ident "to"), Arg.positional (Expr.binary BinaryOp.sub (Expr.call (Expr.member (Expr.call (Expr.typeName (Ty.user ({ segments := ["IBalance"] }))) [Arg.positional (Expr.ident "token")]) "balanceOf") [Arg.positional (Expr.call (Expr.typeName (Ty.address false)) [Arg.positional (Expr.ident "this")])]) (Expr.ident "reserve"))])]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "feeOn", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := some "on", ty := Ty.bool, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "on") AssignOp.assign (Expr.binary BinaryOp.ne (Expr.call (Expr.member (Expr.call (Expr.typeName (Ty.user ({ segments := ["IFeeTo"] }))) [Arg.positional (Expr.ident "factory")]) "feeTo") []) (Expr.call (Expr.typeName (Ty.address false)) [Arg.positional (Expr.literal (Literal.number "0"))]))), Stmt.ifElse (Expr.ident "on") (Stmt.expr (Expr.assign (Expr.ident "kLast") AssignOp.assign (Expr.literal (Literal.number "1")))) none]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "flash", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "to", ty := Ty.address false, location := none }, { name := some "amount", ty := Ty.uint 256, location := none }, { name := some "data", ty := Ty.bytes, location := some DataLocation.calldata }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.ident "pay") [Arg.positional (Expr.ident "to"), Arg.positional (Expr.ident "amount")]), Stmt.ifElse (Expr.binary BinaryOp.gt (Expr.member (Expr.ident "data") "length") (Expr.literal (Literal.number "0"))) (Stmt.expr (Expr.call (Expr.member (Expr.call (Expr.typeName (Ty.user ({ segments := ["ICallback"] }))) [Arg.positional (Expr.ident "to")]) "onFlash") [Arg.positional (Expr.member (Expr.ident "msg") "sender"), Arg.positional (Expr.ident "amount"), Arg.positional (Expr.ident "data")])) none]) })] } + +def importedContract : ContractDecl := + importedContractDecl3 + +def importedContracts : List ContractDecl := + [importedContractDecl0, importedContractDecl1, importedContractDecl2, importedContractDecl3] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.0", SourceItem.contract importedContractDecl0, SourceItem.contract importedContractDecl1, SourceItem.contract importedContractDecl2, SourceItem.contract importedContractDecl3] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end Calls +end Source +end VC +end Verify +end SolidCore diff --git a/Contracts/CallFamilies/SourceFacts.lean b/Contracts/CallFamilies/SourceFacts.lean new file mode 100644 index 00000000..01c23b18 --- /dev/null +++ b/Contracts/CallFamilies/SourceFacts.lean @@ -0,0 +1,102 @@ +import Contracts.CallFamilies.Core +import Contracts.CallFamilies.FeeOnSource + +/-! +# The source stages of `sync` and `feeOn` for `Calls`'s checked core + +The hypotheses `sync_stage_in` and `feeOn_stage_in` take of the checked contract (its `sync` and +`feeOn` bodies, its storage fields, an empty account seed, and a constructor that leaves no storage, +logs, transient storage or adopted world) hold of SolidCore's checked `Calls`: the kernel evaluates +the type checker once (`kernel_rfl`, with the selectors from `Core`'s table) and compares the +result with the literals the stages use. `calls_sync_stage` and `calls_feeOn_stage` are the +stages with only the world's hypotheses left: `CallsAgree o V`, seeded code at addresses below +`2 ^ 160`, and return data shorter than `2 ^ 256` bytes. +-/ + +namespace SolidCore.Refinement.CallFamilies + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Refinement.CallNode +open SolidCore.Solidity.Source EvmCompiler.Simulation +open SolidCore.Verify.VC.Calls (contract? fuel) + +/-- What the constructor of `c` leaves: no storage, no logs, no transient storage, no adopted +world. -/ +def deployFacts (c : SolidCore.Solidity.TypeCheck.CheckedContract) : Bool := + match SolidCore.Solidity.TypeCheck.CheckedContract.constructWithContext? fuel c (Wide.ctxOf c) + State.empty selfAddress 0 [] with + | some (CallResult.returned d _) => + d.storage.toList.isEmpty && d.events.isEmpty && d.transient.toList.isEmpty && d.envWorld?.isNone + | _ => false + +theorem deployFacts_of {c : SolidCore.Solidity.TypeCheck.CheckedContract} (h : deployFacts c = true) : + ∃ d, Wide.DeployedAt fuel c d [] ∧ d.transient.toList = [] ∧ d.envWorld? = none := by + unfold deployFacts at h + split at h + next d vs hc => + simp only [Bool.and_eq_true, List.isEmpty_iff, Option.isNone_iff_eq_none] at h + exact ⟨d, ⟨⟨vs, hc⟩, h.1.1.1, h.1.1.2⟩, h.1.2, h.2⟩ + next => simp at h + +/-- The facts of the checked `Calls` the stages take. -/ +def callsFacts : Option (Option FunctionDef × Option FunctionDef × List StorageField × Bool) := + match contract? with + | .ok c => some (c.core.findFunctionBySelector? 4294363881, c.core.findFunctionBySelector? 1328766218, + c.core.storageFields, + c.core.context.accountBalances.isEmpty && c.core.context.accountCodehashes.isEmpty && + c.core.context.accountCodes.isEmpty && deployFacts c) + | .error _ => none + +kernel_rfl callsFacts_eq callsFacts (some (some syncFn, some feeOnFn, callsFields, true)) using SolidCore.Verify.VC.Calls.selector_eq SolidCore.Verify.VC.mkIdx_eq + +theorem calls_facts : ∃ c, contract? = .ok c ∧ + c.core.findFunctionBySelector? 4294363881 = some syncFn ∧ + c.core.findFunctionBySelector? 1328766218 = some feeOnFn ∧ + c.core.storageFields = callsFields ∧ + c.core.context.accountBalances = [] ∧ c.core.context.accountCodehashes = [] ∧ + c.core.context.accountCodes = [] ∧ + ∃ d, Wide.DeployedAt fuel c d [] ∧ d.transient.toList = [] ∧ d.envWorld? = none := by + have h := callsFacts_eq + unfold callsFacts at h + split at h + next c hc => + simp only [Option.some.injEq, Prod.mk.injEq, Bool.and_eq_true, List.isEmpty_iff] at h + obtain ⟨h1, h2, h3, ⟨⟨hb, hh⟩, hcc⟩, hdep⟩ := h + exact ⟨c, hc, h1, h2, h3, hb, hh, hcc, deployFacts_of hdep⟩ + next => simp at h + +/-- **sync's source stage for `Calls`**: SolidCore's checked `Calls` in a world `V` refines solar's +stage0 on `sync()` under every oracle agreeing with `V`, from every storage whose token is not the +contract itself. -/ +theorem calls_sync_stage : ∃ c, contract? = .ok c ∧ ∀ (V : World), + (∀ p ∈ V.codes.getD [], p.1 < 2 ^ 160) → + (∀ h world request a, V.ans h (.external world (.call request)) = some a → + a.returnData.size < 2 ^ 256) → + ∀ (o : Machine.Oracle), CallsAgree o V → + Stage (solidCoreIn V fuel) (MIR.Lowered.moduleSem o) c SolarTV.Export.Calls.stage0 + (fun call => ∃ σ, slotValue σ 1 % 2 ^ 160 ≠ selfAddress ∧ call = Sync.syncCall σ) := by + obtain ⟨c, hc, h1, -, h3, hb, hh, hcc, d, hd, hdt, hde⟩ := calls_facts + exact ⟨c, hc, fun V hk hs o agree => + sync_stage_in 4091 V hd h1 h3 hdt hde hb hh hcc hk hs o agree⟩ + +/-- **feeOn's source stage for `Calls`**, from every storage whose factory is not the contract +itself. -/ +theorem calls_feeOn_stage : ∃ c, contract? = .ok c ∧ ∀ (V : World), + (∀ p ∈ V.codes.getD [], p.1 < 2 ^ 160) → + (∀ h world request a, V.ans h (.external world (.call request)) = some a → + a.returnData.size < 2 ^ 256) → + ∀ (o : Machine.Oracle), CallsAgree o V → + Stage (solidCoreIn V fuel) (MIR.Lowered.moduleSem o) c SolarTV.Export.Calls.stage0 + (fun call => ∃ σ, slotValue σ 0 % 2 ^ 160 ≠ selfAddress ∧ call = FeeOn.feeOnCall σ) := by + obtain ⟨c, hc, -, h2, h3, hb, hh, hcc, d, hd, hdt, hde⟩ := calls_facts + exact ⟨c, hc, fun V hk hs o agree => + feeOn_stage_in 4091 V hd h2 h3 hdt hde hb hh hcc hk hs o agree⟩ + +/-- info: 'SolidCore.Refinement.CallFamilies.calls_sync_stage' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms calls_sync_stage + +/-- info: 'SolidCore.Refinement.CallFamilies.calls_feeOn_stage' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms calls_feeOn_stage + +end SolidCore.Refinement.CallFamilies diff --git a/Contracts/CallFamilies/Stage0.lean b/Contracts/CallFamilies/Stage0.lean new file mode 100644 index 00000000..609ca96f --- /dev/null +++ b/Contracts/CallFamilies/Stage0.lean @@ -0,0 +1,382 @@ +-- solar-lean-stage: kind=mir index=0 pass=lower-evm-shaped +import SolarTV.MIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `Calls`; do not edit. -/ + +namespace SolarTV.Export.Calls + +/-- The first lowered MIR module, after `lower-evm-shaped` advanced the phase. -/ +def stage0 : MIR.Lowered.Module := + { entry := 10, + functions := [ + -- @factory + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 0], + .pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @token + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 1], + .pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect none .mstore [.const 0, .value 8]], + .ret (.const 0) (.const 32)⟩] }, + -- @reserve + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 2], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @kLast + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 3], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @sync + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 1) .sload [.const 1], + .effect (some 4) .gas [], + .effect (some 5) .address [], + .effect none .mstore [.const 0, .const 0x70a08231], + .effect none .mstore [.const 32, .value 5], + .effect (some 15) (.call .staticcall) [.value 4, .value 1, .const 28, .const 36, .const 0, .const 32], + .assume true .gt [.value 5, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 15) 2 1⟩, + -- bb1 + ⟨[], + [.effect (some 23) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 23], + .effect (some 24) .returndatasize []], + .revert (.const 0) (.value 24)⟩, + -- bb2 + ⟨[], + [.effect (some 17) .returndatasize [], + .pure 18 .lt [.value 17, .const 32]], + .branch (.value 18) 3 4⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 19) .mload [.const 0], + .effect none .sstore [.const 2, .value 19]], + .stop⟩], + entryHeap := some 128 }, + -- @skim + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 37) .calldatasize [], + .pure 39 .lt [.value 37, .const 36], + .effect (some 41) .calldataload [.const 4], + .pure 43 .gt [.value 41, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 50 .or [.value 39, .value 43]], + .branch (.value 50) 3 7⟩, + -- bb1 + ⟨[], + [.effect (some 34) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 34], + .effect (some 35) .returndatasize []], + .revert (.const 0) (.value 35)⟩, + -- bb2 + ⟨[], + [.effect (some 18) .returndatasize [], + .pure 19 .lt [.value 18, .const 32]], + .branch (.value 19) 3 4⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 20) .mload [.const 0], + .effect (some 22) .sload [.const 2], + .pure 25 .sub [.value 20, .value 22], + .pure 26 .lt [.value 20, .value 22]], + .branch (.value 26) 5 6⟩, + -- bb5 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb6 + ⟨[], + [.call none 8 [.value 41, .value 41, .value 25], + .assume true .gt [.value 41, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .stop⟩, + -- bb7 + ⟨[], + [.pure 47 .and [.value 41, .const 0xffffffffffffffffffffffffffffffffffffffff], + .effect (some 2) .sload [.const 1], + .effect (some 5) .gas [], + .effect (some 6) .address [], + .effect none .mstore [.const 0, .const 0x70a08231], + .effect none .mstore [.const 32, .value 6], + .effect (some 16) (.call .staticcall) [.value 5, .value 2, .const 28, .const 36, .const 0, .const 32], + .assume true .gt [.value 6, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 47, .value 41]], + .branch (.value 16) 2 1⟩], + entryHeap := some 128 }, + -- @feeOn + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 1) .sload [.const 0], + .effect (some 4) .gas [], + .effect none .mstore [.const 0, .const 0x17e7e58], + .effect (some 12) (.call .staticcall) [.value 4, .value 1, .const 28, .const 4, .const 0, .const 32]], + .branch (.value 12) 2 1⟩, + -- bb1 + ⟨[], + [.effect (some 26) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 26], + .effect (some 27) .returndatasize []], + .revert (.const 0) (.value 27)⟩, + -- bb2 + ⟨[], + [.effect (some 14) .returndatasize [], + .pure 15 .lt [.value 14, .const 32]], + .branch (.value 15) 5 6⟩, + -- bb3 + ⟨[], + [.effect none .sstore [.const 3, .const 1]], + .jump 4⟩, + -- bb4 + ⟨[], + [.word 31 (.value 21), + .effect none .mstore [.const 0, .value 31]], + .ret (.const 0) (.const 32)⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb6 + ⟨[], + [.effect (some 16) .mload [.const 0], + .pure 18 .gt [.value 16, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 18) 5 7⟩, + -- bb7 + ⟨[], + [.pure 34 .and [.value 16, .const 0xffffffffffffffffffffffffffffffffffffffff], + .ne 21 (.value 16) (.const 0), + .assume false .eq [.value 34, .value 16]], + .branch (.value 21) 3 4⟩], + entryHeap := some 128 }, + -- @flash + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 27) .calldatasize [], + .pure 29 .lt [.value 27, .const 100], + .effect (some 31) .calldataload [.const 4], + .pure 33 .gt [.value 31, .const 0xffffffffffffffffffffffffffffffffffffffff], + .pure 112 .or [.value 29, .value 33], + .effect (some 35) .calldataload [.const 36], + .effect (some 38) .calldataload [.const 68], + .pure 39 .add [.value 38, .const 4], + .pure 43 .sub [.value 27, .const 36], + .pure 44 .lt [.value 43, .value 38], + .effect (some 45) .calldataload [.value 39], + .pure 46 .add [.value 39, .const 32], + .pure 47 .sub [.value 27, .value 46], + .pure 48 .lt [.value 47, .value 45], + .pure 49 .or [.value 44, .value 48], + .pure 113 .or [.value 112, .value 49]], + .branch (.value 113) 4 6⟩, + -- bb1 + ⟨[], + [.effect (some 7) .gas [], + .effect (some 8) .caller [], + .effect (some 100) .mload [.const 64], + .effect none .mstore [.value 100, .const 0x75870edb00000000000000000000000000000000000000000000000000000000], + .pure 59 .add [.value 100, .const 4], + .pure 61 .add [.value 59, .const 96], + .effect none .mstore [.value 59, .value 8], + .pure 63 .add [.value 59, .const 32], + .effect none .mstore [.value 63, .value 35], + .pure 65 .add [.value 59, .const 64], + .effect none .mstore [.value 65, .const 96], + .pure 70 .add [.value 45, .const 31], + .pure 72 .and [.value 70, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0], + .pure 73 .add [.value 61, .const 32], + .pure 74 .add [.value 61, .value 72], + .effect none .mstore [.value 74, .const 0], + .effect none .mstore [.value 61, .value 45], + .pure 77 .add [.value 73, .value 72], + .effect none .calldatacopy [.value 73, .value 46, .value 45], + .pure 78 .sub [.value 77, .value 59], + .pure 80 .add [.value 78, .const 4], + .effect (some 16) (.env "extcodesize") [.value 31], + .pure 18 .eq [.value 16, .const 0], + .assume true .gt [.value 8, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 18) 4 5⟩, + -- bb2 + ⟨[], + [], + .stop⟩, + -- bb3 + ⟨[], + [.effect (some 24) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 24], + .effect (some 25) .returndatasize []], + .revert (.const 0) (.value 25)⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb5 + ⟨[], + [.effect (some 20) (.call .call) [.value 7, .value 31, .const 0, .value 100, .value 80, .const 0, .const 0]], + .branch (.value 20) 2 3⟩, + -- bb6 + ⟨[], + [.pure 102 .and [.value 31, .const 0xffffffffffffffffffffffffffffffffffffffff], + .call none 8 [.value 31, .value 31, .value 35], + .ne 5 (.value 45) (.const 0), + .assume true .gt [.value 31, .const 0xffffffffffffffffffffffffffffffffffffffff], + .assume false .eq [.value 102, .value 31]], + .branch (.value 5) 1 2⟩], + entryHeap := some 128 }, + -- @pay + { params := [0, 100, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 3) .sload [.const 1], + .effect (some 6) .gas [], + .heapFloor 91 128, + .effect (some 93) .mload [.const 64], + .assume false .eq [.value 91, .value 93], + .pure 94 .add [.value 91, .const 128], + .effect none .mstore [.const 64, .value 94], + .pure 82 .add [.value 91, .const 32], + .effect none .mstore [.value 82, .const 0xa9059cbb00000000000000000000000000000000000000000000000000000000], + .pure 84 .add [.value 91, .const 36], + .effect none .mstore [.value 84, .value 0], + .pure 79 .add [.value 84, .const 32], + .effect none .mstore [.value 79, .value 1], + .effect (some 27) (.call .call) [.value 6, .value 3, .const 0, .value 82, .const 68, .const 0, .const 0], + .effect (some 28) .returndatasize [], + .pure 105 .add [.value 28, .const 63], + .pure 34 .and [.value 105, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0], + .assume false .lt [.value 28, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc1], + .assume false .eq [.const 0, .const 0], + .pure 98 .add [.value 94, .value 34], + .effect none .mstore [.const 64, .value 98], + .effect none .mstore [.value 94, .value 28], + .pure 86 .add [.value 94, .const 32], + .effect none .returndatacopy [.value 86, .const 0, .value 28], + .assume true .gt [.value 100, .const 0xffffffffffffffffffffffffffffffffffffffff]], + .branch (.value 27) 1 3⟩, + -- bb1 + ⟨[], + [.effect (some 12) .mload [.value 94], + .pure 14 .eq [.value 28, .const 0], + .assume false .eq [.value 12, .value 28]], + .branch (.value 14) 4 2⟩, + -- bb2 + ⟨[], + [.effect (some 56) .mload [.value 94], + .pure 60 .slt [.value 28, .const 32], + .assume false .eq [.value 56, .value 28]], + .branch (.value 60) 5 6⟩, + -- bb3 + ⟨[], + [], + .tailCall 9 [.const 15, .const 0x5452414e534645525f4641494c45440000000000000000000000000000000000]⟩, + -- bb4 + ⟨[], + [], + .leave []⟩, + -- bb5 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb6 + ⟨[], + [.effect (some 63) .mload [.value 86], + .pure 65 .gt [.value 63, .const 1]], + .branch (.value 65) 5 7⟩, + -- bb7 + ⟨[], + [.ne 69 (.value 63) (.const 0)], + .branch (.value 69) 4 3⟩] }, + -- @revert_error + { params := [0, 1], + blocks := [ + -- bb0 + ⟨[], + [.effect none .mstore [.const 32, .const 32], + .effect none .mstore [.const 64, .value 0], + .effect none .mstore [.const 96, .value 1], + .effect none .mstore [.const 0, .const 0x8c379a0]], + .revert (.const 28) (.const 100)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 10 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 10 [(.const 0x4f335d0a, 2), (.const 0x7464fc3d, 3), (.const 0xbc25cf77, 4), (.const 0xc45a0155, 5), (.const 0xcd3293de, 6), (.const 0xf740f328, 7), (.const 0xfc0c546a, 8), (.const 0xfff6cae9, 9)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 6 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 3 []⟩, + -- bb4 + ⟨[], + [], + .tailCall 5 []⟩, + -- bb5 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb6 + ⟨[], + [], + .tailCall 2 []⟩, + -- bb7 + ⟨[], + [], + .tailCall 7 []⟩, + -- bb8 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb9 + ⟨[], + [], + .tailCall 4 []⟩, + -- bb10 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +end SolarTV.Export.Calls diff --git a/Contracts/CallFamilies/StageOfSource.lean b/Contracts/CallFamilies/StageOfSource.lean new file mode 100644 index 00000000..b9078cf5 --- /dev/null +++ b/Contracts/CallFamilies/StageOfSource.lean @@ -0,0 +1,61 @@ +import Contracts.CallFamilies.SyncAgree +import Contracts.CallFamilies.FeeOnAgree + +/-! +# The source stages of `sync` and `feeOn` from their source halves + +`sync_stage` and `feeOn_stage` compose the MIR halves (`mir_sync_agree`, `mir_feeOn_agree`) with +the source half each function still needs, stated as a proposition of SolidCore alone +(`SyncSource`, `FeeOnSource`): a run of the function in the world `V` that shows `obs` asked `V` +the call the MIR makes, from the world the MIR sees, and shows what the MIR shows for `V`'s answer. +Given it for an open world `V`, every oracle that agrees with `V` (`CallsAgree o V`) runs solar's +stage0 as SolidCore runs the function in `V`: the source stage of a call-making function. The +source halves are not proved here; they are the generic call node's statement-level obligation +(`eraseStmt` of `tryExternalCall` under `foldAns`). +-/ + +namespace SolidCore.Refinement.CallFamilies + +open SolarTV SolarTV.Machine SolarTV.MIR.Lowered SolidCore.Refinement + +/-- The source half of `sync`'s stage in the world `V` from the storage `σ`. -/ +def SyncSource (fuel : Nat) (c : SolidCore.Solidity.TypeCheck.CheckedContract) (V : World) + (σ : List (Nat × Nat)) : Prop := + ∀ obs, Source.runIn V fuel c (Sync.syncCall σ) = some obs → + ∃ world request a, Sync.SyncAsk σ V world request a ∧ obs = Sync.obsOf σ a + +/-- The source half of `feeOn`'s stage in the world `V` from the storage `σ`. -/ +def FeeOnSource (fuel : Nat) (c : SolidCore.Solidity.TypeCheck.CheckedContract) (V : World) + (σ : List (Nat × Nat)) : Prop := + ∀ obs, Source.runIn V fuel c (FeeOn.feeOnCall σ) = some obs → + ∃ world request a, FeeOn.FeeOnAsk σ V world request a ∧ obs = FeeOn.obsOf σ a + +/-- **sync's source stage from its source half**, under every oracle that agrees with `V`. -/ +theorem sync_stage (fuel : Nat) (c : SolidCore.Solidity.TypeCheck.CheckedContract) (V : World) + (scope : List (Nat × Nat) → Prop) (src : ∀ σ, scope σ → SyncSource fuel c V σ) + (o : Oracle) (agree : CallsAgree o V) : + Stage (solidCoreIn V fuel) (moduleSem o) c SolarTV.Export.Calls.stage0 + (fun call => ∃ σ, scope σ ∧ call = Sync.syncCall σ) := by + rintro call ⟨σ, hσ, rfl⟩ obs hrun + obtain ⟨world, request, a, hs, rfl⟩ := src σ hσ obs hrun + exact Sync.mir_sync_agree o V σ world request a agree hs + +/-- **feeOn's source stage from its source half**, under every oracle that agrees with `V`. -/ +theorem feeOn_stage (fuel : Nat) (c : SolidCore.Solidity.TypeCheck.CheckedContract) (V : World) + (scope : List (Nat × Nat) → Prop) (src : ∀ σ, scope σ → FeeOnSource fuel c V σ) + (o : Oracle) (agree : CallsAgree o V) : + Stage (solidCoreIn V fuel) (moduleSem o) c SolarTV.Export.Calls.stage0 + (fun call => ∃ σ, scope σ ∧ call = FeeOn.feeOnCall σ) := by + rintro call ⟨σ, hσ, rfl⟩ obs hrun + obtain ⟨world, request, a, hs, rfl⟩ := src σ hσ obs hrun + exact FeeOn.mir_feeOn_agree o V σ world request a agree hs + +/-- info: 'SolidCore.Refinement.CallFamilies.sync_stage' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms sync_stage + +/-- info: 'SolidCore.Refinement.CallFamilies.feeOn_stage' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms feeOn_stage + +end SolidCore.Refinement.CallFamilies diff --git a/Contracts/CallFamilies/SyncAgree.lean b/Contracts/CallFamilies/SyncAgree.lean new file mode 100644 index 00000000..ccc79159 --- /dev/null +++ b/Contracts/CallFamilies/SyncAgree.lean @@ -0,0 +1,160 @@ +import Contracts.CallFamilies.SyncMir +import SolidCore.Refinement.SourceOracle + +/-! +# `sync` in solar's MIR under the oracle hypothesis + +`mir_sync_agree`: under `CallsAgree o W`, when SolidCore's run of `sync()` in the world `W` asks +`W` the call `SyncAsk` describes (a `STATICCALL` of the token in slot 1 with solc's +`balanceOf(address(this))` input, from a world holding the call's storage) and `W` answers +`a`, solar's stage0 shows `obsOf σ a`: the callee's revert data when the call fails, an empty +revert when it returned fewer than 32 bytes, and otherwise the returned word in slot 2. This is the +MIR half of the source stage of `sync`, with the call's agreement (path induction for one call) +taken from `CallsAgree`. +-/ + +namespace SolidCore.Refinement.CallFamilies.Sync + +open SolarTV SolarTV.Machine SolarTV.MIR.Lowered SolidCore.Refinement +open EvmCompiler.Simulation +open SolidCore.Solidity.Source (addressToWord u256ToWord byteArrayToBytes) + +set_option linter.deprecated false + +/-- The first 32 bytes of the return data as a big-endian word, as `MLOAD` reads them. -/ +def retWord (a : CallResponse) : BitVec 256 := + ((List.range 32).map (fun i => BitVec.ofNat 8 (a.returnData.get! i).toNat)).foldl + (fun acc b => (acc <<< 8) ||| b.setWidth 256) 0 + +/-- What `sync()` shows when the token answers `a`. -/ +def obsOf (σ : List (Nat × Nat)) (a : CallResponse) : Observable := + if a.success then + if a.returnData.size < 32 then ⟨false, [], [], slotValue σ⟩ + else ⟨true, [], [], fun slot => + (update (State.initial (syncCall σ)).storage 2 (retWord a) (BitVec.ofNat 256 slot)).toNat⟩ + else ⟨false, (List.range a.returnData.size).map (fun j => (a.returnData.get! j).toNat), [], + slotValue σ⟩ + +/-- The call SolidCore's `sync()` asks `W`, with its answer. -/ +structure SyncAsk (σ : List (Nat × Nat)) (V : World) (world : SolidCore.Solidity.Shared.OpenWorld) + (request : CallRequest) (a : CallResponse) : Prop where + ans : V.ans [] (.external world (.call request)) = some a + kind : request.kind = .staticcall + callee : addressToWord request.codeAddress = slotValue σ 1 % 2 ^ 160 + value : u256ToWord request.transferValue = 0 + input : byteArrayToBytes request.calldata = input.map BitVec.toNat + storage : ∀ slot < 2 ^ 256, storageIn world slot = slotValue σ slot % 2 ^ 256 + transient : ∀ slot < 2 ^ 256, transientIn world slot = 0 + codes : ∀ x < 2 ^ 160, (codeIn world x).isEmpty = + (SolidCore.Solidity.Shared.Account.codeAt (V.codes.getD []) x).isEmpty + size : a.returnData.size < 2 ^ 256 + +theorem bytes_write (m : Mem) (off size : Nat) (src : Nat → Memory.Byte) (i : Nat) : + (m.write off size src).bytes i = if off ≤ i ∧ i < off + size then src (i - off) else m.bytes i := by + unfold Mem.write Mem.expand + split <;> rfl + +theorem bytes_expand (m : Mem) (off size i : Nat) : (m.expand off size).bytes i = m.bytes i := by + unfold Mem.expand + split <;> rfl + +theorem lt_word (a b : BitVec 256) : EvmRules.Evm.lt a b = if a.toNat < b.toNat then 1 else 0 := by + unfold EvmRules.Evm.lt + by_cases h : a.toNat < b.toNat + · have : a.ult b = true := by simp [BitVec.ult, h] + simp [this, h] + · have : a.ult b = false := by simp [BitVec.ult, h] + simp [this, h] + +/-- The oracle's answer to sync's call, from `CallsAgree`. -/ +theorem answer (o : Oracle) (V : World) (σ : List (Nat × Nat)) + (world : SolidCore.Solidity.Shared.OpenWorld) (request : CallRequest) (a : CallResponse) + (agree : CallsAgree o V) (hs : SyncAsk σ V world request a) : + ((callFlag o (W o σ) = 1) ↔ a.success = true) ∧ + (returndataSize o (W o σ)).toNat = a.returnData.size ∧ + ∀ j < a.returnData.size, (returndataByte o (W o σ) j).toNat = (a.returnData.get! j).toNat := by + have hcalls : machineCalls (W o σ) = + sourceCalls ([] ++ [⟨.external world (.call request), a⟩]) := by + simp only [W, machineCalls, sourceCalls, List.nil_append, hs.kind, hs.callee, hs.value, hs.input, + machineKind, List.getD] + simp + have hstore : ∀ slot < 2 ^ 256, + ((State.initial (syncCall σ)).storage (BitVec.ofNat 256 slot)).toNat = storageIn world slot ∧ + ((fun _ => (0 : BitVec 256)) (BitVec.ofNat 256 slot)).toNat = transientIn world slot := by + intro slot hslot + refine ⟨?_, ?_⟩ + · rw [hs.storage slot hslot] + simp only [State.initial, BitVec.toNat_ofNat] + rw [Nat.mod_eq_of_lt hslot] + rfl + · rw [hs.transient slot hslot]; rfl + have hcodes : CodesAgree o (W o σ).dropLast (codeIn world) := by + intro x hx + rw [hs.codes x hx] + exact agree.codes [.read "gas"] rfl x hx + obtain ⟨hflag, -, hrest⟩ := agree.calls [] world request a hs.ans (W o σ) .staticcall _ _ _ _ + rfl hcalls hstore hcodes + obtain ⟨hsz, hby, -⟩ := hrest [] rfl + simp only [List.append_nil] at hsz hby + refine ⟨hflag, ?_, fun j hj => hby j hj (Nat.lt_trans hj hs.size)⟩ + rw [hsz, Nat.mod_eq_of_lt hs.size] + +theorem callFlag_cases (o : Oracle) (w : List Machine.Event) : callFlag o w = 0 ∨ callFlag o w = 1 := by + unfold callFlag; split <;> simp + +/-- **sync's MIR under the oracle hypothesis.** -/ +theorem mir_sync_agree (o : Oracle) (V : World) (σ : List (Nat × Nat)) + (world : SolidCore.Solidity.Shared.OpenWorld) (request : CallRequest) (a : CallResponse) + (agree : CallsAgree o V) (hs : SyncAsk σ V world request a) : + (moduleSem o).run SolarTV.Export.Calls.stage0 (syncCall σ) = some (obsOf σ a) := by + obtain ⟨hflag, hsize, hbytes⟩ := answer o V σ world request a agree hs + rw [sem_sync] + congr 1 + unfold mirEnd obsOf + by_cases hsucc : a.success = true + · have hf : callFlag o (W o σ) ≠ 0 := by + intro h; have := hflag.mpr hsucc; rw [h] at this; exact absurd this (by decide) + rw [if_neg hf, if_pos hsucc, lt_word, hsize] + by_cases hlt : a.returnData.size < 32 + · have : ¬ ((if a.returnData.size < (32 : BitVec 256).toNat then (1 : BitVec 256) else 0) = 0) := by + simp [hlt] + rw [if_neg this, if_pos hlt] + rfl + · have : ((if a.returnData.size < (32 : BitVec 256).toNat then (1 : BitVec 256) else 0) = 0) := by + simp [hlt] + rw [if_pos this, if_neg hlt] + have hload : (M4 o σ).load 0 = retWord a := by + unfold Mem.load Mem.read retWord + congr 1 + apply List.map_congr_left + intro i hi + rw [List.mem_range] at hi + have hmin : min 32 (returndataSize o (W o σ)).toNat = 32 := by rw [hsize]; omega + rw [M4, bytes_write, hmin] + simp only [Nat.zero_le, Nat.zero_add, hi, and_self, if_true, Nat.sub_zero] + apply BitVec.eq_of_toNat_eq + rw [hbytes i (by omega), BitVec.toNat_ofNat, Nat.mod_eq_of_lt (UInt8.toNat_lt _)] + simp only [observe, hload] + rfl + · have hf : callFlag o (W o σ) = 0 := by + rcases callFlag_cases o (W o σ) with h | h + · exact h + · exact absurd (hflag.mp h) hsucc + rw [if_pos hf, if_neg hsucc] + simp only [halt, if_true, observe] + congr 1 + rw [hsize] + unfold Mem.read + rw [List.map_map] + apply List.map_congr_left + intro i hi + rw [List.mem_range] at hi + simp only [Function.comp, bytes_expand, bytes_write, Nat.zero_le, Nat.zero_add] + simp [hi] + exact hbytes i hi + +/-- info: 'SolidCore.Refinement.CallFamilies.Sync.mir_sync_agree' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms mir_sync_agree + +end SolidCore.Refinement.CallFamilies.Sync diff --git a/Contracts/CallFamilies/SyncMir.lean b/Contracts/CallFamilies/SyncMir.lean new file mode 100644 index 00000000..d70be69d --- /dev/null +++ b/Contracts/CallFamilies/SyncMir.lean @@ -0,0 +1,146 @@ +import Contracts.CallFamilies.Stage0 +import SolidCore.Refinement.KernelThm + +/-! +# `sync` in solar's first lowered MIR, for every oracle + +`sem_sync`: solar's stage0 of `Contracts/CallFamilies/Calls.sol` (`SolarTV.Export.Calls.stage0`, `-Ogas`, +osaka) runs `sync()` from the storage `σ` to `mirEnd o σ` under every oracle `o`: it reads the +token (slot 1), makes one `STATICCALL` of `balanceOf(address(this))` (world `W o σ`), reverts with +the callee's return data when the call fails, reverts with empty data when it returned fewer than +32 bytes, and otherwise stores the returned word in slot 2. Each block step is the kernel's +conversion (`kernel_thm`); the steps whose guard depends on the oracle are split by cases. +-/ + +open SolidCore.Refinement.Kernel +open SolarTV SolarTV.Machine SolarTV.MIR.Lowered + +namespace SolidCore.Refinement.CallFamilies.Sync + +set_option linter.deprecated false + +def syncCall (σ : List (Nat × Nat)) : Call := + { calldata := ⟨#[0xff, 0xf6, 0xca, 0xe9]⟩, callvalue := 0, storage := σ } + +abbrev step (o : Oracle) (σ : List (Nat × Nat)) := moduleBlock o (syncCall σ) SolarTV.Export.Calls.stage0 + +def next {ς : Type} (st : ς → Option ((Halt × State) ⊕ ς)) (x : ς) : ς := + match st x with + | some (.inr y) => y + | _ => x + +def F0 (σ : List (Nat × Nat)) : Frame := ([], .enter 10 0 0, fun _ => 0, State.initial (syncCall σ)) +def F1 (o : Oracle) (σ : List (Nat × Nat)) : Frame := next (step o σ) (F0 σ) +def F2 (o : Oracle) (σ : List (Nat × Nat)) : Frame := next (step o σ) (F1 o σ) +def F3 (o : Oracle) (σ : List (Nat × Nat)) : Frame := next (step o σ) (F2 o σ) +def F4 (o : Oracle) (σ : List (Nat × Nat)) : Frame := next (step o σ) (F3 o σ) + +kernel_thm h0 : ∀ (o : Oracle) (σ : List (Nat × Nat)), step o σ (F0 σ) = some (.inr (F1 o σ)) +kernel_thm h1 : ∀ (o : Oracle) (σ : List (Nat × Nat)), step o σ (F1 o σ) = some (.inr (F2 o σ)) +kernel_thm h2 : ∀ (o : Oracle) (σ : List (Nat × Nat)), step o σ (F2 o σ) = some (.inr (F3 o σ)) +kernel_thm h3 : ∀ (o : Oracle) (σ : List (Nat × Nat)), step o σ (F3 o σ) = some (.inr (F4 o σ)) + +def mem1 : Mem := + ((Mem.initial.store 64 128).store 0 0x70a08231).store 32 (BitVec.ofNat 256 environment.callee) + +def input : List Memory.Byte := ((mem1.expand 28 36).expand 0 32).read 28 36 + +def W (o : Oracle) (σ : List (Nat × Nat)) : List Event := + [.read "gas", .call .staticcall [o.env "gas" [.read "gas"] [], BitVec.ofNat 256 (slotValue σ 1)] input + (State.initial (syncCall σ)).storage (fun _ => 0)] + +def M4 (o : Oracle) (σ : List (Nat × Nat)) : Mem := + ((mem1.expand 28 36).expand 0 32).write 0 (min 32 (returndataSize o (W o σ)).toNat) + (returndataByte o (W o σ)) + +def S4 (o : Oracle) (σ : List (Nat × Nat)) : State := + ⟨M4 o σ, (State.initial (syncCall σ)).storage, fun _ => 0, W o σ⟩ + +kernel_thm F4_eq : ∀ (o : Oracle) (σ : List (Nat × Nat)), F4 o σ = + ([], .enter 4 0 (if callFlag o (W o σ) = 0 then 1 else 2), (F4 o σ).2.2.1, S4 o σ) + +def G2 (o : Oracle) (σ : List (Nat × Nat)) (env : Env) : Frame := ([], .enter 4 0 2, env, S4 o σ) +def G2n (o : Oracle) (σ : List (Nat × Nat)) (env : Env) : Frame := next (step o σ) (G2 o σ env) + +kernel_thm g2 : ∀ (o : Oracle) (σ : List (Nat × Nat)) (env : Env), step o σ (G2 o σ env) = some (.inr (G2n o σ env)) +kernel_thm G2n_eq : ∀ (o : Oracle) (σ : List (Nat × Nat)) (env : Env), G2n o σ env = + ([], .enter 4 2 (if EvmRules.Evm.lt (returndataSize o (W o σ)) 32 = 0 then 4 else 3), (G2n o σ env).2.2.1, S4 o σ) + +kernel_thm g3 : ∀ (o : Oracle) (σ : List (Nat × Nat)) (env : Env), + step o σ ([], .enter 4 2 3, env, S4 o σ) = some (.inl (halt (S4 o σ) 0 0 true)) + +kernel_thm g4 : ∀ (o : Oracle) (σ : List (Nat × Nat)) (env : Env), + step o σ ([], .enter 4 2 4, env, S4 o σ) = some (.inl (.stop, + { S4 o σ with memory := (M4 o σ).expand 0 32, + storage := update (S4 o σ).storage 2 ((M4 o σ).load 0) })) + +def syncFn : Function := (SolarTV.Export.Calls.stage0.functions[4]?).getD ⟨[], [], none⟩ +kernel_thm fn4 : SolarTV.Export.Calls.stage0.functions[4]? = some syncFn +kernel_thm b1 : syncFn.blocks[1]? = some ⟨[], + [.effect (some 23) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 23], + .effect (some 24) .returndatasize []], + .revert (.const 0) (.value 24)⟩ + +theorem exec_b1 (o : Oracle) (call : Call) (env : Env) (s : State) : + execInsts o call [.effect (some 23) .returndatasize [], + .effect none .returndatacopy [.const 0, .const 0, .value 23], + .effect (some 24) .returndatasize []] env s = + some ((env.set 23 (returndataSize o s.world)).set 24 (returndataSize o s.world), + { s with memory := s.memory.write 0 (returndataSize o s.world).toNat (fun i => returndataByte o s.world (0 + i)) }) := by + simp only [execInsts, Effect.apply, List.map_cons, List.map_nil, Operand.eval] + have h : (env.set 23 (returndataSize o s.world)) 23 = returndataSize o s.world := by + simp [Env.set] + simp only [h, returndataSize] + simp + +theorem g1 (o : Oracle) (σ : List (Nat × Nat)) (env : Env) : + step o σ ([], .enter 4 0 1, env, S4 o σ) = some (.inl (halt + { S4 o σ with memory := (M4 o σ).write 0 (returndataSize o (W o σ)).toNat (fun i => returndataByte o (W o σ) (0 + i)) } 0 (returndataSize o (W o σ)) true)) := by + simp only [step, moduleBlock, fn4, b1, bindPhis, segment, splitCall, exec_b1] + simp [Operand.eval, Env.set, S4] + +theorem iter_next {ς : Type} {st : ς → Option ((Halt × State) ⊕ ς)} {n : Nat} {x y : ς} + (h : st x = some (.inr y)) : iterate st (n + 1) x = iterate st n y := by + conv => lhs; unfold iterate + rw [h] + +theorem iter_end {ς : Type} {st : ς → Option ((Halt × State) ⊕ ς)} {n : Nat} {x : ς} {r : Halt × State} + (h : st x = some (.inl r)) : iterate st (n + 1) x = some r := by + conv => lhs; unfold iterate + rw [h] + +/-- The end of solar's stage0 on a call of sync. -/ +def mirEnd (o : Oracle) (σ : List (Nat × Nat)) : Halt × State := + if callFlag o (W o σ) = 0 then + halt { S4 o σ with memory := (M4 o σ).write 0 (returndataSize o (W o σ)).toNat (fun i => returndataByte o (W o σ) (0 + i)) } 0 (returndataSize o (W o σ)) true + else if EvmRules.Evm.lt (returndataSize o (W o σ)) 32 = 0 then + (.stop, { S4 o σ with memory := (M4 o σ).expand 0 32, storage := update (S4 o σ).storage 2 ((M4 o σ).load 0) }) + else halt (S4 o σ) 0 0 true + +theorem run_sync (o : Oracle) (σ : List (Nat × Nat)) : + Module.run o SolarTV.Export.Calls.stage0 (syncCall σ) 7 = some (mirEnd o σ) := by + show iterate (step o σ) 7 (F0 σ) = _ + rw [iter_next (h0 o σ), iter_next (h1 o σ), iter_next (h2 o σ), iter_next (h3 o σ), F4_eq] + unfold mirEnd + by_cases hf : callFlag o (W o σ) = 0 + · rw [if_pos hf, if_pos hf, iter_end (g1 o σ _)] + · rw [if_neg hf, if_neg hf] + have e : (([], .enter 4 0 2, (F4 o σ).2.2.1, S4 o σ) : Frame) = G2 o σ (F4 o σ).2.2.1 := rfl + rw [e, iter_next (g2 o σ _), G2n_eq] + by_cases hl : EvmRules.Evm.lt (returndataSize o (W o σ)) 32 = 0 + · rw [if_pos hl, if_pos hl, iter_end (g4 o σ _)] + · rw [if_neg hl, if_neg hl, iter_end (g3 o σ _)] + +theorem sem_sync (o : Oracle) (σ : List (Nat × Nat)) : + (moduleSem o).run SolarTV.Export.Calls.stage0 (syncCall σ) = + some (observe (syncCall σ) (mirEnd o σ).2 (mirEnd o σ).1) := by + show (moduleLayer.result o _ _).map _ = _ + rw [moduleLayer.result_of_ends (show moduleLayer.Ends o SolarTV.Export.Calls.stage0 (syncCall σ) (mirEnd o σ) from ⟨7, run_sync o σ⟩)] + rfl + +/-- info: 'SolidCore.Refinement.CallFamilies.Sync.sem_sync' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms sem_sync + +end SolidCore.Refinement.CallFamilies.Sync diff --git a/Contracts/CallFamilies/SyncSource.lean b/Contracts/CallFamilies/SyncSource.lean new file mode 100644 index 00000000..5474e706 --- /dev/null +++ b/Contracts/CallFamilies/SyncSource.lean @@ -0,0 +1,463 @@ +import Contracts.CallFamilies.StageOfSource +import SolidCore.Refinement.Generic.StageIn +import SolidCore.Refinement.Generic.CallNode +import SolidCore.Solidity.AdoptionLaws + +namespace SolidCore.Refinement.CallFamilies + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Refinement.CallNode +open SolidCore.Solidity.Source EvmCompiler.Simulation + +/-- SolidCore's `sync()` of `Calls`, as the checker lowers it. -/ +def syncFn : FunctionDef := +{ name := "sync", + selector? := some 4294363881, + payable := false, + params := [], + paramAbiCleanups := [], + returns := [], + body := Stmt.block + [Stmt.block + [Stmt.varDecl (Ty.uint256) "_sol_hoist_0" none, + Stmt.tryExternalCall + (SolidCore.Solidity.Shared.Call.ExternalCallKind.staticcall) + (Expr.storageRead (StorageReadMode.ref) "token" []) + (Expr.encode (EncodeKind.withSelector) (some (Expr.word 1889567281)) [] + [Ty.address] [Expr.self]) + (Expr.word 0) none false false + [{ name := "__ext0", ty := Ty.uint256, isStorageRef := false }] + [AbiCleanup.uint 256] + (Stmt.assign (LValue.var "_sol_hoist_0") + (Expr.castOp (CastKind.uintCleanup) 256 (Expr.var "__ext0"))) + [], + Stmt.assign (LValue.storage "reserve") + (Expr.castOp (CastKind.uintCleanup) 256 (Expr.var "_sol_hoist_0"))]], + dispatchId? := none } + + + + +/-- The input of `balanceOf(address(this))`. -/ +def encSync : List Nat := [112, 160, 130, 49] ++ List.replicate 30 0 ++ [16, 0] + +theorem enc_eval (ctx : Context) (rt : Runtime) (h : ctx.self = selfAddress) : + (Expr.encode (EncodeKind.withSelector) (some (Expr.word 1889567281)) [] [Ty.address] + [Expr.self]).evalWithRuntimeByContext ctx rt = .ok (.bytes encSync, rt) := by + simp only [Expr.evalWithRuntimeByContext, Expr.eval, Expr.orderFuel, Expr.evalFuel, + Expr.listEvalFuel, Expr.evalListFuel, h] + simp [Runtime.materializeForValueUseList, mat_word, bind, pure, liftM, monadLift, + MonadLift.monadLift, SolI.ofExcept, ipure_bind] + rfl + +/-- `Calls`'s `token` field. -/ +def tokenField : StorageField := + { name := "token", + slot := 1, + ty? := some Ty.address, + layout? := some (StorageLayout.scalar Ty.address), + transient := false, + packedOffset := 0, + packedBytes := 20, + packedSigned := false } + +theorem tok_eval (ctx : Context) (rt : Runtime) (hf : AddrFieldOk ctx "token" tokenField) + (hw : rt.state.loadSlot tokenField.slot < Generic.wordSize) : + (Expr.storageRead .ref "token" []).evalWithRuntimeByContext ctx rt = + .ok (.word (fieldValue (rt.state.loadSlot tokenField.slot) tokenField.packedOffset 20), rt) := by + simp only [Expr.evalWithRuntimeByContext, Expr.eval, Expr.orderFuel, Expr.evalFuel, + Expr.listEvalFuel] + simp only [load_addrField hf hw] + rfl + + +theorem done_bind' {α β : Type} (a : α) (f : α → SolI β) : + (Interaction.done (Except.ok a) >>= f : SolI β) = f a := rfl + +/-- `Calls`'s storage fields. -/ +def callsFields : List StorageField := + [{ name := "factory", slot := 0, ty? := some Ty.address, + layout? := some (StorageLayout.scalar Ty.address), transient := false, packedOffset := 0, + packedBytes := 20, packedSigned := false }, + tokenField, + { name := "reserve", slot := 2, ty? := some Ty.uint256, + layout? := some (StorageLayout.scalar Ty.uint256), transient := false, packedOffset := 0, + packedBytes := 32, packedSigned := false }, + { name := "kLast", slot := 3, ty? := some Ty.uint256, + layout? := some (StorageLayout.scalar Ty.uint256), transient := false, packedOffset := 0, + packedBytes := 32, packedSigned := false }] + +theorem fold_mod (M : Nat) (l : List Nat) (x : Nat) : + (l.foldl (fun a b => a * 256 + b) (x % M)) % M = + (l.foldl (fun a b => a * 256 + b) x) % M := by + induction l generalizing x with + | nil => simp + | cons b l ih => + simp only [List.foldl_cons] + have h : (x % M * 256 + b) % M = (x * 256 + b) % M := by + simp [Nat.add_mod, Nat.mul_mod, Nat.mod_mod] + rw [← ih (x % M * 256 + b), h, ih] + +theorem step_or (acc : BitVec 256) (b : BitVec 8) : + ((acc <<< 8) ||| b.setWidth 256).toNat = (acc.toNat * 256 + b.toNat) % 2 ^ 256 := by + have hand : (acc <<< 8) &&& b.setWidth 256 = 0 := by + ext i hi + simp + intro h1 h2 + exact BitVec.getLsbD_of_ge b i (by omega) + rw [← BitVec.add_eq_or_of_and_eq_zero _ _ hand, BitVec.toNat_add, BitVec.toNat_shiftLeft, + BitVec.toNat_setWidth] + have hb := b.isLt + rw [Nat.mod_eq_of_lt (by omega : b.toNat < 2 ^ 256), Nat.shiftLeft_eq] + simp only [Nat.add_mod_mod, Nat.mod_add_mod] + +theorem fold_bv (bs : List (BitVec 8)) (acc : BitVec 256) : + (bs.foldl (fun (acc : BitVec 256) (b : BitVec 8) => (acc <<< 8) ||| b.setWidth 256) acc).toNat = + ((bs.map BitVec.toNat).foldl (fun a b => a * 256 + b) acc.toNat) % 2 ^ 256 := by + induction bs generalizing acc with + | nil => simp [Nat.mod_eq_of_lt acc.isLt] + | cons b bs ih => + simp only [List.foldl_cons, List.map_cons] + rw [ih, step_or, fold_mod] + +theorem retWord_toNat (a : CallResponse) (h : 32 ≤ a.returnData.size) : + (Sync.retWord a).toNat = bytesToWordBE (List.take 32 (byteArrayToBytes a.returnData)) := by + unfold Sync.retWord bytesToWordBE SolidCore.Solidity.Shared.norm + rw [fold_bv, byteArrayToBytes_eq, ← List.map_take, List.take_range, Nat.min_eq_left h] + simp only [List.map_map, BitVec.toNat_zero] + rw [List.foldl_map, List.foldl_map] + have : ∀ x : UInt8, (BitVec.ofNat 8 x.toNat).toNat = normByte x.toNat := by + intro x + simp [normByte, SolidCore.Solidity.Shared.Account.byte] + simp only [Function.comp, this] + rfl + +theorem syncCall_eq (σ : List (Nat × Nat)) : + Sync.syncCall σ = Evm.Wide.callAt 4294363881 [] σ := rfl + +/-- The world hypothesis a static call needs: its answer keeps the caller's storage. -/ +def StaticKeeps (V : World) : Prop := + ∀ h world request a, V.ans h (.external world (.call request)) = some a → + request.kind = .staticcall → ∀ slot, storageIn a.postWorld slot = storageIn world slot + +set_option maxHeartbeats 4000000 in +theorem sync_source (k : Nat) (V : World) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {d : SolidCore.Solidity.Source.State} (hd : Wide.DeployedAt (k + 5) c d []) + (hfind : c.core.findFunctionBySelector? 4294363881 = some syncFn) + (hfields : c.core.storageFields = callsFields) + (hstatic : StaticKeeps V) (hdt : d.transient.toList = []) (hde : d.envWorld? = none) + (hcb : c.core.context.accountBalances = []) (hch : c.core.context.accountCodehashes = []) + (hcc : c.core.context.accountCodes = []) (hkeys : ∀ p ∈ V.codes.getD [], p.1 < 2 ^ 160) + (hsize : ∀ h world request a, V.ans h (.external world (.call request)) = some a → + a.returnData.size < 2 ^ 256) (σ : List (Nat × Nat)) + (hself : slotValue σ 1 % 2 ^ 160 ≠ selfAddress) : SyncSource (k + 5) c V σ := by + have hlt := slotValue_lt σ + intro obs hrun + rw [syncCall_eq, runIn_eq_at V hd] at hrun + simp only [Source.ABI.Oracle.callCalldata, Dirty.readSelector_calldata _ (by decide : 4294363881 < 2 ^ 32), hfind] at hrun + simp only [show ABI.decodeFunctionArgs? syncFn (List.drop ABI.selectorBytes + (List.map (fun x => x.toNat) (EthLib.Base.natToBytes 4 4294363881) ++ + Dirty.argBytes (List.map (fun x => BitVec.toNat x) []))) = .ok [] from rfl, + show syncFn.acceptsValue 0 = true from rfl, ↓reduceIte] at hrun + generalize hctx : ABI.Contract.callContextAtWithBase c.core (ctxIn V c) selfAddress callerAddress 0 + (List.map (fun x => x.toNat) (EthLib.Base.natToBytes 4 4294363881) ++ + Dirty.argBytes (List.map (fun x => BitVec.toNat x) [])) = ctx at hrun + generalize hst : ({ d with storage := σ.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) d.storage } : + SolidCore.Solidity.Source.State) = st0 at hrun + have hctxv : ctx.value = 0 := by subst hctx; rfl + have hctxs : ctx.self = selfAddress := by subst hctx; rfl + simp only [Source.callAns, FunctionDef.call, FunctionDef.evalBodyEntry, hctxv, + show syncFn.acceptsValue 0 = true from rfl, ↓reduceIte, + show syncFn.initialFrame? [] = some [] from rfl, Option.map_some, Option.bind_some] at hrun + generalize hrt0 : ({ state := { st0 with selfBalance := Solidity.Shared.addWord (Solidity.Shared.Account.balanceAt ctx.accountBalances ctx.self) 0, worldMutatedSinceAdoption := true }, locals := [[]] } : Runtime) = rt0 at hrun + rw [show syncFn.body = Stmt.block [Stmt.block [Stmt.varDecl (Ty.uint256) "_sol_hoist_0" none, + Stmt.tryExternalCall + (SolidCore.Solidity.Shared.Call.ExternalCallKind.staticcall) + (Expr.storageRead (StorageReadMode.ref) "token" []) + (Expr.encode (EncodeKind.withSelector) (some (Expr.word 1889567281)) [] + [Ty.address] [Expr.self]) + (Expr.word 0) none false false + [{ name := "__ext0", ty := Ty.uint256, isStorageRef := false }] + [AbiCleanup.uint 256] + (Stmt.assign (LValue.var "_sol_hoist_0") + (Expr.castOp (CastKind.uintCleanup) 256 (Expr.var "__ext0"))) + [], + Stmt.assign (LValue.storage "reserve") + (Expr.castOp (CastKind.uintCleanup) 256 (Expr.var "_sol_hoist_0"))]] from rfl] at hrun + rw [eval_block, evalList_cons, eval_block, evalList_cons, eval_varDecl_none, sbind_pure] at hrun + simp only [evalList_cons] at hrun + have hctxf : ctx.storageFields = callsFields := by subst hctx; exact hfields + have hfx : AddrFieldOk ctx "token" tokenField := + ⟨by simp [Context.storageField?, hctxf, callsFields, tokenField], rfl, rfl, rfl, by decide, by decide⟩ + have hload : ∀ k, k < Generic.wordSize → st0.loadSlot k = slotValue σ k := by + intro k hk + have := getD_storage_cover hd (σ := σ) (by intro kv hkv; simp at hkv) k + subst hst + simp only [State.loadSlot, StorageMap.lookup?] + rw [← this] + simp only [SolidCore.Solidity.Shared.norm, modulus_eq, Std.HashMap.get?_eq_getElem?] + cases (List.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) d.storage σ)[k % Generic.wordSize]? <;> rfl + have hT : (rt0.pushScope.pushScope.declareLocal "_sol_hoist_0" Ty.uint256.defaultValue).state.loadSlot tokenField.slot = slotValue σ 1 := by + subst hrt0; exact hload 1 (by decide) + have ht := tok_eval ctx (rt0.pushScope.pushScope.declareLocal "_sol_hoist_0" Ty.uint256.defaultValue) hfx + (by rw [hT]; exact hlt 1) + rw [hT] at ht + have hne : wordEq (SolidCore.Solidity.Shared.norm (fieldValue (slotValue σ 1) tokenField.packedOffset 20)) ctx.self = false := by + rw [hctxs] + simp only [wordEq, fieldValue, tokenField, SolidCore.Solidity.Shared.norm] + simp + have h1 : slotValue σ 1 % 1461501637330902918203684832716283019655932542976 < Solidity.Shared.wordModulus := + lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (by decide) + rw [Nat.mod_eq_of_lt h1, Nat.mod_eq_of_lt (by decide : selfAddress < Solidity.Shared.wordModulus)] + exact hself + rw [eval_tryCall (k + 2) _ ctx _ _ _ _ _ false _ _ _ _ ht rfl (word0_eval ctx _) rfl (enc_eval ctx _ hctxs) rfl hne] at hrun + generalize hW : snapshotWorld ctx (rt0.pushScope.pushScope.declareLocal "_sol_hoist_0" Ty.uint256.defaultValue).state = world at hrun + generalize hR : buildCallRequest ctx Solidity.Shared.Call.ExternalCallKind.staticcall + (Solidity.Shared.norm (fieldValue (slotValue σ 1) tokenField.packedOffset 20)) + (List.map normByte encSync) (Solidity.Shared.norm 0) none = request at hrun + simp only [bind_request, map_request] at hrun + rw [foldAns_request] at hrun + cases hans : V.ans [] (Query.external world (ExternalRequest.call request)) with + | none => simp [hans] at hrun + | some a => + simp only [hans] at hrun + have hworld : ∀ slot < 2 ^ 256, storageIn world slot = slotValue σ slot % 2 ^ 256 := by + intro slot hslot + have hmut : (rt0.pushScope.pushScope.declareLocal "_sol_hoist_0" Ty.uint256.defaultValue).state.worldMutatedSinceAdoption = true := by + subst hrt0; rfl + have hwf : StorageMap.WF (rt0.pushScope.pushScope.declareLocal "_sol_hoist_0" Ty.uint256.defaultValue).state.storage := by + subst hrt0 hst + exact wf_foldl σ _ (wf_of_toList_nil _ hd.storage) + have hl := hload slot hslot + have hsto : (rt0.pushScope.pushScope.declareLocal "_sol_hoist_0" Ty.uint256.defaultValue).state.storage = st0.storage := by + subst hrt0; rfl + subst hW + unfold storageIn accountIn + rw [show wordToAddress selfAddress = wordToAddress ctx.self by rw [hctxs], + snapshotWorld_find_self ctx _ (Or.inr hmut)] + simp only [Option.getD_some, snapshotSelfAccount] + rw [lookup?_roundtrip _ hwf, hsto] + unfold State.loadSlot at hl + cases h : StorageMap.lookup? st0.storage slot with + | none => rw [h] at hl; simp [← hl] + | some v => rw [h] at hl; simp [← hl, SolidCore.Solidity.Shared.norm]; rfl + refine ⟨world, request, a, ?_, ?_⟩ + · refine ⟨hans, by subst hR; rfl, ?_, by subst hR; rfl, ?_, ?_, ?_, ?_, ?_⟩ + · subst hR + simp [buildCallRequest, addressToWord, wordToAddress, wordToU256, fieldValue, tokenField, + EvmYul.AccountAddress.ofUInt256, SolidCore.Solidity.Shared.norm] + have h1 : slotValue σ 1 % 1461501637330902918203684832716283019655932542976 < + Solidity.Shared.wordModulus := lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (by decide) + rw [Nat.mod_eq_of_lt h1] + simp [EvmYul.UInt256.ofNat, EvmYul.AccountAddress.size, Fin.ofNat, Id.run, EvmYul.UInt256.size] + · subst hR + show byteArrayToBytes (bytesToByteArray (List.map normByte encSync)) = List.map BitVec.toNat Sync.input + simp only [byteArrayToBytes, toList_eq_data, bytesToByteArray] + decide + · exact hworld + · intro slot hslot + have hmut : (rt0.pushScope.pushScope.declareLocal "_sol_hoist_0" Ty.uint256.defaultValue).state.worldMutatedSinceAdoption = true := by + subst hrt0; rfl + have htr : (rt0.pushScope.pushScope.declareLocal "_sol_hoist_0" Ty.uint256.defaultValue).state.transient = d.transient := by + subst hrt0 hst; rfl + subst hW + unfold transientIn accountIn + rw [show wordToAddress selfAddress = wordToAddress ctx.self by rw [hctxs], + snapshotWorld_find_self ctx _ (Or.inr hmut)] + simp only [Option.getD_some, snapshotSelfAccount] + rw [lookup?_roundtrip _ (by rw [htr]; exact wf_of_toList_nil _ hdt), htr] + have hnone : StorageMap.lookup? d.transient slot = none := by + unfold StorageMap.lookup? + rw [Std.HashMap.get?_eq_getElem?] + cases h : d.transient[SolidCore.Solidity.Shared.norm slot]? with + | none => rfl + | some v => + have := Std.HashMap.mem_toList_iff_getElem?_eq_some.mpr h + rw [hdt] at this; cases this + rw [hnone]; rfl + · intro x hx + have hacc : ctx.accountCodes = V.codes.getD [] := by + subst hctx + show V.codes.getD c.core.context.accountCodes = V.codes.getD [] + rw [hcc] + rw [← hacc] + subst hW + apply codeIn_snapshot + · subst hrt0 hst; exact hde + · subst hctx; exact hcb + · subst hctx; exact hch + · rw [hacc]; exact hkeys + · rw [hctxs]; decide + · exact hx + · exact hsize _ _ _ _ hans + · simp only [tryTail, decodeCallResponse] at hrun + cases hs : a.success + · simp only [hs, Bool.false_eq_true, ↓reduceIte, findMatch_nil] at hrun + simp only [sbind_pure, map_pure', foldAns_pure, Result.mapRuntime, FunctionDef.callBodyResult, + RevertData.fromRawBytes, normByte_bytes] at hrun + have hout : ∀ out, ABI.Contract.encodeRevertData? c.core + (if (byteArrayToBytes a.returnData == []) = true then SolidCore.Solidity.Source.RevertData.empty + else SolidCore.Solidity.Source.RevertData.raw (byteArrayToBytes a.returnData)).untagFixedBytes = some out → + out = byteArrayToBytes a.returnData := by + intro out h + split at h + · rename_i he + simp only [beq_iff_eq] at he + simp only [RevertData.untagFixedBytes, ABI.Contract.encodeRevertData?, Option.some.injEq] at h + rw [← h, he] + · simp only [RevertData.untagFixedBytes, ABI.Contract.encodeRevertData?, Option.some.injEq] at h + rw [← h] + exact normByte_bytes a.returnData + simp only [Option.bind_eq_bind, Option.map_bind] at hrun + obtain ⟨out, hout', hobs⟩ := Option.bind_eq_some_iff.mp hrun + rw [hout out hout'] at hobs + simp only [Function.comp, Option.map_some, Option.some.injEq] at hobs + rw [← hobs] + simp only [Source.observe, Sync.obsOf, hs, Bool.false_eq_true, ↓reduceIte, byteArrayToBytes_eq] + rfl + · simp only [hs, ↓reduceIte, normByte_bytes, List.map_cons, List.map_nil] at hrun + by_cases hlen : (byteArrayToBytes a.returnData).length < 32 + · rw [decode_short _ hlen] at hrun + simp only [sbind_pure, map_pure', foldAns_pure, Result.mapRuntime, FunctionDef.callBodyResult, + RevertData.untagFixedBytes, ABI.Contract.encodeRevertData?, Option.bind_eq_bind, Option.bind_some, + Option.map_some, Option.some.injEq] at hrun + have hsz : a.returnData.size < 32 := by + rw [byteArrayToBytes_eq, List.length_map, List.length_range] at hlen; exact hlen + rw [← hrun] + simp only [Source.observe, Sync.obsOf, hs, ↓reduceIte, hsz, Bool.false_eq_true] + rfl + · rw [decode_word _ (by omega)] at hrun + simp only [normByte_bytes] at hrun + generalize hw : bytesToWordBE (List.take 32 (byteArrayToBytes a.returnData)) = w at hrun + have hwlt : w < 2 ^ 256 := by rw [← hw]; exact Nat.mod_lt _ (by decide) + simp only [AbiCleanups.acceptOrUnspecified] at hrun + have hacc : AbiCleanups.accept [AbiCleanup.uint 256] [Value.word w] = true := by + simp [AbiCleanups.accept, AbiCleanup.accepts, SolidCore.Solidity.Shared.norm] + first + | exact decide_eq_true (Nat.mod_lt w (by decide : 0 < Solidity.Shared.wordModulus)) + | exact Nat.mod_lt w (by decide : 0 < Solidity.Shared.wordModulus) + have hbind : BindingDecl.bindArgs? [{ name := "__ext0", ty := Ty.uint256 }] [Value.word w] = + some [("__ext0", Value.word w)] := by + simp [BindingDecl.bindArgs?, BindingDecl.bindArg?, Ty.coerceValue?, SolidCore.Solidity.Shared.norm, + Nat.mod_eq_of_lt hwlt] + simp only [hacc, hbind, Bool.or_true, ↓reduceIte] at hrun + let ρ : Val := ⟨[], slotValue σ, solHash, SolidCore.Refinement.Generic.callerWord⟩ + let E : EraseEnv := { fields := callsFields, events := ctx.eventDecls, tbl := c.core.table } + let S1 : SymState := ⟨[[("__ext0", .lit w)], [("_sol_hoist_0", .lit 0)], [], []], [], [], .lit SolidCore.Refinement.Generic.callerWord⟩ + have hrel1 : StmtRel ρ E ctx ((({ state := adoptWorld a.postWorld ctx (rt0.pushScope.pushScope.declareLocal "_sol_hoist_0" Ty.uint256.defaultValue).state, locals := (rt0.pushScope.pushScope.declareLocal "_sol_hoist_0" Ty.uint256.defaultValue).locals, memory := (rt0.pushScope.pushScope.declareLocal "_sol_hoist_0" Ty.uint256.defaultValue).memory, nextMemory := (rt0.pushScope.pushScope.declareLocal "_sol_hoist_0" Ty.uint256.defaultValue).nextMemory, nextMemoryByte := (rt0.pushScope.pushScope.declareLocal "_sol_hoist_0" Ty.uint256.defaultValue).nextMemoryByte } : Runtime).recordExternalInteraction (ExternalInteraction.lowLevelCall { kind := Solidity.Shared.Call.ExternalCallKind.staticcall, target := Solidity.Shared.norm (fieldValue (slotValue σ 1) tokenField.packedOffset 20), calldata := List.map normByte encSync, value := Solidity.Shared.norm 0, success := true, output := byteArrayToBytes a.returnData })).withFrame [("__ext0", Value.word w)]) S1 := + { fields := hctxf + events := rfl + checked := by subst hctx; rfl + sender := by subst hctx; rfl + hash := rfl + ok := slotValue_store σ + frames := by + subst hrt0 + simp [Runtime.withFrame, Runtime.recordExternalInteraction, Runtime.declareLocal, + Runtime.pushScope, frameOf, S1, WExpr.eval, Nat.mod_eq_of_lt hwlt] + simp [LocalEnv.declare, Ty.defaultValue] + store := by + intro j hj + show (adoptWorld a.postWorld ctx + (rt0.pushScope.pushScope.declareLocal "_sol_hoist_0" Ty.uint256.defaultValue).state).loadSlot j = slotValue σ j + have hadopt : ∀ X, (adoptWorld a.postWorld ctx X).loadSlot j = storageIn a.postWorld j := by + intro X + simp only [adoptWorld, State.loadSlot, storageIn, accountIn, hctxs] + cases StorageMap.lookup? _ j <;> rfl + rw [hadopt, hstatic _ _ _ _ hans (by subst hR; rfl) j, hworld j hj, Nat.mod_eq_of_lt (hlt j)] + logs := by + subst hrt0 hst + show List.map logOf d.events = List.map (Log.eval ρ) [] + rw [hd.events] + rfl + facts := by intro p hp; cases hp } + obtain ⟨r1, hr1, hl1⟩ := eval_stmt ρ E ctx (k + 2) (Stmt.assign (LValue.var "_sol_hoist_0") + (Expr.castOp CastKind.uintCleanup 256 (Expr.var "__ext0"))) S1 _ rfl _ hrel1 + rw [hr1] at hrun + let S1' : SymState := ⟨[[("__ext0", .lit w)], [("_sol_hoist_0", .lit w)], [], []], [], [], .lit SolidCore.Refinement.Generic.callerWord⟩ + have hl1' : LeafRel ρ E ctx r1 (.normal S1') := hl1 + cases r1 with + | normal rt1 => + have hrel2 : StmtRel ρ E ctx rt1.popScope S1'.pop := StmtRel.popScope hl1' + obtain ⟨r2, hr2, hl2⟩ := eval_stmt ρ E ctx (k + 3) (Stmt.assign (LValue.storage "reserve") + (Expr.castOp CastKind.uintCleanup 256 (Expr.var "_sol_hoist_0"))) S1'.pop _ rfl _ hrel2 + simp only [done_bind', Result.mapRuntime, sbind_pure] at hrun + rw [hr2] at hrun + let S3 : SymState := ⟨[[("_sol_hoist_0", .lit w)], [], []], + [(.lit 2, writeField (.init 2) (.lit w) 0 32)], [], .lit SolidCore.Refinement.Generic.callerWord⟩ + have hl2' : LeafRel ρ E ctx r2 (.normal S3) := hl2 + cases r2 with + | normal rt2 => + have hrel3 : StmtRel ρ E ctx rt2 S3 := hl2' + simp only [done_bind', sbind_pure, evalList_nil, Result.mapRuntime, map_pure', foldAns_pure, + FunctionDef.callBodyResult] at hrun + rw [show syncFn.collectReturns rt2.popScope.popScope = .ok [] from rfl] at hrun + simp only [List.map_nil, show ABI.encodeValues? (List.map BindingDecl.ty syncFn.returns) [] = some [] from rfl, + Option.bind_eq_bind, Option.bind_some, Option.map_some, Option.some.injEq] at hrun + have hev : rt2.state.events = [] := by + have := hrel3.logs + simp only [S3, List.map_nil, List.map_eq_nil_iff] at this + exact this + have hsz : 32 ≤ a.returnData.size := by + rw [byteArrayToBytes_eq, List.length_map, List.length_range] at hlen; omega + rw [← hrun] + simp only [Source.observe, Sync.obsOf, hs, ↓reduceIte, Runtime.popScope, State.logEntries, hev, + List.map_nil, show ¬ a.returnData.size < 32 by omega] + congr 1 + funext slot + rw [loadSlot_eq rt2.state S3.writes ρ (slotValue_store σ) hrel3.store slot] + have hv : (Sync.retWord a).toNat = w := by rw [retWord_toNat a hsz, hw] + simp only [S3, Writes.store, Machine.update, Machine.State.initial] + rw [writeField_eval ρ _ _ (by decide) (by decide)] + by_cases h2 : slot % 2 ^ 256 = 2 + · have hb : BitVec.ofNat 256 slot = 2 := by + apply BitVec.eq_of_toNat_eq; simpa using h2 + rw [if_pos hb, hv] + have h2' : slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 2 := h2 + simp [WExpr.eval, Generic.wordSize, h2', fieldWrite, Nat.mod_eq_of_lt hwlt] + exact hwlt + · have hb : BitVec.ofNat 256 slot ≠ 2 := by + intro h; apply h2; have := congrArg BitVec.toNat h; simpa using this + rw [if_neg hb] + have h2' : ¬ slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 2 := h2 + have hne : ¬ ((WExpr.lit 2).eval ρ = slot % Generic.wordSize) := by + intro h; apply h2'; simpa [WExpr.eval, Generic.wordSize] using h.symm + rw [if_neg hne] + simp only [BitVec.toNat_ofNat] + show slotValue σ slot = _ + rw [← slotValue_store σ slot] + rfl + | _ => exact absurd hl2' id + | _ => exact absurd hl1' id + + +/-- info: 'SolidCore.Refinement.CallFamilies.sync_source' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms sync_source + +/-- **sync's source stage in the world `V`**: under every oracle that agrees with `V` +(`CallsAgree o V`), solar's stage0 runs `sync()` as SolidCore runs it in `V`, from every storage +whose token is not the contract itself. Hypotheses: the checked contract's `sync` and fields are +`syncFn` and `callsFields`, its constructor leaves no storage, transient storage, adopted world or +seeded accounts; `V`'s seeded code is at addresses below `2 ^ 160` and its answers' return data is +shorter than `2 ^ 256` bytes. -/ +theorem sync_stage_in (k : Nat) (V : World) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {d : SolidCore.Solidity.Source.State} (hd : Wide.DeployedAt (k + 5) c d []) + (hfind : c.core.findFunctionBySelector? 4294363881 = some syncFn) + (hfields : c.core.storageFields = callsFields) + (hdt : d.transient.toList = []) (hde : d.envWorld? = none) + (hcb : c.core.context.accountBalances = []) (hch : c.core.context.accountCodehashes = []) + (hcc : c.core.context.accountCodes = []) (hkeys : ∀ p ∈ V.codes.getD [], p.1 < 2 ^ 160) + (hsize : ∀ h world request a, V.ans h (.external world (.call request)) = some a → + a.returnData.size < 2 ^ 256) + (o : Machine.Oracle) (agree : CallsAgree o V) : + Stage (solidCoreIn V (k + 5)) (MIR.Lowered.moduleSem o) c SolarTV.Export.Calls.stage0 + (fun call => ∃ σ, slotValue σ 1 % 2 ^ 160 ≠ selfAddress ∧ call = Sync.syncCall σ) := + sync_stage (k + 5) c V _ (fun σ hσ => sync_source k V hd hfind hfields + (fun h w r a ha hk slot => (agree.static h w r a ha hk slot).1) hdt hde hcb hch hcc hkeys hsize σ hσ) + o agree + +/-- info: 'SolidCore.Refinement.CallFamilies.sync_stage_in' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms sync_stage_in + +end SolidCore.Refinement.CallFamilies diff --git a/Contracts/CallFamilies/TransferSel.lean b/Contracts/CallFamilies/TransferSel.lean new file mode 100644 index 00000000..0024026f --- /dev/null +++ b/Contracts/CallFamilies/TransferSel.lean @@ -0,0 +1,31 @@ +import SolidCore.Solidity.ABI +import SolidCore.Refinement.KernelRfl + +/-! +# The selector of transfer(address,uint256), by Keccak-256 in the kernel + +pay's TRANSFER constant is bytes4(keccak256("transfer(address,uint256)")). transfer_sel_eq +evaluates SolidCore's selector (Keccak-256 of the signature's bytes, first four bytes) in the +kernel once; transfer_word_eq shows the word solar's MIR stores before the call's arguments is +that selector in the top four bytes. +-/ + +namespace SolidCore.Verify.VC.Calls + +/-- The selector of transfer(address,uint256), by Keccak-256 of its signature. -/ +def selTransfer : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "transfer(address,uint256)" + +kernel_rfl transfer_sel_eq selTransfer 2835717307 + +/-- The selector word solar's MIR stores at the head of transfer's input. -/ +theorem transfer_word_eq : + (76450787359836037641860180984291677749980919077056822294353438043884394381312 : Nat) = + selTransfer * 2 ^ 224 := by + rw [transfer_sel_eq]; rfl + +/-- info: 'SolidCore.Verify.VC.Calls.transfer_word_eq' depends on axioms: [propext] -/ +#guard_msgs (whitespace := lax) in +#print axioms transfer_word_eq + +end SolidCore.Verify.VC.Calls diff --git a/Contracts/CallSqrt/Final.lean b/Contracts/CallSqrt/Final.lean new file mode 100644 index 00000000..5bc6c854 --- /dev/null +++ b/Contracts/CallSqrt/Final.lean @@ -0,0 +1,48 @@ +import Contracts.CallSqrt.Total +import callsqrt.Proofs.Execution + +/-! +# CallSqrt: termination and the exact bytecode in one statement + +For every call of CallSqrt (any calldata, call value and storage) and every oracle the assembly +certificate admits: + +* the first lowered MIR ends (`stage0_ends`: Math.sqrt's Newton loop by its generated ranking + certificate `z`, under either caller); +* the final EVM IR ends, through the backend stages read forwards (`callsqrt_certified`, cut-point + simulations), in an end that agrees with the MIR's; +* every result of the exact bytecode, at every gas, is the MIR's (which exists) or a failure that + leaves storage and logs as they were (`callsqrt_bytecode`, `checkL`). + +Not stated: that some gas makes the bytecode succeed. Running out of gas is the failure branch of +the last conjunct; a proved gas bound needs a forward per-block gas lemma of the assembly checker. +No user spec of sqrt is stated here: its spec (`z * z <= y < (z + 1) * (z + 1)`) is solar-verify's +SMT result, not yet connected to these semantics. +-/ + +namespace SolarTV.Milestone.CallSqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 + +theorem callsqrt_total (o : Oracle) + (ho : Callsqrt.cert.env = true → SolidCore.Refinement.Solar.Assemble.OracleOk o) + (he : Callsqrt.cert.reads = true → SolidCore.Refinement.Solar.Assemble.EnvOk o) (call : Call) : + (∃ r, MIR.Lowered.moduleLayer.Ends o stage0 call r) ∧ + (∃ r, EVM.Program.layer.Ends o evm13 call r) ∧ + ((mirSem o).run stage0 call).isSome ∧ + ∀ gas, SolidCore.Refinement.Final.Within (mirSem o) (SolidCore.Refinement.Final.ethLibWith gas) + stage0 Callsqrt.code (· = call) := by + obtain ⟨r, e⟩ := stage0_ends o call + obtain ⟨r', e', -⟩ := Callsqrt.callsqrt_certified o call trivial r e + refine ⟨⟨r, e⟩, ⟨r', e'⟩, ?_, fun gas => by + intro c _ obs h + exact Callsqrt.callsqrt_bytecode o ho he gas c (show anyCall c from trivial) obs h⟩ + change ((MIR.Lowered.moduleLayer.result o stage0 call).map _).isSome = true + rw [MIR.Lowered.moduleLayer.result_of_ends e] + rfl + +/-- info: 'SolarTV.Milestone.CallSqrt.callsqrt_total' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms callsqrt_total + +end SolarTV.Milestone.CallSqrt diff --git a/Contracts/CallSqrt/Inferred.lean b/Contracts/CallSqrt/Inferred.lean new file mode 100644 index 00000000..d496b25d --- /dev/null +++ b/Contracts/CallSqrt/Inferred.lean @@ -0,0 +1,41 @@ +-- Generated by solar-tv/milestone/inferred_callee.py from what solar-verify --show-inferred printed +-- (sha256 aaecfc1356cb024d043ecf9833b067c3322d22e5dc26b6c4ea8ab6919eb7cc49) and Stage0.lean (sha256 d957e4a9da2372b09f85b01a61aeb2cb18d23635520f34af608650df94a40846); do not edit. +import SolarTV.MIR.Program +import callsqrt.gen.CallSqrt.Stage0 + +/-! +# The ranking certificate of `sqrt`'s loop, under any caller + +solar-verify proved, for the loop at line 17 of the source (`while (x < z)`), the +termination measure `z`. It is bound to phi 9 of bb4 of function 2 of the first +lowered MIR (the guard compares phi 10 with phi 9), read through its input from +each predecessor (bb1, bb9). The cut points are the header and every +frame resumed after a return; the invariant is the frame at the header under any caller's +return record. The segment proofs check that the rank falls on every back edge. +-/ + +namespace SolarTV.Milestone.CallSqrt.Inferred + +open SolarTV Machine + +/-- Cut points: the header, read off the blocks that enter it, and every resumed frame. -/ +def cut : MIR.Lowered.Frame → Bool := fun x => + match x.2.1 with + | .enter f p _ => (f == 2 && (p == 1 || p == 9)) + | .resume .. => true + +/-- The header, entered from one of its predecessors, under the caller's return. -/ +def Inv (r : MIR.Lowered.Return) (stack : List MIR.Lowered.Return) (x : MIR.Lowered.Frame) : Prop := + ∃ p env s, x = (r :: stack, .enter 2 p 4, env, s) ∧ (p = 1 ∨ p = 9) + +/-- The caller resumed after the function's `leave`. -/ +def Back (r : MIR.Lowered.Return) (stack : List MIR.Lowered.Return) (x : MIR.Lowered.Frame) : Prop := + ∃ env s, x = (stack, .resume r.fn r.block r.rest r.term, env, s) + +/-- The measure `z` at the header, in Nat. -/ +def rank : MIR.Lowered.Frame → Nat + | (_, .enter _ 1 _, env, _) => (env 0).toNat + | (_, .enter _ 9 _, env, _) => (env 10).toNat + | _ => 0 + +end SolarTV.Milestone.CallSqrt.Inferred diff --git a/Contracts/CallSqrt/Total.lean b/Contracts/CallSqrt/Total.lean new file mode 100644 index 00000000..076079f7 --- /dev/null +++ b/Contracts/CallSqrt/Total.lean @@ -0,0 +1,296 @@ +import SolarTV.Termination +import W1Proofs.Segment +import W1Proofs.Stage +import Contracts.CallSqrt.Inferred + +/-! +# Math.sqrt's loop ends, under any caller + +CallSqrt calls Uniswap v2-core's Math.sqrt from its two functions, so the Newton loop +(`while (x < z) { z = x; x = (y / x + x) / 2; }`) runs inside an internal call frame. Its ranking +certificate is generated (`Inferred.lean`, from solar-verify's measure `z` by +`inferred_callee.py`) and checked here through the generic checker +(`SolarTV.CutPoint.reaches_of_start`): + +* `seg0`, `seg1`, `seg9`: sqrt's segments, from its entry and from its header entered from + either predecessor, under any caller's return record and any stack: each ends in a revert, + back in the caller, or at the header with a lower `z` (the guard `x < z` and the update + `z = x`). None is stuck: the compiler's `assume`s are discharged (`shr1_lt_max`). +* `sqrt_reaches`: **sqrt's total contract**: from its entry, under any caller, it returns to + the caller or reverts. +* `stage0_ends`: every call of CallSqrt ends on solar's first lowered MIR, whatever its + calldata: the entry's checks and dispatch, f or g, sqrt by its contract, then the caller's + rest. +-/ + +namespace SolarTV.Milestone.CallSqrt + +open Machine SolarTV.Export.CallSqrt SolarTV.Milestone.W1 +open SolarTV.CutPoint (seg SegReaches) +open Inferred (cut Inv Back rank) + +theorem cut_enter (rs : List MIR.Lowered.Return) (f p b : Nat) (env : MIR.Lowered.Env) (s : State) : + cut (rs, .enter f p b, env, s) = (f == 2 && (p == 1 || p == 9)) := rfl + +theorem cut_resume (rs : List MIR.Lowered.Return) (f b : Nat) (is : List MIR.Lowered.Inst) + (t : MIR.Lowered.Terminator) (env : MIR.Lowered.Env) (s : State) : + cut (rs, .resume f b is t, env, s) = true := rfl + +/-- The cut test of a block a branch picks, distributed over the branch. -/ +theorem ite_beq' {α : Type} [BEq α] (c : Prop) [Decidable c] (a b n : α) : + ((if c then a else b) == n) = (if c then a == n else b == n) := by + split <;> rfl + +/-- A cut test of a block a branch picks evaluates on both branches before any case split. -/ +macro "sq_cut_test" : tactic => `(tactic| + simp only [ite_beq', Nat.reduceBEq, ite_self, Bool.false_eq_true, Bool.true_and, Bool.false_and, + ↓reduceIte, true_or, or_true]) + +set_option hygiene false in +/-- The case just split, rewritten into the branch that tests it. -/ +macro "sq_case" : tactic => `(tactic| simp only [hc, ↓reduceIte, Nat.reduceBEq, Bool.false_eq_true, + Bool.true_and, Bool.false_and, Bool.or_false, Bool.false_or]) + +/-- `seg_norm` with the cut test evaluated first and the last case rewritten. -/ +syntax "sq_norm" "[" Lean.Parser.Tactic.simpLemma,* "]" : tactic +macro_rules + | `(tactic| sq_norm [$ids,*]) => + `(tactic| repeat (first | sym_eval | seg_eval [$ids,*] | sq_cut_test | sym_cond | sq_case)) + +/-- A caller's return record whose call binds one result. -/ +def ret (fn block d : Nat) (rest : List MIR.Lowered.Inst) (term : MIR.Lowered.Terminator) + (renv : MIR.Lowered.Env) (publish : Option EvmRules.Word) : MIR.Lowered.Return := + ⟨fn, block, some d, rest, term, renv, [], publish⟩ + +theorem lt_of_evm_lt {a b : EvmRules.Word} (h : ¬EvmRules.Evm.lt a b = 0) : a.toNat < b.toNat := by + unfold EvmRules.Evm.lt at h + cases hu : a.ult b + · simp [hu] at h + · simpa [BitVec.ult, decide_eq_true_eq] using hu + +/-- sqrt's entry assumes `y >> 1` is below the largest word, which holds of every word. -/ +theorem shr1_lt_max (x : EvmRules.Word) : + ¬EvmRules.Evm.lt (EvmRules.Evm.shr 1 x) + 115792089237316195423570985008687907853269984665640564039457584007913129639935 = 0 := by + have hs : (EvmRules.Evm.shr 1 x).toNat < 2 ^ 255 := by + simp only [EvmRules.Evm.shr] + rw [show BitVec.ult (1 : EvmRules.Word) 256 = true by decide] + simp only [Bool.cond_true, BitVec.ushiftRight_eq', BitVec.toNat_ushiftRight, + Nat.shiftRight_eq_div_pow] + rw [show (1 : EvmRules.Word).toNat = 1 from rfl] + have := x.isLt + omega + have hu : (EvmRules.Evm.shr 1 x).ult + 115792089237316195423570985008687907853269984665640564039457584007913129639935 = true := by + simp only [BitVec.ult, decide_eq_true_eq] + rw [show (115792089237316195423570985008687907853269984665640564039457584007913129639935 : + EvmRules.Word).toNat = 2 ^ 256 - 1 from rfl] + omega + unfold EvmRules.Evm.lt + rw [hu] + decide + +/-- The same, as the entry's branch reads it. -/ +theorem shr1_lt_max' (x : EvmRules.Word) : + EvmRules.Evm.shr 1 x < 115792089237316195423570985008687907853269984665640564039457584007913129639935 := by + have h := shr1_lt_max x + unfold EvmRules.Evm.lt at h + cases hu : (EvmRules.Evm.shr 1 x).ult + 115792089237316195423570985008687907853269984665640564039457584007913129639935 + · rw [hu] at h; exact absurd rfl h + · exact BitVec.ult_iff_lt.mp hu + +/-- The leaves of sqrt's segments: a revert, the caller resumed, the header again with a lower +rank, or a contradiction of the cases. -/ +macro "sq_leaf" : tactic => `(tactic| first + | trivial + | exact Or.inr ⟨_, _, rfl⟩ + | (refine Or.inl ⟨⟨_, _, _, rfl, Or.inl rfl⟩, trivial⟩) + | (refine Or.inl ⟨⟨_, _, _, rfl, Or.inr rfl⟩, ?_⟩ + simp only [rank, MIR.Lowered.Env.set, ↓reduceIte, Nat.reduceEqDiff] + exact lt_of_evm_lt ‹_›) + | exact absurd ‹(0 : EvmRules.Word) = 1› (by decide) + | exact absurd ‹EvmRules.Evm.lt (EvmRules.Evm.shr 1 _) _ = 0› (shr1_lt_max _) + | (exfalso; bv_omega)) + +set_option backward.dsimp.instances true in +set_option maxHeartbeats 4000000 in +theorem seg9 (o : Oracle) (call : Call) (fn block d : Nat) (rest : List MIR.Lowered.Inst) + (term : MIR.Lowered.Terminator) (renv : MIR.Lowered.Env) (publish : Option EvmRules.Word) + (stack : List MIR.Lowered.Return) (env : MIR.Lowered.Env) (s : State) : + SegReaches (Inv (ret fn block d rest term renv publish) stack) + (Back (ret fn block d rest term renv publish) stack) (fun _ => True) + (fun y => rank y < rank (ret fn block d rest term renv publish :: stack, .enter 2 9 4, env, s)) + (seg (MIR.Lowered.moduleBlock o call stage0) cut 20 + (ret fn block d rest term renv publish :: stack, .enter 2 9 4, env, s)) := by + unfold ret + sq_norm [SegReaches, cut_enter, cut_resume] + repeat' (split_cond <;> sq_norm [SegReaches, cut_enter, cut_resume]) + all_goals sq_leaf + +set_option backward.dsimp.instances true in +set_option maxHeartbeats 4000000 in +theorem seg1 (o : Oracle) (call : Call) (fn block d : Nat) (rest : List MIR.Lowered.Inst) + (term : MIR.Lowered.Terminator) (renv : MIR.Lowered.Env) (publish : Option EvmRules.Word) + (stack : List MIR.Lowered.Return) (env : MIR.Lowered.Env) (s : State) : + SegReaches (Inv (ret fn block d rest term renv publish) stack) + (Back (ret fn block d rest term renv publish) stack) (fun _ => True) + (fun y => rank y < rank (ret fn block d rest term renv publish :: stack, .enter 2 1 4, env, s)) + (seg (MIR.Lowered.moduleBlock o call stage0) cut 20 + (ret fn block d rest term renv publish :: stack, .enter 2 1 4, env, s)) := by + unfold ret + sq_norm [SegReaches, cut_enter, cut_resume] + repeat' (split_cond <;> sq_norm [SegReaches, cut_enter, cut_resume]) + all_goals sq_leaf + +set_option backward.dsimp.instances true in +set_option maxHeartbeats 4000000 in +theorem seg0 (o : Oracle) (call : Call) (fn block d : Nat) (rest : List MIR.Lowered.Inst) + (term : MIR.Lowered.Terminator) (renv : MIR.Lowered.Env) (publish : Option EvmRules.Word) + (stack : List MIR.Lowered.Return) (env : MIR.Lowered.Env) (s : State) : + SegReaches (Inv (ret fn block d rest term renv publish) stack) + (Back (ret fn block d rest term renv publish) stack) (fun _ => True) + (fun _ => True) + (seg (MIR.Lowered.moduleBlock o call stage0) cut 20 + (ret fn block d rest term renv publish :: stack, .enter 2 0 0, env, s)) := by + unfold ret + sq_norm [SegReaches, cut_enter, cut_resume] + repeat' (split_cond <;> sq_norm [SegReaches, cut_enter, cut_resume]) + all_goals sq_leaf + + +/-! ## The whole call -/ + +/-- What f runs after its call of sqrt returns. -/ +def restF : List MIR.Lowered.Inst := [.pure 5 .add [.value 2, .const 1], .pure 6 .eq [.value 5, .const 0]] +def termF : MIR.Lowered.Terminator := .branch (.value 6) 1 2 +/-- What g runs after its call of sqrt returns. -/ +def restG : List MIR.Lowered.Inst := [.effect none .mstore [.const 0, .value 4]] +def termG : MIR.Lowered.Terminator := .ret (.const 0) (.const 32) + +/-- sqrt's header under f's or g's call. -/ +def TopInv (x : MIR.Lowered.Frame) : Prop := + ∃ renv, Inv (ret 0 0 2 restF termF renv none) [] x ∨ Inv (ret 1 0 4 restG termG renv none) [] x + +/-- f or g resumed after sqrt returned. -/ +def TopBack (x : MIR.Lowered.Frame) : Prop := + ∃ env s, x = ([], .resume 0 0 restF termF, env, s) ∨ x = ([], .resume 1 0 restG termG, env, s) + +/-- The first configuration of a call. -/ +def start (call : Call) : MIR.Lowered.Frame := + ([], .enter stage0.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState stage0 (State.initial call)) + +macro "top_leaf" : tactic => `(tactic| first + | trivial + | exact Or.inl ⟨⟨_, Or.inl ⟨_, _, _, rfl, Or.inl rfl⟩⟩, trivial⟩ + | exact Or.inl ⟨⟨_, Or.inr ⟨_, _, _, rfl, Or.inl rfl⟩⟩, trivial⟩ + | exact Or.inl ⟨_, Or.inl ⟨_, _, _, rfl, Or.inl rfl⟩⟩ + | exact Or.inl ⟨_, Or.inr ⟨_, _, _, rfl, Or.inl rfl⟩⟩ + | exact Or.inr ⟨_, _, Or.inl rfl⟩ + | exact Or.inr ⟨_, _, Or.inr rfl⟩ + | exact absurd (shr1_lt_max' _) ‹¬EvmRules.Evm.shr 1 _ < _› + | exact absurd ‹(0 : EvmRules.Word) = 1› (by decide) + | exact absurd ‹EvmRules.Evm.lt (EvmRules.Evm.shr 1 _) _ = 0› (shr1_lt_max _) + | (exfalso; bv_omega)) + +set_option backward.dsimp.instances true in +set_option maxHeartbeats 4000000 in +/-- From a call's start: the entry's checks and selector, f or g, into sqrt, to its header or +(for `y <= 3`) back to the caller. -/ +theorem segTop (o : Oracle) (call : Call) : + SegReaches TopInv TopBack (fun _ => True) (fun _ => True) + (seg (MIR.Lowered.moduleBlock o call stage0) cut 40 (start call)) := by + unfold start + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + sq_norm [SegReaches, cut_enter, cut_resume] + repeat' (split_cond <;> sq_norm [SegReaches, cut_enter, cut_resume]) + all_goals top_leaf + +set_option backward.dsimp.instances true in +set_option maxHeartbeats 4000000 in +theorem segF (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) : + CutPoint.SegEnds (fun _ => False) (fun _ => True) (fun _ => True) + (seg (MIR.Lowered.moduleBlock o call stage0) cut 10 ([], .resume 0 0 restF termF, env, s)) := by + unfold restF termF + sq_norm [CutPoint.SegEnds, cut_enter, cut_resume] + repeat' (split_cond <;> sq_norm [CutPoint.SegEnds, cut_enter, cut_resume]) + all_goals trivial + +set_option backward.dsimp.instances true in +set_option maxHeartbeats 4000000 in +theorem segG (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) : + CutPoint.SegEnds (fun _ => False) (fun _ => True) (fun _ => True) + (seg (MIR.Lowered.moduleBlock o call stage0) cut 10 ([], .resume 1 0 restG termG, env, s)) := by + unfold restG termG + sq_norm [CutPoint.SegEnds, cut_enter, cut_resume] + repeat' (split_cond <;> sq_norm [CutPoint.SegEnds, cut_enter, cut_resume]) + all_goals trivial + +/-- sqrt's segments from its header, under any caller. -/ +theorem segH (o : Oracle) (call : Call) (fn block d : Nat) (rest : List MIR.Lowered.Inst) + (term : MIR.Lowered.Terminator) (renv : MIR.Lowered.Env) (publish : Option EvmRules.Word) + (stack : List MIR.Lowered.Return) : + ∀ x, Inv (ret fn block d rest term renv publish) stack x → + ∃ k, SegReaches (Inv (ret fn block d rest term renv publish) stack) + (Back (ret fn block d rest term renv publish) stack) (fun _ => True) + (fun y => rank y < rank x) (seg (MIR.Lowered.moduleBlock o call stage0) cut k x) := by + rintro x ⟨p, env, s, rfl, rfl | rfl⟩ + · exact ⟨20, seg1 o call fn block d rest term renv publish stack env s⟩ + · exact ⟨20, seg9 o call fn block d rest term renv publish stack env s⟩ + +/-- **Math.sqrt's total contract, under any caller**: from its entry, with any argument and any +caller's return record, it returns to the caller or reverts, after finitely many steps; the +rank is the measure `z` solar-verify infers, read off the header's phi of `z`. -/ +theorem sqrt_reaches (o : Oracle) (call : Call) (fn block d : Nat) (rest : List MIR.Lowered.Inst) + (term : MIR.Lowered.Terminator) (renv : MIR.Lowered.Env) (publish : Option EvmRules.Word) + (stack : List MIR.Lowered.Return) (env : MIR.Lowered.Env) (s : State) : + (∃ n r, CutPoint.run (MIR.Lowered.moduleBlock o call stage0) n + (ret fn block d rest term renv publish :: stack, .enter 2 0 0, env, s) = some r) ∨ + ∃ j y, CutPoint.steps (MIR.Lowered.moduleBlock o call stage0) j + (ret fn block d rest term renv publish :: stack, .enter 2 0 0, env, s) = some (.inr y) ∧ + Back (ret fn block d rest term renv publish) stack y := by + rcases CutPoint.reaches_of_start (Post := fun _ => True) rank + ⟨20, seg0 o call fn block d rest term renv publish stack env s⟩ + (segH o call fn block d rest term renv publish stack) with ⟨n, r, h, -⟩ | h + · exact Or.inl ⟨n, r, h⟩ + · exact Or.inr h + +theorem back_ends (o : Oracle) (call : Call) (y : MIR.Lowered.Frame) (hy : TopBack y) : + ∃ n r, CutPoint.run (MIR.Lowered.moduleBlock o call stage0) n y = some r := by + obtain ⟨env, s, rfl | rfl⟩ := hy + · obtain ⟨n, r, h, -⟩ := CutPoint.ends_of_start (Inv := fun _ => False) (Post := fun _ => True) + (fun _ => 0) ⟨10, segF o call env s⟩ (fun _ h => h.elim) + exact ⟨n, r, h⟩ + · obtain ⟨n, r, h, -⟩ := CutPoint.ends_of_start (Inv := fun _ => False) (Post := fun _ => True) + (fun _ => 0) ⟨10, segG o call env s⟩ (fun _ h => h.elim) + exact ⟨n, r, h⟩ + +/-- **Every call of CallSqrt ends on solar's first lowered MIR**, whatever its calldata: the +entry checks and dispatches, f and g call Math.sqrt, whose loop ends by its ranking certificate, +and the caller finishes. -/ +theorem stage0_ends (o : Oracle) (call : Call) : ∃ r, MIR.Lowered.moduleLayer.Ends o stage0 call r := by + have top := CutPoint.reaches_of_start (Inv := TopInv) (Q := TopBack) (Post := fun _ => True) rank + ⟨40, segTop o call⟩ (by + rintro x ⟨renv, hx | hx⟩ + · obtain ⟨k, hk⟩ := segH o call 0 0 2 restF termF renv none [] x hx + exact ⟨k, hk.mono (fun y h => ⟨renv, Or.inl h⟩) + (fun y ⟨env, s, e⟩ => ⟨env, s, Or.inl e⟩) (fun _ h => h)⟩ + · obtain ⟨k, hk⟩ := segH o call 1 0 4 restG termG renv none [] x hx + exact ⟨k, hk.mono (fun y h => ⟨renv, Or.inr h⟩) + (fun y ⟨env, s, e⟩ => ⟨env, s, Or.inr e⟩) (fun _ h => h)⟩) + have hrun : ∃ n r, CutPoint.run (MIR.Lowered.moduleBlock o call stage0) n (start call) = some r := by + rcases top with ⟨n, r, h, -⟩ | ⟨j, y, hy, qy⟩ + · exact ⟨n, r, h⟩ + · obtain ⟨n, r, h⟩ := back_ends o call y qy + exact ⟨j + n, r, by rw [CutPoint.run_add j n _ y hy]; exact h⟩ + obtain ⟨n, r, h⟩ := hrun + exact ⟨r, n, by + change Machine.iterate _ n _ = some r + rw [CutPoint.iterate_eq] + exact h⟩ + +/-- info: 'SolarTV.Milestone.CallSqrt.stage0_ends' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage0_ends + +end SolarTV.Milestone.CallSqrt diff --git a/Contracts/Counter/Deploy.lean b/Contracts/Counter/Deploy.lean new file mode 100644 index 00000000..e2c58552 --- /dev/null +++ b/Contracts/Counter/Deploy.lean @@ -0,0 +1,122 @@ +import SolidCore.Refinement.Evm.Wide +import SolidCore.Refinement.Solar.Counter.Spec +import EthLib.Execution.Proofs.Evm.Logic.Copy + +/-! +# Counter: deployment + +solar's init code for the counter milestone (`-Ogas --evm-version osaka`, the same compiler and +options as the runtime bytecode `code`) is 17 bytes of constructor followed by the 83 bytes of +runtime: + + CALLVALUE PUSH1 0x0d JUMPI ; not payable + PUSH1 0x53 DUP1 PUSH1 0x11 PUSH0 ; 83 bytes from offset 17 to memory 0 + CODECOPY PUSH0 RETURN ; return them + JUMPDEST PUSH0 PUSH0 REVERT + +* `initcode_runs`: EthLib runs the init code, in one frame with no value, no call data and the + empty storage, to success, writing no storage and emitting no log, and returns exactly the + runtime bytecode `code` the rest of the certificate is about. +* `initcode_runtime`: the init code ends with the runtime bytecode, byte for byte. + +The frame runs the init code as the code at the contract's address, as a creation does: CODECOPY +reads the running code, which is the init code. Not covered: the creation message's address +derivation and the code deposit of `processCreateMessage` (EIP-3541's `0xef` check and the +24576-byte limit, which `deposit_ok` checks of `code` separately). +-/ + +namespace SolidCore.Refinement.Solar.Counter.Deploy + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement SolidCore.Refinement.Evm.Logic SolidCore.Refinement.Evm.Symex +open SolidCore.Refinement.Evm.Wide + +/-- The init code solar emits for Counter, read big-endian. -/ +def initNat : Nat := + 0x34600d5760538060115f395ff35b5f5ffd346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd + +/-- The init code's length in bytes: 17 of constructor and the 83 of runtime. -/ +def initSize : Nat := 100 + +/-- solar's init code for Counter. -/ +def initcode : ByteArray := NatCode.ofNat initNat initSize + +/-- The init code ends with the runtime bytecode. -/ +theorem initcode_runtime : + (initcode.data.toList.drop 17) = code.data.toList := by decide +kernel + +/-- The deployment: no call data, no value, the empty storage. -/ +def deployCall : Call := { calldata := .empty, callvalue := 0, storage := [] } + +/-- What the deployment shows: success, the runtime bytecode as output, no log, no storage. -/ +def deployed : Observable := + { success := true, output := code.data.toList.map (·.toNat), logs := [], storage := fun _ => 0 } + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- The frame of the init code, for every message with no value, from every state: it steps +CALLVALUE, the untaken JUMPI, the pushes, CODECOPY and RETURN by EthLib's program logic. -/ +theorem frame (msg : Message .fusaka) (hv : msg.value = 0) (st : State.TransactionState) + (ss : Substate) : + Spec .fusaka (At initcode msg 0 [] .empty 10000000 st ss .empty) (Post deployed st ss) := by + evm_step [initcode, initNat, initSize] + evm_step [initcode, initNat, initSize, hv] + evm_step [initcode, initNat, initSize, hv] + evm_step [initcode, initNat, initSize] + evm_step [initcode, initNat, initSize] + evm_step [initcode, initNat, initSize] + refine' Triple.seq (push0 (by decide) ?lt ?op ?gas ?room) ?beforeCopy + case lt => evm_code [initcode, initNat, initSize] + case op => evm_code [initcode, initNat, initSize] + case gas => evm_gas + case room => evm_room + all_goals evm_tidy + refine' Triple.seq (codecopy ?lt ?op ?gas) ?afterCopy + case lt => evm_code [initcode, initNat, initSize] + case op => evm_code [initcode, initNat, initSize] + case gas => wide_mem + all_goals evm_tidy + refine' Triple.seq (push0 (by decide) ?lt ?op ?gas ?room) ?afterPush + case lt => evm_code [initcode, initNat, initSize] + case op => evm_code [initcode, initNat, initSize] + case gas => wide_mem + case room => evm_room + all_goals evm_tidy + refine return_post ?lt ?op ?gas rfl ?out + case lt => evm_code [initcode, initNat, initSize] + case op => evm_code [initcode, initNat, initSize] + case gas => decide +kernel + case out => decide +kernel + +/-- **solar's init code deploys the runtime bytecode.** EthLib runs Counter's init code in one +frame, with no value, no call data and the empty storage, to success: it returns exactly the +83-byte runtime bytecode `code` (the bytecode `spec_holds_of_bytecode` is about), writes no +storage and emits no log. -/ +theorem initcode_runs : Target.run initcode deployCall = some deployed := by + obtain ⟨evm, hr, herr, hout, hsub, hst⟩ := processMessage_post (Target.message initcode deployCall) + rfl rfl (precompileAddress_message initcode deployCall) deployed + (fun st ss => frame _ rfl st ss) (Target.preState initcode deployCall) Substate.empty + simp only [Target.run, hr] + have hsucc : evm.1.error.isNone = true := by rw [herr]; rfl + congr 1 + simp only [deployed, Observable.mk.injEq] + refine ⟨hsucc, hout, by simp [hsub, Substate.empty], ?_⟩ + funext slot + simp only [hsucc, ↓reduceIte] + rw [hst rfl, getStorage_preState_nil initcode deployCall rfl slot] + rfl + +/-- The returned code passes the deposit's checks: it does not start with `0xef` (EIP-3541) +and fits in 24576 bytes (EIP-170). -/ +theorem deposit_ok : code.size ≤ 24576 ∧ code.data.toList.head? ≠ some 0xef := by + decide +kernel + +/-- info: 'SolidCore.Refinement.Solar.Counter.Deploy.initcode_runs' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms initcode_runs + +/-- info: 'SolidCore.Refinement.Solar.Counter.Deploy.deposit_ok' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms deposit_ok + +end SolidCore.Refinement.Solar.Counter.Deploy diff --git a/Contracts/Counter/EndToEnd.lean b/Contracts/Counter/EndToEnd.lean new file mode 100644 index 00000000..e624b474 --- /dev/null +++ b/Contracts/Counter/EndToEnd.lean @@ -0,0 +1,99 @@ +import Contracts.Counter.Verdict +import Contracts.Counter.VC.Inc +import Contracts.Counter.VC.Get +import Contracts.Counter.VC.Mutants + +/-! +# The counter milestone: solar-verify's spec of `inc` holds of the deployed bytecode + +One theorem from solar-verify's checked obligation to solar's runtime bytecode, for +`inc(uint256 d)` of the counter milestone (`scripts/refinement/counter/counter.sol`; its annotated +copy `scripts/verify/CounterMilestone.sol` adds `@custom:ensures x == old(x) + d`): + +* `SolidCore.Verify.VC.Counter.inc_triple`: SolidCore's checked counter meets `incPost` on every + call of `inc` (any argument word, no value, any storage). It is read off solar-verify's + exported obligation, which `checkScript` accepts by the kernel (`inc_check`), and bound to + SolidCore's run of `inc` (`inc_binding`). +* `Counter.Verdict.bytecode_of_triple`: the stage from SolidCore's checked counter to solar's + bytecode (`Counter.Verdict.agree`, through solar-tv's backend stages and the assembly stage) + carries it to the bytecode under EthLib. +* `Counter.Final.bound`, `Counter.Final.frameLocal`: the bytecode is the exporter's (its hex is the + manifest's, checked by the kernel), and it runs in one frame: no instruction calls out, creates or + reads outside its frame. + +`incPost` says the call succeeds exactly when `x + d` does not overflow, and then sets slot 0 to +`x + d` and leaves every other slot as it was. It is not met trivially: `Counter.Final.inc_succeeds` +and `inc_overflow_fails` run the bytecode both ways, and solar-verify's checked script rejects +a source mutant and a spec mutant (`CounterMutants.lean`). + +The trusted base is empty here: the counter hashes nothing and calls nothing, and the theorem +takes no hypothesis. `get_spec_bytecode` does the same for `get`, from a direct proof (no NatSpec, no VC). What they do not cover: deployment (the constructor), +gas limits other than EthLib's default (`Target.run`), and calls with value (not in +`stageScope`; the bytecode rejects them, as `Counter.Final`'s `scopeEvery` shows). +-/ + +namespace SolidCore.Refinement.Solar.Counter.EndToEnd + +open SolidCore.Refinement SolidCore.Refinement.Final + +/-- Every call of `inc` in solar-verify's binding scope is in the stage's scope. -/ +theorem inc_in_scope {call : Call} + (h : SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnInc [] call) : + scopeEvery call := by + obtain ⟨σ, -, fn, hfn, args, hl, hargs, rfl⟩ := h + simp only [List.mem_singleton] at hfn + subst hfn + match args, hl with + | [a], _ => + have ha : a < 2 ^ 256 := hargs a (List.mem_singleton_self a) + refine ⟨Nat.two_pow_pos 256, Or.inl ⟨BitVec.ofNat 256 a, ?_⟩⟩ + simp only [Evm.Wide.callOf, List.map, BitVec.toNat_ofNat, Nat.mod_eq_of_lt ha] + rfl + +/-- **The counter's `inc`: solar-verify's spec holds of the deployed bytecode.** The bytecode is +the exporter's and runs in one frame, and on every call of `inc(uint256)` with any argument +word, no value and any storage, EthLib runs it to an observable meeting `incPost`. -/ +theorem inc_spec_bytecode : + Bound Final.manifest code ∧ FrameLocal code = true ∧ + ∀ call, SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnInc [] call → + ∃ obs, Target.run code call = some obs ∧ SolidCore.Verify.VC.Counter.incPost call obs := by + obtain ⟨c, hc⟩ := contract_ok + exact ⟨Final.bound, Final.frameLocal, fun call h => + Verdict.bytecode_of_triple hc (fun _ h => inc_in_scope h) + (SolidCore.Verify.VC.Counter.inc_triple (by exact hc)) call h trivial⟩ + +/-- info: 'SolidCore.Refinement.Solar.Counter.EndToEnd.inc_spec_bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms inc_spec_bytecode + +/-- Every call of §get§ in the binding scope is in the stage's scope. -/ +theorem get_in_scope {call : Call} + (h : SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnGet [] call) : + scopeEvery call := by + obtain ⟨σ, -, fn, hfn, args, hl, -, rfl⟩ := h + simp only [List.mem_singleton] at hfn + subst hfn + match args, hl with + | [], _ => + refine ⟨Nat.two_pow_pos 256, Or.inr (Or.inl ?_)⟩ + simp only [Evm.Wide.callOf, List.map] + rfl + +/-- **The counter's §get§ on the deployed bytecode.** On every call of §get()§ with no value and +any storage, EthLib runs the bytecode to a success that returns slot 0 as a word and changes no +slot. §get§ has no NatSpec clause, so solar-verify emits no obligation for it: §get_triple§ is +proved directly of SolidCore's run, with no VC behind it. -/ +theorem get_spec_bytecode : + Bound Final.manifest code ∧ FrameLocal code = true ∧ + ∀ call, SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnGet [] call → + ∃ obs, Target.run code call = some obs ∧ SolidCore.Verify.VC.Counter.getPost call obs := by + obtain ⟨c, hc⟩ := contract_ok + exact ⟨Final.bound, Final.frameLocal, fun call h => + Verdict.bytecode_of_triple hc (fun _ h => get_in_scope h) + (SolidCore.Verify.VC.Counter.get_triple (by exact hc)) call h trivial⟩ + +/-- info: 'SolidCore.Refinement.Solar.Counter.EndToEnd.get_spec_bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms get_spec_bytecode + +end SolidCore.Refinement.Solar.Counter.EndToEnd diff --git a/Contracts/Counter/Execution.lean b/Contracts/Counter/Execution.lean new file mode 100644 index 00000000..c97894d8 --- /dev/null +++ b/Contracts/Counter/Execution.lean @@ -0,0 +1,73 @@ +import SolidCore.Refinement.Solar.AssembleCut +import SolidCore.Refinement.Solar.AssembleFast +import counter.gen.Counter.Evm5 +import counter.gen.Counter.Bytecode + +/-! +# Counter's bytecode runs as its final EVM IR, at every gas + +solar's final EVM IR of `Counter` (`evm5`, freshly exported by the certify driver into +`Certified/counter/gen`) against the exported bytecode: the checker with GAS and memory at any +offset (`AssembleCut.checkC`) accepts it, so at every gas below `2 ^ 256` every result of the +bytecode is the EVM IR's or a failure that changes nothing (`bytecode_runs`). The certificate +is untrusted data from the asm-cert inference; the kernel's evaluation of `checkC` re-derives it. +Mutants of the bytecode (an altered SSTORE byte, an altered jump target) fail the check by +evaluation. +-/ + +namespace SolidCore.Refinement.Solar.CounterRun + +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCut SolarTV.Export.Counter + +/-- The exported runtime bytecode. -/ +def code : ByteArray := ⟨(bytecode.map UInt8.ofNat).toArray⟩ + +def cert : Cert := + { offsets := [0x0, 0x34, 0x38, 0x41], + needs := [0, 0, 1, 2], + top := 2 ^ 140, + turned := [], + costs := [35, 3, 7, 9], + types := [[], [], [some false], [some false, some false]], + rets := [], + env := false, + reads := false } + +def maxs : List Nat := [0, 1, 1, 2] + +set_option maxRecDepth 100000 in +theorem walk_ok : (SolarTV.Assembly.walk (bytesOf code) cert.offset 0 (lower evm5 cert)).isSome = + true := by + have hw := walkS_drop (bytesOf code) cert.offset (lower evm5 cert) 0 (Nat.zero_le _) + rw [List.drop_zero] at hw + rw [← hw] + decide +kernel + +set_option maxRecDepth 100000 in +theorem blocks_ok : blocksOkC evm5 cert maxs 0 evm5.blocks = true := by + decide +kernel + +theorem labels_ok : labelsValid evm5 cert code = true := + labelsValid_of_walk walk_ok + +theorem size_ok : code.size < 2 ^ 32 := by + decide +kernel + +theorem check_ok : checkC evm5 code cert maxs = true := by + simp only [checkC, walk_ok, blocks_ok, labels_ok, decide_eq_true size_ok, Bool.and_true, + Bool.true_and] + decide + +/-- **Counter's bytecode, run by run**: at every gas below `2 ^ 256` and every call, the oracle +of the run's table makes every result of the bytecode the final EVM IR's or a failure that changes +nothing. -/ +theorem bytecode_runs (scope : SolarTV.Call → Prop) : + WithinRunLt SolarTV.evmirSem (fun _ => evm5) code scope (RunOracle.CertOk cert) := + withinRun_of_checkC check_ok scope + +/-- info: 'SolidCore.Refinement.Solar.CounterRun.bytecode_runs' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecode_runs + +end SolidCore.Refinement.Solar.CounterRun diff --git a/Contracts/Counter/Exports.lean b/Contracts/Counter/Exports.lean new file mode 100644 index 00000000..a0157067 --- /dev/null +++ b/Contracts/Counter/Exports.lean @@ -0,0 +1,41 @@ +import Contracts.Counter.Headline +import SolidCore.Refinement.Deploy + +/-! +# Counter's exports, by name, and its deployment + +The names the blueprint's statements use for Counter's existing exports: \`code\` (solar's runtime +bytecode), \`spec\` (solar-verify's exported spec) and \`scope\` (\`scopeEvery\`), with \`spec_holds\` the +headline's spec clause about them, and \`deploys\`: solar's init code deploys \`code\` with the empty +storage (\`Deploys\`, from \`Deploy.initcode_runs\`). +-/ + +namespace Contracts.Counter + +open SolidCore.Refinement + +/-- solar's runtime bytecode for Counter. -/ +abbrev code : ByteArray := SolidCore.Refinement.Solar.Counter.code + +/-- solar-verify's exported spec of Counter. -/ +abbrev spec : SolidCore.Spec.Bundle := SolidCore.Refinement.Solar.Counter.Headline.spec + +/-- Every call the headline covers. -/ +abbrev scope : Call → Prop := SolidCore.Refinement.Solar.Counter.scopeEvery + +/-- The headline's spec clause: solar-verify's spec of Counter holds of \`code\` under EthLib on +\`scope\`. -/ +theorem spec_holds : + SolidCore.Spec.Holds ethLib code scope spec SolidCore.Refinement.Solar.Counter.Headline.ctxOf + SolidCore.Refinement.Solar.Counter.Headline.step := + SolidCore.Refinement.Solar.Counter.Headline.spec_holds_of_bytecode.2.2.2.choose_spec.2.2.1 + +/-- **solar's init code deploys Counter's runtime bytecode**, with the empty storage. -/ +theorem deploys : Deploys SolidCore.Refinement.Solar.Counter.Deploy.initcode code [] := + deploys_of_run SolidCore.Refinement.Solar.Counter.Deploy.initcode_runs rfl rfl (fun _ => rfl) + +/-- info: 'Contracts.Counter.deploys' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms deploys + +end Contracts.Counter diff --git a/Contracts/Counter/Final.lean b/Contracts/Counter/Final.lean new file mode 100644 index 00000000..dca503d6 --- /dev/null +++ b/Contracts/Counter/Final.lean @@ -0,0 +1,243 @@ +import Verify.Final +import SolidCore.Refinement.Solar.Counter.Every + +/-! +# The counter milestone's certificate + +The first instance of `Final.Certificate`: solar's runtime bytecode for + + contract Counter { uint256 x; function inc(uint256 d) external { x += d; } + function get() external view returns (uint256) { return x; } } + +(solar-tv/milestone/counter, `-Ogas --evm-version osaka`), bound to the manifest the exporter +wrote with its stages (`manifest`, `bound`: the bytecode's hex is the manifest's, checked by the +kernel), meets its specification (`spec`: `inc(d)` ensures `x == old(x) + d` and returns +nothing, `get()` ensures `x == old(x)` and returns `x`; neither is payable) and agrees with +SolidCore's checked contract on every call of the specification, with any value and from any +storage (`certificate`). Every stage is a theorem: the source stage and the assembly stage of +`Every.lean` and solar-tv's backend stages, composed by `certifiedEvery`. + +The non-vacuity lemmas show the specification is not met trivially: the bytecode succeeds on +`inc(1)` from the empty storage and stores 1 (`inc_succeeds`), reverts on the overflow +(`inc_overflow_fails`), and the postcondition rejects a state that did not change +(`ensures_rejects`). +-/ + +namespace SolidCore.Refinement.Solar.Counter.Final + +open SolidCore.Refinement SolidCore.Refinement.Final SolidCore.Refinement.Abi +open SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Wide SolidCore.Refinement.Evm +open EthLib.Base + +/-! ## The specification -/ + +/-- `inc(uint256 d)`: `x == old(x) + d`, no return data. -/ +def incSpec : FnSpec Nat where + name := "inc" + sel := incSelector + params := [.uint 256] + requires _ _ := True + ensures args x x' out := x' = x + args.headD 0 ∧ out = [] + payable := false + +/-- `get()`: `x == old(x)`, returns `x`. -/ +def getSpec : FnSpec Nat where + name := "get" + sel := getSelector + params := [] + requires _ _ := True + ensures _ x x' out := x' = x ∧ out = Verify.word x + payable := false + +/-- Counter's specification: the abstract state is `x`, slot 0. -/ +def spec : ContractSpec Nat where + abs s := s 0 + invariant _ := True + fns := [incSpec, getSpec] + +/-! ## From the observable on every call -/ + +theorem inc_call (a v : Nat) (ha : a < 2 ^ 256) (σ : List (Nat × Nat)) : + incSpec.call [a] v σ = + { callOf incSelector [BitVec.ofNat 256 a] with callvalue := v, storage := σ } := by + simp only [FnSpec.call, incSpec, callOf, List.map_cons, List.map_nil, BitVec.toNat_ofNat, + Nat.mod_eq_of_lt ha] + +theorem get_call (v : Nat) (σ : List (Nat × Nat)) : + getSpec.call [] v σ = { callAt getSelector [] σ with callvalue := v } := rfl + +theorem scope_inc (a v : Nat) (ha : a < 2 ^ 256) (hv : v < 2 ^ 256) (σ : List (Nat × Nat)) : + scopeEvery (incSpec.call [a] v σ) := by + rw [inc_call a v ha] + exact ⟨hv, Or.inl ⟨_, rfl⟩⟩ + +theorem scope_get (v : Nat) (hv : v < 2 ^ 256) (σ : List (Nat × Nat)) : + scopeEvery (getSpec.call [] v σ) := + ⟨hv, Or.inr (Or.inl rfl)⟩ + +theorem rejected_outcome {f : FnSpec Nat} {args : List Nat} {call : Call} : + spec.Outcome f args call (Abi.rejected call.storage) := + ⟨fun h => absurd h (by simp [Abi.rejected]), fun _ => ⟨rfl, rfl⟩⟩ + +theorem typed_inc {args : List Nat} (h : incSpec.Typed args) : ∃ a, a < 2 ^ 256 ∧ args = [a] := by + unfold FnSpec.Typed incSpec at h + cases h with + | cons ha hrest => + cases hrest + exact ⟨_, by simpa [Param.clean] using ha, rfl⟩ + +theorem typed_get {args : List Nat} (h : getSpec.Typed args) : args = [] := by + unfold FnSpec.Typed getSpec at h + cases h + rfl + +/-- The specification holds of every program that shows `expectedEvery` on every call of +`scopeEvery`. -/ +theorem holds_of_every {S : Sem} {p : S.Prog} + (h : ∀ call, scopeEvery call → S.run p call = some (expectedEvery call)) : + Holds S p spec := by + intro f hf args ht v hv σ _ _ obs hrun + simp only [spec, List.mem_cons, List.not_mem_nil, or_false] at hf + rcases hf with rfl | rfl + · obtain ⟨a, ha, rfl⟩ := typed_inc ht + rw [h _ (scope_inc a v ha hv σ)] at hrun + cases hrun + by_cases h0 : v = 0 + · subst h0 + rw [inc_call a 0 ha] + have hcall : { callOf incSelector [BitVec.ofNat 256 a] with callvalue := 0, storage := σ } = + { callOf incSelector [BitVec.ofNat 256 a] with storage := σ } := rfl + rw [hcall, expectedEvery_inc] + unfold expectedAt + have hd : (BitVec.ofNat 256 a).toNat = a := by rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt ha] + split_ifs with hof + · refine ⟨fun _ => ⟨?_, trivial, fun _ => rfl⟩, fun h => absurd h (by simp)⟩ + simp [spec, incSpec, ContractSpec.pre, hd, callOf] + · exact ⟨fun h => absurd h (by simp), fun _ => ⟨rfl, rfl⟩⟩ + · rw [expectedEvery_value _ h0] + exact rejected_outcome + · obtain rfl := typed_get ht + rw [h _ (scope_get v hv σ)] at hrun + cases hrun + by_cases h0 : v = 0 + · subst h0 + rw [get_call, show ({ callAt getSelector [] σ with callvalue := 0 } : Call) = + callAt getSelector [] σ from rfl, expectedEvery_get] + exact ⟨fun _ => ⟨⟨rfl, rfl⟩, trivial, fun _ => rfl⟩, fun h => absurd h (by simp [getAt])⟩ + · rw [expectedEvery_value _ h0] + exact rejected_outcome + +theorem calls_every {call : Call} (h : spec.Calls call) : scopeEvery call := by + obtain ⟨f, hf, args, ht, v, hv, σ, rfl⟩ := h + simp only [spec, List.mem_cons, List.not_mem_nil, or_false] at hf + rcases hf with rfl | rfl + · obtain ⟨a, ha, rfl⟩ := typed_inc ht + exact scope_inc a v ha hv σ + · obtain rfl := typed_get ht + exact scope_get v hv σ + +/-- EthLib runs solar's bytecode to `expectedEvery` on every call of `scopeEvery`. -/ +theorem target_every (call : Call) (h : scopeEvery call) : + Target.run code call = some (expectedEvery call) := by + obtain ⟨-, -, -, hsat⟩ := certifiedEvery + obtain ⟨obs, hrun, hpost⟩ := hsat call h trivial + change Target.run code call = some obs at hrun + rw [hrun, show obs = expectedEvery call from hpost] + +/-! ## The manifest -/ + +/-- The manifest the exporter wrote with Counter's stages. -/ +def manifest : Manifest where + contract := "Counter" + sourceSha256 := (SolarTV.Export.Counter.Manifest.sources.headD ("", "")).2 + compilerCommit := SolarTV.Export.Counter.Manifest.compiler + options := SolarTV.Export.Counter.Manifest.arguments + runtimeHex := SolarTV.Export.Counter.Manifest.bytecodeHex + runtimeSha256 := SolarTV.Export.Counter.Manifest.bytecodeSha256 + +theorem hex_bound : hexOf (code.data.toList.map (·.toNat)) = manifest.runtimeHex := by + decide +kernel + +theorem bound : Bound manifest code := hex_bound + +theorem frameLocal : FrameLocal code = true := by decide +kernel + +/-! ## The certificate -/ + +/-- **Counter's certificate.** solar's bytecode, bound to its manifest and running in one frame, +agrees with SolidCore's checked Counter on every call of `inc` and `get`, with any value and +from any storage, and meets Counter's specification, which SolidCore's Counter meets too. -/ +noncomputable def certificate : Certificate spec manifest := + let c := Classical.choose contract_ok + have hc : contract? = .ok c := Classical.choose_spec contract_ok + { code + fuel + source := c + bound + frameLocal + sourceHolds := holds_of_every fun call h => source_run_every hc call h + refines := fun call h => + ⟨_, source_run_every hc call (calls_every h), target_every call (calls_every h)⟩ + holds := holds_of_every target_every } + +/-- The certificate's two theorems, as one statement. -/ +theorem certified : + Bound manifest code ∧ FrameLocal code = true ∧ + ∃ c, contract? = .ok c ∧ Agree (solidCore fuel) ethLib c code spec.Calls ∧ + Holds (solidCore fuel) c spec ∧ Holds ethLib code spec := by + obtain ⟨c, hc⟩ := contract_ok + exact ⟨bound, frameLocal, c, hc, + fun call h => ⟨_, source_run_every hc call (calls_every h), target_every call (calls_every h)⟩, + holds_of_every fun call h => source_run_every hc call h, holds_of_every target_every⟩ + +/-- The invariants and the specification across every sequence of calls, each from the storage +the one before left. -/ +theorem certified_trace {carry : Carry} + (exact : ∀ call obs, Target.run code call = some obs → Carries carry call obs) + (σ : List (Nat × Nat)) (steps : List (Step Nat)) + (hsteps : ∀ s ∈ steps, s.f ∈ spec.fns ∧ s.f.Typed s.args ∧ s.value < 2 ^ 256) : + Trace spec (Target.run code) carry σ steps := + (holds_of_every target_every).trace (S := ethLib) exact σ steps trivial hsteps + +/-! ## Non-vacuity -/ + +/-- The bytecode succeeds on `inc(1)` with no value from the empty storage and stores 1. -/ +theorem inc_succeeds : ∃ obs, Target.run code (incSpec.call [1] 0 []) = some obs ∧ + obs.success = true ∧ obs.storage 0 = 1 := by + refine ⟨_, target_every _ (scope_inc 1 0 (by decide) (by decide) []), ?_⟩ + rw [inc_call 1 0 (by decide)] + rw [show ({ callOf incSelector [BitVec.ofNat 256 1] with callvalue := 0, storage := [] } : Call) = + { callOf incSelector [BitVec.ofNat 256 1] with storage := [] } from rfl, expectedEvery_inc] + simp [expectedAt, slotValue] + +/-- The bytecode fails on `inc(1)` from a storage whose `x` is `2 ^ 256 - 1`. -/ +theorem inc_overflow_fails : ∃ obs, Target.run code (incSpec.call [1] 0 [(0, 2 ^ 256 - 1)]) = some obs ∧ + obs.success = false := by + refine ⟨_, target_every _ (scope_inc 1 0 (by decide) (by decide) _), ?_⟩ + rw [inc_call 1 0 (by decide)] + have hcall : ({ callOf incSelector [BitVec.ofNat 256 1] with callvalue := 0, storage := [(0, 2 ^ 256 - 1)] } : Call) = + { callOf incSelector [BitVec.ofNat 256 1] with storage := [(0, 2 ^ 256 - 1)] } := rfl + rw [hcall, expectedEvery_inc] + simp [expectedAt, slotValue] + +/-- The postcondition of `inc(1)` rejects a state that did not change. -/ +theorem ensures_rejects : ¬ incSpec.ensures [1] 0 0 [] := by + simp [incSpec] + +/-- info: 'SolidCore.Refinement.Solar.Counter.Final.certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified + +/-- info: 'SolidCore.Refinement.Solar.Counter.Final.certified_trace' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified_trace + +/-- info: 'SolidCore.Refinement.Solar.Counter.Final.inc_succeeds' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms inc_succeeds + +/-- info: 'SolidCore.Refinement.Solar.Counter.Final.inc_overflow_fails' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms inc_overflow_fails + +end SolidCore.Refinement.Solar.Counter.Final diff --git a/Contracts/Counter/Headline.lean b/Contracts/Counter/Headline.lean new file mode 100644 index 00000000..13df0037 --- /dev/null +++ b/Contracts/Counter/Headline.lean @@ -0,0 +1,290 @@ +import Contracts.Counter.Verdict +import Contracts.Counter.Spec.Export +import Contracts.Counter.Spec.ExportWrong +import Contracts.Counter.EndToEnd +import Contracts.Counter.Deploy + +/-! +# Counter: solar-verify's spec holds of solar's deployed bytecode + +The counter milestone (`scripts/refinement/counter/counter.sol`, solar-tv/milestone/counter, +`-Ogas --evm-version osaka`) annotated for solar-verify in `scripts/verify/CounterMilestone.sol` +(the same text plus one NatSpec line, which `scripts/verify/check.sh` checks): + + contract Counter { + uint256 x; + /// @custom:ensures x == old(x) + d + function inc(uint256 d) external { x += d; } + function get() external view returns (uint256) { return x; } } + +`solar-verify --emit-lean-spec` writes that spec as `Export.Counter.Counter` (a +`SolidCore.Spec.Bundle`; `get` has no spec, so the exporter leaves it out). Its meaning is +`SolidCore.Spec.Holds`: every call of `inc` with a clean word argument finishes, and when it +succeeds slot 0 holds the old slot 0 plus the argument. There is no succeeds-if, so no claim +that it succeeds. + +* `holds_source`: the spec of SolidCore's checked `Counter` on every call of `scopeEvery` (any + value, any storage; inc's and get's ABI encodings, short call data, unknown selectors, short + arguments), from SolidCore's run of each (`source_run_every`). +* `verdict`: solar-verify's verdict (`SolidCore.Spec.Verdict`, the one trusted item of + `spec_of_verdict`) under Counter's trusted base `Verdict.hyps` (`Hyps.plain`: no hashing, no + external call, no assembly, no assume, no trusted function), proved in Lean rather than + trusted. +* `EndToEnd.inc_spec_bytecode`, `EndToEnd.get_spec_bytecode`: `inc`'s clause read off + solar-verify's own checked obligation through the source bridge + (`SolidCore.Verify.VC.Counter.inc_triple`, whose binding ties solar-verify's encoding of the new + `x` and of the success guard to SolidCore's run), and `get`'s triple, each carried to the + bytecode by the certified stage; the headline includes both. +* **`spec_holds_of_bytecode`**: the headline. solar's runtime bytecode, bound to the exporter's + manifest by its hex and to the spec export by the manifest's SHA-256 string, runs in one frame, + agrees with SolidCore's checked `Counter` on every call of the scope, and meets solar-verify's + spec under EthLib, through the composition `Verdict.bytecode_spec_of_verdict` of the certified + stages (source, backend, assembly) with the verdict. +* `wrong_fails`: the negative. The spec mutant `x == old(x) + d + 1` + (`scripts/verify/mutant/CounterSpecMut.sol`, which solar-verify also rejects) does not hold of + the bytecode, by a mismatch: `inc(1)` from the empty storage stores 1. + +* `Deploy.initcode_runs`: deployment. solar's init code for the same source runs in one frame + with no value to success and returns exactly `code`, writing no storage; the headline includes + it. + +Trusted base left: Lean's kernel; EthLib's EVM (`Target.run`, at its default gas limit, one +frame) as the meaning of the bytecode; that `Export.Counter` is what solar-verify exports for the +annotated source (checked by `scripts/verify/check.sh` outside the kernel). Not covered: the +creation message's address derivation and code deposit (the deposit's checks hold of `code`, +`Deploy.deposit_ok`), other gas limits, and call data with bytes past the ABI encoding. +-/ + +namespace SolidCore.Refinement.Solar.Counter.Headline + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm +open SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Final +open EthLib.Base (U256) + +/-- The exported spec. -/ +abbrev spec : SolidCore.Spec.Bundle := SolidCore.Spec.Export.Counter.Counter + +/-- The call context of SolidCore's and EthLib's interface (`Refinement.Statement`): sender +`0x2000`, the contract at `0x1000`, block timestamp 1. -/ +def ctxOf (call : Call) : SolidCore.Spec.Ctx := + { sender := 0x2000, value := call.callvalue, timestamp := 1, self := 0x1000 } + +/-- Counter has no ghost state. -/ +def step : SolidCore.Spec.GhostStep := fun _ g => g + +/-! ## Reading call data the way the spec does -/ + +theorem bytesWord_map (l : List UInt8) : + SolidCore.Spec.bytesWord (l.map (·.toNat)) = EthLib.Base.bytesToNat l := by + simp [SolidCore.Spec.bytesWord, EthLib.Base.bytesToNat, List.foldl_map] + +theorem spec_selectorOf_append (s : Nat) (hs : s < 2 ^ 32) (data : ByteArray) (v : Nat) + (σ : List (Nat × Nat)) : + SolidCore.Spec.selectorOf { calldata := selectorOf s ++ data, callvalue := v, storage := σ } = s := by + simp only [SolidCore.Spec.selectorOf, selectorOf, ByteArray.data_append, Array.toList_append, + List.map_append, List.toList_toArray] + rw [List.take_append_of_le_length (by simp [EthLib.Base.natToBytes_length]), + List.take_of_length_le (by simp [EthLib.Base.natToBytes_length]), bytesWord_map, + EthLib.Base.bytesToNat_natToBytes_of_lt (by simpa using hs)] + +theorem bytesWord_word {v : Nat} (h : v < 2 ^ 256) : SolidCore.Spec.bytesWord (Verify.word v) = v := by + rw [Verify.word, bytesWord_map, EthLib.Base.bytesToNat_natToBytes_of_lt] + simpa using h + +theorem length_word (v : Nat) : (Verify.word v).length = 32 := by + simp [Verify.word, EthLib.Base.natToBytes_length] + +theorem words_word {v : Nat} (h : v < 2 ^ 256) : SolidCore.Spec.words (Verify.word v) = [v] := by + simp only [SolidCore.Spec.words, length_word, Nat.reduceDiv, List.range_one, List.map_cons, + List.map_nil, Nat.mul_zero, List.drop_zero] + rw [List.take_of_length_le (by rw [length_word]), bytesWord_word h] + +theorem argBytes_one (a : Nat) : Dirty.argBytes [a] = Verify.word a := by + simp [Dirty.argBytes, Verify.word] + +/-- The argument words after the selector of inc's ABI call data. -/ +theorem words_inc (d : U256) : + SolidCore.Spec.words + ((((callOf incSelector [d]).calldata).data.toList.map (·.toNat)).drop 4) = [d.toNat] := by + simp only [callOf, List.map_cons, List.map_nil] + rw [Dirty.bytes_calldata, Wide.drop_selector, argBytes_one, words_word d.isLt] + +/-- Fewer than 32 bytes after the selector: no argument word. -/ +theorem words_short (s : Nat) (data : ByteArray) (h : data.size < 32) : + SolidCore.Spec.words (((selectorOf s ++ data).data.toList.map (·.toNat)).drop 4) = [] := by + have hl : ((selectorOf s ++ data).data.toList.map (·.toNat)).length = 4 + data.size := by + rw [List.length_map, Array.length_toList] + exact (ByteArray.size_append ..).trans (by rw [size_selectorOf]) + unfold SolidCore.Spec.words + rw [List.length_drop, hl, show (4 + data.size - 4) / 32 = 0 by omega] + simp only [List.range_zero, List.map_nil] + +theorem rejected_success (σ : List (Nat × Nat)) : (Abi.rejected σ).success = false := rfl + +/-! ## The spec of SolidCore's checked counter -/ + +/-- The one function the spec has: `inc`. -/ +theorem mem_specs {fs : SolidCore.Spec.FnSpec} (h : fs ∈ spec.spec.specs) : + fs = spec.spec.specs.head (by simp [spec, SolidCore.Spec.Export.Counter.Counter]) := by + simpa [spec, SolidCore.Spec.Export.Counter.Counter] using h + +/-- **What Counter does, read through the spec.** On every call of the scope, the observable +`expectedEvery` meets `inc`'s postcondition from any pre-state meeting its precondition. -/ +theorem post_every {call : Call} (hs : scopeEvery call) {fs : SolidCore.Spec.FnSpec} + (hfs : fs ∈ spec.spec.specs) {args : List Int} {pre : SolidCore.Spec.State} + (hpre : SolidCore.Spec.Pre spec fs (ctxOf call) pre call args) : + SolidCore.Spec.Post spec fs (ctxOf call) pre (step call pre.ghost) (expectedEvery call) args := by + rw [mem_specs hfs] at hpre ⊢ + refine ⟨fun hsucc => ?_, fun hne => absurd rfl hne⟩ + obtain ⟨⟨h4, hsel, hdec⟩, hst, -, -, -⟩ := hpre + rcases call with ⟨cd, v, σ⟩ + obtain ⟨hv, hcl⟩ := hs + dsimp only at hv hcl hsucc hsel hdec h4 hst ⊢ + by_cases h0 : v = 0 + swap + · rw [expectedEvery_value _ h0] at hsucc + exact absurd hsucc (by simp [rejected_success]) + subst h0 + rcases hcl with ⟨d, rfl⟩ | rfl | hshort | ⟨s, data, hs, rfl, hsel'⟩ + · -- inc's ABI call data: the run adds the argument to slot 0. + have hcall : ({ calldata := (callOf incSelector [d]).calldata, callvalue := 0, storage := σ } : Call) = + { callOf incSelector [d] with storage := σ } := rfl + rw [hcall, expectedEvery_inc] at hsucc ⊢ + rw [words_inc] at hdec + simp only [spec, SolidCore.Spec.Export.Counter.Counter, List.head, SolidCore.Spec.decodeWords, + SolidCore.Spec.Ty.ofWord, d.isLt, ite_true, bind, pure, Option.bind, Option.some.injEq] at hdec + subst hdec + unfold expectedAt at hsucc ⊢ + split_ifs at hsucc ⊢ with hof + · refine ⟨[], by simp [SolidCore.Spec.Export.Counter.Counter, SolidCore.Spec.decodeWords], ?_, ?_⟩ + · have hpre0 : pre.storage 0 = slotValue σ 0 := by rw [hst] + have hlt : slotValue σ 0 < 2 ^ 256 := SolidCore.Refinement.Evm.Wide.slotValue_lt σ 0 + simp [SolidCore.Spec.Bundle.satAll, SolidCore.Spec.Bundle.sat, SolidCore.Spec.eval, + SolidCore.Spec.slotOf, SolidCore.Spec.mkEnv, SolidCore.Spec.Env.cur, + SolidCore.Spec.BinOp.apply, SolidCore.Spec.Ty.ofBits, SolidCore.Spec.toWord, + SolidCore.Spec.Export.Counter.Counter, hpre0] + omega + · simp [SolidCore.Spec.Bundle.satAll, SolidCore.Spec.Export.Counter.Counter] + all_goals simp at hsucc + · -- get's call data: not inc's selector. + have : SolidCore.Spec.selectorOf + ({ calldata := (callOf getSelector []).calldata, callvalue := 0, storage := σ } : Call) = + getSelector := by + rw [calldata_get] + exact spec_selectorOf_append _ (by decide) _ _ _ + rw [this] at hsel + simp [spec, SolidCore.Spec.Export.Counter.Counter, getSelector] at hsel + · exact absurd h4 (by omega) + · rw [spec_selectorOf_append s hs data 0 σ] at hsel + simp only [spec, SolidCore.Spec.Export.Counter.Counter, List.head] at hsel + rcases hsel' with ⟨hne, -⟩ | ⟨-, hshort⟩ + · exact absurd hsel (by simpa [incSelector] using hne) + · rw [words_short s data hshort] at hdec + simp [spec, SolidCore.Spec.Export.Counter.Counter, SolidCore.Spec.decodeWords] at hdec + +/-- **solar-verify's spec, of SolidCore's checked `Counter`**, on every call of the scope. -/ +theorem holds_source {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + SolidCore.Spec.Holds (solidCore fuel) c scopeEvery spec ctxOf step := + fun _ hfs call hs _ _ hpre => ⟨_, source_run_every hc call hs, post_every hs hfs hpre⟩ + +/-- **solar-verify's verdict on Counter, proved.** The one trusted item of +`SolidCore.Spec.spec_of_verdict`, under Counter's trusted base, is a theorem here. -/ +theorem verdict {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) + (deployed : Nat → Nat) : + SolidCore.Spec.Verdict (solidCore fuel) c scopeEvery spec ctxOf step + ((Verdict.hyps c deployed).toAssumptions scopeEvery spec ctxOf step) := + fun fs hfs => (holds_source hc fs hfs).mono fun _ h => h.1 + +/-! ## The headline -/ + +/-- The spec export names the bytecode the certificate binds. -/ +theorem export_bound : + SolidCore.Spec.Export.Counter.manifest.bytecodeSha256 = Final.manifest.runtimeSha256 := by + decide +kernel + +/-- **solar-verify's spec of `Counter` holds of solar's deployed bytecode.** solar's runtime +bytecode for the counter milestone is bound to the exporter's manifest (its hex, by the +kernel) and to the spec export (the manifest's SHA-256 string), runs in one frame, agrees with SolidCore's +checked `Counter` on every call of `scopeEvery`, and meets solar-verify's exported spec under +EthLib on every call of `scopeEvery`: any value, any storage, inc's and get's ABI encodings, +short call data, unknown selectors and short arguments. The spec's well-formedness is checked +by the kernel; the verdict and the trusted base are discharged (`verdict`, +`Instances.counter_on`). With it, the source bridge's two end-to-end theorems +(`EndToEnd.inc_spec_bytecode`: solar-verify's checked obligation for `inc`, bound to SolidCore's +run by `inc_triple`; `EndToEnd.get_spec_bytecode`: `get` returns slot 0 and writes nothing), on +the ABI calls of each with no value and any storage; and solar's init code deploys `code` +(`Deploy.initcode_runs`). -/ +theorem spec_holds_of_bytecode : + SolidCore.Spec.Export.Counter.manifest.bytecodeSha256 = Final.manifest.runtimeSha256 ∧ + Bound Final.manifest code ∧ FrameLocal code = true ∧ + ∃ c, contract? = .ok c ∧ Agree (solidCore fuel) ethLib c code scopeEvery ∧ + SolidCore.Spec.Holds ethLib code scopeEvery spec ctxOf step ∧ + (∀ call, SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnInc [] call → + ∃ obs, Target.run code call = some obs ∧ SolidCore.Verify.VC.Counter.incPost call obs) ∧ + (∀ call, SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnGet [] call → + ∃ obs, Target.run code call = some obs ∧ SolidCore.Verify.VC.Counter.getPost call obs) ∧ + Target.run Deploy.initcode Deploy.deployCall = some Deploy.deployed := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hb, hf, ha, hh⟩ := Verdict.bytecode_spec_of_verdict hc (b := spec) (ctxOf := ctxOf) + (step := step) (fun _ => 0) SolidCore.Spec.Export.Counter.Counter_wf + (SolidCore.Spec.opaqueInRange_of_none (by decide)) (verdict hc fun _ => 0) + exact ⟨export_bound, hb, hf, c, hc, ha, hh, EndToEnd.inc_spec_bytecode.2.2, + EndToEnd.get_spec_bytecode.2.2, Deploy.initcode_runs⟩ + +/-! ## The negative -/ + +/-- **The spec mutant fails, by a mismatch.** `x == old(x) + d + 1` does not hold of the +bytecode: `inc(1)` from the empty storage succeeds and stores 1, and the mutant asks for 2. -/ +theorem wrong_fails : + ¬ SolidCore.Spec.Holds ethLib code scopeEvery SolidCore.Spec.Export.CounterSpecMut.Counter + ctxOf step := by + intro h + let call : Call := { callOf incSelector [1#256] with storage := [] } + have hs : scopeEvery call := ⟨by decide, Or.inl ⟨1#256, rfl⟩⟩ + let pre : SolidCore.Spec.State := ⟨slotValue [], SolidCore.Spec.Ghost.zero, 0⟩ + have hne : SolidCore.Spec.Export.CounterSpecMut.Counter.spec.specs ≠ [] := by + simp [SolidCore.Spec.Export.CounterSpecMut.Counter] + have hfs := List.head_mem hne + have hpre : SolidCore.Spec.Pre SolidCore.Spec.Export.CounterSpecMut.Counter + (SolidCore.Spec.Export.CounterSpecMut.Counter.spec.specs.head hne) (ctxOf call) pre call [1] := by + refine ⟨⟨?_, ?_, ?_⟩, rfl, by simp [pre, ctxOf], ?_, ?_⟩ + · have := size_callOf 1#256 + simp only [call] at this ⊢ + omega + · change SolidCore.Spec.selectorOf + ({ calldata := (callOf incSelector [1#256]).calldata, callvalue := 0, storage := [] } : Call) = _ + have := spec_selectorOf_append incSelector (by decide) (wordsBytes [1#256]) 0 [] + rw [← calldata_inc] at this + rw [this] + simp [SolidCore.Spec.Export.CounterSpecMut.Counter, incSelector] + · show SolidCore.Spec.decodeWords _ (SolidCore.Spec.words + (((callOf incSelector [1#256]).calldata.data.toList.map (·.toNat)).drop 4)) = _ + rw [words_inc] + simp [SolidCore.Spec.Export.CounterSpecMut.Counter, SolidCore.Spec.decodeWords, + SolidCore.Spec.Ty.ofWord, bind, pure] + · simp [SolidCore.Spec.Bundle.satAll, SolidCore.Spec.Export.CounterSpecMut.Counter] + · simp [SolidCore.Spec.Bundle.satAll, SolidCore.Spec.Export.CounterSpecMut.Counter] + obtain ⟨obs, hrun, hpost⟩ := h _ hfs call hs [1] pre hpre + simp only [ethLib] at hrun + rw [Final.target_every call hs] at hrun + have hobs := Option.some.inj hrun + subst hobs + have hcall : call = { callOf incSelector [1#256] with storage := [] } := rfl + rw [hcall, expectedEvery_inc] at hpost + have hok : (expectedAt [] 1#256).success = true := by simp [expectedAt, slotValue] + obtain ⟨rets, -, hens, -⟩ := hpost.1 hok + have := hens _ (List.mem_singleton_self _) + simp [SolidCore.Spec.Bundle.sat, SolidCore.Spec.Export.CounterSpecMut.Counter, + SolidCore.Spec.eval, SolidCore.Spec.slotOf, SolidCore.Spec.mkEnv, SolidCore.Spec.Env.cur, + SolidCore.Spec.BinOp.apply, SolidCore.Spec.Ty.ofBits, SolidCore.Spec.toWord, pre, + expectedAt, slotValue] at this + +/-- info: 'SolidCore.Refinement.Solar.Counter.Headline.spec_holds_of_bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms spec_holds_of_bytecode + +/-- info: 'SolidCore.Refinement.Solar.Counter.Headline.wrong_fails' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms wrong_fails + +end SolidCore.Refinement.Solar.Counter.Headline diff --git a/Contracts/Counter/Shape.lean b/Contracts/Counter/Shape.lean new file mode 100644 index 00000000..0000eff7 --- /dev/null +++ b/Contracts/Counter/Shape.lean @@ -0,0 +1,133 @@ +import Verify.Shapes +import Contracts.Counter.Execution +import Contracts.Counter.ShapeSpec +import SolidCore.Refinement.Solar.AssembleGas +import SolidCore.Refinement.Solar.Counter.Assembly + +/-! +# Counter in the certified shape + +The four obligations of `Shapes.Certified` for solar's freshly exported runtime bytecode of +`Counter` (`CounterRun.code`, `Certified/counter/gen`) against SolidCore's checked `Counter` at +fuel 4096, on the declared valid calls `cspec.Calls` (`inc(uint256)` and `get()` with clean +arguments, any value below `2 ^ 256`, any storage): + +* `equiv`: at every gas below `2 ^ 256`, every result of the bytecode is SolidCore's or a failure + that changes nothing: the source stage (`loweringEvery`) and solar's backend stages + (`counter_mir_to_evmir`), under every oracle, composed with the assembly checker's per-run + theorem (`CounterRun.bytecode_runs`, from `checkC`) by `Shapes.equiv_of_runs`. +* `terminates`: SolidCore ends on every valid call within fuel 4096 (`source_run_every`), with an + allowed status (`allowed`): success, a call with value (neither function is payable), or + `inc` overflowing slot 0 with `Panic(0x11)`. No other revert is allowed. +* `meets`: solar-verify's specification (`Final.spec`: `inc(d)` ensures `x == old(x) + d`, + `get()` returns `x`) of every source result (`Shapes.specPost`). +* resources: from 1,281,806 gas on (`ShapeSpec.gasBound`: the straight-line checker's bound, + 22100 per item plus memory), the bytecode shows exactly the source's result, a revert with its + data included: the forward assembly stage at every gas from the bound on + (`Assemble.stage_of_check_gas`) after the same source and backend stages (`resources`). + +So `published` states `Shapes.Certified`, all four (`certified`). + +Negative controls (each by the kernel's evaluation): the assembly checker rejects the bytecode +with one byte changed (`SSTORE` dropped, a jump target moved, an opcode outside the supported set) +and the binding of `final` to the exported hex fails for any other bytes; the specification with +`x == old(x) + d + 1` is not met (`wrong_spec_not_meets`). +-/ + +namespace SolidCore.Refinement.Solar.Counter.Shape + +open SolidCore.Refinement SolidCore.Refinement.Final SolidCore.Refinement.Abi +open SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Wide SolidCore.Refinement.Evm +open SolidCore.Refinement.Solar.Counter.Final SolidCore.Refinement.Solar.Counter.ShapeSpec +open EthLib.Base + +theorem allowed_every (call : Call) (h : cspec.Calls call) : allowed call (expectedEvery call) := by + obtain ⟨f, hf, args, ht, v, hv, σ, rfl⟩ := h + by_cases h0 : v = 0 + swap + · exact Or.inr (Or.inl h0) + subst h0 + simp only [cspec, SolidCore.Refinement.Solar.Counter.Final.spec, List.mem_cons, List.not_mem_nil, or_false] at hf + rcases hf with rfl | rfl + · obtain ⟨a, ha, rfl⟩ := typed_inc ht + rw [inc_call a 0 ha] + have hcall : ({ callOf incSelector [BitVec.ofNat 256 a] with callvalue := 0, storage := σ } : Call) = + { callOf incSelector [BitVec.ofNat 256 a] with storage := σ } := rfl + rw [hcall, expectedEvery_inc] + unfold expectedAt + split_ifs with hof + · exact Or.inl rfl + · exact Or.inr (Or.inr ⟨rfl, _, rfl, Nat.not_lt.mp hof⟩) + · obtain rfl := typed_get ht + rw [get_call, show ({ callAt getSelector [] σ with callvalue := 0 } : Call) = + callAt getSelector [] σ from rfl, expectedEvery_get] + exact Or.inl rfl + +/-- Source to final EVM IR, under every oracle, on the valid calls. -/ +theorem stage (o : SolarTV.Machine.Oracle) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : contract? = .ok c) : + SolarTV.Stage (solidCore fuel) (SolarTV.evmirSem o) c SolarTV.Export.Counter.evm5 cspec.Calls := + ((loweringEvery o hc).trans + ((SolarTV.Milestone.Counter.counter_mir_to_evmir o).mono fun _ _ => trivial)).mono + fun _ h => calls_every h + +theorem inhabited : ∃ call, cspec.Calls call := + ⟨_, ⟨incSpec, by simp [cspec, SolidCore.Refinement.Solar.Counter.Final.spec], [1], .cons (by decide) .nil, 0, by decide, [], rfl⟩⟩ + +theorem functional {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Shapes.Functional (solidCore fuel) c CounterRun.code cspec.Calls allowed (Shapes.specPost cspec) where + inhabited := Shape.inhabited + equiv := Shapes.equiv_of_runs (sem := SolarTV.evmirSem) (q := fun _ => SolarTV.Export.Counter.evm5) + (Ok := RunOracle.CertOk CounterRun.cert) + (fun call h => ⟨_, source_run_every hc call (calls_every h)⟩) + (fun o _ => stage o hc) (CounterRun.bytecode_runs cspec.Calls) + terminates := Shapes.terminates_of expectedEvery + (fun call h => source_run_every hc call (calls_every h)) allowed_every + meets := Shapes.meets_of_holds (holds_of_every fun call h => source_run_every hc call h) + +/-- The straight-line checker accepts the fresh bytecode (the certificate of `Counter.Assembly`). -/ +theorem check_fresh : + Assemble.check SolarTV.Export.Counter.evm5 CounterRun.code SolidCore.Refinement.Solar.Counter.cert = + true := by + decide +kernel + +theorem gasBound_ok : + Assemble.gasBound SolarTV.Export.Counter.evm5 SolidCore.Refinement.Solar.Counter.cert ≤ 1281806 := by + decide + +/-- **Resources**: from 1,281,806 gas on, the fresh bytecode shows SolidCore's result on every valid +call, through the source and backend stages and the forward assembly stage at every gas from the +checker's bound on (`Assemble.stage_of_check_gas`). -/ +theorem resources {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Shapes.Resources (solidCore fuel) c CounterRun.code cspec.Calls gasBound := + Shapes.resources_of_forward (B := SolarTV.evmirSem SolidCore.Refinement.Solar.W1.oracle) + (q := SolarTV.Export.Counter.evm5) + (fun call h => ⟨_, source_run_every hc call (calls_every h)⟩) + (stage _ hc) + (fun _ hv => ⟨show (1281806 : Nat) < 2 ^ 64 by decide, fun _ h1 _ obs hrun => + Assemble.stage_of_check_gas check_fresh _ (fun h => absurd h (by decide)) cspec.Calls + (Nat.le_trans gasBound_ok h1) _ hv obs hrun⟩) + +/-- **All four obligations.** -/ +theorem certified {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Shapes.Certified (solidCore fuel) c CounterRun.code cspec.Calls allowed (Shapes.specPost cspec) + gasBound := + let f := functional hc + ⟨f.inhabited, f.equiv, f.terminates, f.meets, resources hc⟩ + +/-- What the published statement asks of this module. -/ +theorem published : ∃ c, contract? = .ok c ∧ + Shapes.Certified (solidCore fuel) c CounterRun.code cspec.Calls allowed (Shapes.specPost cspec) + gasBound := by + obtain ⟨c, hc⟩ := contract_ok + exact ⟨c, hc, certified hc⟩ + +/-- info: 'SolidCore.Refinement.Solar.Counter.Shape.certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms certified + +/-- info: 'SolidCore.Refinement.Solar.Counter.Shape.functional' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms functional + +end SolidCore.Refinement.Solar.Counter.Shape diff --git a/Contracts/Counter/ShapeExport.lean b/Contracts/Counter/ShapeExport.lean new file mode 100644 index 00000000..3baff2e7 --- /dev/null +++ b/Contracts/Counter/ShapeExport.lean @@ -0,0 +1,110 @@ +import Contracts.Counter.Shape +import Contracts.Counter.Headline +import Verify.ShapeBundle + +/-! +# Counter in the certified shape, with solar-verify's exported spec + +`published` is `Shape.published` with the postcondition read off solar-verify's export of +`Certified/counter/counter.sol` (`/// @custom:ensures x == old(x) + d` on `inc`; `get` has no +spec), `Shapes.bundlePost Headline.spec Headline.ctxOf Headline.step`, in place of the Lean +restatement `Shapes.specPost cspec`: the meets obligation is `Headline.holds_source` (the +exported spec of SolidCore's checked `Counter` on `scopeEvery`, which covers every valid call) +through `Shapes.meets_of_bundle`. The certify driver states the same postcondition over the bundle +it exports in its own run; the kernel accepts this proof there only if the two bundles agree. + +Non-vacuity (`post_rejects`, `allowed_rejects`): the specification rejects a result of a valid +call (`inc(1)` from the empty storage succeeding with slot 0 left at 0), and the allowed statuses +reject a revert of a valid call (`inc(1)` with no value reverting with empty data, which is neither +the overflow's `Panic(0x11)` nor a call with value). +-/ + +namespace SolidCore.Refinement.Solar.Counter.ShapeExport + +open SolidCore.Refinement SolidCore.Refinement.Final SolidCore.Refinement.Abi +open SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Wide SolidCore.Refinement.Evm +open SolidCore.Refinement.Solar.Counter.Final SolidCore.Refinement.Solar.Counter.ShapeSpec +open SolidCore.Refinement.Solar.Counter.Headline +open EthLib.Base + +/-- The published shape with solar-verify's exported spec as the postcondition. -/ +theorem published : ∃ c, contract? = .ok c ∧ + Shapes.Certified (solidCore fuel) c CounterRun.code cspec.Calls allowed + (Shapes.bundlePost Headline.spec Headline.ctxOf Headline.step) gasBound := by + obtain ⟨c, hc, h⟩ := Shape.published + exact ⟨c, hc, { h with meets := Shapes.meets_of_bundle (fun _ h => calls_every h) (holds_source hc) }⟩ + +/-- `inc(1)` with no value from the empty storage. -/ +def incCall : Call := { callOf incSelector [1#256] with storage := [] } + +theorem incCall_valid : cspec.Calls incCall := by + refine ⟨incSpec, by simp [cspec, SolidCore.Refinement.Solar.Counter.Final.spec], [1], + .cons (by decide) .nil, 0, by decide, [], ?_⟩ + rw [inc_call 1 0 (by decide) []] + rfl + +/-- **The specification is not vacuous**: it rejects `inc(1)` succeeding with slot 0 left at 0. -/ +theorem post_rejects : ∃ call obs, cspec.Calls call ∧ + ¬ Shapes.bundlePost Headline.spec Headline.ctxOf Headline.step call obs := by + refine ⟨incCall, { expectedAt [] 1#256 with storage := slotValue [] }, incCall_valid, ?_⟩ + intro h + let pre : SolidCore.Spec.State := ⟨slotValue [], SolidCore.Spec.Ghost.zero, 0⟩ + have hne : Headline.spec.spec.specs ≠ [] := by + simp [Headline.spec, SolidCore.Spec.Export.Counter.Counter] + have hfs := List.head_mem hne + have hpre : SolidCore.Spec.Pre Headline.spec (Headline.spec.spec.specs.head hne) + (Headline.ctxOf incCall) pre incCall [1] := by + refine ⟨⟨?_, ?_, ?_⟩, rfl, by simp [pre, Headline.ctxOf], ?_, ?_⟩ + · have := size_callOf 1#256 + simp only [incCall] at this ⊢ + omega + · change SolidCore.Spec.selectorOf + ({ calldata := (callOf incSelector [1#256]).calldata, callvalue := 0, storage := [] } : Call) = _ + have := spec_selectorOf_append incSelector (by decide) (wordsBytes [1#256]) 0 [] + rw [← calldata_inc] at this + rw [this] + simp [Headline.spec, SolidCore.Spec.Export.Counter.Counter, incSelector] + · show SolidCore.Spec.decodeWords _ (SolidCore.Spec.words + (((callOf incSelector [1#256]).calldata.data.toList.map (·.toNat)).drop 4)) = _ + rw [words_inc] + simp [Headline.spec, SolidCore.Spec.Export.Counter.Counter, SolidCore.Spec.decodeWords, + SolidCore.Spec.Ty.ofWord, bind, pure] + · simp [SolidCore.Spec.Bundle.satAll, Headline.spec, SolidCore.Spec.Export.Counter.Counter] + · simp [SolidCore.Spec.Bundle.satAll, Headline.spec, SolidCore.Spec.Export.Counter.Counter] + have hpost := h _ hfs [1] pre hpre + have hok : (expectedAt [] 1#256).success = true := by simp [expectedAt, slotValue] + obtain ⟨rets, -, hens, -⟩ := hpost.1 hok + have := hens _ (List.mem_singleton_self _) + simp [SolidCore.Spec.Bundle.sat, Headline.spec, SolidCore.Spec.Export.Counter.Counter, + SolidCore.Spec.eval, SolidCore.Spec.slotOf, SolidCore.Spec.mkEnv, SolidCore.Spec.Env.cur, + SolidCore.Spec.BinOp.apply, SolidCore.Spec.Ty.ofBits, SolidCore.Spec.toWord, pre, + slotValue] at this + +/-- **The allowed statuses are not vacuous**: `inc(1)` with no value reverting with empty data is +not allowed. -/ +theorem allowed_rejects : ∃ call obs, cspec.Calls call ∧ obs.success = false ∧ ¬ allowed call obs := by + refine ⟨incCall, { expectedAt [] 1#256 with success := false, output := [] }, + incCall_valid, rfl, ?_⟩ + intro h + rcases h with h | h | ⟨h, -⟩ + · cases h + · exact h rfl + · have := congrArg List.length h + simp only [SolidCore.Verify.panic, List.length_append, List.length_map, length_word, List.length_nil] at this + omega + +/-- Both non-vacuity witnesses, as the published statement asks for them. -/ +theorem nonvacuous : (∃ call obs, cspec.Calls call ∧ + ¬ Shapes.bundlePost Headline.spec Headline.ctxOf Headline.step call obs) ∧ + (∃ call obs, cspec.Calls call ∧ obs.success = false ∧ ¬ allowed call obs) := + ⟨post_rejects, allowed_rejects⟩ + +/-- info: 'SolidCore.Refinement.Solar.Counter.ShapeExport.published' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms published + +/-- info: 'SolidCore.Refinement.Solar.Counter.ShapeExport.nonvacuous' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms nonvacuous + +end SolidCore.Refinement.Solar.Counter.ShapeExport diff --git a/Contracts/Counter/ShapeNeg.lean b/Contracts/Counter/ShapeNeg.lean new file mode 100644 index 00000000..ec258aef --- /dev/null +++ b/Contracts/Counter/ShapeNeg.lean @@ -0,0 +1,84 @@ +import Contracts.Counter.Shape + +/-! +# Counter's negative controls + +Each mutant fails to reach any status by the kernel's evaluation or by a mismatch, never by a +timeout: + +* bytecode mutants (`checkC` rejects each, and the published binding to the exported hex fails + for each): `ADD` turned into `SUB` (byte 42), the overflow branch's jump target moved to + `get`'s block (byte 47), the `SSTORE` dropped for a `POP` (byte 50), `STOP` turned into + `SELFDESTRUCT`, an opcode outside the supported set (byte 51); +* the wrong postcondition `x == old(x) + d + 1` is not met by SolidCore's `Counter` + (`wrong_spec_not_meets`, on `inc(1)` from the empty storage); +* a gas bound of `2 ^ 64` or more is no bound: `Shapes.Certified` with it is refuted outright + (`not_certified_unbounded`). +-/ + +namespace SolidCore.Refinement.Solar.Counter.ShapeNeg + +open SolidCore.Refinement SolidCore.Refinement.Final SolidCore.Refinement.Abi +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleCut +open SolidCore.Refinement.Solar.Counter.Shape SolidCore.Refinement.Solar.Counter.ShapeSpec SolidCore.Refinement.Solar.Counter.Final +open SolidCore.Refinement.Solar.CounterRun (cert maxs) +open SolidCore.Refinement.Evm.Wide EthLib.Base + +/-- The exported bytecode with byte `i` replaced by `b`. -/ +def mutant (i b : Nat) : ByteArray := + ⟨((SolarTV.Export.Counter.bytecode.set i b).map UInt8.ofNat).toArray⟩ + +set_option maxRecDepth 100000 + +theorem add_to_sub : checkC SolarTV.Export.Counter.evm5 (mutant 42 0x03) cert maxs = false := by + decide +kernel + +theorem jump_moved : checkC SolarTV.Export.Counter.evm5 (mutant 47 0x38) cert maxs = false := by + decide +kernel + +theorem sstore_dropped : checkC SolarTV.Export.Counter.evm5 (mutant 50 0x50) cert maxs = false := by + decide +kernel + +theorem unsupported_opcode : + checkC SolarTV.Export.Counter.evm5 (mutant 51 0xff) cert maxs = false := by + decide +kernel + +/-- The binding of the published statement fails for every mutant. -/ +theorem binding_fails : + (([42, 47, 50, 51].zip [0x03, 0x38, 0x50, 0xff]).all fun ib => + hexOf ((mutant ib.1 ib.2).data.toList.map (·.toNat)) != SolarTV.Export.Counter.Manifest.bytecodeHex) + = true := by + decide +kernel + +/-- `inc(d)` with the postcondition `x == old(x) + d + 1`. -/ +def wrongInc : FnSpec Nat := { incSpec with ensures := fun args x x' out => x' = x + args.headD 0 + 1 ∧ out = [] } + +def wrongSpec : ContractSpec Nat := { cspec with fns := [wrongInc, getSpec] } + +theorem wrong_spec_not_meets {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : contract? = .ok c) : + ¬Shapes.Meets (solidCore fuel) c cspec.Calls (Shapes.specPost wrongSpec) := by + have hcall : cspec.Calls (incSpec.call [1] 0 []) := + ⟨incSpec, by simp [cspec, SolidCore.Refinement.Solar.Counter.Final.spec], [1], .cons (by decide) .nil, + 0, by decide, [], rfl⟩ + refine Shapes.not_meets_of hcall (source_run_every hc _ (calls_every hcall)) ?_ + intro h + have := h wrongInc (by simp [wrongSpec]) [1] (.cons (by decide) .nil) 0 (by decide) [] rfl trivial + trivial + rw [inc_call 1 0 (by decide)] at this + have hcall' : ({ callOf incSelector [BitVec.ofNat 256 1] with callvalue := 0, storage := [] } : Call) = + { callOf incSelector [BitVec.ofNat 256 1] with storage := [] } := rfl + rw [hcall', expectedEvery_inc] at this + have h1 := (this.1 (by decide)).1.1 + revert h1 + decide + +/-- The strongest status needs a gas bound below `2 ^ 64`: an unbounded claim is refuted. -/ +theorem not_certified_unbounded {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {A P : Call → Observable → Prop} : + ¬Shapes.Certified (solidCore fuel) c CounterRun.code cspec.Calls A P (fun _ => 2 ^ 64) := by + intro h + obtain ⟨call, hc⟩ := h.inhabited + exact Shapes.not_resources_of_bound hc (le_refl _) h.resources + +end SolidCore.Refinement.Solar.Counter.ShapeNeg diff --git a/Contracts/Counter/ShapeSpec.lean b/Contracts/Counter/ShapeSpec.lean new file mode 100644 index 00000000..ef33ec6e --- /dev/null +++ b/Contracts/Counter/ShapeSpec.lean @@ -0,0 +1,31 @@ +import Contracts.Counter.Final +import Verify.Abi + +/-! +# Counter's declared valid calls, allowed statuses and specification + +The inputs the certify driver names in the published statement of `Certified/counter` +(`Certified/counter/shape.json`): reviewed specification, not proof. The valid calls are +`cspec.Calls`; the postcondition is `Shapes.specPost cspec`; the allowed statuses are +`allowed`; the gas bound is `gasBound`. +-/ + +namespace SolidCore.Refinement.Solar.Counter.ShapeSpec + +open SolidCore.Refinement SolidCore.Refinement.Final SolidCore.Refinement.Evm.Wide +open SolidCore.Refinement.Solar.Counter +open EthLib.Base + +/-- The declared specification (solar-verify's, as `Final.spec`). -/ +abbrev cspec : ContractSpec Nat := SolidCore.Refinement.Solar.Counter.Final.spec + +/-- The statuses the specification allows. -/ +def allowed (call : Call) (obs : Observable) : Prop := + obs.success = true ∨ call.callvalue ≠ 0 ∨ + (obs.output = SolidCore.Verify.panic 0x11 ∧ ∃ d : U256, call.calldata = (callOf incSelector [d]).calldata ∧ + 2 ^ 256 ≤ slotValue call.storage 0 + d.toNat) + +/-- The gas bound: from this gas on every valid call ends with the source's result. -/ +def gasBound : Call → Nat := fun _ => 1281806 + +end SolidCore.Refinement.Solar.Counter.ShapeSpec diff --git a/Contracts/Counter/Spec/Export.lean b/Contracts/Counter/Spec/Export.lean new file mode 100644 index 00000000..7d42da6c --- /dev/null +++ b/Contracts/Counter/Spec/Export.lean @@ -0,0 +1,48 @@ +import Verify.Spec.Contract + +/-! +Specs of `scripts/verify/CounterMilestone.sol`, exported by solar-verify 0.3.0 with `--emit-lean-spec`. +Generated: do not edit. +-/ + +namespace SolidCore.Spec.Export.Counter + +open SolidCore.Spec + +/-- What the specs were exported from and are about. -/ +def manifest : Manifest := + { source := "scripts/verify/CounterMilestone.sol", + sourceSha256 := "6ed83fe1a6c41fb109c6a880ed372b37ca1d895b9bde4bb5f202461289706da9", + compiler := "0.8.38+commit.1134e61f.solar.0.3.0-dev", + options := [], + bytecodeSha256 := "daed21b0c790bb2c08bcf999c9ebc6fea950c213ea0a799418552aa14c18f6ec" } + +/-- The specs of `Counter`. -/ +def Counter : Bundle where + fuel := 0 + spec := + { name := "Counter", + fns := [ + ], + invariants := [ + ], + ghosts := [], + specs := [ + { name := "Counter.inc", + selector := 0x812600df, + params := [(.uint 256)], + rets := [], + payable := false, + requires := [], + ensures := [ + (.bin .eq (.load (.slot 0) (.lit 0) 32 (.uint 256)) (.bin .add (.old (.load (.slot 0) (.lit 0) 32 (.uint 256))) (.arg 0)))], + succeedsIf := [] }] } + +/-- Every spec function call resolves and nests within the fuel. -/ +theorem Counter_wf : Counter.WF = true := by decide +kernel + +/-- Trusted-base items these specs' proofs rely on beyond the verdict +(`SolidCore.Spec.Assumptions`). -/ +def trusted : List String := [] + +end SolidCore.Spec.Export.Counter diff --git a/Contracts/Counter/Spec/ExportWrong.lean b/Contracts/Counter/Spec/ExportWrong.lean new file mode 100644 index 00000000..0988b34e --- /dev/null +++ b/Contracts/Counter/Spec/ExportWrong.lean @@ -0,0 +1,48 @@ +import Verify.Spec.Contract + +/-! +Specs of `scripts/verify/mutant/CounterSpecMut.sol`, exported by solar-verify 0.3.0 with `--emit-lean-spec`. +Generated: do not edit. +-/ + +namespace SolidCore.Spec.Export.CounterSpecMut + +open SolidCore.Spec + +/-- What the specs were exported from and are about. -/ +def manifest : Manifest := + { source := "scripts/verify/mutant/CounterSpecMut.sol", + sourceSha256 := "afaec6975bea758e12835d06dafce1c218409d260471a7a039df235b1e91b224", + compiler := "0.8.38+commit.1134e61f.solar.0.3.0-dev", + options := [], + bytecodeSha256 := "daed21b0c790bb2c08bcf999c9ebc6fea950c213ea0a799418552aa14c18f6ec" } + +/-- The specs of `Counter`. -/ +def Counter : Bundle where + fuel := 0 + spec := + { name := "Counter", + fns := [ + ], + invariants := [ + ], + ghosts := [], + specs := [ + { name := "Counter.inc", + selector := 0x812600df, + params := [(.uint 256)], + rets := [], + payable := false, + requires := [], + ensures := [ + (.bin .eq (.load (.slot 0) (.lit 0) 32 (.uint 256)) (.bin .add (.bin .add (.old (.load (.slot 0) (.lit 0) 32 (.uint 256))) (.arg 0)) (.lit 1)))], + succeedsIf := [] }] } + +/-- Every spec function call resolves and nests within the fuel. -/ +theorem Counter_wf : Counter.WF = true := by decide +kernel + +/-- Trusted-base items these specs' proofs rely on beyond the verdict +(`SolidCore.Spec.Assumptions`). -/ +def trusted : List String := [] + +end SolidCore.Spec.Export.CounterSpecMut diff --git a/Contracts/Counter/SpecTree.lean b/Contracts/Counter/SpecTree.lean new file mode 100644 index 00000000..fd66d0df --- /dev/null +++ b/Contracts/Counter/SpecTree.lean @@ -0,0 +1,101 @@ +import Verify.Spec.Tree +import Contracts.Counter.VC.Inc +import Contracts.Counter.Spec.Export +import Contracts.Counter.Spec.ExportWrong +import Contracts.Counter.EndToEnd + +/-! +# Counter: solar-verify's exported spec of `inc` from its erased tree, generically + +The instance of `SolidCore.Spec.holdsFn_of_tree` for `Counter.inc`: the only per-function proof +is `inc_meets`, by `tree_meets` over the exported spec (`Export.Counter.Counter`) and the +generic stage's tree (`incTree`, `incShape_eq`), with no solver verdict and no binding to +solar-verify's encoding. `wrong_not_meets` is the negative: the spec mutant `x == old(x) + d + 1` +does not hold of the tree, by the call `inc(0)` from the empty storage. +-/ + +namespace SolidCore.Spec.TreeDemo.Counter + +open SolidCore.Spec SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Verify.VC.Counter + +/-- The exported spec. -/ +abbrev spec : Bundle := SolidCore.Spec.Export.Counter.Counter + +/-- `inc`'s spec. -/ +def incSpec : FnSpec := spec.spec.specs.head (by simp [spec, SolidCore.Spec.Export.Counter.Counter]) + +/-- The call context of the stage's calls (no value), as SolidCore's runs see it. -/ +def ctx : Ctx := { sender := 0x2000, value := 0, timestamp := 1, self := 0x1000 } + +/-- The call context of every call: `ctx` with the call's value. -/ +def ctxOf (call : SolarTV.Call) : Ctx := { ctx with value := call.callvalue } + +/-- **`inc`'s spec holds of its erased tree.** -/ +theorem inc_meets : TreeMeets spec incSpec ctx 1 incTree := by + tree_meets [incTree, incSpec, spec, SolidCore.Spec.Export.Counter.Counter] + +/-- **`inc`'s spec holds of SolidCore's checked `Counter`** on the stage's calls of `inc`. -/ +theorem inc_holds {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) + (step : GhostStep) : + HoldsFn (solidCore fuel) c (SolidCore.Verify.VC.stageScope fnInc []) spec ctxOf step incSpec := by + have hshape := incShape_eq + simp only [incShape?, hc, Option.some.injEq, Prod.mk.injEq] at hshape + obtain ⟨hdep, hmap⟩ := hshape + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + simp only [Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + exact holdsFn_of_tree (fn := fnInc) hdd (by decide) hf hlen hT + (fun call h => by simp [ctxOf, ctx, h]) inc_meets + +/-- The mutant's spec of `inc`. -/ +def mutSpec : FnSpec := + SolidCore.Spec.Export.CounterSpecMut.Counter.spec.specs.head + (by simp [SolidCore.Spec.Export.CounterSpecMut.Counter]) + +/-- **The spec mutant does not hold of the tree**: `inc(0)` from the empty storage succeeds +with slot 0 still 0, and the mutant asks for 1. -/ +theorem wrong_not_meets : ¬ TreeMeets SolidCore.Spec.Export.CounterSpecMut.Counter mutSpec ctx 1 incTree := by + intro h + have := (h [0] (fun _ => 0) [0] ⟨fun _ => 0, Ghost.zero, 0⟩ Ghost.zero rfl (by simp) (by simp) + (by simp [mutSpec, SolidCore.Spec.Export.CounterSpecMut.Counter, decodeWords, Ty.ofWord]) + rfl (by simp [ctx]) (by simp [Bundle.satAll, mutSpec, SolidCore.Spec.Export.CounterSpecMut.Counter]) + (by simp [Bundle.satAll, SolidCore.Spec.Export.CounterSpecMut.Counter])).1 + simp [incTree, Tree.eval, WExpr.eval, BinOp.eval, Generic.wordSize, Res.obs, Writes.store, + Bundle.satAll, Bundle.sat, eval, slotOf, mkEnv, Env.cur, BinOp.apply, Ty.ofBits, toWord, + decodeWords, words, mutSpec, SolidCore.Spec.Export.CounterSpecMut.Counter] at this + +/-- info: 'SolidCore.Spec.TreeDemo.Counter.inc_holds' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms inc_holds + +/-- info: 'SolidCore.Spec.TreeDemo.Counter.wrong_not_meets' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms wrong_not_meets + +end SolidCore.Spec.TreeDemo.Counter + +/-! ## The one theorem: the exported spec of `inc` holds of solar's bytecode -/ + +namespace SolidCore.Refinement.Solar.Counter.SpecTree + +open SolidCore.Refinement SolidCore.Refinement.Final SolidCore.Spec + +/-- **solar-verify's exported spec of `inc` holds of solar's runtime bytecode** under EthLib, on +every call of `inc(uint256)` with any argument word, no value and any storage: the spec of the +erased tree (`inc_meets`, by evaluation), SolidCore's run of the tree (`holdsFn_of_tree`) and +the certified agreement of SolidCore's counter with the bytecode (`Verdict.agree`), with no +hypothesis and no solver verdict. -/ +theorem inc_spec_bytecode (step : GhostStep) : + ∃ c, contract? = .ok c ∧ + HoldsFn ethLib code (SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Counter.fnInc []) + SolidCore.Spec.TreeDemo.Counter.spec SolidCore.Spec.TreeDemo.Counter.ctxOf step + SolidCore.Spec.TreeDemo.Counter.incSpec := by + obtain ⟨c, hc⟩ := contract_ok + refine ⟨c, hc, (SolidCore.Spec.TreeDemo.Counter.inc_holds (by exact hc) step).of_stage ?_⟩ + exact fun call h obs hrun => (Verdict.agree hc).stage call (EndToEnd.inc_in_scope h) obs hrun + +/-- info: 'SolidCore.Refinement.Solar.Counter.SpecTree.inc_spec_bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms inc_spec_bytecode + +end SolidCore.Refinement.Solar.Counter.SpecTree diff --git a/Contracts/Counter/VC/Bind.lean b/Contracts/Counter/VC/Bind.lean new file mode 100644 index 00000000..16f15956 --- /dev/null +++ b/Contracts/Counter/VC/Bind.lean @@ -0,0 +1,17 @@ +import Contracts.Counter.VC.Export +import Contracts.Counter.VC.ExportMilestone + +/-! +# The exported scripts are solar-verify's transcripts + +Each exported `script` prints back to its `transcript`, the bytes solar-verify wrote with +`--dump-smt` in the same run. The check runs Lean's evaluator: the kernel's evaluation of the +printer on a transcript of 20 KB, with its 78-digit numerals, does not fit in this build's memory. +-/ + +namespace SolidCore.Verify.VC + +#guard printScript Export.Counter.script == Export.Counter.transcript +#guard printScript Export.CounterMilestone.script == Export.CounterMilestone.transcript + +end SolidCore.Verify.VC diff --git a/Contracts/Counter/VC/Discharged.lean b/Contracts/Counter/VC/Discharged.lean new file mode 100644 index 00000000..01d64cf1 --- /dev/null +++ b/Contracts/Counter/VC/Discharged.lean @@ -0,0 +1,60 @@ +import Contracts.Counter.VC.Discharged.Part0 +import Contracts.Counter.VC.Discharged.Part1 +import Contracts.Counter.VC.Discharged.Part2 +import Contracts.Counter.VC.Discharged.Part3 +import Contracts.Counter.VC.Discharged.Part4 +import Contracts.Counter.VC.Mutant.SpecMut +import Contracts.Counter.VC.Mutant.SrcMut + +/-! +# `SolidCore.Verify.VC.Export.Counter.script`, discharged by the kernel + +Generated by scripts/verify/gen-discharged.py: one kernel evaluation of `dischargeAt` per +obligation (the Part modules, Verify/VC/Discharge.lean), and the script's verdict `Valid` from +them, with no solver. Each rejected mutant script fails by a mismatch at the obligation named. +-/ + +namespace SolidCore.Verify.VC.Counter.Discharged + +open SolidCore.Verify.VC + +set_option maxRecDepth 100000 + +theorem obligation_count : (obligations SolidCore.Verify.VC.Export.Counter.script).length = 17 := by decide +kernel + +/-- Every obligation of the script has no model. -/ +theorem script_valid : Valid SolidCore.Verify.VC.Export.Counter.script := + dischargeScript_of_each _ fun i hi => + match i, obligation_count ▸ hi with + | 0, _ => ob_0 + | 1, _ => ob_1 + | 2, _ => ob_2 + | 3, _ => ob_3 + | 4, _ => ob_4 + | 5, _ => ob_5 + | 6, _ => ob_6 + | 7, _ => ob_7 + | 8, _ => ob_8 + | 9, _ => ob_9 + | 10, _ => ob_10 + | 11, _ => ob_11 + | 12, _ => ob_12 + | 13, _ => ob_13 + | 14, _ => ob_14 + | 15, _ => ob_15 + | 16, _ => ob_16 + | _ + 17, h => absurd h (by omega) + +/-- The mutant script is rejected at obligation 1. -/ +theorem reject_0 : dischargeScript SolidCore.Verify.VC.Export.Mutant.CounterSpecMut.script = false := + dischargeScript_false_of (i := 1) (by decide +kernel) (by decide +kernel) + +/-- The mutant script is rejected at obligation 1. -/ +theorem reject_1 : dischargeScript SolidCore.Verify.VC.Export.Mutant.CounterSrcMut.script = false := + dischargeScript_false_of (i := 1) (by decide +kernel) (by decide +kernel) + +/-- info: 'SolidCore.Verify.VC.Counter.Discharged.script_valid' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms script_valid + +end SolidCore.Verify.VC.Counter.Discharged diff --git a/Contracts/Counter/VC/Discharged/Part0.lean b/Contracts/Counter/VC/Discharged/Part0.lean new file mode 100644 index 00000000..84e0f464 --- /dev/null +++ b/Contracts/Counter/VC/Discharged/Part0.lean @@ -0,0 +1,21 @@ +import Verify.VC.Discharge +import Contracts.Counter.VC.Export + +/-! Obligations 0 to 3 of `SolidCore.Verify.VC.Export.Counter.script`, each discharged by the +kernel (generated by scripts/verify/gen-discharged.py). -/ + +namespace SolidCore.Verify.VC.Counter.Discharged + +open SolidCore.Verify.VC + +set_option maxRecDepth 100000 + +theorem ob_0 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 0 = true := by decide +kernel + +theorem ob_1 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 1 = true := by decide +kernel + +theorem ob_2 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 2 = true := by decide +kernel + +theorem ob_3 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 3 = true := by decide +kernel + +end SolidCore.Verify.VC.Counter.Discharged diff --git a/Contracts/Counter/VC/Discharged/Part1.lean b/Contracts/Counter/VC/Discharged/Part1.lean new file mode 100644 index 00000000..95ec9807 --- /dev/null +++ b/Contracts/Counter/VC/Discharged/Part1.lean @@ -0,0 +1,21 @@ +import Verify.VC.Discharge +import Contracts.Counter.VC.Export + +/-! Obligations 4 to 7 of `SolidCore.Verify.VC.Export.Counter.script`, each discharged by the +kernel (generated by scripts/verify/gen-discharged.py). -/ + +namespace SolidCore.Verify.VC.Counter.Discharged + +open SolidCore.Verify.VC + +set_option maxRecDepth 100000 + +theorem ob_4 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 4 = true := by decide +kernel + +theorem ob_5 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 5 = true := by decide +kernel + +theorem ob_6 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 6 = true := by decide +kernel + +theorem ob_7 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 7 = true := by decide +kernel + +end SolidCore.Verify.VC.Counter.Discharged diff --git a/Contracts/Counter/VC/Discharged/Part2.lean b/Contracts/Counter/VC/Discharged/Part2.lean new file mode 100644 index 00000000..34bf53fc --- /dev/null +++ b/Contracts/Counter/VC/Discharged/Part2.lean @@ -0,0 +1,21 @@ +import Verify.VC.Discharge +import Contracts.Counter.VC.Export + +/-! Obligations 8 to 11 of `SolidCore.Verify.VC.Export.Counter.script`, each discharged by the +kernel (generated by scripts/verify/gen-discharged.py). -/ + +namespace SolidCore.Verify.VC.Counter.Discharged + +open SolidCore.Verify.VC + +set_option maxRecDepth 100000 + +theorem ob_8 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 8 = true := by decide +kernel + +theorem ob_9 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 9 = true := by decide +kernel + +theorem ob_10 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 10 = true := by decide +kernel + +theorem ob_11 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 11 = true := by decide +kernel + +end SolidCore.Verify.VC.Counter.Discharged diff --git a/Contracts/Counter/VC/Discharged/Part3.lean b/Contracts/Counter/VC/Discharged/Part3.lean new file mode 100644 index 00000000..1dba70db --- /dev/null +++ b/Contracts/Counter/VC/Discharged/Part3.lean @@ -0,0 +1,21 @@ +import Verify.VC.Discharge +import Contracts.Counter.VC.Export + +/-! Obligations 12 to 15 of `SolidCore.Verify.VC.Export.Counter.script`, each discharged by the +kernel (generated by scripts/verify/gen-discharged.py). -/ + +namespace SolidCore.Verify.VC.Counter.Discharged + +open SolidCore.Verify.VC + +set_option maxRecDepth 100000 + +theorem ob_12 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 12 = true := by decide +kernel + +theorem ob_13 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 13 = true := by decide +kernel + +theorem ob_14 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 14 = true := by decide +kernel + +theorem ob_15 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 15 = true := by decide +kernel + +end SolidCore.Verify.VC.Counter.Discharged diff --git a/Contracts/Counter/VC/Discharged/Part4.lean b/Contracts/Counter/VC/Discharged/Part4.lean new file mode 100644 index 00000000..7c671abf --- /dev/null +++ b/Contracts/Counter/VC/Discharged/Part4.lean @@ -0,0 +1,15 @@ +import Verify.VC.Discharge +import Contracts.Counter.VC.Export + +/-! Obligations 16 to 16 of `SolidCore.Verify.VC.Export.Counter.script`, each discharged by the +kernel (generated by scripts/verify/gen-discharged.py). -/ + +namespace SolidCore.Verify.VC.Counter.Discharged + +open SolidCore.Verify.VC + +set_option maxRecDepth 100000 + +theorem ob_16 : dischargeAt SolidCore.Verify.VC.Export.Counter.script 16 = true := by decide +kernel + +end SolidCore.Verify.VC.Counter.Discharged diff --git a/Contracts/Counter/VC/Export.lean b/Contracts/Counter/VC/Export.lean new file mode 100644 index 00000000..4c5aa64c --- /dev/null +++ b/Contracts/Counter/VC/Export.lean @@ -0,0 +1,331 @@ +-- Generated by solar-verify --dump-lean. Do not edit. + +import Verify.VC.Term + +namespace SolidCore.Verify.VC.Export.Counter + +open SolidCore.Verify.VC + +/-- The commands solar-verify sent the solver. -/ +def script : List Cmd := [ + .push, + .raw "; ===== Counter.constructor", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@17" .arr, + .elem "__balance@17" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@18")]), (.app "<=" [(.ivar "__code_epoch@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "_limit@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "_limit@19")]), (.app "<=" [(.ivar "_limit@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@20" .bool, + .assert (.app "=" [(.bvar "g@20"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@20"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@20"), + .assert (.app "not" [(.app "and" [(.app "=" [(.ivar "_limit@19"), (.ivar "_limit@19")]), (.app "=" [(.num 0), (.num 0)])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@20"), + .assert (.app "not" [(.app "<=" [(.num 0), (.ivar "_limit@19")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.increment", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "count@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "count@17")]), (.app "<=" [(.ivar "count@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "limit@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "limit@18")]), (.app "<=" [(.ivar "limit@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@19" .arr, + .elem "__balance@19" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@20")]), (.app "<=" [(.ivar "__code_epoch@20"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@21" .bool, + .assert (.app "=" [(.bvar "g@21"), (.app "and" [.tt, (.app "<=" [(.ivar "count@17"), (.ivar "limit@18")])])]), + .decl "g@22" .bool, + .assert (.app "=" [(.bvar "g@22"), (.app "and" [(.bvar "g@21"), (.app "<" [(.ivar "count@17"), (.ivar "limit@18")])])]), + .decl "g@23" .bool, + .assert (.app "=" [(.bvar "g@23"), (.app "and" [(.bvar "g@22"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "arith@24" .int, + .assert (.app "=" [(.ivar "arith@24"), (.app "+" [(.ivar "count@17"), (.num 1)])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [(.bvar "g@23"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@24")]), (.app "<=" [(.ivar "arith@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .push, + .assert (.bvar "g@25"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@25"), + .assert (.app "not" [(.app "=" [(.ivar "arith@24"), (.app "+" [(.ivar "count@17"), (.num 1)])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@25"), + .assert (.app "not" [(.app "<=" [(.ivar "arith@24"), (.ivar "limit@18")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.bump", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "count@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "count@17")]), (.app "<=" [(.ivar "count@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "limit@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "limit@18")]), (.app "<=" [(.ivar "limit@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@19" .arr, + .elem "__balance@19" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@20")]), (.app "<=" [(.ivar "__code_epoch@20"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "n@21" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "n@21")]), (.app "<=" [(.ivar "n@21"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@22" .bool, + .assert (.app "=" [(.bvar "g@22"), (.app "and" [.tt, (.app "<=" [(.ivar "count@17"), (.ivar "limit@18")])])]), + .decl "g@23" .bool, + .assert (.app "=" [(.bvar "g@23"), (.app "and" [(.bvar "g@22"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "arith@24" .int, + .assert (.app "=" [(.ivar "arith@24"), (.app "+" [(.ivar "count@17"), (.ivar "n@21")])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [(.bvar "g@23"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@24")]), (.app "<=" [(.ivar "arith@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "g@26" .bool, + .assert (.app "=" [(.bvar "g@26"), (.app "and" [(.bvar "g@25"), (.app "<=" [(.ivar "arith@24"), (.ivar "limit@18")])])]), + .push, + .assert (.bvar "g@26"), + .assert (.app "not" [(.app "<=" [(.num 0), (.ivar "n@21")])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@26"), + .assert (.app "not" [(.app "=" [(.ivar "count@17"), (.app "+" [(.ivar "count@17"), (.num 0)])])]), + .checkSat, + .pop, + .decl "count@27" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "count@27")]), (.app "<=" [(.ivar "count@27"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "i@28" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "i@28")]), (.app "<=" [(.ivar "i@28"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@29" .bool, + .assert (.app "=" [(.bvar "g@29"), (.app "and" [(.bvar "g@26"), (.app "<=" [(.ivar "i@28"), (.ivar "n@21")])])]), + .decl "g@30" .bool, + .assert (.app "=" [(.bvar "g@30"), (.app "and" [(.bvar "g@29"), (.app "=" [(.ivar "count@27"), (.app "+" [(.ivar "count@17"), (.ivar "i@28")])])])]), + .decl "g@31" .bool, + .assert (.app "=" [(.bvar "g@31"), (.app "and" [(.bvar "g@30"), (.app "<" [(.ivar "i@28"), (.ivar "n@21")])])]), + .decl "arith@32" .int, + .assert (.app "=" [(.ivar "arith@32"), (.app "+" [(.ivar "count@27"), (.num 1)])]), + .decl "g@33" .bool, + .assert (.app "=" [(.bvar "g@33"), (.app "and" [(.bvar "g@31"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@32")]), (.app "<=" [(.ivar "arith@32"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "arith@34" .int, + .assert (.app "=" [(.ivar "arith@34"), (.app "+" [(.ivar "i@28"), (.num 1)])]), + .decl "g@35" .bool, + .assert (.app "=" [(.bvar "g@35"), (.app "and" [(.bvar "g@33"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@34")]), (.app "<=" [(.ivar "arith@34"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .push, + .assert (.bvar "g@35"), + .assert (.app "not" [(.app "<=" [(.ivar "arith@34"), (.ivar "n@21")])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@35"), + .assert (.app "not" [(.app "=" [(.ivar "arith@32"), (.app "+" [(.ivar "count@17"), (.ivar "arith@34")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@35"), + .assert (.app "not" [(.app "and" [(.app "<=" [(.num 0), (.app "-" [(.ivar "n@21"), (.ivar "i@28")])]), (.app "<" [(.app "-" [(.ivar "n@21"), (.ivar "arith@34")]), (.app "-" [(.ivar "n@21"), (.ivar "i@28")])])])]), + .checkSat, + .pop, + .decl "g@36" .bool, + .assert (.app "=" [(.bvar "g@36"), (.app "and" [(.bvar "g@30"), (.app "not" [(.app "<" [(.ivar "i@28"), (.ivar "n@21")])])])]), + .push, + .assert (.bvar "g@36"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@36"), + .assert (.app "not" [(.app "=" [(.ivar "count@27"), (.app "+" [(.ivar "count@17"), (.ivar "n@21")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@36"), + .assert (.app "not" [(.app "<=" [(.ivar "count@27"), (.ivar "limit@18")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.max", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "count@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "count@17")]), (.app "<=" [(.ivar "count@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "limit@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "limit@18")]), (.app "<=" [(.ivar "limit@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@19" .arr, + .elem "__balance@19" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@20")]), (.app "<=" [(.ivar "__code_epoch@20"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "a@21" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "a@21")]), (.app "<=" [(.ivar "a@21"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "b@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "b@22")]), (.app "<=" [(.ivar "b@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@23" .bool, + .assert (.app "=" [(.bvar "g@23"), (.app "and" [.tt, (.app "<=" [(.ivar "count@17"), (.ivar "limit@18")])])]), + .decl "g@24" .bool, + .assert (.app "=" [(.bvar "g@24"), (.app "and" [(.bvar "g@23"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [(.bvar "g@24"), (.app ">=" [(.ivar "a@21"), (.ivar "b@22")])])]), + .decl "g@26" .bool, + .assert (.app "=" [(.bvar "g@26"), (.app "and" [(.bvar "g@24"), (.app "not" [(.app ">=" [(.ivar "a@21"), (.ivar "b@22")])])])]), + .decl "g@27" .bool, + .assert (.app "=" [(.bvar "g@27"), (.app "or" [(.bvar "g@25"), (.bvar "g@26")])]), + .decl "__ret0@28" .int, + .assert (.app "=" [(.ivar "__ret0@28"), (.app "ite" [(.bvar "g@25"), (.ivar "a@21"), (.ivar "b@22")])]), + .push, + .assert (.bvar "g@27"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@27"), + .assert (.app "not" [(.app "=" [(.ivar "__ret0@28"), (.app "ite" [(.app ">=" [(.ivar "a@21"), (.ivar "b@22")]), (.ivar "a@21"), (.ivar "b@22")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@27"), + .assert (.app "not" [(.app "and" [(.app ">=" [(.ivar "__ret0@28"), (.ivar "a@21")]), (.app ">=" [(.ivar "__ret0@28"), (.ivar "b@22")])])]), + .checkSat, + .pop, + .pop +] + +/-- The transcript, as solar-verify wrote it. -/ +def transcript : String := "(push 1)\n; ===== Counter.constructor\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@17| (Array Int Int))\n;@elem |__balance@17| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@18| Int)\n(assert (and (<= 0 |__code_epoch@18|) (<= |__code_epoch@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |_limit@19| Int)\n(assert (and (<= 0 |_limit@19|) (<= |_limit@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@20| Bool)\n(assert (= |g@20| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@20|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@20|)\n(assert (not (and (= |_limit@19| |_limit@19|) (= 0 0))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@20|)\n(assert (not (<= 0 |_limit@19|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.increment\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |count@17| Int)\n(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |limit@18| Int)\n(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@19| (Array Int Int))\n;@elem |__balance@19| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@20| Int)\n(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@21| Bool)\n(assert (= |g@21| (and true (<= |count@17| |limit@18|))))\n(declare-const |g@22| Bool)\n(assert (= |g@22| (and |g@21| (< |count@17| |limit@18|))))\n(declare-const |g@23| Bool)\n(assert (= |g@23| (and |g@22| (= |msg.value@3| 0))))\n(declare-const |arith@24| Int)\n(assert (= |arith@24| (+ |count@17| 1)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(push 1)\n(assert |g@25|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@25|)\n(assert (not (= |arith@24| (+ |count@17| 1))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@25|)\n(assert (not (<= |arith@24| |limit@18|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.bump\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |count@17| Int)\n(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |limit@18| Int)\n(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@19| (Array Int Int))\n;@elem |__balance@19| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@20| Int)\n(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |n@21| Int)\n(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@22| Bool)\n(assert (= |g@22| (and true (<= |count@17| |limit@18|))))\n(declare-const |g@23| Bool)\n(assert (= |g@23| (and |g@22| (= |msg.value@3| 0))))\n(declare-const |arith@24| Int)\n(assert (= |arith@24| (+ |count@17| |n@21|)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |g@26| Bool)\n(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|))))\n(push 1)\n(assert |g@26|)\n(assert (not (<= 0 |n@21|)))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@26|)\n(assert (not (= |count@17| (+ |count@17| 0))))\n(check-sat)\n(pop 1)\n(declare-const |count@27| Int)\n(assert (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |i@28| Int)\n(assert (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@29| Bool)\n(assert (= |g@29| (and |g@26| (<= |i@28| |n@21|))))\n(declare-const |g@30| Bool)\n(assert (= |g@30| (and |g@29| (= |count@27| (+ |count@17| |i@28|)))))\n(declare-const |g@31| Bool)\n(assert (= |g@31| (and |g@30| (< |i@28| |n@21|))))\n(declare-const |arith@32| Int)\n(assert (= |arith@32| (+ |count@27| 1)))\n(declare-const |g@33| Bool)\n(assert (= |g@33| (and |g@31| (and (<= 0 |arith@32|) (<= |arith@32| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |arith@34| Int)\n(assert (= |arith@34| (+ |i@28| 1)))\n(declare-const |g@35| Bool)\n(assert (= |g@35| (and |g@33| (and (<= 0 |arith@34|) (<= |arith@34| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(push 1)\n(assert |g@35|)\n(assert (not (<= |arith@34| |n@21|)))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@35|)\n(assert (not (= |arith@32| (+ |count@17| |arith@34|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@35|)\n(assert (not (and (<= 0 (- |n@21| |i@28|)) (< (- |n@21| |arith@34|) (- |n@21| |i@28|)))))\n(check-sat)\n(pop 1)\n(declare-const |g@36| Bool)\n(assert (= |g@36| (and |g@30| (not (< |i@28| |n@21|)))))\n(push 1)\n(assert |g@36|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@36|)\n(assert (not (= |count@27| (+ |count@17| |n@21|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@36|)\n(assert (not (<= |count@27| |limit@18|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.max\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |count@17| Int)\n(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |limit@18| Int)\n(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@19| (Array Int Int))\n;@elem |__balance@19| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@20| Int)\n(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |a@21| Int)\n(assert (and (<= 0 |a@21|) (<= |a@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |b@22| Int)\n(assert (and (<= 0 |b@22|) (<= |b@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@23| Bool)\n(assert (= |g@23| (and true (<= |count@17| |limit@18|))))\n(declare-const |g@24| Bool)\n(assert (= |g@24| (and |g@23| (= |msg.value@3| 0))))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and |g@24| (>= |a@21| |b@22|))))\n(declare-const |g@26| Bool)\n(assert (= |g@26| (and |g@24| (not (>= |a@21| |b@22|)))))\n(declare-const |g@27| Bool)\n(assert (= |g@27| (or |g@25| |g@26|)))\n(declare-const |__ret0@28| Int)\n(assert (= |__ret0@28| (ite |g@25| |a@21| |b@22|)))\n(push 1)\n(assert |g@27|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@27|)\n(assert (not (= |__ret0@28| (ite (>= |a@21| |b@22|) |a@21| |b@22|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@27|)\n(assert (not (and (>= |__ret0@28| |a@21|) (>= |__ret0@28| |b@22|))))\n(check-sat)\n(pop 1)\n(pop 1)\n" + +end SolidCore.Verify.VC.Export.Counter diff --git a/Contracts/Counter/VC/ExportMilestone.lean b/Contracts/Counter/VC/ExportMilestone.lean new file mode 100644 index 00000000..25bc07c5 --- /dev/null +++ b/Contracts/Counter/VC/ExportMilestone.lean @@ -0,0 +1,169 @@ +-- Generated by solar-verify --dump-lean. Do not edit. + +import Verify.VC.Term + +namespace SolidCore.Verify.VC.Export.CounterMilestone + +open SolidCore.Verify.VC + +/-- The commands solar-verify sent the solver. -/ +def script : List Cmd := [ + .push, + .raw "; ===== Counter.inc", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "x@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "x@17")]), (.app "<=" [(.ivar "x@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@18" .arr, + .elem "__balance@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@19")]), (.app "<=" [(.ivar "__code_epoch@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "d@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "d@20")]), (.app "<=" [(.ivar "d@20"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@21" .bool, + .assert (.app "=" [(.bvar "g@21"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "arith@22" .int, + .assert (.app "=" [(.ivar "arith@22"), (.app "+" [(.ivar "x@17"), (.ivar "d@20")])]), + .decl "g@23" .bool, + .assert (.app "=" [(.bvar "g@23"), (.app "and" [(.bvar "g@21"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@22")]), (.app "<=" [(.ivar "arith@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .push, + .assert (.bvar "g@23"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@23"), + .assert (.app "not" [(.app "=" [(.ivar "arith@22"), (.app "+" [(.ivar "x@17"), (.ivar "d@20")])])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.get", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "x@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "x@17")]), (.app "<=" [(.ivar "x@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@18" .arr, + .elem "__balance@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@19")]), (.app "<=" [(.ivar "__code_epoch@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@20" .bool, + .assert (.app "=" [(.bvar "g@20"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@20"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.constructor", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@17" .arr, + .elem "__balance@17" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@18")]), (.app "<=" [(.ivar "__code_epoch@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@19" .bool, + .assert (.app "=" [(.bvar "g@19"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .pop +] + +/-- The transcript, as solar-verify wrote it. -/ +def transcript : String := "(push 1)\n; ===== Counter.inc\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |x@17| Int)\n(assert (and (<= 0 |x@17|) (<= |x@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@18| (Array Int Int))\n;@elem |__balance@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@19| Int)\n(assert (and (<= 0 |__code_epoch@19|) (<= |__code_epoch@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |d@20| Int)\n(assert (and (<= 0 |d@20|) (<= |d@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@21| Bool)\n(assert (= |g@21| (and true (= |msg.value@3| 0))))\n(declare-const |arith@22| Int)\n(assert (= |arith@22| (+ |x@17| |d@20|)))\n(declare-const |g@23| Bool)\n(assert (= |g@23| (and |g@21| (and (<= 0 |arith@22|) (<= |arith@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(push 1)\n(assert |g@23|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@23|)\n(assert (not (= |arith@22| (+ |x@17| |d@20|))))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.get\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |x@17| Int)\n(assert (and (<= 0 |x@17|) (<= |x@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@18| (Array Int Int))\n;@elem |__balance@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@19| Int)\n(assert (and (<= 0 |__code_epoch@19|) (<= |__code_epoch@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@20| Bool)\n(assert (= |g@20| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@20|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.constructor\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@17| (Array Int Int))\n;@elem |__balance@17| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@18| Int)\n(assert (and (<= 0 |__code_epoch@18|) (<= |__code_epoch@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@19| Bool)\n(assert (= |g@19| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@19|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(pop 1)\n" + +end SolidCore.Verify.VC.Export.CounterMilestone diff --git a/Contracts/Counter/VC/Generic.lean b/Contracts/Counter/VC/Generic.lean new file mode 100644 index 00000000..83386594 --- /dev/null +++ b/Contracts/Counter/VC/Generic.lean @@ -0,0 +1,65 @@ +import Contracts.Counter.VC.Inc +import Verify.VC.Obligations + +/-! +# `Counter.inc` through the generic theorem + +`inc_triple` again, now as an instance of `triple_of_binds`: the only proof about `inc` is the +binding `inc_binds`, which speaks of the erased tree `incTree` and solar-verify's obligation alone +(no SolidCore run, no fuel, no ABI); `triple_of_binds` supplies the rest for every function the +generic source stage erases. The obligation `incHyps ⟹ incGoal` is the one `inc_check` finds in +solar-verify's script, and it is valid by solar-verify's own encoding (`inc_obs_valid`), so the +theorem takes no verdict. +-/ + +namespace SolidCore.Verify.VC.Counter + +open SolidCore.Verify SolidCore.Verify.VC SolidCore.Refinement SolidCore.Refinement.Abi +open SolidCore.Refinement.Generic SolidCore.Solidity + +/-- `inc`'s postcondition of its argument words, its storage and its observable. -/ +def incP (args : List Nat) (s : Storage) (o : SolarTV.Observable) : Prop := + let d := args.getD 0 0 + (o.success = true ↔ s 0 + d < 2 ^ 256) ∧ + (o.success = true → o.storage 0 = s 0 + d ∧ ∀ k, k % 2 ^ 256 ≠ 0 → o.storage k = s k) + +/-- solar-verify's obligation for `inc`'s clause holds everywhere. -/ +theorem inc_obs_valid : ObsValid [(incHyps, incGoal)] := by + intro o ho σ _ + simp only [List.mem_singleton] at ho + subst ho + simp [incGoal, incEff, Ob.add, Ob.eq, Ob.x, Ob.d, Tm.Holds, Tm.eval, Tm.evalList, applyOp, Value.select, Value.store, + Value.toProp, Value.eq] + +/-- The binding of `inc`'s erased tree to solar-verify's obligation. -/ +theorem inc_binds : + Binds fnInc incTree [(incHyps, incGoal)] (fun args s => incEnv (args.getD 0 0) s) incP := by + intro args s hl hargs hs _ + obtain ⟨d, rfl⟩ : ∃ d, args = [d] := by + match args, hl with + | [d], _ => exact ⟨d, rfl⟩ + have hd : d < 2 ^ 256 := hargs d (List.mem_singleton_self d) + obtain ⟨hiff, hok⟩ := inc_binding s hs d hd + have hguard := incHyps_iff d s hd (hs 0) + simp only [incP, Res.obs, List.getD_cons_zero] + refine ⟨hiff.trans hguard, fun hsucc => ?_⟩ + obtain ⟨h0, hk⟩ := hok hsucc + rw [incEff_eval] at h0 + exact ⟨by omega, hk⟩ + +/-- `inc_triple`, from the generic theorem and the binding. -/ +theorem inc_triple_of_binds {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Triple fuel c (stageScope fnInc []) (fun _ => True) incPost := by + have hshape := incShape_eq + simp only [incShape?, hc, Option.some.injEq, Prod.mk.injEq] at hshape + obtain ⟨hdep, hmap⟩ := hshape + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + simp only [Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + exact triple_of_binds (fn := fnInc) hdd (by decide) hf hlen hT inc_obs_valid inc_binds + +/-- info: 'SolidCore.Verify.VC.Counter.inc_triple_of_binds' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms inc_triple_of_binds + +end SolidCore.Verify.VC.Counter diff --git a/Contracts/Counter/VC/Get.lean b/Contracts/Counter/VC/Get.lean new file mode 100644 index 00000000..1c0dc58f --- /dev/null +++ b/Contracts/Counter/VC/Get.lean @@ -0,0 +1,79 @@ +import Contracts.Counter.VC.Inc + +/-! +# The certified counter milestone's `get` + +`get` carries no NatSpec clause, so solar-verify emits no obligation for it and there is nothing of +solar-verify's to bind: `get_triple` is a direct proof against SolidCore, with the shape of +`inc_triple` so that final composition consumes both the same way. + +* `getShape_eq` (kernel): `Counter` deploys with no storage and no logs, and the generic source stage + erases `get()` to `getTree`, one success leaf that returns slot 0's 32 bytes and writes nothing. +* `get_triple`: on the stage's scope (any storage, no value), `get` succeeds, returns slot 0 as a + big-endian word and leaves every slot unchanged. +-/ + +namespace SolidCore.Verify.VC.Counter + +open SolidCore.Verify SolidCore.Verify.VC SolidCore.Refinement SolidCore.Refinement.Abi +open SolidCore.Refinement.Generic SolidCore.Solidity SolidCore.Solidity.Source + +/-- `get()` as the stage's ABI sees it. -/ +def fnGet : Fn := ⟨getSel, []⟩ + +/-- The erasure of `get`: return slot 0's word, write nothing. -/ +def getTree : Tree := .halt true (wordOBytes (.init 0)) [] [] + +/-- Whether `Counter` deploys with no storage and no logs, and how SolidCore dispatches `get` and the +generic source stage erases it. -/ +def getShape? : Option (Bool × Option (Nat × Option Tree)) := + match contract? with + | .ok c => some (Wide.deployedAt fuel c [], + (c.core.findFunctionBySelector? getSel).map fun f => (f.params.length, eraseFn (envOf c.core) fuel f)) + | .error _ => none + +kernel_rfl getShape_eq getShape? (some (true, some (0, some getTree))) using selector_eq mkIdx_eq + +/-- The 32 bytes of the word `w`, big-endian. -/ +def wordBytes (w : Nat) : List Nat := (List.range 32).map fun i => w / 256 ^ (31 - i) % 256 + +/-- `get`'s postcondition: it succeeds, returns slot 0 as a big-endian word and changes no slot. -/ +def getPost (call : Call) (obs : SolarTV.Observable) : Prop := + let s := initStorage call + obs.success = true ∧ obs.output = wordBytes (s 0) ∧ ∀ k, obs.storage k = s k + +/-- `Counter.get` on the stage's scope: it succeeds, returns slot 0 and leaves the storage, through +`implementsTree`. -/ +theorem get_triple {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Triple fuel c (stageScope fnGet []) (fun _ => True) getPost := by + have hshape := getShape_eq + simp only [getShape?, hc, Option.some.injEq, Prod.mk.injEq] at hshape + obtain ⟨hdep, hmap⟩ := hshape + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + simp only [Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + have himpl := implements_tree (fn := fnGet) hdd (by decide) hf hlen hT rfl + apply triple_of_wp himpl + rintro _ ⟨σ, -, fn', hfn', args, hl, hargs, rfl⟩ - + simp only [List.mem_singleton] at hfn' + subst hfn' + obtain rfl : args = [] := List.eq_nil_of_length_eq_zero hl + have hw : argWords 0 ({ calldata := Abi.calldata fnGet.sel [], callvalue := 0, storage := σ } : Call) = + [] := argWords_calldata _ [] hargs 0 σ + rw [vc_eq, treeModel_run, show fnGet.params.length = 0 from rfl, hw] + set s := initStorage ({ calldata := Abi.calldata fnGet.sel [], callvalue := 0, storage := σ } : Call) + with hs_def + have hs : ∀ k, s k < 2 ^ 256 := fun k => Generic.slotValue_lt σ k + simp only [getPost, ← hs_def] + refine ⟨rfl, ?_, fun k => rfl⟩ + simp only [getTree, Tree.eval, resOutcome, observe, ite_true, wordOBytes, wordBytes, List.map_map] + congr 1 + funext i + have h0 := hs 0 + simp only [Function.comp_apply, OByte.eval, WExpr.eval, valOf, Generic.wordSize, Nat.mod_eq_of_lt h0] + +/-- info: 'SolidCore.Verify.VC.Counter.get_triple' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms get_triple + +end SolidCore.Verify.VC.Counter diff --git a/Contracts/Counter/VC/Inc.lean b/Contracts/Counter/VC/Inc.lean new file mode 100644 index 00000000..3cc33416 --- /dev/null +++ b/Contracts/Counter/VC/Inc.lean @@ -0,0 +1,280 @@ +import Verify.VC +import Verify.VC.KernelIdx +import Contracts.Counter.VC.ExportMilestone +import SolidCore.Refinement.Solar.Counter.Source +import SolidCore.Refinement.KernelRfl + +/-! +# solar-verify's `Counter.inc`, bound to the certified counter milestone + +The contract is the one the certified translation covers: SolidCore's checked `Counter` from +`scripts/refinement/counter/counter.sol` (`contract` below is +`SolidCore.Refinement.Solar.Counter.contract?`'s body, so a proof of either equation is one of the +other). solar-verify reads `scripts/verify/CounterMilestone.sol`, the same text with one NatSpec line, +`ensures x == old(x) + d` (`check`.sh checks that stripping the `///` lines gives counter.sol back). + +What is proved: +* `incShape_eq` (kernel): `Counter` deploys with no storage and no logs, and the generic source stage + erases `inc(uint256)` to `incTree`. +* `inc_check` (kernel): solar-verify's script has an obligation that `checkOb` normalizes to + `incHyps ⟹ incGoal`, written here by hand: its facts are the guard of `inc`'s success path + (no value, `x + d` in range) and its goal states solar-verify's encoding `incEff` of the new `x`. +* `inc_binding`: a call of `inc` on `d` from storage `s` succeeds exactly when `incHyps` hold at the + assignment `incEnv d s` it binds (`x` is slot 0, `d` the argument, `msg.value` 0), and then + writes slot 0 with the value of `incEff` there and nothing else. +* `inc_triple`: on the stage's scope (any storage, any argument word, no value), `inc` succeeds + exactly when `x + d < 2 ^ 256`, and then slot 0 holds `x + d` and every other slot is unchanged. + +The goal of solar-verify's obligation for this clause, after its definition `arith = x + d` is +inlined, is `x + d = x + d`: valid by solar-verify's own encoding of the effect, so a verdict adds +nothing to it, and `inc_triple` takes no `Valid` premise. What ties solar-verify to SolidCore is the +binding: the effect solar-verify encodes is the one SolidCore runs, and the guard it assumes is +exactly SolidCore's success condition. The negatives (`CounterMutants`) show the check failing for +a one-line source mutant and a one-line spec mutant. +-/ + +namespace SolidCore.Verify.VC.Counter + +open SolidCore.Verify SolidCore.Verify.VC SolidCore.Refinement SolidCore.Refinement.Abi +open SolidCore.Refinement.Generic SolidCore.Solidity SolidCore.Solidity.Source + +/-- The interpreter fuel of SolidCore's runs. -/ +def fuel : Nat := 4096 + +/-- SolidCore's checked `Counter`: `SolidCore.Refinement.Solar.Counter.contract?`'s body. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract SolidCore.Refinement.Source.Counter.importedSourceUnit "Counter" + +/-- The selector of `inc(uint256)`. -/ +abbrev incSel : Nat := 0x812600df + +/-- The selector of `get()`. -/ +abbrev getSel : Nat := 0x6d4ce63c + +/-- The selector of `inc(uint256)`, by Keccak-256 of its signature. -/ +def selInc : SolidCore.Solidity.Shared.Word := SolidCore.Solidity.Source.ABI.selectorFromSignature "inc(uint256)" + +kernel_rfl selInc_eq selInc incSel + +/-- The selector of `get()`, by Keccak-256 of its signature. -/ +def selGet : SolidCore.Solidity.Shared.Word := SolidCore.Solidity.Source.ABI.selectorFromSignature "get()" + +kernel_rfl selGet_eq selGet getSel + +/-- `ABI.selectorFromSignature`, with `Counter`'s selectors by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "inc(uint256)" then incSel + else if s = "get()" then getSel + else SolidCore.Solidity.Source.ABI.selectorFromSignature s + +theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + by_cases h0 : s = "inc(uint256)" + · rw [ite_eq_left h0, h0] + exact selInc_eq + rw [ite_eq_right h0] + by_cases h1 : s = "get()" + · rw [ite_eq_left h1, h1] + exact selGet_eq + rw [ite_eq_right h1] + +/-- `inc(uint256)` as the stage's ABI sees it. -/ +def fnInc : Fn := ⟨incSel, [.uint 256]⟩ + +/-- The revert data of `Panic(0x11)`, byte by byte. -/ +def panic11 : List OByte := + [78, 72, 123, 113].map .lit ++ (List.replicate 31 (OByte.lit 0)) ++ [.lit 17] + +/-- The erasure of `inc`: panic when `x + d` wraps, else write it to slot 0. -/ +def incTree : Tree := + .ite (.bin .lt (.bin .add (.init 0) (.arg 0)) (.init 0)) (.halt false panic11 [] []) + (.halt true [] [(.lit 0, .bin .add (.init 0) (.arg 0))] []) + +/-- Whether `Counter` deploys with no storage and no logs, and how SolidCore dispatches `inc` and the +generic source stage erases it. -/ +def incShape? : Option (Bool × Option (Nat × Option Tree)) := + match contract? with + | .ok c => some (Wide.deployedAt fuel c [], + (c.core.findFunctionBySelector? incSel).map fun f => (f.params.length, eraseFn (envOf c.core) fuel f)) + | .error _ => none + +kernel_rfl incShape_eq incShape? (some (true, some (1, some incTree))) using selector_eq mkIdx_eq + +/-! ## The Lean obligation -/ + +namespace Ob + +def x : Tm := .ivar "x" +def d : Tm := .ivar "d" +def mv : Tm := .ivar "msg.value" +def ms : Tm := .ivar "msg.sender" +def le0 (t : Tm) : Tm := .app "<=" [.num 0, t] +def leW (t : Tm) : Tm := .app "<=" [t, .num (2 ^ 256 - 1)] +def add (a b : Tm) : Tm := .app "+" [a, b] +def eq (a b : Tm) : Tm := .app "=" [a, b] + +end Ob + +open Ob in +/-- solar-verify's encoding of `x` after `inc`. -/ +def incEff : Tm := add x d + +open Ob in +/-- The guard of `inc`'s success path, and the ranges of the words it reads. -/ +def incHyps : List Tm := + [eq mv (.num 0), le0 incEff, leW incEff, le0 d, leW d, le0 x, leW x, le0 mv, leW mv, + .app "not" [eq ms (.num 0)], le0 ms, .app "<=" [ms, .num (2 ^ 160 - 1)]] + +open Ob in +/-- `inc`'s ensures clause as solar-verify states it, of its own encoding of the new `x`. -/ +def incGoal : Tm := eq incEff (add x d) + +/-- solar-verify's script for the annotated counter has an obligation that `checkOb` normalizes to +`incHyps ⟹ incGoal`. -/ +theorem inc_check : checkScript Export.CounterMilestone.script [(incHyps, incGoal)] = true := by + decide +kernel + +/-! ## The binding -/ + +/-- The assignment of solar-verify's names that a call of `inc` on `d` from storage `s` binds. -/ +def incEnv (d : Nat) (s : Storage) : Env where + i := fun y => if y = "x" then s 0 else if y = "d" then d else if y = "msg.sender" then callerWord else 0 + b := fun _ => False + a := fun _ => fun _ => 0 + +section +variable (d : Nat) (s : Storage) +@[simp] theorem incEnv_x : (incEnv d s).i "x" = s 0 := rfl +@[simp] theorem incEnv_d : (incEnv d s).i "d" = d := rfl +@[simp] theorem incEnv_mv : (incEnv d s).i "msg.value" = 0 := rfl +@[simp] theorem incEnv_ms : (incEnv d s).i "msg.sender" = 8192 := rfl +end + +theorem incEff_eval (d : Nat) (s : Storage) : (incEff.eval (incEnv d s)).toInt = (s 0 : Int) + d := by + simp [incEff, Ob.add, Ob.x, Ob.d, Tm.eval, Tm.evalList, applyOp, Value.select, Value.store, Value.toInt] + +theorem incHyps_iff (d : Nat) (s : Storage) (hd : d < 2 ^ 256) (hs : s 0 < 2 ^ 256) : + (∀ t ∈ incHyps, t.Holds (incEnv d s)) ↔ s 0 + d < 2 ^ 256 := by + simp only [incHyps, List.mem_cons, List.mem_nil_iff, or_false, forall_eq_or_imp, forall_eq] + simp [Tm.Holds, Tm.eval, Tm.evalList, applyOp, Value.select, Value.store, Value.toProp, Value.toInt, Value.eq, incEff, Ob.add, + Ob.x, Ob.d, Ob.mv, Ob.ms, Ob.le0, Ob.leW, Ob.eq] + omega + +theorem incAdd_eval (s : Storage) (hs : ∀ k, s k < 2 ^ 256) (d : Nat) (hd : d < 2 ^ 256) : + (WExpr.bin .add (.init 0) (.arg 0)).eval (valOf [d] s) = (s 0 + d) % 2 ^ 256 := by + simp [WExpr.eval, BinOp.eval, valOf, Generic.wordSize, Nat.mod_eq_of_lt hd, Nat.mod_eq_of_lt (hs 0)] + +theorem incCond_eval (s : Storage) (hs : ∀ k, s k < 2 ^ 256) (d : Nat) (hd : d < 2 ^ 256) : + (WExpr.bin .lt (.bin .add (.init 0) (.arg 0)) (.init 0)).eval (valOf [d] s) = + if s 0 + d < 2 ^ 256 then 0 else 1 := by + have h := incAdd_eval s hs d hd + simp only [WExpr.eval] at h ⊢ + rw [h] + have h0 := hs 0 + simp only [BinOp.eval, valOf, Generic.wordSize, Nat.mod_eq_of_lt h0] + by_cases hov : s 0 + d < 2 ^ 256 + · rw [Nat.mod_eq_of_lt hov, if_neg (by omega), if_pos hov] + · have : (s 0 + d) % 2 ^ 256 = s 0 + d - 2 ^ 256 := by omega + rw [this, if_pos (by omega), if_neg hov] + +/-- The binding: a call of `inc` succeeds exactly when solar-verify's guard holds at the assignment +it binds, and then writes slot 0 with solar-verify's encoding of the new `x` and leaves every other +slot. -/ +theorem inc_binding (s : Storage) (hs : ∀ k, s k < 2 ^ 256) (d : Nat) (hd : d < 2 ^ 256) : + let R := incTree.eval (valOf [d] s) + (R.success = true ↔ ∀ t ∈ incHyps, t.Holds (incEnv d s)) ∧ + (R.success = true → ((R.store 0 : Nat) : Int) = (incEff.eval (incEnv d s)).toInt ∧ + ∀ k, k % 2 ^ 256 ≠ 0 → R.store k = s k) := by + intro R + rw [incHyps_iff d s hd (hs 0), incEff_eval] + have hc := incCond_eval s hs d hd + have ha := incAdd_eval s hs d hd + by_cases hov : s 0 + d < 2 ^ 256 + · have hsucc : R.success = true := by + simp only [R, incTree, Tree.eval, hc, if_pos hov, ite_true] + have hst : R.store = Writes.store (valOf [d] s) [(.lit 0, .bin .add (.init 0) (.arg 0))] := by + simp only [R, incTree, Tree.eval, hc, if_pos hov, ite_true] + refine ⟨by simp only [hsucc, true_iff]; omega, fun _ => ⟨?_, fun k hk => ?_⟩⟩ + · rw [hst] + simp only [Writes.store, ha] + split + · rw [Nat.mod_eq_of_lt hov]; push_cast; rfl + · rename_i h; exact absurd (by simp [WExpr.eval]) h + · rw [hst] + simp only [Writes.store] + split + · rename_i h; simp [WExpr.eval, Generic.wordSize] at h; omega + · rfl + · have hR : R.success = false := by + simp only [R, incTree, Tree.eval, hc, if_neg hov]; rfl + simp only [hR, Bool.false_eq_true, false_iff, false_implies, and_true] + omega + +/-- `inc`'s postcondition: it succeeds exactly when `x + d` does not wrap, and then slot 0 holds +`x + d` and every other slot is unchanged. -/ +def incPost (call : Call) (obs : SolarTV.Observable) : Prop := + let d := (argWords 1 call).getD 0 0 + let s := initStorage call + (obs.success = true ↔ s 0 + d < 2 ^ 256) ∧ + (obs.success = true → obs.storage 0 = s 0 + d ∧ ∀ k, k % 2 ^ 256 ≠ 0 → obs.storage k = s k) + +theorem vc_eq (model : List Nat → SolM (List Nat)) (args : Call → List Nat) + (post : Call → SolarTV.Observable → Prop) (call : Call) : + vc model args post call = + post call (observe (initStorage call) (model (args call) (initStorage call))) := by + unfold vc + rw [wp_eq] + rcases h : model (args call) (initStorage call) with e | ⟨out, s'⟩ <;> simp only [h] <;> rfl + +/-- `Counter.inc` on the stage's scope: it succeeds exactly when `x + d` does not wrap, and then slot 0 +holds `x + d` and every other slot is unchanged, through `implementsTree` and the binding to +solar-verify's encoding. -/ +theorem inc_triple {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Triple fuel c (stageScope fnInc []) (fun _ => True) incPost := by + have hshape := incShape_eq + simp only [incShape?, hc, Option.some.injEq, Prod.mk.injEq] at hshape + obtain ⟨hdep, hmap⟩ := hshape + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + simp only [Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + have himpl := implements_tree (fn := fnInc) hdd (by decide) hf hlen hT rfl + apply triple_of_wp himpl + rintro _ ⟨σ, -, fn', hfn', args, hl, hargs, rfl⟩ - + simp only [List.mem_singleton] at hfn' + subst hfn' + obtain ⟨d, rfl⟩ : ∃ d, args = [d] := by + match args, hl with + | [d], _ => exact ⟨d, rfl⟩ + have hd : d < 2 ^ 256 := hargs d (List.mem_singleton_self d) + have hw : argWords 1 ({ calldata := Abi.calldata fnInc.sel [d], callvalue := 0, storage := σ } : Call) = + [d] := argWords_calldata _ [d] hargs 0 σ + rw [vc_eq, treeModel_run, show fnInc.params.length = 1 from rfl, hw] + set s := initStorage ({ calldata := Abi.calldata fnInc.sel [d], callvalue := 0, storage := σ } : Call) + with hs_def + have hs : ∀ k, s k < 2 ^ 256 := fun k => Generic.slotValue_lt σ k + obtain ⟨hiff, hok⟩ := inc_binding s hs d hd + have hguard := incHyps_iff d s hd (hs 0) + simp only [incPost, hw, List.getD_cons_zero, ← hs_def] + unfold resOutcome + split + · next hsucc => + obtain ⟨h0, hk⟩ := hok hsucc + rw [incEff_eval] at h0 + simp only [observe, true_iff] + refine ⟨hguard.mp (hiff.mp hsucc), fun _ => ⟨?_, hk⟩⟩ + omega + · next hfail => + simp only [observe, Bool.false_eq_true, false_iff, false_implies, and_true] + intro hlt + exact hfail (hiff.mpr (hguard.mpr hlt)) + +/-- info: 'SolidCore.Verify.VC.Counter.inc_triple' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms inc_triple + +/-- info: 'SolidCore.Verify.VC.Counter.inc_check' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms inc_check + +end SolidCore.Verify.VC.Counter diff --git a/Contracts/Counter/VC/MilestoneDischarged.lean b/Contracts/Counter/VC/MilestoneDischarged.lean new file mode 100644 index 00000000..8f6e04d3 --- /dev/null +++ b/Contracts/Counter/VC/MilestoneDischarged.lean @@ -0,0 +1,33 @@ +import Contracts.Counter.VC.MilestoneDischarged.Part0 + +/-! +# `SolidCore.Verify.VC.Export.CounterMilestone.script`, discharged by the kernel + +Generated by scripts/verify/gen-discharged.py: one kernel evaluation of `dischargeAt` per +obligation (the Part modules, Verify/VC/Discharge.lean), and the script's verdict `Valid` from +them, with no solver. Each rejected mutant script fails by a mismatch at the obligation named. +-/ + +namespace SolidCore.Verify.VC.Counter.MilestoneDischarged + +open SolidCore.Verify.VC + +set_option maxRecDepth 100000 + +theorem obligation_count : (obligations SolidCore.Verify.VC.Export.CounterMilestone.script).length = 4 := by decide +kernel + +/-- Every obligation of the script has no model. -/ +theorem script_valid : Valid SolidCore.Verify.VC.Export.CounterMilestone.script := + dischargeScript_of_each _ fun i hi => + match i, obligation_count ▸ hi with + | 0, _ => ob_0 + | 1, _ => ob_1 + | 2, _ => ob_2 + | 3, _ => ob_3 + | _ + 4, h => absurd h (by omega) + +/-- info: 'SolidCore.Verify.VC.Counter.MilestoneDischarged.script_valid' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms script_valid + +end SolidCore.Verify.VC.Counter.MilestoneDischarged diff --git a/Contracts/Counter/VC/MilestoneDischarged/Part0.lean b/Contracts/Counter/VC/MilestoneDischarged/Part0.lean new file mode 100644 index 00000000..b4030c14 --- /dev/null +++ b/Contracts/Counter/VC/MilestoneDischarged/Part0.lean @@ -0,0 +1,21 @@ +import Verify.VC.Discharge +import Contracts.Counter.VC.ExportMilestone + +/-! Obligations 0 to 3 of `SolidCore.Verify.VC.Export.CounterMilestone.script`, each discharged by the +kernel (generated by scripts/verify/gen-discharged.py). -/ + +namespace SolidCore.Verify.VC.Counter.MilestoneDischarged + +open SolidCore.Verify.VC + +set_option maxRecDepth 100000 + +theorem ob_0 : dischargeAt SolidCore.Verify.VC.Export.CounterMilestone.script 0 = true := by decide +kernel + +theorem ob_1 : dischargeAt SolidCore.Verify.VC.Export.CounterMilestone.script 1 = true := by decide +kernel + +theorem ob_2 : dischargeAt SolidCore.Verify.VC.Export.CounterMilestone.script 2 = true := by decide +kernel + +theorem ob_3 : dischargeAt SolidCore.Verify.VC.Export.CounterMilestone.script 3 = true := by decide +kernel + +end SolidCore.Verify.VC.Counter.MilestoneDischarged diff --git a/Contracts/Counter/VC/Mutant/SpecMut.lean b/Contracts/Counter/VC/Mutant/SpecMut.lean new file mode 100644 index 00000000..3c3d3de3 --- /dev/null +++ b/Contracts/Counter/VC/Mutant/SpecMut.lean @@ -0,0 +1,169 @@ +-- Generated by solar-verify --dump-lean. Do not edit. + +import Verify.VC.Term + +namespace SolidCore.Verify.VC.Export.Mutant.CounterSpecMut + +open SolidCore.Verify.VC + +/-- The commands solar-verify sent the solver. -/ +def script : List Cmd := [ + .push, + .raw "; ===== Counter.inc", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "x@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "x@17")]), (.app "<=" [(.ivar "x@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@18" .arr, + .elem "__balance@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@19")]), (.app "<=" [(.ivar "__code_epoch@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "d@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "d@20")]), (.app "<=" [(.ivar "d@20"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@21" .bool, + .assert (.app "=" [(.bvar "g@21"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "arith@22" .int, + .assert (.app "=" [(.ivar "arith@22"), (.app "+" [(.ivar "x@17"), (.ivar "d@20")])]), + .decl "g@23" .bool, + .assert (.app "=" [(.bvar "g@23"), (.app "and" [(.bvar "g@21"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@22")]), (.app "<=" [(.ivar "arith@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .push, + .assert (.bvar "g@23"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@23"), + .assert (.app "not" [(.app "=" [(.ivar "arith@22"), (.app "+" [(.app "+" [(.ivar "x@17"), (.ivar "d@20")]), (.num 1)])])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.get", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "x@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "x@17")]), (.app "<=" [(.ivar "x@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@18" .arr, + .elem "__balance@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@19")]), (.app "<=" [(.ivar "__code_epoch@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@20" .bool, + .assert (.app "=" [(.bvar "g@20"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@20"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.constructor", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@17" .arr, + .elem "__balance@17" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@18")]), (.app "<=" [(.ivar "__code_epoch@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@19" .bool, + .assert (.app "=" [(.bvar "g@19"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .pop +] + +/-- The transcript, as solar-verify wrote it. -/ +def transcript : String := "(push 1)\n; ===== Counter.inc\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |x@17| Int)\n(assert (and (<= 0 |x@17|) (<= |x@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@18| (Array Int Int))\n;@elem |__balance@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@19| Int)\n(assert (and (<= 0 |__code_epoch@19|) (<= |__code_epoch@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |d@20| Int)\n(assert (and (<= 0 |d@20|) (<= |d@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@21| Bool)\n(assert (= |g@21| (and true (= |msg.value@3| 0))))\n(declare-const |arith@22| Int)\n(assert (= |arith@22| (+ |x@17| |d@20|)))\n(declare-const |g@23| Bool)\n(assert (= |g@23| (and |g@21| (and (<= 0 |arith@22|) (<= |arith@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(push 1)\n(assert |g@23|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@23|)\n(assert (not (= |arith@22| (+ (+ |x@17| |d@20|) 1))))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.get\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |x@17| Int)\n(assert (and (<= 0 |x@17|) (<= |x@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@18| (Array Int Int))\n;@elem |__balance@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@19| Int)\n(assert (and (<= 0 |__code_epoch@19|) (<= |__code_epoch@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@20| Bool)\n(assert (= |g@20| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@20|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.constructor\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@17| (Array Int Int))\n;@elem |__balance@17| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@18| Int)\n(assert (and (<= 0 |__code_epoch@18|) (<= |__code_epoch@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@19| Bool)\n(assert (= |g@19| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@19|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(pop 1)\n" + +end SolidCore.Verify.VC.Export.Mutant.CounterSpecMut diff --git a/Contracts/Counter/VC/Mutant/SrcMut.lean b/Contracts/Counter/VC/Mutant/SrcMut.lean new file mode 100644 index 00000000..d044b751 --- /dev/null +++ b/Contracts/Counter/VC/Mutant/SrcMut.lean @@ -0,0 +1,173 @@ +-- Generated by solar-verify --dump-lean. Do not edit. + +import Verify.VC.Term + +namespace SolidCore.Verify.VC.Export.Mutant.CounterSrcMut + +open SolidCore.Verify.VC + +/-- The commands solar-verify sent the solver. -/ +def script : List Cmd := [ + .push, + .raw "; ===== Counter.inc", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "x@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "x@17")]), (.app "<=" [(.ivar "x@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@18" .arr, + .elem "__balance@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@19")]), (.app "<=" [(.ivar "__code_epoch@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "d@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "d@20")]), (.app "<=" [(.ivar "d@20"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@21" .bool, + .assert (.app "=" [(.bvar "g@21"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "arith@22" .int, + .assert (.app "=" [(.ivar "arith@22"), (.app "+" [(.ivar "d@20"), (.num 1)])]), + .decl "g@23" .bool, + .assert (.app "=" [(.bvar "g@23"), (.app "and" [(.bvar "g@21"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@22")]), (.app "<=" [(.ivar "arith@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "arith@24" .int, + .assert (.app "=" [(.ivar "arith@24"), (.app "+" [(.ivar "x@17"), (.ivar "arith@22")])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [(.bvar "g@23"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@24")]), (.app "<=" [(.ivar "arith@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .push, + .assert (.bvar "g@25"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@25"), + .assert (.app "not" [(.app "=" [(.ivar "arith@24"), (.app "+" [(.ivar "x@17"), (.ivar "d@20")])])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.get", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "x@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "x@17")]), (.app "<=" [(.ivar "x@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@18" .arr, + .elem "__balance@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@19")]), (.app "<=" [(.ivar "__code_epoch@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@20" .bool, + .assert (.app "=" [(.bvar "g@20"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@20"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Counter.constructor", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@17" .arr, + .elem "__balance@17" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@18")]), (.app "<=" [(.ivar "__code_epoch@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@19" .bool, + .assert (.app "=" [(.bvar "g@19"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .pop +] + +/-- The transcript, as solar-verify wrote it. -/ +def transcript : String := "(push 1)\n; ===== Counter.inc\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |x@17| Int)\n(assert (and (<= 0 |x@17|) (<= |x@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@18| (Array Int Int))\n;@elem |__balance@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@19| Int)\n(assert (and (<= 0 |__code_epoch@19|) (<= |__code_epoch@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |d@20| Int)\n(assert (and (<= 0 |d@20|) (<= |d@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@21| Bool)\n(assert (= |g@21| (and true (= |msg.value@3| 0))))\n(declare-const |arith@22| Int)\n(assert (= |arith@22| (+ |d@20| 1)))\n(declare-const |g@23| Bool)\n(assert (= |g@23| (and |g@21| (and (<= 0 |arith@22|) (<= |arith@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |arith@24| Int)\n(assert (= |arith@24| (+ |x@17| |arith@22|)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(push 1)\n(assert |g@25|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@25|)\n(assert (not (= |arith@24| (+ |x@17| |d@20|))))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.get\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |x@17| Int)\n(assert (and (<= 0 |x@17|) (<= |x@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@18| (Array Int Int))\n;@elem |__balance@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@19| Int)\n(assert (and (<= 0 |__code_epoch@19|) (<= |__code_epoch@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@20| Bool)\n(assert (= |g@20| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@20|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Counter.constructor\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@17| (Array Int Int))\n;@elem |__balance@17| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@18| Int)\n(assert (and (<= 0 |__code_epoch@18|) (<= |__code_epoch@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@19| Bool)\n(assert (= |g@19| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@19|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(pop 1)\n" + +end SolidCore.Verify.VC.Export.Mutant.CounterSrcMut diff --git a/Contracts/Counter/VC/Mutants.lean b/Contracts/Counter/VC/Mutants.lean new file mode 100644 index 00000000..14e16398 --- /dev/null +++ b/Contracts/Counter/VC/Mutants.lean @@ -0,0 +1,28 @@ +import Contracts.Counter.VC.Inc +import Contracts.Counter.VC.Mutant.SrcMut +import Contracts.Counter.VC.Mutant.SpecMut + +/-! +# Mutants that break `Counter.inc`'s binding + +Two copies of `scripts/verify/CounterMilestone.sol`, each changed in one line and exported by the same +solar-verify (`scripts/verify/mutant/MANIFEST`): +* `CounterSrcMut` changes the source to `x += d + 1`. solar-verify's encoding of the new `x` changes with + it, so none of its obligations is `incHyps ⟹ incGoal`, whose effect term `incEff` is the one + `inc_binding` ties to what SolidCore runs on the real source. +* `CounterSpecMut` changes the spec to `x == old(x) + d + 1`. Its obligation's goal is not `incGoal`. + +`checkScript` rejects both, so neither script is bound to SolidCore's `Counter`. +-/ + +namespace SolidCore.Verify.VC.Counter + +open SolidCore.Verify.VC + +theorem srcMut_rejected : checkScript Export.Mutant.CounterSrcMut.script [(incHyps, incGoal)] = false := by + decide +kernel + +theorem specMut_rejected : checkScript Export.Mutant.CounterSpecMut.script [(incHyps, incGoal)] = false := by + decide +kernel + +end SolidCore.Verify.VC.Counter diff --git a/Contracts/Counter/VC/ScriptEndToEnd.lean b/Contracts/Counter/VC/ScriptEndToEnd.lean new file mode 100644 index 00000000..b3cb5c59 --- /dev/null +++ b/Contracts/Counter/VC/ScriptEndToEnd.lean @@ -0,0 +1,44 @@ +import Contracts.Counter.EndToEnd +import Contracts.Counter.VC.Generic +import Contracts.Counter.VC.MilestoneDischarged +import Verify.VC.EndToEnd + +/-! +# Counter's `inc`: solar-verify's script to the bytecode, by the generic composition + +`inc_bytecode_of_script` is `bytecode_of_checked` (Verify/VC/EndToEnd.lean) for `inc`: solar-verify's +script for scripts/verify/CounterMilestone.sol, discharged by the kernel +(`MilestoneDischarged.script_valid`), its obligation checked to be `inc`'s Lean obligation +(`inc_check`), the binding of `inc`'s erased tree to it (`inc_binds`), and the certified stage from +SolidCore's checked `Counter` to solar's bytecode (`Verdict.agree`) give EthLib's run of the exact +bytecode on every call of `inc(uint256)`. No verdict, no hand-proved obligation. +-/ + +namespace SolidCore.Verify.VC.Counter + +open SolidCore.Verify SolidCore.Verify.VC SolidCore.Refinement SolidCore.Refinement.Abi +open SolidCore.Refinement.Generic SolidCore.Solidity + +/-- **`inc` on solar's bytecode, from solar-verify's discharged script.** -/ +theorem inc_bytecode_of_script : + ∀ call, stageScope fnInc [] call → + ∃ o, Target.run SolidCore.Refinement.Solar.Counter.code call = some o ∧ treePost fnInc incP call o := by + obtain ⟨c, hc⟩ := SolidCore.Refinement.Solar.Counter.contract_ok + have hc' : contract? = .ok c := by exact hc + have hshape := incShape_eq + simp only [incShape?, hc', Option.some.injEq, Prod.mk.injEq] at hshape + obtain ⟨hdep, hmap⟩ := hshape + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + simp only [Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + exact bytecode_of_checked (fn := fnInc) hdd (by decide) hf hlen hT MilestoneDischarged.script_valid + inc_check inc_binds + (fun call h => (SolidCore.Refinement.Solar.Counter.Verdict.agree hc).stage call + (SolidCore.Refinement.Solar.Counter.EndToEnd.inc_in_scope h)) + +/-- info: 'SolidCore.Verify.VC.Counter.inc_bytecode_of_script' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms inc_bytecode_of_script + +end SolidCore.Verify.VC.Counter + diff --git a/Contracts/Counter/Verdict.lean b/Contracts/Counter/Verdict.lean new file mode 100644 index 00000000..a9940048 --- /dev/null +++ b/Contracts/Counter/Verdict.lean @@ -0,0 +1,81 @@ +import Contracts.Counter.Final +import Verify.Spec.TrustedBase.Instances + +/-! +# The counter milestone's bytecode meets solar-verify's spec, given its verdict + +This is where the certified translation and solar-verify meet for the counter milestone +(solar-tv/milestone/counter, the source `scripts/refinement/counter/counter.sol`). The stage from +SolidCore's checked contract to solar's bytecode is a theorem (`agree`, from +`Counter.Every`'s source run and `Counter.Final.target_every`, which compose solar-tv's backend +stages); the bytecode is bound to the exporter's manifest (`Counter.Final.bound`: its hex, +checked by the kernel) and runs in one frame (`Counter.Final.frameLocal`). + +`bytecode_spec_of_verdict` takes the rest as hypotheses and nothing else: a spec bundle `b` +(what `solar-verify --emit-lean-spec` exports), its well-formedness and opaque ranges, and +solar-verify's verdict on SolidCore's contract under the trusted base `Hyps.plain` of +`SolidCore.Spec.TrustedBase` (no hashing, no external call, no assembly, no assume, no trusted +function), which `TrustedBase.Instances.counter_on` discharges. The verdict is the only premise +about the spec: the theorem holds for every bundle whose verdict holds, and for a bundle the +bytecode does not meet the conclusion fails, so the verdict fails too. + +What it covers: runtime calls of `scopeEvery` (`inc` and `get` with any value, malformed call +data and unknown selectors, from any storage), under EthLib's run at its default gas limit +(`Target.run`). Not covered: deployment, other gas limits, and calls from other contracts +(the code makes none). +-/ + +namespace SolidCore.Refinement.Solar.Counter.Verdict + +open SolidCore.Refinement SolidCore.Refinement.Final + +/-- The counter's trusted base: nothing to trust beyond the verdict (`Hyps.plain`). -/ +abbrev hyps (c : SolidCore.Solidity.TypeCheck.CheckedContract) (deployed : Nat → Nat) : + SolidCore.Spec.TrustedBase.Hyps (solidCore fuel) c := + SolidCore.Spec.TrustedBase.Hyps.plain (solidCore fuel) c Source.Counter.importedSourceUnit + deployed (fun _ => []) + +/-- SolidCore's checked counter and solar's bytecode show the same observable on every call of +the scope. -/ +theorem agree {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Agree (solidCore fuel) ethLib c code scopeEvery := + fun call h => ⟨_, source_run_every hc call h, Final.target_every call h⟩ + +/-- **The counter's bytecode meets every spec solar-verify accepts of its source.** -/ +theorem bytecode_spec_of_verdict {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) + {b : SolidCore.Spec.Bundle} {ctxOf : Call → SolidCore.Spec.Ctx} + {step : SolidCore.Spec.GhostStep} (deployed : Nat → Nat) + (hwf : b.WF = true) (hopaque : SolidCore.Spec.OpaqueInRange b) + (verdict : SolidCore.Spec.Verdict (solidCore fuel) c scopeEvery b ctxOf step + ((hyps c deployed).toAssumptions scopeEvery b ctxOf step)) : + Bound Final.manifest code ∧ FrameLocal code = true ∧ + Agree (solidCore fuel) ethLib c code scopeEvery ∧ + SolidCore.Spec.Holds ethLib code scopeEvery b ctxOf step := + ⟨Final.bound, Final.frameLocal, agree hc, + SolidCore.Spec.TrustedBase.Instances.counter_spec_of_verdict deployed hwf hopaque verdict + (agree hc).stage⟩ + +/-- info: 'SolidCore.Refinement.Solar.Counter.Verdict.bytecode_spec_of_verdict' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecode_spec_of_verdict + +/-- **The counter's bytecode meets every total-correctness triple of its source.** A +`SolidCore.Verify.Triple` of SolidCore's checked counter, the shape solar-verify's VCs discharge +to through Loom's `triple_of_wp`, on a scope inside `scopeEvery` carries to solar's bytecode +under EthLib: each call of the scope that meets `pre` finishes on the bytecode with an +observable meeting `post`. Pointwise: the fuel is the triple's own. -/ +theorem bytecode_of_triple {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : contract? = .ok c) {scope pre : Call → Prop} {post : Call → Observable → Prop} + (hs : ∀ call, scope call → scopeEvery call) + (h : SolidCore.Verify.Triple fuel c scope pre post) : + ∀ call, scope call → pre call → ∃ obs, Target.run code call = some obs ∧ post call obs := by + intro call hsc hp + obtain ⟨hsome, hpost⟩ := h call hsc hp + obtain ⟨obs, hobs⟩ := Option.isSome_iff_exists.mp hsome + exact ⟨obs, (agree hc).stage call (hs call hsc) obs hobs, hpost obs hobs⟩ + +/-- info: 'SolidCore.Refinement.Solar.Counter.Verdict.bytecode_of_triple' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecode_of_triple + +end SolidCore.Refinement.Solar.Counter.Verdict diff --git a/Contracts/Counter/Verify.lean b/Contracts/Counter/Verify.lean new file mode 100644 index 00000000..751a2213 --- /dev/null +++ b/Contracts/Counter/Verify.lean @@ -0,0 +1,254 @@ +import Verify.Final +import Verify.Abi + +/-! +# solar-verify's Counter: its specification and what certifies it + +The contract is `crates/verify/examples/Counter.sol` of solar (branch `alpharush/verify`), +compiled by solar at 3a044a9d (`alpharush/tv-backend-stages`) with `-Ogas --evm-version osaka` +to 496 bytes of runtime bytecode (`manifest`, `code`; `bound` checks the hex in +the kernel). Its NatSpec, read as `Final.ContractSpec` over the abstract state `(count, limit)` +that slots 0 and 1 hold: + +* `@custom:invariant count <= limit`; +* `increment()`: requires `count < limit`, ensures `count == old(count) + 1`; +* `bump(uint256 n)`: ensures `count == old(count) + n` (its loop's invariants and variant are + the proof's, not the contract's); +* `max(uint256 a, uint256 b)`: ensures `result == (a >= b ? a : b)`, `result >= a` and + `result >= b`; +* the getters `count()` and `limit()` have no specification but the invariants; +* nothing is payable. + +The constructor's `@custom:ensures limit == _limit && count == 0` is about deployment, which +`Final` does not cover; it is what makes the invariant hold of the first storage. + +`bump(n)` runs its loop `n` times, so its gas grows with `n` and SolidCore needs fuel that grows +with `n`: no fixed gas limit or fuel finishes every call. The statement is therefore +`Final.compose_anyGas`'s, against SolidCore with as much fuel as a call needs (`solidCoreAny`) +and at every gas: every result of the bytecode is SolidCore's or a failure that changes nothing, +and the specification holds at every gas. `certified_of_stages` gives it from the stages, each a +hypothesis named after its obligation. None of them is proved yet: the generic source stage, +solar-tv's backend stages and the assembly stage handle loop-free programs only. + +The specification is not met trivially (`satisfiable`: every function has a state that meets the +invariant and its precondition; `ensures_rejects`: each postcondition rejects some result), and +the code runs in one frame (`frameLocal`), so no other contract can run during a call. +-/ + +namespace SolidCore.Refinement.Solar.VerifyCounter + +open SolidCore.Refinement SolidCore.Refinement.Final + +/-- The abstract state: `count` (slot 0) and `limit` (slot 1). -/ +structure State where + count : Nat + limit : Nat + +/-- The storage layout. -/ +def layout (s : Nat → Nat) : State := ⟨s 0, s 1⟩ + +/-- The ABI return data of one word. -/ +def returns (out : List Nat) (r : Nat) : Prop := out = SolidCore.Verify.word r + +def countSpec : FnSpec State where + name := "count" + sel := 0x06661abd + params := [] + requires _ _ := True + ensures _ _ _ _ := True + payable := false + +def limitSpec : FnSpec State where + name := "limit" + sel := 0xa4d66daf + params := [] + requires _ _ := True + ensures _ _ _ _ := True + payable := false + +/-- `@custom:requires count < limit`, `@custom:ensures count == old(count) + 1`. -/ +def incrementSpec : FnSpec State where + name := "increment" + sel := 0xd09de08a + params := [] + requires _ s := s.count < s.limit + ensures _ s s' _ := s'.count = s.count + 1 + payable := false + +/-- `@custom:ensures count == old(count) + n`. -/ +def bumpSpec : FnSpec State where + name := "bump" + sel := 0xb20eb4c4 + params := [.uint 256] + requires _ _ := True + ensures args s s' _ := s'.count = s.count + args.headD 0 + payable := false + +/-- `@custom:ensures result == (a >= b ? a : b)`, `result >= a && result >= b`. -/ +def maxSpec : FnSpec State where + name := "max" + sel := 0x6d5433e6 + params := [.uint 256, .uint 256] + requires _ _ := True + ensures args _ _ out := + let a := args.getD 0 0 + let b := args.getD 1 0 + ∃ r, returns out r ∧ r = (if a ≥ b then a else b) ∧ r ≥ a ∧ r ≥ b + payable := false + +/-- Counter's specification. -/ +def spec : ContractSpec State where + abs := layout + invariant s := s.count ≤ s.limit + fns := [countSpec, limitSpec, incrementSpec, bumpSpec, maxSpec] + +/-! ## The bytecode and its manifest -/ + +def manifest : Manifest where + contract := "Counter" + sourceSha256 := "f1c87a334b8db31fc8f80541febeaf8617318d20b685634f44e26c74146ad326" + compilerCommit := "0.8.38+commit.3a044a9d.solar.0.3.0-dev" + options := ["-Ogas", "--evm-version", "osaka"] + runtimeHex := + "34603c575f3560e01c806306661abd1460525780636d5433e6146101af578063a4d66daf14605b578063b20eb4c4146073578063d09de08a146065575b5f5ffd5b6011602052634e487b715f526024601cfd5b5f545f5260205ff35b6001545f5260205ff35b5f5460010180156040575f55005b60243610603c576004355f54818101818110604057600154106101d25780816080525f60a0528082820361019a575f5f91925060db565b506080516001840180158583036101675760405780608052600160a05260018301925f191480610182575093505060015b8482105f54808503610111575060aa5760a051815f10828203610152571561010f5750505050608051815f5581810361013e575b005b90506d011100000004000000010000000f939091935b60205260405260605263ed572b275b5f526064601cfd5b6d012100000004000000050000000e610127565b506d012100000004000000040000000c610127565b505090506d0121000000040000000300000008929192610127565b5f6d0102000000040000000a00000012919091610127565b506d010300000004000000070000000b610127565b60443610603c576004356024358082106101cb57505f5260205ff35b5f5260205ff35b636f76657260e01b6004602080526040526060526308c379a061013656" + runtimeSha256 := "d74a847b897f855f93daf2805937efe40aec636c2ec3ca0c2d4ca6d21f214cc1" + +/-- The runtime bytecode as one number, most significant byte first, as the milestones write +it: the kernel computes with it by GMP, where parsing the hex string would cost it minutes. -/ +def runtimeNat : Nat := 0x34603c575f3560e01c806306661abd1460525780636d5433e6146101af578063a4d66daf14605b578063b20eb4c4146073578063d09de08a146065575b5f5ffd5b6011602052634e487b715f526024601cfd5b5f545f5260205ff35b6001545f5260205ff35b5f5460010180156040575f55005b60243610603c576004355f54818101818110604057600154106101d25780816080525f60a0528082820361019a575f5f91925060db565b506080516001840180158583036101675760405780608052600160a05260018301925f191480610182575093505060015b8482105f54808503610111575060aa5760a051815f10828203610152571561010f5750505050608051815f5581810361013e575b005b90506d011100000004000000010000000f939091935b60205260405260605263ed572b275b5f526064601cfd5b6d012100000004000000050000000e610127565b506d012100000004000000040000000c610127565b505090506d0121000000040000000300000008929192610127565b5f6d0102000000040000000a00000012919091610127565b506d010300000004000000070000000b610127565b60443610603c576004356024358082106101cb57505f5260205ff35b5f5260205ff35b636f76657260e01b6004602080526040526060526308c379a061013656 + +/-- The runtime bytecode. `bound` checks it against the manifest's hex. -/ +def code : ByteArray := EthLib.Execution.Evm.Logic.NatCode.ofNat runtimeNat 496 + +/-! ## The bytecode is the manifest's + +The kernel reads `code` (an `Array.ofFn`) and the manifest's strings slowly, so the check goes +through forms the kernel computes with cheaply, each proved equal to the original: `code` as a +list (`code_eq`) and the hex of bytes as a list of characters, compared with the manifest's +string character by character (`hexOf_eq`). Exact equality with the manifest's hex binds the +bytes; the manifest's SHA-256 is recorded data, not checked in the kernel. -/ + +/-- The lowest `k` bytes of `n`, most significant first. -/ +def natBytes (n : Nat) : Nat → List UInt8 + | 0 => [] + | k + 1 => UInt8.ofNat (n >>> (8 * k)) :: natBytes n k + +/-- `code` as a list of bytes. -/ +def code' : ByteArray := ⟨⟨natBytes runtimeNat 496⟩⟩ + +/-- A hex digit, as `hexOf` writes it. -/ +def hexDigit (n : Nat) : Char := if n < 10 then Char.ofNat (48 + n) else Char.ofNat (87 + n) + +/-- The characters `hexOf` writes. -/ +def hexChars : List Nat → List Char + | [] => [] + | b :: rest => hexDigit (b / 16 % 16) :: hexDigit (b % 16) :: hexChars rest + +theorem length_natBytes (n k : Nat) : (natBytes n k).length = k := by + induction k with + | zero => rfl + | succ k ih => simp [natBytes, ih] + +theorem getElem_natBytes (n k i : Nat) (h : i < (natBytes n k).length) : + (natBytes n k)[i] = EthLib.Execution.Evm.Logic.NatCode.natByte n k i := by + induction k generalizing i with + | zero => simp [natBytes] at h + | succ k ih => + have hk : i < k + 1 := by simpa [length_natBytes] using h + cases i with + | zero => simp [natBytes, EthLib.Execution.Evm.Logic.NatCode.natByte] + | succ i => + have hi : i < (natBytes n k).length := by rw [length_natBytes]; omega + simp only [natBytes, List.getElem_cons_succ] + rw [ih i hi] + simp only [EthLib.Execution.Evm.Logic.NatCode.natByte] + rw [ite_eq_left (by omega), ite_eq_left (by omega)] + congr 3 + omega + +theorem ofNat_eq (n k : Nat) : + EthLib.Execution.Evm.Logic.NatCode.ofNat n k = ⟨⟨natBytes n k⟩⟩ := by + unfold EthLib.Execution.Evm.Logic.NatCode.ofNat + congr 1 + apply Array.ext + · simp [length_natBytes] + · intro i h1 h2 + simp only [Array.getElem_ofFn] + exact (getElem_natBytes n k i (by simpa using h2)).symm + +theorem code_eq : code = code' := ofNat_eq _ _ + +theorem hexOf_eq (l : List Nat) : hexOf l = String.ofList (hexChars l) := by + induction l with + | nil => simp [hexOf, hexChars] + | cons b rest ih => + simp only [hexOf, List.map_cons, String.join_cons] at ih ⊢ + rw [ih, hexChars, ← String.ofList_append] + rfl + +set_option maxRecDepth 200000 in +theorem hex_bound : hexOf (code.data.toList.map (·.toNat)) = manifest.runtimeHex := by + rw [code_eq, hexOf_eq] + rfl + +theorem size_code : code.size = 496 := by + rw [code_eq]; decide +kernel + +/-- No instruction of the code runs other code or reads outside its frame. -/ +theorem frameLocal : FrameLocal code = true := by + rw [code_eq]; decide +kernel + +theorem bound : Bound manifest code := hex_bound + + +/-! ## The specification is not trivial -/ + +/-- Every function has argument words and a state that meet the invariant and its +precondition. -/ +theorem satisfiable : ∀ f ∈ spec.fns, ∃ args st, f.Typed args ∧ spec.invariant st ∧ f.requires args st := by + intro f hf + simp only [spec, List.mem_cons, List.not_mem_nil, or_false] at hf + rcases hf with rfl | rfl | rfl | rfl | rfl + · exact ⟨[], ⟨0, 0⟩, List.Forall₂.nil, Nat.le_refl _, trivial⟩ + · exact ⟨[], ⟨0, 0⟩, List.Forall₂.nil, Nat.le_refl _, trivial⟩ + · exact ⟨[], ⟨0, 1⟩, List.Forall₂.nil, Nat.zero_le 1, Nat.zero_lt_one⟩ + · exact ⟨[0], ⟨0, 0⟩, List.Forall₂.cons (by decide) List.Forall₂.nil, Nat.le_refl _, trivial⟩ + · exact ⟨[0, 0], ⟨0, 0⟩, List.Forall₂.cons (by decide) (List.Forall₂.cons (by decide) + List.Forall₂.nil), Nat.le_refl _, trivial⟩ + +/-- The postconditions of `increment`, `bump` and `max` each reject some result. -/ +theorem ensures_rejects : + ¬ incrementSpec.ensures [] ⟨0, 1⟩ ⟨0, 1⟩ [] ∧ ¬ bumpSpec.ensures [1] ⟨0, 1⟩ ⟨0, 1⟩ [] ∧ + ¬ maxSpec.ensures [1, 2] ⟨0, 0⟩ ⟨0, 0⟩ (SolidCore.Verify.word 1) := by + refine ⟨by simp [incrementSpec], by simp [bumpSpec], ?_⟩ + rintro ⟨r, hret, hr, -⟩ + have h2 : r = 2 := by simpa using hr + subst h2 + exact absurd hret (by unfold returns; decide +kernel) + +/-! ## The certificate from its stages -/ + +/-- **solar-verify's Counter from its stages.** SolidCore's checked contract `c`, which meets the +specification and finishes every call of it with enough fuel, a stage from SolidCore to a lowered +MIR program, the backend's stage to an EVM IR program, and an assembly stage that gives at every +gas the EVM IR's result or a failure, give at every gas: every result of the bytecode is +SolidCore's or a failure that changes nothing, and the specification holds of the bytecode. -/ +theorem certified_of_stages {mirSem evmirSem : Sem} + {c : SolidCore.Solidity.TypeCheck.CheckedContract} {mir : mirSem.Prog} {evmir : evmirSem.Prog} + (source : Holds solidCoreAny c spec) + (fin : ∀ call, spec.Calls call → (solidCoreAny.run c call).isSome) + (lowering : Stage solidCoreAny mirSem c mir spec.Calls) + (backend : Stage mirSem evmirSem mir evmir spec.Calls) + (assembly : ∀ gas, Within evmirSem (ethLibWith gas) evmir code spec.Calls) (gas : Nat) : + Within solidCoreAny (ethLibWith gas) c code spec.Calls ∧ Holds (ethLibWith gas) code spec := + compose_anyGas source fin lowering backend assembly gas + +/-- info: 'SolidCore.Refinement.Solar.VerifyCounter.bound' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bound + +/-- info: 'SolidCore.Refinement.Solar.VerifyCounter.certified_of_stages' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms certified_of_stages + +end SolidCore.Refinement.Solar.VerifyCounter diff --git a/Contracts/Create2/Deployer.sol b/Contracts/Create2/Deployer.sol new file mode 100644 index 00000000..79aa4bcb --- /dev/null +++ b/Contracts/Create2/Deployer.sol @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +// The inline assembly create2 assignment SolidCore's frontend translates (Stmt.assemblyCreate2): +// a literal value and a bytes32 salt, and every operand a local. +contract Deployer { + function deploy(bytes32 salt) external returns (address a) { + bytes memory code = hex"6001600c60003960016000f300"; + assembly { + a := create2(0, add(code, 32), mload(code), salt) + } + } + + function deployWith(uint256 v, uint256 salt, bytes memory code) external payable returns (address a) { + assembly { + a := create2(v, add(code, 32), mload(code), salt) + } + } +} diff --git a/Contracts/Create2/Run.lean b/Contracts/Create2/Run.lean new file mode 100644 index 00000000..3b06e4c7 --- /dev/null +++ b/Contracts/Create2/Run.lean @@ -0,0 +1,102 @@ +import Contracts.Create2.Source +import Contracts.Create2.SourceView + +/-! +# Inline assembly create2 in SolidCore's semantics: execution tests + +`Contracts/Create2/Deployer.sol` assigns `create2(value, add(code, 32), mload(code), salt)` to a +local in inline assembly, which the frontend translates to `Stmt.assemblyCreate2` and SolidCore +runs as one open-world creation request (`emitCreate2Bytes`). Each `#guard` runs the checked +contract's function and answers its requests: + +* the request is CREATE2 from the contract, with the bytes of `code` as init code, the salt and + the value of the call, and the function returns the answered address; +* a failed creation (address 0) returns 0 and does not revert, as the EVM's CREATE2; +* the same function declared `view` is rejected by SolidCore's checker (negative control), as solc + rejects it. +-/ + +namespace SolidCore.Verify.Create2.Run +open SolidCore.Solidity SolidCore.Solidity.Source EvmCompiler.Simulation + +def fuel : Nat := 256 +def self : Nat := 0xde91 +def code : List Nat := [0x60, 0x01, 0x60, 0x0c, 0x60, 0x00, 0x39, 0x60, 0x01, 0x60, 0x00, 0xf3, 0x00] + +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract SolidCore.Verify.Create2.Source.importedSourceUnit "Deployer" + +def viewContract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract SolidCore.Verify.Create2.SourceView.importedSourceUnit "Deployer" + +def context (c : TypeCheck.CheckedContract) (value : Nat) : Context := + { c.core.context with + self := self + sender := 0x5e + value := value } + +/-- The creation requests of a run, answering each with `address` (and calls with success). -/ +structure Seen where + kind : CreateKind + creator : Nat + value : Nat + initCode : List Nat + salt : Option Nat + deriving DecidableEq, Repr + +def answered (w : OpenWorld) (a : Nat) : CreateResponse := + { address := EvmYul.UInt256.ofNat a + returnData := default + postWorld := w + returnedGas := EvmYul.UInt256.ofNat 0 } + +/-- The creation requests and the returned words (`none` on a revert or a stuck run). -/ +def run (a : Nat) : Nat → SolI CallResult → List Seen × Option (List Nat) + | 0, _ => ([], none) + | _, .done (.ok (.returned _ vs)) => ([], vs.mapM (fun v => v.expectWord.toOption)) + | _, .done _ => ([], none) + | n + 1, .request q k => + match q, k with + | .external w (.create r), k => + let (rs, out) := run a n (k (answered w a)) + ({ kind := r.kind, creator := addressToWord r.creator, value := u256ToWord r.value, + initCode := r.initCode.toList.map UInt8.toNat, salt := r.salt.map u256ToWord } :: rs, out) + | _, _ => ([], none) + +def call (name : String) (value : Nat) (args : List Value) (a : Nat) : List Seen × Option (List Nat) := + match contract? with + | .ok c => + match TypeCheck.CheckedContract.callFunctionWithContextTree fuel c name (context c value) + State.empty args with + | some tree => run a 8 tree + | none => ([], none) + | .error _ => ([], none) + +#guard contract?.isOk + +-- `deploy(salt)`: CREATE2 of the local's bytes with value 0; it returns the new address. +#guard call "deploy" 0 [Value.fixedBytes 32 0x1234] 0xbeef == + ([{ kind := .create2, creator := self, value := 0, initCode := code, salt := some 0x1234 }], + some [0xbeef]) + +-- A failed creation returns 0: CREATE2 never reverts the caller. +#guard call "deploy" 0 [Value.fixedBytes 32 0x1234] 0 == + ([{ kind := .create2, creator := self, value := 0, initCode := code, salt := some 0x1234 }], + some [0]) + +-- `deployWith(v, salt, code)`: the value, the uint256 salt and the init code are the arguments. +#guard call "deployWith" 5 [Value.word 5, Value.word 7, Value.bytes [1, 2, 3]] 0xcafe == + ([{ kind := .create2, creator := self, value := 5, initCode := [1, 2, 3], salt := some 7 }], + some [0xcafe]) + +-- Negative control: the request is the operands' and nothing else (another salt, another request). +#guard call "deploy" 0 [Value.fixedBytes 32 0x1235] 0xbeef != + ([{ kind := .create2, creator := self, value := 0, initCode := code, salt := some 0x1234 }], + some [0xbeef]) + +-- Negative control: `deploy` declared `view` creates an account, which SolidCore's checker rejects. +#guard match viewContract? with + | .error (.mutabilityViolation _) => true + | _ => false + +end SolidCore.Verify.Create2.Run diff --git a/Contracts/Create2/Source.lean b/Contracts/Create2/Source.lean new file mode 100644 index 00000000..b4f40a32 --- /dev/null +++ b/Contracts/Create2/Source.lean @@ -0,0 +1,56 @@ +-- Generated from Contracts/Create2/Deployer.sol with solc 0.8.35 by scripts/verify/create2_sources.py. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Verify +namespace Create2 +namespace Source + +def importedSourceName : String := "Contracts/Create2/Deployer.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Deployer" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "deploy", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "salt", ty := Ty.bytesN 32, location := none }], + returns := [{ name := some "a", ty := Ty.address false, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.varDecl [{ name := some "code", ty := Ty.bytes, location := some DataLocation.memory }] (some (Expr.literal (Literal.hexString "6001600c60003960016000f300"))), Stmt.assemblyCreate2 (Expr.ident "a") (Expr.literal (Literal.number "0")) (Expr.ident "code") (Expr.ident "salt")]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "deployWith", + visibility := some Visibility.external_, + mutability := StateMutability.payable, + params := [{ name := some "v", ty := Ty.uint 256, location := none }, { name := some "salt", ty := Ty.uint 256, location := none }, { name := some "code", ty := Ty.bytes, location := some DataLocation.memory }], + returns := [{ name := some "a", ty := Ty.address false, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.assemblyCreate2 (Expr.ident "a") (Expr.ident "v") (Expr.ident "code") (Expr.ident "salt")]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.0", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end Source +end Create2 +end Verify +end SolidCore diff --git a/Contracts/Create2/SourceView.lean b/Contracts/Create2/SourceView.lean new file mode 100644 index 00000000..934686db --- /dev/null +++ b/Contracts/Create2/SourceView.lean @@ -0,0 +1,56 @@ +-- Generated from Contracts/Create2/Deployer.sol with solc 0.8.35 by scripts/verify/create2_sources.py. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Verify +namespace Create2 +namespace SourceView + +def importedSourceName : String := "Contracts/Create2/Deployer.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Deployer" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "deploy", + visibility := some Visibility.external_, + mutability := StateMutability.view, + params := [{ name := some "salt", ty := Ty.bytesN 32, location := none }], + returns := [{ name := some "a", ty := Ty.address false, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.varDecl [{ name := some "code", ty := Ty.bytes, location := some DataLocation.memory }] (some (Expr.literal (Literal.hexString "6001600c60003960016000f300"))), Stmt.assemblyCreate2 (Expr.ident "a") (Expr.literal (Literal.number "0")) (Expr.ident "code") (Expr.ident "salt")]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "deployWith", + visibility := some Visibility.external_, + mutability := StateMutability.payable, + params := [{ name := some "v", ty := Ty.uint 256, location := none }, { name := some "salt", ty := Ty.uint 256, location := none }, { name := some "code", ty := Ty.bytes, location := some DataLocation.memory }], + returns := [{ name := some "a", ty := Ty.address false, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.assemblyCreate2 (Expr.ident "a") (Expr.ident "v") (Expr.ident "code") (Expr.ident "salt")]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.0", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end SourceView +end Create2 +end Verify +end SolidCore diff --git a/Contracts/Token/Assembly.lean b/Contracts/Token/Assembly.lean new file mode 100644 index 00000000..3826f5ab --- /dev/null +++ b/Contracts/Token/Assembly.lean @@ -0,0 +1,98 @@ +import SolidCore.Refinement.Solar.AssembleSim +import SolidCore.Refinement.Solar.AssembleFast +import verify_token.gen.Token.Evm12 +import verify_token.gen.Token.Bytecode +import verify_token.Proofs.Stages + +/-! +# solar-verify's Token: the final EVM IR to solar's bytecode + +solar compiles solar-verify's Token (Certified/verify_token/verify_token.sol, byte for byte +scripts/verify/Token.sol) to the final EVM IR evm12 (after `late-word`) and to 685 bytes of runtime +bytecode, both exported by -Zemit-lean-stages into Certified/verify_token/gen. Certified/verify_token +proves solar-tv's backend stages from the first lowered MIR stage0 to evm12 +(`SolarTV.Milestone.VerifyToken.verify_token_mir_to_evmir`); this file proves the last one, evm12 +to the bytecode, with the generic assembler check: the balances mapping's slots are KECCAK256 of the +key and slot 0 at constant offsets, `transfer`, `mint` and `burn` read CALLER, every jump goes to a +labelled block, and the checked arithmetic's panics and the reverts write memory below 128 bytes. + +* `check_ok`: the checker accepts evm12 and the bytes with `cert`, by the kernel's evaluation of its + one-pass form (`Assemble.checkFast`). +* `stageOk`: EVM IR to bytecode is a stage on every call, under every oracle whose caller and hash + are EthLib's (`Assemble.OracleOk`). +* `backend`: stage0 to the bytecode, on every call, under every such oracle. +* `mutant_check`: the checker rejects the bytecode with `transfer`'s dispatch jump retargeted. + +The certificate's numbers are not trusted: offsets are where the walk finds each block's +JUMPDEST, needs and types the lowest stack each block is entered with (all data), costs each +block's potential, and the checker re-derives every claim from them. +-/ + +namespace SolidCore.Refinement.Solar.VerifyTokenAsm + +open SolidCore.Refinement.Solar SolarTV.Export.Token + +/-- The runtime bytecode solar exported with the stages. -/ +def code : ByteArray := ⟨(bytecode.map UInt8.ofNat).toArray⟩ + +/-- The certificate: each block's offset in the code, the lowest stack height each block is +entered with (every entry word is data), the bound on memory (128 bytes), each block's potential +(the items any run from its entry executes, at most), and that the program reads the caller and +hashes. -/ +def cert : Assemble.Cert := + { offsets := [0, 0x47, 0x4b, 0x5d, 0x8f, 0x99, 0xa9, 0x10c, 0x11c, 0x12c, 0x134, 0x145, 0x149, + 0x159, 0x172, 0x1dd, 0x1ee, 0x1f8, 0x20f, 0x22a, 0x243, 0x27f, 0x293], + needs := [0, 0, 3, 1, 1, 1, 1, 3, 5, 2, 4, 4, 3, 4, 1, 2, 4, 7, 7, 7, 1, 3, 5], + top := 128, + costs := [142, 3, 9, 56, 7, 11, 85, 19, 14, 5, 19, 16, 13, 27, 105, 23, 20, 21, 31, 31, 61, + 20, 28], + types := [0, 0, 3, 1, 1, 1, 1, 3, 5, 2, 4, 4, 3, 4, 1, 2, 4, 7, 7, 7, 1, 3, 5].map + (fun n => List.replicate n (some false)), + env := true } + +set_option maxRecDepth 100000 in +/-- The checker accepts solar's bytecode for evm12, by the kernel's evaluation. -/ +theorem check_ok : Assemble.check evm12 code cert = true := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +/-- EVM IR to bytecode is a stage on every call, under every oracle whose caller and hash are +EthLib's. -/ +theorem stageOk (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) + (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.evmirSem o) SolidCore.Refinement.ethLib evm12 + (show SolidCore.Refinement.ethLib.Prog from code) scope := + Assemble.stage_of_check_env check_ok o (fun _ => ho) scope + +/-- The backend: solar-tv's stages from stage0 to evm12, then the assembly stage, on every call +(any calldata, mapping keys, value and storage), under every oracle with EthLib's caller and +hash. -/ +theorem backend (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) + (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.mirSem o) SolidCore.Refinement.ethLib stage0 + (show SolidCore.Refinement.ethLib.Prog from code) scope := + SolarTV.Stage.trans (B := SolarTV.evmirSem o) + (fun call _ => SolarTV.Milestone.VerifyToken.verify_token_mir_to_evmir o call trivial) + (stageOk o ho scope) + +/-- The bytecode with `transfer`'s dispatch (`PUSH2 0x0172` at byte 0x43) sent to block 13's +JUMPDEST (0x0159) instead. -/ +def mutant : ByteArray := ⟨((bytecode.set 0x45 0x59).map UInt8.ofNat).toArray⟩ + +set_option maxRecDepth 100000 in +/-- The checker rejects the retargeted jump: the walk finds a push of 0x0159 where the layout +puts block 14 at 0x0172. -/ +theorem mutant_check : Assemble.check evm12 mutant cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +/-- info: 'SolidCore.Refinement.Solar.VerifyTokenAsm.check_ok' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms check_ok + +/-- info: 'SolidCore.Refinement.Solar.VerifyTokenAsm.backend' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms backend + +end SolidCore.Refinement.Solar.VerifyTokenAsm + diff --git a/Contracts/Token/Discharge.lean b/Contracts/Token/Discharge.lean new file mode 100644 index 00000000..dc42742c --- /dev/null +++ b/Contracts/Token/Discharge.lean @@ -0,0 +1,121 @@ +import Contracts.Token.VC.Transfer + +/-! +# Token.transfer's obligations, discharged in Lean + +`transfer_triple` takes solar-verify's verdict `Valid Export.Token.script` and reads each of +`transfer`'s three clauses off the obligation the checked script gives (`checkScript_sound`). The three +obligations `trObs` it uses hold in the array theory on their own: `trObs_valid` proves them for +every assignment, by the semantics of `select` and `store` (no solver, no verdict). So +`transfer_triple_discharged` is `transfer_triple` with the verdict gone: its one hypothesis is `HashInj`, +injectivity of the mapping slot on address keys. `transfer_check` (the kernel's check that solar-verify's +script has these obligations) still ties them to solar-verify's encoding of the clauses. +-/ + +namespace SolidCore.Verify.VC.Token + +open SolidCore.Verify SolidCore.Verify.VC SolidCore.Refinement SolidCore.Refinement.Abi +open SolidCore.Refinement.Generic + +/-- `transfer`'s three obligations hold at every assignment of the array theory. -/ +theorem trObs_valid : ObsValid trObs := by + intro o ho σ _ + simp only [trObs, List.mem_cons, List.mem_nil_iff, or_false] at ho + rcases ho with rfl | rfl | rfl + · simp only [trGoalFrom] + simp [Tm.Holds, Tm.eval, Tm.evalList, applyOp, Value.select, Value.store, Value.toProp, Value.toInt, Value.toArr, Value.eq, Ob.eq, Ob.sel, Ob.sub, Ob.add, Ob.S2, Ob.S1, Ob.sto, Ob.ms, Ob.rcpt, Ob.B, Ob.bal, Ob.amt] + intro h1 h2 + exact absurd h2 h1 + · simp only [trGoalTo] + simp [Tm.Holds, Tm.eval, Tm.evalList, applyOp, Value.select, Value.store, Value.toProp, Value.toInt, Value.toArr, Value.eq, Ob.eq, Ob.sel, Ob.sub, Ob.add, Ob.S2, Ob.S1, Ob.sto, Ob.ms, Ob.rcpt, Ob.B, Ob.bal, Ob.amt] + intro h + exact ite_cond_eq_false _ _ (eq_false (Ne.symm h)) + · simp only [trGoalFrame] + simp [Tm.Holds, Tm.eval, Tm.evalList, applyOp, Value.select, Value.store, Value.toProp, Value.toInt, Value.toArr, Value.eq, Ob.eq, Ob.sel, Ob.sub, Ob.add, Ob.S2, Ob.S1, Ob.sto, Ob.ms, Ob.rcpt, Ob.B, Ob.bal, Ob.amt] + intro n _ _ h1 h2 + simp only [Env.setI] at * + simp_all + + +/-- The goal of one of `transfer`'s obligations at `trEnv`, with no verdict. -/ +theorem tr_obligation_discharged {φ : Tm} (hφ : (trHyps, φ) ∈ trObs) + {s : Storage} (hs : ∀ k, s k < 2 ^ 256) {t a : Nat} (hta : t < 2 ^ 160) (ha : a < 2 ^ 256) + (hle : a ≤ s senderSlot) (hov : midTo t a s + a < 2 ^ 256) : φ.Holds (trEnv t a s) := + trObs_valid _ hφ _ (trHyps_hold s hs t a hta ha hle hov) + +/-- `Token.transfer` meets its three ensures clauses on distinct addresses on the stage's scope, +given only injectivity of the mapping slot on address keys. -/ +theorem transfer_triple_discharged (inj : HashInj) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Triple fuel c (stageScope fnTransfer [(2, 4096)]) (fun _ => True) trPost := by + have hdep := burnShape_eq + simp only [burnShape?, hc, Option.some.injEq, Prod.mk.injEq] at hdep + obtain ⟨d, hd⟩ := Wide.deployedAt_of hdep.1 + have hshape := transferShape_eq + simp only [transferShape?, hc, Option.some.injEq, Option.map_eq_some_iff, Prod.mk.injEq] at hshape + obtain ⟨f, hf, hlen, hT⟩ := hshape + have himpl := implements_tree (fn := fnTransfer) hd (by decide) hf hlen hT rfl + apply triple_of_wp himpl + rintro _ ⟨σ, hcov, fn', hfn', args, hl, hargs, rfl⟩ - + simp only [List.mem_singleton] at hfn' + subst hfn' + obtain ⟨t, a, rfl⟩ : ∃ t a, args = [t, a] := by + match args, hl with + | [t, a], _ => exact ⟨t, a, rfl⟩ + have ht : t < 2 ^ 256 := hargs t (by simp) + have ha : a < 2 ^ 256 := hargs a (by simp) + have hw : argWords 2 ({ calldata := Abi.calldata fnTransfer.sel [t, a], callvalue := 0, storage := σ } : Call) = + [t, a] := argWords_calldata _ [t, a] hargs 0 σ + rw [vc_eq, treeModel_run, show fnTransfer.params.length = 2 from rfl, hw] + set s := initStorage ({ calldata := Abi.calldata fnTransfer.sel [t, a], callvalue := 0, storage := σ } : Call) + with hs_def + have hs : ∀ k, s k < 2 ^ 256 := fun k => Generic.slotValue_lt σ k + unfold resOutcome + split + · next hok => + intro _ + obtain ⟨hta, hle, hov, -⟩ := tr_success inj s hs t a ht ha hok + have hb := trStore_eval inj s hs t a ht ha hok + have hcw : (callerWord : Int) = 8192 := rfl + have h8 : balArr s 8192 = (s senderSlot : Int) := balArr_caller s + have hob := fun φ (hφ : (trHyps, φ) ∈ trObs) => tr_obligation_discharged hφ hs hta ha hle hov + have gFrom := hob trGoalFrom (by simp [trObs]) + have gTo := hob trGoalTo (by simp [trObs]) + have gFrame := hob trGoalFrame (by simp [trObs]) + obtain ⟨f2, hf2⟩ : ∃ f, Ob.S2.eval (trEnv t a s) = .arr f := + ⟨_, Value.sortOf_arr (Tm.eval_sortOf _ _ (by decide))⟩ + simp only [trGoalFrom, trGoalTo, trGoalFrame, Tm.Holds, Tm.eval, Tm.evalList, applyOp, Value.select, Value.store, + Value.toProp, Value.toInt, Value.toArr, Value.eq, Ob.eq, Ob.sel, Ob.sub, Ob.add, Ob.le0, + Ob.leA, Ob.bal, Ob.B, Ob.ms, Ob.amt, Ob.rcpt, S2_setI, hf2] at gFrom gTo gFrame + simp only [observe, hw, List.getD_cons_zero, List.getD_cons_succ] + rw [← hs_def] + have hsl : solHash callerWord 0 = senderSlot := hash_eq + refine ⟨fun hne => ?_, fun hne => ?_, fun x hx hx8 hxt => ?_⟩ + · have e : (((transferTree.eval (valOf [t, a] s)).store senderSlot : Nat) : Int) = + (Ob.S2.eval (trEnv t a s)).toArr 8192 := by + have := hb callerWord (by decide); rwa [hsl] at this + have g := gFrom (by simp; omega) + simp [h8] at g + simp only [hf2, Value.toArr] at e g + rw [hsl] + omega + · have e := hb t hta + have g := gTo (by simp; omega) + simp [balArr_nat] at g + simp only [hf2, Value.toArr] at e g + omega + · have e := hb x hx + have hx8' : ¬ (x : Int) = 8192 := by intro h; apply hx8; exact_mod_cast h + have hxt' : ¬ (x : Int) = t := by omega + have hxA : (x : Int) ≤ 1461501637330902918203684832716283019655932542975 := by omega + have g := gFrame x + simp [balArr_nat, hx8', hxt', hxA, S2_setI] at g + simp only [hf2, Value.toArr] at e g + omega + · intro h; simp_all [observe] + +/-- info: 'SolidCore.Verify.VC.Token.transfer_triple_discharged' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms transfer_triple_discharged + +end SolidCore.Verify.VC.Token diff --git a/Contracts/Token/EndToEnd.lean b/Contracts/Token/EndToEnd.lean new file mode 100644 index 00000000..1bdfbf95 --- /dev/null +++ b/Contracts/Token/EndToEnd.lean @@ -0,0 +1,131 @@ +import Contracts.Token.Lowering +import Contracts.Token.Assembly +import Contracts.Token.Discharge +import SolidCore.Refinement.Keccak.TwoWords +import SolidCore.Refinement.Solar.Hex +import verify_token.gen.Token.Manifest + +/-! +# solar-verify's Token: its spec holds of solar's bytecode + +solar-verify's Token (scripts/verify/Token.sol, compiled by solar as +Certified/verify_token/verify_token.sol, the same bytes) from its checked obligations to the 685 +bytes of runtime bytecode solar emits for it, every step a theorem: + +1. the source stage (Lowering.lean): SolidCore's checked Token to solar's first lowered MIR + stage0, by the generic check, for `transfer`, `burn`, `mint`, `totalSupply` and `owner`; +2. solar-tv's backend stages from stage0 to the final EVM IR evm12 (Certified/verify_token) and the + assembly stage from evm12 to the bytecode (Assembly.lean); +3. solar-verify's triples of SolidCore's Token (Contracts/Token/VC): `burn_triple`, with no + hypothesis, and `transfer_triple_discharged` (Discharge.lean: the obligations the kernel checks + solar-verify's script has, proved in Lean), whose one hypothesis is injectivity of the mapping + slot on address keys. + +The stages hold under every oracle with EthLib's caller and Keccak-256 (`oracle` is one, and the +source stage's hash of two words is EthLib's by `Keccak.ethKeccak_twoWords`), so the composition +is about EthLib's run of the bytes alone (`Target.run`). + +* `burn_spec_bytecode`: on every call of `burn(uint256)` in solar-verify's binding scope (any argument + word, no value, any storage that writes `owner`'s slot), EthLib runs the bytecode to an observable + that meets `burnPost` (on success the caller's balance and the total supply drop by the + amount). No hypothesis. +* `spec_holds_of_bytecode`: the same for `transfer(address,uint256)`'s three ensures clauses on + distinct addresses (`trPost`) and for `burn`, given `HashInj` alone (an explicit + hypothesis, never an axiom; no solver verdict). +* `certified`: the stage from SolidCore's checked Token to the bytecode for each checked function, + `mint` included; `manifest_hex`: the bytes are the exporter's manifest hex. + +Negatives: the source check rejects a `transfer` that drops the recipient's credit and a `burn` that +writes the supply to `owner`'s slot (`VerifyTokenSource.check_rejects_*`), the assembly check rejects a +retargeted dispatch jump (`VerifyTokenAsm.mutant_check`), and solar-verify's checked script rejects +source and spec mutants (Contracts/Token/VC/Mutants.lean). Not covered: deployment (the constructor), +gas limits other than EthLib's default, calls with value, and the getter `balanceOf` (a public +mapping getter, outside the generic source stage's fragment). +-/ + +namespace Contracts.Token + +open SolidCore.Refinement SolidCore.Refinement.Solar SolidCore.Verify SolidCore.Verify.VC +open SolidCore.Verify.VC.Token +open SolidCore.Refinement.Solar.VerifyTokenSource (stage checkOn check_transfer_eq check_burn_eq + check_mint_eq contract_ok) +open SolidCore.Refinement.Solar.VerifyTokenAsm (code backend) +open SolarTV.Export.Token (stage0) + +/-- The oracle with EthLib's caller and Keccak-256, every other field constant. -/ +def oracle : SolarTV.Machine.Oracle := + { env := fun _ _ _ => 0, result := fun _ => 0, storageAfter := fun _ _ => 0, + transientAfter := fun _ _ => 0, + keccak := fun bytes => EthLib.Execution.Evm.keccak ⟨(bytes.map UInt8.ofBitVec).toArray⟩, + caller := BitVec.ofNat 160 SolidCore.Refinement.callerAddress } + +/-- Its caller is SolidCore's and its hash of two words SolidCore's slot hash. -/ +theorem oracle_sourceEnvOk : Generic.SourceEnvOk oracle := + ⟨by unfold Generic.CallerOk; decide +kernel, + fun a b _ _ => SolidCore.Refinement.Keccak.ethKeccak_twoWords a b⟩ + +/-- Its caller and hash are EthLib's. -/ +theorem oracle_ok : Assemble.OracleOk oracle := + ⟨show (BitVec.ofNat 160 callerAddress).setWidth 256 = (Target.address callerAddress).toU256 by + decide +kernel, fun _ => rfl⟩ + +/-- **SolidCore's checked Token to solar's bytecode**, for each function the source check accepts, +on solar-verify's binding scope. -/ +theorem certified {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) + {fn : SolidCore.Refinement.Abi.Fn} (h : checkOn stage0 fn = some true) : + SolarTV.Stage (solidCore fuel) ethLib c code (stageScope fn [(2, 4096)]) := + SolarTV.Stage.trans (stage oracle oracle_sourceEnvOk hc h) (backend oracle oracle_ok _) + +/-- A total-correctness triple of SolidCore's Token on a checked function holds of the bytecode. -/ +theorem bytecode_of_triple {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : contract? = .ok c) {fn : SolidCore.Refinement.Abi.Fn} (h : checkOn stage0 fn = some true) + {post : Call → Observable → Prop} + (ht : Triple fuel c (stageScope fn [(2, 4096)]) (fun _ => True) post) : + ∀ call, stageScope fn [(2, 4096)] call → + ∃ obs, Target.run code call = some obs ∧ post call obs := by + intro call hs + obtain ⟨hsome, hpost⟩ := ht call hs trivial + obtain ⟨obs, hobs⟩ := Option.isSome_iff_exists.mp hsome + exact ⟨obs, certified hc h call hs obs hobs, hpost obs hobs⟩ + +/-- **Token's `burn` on solar's bytecode**, with no hypothesis: every call of `burn(uint256)` in +solar-verify's binding scope runs, under EthLib, to an observable meeting `burnPost`. -/ +theorem burn_spec_bytecode : + ∀ call, stageScope fnBurn [(2, 4096)] call → + ∃ obs, Target.run code call = some obs ∧ burnPost call obs := by + obtain ⟨c, hc⟩ := contract_ok + exact bytecode_of_triple hc (fn := fnBurn) check_burn_eq (burn_triple hc) + +/-- **solar-verify's spec of Token holds of solar's bytecode**: given injectivity of the mapping slot +on address keys (Keccak-256 of an address and slot 0), every call of +`transfer(address,uint256)` in the binding scope runs under EthLib to an observable meeting +`transfer`'s ensures clauses on distinct addresses, and every call of `burn` to one meeting +`burn`'s. -/ +theorem spec_holds_of_bytecode (inj : HashInj) : + (∀ call, stageScope fnTransfer [(2, 4096)] call → + ∃ obs, Target.run code call = some obs ∧ trPost call obs) ∧ + (∀ call, stageScope fnBurn [(2, 4096)] call → + ∃ obs, Target.run code call = some obs ∧ burnPost call obs) := by + obtain ⟨c, hc⟩ := contract_ok + exact ⟨bytecode_of_triple hc (fn := fnTransfer) check_transfer_eq (transfer_triple_discharged inj hc), + burn_spec_bytecode⟩ + +open SolarTV.Export.Token Hex in +set_option maxRecDepth 100000 in +/-- The manifest's hex is the lowercase hex of the bytes the stages run. -/ +theorem manifest_hex : Manifest.bytecodeHex = String.ofList (hexChars bytecode) := by rfl + +/-- info: 'Contracts.Token.certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms certified + +/-- info: 'Contracts.Token.burn_spec_bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms burn_spec_bytecode + +/-- info: 'Contracts.Token.spec_holds_of_bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms spec_holds_of_bytecode + +end Contracts.Token + diff --git a/Contracts/Token/Exports.lean b/Contracts/Token/Exports.lean new file mode 100644 index 00000000..38d9229f --- /dev/null +++ b/Contracts/Token/Exports.lean @@ -0,0 +1,78 @@ +import Contracts.Token.EndToEnd +import Contracts.Token.Spec.Export +import Verify.Final + +/-! +# Token's exports, by name + +The Lean targets the exporters write for Token, under one name each, as the certify driver names +them for every contract: + +* \`code\`: solar's runtime bytecode (Certified/verify_token, \`VerifyTokenAsm.code\`), and \`manifest\` + the exporter's manifest of it (\`manifest_hex\`: its hex is the bytes'; \`export_bound\`: the spec + export names the same SHA-256); +* \`spec\`: solar-verify's \`--emit-lean-spec\` export of scripts/verify/Token.sol + (Contracts/Token/Spec/Export.lean, \`Token_wf\` checked by the kernel); +* \`contract\`: SolidCore's checked Token (\`contract_eq\`), \`fuel\` its source stage's fuel; +* \`scope\`: the calls the end-to-end theorem covers, \`transfer\` and \`burn\` in solar-verify's binding + scope (\`spec_holds_of_bytecode\`); +* \`ctxOf\`: the call context of SolidCore's and EthLib's interface; \`step\`: the ghost \`sumBalances\` + as the source's ghost updates write it (\`mint\` adds its amount, \`burn\` takes it away). +-/ + +namespace Contracts.Token + +open SolidCore.Refinement SolidCore.Verify.VC SolidCore.Verify.VC.Token + +/-- solar's runtime bytecode for Token. -/ +abbrev code : ByteArray := SolidCore.Refinement.Solar.VerifyTokenAsm.code + +/-- solar-verify's exported spec of Token. -/ +abbrev spec : SolidCore.Spec.Bundle := SolidCore.Spec.Export.Token.Token + +/-- The exporter's manifest of the bytecode. -/ +def manifest : SolidCore.Refinement.Final.Manifest where + contract := "Token" + sourceSha256 := (SolarTV.Export.Token.Manifest.sources.headD ("", "")).2 + compilerCommit := SolarTV.Export.Token.Manifest.compiler + options := SolarTV.Export.Token.Manifest.arguments + runtimeHex := SolarTV.Export.Token.Manifest.bytecodeHex + runtimeSha256 := SolarTV.Export.Token.Manifest.bytecodeSha256 + +/-- The spec export names the bytecode of the manifest. -/ +theorem export_bound : SolidCore.Spec.Export.Token.manifest.bytecodeSha256 = manifest.runtimeSha256 := by + decide +kernel + +/-- SolidCore's checked Token. -/ +noncomputable def contract : SolidCore.Solidity.TypeCheck.CheckedContract := + Classical.choose SolidCore.Refinement.Solar.VerifyTokenSource.contract_ok + +theorem contract_eq : SolidCore.Verify.VC.Token.contract? = .ok contract := + Classical.choose_spec SolidCore.Refinement.Solar.VerifyTokenSource.contract_ok + +/-- The source stage's fuel. -/ +abbrev fuel : Nat := SolidCore.Verify.VC.Token.fuel + +/-- The calls the end-to-end theorem covers. -/ +def scope (call : Call) : Prop := + stageScope fnTransfer [(2, 4096)] call ∨ stageScope fnBurn [(2, 4096)] call + +/-- The call context of SolidCore's and EthLib's interface (\`Refinement.Statement\`): sender +\`0x2000\`, the contract at \`0x1000\`, block timestamp 1. -/ +def ctxOf (call : Call) : SolidCore.Spec.Ctx := + { sender := 0x2000, value := call.callvalue, timestamp := 1, self := 0x1000 } + +/-- The word at argument \`i\` of a call. -/ +def argWord (call : Call) (i : Nat) : Int := + ((SolidCore.Spec.words ((call.calldata.data.toList.map (·.toNat)).drop 4)).getD i 0 : Nat) + +/-- The ghost \`sumBalances\` after a call: \`mint(address,uint256)\` adds its amount and +\`burn(uint256)\` takes its amount away, as the source's ghost updates write it. -/ +def step : SolidCore.Spec.GhostStep := fun call g name keys => + if name = "sumBalances" ∧ keys = [] then + if SolidCore.Spec.selectorOf call = 0x40c10f19 then g name keys + argWord call 1 + else if SolidCore.Spec.selectorOf call = 0x42966c68 then g name keys - argWord call 0 + else g name keys + else g name keys + +end Contracts.Token diff --git a/Contracts/Token/HashScope.lean b/Contracts/Token/HashScope.lean new file mode 100644 index 00000000..f41dc470 --- /dev/null +++ b/Contracts/Token/HashScope.lean @@ -0,0 +1,101 @@ +import Verify.Spec.HashScope +import Contracts.Token.TransferMeets +import Contracts.Token.Spec.ExportCollide + +/-! +# Token's `transfer` under keccak256 separation scoped to the call's footprint + +The single-level instance of Verify/Spec/HashScope.lean: `transfer(to, amount)` touches `balanceOf` +(slot 0) at the caller and at `to`, so its premise is `ScopedSep (transferFootprint 0 caller to)`: +keccak256 injective and at least `2 ^ 128` on those two preimages, nothing about any other key. + +* `collide_not_meets_scoped` (negative control): the collision spec of + scripts/verify/keccak/TokenSpecCollide.sol (`balanceOf[to] == old(balanceOf[msg.sender]) + amount`, + true only if the two slots coincide) fails on `transfer(1, 0)` under that call's premise. +* `transferFP_real`: that premise holds of the real keccak256 (kernel evaluation), so + `collide_refuted` refutes the collision spec with no hypothesis left. + +The legacy exported spec of Token's `transfer` (Spec/Export.lean) frames `balanceOf` at every other +address, which needs separation from every key; CERTIFICATION_TARGET.md (a1c3143) rules that frame +out, so it is not proved here under the scoped premise. +-/ + +namespace SolidCore.Spec.TreeDemo.Token + +open SolidCore.Spec SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Verify.VC.Token + +/-- The call's premise: keccak256 separated on `transfer`'s footprint, `balanceOf` (slot 0) of the +caller (`ctx`'s sender, `0x2000`) and of `to` (argument 0). Nothing about any other key. -/ +abbrev TransferFP (args : List Nat) : Prop := + ScopedSep (transferFootprint 0 8192 (args.getD 0 0 % 2 ^ 160)) + +/-- The collision spec of `transfer`. -/ +def collideSpec : FnSpec := SolidCore.Spec.Export.TokenSpecCollide.Token.spec.specs[1]'(by decide) + +/-- The witness storage: the caller's balance is 5, every other slot 0. -/ +def collideStore : Storage := fun k => if k = solHash 8192 0 then 5 else 0 + +set_option linter.unusedSimpArgs false in +/-- **A spec that needs a collision is refuted under the scoped premise**: with the premise of +`transfer(1, 0)`, that call from `collideStore` succeeds with `balanceOf[1]` still 0, and the +collision spec asks for the caller's old balance, 5. -/ +theorem collide_not_meets_scoped (hP : TransferFP [1, 0]) : + ¬ TreeMeetsFixedOn (fun ρ => TransferFP ρ.args) SolidCore.Spec.Export.TokenSpecCollide.Token + collideSpec ctx 2 transferTree := by + intro h + have hP' : ScopedSep (transferFootprint 0 8192 1) := by simpa [TransferFP] using hP + obtain ⟨hne', hge0, -⟩ := transfer_slots hP' (by decide) (by decide) (by decide) + have hne : solHash 1 0 ≠ solHash 8192 0 := fun he => hne' (by decide) he.symm + have hs : ∀ k, collideStore k < 2 ^ 256 := fun k => by unfold collideStore; split <;> omega + have h1 : (1 : Nat) ≠ solHash 8192 0 := by omega + have hp := h [1, 0] collideStore [1, 0] ⟨collideStore, Ghost.zero, 0⟩ rfl (by simp) hs + (by simp [collideSpec, SolidCore.Spec.Export.TokenSpecCollide.Token, decodeWords, Ty.ofWord]) rfl + (by simp [ctx]) (by simp [Bundle.satAll, collideSpec, SolidCore.Spec.Export.TokenSpecCollide.Token]) + (by simp [Bundle.satAll, Bundle.sat, SolidCore.Spec.Export.TokenSpecCollide.Token, eval, slotOf, mkEnv, + Env.cur, Ghost.zero, BinOp.apply, Ty.ofBits, collideStore, h1]) + (by simpa [TransferFP] using hP) + have hlt := solHash_lt' + have hkec := keccak_solHash + unfold collideStore at hp + generalize solHash = H at hp hlt hkec hge0 hne + simp only [transferTree, Tree.eval, WExpr.eval, BinOp.eval, UnOp.eval, Generic.wordSize, Res.obs, + Writes.store, List.getD_cons_zero, List.getD_cons_succ, Nat.reducePow, Nat.reduceMod, Nat.zero_mod, + Nat.reduceLT, ite_mod_nat, ite_true, ite_false, Nat.lt_irrefl, Nat.not_lt_zero, decide_false, + Nat.reduceAdd, Nat.reduceSub, Nat.zero_add, Nat.add_zero, ite_self, Nat.one_ne_zero, ite_false, + Nat.reduceEqDiff, reduceIte, hne, if_true, if_false] at hp + obtain ⟨rets, -, hens, -⟩ := hp.1 (by simp_all) + simp only [Bundle.satAll, Bundle.sat, collideSpec, SolidCore.Spec.Export.TokenSpecCollide.Token, + List.getElem_cons_succ, List.getElem_cons_zero, List.mem_cons, List.not_mem_nil, or_false, + forall_eq_or_imp, forall_eq, eval, evalList, slotOf, mkEnv, Env.cur, Env.bind, BinOp.apply, Ty.ofBits, + toWord, ctx, List.getD_cons_zero, List.getD_cons_succ, hkec, ofProp_ne_zero, ite_true, ite_false, + Nat.zero_div, Nat.zero_mod, Int.reduceMod, Int.reduceToNat] at hens + have hm1 := Nat.mod_eq_of_lt (hlt 1 0) + have hm2 := Nat.mod_eq_of_lt (hlt 8192 0) + simp_all + +/-- **The premise of `transfer(1, ·)` from `ctx`'s caller holds of the real keccak256**: the +caller's and address 1's `balanceOf` slots hash apart, both at least `2 ^ 128` (kernel evaluation of +the sponge, TrustedBase.image1 and image2). So `collide_not_meets_scoped`'s hypothesis is satisfiable. -/ +theorem transferFP_real : TransferFP [1, 0] := by + have e1 := TrustedBase.image1 + have e2 := TrustedBase.image2 + refine ⟨fun x y hx hy he => ?_, fun x hx => ?_⟩ + · simp only [transferFootprint, List.getD_cons_zero, List.mem_cons, List.not_mem_nil, or_false, + show (8192 : Nat) = 0x2000 from rfl, show (1 % 2 ^ 160 : Nat) = 1 from rfl] at hx hy + rcases hx with rfl | rfl <;> rcases hy with rfl | rfl <;> + first | rfl | (rw [e1, e2] at he; exact absurd he (by decide)) | (rw [e2, e1] at he; exact absurd he (by decide)) + · simp only [transferFootprint, List.getD_cons_zero, List.mem_cons, List.not_mem_nil, or_false, + show (8192 : Nat) = 0x2000 from rfl, show (1 % 2 ^ 160 : Nat) = 1 from rfl] at hx + rcases hx with rfl | rfl + · rw [e2]; decide + · rw [e1]; decide + +theorem collide_refuted : ¬ TreeMeetsFixedOn (fun ρ => TransferFP ρ.args) + SolidCore.Spec.Export.TokenSpecCollide.Token collideSpec ctx 2 transferTree := + collide_not_meets_scoped transferFP_real + +/-- info: 'SolidCore.Spec.TreeDemo.Token.collide_refuted' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms collide_refuted + +end SolidCore.Spec.TreeDemo.Token diff --git a/Contracts/Token/Lowering.lean b/Contracts/Token/Lowering.lean new file mode 100644 index 00000000..0eecaa38 --- /dev/null +++ b/Contracts/Token/Lowering.lean @@ -0,0 +1,141 @@ +import Contracts.Token.VC.Transfer +import SolidCore.Refinement.Generic.Stage +import verify_token.gen.Token.Stage0 + +/-! +# solar-verify's Token: the generic source stage to solar's first lowered MIR + +SolidCore's checked `Token` (`SolidCore.Verify.VC.Token.contract?`, solc 0.8.35's AST of +scripts/verify/Token.sol through scripts/solc_ast_to_lean_source.py into Contracts/Token/VC/Source.lean; +Certified/verify_token/verify_token.sol is the same file byte for byte) against +`SolarTV.Export.Token.stage0`, solar's first lowered MIR module of that source after +`lower-evm-shaped` (Certified/verify_token/gen, -Ogas, osaka), the module Certified/verify_token's +backend stages start from. + +`Generic.check` erases each external function of the SolidCore contract to a tree, runs the module +symbolically on its selector with the environment flags (the caller is `callerWord`, a mapping slot +the word `solHash key slot`), and compares the trees in canonical form. The kernel evaluates it +from the source text up (`kernel_rfl`, with the selectors and the hash-map index by table, each +entry checked against Keccak-256 or its definition once), one function at a time. + +* `check_*_eq`: the check accepts stage0 for `transfer`, `burn` and the other external functions. +* `stage`: for each of them, the stage from SolidCore to stage0 on solar-verify's binding scope + `stageScope fn [(2, 4096)]` (any argument words, no value, any storage that writes the slot the + constructor wrote), under every oracle with SolidCore's caller and hash of two words. +* `check_rejects_*`: the check rejects stage0 with `transfer`'s recipient credit dropped and with + `burn`'s total-supply write sent to another slot. +-/ + +namespace SolidCore.Refinement.Solar.VerifyTokenSource + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Generic +open SolidCore.Solidity SolidCore.Verify.VC.Token +open SolarTV.Export.Token (stage0) + +/-- The steps along each path of the symbolic run of the module. -/ +def mirFuel : Nat := 40 + +/-- `balanceOf(address)`, the mapping's getter, as the stage's ABI sees it. -/ +def fnBalanceOf : Fn := ⟨balanceofSel, [.uint 256]⟩ + +/-- `totalSupply()`. -/ +def fnTotalSupply : Fn := ⟨totalsupplySel, []⟩ + +/-- `owner()`. -/ +def fnOwner : Fn := ⟨ownerSel, []⟩ + +/-- `mint(address,uint256)`. -/ +def fnMint : Fn := ⟨mintSel, [.uint 256, .uint 256]⟩ + +/-- Whether the generic check accepts stage0 for `fn` against SolidCore's checked `Token`. -/ +def checkOn (m : SolarTV.MIR.Lowered.Module) (fn : Fn) : Option Bool := + match contract? with + | .ok c => some (Generic.check fuel mirFuel c.core m [fn] .all) + | .error _ => none + + + +/-- The check on stage0, for each function. -/ +def transferOk? : Option Bool := checkOn stage0 fnTransfer +def burnOk? : Option Bool := checkOn stage0 fnBurn +def mintOk? : Option Bool := checkOn stage0 fnMint +def totalSupplyOk? : Option Bool := checkOn stage0 fnTotalSupply +def ownerOk? : Option Bool := checkOn stage0 fnOwner + +-- Each by the kernel's conversion check, from the source text up. +kernel_rfl check_transfer_eq transferOk? (some true) using SolidCore.Verify.VC.Token.selector_eq SolidCore.Verify.VC.mkIdx_eq +kernel_rfl check_burn_eq burnOk? (some true) using SolidCore.Verify.VC.Token.selector_eq SolidCore.Verify.VC.mkIdx_eq +kernel_rfl check_mint_eq mintOk? (some true) using SolidCore.Verify.VC.Token.selector_eq SolidCore.Verify.VC.mkIdx_eq +kernel_rfl check_totalSupply_eq totalSupplyOk? (some true) using SolidCore.Verify.VC.Token.selector_eq SolidCore.Verify.VC.mkIdx_eq +kernel_rfl check_owner_eq ownerOk? (some true) using SolidCore.Verify.VC.Token.selector_eq SolidCore.Verify.VC.mkIdx_eq + +/-! ## Mutants the check rejects -/ + +/-- stage0 with each instruction of function `i` changed by `f`. -/ +def mapFn (i : Nat) (f : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst) : + SolarTV.MIR.Lowered.Module := + { stage0 with + functions := stage0.functions.mapIdx fun j fn => + if j = i then { fn with blocks := fn.blocks.map fun b => { b with insts := b.insts.map f } } + else fn } + +/-- `transfer` storing the recipient's old balance back instead of the credited one. -/ +def dropCredit : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect none .sstore [.value 58, .value 27] => .effect none .sstore [.value 58, .value 20] + | i => i + +/-- `burn` writing the new total supply to slot 2 (`owner`) instead of slot 1. -/ +def wrongSupplySlot : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect none .sstore [.const 1, .value 18] => .effect none .sstore [.const 2, .value 18] + | i => i + +def transferMutantOk? : Option Bool := checkOn (mapFn 5 dropCredit) fnTransfer +def burnMutantOk? : Option Bool := checkOn (mapFn 6 wrongSupplySlot) fnBurn + +kernel_rfl check_rejects_dropCredit transferMutantOk? (some false) using SolidCore.Verify.VC.Token.selector_eq SolidCore.Verify.VC.mkIdx_eq +kernel_rfl check_rejects_wrongSupplySlot burnMutantOk? (some false) using SolidCore.Verify.VC.Token.selector_eq SolidCore.Verify.VC.mkIdx_eq + +/-! ## The stage -/ + +theorem check_of {fn : Fn} {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) + (h : checkOn stage0 fn = some true) : + Generic.check fuel mirFuel c.core stage0 [fn] .all = true := by + simp only [checkOn, hc, Option.some.injEq] at h + exact h + +/-- The constructor leaves `owner` (slot 2) as SolidCore's deployer, 4096, and no logs. -/ +theorem deployed {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + ∃ d, Wide.DeployedAt fuel c d [(2, 4096)] := by + have hshape := burnShape_eq + simp only [burnShape?, hc, Option.some.injEq, Prod.mk.injEq] at hshape + exact Wide.deployedAt_of hshape.1 + +/-- **The source stage of solar-verify's Token**, for a function the check accepts: every call of +solar-verify's binding scope `stageScope fn [(2, 4096)]` (any argument words, no value, any storage +that writes slot 2) that SolidCore finishes, stage0 finishes the same way, under every oracle with +SolidCore's caller and hash of two words. -/ +theorem stage (o : SolarTV.Machine.Oracle) (henv : SourceEnvOk o) {c : TypeCheck.CheckedContract} + (hc : contract? = .ok c) {fn : Fn} (h : checkOn stage0 fn = some true) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c stage0 + (SolidCore.Verify.VC.stageScope fn [(2, 4096)]) := by + obtain ⟨d, hd⟩ := deployed hc + exact Generic.stageAtEnv o henv hd (check_of hc h) + +/-- SolidCore type checks solar-verify's Token. -/ +theorem contract_ok : ∃ c, contract? = .ok c := by + have hshape := burnShape_eq + unfold burnShape? at hshape + split at hshape + · next c hc => exact ⟨c, hc⟩ + · simp at hshape + +/-- info: 'SolidCore.Refinement.Solar.VerifyTokenSource.check_transfer_eq' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms check_transfer_eq + +/-- info: 'SolidCore.Refinement.Solar.VerifyTokenSource.stage' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage + +end SolidCore.Refinement.Solar.VerifyTokenSource + diff --git a/Contracts/Token/LoweringIn.lean b/Contracts/Token/LoweringIn.lean new file mode 100644 index 00000000..98e7f3dd --- /dev/null +++ b/Contracts/Token/LoweringIn.lean @@ -0,0 +1,39 @@ +import Contracts.Token.Lowering +import SolidCore.Refinement.Generic.StageIn + +/-! +# solar-verify's Token: the source stage in every world + +`stageIn` is `Contracts/Token/Lowering.lean`'s `stage` with SolidCore run in any world `W` (any call +oracle, any other accounts' code; SolidCore/Refinement/SourceOracle.lean), from the same kernel +check: Token makes no external call, so its stage holds in every world, the open ones that +`holds_of_runs` quantifies over included, with no hypothesis on the world. +-/ + +namespace SolidCore.Refinement.Solar.VerifyTokenSource + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Generic +open SolidCore.Solidity SolidCore.Verify.VC.Token +open SolarTV.Export.Token (stage0) + +/-- **The source stage of solar-verify's Token in every world.** -/ +theorem stageIn (W : World) (o : SolarTV.Machine.Oracle) (henv : SourceEnvOk o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) {fn : Fn} + (h : checkOn stage0 fn = some true) : + Stage (solidCoreIn W fuel) (SolarTV.MIR.Lowered.moduleSem o) c stage0 + (SolidCore.Verify.VC.stageScope fn [(2, 4096)]) := by + obtain ⟨d, hd⟩ := deployed hc + exact Generic.stageInAtEnv W o henv hd (check_of hc h) + +/-- `transfer`'s stage in every world, from the kernel's check. -/ +theorem stageIn_transfer (W : World) (o : SolarTV.Machine.Oracle) (henv : SourceEnvOk o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCoreIn W fuel) (SolarTV.MIR.Lowered.moduleSem o) c stage0 + (SolidCore.Verify.VC.stageScope fnTransfer [(2, 4096)]) := + stageIn W o henv hc check_transfer_eq + +/-- info: 'SolidCore.Refinement.Solar.VerifyTokenSource.stageIn_transfer' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stageIn_transfer + +end SolidCore.Refinement.Solar.VerifyTokenSource diff --git a/Contracts/Token/Spec/Export.lean b/Contracts/Token/Spec/Export.lean new file mode 100644 index 00000000..4f8bf561 --- /dev/null +++ b/Contracts/Token/Spec/Export.lean @@ -0,0 +1,71 @@ +import Verify.Spec.Contract + +/-! +Specs of `scripts/verify/Token.sol`, exported by solar-verify 0.3.0 with `--emit-lean-spec`. +Generated: do not edit. +-/ + +namespace SolidCore.Spec.Export.Token + +open SolidCore.Spec + +/-- What the specs were exported from and are about. -/ +def manifest : Manifest := + { source := "scripts/verify/Token.sol", + sourceSha256 := "45b62aa1152c4ec09e76735ac7257a06bf3e4be0f435fdacdc174f41e8c8e75c", + compiler := "0.8.38+commit.d5bf3d61.solar.0.3.0-dev", + options := [], + bytecodeSha256 := "dc9b316028e6184a20b02cf865e2b5fa72a87eb066dc745e9a75d5da5fb252d7" } + +/-- The specs of `Token`. -/ +def Token : Bundle where + fuel := 0 + spec := + { name := "Token", + fns := [ + ], + invariants := [ + (.bin .eq (.load (.slot 1) (.lit 0) 32 (.uint 256)) (.ghost "sumBalances" []))], + ghosts := ["sumBalances"], + specs := [ + { name := "Token.mint", + selector := 0x40c10f19, + params := [.address, (.uint 256)], + rets := [], + payable := false, + requires := [], + ensures := [ + (.bin .eq (.load (.entry (.slot 0) (.arg 0)) (.lit 0) 32 (.uint 256)) (.bin .add (.old (.load (.entry (.slot 0) (.arg 0)) (.lit 0) 32 (.uint 256))) (.arg 1))), + (.bin .eq (.load (.slot 1) (.lit 0) 32 (.uint 256)) (.bin .add (.old (.load (.slot 1) (.lit 0) 32 (.uint 256))) (.arg 1))), + (.all "a" .address (.bin .implies (.bin .ne (.var "a") (.arg 0)) (.bin .eq (.load (.entry (.slot 0) (.var "a")) (.lit 0) 32 (.uint 256)) (.old (.load (.entry (.slot 0) (.var "a")) (.lit 0) 32 (.uint 256))))))], + succeedsIf := [] }, + { name := "Token.transfer", + selector := 0xa9059cbb, + params := [.address, (.uint 256)], + rets := [.bool], + payable := false, + requires := [], + ensures := [ + (.bin .implies (.bin .ne (.env .sender) (.arg 0)) (.bin .eq (.load (.entry (.slot 0) (.env .sender)) (.lit 0) 32 (.uint 256)) (.bin .sub (.old (.load (.entry (.slot 0) (.env .sender)) (.lit 0) 32 (.uint 256))) (.arg 1)))), + (.bin .implies (.bin .ne (.env .sender) (.arg 0)) (.bin .eq (.load (.entry (.slot 0) (.arg 0)) (.lit 0) 32 (.uint 256)) (.bin .add (.old (.load (.entry (.slot 0) (.arg 0)) (.lit 0) 32 (.uint 256))) (.arg 1)))), + (.all "a" .address (.bin .implies (.bin .and (.bin .ne (.var "a") (.env .sender)) (.bin .ne (.var "a") (.arg 0))) (.bin .eq (.load (.entry (.slot 0) (.var "a")) (.lit 0) 32 (.uint 256)) (.old (.load (.entry (.slot 0) (.var "a")) (.lit 0) 32 (.uint 256)))))), + (.bin .eq (.load (.slot 1) (.lit 0) 32 (.uint 256)) (.old (.load (.slot 1) (.lit 0) 32 (.uint 256))))], + succeedsIf := [] }, + { name := "Token.burn", + selector := 0x42966c68, + params := [(.uint 256)], + rets := [], + payable := false, + requires := [], + ensures := [ + (.bin .eq (.load (.entry (.slot 0) (.env .sender)) (.lit 0) 32 (.uint 256)) (.bin .sub (.old (.load (.entry (.slot 0) (.env .sender)) (.lit 0) 32 (.uint 256))) (.arg 0)))], + succeedsIf := [] }] } + +/-- Every spec function call resolves and nests within the fuel. -/ +theorem Token_wf : Token.WF = true := by decide +kernel + +/-- Trusted-base items these specs' proofs rely on beyond the verdict +(`SolidCore.Spec.Assumptions`). -/ +def trusted : List String := [] + +end SolidCore.Spec.Export.Token diff --git a/Contracts/Token/Spec/ExportCollide.lean b/Contracts/Token/Spec/ExportCollide.lean new file mode 100644 index 00000000..52a30ff5 --- /dev/null +++ b/Contracts/Token/Spec/ExportCollide.lean @@ -0,0 +1,71 @@ +import Verify.Spec.Contract + +/-! +Specs of `scripts/verify/keccak/TokenSpecCollide.sol`, exported by solar-verify 0.3.0 with `--emit-lean-spec`. +Generated: do not edit. +-/ + +namespace SolidCore.Spec.Export.TokenSpecCollide + +open SolidCore.Spec + +/-- What the specs were exported from and are about. -/ +def manifest : Manifest := + { source := "scripts/verify/keccak/TokenSpecCollide.sol", + sourceSha256 := "ca9f9157c21b7e8648a21a62dc7c848c2a32482d7bdac6a794f649028cd1a1a9", + compiler := "", + options := [], + bytecodeSha256 := "" } + +/-- The specs of `Token`. -/ +def Token : Bundle where + fuel := 0 + spec := + { name := "Token", + fns := [ + ], + invariants := [ + (.bin .eq (.load (.slot 1) (.lit 0) 32 (.uint 256)) (.ghost "sumBalances" []))], + ghosts := ["sumBalances"], + specs := [ + { name := "Token.mint", + selector := 0x40c10f19, + params := [.address, (.uint 256)], + rets := [], + payable := false, + requires := [], + ensures := [ + (.bin .eq (.load (.entry (.slot 0) (.arg 0)) (.lit 0) 32 (.uint 256)) (.bin .add (.old (.load (.entry (.slot 0) (.arg 0)) (.lit 0) 32 (.uint 256))) (.arg 1))), + (.bin .eq (.load (.slot 1) (.lit 0) 32 (.uint 256)) (.bin .add (.old (.load (.slot 1) (.lit 0) 32 (.uint 256))) (.arg 1))), + (.all "a" .address (.bin .implies (.bin .ne (.var "a") (.arg 0)) (.bin .eq (.load (.entry (.slot 0) (.var "a")) (.lit 0) 32 (.uint 256)) (.old (.load (.entry (.slot 0) (.var "a")) (.lit 0) 32 (.uint 256))))))], + succeedsIf := [] }, + { name := "Token.transfer", + selector := 0xa9059cbb, + params := [.address, (.uint 256)], + rets := [.bool], + payable := false, + requires := [], + ensures := [ + (.bin .implies (.bin .ne (.env .sender) (.arg 0)) (.bin .eq (.load (.entry (.slot 0) (.env .sender)) (.lit 0) 32 (.uint 256)) (.bin .sub (.old (.load (.entry (.slot 0) (.env .sender)) (.lit 0) 32 (.uint 256))) (.arg 1)))), + (.bin .implies (.bin .ne (.env .sender) (.arg 0)) (.bin .eq (.load (.entry (.slot 0) (.arg 0)) (.lit 0) 32 (.uint 256)) (.bin .add (.old (.load (.entry (.slot 0) (.env .sender)) (.lit 0) 32 (.uint 256))) (.arg 1)))), + (.all "a" .address (.bin .implies (.bin .and (.bin .ne (.var "a") (.env .sender)) (.bin .ne (.var "a") (.arg 0))) (.bin .eq (.load (.entry (.slot 0) (.var "a")) (.lit 0) 32 (.uint 256)) (.old (.load (.entry (.slot 0) (.var "a")) (.lit 0) 32 (.uint 256)))))), + (.bin .eq (.load (.slot 1) (.lit 0) 32 (.uint 256)) (.old (.load (.slot 1) (.lit 0) 32 (.uint 256))))], + succeedsIf := [] }, + { name := "Token.burn", + selector := 0x42966c68, + params := [(.uint 256)], + rets := [], + payable := false, + requires := [], + ensures := [ + (.bin .eq (.load (.entry (.slot 0) (.env .sender)) (.lit 0) 32 (.uint 256)) (.bin .sub (.old (.load (.entry (.slot 0) (.env .sender)) (.lit 0) 32 (.uint 256))) (.arg 0)))], + succeedsIf := [] }] } + +/-- Every spec function call resolves and nests within the fuel. -/ +theorem Token_wf : Token.WF = true := by decide +kernel + +/-- Trusted-base items these specs' proofs rely on beyond the verdict +(`SolidCore.Spec.Assumptions`). -/ +def trusted : List String := [] + +end SolidCore.Spec.Export.TokenSpecCollide diff --git a/Contracts/Token/Spec/ExportWrong.lean b/Contracts/Token/Spec/ExportWrong.lean new file mode 100644 index 00000000..7a550573 --- /dev/null +++ b/Contracts/Token/Spec/ExportWrong.lean @@ -0,0 +1,71 @@ +import Verify.Spec.Contract + +/-! +Specs of `scripts/verify/mutant/TokenSpecMut.sol`, exported by solar-verify 0.3.0 with `--emit-lean-spec`. +Generated: do not edit. +-/ + +namespace SolidCore.Spec.Export.TokenSpecMut + +open SolidCore.Spec + +/-- What the specs were exported from and are about. -/ +def manifest : Manifest := + { source := "scripts/verify/mutant/TokenSpecMut.sol", + sourceSha256 := "7d9e63fce842edd61266528e84206a5a9815f1399f7756c0a0ea34799cacf3d2", + compiler := "", + options := [], + bytecodeSha256 := "" } + +/-- The specs of `Token`. -/ +def Token : Bundle where + fuel := 0 + spec := + { name := "Token", + fns := [ + ], + invariants := [ + (.bin .eq (.load (.slot 1) (.lit 0) 32 (.uint 256)) (.ghost "sumBalances" []))], + ghosts := ["sumBalances"], + specs := [ + { name := "Token.mint", + selector := 0x40c10f19, + params := [.address, (.uint 256)], + rets := [], + payable := false, + requires := [], + ensures := [ + (.bin .eq (.load (.entry (.slot 0) (.arg 0)) (.lit 0) 32 (.uint 256)) (.bin .add (.old (.load (.entry (.slot 0) (.arg 0)) (.lit 0) 32 (.uint 256))) (.arg 1))), + (.bin .eq (.load (.slot 1) (.lit 0) 32 (.uint 256)) (.bin .add (.old (.load (.slot 1) (.lit 0) 32 (.uint 256))) (.arg 1))), + (.all "a" .address (.bin .implies (.bin .ne (.var "a") (.arg 0)) (.bin .eq (.load (.entry (.slot 0) (.var "a")) (.lit 0) 32 (.uint 256)) (.old (.load (.entry (.slot 0) (.var "a")) (.lit 0) 32 (.uint 256))))))], + succeedsIf := [] }, + { name := "Token.transfer", + selector := 0xa9059cbb, + params := [.address, (.uint 256)], + rets := [.bool], + payable := false, + requires := [], + ensures := [ + (.bin .implies (.bin .ne (.env .sender) (.arg 0)) (.bin .eq (.load (.entry (.slot 0) (.env .sender)) (.lit 0) 32 (.uint 256)) (.bin .sub (.old (.load (.entry (.slot 0) (.env .sender)) (.lit 0) 32 (.uint 256))) (.arg 1)))), + (.bin .implies (.bin .ne (.env .sender) (.arg 0)) (.bin .eq (.load (.entry (.slot 0) (.arg 0)) (.lit 0) 32 (.uint 256)) (.bin .add (.bin .add (.old (.load (.entry (.slot 0) (.arg 0)) (.lit 0) 32 (.uint 256))) (.arg 1)) (.lit 1)))), + (.all "a" .address (.bin .implies (.bin .and (.bin .ne (.var "a") (.env .sender)) (.bin .ne (.var "a") (.arg 0))) (.bin .eq (.load (.entry (.slot 0) (.var "a")) (.lit 0) 32 (.uint 256)) (.old (.load (.entry (.slot 0) (.var "a")) (.lit 0) 32 (.uint 256)))))), + (.bin .eq (.load (.slot 1) (.lit 0) 32 (.uint 256)) (.old (.load (.slot 1) (.lit 0) 32 (.uint 256))))], + succeedsIf := [] }, + { name := "Token.burn", + selector := 0x42966c68, + params := [(.uint 256)], + rets := [], + payable := false, + requires := [], + ensures := [ + (.bin .eq (.load (.entry (.slot 0) (.env .sender)) (.lit 0) 32 (.uint 256)) (.bin .sub (.old (.load (.entry (.slot 0) (.env .sender)) (.lit 0) 32 (.uint 256))) (.arg 0)))], + succeedsIf := [] }] } + +/-- Every spec function call resolves and nests within the fuel. -/ +theorem Token_wf : Token.WF = true := by decide +kernel + +/-- Trusted-base items these specs' proofs rely on beyond the verdict +(`SolidCore.Spec.Assumptions`). -/ +def trusted : List String := [] + +end SolidCore.Spec.Export.TokenSpecMut diff --git a/Contracts/Token/SpecTree.lean b/Contracts/Token/SpecTree.lean new file mode 100644 index 00000000..36f24b58 --- /dev/null +++ b/Contracts/Token/SpecTree.lean @@ -0,0 +1,92 @@ +import Verify.Spec.Tree +import Verify.Spec.Hash +import Verify.Spec.TreeIn +import Contracts.Token.TransferMeets +import Contracts.Token.EndToEnd + +/-! +# Token: solar-verify's exported spec of `transfer` of solar's bytecode, generically + +`Spec/Export.lean` is solar-verify's `--emit-lean-spec` export of `scripts/verify/Token.sol`. +`transfer_meets` (TransferMeets.lean, by the generic mapping tactic `tree_meets_map`) proves +`transfer`'s exported spec of the generic source stage's tree (`transferTree`, `transferShape_eq`): +the two balance clauses, the frame clause over every other address, the supply clause and the +invariant `totalSupply == sumBalances` (`TreeMeetsFixed`: `transfer` writes no ghost). The mapping +slots are SolidCore's `solHash`, which is the spec semantics' slot by `solHash_eq`; their +separation (distinct on distinct addresses, and from the scalar slots) is the one hypothesis, +`SlotsSeparated 0`. `transfer_holds` lifts it to SolidCore's checked Token (`holdsFn_of_tree_fixed`) +and `transfer_spec_bytecode` carries it to solar's bytecode through the certified stages +(`Contracts.Token.certified`). No solver verdict is used. The negative, `wrong_not_meets`, is in +TransferMeets.lean. +-/ + +namespace SolidCore.Spec.TreeDemo.Token + +open SolidCore.Spec SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Verify.VC.Token + +/-- **`transfer`'s exported spec holds of SolidCore's checked Token** on the stage's calls of +`transfer` (storage covering the deployed owner slot), for a ghost step that leaves the ghost +state alone on them. -/ +theorem transfer_holds (hsep : SlotsSeparated 0) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : contract? = .ok c) (step : GhostStep) + (hstep : ∀ call, SolidCore.Verify.VC.stageScope fnTransfer [(2, 4096)] call → ∀ g, step call g = g) : + HoldsFn (solidCore fuel) c (SolidCore.Verify.VC.stageScope fnTransfer [(2, 4096)]) spec ctxOf step + transferSpec := by + have hdep := burnShape_eq + simp only [burnShape?, hc, Option.some.injEq, Prod.mk.injEq] at hdep + obtain ⟨d, hd⟩ := Wide.deployedAt_of hdep.1 + have hshape := transferShape_eq + simp only [transferShape?, hc, Option.some.injEq, Option.map_eq_some_iff, Prod.mk.injEq] at hshape + obtain ⟨f, hf, hlen, hT⟩ := hshape + exact holdsFn_of_tree_fixed (fn := fnTransfer) hd (by decide) hf hlen hT + (fun call h => by simp [ctxOf, ctx, h]) hstep (transfer_meets hsep) + + +/-- **`transfer`'s exported spec holds of SolidCore's checked Token in every world `W`** (Token +calls out nowhere), the source side `compose_in` and `holds_of_runs` take. -/ +theorem transfer_holds_in (W : SolidCore.Refinement.World) (hsep : SlotsSeparated 0) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) (step : GhostStep) + (hstep : ∀ call, SolidCore.Verify.VC.stageScope fnTransfer [(2, 4096)] call → ∀ g, step call g = g) : + HoldsFn (solidCoreIn W fuel) c (SolidCore.Verify.VC.stageScope fnTransfer [(2, 4096)]) spec ctxOf + step transferSpec := by + have hdep := burnShape_eq + simp only [burnShape?, hc, Option.some.injEq, Prod.mk.injEq] at hdep + obtain ⟨d, hd⟩ := Wide.deployedAt_of hdep.1 + have hshape := transferShape_eq + simp only [transferShape?, hc, Option.some.injEq, Option.map_eq_some_iff, Prod.mk.injEq] at hshape + obtain ⟨f, hf, hlen, hT⟩ := hshape + exact holdsFn_of_tree_fixed_in W (fn := fnTransfer) hd (by decide) hf hlen hT + (fun call h => by simp [ctxOf, ctx, h]) hstep (transfer_meets hsep) + +/-- info: 'SolidCore.Spec.TreeDemo.Token.transfer_holds_in' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms transfer_holds_in + +end SolidCore.Spec.TreeDemo.Token + +namespace SolidCore.Refinement.Solar.Token.SpecTree + +open SolidCore.Spec SolidCore.Refinement + +/-- **solar-verify's exported spec of `transfer` holds of solar's runtime bytecode** under EthLib, +on every call of `transfer(address,uint256)` in the stage's scope (any argument words, no value, +any storage covering the owner slot), given `SlotsSeparated 0`, for any ghost step that leaves +the ghost state alone on those calls: the spec of the erased tree (`transfer_meets`), SolidCore's +run of the tree (`holdsFn_of_tree_fixed`) and the certified stage from SolidCore's Token to the +bytecode (`Contracts.Token.certified`). No solver verdict. -/ +theorem transfer_spec_bytecode (hsep : SlotsSeparated 0) (step : GhostStep) + (hstep : ∀ call, SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Token.fnTransfer [(2, 4096)] call → + ∀ g, step call g = g) : + HoldsFn ethLib SolidCore.Refinement.Solar.VerifyTokenAsm.code + (SolidCore.Verify.VC.stageScope SolidCore.Verify.VC.Token.fnTransfer [(2, 4096)]) + SolidCore.Spec.TreeDemo.Token.spec SolidCore.Spec.TreeDemo.Token.ctxOf step + SolidCore.Spec.TreeDemo.Token.transferSpec := by + obtain ⟨c, hc⟩ := SolidCore.Refinement.Solar.VerifyTokenSource.contract_ok + exact (SolidCore.Spec.TreeDemo.Token.transfer_holds hsep hc step hstep).of_stage + (Contracts.Token.certified hc SolidCore.Refinement.Solar.VerifyTokenSource.check_transfer_eq) + +/-- info: 'SolidCore.Refinement.Solar.Token.SpecTree.transfer_spec_bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms transfer_spec_bytecode + +end SolidCore.Refinement.Solar.Token.SpecTree diff --git a/Contracts/Token/TransferMeets.lean b/Contracts/Token/TransferMeets.lean new file mode 100644 index 00000000..3e7d6998 --- /dev/null +++ b/Contracts/Token/TransferMeets.lean @@ -0,0 +1,77 @@ +import Verify.Spec.TreeMap +import Contracts.Token.VC.Transfer +import Contracts.Token.Spec.Export +import Contracts.Token.Spec.ExportWrong + +/-! +# Token: `transfer`'s exported spec of its erased tree, by the generic mapping tactic + +`transfer_meets` proves solar-verify's exported spec of `transfer` (`Spec/Export.lean`) of the +generic source stage's tree (`transferTree`) by `tree_meets_map` alone: no per-function proof +steps, no solver verdict. Its one hypothesis is `SlotsSeparated 0` (keccak256 separated on the +slots of `balanceOf[a]`), which `tree_meets_map` reads as `MapSlotsSeparated [0]`. + +`wrong_not_meets` is the negative: the spec mutant of `scripts/verify/mutant/TokenSpecMut.sol` +(`balanceOf[to] == old(balanceOf[to]) + amount + 1`, `Spec/ExportWrong.lean`) does not hold of the +same tree, with no hypothesis: `transfer(1, 0)` from the empty storage succeeds and leaves +`balanceOf[1]` at 0. +-/ + +namespace SolidCore.Spec.TreeDemo.Token + +open SolidCore.Spec SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Verify.VC.Token + +abbrev spec : Bundle := SolidCore.Spec.Export.Token.Token +def transferSpec : FnSpec := spec.spec.specs[1]'(by decide) +def ctx : Ctx := { sender := 0x2000, value := 0, timestamp := 1, self := 0x1000 } + +/-- The call context of every call: `ctx` with the call's value. -/ +def ctxOf (call : SolarTV.Call) : Ctx := { ctx with value := call.callvalue } + +set_option linter.unusedSimpArgs false in +/-- **`transfer`'s exported spec holds of its erased tree**, by `tree_meets_map`. -/ +theorem transfer_meets (hsep : SlotsSeparated 0) : + TreeMeetsFixed spec transferSpec ctx 2 transferTree := by + have hsep' := (mapSlotsSeparated_singleton 0).2 hsep + tree_meets_map [transferTree, transferSpec, SolidCore.Spec.TreeDemo.Token.spec, + SolidCore.Spec.Export.Token.Token, SolidCore.Spec.TreeDemo.Token.ctx] hsep' + +/-- The mutant's spec of `transfer`. -/ +def mutSpec : FnSpec := SolidCore.Spec.Export.TokenSpecMut.Token.spec.specs[1]'(by decide) + +set_option linter.unusedSimpArgs false in +/-- **The spec mutant does not hold of the tree**: `transfer(1, 0)` from the empty storage +succeeds with `balanceOf[1]` still 0, and the mutant asks for 1. -/ +theorem wrong_not_meets : + ¬ TreeMeetsFixed SolidCore.Spec.Export.TokenSpecMut.Token mutSpec ctx 2 transferTree := by + intro h + have hp := h [1, 0] (fun _ => 0) [1, 0] ⟨fun _ => 0, Ghost.zero, 0⟩ rfl (by simp) (by simp) + (by simp [mutSpec, SolidCore.Spec.Export.TokenSpecMut.Token, decodeWords, Ty.ofWord]) rfl + (by simp [ctx]) (by simp [Bundle.satAll, mutSpec, SolidCore.Spec.Export.TokenSpecMut.Token]) + (by simp [Bundle.satAll, Bundle.sat, SolidCore.Spec.Export.TokenSpecMut.Token, eval, slotOf, mkEnv, + Env.cur, Ghost.zero, BinOp.apply, Ty.ofBits]) + have hlt := solHash_lt' + have hkec := keccak_solHash + generalize solHash = H at hp hlt hkec + simp only [transferTree, Tree.eval, WExpr.eval, BinOp.eval, UnOp.eval, Generic.wordSize, Res.obs, + Writes.store, List.getD_cons_zero, List.getD_cons_succ, Nat.reducePow, Nat.reduceMod, Nat.zero_mod, + Nat.reduceLT, ite_mod_nat, ite_true, ite_false, Nat.lt_irrefl, Nat.not_lt_zero, decide_false, + Nat.reduceAdd, Nat.reduceSub, Nat.zero_add, Nat.add_zero, ite_self, Nat.one_ne_zero, ite_false, Nat.reduceEqDiff, reduceIte] at hp + obtain ⟨rets, -, hens, -⟩ := hp.1 rfl + simp only [Bundle.satAll, Bundle.sat, mutSpec, SolidCore.Spec.Export.TokenSpecMut.Token, + List.getElem_cons_succ, List.getElem_cons_zero, List.mem_cons, List.not_mem_nil, or_false, + forall_eq_or_imp, forall_eq, eval, evalList, slotOf, mkEnv, Env.cur, Env.bind, BinOp.apply, Ty.ofBits, + toWord, ctx, List.getD_cons_zero, List.getD_cons_succ, hkec, ofProp_ne_zero, ite_true, ite_false, + Nat.zero_div, Nat.zero_mod, Int.reduceMod, Int.reduceToNat] at hens + have h2 := hens.2.1 (by decide) + simp at h2 + +/-- info: 'SolidCore.Spec.TreeDemo.Token.transfer_meets' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms transfer_meets + +/-- info: 'SolidCore.Spec.TreeDemo.Token.wrong_not_meets' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms wrong_not_meets + +end SolidCore.Spec.TreeDemo.Token diff --git a/Contracts/Token/VC/Bind.lean b/Contracts/Token/VC/Bind.lean new file mode 100644 index 00000000..98eeafc7 --- /dev/null +++ b/Contracts/Token/VC/Bind.lean @@ -0,0 +1,15 @@ +import Contracts.Token.VC.Export + +/-! +# The exported scripts are solar-verify's transcripts + +Each exported `script` prints back to its `transcript`, the bytes solar-verify wrote with +`--dump-smt` in the same run. The check runs Lean's evaluator: the kernel's evaluation of the +printer on a transcript of 20 KB, with its 78-digit numerals, does not fit in this build's memory. +-/ + +namespace SolidCore.Verify.VC + +#guard printScript Export.Token.script == Export.Token.transcript + +end SolidCore.Verify.VC diff --git a/Contracts/Token/VC/Burn.lean b/Contracts/Token/VC/Burn.lean new file mode 100644 index 00000000..25dd5482 --- /dev/null +++ b/Contracts/Token/VC/Burn.lean @@ -0,0 +1,330 @@ +import Verify.VC +import Contracts.Token.VC.Source +import Contracts.Token.VC.Export +import SolidCore.Refinement.KernelRfl +import Verify.VC.KernelIdx + +/-! +# solar-verify's `Token.burn` against SolidCore + +The kernel's evaluation fixes what SolidCore does with `scripts/verify/Token.sol`: it type checks, +its constructor leaves only `owner` (slot 2) and no logs, `burn(uint256)` dispatches to a function +of one parameter, and the generic source stage erases it to `burnTree` (`burnShape_eq`). As in the +Token source stage, the checker's selectors come from a table each of whose entries the kernel +checks against Keccak-256 once. +-/ + +namespace SolidCore.Verify.VC.Token + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Generic +open SolidCore.Solidity SolidCore.Solidity.Source + +/-- The interpreter fuel of SolidCore's runs. -/ +def fuel : Nat := 4096 + +/-- SolidCore's checked `Token`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract SolidCore.Verify.VC.Source.Token.importedSourceUnit "Token" + +/-- The selector of `balanceOf(address)`. -/ +abbrev balanceofSel : Nat := 1889567281 + +/-- The selector of `balanceOf(address)`, by Keccak-256 of its signature. -/ +def selBalanceOf : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "balanceOf(address)" + +kernel_rfl selBalanceOf_eq selBalanceOf balanceofSel + +/-- The selector of `totalSupply()`. -/ +abbrev totalsupplySel : Nat := 404098525 + +/-- The selector of `totalSupply()`, by Keccak-256 of its signature. -/ +def selTotalSupply : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "totalSupply()" + +kernel_rfl selTotalSupply_eq selTotalSupply totalsupplySel + +/-- The selector of `owner()`. -/ +abbrev ownerSel : Nat := 2376452955 + +/-- The selector of `owner()`, by Keccak-256 of its signature. -/ +def selOwner : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "owner()" + +kernel_rfl selOwner_eq selOwner ownerSel + +/-- The selector of `mint(address,uint256)`. -/ +abbrev mintSel : Nat := 1086394137 + +/-- The selector of `mint(address,uint256)`, by Keccak-256 of its signature. -/ +def selMint : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "mint(address,uint256)" + +kernel_rfl selMint_eq selMint mintSel + +/-- The selector of `transfer(address,uint256)`. -/ +abbrev transferSel : Nat := 2835717307 + +/-- The selector of `transfer(address,uint256)`, by Keccak-256 of its signature. -/ +def selTransfer : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "transfer(address,uint256)" + +kernel_rfl selTransfer_eq selTransfer transferSel + +/-- The selector of `burn(uint256)`. -/ +abbrev burnSel : Nat := 1117154408 + +/-- The selector of `burn(uint256)`, by Keccak-256 of its signature. -/ +def selBurn : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "burn(uint256)" + +kernel_rfl selBurn_eq selBurn burnSel + +/-- `ABI.selectorFromSignature`, with `Token`'s selectors by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "balanceOf(address)" then balanceofSel + else if s = "totalSupply()" then totalsupplySel + else if s = "owner()" then ownerSel + else if s = "mint(address,uint256)" then mintSel + else if s = "transfer(address,uint256)" then transferSel + else if s = "burn(uint256)" then burnSel + else SolidCore.Solidity.Source.ABI.selectorFromSignature s + +theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + by_cases h0 : s = "balanceOf(address)" + · rw [ite_eq_left h0, h0] + exact selBalanceOf_eq + rw [ite_eq_right h0] + by_cases h1 : s = "totalSupply()" + · rw [ite_eq_left h1, h1] + exact selTotalSupply_eq + rw [ite_eq_right h1] + by_cases h2 : s = "owner()" + · rw [ite_eq_left h2, h2] + exact selOwner_eq + rw [ite_eq_right h2] + by_cases h3 : s = "mint(address,uint256)" + · rw [ite_eq_left h3, h3] + exact selMint_eq + rw [ite_eq_right h3] + by_cases h4 : s = "transfer(address,uint256)" + · rw [ite_eq_left h4, h4] + exact selTransfer_eq + rw [ite_eq_right h4] + by_cases h5 : s = "burn(uint256)" + · rw [ite_eq_left h5, h5] + exact selBurn_eq + rw [ite_eq_right h5] + +/-- The revert data of `Panic(0x11)`, byte by byte. -/ +def panic11 : List OByte := + [78, 72, 123, 113].map .lit ++ (List.replicate 31 (OByte.lit 0)) ++ [.lit 17] + +/-- The erasure of `burn`, as the generic source stage computes it. -/ +def burnTree : Tree := + (.ite (.bin .lt (.sinit (.hash (.lit 8192) (.lit 0))) (.arg 0)) (.halt false panic11 [] []) + (.ite (.bin .lt (.sel (.bin .eq (.lit 1) (.hash (.lit 8192) (.lit 0))) + (.bin .sub (.sinit (.hash (.lit 8192) (.lit 0))) (.arg 0)) (.init 1)) (.arg 0)) + (.halt false panic11 [] []) + (.halt true [] [(.lit 1, .bin .sub (.sel (.bin .eq (.lit 1) (.hash (.lit 8192) (.lit 0))) + (.bin .sub (.sinit (.hash (.lit 8192) (.lit 0))) (.arg 0)) (.init 1)) (.arg 0)), + (.hash (.lit 8192) (.lit 0), .bin .sub (.sinit (.hash (.lit 8192) (.lit 0))) (.arg 0))] []))) + +/-- Whether `Token` deploys with `owner` alone in storage and no logs, and how SolidCore dispatches +`burn` and the generic source stage erases it. -/ +def burnShape? : Option (Bool × Option (Nat × Option Tree)) := + match contract? with + | .ok c => some (Wide.deployedAt fuel c [(2, 4096)], + (c.core.findFunctionBySelector? burnSel).map fun f => (f.params.length, eraseFn (envOf c.core) fuel f)) + | .error _ => none + +kernel_rfl burnShape_eq burnShape? (some (true, some (1, some burnTree))) using selector_eq mkIdx_eq + +open SolidCore.Verify SolidCore.Verify.VC SolidCore.Refinement SolidCore.Refinement.Abi +open SolidCore.Refinement.Generic + +/-- `burn` as the stage's ABI sees it. -/ +def fnBurn : Fn := ⟨burnSel, [.uint 256]⟩ + +/-- The slot of `balanceOf[msg.sender]` for the stage's caller `callerWord`. -/ +def senderSlot : Nat := + 55339514551095541597166361489097532198990872027936225909895186517043906691032 + +/-- `balanceOf[msg.sender]`'s slot, by Keccak-256. -/ +def senderSlotOf : Nat := solHash callerWord 0 + +kernel_rfl senderSlot_eq senderSlotOf senderSlot + +theorem hash_eq : solHash 8192 0 = senderSlot := senderSlot_eq + +theorem tree_success (s : Nat → Nat) (hs : ∀ k, s k < 2 ^ 256) (a : Nat) (ha : a < 2 ^ 256) : + let R := burnTree.eval (valOf [a] s) + R.success = true → a ≤ s senderSlot ∧ a ≤ s 1 ∧ + R.store senderSlot = s senderSlot - a ∧ R.store 1 = s 1 - a := by + intro R + have hsm : ∀ k, s k % 2 ^ 256 = s k := fun k => Nat.mod_eq_of_lt (hs k) + have ham : a % 2 ^ 256 = a := Nat.mod_eq_of_lt ha + have hss : senderSlot % 2 ^ 256 = senderSlot := by decide + have hne : (1 = senderSlot) = False := by decide + have hne' : (senderSlot = 1) = False := by decide + have h1 := hs senderSlot + have h2 := hs 1 + have h8 : 8192 % 2 ^ 256 = 8192 := by decide + have h0 : 0 % 2 ^ 256 = 0 := by decide + have h1' : 1 % 2 ^ 256 = 1 := by decide + simp only [R, burnTree, Tree.eval, WExpr.eval, BinOp.eval, valOf, Generic.wordSize, + h8, h0, h1', hash_eq, List.getD_cons_zero, hss, hsm, ham, hne, ite_false, ite_true] + split_ifs <;> simp only [Writes.store, WExpr.eval, BinOp.eval, Generic.wordSize, hash_eq, hss, hsm, + ham, hne, hne', h8, h0, h1', ite_false, ite_true, List.getD_cons_zero, + false_implies, true_implies] <;> first | contradiction | omega + +/-! ## solar-verify's obligation for `burn`, on the Lean side -/ + +namespace Ob + +def amt : Tm := .ivar "amount" +def ms : Tm := .ivar "msg.sender" +def ts : Tm := .ivar "totalSupply" +def sum : Tm := .ivar "sumBalances" +def mv : Tm := .ivar "msg.value" +def bal : Tm := .app "select" [.avar "balanceOf", ms] +def le0 (t : Tm) : Tm := .app "<=" [.num 0, t] +def leW (t : Tm) : Tm := .app "<=" [t, .num (2 ^ 256 - 1)] +def sub (a b : Tm) : Tm := .app "-" [a, b] +def eq (a b : Tm) : Tm := .app "=" [a, b] + +end Ob + +open Ob in +/-- The facts the Lean side of `burn`'s ensures clause rests on: the invariant, no value, the +success path's two range checks, and the words' ranges. -/ +def burnHyps : List Tm := + [eq ts sum, eq mv (.num 0), le0 (sub bal amt), leW (sub bal amt), le0 (sub ts amt), + leW (sub ts amt), le0 bal, leW bal, le0 amt, leW amt, le0 ts, leW ts, le0 sum, leW sum, le0 mv, + leW mv, .app "not" [eq ms (.num 0)], le0 ms, .app "<=" [ms, .num (2 ^ 160 - 1)]] + +open Ob in +/-- solar-verify's encoding of `balanceOf[msg.sender]` after `burn`. -/ +def burnStore : Tm := .app "select" [.app "store" [.avar "balanceOf", ms, sub bal amt], ms] + +open Ob in +/-- `burn`'s ensures clause `balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount` as +solar-verify states it, of its own encoding of the function's effect. -/ +def burnGoal : Tm := eq burnStore (sub bal amt) + +/-- solar-verify's script for `Token` has an obligation that `checkOb` normalizes to +`burnHyps → burnGoal`. -/ +theorem burn_check : checkScript Export.Token.script [(burnHyps, burnGoal)] = true := by + decide +kernel + +/-- The assignment of solar-verify's names that a call of `burn` on `amount` gives, from the +balance `b` of the caller and the total supply `t`; the ghost `sumBalances` is chosen equal to +`totalSupply`, which the invariant assumes. -/ +def burnEnv (a b t : Nat) : Env where + i := fun x => if x = "amount" then a else if x = "msg.sender" then callerWord + else if x = "totalSupply" then t else if x = "sumBalances" then t else 0 + b := fun _ => False + a := fun x => if x = "balanceOf" then fun k => if k = callerWord then b else 0 else fun _ => 0 + +theorem burnHyps_hold {a b t : Nat} (ha : a ≤ b) (ht : a ≤ t) (hb : b < 2 ^ 256) (htt : t < 2 ^ 256) : + ∀ x ∈ burnHyps, x.Holds (burnEnv a b t) := by + have hca : callerWord = 8192 := rfl + simp only [burnHyps, List.mem_cons, List.mem_nil_iff, or_false] + rintro x (rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | + rfl | rfl | rfl | rfl) <;> + simp [Tm.Holds, Tm.eval, Tm.evalList, applyOp, Value.select, Value.store, Value.toProp, Value.toInt, Value.toArr, Value.eq, + burnEnv, Ob.amt, Ob.ms, Ob.ts, Ob.sum, Ob.mv, Ob.bal, Ob.le0, Ob.leW, Ob.sub, Ob.eq, hca] <;> + omega + +/-- What solar-verify's encoding of the caller's new balance is at `burnEnv`: the old balance less +the amount. -/ +theorem burnStore_eval (a b t : Nat) : + (burnStore.eval (burnEnv a b t)).toInt = (b : Int) - a := by + have hca : callerWord = 8192 := rfl + simp [burnStore, Tm.eval, Tm.evalList, applyOp, Value.select, Value.store, Value.toInt, Value.toArr, burnEnv, Ob.amt, Ob.ms, + Ob.bal, Ob.sub, hca] + +/-- `burn`'s postcondition: on success, the caller's balance and the total supply drop by the +amount. -/ +def burnPost (call : Call) (obs : SolarTV.Observable) : Prop := + obs.success = true → + obs.storage senderSlot = initStorage call senderSlot - (argWords 1 call).getD 0 0 ∧ + obs.storage 1 = initStorage call 1 - (argWords 1 call).getD 0 0 + +theorem vc_eq (model : List Nat → SolM (List Nat)) (args : Call → List Nat) + (post : Call → SolarTV.Observable → Prop) (call : Call) : + vc model args post call = + post call (observe (initStorage call) (model (args call) (initStorage call))) := by + unfold vc + rw [wp_eq] + rcases h : model (args call) (initStorage call) with e | ⟨out, s'⟩ <;> simp only [h] <;> rfl + +/-- solar-verify's verdict on its script for `Token` gives `burn`'s ensures obligation at the +assignment of every successful call: `checkScript_sound`, with the facts discharged from the +success path. -/ +theorem burn_obligation (hv : Valid Export.Token.script) {a b t : Nat} (ha : a ≤ b) (ht : a ≤ t) + (hb : b < 2 ^ 256) (htt : t < 2 ^ 256) : burnGoal.Holds (burnEnv a b t) := + checkScript_sound burn_check hv (burnHyps, burnGoal) (List.mem_singleton_self _) _ + (burnHyps_hold ha ht hb htt) + +/-- `burn` meets its ensures clause on the stage's scope. SolidCore runs every call as the erased +tree (`implements_tree`), whose success path writes the caller's slot with the value of +solar-verify's encoding `burnStore` of the new balance at `burnEnv` (`hagree` below). solar-verify's +goal for this clause selects the stored value back out of its own `store`, which is valid in the +array theory, so the triple rests on that agreement and needs no verdict; `burn_obligation` is the +transfer through `checkScript_sound` that a goal not valid on its own (the invariant, `transfer`'s +frame) needs. -/ +theorem burn_triple {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : contract? = .ok c) : + Triple fuel c (stageScope fnBurn [(2, 4096)]) (fun _ => True) burnPost := by + have hshape := burnShape_eq + simp only [burnShape?, hc, Option.some.injEq, Prod.mk.injEq] at hshape + obtain ⟨hdep, hmap⟩ := hshape + obtain ⟨d, hd⟩ := Wide.deployedAt_of hdep + simp only [Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + have himpl := implements_tree (fn := fnBurn) hd (by decide) hf hlen hT rfl + apply triple_of_wp himpl + rintro _ ⟨σ, hcov, fn', hfn', args, hl, hargs, rfl⟩ - + simp only [List.mem_singleton] at hfn' + subst hfn' + obtain ⟨a, rfl⟩ : ∃ a, args = [a] := by + match args, hl with + | [a], _ => exact ⟨a, rfl⟩ + have ha : a < 2 ^ 256 := hargs a (List.mem_singleton_self a) + have hw : argWords 1 ({ calldata := Abi.calldata fnBurn.sel [a], callvalue := 0, storage := σ } : + Call) = [a] := argWords_calldata _ [a] hargs 0 σ + rw [vc_eq, treeModel_run, show fnBurn.params.length = 1 from rfl, hw] + set s := initStorage ({ calldata := Abi.calldata fnBurn.sel [a], callvalue := 0, storage := σ } : + Call) with hs_def + have hs : ∀ k, s k < 2 ^ 256 := fun k => Generic.slotValue_lt σ k + unfold resOutcome + split + · next hok => + intro _ + obtain ⟨hb, ht, h1, h2⟩ := tree_success s hs a ha hok + have hgoal : (burnStore.eval (burnEnv a (s senderSlot) (s 1))).toInt = + ((s senderSlot : Int) - a) := burnStore_eval a _ _ + -- SolidCore's new balance is the value of solar-verify's encoding of it. + have hagree : (((burnTree.eval (valOf [a] s)).store senderSlot : Nat) : Int) = + (burnStore.eval (burnEnv a (s senderSlot) (s 1))).toInt := by + rw [hgoal, h1]; omega + simp only [observe, hw, List.getD_cons_zero] + rw [← hs_def] + refine ⟨?_, ?_⟩ + · omega + · exact h2 + · intro h; simp_all [observe] + + +/-- info: 'SolidCore.Verify.VC.Token.burn_triple' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms burn_triple + +/-- info: 'SolidCore.Verify.VC.Token.burn_obligation' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms burn_obligation + +end SolidCore.Verify.VC.Token diff --git a/Contracts/Token/VC/Discharged.lean b/Contracts/Token/VC/Discharged.lean new file mode 100644 index 00000000..8ae006ef --- /dev/null +++ b/Contracts/Token/VC/Discharged.lean @@ -0,0 +1,58 @@ +import Contracts.Token.VC.Discharged.Part0 +import Contracts.Token.VC.Discharged.Part1 +import Contracts.Token.VC.Discharged.Part2 +import Contracts.Token.VC.Discharged.Part3 +import Contracts.Token.VC.Mutant.SpecMut +import Contracts.Token.VC.Mutant.SrcMut + +/-! +# `SolidCore.Verify.VC.Export.Token.script`, discharged by the kernel + +Generated by scripts/verify/gen-discharged.py: one kernel evaluation of `dischargeAt` per +obligation (the Part modules, Verify/VC/Discharge.lean), and the script's verdict `Valid` from +them, with no solver. Each rejected mutant script fails by a mismatch at the obligation named. +-/ + +namespace SolidCore.Verify.VC.Token.Discharged + +open SolidCore.Verify.VC + +set_option maxRecDepth 100000 + +theorem obligation_count : (obligations SolidCore.Verify.VC.Export.Token.script).length = 16 := by decide +kernel + +/-- Every obligation of the script has no model. -/ +theorem script_valid : Valid SolidCore.Verify.VC.Export.Token.script := + dischargeScript_of_each _ fun i hi => + match i, obligation_count ▸ hi with + | 0, _ => ob_0 + | 1, _ => ob_1 + | 2, _ => ob_2 + | 3, _ => ob_3 + | 4, _ => ob_4 + | 5, _ => ob_5 + | 6, _ => ob_6 + | 7, _ => ob_7 + | 8, _ => ob_8 + | 9, _ => ob_9 + | 10, _ => ob_10 + | 11, _ => ob_11 + | 12, _ => ob_12 + | 13, _ => ob_13 + | 14, _ => ob_14 + | 15, _ => ob_15 + | _ + 16, h => absurd h (by omega) + +/-- The mutant script is rejected at obligation 10. -/ +theorem reject_0 : dischargeScript SolidCore.Verify.VC.Export.Mutant.TokenSpecMut.script = false := + dischargeScript_false_of (i := 10) (by decide +kernel) (by decide +kernel) + +/-- The mutant script is rejected at obligation 10. -/ +theorem reject_1 : dischargeScript SolidCore.Verify.VC.Export.Mutant.TokenSrcMut.script = false := + dischargeScript_false_of (i := 10) (by decide +kernel) (by decide +kernel) + +/-- info: 'SolidCore.Verify.VC.Token.Discharged.script_valid' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms script_valid + +end SolidCore.Verify.VC.Token.Discharged diff --git a/Contracts/Token/VC/Discharged/Part0.lean b/Contracts/Token/VC/Discharged/Part0.lean new file mode 100644 index 00000000..fece123c --- /dev/null +++ b/Contracts/Token/VC/Discharged/Part0.lean @@ -0,0 +1,21 @@ +import Verify.VC.Discharge +import Contracts.Token.VC.Export + +/-! Obligations 0 to 3 of `SolidCore.Verify.VC.Export.Token.script`, each discharged by the +kernel (generated by scripts/verify/gen-discharged.py). -/ + +namespace SolidCore.Verify.VC.Token.Discharged + +open SolidCore.Verify.VC + +set_option maxRecDepth 100000 + +theorem ob_0 : dischargeAt SolidCore.Verify.VC.Export.Token.script 0 = true := by decide +kernel + +theorem ob_1 : dischargeAt SolidCore.Verify.VC.Export.Token.script 1 = true := by decide +kernel + +theorem ob_2 : dischargeAt SolidCore.Verify.VC.Export.Token.script 2 = true := by decide +kernel + +theorem ob_3 : dischargeAt SolidCore.Verify.VC.Export.Token.script 3 = true := by decide +kernel + +end SolidCore.Verify.VC.Token.Discharged diff --git a/Contracts/Token/VC/Discharged/Part1.lean b/Contracts/Token/VC/Discharged/Part1.lean new file mode 100644 index 00000000..a5bca0e7 --- /dev/null +++ b/Contracts/Token/VC/Discharged/Part1.lean @@ -0,0 +1,21 @@ +import Verify.VC.Discharge +import Contracts.Token.VC.Export + +/-! Obligations 4 to 7 of `SolidCore.Verify.VC.Export.Token.script`, each discharged by the +kernel (generated by scripts/verify/gen-discharged.py). -/ + +namespace SolidCore.Verify.VC.Token.Discharged + +open SolidCore.Verify.VC + +set_option maxRecDepth 100000 + +theorem ob_4 : dischargeAt SolidCore.Verify.VC.Export.Token.script 4 = true := by decide +kernel + +theorem ob_5 : dischargeAt SolidCore.Verify.VC.Export.Token.script 5 = true := by decide +kernel + +theorem ob_6 : dischargeAt SolidCore.Verify.VC.Export.Token.script 6 = true := by decide +kernel + +theorem ob_7 : dischargeAt SolidCore.Verify.VC.Export.Token.script 7 = true := by decide +kernel + +end SolidCore.Verify.VC.Token.Discharged diff --git a/Contracts/Token/VC/Discharged/Part2.lean b/Contracts/Token/VC/Discharged/Part2.lean new file mode 100644 index 00000000..95bc2d85 --- /dev/null +++ b/Contracts/Token/VC/Discharged/Part2.lean @@ -0,0 +1,21 @@ +import Verify.VC.Discharge +import Contracts.Token.VC.Export + +/-! Obligations 8 to 11 of `SolidCore.Verify.VC.Export.Token.script`, each discharged by the +kernel (generated by scripts/verify/gen-discharged.py). -/ + +namespace SolidCore.Verify.VC.Token.Discharged + +open SolidCore.Verify.VC + +set_option maxRecDepth 100000 + +theorem ob_8 : dischargeAt SolidCore.Verify.VC.Export.Token.script 8 = true := by decide +kernel + +theorem ob_9 : dischargeAt SolidCore.Verify.VC.Export.Token.script 9 = true := by decide +kernel + +theorem ob_10 : dischargeAt SolidCore.Verify.VC.Export.Token.script 10 = true := by decide +kernel + +theorem ob_11 : dischargeAt SolidCore.Verify.VC.Export.Token.script 11 = true := by decide +kernel + +end SolidCore.Verify.VC.Token.Discharged diff --git a/Contracts/Token/VC/Discharged/Part3.lean b/Contracts/Token/VC/Discharged/Part3.lean new file mode 100644 index 00000000..854ed6c8 --- /dev/null +++ b/Contracts/Token/VC/Discharged/Part3.lean @@ -0,0 +1,21 @@ +import Verify.VC.Discharge +import Contracts.Token.VC.Export + +/-! Obligations 12 to 15 of `SolidCore.Verify.VC.Export.Token.script`, each discharged by the +kernel (generated by scripts/verify/gen-discharged.py). -/ + +namespace SolidCore.Verify.VC.Token.Discharged + +open SolidCore.Verify.VC + +set_option maxRecDepth 100000 + +theorem ob_12 : dischargeAt SolidCore.Verify.VC.Export.Token.script 12 = true := by decide +kernel + +theorem ob_13 : dischargeAt SolidCore.Verify.VC.Export.Token.script 13 = true := by decide +kernel + +theorem ob_14 : dischargeAt SolidCore.Verify.VC.Export.Token.script 14 = true := by decide +kernel + +theorem ob_15 : dischargeAt SolidCore.Verify.VC.Export.Token.script 15 = true := by decide +kernel + +end SolidCore.Verify.VC.Token.Discharged diff --git a/Contracts/Token/VC/Export.lean b/Contracts/Token/VC/Export.lean new file mode 100644 index 00000000..df21fb07 --- /dev/null +++ b/Contracts/Token/VC/Export.lean @@ -0,0 +1,354 @@ +-- Generated by solar-verify --dump-lean. Do not edit. + +import Verify.VC.Term + +namespace SolidCore.Verify.VC.Export.Token + +open SolidCore.Verify.VC + +/-- The commands solar-verify sent the solver. -/ +def script : List Cmd := [ + .push, + .raw "; ===== Token.constructor", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@17" .arr, + .elem "__balance@17" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@18")]), (.app "<=" [(.ivar "__code_epoch@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@19" .bool, + .assert (.app "=" [(.bvar "g@19"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "msg.sender@2")])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [(.app "=" [(.num 0), (.num 0)])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.mint", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "to@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "to@23")]), (.app "<=" [(.ivar "to@23"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "amount@24" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@24")]), (.app "<=" [(.ivar "amount@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@26" .bool, + .assert (.app "=" [(.bvar "g@26"), (.app "and" [(.bvar "g@25"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "g@27" .bool, + .assert (.app "=" [(.bvar "g@27"), (.app "and" [(.bvar "g@26"), (.app "=" [(.ivar "msg.sender@2"), (.ivar "owner@20")])])]), + .decl "arith@28" .int, + .assert (.app "=" [(.ivar "arith@28"), (.app "+" [(.ivar "totalSupply@19"), (.ivar "amount@24")])]), + .decl "g@29" .bool, + .assert (.app "=" [(.bvar "g@29"), (.app "and" [(.bvar "g@27"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@28")]), (.app "<=" [(.ivar "arith@28"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "sumBalances@30" .int, + .assert (.app "=" [(.ivar "sumBalances@30"), (.app "+" [(.ivar "sumBalances@17"), (.ivar "amount@24")])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@31" .int, + .assert (.app "=" [(.ivar "arith@31"), (.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")])]), + .decl "g@32" .bool, + .assert (.app "=" [(.bvar "g@32"), (.app "and" [(.bvar "g@29"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@31")]), (.app "<=" [(.ivar "arith@31"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@33" .arr, + .assert (.app "=" [(.avar "balanceOf@33"), (.app "store" [(.avar "balanceOf@18"), (.ivar "to@23"), (.ivar "arith@31")])]), + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")]), (.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.ivar "arith@28"), (.app "+" [(.ivar "totalSupply@19"), (.ivar "amount@24")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.all "a!34" (.app "=>" [(.app "and" [(.app "and" [(.app "<=" [(.num 0), (.ivar "a!34")]), (.app "<=" [(.ivar "a!34"), (.num 1461501637330902918203684832716283019655932542975)])])]), (.app "=>" [(.app "not" [(.app "=" [(.ivar "a!34"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "a!34")]), (.app "select" [(.avar "balanceOf@18"), (.ivar "a!34")])])])]))]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.ivar "arith@28"), (.ivar "sumBalances@30")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.transfer", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "to@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "to@23")]), (.app "<=" [(.ivar "to@23"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "amount@24" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@24")]), (.app "<=" [(.ivar "amount@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@26" .bool, + .assert (.app "=" [(.bvar "g@26"), (.app "and" [(.bvar "g@25"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "bal@27" .int, + .assert (.app "=" [(.ivar "bal@27"), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), + .decl "g@28" .bool, + .assert (.app "=" [(.bvar "g@28"), (.app "and" [(.bvar "g@26"), (.app ">=" [(.ivar "bal@27"), (.ivar "amount@24")])])]), + .decl "arith@29" .int, + .assert (.app "=" [(.ivar "arith@29"), (.app "-" [(.ivar "bal@27"), (.ivar "amount@24")])]), + .decl "g@30" .bool, + .assert (.app "=" [(.bvar "g@30"), (.app "and" [(.bvar "g@28"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@29")]), (.app "<=" [(.ivar "arith@29"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@31" .arr, + .assert (.app "=" [(.avar "balanceOf@31"), (.app "store" [(.avar "balanceOf@18"), (.ivar "msg.sender@2"), (.ivar "arith@29")])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@32" .int, + .assert (.app "=" [(.ivar "arith@32"), (.app "+" [(.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")]), (.ivar "amount@24")])]), + .decl "g@33" .bool, + .assert (.app "=" [(.bvar "g@33"), (.app "and" [(.bvar "g@30"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@32")]), (.app "<=" [(.ivar "arith@32"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@34" .arr, + .assert (.app "=" [(.avar "balanceOf@34"), (.app "store" [(.avar "balanceOf@31"), (.ivar "to@23"), (.ivar "arith@32")])]), + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@34"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [(.app "=>" [(.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "msg.sender@2")]), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@24")])])])]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@34"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [(.app "=>" [(.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "to@23")]), (.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")])])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [(.all "a!35" (.app "=>" [(.app "and" [(.app "and" [(.app "<=" [(.num 0), (.ivar "a!35")]), (.app "<=" [(.ivar "a!35"), (.num 1461501637330902918203684832716283019655932542975)])])]), (.app "=>" [(.app "and" [(.app "not" [(.app "=" [(.ivar "a!35"), (.ivar "msg.sender@2")])]), (.app "not" [(.app "=" [(.ivar "a!35"), (.ivar "to@23")])])]), (.app "=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "a!35")]), (.app "select" [(.avar "balanceOf@18"), (.ivar "a!35")])])])]))]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [(.app "=" [(.ivar "totalSupply@19"), (.ivar "totalSupply@19")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.burn", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "amount@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@23")]), (.app "<=" [(.ivar "amount@23"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@24" .bool, + .assert (.app "=" [(.bvar "g@24"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [(.bvar "g@24"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@26" .int, + .assert (.app "=" [(.ivar "arith@26"), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@23")])]), + .decl "g@27" .bool, + .assert (.app "=" [(.bvar "g@27"), (.app "and" [(.bvar "g@25"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@26")]), (.app "<=" [(.ivar "arith@26"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@28" .arr, + .assert (.app "=" [(.avar "balanceOf@28"), (.app "store" [(.avar "balanceOf@18"), (.ivar "msg.sender@2"), (.ivar "arith@26")])]), + .decl "sumBalances@29" .int, + .assert (.app "=" [(.ivar "sumBalances@29"), (.app "-" [(.ivar "sumBalances@17"), (.ivar "amount@23")])]), + .decl "arith@30" .int, + .assert (.app "=" [(.ivar "arith@30"), (.app "-" [(.ivar "totalSupply@19"), (.ivar "amount@23")])]), + .decl "g@31" .bool, + .assert (.app "=" [(.bvar "g@31"), (.app "and" [(.bvar "g@27"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@30")]), (.app "<=" [(.ivar "arith@30"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [(.app "=" [(.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")]), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@23")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [(.app "=" [(.ivar "arith@30"), (.ivar "sumBalances@29")])]), + .checkSat, + .pop, + .pop +] + +/-- The transcript, as solar-verify wrote it. -/ +def transcript : String := "(push 1)\n; ===== Token.constructor\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@17| (Array Int Int))\n;@elem |__balance@17| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@18| Int)\n(assert (and (<= 0 |__code_epoch@18|) (<= |__code_epoch@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@19| Bool)\n(assert (= |g@19| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@19|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@19|)\n(assert (not (= |msg.sender@2| |msg.sender@2|)))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@19|)\n(assert (not (= 0 0)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.mint\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |to@23| Int)\n(assert (and (<= 0 |to@23|) (<= |to@23| 1461501637330902918203684832716283019655932542975)))\n(declare-const |amount@24| Int)\n(assert (and (<= 0 |amount@24|) (<= |amount@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@26| Bool)\n(assert (= |g@26| (and |g@25| (= |msg.value@3| 0))))\n(declare-const |g@27| Bool)\n(assert (= |g@27| (and |g@26| (= |msg.sender@2| |owner@20|))))\n(declare-const |arith@28| Int)\n(assert (= |arith@28| (+ |totalSupply@19| |amount@24|)))\n(declare-const |g@29| Bool)\n(assert (= |g@29| (and |g@27| (and (<= 0 |arith@28|) (<= |arith@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |sumBalances@30| Int)\n(assert (= |sumBalances@30| (+ |sumBalances@17| |amount@24|)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@31| Int)\n(assert (= |arith@31| (+ (select |balanceOf@18| |to@23|) |amount@24|)))\n(declare-const |g@32| Bool)\n(assert (= |g@32| (and |g@29| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@33| (Array Int Int))\n(assert (= |balanceOf@33| (store |balanceOf@18| |to@23| |arith@31|)))\n(push 1)\n(assert |g@32|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@33| |to@23|)) (<= (select |balanceOf@33| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@32|)\n(assert (not (= (select |balanceOf@33| |to@23|) (+ (select |balanceOf@18| |to@23|) |amount@24|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (= |arith@28| (+ |totalSupply@19| |amount@24|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (forall ((|a!34| Int)) (=> (and (and (<= 0 |a!34|) (<= |a!34| 1461501637330902918203684832716283019655932542975))) (=> (not (= |a!34| |to@23|)) (= (select |balanceOf@33| |a!34|) (select |balanceOf@18| |a!34|)))))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (= |arith@28| |sumBalances@30|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.transfer\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |to@23| Int)\n(assert (and (<= 0 |to@23|) (<= |to@23| 1461501637330902918203684832716283019655932542975)))\n(declare-const |amount@24| Int)\n(assert (and (<= 0 |amount@24|) (<= |amount@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@26| Bool)\n(assert (= |g@26| (and |g@25| (= |msg.value@3| 0))))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |bal@27| Int)\n(assert (= |bal@27| (select |balanceOf@18| |msg.sender@2|)))\n(declare-const |g@28| Bool)\n(assert (= |g@28| (and |g@26| (>= |bal@27| |amount@24|))))\n(declare-const |arith@29| Int)\n(assert (= |arith@29| (- |bal@27| |amount@24|)))\n(declare-const |g@30| Bool)\n(assert (= |g@30| (and |g@28| (and (<= 0 |arith@29|) (<= |arith@29| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@31| (Array Int Int))\n(assert (= |balanceOf@31| (store |balanceOf@18| |msg.sender@2| |arith@29|)))\n(assert (and (<= 0 (select |balanceOf@31| |to@23|)) (<= (select |balanceOf@31| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@32| Int)\n(assert (= |arith@32| (+ (select |balanceOf@31| |to@23|) |amount@24|)))\n(declare-const |g@33| Bool)\n(assert (= |g@33| (and |g@30| (and (<= 0 |arith@32|) (<= |arith@32| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@34| (Array Int Int))\n(assert (= |balanceOf@34| (store |balanceOf@31| |to@23| |arith@32|)))\n(push 1)\n(assert |g@33|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@34| |msg.sender@2|)) (<= (select |balanceOf@34| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@33|)\n(assert (not (=> (not (= |msg.sender@2| |to@23|)) (= (select |balanceOf@34| |msg.sender@2|) (- (select |balanceOf@18| |msg.sender@2|) |amount@24|)))))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@34| |to@23|)) (<= (select |balanceOf@34| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@33|)\n(assert (not (=> (not (= |msg.sender@2| |to@23|)) (= (select |balanceOf@34| |to@23|) (+ (select |balanceOf@18| |to@23|) |amount@24|)))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@33|)\n(assert (not (forall ((|a!35| Int)) (=> (and (and (<= 0 |a!35|) (<= |a!35| 1461501637330902918203684832716283019655932542975))) (=> (and (not (= |a!35| |msg.sender@2|)) (not (= |a!35| |to@23|))) (= (select |balanceOf@34| |a!35|) (select |balanceOf@18| |a!35|)))))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@33|)\n(assert (not (= |totalSupply@19| |totalSupply@19|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.burn\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |amount@23| Int)\n(assert (and (<= 0 |amount@23|) (<= |amount@23| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@24| Bool)\n(assert (= |g@24| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and |g@24| (= |msg.value@3| 0))))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@26| Int)\n(assert (= |arith@26| (- (select |balanceOf@18| |msg.sender@2|) |amount@23|)))\n(declare-const |g@27| Bool)\n(assert (= |g@27| (and |g@25| (and (<= 0 |arith@26|) (<= |arith@26| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@28| (Array Int Int))\n(assert (= |balanceOf@28| (store |balanceOf@18| |msg.sender@2| |arith@26|)))\n(declare-const |sumBalances@29| Int)\n(assert (= |sumBalances@29| (- |sumBalances@17| |amount@23|)))\n(declare-const |arith@30| Int)\n(assert (= |arith@30| (- |totalSupply@19| |amount@23|)))\n(declare-const |g@31| Bool)\n(assert (= |g@31| (and |g@27| (and (<= 0 |arith@30|) (<= |arith@30| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(push 1)\n(assert |g@31|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@28| |msg.sender@2|)) (<= (select |balanceOf@28| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@31|)\n(assert (not (= (select |balanceOf@28| |msg.sender@2|) (- (select |balanceOf@18| |msg.sender@2|) |amount@23|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@31|)\n(assert (not (= |arith@30| |sumBalances@29|)))\n(check-sat)\n(pop 1)\n(pop 1)\n" + +end SolidCore.Verify.VC.Export.Token diff --git a/Contracts/Token/VC/FromScript.lean b/Contracts/Token/VC/FromScript.lean new file mode 100644 index 00000000..9a6f0782 --- /dev/null +++ b/Contracts/Token/VC/FromScript.lean @@ -0,0 +1,26 @@ +import Contracts.Token.VC.Discharged +import Contracts.Token.VC.Transfer + +/-! +# Token's triples from solar-verify's script, its verdict discharged by the kernel + +\`transfer_triple\` and \`burn_obligation\` (Contracts/Token/VC) take solar-verify's verdict +\`Valid Export.Token.script\` as a hypothesis; \`Discharged.script_valid\` proves it in the kernel +(\`dischargeScript\`), so they hold with \`HashInj\` as the only hypothesis. +-/ + +namespace SolidCore.Verify.VC.Token + +open SolidCore.Verify.VC + +/-- \`Token.transfer\`'s three clauses from solar-verify's own obligations, with no verdict. -/ +theorem transfer_triple_of_script (inj : HashInj) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Triple fuel c (stageScope fnTransfer [(2, 4096)]) (fun _ => True) trPost := + transfer_triple Discharged.script_valid inj hc + +/-- info: 'SolidCore.Verify.VC.Token.transfer_triple_of_script' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms transfer_triple_of_script + +end SolidCore.Verify.VC.Token diff --git a/Contracts/Token/VC/Mutant/SpecMut.lean b/Contracts/Token/VC/Mutant/SpecMut.lean new file mode 100644 index 00000000..84ac5c32 --- /dev/null +++ b/Contracts/Token/VC/Mutant/SpecMut.lean @@ -0,0 +1,354 @@ +-- Generated by solar-verify --dump-lean. Do not edit. + +import Verify.VC.Term + +namespace SolidCore.Verify.VC.Export.Mutant.TokenSpecMut + +open SolidCore.Verify.VC + +/-- The commands solar-verify sent the solver. -/ +def script : List Cmd := [ + .push, + .raw "; ===== Token.constructor", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@17" .arr, + .elem "__balance@17" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@18")]), (.app "<=" [(.ivar "__code_epoch@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@19" .bool, + .assert (.app "=" [(.bvar "g@19"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "msg.sender@2")])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [(.app "=" [(.num 0), (.num 0)])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.mint", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "to@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "to@23")]), (.app "<=" [(.ivar "to@23"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "amount@24" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@24")]), (.app "<=" [(.ivar "amount@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@26" .bool, + .assert (.app "=" [(.bvar "g@26"), (.app "and" [(.bvar "g@25"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "g@27" .bool, + .assert (.app "=" [(.bvar "g@27"), (.app "and" [(.bvar "g@26"), (.app "=" [(.ivar "msg.sender@2"), (.ivar "owner@20")])])]), + .decl "arith@28" .int, + .assert (.app "=" [(.ivar "arith@28"), (.app "+" [(.ivar "totalSupply@19"), (.ivar "amount@24")])]), + .decl "g@29" .bool, + .assert (.app "=" [(.bvar "g@29"), (.app "and" [(.bvar "g@27"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@28")]), (.app "<=" [(.ivar "arith@28"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "sumBalances@30" .int, + .assert (.app "=" [(.ivar "sumBalances@30"), (.app "+" [(.ivar "sumBalances@17"), (.ivar "amount@24")])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@31" .int, + .assert (.app "=" [(.ivar "arith@31"), (.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")])]), + .decl "g@32" .bool, + .assert (.app "=" [(.bvar "g@32"), (.app "and" [(.bvar "g@29"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@31")]), (.app "<=" [(.ivar "arith@31"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@33" .arr, + .assert (.app "=" [(.avar "balanceOf@33"), (.app "store" [(.avar "balanceOf@18"), (.ivar "to@23"), (.ivar "arith@31")])]), + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")]), (.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.ivar "arith@28"), (.app "+" [(.ivar "totalSupply@19"), (.ivar "amount@24")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.all "a!34" (.app "=>" [(.app "and" [(.app "and" [(.app "<=" [(.num 0), (.ivar "a!34")]), (.app "<=" [(.ivar "a!34"), (.num 1461501637330902918203684832716283019655932542975)])])]), (.app "=>" [(.app "not" [(.app "=" [(.ivar "a!34"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "a!34")]), (.app "select" [(.avar "balanceOf@18"), (.ivar "a!34")])])])]))]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.ivar "arith@28"), (.ivar "sumBalances@30")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.transfer", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "to@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "to@23")]), (.app "<=" [(.ivar "to@23"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "amount@24" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@24")]), (.app "<=" [(.ivar "amount@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@26" .bool, + .assert (.app "=" [(.bvar "g@26"), (.app "and" [(.bvar "g@25"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "bal@27" .int, + .assert (.app "=" [(.ivar "bal@27"), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), + .decl "g@28" .bool, + .assert (.app "=" [(.bvar "g@28"), (.app "and" [(.bvar "g@26"), (.app ">=" [(.ivar "bal@27"), (.ivar "amount@24")])])]), + .decl "arith@29" .int, + .assert (.app "=" [(.ivar "arith@29"), (.app "-" [(.ivar "bal@27"), (.ivar "amount@24")])]), + .decl "g@30" .bool, + .assert (.app "=" [(.bvar "g@30"), (.app "and" [(.bvar "g@28"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@29")]), (.app "<=" [(.ivar "arith@29"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@31" .arr, + .assert (.app "=" [(.avar "balanceOf@31"), (.app "store" [(.avar "balanceOf@18"), (.ivar "msg.sender@2"), (.ivar "arith@29")])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@32" .int, + .assert (.app "=" [(.ivar "arith@32"), (.app "+" [(.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")]), (.ivar "amount@24")])]), + .decl "g@33" .bool, + .assert (.app "=" [(.bvar "g@33"), (.app "and" [(.bvar "g@30"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@32")]), (.app "<=" [(.ivar "arith@32"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@34" .arr, + .assert (.app "=" [(.avar "balanceOf@34"), (.app "store" [(.avar "balanceOf@31"), (.ivar "to@23"), (.ivar "arith@32")])]), + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@34"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [(.app "=>" [(.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "msg.sender@2")]), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@24")])])])]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@34"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [(.app "=>" [(.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "to@23")]), (.app "+" [(.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")]), (.num 1)])])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [(.all "a!35" (.app "=>" [(.app "and" [(.app "and" [(.app "<=" [(.num 0), (.ivar "a!35")]), (.app "<=" [(.ivar "a!35"), (.num 1461501637330902918203684832716283019655932542975)])])]), (.app "=>" [(.app "and" [(.app "not" [(.app "=" [(.ivar "a!35"), (.ivar "msg.sender@2")])]), (.app "not" [(.app "=" [(.ivar "a!35"), (.ivar "to@23")])])]), (.app "=" [(.app "select" [(.avar "balanceOf@34"), (.ivar "a!35")]), (.app "select" [(.avar "balanceOf@18"), (.ivar "a!35")])])])]))]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@33"), + .assert (.app "not" [(.app "=" [(.ivar "totalSupply@19"), (.ivar "totalSupply@19")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.burn", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "amount@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@23")]), (.app "<=" [(.ivar "amount@23"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@24" .bool, + .assert (.app "=" [(.bvar "g@24"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [(.bvar "g@24"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@26" .int, + .assert (.app "=" [(.ivar "arith@26"), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@23")])]), + .decl "g@27" .bool, + .assert (.app "=" [(.bvar "g@27"), (.app "and" [(.bvar "g@25"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@26")]), (.app "<=" [(.ivar "arith@26"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@28" .arr, + .assert (.app "=" [(.avar "balanceOf@28"), (.app "store" [(.avar "balanceOf@18"), (.ivar "msg.sender@2"), (.ivar "arith@26")])]), + .decl "sumBalances@29" .int, + .assert (.app "=" [(.ivar "sumBalances@29"), (.app "-" [(.ivar "sumBalances@17"), (.ivar "amount@23")])]), + .decl "arith@30" .int, + .assert (.app "=" [(.ivar "arith@30"), (.app "-" [(.ivar "totalSupply@19"), (.ivar "amount@23")])]), + .decl "g@31" .bool, + .assert (.app "=" [(.bvar "g@31"), (.app "and" [(.bvar "g@27"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@30")]), (.app "<=" [(.ivar "arith@30"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [(.app "=" [(.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")]), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@23")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [(.app "=" [(.ivar "arith@30"), (.ivar "sumBalances@29")])]), + .checkSat, + .pop, + .pop +] + +/-- The transcript, as solar-verify wrote it. -/ +def transcript : String := "(push 1)\n; ===== Token.constructor\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@17| (Array Int Int))\n;@elem |__balance@17| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@18| Int)\n(assert (and (<= 0 |__code_epoch@18|) (<= |__code_epoch@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@19| Bool)\n(assert (= |g@19| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@19|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@19|)\n(assert (not (= |msg.sender@2| |msg.sender@2|)))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@19|)\n(assert (not (= 0 0)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.mint\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |to@23| Int)\n(assert (and (<= 0 |to@23|) (<= |to@23| 1461501637330902918203684832716283019655932542975)))\n(declare-const |amount@24| Int)\n(assert (and (<= 0 |amount@24|) (<= |amount@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@26| Bool)\n(assert (= |g@26| (and |g@25| (= |msg.value@3| 0))))\n(declare-const |g@27| Bool)\n(assert (= |g@27| (and |g@26| (= |msg.sender@2| |owner@20|))))\n(declare-const |arith@28| Int)\n(assert (= |arith@28| (+ |totalSupply@19| |amount@24|)))\n(declare-const |g@29| Bool)\n(assert (= |g@29| (and |g@27| (and (<= 0 |arith@28|) (<= |arith@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |sumBalances@30| Int)\n(assert (= |sumBalances@30| (+ |sumBalances@17| |amount@24|)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@31| Int)\n(assert (= |arith@31| (+ (select |balanceOf@18| |to@23|) |amount@24|)))\n(declare-const |g@32| Bool)\n(assert (= |g@32| (and |g@29| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@33| (Array Int Int))\n(assert (= |balanceOf@33| (store |balanceOf@18| |to@23| |arith@31|)))\n(push 1)\n(assert |g@32|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@33| |to@23|)) (<= (select |balanceOf@33| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@32|)\n(assert (not (= (select |balanceOf@33| |to@23|) (+ (select |balanceOf@18| |to@23|) |amount@24|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (= |arith@28| (+ |totalSupply@19| |amount@24|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (forall ((|a!34| Int)) (=> (and (and (<= 0 |a!34|) (<= |a!34| 1461501637330902918203684832716283019655932542975))) (=> (not (= |a!34| |to@23|)) (= (select |balanceOf@33| |a!34|) (select |balanceOf@18| |a!34|)))))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (= |arith@28| |sumBalances@30|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.transfer\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |to@23| Int)\n(assert (and (<= 0 |to@23|) (<= |to@23| 1461501637330902918203684832716283019655932542975)))\n(declare-const |amount@24| Int)\n(assert (and (<= 0 |amount@24|) (<= |amount@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@26| Bool)\n(assert (= |g@26| (and |g@25| (= |msg.value@3| 0))))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |bal@27| Int)\n(assert (= |bal@27| (select |balanceOf@18| |msg.sender@2|)))\n(declare-const |g@28| Bool)\n(assert (= |g@28| (and |g@26| (>= |bal@27| |amount@24|))))\n(declare-const |arith@29| Int)\n(assert (= |arith@29| (- |bal@27| |amount@24|)))\n(declare-const |g@30| Bool)\n(assert (= |g@30| (and |g@28| (and (<= 0 |arith@29|) (<= |arith@29| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@31| (Array Int Int))\n(assert (= |balanceOf@31| (store |balanceOf@18| |msg.sender@2| |arith@29|)))\n(assert (and (<= 0 (select |balanceOf@31| |to@23|)) (<= (select |balanceOf@31| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@32| Int)\n(assert (= |arith@32| (+ (select |balanceOf@31| |to@23|) |amount@24|)))\n(declare-const |g@33| Bool)\n(assert (= |g@33| (and |g@30| (and (<= 0 |arith@32|) (<= |arith@32| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@34| (Array Int Int))\n(assert (= |balanceOf@34| (store |balanceOf@31| |to@23| |arith@32|)))\n(push 1)\n(assert |g@33|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@34| |msg.sender@2|)) (<= (select |balanceOf@34| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@33|)\n(assert (not (=> (not (= |msg.sender@2| |to@23|)) (= (select |balanceOf@34| |msg.sender@2|) (- (select |balanceOf@18| |msg.sender@2|) |amount@24|)))))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@34| |to@23|)) (<= (select |balanceOf@34| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@33|)\n(assert (not (=> (not (= |msg.sender@2| |to@23|)) (= (select |balanceOf@34| |to@23|) (+ (+ (select |balanceOf@18| |to@23|) |amount@24|) 1)))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@33|)\n(assert (not (forall ((|a!35| Int)) (=> (and (and (<= 0 |a!35|) (<= |a!35| 1461501637330902918203684832716283019655932542975))) (=> (and (not (= |a!35| |msg.sender@2|)) (not (= |a!35| |to@23|))) (= (select |balanceOf@34| |a!35|) (select |balanceOf@18| |a!35|)))))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@33|)\n(assert (not (= |totalSupply@19| |totalSupply@19|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.burn\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |amount@23| Int)\n(assert (and (<= 0 |amount@23|) (<= |amount@23| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@24| Bool)\n(assert (= |g@24| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and |g@24| (= |msg.value@3| 0))))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@26| Int)\n(assert (= |arith@26| (- (select |balanceOf@18| |msg.sender@2|) |amount@23|)))\n(declare-const |g@27| Bool)\n(assert (= |g@27| (and |g@25| (and (<= 0 |arith@26|) (<= |arith@26| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@28| (Array Int Int))\n(assert (= |balanceOf@28| (store |balanceOf@18| |msg.sender@2| |arith@26|)))\n(declare-const |sumBalances@29| Int)\n(assert (= |sumBalances@29| (- |sumBalances@17| |amount@23|)))\n(declare-const |arith@30| Int)\n(assert (= |arith@30| (- |totalSupply@19| |amount@23|)))\n(declare-const |g@31| Bool)\n(assert (= |g@31| (and |g@27| (and (<= 0 |arith@30|) (<= |arith@30| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(push 1)\n(assert |g@31|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@28| |msg.sender@2|)) (<= (select |balanceOf@28| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@31|)\n(assert (not (= (select |balanceOf@28| |msg.sender@2|) (- (select |balanceOf@18| |msg.sender@2|) |amount@23|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@31|)\n(assert (not (= |arith@30| |sumBalances@29|)))\n(check-sat)\n(pop 1)\n(pop 1)\n" + +end SolidCore.Verify.VC.Export.Mutant.TokenSpecMut diff --git a/Contracts/Token/VC/Mutant/SrcMut.lean b/Contracts/Token/VC/Mutant/SrcMut.lean new file mode 100644 index 00000000..fdbe7367 --- /dev/null +++ b/Contracts/Token/VC/Mutant/SrcMut.lean @@ -0,0 +1,358 @@ +-- Generated by solar-verify --dump-lean. Do not edit. + +import Verify.VC.Term + +namespace SolidCore.Verify.VC.Export.Mutant.TokenSrcMut + +open SolidCore.Verify.VC + +/-- The commands solar-verify sent the solver. -/ +def script : List Cmd := [ + .push, + .raw "; ===== Token.constructor", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "__balance@17" .arr, + .elem "__balance@17" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@18" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@18")]), (.app "<=" [(.ivar "__code_epoch@18"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@19" .bool, + .assert (.app "=" [(.bvar "g@19"), (.app "and" [.tt, (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "msg.sender@2")])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@19"), + .assert (.app "not" [(.app "=" [(.num 0), (.num 0)])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.mint", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "to@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "to@23")]), (.app "<=" [(.ivar "to@23"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "amount@24" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@24")]), (.app "<=" [(.ivar "amount@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@26" .bool, + .assert (.app "=" [(.bvar "g@26"), (.app "and" [(.bvar "g@25"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .decl "g@27" .bool, + .assert (.app "=" [(.bvar "g@27"), (.app "and" [(.bvar "g@26"), (.app "=" [(.ivar "msg.sender@2"), (.ivar "owner@20")])])]), + .decl "arith@28" .int, + .assert (.app "=" [(.ivar "arith@28"), (.app "+" [(.ivar "totalSupply@19"), (.ivar "amount@24")])]), + .decl "g@29" .bool, + .assert (.app "=" [(.bvar "g@29"), (.app "and" [(.bvar "g@27"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@28")]), (.app "<=" [(.ivar "arith@28"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "sumBalances@30" .int, + .assert (.app "=" [(.ivar "sumBalances@30"), (.app "+" [(.ivar "sumBalances@17"), (.ivar "amount@24")])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@31" .int, + .assert (.app "=" [(.ivar "arith@31"), (.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")])]), + .decl "g@32" .bool, + .assert (.app "=" [(.bvar "g@32"), (.app "and" [(.bvar "g@29"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@31")]), (.app "<=" [(.ivar "arith@31"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@33" .arr, + .assert (.app "=" [(.avar "balanceOf@33"), (.app "store" [(.avar "balanceOf@18"), (.ivar "to@23"), (.ivar "arith@31")])]), + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "to@23")]), (.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.ivar "arith@28"), (.app "+" [(.ivar "totalSupply@19"), (.ivar "amount@24")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.all "a!34" (.app "=>" [(.app "and" [(.app "and" [(.app "<=" [(.num 0), (.ivar "a!34")]), (.app "<=" [(.ivar "a!34"), (.num 1461501637330902918203684832716283019655932542975)])])]), (.app "=>" [(.app "not" [(.app "=" [(.ivar "a!34"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@33"), (.ivar "a!34")]), (.app "select" [(.avar "balanceOf@18"), (.ivar "a!34")])])])]))]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@32"), + .assert (.app "not" [(.app "=" [(.ivar "arith@28"), (.ivar "sumBalances@30")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.transfer", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "to@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "to@23")]), (.app "<=" [(.ivar "to@23"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "amount@24" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@24")]), (.app "<=" [(.ivar "amount@24"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@26" .bool, + .assert (.app "=" [(.bvar "g@26"), (.app "and" [(.bvar "g@25"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "bal@27" .int, + .assert (.app "=" [(.ivar "bal@27"), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), + .decl "g@28" .bool, + .assert (.app "=" [(.bvar "g@28"), (.app "and" [(.bvar "g@26"), (.app ">=" [(.ivar "bal@27"), (.ivar "amount@24")])])]), + .decl "arith@29" .int, + .assert (.app "=" [(.ivar "arith@29"), (.app "-" [(.ivar "bal@27"), (.ivar "amount@24")])]), + .decl "g@30" .bool, + .assert (.app "=" [(.bvar "g@30"), (.app "and" [(.bvar "g@28"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@29")]), (.app "<=" [(.ivar "arith@29"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@31" .arr, + .assert (.app "=" [(.avar "balanceOf@31"), (.app "store" [(.avar "balanceOf@18"), (.ivar "msg.sender@2"), (.ivar "arith@29")])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@32" .int, + .assert (.app "=" [(.ivar "arith@32"), (.app "+" [(.ivar "amount@24"), (.num 1)])]), + .decl "g@33" .bool, + .assert (.app "=" [(.bvar "g@33"), (.app "and" [(.bvar "g@30"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@32")]), (.app "<=" [(.ivar "arith@32"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "arith@34" .int, + .assert (.app "=" [(.ivar "arith@34"), (.app "+" [(.app "select" [(.avar "balanceOf@31"), (.ivar "to@23")]), (.ivar "arith@32")])]), + .decl "g@35" .bool, + .assert (.app "=" [(.bvar "g@35"), (.app "and" [(.bvar "g@33"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@34")]), (.app "<=" [(.ivar "arith@34"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@36" .arr, + .assert (.app "=" [(.avar "balanceOf@36"), (.app "store" [(.avar "balanceOf@31"), (.ivar "to@23"), (.ivar "arith@34")])]), + .push, + .assert (.bvar "g@35"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@36"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@36"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@35"), + .assert (.app "not" [(.app "=>" [(.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@36"), (.ivar "msg.sender@2")]), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@24")])])])]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@36"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@36"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@35"), + .assert (.app "not" [(.app "=>" [(.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.ivar "to@23")])]), (.app "=" [(.app "select" [(.avar "balanceOf@36"), (.ivar "to@23")]), (.app "+" [(.app "select" [(.avar "balanceOf@18"), (.ivar "to@23")]), (.ivar "amount@24")])])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@35"), + .assert (.app "not" [(.all "a!37" (.app "=>" [(.app "and" [(.app "and" [(.app "<=" [(.num 0), (.ivar "a!37")]), (.app "<=" [(.ivar "a!37"), (.num 1461501637330902918203684832716283019655932542975)])])]), (.app "=>" [(.app "and" [(.app "not" [(.app "=" [(.ivar "a!37"), (.ivar "msg.sender@2")])]), (.app "not" [(.app "=" [(.ivar "a!37"), (.ivar "to@23")])])]), (.app "=" [(.app "select" [(.avar "balanceOf@36"), (.ivar "a!37")]), (.app "select" [(.avar "balanceOf@18"), (.ivar "a!37")])])])]))]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@35"), + .assert (.app "not" [(.app "=" [(.ivar "totalSupply@19"), (.ivar "totalSupply@19")])]), + .checkSat, + .pop, + .pop, + .push, + .raw "; ===== Token.burn", + .decl "this@1" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "this@1")]), (.app "<=" [(.ivar "this@1"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "msg.sender@2" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sender@2")]), (.app "<=" [(.ivar "msg.sender@2"), (.num 1461501637330902918203684832716283019655932542975)])]), + .assert (.app "not" [(.app "=" [(.ivar "msg.sender@2"), (.num 0)])]), + .decl "msg.value@3" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.value@3")]), (.app "<=" [(.ivar "msg.value@3"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.timestamp@4" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.timestamp@4")]), (.app "<=" [(.ivar "block.timestamp@4"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.number@5" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.number@5")]), (.app "<=" [(.ivar "block.number@5"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.chainid@6" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.chainid@6")]), (.app "<=" [(.ivar "block.chainid@6"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "tx.origin@7" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.origin@7")]), (.app "<=" [(.ivar "tx.origin@7"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "tx.gasprice@8" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "tx.gasprice@8")]), (.app "<=" [(.ivar "tx.gasprice@8"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "msg.sig@9" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "msg.sig@9")]), (.app "<=" [(.ivar "msg.sig@9"), (.num 4294967295)])]), + .decl "msg.data@10" .int, + .decl "block.basefee@11" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.basefee@11")]), (.app "<=" [(.ivar "block.basefee@11"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.blobbasefee@12" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.blobbasefee@12")]), (.app "<=" [(.ivar "block.blobbasefee@12"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.coinbase@13" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.coinbase@13")]), (.app "<=" [(.ivar "block.coinbase@13"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "block.prevrandao@14" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.prevrandao@14")]), (.app "<=" [(.ivar "block.prevrandao@14"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.difficulty@15" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.difficulty@15")]), (.app "<=" [(.ivar "block.difficulty@15"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "block.gaslimit@16" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "block.gaslimit@16")]), (.app "<=" [(.ivar "block.gaslimit@16"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "sumBalances@17" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "sumBalances@17")]), (.app "<=" [(.ivar "sumBalances@17"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "balanceOf@18" .arr, + .elem "balanceOf@18" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "totalSupply@19" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "totalSupply@19")]), (.app "<=" [(.ivar "totalSupply@19"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "owner@20" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "owner@20")]), (.app "<=" [(.ivar "owner@20"), (.num 1461501637330902918203684832716283019655932542975)])]), + .decl "__balance@21" .arr, + .elem "__balance@21" 0 115792089237316195423570985008687907853269984665640564039457584007913129639935, + .decl "__code_epoch@22" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "__code_epoch@22")]), (.app "<=" [(.ivar "__code_epoch@22"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "amount@23" .int, + .assert (.app "and" [(.app "<=" [(.num 0), (.ivar "amount@23")]), (.app "<=" [(.ivar "amount@23"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "g@24" .bool, + .assert (.app "=" [(.bvar "g@24"), (.app "and" [.tt, (.app "=" [(.ivar "totalSupply@19"), (.ivar "sumBalances@17")])])]), + .decl "g@25" .bool, + .assert (.app "=" [(.bvar "g@25"), (.app "and" [(.bvar "g@24"), (.app "=" [(.ivar "msg.value@3"), (.num 0)])])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .decl "arith@26" .int, + .assert (.app "=" [(.ivar "arith@26"), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@23")])]), + .decl "g@27" .bool, + .assert (.app "=" [(.bvar "g@27"), (.app "and" [(.bvar "g@25"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@26")]), (.app "<=" [(.ivar "arith@26"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .decl "balanceOf@28" .arr, + .assert (.app "=" [(.avar "balanceOf@28"), (.app "store" [(.avar "balanceOf@18"), (.ivar "msg.sender@2"), (.ivar "arith@26")])]), + .decl "sumBalances@29" .int, + .assert (.app "=" [(.ivar "sumBalances@29"), (.app "-" [(.ivar "sumBalances@17"), (.ivar "amount@23")])]), + .decl "arith@30" .int, + .assert (.app "=" [(.ivar "arith@30"), (.app "-" [(.ivar "totalSupply@19"), (.ivar "amount@23")])]), + .decl "g@31" .bool, + .assert (.app "=" [(.bvar "g@31"), (.app "and" [(.bvar "g@27"), (.app "and" [(.app "<=" [(.num 0), (.ivar "arith@30")]), (.app "<=" [(.ivar "arith@30"), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])])])]), + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [.ff]), + .checkSat, + .pop, + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .assert (.app "and" [(.app "<=" [(.num 0), (.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")])]), (.app "<=" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.num 115792089237316195423570985008687907853269984665640564039457584007913129639935)])]), + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [(.app "=" [(.app "select" [(.avar "balanceOf@28"), (.ivar "msg.sender@2")]), (.app "-" [(.app "select" [(.avar "balanceOf@18"), (.ivar "msg.sender@2")]), (.ivar "amount@23")])])]), + .checkSat, + .pop, + .push, + .assert (.bvar "g@31"), + .assert (.app "not" [(.app "=" [(.ivar "arith@30"), (.ivar "sumBalances@29")])]), + .checkSat, + .pop, + .pop +] + +/-- The transcript, as solar-verify wrote it. -/ +def transcript : String := "(push 1)\n; ===== Token.constructor\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |__balance@17| (Array Int Int))\n;@elem |__balance@17| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@18| Int)\n(assert (and (<= 0 |__code_epoch@18|) (<= |__code_epoch@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@19| Bool)\n(assert (= |g@19| (and true (= |msg.value@3| 0))))\n(push 1)\n(assert |g@19|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@19|)\n(assert (not (= |msg.sender@2| |msg.sender@2|)))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@19|)\n(assert (not (= 0 0)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.mint\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |to@23| Int)\n(assert (and (<= 0 |to@23|) (<= |to@23| 1461501637330902918203684832716283019655932542975)))\n(declare-const |amount@24| Int)\n(assert (and (<= 0 |amount@24|) (<= |amount@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@26| Bool)\n(assert (= |g@26| (and |g@25| (= |msg.value@3| 0))))\n(declare-const |g@27| Bool)\n(assert (= |g@27| (and |g@26| (= |msg.sender@2| |owner@20|))))\n(declare-const |arith@28| Int)\n(assert (= |arith@28| (+ |totalSupply@19| |amount@24|)))\n(declare-const |g@29| Bool)\n(assert (= |g@29| (and |g@27| (and (<= 0 |arith@28|) (<= |arith@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |sumBalances@30| Int)\n(assert (= |sumBalances@30| (+ |sumBalances@17| |amount@24|)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@31| Int)\n(assert (= |arith@31| (+ (select |balanceOf@18| |to@23|) |amount@24|)))\n(declare-const |g@32| Bool)\n(assert (= |g@32| (and |g@29| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@33| (Array Int Int))\n(assert (= |balanceOf@33| (store |balanceOf@18| |to@23| |arith@31|)))\n(push 1)\n(assert |g@32|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@33| |to@23|)) (<= (select |balanceOf@33| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@32|)\n(assert (not (= (select |balanceOf@33| |to@23|) (+ (select |balanceOf@18| |to@23|) |amount@24|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (= |arith@28| (+ |totalSupply@19| |amount@24|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (forall ((|a!34| Int)) (=> (and (and (<= 0 |a!34|) (<= |a!34| 1461501637330902918203684832716283019655932542975))) (=> (not (= |a!34| |to@23|)) (= (select |balanceOf@33| |a!34|) (select |balanceOf@18| |a!34|)))))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@32|)\n(assert (not (= |arith@28| |sumBalances@30|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.transfer\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |to@23| Int)\n(assert (and (<= 0 |to@23|) (<= |to@23| 1461501637330902918203684832716283019655932542975)))\n(declare-const |amount@24| Int)\n(assert (and (<= 0 |amount@24|) (<= |amount@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@26| Bool)\n(assert (= |g@26| (and |g@25| (= |msg.value@3| 0))))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |bal@27| Int)\n(assert (= |bal@27| (select |balanceOf@18| |msg.sender@2|)))\n(declare-const |g@28| Bool)\n(assert (= |g@28| (and |g@26| (>= |bal@27| |amount@24|))))\n(declare-const |arith@29| Int)\n(assert (= |arith@29| (- |bal@27| |amount@24|)))\n(declare-const |g@30| Bool)\n(assert (= |g@30| (and |g@28| (and (<= 0 |arith@29|) (<= |arith@29| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@31| (Array Int Int))\n(assert (= |balanceOf@31| (store |balanceOf@18| |msg.sender@2| |arith@29|)))\n(assert (and (<= 0 (select |balanceOf@31| |to@23|)) (<= (select |balanceOf@31| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@32| Int)\n(assert (= |arith@32| (+ |amount@24| 1)))\n(declare-const |g@33| Bool)\n(assert (= |g@33| (and |g@30| (and (<= 0 |arith@32|) (<= |arith@32| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |arith@34| Int)\n(assert (= |arith@34| (+ (select |balanceOf@31| |to@23|) |arith@32|)))\n(declare-const |g@35| Bool)\n(assert (= |g@35| (and |g@33| (and (<= 0 |arith@34|) (<= |arith@34| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@36| (Array Int Int))\n(assert (= |balanceOf@36| (store |balanceOf@31| |to@23| |arith@34|)))\n(push 1)\n(assert |g@35|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@36| |msg.sender@2|)) (<= (select |balanceOf@36| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@35|)\n(assert (not (=> (not (= |msg.sender@2| |to@23|)) (= (select |balanceOf@36| |msg.sender@2|) (- (select |balanceOf@18| |msg.sender@2|) |amount@24|)))))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@36| |to@23|)) (<= (select |balanceOf@36| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |to@23|)) (<= (select |balanceOf@18| |to@23|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@35|)\n(assert (not (=> (not (= |msg.sender@2| |to@23|)) (= (select |balanceOf@36| |to@23|) (+ (select |balanceOf@18| |to@23|) |amount@24|)))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@35|)\n(assert (not (forall ((|a!37| Int)) (=> (and (and (<= 0 |a!37|) (<= |a!37| 1461501637330902918203684832716283019655932542975))) (=> (and (not (= |a!37| |msg.sender@2|)) (not (= |a!37| |to@23|))) (= (select |balanceOf@36| |a!37|) (select |balanceOf@18| |a!37|)))))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@35|)\n(assert (not (= |totalSupply@19| |totalSupply@19|)))\n(check-sat)\n(pop 1)\n(pop 1)\n(push 1)\n; ===== Token.burn\n(declare-const |this@1| Int)\n(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)))\n(declare-const |msg.sender@2| Int)\n(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)))\n(assert (not (= |msg.sender@2| 0)))\n(declare-const |msg.value@3| Int)\n(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.timestamp@4| Int)\n(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.number@5| Int)\n(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.chainid@6| Int)\n(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |tx.origin@7| Int)\n(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)))\n(declare-const |tx.gasprice@8| Int)\n(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |msg.sig@9| Int)\n(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)))\n(declare-const |msg.data@10| Int)\n(declare-const |block.basefee@11| Int)\n(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.blobbasefee@12| Int)\n(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.coinbase@13| Int)\n(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)))\n(declare-const |block.prevrandao@14| Int)\n(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.difficulty@15| Int)\n(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |block.gaslimit@16| Int)\n(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |sumBalances@17| Int)\n(assert (and (<= 0 |sumBalances@17|) (<= |sumBalances@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |balanceOf@18| (Array Int Int))\n;@elem |balanceOf@18| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |totalSupply@19| Int)\n(assert (and (<= 0 |totalSupply@19|) (<= |totalSupply@19| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |owner@20| Int)\n(assert (and (<= 0 |owner@20|) (<= |owner@20| 1461501637330902918203684832716283019655932542975)))\n(declare-const |__balance@21| (Array Int Int))\n;@elem |__balance@21| 0 115792089237316195423570985008687907853269984665640564039457584007913129639935\n(declare-const |__code_epoch@22| Int)\n(assert (and (<= 0 |__code_epoch@22|) (<= |__code_epoch@22| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |amount@23| Int)\n(assert (and (<= 0 |amount@23|) (<= |amount@23| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |g@24| Bool)\n(assert (= |g@24| (and true (= |totalSupply@19| |sumBalances@17|))))\n(declare-const |g@25| Bool)\n(assert (= |g@25| (and |g@24| (= |msg.value@3| 0))))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(declare-const |arith@26| Int)\n(assert (= |arith@26| (- (select |balanceOf@18| |msg.sender@2|) |amount@23|)))\n(declare-const |g@27| Bool)\n(assert (= |g@27| (and |g@25| (and (<= 0 |arith@26|) (<= |arith@26| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(declare-const |balanceOf@28| (Array Int Int))\n(assert (= |balanceOf@28| (store |balanceOf@18| |msg.sender@2| |arith@26|)))\n(declare-const |sumBalances@29| Int)\n(assert (= |sumBalances@29| (- |sumBalances@17| |amount@23|)))\n(declare-const |arith@30| Int)\n(assert (= |arith@30| (- |totalSupply@19| |amount@23|)))\n(declare-const |g@31| Bool)\n(assert (= |g@31| (and |g@27| (and (<= 0 |arith@30|) (<= |arith@30| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))))\n(push 1)\n(assert |g@31|)\n(assert (not false))\n(check-sat)\n(pop 1)\n(assert (and (<= 0 (select |balanceOf@28| |msg.sender@2|)) (<= (select |balanceOf@28| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(assert (and (<= 0 (select |balanceOf@18| |msg.sender@2|)) (<= (select |balanceOf@18| |msg.sender@2|) 115792089237316195423570985008687907853269984665640564039457584007913129639935)))\n(push 1)\n(assert |g@31|)\n(assert (not (= (select |balanceOf@28| |msg.sender@2|) (- (select |balanceOf@18| |msg.sender@2|) |amount@23|))))\n(check-sat)\n(pop 1)\n(push 1)\n(assert |g@31|)\n(assert (not (= |arith@30| |sumBalances@29|)))\n(check-sat)\n(pop 1)\n(pop 1)\n" + +end SolidCore.Verify.VC.Export.Mutant.TokenSrcMut diff --git a/Contracts/Token/VC/Mutants.lean b/Contracts/Token/VC/Mutants.lean new file mode 100644 index 00000000..f14d8c44 --- /dev/null +++ b/Contracts/Token/VC/Mutants.lean @@ -0,0 +1,43 @@ +import Contracts.Token.VC.Transfer +import Contracts.Token.VC.Mutant.SrcMut +import Contracts.Token.VC.Mutant.SpecMut + +/-! +# Mutants that break `transfer`'s binding + +Two copies of `scripts/verify/Token.sol`, each changed in one line, exported by the same +solar-verify (`scripts/verify/mutant/MANIFEST`): +* `TokenSrcMut` changes the source: `transfer` credits `amount + 1`. solar-verify's encoding of the + call's effect changes with it, so none of its obligations is the Lean obligation of + `transfer`'s clauses, which `trStore_eval` ties to what SolidCore does with the real source. +* `TokenSpecMut` changes the spec: the recipient's clause claims `old + amount + 1`. Its obligation + for that clause is not the one SolidCore's run supports. + +In both, `checkScript` rejects, so no verdict on a mutant yields `transfer_triple`'s clauses. +-/ + +namespace SolidCore.Verify.VC.Token + +open SolidCore.Verify.VC + +theorem srcMut_rejects_to : checkScript Export.Mutant.TokenSrcMut.script [(trHyps, trGoalTo)] = false := by + decide +kernel + +theorem srcMut_rejects_from : + checkScript Export.Mutant.TokenSrcMut.script [(trHyps, trGoalFrom)] = false := by + decide +kernel + +theorem srcMut_rejects_frame : + checkScript Export.Mutant.TokenSrcMut.script [(trHyps, trGoalFrame)] = false := by + decide +kernel + +theorem specMut_rejects_to : + checkScript Export.Mutant.TokenSpecMut.script [(trHyps, trGoalTo)] = false := by + decide +kernel + +/-- The unchanged clauses of the spec mutant still check: the rejection is the changed clause's. -/ +theorem specMut_keeps_from_frame : + checkScript Export.Mutant.TokenSpecMut.script [(trHyps, trGoalFrom), (trHyps, trGoalFrame)] = true := by + decide +kernel + +end SolidCore.Verify.VC.Token diff --git a/Contracts/Token/VC/Source.lean b/Contracts/Token/VC/Source.lean new file mode 100644 index 00000000..8e004dda --- /dev/null +++ b/Contracts/Token/VC/Source.lean @@ -0,0 +1,101 @@ +-- Generated from scripts/verify/Token.sol (solar-verify's crates/verify/examples/Token.sol) with solc 0.8.35 by scripts/solc_ast_to_lean_source.py. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Verify +namespace VC +namespace Source +namespace Token + +def importedSourceName : String := "scripts/verify/Token.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Token" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "balanceOf", + ty := Ty.mapping (Ty.address false) (Ty.uint 256), + visibility := some Visibility.public_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "totalSupply", + ty := Ty.uint 256, + visibility := some Visibility.public_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "owner", + ty := Ty.address false, + visibility := some Visibility.public_, + mutability := VarMutability.mutable, + override? := none, + init := none }), ContractItem.modifierDecl + { name := "onlyOwner" + params := [] + virtual := false + override? := none + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.ident "require") [Arg.positional (Expr.binary BinaryOp.eq (Expr.member (Expr.ident "msg") "sender") (Expr.ident "owner")), Arg.positional (Expr.literal (Literal.string "not owner"))]), Stmt.modifierPlaceholder]) }, (ContractItem.function + { kind := FunctionKind.constructor, + name := none, + visibility := some Visibility.public_, + mutability := StateMutability.nonpayable, + params := [], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "owner") AssignOp.assign (Expr.member (Expr.ident "msg") "sender"))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "mint", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "to", ty := Ty.address false, location := none }, { name := some "amount", ty := Ty.uint 256, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [{ target := { segments := ["onlyOwner"] }, args := [], hasArgList := false }], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "totalSupply") AssignOp.addAssign (Expr.ident "amount")), Stmt.expr (Expr.assign (Expr.index (Expr.ident "balanceOf") (Expr.ident "to")) AssignOp.addAssign (Expr.ident "amount"))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "transfer", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "to", ty := Ty.address false, location := none }, { name := some "amount", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.bool, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.varDecl [{ name := some "bal", ty := Ty.uint 256, location := none }] (some (Expr.index (Expr.ident "balanceOf") (Expr.member (Expr.ident "msg") "sender"))), Stmt.expr (Expr.call (Expr.ident "require") [Arg.positional (Expr.binary BinaryOp.ge (Expr.ident "bal") (Expr.ident "amount")), Arg.positional (Expr.literal (Literal.string "insufficient"))]), Stmt.expr (Expr.assign (Expr.index (Expr.ident "balanceOf") (Expr.member (Expr.ident "msg") "sender")) AssignOp.assign (Expr.binary BinaryOp.sub (Expr.ident "bal") (Expr.ident "amount"))), Stmt.expr (Expr.assign (Expr.index (Expr.ident "balanceOf") (Expr.ident "to")) AssignOp.addAssign (Expr.ident "amount")), Stmt.returnValues (some (Expr.literal (Literal.bool true)))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "burn", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "amount", ty := Ty.uint 256, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.index (Expr.ident "balanceOf") (Expr.member (Expr.ident "msg") "sender")) AssignOp.subAssign (Expr.ident "amount")), Stmt.expr (Expr.assign (Expr.ident "totalSupply") AssignOp.subAssign (Expr.ident "amount"))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.20", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end Token +end Source +end VC +end Verify +end SolidCore diff --git a/Contracts/Token/VC/Transfer.lean b/Contracts/Token/VC/Transfer.lean new file mode 100644 index 00000000..e62f68d4 --- /dev/null +++ b/Contracts/Token/VC/Transfer.lean @@ -0,0 +1,685 @@ +import Contracts.Token.VC.Burn + +/-! +# solar-verify's `Token.transfer`, bound to SolidCore + +`transfer`'s three ensures clauses on distinct addresses (the sender's and the recipient's new +balances, and every other balance unchanged) as a `Triple` against SolidCore's `Source.run`, proved +from solar-verify's own obligations: `transfer_triple` takes the verdict `Valid Export.Token.script`, +and its proof reads each clause off the obligation `checkScript_sound` gives, at the assignment +`trEnv` that a call binds. Nothing in the proof re-derives a clause in Lean: the bridge is the +binding lemma `trStore_eval`, which says that SolidCore's storage after the call, read through +`balanceOf`'s layout (`balanceOf[k]` at slot `keccak(k, 0)`), is solar-verify's array term `S2` at +`trEnv`, for every address. + +The binding is explicit: +* widths: `amount` is the call's second word, below `2 ^ 256`; `to` its first, which the erased tree + reverts on above `2 ^ 160 - 1` (any word is in scope, dirty ones included); +* environment: `msg.sender` is the stage's caller `callerWord`, `msg.value` is 0 (the stage's scope); +* storage: `totalSupply` is slot 1, `balanceOf` is the array `k ↦ storage (keccak(k, 0))`; +* ghost: `sumBalances` is not program state, so the assignment sets it to `totalSupply`, which is + what solar-verify's assumed invariant asks; the clauses proved here do not mention it; +* Keccak: `HashInj`, injectivity of the mapping slot on address keys, is a hypothesis of the + theorem, never an axiom. It is what makes `to`, the sender and every third address name distinct + slots. +-/ + +namespace SolidCore.Verify.VC.Token + +open SolidCore.Verify SolidCore.Verify.VC SolidCore.Refinement SolidCore.Refinement.Abi +open SolidCore.Refinement.Generic + +/-- `transfer` as the stage's ABI sees it: two words, any value below `2 ^ 256`. -/ +def fnTransfer : Fn := ⟨transferSel, [.uint 256, .uint 256]⟩ + +/-- The erasure of `transfer`, as the generic source stage computes it. -/ +def transferTree : Tree := + (Tree.ite + (WExpr.bin + (BinOp.gt) + (WExpr.arg 0) + (WExpr.lit 1461501637330902918203684832716283019655932542975)) + (Tree.halt false [] [] []) + (Tree.ite + (WExpr.un + (UnOp.iszero) + (WExpr.bin + (BinOp.lt) + (WExpr.sinit + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.arg 1))) + (Tree.ite + (WExpr.bin + (BinOp.lt) + (WExpr.sinit + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.arg 1)) + (Tree.halt + false + [OByte.lit 78, + OByte.lit 72, + OByte.lit 123, + OByte.lit 113, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 17] + [] + []) + (Tree.ite + (WExpr.bin + (BinOp.lt) + (WExpr.bin + (BinOp.add) + (WExpr.sel + (WExpr.bin + (BinOp.eq) + (WExpr.hash + (WExpr.arg 0) + (WExpr.lit 0)) + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.bin + (BinOp.sub) + (WExpr.sinit + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.arg 1)) + (WExpr.sinit + (WExpr.hash + (WExpr.arg 0) + (WExpr.lit 0)))) + (WExpr.arg 1)) + (WExpr.sel + (WExpr.bin + (BinOp.eq) + (WExpr.hash + (WExpr.arg 0) + (WExpr.lit 0)) + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.bin + (BinOp.sub) + (WExpr.sinit + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.arg 1)) + (WExpr.sinit + (WExpr.hash + (WExpr.arg 0) + (WExpr.lit 0))))) + (Tree.halt + false + [OByte.lit 78, + OByte.lit 72, + OByte.lit 123, + OByte.lit 113, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 17] + [] + []) + (Tree.halt + true + [OByte.byteOf (WExpr.lit 1) 0, + OByte.byteOf (WExpr.lit 1) 1, + OByte.byteOf (WExpr.lit 1) 2, + OByte.byteOf (WExpr.lit 1) 3, + OByte.byteOf (WExpr.lit 1) 4, + OByte.byteOf (WExpr.lit 1) 5, + OByte.byteOf (WExpr.lit 1) 6, + OByte.byteOf (WExpr.lit 1) 7, + OByte.byteOf (WExpr.lit 1) 8, + OByte.byteOf (WExpr.lit 1) 9, + OByte.byteOf (WExpr.lit 1) 10, + OByte.byteOf (WExpr.lit 1) 11, + OByte.byteOf (WExpr.lit 1) 12, + OByte.byteOf (WExpr.lit 1) 13, + OByte.byteOf (WExpr.lit 1) 14, + OByte.byteOf (WExpr.lit 1) 15, + OByte.byteOf (WExpr.lit 1) 16, + OByte.byteOf (WExpr.lit 1) 17, + OByte.byteOf (WExpr.lit 1) 18, + OByte.byteOf (WExpr.lit 1) 19, + OByte.byteOf (WExpr.lit 1) 20, + OByte.byteOf (WExpr.lit 1) 21, + OByte.byteOf (WExpr.lit 1) 22, + OByte.byteOf (WExpr.lit 1) 23, + OByte.byteOf (WExpr.lit 1) 24, + OByte.byteOf (WExpr.lit 1) 25, + OByte.byteOf (WExpr.lit 1) 26, + OByte.byteOf (WExpr.lit 1) 27, + OByte.byteOf (WExpr.lit 1) 28, + OByte.byteOf (WExpr.lit 1) 29, + OByte.byteOf (WExpr.lit 1) 30, + OByte.byteOf (WExpr.lit 1) 31] + [(WExpr.hash + (WExpr.arg 0) + (WExpr.lit 0), + WExpr.bin + (BinOp.add) + (WExpr.sel + (WExpr.bin + (BinOp.eq) + (WExpr.hash + (WExpr.arg 0) + (WExpr.lit 0)) + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.bin + (BinOp.sub) + (WExpr.sinit + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.arg 1)) + (WExpr.sinit + (WExpr.hash + (WExpr.arg 0) + (WExpr.lit 0)))) + (WExpr.arg 1)), + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0), + WExpr.bin + (BinOp.sub) + (WExpr.sinit + (WExpr.hash + (WExpr.lit 8192) + (WExpr.lit 0))) + (WExpr.arg 1))] + []))) + (Tree.halt + false + [OByte.lit 8, + OByte.lit 195, + OByte.lit 121, + OByte.lit 160, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 32, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 12, + OByte.lit 105, + OByte.lit 110, + OByte.lit 115, + OByte.lit 117, + OByte.lit 102, + OByte.lit 102, + OByte.lit 105, + OByte.lit 99, + OByte.lit 105, + OByte.lit 101, + OByte.lit 110, + OByte.lit 116, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0, + OByte.lit 0] + [] + []))) + +/-- How SolidCore dispatches `transfer` and the generic source stage erases it. -/ +def transferShape? : Option (Option (Nat × Option Tree)) := + match contract? with + | .ok c => some ((c.core.findFunctionBySelector? transferSel).map fun f => + (f.params.length, eraseFn (envOf c.core) fuel f)) + | .error _ => none + +kernel_rfl transferShape_eq transferShape? (some (some (2, some transferTree))) using selector_eq mkIdx_eq + +/-! ## The Lean obligations -/ + +namespace Ob + +def rcpt : Tm := .ivar "to" +def add (a b : Tm) : Tm := .app "+" [a, b] +def leA (t : Tm) : Tm := .app "<=" [t, .num (2 ^ 160 - 1)] +def sel (a i : Tm) : Tm := .app "select" [a, i] +def sto (a i v : Tm) : Tm := .app "store" [a, i, v] +def B : Tm := .avar "balanceOf" +/-- The balances after the sender's debit. -/ +def S1 : Tm := sto B ms (sub bal amt) +/-- `balanceOf` after the call, as solar-verify encodes it. -/ +def S2 : Tm := sto S1 rcpt (add (sel S1 rcpt) amt) + +end Ob + +open Ob in +/-- The facts every successful `transfer` meets at `trEnv`. -/ +def trHyps : List Tm := + [eq ts sum, eq mv (.num 0), .app ">=" [bal, amt], le0 (sub bal amt), leW (sub bal amt), + le0 (add (sel S1 rcpt) amt), leW (add (sel S1 rcpt) amt), arrFact "k" "balanceOf" (2 ^ 256 - 1), + le0 amt, leW amt, le0 rcpt, leA rcpt, le0 ts, leW ts, le0 sum, leW sum, le0 mv, leW mv, + .app "not" [eq ms (.num 0)], le0 ms, .app "<=" [ms, .num (2 ^ 160 - 1)]] + +open Ob in +/-- The sender's clause: `msg.sender != to ==> balanceOf[msg.sender] == old(…) - amount`. -/ +def trGoalFrom : Tm := .app "=>" [.app "not" [eq ms rcpt], eq (sel S2 ms) (sub bal amt)] + +open Ob in +/-- The recipient's clause: `msg.sender != to ==> balanceOf[rcpt] == old(balanceOf[rcpt]) + amount`. -/ +def trGoalTo : Tm := .app "=>" [.app "not" [eq ms rcpt], eq (sel S2 rcpt) (add (sel B rcpt) amt)] + +open Ob in +/-- The frame: every other address keeps its balance. -/ +def trGoalFrame : Tm := + .all "a" (.app "=>" [.app "and" [.app "and" [le0 (.ivar "a"), leA (.ivar "a")]], + .app "=>" [.app "and" [.app "not" [eq (.ivar "a") ms], .app "not" [eq (.ivar "a") rcpt]], + eq (sel S2 (.ivar "a")) (sel B (.ivar "a"))]]) + +/-- The Lean obligations of `transfer`'s clauses. -/ +def trObs : List (List Tm × Tm) := [(trHyps, trGoalFrom), (trHyps, trGoalTo), (trHyps, trGoalFrame)] + +/-- solar-verify's script for `Token` has obligations that `checkOb` normalizes to each of them. -/ +theorem transfer_check : checkScript Export.Token.script trObs = true := by + decide +kernel + + +/-! ## The binding -/ + +/-- Injectivity of `balanceOf`'s slot on address keys: distinct addresses name distinct slots. A +hypothesis on Keccak-256, stated where it is used, never assumed. -/ +def HashInj : Prop := ∀ x y, x < 2 ^ 160 → y < 2 ^ 160 → solHash x 0 = solHash y 0 → x = y + +/-- `balanceOf` as an array, through its storage layout. -/ +def balArr (s : Storage) : Int → Int := fun k => s (solHash k.toNat 0) + +/-- The assignment of solar-verify's names that a call of `transfer` binds: `to = t`, `amount = a`, +`msg.sender` the stage's caller, `totalSupply` slot 1, `balanceOf` its layout in the storage `s`, +the ghost `sumBalances` set to `totalSupply`, and every other name 0. -/ +def trEnv (t a : Nat) (s : Storage) : Env where + i := fun x => if x = "amount" then a else if x = "to" then t else if x = "msg.sender" then callerWord + else if x = "totalSupply" then s 1 else if x = "sumBalances" then s 1 else 0 + b := fun _ => False + a := fun x => if x = "balanceOf" then balArr s else fun _ => 0 + +/-- The recipient's balance after the debit: the sender's own when they are one address. -/ +def midTo (t a : Nat) (s : Storage) : Nat := if t = callerWord then s senderSlot - a else s (solHash t 0) + +theorem S2_eval (t a : Nat) (s : Storage) (j : Int) : + (Ob.S2.eval (trEnv t a s)).toArr j = + if j = t then (if t = callerWord then balArr s callerWord - a else balArr s t) + a + else if j = callerWord then balArr s callerWord - a else balArr s j := by + simp [Ob.S2, Ob.S1, Ob.sto, Ob.sel, Ob.add, Ob.B, Ob.rcpt, Ob.sub, Ob.bal, Ob.amt, Ob.ms, + Tm.eval, Tm.evalList, applyOp, Value.select, Value.store, Value.toArr, Value.toInt, trEnv, callerWord] + by_cases h1 : j = t <;> by_cases h2 : t = 8192 <;> by_cases h3 : j = 8192 <;> + simp [h1, h2, h3] <;> omega + +theorem hashT (t : Nat) : solHash t 0 % 2 ^ 256 = solHash t 0 := Nat.mod_eq_of_lt (solHash_lt t 0) + +/-- What a successful run of QtransferQ's erased tree shows: QtoQ is an address, the sender had +the amount, the recipient's credit does not overflow, and the storage changes in exactly the +recipient's and the sender's slots. QHashInjQ decides the tree's test of whether they are one. -/ +theorem tr_success (inj : HashInj) (s : Storage) (hs : ∀ k, s k < 2 ^ 256) (t a : Nat) + (ht : t < 2 ^ 256) (ha : a < 2 ^ 256) : + let R := transferTree.eval (valOf [t, a] s) + R.success = true → t < 2 ^ 160 ∧ a ≤ s senderSlot ∧ midTo t a s + a < 2 ^ 256 ∧ + ∀ n < 2 ^ 256, R.store n = if n = solHash t 0 then midTo t a s + a + else if n = senderSlot then s senderSlot - a else s n := by + intro R hR + have hsm : ∀ k, s k % 2 ^ 256 = s k := fun k => Nat.mod_eq_of_lt (hs k) + have ham : a % 2 ^ 256 = a := Nat.mod_eq_of_lt ha + have htm : t % 2 ^ 256 = t := Nat.mod_eq_of_lt ht + have hss : senderSlot % 2 ^ 256 = senderSlot := by decide + have h8 : 8192 % 2 ^ 256 = 8192 := by decide + have h0 : 0 % 2 ^ 256 = 0 := by decide + have hA : 1461501637330902918203684832716283019655932542975 % 2 ^ 256 = + 1461501637330902918203684832716283019655932542975 := by decide + have h1 := hs senderSlot + have hmid : midTo t a s = if t = 8192 then s senderSlot - a else s (solHash t 0) := rfl + simp only [R, transferTree, Tree.eval] at hR ⊢ + simp only [WExpr.eval, BinOp.eval, UnOp.eval, valOf, Generic.wordSize, List.getD_cons_zero, + List.getD_cons_succ, htm, hA, h8, h0, ham, hss, hsm, hashT, hash_eq] at hR ⊢ + split_ifs at hR ⊢ <;> simp only at hR + · rename_i hgt hlt _ hc hov + have hta : t < 2 ^ 160 := by omega + have ht8 : t = 8192 := inj t 8192 hta (by decide) (hc.trans hash_eq.symm) + subst ht8 + have hsub : (s senderSlot + (2 ^ 256 - a)) % 2 ^ 256 = s senderSlot - a := by omega + rw [hsub, Nat.mod_eq_of_lt (by omega : s senderSlot - a < 2 ^ 256)] at hov + have hm : midTo 8192 a s = s senderSlot - a := by simp [hmid] + refine ⟨hta, by omega, by omega, ?_⟩ + intro n hn + rw [hm, hc] + simp only [Writes.store, WExpr.eval, BinOp.eval, Generic.wordSize, List.getD_cons_zero, + List.getD_cons_succ, h8, h0, ham, hss, hsm, hashT, hash_eq, Nat.mod_eq_of_lt hn, hsub] + by_cases hn' : n = senderSlot + · subst hn'; simp; omega + · simp [hn', Ne.symm hn'] + · rename_i hgt hlt _ hc hov + have hta : t < 2 ^ 160 := by omega + have ht8 : t ≠ 8192 := fun h => hc (h ▸ hash_eq) + have hm : midTo t a s = s (solHash t 0) := by simp [hmid, ht8] + have hst := hs (solHash t 0) + have hno : s (solHash t 0) + a < 2 ^ 256 := by omega + refine ⟨hta, by omega, by omega, ?_⟩ + intro n hn + rw [hm] + simp only [Writes.store, WExpr.eval, BinOp.eval, Generic.wordSize, List.getD_cons_zero, + List.getD_cons_succ, htm, h8, h0, ham, hss, hsm, hashT, hash_eq, Nat.mod_eq_of_lt hn] + by_cases hn1 : n = solHash t 0 + · subst hn1; simp [hc]; omega + · by_cases hn2 : n = senderSlot + · subst hn2; simp [hc, Ne.symm hc]; omega + · simp [hn1, hn2, Ne.symm hn1, Ne.symm hn2] + +theorem balArr_nat (s : Storage) (x : Nat) : balArr s x = s (solHash x 0) := by simp [balArr] + +theorem balArr_caller (s : Storage) : balArr s callerWord = s senderSlot := by + rw [balArr_nat]; exact congrArg (fun n => ((s n : Nat) : Int)) hash_eq + + +section +variable (t a : Nat) (s : Storage) +@[simp] theorem trEnv_amount : (trEnv t a s).i "amount" = a := rfl +@[simp] theorem trEnv_to : (trEnv t a s).i "to" = t := rfl +@[simp] theorem trEnv_sender : (trEnv t a s).i "msg.sender" = 8192 := rfl +@[simp] theorem trEnv_bal : (trEnv t a s).a "balanceOf" = balArr s := rfl +end + +section +variable (t a : Nat) (s : Storage) (n : Int) +@[simp] theorem trEnvA_a : ((trEnv t a s).setI "a" n).i "a" = n := rfl +@[simp] theorem trEnvA_to : ((trEnv t a s).setI "a" n).i "to" = t := rfl +@[simp] theorem trEnvA_sender : ((trEnv t a s).setI "a" n).i "msg.sender" = 8192 := rfl +@[simp] theorem trEnvA_amount : ((trEnv t a s).setI "a" n).i "amount" = a := rfl +@[simp] theorem trEnvA_bal : ((trEnv t a s).setI "a" n).a "balanceOf" = balArr s := rfl + +/-- solar-verify's array term does not read the frame's bound address. -/ +theorem S2_setI : Ob.S2.eval ((trEnv t a s).setI "a" n) = Ob.S2.eval (trEnv t a s) := by + apply Tm.eval_congr _ rfl + intro y hy + have hna : y ≠ "a" := by + rintro rfl + revert hy + decide + exact ⟨by simp [Env.setI, hna], rfl, rfl, rfl⟩ +end + +/-- The binding: after a successful `transfer`, every address's `balanceOf` slot in SolidCore's +storage holds solar-verify's array term `S2` at `trEnv`. -/ +theorem trStore_eval (inj : HashInj) (s : Storage) (hs : ∀ k, s k < 2 ^ 256) (t a : Nat) + (ht : t < 2 ^ 256) (ha : a < 2 ^ 256) + (hR : (transferTree.eval (valOf [t, a] s)).success = true) (x : Nat) (hx : x < 2 ^ 160) : + (((transferTree.eval (valOf [t, a] s)).store (solHash x 0) : Nat) : Int) = + (Ob.S2.eval (trEnv t a s)).toArr x := by + obtain ⟨hta, hle, hov, hst⟩ := tr_success inj s hs t a ht ha hR + rw [hst _ (solHash_lt x 0), S2_eval] + have hc : (callerWord : Int) = 8192 := rfl + have hxt : (solHash x 0 = solHash t 0) ↔ x = t := + ⟨inj x t hx hta, fun h => h ▸ rfl⟩ + have hx8 : (solHash x 0 = senderSlot) ↔ x = 8192 := + ⟨fun h => inj x 8192 hx (by decide) (h.trans hash_eq.symm), fun h => h ▸ hash_eq⟩ + have hmid : midTo t a s = if t = 8192 then s senderSlot - a else s (solHash t 0) := rfl + rw [balArr_caller, balArr_nat, balArr_nat] + by_cases h1 : x = t + · subst h1 + by_cases h2 : x = 8192 + · subst h2; simp [hmid]; omega + · simp [hmid, h2, hc]; omega + · by_cases h2 : x = 8192 + · subst h2 + have : ¬ (8192 : Int) = t := by omega + simp [hxt, h1, hash_eq, this]; omega + · have h1' : ¬ (x : Int) = t := by omega + have h2' : ¬ (x : Int) = 8192 := by omega + simp [hxt, h1, hx8, h2, h1', h2', hc] + +theorem trHyps_hold (s : Storage) (hs : ∀ k, s k < 2 ^ 256) (t a : Nat) (hta : t < 2 ^ 160) + (ha : a < 2 ^ 256) (hle : a ≤ s senderSlot) (hov : midTo t a s + a < 2 ^ 256) : + ∀ x ∈ trHyps, x.Holds (trEnv t a s) := by + have hc : (callerWord : Int) = 8192 := rfl + have h8 : balArr s 8192 = s senderSlot := balArr_caller s + have hmid : midTo t a s = if t = 8192 then s senderSlot - a else s (solHash t 0) := rfl + have h1 := hs senderSlot + have h1' := hs (solHash t 0) + have h2 := hs 1 + simp only [trHyps, List.mem_cons, List.mem_nil_iff, or_false] + rintro x (rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | + rfl | rfl | rfl | rfl | rfl | rfl) <;> + simp [Tm.Holds, Tm.eval, Tm.evalList, applyOp, Value.select, Value.store, Value.toProp, Value.toInt, Value.toArr, Value.eq, + trEnv, Ob.amt, Ob.ms, Ob.ts, Ob.sum, Ob.mv, Ob.bal, Ob.le0, Ob.leW, Ob.sub, Ob.eq, Ob.add, + Ob.leA, Ob.sel, Ob.sto, Ob.S1, Ob.B, Ob.rcpt, arrFact, Env.setI, hc, h8, balArr_nat] <;> + first + | omega + | (intro n; have := hs (solHash n.toNat 0); simp only [balArr]; omega) + | (by_cases ht8 : t = 8192 <;> simp [ht8, hmid] at hov ⊢ <;> omega) + +/-- `transfer`'s ensures clauses on distinct addresses, as SolidCore sees them: on success, for +the call's words `t = to` and `a = amount`, the sender's slot drops by `a` and the recipient's +rises by `a` when they differ, and every other address's slot is unchanged. -/ +def trPost (call : Call) (obs : SolarTV.Observable) : Prop := + obs.success = true → + let t := (argWords 2 call).getD 0 0 + let a := (argWords 2 call).getD 1 0 + let s := initStorage call + (t ≠ callerWord → obs.storage (solHash callerWord 0) = s (solHash callerWord 0) - a) ∧ + (t ≠ callerWord → obs.storage (solHash t 0) = s (solHash t 0) + a) ∧ + (∀ x < 2 ^ 160, x ≠ callerWord → x ≠ t → obs.storage (solHash x 0) = s (solHash x 0)) + +/-- The goal of one of `transfer`'s obligations, at `trEnv`, from solar-verify's verdict. -/ +theorem tr_obligation (hv : Valid Export.Token.script) {φ : Tm} (hφ : (trHyps, φ) ∈ trObs) + {s : Storage} (hs : ∀ k, s k < 2 ^ 256) {t a : Nat} (hta : t < 2 ^ 160) (ha : a < 2 ^ 256) + (hle : a ≤ s senderSlot) (hov : midTo t a s + a < 2 ^ 256) : φ.Holds (trEnv t a s) := + checkScript_sound transfer_check hv _ hφ _ (trHyps_hold s hs t a hta ha hle hov) + +/-- `Token.transfer` meets its three ensures clauses on distinct addresses on the stage's scope, +given solar-verify's verdict on its script for `Token` and injectivity of the mapping slot on +address keys. Each clause is read off solar-verify's obligation for it (`tr_obligation`) through +the binding `trStore_eval`. -/ +theorem transfer_triple (hv : Valid Export.Token.script) (inj : HashInj) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Triple fuel c (stageScope fnTransfer [(2, 4096)]) (fun _ => True) trPost := by + have hdep := burnShape_eq + simp only [burnShape?, hc, Option.some.injEq, Prod.mk.injEq] at hdep + obtain ⟨d, hd⟩ := Wide.deployedAt_of hdep.1 + have hshape := transferShape_eq + simp only [transferShape?, hc, Option.some.injEq, Option.map_eq_some_iff, Prod.mk.injEq] at hshape + obtain ⟨f, hf, hlen, hT⟩ := hshape + have himpl := implements_tree (fn := fnTransfer) hd (by decide) hf hlen hT rfl + apply triple_of_wp himpl + rintro _ ⟨σ, hcov, fn', hfn', args, hl, hargs, rfl⟩ - + simp only [List.mem_singleton] at hfn' + subst hfn' + obtain ⟨t, a, rfl⟩ : ∃ t a, args = [t, a] := by + match args, hl with + | [t, a], _ => exact ⟨t, a, rfl⟩ + have ht : t < 2 ^ 256 := hargs t (by simp) + have ha : a < 2 ^ 256 := hargs a (by simp) + have hw : argWords 2 ({ calldata := Abi.calldata fnTransfer.sel [t, a], callvalue := 0, storage := σ } : Call) = + [t, a] := argWords_calldata _ [t, a] hargs 0 σ + rw [vc_eq, treeModel_run, show fnTransfer.params.length = 2 from rfl, hw] + set s := initStorage ({ calldata := Abi.calldata fnTransfer.sel [t, a], callvalue := 0, storage := σ } : Call) + with hs_def + have hs : ∀ k, s k < 2 ^ 256 := fun k => Generic.slotValue_lt σ k + unfold resOutcome + split + · next hok => + intro _ + obtain ⟨hta, hle, hov, -⟩ := tr_success inj s hs t a ht ha hok + have hb := trStore_eval inj s hs t a ht ha hok + have hcw : (callerWord : Int) = 8192 := rfl + have h8 : balArr s 8192 = (s senderSlot : Int) := balArr_caller s + have hob := fun φ (hφ : (trHyps, φ) ∈ trObs) => tr_obligation hv hφ hs hta ha hle hov + have gFrom := hob trGoalFrom (by simp [trObs]) + have gTo := hob trGoalTo (by simp [trObs]) + have gFrame := hob trGoalFrame (by simp [trObs]) + obtain ⟨f2, hf2⟩ : ∃ f, Ob.S2.eval (trEnv t a s) = .arr f := + ⟨_, Value.sortOf_arr (Tm.eval_sortOf _ _ (by decide))⟩ + simp only [trGoalFrom, trGoalTo, trGoalFrame, Tm.Holds, Tm.eval, Tm.evalList, applyOp, Value.select, Value.store, + Value.toProp, Value.toInt, Value.toArr, Value.eq, Ob.eq, Ob.sel, Ob.sub, Ob.add, Ob.le0, + Ob.leA, Ob.bal, Ob.B, Ob.ms, Ob.amt, Ob.rcpt, S2_setI, hf2] at gFrom gTo gFrame + simp only [observe, hw, List.getD_cons_zero, List.getD_cons_succ] + rw [← hs_def] + have hsl : solHash callerWord 0 = senderSlot := hash_eq + refine ⟨fun hne => ?_, fun hne => ?_, fun x hx hx8 hxt => ?_⟩ + · have e : (((transferTree.eval (valOf [t, a] s)).store senderSlot : Nat) : Int) = + (Ob.S2.eval (trEnv t a s)).toArr 8192 := by + have := hb callerWord (by decide); rwa [hsl] at this + have g := gFrom (by simp; omega) + simp [h8] at g + simp only [hf2, Value.toArr] at e g + rw [hsl] + omega + · have e := hb t hta + have g := gTo (by simp; omega) + simp [balArr_nat] at g + simp only [hf2, Value.toArr] at e g + omega + · have e := hb x hx + have hx8' : ¬ (x : Int) = 8192 := by intro h; apply hx8; exact_mod_cast h + have hxt' : ¬ (x : Int) = t := by omega + have hxA : (x : Int) ≤ 1461501637330902918203684832716283019655932542975 := by omega + have g := gFrame x + simp [balArr_nat, hx8', hxt', hxA, S2_setI] at g + simp only [hf2, Value.toArr] at e g + omega + · intro h; simp_all [observe] + +/-- info: 'SolidCore.Verify.VC.Token.transfer_triple' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms transfer_triple + +end SolidCore.Verify.VC.Token diff --git a/Contracts/Token/WorldSpec.lean b/Contracts/Token/WorldSpec.lean new file mode 100644 index 00000000..94540c62 --- /dev/null +++ b/Contracts/Token/WorldSpec.lean @@ -0,0 +1,41 @@ +import Contracts.Token.EndToEnd +import Verify.SourceOracle + +/-! +# solar-verify's Token: its triples in every world + +`transfer_tripleIn` and `burn_tripleIn` are solar-verify's triples of SolidCore's Token +(`transfer_triple_discharged`, `burn_triple`) with SolidCore run in any world `W` (any call oracle, any +other accounts' code), from the generic check that accepts both functions +(`tripleIn_of_triple`): the open worlds of `holds_of_runs` included, with the same hypothesis +(`HashInj` for `transfer`, none for `burn`) and none on the world. +-/ + +namespace Contracts.Token + +open SolidCore.Refinement SolidCore.Verify SolidCore.Verify.VC SolidCore.Verify.VC.Token +open SolidCore.Refinement.Solar.VerifyTokenSource (check_of deployed check_transfer_eq check_burn_eq) + +/-- **`transfer`'s triple in every world**, given `HashInj`. -/ +theorem transfer_tripleIn (inj : HashInj) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : contract? = .ok c) (W : World) : + TripleIn W fuel c (stageScope fnTransfer [(2, 4096)]) (fun _ => True) trPost := by + obtain ⟨d, hd⟩ := deployed hc + exact tripleIn_of_triple hd (check_of hc check_transfer_eq) (fun _ h => h) + (transfer_triple_discharged inj hc) W + +/-- **`burn`'s triple in every world**, with no hypothesis. -/ +theorem burn_tripleIn {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) + (W : World) : TripleIn W fuel c (stageScope fnBurn [(2, 4096)]) (fun _ => True) burnPost := by + obtain ⟨d, hd⟩ := deployed hc + exact tripleIn_of_triple hd (check_of hc check_burn_eq) (fun _ h => h) (burn_triple hc) W + +/-- info: 'Contracts.Token.transfer_tripleIn' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms transfer_tripleIn + +/-- info: 'Contracts.Token.burn_tripleIn' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms burn_tripleIn + +end Contracts.Token diff --git a/Contracts/UniswapV2/.gitignore b/Contracts/UniswapV2/.gitignore new file mode 100644 index 00000000..5a6842ae --- /dev/null +++ b/Contracts/UniswapV2/.gitignore @@ -0,0 +1,25 @@ +# Generated by scripts/verify/uniswap_v2_gen.sh (sources from the GPL-3.0 v2-core port); not committed. +*/Source.lean +*/Core.lean +*/Spec.lean +*/SpecMut.lean +*/Connect.lean +ERC20/VC/ +*/Ctx.lean +*/Fn/ +*/Groups.lean +*/Asm.lean +*/Contract.lean +*/Check.lean +*/Clones.lean +*/ClonesStaged.lean +*/SpecWrongK.lean +*/Bytecode.lean +*/Runtime.lean +*/SourceNoUpdate.lean +*/RuntimeNoUpdate.lean +*/SourceSkimUpdate.lean +*/RuntimeSkimUpdate.lean + +# Generated by scripts/verify/uniswap_v2_transfer_slice.sh; not committed. +ERC20/Slice/Gen/ diff --git a/Contracts/UniswapV2/ERC20/Certified/Transfer.lean b/Contracts/UniswapV2/ERC20/Certified/Transfer.lean new file mode 100644 index 00000000..c99b0505 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Certified/Transfer.lean @@ -0,0 +1,233 @@ +import Contracts.UniswapV2.ERC20.SourceMir +import Contracts.UniswapV2.ERC20.Slice.Bytes +import uv2_erc20.Gas +import uv2_erc20.ProofsT.Stages +import uv2_erc20.AnyCaller +import Contracts.UniswapV2.ERC20.SourceMirFrom + +/-! +# UniswapV2ERC20.transfer: certified, with the bytes matching the source from any caller + +The composition of the slice's edges into one `Shapes.Certified` statement (docs/CERTIFICATION_TARGET.md, +first slice), for `transfer(address,uint256)` of the pinned port on the exact runtime bytes +`CtxGas.code`, from the edges already proved and checked in CI: + +* E3 `SourceMir.check_ok` / `SourceMir.transfer_stage`: SolidCore's checked source to solar's + first lowered MIR `stage0` (here through `compiled0XL`, which takes the same check); +* E4 `SolarTV.Milestone.Uv2Erc20T.uv2_erc20_transfer_mir_to_evmir`: `stage0` to the final EVM IR + `evm11` on the calls of transfer's selector, under every oracle; +* E5 + E8 `CtxGas.check_ok` with the guard stage (`guard_ends`, `guard_run`): the checker with + contexts and gas accepts the exact bytes against `evm11` (in effect form), which gives the + equivalence at every gas and the gas bound `G = 8199112` (`CtxGas.G_eq`); +* E7 `Slice.meets_target` and `Slice.terminates`: `TargetPost` and the allowed statuses of every + SolidCore run of a valid call, through `Slice.certified_of`. + +**Caller.** Every edge's semantics fixes the caller to `callerAddress` = `Generic.callerWord` = +0x2000 (`SolarTV.Call` has no caller field), so `certified` is about calls from 0x2000. +`certified_any_caller` adds, for every caller `a < 2 ^ 160` other than the contract, that the exact +bytes run from `a` give SolidCore's run of the call sent by `a` (`ResourcesFrom`): E3 from any +caller (`SourceMirFrom.transfer_stage_from`, the generic check with a symbolic caller), E4 under +every oracle and the gas edge from any caller (`AnyCaller.resources_any_caller`). The +postcondition `TargetPost` is still stated at 0x2000. + +**Not yet covered.** The deployer stays `callerAddress`, and `TargetPost` and the allowed statuses +are stated for calls from 0x2000 only. E6 (that `code` is the bytes a fresh solar run emits, by +driver byte equality and a leanchecker replay) is pending: the statement is about `CtxGas.code` as +exported at the pinned solar commit. + +**Premise.** The valid calls are `Slice.ValidIn` = `Valid deployed call ∧ Scope call`, where +`Scope call` is the scoped hash premise +`ScopedSep (transferFootprint balanceSlot caller dst)` of the call's recipient `dst` (keccak256 +separated on the two balance preimages only). It is part of the statement's precondition, at the +call it is about; nothing else is assumed. + +* `certified`: `∃ c, contract? = .ok c ∧ Certified (solidCore fuel) c code ValidIn Allowed + TargetPost (fun _ => 8199112)`. +* `certified_any_caller`: `certified` and `ResourcesFrom (fun a => (solidCoreFrom a fuel).run c) + code (genericValid0 fns deployed) (fun _ => 8199112)`. +* `self_max_bytes`, `self_short_bytes`: the two required self-transfer cases run on the exact + bytes (EthLib), from the gas bound on: balance `2 ^ 256 - 1`, `transfer(caller, 1)` succeeds + with the storage unchanged and `Transfer(caller, caller, 1)` logged; a self-transfer of 6 from a + balance of 5 reverts with `Error("ds-math-sub-underflow")` and no change. Neither needs the hash + premise (they use the compiled shape on `Valid`). +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Certified + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Refinement.Shapes +open SolidCore.Spec.UniswapV2.ERC20.Slice SolidCore.Spec.UniswapV2.ERC20.Slice.Gen +open SolarTV.Export.UniswapV2ERC20.CtxGas + +/-- The exact runtime bytes. -/ +abbrev code : ByteArray := SolarTV.Export.UniswapV2ERC20.CtxGas.code + +/-- A valid call of the slice is a call of E3's generic stage. -/ +theorem valid_sub : ∀ call, Valid deployed call → + genericValid0 SourceMir.fns SourceMir.deployed call := by + rintro _ ⟨σ, dst, v, hcov, hto, hv, rfl⟩ + refine ⟨σ, ?_, SourceMir.fn_transfer, List.mem_singleton_self _, [dst, v], rfl, + by intro a ha; simp at ha; rcases ha with rfl | rfl <;> omega, rfl⟩ + intro kv hkv + simp only [SourceMir.deployed, List.mem_singleton] at hkv + subst hkv + exact hcov _ (by simp [deployed]) + +/-- A call of E3's generic stage has transfer's selector. -/ +theorem selector_of : ∀ call, genericValid0 SourceMir.fns SourceMir.deployed call → + TransferCall call := by + rintro _ ⟨σ, -, f, hf, args, hlen, hargs, rfl⟩ + simp only [SourceMir.fns, List.mem_cons, List.not_mem_nil, or_false] at hf + subst hf + exact (SolidCore.Refinement.Generic.callFacts SourceMir.fn_transfer.sel (by decide) args hargs σ).selector + +set_option maxRecDepth 200000 in +theorem hscope : ∀ call, genericValid0 SourceMir.fns SourceMir.deployed call → + SolarTV.Milestone.Uv2Erc20T.scope call := by + intro call h + simp only [SolarTV.Milestone.Uv2Erc20T.scope] + have hs := selector_of call h + simp only [TransferCall] at hs + rw [hs] + decide + +/-- E4 onto the final EVM IR's effect form (the same runs, `sem_norm`). -/ +theorem backend : Stage (mirSem oracle) (evmirSem oracle) SolarTV.Export.UniswapV2ERC20.stage0 + (SolidCore.Refinement.Solar.AssembleCtx.norm prog) SolarTV.Milestone.Uv2Erc20T.scope := + fun call h obs hr => (SolidCore.Refinement.Solar.AssembleCtx.sem_norm oracle prog call).trans + (SolarTV.Milestone.Uv2Erc20T.uv2_erc20_transfer_mir_to_evmir oracle call h obs hr) + +set_option maxRecDepth 200000 in +/-- **E3, E4, E5 and E8 composed**: equivalence at every gas, termination and resources of the +exact bytes on E3's calls of transfer, with the gas bound `G`. -/ +theorem compiled {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Compiled (solidCore fuel) c code (genericValid0 SourceMir.fns SourceMir.deployed) (fun _ => G) := by + have hdep := SolidCore.Spec.UniswapV2.ERC20.SourceMirDeploy.deploy_eq + simp only [SourceMir.deploy?, hc] at hdep + obtain ⟨_, hdd⟩ := Wide.deployedAt_of hdep + exact compiled0XL hdd (SourceMir.check_ok hc) SourceMir.valid_inhabited backend hscope + (fun call h => guard_ends oracle call (selector_of call h)) + (fun call h => guard_run oracle call (selector_of call h)) check_ok G_lt + +/-- Equivalence on the slice's valid calls with their premise. -/ +theorem equiv {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Equiv (solidCore fuel) c code ValidIn := + fun gas hg call hv => (compiled hc).equiv.equiv gas hg call (valid_sub call hv.1) + +/-- Resources on the slice's valid calls with their premise. -/ +theorem resources {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Resources (solidCore fuel) c code ValidIn (fun _ => G) := + fun call hv => (compiled hc).resources call (valid_sub call hv.1) + +/-- **UniswapV2ERC20.transfer is certified at the caller 0x2000**: on every call of +`transfer(dst, v)` from 0x2000 with well-formed calldata, no value and any storage writing the +constructor's slot, whose scoped hash premise `ScopedSep (transferFootprint 1 0x2000 dst)` holds, +the exact runtime bytes behave as SolidCore's checked source (at every gas, and exactly from +8199112 gas on), which ends with an allowed status and meets the target's postcondition. -/ +theorem certified : ∃ c, SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c ∧ + Certified (solidCore fuel) c code ValidIn Allowed TargetPost (fun _ => 8199112) := by + obtain ⟨c, hc⟩ := SolidCore.Verify.VC.UniswapV2ERC20.contract_ok + have h := certified_of hc (equiv hc) (resources hc) + rw [show (fun _ : Call => G) = fun _ => 8199112 from funext fun _ => G_eq] at h + exact ⟨c, hc, h⟩ + +/-- The oracle of a call from `a` meets E3's premise: its caller is `a` and its Keccak-256 is +EthLib's. -/ +theorem fromOk_oracleFrom {a : Nat} (ha : a < 2 ^ 160) : Generic.FromOk a (Shapes.oracleFrom a) := + ⟨by + show ((BitVec.ofNat 160 a).setWidth 256).toNat = a + rw [BitVec.toNat_setWidth, BitVec.toNat_ofNat, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt (by omega)], + fun x y _ _ => by + show (Shapes.oracle.keccak _).toNat = _ + rw [Shapes.oracle_ok.1.2] + exact SolidCore.Refinement.Keccak.ethKeccak_twoWords x y⟩ + +/-- **E3 from any caller, E4 and E5 composed**: from every account `a` below `2 ^ 160` but the +contract's own, on every call of transfer E3 takes, the exact runtime bytes run from `a` give +SolidCore's run of the call sent by `a`, at every gas from `G` on. -/ +theorem resources_any_caller {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + ResourcesFrom (fun a => (solidCoreFrom a fuel).run c) code + (genericValid0 SourceMir.fns SourceMir.deployed) (fun _ => G) := by + have hdep := SolidCore.Spec.UniswapV2.ERC20.SourceMirDeploy.deploy_eq + simp only [SourceMir.deploy?, hc] at hdep + obtain ⟨_, hdd⟩ := Wide.deployedAt_of hdep + refine SolarTV.Export.UniswapV2ERC20.AnyCaller.resources_any_caller selector_of ?_ ?_ + · intro a ha _ call hv + exact Option.isSome_iff_exists.mp + (Generic.definedFrom a ha hdd (SourceMirFrom.checkFrom_ok hc) call hv) + · intro a ha _ call hv obs h + exact SourceMirFrom.transfer_stage_from a ha (Shapes.oracleFrom a) (fromOk_oracleFrom ha) hc + call hv obs h + +/-- **UniswapV2ERC20.transfer is certified, with the bytes matching the source from any caller**: +the statement `certified` (at the caller 0x2000, where the postcondition is stated), and, from +every caller `a < 2 ^ 160` other than the contract, on every call of `transfer(dst, v)` with +well-formed calldata, no value and any storage writing the constructor's slot, the exact runtime +bytes run from `a` give SolidCore's run of the call sent by `a`, exactly from 8199112 gas on. -/ +theorem certified_any_caller : ∃ c, SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c ∧ + Certified (solidCore fuel) c code ValidIn Allowed TargetPost (fun _ => 8199112) ∧ + ResourcesFrom (fun a => (solidCoreFrom a fuel).run c) code + (genericValid0 SourceMir.fns SourceMir.deployed) (fun _ => 8199112) := by + obtain ⟨c, hc⟩ := SolidCore.Verify.VC.UniswapV2ERC20.contract_ok + have h := certified_of hc (equiv hc) (resources hc) + have hr := resources_any_caller hc + rw [show (fun _ : Call => G) = fun _ => 8199112 from funext fun _ => G_eq] at h hr + exact ⟨c, hc, h, hr⟩ + +/-- The scoped hash premise inside the statement's valid calls, as stated. -/ +theorem validIn_iff (call : Call) : + ValidIn call ↔ Valid deployed call ∧ ∀ σ dst v, call = transferCall σ dst v → dst < 2 ^ 160 → + v < 2 ^ 256 → SolidCore.Spec.ScopedSep (SolidCore.Spec.transferFootprint 1 caller dst) := + Iff.rfl + +/-- The caller every call of the statement comes from. -/ +theorem caller_eq : caller = 0x2000 := rfl + +/-! ## The required self-transfer cases, on the exact bytes -/ + +/-- From the gas bound on, the bytes give SolidCore's result on a valid call (no premise). -/ +theorem bytes_eq_source {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) {call : Call} (hv : Valid deployed call) + {gas : Nat} (h1 : 8199112 ≤ gas) (h2 : gas < 2 ^ 256) : + Final.Target.runWith gas code call = (solidCore fuel).run c call := + ((compiled hc).resources call (valid_sub call hv)).2 gas (by rw [G_eq]; exact h1) h2 + +/-- **Required case, on the bytes**: balance `2 ^ 256 - 1`, `transfer(caller, 1)` succeeds, the +storage is unchanged and `Transfer(caller, caller, 1)` is logged. -/ +theorem self_max_bytes (gas : Nat) (h1 : 8199112 ≤ gas) (h2 : gas < 2 ^ 256) : + slotValue σmax (balKey caller) = 2 ^ 256 - 1 ∧ + Final.Target.runWith gas code (transferCall σmax caller 1) = + some ⟨true, be32 1, [transferLog caller caller 1], slotValue σmax⟩ := by + obtain ⟨c, hc⟩ := SolidCore.Verify.VC.UniswapV2ERC20.contract_ok + obtain ⟨hb, hrun⟩ := self_max hc + exact ⟨hb, (bytes_eq_source hc ⟨σmax, caller, 1, covers_pair _ _, by decide, by decide, rfl⟩ h1 h2).trans hrun⟩ + +/-- **Required case, on the bytes**: a self-transfer of 6 from a balance of 5 reverts with +`Error("ds-math-sub-underflow")`, no log and no change. -/ +theorem self_short_bytes (gas : Nat) (h1 : 8199112 ≤ gas) (h2 : gas < 2 ^ 256) : + Final.Target.runWith gas code (transferCall σshort caller 6) = + some ⟨false, errorData subMsg, [], slotValue σshort⟩ := by + obtain ⟨c, hc⟩ := SolidCore.Verify.VC.UniswapV2ERC20.contract_ok + exact (bytes_eq_source hc ⟨σshort, caller, 6, covers_pair _ _, by decide, by decide, rfl⟩ h1 h2).trans + (self_short hc) + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Certified.certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms certified + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Certified.self_max_bytes' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms self_max_bytes + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Certified.self_short_bytes' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms self_short_bytes + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Certified.certified_any_caller' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms certified_any_caller + +end SolidCore.Spec.UniswapV2.ERC20.Certified diff --git a/Contracts/UniswapV2/ERC20/CtxNeg.lean b/Contracts/UniswapV2/ERC20/CtxNeg.lean new file mode 100644 index 00000000..41644fcc --- /dev/null +++ b/Contracts/UniswapV2/ERC20/CtxNeg.lean @@ -0,0 +1,30 @@ +import uv2_erc20.Ctx +import W1Proofs.Axioms + +/-! +# Negative controls of UniswapV2ERC20's context-checker certificate + +The checker refuses the exact bytecode with one byte changed, by the kernel's evaluation: a jump +target moved (byte 7, the dispatcher's guard `PUSH1 0x65`), the first SSTORE dropped (as POP, +byte 685) and an opcode outside the fragment (CREATE) for that SSTORE. Each refusal is a mismatch +of the walk against the final EVM IR, never a timeout. +-/ + +namespace SolarTV.Export.UniswapV2ERC20.Ctx + +open SolidCore.Refinement.Solar SolidCore.Refinement.Solar.AssembleCtx + +/-- The bytecode with byte `i` replaced by `b`. -/ +noncomputable def mutant (i b : Nat) : ByteArray := ⟨((bytes.set i b).map UInt8.ofNat).toArray⟩ + +theorem rejects_jump : checkXB (norm evm16) (mutant 7 0x66) cx = false := by decide +kernel + +theorem rejects_sstore : checkXB (norm evm16) (mutant 685 0x50) cx = false := by decide +kernel + +theorem rejects_opcode : checkXB (norm evm16) (mutant 685 0xf0) cx = false := by decide +kernel + +/-- info: 'SolarTV.Export.UniswapV2ERC20.Ctx.rejects_sstore' depends on axioms within [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#axioms_within rejects_sstore + +end SolarTV.Export.UniswapV2ERC20.Ctx diff --git a/Contracts/UniswapV2/ERC20/EndToEnd.lean b/Contracts/UniswapV2/ERC20/EndToEnd.lean new file mode 100644 index 00000000..1527034f --- /dev/null +++ b/Contracts/UniswapV2/ERC20/EndToEnd.lean @@ -0,0 +1,98 @@ +import Verify.ShapeCtx +import Contracts.UniswapV2.ERC20.Lowering +import uv2_erc20.ProofsAT.Stages +import uv2_erc20.Ctx + +/-! +# UniswapV2ERC20's approve and transfer: SolidCore's source to solar's exact runtime bytecode + +`published`: `Shapes.Functional` (equivalence, termination and the specification; no gas bound) +of SolidCore's checked `UniswapV2ERC20` (the kernel's type check and translation of the port, +`Contracts.UniswapV2.ERC20.Core`) and the exact runtime bytecode solar emitted for it +(`SolarTV.Export.UniswapV2ERC20.bytecode`, 2187 bytes, -Ogas, osaka), on the valid calls +`genericValid0 fns deployed`: `approve(address,uint256)` and `transfer(address,uint256)` on any +argument words below `2 ^ 256`, with no value, from the stage's caller, from any storage that writes +the slot the constructor wrote (`DOMAIN_SEPARATOR`). + +It composes, by `Shapes.functional_ctx` alone: + +* the generic source stage, `check_ok` (`Generic.check` of stage0 for both functions); +* solar-tv's backend stages from stage0 to the final EVM IR `evm16` under every oracle + (`SolarTV.Milestone.Uv2Erc20AT.uv2_erc20_at_mir_to_evmir`, on every call whose selector is none + of the eleven other external functions'); +* the context checker's per-run theorem on the exact bytecode + (`SolarTV.Export.UniswapV2ERC20.Ctx.bytecode`, `assembly_of_checkXB_norm`: the whole runtime, + permit's STATICCALL to `ecrecover` included, under calling contexts); +* solar-verify's exported specs of approve and transfer (`approve_holds`, `transfer_holds`), with + the identity ghost step (the spec moves its ghosts only in `_mint` and `_burn`). + +Named hypotheses, all in the statement: + +* `NestedSlotsSeparated [1, 4] [2]`: keccak256 injective with images at least `2 ^ 128` on the + slots of `balanceOf[a]`, `nonces[a]` and `allowance[o][s]`; used by the specification only; +* `AssembleCallSeg.StaticRunner` at every gas (a static message that succeeds ends with no log, a + callee's output has fewer than `2 ^ 256` bytes) and `AssembleCallSeg.CalleesRun` on the valid + calls: the context checker's hypotheses on the message runner, used by equivalence only. + +Not covered: resources (the context checker proves no gas bound, so this is not +`Shapes.Certified`); `transferFrom`, `permit`, the getters and the constructor (only through the +storage it leaves, `deploy_eq`); callers other than the stage's. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.EndToEnd + +open SolidCore.Spec SolidCore.Refinement SolidCore.Refinement.Shapes SolidCore.Spec.UniswapV2.ERC20 + +/-- The exact runtime bytecode. -/ +abbrev code : ByteArray := SolarTV.Export.UniswapV2ERC20.Ctx.code + +/-- The identity ghost step: approve and transfer leave the spec's ghosts alone. -/ +def idStep : GhostStep := fun _ g => g + +/-- The specification: approve's and transfer's exported specs of every result on their calls. -/ +def Post (call : SolarTV.Call) (obs : SolarTV.Observable) : Prop := + holdsPost spec ctxOf idStep approve_spec (SolidCore.Verify.VC.stageScope fn_approve deployed) call obs ∧ + holdsPost spec ctxOf idStep transfer_spec (SolidCore.Verify.VC.stageScope fn_transfer deployed) call obs + +/-- The valid calls are in the backend stages' scope: their selector is approve's or transfer's. -/ +theorem hscope : ∀ call, genericValid0 fns deployed call → SolarTV.Milestone.Uv2Erc20AT.scope call := by + rintro _ ⟨σ, -, f, hf, args, hlen, hargs, rfl⟩ + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hf + rcases hf with rfl | rfl + · have h := (Generic.callFacts fn_approve.sel (by decide) args hargs σ).selector + simp only [SolarTV.Milestone.Uv2Erc20AT.scope] + rw [h] + decide + · have h := (Generic.callFacts fn_transfer.sel (by decide) args hargs σ).selector + simp only [SolarTV.Milestone.Uv2Erc20AT.scope] + rw [h] + decide + +/-- **approve and transfer, from SolidCore's source to the exact bytecode**: equivalence, +termination and the exported specs, under the named hypotheses. -/ +theorem published (hsep : NestedSlotsSeparated [1, 4] [2]) + (hP : ∀ gas, SolidCore.Refinement.Solar.AssembleCallSeg.StaticRunner gas) + (hQ : ∀ gas call, genericValid0 fns deployed call → + SolidCore.Refinement.Solar.AssembleCallSeg.CalleesRun gas code call) : + ∃ c, SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c ∧ + Functional (solidCore SolidCore.Verify.VC.UniswapV2ERC20.fuel) c code (genericValid0 fns deployed) + (fun _ _ => True) Post := by + obtain ⟨c, hc⟩ := SolidCore.Verify.VC.UniswapV2ERC20.contract_ok + have hdep := deploy_eq + simp only [deploy?, hc] at hdep + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + refine ⟨c, hc, functional_ctx hdd (check_ok hc) (base := SolarTV.Export.UniswapV2ERC20.Ctx.cx.base) + (by decide) (genericValid0_inhabited fn_approve [fn_transfer] deployed) + (fun o => SolarTV.Milestone.Uv2Erc20AT.uv2_erc20_at_mir_to_evmir o) hscope ?_ ?_⟩ + · intro gas hg call hv + obtain ⟨o, -, -, -, hok, hw⟩ := + SolarTV.Export.UniswapV2ERC20.Ctx.bytecode [] _ hP hQ gas hg call hv + exact ⟨o, hok, hw⟩ + · exact (meets_of_holdsFn (approve_holds hsep hc idStep (fun _ _ _ => rfl))).and + (meets_of_holdsFn (transfer_holds hsep hc idStep (fun _ _ _ => rfl))) + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.EndToEnd.published' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms published + +end SolidCore.Spec.UniswapV2.ERC20.EndToEnd diff --git a/Contracts/UniswapV2/ERC20/EndToEndAll.lean b/Contracts/UniswapV2/ERC20/EndToEndAll.lean new file mode 100644 index 00000000..22d784bb --- /dev/null +++ b/Contracts/UniswapV2/ERC20/EndToEndAll.lean @@ -0,0 +1,92 @@ +import Contracts.UniswapV2.ERC20.EndToEnd +import Contracts.UniswapV2.ERC20.EndToEndTFSpec + +/-! +# UniswapV2ERC20's approve, transfer and transferFrom: one theorem on the exact runtime bytecode + +`published`: `Shapes.Functional` (equivalence at every gas below `2 ^ 256`, termination and the +exported specs) of SolidCore's checked `UniswapV2ERC20` and the exact runtime bytecode solar emitted +for it (2187 bytes, `SolarTV.Export.UniswapV2ERC20.Ctx.code`), on the valid calls of all three +functions: any argument words below `2 ^ 256`, no value, the stage's caller, any storage that +writes the slot the constructor wrote. It composes, by `Shapes.functional_ctx` alone, the generic +source stage for the three functions (`check_ok` and `check_tf_ok`, joined by `List.all_append`), +solar-tv's backend stages whose scope covers the three selectors (`Uv2Erc20ATF`), the context +checker's per-run theorem and solar-verify's exported specs of the three functions. + +Named hypotheses, all in the statement: `NestedSlotsSeparated [1, 4] [2]` (keccak256 injective with large +images on the mapping slots; specification only), `AssembleCallSeg.StaticRunner` at every gas and +`AssembleCallSeg.CalleesRun` on the valid calls (equivalence only). + +Not covered: resources (no gas bound, so not `Shapes.Certified`), `permit`, the getters, the +constructor (only through the storage it leaves), callers other than the stage's. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.EndToEndAll + +open SolidCore.Spec SolidCore.Refinement SolidCore.Refinement.Shapes SolidCore.Spec.UniswapV2.ERC20 + +/-- The functions of the statement. -/ +def fns3 : List SolidCore.Refinement.Abi.Fn := [fn_approve, fn_transfer, fn_transferFrom] + +/-- The specification: the exported specs of approve, transfer and transferFrom. -/ +def Post (call : SolarTV.Call) (obs : SolarTV.Observable) : Prop := + EndToEnd.Post call obs ∧ EndToEndTF.Post call obs + +theorem check3_ok {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Generic.check SolidCore.Verify.VC.UniswapV2ERC20.fuel mirFuel c.core + SolarTV.Export.UniswapV2ERC20.stage0 fns3 .all = true := by + have h1 := check_ok hc + have h2 := check_tf_ok hc + unfold Generic.check at h1 h2 ⊢ + rw [show fns3 = fns ++ fnsTF from rfl, List.all_append, h1, h2] + all_goals rfl + +/-- The valid calls are in the backend stages' scope. -/ +theorem hscope3 : ∀ call, genericValid0 fns3 deployed call → SolarTV.Milestone.Uv2Erc20ATF.scope call := by + rintro _ ⟨σ, -, f, hf, args, hlen, hargs, rfl⟩ + simp only [fns3, List.mem_cons, List.not_mem_nil, or_false] at hf + rcases hf with rfl | rfl | rfl + · have h := (Generic.callFacts fn_approve.sel (by decide) args hargs σ).selector + simp only [SolarTV.Milestone.Uv2Erc20ATF.scope] + rw [h] + decide + · have h := (Generic.callFacts fn_transfer.sel (by decide) args hargs σ).selector + simp only [SolarTV.Milestone.Uv2Erc20ATF.scope] + rw [h] + decide + · have h := (Generic.callFacts fn_transferFrom.sel (by decide) args hargs σ).selector + simp only [SolarTV.Milestone.Uv2Erc20ATF.scope] + rw [h] + decide + +/-- **approve, transfer and transferFrom, from SolidCore's source to the exact bytecode**: +equivalence, termination and the exported specs, under the named hypotheses. -/ +theorem published (hsep : NestedSlotsSeparated [1, 4] [2]) + (hP : ∀ gas, SolidCore.Refinement.Solar.AssembleCallSeg.StaticRunner gas) + (hQ : ∀ gas call, genericValid0 fns3 deployed call → + SolidCore.Refinement.Solar.AssembleCallSeg.CalleesRun gas SolarTV.Export.UniswapV2ERC20.Ctx.code call) : + ∃ c, SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c ∧ + Functional (solidCore SolidCore.Verify.VC.UniswapV2ERC20.fuel) c SolarTV.Export.UniswapV2ERC20.Ctx.code + (genericValid0 fns3 deployed) (fun _ _ => True) Post := by + obtain ⟨c, hc⟩ := SolidCore.Verify.VC.UniswapV2ERC20.contract_ok + have hdep := deploy_eq + simp only [deploy?, hc] at hdep + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + refine ⟨c, hc, functional_ctx hdd (check3_ok hc) (base := SolarTV.Export.UniswapV2ERC20.Ctx.cx.base) + (by decide) (genericValid0_inhabited fn_approve [fn_transfer, fn_transferFrom] deployed) + (fun o => SolarTV.Milestone.Uv2Erc20ATF.uv2_erc20_atf_mir_to_evmir o) hscope3 ?_ ?_⟩ + · intro gas hg call hv + obtain ⟨o, -, -, -, hok, hw⟩ := + SolarTV.Export.UniswapV2ERC20.Ctx.bytecode [] _ hP hQ gas hg call hv + exact ⟨o, hok, hw⟩ + · exact ((meets_of_holdsFn (approve_holds hsep hc EndToEnd.idStep (fun _ _ _ => rfl))).and + (meets_of_holdsFn (transfer_holds hsep hc EndToEnd.idStep (fun _ _ _ => rfl)))).and + (meets_of_holdsFn (SolidCore.Spec.UniswapV2.ERC20TF.transferFrom_holds hsep hc EndToEndTF.idStep + (fun _ _ _ => rfl))) + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.EndToEndAll.published' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms published + +end SolidCore.Spec.UniswapV2.ERC20.EndToEndAll diff --git a/Contracts/UniswapV2/ERC20/EndToEndTF.lean b/Contracts/UniswapV2/ERC20/EndToEndTF.lean new file mode 100644 index 00000000..7e268972 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/EndToEndTF.lean @@ -0,0 +1,89 @@ +import Contracts.UniswapV2.ERC20.Lowering +import Verify.ShapeCtx +import uv2_erc20.ProofsATF.Stages +import uv2_erc20.Ctx + +/-! +# UniswapV2ERC20's transferFrom: SolidCore's source to solar's exact runtime bytecode + +The generic check accepts stage0 for `transferFrom` (`check_tf_ok`, `kernel_rfl`), and +`functional_tf` composes it with solar-tv's backend stages (on every call whose selector is none of +the ten functions other than approve, transfer and transferFrom) and the context checker's per-run +theorem on the exact bytecode: equivalence and termination of `transferFrom(from, to, value)` on +any argument words, no value, from the stage's caller, from any storage that writes +`DOMAIN_SEPARATOR`'s slot, under the context checker's named hypotheses on the message runner +(`StaticRunner`, `CalleesRun`). Its postcondition is the one given (`Post`), proved of the same +source runs: `True` here; the exported spec is ConnectTFSplit's. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20 + +open SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Refinement.Shapes + +/-- `transferFrom(address,address,uint256)` as the stage's ABI sees it. -/ +def fn_transferFrom : SolidCore.Refinement.Abi.Fn := ⟨599290589, List.replicate 3 (.uint 256)⟩ + +def fnsTF : List SolidCore.Refinement.Abi.Fn := [fn_transferFrom] + +def checkTF? : Bool := + match SolidCore.Verify.VC.UniswapV2ERC20.contract? with + | .ok c => Generic.check SolidCore.Verify.VC.UniswapV2ERC20.fuel mirFuel c.core + SolarTV.Export.UniswapV2ERC20.stage0 fnsTF .all + | .error _ => false + +kernel_rfl checkTF_eq checkTF? true using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +theorem check_tf_ok {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Generic.check SolidCore.Verify.VC.UniswapV2ERC20.fuel mirFuel c.core + SolarTV.Export.UniswapV2ERC20.stage0 fnsTF .all = true := by + have h := checkTF_eq + simp only [checkTF?, hc] at h + exact h + +theorem hscopeTF : ∀ call, genericValid0 fnsTF deployed call → SolarTV.Milestone.Uv2Erc20ATF.scope call := by + rintro _ ⟨σ, -, f, hf, args, hlen, hargs, rfl⟩ + simp only [fnsTF, List.mem_cons, List.not_mem_nil, or_false] at hf + subst hf + have h := (Generic.callFacts fn_transferFrom.sel (by decide) args hargs σ).selector + simp only [SolarTV.Milestone.Uv2Erc20ATF.scope] + rw [h] + decide + +/-- **transferFrom, from SolidCore's source to the exact bytecode**: equivalence and termination, +and any postcondition proved of the same source runs. -/ +theorem functional_tf {Post : SolarTV.Call → SolarTV.Observable → Prop} + (hP : ∀ gas, SolidCore.Refinement.Solar.AssembleCallSeg.StaticRunner gas) + (hQ : ∀ gas call, genericValid0 fnsTF deployed call → + SolidCore.Refinement.Solar.AssembleCallSeg.CalleesRun gas SolarTV.Export.UniswapV2ERC20.Ctx.code call) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) + (meets : Meets (solidCore SolidCore.Verify.VC.UniswapV2ERC20.fuel) c (genericValid0 fnsTF deployed) Post) : + Functional (solidCore SolidCore.Verify.VC.UniswapV2ERC20.fuel) c SolarTV.Export.UniswapV2ERC20.Ctx.code + (genericValid0 fnsTF deployed) (fun _ _ => True) Post := by + have hdep := deploy_eq + simp only [deploy?, hc] at hdep + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + refine functional_ctx hdd (check_tf_ok hc) (base := SolarTV.Export.UniswapV2ERC20.Ctx.cx.base) + (by decide) (genericValid0_inhabited fn_transferFrom [] deployed) + (fun o => SolarTV.Milestone.Uv2Erc20ATF.uv2_erc20_atf_mir_to_evmir o) hscopeTF ?_ meets + intro gas hg call hv + obtain ⟨o, -, -, -, hok, hw⟩ := SolarTV.Export.UniswapV2ERC20.Ctx.bytecode [] _ hP hQ gas hg call hv + exact ⟨o, hok, hw⟩ + +/-- Equivalence and termination of transferFrom, with no specification. -/ +theorem compiled_tf + (hP : ∀ gas, SolidCore.Refinement.Solar.AssembleCallSeg.StaticRunner gas) + (hQ : ∀ gas call, genericValid0 fnsTF deployed call → + SolidCore.Refinement.Solar.AssembleCallSeg.CalleesRun gas SolarTV.Export.UniswapV2ERC20.Ctx.code call) : + ∃ c, SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c ∧ + Functional (solidCore SolidCore.Verify.VC.UniswapV2ERC20.fuel) c SolarTV.Export.UniswapV2ERC20.Ctx.code + (genericValid0 fnsTF deployed) (fun _ _ => True) (fun _ _ => True) := by + obtain ⟨c, hc⟩ := SolidCore.Verify.VC.UniswapV2ERC20.contract_ok + exact ⟨c, hc, functional_tf hP hQ hc fun _ _ _ _ => trivial⟩ + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.compiled_tf' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms compiled_tf + +end SolidCore.Spec.UniswapV2.ERC20 diff --git a/Contracts/UniswapV2/ERC20/EndToEndTFSpec.lean b/Contracts/UniswapV2/ERC20/EndToEndTFSpec.lean new file mode 100644 index 00000000..873a624d --- /dev/null +++ b/Contracts/UniswapV2/ERC20/EndToEndTFSpec.lean @@ -0,0 +1,41 @@ +import Contracts.UniswapV2.ERC20.EndToEndTF +import Contracts.UniswapV2.ERC20.ConnectTFSplit + +/-! +# UniswapV2ERC20's transferFrom: equivalence, termination and its exported spec on the exact bytecode + +`published_tf` is `functional_tf` with solar-verify's exported spec of `transferFrom`, proved of +SolidCore's checked contract branch by branch (ConnectTFSplit's `transferFrom_holds`, under +`NestedSlotsSeparated [1, 4] [2]`), with the identity ghost step. No gas bound: not +`Shapes.Certified`. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.EndToEndTF + +open SolidCore.Spec SolidCore.Refinement SolidCore.Refinement.Shapes SolidCore.Spec.UniswapV2.ERC20 + +def idStep : GhostStep := fun _ g => g + +/-- transferFrom's exported spec of every result on its calls. -/ +def Post (call : SolarTV.Call) (obs : SolarTV.Observable) : Prop := + holdsPost SolidCore.Spec.UniswapV2.ERC20TF.spec SolidCore.Spec.UniswapV2.ERC20TF.ctxOf idStep + SolidCore.Spec.UniswapV2.ERC20TF.transferFrom_spec + (SolidCore.Verify.VC.stageScope SolidCore.Spec.UniswapV2.ERC20TF.fn_transferFrom + SolidCore.Spec.UniswapV2.ERC20TF.deployed) call obs + +theorem published_tf (hsep : NestedSlotsSeparated [1, 4] [2]) + (hP : ∀ gas, SolidCore.Refinement.Solar.AssembleCallSeg.StaticRunner gas) + (hQ : ∀ gas call, genericValid0 fnsTF deployed call → + SolidCore.Refinement.Solar.AssembleCallSeg.CalleesRun gas SolarTV.Export.UniswapV2ERC20.Ctx.code call) : + ∃ c, SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c ∧ + Functional (solidCore SolidCore.Verify.VC.UniswapV2ERC20.fuel) c SolarTV.Export.UniswapV2ERC20.Ctx.code + (genericValid0 fnsTF deployed) (fun _ _ => True) Post := by + obtain ⟨c, hc⟩ := SolidCore.Verify.VC.UniswapV2ERC20.contract_ok + exact ⟨c, hc, functional_tf hP hQ hc + (meets_of_holdsFn (SolidCore.Spec.UniswapV2.ERC20TF.transferFrom_holds hsep hc idStep (fun _ _ _ => rfl)))⟩ + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.EndToEndTF.published_tf' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms published_tf + +end SolidCore.Spec.UniswapV2.ERC20.EndToEndTF diff --git a/Contracts/UniswapV2/ERC20/Lowering.lean b/Contracts/UniswapV2/ERC20/Lowering.lean new file mode 100644 index 00000000..084d72b7 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Lowering.lean @@ -0,0 +1,46 @@ +import Contracts.UniswapV2.ERC20.Connect +import SolidCore.Refinement.Generic.Stage +import uv2_erc20.gen.UniswapV2ERC20.Stage0 + +/-! +# UniswapV2ERC20: the generic source stage to solar's first lowered MIR, for approve and transfer + +`check_eq`: the generic check (`Generic.check` with the caller and the hash of two words) accepts +`SolarTV.Export.UniswapV2ERC20.stage0`, solar's first lowered MIR of the same file, for `approve` +and `transfer` against SolidCore's checked contract, evaluated by the kernel from the source text +up (`kernel_rfl`, with the selector, event-topic and Keccak-256 tables each entry of which the +kernel checks once). +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20 + +open SolidCore.Refinement SolidCore.Refinement.Generic + +/-- The steps along each path of the symbolic run of the module. -/ +def mirFuel : Nat := 200 + +/-- The functions of the statement. -/ +def fns : List SolidCore.Refinement.Abi.Fn := [fn_approve, fn_transfer] + +/-- Whether the generic check accepts stage0 for `fns`. -/ +def check? : Bool := + match SolidCore.Verify.VC.UniswapV2ERC20.contract? with + | .ok c => Generic.check SolidCore.Verify.VC.UniswapV2ERC20.fuel mirFuel c.core + SolarTV.Export.UniswapV2ERC20.stage0 fns .all + | .error _ => false + +kernel_rfl check_eq check? true using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +theorem check_ok {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Generic.check SolidCore.Verify.VC.UniswapV2ERC20.fuel mirFuel c.core + SolarTV.Export.UniswapV2ERC20.stage0 fns .all = true := by + have h := check_eq + simp only [check?, hc] at h + exact h + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.check_ok' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms check_ok + +end SolidCore.Spec.UniswapV2.ERC20 diff --git a/Contracts/UniswapV2/ERC20/Meets.lean b/Contracts/UniswapV2/ERC20/Meets.lean new file mode 100644 index 00000000..d8f65471 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Meets.lean @@ -0,0 +1,71 @@ +import Contracts.UniswapV2.ERC20.Connect +import Contracts.UniswapV2.ERC20.SpecMut + +/-! +# UniswapV2ERC20: the specs of SolidCore's checked contract, and a spec mutant refused + +`Connect.lean` (generated by scripts/verify/uniswap_v2_spec.sh with solar's +tools/certify/spec_connect.py; not committed, since it holds the erased trees of the GPL-3.0 +v2-core port) proves, for `approve` and `transfer`, solar-verify's exported spec +(`--emit-lean-spec` of crates/verify/uniswap-v2/uniswap-v2.spec) of the generic source stage's +erased tree by `tree_meets_map2` (`_meets`), and of SolidCore's checked UniswapV2ERC20 on the +stage's calls in every world (`_holds_in`). `transfer`'s tree is `_transfer` inlined with its +two SafeMath calls by `eraseFn`. + +The hypotheses are named: `NestedSlotsSeparated [1] [2]` (keccak256 separated on the slots of +`balanceOf[a]` and `allowance[o][s]`), and the ghost step (`hstep`): the ghosts `sumBalances` and +`zeroMinted` change only in `_mint` and `_burn`, so on a call of `approve` or `transfer` the +ghost state is unchanged. The specs' invariants (`totalSupply == sumBalances`, +`allowance[address(0)][s] == 0`, `balanceOf[address(0)] >= zeroMinted`) are assumed before the +call and proved after it. + +`wrong_not_meets` is the negative control: the spec mutant (`transfer` credits +`old(balanceOf[to]) + value + 1`, SpecMut.lean) does not hold of the same tree, with no +hypothesis: `transfer(1, 0)` from the empty storage succeeds and leaves `balanceOf[1]` at 0. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Meets + +open SolidCore.Spec SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Spec.UniswapV2.ERC20 + +/-- The mutant's spec of `transfer`. -/ +def mutSpec : FnSpec := + SolidCore.Spec.Export.UniswapV2ERC20SpecMut.UniswapV2ERC20.spec.specs[1]'(by decide) + +set_option linter.unusedSimpArgs false in +/-- **The spec mutant does not hold of `transfer`'s tree**: `transfer(1, 0)` from the empty storage +succeeds with `balanceOf[1]` still 0, and the mutant asks for 1. -/ +theorem wrong_not_meets : + ¬ TreeMeetsFixed SolidCore.Spec.Export.UniswapV2ERC20SpecMut.UniswapV2ERC20 mutSpec ctx 2 + transfer_tree := by + intro h + have hp := h [1, 0] (fun _ => 0) [1, 0] ⟨fun _ => 0, Ghost.zero, 0⟩ rfl (by simp) (by simp) + (by simp [mutSpec, SolidCore.Spec.Export.UniswapV2ERC20SpecMut.UniswapV2ERC20, decodeWords, + Ty.ofWord]) + rfl (by simp [ctx]) + (by simp [Bundle.satAll, mutSpec, SolidCore.Spec.Export.UniswapV2ERC20SpecMut.UniswapV2ERC20]) + (by simp [Bundle.satAll, Bundle.sat, SolidCore.Spec.Export.UniswapV2ERC20SpecMut.UniswapV2ERC20, + eval, slotOf, mkEnv, Env.cur, Env.bind, Ghost.zero, BinOp.apply, Ty.ofBits, forall_int_range, + Nat.zero_div, Nat.zero_mod]) + have hlt := solHash_lt' + have hkec := keccak_solHash + generalize solHash = H at hp hlt hkec + simp only [transfer_tree, Tree.eval, WExpr.eval, BinOp.eval, UnOp.eval, Generic.wordSize, Res.obs, + Writes.store, List.getD_cons_zero, List.getD_cons_succ, Nat.reducePow, Nat.reduceMod, Nat.zero_mod, + Nat.reduceLT, ite_mod_nat, ite_true, ite_false, Nat.lt_irrefl, Nat.not_lt_zero, decide_false, + Nat.reduceAdd, Nat.reduceSub, Nat.zero_add, Nat.add_zero, ite_self, Nat.one_ne_zero, + Nat.reduceEqDiff, reduceIte] at hp + obtain ⟨rets, -, hens, -⟩ := hp.1 rfl + simp only [Bundle.satAll, Bundle.sat, mutSpec, SolidCore.Spec.Export.UniswapV2ERC20SpecMut.UniswapV2ERC20, + List.getElem_cons_succ, List.getElem_cons_zero, List.mem_cons, List.not_mem_nil, or_false, + forall_eq_or_imp, forall_eq, eval, evalList, slotOf, mkEnv, Env.cur, Env.bind, BinOp.apply, Ty.ofBits, + toWord, ctx, List.getD_cons_zero, List.getD_cons_succ, hkec, ofProp_ne_zero, ite_true, ite_false, + Nat.zero_div, Nat.zero_mod, Int.reduceMod, Int.reduceToNat] at hens + have h2 := hens.2.1 (by decide) + simp at h2 + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Meets.wrong_not_meets' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms wrong_not_meets + +end SolidCore.Spec.UniswapV2.ERC20.Meets diff --git a/Contracts/UniswapV2/ERC20/Nested/All.lean b/Contracts/UniswapV2/ERC20/Nested/All.lean new file mode 100644 index 00000000..43842e25 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Nested/All.lean @@ -0,0 +1,7 @@ +import Contracts.UniswapV2.ERC20.Nested.Approve +import Contracts.UniswapV2.ERC20.Nested.LoweringApprove +import Contracts.UniswapV2.ERC20.Nested.LoweringTransferFrom +import Contracts.UniswapV2.ERC20.Nested.TransferFrom +import Contracts.UniswapV2.ERC20.Nested.NegE3 + +/-! # slice2-nested: UniswapV2ERC20's approve and transferFrom (see RESULT.md for the edges proved). -/ diff --git a/Contracts/UniswapV2/ERC20/Nested/Approve.lean b/Contracts/UniswapV2/ERC20/Nested/Approve.lean new file mode 100644 index 00000000..7009e0e2 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Nested/Approve.lean @@ -0,0 +1,159 @@ +import Contracts.UniswapV2.ERC20.Nested.Trees +import Verify.Spec.HashScopeNested +import Verify.Spec.Tree +import Verify.Shapes + +/-! +# UniswapV2ERC20.approve: its exact result, sequentially, and the source's runs meet it + +The slot-level statement needs no hash premise: `approveResult st spender value` is the source's +effect in source order (one write `allowance[caller][spender] = value` at the slot SolidCore computes, +`solHash spender (solHash caller 2)`, then the `Approval` log and `true`), and `approve_tree_eval` proves +the generic source stage's tree gives exactly it on every argument word and every storage. The frame +is over that one slot (`approve_frame`): every slot other than the written one keeps its value, said +of slots, never of "all other keys" (which would ask keccak256 to be injective everywhere). + +`approve_meets` carries it to SolidCore's checked contract on every valid call of approve (the +generic stage's calls: any argument words, no value, any storage covering the deployed one), by +`source_run`. + +`approve_keys` is the key-level reading, under `HashScopeNested.Scoped (approveFootprint caller spender)` +(keccak256 separated on the two preimages this call hashes): the written slot is no small constant +slot, so `totalSupply` (slot 0) and `DOMAIN_SEPARATOR` (slot 3) are unchanged. + +Scope: the caller is the stage's (`0x2000`, SolidCore's `msg.sender` on these runs); `SolarTV.Call` has +no caller field, so any-caller is a gap of the shared statement, named in RESULT.md. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Nested + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Refinement.Shapes + +/-- The stage's caller: `msg.sender` of SolidCore's runs of the generic stage. -/ +abbrev caller : Nat := 0x2000 + +/-- `st` with slot `k` set to `v`; slots are words, so slot `n` is slot `n % 2 ^ 256`. -/ +def upd (st : Nat → Nat) (k v : Nat) : Nat → Nat := fun n => if k = n % 2 ^ 256 then v else st n + +/-- A word as its 32 big-endian bytes. -/ +def word32 (v : Nat) : List Nat := (List.range 32).map fun i => v / 256 ^ (31 - i) % 256 + +/-- The slot of `allowance[o][s]` (allowance at slot 2), as SolidCore computes it. -/ +abbrev allowanceSlot (o s : Nat) : Nat := solHash s (solHash o 2) + +/-- The slot of `balanceOf[a]` (balanceOf at slot 1). -/ +abbrev balanceSlot (a : Nat) : Nat := solHash a 1 + +/-- `keccak256("Approval(address,address,uint256)")`. -/ +abbrev approvalTopic : Nat := 63486140976153616755203102783360879283472101686154884697241723088393386309925 + +/-- The argument words of a call: its calldata's words after the selector. -/ +def callArgs (call : Call) : List Nat := words ((call.calldata.data.toList.map (·.toNat)).drop 4) + +/-- **approve(spender, value) from the caller on storage `st`**: a dirty address reverts with no data +and no change; otherwise `allowance[caller][spender] = value`, `Approval(caller, spender, value)`, +returns `true`. -/ +def approveResult (st : Nat → Nat) (spender value : Nat) : Observable := + if spender < 2 ^ 160 then + { success := true, output := word32 1, + logs := [([approvalTopic, caller, spender], word32 value)], + storage := upd st (allowanceSlot caller spender) value } + else { success := false, output := [], logs := [], storage := st } + +/-- **The generic source stage's tree of approve gives exactly `approveResult`**, on every argument +word and every storage. -/ +theorem approve_tree_eval (spender value : Nat) (st : Nat → Nat) (hs : spender < 2 ^ 256) + (hv : value < 2 ^ 256) : + (approve_tree.eval ⟨[spender, value], st, solHash, SolidCore.Refinement.Generic.callerWord⟩).obs = approveResult st spender value := by + have hl := solHash_lt + simp only [Generic.wordSize] at hl + have hsN : spender % 2 ^ 256 = spender := Nat.mod_eq_of_lt hs + have hvN : value % 2 ^ 256 = value := Nat.mod_eq_of_lt hv + have hH : ∀ a b, solHash a b % 2 ^ 256 = solHash a b := fun a b => Nat.mod_eq_of_lt (hl a b) + simp only [approve_tree, approveResult, Tree.eval, WExpr.eval, BinOp.eval, Res.obs, Generic.wordSize, + List.getD_cons_zero, List.getD_cons_succ, Writes.store, Log.eval, List.map_cons, List.map_nil, + OByte.eval, hsN, hvN, hH] + by_cases h : spender < 2 ^ 160 + · have hn : ¬ (1461501637330902918203684832716283019655932542975 % 2 ^ 256 < spender) := by omega + simp only [hn, h, if_false, if_true, Nat.zero_mod] + simp only [Observable.mk.injEq, true_and] + refine ⟨by simp [word32, List.range_succ], by simp [word32, List.range_succ, caller, approvalTopic], ?_⟩ + funext n + simp [upd, caller, allowanceSlot] + · have hn : 1461501637330902918203684832716283019655932542975 < spender := by omega + have h' : ¬ spender < 1461501637330902918203684832716283019655932542976 := h + simp [hn, h'] + +/-- **approve's frame is its one slot**: on success, every slot but `allowance[caller][spender]`'s +keeps its value. Said of slots: no premise on keccak256. -/ +theorem approve_frame (st : Nat → Nat) (spender value n : Nat) + (hn : n % 2 ^ 256 ≠ allowanceSlot caller spender) : + (approveResult st spender value).storage n = st n := by + simp only [Nat.reducePow] at hn + unfold approveResult + split <;> simp [upd, Ne.symm hn] + +/-- The postcondition of every source result on a valid call of approve: exactly `approveResult` of +the call's storage and argument words. -/ +def ApprovePost (call : Call) (obs : Observable) : Prop := + obs = approveResult (slotValue call.storage) ((callArgs call).getD 0 0) ((callArgs call).getD 1 0) + +/-- The valid calls of approve: the generic stage's (any argument words, no value, any storage +covering the deployed one). -/ +abbrev ApproveValid (call : Call) : Prop := + ∃ σ, Covers deployed σ ∧ SolidCore.Refinement.Abi.fullScope [fn_approve] σ call + +/-- **approve's exact result holds of every SolidCore run of the checked UniswapV2ERC20** on its +valid calls. No hash premise. -/ +theorem approve_meets {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Meets (solidCore SolidCore.Verify.VC.UniswapV2ERC20.fuel) c ApproveValid ApprovePost := by + have hdep := deploy_eq + simp only [deploy?, hc] at hdep + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + have hmap := approve_erase_eq + simp only [approve_erase?, hc, Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + rintro _ ⟨σ, hcov, fn, hfn, args, hl, hargs, rfl⟩ obs hrun + simp only [List.mem_singleton] at hfn + subst hfn + change Source.run SolidCore.Verify.VC.UniswapV2ERC20.fuel c + { calldata := SolidCore.Refinement.Abi.calldata 157198259 args, callvalue := 0, storage := σ } = some obs at hrun + have hrun' := source_run hdd hcov (by decide) hf hT args (by simpa [fn_approve] using hl.trans hlen.symm) hargs + rw [hrun'] at hrun + cases hrun + match args, hl, hargs with + | [spender, value], _, hargs => + have h0 := hargs spender (by simp) + have h1 := hargs value (by simp) + unfold ApprovePost callArgs + rw [words_calldata _ hargs] + exact approve_tree_eval spender value _ h0 h1 + +/-- **approve, key by key, on its footprint**: under keccak256's separation on the two preimages of +`allowance[caller][spender]`'s slot, a clean call succeeds, `allowance[caller][spender]` is `value`, +and every small constant slot (`totalSupply` at 0, `DOMAIN_SEPARATOR` at 3) is unchanged. -/ +theorem approve_keys (st : Nat → Nat) (spender value : Nat) (hsp : spender < 2 ^ 160) + (h : HashScopeNested.Scoped (HashScopeNested.approveFootprint caller spender)) : + (approveResult st spender value).success = true ∧ + (approveResult st spender value).storage (allowanceSlot caller spender) = value ∧ + ∀ k < 2 ^ 128, (approveResult st spender value).storage k = st k := by + have hge := HashScopeNested.approve_slot h + have hlt := solHash_lt spender (solHash caller 2) + unfold Generic.wordSize at hlt + have hsp' : spender < 1461501637330902918203684832716283019655932542976 := hsp + have hlt' : allowanceSlot caller spender < 115792089237316195423570985008687907853269984665640564039457584007913129639936 := hlt + refine ⟨by simp [approveResult, hsp'], by simp [approveResult, hsp', upd, Nat.mod_eq_of_lt hlt'], ?_⟩ + intro k hk + have hk' : k % 2 ^ 256 = k := Nat.mod_eq_of_lt (by omega) + exact approve_frame st spender value k (by rw [hk']; intro e; simp only [allowanceSlot] at e; omega) + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Nested.approve_meets' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms approve_meets + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Nested.approve_keys' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms approve_keys + +end SolidCore.Spec.UniswapV2.ERC20.Nested diff --git a/Contracts/UniswapV2/ERC20/Nested/LoweringApprove.lean b/Contracts/UniswapV2/ERC20/Nested/LoweringApprove.lean new file mode 100644 index 00000000..ccdbd89d --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Nested/LoweringApprove.lean @@ -0,0 +1,68 @@ +import Contracts.UniswapV2.ERC20.Nested.Trees +import SolidCore.Refinement.Generic.Stage +import SolidCore.Refinement.Generic.Total +import uv2_erc20.gen.UniswapV2ERC20.Stage0 + +/-! +# UniswapV2ERC20.approve: SolidCore's source to solar's first lowered MIR (edge E3) + +`check_approve_ok`: the generic source check (`Generic.check`, every environment flag) accepts +`SolarTV.Export.UniswapV2ERC20.stage0`, solar's first lowered MIR of the same pinned source +(scripts/verify/uniswap_v2_erc20_stages.sh, `-Ogas --evm-version osaka`), for `approve` alone, against +SolidCore's checked contract, evaluated by the kernel from the source text up (`kernel_rfl`). +`approve_source_to_mir` is the stage it gives: under every oracle whose caller and two-word Keccak-256 +are SolidCore's (`Generic.SourceEnvOk`), every SolidCore result on a valid call of approve (any argument +words, no value, any storage covering the deployed one) is stage0's; `approve_defined`: SolidCore has a +result on each (termination within the fuel, by the checker, not by a fuel premise). +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Nested + +open SolidCore.Refinement SolidCore.Refinement.Generic + +/-- The steps along each path of the symbolic run of stage0. -/ +def mirFuel : Nat := 200 + +def checkapprove? : Bool := + match SolidCore.Verify.VC.UniswapV2ERC20.contract? with + | .ok c => Generic.check SolidCore.Verify.VC.UniswapV2ERC20.fuel mirFuel c.core + SolarTV.Export.UniswapV2ERC20.stage0 [fn_approve] .all + | .error _ => false + +kernel_rfl checkapprove_eq checkapprove? true using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +theorem check_approve_ok {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Generic.check SolidCore.Verify.VC.UniswapV2ERC20.fuel mirFuel c.core + SolarTV.Export.UniswapV2ERC20.stage0 [fn_approve] .all = true := by + have h := checkapprove_eq + simp only [checkapprove?, hc] at h + exact h + +/-- **E3 for approve**: SolidCore's checked source to solar's stage0, on approve's valid calls. -/ +theorem approve_source_to_mir (o : SolarTV.Machine.Oracle) (ho : Generic.SourceEnvOk o) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + SolarTV.Stage (solidCore SolidCore.Verify.VC.UniswapV2ERC20.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.UniswapV2ERC20.stage0 + (fun call => ∃ σ, Covers deployed σ ∧ SolidCore.Refinement.Abi.fullScope [fn_approve] σ call) := by + have hdep := deploy_eq + simp only [deploy?, hc] at hdep + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + exact stageAtWith o hdd ho.ask (check_approve_ok hc) + +/-- SolidCore has a result on every valid call of approve. -/ +theorem approve_defined {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Defined (solidCore SolidCore.Verify.VC.UniswapV2ERC20.fuel) c + (fun call => ∃ σ, Covers deployed σ ∧ SolidCore.Refinement.Abi.fullScope [fn_approve] σ call) := by + have hdep := deploy_eq + simp only [deploy?, hc] at hdep + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + exact definedAt hdd (check_approve_ok hc) + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Nested.approve_source_to_mir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms approve_source_to_mir + +end SolidCore.Spec.UniswapV2.ERC20.Nested diff --git a/Contracts/UniswapV2/ERC20/Nested/LoweringTransferFrom.lean b/Contracts/UniswapV2/ERC20/Nested/LoweringTransferFrom.lean new file mode 100644 index 00000000..d9241e12 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Nested/LoweringTransferFrom.lean @@ -0,0 +1,66 @@ +import Contracts.UniswapV2.ERC20.Nested.Trees +import SolidCore.Refinement.Generic.Stage +import SolidCore.Refinement.Generic.Total +import uv2_erc20.gen.UniswapV2ERC20.Stage0 +import Contracts.UniswapV2.ERC20.Nested.LoweringApprove + +/-! +# UniswapV2ERC20.transferFrom: SolidCore's source to solar's first lowered MIR (edge E3) + +`check_transferFrom_ok`: the generic source check (`Generic.check`, every environment flag) accepts +`SolarTV.Export.UniswapV2ERC20.stage0`, solar's first lowered MIR of the same pinned source +(scripts/verify/uniswap_v2_erc20_stages.sh, `-Ogas --evm-version osaka`), for `transferFrom` alone, against +SolidCore's checked contract, evaluated by the kernel from the source text up (`kernel_rfl`). +`transferFrom_source_to_mir` is the stage it gives: under every oracle whose caller and two-word Keccak-256 +are SolidCore's (`Generic.SourceEnvOk`), every SolidCore result on a valid call of transferFrom (any argument +words, no value, any storage covering the deployed one) is stage0's; `transferFrom_defined`: SolidCore has a +result on each (termination within the fuel, by the checker, not by a fuel premise). +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Nested + +open SolidCore.Refinement SolidCore.Refinement.Generic + +def checktransferFrom? : Bool := + match SolidCore.Verify.VC.UniswapV2ERC20.contract? with + | .ok c => Generic.check SolidCore.Verify.VC.UniswapV2ERC20.fuel mirFuel c.core + SolarTV.Export.UniswapV2ERC20.stage0 [fn_transferFrom] .all + | .error _ => false + +kernel_rfl checktransferFrom_eq checktransferFrom? true using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +theorem check_transferFrom_ok {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Generic.check SolidCore.Verify.VC.UniswapV2ERC20.fuel mirFuel c.core + SolarTV.Export.UniswapV2ERC20.stage0 [fn_transferFrom] .all = true := by + have h := checktransferFrom_eq + simp only [checktransferFrom?, hc] at h + exact h + +/-- **E3 for transferFrom**: SolidCore's checked source to solar's stage0, on transferFrom's valid calls. -/ +theorem transferFrom_source_to_mir (o : SolarTV.Machine.Oracle) (ho : Generic.SourceEnvOk o) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + SolarTV.Stage (solidCore SolidCore.Verify.VC.UniswapV2ERC20.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.UniswapV2ERC20.stage0 + (fun call => ∃ σ, Covers deployed σ ∧ SolidCore.Refinement.Abi.fullScope [fn_transferFrom] σ call) := by + have hdep := deploy_eq + simp only [deploy?, hc] at hdep + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + exact stageAtWith o hdd ho.ask (check_transferFrom_ok hc) + +/-- SolidCore has a result on every valid call of transferFrom. -/ +theorem transferFrom_defined {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Defined (solidCore SolidCore.Verify.VC.UniswapV2ERC20.fuel) c + (fun call => ∃ σ, Covers deployed σ ∧ SolidCore.Refinement.Abi.fullScope [fn_transferFrom] σ call) := by + have hdep := deploy_eq + simp only [deploy?, hc] at hdep + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + exact definedAt hdd (check_transferFrom_ok hc) + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Nested.transferFrom_source_to_mir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms transferFrom_source_to_mir + +end SolidCore.Spec.UniswapV2.ERC20.Nested diff --git a/Contracts/UniswapV2/ERC20/Nested/NegE3.lean b/Contracts/UniswapV2/ERC20/Nested/NegE3.lean new file mode 100644 index 00000000..a1ad5971 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Nested/NegE3.lean @@ -0,0 +1,35 @@ +import Contracts.UniswapV2.ERC20.Nested.LoweringTransferFrom +import uv2_erc20.gen.UniswapV2ERC20.Stage0Mut1 +import uv2_erc20.gen.UniswapV2ERC20.Stage0Mut2 +import uv2_erc20.gen.UniswapV2ERC20.Stage0Mut3 + +/-! +# Negative controls of E3 for approve and transferFrom, by execution + +The generic source check that accepts solar's stage0 (`check_approve_ok`, `check_transferFrom_ok`) +refuses, by the kernel's evaluation, three mutants of that same stage0 +(scripts/verify/uniswap_v2_stage0_mutants.py): `_approve` with its SSTORE of +`allowance[owner][spender]` dropped (`rejects_approve_no_write`), `_approve` hashing the owner into +mapping slot 3 instead of allowance's slot 2 (`rejects_approve_wrong_slot`), and `transferFrom` with +the SSTORE of the spent allowance dropped (`rejects_transferFrom_no_spend`). Each is a mismatch of the +symbolic run against the source's tree, `false`, never a timeout. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Nested + +open SolidCore.Refinement SolidCore.Refinement.Generic + +def checkMut? (m : SolarTV.MIR.Lowered.Module) (fn : SolidCore.Refinement.Abi.Fn) : Bool := + match SolidCore.Verify.VC.UniswapV2ERC20.contract? with + | .ok c => Generic.check SolidCore.Verify.VC.UniswapV2ERC20.fuel mirFuel c.core m [fn] .all + | .error _ => true + +def checkMut1? : Bool := checkMut? SolarTV.Export.UniswapV2ERC20Mut1.stage0 fn_approve +def checkMut2? : Bool := checkMut? SolarTV.Export.UniswapV2ERC20Mut2.stage0 fn_approve +def checkMut3? : Bool := checkMut? SolarTV.Export.UniswapV2ERC20Mut3.stage0 fn_transferFrom + +kernel_rfl rejects_approve_no_write checkMut1? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq +kernel_rfl rejects_approve_wrong_slot checkMut2? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq +kernel_rfl rejects_transferFrom_no_spend checkMut3? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +end SolidCore.Spec.UniswapV2.ERC20.Nested diff --git a/Contracts/UniswapV2/ERC20/Nested/TransferFrom.lean b/Contracts/UniswapV2/ERC20/Nested/TransferFrom.lean new file mode 100644 index 00000000..9e06afdd --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Nested/TransferFrom.lean @@ -0,0 +1,161 @@ +import Contracts.UniswapV2.ERC20.Nested.TransferFromSpec + +namespace SolidCore.Spec.UniswapV2.ERC20.Nested + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Refinement.Shapes + +/-- The postcondition of every source result on a valid call of transferFrom: exactly +`transferFromResult` of the call's storage and argument words. -/ +def TransferFromPost (call : Call) (obs : Observable) : Prop := + obs = transferFromResult (slotValue call.storage) ((callArgs call).getD 0 0) ((callArgs call).getD 1 0) + ((callArgs call).getD 2 0) + +/-- The valid calls of transferFrom: the generic stage's. -/ +abbrev TransferFromValid (call : Call) : Prop := + ∃ σ, Covers deployed σ ∧ SolidCore.Refinement.Abi.fullScope [fn_transferFrom] σ call + +/-- **transferFrom's exact sequential result holds of every SolidCore run of the checked +UniswapV2ERC20** on its valid calls. No hash premise. -/ +theorem transferFrom_meets {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Meets (solidCore SolidCore.Verify.VC.UniswapV2ERC20.fuel) c TransferFromValid TransferFromPost := by + have hdep := deploy_eq + simp only [deploy?, hc] at hdep + obtain ⟨dd, hdd⟩ := Wide.deployedAt_of hdep + have hmap := transferFrom_erase_eq + simp only [transferFrom_erase?, hc, Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + rintro _ ⟨σ, hcov, fn, hfn, args, hl, hargs, rfl⟩ obs hrun + simp only [List.mem_singleton] at hfn + subst hfn + change Source.run SolidCore.Verify.VC.UniswapV2ERC20.fuel c + { calldata := SolidCore.Refinement.Abi.calldata 599290589 args, callvalue := 0, storage := σ } = some obs at hrun + have hrun' := source_run hdd hcov (by decide) hf hT args + (by simpa [fn_transferFrom] using hl.trans hlen.symm) hargs + rw [hrun'] at hrun + cases hrun + match args, hl, hargs with + | [frm, dst, value], _, hargs => + unfold TransferFromPost callArgs + rw [words_calldata _ hargs] + exact transferFrom_tree_eval frm dst value _ (hargs frm (by simp)) (hargs dst (by simp)) + (hargs value (by simp)) (fun k => Generic.slotValue_lt σ k) + +theorem upd_eq (st : Nat → Nat) {k : Nat} (v : Nat) (hk : k < 2 ^ 256) : upd st k v k = v := by + unfold upd; rw [Nat.mod_eq_of_lt hk]; simp + +theorem upd_ne (st : Nat → Nat) {k n : Nat} (v : Nat) (hn : n < 2 ^ 256) (h : k ≠ n) : + upd st k v n = st n := by + unfold upd; rw [Nat.mod_eq_of_lt hn]; simp [h] + +/-- **transferFrom between two parties, key by key, on its footprint**: under keccak256's separation +on the four preimages the call hashes, a clean call succeeds exactly when the allowance is infinite or +covers `value`, the balance covers it and the recipient's balance does not overflow (all on the +storage before the call), and then the allowance is spent (or stays infinite), the balance debited +and the recipient's credited. -/ +theorem transferFrom_keys (st : Nat → Nat) (hst : ∀ k, st k < 2 ^ 256) (frm dst value : Nat) + (hfa : frm < 2 ^ 160) (hda : dst < 2 ^ 160) (hne : frm ≠ dst) + (h : HashScopeNested.Scoped (HashScopeNested.transferFromFootprint caller frm dst)) : + ((transferFromResult st frm dst value).success = true ↔ + (st (allowanceSlot frm caller) = umax ∨ value ≤ st (allowanceSlot frm caller)) ∧ + value ≤ st (balanceSlot frm) ∧ st (balanceSlot dst) + value < 2 ^ 256) ∧ + ((transferFromResult st frm dst value).success = true → + (transferFromResult st frm dst value).storage (allowanceSlot frm caller) = + (if st (allowanceSlot frm caller) = umax then umax else st (allowanceSlot frm caller) - value) ∧ + (transferFromResult st frm dst value).storage (balanceSlot frm) = st (balanceSlot frm) - value ∧ + (transferFromResult st frm dst value).storage (balanceSlot dst) = st (balanceSlot dst) + value) := by + obtain ⟨hAF, hAT, hFT, -, -, -⟩ := HashScopeNested.transferFrom_slots h (by decide) (by omega) (by omega) + have hFT := hFT hne + have hl := solHash_lt + simp only [Generic.wordSize] at hl + have hA := hl caller (solHash frm 2) + have hF := hl frm 1 + have hT := hl dst 1 + have hsA := hst (allowanceSlot frm caller) + have hsF := hst (balanceSlot frm) + have hsT := hst (balanceSlot dst) + unfold transferFromResult transferSteps revertWith + simp only [allowanceSlot, balanceSlot, umax] at * + generalize solHash caller (solHash frm 2) = A at * + generalize solHash frm 1 = F at * + generalize solHash dst 1 = T at * + clear hl hst + simp only [hfa, hda, and_self, ite_true] + have r1 := upd_eq st (k := A); have r2 := upd_eq st (k := F); have r3 := upd_eq st (k := T) + have r1' := fun (s : Nat → Nat) v => upd_eq s (k := A) v hA + have r2' := fun (s : Nat → Nat) v => upd_eq s (k := F) v hF + have r3' := fun (s : Nat → Nat) v => upd_eq s (k := T) v hT + have q1 := fun (s : Nat → Nat) v => upd_ne s v hF hAF + have q2 := fun (s : Nat → Nat) v => upd_ne s v hT hAT + have q3 := fun (s : Nat → Nat) v => upd_ne s v hT hFT + have q4 := fun (s : Nat → Nat) v => upd_ne s v hA (Ne.symm hAT) + have q5 := fun (s : Nat → Nat) v => upd_ne s v hA (Ne.symm hAF) + have q6 := fun (s : Nat → Nat) v => upd_ne s v hF (Ne.symm hFT) + clear r1 r2 r3 + simp only [r1', r2', r3', q1, q2, q3, q4, q5, q6] + split_ifs <;> simp only [r1', r2', r3', q1, q2, q3, q4, q5, q6, Bool.true_eq_false, Bool.false_eq_true, + iff_true, iff_false, true_iff, false_iff, true_implies, false_implies, and_true, true_and, not_true_eq_false, + not_false_eq_true, IsEmpty.forall_iff, if_true, if_false, ite_true, ite_false] <;> omega + +/-- **transferFrom to oneself, on its footprint**: success exactly when the allowance is infinite or +covers `value` and the balance covers it, with no overflow condition (the credit reads the debited +slot); the balance is unchanged. -/ +theorem transferFrom_self (st : Nat → Nat) (hst : ∀ k, st k < 2 ^ 256) (frm value : Nat) + (hfa : frm < 2 ^ 160) + (h : HashScopeNested.Scoped (HashScopeNested.transferFromFootprint caller frm frm)) : + ((transferFromResult st frm frm value).success = true ↔ + (st (allowanceSlot frm caller) = umax ∨ value ≤ st (allowanceSlot frm caller)) ∧ + value ≤ st (balanceSlot frm)) ∧ + ((transferFromResult st frm frm value).success = true → + (transferFromResult st frm frm value).storage (balanceSlot frm) = st (balanceSlot frm)) := by + obtain ⟨hAF, -, -, -, -, -⟩ := HashScopeNested.transferFrom_slots h (by decide) (by omega) (by omega) + have hl := solHash_lt + simp only [Generic.wordSize] at hl + have hA := hl caller (solHash frm 2) + have hF := hl frm 1 + have hsA := hst (allowanceSlot frm caller) + have hsF := hst (balanceSlot frm) + unfold transferFromResult transferSteps revertWith + simp only [allowanceSlot, balanceSlot, umax] at * + generalize solHash caller (solHash frm 2) = A at * + generalize solHash frm 1 = F at * + clear hl hst + simp only [hfa, and_self, ite_true] + have r1' := fun (s : Nat → Nat) v => upd_eq s (k := A) v hA + have r2' := fun (s : Nat → Nat) v => upd_eq s (k := F) v hF + have q1 := fun (s : Nat → Nat) v => upd_ne s v hF hAF + have q5 := fun (s : Nat → Nat) v => upd_ne s v hA (Ne.symm hAF) + simp only [r1', r2', q1, q5] + split_ifs <;> simp only [r1', r2', q1, q5, Bool.true_eq_false, Bool.false_eq_true, + iff_true, iff_false, true_iff, false_iff, true_implies, false_implies, and_true, true_and, not_true_eq_false, + not_false_eq_true, IsEmpty.forall_iff, if_true, if_false, ite_true, ite_false] <;> omega + +/-- The target's concrete case, for transferFrom: a self-transfer of 1 at the maximal balance with an +infinite allowance succeeds and leaves the balance at `2 ^ 256 - 1`. -/ +theorem transferFrom_self_max (st : Nat → Nat) (hst : ∀ k, st k < 2 ^ 256) (frm : Nat) + (hfa : frm < 2 ^ 160) + (h : HashScopeNested.Scoped (HashScopeNested.transferFromFootprint caller frm frm)) + (hb : st (balanceSlot frm) = 2 ^ 256 - 1) (ha : st (allowanceSlot frm caller) = umax) : + (transferFromResult st frm frm 1).success = true ∧ + (transferFromResult st frm frm 1).storage (balanceSlot frm) = 2 ^ 256 - 1 := by + have := transferFrom_self st hst frm 1 hfa h + have hs : (transferFromResult st frm frm 1).success = true := this.1.2 ⟨.inl ha, by omega⟩ + exact ⟨hs, (this.2 hs).trans hb⟩ + +/-- The target's other concrete case: a self-transfer above the balance reverts. -/ +theorem transferFrom_self_short (st : Nat → Nat) (hst : ∀ k, st k < 2 ^ 256) (frm value : Nat) + (hfa : frm < 2 ^ 160) + (h : HashScopeNested.Scoped (HashScopeNested.transferFromFootprint caller frm frm)) + (hlt : st (balanceSlot frm) < value) : + (transferFromResult st frm frm value).success = false := by + have := (transferFrom_self st hst frm value hfa h).1 + cases hr : (transferFromResult st frm frm value).success + · rfl + · exact absurd (this.1 hr).2 (by omega) + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Nested.transferFrom_meets' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms transferFrom_meets + +end SolidCore.Spec.UniswapV2.ERC20.Nested + diff --git a/Contracts/UniswapV2/ERC20/Nested/TransferFromSpec.lean b/Contracts/UniswapV2/ERC20/Nested/TransferFromSpec.lean new file mode 100644 index 00000000..b7dcdf9f --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Nested/TransferFromSpec.lean @@ -0,0 +1,198 @@ +import Contracts.UniswapV2.ERC20.Nested.Approve + +/-! +# UniswapV2ERC20.transferFrom: its exact result, as sequential storage updates in source order + +`transferFromResult st frm dst value` is the source's effect step by step, each read seeing the writes +before it (so any aliasing of the slots is the source's, not assumed away): + +1. a dirty address (`frm` or `to` at least `2 ^ 160`) reverts with no data; +2. `a := allowance[frm][caller]`; unless `a` is `type(uint256).max`, `a < value` reverts with SafeMath's + `ds-math-sub-underflow`, else `allowance[frm][caller] = a - value`; +3. `b := balanceOf[frm]` (reading step 2's storage); `b < value` reverts (`ds-math-sub-underflow`), else + `balanceOf[frm] = b - value`; +4. `d := balanceOf[to]` (reading step 3's storage); `d + value >= 2 ^ 256` reverts + (`ds-math-add-overflow`), else `balanceOf[to] = d + value`; +5. `Transfer(frm, to, value)`, returns `true`. + +A revert changes no storage and logs nothing. `transferFrom_tree_eval` proves the generic stage's tree +gives exactly this on every argument word and every storage of words, with no hash premise; +`transferFrom_meets` carries it to SolidCore's checked contract on every valid call. +`transferFrom_keys` reads it key by key under `HashScopeNested.Scoped (transferFromFootprint caller frm dst)`: +the three slots are apart, so for `frm ≠ dst` success is `value ≤ a` (or `a` infinite), `value ≤ b` and +`d + value < 2 ^ 256` on the storage before the call, and for `frm = to` the balance is unchanged with +no overflow condition. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Nested + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Refinement.Shapes + +/-- `keccak256("Transfer(address,address,uint256)")`. -/ +abbrev transferTopic : Nat := 100389287136786176327247604509743168900146139575972864366142685224231313322991 + +/-- `type(uint256).max`. -/ +abbrev umax : Nat := 2 ^ 256 - 1 + +/-- The revert data of `Error(string)` for a message of at most 32 bytes. -/ +def errorData (msg : List Nat) : List Nat := + [8, 195, 121, 160] ++ word32 32 ++ word32 msg.length ++ msg ++ List.replicate (32 - msg.length) 0 + +/-- SafeMath's `ds-math-sub-underflow` revert data. -/ +def subUnderflow : List Nat := errorData ("ds-math-sub-underflow".toUTF8.toList.map (·.toNat)) + +/-- SafeMath's `ds-math-add-overflow` revert data. -/ +def addOverflow : List Nat := errorData ("ds-math-add-overflow".toUTF8.toList.map (·.toNat)) + +/-- A revert with data `d`: no change, no log. -/ +def revertWith (st : Nat → Nat) (d : List Nat) : Observable := + { success := false, output := d, logs := [], storage := st } + +/-- Steps 3 to 5 of transferFrom on the storage `s1` after the allowance step. -/ +def transferSteps (st s1 : Nat → Nat) (frm dst value : Nat) : Observable := + if value ≤ s1 (balanceSlot frm) then + let s2 := upd s1 (balanceSlot frm) (s1 (balanceSlot frm) - value) + if s2 (balanceSlot dst) + value < 2 ^ 256 then + { success := true, output := word32 1, logs := [([transferTopic, frm, dst], word32 value)], + storage := upd s2 (balanceSlot dst) (s2 (balanceSlot dst) + value) } + else revertWith st addOverflow + else revertWith st subUnderflow + +/-- **transferFrom(frm, to, value) from the caller on storage `st`**: see the module comment. -/ +def transferFromResult (st : Nat → Nat) (frm dst value : Nat) : Observable := + if frm < 2 ^ 160 ∧ dst < 2 ^ 160 then + if st (allowanceSlot frm caller) = umax then transferSteps st st frm dst value + else if value ≤ st (allowanceSlot frm caller) then + transferSteps st (upd st (allowanceSlot frm caller) (st (allowanceSlot frm caller) - value)) frm dst value + else revertWith st subUnderflow + else revertWith st [] + +end SolidCore.Spec.UniswapV2.ERC20.Nested + +namespace SolidCore.Spec.UniswapV2.ERC20.Nested + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic + +/-! ## The tree, compactly + +`tfTree` is `transferFrom_tree` with its words named (`transferFrom_tree_eq`, by `rfl`): the slots `wA` +(`allowance[frm][caller]`), `wF` (`balanceOf[frm]`), `wT` (`balanceOf[dst]`), and each read as the source +makes it after the writes before it (`wbF`: `balanceOf[frm]` after the allowance write, `wdT`: +`balanceOf[dst]` after both). -/ + +def wV : WExpr := .arg 2 +def wA : WExpr := .hash (.lit 8192) (.hash (.arg 0) (.lit 2)) +def wF : WExpr := .hash (.arg 0) (.lit 1) +def wT : WExpr := .hash (.arg 1) (.lit 1) +def wA1 : WExpr := .bin .sub (.sinit wA) wV +def wbF : WExpr := .sel (.bin .eq wF wA) wA1 (.sinit wF) +def wbT1 : WExpr := .sel (.bin .eq wT wA) wA1 (.sinit wT) +def wF2 : WExpr := .bin .sub wbF wV +def wdT : WExpr := .sel (.bin .eq wT wF) wF2 wbT1 +def wF2n : WExpr := .bin .sub (.sinit wF) wV +def wdTn : WExpr := .sel (.bin .eq wT wF) wF2n (.sinit wT) + +/-- A revert with the bytes `b`. -/ +def errT (b : List Nat) : Tree := .halt false (b.map OByte.lit) [] [] + +/-- Success with the writes `ws`: returns `true`, logs `Transfer(frm, dst, value)`. -/ +def okT (ws : Writes) : Tree := + .halt true (wordOBytes (.lit 1)) ws [⟨[.lit transferTopic, .arg 0, .arg 1], wordOBytes wV⟩] + +/-- SafeMath's check `require(x - y <= x)`, as the tree's condition (nonzero: no underflow). -/ +def noUnder (x x1 : WExpr) : WExpr := .un .iszero (.bin .lt x x1) + +def tfTree : Tree := + .ite (.bin .gt (.arg 0) (.lit 1461501637330902918203684832716283019655932542975)) (errT []) + (.ite (.bin .gt (.arg 1) (.lit 1461501637330902918203684832716283019655932542975)) (errT []) + (.ite (.un .iszero (.bin .eq (.sinit wA) (.lit (2 ^ 256 - 1)))) + (.ite (noUnder (.sinit wA) wA1) + (.ite (noUnder wbF wF2) + (.ite (noUnder (.bin .add wdT wV) wdT) + (okT [(wT, .bin .add wdT wV), (wF, .bin .sub wbF wV), (wA, wA1)]) + (errT addOverflow)) + (errT subUnderflow)) + (errT subUnderflow)) + (.ite (noUnder (.sinit wF) wF2n) + (.ite (noUnder (.bin .add wdTn wV) wdTn) (okT [(wT, .bin .add wdTn wV), (wF, wF2n)]) + (errT addOverflow)) + (errT subUnderflow)))) + +theorem transferFrom_tree_eq : transferFrom_tree = tfTree := by + decide +kernel + +theorem errT_eval (ρ : Val) (b : List Nat) (hb : b.map (· % 256) = b) : + ((errT b).eval ρ).obs = { success := false, output := b, logs := [], storage := ρ.store } := by + simp only [errT, Tree.eval, Res.obs, List.map_map, Function.comp_def, OByte.eval] + simp only [Bool.false_eq_true, if_false, Observable.mk.injEq, and_true, true_and] + exact hb + +theorem wordOBytes_eval (ρ : Val) (e : WExpr) : + (wordOBytes e).map (OByte.eval ρ) = word32 (e.eval ρ) := by + simp [wordOBytes, word32, List.map_map, Function.comp_def, OByte.eval] + +theorem okT_eval (ρ : Val) (ws : Writes) : + ((okT ws).eval ρ).obs = (⟨true, word32 1, + [([transferTopic, ρ.args.getD 0 0 % 2 ^ 256, ρ.args.getD 1 0 % 2 ^ 256], + word32 (ρ.args.getD 2 0 % 2 ^ 256))], Writes.store ρ ws⟩ : Observable) := by + simp only [okT, Tree.eval, Res.obs, if_true, List.map_cons, List.map_nil, Log.eval, wordOBytes_eval, + WExpr.eval, wV, Generic.wordSize] + simp [word32] + all_goals decide + +theorem eval_ite_obs (ρ : Val) (c : WExpr) (t e : Tree) : + ((Tree.ite c t e).eval ρ).obs = if c.eval ρ = 0 then (e.eval ρ).obs else (t.eval ρ).obs := by + simp only [Tree.eval] + split <;> rfl + +theorem subUnderflow_mod : subUnderflow.map (· % 256) = subUnderflow := by decide +kernel +theorem addOverflow_mod : addOverflow.map (· % 256) = addOverflow := by decide +kernel + +theorem ite01 (p : Prop) [Decidable p] : ((if p then 1 else 0) % 2 ^ 256 = 0) = ¬p := by + by_cases h : p <;> simp [h] + +set_option maxHeartbeats 4000000 in +/-- **The generic source stage's tree of transferFrom gives exactly `transferFromResult`**, on every +argument word and every storage of words, with no hash premise: the tree's selects on slot equality +are the source's own aliasing, which `upd` reproduces. -/ +theorem transferFrom_tree_eval (frm dst value : Nat) (st : Nat → Nat) (hf : frm < 2 ^ 256) + (ht : dst < 2 ^ 256) (hv : value < 2 ^ 256) (hst : ∀ k, st k < 2 ^ 256) : + (transferFrom_tree.eval ⟨[frm, dst, value], st, solHash, SolidCore.Refinement.Generic.callerWord⟩).obs = transferFromResult st frm dst value := by + have hl := solHash_lt + simp only [Generic.wordSize] at hl + have hH : ∀ a b, solHash a b % 2 ^ 256 = solHash a b := fun a b => Nat.mod_eq_of_lt (hl a b) + have hS : ∀ k, st k % 2 ^ 256 = st k := fun k => Nat.mod_eq_of_lt (hst k) + have hfN : frm % 2 ^ 256 = frm := Nat.mod_eq_of_lt hf + have htN : dst % 2 ^ 256 = dst := Nat.mod_eq_of_lt ht + have hvN : value % 2 ^ 256 = value := Nat.mod_eq_of_lt hv + rw [transferFrom_tree_eq] + simp only [tfTree, noUnder, eval_ite_obs, okT_eval, errT_eval _ _ subUnderflow_mod, + errT_eval _ _ addOverflow_mod, errT_eval _ [] rfl] + simp only [wA, wF, wT, wV, wA1, wbF, wbT1, wF2, wdT, wF2n, wdTn, WExpr.eval, BinOp.eval, UnOp.eval, + Writes.store, List.getD_cons_zero, List.getD_cons_succ, Generic.wordSize, hH, hS, hfN, htN, hvN] + unfold transferFromResult transferSteps revertWith + simp only [allowanceSlot, balanceSlot, caller, umax] + have hA := hl 8192 (solHash frm 2) + have hF := hl frm 1 + have hT := hl dst 1 + have hsA := hst (solHash 8192 (solHash frm 2)) + have hsF := hst (solHash frm 1) + have hsT := hst (solHash dst 1) + generalize solHash 8192 (solHash frm 2) = A at * + generalize solHash frm 1 = F at * + generalize solHash dst 1 = T at * + have hAm : A % 2 ^ 256 = A := Nat.mod_eq_of_lt hA + have hFm : F % 2 ^ 256 = F := Nat.mod_eq_of_lt hF + have hTm : T % 2 ^ 256 = T := Nat.mod_eq_of_lt hT + simp only [upd, ite01, not_not, Nat.mod_mod, hAm, hFm, hTm] + simp only [Nat.reducePow, Nat.reduceSub, Nat.reduceMod] + clear hl hH hS + split_ifs <;> first + | (exfalso; omega) + | (simp only [Observable.mk.injEq, true_and, and_true] + all_goals first + | rfl + | (funext n; (try simp only [upd]); (try dsimp only); split_ifs <;> omega)) + +end SolidCore.Spec.UniswapV2.ERC20.Nested + diff --git a/Contracts/UniswapV2/ERC20/NoCall.lean b/Contracts/UniswapV2/ERC20/NoCall.lean new file mode 100644 index 00000000..f3dcb6df --- /dev/null +++ b/Contracts/UniswapV2/ERC20/NoCall.lean @@ -0,0 +1,43 @@ +import SolidCore.Refinement.Solar.AssembleNoCall +import Contracts.UniswapV2.ERC20.Runtime + +/-! +# UniswapV2ERC20's exact runtime bytes and the call-free route + +`Runtime.code` is the runtime bytecode solar emits for the port (`-Ogas --evm-version osaka`), +written at build time by `scripts/verify/uniswap_v2_runtime.sh` (not committed). The kernel evaluates +`AssembleNoCall`'s call-free checks on it, and both **fail**: + +* `runtime_not_callFree`: the linear decode has instructions `callFree` refuses + (`NoCallAt`: a STATICCALL at 903, permit's call to ECRECOVER, and return-data reads at 1158, 1161 and + 1162; `NoCallOnly`: no other message-sending instruction). So + `AssembleNoCall.holds_of_checkCB_callFree` and `assembly_of_checkXB_norm_callFree` do not apply to + UniswapV2ERC20's runtime, and the call-free route cannot remove `StaticRunner`/`CalleesRun` there. +* `runtime_not_noFaByte`: `calleesRun_of_noFaByte` does not apply either. + +Each kernel evaluation of the 1183-byte decode peaks near 4.6 GB, so the checks are split across +the `NoCall*` modules, one process each under `-M 6000`. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.NoCall + +open SolidCore.Refinement.Solar.AssembleNoCall SolidCore.Refinement.Solar.Assemble +open SolarTV.Assembly + +abbrev code : ByteArray := Runtime.code + +/-- The decoded instructions of `c`, as `callFree` reads them. -/ +def decoded (c : ByteArray) : List (Nat × SolarTV.Assembly.Instr) := decodeFrom (bytesOf c) c.size 0 + +/-- The counters of the instructions `callFree` refuses. -/ +def refusedAt (c : ByteArray) : List Nat := + (decoded c).filterMap fun x => if instrFree x.2 then none else some x.1 + +/-- **The exact runtime fails the call-free check.** -/ +theorem runtime_not_callFree : callFree code = false := by decide +kernel + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.NoCall.runtime_not_callFree' depends on axioms: [propext] -/ +#guard_msgs (whitespace := lax) in +#print axioms runtime_not_callFree + +end SolidCore.Spec.UniswapV2.ERC20.NoCall diff --git a/Contracts/UniswapV2/ERC20/NoCallAt.lean b/Contracts/UniswapV2/ERC20/NoCallAt.lean new file mode 100644 index 00000000..e54884ce --- /dev/null +++ b/Contracts/UniswapV2/ERC20/NoCallAt.lean @@ -0,0 +1,21 @@ +import Contracts.UniswapV2.ERC20.NoCall + +/-! +# Where UniswapV2ERC20's runtime fails the call-free check + +`refusedAt_eq`: the counters of the instructions `callFree` refuses, the STATICCALL at 903 (permit's call +to ECRECOVER) and RETURNDATASIZE, RETURNDATACOPY, RETURNDATASIZE at 1158, 1161, 1162. They are of +solar 38b5232's output (Runtime.lean's header has its digest): bytes from another compiler fail this +theorem by evaluation, not silently. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.NoCall + +/-- The counters of the refused instructions. -/ +theorem refusedAt_eq : refusedAt code = [903, 1158, 1161, 1162] := by decide +kernel + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.NoCall.refusedAt_eq' depends on axioms: [propext] -/ +#guard_msgs (whitespace := lax) in +#print axioms refusedAt_eq + +end SolidCore.Spec.UniswapV2.ERC20.NoCall diff --git a/Contracts/UniswapV2/ERC20/NoCallControl.lean b/Contracts/UniswapV2/ERC20/NoCallControl.lean new file mode 100644 index 00000000..24f879ec --- /dev/null +++ b/Contracts/UniswapV2/ERC20/NoCallControl.lean @@ -0,0 +1,60 @@ +import Contracts.UniswapV2.ERC20.NoCallAt + +/-! +# Control: the refusal comes from the refused instructions alone + +`scrubWith qs c` is `c` with the byte at each counter of `qs` replaced by INVALID (0xfe), and +`scrubbed` scrubs exactly `refusedAt code` (`scrubbed_eq`, from `refusedAt_eq`). It has the runtime's size and its bytes off those counters +(`scrubWith_size`, `scrubWith_get`, by proof, not evaluation), and it **passes** `callFree` +(`scrubbed_callFree`): the decode stays aligned, and nothing but those instructions fails the check. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.NoCall + +open SolidCore.Refinement.Solar.AssembleNoCall SolidCore.Refinement.Solar.Assemble +open SolarTV.Assembly + +def scrubList (qs : List Nat) : Nat → List UInt8 → List UInt8 + | _, [] => [] + | i, b :: bs => (if qs.contains i then 0xfe else b) :: scrubList qs (i + 1) bs + +def scrubWith (qs : List Nat) (c : ByteArray) : ByteArray := ⟨(scrubList qs 0 c.data.toList).toArray⟩ + +theorem scrubList_length (qs : List Nat) : ∀ i (l : List UInt8), (scrubList qs i l).length = l.length + | _, [] => rfl + | i, _ :: bs => by rw [scrubList, List.length_cons, List.length_cons, scrubList_length qs (i + 1) bs] + +theorem scrubList_get (qs : List Nat) : ∀ i (l : List UInt8) k (hk : k < l.length), + qs.contains (i + k) = false → + (scrubList qs i l)[k]'(by rw [scrubList_length]; exact hk) = l[k] + | _, [], _, hk, _ => absurd hk (by simp) + | i, b :: bs, 0, _, hq => by + simp only [scrubList, List.getElem_cons_zero] + rw [Nat.add_zero] at hq + rw [hq]; rfl + | i, b :: bs, k + 1, hk, hq => by + simp only [scrubList, List.getElem_cons_succ] + exact scrubList_get qs (i + 1) bs k (Nat.lt_of_succ_lt_succ hk) (by rw [← hq]; congr 1; omega) + +theorem scrubWith_size (qs : List Nat) (c : ByteArray) : (scrubWith qs c).size = c.size := by + show (scrubList qs 0 c.data.toList).toArray.size = c.data.size + rw [List.size_toArray, scrubList_length, Array.length_toList] + +theorem scrubWith_get (qs : List Nat) (c : ByteArray) (i : Nat) (hi : i < c.size) + (hq : qs.contains i = false) : + (scrubWith qs c).data[i]'(by rw [← ByteArray.size, scrubWith_size]; exact hi) = c.data[i] := by + have h := scrubList_get qs 0 c.data.toList i (by rw [Array.length_toList]; exact hi) + (by rw [Nat.zero_add]; exact hq) + exact h.trans (by simp) + +def scrubbed : ByteArray := scrubWith [903, 1158, 1161, 1162] code + +theorem scrubbed_eq : scrubbed = scrubWith (refusedAt code) code := by rw [refusedAt_eq]; rfl + +theorem scrubbed_callFree : callFree scrubbed = true := by decide +kernel + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.NoCall.scrubbed_callFree' depends on axioms: [propext] -/ +#guard_msgs (whitespace := lax) in +#print axioms scrubbed_callFree + +end SolidCore.Spec.UniswapV2.ERC20.NoCall diff --git a/Contracts/UniswapV2/ERC20/NoCallDecode.lean b/Contracts/UniswapV2/ERC20/NoCallDecode.lean new file mode 100644 index 00000000..6e680671 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/NoCallDecode.lean @@ -0,0 +1,25 @@ +import Contracts.UniswapV2.ERC20.NoCall + +/-! +# What UniswapV2ERC20's runtime decode holds that `callFree` refuses + +A STATICCALL (`runtime_has_staticcall`) and no other message-sending instruction (`runtime_only_staticcall`: +no CALL, CALLCODE, DELEGATECALL, CREATE or CREATE2), at the counters `refusedAt_eq` lists: the +STATICCALL at 903 and RETURNDATASIZE, RETURNDATACOPY, RETURNDATASIZE at 1158, 1161, 1162. These +counters are of solar 38b5232's output (Runtime.lean's header has its digest): bytes from another +compiler fail this theorem by evaluation, not silently. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.NoCall + +open SolidCore.Refinement.Solar.AssembleNoCall SolidCore.Refinement.Solar.Assemble +open SolarTV.Assembly + +theorem runtime_has_staticcall : (decoded code).any (fun x => x.2 == .op 0xfa) = true := by + decide +kernel + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.NoCall.runtime_has_staticcall' depends on axioms: [propext] -/ +#guard_msgs (whitespace := lax) in +#print axioms runtime_has_staticcall + +end SolidCore.Spec.UniswapV2.ERC20.NoCall diff --git a/Contracts/UniswapV2/ERC20/NoCallFa.lean b/Contracts/UniswapV2/ERC20/NoCallFa.lean new file mode 100644 index 00000000..3cee9b22 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/NoCallFa.lean @@ -0,0 +1,18 @@ +import Contracts.UniswapV2.ERC20.NoCall + +/-! +# UniswapV2ERC20's runtime has a 0xfa byte, so `AssembleNoCall.calleesRun_of_noFaByte` does not apply. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.NoCall + +open SolidCore.Refinement.Solar.AssembleNoCall SolidCore.Refinement.Solar.Assemble +open SolarTV.Assembly + +theorem runtime_not_noFaByte : noFaByte code = false := by decide +kernel + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.NoCall.runtime_not_noFaByte' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms runtime_not_noFaByte + +end SolidCore.Spec.UniswapV2.ERC20.NoCall diff --git a/Contracts/UniswapV2/ERC20/NoCallNeg.lean b/Contracts/UniswapV2/ERC20/NoCallNeg.lean new file mode 100644 index 00000000..669940d7 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/NoCallNeg.lean @@ -0,0 +1,21 @@ +import Contracts.UniswapV2.ERC20.NoCallControl + +/-! +# Negative control of the scrubbed bytes + +Scrubbing the three return-data reads but leaving permit's STATICCALL at 903 fails the call-free +check: the STATICCALL alone is enough for the refusal. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.NoCall + +open SolidCore.Refinement.Solar.AssembleNoCall + +theorem staticcall_kept_not_callFree : callFree (scrubWith [1158, 1161, 1162] code) = false := by + decide +kernel + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.NoCall.staticcall_kept_not_callFree' depends on axioms: [propext] -/ +#guard_msgs (whitespace := lax) in +#print axioms staticcall_kept_not_callFree + +end SolidCore.Spec.UniswapV2.ERC20.NoCall diff --git a/Contracts/UniswapV2/ERC20/NoCallOnly.lean b/Contracts/UniswapV2/ERC20/NoCallOnly.lean new file mode 100644 index 00000000..6ff74e1e --- /dev/null +++ b/Contracts/UniswapV2/ERC20/NoCallOnly.lean @@ -0,0 +1,20 @@ +import Contracts.UniswapV2.ERC20.NoCall + +/-! +# UniswapV2ERC20's runtime sends no message other than by STATICCALL +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.NoCall + +open SolidCore.Refinement.Solar.AssembleNoCall SolidCore.Refinement.Solar.Assemble +open SolarTV.Assembly + +theorem runtime_only_staticcall : + (decoded code).all (fun x => !([0xf0, 0xf1, 0xf2, 0xf4, 0xf5].map SolarTV.Assembly.Instr.op).contains x.2) = true := by + decide +kernel + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.NoCall.runtime_only_staticcall' depends on axioms: [propext] -/ +#guard_msgs (whitespace := lax) in +#print axioms runtime_only_staticcall + +end SolidCore.Spec.UniswapV2.ERC20.NoCall diff --git a/Contracts/UniswapV2/ERC20/Slice/All.lean b/Contracts/UniswapV2/ERC20/Slice/All.lean new file mode 100644 index 00000000..e5e3964d --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Slice/All.lean @@ -0,0 +1,165 @@ +import Contracts.UniswapV2.ERC20.Slice.BundleNeg +import Contracts.UniswapV2.ERC20.Slice.MutantsDebit + +/-! +# UniswapV2ERC20.transfer's certified slice (E7): every module, and the axioms of its theorems + +Each theorem below depends on `propext`, `Classical.choice` and `Quot.sound` at most: no `sorryAx`, no +other axiom (the kernel checks `Gen.transfer_erase_eq`, `Gen.deploy_eq` and `tree_eq` are `kernel_rfl` equations). +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Slice + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.targetPost_of_seq' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms targetPost_of_seq + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.tree_seq' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms tree_seq + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.res_ok' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms res_ok + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.res_sub' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms res_sub + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.res_add' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms res_add + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.tree_eq' depends on axioms: [propext] -/ +#guard_msgs (whitespace := lax) in +#print axioms tree_eq + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.transfer_meets' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms transfer_meets + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.sepArgs_iff' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms sepArgs_iff + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.run_tree' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms run_tree + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.meets_seq' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms meets_seq + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.meets_target' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms meets_target + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.transfer_holds' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms transfer_holds + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.meets_bundle' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms meets_bundle + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.valid_inhabited' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms valid_inhabited + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.nonVacuous_seq' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms nonVacuous_seq + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.nonVacuous_target' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms nonVacuous_target + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.self_ok' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms self_ok + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.self_fail' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms self_fail + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.self_max' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms self_max + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.self_short' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms self_short + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.meets_bytes' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms meets_bytes + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.meets_bytes_enough' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms meets_bytes_enough + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.terminates' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms terminates + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.functional_of_equiv' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms functional_of_equiv + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.certified_of' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms certified_of + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.bytes_target' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytes_target + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.bytes_seq' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytes_seq + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.bytes_bundle' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytes_bundle + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.bytes_target_enough' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytes_target_enough + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.inert_not_target' depends on axioms: [propext] -/ +#guard_msgs (whitespace := lax) in +#print axioms inert_not_target + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants.log_refuted_seq' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms Mutants.log_refuted_seq + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants.log_refuted_target' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms Mutants.log_refuted_target + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants.ret_refuted_seq' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms Mutants.ret_refuted_seq + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants.ret_refuted_target' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms Mutants.ret_refuted_target + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants.ret_refuted_bundle' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms Mutants.ret_refuted_bundle + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants.nonVacuous_bundle' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms Mutants.nonVacuous_bundle + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants.debit_refuted_seq' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms Mutants.debit_refuted_seq + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants.debit_refuted_target' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms Mutants.debit_refuted_target + +end SolidCore.Spec.UniswapV2.ERC20.Slice diff --git a/Contracts/UniswapV2/ERC20/Slice/BundleNeg.lean b/Contracts/UniswapV2/ERC20/Slice/BundleNeg.lean new file mode 100644 index 00000000..96626a73 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Slice/BundleNeg.lean @@ -0,0 +1,61 @@ +import Contracts.UniswapV2.ERC20.Slice.Mutants + +/-! +# UniswapV2ERC20.transfer: the exported spec is not vacuous + +solar-verify's exported spec (as `bundlePost`) rejects the return mutant's run of `call0` (success, +returning `false`): its `ensures` `returns true` fails. So the spec the unmutated contract meets on +every valid call (`meets_bundle`) rejects an observable a compiled program actually produces +(`nonVacuous_bundle`, `ret_refuted_bundle`). +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Spec SolidCore.Refinement.Shapes +open SolidCore.Spec.UniswapV2.ERC20.Slice SolidCore.Spec.UniswapV2.ERC20.Slice.Gen + +/-- The state before `call0`. -/ +def pre0 : State := ⟨slotValue σ0, Ghost.zero, 0⟩ + +theorem decodes0 : Decodes transfer_spec call0 [1, 0] := by + refine ⟨by decide +kernel, by decide +kernel, ?_⟩ + rw [show call0.calldata = Abi.calldata transferSel [1, 0] from rfl, words_calldata _ (by simp)] + decide +kernel + +theorem pre_call0 : Pre spec transfer_spec (ctxOf call0) pre0 call0 [1, 0] := + ⟨decodes0, rfl, by decide, by simp [Bundle.satAll, transfer_spec, Gen.spec, + SolidCore.Spec.Export.UniswapV2ERC20Slice.UniswapV2ERC20], + by simp [Bundle.satAll, Gen.spec, SolidCore.Spec.Export.UniswapV2ERC20Slice.UniswapV2ERC20]⟩ + +/-- **The exported spec rejects a success returning `false`** on `call0`. -/ +theorem bundle_rejects_false {obs : Observable} (h1 : obs.success = true) (h2 : obs.output = be32 0) : + ¬ bundlePost spec ctxOf idStep call0 obs := by + intro hb + have hp := hb transfer_spec (by rw [specs_eq]; exact List.mem_singleton_self _) [1, 0] pre0 pre_call0 + obtain ⟨rets, hdec, hens, -⟩ := hp.1 h1 + rw [h2, show words (be32 0) = [0] by decide +kernel] at hdec + have hr : rets = [0] := by + simp [transfer_spec, Gen.spec, SolidCore.Spec.Export.UniswapV2ERC20Slice.UniswapV2ERC20, decodeWords, + Ty.ofWord] at hdec + exact hdec.symm + subst hr + have := hens (.ret 0) (by simp [transfer_spec, Gen.spec, SolidCore.Spec.Export.UniswapV2ERC20Slice.UniswapV2ERC20]) + simp [Bundle.sat, eval, mkEnv, Env.cur, Env.bind] at this + +/-- **The exported spec is not vacuous** on the valid calls with their premise. -/ +theorem nonVacuous_bundle : ∃ call obs, ValidIn call ∧ ¬ bundlePost spec ctxOf idStep call obs := + ⟨call0, ⟨true, be32 0, [], slotValue σ0⟩, valid_call0, bundle_rejects_false rfl rfl⟩ + +/-- **The return mutant fails the exported spec**, by its run on `call0`. -/ +theorem ret_refuted_bundle {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20MutRet.contract? = .ok c) : + ¬ Meets (solidCore fuel) c (fun call => Valid Gen.MutRet.deployed call ∧ Scope call) + (bundlePost spec ctxOf idStep) := fun h => + bundle_rejects_false ret_result.1 ret_result.2 + (h call0 ⟨valid0 _ coversRet, scope_call0⟩ _ (runRet hc)) + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants.ret_refuted_bundle' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms ret_refuted_bundle + +end SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants diff --git a/Contracts/UniswapV2/ERC20/Slice/Bytes.lean b/Contracts/UniswapV2/ERC20/Slice/Bytes.lean new file mode 100644 index 00000000..6403d456 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Slice/Bytes.lean @@ -0,0 +1,120 @@ +import Contracts.UniswapV2.ERC20.Slice.Statement + +/-! +# UniswapV2ERC20.transfer: the specification carried to the bytes through `Equiv` + +E7 of docs/CERTIFICATION_TARGET.md: the slice's specification, proved of SolidCore's runs +(Statement.lean), transferred to the exact runtime bytes by the behavioural equivalence +`Shapes.Equiv` the backend stages and the byte binding deliver (E4 to E6, other lanes). Nothing +here assumes anything of the bytes beyond the hypotheses named in each statement. + +* `meets_bytes` (any source, any spec): `Equiv` and `Meets` give, at every gas below `2 ^ 256`, + every result of the bytes on a valid call meeting the spec, or an inert failure (`Inert`: no + change, no log; running out of gas is one, so no more can be said without a gas bound); +* `meets_bytes_enough`: with `Resources` (E8) as well, every result of the bytes from the gas bound + on meets the spec exactly; +* for the slice: `terminates` (SolidCore halts on every valid call, succeeding or reverting with + one of SafeMath's two errors, `Allowed`), and `functional_of_equiv`, `certified_of`: given + `Equiv` (and `Resources`) for some bytes `code` on `ValidIn`, the target's `Functional` + (`Certified`) statement with `TargetPost`; `bytes_target`, `bytes_seq`, `bytes_bundle`: the + three specifications on the bytes, each with its `Inert` alternative. + +The binding of `code` to the bytes solar emits for the pinned port, and `Equiv` itself, are not +proved here: they are the named premises `heq` (E4 to E6) and `hres` (E8). +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Slice + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Spec SolidCore.Refinement.Shapes +open SolidCore.Spec.UniswapV2.ERC20.Slice.Gen + +/-! ## The transfer lemma -/ + +/-- **`Meets` from the source to the bytes through `Equiv`.** -/ +theorem meets_bytes {S : Sem} {p : S.Prog} {code : ByteArray} {V : Call → Prop} + {P : Call → Observable → Prop} (heq : Equiv S p code V) (hm : Meets S p V P) (gas : Nat) + (hg : gas < 2 ^ 256) (call : Call) (hc : V call) (obs : Observable) + (hrun : Final.Target.runWith gas code call = some obs) : P call obs ∨ Inert call obs := + (heq gas hg call hc obs hrun).imp (hm call hc obs) id + +/-- **With a gas bound, exactly**: from `G call` gas on, every result of the bytes meets `P`. -/ +theorem meets_bytes_enough {S : Sem} {p : S.Prog} {code : ByteArray} {V : Call → Prop} + {P : Call → Observable → Prop} {G : Call → Nat} (hres : Resources S p code V G) (hm : Meets S p V P) + (call : Call) (hc : V call) (gas : Nat) (h1 : G call ≤ gas) (h2 : gas < 2 ^ 256) (obs : Observable) + (hrun : Final.Target.runWith gas code call = some obs) : P call obs := by + rw [(hres call hc).2 gas h1 h2] at hrun + exact hm call hc obs hrun + +/-- A specification no bytes can meet vacuously by an inert failure: `TargetPost` asks a revert for +SafeMath's revert data, so an inert result with other output does not meet it. -/ +theorem inert_not_target : ¬ TargetPost call0 ⟨false, [], [], slotValue σ0⟩ := by + intro h + have := ((h σ0 1 0 rfl (by decide) (by decide)).2.2.2 rfl).2.2 + simp [errorData] at this + +/-! ## The slice -/ + +/-- The statuses `transfer` may end with: success, or a revert with one of SafeMath's errors. -/ +def Allowed (_call : Call) (obs : Observable) : Prop := + obs.success = true ∨ obs.output = errorData subMsg ∨ obs.output = errorData addMsg + +/-- **SolidCore halts on every valid call**, with an allowed status. -/ +theorem terminates {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Terminates (solidCore fuel) c ValidIn Allowed := by + rintro _ ⟨⟨σ, dst, v, hcov, hto, hv, rfl⟩, -⟩ + refine ⟨_, run_tree hc hcov hto hv, ?_⟩ + have hs := fun k => Generic.slotValue_lt σ k + by_cases hle : v ≤ slotValue σ (balKey caller) + · by_cases hov : debit (slotValue σ) v (balKey dst) + v < 2 ^ 256 + · rw [res_ok hs hto hv hle hov]; exact Or.inl rfl + · rw [res_add hs hto hv hle hov]; exact Or.inr (Or.inr rfl) + · rw [res_sub hs hto hv hle]; exact Or.inr (Or.inl rfl) + +/-- **The slice's functional statement, given `Equiv`** for bytes `code` on the valid calls. -/ +theorem functional_of_equiv {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) {code : ByteArray} + (heq : Equiv (solidCore fuel) c code ValidIn) : + Functional (solidCore fuel) c code ValidIn Allowed TargetPost := + ⟨valid_inhabited, heq, terminates hc, meets_target hc⟩ + +/-- **The slice's certified statement, given `Equiv` and `Resources`.** -/ +theorem certified_of {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) {code : ByteArray} {G : Call → Nat} + (heq : Equiv (solidCore fuel) c code ValidIn) (hres : Resources (solidCore fuel) c code ValidIn G) : + Certified (solidCore fuel) c code ValidIn Allowed TargetPost G := + ⟨valid_inhabited, heq, terminates hc, meets_target hc, hres⟩ + +/-- **`TargetPost` on the bytes**, at every gas, or an inert failure. -/ +theorem bytes_target {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) {code : ByteArray} + (heq : Equiv (solidCore fuel) c code ValidIn) (gas : Nat) (hg : gas < 2 ^ 256) (call : Call) + (hv : ValidIn call) (obs : Observable) (hrun : Final.Target.runWith gas code call = some obs) : + TargetPost call obs ∨ Inert call obs := + meets_bytes heq (meets_target hc) gas hg call hv obs hrun + +/-- **`SeqPost` on the bytes**: no hash premise on the calls, only in `Equiv`'s. -/ +theorem bytes_seq {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) {code : ByteArray} + (heq : Equiv (solidCore fuel) c code (Valid deployed)) (gas : Nat) (hg : gas < 2 ^ 256) (call : Call) + (hv : Valid deployed call) (obs : Observable) (hrun : Final.Target.runWith gas code call = some obs) : + SeqPost call obs ∨ Inert call obs := + meets_bytes heq (meets_seq hc) gas hg call hv obs hrun + +/-- **solar-verify's exported spec on the bytes.** -/ +theorem bytes_bundle {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) {code : ByteArray} + (heq : Equiv (solidCore fuel) c code ValidIn) (gas : Nat) (hg : gas < 2 ^ 256) (call : Call) + (hv : ValidIn call) (obs : Observable) (hrun : Final.Target.runWith gas code call = some obs) : + bundlePost spec ctxOf idStep call obs ∨ Inert call obs := + meets_bytes heq (meets_bundle hc) gas hg call hv obs hrun + +/-- **With `Resources`, `TargetPost` of the bytes exactly** from the gas bound on. -/ +theorem bytes_target_enough {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) {code : ByteArray} {G : Call → Nat} + (hres : Resources (solidCore fuel) c code ValidIn G) (call : Call) (hv : ValidIn call) (gas : Nat) + (h1 : G call ≤ gas) (h2 : gas < 2 ^ 256) (obs : Observable) + (hrun : Final.Target.runWith gas code call = some obs) : TargetPost call obs := + meets_bytes_enough hres (meets_target hc) call hv gas h1 h2 obs hrun + +end SolidCore.Spec.UniswapV2.ERC20.Slice diff --git a/Contracts/UniswapV2/ERC20/Slice/Mutants.lean b/Contracts/UniswapV2/ERC20/Slice/Mutants.lean new file mode 100644 index 00000000..2cc848c9 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Slice/Mutants.lean @@ -0,0 +1,141 @@ +import Contracts.UniswapV2.ERC20.Slice.Bytes +import Contracts.UniswapV2.ERC20.Slice.Gen.MutLog.Tree +import Contracts.UniswapV2.ERC20.Slice.Gen.MutRet.Tree + +/-! +# UniswapV2ERC20.transfer: semantic mutants of the port, refused by execution + +Each mutant is one text edit of the pinned port (scripts/verify/uniswap-v2/transfer-mutants.txt), +compiled by the same frontend and checked by the kernel (`Gen/Mut/Core.lean`, `contract_ok`), +its `transfer` erased by the same generic source stage (`Gen/Mut/Tree.lean`, +`transfer_erase_eq`, `deploy_eq`). The refutations run SolidCore's checked mutant on one valid call +(`run`, `source_run`) and evaluate the result: no formula is checked on a hand-written state. + +* `Log` (`emit Transfer(to, from, value)`): `transfer(1, 0)` from `σ0` succeeds with the log's + addresses swapped; `SeqPost` and `TargetPost` refuse it (`log_refuted_seq`, + `log_refuted_target`). solar-verify's exported spec says nothing of logs, so it does not. +* `Ret` (`return false`): the same call returns `false`; refused by `SeqPost`, `TargetPost` and + the exported spec (`returns true`; `ret_refuted_bundle`). +* `Debit` (`balanceOf[from] = balanceOf[from].sub(value).add(value)`: the debit undone): + `transfer(1, 2)` from a balance of 5 succeeds and leaves it at 5; `TargetPost` and `SeqPost` + refuse it (`debit_refuted_target`, `debit_refuted_seq`, MutantsDebit.lean). + +The unmutated contract meets all three on the same call (`meets_seq`, `meets_target`, +`meets_bundle`), so each refusal is the mutation's. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Spec SolidCore.Refinement.Shapes +open SolidCore.Spec.UniswapV2.ERC20.Slice + +theorem slotValue_σ0 : slotValue σ0 = fun _ => 0 := by + funext n; simp [slotValue, σ0] + +theorem valid0 (s : List (Nat × Nat)) (hs : Generic.Covers s σ0) : Valid s call0 := + ⟨σ0, 1, 0, hs, by decide, by decide, rfl⟩ + +/-- \`σ0\` writes every slot of a constructor storage that writes only slot 3. -/ +theorem covers_3 {s : List (Nat × Nat)} (h : ∀ kv ∈ s, kv.1 = 3) : Generic.Covers s σ0 := by + intro kv hkv + exact ⟨(3, 0), by simp [σ0], by rw [h kv hkv]⟩ + +theorem coversLog : Generic.Covers Gen.MutLog.deployed σ0 := covers_3 (by simp [Gen.MutLog.deployed]) +theorem coversRet : Generic.Covers Gen.MutRet.deployed σ0 := covers_3 (by simp [Gen.MutRet.deployed]) + +/-! ## Log -/ + +section Log +open SolidCore.Spec.UniswapV2.ERC20.Slice.Gen.MutLog in +/-- SolidCore's run of `call0` on the mutant is its erased tree's result. -/ +theorem runLog {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20MutLog.contract? = .ok c) : + (solidCore fuel).run c call0 = some (transfer_tree.eval ⟨[1, 0], slotValue σ0, solHash, SolidCore.Refinement.Generic.callerWord⟩).obs := by + have hdep := deploy_eq + simp only [deploy?, hc] at hdep + obtain ⟨d, hd⟩ := Wide.deployedAt_of hdep + have hmap := transfer_erase_eq + simp only [transfer_erase?, hc, Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + exact source_run hd covers_σ0 (by decide) hf hT [1, 0] (by simp [hlen]) (by simp) +end Log + +/-! ## Ret -/ + +section Ret +open SolidCore.Spec.UniswapV2.ERC20.Slice.Gen.MutRet in +/-- SolidCore's run of `call0` on the mutant is its erased tree's result. -/ +theorem runRet {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20MutRet.contract? = .ok c) : + (solidCore fuel).run c call0 = some (transfer_tree.eval ⟨[1, 0], slotValue σ0, solHash, SolidCore.Refinement.Generic.callerWord⟩).obs := by + have hdep := deploy_eq + simp only [deploy?, hc] at hdep + obtain ⟨d, hd⟩ := Wide.deployedAt_of hdep + have hmap := transfer_erase_eq + simp only [transfer_erase?, hc, Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + exact source_run hd covers_σ0 (by decide) hf hT [1, 0] (by simp [hlen]) (by simp) +end Ret + +/-- The log mutant's result on `call0`: success, with `Transfer(1, caller, 0)`. -/ +theorem log_result : + (Gen.MutLog.transfer_tree.eval ⟨[1, 0], slotValue σ0, solHash, SolidCore.Refinement.Generic.callerWord⟩).obs.success = true ∧ + (Gen.MutLog.transfer_tree.eval ⟨[1, 0], slotValue σ0, solHash, SolidCore.Refinement.Generic.callerWord⟩).obs.logs ≠ [transferLog caller 1 0] := by + simp only [Res.obs, slotValue_σ0] + generalize solHash = H + simp [Gen.MutLog.transfer_tree, Tree.eval, WExpr.eval, BinOp.eval, UnOp.eval, Log.eval, transferLog, + caller, Generic.callerWord, Generic.wordSize] + +/-- The return mutant's result on `call0`: success, returning `false`. -/ +theorem ret_result : + (Gen.MutRet.transfer_tree.eval ⟨[1, 0], slotValue σ0, solHash, SolidCore.Refinement.Generic.callerWord⟩).obs.success = true ∧ + (Gen.MutRet.transfer_tree.eval ⟨[1, 0], slotValue σ0, solHash, SolidCore.Refinement.Generic.callerWord⟩).obs.output = be32 0 := by + simp only [Res.obs, slotValue_σ0] + generalize solHash = H + simp [Gen.MutRet.transfer_tree, Tree.eval, WExpr.eval, BinOp.eval, UnOp.eval, OByte.eval, be32, + Generic.wordSize] + +theorem be32_ne : be32 0 ≠ be32 1 := by decide + +/-- **The log mutant fails `SeqPost`**, by its run on `call0`. -/ +theorem log_refuted_seq {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20MutLog.contract? = .ok c) : + ¬ Meets (solidCore fuel) c (Valid Gen.MutLog.deployed) SeqPost := by + intro h + have hp := h call0 (valid0 _ coversLog) _ (runLog hc) σ0 1 0 rfl (by decide) (by decide) + exact log_result.2 (hp.2.1 log_result.1).2.1 + +/-- **The log mutant fails `TargetPost`** on a call whose footprint premise holds. -/ +theorem log_refuted_target {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20MutLog.contract? = .ok c) : + ¬ Meets (solidCore fuel) c (fun call => Valid Gen.MutLog.deployed call ∧ Scope call) TargetPost := by + intro h + have hp := h call0 ⟨valid0 _ coversLog, scope_call0⟩ _ (runLog hc) σ0 1 0 rfl (by decide) (by decide) + exact log_result.2 (hp.2.2.1 log_result.1).1 + +/-- **The return mutant fails `SeqPost`.** -/ +theorem ret_refuted_seq {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20MutRet.contract? = .ok c) : + ¬ Meets (solidCore fuel) c (Valid Gen.MutRet.deployed) SeqPost := by + intro h + have hp := h call0 (valid0 _ coversRet) _ (runRet hc) σ0 1 0 rfl (by decide) (by decide) + exact be32_ne (ret_result.2.symm.trans (hp.2.1 ret_result.1).2.2) + +/-- **The return mutant fails `TargetPost`.** -/ +theorem ret_refuted_target {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20MutRet.contract? = .ok c) : + ¬ Meets (solidCore fuel) c (fun call => Valid Gen.MutRet.deployed call ∧ Scope call) TargetPost := by + intro h + have hp := h call0 ⟨valid0 _ coversRet, scope_call0⟩ _ (runRet hc) σ0 1 0 rfl (by decide) (by decide) + exact be32_ne (ret_result.2.symm.trans (hp.2.2.1 ret_result.1).2.1) + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants.log_refuted_target' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms log_refuted_target + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants.ret_refuted_target' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms ret_refuted_target + + +end SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants diff --git a/Contracts/UniswapV2/ERC20/Slice/MutantsDebit.lean b/Contracts/UniswapV2/ERC20/Slice/MutantsDebit.lean new file mode 100644 index 00000000..ed5d26a6 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Slice/MutantsDebit.lean @@ -0,0 +1,170 @@ +import Contracts.UniswapV2.ERC20.Slice.Bytes +import Contracts.UniswapV2.ERC20.Slice.Gen.MutDebit.Tree + +/-! +# UniswapV2ERC20.transfer: the missing-debit mutant, refused by execution + +See Mutants.lean. The mutant undoes the debit (`balanceOf[from] = balanceOf[from].sub(value).add(value)`): +`transfer(1, 2)` from a caller balance of 5 succeeds and leaves it at 5, where `TargetPost` asks 3. Its +own module, so that each module checks within 6 GB. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Spec SolidCore.Refinement.Shapes +open SolidCore.Spec.UniswapV2.ERC20.Slice + +/-! ## Debit -/ + +section Debit +open SolidCore.Spec.UniswapV2.ERC20.Slice.Gen.MutDebit in +/-- SolidCore's run of a valid call on the debit mutant is its erased tree's result. -/ +theorem runDebit {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20MutDebit.contract? = .ok c) {σ : List (Nat × Nat)} {dst v : Nat} + (hcov : Generic.Covers deployed σ) (hto : dst < 2 ^ 160) (hv : v < 2 ^ 256) : + (solidCore fuel).run c (transferCall σ dst v) = + some (transfer_tree.eval ⟨[dst, v], slotValue σ, solHash, SolidCore.Refinement.Generic.callerWord⟩).obs := by + have hdep := deploy_eq + simp only [deploy?, hc] at hdep + obtain ⟨d, hd⟩ := Wide.deployedAt_of hdep + have hmap := transfer_erase_eq + simp only [transfer_erase?, hc, Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + exact source_run hd hcov (by decide) hf hT [dst, v] (by simp [hlen]) (by simp; omega) +end Debit + +/-! ## The debit mutant's tree, by parts -/ + +section DebitParts +set_option simprocs false + +/-- The debited balance credited back: the mutant's caller slot. -/ +abbrev eAddBack : WExpr := .bin .add eSub (.arg 1) +/-- The recipient's balance in the mutant's state after its caller write. -/ +abbrev eSelD : WExpr := .sel (.bin .eq hT hC) eAddBack (.sinit hT) +/-- The mutant's credited balance. -/ +abbrev eAddD : WExpr := .bin .add eSelD (.arg 1) +/-- SafeMath's `add` test of the credit-back. -/ +abbrev c3d : WExpr := .un .iszero (.bin .lt eAddBack eSub) +/-- SafeMath's `add` test of the credit. -/ +abbrev c4d : WExpr := .un .iszero (.bin .lt eAddD eSelD) + +/-- The mutant's success leaf. -/ +def okD : Tree := + .halt true (wordOBytes (.lit 1)) [(hT, eAddD), (hC, eAddBack)] + [{ topics := [.lit transferTopic, .lit 8192, .arg 0], data := wordOBytes (.arg 1) }] + +-- The mutant's erased tree, by parts: the kernel's conversion check. +kernel_rfl dtree_eq Gen.MutDebit.transfer_tree + (.ite c1 (.halt false [] [] []) + (.ite c2 (.ite c3d (.ite c4d okD (.halt false (errBytes addMsg) [] [])) (.halt false (errBytes addMsg) [] [])) + (.halt false (errBytes subMsg) [] []))) + +variable {s : Nat → Nat} {dst v : Nat} (hs : ∀ k, s k < 2 ^ 256) (hto : dst < 2 ^ 160) (hv : v < 2 ^ 256) +include hs hto hv + +theorem ev_addBack (hle : v ≤ s (balKey caller)) : eAddBack.eval (val s dst v) = s (balKey caller) := by + simp only [eAddBack, eval_bin, ev_sub hs hto hv, ev_arg1 hv, BinOp.eval, wsub_of_le (hs _) hle, + Generic.wordSize, Nat.mod_mod, Nat.sub_add_cancel hle] + exact Nat.mod_eq_of_lt (hs _) + +theorem ev_c3d (hle : v ≤ s (balKey caller)) : c3d.eval (val s dst v) = 1 := by + simp only [c3d, WExpr.eval.eq_4, eval_bin, ev_addBack hs hto hv hle, ev_sub hs hto hv, + wsub_of_le (hs _) hle, BinOp.eval, UnOp.eval, ite01_modW, Generic.wordSize] + split_ifs <;> omega + +theorem ev_selD (hne : balKey dst ≠ balKey caller) : eSelD.eval (val s dst v) = s (balKey dst) := by + simp only [eSelD, WExpr.eval.eq_7, eval_bin, ev_hT hto, ev_hC, BinOp.eval, ite01_modW, Generic.wordSize, + if_neg hne, ev_b hs hto hv, eq_self_iff_true, if_true] + +theorem ev_c4d (hne : balKey dst ≠ balKey caller) (hov : s (balKey dst) + v < 2 ^ 256) : + c4d.eval (val s dst v) = 1 := by + simp only [c4d, eAddD, WExpr.eval.eq_4, eval_bin, ev_selD hs hto hv hne, ev_arg1 hv, BinOp.eval, UnOp.eval, + ite01_modW, Generic.wordSize, Nat.mod_mod, Nat.mod_eq_of_lt hov] + split_ifs <;> omega + +/-- **The debit mutant on a call that the source accepts, with distinct slots**: success, and the +caller's slot keeps its balance. -/ +theorem debit_eval (hle : v ≤ s (balKey caller)) (hne : balKey dst ≠ balKey caller) + (hov : s (balKey dst) + v < 2 ^ 256) : + (Gen.MutDebit.transfer_tree.eval (val s dst v)).success = true ∧ + (Gen.MutDebit.transfer_tree.eval (val s dst v)).store (balKey caller) = s (balKey caller) := by + have e2 : c2.eval (val s dst v) = 1 := by rw [ev_c2 hs hto hv, if_pos hle] + rw [dtree_eq] + simp only [Tree.eval, ev_c1 hs hto hv, e2, ev_c3d hs hto hv hle, ev_c4d hs hto hv hne hov, if_pos, + one_ne_zero, if_false, okD, if_true, eq_self_iff_true, true_and] + simp only [Writes.store, Generic.wordSize, ev_hT hto, ev_hC, balKey_mod, if_neg hne, if_true, + eq_self_iff_true, ev_addBack hs hto hv hle] + +end DebitParts + +/-- The caller holds 5, every other slot 0. -/ +def σd : List (Nat × Nat) := [(3, 0), (balKey caller, 5)] + +theorem coversDebit : Generic.Covers Gen.MutDebit.deployed σd := by + intro kv hkv + simp only [Gen.MutDebit.deployed, List.mem_singleton] at hkv + subst hkv + exact ⟨(3, 0), by simp [σd], rfl⟩ + +/-- The caller's and address 1's `balanceOf` slots differ (the real keccak256, by the kernel). -/ +theorem slots_ne : solHash 1 1 ≠ solHash 8192 1 := fun h => + (transfer_slots scopedSep_transfer_example (by decide) (by decide) (by decide)).1 (by decide) h.symm + +theorem obs_success (R : Res) (h : R.success = true) : R.obs.success = true := h + +theorem obs_storage (R : Res) (k : Nat) {n : Nat} (h : R.store k = n) : R.obs.storage k = n := h + +set_option simprocs false in +/-- The debit mutant's result on `transfer(1, 2)` from `σd`: success, with the caller's balance +still 5. -/ +theorem debit_result : + (Gen.MutDebit.transfer_tree.eval ⟨[1, 2], slotValue σd, solHash, SolidCore.Refinement.Generic.callerWord⟩).obs.success = true ∧ + (Gen.MutDebit.transfer_tree.eval ⟨[1, 2], slotValue σd, solHash, SolidCore.Refinement.Generic.callerWord⟩).obs.storage (balKey caller) = 5 := by + have hs : ∀ k, slotValue σd k < 2 ^ 256 := fun k => Generic.slotValue_lt σd k + have hne : balKey 1 ≠ balKey caller := by + rw [show balKey caller = solHash 8192 1 by simp only [balKey, caller, Generic.callerWord]] + exact slots_ne + have ha : slotValue σd (balKey caller) = 5 := by rw [σd, slotValue_last]; decide + have hb : slotValue σd (balKey 1) = 0 := by + have h : ¬ (balKey caller % 2 ^ 256 = balKey 1 % 2 ^ 256) := by + rw [balKey_mod, balKey_mod]; exact Ne.symm hne + simp only [slotValue, σd, List.foldl_cons, List.foldl_nil, if_neg h, Nat.zero_mod, ite_self] + have h := debit_eval (s := slotValue σd) (dst := 1) (v := 2) hs (by norm_num) (by norm_num) + (by rw [ha]; norm_num) hne (by rw [hb]; norm_num) + have e1 : (⟨[1, 2], slotValue σd, solHash, SolidCore.Refinement.Generic.callerWord⟩ : Val) = val (slotValue σd) 1 2 := rfl + rw [← e1] at h + exact ⟨obs_success _ h.1, obs_storage _ _ (h.2.trans ha)⟩ + +theorem validDebit : Valid Gen.MutDebit.deployed (transferCall σd 1 2) := + ⟨σd, 1, 2, coversDebit, by decide, by decide, rfl⟩ + +theorem scopeDebit : Scope (transferCall σd 1 2) := by + intro σ dst v h hto hv + obtain ⟨-, rfl, -⟩ := transferCall_inj (by decide) (by decide) (by omega) hv h + exact scopedSep_transfer_example + +/-- **The debit mutant fails `TargetPost`**: `transfer(1, 2)` from a balance of 5 succeeds and +leaves the caller's balance at 5, not 3. -/ +theorem debit_refuted_target {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20MutDebit.contract? = .ok c) : + ¬ Meets (solidCore fuel) c (fun call => Valid Gen.MutDebit.deployed call ∧ Scope call) TargetPost := by + intro h + have hp := h _ ⟨validDebit, scopeDebit⟩ _ (runDebit hc coversDebit (by decide) (by decide)) + σd 1 2 rfl (by decide) (by decide) + have hb : slotValue σd (balKey caller) = 5 := by rw [σd, slotValue_last]; decide + have := ((hp.1 (by decide)).2 debit_result.1).1 + rw [debit_result.2, hb] at this + omega + +/-- **The debit mutant fails `SeqPost`** (through `targetPost_of_seq`). -/ +theorem debit_refuted_seq {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20MutDebit.contract? = .ok c) : + ¬ Meets (solidCore fuel) c (Valid Gen.MutDebit.deployed) SeqPost := fun h => + debit_refuted_target hc fun call hv obs hrun => targetPost_of_seq (h call hv.1 obs hrun) hv.2 + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants.debit_refuted_target' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms debit_refuted_target + +end SolidCore.Spec.UniswapV2.ERC20.Slice.Mutants diff --git a/Contracts/UniswapV2/ERC20/Slice/Post.lean b/Contracts/UniswapV2/ERC20/Slice/Post.lean new file mode 100644 index 00000000..ff28b2ec --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Slice/Post.lean @@ -0,0 +1,192 @@ +import Verify.Shapes +import Verify.Spec.HashScope + +/-! +# UniswapV2ERC20.transfer: the slice's valid calls and postcondition over the observable + +The first certified slice of docs/CERTIFICATION_TARGET.md, `transfer(address,uint256)` of the +pinned 0.8 port's `UniswapV2ERC20`, stated over `SolarTV.Call` and `SolarTV.Observable`, the +interface both SolidCore and EthLib run on. Nothing here depends on the port's code. + +* `Valid s`: the selector `transfer(address,uint256)`, well-formed call data (a clean address + `to` and any word `value`), no value, any storage that writes the slots of `s` (the + constructor's storage, as every generic-stage scope asks). The caller is the interface's one + caller, `0x2000` (`Generic.callerWord`): `SolarTV.Call` has no caller field, so "any caller" + is not expressible yet (a missing bridge, named in RESULT.md); `to` ranges over every + address, the caller among them. +* `SeqPost`: what the source does, as sequential storage updates in source order: the debit of + the caller, then the credit of the recipient reading the debited state (`seqStore`). It + succeeds iff the caller's balance covers `value` and the credit does not overflow, logs + `Transfer(caller, to, value)` and returns `true`; otherwise it reverts with the source's + revert data (`Error("ds-math-sub-underflow")` or `Error("ds-math-add-overflow")`), no log and + the storage it started with. It needs no hash premise: it is stated at the slots the source + computes, `solHash k 1`. +* `TargetPost`: the same in the target's words, split on `caller = to`, reading the recipient's + balance in the state before the call, with the frame over the footprint. It follows from + `SeqPost` under `Scope` (`targetPost_of_seq`): keccak256 separated on the call's two balance + preimages only (`ScopedSep (transferFootprint 1 caller to)`, Verify/Spec/HashScope.lean), never + over all keys and with no frame family. +* `Post`: `SeqPost`, and `TargetPost` and solar-verify's exported spec under the call's + `Scope`: the scoped premise is printed in the statement, at the call it is about. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Slice + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Spec + +/-- `balanceOf`'s slot in the port's storage layout. -/ +abbrev balanceSlot : Nat := 1 + +/-- The caller of every call (the interface's one caller). -/ +abbrev caller : Nat := Generic.callerWord + +/-- The slot of `balanceOf[a]`. -/ +abbrev balKey (a : Nat) : Nat := solHash a balanceSlot + +/-- The selector of `transfer(address,uint256)`. -/ +abbrev transferSel : Nat := 0xa9059cbb + +/-- The call `transfer(to, value)` from the storage `σ`, with no value. -/ +def transferCall (σ : List (Nat × Nat)) (dst v : Nat) : Call := + { calldata := Abi.calldata transferSel [dst, v], callvalue := 0, storage := σ } + +/-- **The valid calls**: `transfer(to, value)` on a clean address and any word, no value, from any +storage that writes every slot of `s`. -/ +def Valid (s : List (Nat × Nat)) (call : Call) : Prop := + ∃ σ dst v, Generic.Covers s σ ∧ dst < 2 ^ 160 ∧ v < 2 ^ 256 ∧ call = transferCall σ dst v + +/-- The storage `s` with the slot `k` (a word) set to `x`. -/ +def upd (s : Nat → Nat) (k x : Nat) : Nat → Nat := fun n => if n % 2 ^ 256 = k then x else s n + +/-- The debited state: the caller's balance less `v`. -/ +def debit (s : Nat → Nat) (v : Nat) : Nat → Nat := upd s (balKey caller) (s (balKey caller) - v) + +/-- **The source's storage updates, in order**: the debit of the caller, then the credit of `to` +reading the debited state. -/ +def seqStore (s : Nat → Nat) (dst v : Nat) : Nat → Nat := + upd (debit s v) (balKey dst) (debit s v (balKey dst) + v) + +/-- A word's 32 bytes, big-endian. -/ +def be32 (w : Nat) : List Nat := (List.range 32).map fun i => w / 256 ^ (31 - i) % 256 + +/-- The topic of `Transfer(address,address,uint256)`. -/ +abbrev transferTopic : Nat := + 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef + +/-- The log `Transfer(from, to, value)`: its topics and data. -/ +def transferLog (f t v : Nat) : List Nat × List Nat := ([transferTopic, f, t], be32 v) + +/-- The revert data of `Error(msg)` for a message of at most 32 bytes: the selector, the offset +`0x20`, the length and the message padded to a word. -/ +def errorData (msg : List Nat) : List Nat := + [0x08, 0xc3, 0x79, 0xa0] ++ be32 0x20 ++ be32 msg.length ++ msg ++ + List.replicate (32 - msg.length) 0 + +/-- `"ds-math-sub-underflow"`'s bytes (`subMsg_eq`). -/ +def subMsg : List Nat := + [100, 115, 45, 109, 97, 116, 104, 45, 115, 117, 98, 45, 117, 110, 100, 101, 114, 102, 108, 111, 119] +/-- `"ds-math-add-overflow"`'s bytes (`addMsg_eq`). -/ +def addMsg : List Nat := + [100, 115, 45, 109, 97, 116, 104, 45, 97, 100, 100, 45, 111, 118, 101, 114, 102, 108, 111, 119] + +theorem subMsg_eq : subMsg = "ds-math-sub-underflow".toUTF8.toList.map (·.toNat) := by decide +kernel +theorem addMsg_eq : addMsg = "ds-math-add-overflow".toUTF8.toList.map (·.toNat) := by decide +kernel + +/-- **What the source does** on `transfer(to, v)` from `σ`: see the module comment. -/ +def SeqPost (call : Call) (obs : Observable) : Prop := + ∀ σ dst v, call = transferCall σ dst v → dst < 2 ^ 160 → v < 2 ^ 256 → + (obs.success = true ↔ + (v ≤ slotValue σ (balKey caller) ∧ debit (slotValue σ) v (balKey dst) + v < 2 ^ 256)) ∧ + (obs.success = true → obs.storage = seqStore (slotValue σ) dst v ∧ + obs.logs = [transferLog caller dst v] ∧ obs.output = be32 1) ∧ + (obs.success = false → obs.storage = slotValue σ ∧ obs.logs = [] ∧ + obs.output = errorData (if v ≤ slotValue σ (balKey caller) then addMsg else subMsg)) + +/-- **The scoped premise of a call**: keccak256 separated on its footprint, the preimages of the +caller's and the recipient's `balanceOf` slots, and nothing else. -/ +def Scope (call : Call) : Prop := + ∀ σ dst v, call = transferCall σ dst v → dst < 2 ^ 160 → v < 2 ^ 256 → + ScopedSep (transferFootprint balanceSlot caller dst) + +/-- **The target's postcondition** (docs/CERTIFICATION_TARGET.md, "First slice"): with `s` the +storage before the call, `caller ≠ to` succeeds iff `s[caller] ≥ v` and `s[to] + v < 2 ^ 256`, +then debits and credits; `caller = to` succeeds iff `s[caller] ≥ v` and leaves the storage as it +was; a success logs `Transfer(caller, to, v)`, returns `true` and changes no slot outside the +footprint; a failure reverts with the source's revert data, no log, no change. -/ +def TargetPost (call : Call) (obs : Observable) : Prop := + ∀ σ dst v, call = transferCall σ dst v → dst < 2 ^ 160 → v < 2 ^ 256 → + (caller ≠ dst → + (obs.success = true ↔ + v ≤ slotValue σ (balKey caller) ∧ slotValue σ (balKey dst) + v < 2 ^ 256) ∧ + (obs.success = true → obs.storage (balKey caller) = slotValue σ (balKey caller) - v ∧ + obs.storage (balKey dst) = slotValue σ (balKey dst) + v)) ∧ + (caller = dst → + (obs.success = true ↔ v ≤ slotValue σ (balKey caller)) ∧ + (obs.success = true → obs.storage = slotValue σ)) ∧ + (obs.success = true → obs.logs = [transferLog caller dst v] ∧ obs.output = be32 1 ∧ + ∀ n, n % 2 ^ 256 ≠ balKey caller → n % 2 ^ 256 ≠ balKey dst → obs.storage n = slotValue σ n) ∧ + (obs.success = false → obs.storage = slotValue σ ∧ obs.logs = [] ∧ + obs.output = errorData (if v ≤ slotValue σ (balKey caller) then addMsg else subMsg)) + +theorem balKey_mod (a : Nat) : balKey a % 2 ^ 256 = balKey a := Nat.mod_eq_of_lt (solHash_lt a _) + +theorem balKey_mod' (a : Nat) : + balKey a % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = + balKey a := Nat.mod_eq_of_lt (solHash_lt a _) + +theorem slotValue_mod (σ : List (Nat × Nat)) (n : Nat) : + slotValue σ (n % 2 ^ 256) = slotValue σ n := by + unfold slotValue + simp only [Nat.mod_mod] + +/-- **The target's postcondition from the source's, under the call's scope.** -/ +theorem targetPost_of_seq {call : Call} {obs : Observable} (h : SeqPost call obs) + (hs : Scope call) : TargetPost call obs := by + intro σ dst v hc hto hv + obtain ⟨hsucc, hok, hfail⟩ := h σ dst v hc hto hv + have hsep := hs σ dst v hc hto hv + have hlt : ∀ a, balKey a < 2 ^ 256 := fun a => solHash_lt a balanceSlot + -- the debited state at the recipient's slot + have hdeb_ne : caller ≠ dst → debit (slotValue σ) v (balKey dst) = slotValue σ (balKey dst) := by + intro hne + have hk : balKey caller ≠ balKey dst := + (transfer_slots hsep (by decide) (by decide) (by omega)).1 hne + simp only [debit, upd, Nat.mod_eq_of_lt (hlt dst)] + rw [if_neg (Ne.symm hk)] + refine ⟨fun hne => ?_, fun heq => ?_, fun hsc => ?_, hfail⟩ + · have hk : balKey caller ≠ balKey dst := + (transfer_slots hsep (by decide) (by decide) (by omega)).1 hne + have hd := hdeb_ne hne + refine ⟨by rw [hsucc, hd], fun hsc => ?_⟩ + obtain ⟨hst, -, -⟩ := hok hsc + rw [hst] + constructor + · simp [seqStore, upd, debit, balKey_mod', hk, Ne.symm hk] + · simp only [seqStore, upd, balKey_mod, ↓reduceIte] + rw [hd] + · subst heq + have hlt' : slotValue σ (balKey caller) < 2 ^ 256 := Generic.slotValue_lt σ _ + have hd : debit (slotValue σ) v (balKey caller) = slotValue σ (balKey caller) - v := by + simp [debit, upd, balKey_mod'] + refine ⟨?_, fun hsc => ?_⟩ + · rw [hsucc, hd] + exact ⟨fun h => h.1, fun h => ⟨h, by omega⟩⟩ + · obtain ⟨hst, -, -⟩ := hok hsc + have hle := (hsucc.mp hsc).1 + rw [hst] + funext n + by_cases h1 : n % 2 ^ 256 = balKey caller + · simp only [seqStore, upd, h1, ↓reduceIte] + rw [hd, ← slotValue_mod σ n, h1] + omega + · simp only [seqStore, debit, upd, if_neg h1] + · obtain ⟨hst, hlog, hout⟩ := hok hsc + refine ⟨hlog, hout, fun n h1 h2 => ?_⟩ + rw [hst] + simp only [seqStore, debit, upd, if_neg h1, if_neg h2] + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.targetPost_of_seq' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms targetPost_of_seq + +end SolidCore.Spec.UniswapV2.ERC20.Slice diff --git a/Contracts/UniswapV2/ERC20/Slice/Run.lean b/Contracts/UniswapV2/ERC20/Slice/Run.lean new file mode 100644 index 00000000..9c0c290c --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Slice/Run.lean @@ -0,0 +1,253 @@ +import Contracts.UniswapV2.ERC20.Slice.Post +import Contracts.UniswapV2.ERC20.Slice.Gen.Tree + +/-! +# UniswapV2ERC20.transfer: what SolidCore's checked contract does, from its erased tree + +The generic source stage erases SolidCore's checked `transfer` to the tree +`Gen.transfer_tree` (`Gen.transfer_erase_eq`, a kernel check against the contract the frontend +built from the pinned port; `Gen.deploy_eq` for the constructor's storage), and SolidCore runs +every call of the stage's scope as that tree (`Generic.source_run`). So: + +* `tree_eq`: the tree, by named parts (its three tests and its three leaves); +* `tree_seq`: the tree's result on `transfer(to, v)` from any storage of words is + `SeqPost`'s, by evaluating it: no hash premise, the slots are the ones the source computes; +* `run_tree`: SolidCore's run of a valid call is the tree's result; +* `meets_seq`: `Shapes.Meets` of `SeqPost` over SolidCore's runs, with no premise; +* `meets_target`: `Shapes.Meets` of `TargetPost` on the valid calls whose footprint premise + holds (`ValidIn`: `Valid` and `Scope`). + +The proofs read the tree only through `tree_eq`, a definitional check: they hold of the tree the +kernel checked `transfer` erases to, and fail to build for another. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Slice + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Spec +open SolidCore.Spec.UniswapV2.ERC20.Slice.Gen + +set_option simprocs false + +/-! ## The tree by parts -/ + +/-- The caller's `balanceOf` slot word. -/ +abbrev hC : WExpr := .hash (.lit 8192) (.lit 1) +/-- The recipient's `balanceOf` slot word. -/ +abbrev hT : WExpr := .hash (.arg 0) (.lit 1) +/-- The debited balance (wrapping subtraction). -/ +abbrev eSub : WExpr := .bin .sub (.sinit hC) (.arg 1) +/-- The recipient's balance in the debited state. -/ +abbrev eSel : WExpr := .sel (.bin .eq hT hC) eSub (.sinit hT) +/-- The credited balance (wrapping addition). -/ +abbrev eAdd : WExpr := .bin .add eSel (.arg 1) +/-- The address test of `to`. -/ +abbrev c1 : WExpr := .bin .gt (.arg 0) (.lit 1461501637330902918203684832716283019655932542975) +/-- SafeMath's `sub` test. -/ +abbrev c2 : WExpr := .un .iszero (.bin .lt (.sinit hC) eSub) +/-- SafeMath's `add` test. -/ +abbrev c3 : WExpr := .un .iszero (.bin .lt eAdd eSel) + +/-- The bytes of `Error(msg)` as constant output bytes. -/ +def errBytes (msg : List Nat) : List OByte := (errorData msg).map OByte.lit + +/-- The success leaf: return `true`, the credit then the debit, `Transfer(caller, to, v)`. -/ +def okLeaf : Tree := + .halt true (wordOBytes (.lit 1)) [(hT, eAdd), (hC, eSub)] + [{ topics := [.lit transferTopic, .lit 8192, .arg 0], data := wordOBytes (.arg 1) }] + +-- The erased tree, by parts: the kernel's conversion check. +kernel_rfl tree_eq transfer_tree + (.ite c1 (.halt false [] [] []) + (.ite c2 (.ite c3 okLeaf (.halt false (errBytes addMsg) [] [])) (.halt false (errBytes subMsg) [] []))) + +/-! ## Evaluating the parts -/ + +/-- The words `transfer(to, v)` reads from the storage `s`. -/ +abbrev val (s : Nat → Nat) (dst v : Nat) : Val := ⟨[dst, v], s, solHash, SolidCore.Refinement.Generic.callerWord⟩ + +/-- The tree's result on `transfer(to, v)` from the storage `s`. -/ +abbrev res (s : Nat → Nat) (dst v : Nat) : Res := transfer_tree.eval (val s dst v) + +theorem modW {n : Nat} (h : n < 2 ^ 256) : n % 2 ^ 256 = n := Nat.mod_eq_of_lt h + +theorem ite01_modW (p : Prop) [Decidable p] : (if p then 1 else 0) % 2 ^ 256 = if p then 1 else 0 := by + split + · exact modW (by norm_num) + · exact Nat.zero_mod _ + +/-- Wrapping subtraction of words. -/ +def wsub (a v : Nat) : Nat := (a + (2 ^ 256 - v)) % 2 ^ 256 + +theorem wsub_of_le {a v : Nat} (ha : a < 2 ^ 256) (h : v ≤ a) : wsub a v = a - v := by + unfold wsub + rw [Nat.mod_eq_sub_mod (by omega), Nat.mod_eq_of_lt (by omega)] + omega + +theorem lt_wsub_iff {a v : Nat} (ha : a < 2 ^ 256) (hv : v < 2 ^ 256) : a < wsub a v ↔ a < v := by + unfold wsub + rcases Nat.lt_or_ge (a + (2 ^ 256 - v)) (2 ^ 256) with h | h + · rw [Nat.mod_eq_of_lt h]; omega + · rw [Nat.mod_eq_sub_mod h, Nat.mod_eq_of_lt (by omega)]; omega + +theorem add_mod_lt_iff {d v : Nat} (hd : d < 2 ^ 256) (hv : v < 2 ^ 256) : + (d + v) % 2 ^ 256 < d ↔ 2 ^ 256 ≤ d + v := by + rcases Nat.lt_or_ge (d + v) (2 ^ 256) with h | h + · rw [Nat.mod_eq_of_lt h]; omega + · rw [Nat.mod_eq_sub_mod h, Nat.mod_eq_of_lt (by omega)]; omega + +section +variable {s : Nat → Nat} {dst v : Nat} + +/-- The hash of two constant words (stated for variables: the kernel never evaluates Keccak-256 here). -/ +theorem ev_hash_lit {a b : Nat} (ha : a < 2 ^ 256) (hb : b < 2 ^ 256) : + (WExpr.hash (.lit a) (.lit b)).eval (val s dst v) = solHash a b := by + simp only [WExpr.eval, Generic.wordSize, modW ha, modW hb] + exact modW (solHash_lt _ _) + +theorem ev_hC : hC.eval (val s dst v) = balKey caller := + ev_hash_lit (by decide) (by decide) + +theorem ev_arg0 (hto : dst < 2 ^ 160) : (WExpr.arg 0).eval (val s dst v) = dst := by + simp only [WExpr.eval, Generic.wordSize, List.getD_cons_zero]; exact modW (by omega) + +theorem ev_arg1 (hv : v < 2 ^ 256) : (WExpr.arg 1).eval (val s dst v) = v := by + simp only [WExpr.eval, Generic.wordSize, List.getD_cons_succ, List.getD_cons_zero]; exact modW hv + +theorem ev_hT (hto : dst < 2 ^ 160) : hT.eval (val s dst v) = balKey dst := by + simp only [hT, WExpr.eval.eq_8, Generic.wordSize, ev_arg0 hto] + simp only [WExpr.eval, Generic.wordSize, modW (show 1 < 2 ^ 256 by decide)] + exact modW (solHash_lt _ _) + +variable (hs : ∀ k, s k < 2 ^ 256) (hto : dst < 2 ^ 160) (hv : v < 2 ^ 256) +include hs hto hv + +theorem ev_a : (WExpr.sinit hC).eval (val s dst v) = s (balKey caller) := by + simp only [WExpr.eval.eq_6, Generic.wordSize, ev_hC]; exact modW (hs _) + +theorem ev_b : (WExpr.sinit hT).eval (val s dst v) = s (balKey dst) := by + simp only [WExpr.eval.eq_6, Generic.wordSize, ev_hT hto]; exact modW (hs _) + +theorem ev_sub : eSub.eval (val s dst v) = wsub (s (balKey caller)) v := by + simp only [eSub, eval_bin, ev_a hs hto hv, ev_arg1 hv, BinOp.eval, wsub, Generic.wordSize, Nat.mod_mod] + +theorem ev_sel : eSel.eval (val s dst v) = + if balKey dst = balKey caller then wsub (s (balKey caller)) v else s (balKey dst) := by + simp only [eSel, WExpr.eval.eq_7, eval_bin, Generic.wordSize, ev_hT hto, ev_hC, BinOp.eval, ite01_modW, + ev_sub hs hto hv, ev_b hs hto hv] + by_cases h : balKey dst = balKey caller <;> simp [h] + +theorem ev_c1 : c1.eval (val s dst v) = 0 := by + simp only [c1, eval_bin, ev_arg0 hto, eval_lit, Generic.wordSize, modW (show 1461501637330902918203684832716283019655932542975 < 2 ^ 256 by decide), + BinOp.eval, ite01_modW, Generic.wordSize] + split_ifs <;> omega + +theorem ev_c2 : c2.eval (val s dst v) = if v ≤ s (balKey caller) then 1 else 0 := by + simp only [c2, WExpr.eval.eq_4, eval_bin, ev_a hs hto hv, ev_sub hs hto hv, BinOp.eval, UnOp.eval, + ite01_modW, lt_wsub_iff (hs _) hv, Generic.wordSize] + split_ifs <;> omega + +/-- The recipient's balance after the debit, as the tree reads it. -/ +theorem ev_sel_debit (hle : v ≤ s (balKey caller)) : + eSel.eval (val s dst v) = debit s v (balKey dst) := by + rw [ev_sel hs hto hv, wsub_of_le (hs _) hle] + simp only [debit, upd, balKey_mod] + +theorem ev_c3 (hle : v ≤ s (balKey caller)) : + c3.eval (val s dst v) = if debit s v (balKey dst) + v < 2 ^ 256 then 1 else 0 := by + have hd : debit s v (balKey dst) < 2 ^ 256 := by + rw [← ev_sel_debit hs hto hv hle]; exact WExpr.eval_lt _ _ + simp only [c3, eAdd, WExpr.eval.eq_4, eval_bin, ev_sel_debit hs hto hv hle, ev_arg1 hv, BinOp.eval, + UnOp.eval, ite01_modW, Generic.wordSize, Nat.mod_mod, add_mod_lt_iff hd hv] + split_ifs <;> omega + +end + +/-! ## The tree's result -/ + +theorem bytes_err (ρ : Val) (msg : List Nat) (h : ∀ b ∈ errorData msg, b < 256) : + (errBytes msg).map (OByte.eval ρ) = errorData msg := by + simp only [errBytes, List.map_map] + conv_rhs => rw [← List.map_id (errorData msg)] + apply List.map_congr_left + intro b hb + exact Nat.mod_eq_of_lt (h b hb) + +theorem errorData_add_lt : ∀ b ∈ errorData addMsg, b < 256 := by decide +kernel +theorem errorData_sub_lt : ∀ b ∈ errorData subMsg, b < 256 := by decide +kernel + +theorem bytes_word (ρ : Val) (e : WExpr) : + (wordOBytes e).map (OByte.eval ρ) = be32 (e.eval ρ) := by + simp only [wordOBytes, be32, List.map_map] + rfl + +/-- The result of a failure with the revert data `Error(msg)`. -/ +def failRes (s : Nat → Nat) (msg : List Nat) : Res := + { success := false, output := errorData msg, logs := [], store := s } + +/-- The result of a success. -/ +def okRes (s : Nat → Nat) (dst v : Nat) : Res := + { success := true, output := be32 1, logs := [transferLog caller dst v], store := seqStore s dst v } + +section +variable {s : Nat → Nat} {dst v : Nat} (hs : ∀ k, s k < 2 ^ 256) (hto : dst < 2 ^ 160) (hv : v < 2 ^ 256) +include hs hto hv + +/-- The caller's balance does not cover `v`: SafeMath's `sub` reverts. -/ +theorem res_sub (hle : ¬ v ≤ s (balKey caller)) : res s dst v = failRes s subMsg := by + simp only [res, tree_eq, Tree.eval, ev_c1 hs hto hv, ev_c2 hs hto hv, if_neg hle, if_true, + eq_self_iff_true, Bool.false_eq_true, if_false, failRes] + rw [bytes_err _ _ errorData_sub_lt] + +/-- The credit overflows: SafeMath's `add` reverts. -/ +theorem res_add (hle : v ≤ s (balKey caller)) (hov : ¬ debit s v (balKey dst) + v < 2 ^ 256) : + res s dst v = failRes s addMsg := by + simp only [res, tree_eq, Tree.eval, ev_c1 hs hto hv, ev_c2 hs hto hv, ev_c3 hs hto hv hle, if_pos hle, + if_neg hov, one_ne_zero, if_true, eq_self_iff_true, Bool.false_eq_true, if_false, failRes] + rw [bytes_err _ _ errorData_add_lt] + +/-- Otherwise the call succeeds: the debit, then the credit, the log and `true`. -/ +theorem res_ok (hle : v ≤ s (balKey caller)) (hov : debit s v (balKey dst) + v < 2 ^ 256) : + res s dst v = okRes s dst v := by + simp only [res, tree_eq, Tree.eval, ev_c1 hs hto hv, ev_c2 hs hto hv, ev_c3 hs hto hv hle, if_pos hle, + if_pos hov, one_ne_zero, if_true, eq_self_iff_true, if_false, okLeaf, okRes] + congr 1 + case e_logs => + simp only [Log.eval, List.map_cons, List.map_nil, bytes_word, ev_arg1 hv, ev_arg0 hto, eval_lit, + transferLog, transferTopic, caller, Generic.callerWord, Generic.wordSize, + modW (show 100389287136786176327247604509743168900146139575972864366142685224231313322991 < 2 ^ 256 by decide), + modW (show 8192 < 2 ^ 256 by decide)] + case e_store => + funext n + simp only [Writes.store, ev_hT hto, ev_hC, seqStore, upd, Generic.wordSize] + rw [show eAdd.eval (val s dst v) = debit s v (balKey dst) + v by + simp only [eAdd, eval_bin, ev_sel_debit hs hto hv hle, ev_arg1 hv, BinOp.eval, Generic.wordSize, + Nat.mod_mod] + exact Nat.mod_eq_of_lt hov] + rw [ev_sub hs hto hv, wsub_of_le (hs _) hle] + by_cases h1 : n % 2 ^ 256 = balKey dst + · rw [if_pos h1.symm, if_pos h1] + · rw [if_neg (Ne.symm h1), if_neg h1] + simp only [debit, upd] + by_cases h2 : n % 2 ^ 256 = balKey caller + · rw [if_pos h2.symm, if_pos h2] + · rw [if_neg (Ne.symm h2), if_neg h2] + + all_goals rw [bytes_word, eval_lit, Generic.wordSize, modW (show 1 < 2 ^ 256 by decide)] +end + +/-- **The erased tree is `SeqPost`'s source**, from any storage of words. -/ +theorem tree_seq (s : Nat → Nat) (hs : ∀ k, s k < 2 ^ 256) (dst v : Nat) (hto : dst < 2 ^ 160) + (hv : v < 2 ^ 256) : + ((res s dst v).success = true ↔ + (v ≤ s (balKey caller) ∧ debit s v (balKey dst) + v < 2 ^ 256)) ∧ + ((res s dst v).success = true → (res s dst v).store = seqStore s dst v ∧ + (res s dst v).logs = [transferLog caller dst v] ∧ (res s dst v).output = be32 1) ∧ + ((res s dst v).success = false → (res s dst v).store = s ∧ (res s dst v).logs = [] ∧ + (res s dst v).output = errorData (if v ≤ s (balKey caller) then addMsg else subMsg)) := by + by_cases hle : v ≤ s (balKey caller) + · by_cases hov : debit s v (balKey dst) + v < 2 ^ 256 + · rw [res_ok hs hto hv hle hov]; simp [okRes, hle, hov] + · rw [res_add hs hto hv hle hov]; simp [failRes, hle, hov] + · rw [res_sub hs hto hv hle]; simp [failRes, hle] + +end SolidCore.Spec.UniswapV2.ERC20.Slice diff --git a/Contracts/UniswapV2/ERC20/Slice/Statement.lean b/Contracts/UniswapV2/ERC20/Slice/Statement.lean new file mode 100644 index 00000000..e739417d --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Slice/Statement.lean @@ -0,0 +1,237 @@ +import Contracts.UniswapV2.ERC20.Slice.Vc + +/-! +# UniswapV2ERC20.transfer: the slice's statements over SolidCore's runs + +From the erased tree (Run.lean) and the deployment and erasure checks (`Gen.deploy_eq`, +`Gen.transfer_erase_eq`), for SolidCore's checked contract `c` of the pinned port: + +* `run_tree`: SolidCore's run of every valid call is the tree's result; +* `meets_seq`: `Shapes.Meets` of `SeqPost` on `Valid deployed`, with no premise; +* `meets_target`: `Shapes.Meets` of `TargetPost` on `ValidIn` (`Valid` and the call's + footprint premise `Scope`); +* `transfer_holds`, `meets_bundle`: solar-verify's exported spec of `transfer` on the stage's + calls whose footprint premise holds, and as `Shapes.Meets` of `bundlePost` on `ValidIn`; +* `nonVacuous_seq`, `nonVacuous_target`, `nonVacuous_bundle`: each postcondition rejects some + observable of a valid call (the premise holding of the real keccak256, by the kernel), and + `valid_inhabited`; +* the required concrete runs (docs/CERTIFICATION_TARGET.md): `self_max`, a self-transfer of 1 from + a balance of `2 ^ 256 - 1` succeeds with the storage unchanged and `Transfer` logged; + `self_short`, a self-transfer of more than the balance reverts with SafeMath's + `ds-math-sub-underflow` and no change; both as SolidCore runs of concrete calls, and in general + (`self_ok`, `self_fail`). +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Slice + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Spec SolidCore.Refinement.Shapes +open SolidCore.Spec.UniswapV2.ERC20.Slice.Gen + +/-- SolidCore's interpreter fuel for the port. -/ +abbrev fuel : Nat := SolidCore.Verify.VC.UniswapV2ERC20.fuel + +/-- **The valid calls with their premise**: `Valid` from the constructor's storage, and the call's +footprint premise. -/ +def ValidIn (call : Call) : Prop := Valid deployed call ∧ Scope call + +/-- The deployment and the erasure of `transfer`, from the kernel checks. -/ +theorem facts {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + (∃ d, Wide.DeployedAt fuel c d deployed) ∧ ∃ f, c.core.findFunctionBySelector? 2835717307 = some f ∧ + f.params.length = 2 ∧ eraseFn (envOf c.core) fuel f = some transfer_tree := by + refine ⟨?_, ?_⟩ + · have hdep := deploy_eq + simp only [deploy?, hc] at hdep + exact Wide.deployedAt_of hdep + · have hmap := transfer_erase_eq + simp only [transfer_erase?, hc, Option.map_eq_some_iff, Prod.mk.injEq] at hmap + obtain ⟨f, hf, hlen, hT⟩ := hmap + exact ⟨f, hf, hlen, hT⟩ + +theorem callArgs_transferCall (σ : List (Nat × Nat)) {dst v : Nat} (hto : dst < 2 ^ 256) (hv : v < 2 ^ 256) : + callArgs (transferCall σ dst v) = [dst, v] := by + simp only [callArgs, transferCall] + exact words_calldata _ (by simp; omega) + +theorem transferCall_inj {σ σ' : List (Nat × Nat)} {dst dst' v v' : Nat} (hto : dst < 2 ^ 256) + (hv : v < 2 ^ 256) (hto' : dst' < 2 ^ 256) (hv' : v' < 2 ^ 256) + (h : transferCall σ dst v = transferCall σ' dst' v') : σ = σ' ∧ dst = dst' ∧ v = v' := by + have hs : σ = σ' := congrArg Call.storage h + have ha := congrArg callArgs h + rw [callArgs_transferCall σ hto hv, callArgs_transferCall σ' hto' hv'] at ha + simp only [List.cons.injEq, and_true] at ha + exact ⟨hs, ha.1, ha.2⟩ + +/-- **SolidCore's run of a valid call is the erased tree's result.** -/ +theorem run_tree {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) {σ : List (Nat × Nat)} {dst v : Nat} + (hcov : Generic.Covers deployed σ) (hto : dst < 2 ^ 160) (hv : v < 2 ^ 256) : + (solidCore fuel).run c (transferCall σ dst v) = some (res (slotValue σ) dst v).obs := by + obtain ⟨⟨d, hd⟩, f, hf, hlen, hT⟩ := facts hc + exact source_run hd hcov (by decide) hf hT [dst, v] (by simp [hlen]) (by simp; omega) + +/-- **`SeqPost` of every SolidCore run of a valid call**: no premise. -/ +theorem meets_seq {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Meets (solidCore fuel) c (Valid deployed) SeqPost := by + rintro _ ⟨σ, dst, v, hcov, hto, hv, rfl⟩ obs hrun + rw [run_tree hc hcov hto hv, Option.some.injEq] at hrun + subst hrun + intro σ' dst' v' heq hto' hv' + obtain ⟨rfl, rfl, rfl⟩ := transferCall_inj (by omega) hv (by omega) hv' heq + exact tree_seq (slotValue σ) (fun k => Generic.slotValue_lt σ k) dst v hto hv + +/-- **`TargetPost` of every SolidCore run of a valid call whose footprint premise holds.** -/ +theorem meets_target {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Meets (solidCore fuel) c ValidIn TargetPost := + fun call h obs hrun => targetPost_of_seq (meets_seq hc call h.1 obs hrun) h.2 + +/-! ## solar-verify's exported spec over SolidCore's runs -/ + +/-- The ghost step of a call of `transfer`: the spec has no ghosts. -/ +def idStep : GhostStep := fun _ g => g + +/-- **The exported spec holds of SolidCore's checked contract** on the stage's calls of `transfer` +whose argument words meet the footprint premise. -/ +theorem transfer_holds {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + HoldsFnUnder (fun call => SepArgs (callArgs call)) (solidCore fuel) c + (SolidCore.Verify.VC.stageScope fn_transfer deployed) spec ctxOf idStep transfer_spec := by + obtain ⟨⟨d, hd⟩, f, hf, hlen, hT⟩ := facts hc + exact holdsFnUnder_of_tree_fixed (fn := fn_transfer) (ctx := ctx) hd (by decide) hf + (by simpa [fn_transfer] using hlen) hT (fun call h => by simp [ctxOf, ctx, h]) (fun _ _ _ => rfl) + (by simpa [fn_transfer] using transfer_meets) + +theorem specs_eq : spec.spec.specs = [transfer_spec] := rfl + +/-- A valid call is a stage call of `transfer` whose words meet the premise. -/ +theorem scope_of_validIn {call : Call} (h : ValidIn call) : + SolidCore.Verify.VC.stageScope fn_transfer deployed call ∧ SepArgs (callArgs call) := by + obtain ⟨⟨σ, dst, v, hcov, hto, hv, rfl⟩, hs⟩ := h + refine ⟨⟨σ, hcov, fn_transfer, by simp, [dst, v], rfl, by simp; omega, rfl⟩, ?_⟩ + rw [callArgs_transferCall σ (by omega) hv, sepArgs_iff hto] + exact hs σ dst v rfl hto hv + +/-- **The exported spec as `Shapes.Meets`** of `bundlePost` on the valid calls with their premise. -/ +theorem meets_bundle {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Meets (solidCore fuel) c ValidIn (bundlePost spec ctxOf idStep) := by + intro call h obs hrun fs hfs args pre hpre + rw [specs_eq, List.mem_singleton] at hfs + subst hfs + obtain ⟨hsc, hP⟩ := scope_of_validIn h + obtain ⟨obs', h1, h2⟩ := transfer_holds hc call hsc hP args pre hpre + rw [hrun, Option.some.injEq] at h1 + subst h1 + exact h2 + +/-! ## Non-vacuity -/ + +/-- The witness storage: slot 3 (the constructor's) written, every `balanceOf` slot 0. -/ +def σ0 : List (Nat × Nat) := [(3, 0)] + +theorem covers_σ0 : Generic.Covers deployed σ0 := by + intro kv hkv + simp only [deployed, List.mem_singleton] at hkv + subst hkv + exact ⟨(3, 0), by simp [σ0], rfl⟩ + +/-- `transfer(1, 0)` from `σ0`, the caller `0x2000`. -/ +def call0 : Call := transferCall σ0 1 0 + +theorem scope_call0 : Scope call0 := by + intro σ dst v h hto hv + obtain ⟨-, rfl, -⟩ := transferCall_inj (by decide) (by decide) (by omega) hv h + exact scopedSep_transfer_example + +theorem valid_call0 : ValidIn call0 := + ⟨⟨σ0, 1, 0, covers_σ0, by decide, by decide, rfl⟩, scope_call0⟩ + +/-- **The valid calls are inhabited**, the premise included (it holds of the real keccak256). -/ +theorem valid_inhabited : ∃ call, ValidIn call := ⟨call0, valid_call0⟩ + +/-- An observable no correct `transfer` shows: success, with no log and no output. -/ +def badObs : Observable := { success := true, output := [], logs := [], storage := slotValue σ0 } + +/-- **`SeqPost` rejects something** on a valid call. -/ +theorem nonVacuous_seq : ∃ call obs, Valid deployed call ∧ ¬ SeqPost call obs := by + refine ⟨call0, badObs, valid_call0.1, fun h => ?_⟩ + have := ((h σ0 1 0 rfl (by decide) (by decide)).2.1 rfl).2.1 + simp [badObs] at this + +/-- **`TargetPost` rejects something** on a valid call whose premise holds. -/ +theorem nonVacuous_target : ∃ call obs, ValidIn call ∧ ¬ TargetPost call obs := by + refine ⟨call0, badObs, valid_call0, fun h => ?_⟩ + have := ((h σ0 1 0 rfl (by decide) (by decide)).2.2.1 rfl).1 + simp [badObs] at this + + +/-! ## The required concrete runs -/ + +theorem slotValue_last (a b k x : Nat) : slotValue [(a, b), (k, x)] k = x % 2 ^ 256 := by + simp [slotValue] + +theorem covers_pair (k x : Nat) : Generic.Covers deployed [(3, 0), (k, x)] := by + intro kv hkv + simp only [deployed, List.mem_singleton] at hkv + subst hkv + exact ⟨(3, 0), by simp, rfl⟩ + +/-- **A self-transfer the balance covers succeeds, with the storage unchanged**, `Transfer(caller, +caller, v)` logged and `true` returned: no recipient-overflow condition. -/ +theorem self_ok {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) {σ : List (Nat × Nat)} {v : Nat} + (hcov : Generic.Covers deployed σ) (hv : v < 2 ^ 256) (hle : v ≤ slotValue σ (balKey caller)) : + (solidCore fuel).run c (transferCall σ caller v) = + some ⟨true, be32 1, [transferLog caller caller v], slotValue σ⟩ := by + rw [run_tree hc hcov (by decide) hv] + have hs := fun k => Generic.slotValue_lt σ k + have hk : slotValue σ (balKey caller) < 2 ^ 256 := hs (balKey caller) + have hov : debit (slotValue σ) v (balKey caller) + v < 2 ^ 256 := by + simp only [debit, upd, balKey_mod, if_pos] + omega + rw [res_ok hs (by decide) hv hle hov] + simp only [okRes, Res.obs, Option.some.injEq, Observable.mk.injEq, true_and] + funext n + simp only [seqStore, debit, upd, balKey_mod, if_pos] + by_cases h : n % 2 ^ 256 = balKey caller + · rw [if_pos h, ← SolidCore.Spec.UniswapV2.ERC20.Slice.slotValue_mod σ n, h] + omega + · rw [if_neg h, if_neg h] + +/-- **A self-transfer of more than the balance reverts** with SafeMath's `ds-math-sub-underflow`, +no log and the storage unchanged. -/ +theorem self_fail {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) {σ : List (Nat × Nat)} {v : Nat} + (hcov : Generic.Covers deployed σ) (hv : v < 2 ^ 256) (hlt : slotValue σ (balKey caller) < v) : + (solidCore fuel).run c (transferCall σ caller v) = + some ⟨false, errorData subMsg, [], slotValue σ⟩ := by + rw [run_tree hc hcov (by decide) hv, res_sub (fun k => Generic.slotValue_lt σ k) (by decide) hv (by omega)] + rfl + +/-- The storage with the caller's balance at `2 ^ 256 - 1`. -/ +def σmax : List (Nat × Nat) := [(3, 0), (balKey caller, 2 ^ 256 - 1)] + +/-- **Required case**: balance `2 ^ 256 - 1`, `transfer(caller, 1)` succeeds, the balance is +unchanged and `Transfer(caller, caller, 1)` is logged. -/ +theorem self_max {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + slotValue σmax (balKey caller) = 2 ^ 256 - 1 ∧ + (solidCore fuel).run c (transferCall σmax caller 1) = + some ⟨true, be32 1, [transferLog caller caller 1], slotValue σmax⟩ := by + have hb : slotValue σmax (balKey caller) = 2 ^ 256 - 1 := by + rw [σmax, slotValue_last]; decide + exact ⟨hb, self_ok hc (covers_pair _ _) (by decide) (by rw [hb]; decide)⟩ + +/-- The storage with the caller's balance at 5. -/ +def σshort : List (Nat × Nat) := [(3, 0), (balKey caller, 5)] + +/-- **Required case**: a self-transfer of 6 from a balance of 5 reverts, with no change. -/ +theorem self_short {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + (solidCore fuel).run c (transferCall σshort caller 6) = + some ⟨false, errorData subMsg, [], slotValue σshort⟩ := + self_fail hc (covers_pair _ _) (by decide) (by rw [σshort, slotValue_last]; decide) + +end SolidCore.Spec.UniswapV2.ERC20.Slice diff --git a/Contracts/UniswapV2/ERC20/Slice/Vc.lean b/Contracts/UniswapV2/ERC20/Slice/Vc.lean new file mode 100644 index 00000000..31539a8c --- /dev/null +++ b/Contracts/UniswapV2/ERC20/Slice/Vc.lean @@ -0,0 +1,124 @@ +import Contracts.UniswapV2.ERC20.Slice.Run +import Verify.ShapeBundle + +/-! +# UniswapV2ERC20.transfer: solar-verify's exported spec, discharged over SolidCore's runs + +`Gen.spec` is solar-verify's `--emit-lean-spec` export of solar's +crates/verify/uniswap-v2/transfer-slice.spec (the annotations of the slice on the pinned port): + +* `old(balanceOf[msg.sender]) >= value` on success, and the recipient-overflow condition only when + `msg.sender != to`; +* `msg.sender != to`: `balanceOf[msg.sender] == old(...) - value` and + `balanceOf[to] == old(balanceOf[to]) + value`; +* `msg.sender == to`: `balanceOf[msg.sender] == old(balanceOf[msg.sender])`; +* `returns true`; and `succeeds-if` the balance covers `value` and (`msg.sender == to` or the + credit does not overflow): with the ensures, success iff that condition. + +Its verification condition over SolidCore: + +* `transfer_meets`: the spec of the erased tree on every argument list whose footprint premise + holds (`SepArgs`: `ScopedSep` on the caller's and `to`'s `balanceOf` preimages, nothing else); + `tree_meets_sep` is Verify/Spec/HashScope.lean's `tree_meets_scoped` with that premise in place of + `MapScope` (no frame family: the spec has no clause over other addresses); +* `transfer_holds`: the spec of SolidCore's checked contract on the stage's calls of `transfer` + whose premise holds (`HoldsFnUnder`, by `holdsFnUnder_of_tree_fixed`); +* `meets_bundle`: as `Shapes.Meets` of `Shapes.bundlePost` on `ValidIn`, the form `Equiv` carries to + the bytes (Bytes.lean); +* `sepArgs_iff`: the premise on a call's words is `Post.Scope`'s, `ScopedSep (transferFootprint 1 + caller to)`. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Slice + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Spec +open SolidCore.Spec.UniswapV2.ERC20.Slice.Gen + +/-- **The call's footprint premise on its argument words**: keccak256 separated on the +`balanceOf` preimages of the caller and of `to` (argument 0). -/ +def SepArgs (args : List Nat) : Prop := ScopedSep (mapScope (callKeys 8192 [0] args) [1]) + +theorem sepArgs_iff {dst v : Nat} (hto : dst < 2 ^ 160) : + SepArgs [dst, v] ↔ ScopedSep (transferFootprint balanceSlot caller dst) := by + have : dst % 2 ^ 160 = dst := Nat.mod_eq_of_lt hto + simp only [SepArgs, callKeys, mapScope, transferFootprint, List.map_cons, List.map_nil, List.getD_cons_zero, + List.flatMap_cons, List.flatMap_nil, List.cons_append, List.nil_append, List.append_nil, this, caller, + Generic.callerWord, balanceSlot] + +/-- Two slots of the footprint are equal only for the same key and mapping. -/ +theorem sep_inj {K ms : List Nat} (h : ScopedSep (mapScope K ms)) (m n : Nat) (hm : m ∈ ms) (hn : n ∈ ms) + (hmw : m < 2 ^ 256) (hnw : n < 2 ^ 256) (a b : Nat) (hK : a ∈ K ∧ b ∈ K) : + a < 2 ^ 160 → b < 2 ^ 160 → solHash a m = solHash b n → a = b ∧ m = n := fun ha hb he => + scoped_inj h (by omega) (by omega) hmw hnw (mem_mapScope hK.1 hm) (mem_mapScope hK.2 hn) he + +/-- A slot of the footprint is at least `2 ^ 128`. -/ +theorem sep_ge {K ms : List Nat} (h : ScopedSep (mapScope K ms)) (m : Nat) (hm : m ∈ ms) (a : Nat) + (hK : a ∈ K) : 2 ^ 128 ≤ solHash a m := + scoped_ge h (mem_mapScope hK hm) + +set_option maxHeartbeats 4000000 in +/-- **The exported spec holds of the erased tree** on every argument list whose footprint premise holds. -/ +theorem transfer_meets : + TreeMeetsFixedOn (fun ρ => SepArgs ρ.args) spec transfer_spec ctx 2 transfer_tree := by + intro args s iargs pre hl hargs hs hdec hst ht hreq hinv hP + simp only [Nat.reducePow] at hs + rcases args with _ | ⟨a0, _ | ⟨a1, _ | ⟨a2, _ | ⟨a3, _ | ⟨a4, _ | ⟨a5, _ | ⟨a6, _ | ⟨a7, _ | ⟨_, _⟩⟩⟩⟩⟩⟩⟩⟩⟩ <;> + simp only [List.length_cons, List.length_nil] at hl <;> (try omega) <;> + simp only [List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, + IsEmpty.forall_iff, implies_true, and_true, Nat.reducePow] at hargs <;> + simp only [transfer_tree, transfer_spec, Gen.spec, SolidCore.Spec.Export.UniswapV2ERC20Slice.UniswapV2ERC20, ctx, List.head, List.getElem_cons_zero, List.getElem_cons_succ, decodeWords, Ty.ofWord, + bind, pure, Option.bind, Nat.reducePow] at hdec <;> + split_ifs at hdec <;> simp only [Option.some.injEq, reduceCtorEq] at hdec <;> + subst hdec <;> + simp only [SepArgs, callKeys, List.map_cons, List.map_nil, List.getD_cons_zero, + List.getD_cons_succ, Nat.reducePow] at hP <;> + simp (disch := omega) only [Nat.mod_eq_of_lt] at hP <;> + have hinj := sep_inj hP <;> have hge := sep_ge hP <;> have hlt := solHash_lt' <;> + have hkec := keccak_solHash <;> + generalize solHash = H at hinj hge hlt hkec ⊢ <;> + refine ⟨fun hsucc => have hsi : True := trivial; ?_, fun hne hsi => have hsucc : True := trivial; ?_⟩ + all_goals try (simp [transfer_tree, transfer_spec, Gen.spec, SolidCore.Spec.Export.UniswapV2ERC20Slice.UniswapV2ERC20, ctx] at hne; done) + all_goals simp only [transfer_tree, transfer_spec, Gen.spec, SolidCore.Spec.Export.UniswapV2ERC20Slice.UniswapV2ERC20, ctx, Tree.eval, WExpr.eval, BinOp.eval, UnOp.eval, Generic.wordSize, Res.obs, + Writes.store, List.getD_cons_zero, List.getD_cons_succ, Nat.reducePow] at hsucc ⊢ + all_goals simp (disch := simp only [hargs, hs, hlt, Nat.reduceLT]) only [Nat.mod_eq_of_lt, ite_mod_nat, + Nat.reduceMod, Nat.zero_mod, ite10_eq_zero_iff, Decidable.not_not] at hsucc ⊢ + all_goals split_ifs at hsucc ⊢ + all_goals try simp only [Bool.false_eq_true, Bool.true_eq_false, imp_false, not_true_eq_false, + IsEmpty.forall_iff] at hsucc + all_goals try simp only [transfer_tree, transfer_spec, Gen.spec, SolidCore.Spec.Export.UniswapV2ERC20Slice.UniswapV2ERC20, ctx, OByte.eval, WExpr.eval, Generic.wordSize, words, bytesWord, decodeWords, Ty.ofWord, + List.map_cons, List.map_nil, List.length_cons, List.length_nil, List.range_succ, List.range_zero, + List.nil_append, List.cons_append, List.drop_zero, List.take_succ_cons, List.take_zero, List.foldl_cons, + List.foldl_nil, Nat.reduceDiv, Nat.reducePow, Nat.reduceMod, Nat.reduceSub, Nat.reduceMul, Nat.reduceAdd, + Nat.reduceLT, ite_true, ite_false, List.getElem_cons_succ, List.getElem_cons_zero, Option.some.injEq, + exists_eq_left', bind, pure, Option.bind, Ty.InRange, Nat.cast_ofNat, Nat.zero_add, + Nat.reduceLeDiff] at hsucc ⊢ + all_goals try clear hsucc + all_goals try refine ⟨?_, ?_⟩ + all_goals simp only [Bundle.satAll, Bundle.sat, transfer_tree, transfer_spec, Gen.spec, SolidCore.Spec.Export.UniswapV2ERC20Slice.UniswapV2ERC20, ctx, List.getElem_cons_succ, List.getElem_cons_zero, + List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, eval, evalList, slotOf, mkEnv, + Env.cur, Env.bind, BinOp.apply, Ty.ofBits, toWord, List.getD_cons_zero, List.getD_cons_succ, + List.lookup, hkec, ofProp_ne_zero, ite_true, ite_false, Bool.false_eq_true, Nat.zero_mod, hst, + beq_self_eq_true, Ty.InRange, Option.getD_some, forall_int_range, Nat.cast_ofNat] at hinv hsi ⊢ + all_goals try simp only [wordMod, Nat.reducePow] at hinv hsi ⊢ + all_goals try simp (disch := first | exact hlt _ _ | exact hs _ | omega) only [Nat.mod_eq_of_lt, + toNat_natCast_emod] at hinv hsi ⊢ + all_goals try simp (disch := first | exact hlt _ _ | exact hs _ | omega) only [Nat.cast_ofNat, + Int.reduceMod, Int.reduceToNat, Nat.mod_eq_of_lt, toNat_natCast_emod, toNat_ofNat_emod, + toNat_zero_emod, toNat_one_emod, wordMod, Nat.reducePow, Nat.reduceMul, Nat.reduceMod, Nat.div_one, + Nat.reduceDiv, Int.reducePow] at hinv hsi ⊢ + all_goals (repeat' (first | (apply And.intro) | intro)) + -- The footprint premise, the one way it is used: the caller's and `to`'s slots differ when the + -- addresses do (Verify/Spec/HashScope.lean's `hash_facts_scoped` instances close with the main goal + -- still open, so its `done` fails and it adds none). + all_goals have hk : a0 = 8192 ∨ H a0 1 ≠ H 8192 1 := + (Decidable.em (a0 = 8192)).elim Or.inl fun h => Or.inr fun (he : H a0 1 = H 8192 1) => + absurd (hinj 1 1 (by simp) (by simp) (by decide) (by decide) a0 8192 (by simp) (by omega) (by decide) he).1 h + all_goals have hk' : a0 ≠ 8192 ∨ H a0 1 = H 8192 1 := + (Decidable.em (a0 = 8192)).elim (fun h => Or.inr (congrArg (H · 1) h)) Or.inl + all_goals (hash_facts_scoped H s hinj hge hlt hs; (try split_ifs) <;> omega) + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Slice.transfer_meets' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms transfer_meets + +end SolidCore.Spec.UniswapV2.ERC20.Slice diff --git a/Contracts/UniswapV2/ERC20/SourceMir.lean b/Contracts/UniswapV2/ERC20/SourceMir.lean new file mode 100644 index 00000000..142cf9dd --- /dev/null +++ b/Contracts/UniswapV2/ERC20/SourceMir.lean @@ -0,0 +1,86 @@ +import Contracts.UniswapV2.ERC20.SourceMirCheck +import Contracts.UniswapV2.ERC20.SourceMirDeploy +import Verify.ShapeCtx + +/-! +# UniswapV2ERC20.transfer: SolidCore's checked source to solar's first lowered MIR (E3) + +The source-to-MIR edge (E3) of the first slice of docs/CERTIFICATION_TARGET.md, for +`transfer(address,uint256)` and the private `_transfer` it calls (SafeMath's checked `sub` and +`add` in `unchecked` blocks, the two `balanceOf` writes, sequential, and the `Transfer` event), +proved by the generic source checker alone: no per-contract glue and no hand-written model. + +* The source is SolidCore's checked `UniswapV2ERC20` (`SolidCore.Verify.VC.UniswapV2ERC20.contract?`, + the kernel's type check of the generated `Contracts/UniswapV2/ERC20/Source.lean`). The frontend + that generated that file from the port is TRUSTED (edge E1). +* The MIR is `SolarTV.Export.UniswapV2ERC20.stage0`: solar's first lowered MIR of the same port + (`-Ogas --evm-version osaka`), exported fresh at build time by + `scripts/verify/uniswap_v2_erc20_stages.sh` (`-Zemit-lean-stages`, bytecode unchanged by the flag). +* `check_eq` (`kernel_rfl`): the kernel evaluates `Generic.check` of stage0 for `[fn_transfer]`, + with the caller and two-word Keccak-256 flags, to `true`, from the source text up, with the + selector, event-topic and Keccak-256 tables each entry of which the kernel checks once. +* `deploy_eq` (`kernel_rfl`): the constructor leaves exactly `deployed` (slot 3, + `DOMAIN_SEPARATOR`) and no logs. +* `transfer_stage`: `Stage (solidCore fuel) (moduleSem o) c stage0 (genericValid0 fns deployed)` + under every oracle `o` with `SourceEnvOk o`, from `Generic.stageAtEnv`. + +`SourceEnvOk o` is the only premise. It asks that the oracle's caller be SolidCore's caller +`callerWord` (0x2000, the caller of every run of `solidCore`) and that its Keccak-256 of the 64 +bytes of two words be SolidCore's slot hash of the same bytes, which is Keccak-256 itself. It is +not a hash-separation premise: both sides compute the same mapping slots, so no injectivity is +assumed. It is satisfiable: EthLib's own oracle meets it (`sourceEnvOk_inhabited`), so the +stage is not vacuous, and `valid_inhabited` gives a valid call. + +Valid calls (`genericValid0 fns deployed`): `transfer(to, value)` on any argument words below +`2 ^ 256` (a `to` word above `2 ^ 160` reverts on both sides), no value, from any storage, given as +a list of entries, that lists the `DOMAIN_SEPARATOR` slot. The caller is `callerWord`: SolidCore's +semantics and `SolarTV.Call` fix it, so "any caller" is not stated here (see RESULT.md). +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.SourceMir + +open SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Refinement.Shapes + +/-- **E3 for transfer**: on every valid call, solar's first lowered MIR shows what SolidCore's +checked source shows (status, return data, revert data, storage and logs), under every oracle +with SolidCore's caller and Keccak-256. -/ +theorem transfer_stage (o : SolarTV.Machine.Oracle) (henv : SourceEnvOk o) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + SolarTV.Stage (solidCore SolidCore.Verify.VC.UniswapV2ERC20.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.UniswapV2ERC20.stage0 (genericValid0 fns deployed) := by + have hdep := SolidCore.Spec.UniswapV2.ERC20.SourceMirDeploy.deploy_eq + simp only [deploy?, hc] at hdep + obtain ⟨_, hdd⟩ := Wide.deployedAt_of hdep + exact stageAtEnv o henv hdd (check_ok hc) + +/-- The premise is satisfiable: EthLib's oracle has SolidCore's caller and Keccak-256. -/ +theorem sourceEnvOk_inhabited : ∃ o, SourceEnvOk o := + ⟨Solar.Assemble.ethOracle ⟨fun _ _ _ => 0, fun _ => 0, fun _ _ => 0, fun _ _ => 0, fun _ => 0, 0⟩, + sourceEnvOk_of (Solar.Assemble.ethOracle_ok _)⟩ + +/-- The valid calls are inhabited. -/ +theorem valid_inhabited : ∃ call, genericValid0 fns deployed call := + genericValid0_inhabited fn_transfer [] deployed + +/-- **The edge, closed**: the checked contract exists and E3 holds of it, the premise is +satisfiable and the valid calls are inhabited. -/ +theorem transfer_source_mir : + (∃ c, SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c ∧ + ∀ o, SourceEnvOk o → + SolarTV.Stage (solidCore SolidCore.Verify.VC.UniswapV2ERC20.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.UniswapV2ERC20.stage0 (genericValid0 fns deployed)) ∧ + (∃ o, SourceEnvOk o) ∧ (∃ call, genericValid0 fns deployed call) := by + obtain ⟨c, hc⟩ := SolidCore.Verify.VC.UniswapV2ERC20.contract_ok + exact ⟨⟨c, hc, fun o h => transfer_stage o h hc⟩, sourceEnvOk_inhabited, valid_inhabited⟩ + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.SourceMir.transfer_source_mir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms transfer_source_mir + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.SourceMir.transfer_stage' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms transfer_stage + +end SolidCore.Spec.UniswapV2.ERC20.SourceMir + diff --git a/Contracts/UniswapV2/ERC20/SourceMirCheck.lean b/Contracts/UniswapV2/ERC20/SourceMirCheck.lean new file mode 100644 index 00000000..e99e25b5 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/SourceMirCheck.lean @@ -0,0 +1,20 @@ +import Contracts.UniswapV2.ERC20.SourceMirDefs + +/-! The kernel's evaluation of the generic check of stage0 for transfer (see SourceMir.lean). -/ + +namespace SolidCore.Spec.UniswapV2.ERC20.SourceMir + +open SolidCore.Refinement SolidCore.Refinement.Generic + +kernel_rfl check_eq check? true using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + + +theorem check_ok {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Generic.check SolidCore.Verify.VC.UniswapV2ERC20.fuel mirFuel c.core + SolarTV.Export.UniswapV2ERC20.stage0 fns .all = true := by + have h := check_eq + simp only [check?, checkOf, hc] at h + exact h + +end SolidCore.Spec.UniswapV2.ERC20.SourceMir diff --git a/Contracts/UniswapV2/ERC20/SourceMirDefs.lean b/Contracts/UniswapV2/ERC20/SourceMirDefs.lean new file mode 100644 index 00000000..43cc02f6 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/SourceMirDefs.lean @@ -0,0 +1,41 @@ +import Contracts.UniswapV2.ERC20.Core +import Contracts.UniswapV2.ERC20.SpecTreeKeccak +import SolidCore.Refinement.Generic.Stage +import uv2_erc20.gen.UniswapV2ERC20.Stage0 + +/-! The definitions of E3 for UniswapV2ERC20.transfer (SourceMir.lean): the functions, the deployed +storage and the checks the kernel evaluates in SourceMirCheck and SourceMirDeploy, one module each +so that each Lean process stays within 6 GB. -/ + +namespace SolidCore.Spec.UniswapV2.ERC20.SourceMir + +open SolidCore.Refinement SolidCore.Refinement.Generic + +/-- The steps along each path of the symbolic run of the module. -/ +def mirFuel : Nat := 200 + +/-- `transfer(address,uint256)` as the stage's ABI sees it: its selector and two words. -/ +def fn_transfer : Abi.Fn := ⟨2835717307, List.replicate 2 (.uint 256)⟩ + +/-- The functions of the stage. -/ +def fns : List Abi.Fn := [fn_transfer] + +/-- The storage the constructor leaves: `DOMAIN_SEPARATOR` (slot 3), the EIP-712 domain hash. -/ +def deployed : List (Nat × Nat) := [(3, SolidCore.Spec.UniswapV2.ERC20.Keccak.kDomain)] + +/-- Whether the generic check accepts `m` for `fns`, with the caller and Keccak-256 flags. -/ +def checkOf (m : SolarTV.MIR.Lowered.Module) : Bool := + match SolidCore.Verify.VC.UniswapV2ERC20.contract? with + | .ok c => Generic.check SolidCore.Verify.VC.UniswapV2ERC20.fuel mirFuel c.core m fns .all + | .error _ => false + +/-- Whether the generic check accepts stage0. -/ +def check? : Bool := checkOf SolarTV.Export.UniswapV2ERC20.stage0 + +/-- Whether the contract deploys with `deployed` and no logs. -/ +def deploy? : Bool := + match SolidCore.Verify.VC.UniswapV2ERC20.contract? with + | .ok c => Wide.deployedAt SolidCore.Verify.VC.UniswapV2ERC20.fuel c deployed + | .error _ => false + +end SolidCore.Spec.UniswapV2.ERC20.SourceMir diff --git a/Contracts/UniswapV2/ERC20/SourceMirDeploy.lean b/Contracts/UniswapV2/ERC20/SourceMirDeploy.lean new file mode 100644 index 00000000..6b7a61e8 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/SourceMirDeploy.lean @@ -0,0 +1,13 @@ +import Contracts.UniswapV2.ERC20.SourceMirDefs + +/-! The kernel's evaluation of UniswapV2ERC20's deployment: the constructor leaves exactly +`deployed` and no logs (see SourceMir.lean). -/ + +namespace SolidCore.Spec.UniswapV2.ERC20.SourceMirDeploy + +open SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Spec.UniswapV2.ERC20.SourceMir + +kernel_rfl deploy_eq deploy? true using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + + +end SolidCore.Spec.UniswapV2.ERC20.SourceMirDeploy diff --git a/Contracts/UniswapV2/ERC20/SourceMirFrom.lean b/Contracts/UniswapV2/ERC20/SourceMirFrom.lean new file mode 100644 index 00000000..3612283b --- /dev/null +++ b/Contracts/UniswapV2/ERC20/SourceMirFrom.lean @@ -0,0 +1,87 @@ +import Contracts.UniswapV2.ERC20.SourceMirFromCheck +import Contracts.UniswapV2.ERC20.SourceMirDeploy +import Verify.ShapeCtx + +/-! +# UniswapV2ERC20.transfer from every caller: SolidCore's checked source to solar's first lowered MIR (E3) + +`SourceMir.transfer_stage` fixes the caller (SolidCore's `callerAddress`, 0x2000). This module states +E3 for **every caller** `a < 2 ^ 160`, proved once by the generic checker with the caller a symbolic +word (`Generic.checkSym`, `Generic.stageFrom`), not per address: + +* `checkFrom_eq` (`kernel_rfl`): the kernel evaluates `Generic.checkSym` of stage0 for `[fn_transfer]` + to `true`. The source side erases `msg.sender` to `WExpr.caller`, knowing only that it fits in 160 + bits; the MIR side reads `CALLER` as the same word (`EnvFlags.allSym`). +* `transfer_stage_from`: for every `a < 2 ^ 160` and every oracle `o` with `FromOk a o` (its caller is `a` + and its Keccak-256 of two words is SolidCore's slot hash, i.e. Keccak-256), the stage + `Stage (solidCoreFrom a fuel) (moduleSem o) c stage0 (genericValid0 fns deployed)`: on every valid call, + sent by `a`, solar's first lowered MIR shows what SolidCore's checked source shows (status, return + data, revert data, storage, logs). +* `fromOk_inhabited`: for every `a < 2 ^ 160` an oracle meets `FromOk a` (EthLib's Keccak-256 with caller + `a`), so no case of the statement is vacuous. +* `transfer_source_mir_any_caller`: the closed statement. `transfer_stage_callerAddress`: its instance at + `callerAddress` is the fixed-caller stage of `SourceMir` (`solidCoreFrom callerAddress = solidCore`). + +`Source.runFrom a` is SolidCore's run of a call sent by `a` to the contract as `callerAddress` deployed +it (the constructor's caller is unchanged; transfer's constructor storage is `deployed`). No hash +separation premise: both sides compute the same mapping slots, so none is assumed. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.SourceMirFrom + +open SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Refinement.Shapes +open SolidCore.Spec.UniswapV2.ERC20.SourceMir + +/-- **E3 for transfer, from every caller.** -/ +theorem transfer_stage_from (a : Nat) (ha : a < 2 ^ 160) (o : SolarTV.Machine.Oracle) (ho : FromOk a o) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + SolarTV.Stage (solidCoreFrom a SolidCore.Verify.VC.UniswapV2ERC20.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.UniswapV2ERC20.stage0 (genericValid0 fns deployed) := by + have hdep := SolidCore.Spec.UniswapV2.ERC20.SourceMirDeploy.deploy_eq + simp only [deploy?, hc] at hdep + obtain ⟨_, hdd⟩ := Wide.deployedAt_of hdep + exact stageFrom a ha o ho hdd (checkFrom_ok hc) + +/-- The oracle of caller `a`: EthLib's Keccak-256, and `a` as `CALLER`. -/ +def oracleFrom (a : Nat) : SolarTV.Machine.Oracle := + { Solar.Assemble.ethOracle ⟨fun _ _ _ => 0, fun _ => 0, fun _ _ => 0, fun _ _ => 0, fun _ => 0, 0⟩ with + caller := BitVec.ofNat 160 a } + +/-- For every caller the premise is satisfiable. -/ +theorem fromOk_inhabited (a : Nat) (ha : a < 2 ^ 160) : FromOk a (oracleFrom a) := + ⟨by + have : a < 1461501637330902918203684832716283019655932542976 := ha + simp [oracleFrom]; omega, + fun x y _ _ => SolidCore.Refinement.Keccak.ethKeccak_twoWords x y⟩ + +/-- **The edge, closed, for every caller**: the checked contract exists and E3 holds of it from every +caller `a < 2 ^ 160` under every oracle with `FromOk a`; for every such caller the premise is met, and +the valid calls are inhabited. -/ +theorem transfer_source_mir_any_caller : + (∃ c, SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c ∧ + ∀ a, a < 2 ^ 160 → ∀ o, FromOk a o → + SolarTV.Stage (solidCoreFrom a SolidCore.Verify.VC.UniswapV2ERC20.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.UniswapV2ERC20.stage0 (genericValid0 fns deployed)) ∧ + (∀ a, a < 2 ^ 160 → ∃ o, FromOk a o) ∧ (∃ call, genericValid0 fns deployed call) := by + obtain ⟨c, hc⟩ := SolidCore.Verify.VC.UniswapV2ERC20.contract_ok + exact ⟨⟨c, hc, fun a ha o h => transfer_stage_from a ha o h hc⟩, + fun a ha => ⟨oracleFrom a, fromOk_inhabited a ha⟩, genericValid0_inhabited fn_transfer [] deployed⟩ + +/-- At `callerAddress` the statement is the fixed-caller stage (on the oracles with that caller). -/ +theorem transfer_stage_callerAddress (o : SolarTV.Machine.Oracle) (ho : FromOk callerAddress o) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + SolarTV.Stage (solidCore SolidCore.Verify.VC.UniswapV2ERC20.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.UniswapV2ERC20.stage0 (genericValid0 fns deployed) := by + exact transfer_stage_from callerAddress (by decide) o ho hc + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.SourceMirFrom.transfer_source_mir_any_caller' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms transfer_source_mir_any_caller + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.SourceMirFrom.transfer_stage_from' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms transfer_stage_from + +end SolidCore.Spec.UniswapV2.ERC20.SourceMirFrom diff --git a/Contracts/UniswapV2/ERC20/SourceMirFromCheck.lean b/Contracts/UniswapV2/ERC20/SourceMirFromCheck.lean new file mode 100644 index 00000000..ebf3c837 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/SourceMirFromCheck.lean @@ -0,0 +1,20 @@ +import Contracts.UniswapV2.ERC20.SourceMirFromDefs + +/-! The kernel's evaluation of the generic check of stage0 for transfer with the symbolic caller +(see SourceMirFrom.lean). -/ + +namespace SolidCore.Spec.UniswapV2.ERC20.SourceMirFrom + +open SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Spec.UniswapV2.ERC20.SourceMir + +kernel_rfl checkFrom_eq checkFrom? true using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +theorem checkFrom_ok {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) : + Generic.checkSym SolidCore.Verify.VC.UniswapV2ERC20.fuel mirFuel c.core + SolarTV.Export.UniswapV2ERC20.stage0 fns = true := by + have h := checkFrom_eq + simp only [checkFrom?, checkFromOf, hc] at h + exact h + +end SolidCore.Spec.UniswapV2.ERC20.SourceMirFrom diff --git a/Contracts/UniswapV2/ERC20/SourceMirFromDefs.lean b/Contracts/UniswapV2/ERC20/SourceMirFromDefs.lean new file mode 100644 index 00000000..979a9349 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/SourceMirFromDefs.lean @@ -0,0 +1,20 @@ +import Contracts.UniswapV2.ERC20.SourceMirDefs +import SolidCore.Refinement.Generic.StageFrom + +/-! The definitions of E3 for UniswapV2ERC20.transfer from every caller (SourceMirFrom.lean): the +check with the symbolic caller, which SourceMirFromCheck evaluates in the kernel. -/ + +namespace SolidCore.Spec.UniswapV2.ERC20.SourceMirFrom + +open SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Spec.UniswapV2.ERC20.SourceMir + +/-- Whether the generic check with the symbolic caller accepts `m` for transfer. -/ +def checkFromOf (m : SolarTV.MIR.Lowered.Module) : Bool := + match SolidCore.Verify.VC.UniswapV2ERC20.contract? with + | .ok c => Generic.checkSym SolidCore.Verify.VC.UniswapV2ERC20.fuel mirFuel c.core m fns + | .error _ => false + +/-- Whether it accepts stage0. -/ +def checkFrom? : Bool := checkFromOf SolarTV.Export.UniswapV2ERC20.stage0 + +end SolidCore.Spec.UniswapV2.ERC20.SourceMirFrom diff --git a/Contracts/UniswapV2/ERC20/SourceMirFromNeg.lean b/Contracts/UniswapV2/ERC20/SourceMirFromNeg.lean new file mode 100644 index 00000000..80b8a8b0 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/SourceMirFromNeg.lean @@ -0,0 +1,73 @@ +import Contracts.UniswapV2.ERC20.SourceMirFromDefs +import uv2_erc20.gen.UniswapV2ERC20Mut.NoDebit +import uv2_erc20.gen.UniswapV2ERC20Mut.WrongSlot +import uv2_erc20.gen.UniswapV2ERC20Mut.NoOverflowCheck +import uv2_erc20.gen.UniswapV2ERC20Mut.NoUnderflowCheck +import uv2_erc20.gen.UniswapV2ERC20Mut.WrongTopic +import uv2_erc20.gen.UniswapV2ERC20Mut.WrongReturn +import uv2_erc20.gen.UniswapV2ERC20Mut.WrongRevertData +import uv2_erc20.gen.UniswapV2ERC20Mut.SwappedLogArgs +import uv2_erc20.gen.UniswapV2ERC20Mut.PinnedCaller + +/-! +# Negative controls of E3 for transfer from every caller + +The kernel evaluates `Generic.checkSym` (the check with the symbolic caller) of each stage0 mutant of +scripts/verify/uniswap_v2_erc20_mutants.py, against the same checked source, to `false`. + +`PinnedCaller` replaces transfer's `CALLER` with the constant `0x2000` (`callerAddress`): code that is +right only when the caller is `callerAddress`. The fixed-caller check (`SourceMir.checkOf`, which +erases `msg.sender` to that same constant) **accepts** it (`pinned_fixed_accepts`), and the check for +every caller refuses it (`refuses_PinnedCaller`): the generalisation is not vacuous. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.SourceMirFromNeg + +open SolidCore.Spec.UniswapV2.ERC20.SourceMirFrom + +/-- The check for every caller refuses the mutant `NoDebit`. -/ +def NoDebit? : Bool := checkFromOf SolarTV.Export.UniswapV2ERC20Mut.NoDebit.stage0 + +kernel_rfl refuses_NoDebit NoDebit? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +/-- The check for every caller refuses the mutant `WrongSlot`. -/ +def WrongSlot? : Bool := checkFromOf SolarTV.Export.UniswapV2ERC20Mut.WrongSlot.stage0 + +kernel_rfl refuses_WrongSlot WrongSlot? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +/-- The check for every caller refuses the mutant `NoOverflowCheck`. -/ +def NoOverflowCheck? : Bool := checkFromOf SolarTV.Export.UniswapV2ERC20Mut.NoOverflowCheck.stage0 + +kernel_rfl refuses_NoOverflowCheck NoOverflowCheck? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +/-- The check for every caller refuses the mutant `NoUnderflowCheck`. -/ +def NoUnderflowCheck? : Bool := checkFromOf SolarTV.Export.UniswapV2ERC20Mut.NoUnderflowCheck.stage0 + +kernel_rfl refuses_NoUnderflowCheck NoUnderflowCheck? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +/-- The check for every caller refuses the mutant `WrongTopic`. -/ +def WrongTopic? : Bool := checkFromOf SolarTV.Export.UniswapV2ERC20Mut.WrongTopic.stage0 + +kernel_rfl refuses_WrongTopic WrongTopic? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +/-- The check for every caller refuses the mutant `WrongReturn`. -/ +def WrongReturn? : Bool := checkFromOf SolarTV.Export.UniswapV2ERC20Mut.WrongReturn.stage0 + +kernel_rfl refuses_WrongReturn WrongReturn? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +/-- The check for every caller refuses the mutant `WrongRevertData`. -/ +def WrongRevertData? : Bool := checkFromOf SolarTV.Export.UniswapV2ERC20Mut.WrongRevertData.stage0 + +kernel_rfl refuses_WrongRevertData WrongRevertData? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +/-- The check for every caller refuses the mutant `SwappedLogArgs`. -/ +def SwappedLogArgs? : Bool := checkFromOf SolarTV.Export.UniswapV2ERC20Mut.SwappedLogArgs.stage0 + +kernel_rfl refuses_SwappedLogArgs SwappedLogArgs? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +/-- The check for every caller refuses the mutant `PinnedCaller`. -/ +def PinnedCaller? : Bool := checkFromOf SolarTV.Export.UniswapV2ERC20Mut.PinnedCaller.stage0 + +kernel_rfl refuses_PinnedCaller PinnedCaller? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +end SolidCore.Spec.UniswapV2.ERC20.SourceMirFromNeg diff --git a/Contracts/UniswapV2/ERC20/SourceMirNeg.lean b/Contracts/UniswapV2/ERC20/SourceMirNeg.lean new file mode 100644 index 00000000..fa118ac7 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/SourceMirNeg.lean @@ -0,0 +1,67 @@ +import Contracts.UniswapV2.ERC20.SourceMirDefs +import uv2_erc20.gen.UniswapV2ERC20Mut.NoDebit +import uv2_erc20.gen.UniswapV2ERC20Mut.WrongSlot +import uv2_erc20.gen.UniswapV2ERC20Mut.NoOverflowCheck +import uv2_erc20.gen.UniswapV2ERC20Mut.NoUnderflowCheck +import uv2_erc20.gen.UniswapV2ERC20Mut.WrongTopic +import uv2_erc20.gen.UniswapV2ERC20Mut.WrongReturn +import uv2_erc20.gen.UniswapV2ERC20Mut.WrongRevertData +import uv2_erc20.gen.UniswapV2ERC20Mut.SwappedLogArgs + +/-! +# Negative controls of E3 for transfer: mutated MIR refused by the kernel's evaluation + +Each mutant is solar's exported stage0 with one instruction of `transfer`, `_transfer` or SafeMath's +`sub` edited (scripts/verify/uniswap_v2_erc20_mutants.py, which fails if an edit does not apply), +and the kernel evaluates the same generic check of it, against the same checked source, to `false`: +the check that accepts stage0 (`SourceMir.check_eq`) does not accept a debit dropped, a wrong +mapping slot, either overflow test reversed, a wrong event topic, swapped topic arguments, a wrong +return value or wrong revert data. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.SourceMirNeg + +open SolidCore.Spec.UniswapV2.ERC20.SourceMir + +/-- The check refuses the mutant `NoDebit`. -/ +def NoDebit? : Bool := checkOf SolarTV.Export.UniswapV2ERC20Mut.NoDebit.stage0 + +kernel_rfl refuses_NoDebit NoDebit? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +/-- The check refuses the mutant `WrongSlot`. -/ +def WrongSlot? : Bool := checkOf SolarTV.Export.UniswapV2ERC20Mut.WrongSlot.stage0 + +kernel_rfl refuses_WrongSlot WrongSlot? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +/-- The check refuses the mutant `NoOverflowCheck`. -/ +def NoOverflowCheck? : Bool := checkOf SolarTV.Export.UniswapV2ERC20Mut.NoOverflowCheck.stage0 + +kernel_rfl refuses_NoOverflowCheck NoOverflowCheck? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +/-- The check refuses the mutant `NoUnderflowCheck`. -/ +def NoUnderflowCheck? : Bool := checkOf SolarTV.Export.UniswapV2ERC20Mut.NoUnderflowCheck.stage0 + +kernel_rfl refuses_NoUnderflowCheck NoUnderflowCheck? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +/-- The check refuses the mutant `WrongTopic`. -/ +def WrongTopic? : Bool := checkOf SolarTV.Export.UniswapV2ERC20Mut.WrongTopic.stage0 + +kernel_rfl refuses_WrongTopic WrongTopic? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +/-- The check refuses the mutant `WrongReturn`. -/ +def WrongReturn? : Bool := checkOf SolarTV.Export.UniswapV2ERC20Mut.WrongReturn.stage0 + +kernel_rfl refuses_WrongReturn WrongReturn? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +/-- The check refuses the mutant `WrongRevertData`. -/ +def WrongRevertData? : Bool := checkOf SolarTV.Export.UniswapV2ERC20Mut.WrongRevertData.stage0 + +kernel_rfl refuses_WrongRevertData WrongRevertData? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +/-- The check refuses the mutant `SwappedLogArgs`. -/ +def SwappedLogArgs? : Bool := checkOf SolarTV.Export.UniswapV2ERC20Mut.SwappedLogArgs.stage0 + +kernel_rfl refuses_SwappedLogArgs SwappedLogArgs? false using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +end SolidCore.Spec.UniswapV2.ERC20.SourceMirNeg + diff --git a/Contracts/UniswapV2/ERC20/SourceMirPinned.lean b/Contracts/UniswapV2/ERC20/SourceMirPinned.lean new file mode 100644 index 00000000..d35772dc --- /dev/null +++ b/Contracts/UniswapV2/ERC20/SourceMirPinned.lean @@ -0,0 +1,17 @@ +import Contracts.UniswapV2.ERC20.SourceMirDefs +import uv2_erc20.gen.UniswapV2ERC20Mut.PinnedCaller + +/-! The fixed-caller check accepts `PinnedCaller` (stage0 with `CALLER` replaced by `0x2000`): a stage +for one caller does not tell such code apart; `SourceMirFromNeg.refuses_PinnedCaller` shows the check +for every caller does. -/ + +namespace SolidCore.Spec.UniswapV2.ERC20.SourceMirPinned + +open SolidCore.Spec.UniswapV2.ERC20.SourceMir + +/-- The fixed-caller check of `PinnedCaller`. -/ +def pinnedFixed? : Bool := checkOf SolarTV.Export.UniswapV2ERC20Mut.PinnedCaller.stage0 + +kernel_rfl pinned_fixed_accepts pinnedFixed? true using SolidCore.Verify.VC.UniswapV2ERC20.selector_eq SolidCore.Verify.VC.mkIdx_eq SolidCore.Verify.VC.UniswapV2ERC20.digest_eq SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq + +end SolidCore.Spec.UniswapV2.ERC20.SourceMirPinned diff --git a/Contracts/UniswapV2/ERC20/SpecTree.lean b/Contracts/UniswapV2/ERC20/SpecTree.lean new file mode 100644 index 00000000..a0177a77 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/SpecTree.lean @@ -0,0 +1,49 @@ +import Contracts.UniswapV2.ERC20.Meets + +/-! +# UniswapV2ERC20: solar-verify's exported specs of SolidCore's checked contract + +The statement this lane delivers, for the functions the generic source stage erases with a spec +proved of their tree (`approve` and `transfer`): solar-verify's exported spec of each holds of SolidCore's +checked UniswapV2ERC20 (`contract? = .ok c`, the kernel's type check and translation of the port, +`Contracts.UniswapV2.ERC20.Core`) on the stage's calls of it (any argument words, no value, any storage +covering the deployed one), in every world `W` (the functions call out nowhere), under two named +hypotheses: + +* `NestedSlotsSeparated [1, 4] [2]`: keccak256 separated on the slots of `balanceOf[a]`, `nonces[a]` and + `allowance[o][s]` (injective, images at least `2 ^ 128`); not provable of keccak256, so a premise; +* the ghost step leaves the ghost state (`sumBalances`, `zeroMinted`) alone on these calls: the spec + updates the ghosts only in `_mint` and `_burn`, which neither function reaches. + +Scope: runtime calls of `approve` and `transfer` from the stage's caller (`0x2000`) with no value; the +constructor is covered only through the deployed storage it leaves (`deploy_eq`). Not covered here: +`transferFrom` (tree erased; its spec of the tree is pending), `permit` (outside the generic stage: +keccak256 of memory and the ECRECOVER call), and the bytecode side (the stages from SolidCore to +solar's bytecode for UniswapV2ERC20 are not yet built), so this is a source-level spec result, not +an end-to-end one. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20 + +open SolidCore.Spec SolidCore.Refinement + +/-- **approve's and transfer's exported specs hold of SolidCore's checked UniswapV2ERC20 in every +world**, under keccak256's separation on the mapping slots and a ghost step that leaves the ghosts +alone on these calls. -/ +theorem specs_hold_in (W : SolidCore.Refinement.World) (hsep : NestedSlotsSeparated [1, 4] [2]) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : SolidCore.Verify.VC.UniswapV2ERC20.contract? = .ok c) (step : GhostStep) + (hstep : ∀ fn ∈ [fn_approve, fn_transfer], ∀ call, + SolidCore.Verify.VC.stageScope fn deployed call → ∀ g, step call g = g) : + HoldsFn (solidCoreIn W SolidCore.Verify.VC.UniswapV2ERC20.fuel) c + (SolidCore.Verify.VC.stageScope fn_approve deployed) spec ctxOf step approve_spec ∧ + HoldsFn (solidCoreIn W SolidCore.Verify.VC.UniswapV2ERC20.fuel) c + (SolidCore.Verify.VC.stageScope fn_transfer deployed) spec ctxOf step transfer_spec := + ⟨approve_holds_in W hsep hc step (hstep _ (by simp)), + transfer_holds_in W hsep hc step (hstep _ (by simp))⟩ + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.specs_hold_in' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms specs_hold_in + +end SolidCore.Spec.UniswapV2.ERC20 diff --git a/Contracts/UniswapV2/ERC20/SpecTreeKeccak.lean b/Contracts/UniswapV2/ERC20/SpecTreeKeccak.lean new file mode 100644 index 00000000..0fac5802 --- /dev/null +++ b/Contracts/UniswapV2/ERC20/SpecTreeKeccak.lean @@ -0,0 +1,77 @@ +import SolidCore.Solidity.Interpreter +import SolidCore.Refinement.KernelRfl + +/-! +# The constructor's Keccak-256 hashes of UniswapV2ERC20, by table + +UniswapV2ERC20's constructor sets `DOMAIN_SEPARATOR` to the EIP-712 domain hash: Keccak-256 of the +domain type string, of the name `Uniswap V2`, of the version `1`, and of the ABI encoding of the three +with the chain ID (0 in SolidCore's closed deployment context) and the contract's address +(`selfAddress`). The kernel's evaluation of one hash costs about 400 MB, so each is checked once, +in its own declaration (`kernel_rfl`), and `keccakWord_eq` replaces SolidCore's `keccakWord` by a +table of the four, which a `kernel_rfl` of the deployment takes with `using`, as the cores take +`selector_eq`. Every other input is hashed as before. +-/ + +namespace SolidCore.Spec.UniswapV2.ERC20.Keccak + +open SolidCore.Solidity SolidCore.Solidity.Source + +/-- The UTF-8 bytes of a string. -/ +def sb (s : String) : List Nat := s.toUTF8.toList.map (·.toNat) + +/-- The EIP-712 domain type string. -/ +def domainType : List Nat := + sb "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" +def nameBytes : List Nat := sb "Uniswap V2" +def versionBytes : List Nat := sb "1" + +abbrev kDomainType : Nat := 63076024560530113402979550242307453568063438748328787417531900361828837441551 +abbrev kName : Nat := 86753177656789946143617852270382413483605072673293953774383968070347263481656 +abbrev kVersion : Nat := 90743482286830539503240959006302832933333810038750515972785732718729991261126 + +/-- The ABI encoding the constructor hashes: the three hashes, the chain ID 0 and the address. -/ +def domainBytes : List Nat := + storageWordBytes kDomainType ++ storageWordBytes kName ++ storageWordBytes kVersion ++ + storageWordBytes 0 ++ storageWordBytes 0x1000 + +abbrev kDomain : Nat := 78390027508550153555773896992835392567232765649225488394068785439274740276969 + +def hDomainType : Nat := keccakWord domainType +kernel_rfl hDomainType_eq hDomainType kDomainType +def hName : Nat := keccakWord nameBytes +kernel_rfl hName_eq hName kName +def hVersion : Nat := keccakWord versionBytes +kernel_rfl hVersion_eq hVersion kVersion +def hDomain : Nat := keccakWord domainBytes +kernel_rfl hDomain_eq hDomain kDomain + +/-- `keccakWord`, with the constructor's four hashes by table. -/ +def keccakTable (bs : List Nat) : Nat := + if bs = domainType then kDomainType + else if bs = nameBytes then kName + else if bs = versionBytes then kVersion + else if bs = domainBytes then kDomain + else keccakWord bs + +theorem keccakWord_eq : keccakWord = keccakTable := by + funext bs + unfold keccakTable + by_cases h0 : bs = domainType + · rw [if_pos h0, h0]; exact hDomainType_eq + rw [if_neg h0] + by_cases h1 : bs = nameBytes + · rw [if_pos h1, h1]; exact hName_eq + rw [if_neg h1] + by_cases h2 : bs = versionBytes + · rw [if_pos h2, h2]; exact hVersion_eq + rw [if_neg h2] + by_cases h3 : bs = domainBytes + · rw [if_pos h3, h3]; exact hDomain_eq + rw [if_neg h3] + +/-- info: 'SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms keccakWord_eq + +end SolidCore.Spec.UniswapV2.ERC20.Keccak diff --git a/Contracts/UniswapV2/Factory/Create2.lean b/Contracts/UniswapV2/Factory/Create2.lean new file mode 100644 index 00000000..1933f4ad --- /dev/null +++ b/Contracts/UniswapV2/Factory/Create2.lean @@ -0,0 +1,126 @@ +import EthLib.Execution.Evm.Call.ContractAddress +import EthLib.Base.Proofs.U256 + +/-! +# CREATE2 addresses under a modelled hash + +The address of the pair `UniswapV2Factory.createPair` deploys is EIP-1014's: the last 20 bytes of the +hash of `0xff ++ factory ++ salt ++ hash(initCode)`, with `salt = hash(token0 ++ token1)` (the 40 +bytes of `abi.encodePacked(token0, token1)`). EthLib computes it with its Keccak-256 +(`EthLib.Execution.Evm.create2Address`), which `create2Address_eq` restates over any hash `H`. + +Keccak-256 is modelled as hevm and Certora do: an uninterpreted function with named assumptions. +`KeccakModel H xs` says `H` has no collision on the finite list `xs` of inputs a statement uses, in +the whole digest and in its last 20 bytes (the address). It is stated over a finite list on purpose: +injectivity on every input, or on every input of one length above 32 bytes, is refuted by counting +for Keccak-256 itself, so a statement assuming it of the real hash would hold vacuously. Over a +finite list the premise is consistent with the real hash (it is what "no collision among the hashes +this run computes" means) and stays a premise: nothing here proves it of Keccak-256. + +Proved: two pairs created by the same factory from the same init code at the same address were +created for the same ordered tokens (`pair_inj`), and the address is a function of the sorted tokens +(`pairAddr_comm`), so creating (A, B) and (B, A) name one pair. +-/ + +namespace Contracts.UniswapV2.Factory.Create2 + +open EthLib.Base EthLib.Execution.Evm + +/-- A 32-byte hash function. -/ +abbrev Hash := ByteArray → Vector UInt8 32 + +/-- EIP-1014's address under a hash `H`. -/ +def create2AddrH (H : Hash) (sender : Address) (salt : U256) (init : ByteArray) : Address := + addressOfHash (H (create2Preimage sender salt (H init))) + +/-- EthLib's CREATE2 address is the model's at EthLib's Keccak-256. -/ +theorem create2Address_eq (sender : Address) (salt : U256) (init : ByteArray) : + create2Address sender salt init = + create2AddrH EthLib.Cryptography.Hash.Keccak.keccak256 sender salt init := rfl + +/-- **The hash model** (one named premise): no collision of `H` on the inputs `xs`, in the digest +and in its address bytes. -/ +structure KeccakModel (H : Hash) (xs : List ByteArray) : Prop where + inj : ∀ a ∈ xs, ∀ b ∈ xs, H a = H b → a = b + addrInj : ∀ a ∈ xs, ∀ b ∈ xs, addressOfHash (H a) = addressOfHash (H b) → a = b + +/-- `abi.encodePacked(token0, token1)`: the 40 bytes of two addresses. -/ +def packed (t0 t1 : Address) : ByteArray := ⟨t0.toArray⟩ ++ ⟨t1.toArray⟩ + +/-- The salt of `createPair`: the hash of the packed tokens, as a word. -/ +def saltOf (H : Hash) (t0 t1 : Address) : U256 := U256.fromBeBytes (H (packed t0 t1)) + +/-- The pair's address: CREATE2 from the factory with the pair's salt and init code. -/ +def pairAddr (H : Hash) (factory : Address) (init : ByteArray) (t0 t1 : Address) : Address := + create2AddrH H factory (saltOf H t0 t1) init + +/-- The inputs whose hashes `createPair` of `(t0, t1)` computes: the packed tokens and the +CREATE2 preimage (the init code's hash is shared by every pair). -/ +def inputs (H : Hash) (factory : Address) (init : ByteArray) (t0 t1 : Address) : List ByteArray := + [packed t0 t1, create2Preimage factory (saltOf H t0 t1) (H init)] + +theorem toList_data_mk (v : Array UInt8) : (ByteArray.mk v).data.toList = v.toList := rfl + +/-- The list of bytes of a CREATE2 preimage. -/ +theorem preimage_toList (sender : Address) (salt : U256) (h : Vector UInt8 32) : + (create2Preimage sender salt h).data.toList = + [0xff] ++ sender.toList ++ (U256.toBeBytes salt).toList ++ h.toList := by + simp [create2Preimage, Vector.toList] + +/-- The preimage determines the salt. -/ +theorem salt_of_preimage {sender : Address} {s1 s2 : U256} {h : Vector UInt8 32} + (he : create2Preimage sender s1 h = create2Preimage sender s2 h) : s1 = s2 := by + have hl := congrArg (fun b : ByteArray => b.data.toList) he + simp only [preimage_toList] at hl + have h1 : (U256.toBeBytes s1).toList = (U256.toBeBytes s2).toList := by + have := List.append_cancel_right hl + simpa [List.append_assoc] using this + exact U256.toBeBytes_inj (Vector.toList_inj.mp h1) + +/-- The packed tokens determine the tokens. -/ +theorem tokens_of_packed {a0 a1 b0 b1 : Address} (he : packed a0 a1 = packed b0 b1) : + a0 = b0 ∧ a1 = b1 := by + have hl := congrArg (fun b : ByteArray => b.data.toList) he + simp only [packed, ByteArray.toList_data_append] at hl + have hlen : a0.toArray.toList.length = b0.toArray.toList.length := by simp + obtain ⟨h0, h1⟩ := List.append_inj hl hlen + exact ⟨Vector.toArray_inj.mp (Array.toList_inj.mp h0), Vector.toArray_inj.mp (Array.toList_inj.mp h1)⟩ + +/-- **One address, one pair**: under the hash model on the inputs of both creations, two pairs the +same factory creates from the same init code at the same address have the same ordered tokens. -/ +theorem pair_inj {H : Hash} {factory : Address} {init : ByteArray} {a0 a1 b0 b1 : Address} + (hm : KeccakModel H (inputs H factory init a0 a1 ++ inputs H factory init b0 b1)) + (he : pairAddr H factory init a0 a1 = pairAddr H factory init b0 b1) : a0 = b0 ∧ a1 = b1 := by + have hpre := hm.addrInj _ (by simp [inputs]) _ (by simp [inputs]) he + have hs := salt_of_preimage hpre + have hh : H (packed a0 a1) = H (packed b0 b1) := by + have := congrArg U256.toBeBytes hs + simpa [saltOf, U256.toBeBytes_fromBeBytes] using this + exact tokens_of_packed (hm.inj _ (by simp [inputs]) _ (by simp [inputs]) hh) + +/-- The ordered tokens of `createPair(tokenA, tokenB)`: the smaller address first. -/ +def sortTokens (a b : Address) : Address × Address := + if a.toU256 < b.toU256 then (a, b) else (b, a) + +/-- `createPair(A, B)` and `createPair(B, A)` derive one address when `A ≠ B`. -/ +theorem pairAddr_comm (H : Hash) (factory : Address) (init : ByteArray) {a b : Address} + (hab : a.toU256 ≠ b.toU256) : + pairAddr H factory init (sortTokens a b).1 (sortTokens a b).2 = + pairAddr H factory init (sortTokens b a).1 (sortTokens b a).2 := by + unfold sortTokens + have hne : a.toU256.toNat ≠ b.toU256.toNat := fun h => hab (BitVec.eq_of_toNat_eq h) + by_cases h1 : a.toU256 < b.toU256 + · have h2 : ¬ b.toU256 < a.toU256 := by + rw [BitVec.lt_def] at h1 ⊢ + omega + simp [h1, h2] + · have h2 : b.toU256 < a.toU256 := by + rw [BitVec.lt_def] at h1 ⊢ + omega + simp [h1, h2] + +/-- info: 'Contracts.UniswapV2.Factory.Create2.pair_inj' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms pair_inj + +end Contracts.UniswapV2.Factory.Create2 diff --git a/Contracts/UniswapV2/Factory/Create2Run.lean b/Contracts/UniswapV2/Factory/Create2Run.lean new file mode 100644 index 00000000..94cbcc25 --- /dev/null +++ b/Contracts/UniswapV2/Factory/Create2Run.lean @@ -0,0 +1,132 @@ +import Contracts.UniswapV2.Factory.Core + +/-! +# UniswapV2Factory.createPair in SolidCore's semantics: execution tests + +The frontend translates createPair's inline assembly +`pair := create2(0, add(bytecode, 32), mload(bytecode), salt)` to `Stmt.assemblyCreate2`, so +SolidCore's checked Factory (`contract_ok`, Core.lean) has createPair. Its run is one open-world +creation request, then the call of the new pair's `initialize`. Each `#guard` runs the checked +contract's `createPair(tokenA, tokenB)` with the context's Pair creation code (`initCode`, any +bytes: the semantics takes `type(UniswapV2Pair).creationCode` from the context, which a +certificate binds to the compiler's) and answers its requests: + +* the creation is CREATE2 from the factory, with the creation code as init code, value 0 and the + salt `keccak256(abi.encodePacked(token0, token1))` of the sorted tokens (`saltWord`, by + `cast keccak` of `0x…a1…b2`); the call is `initialize(token0, token1)` (selector `0x485cc955`) + to the new address; +* on success: both getPair entries and `allPairs[0]` hold the pair, `allPairs.length` is 1, one + `PairCreated(token0, token1, pair, 1)` is logged and the pair is returned; +* a failed creation (address 0) reverts with empty data: the call of `initialize` on an address + without code fails solc's code check (negative control: the run depends on the answer); +* identical tokens revert before any request (negative control). +-/ + +namespace SolidCore.Verify.VC.UniswapV2Factory.Create2Run +open SolidCore.Solidity SolidCore.Solidity.Source EvmCompiler.Simulation + +def initCode : List Nat := [0x60, 0x0a, 0x60, 0x0c, 0x60, 0x00, 0x39] +def factory : Nat := 0xfac +def tokenA : Nat := 0xb2 +def tokenB : Nat := 0xa1 +/-- `keccak256(abi.encodePacked(address(0xa1), address(0xb2)))`. -/ +def saltWord : Nat := 0x40574bd1d889509cb66f9e509f7097df8329f8630487c71851b8902c58e02ee9 +/-- `getPair[0xa1][0xb2]`, `getPair[0xb2][0xa1]` and `allPairs[0]` (slots 2 and 3). -/ +def slot01 : Nat := 108652669453705631790926710226022211974085131167983690354478284877256485211757 +def slot10 : Nat := 57201578420072540254588938014418563046356737943153306285054012880760464517709 +def slotAll0 : Nat := 87903029871075914254377627908054574944891091886930582284385770809450030037083 +/-- `PairCreated(address,address,address,uint256)`'s topic. -/ +def pairCreated : Nat := 5975978795871356409810236859912046109003452147125615103110369160851519754473 + +def context (c : TypeCheck.CheckedContract) : Context := + { c.core.context with + self := factory + sender := 0x5e + contractCreationCodes := [("UniswapV2Pair", initCode)] } + +def newAccount : OpenAccount := + { nonce := EvmYul.UInt256.ofNat 1 + balance := EvmYul.UInt256.ofNat 0 + storage := default + transientStorage := default + codeBytes := ⟨#[0]⟩ } + +/-- The answer to a creation: `a`, with an account with code there unless `a = 0`. -/ +def created (w : OpenWorld) (a : Nat) : CreateResponse := + { address := EvmYul.UInt256.ofNat a + returnData := default + postWorld := if a = 0 then w else { w with accounts := w.accounts.insert (wordToAddress a) newAccount } + returnedGas := EvmYul.UInt256.ofNat 0 } + +def called (w : OpenWorld) : CallResponse := + { success := true + returnData := default + postWorld := w + returnedGas := EvmYul.UInt256.ofNat 0 } + +/-- A request of a run. -/ +inductive Seen where + | create (kind : CreateKind) (creator value : Nat) (initCode : List Nat) (salt : Option Nat) + | call (target : Nat) (calldata : List Nat) + | other + deriving DecidableEq, Repr + +/-- The end of a run: the returned words, the values of the storage slots `probe` and the number +of slots written, and the events' topics and data words; or whether a revert's data is empty. -/ +inductive End where + | returned (words : List Nat) (slots : List (Option Nat)) (size : Nat) + (events : List (List Nat × List Nat)) + | reverted (empty : Bool) + | stuck + deriving DecidableEq, Repr + +def words (vs : List Value) : List Nat := vs.filterMap (fun v => v.expectWord.toOption) + +/-- The slots the tests read: getPair both ways, allPairs' length and first element, feeTo and +feeToSetter. -/ +def probe : List Nat := [slot01, slot10, 3, slotAll0, 0, 1] + +def run (a : Nat) : Nat → SolI CallResult → List Seen × End + | 0, _ => ([], .stuck) + | _, .done (.ok (.returned st vs)) => + ([], .returned (words vs) (probe.map st.storage.lookup?) st.storage.size + (st.events.map (fun e => (e.topics, words e.data)))) + | _, .done (.ok (.reverted _ d)) => ([], .reverted (match d with | .empty => true | _ => false)) + | _, .done (.error _) => ([], .stuck) + | n + 1, .request q k => + match q, k with + | .external w (.create r), k => + let (rs, e) := run a n (k (created w a)) + (.create r.kind (addressToWord r.creator) (u256ToWord r.value) (r.initCode.toList.map UInt8.toNat) + (r.salt.map u256ToWord) :: rs, e) + | .external w (.call r), k => + let (rs, e) := run a n (k (called w)) + (.call (addressToWord r.codeAddress) (r.calldata.toList.map UInt8.toNat) :: rs, e) + | _, _ => ([.other], .stuck) + +def createPair (t0 t1 a : Nat) : List Seen × End := + match contract? with + | .ok c => + match TypeCheck.CheckedContract.callFunctionWithContextTree fuel c "createPair" (context c) + State.empty [Value.word t0, Value.word t1] with + | some tree => run a 8 tree + | none => ([], .stuck) + | .error _ => ([], .stuck) + +def word (n : Nat) : List Nat := (List.range 32).reverse.map (fun i => n / 256 ^ i % 256) + +def creation : Seen := .create .create2 factory 0 initCode (some saltWord) + +#guard createPair tokenA tokenB 0xbeef == + ([creation, .call 0xbeef ([0x48, 0x5c, 0xc9, 0x55] ++ word 0xa1 ++ word 0xb2)], + .returned [0xbeef] [some 0xbeef, some 0xbeef, some 1, some 0xbeef, none, none] 4 + [([pairCreated, 0xa1, 0xb2], [0xbeef, 1])]) + +-- The salt is of the sorted tokens: createPair(B, A) asks the same creation. +#guard (createPair tokenB tokenA 0xbeef).1.head? == some creation + +#guard createPair tokenA tokenB 0 == ([creation], .reverted true) + +#guard (createPair tokenA tokenA 0xbeef).1 == [] + +end SolidCore.Verify.VC.UniswapV2Factory.Create2Run diff --git a/Contracts/UniswapV2/PairSpec/Axioms.lean b/Contracts/UniswapV2/PairSpec/Axioms.lean new file mode 100644 index 00000000..282cee55 --- /dev/null +++ b/Contracts/UniswapV2/PairSpec/Axioms.lean @@ -0,0 +1,95 @@ +import Contracts.UniswapV2.PairSpec.Negative +import Contracts.UniswapV2.PairSpec.NonVacuous + +/-! +# UniswapV2Pair statement: the axiom audit + +Every theorem of the pair's statement, wrapper, binding and negative controls, with the axioms the +kernel reports for it. The build fails if any gains an axiom (`#guard_msgs`): each is a subset of +propext, Classical.choice and Quot.sound; none uses sorry, native_decide or ofReduceBool. The +evaluated runs of Negative.lean (`#guard`) are not theorems and are not listed. +-/ + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.inhabited' depends on axioms: [propext] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.inhabited + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.published_of_stages' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.published_of_stages + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.bytecode_of_statement' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.bytecode_of_statement + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.nonVacuous' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.nonVacuous + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.bound' does not depend on any axioms -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.Negative.bound + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.alterJump_changes' depends on axioms: [propext] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.Negative.alterJump_changes + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.altered_not_bound' depends on axioms: [propext] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.Negative.altered_not_bound + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.swapCall_valid' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.Negative.swapCall_valid + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.pre_swap' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.Negative.pre_swap + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.pre_swapWrongK' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.Negative.pre_swapWrongK + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.noUpdate_refused' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.Negative.noUpdate_refused + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.wrongK_refused' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.Negative.wrongK_refused + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.k_accepts' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.Negative.k_accepts + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.zeroBalance_ge' depends on axioms: [propext] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.Negative.zeroBalance_ge + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.PairAllowanceApart.satisfiable' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.Negative.PairAllowanceApart.satisfiable + +/-- info: 'SolidCore.Refinement.Shapes.OpenFunctional.bytecode_any' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Refinement.Shapes.OpenFunctional.bytecode_any + +/-- info: 'SolidCore.Refinement.Shapes.OpenFunctional.of_parts' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Refinement.Shapes.OpenFunctional.of_parts + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.skimCall_valid' depends on axioms: [propext] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.Negative.skimCall_valid + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.pre_skim' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.Negative.pre_skim + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.skimUpdate_refused' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.Negative.skimUpdate_refused + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.syncNoop_accepted' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms SolidCore.Spec.UniswapV2.PairSpec.Negative.syncNoop_accepted diff --git a/Contracts/UniswapV2/PairSpec/Inputs.lean b/Contracts/UniswapV2/PairSpec/Inputs.lean new file mode 100644 index 00000000..52a43a3d --- /dev/null +++ b/Contracts/UniswapV2/PairSpec/Inputs.lean @@ -0,0 +1,116 @@ +import Verify.ShapeOpen +import Verify.Spec.TreeMapNested + +/-! +# UniswapV2Pair: the reviewed inputs of the published statement + +The valid calls, the admitted environments and worlds, the named premise, the allowed statuses +and the specification's call context and ghost step (Statement.lean says what each means). This +module imports neither the export nor any proof, so a driver-written statement can import it as a +spec module (tools/certify/final.py, kind open_functional). +-/ + +namespace SolidCore.Spec.UniswapV2.PairSpec + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Shapes + +/-! ## The calls -/ + +/-- `swap(uint256,uint256,address,bytes)`. -/ +abbrev swapSel : Nat := 0x022c0d9f +/-- `skim(address)`. -/ +abbrev skimSel : Nat := 0xbc25cf77 +/-- `sync()`. -/ +abbrev syncSel : Nat := 0xfff6cae9 + +/-- `n` as a 32-byte big-endian word. -/ +def word (n : Nat) : List Nat := (EthLib.Base.natToBytes 32 n).map (·.toNat) + +/-- The call data of `swap(a0, a1, to, data)` as solc's encoder writes it: the head, the offset +`0x80`, the length and the data padded to whole words. -/ +def swapData (a0 a1 dst : Nat) (data : List Nat) : List Nat := + (EthLib.Base.natToBytes 4 swapSel).map (·.toNat) ++ word a0 ++ word a1 ++ word dst ++ word 0x80 ++ + word data.length ++ data ++ List.replicate ((32 - data.length % 32) % 32) 0 + +/-- A call with call data `d` from the storage `σ`, without value. -/ +def mkCall (d : List Nat) (σ : List (Nat × Nat)) : Call := + { calldata := ⟨(d.map UInt8.ofNat).toArray⟩, callvalue := 0, storage := σ } + +/-- The valid calls of `swap`. -/ +def ValidSwap (call : Call) : Prop := + ∃ σ a0 a1 dst data, a0 < 2 ^ 256 ∧ a1 < 2 ^ 256 ∧ dst < 2 ^ 160 ∧ data.length < 2 ^ 32 ∧ + (∀ b ∈ data, b < 256) ∧ call = mkCall (swapData a0 a1 dst data) σ + +/-- The valid calls of `skim`. -/ +def ValidSkim (call : Call) : Prop := + ∃ σ dst, dst < 2 ^ 160 ∧ call = mkCall ((EthLib.Base.natToBytes 4 skimSel).map (·.toNat) ++ word dst) σ + +/-- The valid calls of `sync`. -/ +def ValidSync (call : Call) : Prop := + ∃ σ, call = mkCall ((EthLib.Base.natToBytes 4 syncSel).map (·.toNat)) σ + +/-- The statement's valid calls. -/ +def Valid (call : Call) : Prop := ValidSwap call ∨ ValidSkim call ∨ ValidSync call + +/-! ## The environment -/ + +/-- The admitted bytecode environments. -/ +def EnvOk (env : TargetEnv) : Prop := env.WF + +/-- The source worlds a result of the bytes may be explained by: open worlds (every call +answered), return data below `2 ^ 64` bytes, account code at addresses below `2 ^ 160`. -/ +def Wide (W : World) : Prop := + W.Open ∧ (∀ p ∈ W.codes.getD [], p.1 < 2 ^ 160) ∧ + (∀ h world request a, W.ans h (.external world (.call request)) = some a → + a.returnData.size < 2 ^ 64) + +open SolidCore.Solidity.Source in +/-- The pair's storage in an open world, as SolidCore adopts it after a call (`adoptWorld`). -/ +def selfStorage (w : SolidCore.Solidity.Shared.OpenWorld) : List (Nat × Nat) := + ((w.accounts.find? (wordToAddress selfAddress)).getD default).storage.toList.map + fun kv => (u256ToWord kv.1, u256ToWord kv.2) + +/-- **No reentrant state change**: every answer to an external call leaves the pair's storage as +it was sent. A token or callee that calls back into the pair's unlocked ERC20 functions and +changes its storage during swap, skim or sync is outside the admitted worlds; such a result of the +bytes is reported as `Unadmitted`, not as meeting the specification. -/ +def PairFramed (W : World) : Prop := + ∀ h world request a, W.ans h (.external world (.call request)) = some a → + slotValue (selfStorage a.postWorld) = slotValue (selfStorage world) + +/-- The admitted source worlds: the wide ones without reentrant state change. -/ +def Admit (W : World) : Prop := Wide W ∧ PairFramed W + +/-- The storage word of `allowance[address(0)][s]` (slot 2), as the specification computes it. -/ +def zeroAllowanceSlot (s : Nat) : Nat := + SolidCore.Spec.keccakWord (SolidCore.Spec.wordBytes s ++ + SolidCore.Spec.wordBytes (SolidCore.Spec.keccakWord (SolidCore.Spec.wordBytes 0 ++ SolidCore.Spec.wordBytes 2))) + +/-- **The named premise**: the words `allowance[address(0)][s]` (the ERC20 invariant +`forall s :: allowance[address(0)][s] == 0` reads them for every address `s`) are none of the +pair's 13 fixed slots, the only slots swap, skim and sync write (8, 9, 10, 12). It asks +`2 ^ 160` keccak256 images to avoid 13 values: avoidance, not injectivity, so no counting +argument refutes it, and a hash model meets it (`PairAllowanceApart.satisfiable`, Refusal.lean). +It is not footprint-scoped (the invariant's family is every address), a computational assumption +of the statement, never an axiom. The other keccak word the specification reads, +`balanceOf[address(0)]`, needs no premise: the kernel computes it (`zeroBalance_ge`). -/ +def PairAllowanceApart : Prop := + ∀ s, s < 2 ^ 160 → 13 ≤ zeroAllowanceSlot s % 2 ^ 256 + +/-! ## Allowed statuses and the specification -/ + +/-- **The allowed statuses: every status.** swap, skim and sync bubble a callee's revert data +verbatim (the tokens' `balanceOf` and the `uniswapV2Call` callback are high-level calls), and an +admitted world may revert with any data, so no revert data can be excluded: termination is stated +with any status, and an arbitrary revert is not counted as functional success (`Post` constrains +successes only). Recorded as the statement's declared vacuity of the allowed statuses. -/ +def Allowed (_W : World) (_call : Call) (_obs : Observable) : Prop := True + +/-- The call context of the specification: the statement's caller and contract, its block. -/ +def ctxOf (call : Call) : SolidCore.Spec.Ctx := + { sender := callerAddress, value := call.callvalue, timestamp := 1, self := selfAddress } + +/-- swap, skim and sync update no ghost. -/ +def idStep : SolidCore.Spec.GhostStep := fun _ g => g + +end SolidCore.Spec.UniswapV2.PairSpec diff --git a/Contracts/UniswapV2/PairSpec/Negative.lean b/Contracts/UniswapV2/PairSpec/Negative.lean new file mode 100644 index 00000000..00986e71 --- /dev/null +++ b/Contracts/UniswapV2/PairSpec/Negative.lean @@ -0,0 +1,161 @@ +import Contracts.UniswapV2.PairSpec.Refusal +import Contracts.UniswapV2.PairSpec.SourceNoUpdate +import Contracts.UniswapV2.PairSpec.RuntimeNoUpdate +import Contracts.UniswapV2.PairSpec.SourceSkimUpdate +import Contracts.UniswapV2.PairSpec.RuntimeSkimUpdate + +/-! +# UniswapV2Pair: the binding and the negative controls, by execution + +One swap is run on the exact bytes in EthLib (`Target.runWithIn`, with two token accounts whose +code answers `balanceOf` with a fixed balance and `transfer` with `true`) and on SolidCore's +checked source in the matching world (`Source.runIn`, answers the same), then on the mutants: + +| control | what runs | what refuses it | +|---|---|---| +| altered jump | the bytes with the first `PUSH2 t; JUMPI` target moved by one | the binding (`altered_not_bound`, kernel); the altered bytes revert on the swap the real bytes perform (evaluated) | +| skim that moves the reserves | skim with sync's `_update` first: solar's compile and SolidCore's translation of it | the published specification refuses every successful skim observable with reserve0 moved (`skimUpdate_refused`, kernel) | +| missing reserve update | swap without `_update`: solar's compile of the mutant source, and SolidCore's translation of it | the published specification refuses every observable with the executed features (`noUpdate_refused`, kernel) | +| wrong K | the real bytes and source | the mutated specification (fee 4/1000, SpecWrongK) refuses every observable with the executed features (`wrongK_refused`, kernel); the published clause accepts them (`k_accepts`, kernel) | +| mismatched environment | the real bytes among tokens answering 11000/9094, the source in a world answering 11000/9000 | the observables differ (evaluated): no equivalence claim relates them | +| closed world | the real bytes with no token accounts | swap reverts (evaluated): a closed-world statement would hold vacuously | + +**What is kernel-checked and what is evaluated.** The runs are evaluated by Lean's compiled +evaluator (`#guard`), not by the kernel: EthLib's `processMessage` is well-founded recursion that +the kernel does not reduce, and the source run needs the checked contract, which only the 22 +staged modules (ContractsUniswapV2Pair) produce in the kernel. Each refusal is a kernel theorem +over **every** observable with the features the evaluation checks (success, the reserves word), +so a refusal does not depend on the evaluator beyond those features. The mutants are generated by +scripts/verify/uniswap_v2_pair_spec.sh (not committed: derived from the GPL-3.0 port). +-/ + +namespace SolidCore.Spec.UniswapV2.PairSpec.Negative + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Shapes SolidCore.Spec +open SolidCore.Spec.UniswapV2.PairSpec EvmCompiler.Simulation SolidCore.Solidity + +/-! ## The binding and an altered jump -/ + +set_option maxRecDepth 100000 in +/-- The export is the bytes of the plain compile. -/ +theorem bound : Bound := + @of_decide_eq_true _ (instDecidableEqList _ _) (by decide +kernel) + +/-- The bytes with the first `PUSH2 t; JUMP` or `PUSH2 t; JUMPI` target moved by one. -/ +def alterJump : List Nat → List Nat + | 0x61 :: hi :: lo :: 0x56 :: rest => 0x61 :: hi :: ((lo + 1) % 256) :: 0x56 :: rest + | 0x61 :: hi :: lo :: 0x57 :: rest => 0x61 :: hi :: ((lo + 1) % 256) :: 0x57 :: rest + | b :: rest => b :: alterJump rest + | [] => [] + +set_option maxRecDepth 100000 in +/-- The alteration changes the bytes. -/ +theorem alterJump_changes : alterJump runtimeBytes ≠ runtimeBytes := by decide +kernel + +set_option maxRecDepth 100000 in +/-- **Altered jump**: the export is not the altered bytes. -/ +theorem altered_not_bound : ¬ (code.data.toList.map (·.toNat) = alterJump runtimeBytes) := by + rw [bound] + exact alterJump_changes.symm + +/-! ## The environment of the runs -/ + +/-- Token code: `transfer(...)` returns `true`, every other call the word `bal` (`bal < 2^16`). -/ +def tokenCode (bal : Nat) : ByteArray := + ⟨(([0x60, 0, 0x35, 0x60, 0xe0, 0x1c, 0x63, 0xa9, 0x05, 0x9c, 0xbb, 0x14, 0x60, 0x1a, 0x57, + 0x61, bal / 256, bal % 256, 0x60, 0, 0x52, 0x60, 0x20, 0x60, 0, 0xf3, + 0x5b, 0x60, 1, 0x60, 0, 0x52, 0x60, 0x20, 0x60, 0, 0xf3] : List Nat).map UInt8.ofNat).toArray⟩ + +/-- token0 at `0x4000` holding `b0` for the pair, token1 at `0x5000` holding `b1`. -/ +def env (b0 b1 : Nat) : TargetEnv := + [{ addr := 0x4000, code := tokenCode b0, storage := [], balance := 0, nonce := 1 }, + { addr := 0x5000, code := tokenCode b1, storage := [], balance := 0, nonce := 1 }] + +/-- A word as return data. -/ +def wordBA (n : Nat) : ByteArray := ⟨((word n).map UInt8.ofNat).toArray⟩ + +/-- The same answers on the source side: `transfer` answers `true`, every other call the balance +of the token called; no answer changes the pair's storage. -/ +def ans (b0 b1 : Nat) : Ans := fun _ q => + match q with + | .resource r => some (Query.defaultAnswer (.resource r)) + | .external w0 (.call req) => + let v := if (req.calldata.data.toList.take 4).map (·.toNat) = [0xa9, 0x05, 0x9c, 0xbb] then 1 + else if req.recipient.val = 0x4000 then b0 else b1 + some (CallResponse.mk true (wordBA v) w0 (EvmYul.UInt256.ofNat 0)) + | .external w0 (.create r) => some (Query.defaultAnswer (.external w0 (.create r))) + +/-- The source world of the runs: the tokens' answers and code at both addresses. -/ +def W (b0 b1 : Nat) : World := { ans := ans b0 b1, codes := some [(0x4000, [0x60]), (0x5000, [0x60])] } + +/-- The mutant bytes (swap without `_update`) and the altered bytes. -/ +def codeNoUpdate : ByteArray := ⟨(runtimeNoUpdate.map UInt8.ofNat).toArray⟩ +def codeAltered : ByteArray := ⟨((alterJump runtimeBytes).map UInt8.ofNat).toArray⟩ + +/-- SolidCore's checked mutant. -/ +def contractNoUpdate? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract SolidCore.Verify.VC.Source.UniswapV2PairNoUpdate.importedSourceUnit + "UniswapV2Pair" + +/-- The mutant bytes of skim forcing the reserves to the balances. -/ +def codeSkimUpdate : ByteArray := ⟨(runtimeSkimUpdate.map UInt8.ofNat).toArray⟩ + +/-- SolidCore's checked skim mutant. -/ +def contractSkimUpdate? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract SolidCore.Verify.VC.Source.UniswapV2PairSkimUpdate.importedSourceUnit + "UniswapV2Pair" + +/-- The features of a run the controls check: success, reserve0, reserve1, the lock word. -/ +def feat : Option Observable → Option (Bool × Nat × Nat × Nat) + | some o => some (o.success, o.storage 8 % 2 ^ 112, o.storage 8 / 2 ^ 112 % 2 ^ 112, o.storage 12) + | none => none + +def srcRun (c? : Except TypeCheck.TypeError TypeCheck.CheckedContract) (w : World) (call : Call) : + Option Observable := + match c? with + | .ok c => Source.runIn w SolidCore.Verify.VC.UniswapV2Pair.fuel c call + | .error _ => none + +/-! ## The runs (evaluated) -/ + +-- The exact bytes: the swap succeeds, reserves 11000/9094, unlocked. +#guard feat (Target.runWithIn (env 11000 9094) 10000000 code swapCall) = some (true, 11000, 9094, 1) +-- The checked source in the matching world: the same features. +#guard feat (srcRun SolidCore.Verify.VC.UniswapV2Pair.contract? (W 11000 9094) swapCall) = + some (true, 11000, 9094, 1) +-- Mutant bytes: the swap succeeds and leaves the reserves at 10000/10000. +#guard feat (Target.runWithIn (env 11000 9094) 10000000 codeNoUpdate swapCall) = some (true, 10000, 10000, 1) +-- Mutant source: the same. +#guard feat (srcRun contractNoUpdate? (W 11000 9094) swapCall) = some (true, 10000, 10000, 1) +-- Altered bytes: the swap the real bytes perform fails. +#guard ((Target.runWithIn (env 11000 9094) 10000000 codeAltered swapCall).map (·.success)) = some false +-- Mismatched environment: the source in a world answering 11000/9000 does not show the bytes' +-- observable among tokens answering 11000/9094. +#guard feat (srcRun SolidCore.Verify.VC.UniswapV2Pair.contract? (W 11000 9000) swapCall) ≠ + feat (Target.runWithIn (env 11000 9094) 10000000 code swapCall) +-- Closed world: without token accounts the swap reverts. +#guard ((Target.runWithIn [] 10000000 code swapCall).map (·.success)) = some false + +/-! ## skim (evaluated): token balances 11000/10500 over reserves 10000/10000 -/ + +-- The exact bytes: skim succeeds and keeps the reserves at 10000/10000. +#guard feat (Target.runWithIn (env 11000 10500) 10000000 code skimCall) = some (true, 10000, 10000, 1) +-- The checked source in the matching world: the same features. +#guard feat (srcRun SolidCore.Verify.VC.UniswapV2Pair.contract? (W 11000 10500) skimCall) = + some (true, 10000, 10000, 1) +-- Mutant bytes (skim forcing the reserves to the balances): reserves 11000/10500. +#guard feat (Target.runWithIn (env 11000 10500) 10000000 codeSkimUpdate skimCall) = some (true, 11000, 10500, 1) +-- Mutant source: the same. +#guard feat (srcRun contractSkimUpdate? (W 11000 10500) skimCall) = some (true, 11000, 10500, 1) + +/-! ## sync (evaluated): the real code moves the reserves, which the spec does not require -/ + +-- The exact bytes: sync sets the reserves to the balances 11000/9094. +#guard feat (Target.runWithIn (env 11000 9094) 10000000 code syncCallσ) = some (true, 11000, 9094, 1) +-- The checked source: the same. +#guard feat (srcRun SolidCore.Verify.VC.UniswapV2Pair.contract? (W 11000 9094) syncCallσ) = + some (true, 11000, 9094, 1) +-- The observable syncNoop_accepted proves the spec accepts differs: reserves 10000/10000. +#guard feat (some syncNoop) = some (true, 10000, 10000, 1) + +end SolidCore.Spec.UniswapV2.PairSpec.Negative diff --git a/Contracts/UniswapV2/PairSpec/NonVacuous.lean b/Contracts/UniswapV2/PairSpec/NonVacuous.lean new file mode 100644 index 00000000..d2127a96 --- /dev/null +++ b/Contracts/UniswapV2/PairSpec/NonVacuous.lean @@ -0,0 +1,36 @@ +import Contracts.UniswapV2.PairSpec.Published + +namespace SolidCore.Spec.UniswapV2.PairSpec + +open SolarTV SolidCore.Refinement SolidCore.Spec + +/-- sync() from the empty storage. -/ +def syncCall : Call := mkCall ((EthLib.Base.natToBytes 4 syncSel).map (·.toNat)) [] + +/-- A success that changes the total supply (slot 0) from 0 to 1. -/ +def badObs : Observable := + { success := true, output := [], logs := [], storage := fun s => if s = 0 then 1 else 0 } + +theorem nonVacuous : NonVacuous := by + refine ⟨syncCall, badObs, Or.inr (Or.inr ⟨[], rfl⟩), fun W h => ?_⟩ + have hmem : (SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair.spec.specs[10]'(by decide)) ∈ + SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair.spec.specs := List.getElem_mem _ + have hpre : SolidCore.Spec.Pre SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair + (SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair.spec.specs[10]'(by decide)) (ctxOf syncCall) + { storage := slotValue [], ghost := Ghost.zero, time := 0 } syncCall [] := by + refine ⟨⟨by decide, by decide, by decide⟩, rfl, by decide, ?_, ?_⟩ + · simp [Bundle.satAll, SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair] + · simp [Bundle.satAll, Bundle.sat, SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair, eval, + BinOp.apply, mkEnv, Env.cur, slotOf, slotValue, Ty.ofBits, toWord, Ghost.zero, Env.bind] + have hp := (h _ hmem [] _ hpre).1 rfl + obtain ⟨rets, -, hens, -⟩ := hp + have h0 := hens _ (List.getElem_mem (by decide : 0 < (SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair.spec.specs[10]'(by decide)).ensures.length)) + simp [Bundle.sat, SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair, eval, BinOp.apply, mkEnv, + Env.cur, slotOf, slotValue, Ty.ofBits, toWord, badObs, idStep] at h0 + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.nonVacuous' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms nonVacuous + +end SolidCore.Spec.UniswapV2.PairSpec + diff --git a/Contracts/UniswapV2/PairSpec/Published.lean b/Contracts/UniswapV2/PairSpec/Published.lean new file mode 100644 index 00000000..bffa53af --- /dev/null +++ b/Contracts/UniswapV2/PairSpec/Published.lean @@ -0,0 +1,58 @@ +import Contracts.UniswapV2.PairSpec.Stages + +/-! +# UniswapV2Pair: the composition wrapper + +`published_of_stages` proves the published `Statement` from the binding, the checked source and +the nine stage theorems (Stages.lean), by `OpenFunctional.of_parts` alone. Every input is a named +hypothesis of the theorem: nothing is assumed, and the theorem says exactly what is still owed. +When the lanes' theorems land, `published := published_of_stages bound contract_ok ...` is the +published theorem, checked against `Statement` by the driver (tools/certify/check_final.lean). +-/ + +namespace SolidCore.Spec.UniswapV2.PairSpec + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Shapes SolidCore.Spec.UniswapV2.PairSpec.Stages + +/-- A valid call exists: `sync()` from the empty storage. -/ +theorem inhabited : ∃ call, Valid call := + ⟨_, Or.inr (Or.inr ⟨[], rfl⟩)⟩ + +/-- **The composition**: the statement from the binding, the checked source and the stages. -/ +theorem published_of_stages (hbound : Bound) + (hc : ∃ c, SolidCore.Verify.VC.UniswapV2Pair.contract? = .ok c) + (heq : ∀ c, SolidCore.Verify.VC.UniswapV2Pair.contract? = .ok c → + EquivSwap c ∧ EquivSkim c ∧ EquivSync c) + (hterm : ∀ c, SolidCore.Verify.VC.UniswapV2Pair.contract? = .ok c → + TermSwap c ∧ TermSkim c ∧ TermSync c) + (hmeets : ∀ c, SolidCore.Verify.VC.UniswapV2Pair.contract? = .ok c → + MeetsSwap c ∧ MeetsSkim c ∧ MeetsSync c) : + Statement := by + refine ⟨hbound, fun hk => ?_⟩ + obtain ⟨c, hc⟩ := hc + obtain ⟨e1, e2, e3⟩ := heq c hc + obtain ⟨t1, t2, t3⟩ := hterm c hc + obtain ⟨m1, m2, m3⟩ := hmeets c hc + refine ⟨c, hc, OpenFunctional.of_parts inhabited (e1.or (e2.or e3)) (t1.or (t2.or t3)) ?_⟩ + exact fun W hW => (m1.or (m2.or m3)) hk W hW + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.published_of_stages' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms published_of_stages + +/-- **What the statement gives of the bytes**: in every admitted environment, every result of the +exact bytecode on a valid call, at any gas below `2 ^ 256`, is allowed and meets the exported +specification (for some admitted world), or changes nothing, or is explained only by a world +with a reentrant state change. -/ +theorem bytecode_of_statement {c0 : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc0 : SolidCore.Verify.VC.UniswapV2Pair.contract? = .ok c0) (h : Statement) (hk : PairAllowanceApart) (env : TargetEnv) (he : EnvOk env) + (gas : Nat) (hg : gas < 2 ^ 256) (call : Call) (hv : Valid call) (obs : Observable) + (hrun : Target.runWithIn env gas code call = some obs) : + (∃ W, Admit W ∧ Allowed W call obs ∧ Post W call obs) ∨ Inert call obs ∨ + Unadmitted SolidCore.Verify.VC.UniswapV2Pair.fuel c0 Wide Admit call obs := by + obtain ⟨c, hc, hf⟩ := h.2 hk + obtain rfl : c = c0 := Except.ok.inj (hc.symm.trans hc0) + exact hf.bytecode_any env he gas hg call hv obs hrun + +end SolidCore.Spec.UniswapV2.PairSpec + diff --git a/Contracts/UniswapV2/PairSpec/Refusal.lean b/Contracts/UniswapV2/PairSpec/Refusal.lean new file mode 100644 index 00000000..c03ef419 --- /dev/null +++ b/Contracts/UniswapV2/PairSpec/Refusal.lean @@ -0,0 +1,256 @@ +import Contracts.UniswapV2.PairSpec.Published +import Contracts.UniswapV2.PairSpec.SpecWrongK + +/-! +# UniswapV2Pair: refusals of the executed observables + +The kernel half of the negative controls (Negative.lean runs the programs): for the swap +`swap(0, 906, 0x3000, "")` from reserves 10000/10000 with 1000 of token0 in, the published +specification refuses **every** observable that succeeds and leaves the reserves at 10000/10000 +(what the pair without `_update` does), the wrong-K specification refuses every observable that +succeeds with reserves 11000/9094 (what the pair does), and the published fee-adjusted clause +accepts those reserves. The pre-state meets the specification's precondition under the +statement's premise `PairAllowanceApart` (the ERC20 invariants read `allowance[address(0)][s]`, which must +not be one of the pair's fixed slots). +-/ + +namespace SolidCore.Spec.UniswapV2.PairSpec.Negative + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Shapes SolidCore.Spec +open SolidCore.Spec.UniswapV2.PairSpec + +/-- The pair's storage: token0, token1, reserves 10000/10000, unlocked. -/ +def σ : List (Nat × Nat) := [(6, 0x4000), (7, 0x5000), (8, 10000 + 10000 * 2 ^ 112), (12, 1)] + +/-- `swap(0, 906, 0x3000, "")` after 1000 of token0 arrived (token0 balance 11000). -/ +def swapCall : Call := mkCall (swapData 0 906 0x3000 []) σ + +theorem swapCall_valid : Valid swapCall := + Or.inl ⟨σ, 0, 906, 0x3000, [], by decide, by decide, by decide, by decide, by simp, rfl⟩ + + +/-- swap's spec in a bundle (the ninth). -/ +abbrev swapFs (b : Bundle) (h : 8 < b.spec.specs.length) : FnSpec := b.spec.specs[8] + +/-- The pre-state of the swap. -/ +def preSt : State := { storage := slotValue σ, ghost := Ghost.zero, time := 0 } + +theorem slotValue_σ_big {x : Nat} (hx : 13 ≤ x % 2 ^ 256) : slotValue σ x = 0 := by + simp only [slotValue, σ, List.foldl] + split_ifs <;> omega + +/-- The swap's arguments as the spec decodes them. -/ +def swapArgs : List Int := [0, 906, 0x3000, 0x80] + +set_option maxRecDepth 100000 in +theorem pre_swap (hk : PairAllowanceApart) : + Pre SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair + (SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair.spec.specs[8]'(by decide)) (ctxOf swapCall) preSt swapCall swapArgs := by + refine ⟨⟨by decide +kernel, by decide +kernel, by decide +kernel⟩, rfl, by decide, ?_, ?_⟩ + · simp [Bundle.satAll, SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair] + · simp [Bundle.satAll, Bundle.sat, SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair, eval, + BinOp.apply, mkEnv, Env.cur, slotOf, preSt, Ty.ofBits, toWord, Ghost.zero, Env.bind] + refine ⟨by decide, fun v hv => ?_, Int.emod_nonneg _ (by decide)⟩ + obtain ⟨hv0, hv1⟩ := hv + have hs : (v % 115792089237316195423570985008687907853269984665640564039457584007913129639936).toNat + = v.toNat := by rw [Int.emod_eq_of_lt hv0 (by omega)] + have h2 : 2 % wordMod = 2 := by decide + rw [hs, h2] + have := slotValue_σ_big (hk v.toNat (by omega)) + simp only [zeroAllowanceSlot] at this + rw [this] + rfl + +/-- The published specification as a postcondition (the statement's `Post`, any world). -/ +abbrev PostPub : Call → Observable → Prop := + bundlePost SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair ctxOf idStep + +/-- The wrong-K specification as a postcondition. -/ +abbrev PostWrongK : Call → Observable → Prop := + bundlePost SolidCore.Spec.Export.UniswapV2PairWrongK.UniswapV2Pair ctxOf idStep + +set_option maxRecDepth 100000 in +/-- **Missing reserve update, refused**: the published specification refuses every observable of +the swap that succeeds with the reserves left at 10000/10000. -/ +theorem noUpdate_refused (hk : PairAllowanceApart) (W : World) (obs : Observable) (hs : obs.success = true) + (h0 : obs.storage 8 % 2 ^ 112 = 10000) (h1 : obs.storage 8 / 2 ^ 112 % 2 ^ 112 = 10000) : + ¬ Post W swapCall obs := by + intro h + have hmem : (SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair.spec.specs[8]'(by decide)) ∈ + SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair.spec.specs := List.getElem_mem _ + obtain ⟨rets, -, hens, -⟩ := (h _ hmem swapArgs preSt (pre_swap hk)).1 hs + have hK := hens _ (List.getElem_mem (by decide : 0 < (SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair.spec.specs[8]'(by decide)).ensures.length)) + simp only [Nat.reducePow] at h0 h1 + have h0i : ((obs.storage 8 : Nat) : Int) % 5192296858534827628530496329220096 = 10000 := by omega + have h1i : ((obs.storage 8 : Nat) : Int) / 5192296858534827628530496329220096 % + 5192296858534827628530496329220096 = 10000 := by omega + simp [Bundle.sat, SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair, eval, BinOp.apply, mkEnv, + Env.cur, slotOf, Ty.ofBits, toWord, idStep, preSt, swapArgs, wordMod, slotValue, σ, h0i, h1i] at hK + +set_option maxRecDepth 100000 in +theorem pre_swapWrongK (hk : PairAllowanceApart) : + Pre SolidCore.Spec.Export.UniswapV2PairWrongK.UniswapV2Pair + (SolidCore.Spec.Export.UniswapV2PairWrongK.UniswapV2Pair.spec.specs[8]'(by decide)) (ctxOf swapCall) preSt swapCall swapArgs := by + refine ⟨⟨by decide +kernel, by decide +kernel, by decide +kernel⟩, rfl, by decide, ?_, ?_⟩ + · simp [Bundle.satAll, SolidCore.Spec.Export.UniswapV2PairWrongK.UniswapV2Pair] + · simp [Bundle.satAll, Bundle.sat, SolidCore.Spec.Export.UniswapV2PairWrongK.UniswapV2Pair, eval, + BinOp.apply, mkEnv, Env.cur, slotOf, preSt, Ty.ofBits, toWord, Ghost.zero, Env.bind] + refine ⟨by decide, fun v hv => ?_, Int.emod_nonneg _ (by decide)⟩ + obtain ⟨hv0, hv1⟩ := hv + have hs : (v % 115792089237316195423570985008687907853269984665640564039457584007913129639936).toNat + = v.toNat := by rw [Int.emod_eq_of_lt hv0 (by omega)] + have h2 : 2 % wordMod = 2 := by decide + rw [hs, h2] + have := slotValue_σ_big (hk v.toNat (by omega)) + simp only [zeroAllowanceSlot] at this + rw [this] + rfl + +set_option maxRecDepth 100000 in +/-- **Wrong K, refused**: the wrong-K specification (fee 4/1000) refuses every observable of the +swap that succeeds with reserves 11000/9094, what the pair's bytes and source do. -/ +theorem wrongK_refused (hk : PairAllowanceApart) (obs : Observable) (hs : obs.success = true) + (h0 : obs.storage 8 % 2 ^ 112 = 11000) (h1 : obs.storage 8 / 2 ^ 112 % 2 ^ 112 = 9094) : + ¬ PostWrongK swapCall obs := by + intro h + have hmem : (SolidCore.Spec.Export.UniswapV2PairWrongK.UniswapV2Pair.spec.specs[8]'(by decide)) ∈ + SolidCore.Spec.Export.UniswapV2PairWrongK.UniswapV2Pair.spec.specs := List.getElem_mem _ + obtain ⟨rets, -, hens, -⟩ := (h _ hmem swapArgs preSt (pre_swapWrongK hk)).1 hs + have hK := hens _ (List.getElem_mem (by decide : 0 < (SolidCore.Spec.Export.UniswapV2PairWrongK.UniswapV2Pair.spec.specs[8]'(by decide)).ensures.length)) + simp only [Nat.reducePow] at h0 h1 + have h0i : ((obs.storage 8 : Nat) : Int) % 5192296858534827628530496329220096 = 11000 := by omega + have h1i : ((obs.storage 8 : Nat) : Int) / 5192296858534827628530496329220096 % + 5192296858534827628530496329220096 = 9094 := by omega + simp [Bundle.sat, SolidCore.Spec.Export.UniswapV2PairWrongK.UniswapV2Pair, eval, BinOp.apply, mkEnv, + Env.cur, slotOf, Ty.ofBits, toWord, idStep, preSt, swapArgs, wordMod, slotValue, σ, h0i, h1i] at hK + +set_option maxRecDepth 100000 in +/-- **The published clause accepts the pair's swap**: the fee-adjusted constant product holds of +every post-state with reserves 11000/9094 after the swap from 10000/10000. -/ +theorem k_accepts (obs : Observable) (h0 : obs.storage 8 % 2 ^ 112 = 11000) + (h1 : obs.storage 8 / 2 ^ 112 % 2 ^ 112 = 9094) (rets : List Int) : + SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair.sat + ((SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair.spec.specs[8]'(by decide)).ensures[0]'(by decide)) + (mkEnv (ctxOf swapCall) swapArgs rets preSt + { storage := obs.storage, ghost := idStep swapCall preSt.ghost, time := (ctxOf swapCall).timestamp }) := by + simp only [Nat.reducePow] at h0 h1 + have h0i : ((obs.storage 8 : Nat) : Int) % 5192296858534827628530496329220096 = 11000 := by omega + have h1i : ((obs.storage 8 : Nat) : Int) / 5192296858534827628530496329220096 % + 5192296858534827628530496329220096 = 9094 := by omega + simp [Bundle.sat, SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair, eval, BinOp.apply, mkEnv, + Env.cur, slotOf, Ty.ofBits, toWord, idStep, preSt, swapArgs, wordMod, slotValue, σ, h0i, h1i] + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.noUpdate_refused' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms noUpdate_refused + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.wrongK_refused' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms wrongK_refused + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.k_accepts' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms k_accepts + +/-- `balanceOf[address(0)]`'s word is no fixed slot, by the kernel's evaluation of keccak256 +(`TrustedBase.image3`): no premise needed for it. -/ +theorem zeroBalance_ge : 13 ≤ SolidCore.Spec.keccakWord (SolidCore.Spec.wordBytes 0 ++ SolidCore.Spec.wordBytes 1) % 2 ^ 256 := by + have h := SolidCore.Spec.TrustedBase.image3 + simp only [SolidCore.Spec.TrustedBase.mappingPreimage] at h + rw [h]; decide + +/-- **The premise is satisfiable**: with the hash replaced by any function whose images are at +least 13 (here the constant `2 ^ 128`), it holds. The premise is about keccak256 itself and stays a +premise; this shows it is not `False` in disguise. -/ +theorem PairAllowanceApart.satisfiable : ∃ h : List Nat → Nat, + ∀ s, s < 2 ^ 160 → 13 ≤ h (SolidCore.Spec.wordBytes s ++ + SolidCore.Spec.wordBytes (h (SolidCore.Spec.wordBytes 0 ++ SolidCore.Spec.wordBytes 2))) % 2 ^ 256 := + ⟨fun _ => 2 ^ 128, fun _ _ => by norm_num⟩ + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.zeroBalance_ge' depends on axioms: [propext] -/ +#guard_msgs (whitespace := lax) in +#print axioms zeroBalance_ge + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.pre_swap' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms pre_swap + +/-- `skim(0x3000)` from the same storage (the runs: token balances 11000/10500 over reserves 10000/10000). -/ +def skimCall : Call := mkCall ((EthLib.Base.natToBytes 4 skimSel).map (·.toNat) ++ word 0x3000) σ + +theorem skimCall_valid : Valid skimCall := Or.inr (Or.inl ⟨σ, 0x3000, by decide, rfl⟩) + +set_option maxRecDepth 100000 in +theorem pre_skim (hk : PairAllowanceApart) : + Pre SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair + (SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair.spec.specs[9]'(by decide)) (ctxOf skimCall) preSt skimCall [0x3000] := by + refine ⟨⟨by decide +kernel, by decide +kernel, by decide +kernel⟩, rfl, by decide, ?_, ?_⟩ + · simp [Bundle.satAll, SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair] + · simp [Bundle.satAll, Bundle.sat, SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair, eval, + BinOp.apply, mkEnv, Env.cur, slotOf, preSt, Ty.ofBits, toWord, Ghost.zero, Env.bind] + refine ⟨by decide, fun v hv => ?_, Int.emod_nonneg _ (by decide)⟩ + obtain ⟨hv0, hv1⟩ := hv + have hs : (v % 115792089237316195423570985008687907853269984665640564039457584007913129639936).toNat + = v.toNat := by rw [Int.emod_eq_of_lt hv0 (by omega)] + have h2 : 2 % wordMod = 2 := by decide + rw [hs, h2] + have := slotValue_σ_big (hk v.toNat (by omega)) + simp only [zeroAllowanceSlot] at this + rw [this] + rfl + +set_option maxRecDepth 100000 in +/-- **Skim that moves the reserves, refused**: the published specification refuses every observable +of `skim(0x3000)` that succeeds with reserve0 moved off 10000 (the mutant's 11000). -/ +theorem skimUpdate_refused (hk : PairAllowanceApart) (W : World) (obs : Observable) (hs : obs.success = true) + (h0 : obs.storage 8 % 2 ^ 112 ≠ 10000) : ¬ Post W skimCall obs := by + intro h + have hmem : (SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair.spec.specs[9]'(by decide)) ∈ + SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair.spec.specs := List.getElem_mem _ + obtain ⟨rets, -, hens, -⟩ := (h _ hmem [0x3000] preSt (pre_skim hk)).1 hs + have hK := hens _ (List.getElem_mem (by decide : 0 < (SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair.spec.specs[9]'(by decide)).ensures.length)) + simp only [Nat.reducePow] at h0 + have h0i : ((obs.storage 8 : Nat) : Int) % 5192296858534827628530496329220096 ≠ 10000 := by omega + simp [Bundle.sat, SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair, eval, BinOp.apply, mkEnv, + Env.cur, slotOf, Ty.ofBits, toWord, idStep, preSt, wordMod, slotValue, σ] at hK + omega + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.skimUpdate_refused' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms skimUpdate_refused + +/-- `sync()` from the storage `σ`. -/ +def syncCallσ : Call := mkCall ((EthLib.Base.natToBytes 4 syncSel).map (·.toNat)) σ + +/-- A sync that changes nothing: success, no output, the storage as it was (reserves 10000/10000 +while the tokens hold other balances). -/ +def syncNoop : Observable := { success := true, output := [], logs := [], storage := slotValue σ } + +set_option maxRecDepth 100000 in +/-- **A spec gap, proved**: the published specification accepts a sync that does not update the +reserves. sync's exported ensures are only that the supply and the lock are kept; the reserve +postcondition is `_update`'s, which is private and not among the exported function specs. So a +mutant sync without `_update` cannot be refused by this specification. -/ +theorem syncNoop_accepted (W : World) : Post W syncCallσ syncNoop := by + intro fs hfs args pre hpre + obtain ⟨⟨_, hsel, _⟩, hst, -, -, hinv⟩ := hpre + simp only [SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair, List.mem_cons, List.not_mem_nil, + or_false] at hfs + rcases hfs with rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl | rfl + all_goals try exact absurd hsel (by decide +kernel) + obtain ⟨st, gh, tm⟩ := pre + simp only at hst + subst hst + have hσ : syncCallσ.storage = σ := rfl + rw [hσ] at hinv ⊢ + refine ⟨fun _ => ⟨[], by decide, ?_, ?_⟩, fun h => absurd rfl h⟩ + · simp [Bundle.satAll, Bundle.sat, SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair, eval, + BinOp.apply, mkEnv, Env.cur, slotOf, Ty.ofBits, toWord, syncNoop, idStep, wordMod, slotValue, σ] + · simpa [Bundle.satAll, Bundle.sat, SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair, eval, + BinOp.apply, mkEnv, Env.cur, slotOf, Ty.ofBits, toWord, syncNoop, idStep, Env.bind, evalList] using hinv + +/-- info: 'SolidCore.Spec.UniswapV2.PairSpec.Negative.syncNoop_accepted' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms syncNoop_accepted + +end SolidCore.Spec.UniswapV2.PairSpec.Negative diff --git a/Contracts/UniswapV2/PairSpec/Stages.lean b/Contracts/UniswapV2/PairSpec/Stages.lean new file mode 100644 index 00000000..6c51bd9c --- /dev/null +++ b/Contracts/UniswapV2/PairSpec/Stages.lean @@ -0,0 +1,76 @@ +import Contracts.UniswapV2.PairSpec.Statement + +/-! +# UniswapV2Pair: the stage theorems the published statement composes + +These are the statements of the theorems the backend lanes produce, as `Prop`s, so that the +composition (Published.lean) is kernel-checked now and becomes the published theorem by applying +it to the lanes' theorems once they land. None is assumed anywhere: each is a hypothesis of +`published_of_stages`, visible in its statement. Names (RESULT.md lists them): + +| Prop | the theorem that will prove it | lane | +|---|---|---| +| `EquivSwap`, `EquivSkim`, `EquivSync` | `SolarTV.Export.UniswapV2Pair.Ctx.equiv_swap` / `_skim` / `_sync` | pair-stages-b | +| `TermSwap`, `TermSkim`, `TermSync` | `SolidCore.Spec.UniswapV2.Pair.terminates_swap` / `_skim` / `_sync` | pair-stages-b | +| `MeetsSwap`, `MeetsSkim`, `MeetsSync` | `SolidCore.Spec.UniswapV2.Pair.swap_holds` / `skim_holds` / `sync_holds` | pair-spec (spec connection) | + +pair-stages-a's mint and burn enter the same way (`EquivMint`, ...) once their ghost step is +written; the statement does not cover them yet. +-/ + +namespace SolidCore.Spec.UniswapV2.PairSpec.Stages + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Shapes SolidCore.Spec.UniswapV2.PairSpec + +/-- Equivalence on the calls `V` of one function: every result of the exact bytes in every admitted +environment, at every gas below `2 ^ 256`, is the checked source's in some admitted world, or an +inert failure, or explained only by a wide world that is not admitted (`Unadmitted`). -/ +def EquivOn (c : SolidCore.Solidity.TypeCheck.CheckedContract) (V : Call → Prop) : Prop := + ∀ env, EnvOk env → ∀ gas, gas < 2 ^ 256 → ∀ call, V call → ∀ obs, + Target.runWithIn env gas code call = some obs → + (∃ W, Admit W ∧ Source.runIn W SolidCore.Verify.VC.UniswapV2Pair.fuel c call = some obs) ∨ + Inert call obs ∨ Unadmitted SolidCore.Verify.VC.UniswapV2Pair.fuel c Wide Admit call obs + +/-- Termination on the calls `V` of one function, with an allowed status, in every admitted world. -/ +def TermOn (c : SolidCore.Solidity.TypeCheck.CheckedContract) (V : Call → Prop) : Prop := + ∀ W, Admit W → ∀ call, V call → + ∃ obs, Source.runIn W SolidCore.Verify.VC.UniswapV2Pair.fuel c call = some obs ∧ Allowed W call obs + +/-- The specification on the calls `V` of one function, in every admitted world, under the named +premise. -/ +def MeetsOn (c : SolidCore.Solidity.TypeCheck.CheckedContract) (V : Call → Prop) : Prop := + PairAllowanceApart → ∀ W, Admit W → Meets (solidCoreIn W SolidCore.Verify.VC.UniswapV2Pair.fuel) c V (Post W) + +def EquivSwap (c : SolidCore.Solidity.TypeCheck.CheckedContract) : Prop := EquivOn c ValidSwap +def EquivSkim (c : SolidCore.Solidity.TypeCheck.CheckedContract) : Prop := EquivOn c ValidSkim +def EquivSync (c : SolidCore.Solidity.TypeCheck.CheckedContract) : Prop := EquivOn c ValidSync +def TermSwap (c : SolidCore.Solidity.TypeCheck.CheckedContract) : Prop := TermOn c ValidSwap +def TermSkim (c : SolidCore.Solidity.TypeCheck.CheckedContract) : Prop := TermOn c ValidSkim +def TermSync (c : SolidCore.Solidity.TypeCheck.CheckedContract) : Prop := TermOn c ValidSync +def MeetsSwap (c : SolidCore.Solidity.TypeCheck.CheckedContract) : Prop := MeetsOn c ValidSwap +def MeetsSkim (c : SolidCore.Solidity.TypeCheck.CheckedContract) : Prop := MeetsOn c ValidSkim +def MeetsSync (c : SolidCore.Solidity.TypeCheck.CheckedContract) : Prop := MeetsOn c ValidSync + +theorem EquivOn.or {c : SolidCore.Solidity.TypeCheck.CheckedContract} {V V' : Call → Prop} + (h : EquivOn c V) (h' : EquivOn c V') : EquivOn c (fun call => V call ∨ V' call) := by + intro env he gas hg call hc obs hr + rcases hc with hc | hc + · exact h env he gas hg call hc obs hr + · exact h' env he gas hg call hc obs hr + +theorem TermOn.or {c : SolidCore.Solidity.TypeCheck.CheckedContract} {V V' : Call → Prop} + (h : TermOn c V) (h' : TermOn c V') : TermOn c (fun call => V call ∨ V' call) := by + intro W hW call hc + rcases hc with hc | hc + · exact h W hW call hc + · exact h' W hW call hc + +theorem MeetsOn.or {c : SolidCore.Solidity.TypeCheck.CheckedContract} {V V' : Call → Prop} + (h : MeetsOn c V) (h' : MeetsOn c V') : MeetsOn c (fun call => V call ∨ V' call) := by + intro hk W hW call hc obs hr + rcases hc with hc | hc + · exact h hk W hW call hc obs hr + · exact h' hk W hW call hc obs hr + +end SolidCore.Spec.UniswapV2.PairSpec.Stages + diff --git a/Contracts/UniswapV2/PairSpec/Statement.lean b/Contracts/UniswapV2/PairSpec/Statement.lean new file mode 100644 index 00000000..a4f5f377 --- /dev/null +++ b/Contracts/UniswapV2/PairSpec/Statement.lean @@ -0,0 +1,78 @@ +import Contracts.UniswapV2.PairSpec.Inputs +import Verify.ShapeBundle +import Contracts.UniswapV2.Pair.Core +import Contracts.UniswapV2.PairSpec.Spec +import Contracts.UniswapV2.PairSpec.Bytecode +import Contracts.UniswapV2.PairSpec.Runtime + +/-! +# UniswapV2Pair: the published statement of swap, skim and sync + +The statement is fixed here, from reviewed inputs only (never from a proof module): + +* the source: SolidCore's checked `UniswapV2Pair` (`SolidCore.Verify.VC.UniswapV2Pair.contract?`, + scripts/verify/uniswap_v2_core.py; not committed, the port is GPL-3.0); +* the bytes: `SolarTV.Export.UniswapV2Pair.bytecode`, the runtime bytecode solar emitted + (`-Ogas --evm-version osaka`), bound to `runtimeBytes` by exact equality (`Bound`); +* the valid calls (`Valid`): `swap(amount0Out, amount1Out, to, data)` with its `bytes` argument + ABI-encoded at offset `0x80` (any data below `2 ^ 32` bytes), `skim(to)` and `sync()`, clean + argument words, no value, from any storage; +* the environment: every list of other accounts (`TargetEnv.WF`: the tokens, the factory, a + callee, with any code and storage) on the bytecode side, and every admitted open world on the + source side (`Admit`: answers every call; return data below `2 ^ 64` bytes; account code at + addresses below `2 ^ 160`; no answer changes the pair's storage, `PairFramed`). A result of + the bytes that only a world with a reentrant state change explains is `Unadmitted`: reported, + outside the specification's guarantee; +* the allowed statuses (`Allowed`): every status, since a callee's revert data is bubbled + verbatim (declared vacuity of the allowed statuses; the specification constrains successes); +* the specification (`Post`): solar-verify's export of crates/verify/uniswap-v2/uniswap-v2.spec + for `UniswapV2Pair` (`SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair`, generated by + scripts/verify/uniswap_v2_pair_spec.sh), read by `Shapes.bundlePost` with the identity ghost + step: swap, skim and sync update no ghost, and the inherited ERC20 invariants + (`totalSupply == sumBalances`, `allowance[0][s] == 0`, `balanceOf[0] >= zeroMinted`) are + assumed before the call and required after it; +* one named premise, `PairAllowanceApart`: the words `allowance[address(0)][s]` the ERC20 + invariant reads avoid the pair's 13 fixed slots (Inputs.lean; satisfiable, never an axiom; + no global hash separation, which is unsatisfiable). + +Not in the statement: mint and burn (their exported ensures read statement-level ghosts, +`mintAmount0 = amount0` and the like, whose values depend on the tokens' answers: the ghost step +that computes them from the world is not written, see RESULT.md), the ERC20 functions, permit, +initialize, the getters, the constructor (the statement starts from any storage), resources (no +gas bound: callees spend gas), the source model (SolidCore's checked contract is the meaning of +the source: frontend trust boundary). +-/ + +namespace SolidCore.Spec.UniswapV2.PairSpec + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Shapes + +/-! ## The bytes -/ + +/-- The runtime bytecode the statement speaks of: the fresh export. -/ +def code : ByteArray := ⟨(SolarTV.Export.UniswapV2Pair.bytecode.map UInt8.ofNat).toArray⟩ + +/-- The binding of the export to the bytes this run compiled (`runtimeBytes`, generated beside +the export from solar's own output). -/ +def Bound : Prop := code.data.toList.map (·.toNat) = runtimeBytes + +/-- **The specification**: solar-verify's export, as a postcondition of one call. -/ +def Post (_W : World) : Call → Observable → Prop := + bundlePost SolidCore.Spec.Export.UniswapV2Pair.UniswapV2Pair ctxOf idStep + +/-! ## The statement -/ + +/-- **The published statement**: the binding, and, under the named premise, equivalence, +termination and the exported specification of swap, skim and sync on the exact bytes, in every +admitted environment. -/ +def Statement : Prop := + Bound ∧ (PairAllowanceApart → + ∃ c, SolidCore.Verify.VC.UniswapV2Pair.contract? = .ok c ∧ + OpenFunctional SolidCore.Verify.VC.UniswapV2Pair.fuel c code EnvOk Wide Admit Valid Allowed Post) + +/-- The specification rejects something: a valid call with a result the specification rejects in +every world. (The allowed statuses reject nothing; see `Allowed`.) -/ +def NonVacuous : Prop := ∃ call obs, Valid call ∧ ∀ W, ¬ Post W call obs + +end SolidCore.Spec.UniswapV2.PairSpec + diff --git a/Contracts/UniswapV2/VC/README.md b/Contracts/UniswapV2/VC/README.md new file mode 100644 index 00000000..abfee552 --- /dev/null +++ b/Contracts/UniswapV2/VC/README.md @@ -0,0 +1,56 @@ +# Uniswap V2: solar-verify's verification conditions in the kernel + +v2-core is GPL-3.0, so this directory keeps no port, export or proof of it: `discharge.sh` writes +them under an output directory at build time from solar's `solar-tv/uniswap-v2/port.py` and +`crates/verify/uniswap-v2/` (specs and `apply_specs.py`), and runs +[Verify/Discharge/discharge.sh](../../../Verify/Discharge/discharge.sh) on each contract's export: + +```text +Contracts/UniswapV2/VC/discharge.sh SOLAR_ROOT SOLAR_VERIFY OUT [Math|Factory|ERC20|Pair...] +``` + +Each export is `solar-verify --emit-lean` (manifest version 2) of the spec-applied port. Every +required obligation is accepted only by a kernel-checked proof of `.Valid` whose axioms are +`propext`, `Classical.choice` and `Quot.sound`: cvc5's refutation rebuilt by lean-smt +(`vc_smt`) first, then `vc_valid`. `OUT/vcs//discharge/results.tsv` has one row per obligation +and backend with its axioms, `summary.tsv` the verdict per obligation and the vacuity column +(`yes`: the kernel also proves the obligation with goal `false`, so its path is unreachable). +Math.sqrt's loop invariants are solar-verify's inferred ones, re-proved here like any obligation. + +Two leaves of `vc_valid` exist for these exports (Verify/Discharge/Leaf.lean): `omega` after +reading SMT-LIB's `div` and `mod` as `/` and `%` (Math's `y / 2`), and `omega` with the facts of +Verify/Discharge/Nonlinear.lean: square bounds, division bounds and the two Newton-step facts of +the integer square root, `y < ((y / x + x) / 2 + 1)²` for `1 ≤ x` (the arithmetic-geometric +mean step, `newton_lt`) and `x ≤ (y / x + x) / 2 → x * x ≤ y` (`newton_le`), each a theorem. +Verify/Discharge/IteApply.lean makes a store into a nested mapping (an ERC20 allowance) +readable by both backends. + +## Results (2026-11-13) + +With `DISCHARGE_BACKENDS='smt=vc_smt;vc_valid=vc_valid@90'`, every required row run +(`OUT/vcs//discharge/summary.tsv`): + +| Contract | Required | Proved (smt / vc_valid) | Failed | Vacuous | +|---|---|---|---|---| +| Math | 82 | 82 (34 / 48) | 0 | 0 | +| ERC20 | 40 | 33 (17 / 16) | 7 | 0 | +| Factory | 27 | 21 (19 / 2) | 6 | 0 | + +Every proved row's axioms are `propext`, `Classical.choice`, `Quot.sound`; no row fails by a +counterexample. `vc_valid` tries `vc_lite` (Verify/Discharge/Lite.lean) before its search: it +reads pointwise array definitions as function equations, opens a negated quantified goal into a +witness, splits on every `if` and calls `omega` with the facts of Nonlinear.lean, which now also +compare `y / x` with `2`, `x`, `x + 1`, `x + 2` and `x + 3` over the atom `x * x` +(`div_cmp`), expand `(a + 1) * (a + 1)` and bound a Newton step from below. That closes all of +Math.sqrt, including solar-verify's inferred loop invariants and the postcondition +`z * z <= y && y < (z + 1) * (z + 1)`. Quantifiers over two to four integers (Factory's +invariants over pairs of addresses) are evaluated as Lean binders (`eval_forall_int2` to `4`). + +Still failing: ERC20 `transferFrom#5, #6, #10, #11` (the conditional allowance update in a +nested mapping: `vc_lite`'s `omega` leaf misses the case split, the search times out) and +`permit#2, #4, #8` (simp exceeds the recursion limit on the signature digest terms), Factory +`createPair#4` to `#9`: their goals need an instance of a quantified assertion about an +uninterpreted two-argument symbol (the pair address of `(token0, token1)`), which neither +`omega` nor the search instantiates; `vc_lite`'s `simp_all` alternative also loops there, and its +recursion-limit error, a runtime exception, is not caught by `first`. These rows prove solar-verify's exported obligations only; tying them to the source +semantics and the bytecode is the spec connection's work (Verify/Spec), not this directory's. diff --git a/Contracts/UniswapV2/VC/discharge.sh b/Contracts/UniswapV2/VC/discharge.sh new file mode 100755 index 00000000..0157aca1 --- /dev/null +++ b/Contracts/UniswapV2/VC/discharge.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Kernel discharge of solar-verify's verification conditions for the Uniswap V2 port. +# +# Contracts/UniswapV2/VC/discharge.sh SOLAR_ROOT SOLAR_VERIFY OUT [CONTRACT...] +# +# SOLAR_ROOT is a solar checkout (paradigmxyz/solar) with solar-tv/uniswap-v2/port.py and +# crates/verify/uniswap-v2/{apply_specs.py,uniswap-v2.spec}; SOLAR_VERIFY its solar-verify binary. +# v2-core is GPL-3.0, so this repository keeps neither the port nor its exports: the script writes +# the port (port.py clones v2-core at the pinned commit), applies the specs, exports every query +# with 'solar-verify --emit-lean' (manifest version 2) and runs Verify/Discharge/discharge.sh on +# each export, all under OUT. CONTRACT is Math, Factory, ERC20 or Pair (default: all four). +# +# Each OUT/vcs//discharge/{results,summary}.tsv is the per-row verdict, with the axioms of every +# proof and the vacuity column; the run fails unless every required obligation of every contract +# is proved by a proof whose axioms are propext, Classical.choice and Quot.sound. +# +# Environment: UV2_TIMEOUT_MS (solar-verify's per-query timeout, default 120000; Pair.swap needs +# it), UV2_LEAN_TIMEOUT (seconds per Lean attempt, default 120), and discharge.sh's DISCHARGE_*. +set -euo pipefail +solar=$(cd "$1" && pwd) +verifier=$(realpath "$2") +mkdir -p "$3" +out=$(cd "$3" && pwd) +shift 3 +here=$(cd "$(dirname "$0")" && pwd) +root=$(cd "$here/../../.." && pwd) +contracts=("$@") +[[ ${#contracts[@]} -gt 0 ]] || contracts=(Math Factory ERC20 Pair) +declare -A file=([Math]=libraries/Math.sol [Factory]=UniswapV2Factory.sol + [ERC20]=UniswapV2ERC20.sol [Pair]=UniswapV2Pair.sol) + +python3 "$solar/solar-tv/uniswap-v2/port.py" --v2-core "$out/v2-core" --out "$out/src" +rm -rf "$out/spec" +python3 "$solar/crates/verify/uniswap-v2/apply_specs.py" --src "$out/src" --out "$out/spec" + +status=0 +for c in "${contracts[@]}"; do + f=${file[$c]:-} + [[ -n $f ]] || { echo "error: unknown contract $c" >&2; exit 2; } + rm -rf "$out/vcs/$c" + # solar-verify exits 1 when a unit fails to verify or export; discharge.sh then fails closed on + # the manifest, so the export's own status is reported but not trusted. + (cd "$out/spec" && "$verifier" --timeout "${UV2_TIMEOUT_MS:-120000}" --emit-lean "$out/vcs/$c" "$f") \ + >"$out/vcs-$c.log" 2>&1 || echo "solar-verify: $c exited $?" >&2 + if DISCHARGE_SOURCE_ROOT="$out/spec" "$root/Verify/Discharge/discharge.sh" "$out/vcs/$c" \ + "${UV2_LEAN_TIMEOUT:-120}"; then + echo "$c: every required obligation proved" + else + echo "$c: FAILED (see $out/vcs/$c/discharge/results.tsv)" + status=1 + fi +done +exit $status diff --git a/Contracts/Vault/Audit.lean b/Contracts/Vault/Audit.lean new file mode 100644 index 00000000..e89745e1 --- /dev/null +++ b/Contracts/Vault/Audit.lean @@ -0,0 +1,24 @@ +import Contracts.Vault.Proofs.Vault.constructor +import Contracts.Vault.Proofs.Vault.deposit +import Contracts.Vault.Proofs.Vault.withdraw +import Contracts.Vault.Proofs.Vacuous + +/-! Fails unless every theorem under `Contracts.Vault.constructor`, `Contracts.Vault.deposit`, `Contracts.Vault.withdraw`, `Contracts.Vault.Vacuous` uses no axiom but `propext`, +`Classical.choice` and `Quot.sound`, and prints how many it checked. -/ + +open Lean Elab Command in +#eval show CommandElabM Unit from do + let env ← getEnv + let roots : List Name := [`Contracts.Vault.constructor, `Contracts.Vault.deposit, `Contracts.Vault.withdraw, + `Contracts.Vault.Vacuous] + let allowed : List Name := [`propext, `Classical.choice, `Quot.sound] + let mut n := 0 + for (name, info) in env.constants.toList do + unless roots.any (·.isPrefixOf name) do continue + unless info matches .thmInfo _ do continue + let axs ← Lean.collectAxioms name + for a in axs do + unless allowed.contains a do throwError "{name} uses axiom {a}" + n := n + 1 + if n == 0 then throwError "no theorems found" + IO.println s!"Vault: {n} theorems, axioms within propext, Classical.choice, Quot.sound" diff --git a/Contracts/Vault/Proofs/Vacuous.lean b/Contracts/Vault/Proofs/Vacuous.lean new file mode 100644 index 00000000..fbdb05f0 --- /dev/null +++ b/Contracts/Vault/Proofs/Vacuous.lean @@ -0,0 +1,41 @@ +import Contracts.ArrayMax.Bounded +import Contracts.Vault.Vc.Vault.deposit +import Contracts.Vault.Vc.Vault.withdraw + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +/-! Vault's vacuous obligations. Each theorem proves that the obligation's assertions and guard +alone are unsatisfiable: the obligation with its goal replaced by `false` is valid. These +obligations therefore hold whatever their goal says, and their proofs (Proofs/Vault/) are no +evidence about the goal. They are the paths that start with the reentrancy guard `locked` held, +which the contract invariant and the entry point's own check exclude. -/ + +namespace Contracts.Vault.Vacuous + +open SolarVerify.Vc SolarVerify.Smt + +/-- The obligation with goal `false`: valid exactly when its hypotheses refute. -/ +def refute (o : Obligation) : Obligation := { o with goal := .bool false } + +/-- Vault.deposit#6 (side): its hypotheses refute. -/ +theorem deposit_ob6 : (refute SolarVerifyVc.Vault.deposit.ob6).Valid := by + unfold refute; first | vc_bounded_valid | vc_valid + +/-- Vault.deposit#7: its hypotheses refute (its goal is already `false`). -/ +theorem deposit_ob7 : (refute SolarVerifyVc.Vault.deposit.ob7).Valid := by + unfold refute; first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#6: its hypotheses refute. -/ +theorem withdraw_ob6 : (refute SolarVerifyVc.Vault.withdraw.ob6).Valid := by + unfold refute; first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#7 (side): its hypotheses refute. -/ +theorem withdraw_ob7 : (refute SolarVerifyVc.Vault.withdraw.ob7).Valid := by + unfold refute; first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#8: its hypotheses refute (its goal is already `false`). -/ +theorem withdraw_ob8 : (refute SolarVerifyVc.Vault.withdraw.ob8).Valid := by + unfold refute; first | vc_bounded_valid | vc_valid + +end Contracts.Vault.Vacuous diff --git a/Contracts/Vault/Proofs/Vault/constructor.lean b/Contracts/Vault/Proofs/Vault/constructor.lean new file mode 100644 index 00000000..a3d5d50a --- /dev/null +++ b/Contracts/Vault/Proofs/Vault/constructor.lean @@ -0,0 +1,20 @@ +import Contracts.ArrayMax.Bounded +import Contracts.Vault.Vc.Vault.constructor + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +/-! Kernel proofs of the required obligations of Vault.constructor, as the frozen v1 export states them +(`Vc/Vault/constructor.lean`). -/ + +namespace Contracts.Vault.constructor + +/-- Vault.constructor#1 (obligation): contract invariant not established by constructor: totalShares == sumShares. -/ +theorem ob1 : SolarVerifyVc.Vault.constructor.ob1.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.constructor#2 (obligation): contract invariant not established by constructor: totalShares <= totalAssets. -/ +theorem ob2 : SolarVerifyVc.Vault.constructor.ob2.Valid := by + first | vc_bounded_valid | vc_valid + +end Contracts.Vault.constructor diff --git a/Contracts/Vault/Proofs/Vault/deposit.lean b/Contracts/Vault/Proofs/Vault/deposit.lean new file mode 100644 index 00000000..8ac0a56e --- /dev/null +++ b/Contracts/Vault/Proofs/Vault/deposit.lean @@ -0,0 +1,40 @@ +import Contracts.ArrayMax.Bounded +import Contracts.Vault.Vc.Vault.deposit + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +/-! Kernel proofs of the required obligations of Vault.deposit, as the frozen v1 export states them +(`Vc/Vault/deposit.lean`). -/ + +namespace Contracts.Vault.deposit + +/-- Vault.deposit#0 (side): side. -/ +theorem ob0 : SolarVerifyVc.Vault.deposit.ob0.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.deposit#2 (obligation): postcondition not satisfied: shares[msg.sender] == old(shares[msg.sender]) + amount. -/ +theorem ob2 : SolarVerifyVc.Vault.deposit.ob2.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.deposit#3 (obligation): postcondition not satisfied: !locked. -/ +theorem ob3 : SolarVerifyVc.Vault.deposit.ob3.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.deposit#4 (obligation): contract invariant not preserved: totalShares == sumShares. -/ +theorem ob4 : SolarVerifyVc.Vault.deposit.ob4.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.deposit#5 (obligation): contract invariant not preserved: totalShares <= totalAssets. -/ +theorem ob5 : SolarVerifyVc.Vault.deposit.ob5.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.deposit#6 (side): side. -/ +theorem ob6 : SolarVerifyVc.Vault.deposit.ob6.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.deposit#7 (obligation): entry point does not revert while reentrancy guard 'locked' is held. -/ +theorem ob7 : SolarVerifyVc.Vault.deposit.ob7.Valid := by + first | vc_bounded_valid | vc_valid + +end Contracts.Vault.deposit diff --git a/Contracts/Vault/Proofs/Vault/withdraw.lean b/Contracts/Vault/Proofs/Vault/withdraw.lean new file mode 100644 index 00000000..59e308bf --- /dev/null +++ b/Contracts/Vault/Proofs/Vault/withdraw.lean @@ -0,0 +1,44 @@ +import Contracts.ArrayMax.Bounded +import Contracts.Vault.Vc.Vault.withdraw + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 + +/-! Kernel proofs of the required obligations of Vault.withdraw, as the frozen v1 export states them +(`Vc/Vault/withdraw.lean`). -/ + +namespace Contracts.Vault.withdraw + +/-- Vault.withdraw#0 (obligation): assertion failed: totalShares == sumShares && totalShares <= totalAssets. -/ +theorem ob0 : SolarVerifyVc.Vault.withdraw.ob0.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#1 (side): side. -/ +theorem ob1 : SolarVerifyVc.Vault.withdraw.ob1.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#3 (obligation): postcondition not satisfied: !locked. -/ +theorem ob3 : SolarVerifyVc.Vault.withdraw.ob3.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#4 (obligation): contract invariant not preserved: totalShares == sumShares. -/ +theorem ob4 : SolarVerifyVc.Vault.withdraw.ob4.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#5 (obligation): contract invariant not preserved: totalShares <= totalAssets. -/ +theorem ob5 : SolarVerifyVc.Vault.withdraw.ob5.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#6 (obligation): assertion failed: totalShares == sumShares && totalShares <= totalAssets. -/ +theorem ob6 : SolarVerifyVc.Vault.withdraw.ob6.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#7 (side): side. -/ +theorem ob7 : SolarVerifyVc.Vault.withdraw.ob7.Valid := by + first | vc_bounded_valid | vc_valid + +/-- Vault.withdraw#8 (obligation): entry point does not revert while reentrancy guard 'locked' is held. -/ +theorem ob8 : SolarVerifyVc.Vault.withdraw.ob8.Valid := by + first | vc_bounded_valid | vc_valid + +end Contracts.Vault.withdraw diff --git a/Contracts/Vault/README.md b/Contracts/Vault/README.md new file mode 100644 index 00000000..fe06d503 --- /dev/null +++ b/Contracts/Vault/README.md @@ -0,0 +1,28 @@ +# Vault: solar-verify's obligations in the Lean kernel + +`Vc/` holds the frozen v1 export of `crates/verify/examples/Vault.sol` (paradigmxyz/solar +7f4e94e, `solar-verify --emit-lean`), with its first line `import SolarVerify` read as +`import Verify.Obligation`; `Vc/frozen.sha256` locks the unchanged export. `Proofs/Vault/` proves +every required obligation with `vc_valid` or the bounded search of `../ArrayMax/Bounded.lean`, and +`Audit.lean` fails unless every theorem uses only `propext`, `Classical.choice` and `Quot.sound`. + +## Vacuous obligations + +Five obligations hold only because their hypotheses refute: `Proofs/Vacuous.lean` proves, for +each, the obligation with its goal replaced by `false`. Their proofs say nothing about their +goals, so they are not evidence for the property they name: + +| Obligation | Kind | +| --- | --- | +| Vault.deposit#6 | side | +| Vault.deposit#7 | entry point does not revert while the reentrancy guard is held | +| Vault.withdraw#6 | assertion `totalShares == sumShares && totalShares <= totalAssets` | +| Vault.withdraw#7 | side | +| Vault.withdraw#8 | entry point does not revert while the reentrancy guard is held | + +They are the queries of each entry point's second script (`script1`), which models a call +that enters while `locked` is held: its first guard is `locked` and the next conjoins +`!locked` (the entry point's `require(!locked)`), so every path of the script is infeasible. For +the reentrancy checks (#7, #8) that refutation is the intended answer: a reentrant call cannot get +past the guard. withdraw#6 is the invariant assertion on that infeasible path; the same +assertion on the feasible path is withdraw#0, which is not vacuous. diff --git a/Contracts/Vault/Vc/Vault/constructor.lean b/Contracts/Vault/Vc/Vault/constructor.lean new file mode 100644 index 00000000..4ac9c2da --- /dev/null +++ b/Contracts/Vault/Vc/Vault/constructor.lean @@ -0,0 +1,78 @@ +-- Generated by solar-verify --emit-lean (format 1); do not edit. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.Vault.constructor +open SolarVerify.Smt SolarVerify.Vc + +/-- Script 0 of Vault.constructor: the solver's assertion stack. -/ +def script0 : Script where + decls := [ + ⟨"|this@1|", [], .int⟩, + ⟨"|msg.sender@2|", [], .int⟩, + ⟨"|msg.value@3|", [], .int⟩, + ⟨"|block.timestamp@4|", [], .int⟩, + ⟨"|block.number@5|", [], .int⟩, + ⟨"|block.chainid@6|", [], .int⟩, + ⟨"|tx.origin@7|", [], .int⟩, + ⟨"|tx.gasprice@8|", [], .int⟩, + ⟨"|msg.sig@9|", [], .int⟩, + ⟨"|msg.data@10|", [], .int⟩, + ⟨"|block.basefee@11|", [], .int⟩, + ⟨"|block.blobbasefee@12|", [], .int⟩, + ⟨"|block.coinbase@13|", [], .int⟩, + ⟨"|block.prevrandao@14|", [], .int⟩, + ⟨"|block.difficulty@15|", [], .int⟩, + ⟨"|block.gaslimit@16|", [], .int⟩, + ⟨"|asset@17|", [], .int⟩, + ⟨"|__balance@18|", [], (.array .int .int)⟩, + ⟨"|__code_epoch@19|", [], .int⟩, + ⟨"|_asset@20|", [], .int⟩, + ⟨"|g@21|", [], .bool⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 16 []], .app .le [.fn 16 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 18 []], .app .le [.fn 18 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 19 []], .app .le [.fn 19 [], .int 1461501637330902918203684832716283019655932542975]], + .app .eq [.fn 20 [], .app .and [.bool true, .app .eq [.fn 2 [], .int 0]]] + ] + +/-- Vault.constructor#0: a query only a warning reads (sat). -/ +def ob0 : Obligation where + script := script0 + upto := 20 + guard := .fn 20 [] + goal := .bool false + +/-- Vault.constructor#1: contract invariant not established by constructor: `totalShares == sumShares` (unsat). -/ +def ob1 : Obligation where + script := script0 + upto := 20 + guard := .fn 20 [] + goal := .app .eq [.int 0, .int 0] + +/-- Vault.constructor#2: contract invariant not established by constructor: `totalShares <= totalAssets` (unsat). -/ +def ob2 : Obligation where + script := script0 + upto := 20 + guard := .fn 20 [] + goal := .app .le [.int 0, .int 0] + +end SolarVerifyVc.Vault.constructor diff --git a/Contracts/Vault/Vc/Vault/deposit.lean b/Contracts/Vault/Vc/Vault/deposit.lean new file mode 100644 index 00000000..e45fd54e --- /dev/null +++ b/Contracts/Vault/Vc/Vault/deposit.lean @@ -0,0 +1,237 @@ +-- Generated by solar-verify --emit-lean (format 1); do not edit. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.Vault.deposit +open SolarVerify.Smt SolarVerify.Vc + +/-- Script 0 of Vault.deposit: the solver's assertion stack. -/ +def script0 : Script where + decls := [ + ⟨"|this@1|", [], .int⟩, + ⟨"|msg.sender@2|", [], .int⟩, + ⟨"|msg.value@3|", [], .int⟩, + ⟨"|block.timestamp@4|", [], .int⟩, + ⟨"|block.number@5|", [], .int⟩, + ⟨"|block.chainid@6|", [], .int⟩, + ⟨"|tx.origin@7|", [], .int⟩, + ⟨"|tx.gasprice@8|", [], .int⟩, + ⟨"|msg.sig@9|", [], .int⟩, + ⟨"|msg.data@10|", [], .int⟩, + ⟨"|block.basefee@11|", [], .int⟩, + ⟨"|block.blobbasefee@12|", [], .int⟩, + ⟨"|block.coinbase@13|", [], .int⟩, + ⟨"|block.prevrandao@14|", [], .int⟩, + ⟨"|block.difficulty@15|", [], .int⟩, + ⟨"|block.gaslimit@16|", [], .int⟩, + ⟨"|sumShares@17|", [], .int⟩, + ⟨"|asset@18|", [], .int⟩, + ⟨"|totalShares@19|", [], .int⟩, + ⟨"|totalAssets@20|", [], .int⟩, + ⟨"|shares@21|", [], (.array .int .int)⟩, + ⟨"|locked@22|", [], .bool⟩, + ⟨"|__balance@23|", [], (.array .int .int)⟩, + ⟨"|__code_epoch@24|", [], .int⟩, + ⟨"|amount@25|", [], .int⟩, + ⟨"|g@26|", [], .bool⟩, + ⟨"|g@27|", [], .bool⟩, + ⟨"|g@28|", [], .bool⟩, + ⟨"|g@29|", [], .bool⟩, + ⟨"|__code_epoch@30|", [], .int⟩, + ⟨"|__balance@31|", [], (.array .int .int)⟩, + ⟨"|g@32|", [], .bool⟩, + ⟨"|ext_ret@33|", [], .bool⟩, + ⟨"|g@34|", [], .bool⟩, + ⟨"|arith@35|", [], .int⟩, + ⟨"|g@36|", [], .bool⟩, + ⟨"|arith@37|", [], .int⟩, + ⟨"|g@38|", [], .bool⟩, + ⟨"|sumShares@39|", [], .int⟩, + ⟨"|arith@40|", [], .int⟩, + ⟨"|g@41|", [], .bool⟩, + ⟨"|shares@42|", [], (.array .int .int)⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 16 []], .app .le [.fn 16 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 18 []], .app .le [.fn 18 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 19 []], .app .le [.fn 19 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 23 []], .app .le [.fn 23 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 24 []], .app .le [.fn 24 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 25 [], .app .and [.bool true, .app .eq [.fn 18 [], .fn 16 []]]], + .app .eq [.fn 26 [], .app .and [.fn 25 [], .app .le [.fn 18 [], .fn 19 []]]], + .app .eq [.fn 27 [], .app .and [.fn 26 [], .app .eq [.fn 2 [], .int 0]]], + .app .eq [.fn 28 [], .app .and [.fn 27 [], .app .not [.fn 21 []]]], + .app .and [.app .le [.int 0, .fn 29 []], .app .le [.fn 29 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 31 [], .app .and [.fn 28 [], .app .ge [.app .select [.fn 30 [], .fn 0 []], .app .select [.fn 22 [], .fn 0 []]]]], + .app .eq [.fn 33 [], .app .and [.fn 31 [], .fn 32 []]], + .app .eq [.fn 34 [], .app .add [.fn 19 [], .fn 24 []]], + .app .eq [.fn 35 [], .app .and [.fn 33 [], .app .and [.app .le [.int 0, .fn 34 []], .app .le [.fn 34 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 36 [], .app .add [.fn 18 [], .fn 24 []]], + .app .eq [.fn 37 [], .app .and [.fn 35 [], .app .and [.app .le [.int 0, .fn 36 []], .app .le [.fn 36 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 38 [], .app .add [.fn 16 [], .fn 24 []]], + .app .and [.app .le [.int 0, .app .select [.fn 20 [], .fn 1 []]], .app .le [.app .select [.fn 20 [], .fn 1 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 39 [], .app .add [.app .select [.fn 20 [], .fn 1 []], .fn 24 []]], + .app .eq [.fn 40 [], .app .and [.fn 37 [], .app .and [.app .le [.int 0, .fn 39 []], .app .le [.fn 39 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 41 [], .app .store [.fn 20 [], .fn 1 [], .fn 39 []]], + .app .and [.app .le [.int 0, .app .select [.fn 41 [], .fn 1 []]], .app .le [.app .select [.fn 41 [], .fn 1 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .app .select [.fn 20 [], .fn 1 []]], .app .le [.app .select [.fn 20 [], .fn 1 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]] + ] + +/-- Script 1 of Vault.deposit: the solver's assertion stack. -/ +def script1 : Script where + decls := [ + ⟨"|this@43|", [], .int⟩, + ⟨"|msg.sender@44|", [], .int⟩, + ⟨"|msg.value@45|", [], .int⟩, + ⟨"|block.timestamp@46|", [], .int⟩, + ⟨"|block.number@47|", [], .int⟩, + ⟨"|block.chainid@48|", [], .int⟩, + ⟨"|tx.origin@49|", [], .int⟩, + ⟨"|tx.gasprice@50|", [], .int⟩, + ⟨"|msg.sig@51|", [], .int⟩, + ⟨"|msg.data@52|", [], .int⟩, + ⟨"|block.basefee@53|", [], .int⟩, + ⟨"|block.blobbasefee@54|", [], .int⟩, + ⟨"|block.coinbase@55|", [], .int⟩, + ⟨"|block.prevrandao@56|", [], .int⟩, + ⟨"|block.difficulty@57|", [], .int⟩, + ⟨"|block.gaslimit@58|", [], .int⟩, + ⟨"|sumShares@59|", [], .int⟩, + ⟨"|asset@60|", [], .int⟩, + ⟨"|totalShares@61|", [], .int⟩, + ⟨"|totalAssets@62|", [], .int⟩, + ⟨"|shares@63|", [], (.array .int .int)⟩, + ⟨"|locked@64|", [], .bool⟩, + ⟨"|__balance@65|", [], (.array .int .int)⟩, + ⟨"|__code_epoch@66|", [], .int⟩, + ⟨"|amount@67|", [], .int⟩, + ⟨"|g@68|", [], .bool⟩, + ⟨"|g@69|", [], .bool⟩, + ⟨"|__code_epoch@70|", [], .int⟩, + ⟨"|__balance@71|", [], (.array .int .int)⟩, + ⟨"|g@72|", [], .bool⟩, + ⟨"|ext_ret@73|", [], .bool⟩, + ⟨"|g@74|", [], .bool⟩, + ⟨"|arith@75|", [], .int⟩, + ⟨"|g@76|", [], .bool⟩, + ⟨"|arith@77|", [], .int⟩, + ⟨"|g@78|", [], .bool⟩, + ⟨"|sumShares@79|", [], .int⟩, + ⟨"|arith@80|", [], .int⟩, + ⟨"|g@81|", [], .bool⟩, + ⟨"|shares@82|", [], (.array .int .int)⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 16 []], .app .le [.fn 16 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 18 []], .app .le [.fn 18 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 19 []], .app .le [.fn 19 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 23 []], .app .le [.fn 23 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 24 []], .app .le [.fn 24 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 25 [], .app .and [.bool true, .fn 21 []]], + .app .eq [.fn 26 [], .app .and [.fn 25 [], .app .not [.fn 21 []]]], + .app .and [.app .le [.int 0, .fn 27 []], .app .le [.fn 27 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 29 [], .app .and [.fn 26 [], .app .ge [.app .select [.fn 28 [], .fn 0 []], .app .select [.fn 22 [], .fn 0 []]]]], + .app .eq [.fn 31 [], .app .and [.fn 29 [], .fn 30 []]], + .app .eq [.fn 32 [], .app .add [.fn 19 [], .fn 24 []]], + .app .eq [.fn 33 [], .app .and [.fn 31 [], .app .and [.app .le [.int 0, .fn 32 []], .app .le [.fn 32 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 34 [], .app .add [.fn 18 [], .fn 24 []]], + .app .eq [.fn 35 [], .app .and [.fn 33 [], .app .and [.app .le [.int 0, .fn 34 []], .app .le [.fn 34 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 36 [], .app .add [.fn 16 [], .fn 24 []]], + .app .and [.app .le [.int 0, .app .select [.fn 20 [], .fn 1 []]], .app .le [.app .select [.fn 20 [], .fn 1 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 37 [], .app .add [.app .select [.fn 20 [], .fn 1 []], .fn 24 []]], + .app .eq [.fn 38 [], .app .and [.fn 35 [], .app .and [.app .le [.int 0, .fn 37 []], .app .le [.fn 37 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 39 [], .app .store [.fn 20 [], .fn 1 [], .fn 37 []]] + ] + +/-- Vault.deposit#0: a query the encoding relies on (unsat). -/ +def ob0 : Obligation where + script := script0 + upto := 27 + guard := .fn 28 [] + goal := .bool true + +/-- Vault.deposit#1: a query only a warning reads (sat). -/ +def ob1 : Obligation where + script := script0 + upto := 38 + guard := .fn 40 [] + goal := .bool false + +/-- Vault.deposit#2: postcondition not satisfied: `shares[msg.sender] == old(shares[msg.sender]) + amount` (unsat). -/ +def ob2 : Obligation where + script := script0 + upto := 40 + guard := .fn 40 [] + goal := .app .eq [.app .select [.fn 41 [], .fn 1 []], .app .add [.app .select [.fn 20 [], .fn 1 []], .fn 24 []]] + +/-- Vault.deposit#3: postcondition not satisfied: `!locked` (unsat). -/ +def ob3 : Obligation where + script := script0 + upto := 40 + guard := .fn 40 [] + goal := .app .not [.bool false] + +/-- Vault.deposit#4: contract invariant not preserved: `totalShares == sumShares` (unsat). -/ +def ob4 : Obligation where + script := script0 + upto := 40 + guard := .fn 40 [] + goal := .app .eq [.fn 36 [], .fn 38 []] + +/-- Vault.deposit#5: contract invariant not preserved: `totalShares <= totalAssets` (unsat). -/ +def ob5 : Obligation where + script := script0 + upto := 40 + guard := .fn 40 [] + goal := .app .le [.fn 36 [], .fn 34 []] + +/-- Vault.deposit#6: a query the encoding relies on (unsat). -/ +def ob6 : Obligation where + script := script1 + upto := 25 + guard := .fn 26 [] + goal := .bool true + +/-- Vault.deposit#7: entry point does not revert while reentrancy guard `locked` is held (unsat). -/ +def ob7 : Obligation where + script := script1 + upto := 36 + guard := .fn 38 [] + goal := .bool false + +end SolarVerifyVc.Vault.deposit diff --git a/Contracts/Vault/Vc/Vault/withdraw.lean b/Contracts/Vault/Vc/Vault/withdraw.lean new file mode 100644 index 00000000..585c9b6c --- /dev/null +++ b/Contracts/Vault/Vc/Vault/withdraw.lean @@ -0,0 +1,252 @@ +-- Generated by solar-verify --emit-lean (format 1); do not edit. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.Vault.withdraw +open SolarVerify.Smt SolarVerify.Vc + +/-- Script 0 of Vault.withdraw: the solver's assertion stack. -/ +def script0 : Script where + decls := [ + ⟨"|this@1|", [], .int⟩, + ⟨"|msg.sender@2|", [], .int⟩, + ⟨"|msg.value@3|", [], .int⟩, + ⟨"|block.timestamp@4|", [], .int⟩, + ⟨"|block.number@5|", [], .int⟩, + ⟨"|block.chainid@6|", [], .int⟩, + ⟨"|tx.origin@7|", [], .int⟩, + ⟨"|tx.gasprice@8|", [], .int⟩, + ⟨"|msg.sig@9|", [], .int⟩, + ⟨"|msg.data@10|", [], .int⟩, + ⟨"|block.basefee@11|", [], .int⟩, + ⟨"|block.blobbasefee@12|", [], .int⟩, + ⟨"|block.coinbase@13|", [], .int⟩, + ⟨"|block.prevrandao@14|", [], .int⟩, + ⟨"|block.difficulty@15|", [], .int⟩, + ⟨"|block.gaslimit@16|", [], .int⟩, + ⟨"|sumShares@17|", [], .int⟩, + ⟨"|asset@18|", [], .int⟩, + ⟨"|totalShares@19|", [], .int⟩, + ⟨"|totalAssets@20|", [], .int⟩, + ⟨"|shares@21|", [], (.array .int .int)⟩, + ⟨"|locked@22|", [], .bool⟩, + ⟨"|__balance@23|", [], (.array .int .int)⟩, + ⟨"|__code_epoch@24|", [], .int⟩, + ⟨"|amount@25|", [], .int⟩, + ⟨"|g@26|", [], .bool⟩, + ⟨"|g@27|", [], .bool⟩, + ⟨"|g@28|", [], .bool⟩, + ⟨"|g@29|", [], .bool⟩, + ⟨"|g@30|", [], .bool⟩, + ⟨"|arith@31|", [], .int⟩, + ⟨"|g@32|", [], .bool⟩, + ⟨"|shares@33|", [], (.array .int .int)⟩, + ⟨"|sumShares@34|", [], .int⟩, + ⟨"|arith@35|", [], .int⟩, + ⟨"|g@36|", [], .bool⟩, + ⟨"|arith@37|", [], .int⟩, + ⟨"|g@38|", [], .bool⟩, + ⟨"|g@39|", [], .bool⟩, + ⟨"|__code_epoch@40|", [], .int⟩, + ⟨"|__balance@41|", [], (.array .int .int)⟩, + ⟨"|g@42|", [], .bool⟩, + ⟨"|ext_ret@43|", [], .bool⟩, + ⟨"|g@44|", [], .bool⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 16 []], .app .le [.fn 16 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 18 []], .app .le [.fn 18 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 19 []], .app .le [.fn 19 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 23 []], .app .le [.fn 23 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 24 []], .app .le [.fn 24 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 25 [], .app .and [.bool true, .app .eq [.fn 18 [], .fn 16 []]]], + .app .eq [.fn 26 [], .app .and [.fn 25 [], .app .le [.fn 18 [], .fn 19 []]]], + .app .eq [.fn 27 [], .app .and [.fn 26 [], .app .eq [.fn 2 [], .int 0]]], + .app .eq [.fn 28 [], .app .and [.fn 27 [], .app .not [.fn 21 []]]], + .app .and [.app .le [.int 0, .app .select [.fn 20 [], .fn 1 []]], .app .le [.app .select [.fn 20 [], .fn 1 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 29 [], .app .and [.fn 28 [], .app .ge [.app .select [.fn 20 [], .fn 1 []], .fn 24 []]]], + .app .and [.app .le [.int 0, .app .select [.fn 20 [], .fn 1 []]], .app .le [.app .select [.fn 20 [], .fn 1 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 30 [], .app .sub [.app .select [.fn 20 [], .fn 1 []], .fn 24 []]], + .app .eq [.fn 31 [], .app .and [.fn 29 [], .app .and [.app .le [.int 0, .fn 30 []], .app .le [.fn 30 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 32 [], .app .store [.fn 20 [], .fn 1 [], .fn 30 []]], + .app .eq [.fn 33 [], .app .sub [.fn 16 [], .fn 24 []]], + .app .eq [.fn 34 [], .app .sub [.fn 18 [], .fn 24 []]], + .app .eq [.fn 35 [], .app .and [.fn 31 [], .app .and [.app .le [.int 0, .fn 34 []], .app .le [.fn 34 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 36 [], .app .sub [.fn 19 [], .fn 24 []]], + .app .eq [.fn 37 [], .app .and [.fn 35 [], .app .and [.app .le [.int 0, .fn 36 []], .app .le [.fn 36 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 38 [], .app .and [.fn 37 [], .app .and [.app .eq [.fn 34 [], .fn 33 []], .app .le [.fn 34 [], .fn 36 []]]]], + .app .and [.app .le [.int 0, .fn 39 []], .app .le [.fn 39 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 41 [], .app .and [.fn 38 [], .app .ge [.app .select [.fn 40 [], .fn 0 []], .app .select [.fn 22 [], .fn 0 []]]]], + .app .eq [.fn 43 [], .app .and [.fn 41 [], .fn 42 []]] + ] + +/-- Script 1 of Vault.withdraw: the solver's assertion stack. -/ +def script1 : Script where + decls := [ + ⟨"|this@45|", [], .int⟩, + ⟨"|msg.sender@46|", [], .int⟩, + ⟨"|msg.value@47|", [], .int⟩, + ⟨"|block.timestamp@48|", [], .int⟩, + ⟨"|block.number@49|", [], .int⟩, + ⟨"|block.chainid@50|", [], .int⟩, + ⟨"|tx.origin@51|", [], .int⟩, + ⟨"|tx.gasprice@52|", [], .int⟩, + ⟨"|msg.sig@53|", [], .int⟩, + ⟨"|msg.data@54|", [], .int⟩, + ⟨"|block.basefee@55|", [], .int⟩, + ⟨"|block.blobbasefee@56|", [], .int⟩, + ⟨"|block.coinbase@57|", [], .int⟩, + ⟨"|block.prevrandao@58|", [], .int⟩, + ⟨"|block.difficulty@59|", [], .int⟩, + ⟨"|block.gaslimit@60|", [], .int⟩, + ⟨"|sumShares@61|", [], .int⟩, + ⟨"|asset@62|", [], .int⟩, + ⟨"|totalShares@63|", [], .int⟩, + ⟨"|totalAssets@64|", [], .int⟩, + ⟨"|shares@65|", [], (.array .int .int)⟩, + ⟨"|locked@66|", [], .bool⟩, + ⟨"|__balance@67|", [], (.array .int .int)⟩, + ⟨"|__code_epoch@68|", [], .int⟩, + ⟨"|amount@69|", [], .int⟩, + ⟨"|g@70|", [], .bool⟩, + ⟨"|g@71|", [], .bool⟩, + ⟨"|g@72|", [], .bool⟩, + ⟨"|arith@73|", [], .int⟩, + ⟨"|g@74|", [], .bool⟩, + ⟨"|shares@75|", [], (.array .int .int)⟩, + ⟨"|sumShares@76|", [], .int⟩, + ⟨"|arith@77|", [], .int⟩, + ⟨"|g@78|", [], .bool⟩, + ⟨"|arith@79|", [], .int⟩, + ⟨"|g@80|", [], .bool⟩, + ⟨"|g@81|", [], .bool⟩, + ⟨"|__code_epoch@82|", [], .int⟩, + ⟨"|__balance@83|", [], (.array .int .int)⟩, + ⟨"|g@84|", [], .bool⟩, + ⟨"|ext_ret@85|", [], .bool⟩, + ⟨"|g@86|", [], .bool⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 16 []], .app .le [.fn 16 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 18 []], .app .le [.fn 18 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 19 []], .app .le [.fn 19 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 23 []], .app .le [.fn 23 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 24 []], .app .le [.fn 24 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 25 [], .app .and [.bool true, .fn 21 []]], + .app .eq [.fn 26 [], .app .and [.fn 25 [], .app .not [.fn 21 []]]], + .app .and [.app .le [.int 0, .app .select [.fn 20 [], .fn 1 []]], .app .le [.app .select [.fn 20 [], .fn 1 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 27 [], .app .and [.fn 26 [], .app .ge [.app .select [.fn 20 [], .fn 1 []], .fn 24 []]]], + .app .and [.app .le [.int 0, .app .select [.fn 20 [], .fn 1 []]], .app .le [.app .select [.fn 20 [], .fn 1 []], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 28 [], .app .sub [.app .select [.fn 20 [], .fn 1 []], .fn 24 []]], + .app .eq [.fn 29 [], .app .and [.fn 27 [], .app .and [.app .le [.int 0, .fn 28 []], .app .le [.fn 28 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 30 [], .app .store [.fn 20 [], .fn 1 [], .fn 28 []]], + .app .eq [.fn 31 [], .app .sub [.fn 16 [], .fn 24 []]], + .app .eq [.fn 32 [], .app .sub [.fn 18 [], .fn 24 []]], + .app .eq [.fn 33 [], .app .and [.fn 29 [], .app .and [.app .le [.int 0, .fn 32 []], .app .le [.fn 32 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 34 [], .app .sub [.fn 19 [], .fn 24 []]], + .app .eq [.fn 35 [], .app .and [.fn 33 [], .app .and [.app .le [.int 0, .fn 34 []], .app .le [.fn 34 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 36 [], .app .and [.fn 35 [], .app .and [.app .eq [.fn 32 [], .fn 31 []], .app .le [.fn 32 [], .fn 34 []]]]], + .app .and [.app .le [.int 0, .fn 37 []], .app .le [.fn 37 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 39 [], .app .and [.fn 36 [], .app .ge [.app .select [.fn 38 [], .fn 0 []], .app .select [.fn 22 [], .fn 0 []]]]], + .app .eq [.fn 41 [], .app .and [.fn 39 [], .fn 40 []]] + ] + +/-- Vault.withdraw#0: assertion failed: `totalShares == sumShares && totalShares <= totalAssets` (unsat). -/ +def ob0 : Obligation where + script := script0 + upto := 37 + guard := .fn 37 [] + goal := .app .and [.app .eq [.fn 34 [], .fn 33 []], .app .le [.fn 34 [], .fn 36 []]] + +/-- Vault.withdraw#1: a query the encoding relies on (unsat). -/ +def ob1 : Obligation where + script := script0 + upto := 39 + guard := .fn 38 [] + goal := .bool true + +/-- Vault.withdraw#2: a query only a warning reads (sat). -/ +def ob2 : Obligation where + script := script0 + upto := 41 + guard := .fn 43 [] + goal := .bool false + +/-- Vault.withdraw#3: postcondition not satisfied: `!locked` (unsat). -/ +def ob3 : Obligation where + script := script0 + upto := 41 + guard := .fn 43 [] + goal := .app .not [.bool false] + +/-- Vault.withdraw#4: contract invariant not preserved: `totalShares == sumShares` (unsat). -/ +def ob4 : Obligation where + script := script0 + upto := 41 + guard := .fn 43 [] + goal := .app .eq [.fn 34 [], .fn 33 []] + +/-- Vault.withdraw#5: contract invariant not preserved: `totalShares <= totalAssets` (unsat). -/ +def ob5 : Obligation where + script := script0 + upto := 41 + guard := .fn 43 [] + goal := .app .le [.fn 34 [], .fn 36 []] + +/-- Vault.withdraw#6: assertion failed: `totalShares == sumShares && totalShares <= totalAssets` (unsat). -/ +def ob6 : Obligation where + script := script1 + upto := 35 + guard := .fn 35 [] + goal := .app .and [.app .eq [.fn 32 [], .fn 31 []], .app .le [.fn 32 [], .fn 34 []]] + +/-- Vault.withdraw#7: a query the encoding relies on (unsat). -/ +def ob7 : Obligation where + script := script1 + upto := 37 + guard := .fn 36 [] + goal := .bool true + +/-- Vault.withdraw#8: entry point does not revert while reentrancy guard `locked` is held (unsat). -/ +def ob8 : Obligation where + script := script1 + upto := 39 + guard := .fn 41 [] + goal := .bool false + +end SolarVerifyVc.Vault.withdraw diff --git a/Contracts/Vault/Vc/frozen.sha256 b/Contracts/Vault/Vc/frozen.sha256 new file mode 100644 index 00000000..0014a46c --- /dev/null +++ b/Contracts/Vault/Vc/frozen.sha256 @@ -0,0 +1,4 @@ +2589125ac7c0b22969b81edb8b4f4bba10b7404351cd3e1276974c2b25849edb manifest.json +93b5b6971bf6f4c4c907a55e8d270c15b831e41ce858493d1c02da1ddcacfc41 Vault/constructor.lean +de6d589769c68862abcf874f9f8a316923ce34478346ebd2ef62d9af5cd0ca74 Vault/deposit.lean +b7fc9bfd454493489523a9c64689393906408761f5f5fb42612e2fdd4b71320a Vault/withdraw.lean diff --git a/Contracts/Vault/Vc/manifest.json b/Contracts/Vault/Vc/manifest.json new file mode 100644 index 00000000..4c7b722f --- /dev/null +++ b/Contracts/Vault/Vc/manifest.json @@ -0,0 +1,716 @@ +{ + "arguments": [ + "--emit-lean", + "vc-exports/Vault", + "crates/verify/examples/Vault.sol" + ], + "compiler": "0.8.38+commit.7f4e94e0.solar.0.3.0-dev", + "errors": [], + "format": "solar-verify-lean", + "lean": { + "library": "SolarVerify", + "smt_sha256": "2c92f3bcd927369da89250662bd5a6174d3c06d0c3c38f5021509fe8810036e3", + "toolchain": "leanprover/lean4:v4.35.0", + "vc_sha256": "7275fa354f077a4826dd9fe56124cbffee2337d7a21975b477534fc5f45d7cfe" + }, + "options": { + "dry_run": false, + "only": null, + "strict": false, + "timeout_ms": 10000 + }, + "solvers": { + "bitwuzla": null, + "cvc5": "This is cvc5 version 1.3.1 [git ea1b484 on branch HEAD]", + "z3": "Z3 version 4.13.4 - 64 bit" + }, + "sources": [ + { + "path": "/home/hand/wt-inferred/crates/verify/examples/Vault.sol", + "sha256": "0e2017a2679b3fc98aa539d29ce350f9776dd0d14a0085aed88d9b26a9921526" + } + ], + "units": [ + { + "module": "Vault/constructor.lean", + "name": "Vault.constructor", + "namespace": "SolarVerifyVc.Vault.constructor", + "obligations": [ + { + "answer": "sat", + "asserts": 20, + "commands": 41, + "goal": "false", + "guard": "|g@21|", + "id": "Vault.constructor#0", + "lean": "SolarVerifyVc.Vault.constructor.ob0", + "required": false, + "role": "advisory", + "script": 0, + "smt_sha256": "be9fed92fdf387b9caa157050c55e1204e8292bab32c407b116b85ec1d83eb85", + "solver": "z3" + }, + { + "answer": "unsat", + "asserts": 20, + "commands": 41, + "goal": "(= 0 0)", + "guard": "|g@21|", + "id": "Vault.constructor#1", + "kind": "contract invariant not established by constructor", + "lean": "SolarVerifyVc.Vault.constructor.ob1", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 5, + "file": "crates/verify/examples/Vault.sol", + "line": 29 + }, + "smt_sha256": "cf9fc5408ee75df3d38cb1ed2d9d5da6a295560630661aa6e182a4ce3ef25911", + "solver": "z3", + "spec": { + "column": 6, + "file": "crates/verify/examples/Vault.sol", + "line": 12, + "text": "totalShares == sumShares" + } + }, + { + "answer": "unsat", + "asserts": 20, + "commands": 41, + "goal": "(<= 0 0)", + "guard": "|g@21|", + "id": "Vault.constructor#2", + "kind": "contract invariant not established by constructor", + "lean": "SolarVerifyVc.Vault.constructor.ob2", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 5, + "file": "crates/verify/examples/Vault.sol", + "line": 29 + }, + "smt_sha256": "f6f3a0446b0723589b121ca64f30214516787a05675926cd3863d1188000cd08", + "solver": "z3", + "spec": { + "column": 6, + "file": "crates/verify/examples/Vault.sol", + "line": 13, + "text": "totalShares <= totalAssets" + } + } + ], + "scripts": [ + { + "commands": 41, + "decls": [ + "|this@1|", + "|msg.sender@2|", + "|msg.value@3|", + "|block.timestamp@4|", + "|block.number@5|", + "|block.chainid@6|", + "|tx.origin@7|", + "|tx.gasprice@8|", + "|msg.sig@9|", + "|msg.data@10|", + "|block.basefee@11|", + "|block.blobbasefee@12|", + "|block.coinbase@13|", + "|block.prevrandao@14|", + "|block.difficulty@15|", + "|block.gaslimit@16|", + "|asset@17|", + "|__balance@18|", + "|__code_epoch@19|", + "|_asset@20|", + "|g@21|" + ], + "lean": "SolarVerifyVc.Vault.constructor.script0", + "smt": "Vault/constructor.script0.smt2" + } + ], + "status": "verified" + }, + { + "module": "Vault/deposit.lean", + "name": "Vault.deposit", + "namespace": "SolarVerifyVc.Vault.deposit", + "obligations": [ + { + "answer": "unsat", + "asserts": 27, + "commands": 57, + "goal": "true", + "guard": "|g@29|", + "id": "Vault.deposit#0", + "lean": "SolarVerifyVc.Vault.deposit.ob0", + "required": true, + "role": "side", + "script": 0, + "smt_sha256": "1bb13ffa737fca394f363c54a28e6230cbb4cfd769d2e2597c6707db6751f5e9", + "solver": "z3" + }, + { + "answer": "sat", + "asserts": 38, + "commands": 80, + "goal": "false", + "guard": "|g@41|", + "id": "Vault.deposit#1", + "lean": "SolarVerifyVc.Vault.deposit.ob1", + "required": false, + "role": "advisory", + "script": 0, + "smt_sha256": "298965751598e4d2a186c287e1401a935a5127ccea2ef00d9a5c7039e7082cf5", + "solver": "z3" + }, + { + "answer": "unsat", + "asserts": 40, + "commands": 82, + "goal": "(= (select |shares@42| |msg.sender@2|) (+ (select |shares@21| |msg.sender@2|) |amount@25|))", + "guard": "|g@41|", + "id": "Vault.deposit#2", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.Vault.deposit.ob2", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 10, + "file": "crates/verify/examples/Vault.sol", + "line": 33 + }, + "smt_sha256": "43c09697a2aba1cf1ac56b6328745301a9db8423ecb22680ebdbc7fa2583a9dc", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/Vault.sol", + "line": 33, + "text": "shares[msg.sender] == old(shares[msg.sender]) + amount" + } + }, + { + "answer": "unsat", + "asserts": 40, + "commands": 82, + "goal": "(not false)", + "guard": "|g@41|", + "id": "Vault.deposit#3", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.Vault.deposit.ob3", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 10, + "file": "crates/verify/examples/Vault.sol", + "line": 34 + }, + "smt_sha256": "502e56422a7eb88762cb36aaf99ff065e45e3c9f3c8aa94f4c9caf06ffe86fb7", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/Vault.sol", + "line": 34, + "text": "!locked" + } + }, + { + "answer": "unsat", + "asserts": 40, + "commands": 82, + "goal": "(= |arith@37| |sumShares@39|)", + "guard": "|g@41|", + "id": "Vault.deposit#4", + "kind": "contract invariant not preserved", + "lean": "SolarVerifyVc.Vault.deposit.ob4", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 5, + "file": "crates/verify/examples/Vault.sol", + "line": 35 + }, + "smt_sha256": "d240866e7adba02c2d167d110e95694e9e8d4fbae70f3161f60bd3fb907e7621", + "solver": "z3", + "spec": { + "column": 6, + "file": "crates/verify/examples/Vault.sol", + "line": 12, + "text": "totalShares == sumShares" + } + }, + { + "answer": "unsat", + "asserts": 40, + "commands": 82, + "goal": "(<= |arith@37| |arith@35|)", + "guard": "|g@41|", + "id": "Vault.deposit#5", + "kind": "contract invariant not preserved", + "lean": "SolarVerifyVc.Vault.deposit.ob5", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 5, + "file": "crates/verify/examples/Vault.sol", + "line": 35 + }, + "smt_sha256": "31d1668788e1beb06c7486ae834e50bba336d7f221b3510a921101d0d75ccef5", + "solver": "z3", + "spec": { + "column": 6, + "file": "crates/verify/examples/Vault.sol", + "line": 13, + "text": "totalShares <= totalAssets" + } + }, + { + "answer": "unsat", + "asserts": 25, + "commands": 53, + "goal": "true", + "guard": "|g@69|", + "id": "Vault.deposit#6", + "lean": "SolarVerifyVc.Vault.deposit.ob6", + "required": true, + "role": "side", + "script": 1, + "smt_sha256": "96336f40e2b3e9767e82579f08cbdff75976151a531f72d566b25e72124c3c2a", + "solver": "z3" + }, + { + "answer": "unsat", + "asserts": 36, + "commands": 76, + "goal": "false", + "guard": "|g@81|", + "id": "Vault.deposit#7", + "kind": "entry point does not revert while reentrancy guard `locked` is held", + "lean": "SolarVerifyVc.Vault.deposit.ob7", + "required": true, + "role": "obligation", + "script": 1, + "site": { + "column": 5, + "file": "crates/verify/examples/Vault.sol", + "line": 35 + }, + "smt_sha256": "97b1ef4bdf747896c6021c3e7822679cfe8502b8db97a1eb8770ec12d32aa602", + "solver": "z3", + "spec": null + } + ], + "scripts": [ + { + "commands": 82, + "decls": [ + "|this@1|", + "|msg.sender@2|", + "|msg.value@3|", + "|block.timestamp@4|", + "|block.number@5|", + "|block.chainid@6|", + "|tx.origin@7|", + "|tx.gasprice@8|", + "|msg.sig@9|", + "|msg.data@10|", + "|block.basefee@11|", + "|block.blobbasefee@12|", + "|block.coinbase@13|", + "|block.prevrandao@14|", + "|block.difficulty@15|", + "|block.gaslimit@16|", + "|sumShares@17|", + "|asset@18|", + "|totalShares@19|", + "|totalAssets@20|", + "|shares@21|", + "|locked@22|", + "|__balance@23|", + "|__code_epoch@24|", + "|amount@25|", + "|g@26|", + "|g@27|", + "|g@28|", + "|g@29|", + "|__code_epoch@30|", + "|__balance@31|", + "|g@32|", + "|ext_ret@33|", + "|g@34|", + "|arith@35|", + "|g@36|", + "|arith@37|", + "|g@38|", + "|sumShares@39|", + "|arith@40|", + "|g@41|", + "|shares@42|" + ], + "lean": "SolarVerifyVc.Vault.deposit.script0", + "smt": "Vault/deposit.script0.smt2" + }, + { + "commands": 76, + "decls": [ + "|this@43|", + "|msg.sender@44|", + "|msg.value@45|", + "|block.timestamp@46|", + "|block.number@47|", + "|block.chainid@48|", + "|tx.origin@49|", + "|tx.gasprice@50|", + "|msg.sig@51|", + "|msg.data@52|", + "|block.basefee@53|", + "|block.blobbasefee@54|", + "|block.coinbase@55|", + "|block.prevrandao@56|", + "|block.difficulty@57|", + "|block.gaslimit@58|", + "|sumShares@59|", + "|asset@60|", + "|totalShares@61|", + "|totalAssets@62|", + "|shares@63|", + "|locked@64|", + "|__balance@65|", + "|__code_epoch@66|", + "|amount@67|", + "|g@68|", + "|g@69|", + "|__code_epoch@70|", + "|__balance@71|", + "|g@72|", + "|ext_ret@73|", + "|g@74|", + "|arith@75|", + "|g@76|", + "|arith@77|", + "|g@78|", + "|sumShares@79|", + "|arith@80|", + "|g@81|", + "|shares@82|" + ], + "lean": "SolarVerifyVc.Vault.deposit.script1", + "smt": "Vault/deposit.script1.smt2" + } + ], + "status": "verified" + }, + { + "module": "Vault/withdraw.lean", + "name": "Vault.withdraw", + "namespace": "SolarVerifyVc.Vault.withdraw", + "obligations": [ + { + "answer": "unsat", + "asserts": 37, + "commands": 75, + "goal": "(and (= |arith@35| |sumShares@34|) (<= |arith@35| |arith@37|))", + "guard": "|g@38|", + "id": "Vault.withdraw#0", + "kind": "assertion failed", + "lean": "SolarVerifyVc.Vault.withdraw.ob0", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 14, + "file": "crates/verify/examples/Vault.sol", + "line": 52 + }, + "smt_sha256": "1252b739085b0777efae91e71682c72aea3adcc162f5f042167c7ca2f10b17a7", + "solver": "z3", + "spec": { + "column": 14, + "file": "crates/verify/examples/Vault.sol", + "line": 52, + "text": "totalShares == sumShares && totalShares <= totalAssets" + } + }, + { + "answer": "unsat", + "asserts": 39, + "commands": 79, + "goal": "true", + "guard": "|g@39|", + "id": "Vault.withdraw#1", + "lean": "SolarVerifyVc.Vault.withdraw.ob1", + "required": true, + "role": "side", + "script": 0, + "smt_sha256": "d701c0d47a6853af394b695af44112daf8fe8eacdf48bfbb521c3d0cf529264c", + "solver": "z3" + }, + { + "answer": "sat", + "asserts": 41, + "commands": 85, + "goal": "false", + "guard": "|g@44|", + "id": "Vault.withdraw#2", + "lean": "SolarVerifyVc.Vault.withdraw.ob2", + "required": false, + "role": "advisory", + "script": 0, + "smt_sha256": "8c305b6846feade818b296c08020d0df18f059f6d7b87febd2fa6c372a9d60f7", + "solver": "z3" + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 85, + "goal": "(not false)", + "guard": "|g@44|", + "id": "Vault.withdraw#3", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.Vault.withdraw.ob3", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 10, + "file": "crates/verify/examples/Vault.sol", + "line": 45 + }, + "smt_sha256": "5bbdce5d21562334b7321c071b7bdeee3531c6d507d3732b79f18781e81610fe", + "solver": "z3", + "spec": { + "column": 10, + "file": "crates/verify/examples/Vault.sol", + "line": 45, + "text": "!locked" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 85, + "goal": "(= |arith@35| |sumShares@34|)", + "guard": "|g@44|", + "id": "Vault.withdraw#4", + "kind": "contract invariant not preserved", + "lean": "SolarVerifyVc.Vault.withdraw.ob4", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 5, + "file": "crates/verify/examples/Vault.sol", + "line": 46 + }, + "smt_sha256": "bb349cd02022a8e7e21c04526b093b282ad13f4c280cc72689154a8bdfda81e6", + "solver": "z3", + "spec": { + "column": 6, + "file": "crates/verify/examples/Vault.sol", + "line": 12, + "text": "totalShares == sumShares" + } + }, + { + "answer": "unsat", + "asserts": 41, + "commands": 85, + "goal": "(<= |arith@35| |arith@37|)", + "guard": "|g@44|", + "id": "Vault.withdraw#5", + "kind": "contract invariant not preserved", + "lean": "SolarVerifyVc.Vault.withdraw.ob5", + "required": true, + "role": "obligation", + "script": 0, + "site": { + "column": 5, + "file": "crates/verify/examples/Vault.sol", + "line": 46 + }, + "smt_sha256": "db9c8d9b57a1c9be630a4a120d997b956b17a3b36e17b626230fb95922fa714a", + "solver": "z3", + "spec": { + "column": 6, + "file": "crates/verify/examples/Vault.sol", + "line": 13, + "text": "totalShares <= totalAssets" + } + }, + { + "answer": "unsat", + "asserts": 35, + "commands": 71, + "goal": "(and (= |arith@77| |sumShares@76|) (<= |arith@77| |arith@79|))", + "guard": "|g@80|", + "id": "Vault.withdraw#6", + "kind": "assertion failed", + "lean": "SolarVerifyVc.Vault.withdraw.ob6", + "required": true, + "role": "obligation", + "script": 1, + "site": { + "column": 14, + "file": "crates/verify/examples/Vault.sol", + "line": 52 + }, + "smt_sha256": "9a76d82676eeca0203f21ca31646bc50d18b6a2cb5048151957e039a57974d48", + "solver": "z3", + "spec": { + "column": 14, + "file": "crates/verify/examples/Vault.sol", + "line": 52, + "text": "totalShares == sumShares && totalShares <= totalAssets" + } + }, + { + "answer": "unsat", + "asserts": 37, + "commands": 75, + "goal": "true", + "guard": "|g@81|", + "id": "Vault.withdraw#7", + "lean": "SolarVerifyVc.Vault.withdraw.ob7", + "required": true, + "role": "side", + "script": 1, + "smt_sha256": "9fc0c8a347d0b5e7e0d4a61a94ff5518a3c81ca9f410bc8a019859df55d311e3", + "solver": "z3" + }, + { + "answer": "unsat", + "asserts": 39, + "commands": 81, + "goal": "false", + "guard": "|g@86|", + "id": "Vault.withdraw#8", + "kind": "entry point does not revert while reentrancy guard `locked` is held", + "lean": "SolarVerifyVc.Vault.withdraw.ob8", + "required": true, + "role": "obligation", + "script": 1, + "site": { + "column": 5, + "file": "crates/verify/examples/Vault.sol", + "line": 46 + }, + "smt_sha256": "b45831738ad0a31289afbaf330f5e0f6f7f55eec0759397684871a31b4e3f869", + "solver": "z3", + "spec": null + } + ], + "scripts": [ + { + "commands": 85, + "decls": [ + "|this@1|", + "|msg.sender@2|", + "|msg.value@3|", + "|block.timestamp@4|", + "|block.number@5|", + "|block.chainid@6|", + "|tx.origin@7|", + "|tx.gasprice@8|", + "|msg.sig@9|", + "|msg.data@10|", + "|block.basefee@11|", + "|block.blobbasefee@12|", + "|block.coinbase@13|", + "|block.prevrandao@14|", + "|block.difficulty@15|", + "|block.gaslimit@16|", + "|sumShares@17|", + "|asset@18|", + "|totalShares@19|", + "|totalAssets@20|", + "|shares@21|", + "|locked@22|", + "|__balance@23|", + "|__code_epoch@24|", + "|amount@25|", + "|g@26|", + "|g@27|", + "|g@28|", + "|g@29|", + "|g@30|", + "|arith@31|", + "|g@32|", + "|shares@33|", + "|sumShares@34|", + "|arith@35|", + "|g@36|", + "|arith@37|", + "|g@38|", + "|g@39|", + "|__code_epoch@40|", + "|__balance@41|", + "|g@42|", + "|ext_ret@43|", + "|g@44|" + ], + "lean": "SolarVerifyVc.Vault.withdraw.script0", + "smt": "Vault/withdraw.script0.smt2" + }, + { + "commands": 81, + "decls": [ + "|this@45|", + "|msg.sender@46|", + "|msg.value@47|", + "|block.timestamp@48|", + "|block.number@49|", + "|block.chainid@50|", + "|tx.origin@51|", + "|tx.gasprice@52|", + "|msg.sig@53|", + "|msg.data@54|", + "|block.basefee@55|", + "|block.blobbasefee@56|", + "|block.coinbase@57|", + "|block.prevrandao@58|", + "|block.difficulty@59|", + "|block.gaslimit@60|", + "|sumShares@61|", + "|asset@62|", + "|totalShares@63|", + "|totalAssets@64|", + "|shares@65|", + "|locked@66|", + "|__balance@67|", + "|__code_epoch@68|", + "|amount@69|", + "|g@70|", + "|g@71|", + "|g@72|", + "|arith@73|", + "|g@74|", + "|shares@75|", + "|sumShares@76|", + "|arith@77|", + "|g@78|", + "|arith@79|", + "|g@80|", + "|g@81|", + "|__code_epoch@82|", + "|__balance@83|", + "|g@84|", + "|ext_ret@85|", + "|g@86|" + ], + "lean": "SolarVerifyVc.Vault.withdraw.script1", + "smt": "Vault/withdraw.script1.smt2" + } + ], + "status": "verified" + } + ], + "version": 1 +} diff --git a/Contracts/VerifyCounter/Assembly.lean b/Contracts/VerifyCounter/Assembly.lean new file mode 100644 index 00000000..38a9c6ac --- /dev/null +++ b/Contracts/VerifyCounter/Assembly.lean @@ -0,0 +1,161 @@ +import SolidCore.Refinement.Solar.AssembleLoopWithin +import verify_counter.gen.Counter.Evm11 +import SolidCore.Refinement.Solar.AssembleFast +import verify_counter.gen.Counter.Bytecode + +/-! +# verify_counter: the assembly stage of looping code at every gas + +solar's final EVM IR of solar-verify's Counter (`SolarTV.Export.Counter.evm11`, after +`loop-layout`) has the loop of `bump` (blocks 7 and 8, with the back edge from block 7 to +block 8). `Assemble.check` bounds runs by a static potential and so rejects it; the checker of +code with loops accepts it (`check_ok`, the kernel's evaluation), and `within_of_checkL` gives +the stage `Final.compose_anyGas` needs: at every gas, every result of the 496-byte runtime +is the EVM IR's or a failure that changes nothing, on every call, under every oracle. + +`loopTarget_check`: the bytecode whose back edge jumps to block 7's JUMPDEST in place of block +8's (byte 168) is rejected: its walk decodes a push of 0xaa where the layout puts block 8 at +0xdb. +-/ + +namespace SolidCore.Refinement.Solar.VerifyCounterAsm + +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleLoop + +/-- The runtime bytecode solar exported with its stages. -/ +def code : ByteArray := ⟨(SolarTV.Export.Counter.bytecode.map UInt8.ofNat).toArray⟩ + +/-- The certificate: each labelled block's offset, each block's lowest entry height, its entry +words (all data), a bound on each block's items, and memory up to 192 bytes (MSTORE and MLOAD at +160). -/ +def cert : Cert := + { offsets := [0x0, 0x3c, 0x40, 0x52, 0x5b, 0x65, 0x73, 0xaa, 0xdb, 0x10f, 0x111, 0x127, 0x136, 0x13e, 0x152, 0x167, 0x182, 0x19a, 0x1af, 0x1cb, 0x1d2] + needs := [0, 0, 2, 1, 1, 1, 1, 6, 6, 4, 8, 5, 3, 4, 8, 8, 8, 5, 1, 3, 3] + top := 192 + costs := [55, 7, 19, 15, 15, 21, 75, 69, 73, 3, 17, 17, 11, 5, 7, 19, 13, 7, 37, 11, 27] + types := [[], + [], + [some false, some false], + [some false], + [some false], + [some false], + [some false], + [some false, some false, some false, some false, some false, some false], + [some false, some false, some false, some false, some false, some false], + [some false, some false, some false, some false], + [some false, some false, some false, some false, some false, some false, some false, some false], + [some false, some false, some false, some false, some false], + [some false, some false, some false], + [some false, some false, some false, some false], + [some false, some false, some false, some false, some false, some false, some false, some false], + [some false, some false, some false, some false, some false, some false, some false, some false], + [some false, some false, some false, some false, some false, some false, some false, some false], + [some false, some false, some false, some false, some false], + [some false], + [some false, some false, some false], + [some false, some false, some false]] } + +/-- The highest stack each block is entered with. -/ +def maxs : List Nat := [0, 1, 7, 1, 1, 1, 1, 6, 6, 7, 8, 10, 8, 4, 8, 8, 8, 5, 1, 3, 3] + +set_option maxRecDepth 100000 in +/-- The code's linear decoding is the lowered program at the layout, by the kernel's evaluation +of the walk's one-pass form (`Assemble.walkS`). -/ +theorem walk_ok : (SolarTV.Assembly.walk (bytesOf code) cert.offset 0 + (lower SolarTV.Export.Counter.evm11 cert)).isSome = true := by + have hw := walkS_drop (bytesOf code) cert.offset (lower SolarTV.Export.Counter.evm11 cert) 0 + (Nat.zero_le _) + rw [List.drop_zero] at hw + rw [← hw] + decide +kernel + +set_option maxRecDepth 100000 in +/-- Every block checks within its budget and stack bounds. -/ +theorem blocks_ok : blocksOkL SolarTV.Export.Counter.evm11 cert maxs 0 + SolarTV.Export.Counter.evm11.blocks = true := by + decide +kernel + +/-- Every label is a valid jump destination of the code, which the walk implies. -/ +theorem labels_ok : labelsValid SolarTV.Export.Counter.evm11 cert code = true := + labelsValid_of_walk walk_ok + +theorem size_ok : code.size < 2 ^ 32 := by + decide +kernel + +/-- The checker of code with loops accepts solar's bytecode for the final EVM IR, by the kernel's +evaluation of each of its parts. -/ +theorem check_ok : checkL SolarTV.Export.Counter.evm11 code cert maxs = true := by + simp only [checkL, walk_ok, blocks_ok, labels_ok, decide_eq_true size_ok, Bool.and_true, + Bool.true_and] + decide + +/-- **The assembly stage of verify_counter at every gas.** -/ +theorem assembly (o : SolarTV.Machine.Oracle) (scope : SolarTV.Call → Prop) (gas : Nat) : + Final.Within (SolarTV.evmirSem o) (Final.ethLibWith gas) SolarTV.Export.Counter.evm11 code + scope := + within_of_checkL check_ok o (fun h => absurd h (by decide)) scope gas + +/-- The bytes of `loopTargetCode`. -/ +def loopTargetBytes : List Nat := + [0x34, 0x60, 0x3c, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x6, 0x66, 0x1a, 0xbd, 0x14, + 0x60, 0x52, 0x57, 0x80, 0x63, 0x6d, 0x54, 0x33, 0xe6, 0x14, 0x61, 0x1, 0xaf, 0x57, 0x80, 0x63, + 0xa4, 0xd6, 0x6d, 0xaf, 0x14, 0x60, 0x5b, 0x57, 0x80, 0x63, 0xb2, 0xe, 0xb4, 0xc4, 0x14, 0x60, + 0x73, 0x57, 0x80, 0x63, 0xd0, 0x9d, 0xe0, 0x8a, 0x14, 0x60, 0x65, 0x57, 0x5b, 0x5f, 0x5f, 0xfd, + 0x5b, 0x60, 0x11, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, 0x60, + 0x1c, 0xfd, 0x5b, 0x5f, 0x54, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x1, 0x54, 0x5f, + 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x5f, 0x54, 0x60, 0x1, 0x1, 0x80, 0x15, 0x60, 0x40, 0x57, + 0x5f, 0x55, 0x0, 0x5b, 0x60, 0x24, 0x36, 0x10, 0x60, 0x3c, 0x57, 0x60, 0x4, 0x35, 0x5f, 0x54, + 0x81, 0x81, 0x1, 0x81, 0x81, 0x10, 0x60, 0x40, 0x57, 0x60, 0x1, 0x54, 0x10, 0x61, 0x1, 0xd2, + 0x57, 0x80, 0x81, 0x60, 0x80, 0x52, 0x5f, 0x60, 0xa0, 0x52, 0x80, 0x82, 0x82, 0x3, 0x61, 0x1, + 0x9a, 0x57, 0x5f, 0x5f, 0x91, 0x92, 0x50, 0x60, 0xaa, 0x56, 0x5b, 0x50, 0x60, 0x80, 0x51, 0x60, + 0x1, 0x84, 0x1, 0x80, 0x15, 0x85, 0x83, 0x3, 0x61, 0x1, 0x67, 0x57, 0x60, 0x40, 0x57, 0x80, + 0x60, 0x80, 0x52, 0x60, 0x1, 0x60, 0xa0, 0x52, 0x60, 0x1, 0x83, 0x1, 0x92, 0x5f, 0x19, 0x14, + 0x80, 0x61, 0x1, 0x82, 0x57, 0x50, 0x93, 0x50, 0x50, 0x60, 0x1, 0x5b, 0x84, 0x82, 0x10, 0x5f, + 0x54, 0x80, 0x85, 0x3, 0x61, 0x1, 0x11, 0x57, 0x50, 0x60, 0xaa, 0x57, 0x60, 0xa0, 0x51, 0x81, + 0x5f, 0x10, 0x82, 0x82, 0x3, 0x61, 0x1, 0x52, 0x57, 0x15, 0x61, 0x1, 0xf, 0x57, 0x50, 0x50, + 0x50, 0x50, 0x60, 0x80, 0x51, 0x81, 0x5f, 0x55, 0x81, 0x81, 0x3, 0x61, 0x1, 0x3e, 0x57, 0x5b, + 0x0, 0x5b, 0x90, 0x50, 0x6d, 0x1, 0x11, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x1, 0x0, + 0x0, 0x0, 0xf, 0x93, 0x90, 0x91, 0x93, 0x5b, 0x60, 0x20, 0x52, 0x60, 0x40, 0x52, 0x60, 0x60, + 0x52, 0x63, 0xed, 0x57, 0x2b, 0x27, 0x5b, 0x5f, 0x52, 0x60, 0x64, 0x60, 0x1c, 0xfd, 0x5b, 0x6d, + 0x1, 0x21, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x5, 0x0, 0x0, 0x0, 0xe, 0x61, 0x1, + 0x27, 0x56, 0x5b, 0x50, 0x6d, 0x1, 0x21, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x4, 0x0, + 0x0, 0x0, 0xc, 0x61, 0x1, 0x27, 0x56, 0x5b, 0x50, 0x50, 0x90, 0x50, 0x6d, 0x1, 0x21, 0x0, + 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x8, 0x92, 0x91, 0x92, 0x61, 0x1, + 0x27, 0x56, 0x5b, 0x5f, 0x6d, 0x1, 0x2, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0xa, 0x0, + 0x0, 0x0, 0x12, 0x91, 0x90, 0x91, 0x61, 0x1, 0x27, 0x56, 0x5b, 0x50, 0x6d, 0x1, 0x3, 0x0, + 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x7, 0x0, 0x0, 0x0, 0xb, 0x61, 0x1, 0x27, 0x56, 0x5b, + 0x60, 0x44, 0x36, 0x10, 0x60, 0x3c, 0x57, 0x60, 0x4, 0x35, 0x60, 0x24, 0x35, 0x80, 0x82, 0x10, + 0x61, 0x1, 0xcb, 0x57, 0x50, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x5f, 0x52, 0x60, 0x20, + 0x5f, 0xf3, 0x5b, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x60, 0xe0, 0x1b, 0x60, 0x4, 0x60, 0x20, 0x80, + 0x52, 0x60, 0x40, 0x52, 0x60, 0x60, 0x52, 0x63, 0x8, 0xc3, 0x79, 0xa0, 0x61, 0x1, 0x36, 0x56] + +/-- The bytecode with the loop's back edge to block 7's JUMPDEST (0xaa) in place of block 8's. -/ +def loopTargetCode : ByteArray := ⟨(loopTargetBytes.map UInt8.ofNat).toArray⟩ + +set_option maxRecDepth 100000 in +/-- The checker rejects the wrong loop target: the walk decodes a push of 0xaa where the layout +puts block 8 at 0xdb. -/ +theorem loopTarget_check : + checkL SolarTV.Export.Counter.evm11 loopTargetCode cert maxs = false := by + have hw := walkS_drop (bytesOf loopTargetCode) cert.offset + (lower SolarTV.Export.Counter.evm11 cert) 0 (Nat.zero_le _) + rw [List.drop_zero] at hw + have hf : (SolarTV.Assembly.walk (bytesOf loopTargetCode) cert.offset 0 + (lower SolarTV.Export.Counter.evm11 cert)).isSome = false := by + rw [← hw] + decide +kernel + simp [checkL, hf] + +/-- info: 'SolidCore.Refinement.Solar.VerifyCounterAsm.check_ok' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms check_ok + +/-- info: 'SolidCore.Refinement.Solar.VerifyCounterAsm.assembly' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms assembly + +/-- info: 'SolidCore.Refinement.Solar.VerifyCounterAsm.loopTarget_check' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms loopTarget_check + +end SolidCore.Refinement.Solar.VerifyCounterAsm diff --git a/Contracts/VerifyCounter/Bump.lean b/Contracts/VerifyCounter/Bump.lean new file mode 100644 index 00000000..e9187b26 --- /dev/null +++ b/Contracts/VerifyCounter/Bump.lean @@ -0,0 +1,252 @@ +import SolarTV.CutPointHoare +import W1Proofs.Segment +import W1Proofs.Stage +import Contracts.VerifyCounter.Inferred + +/-! +# bump's loop on solar's first lowered MIR, through one cut point + +`bump(n)` of solar's `crates/verify/examples/Counter.sol`: + + function bump(uint256 n) external { + require(count + n <= limit, "over"); + for (uint256 i = 0; i < n; i++) { count++; } + } + +solar keeps `count` in a value across the loop (block 1 of function 4 of `stage0`, entered +from block 7 before the first iteration and from block 10 after each), caches it at memory 128 +with a written flag at 160, and writes slot 0 once after the loop. One cut point, the loop's +header, splits every run into loop-free segments, each evaluated symbolically by solar-tv's +procedures. + +The header invariant and the variant are not written here: `Inferred.lean` is generated by +solar's `solar-tv/milestone/inferred.py` from what `solar-verify --show-inferred` inferred +for the loop (`i <= n`, `count == old(count) + i`, `count <= limit` and the guard's +bounds, the measure `n - i`), bound to the header's values, with the frame the compiler keeps +read off the MIR. The segments below check every conjunct of it, so a wrong one fails by +mismatch. + +* `stage0_ends` (total correctness, `CutPoint.ends_of_start`): every call of bump ends, and + meets `Post`: on success slot 0 holds the old `count` plus `n`, the sum does not wrap and is + at most slot 1 (`limit`), and every other slot is unchanged. +* `stage0_post`: every end of stage0 on a call of bump meets `Post`, since stage0 runs + deterministically. +* `post_of_certified`, `ends_of_certified`: the same of any program proved to match stage0's + ends, backwards or forwards. + +No sorry, native_decide or bv_decide. +-/ + +namespace SolarTV.Milestone.VerifyCounter.Bump + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 +open SolarTV.CutPoint (seg SegEnds) + +def cut : MIR.Lowered.Frame → Bool := fun x => + match x.2.1 with + | .enter f _ b => (f == 4 && b == 1) + | .resume .. => false + +theorem cut_enter (rs : List MIR.Lowered.Return) (f p b : Nat) (env : MIR.Lowered.Env) (s : State) : + cut (rs, .enter f p b, env, s) = ((f == 4 && b == 1)) := rfl + +theorem cut_resume (rs : List MIR.Lowered.Return) (f b : Nat) (is : List MIR.Lowered.Inst) (t : MIR.Lowered.Terminator) (env : MIR.Lowered.Env) (s : State) : + cut (rs, .resume f b is t, env, s) = false := rfl + +/-- bump's selector. -/ +def IsBump (call : Call) : Prop := EvmRules.Evm.shr 224 (calldataWord call 0) = 0xb20eb4c4 + +/-- What bump's spec asks of an end: when it succeeds, slot 0 (`count`) holds its old value plus +the argument `n`, the sum did not wrap and is at most slot 1 (`limit`), and every other slot is +unchanged. -/ +def Post (call : Call) (r : Halt × State) : Prop := + (r.1 = .stop ∨ ∃ d, r.1 = .ret d) → + r.2.storage 0 = (State.initial call).storage 0 + calldataWord call 4 ∧ + (State.initial call).storage 0 ≤ (State.initial call).storage 0 + calldataWord call 4 ∧ + (State.initial call).storage 0 + calldataWord call 4 ≤ (State.initial call).storage 1 ∧ + ∀ k, k ≠ 0 → r.2.storage k = (State.initial call).storage k + +/-- The cut test of a block a branch picks, distributed over the branch. -/ +theorem ite_beq' {α : Type} [BEq α] (c : Prop) [Decidable c] (a b n : α) : + ((if c then a else b) == n) = (if c then a == n else b == n) := by + split <;> rfl + +/-- A cut test of a block a branch picks evaluates on both branches before any case split. -/ +macro "cut_test" : tactic => `(tactic| + simp only [ite_beq', Nat.reduceBEq, ite_self, Bool.false_eq_true, ↓reduceIte, true_or, or_true]) + +/-- `seg_norm` with the cut test of a branch evaluated first. -/ +syntax "bump_norm" "[" Lean.Parser.Tactic.simpLemma,* "]" : tactic +macro_rules + | `(tactic| bump_norm [$ids,*]) => + `(tactic| repeat (first | sym_eval | seg_eval [$ids,*] | cut_test | sym_cond)) + +macro "word_goal" : tactic => `(tactic| ( + first + | rfl + | (intro k hk; simp only [update, hk, ↓reduceIte]) + | (simp only [update, MIR.Lowered.Env.set, ↓reduceIte, Nat.reduceEqDiff, EvmRules.Evm.add, *]; done) + | (simp only [update, MIR.Lowered.Env.set, ↓reduceIte, Nat.reduceEqDiff, EvmRules.Evm.add, *]; bv_omega) + | bv_omega)) + +theorem load_store_apart (m : Mem) (offset address : Nat) (value : EvmRules.Word) + (apart : address + 32 ≤ offset ∨ offset + 32 ≤ address) : + (m.store offset value).load address = m.load address := by + unfold Mem.store + rw [Mem.load_expand] + unfold Mem.load Mem.read + congr 1 + apply List.map_congr_left + intro i mem + simp only [List.mem_range] at mem + have : ¬(offset ≤ address + i ∧ address + i < offset + 32) := by omega + simp only [this, ↓reduceIte] + +theorem load_128_store_160 (m : Mem) (w : EvmRules.Word) : (m.store 160 w).load 128 = m.load 128 := + load_store_apart _ _ _ _ (by decide) + +theorem load_160_store_128 (m : Mem) (w : EvmRules.Word) : (m.store 128 w).load 160 = m.load 160 := + load_store_apart _ _ _ _ (by decide) + +macro "mem_goal" : tactic => `(tactic| ( + first + | (simp only [load_128_store_160, load_160_store_128, Mem.load_store_same, Mem.load_expand, + MIR.Lowered.Env.set, ↓reduceIte, Nat.reduceEqDiff, EvmRules.Evm.add, *]; done) + | word_goal)) + +macro "rank_goal" : tactic => `(tactic| ( + simp only [Inferred.rank, MIR.Lowered.Env.set, ↓reduceIte, Nat.reduceEqDiff, EvmRules.Evm.add, *] <;> bv_omega)) + +/-- The generated invariant at the header, entered from block 7 or from block 10: the frame is +picked by its predecessor, and every conjunct is proved. -/ +macro "inv_goal" : tactic => `(tactic| ( + first + | (unfold Inferred.Inv; refine Or.inl ⟨_, _, rfl, ?_⟩; unfold Inferred.at7; + (try simp only [EvmRules.Evm.add] at *); and_intros <;> mem_goal) + | (unfold Inferred.Inv; refine Or.inr ⟨_, _, rfl, ?_⟩; unfold Inferred.at10; + (try simp only [EvmRules.Evm.add] at *); and_intros <;> mem_goal))) + +macro "total_leaf" : tactic => `(tactic| ( + first + | (unfold Post; dsimp only; intro h; rcases h with h | ⟨_, h⟩ <;> exact Halt.noConfusion h) + | (unfold Post; dsimp only; intro _; (try simp only [EvmRules.Evm.add] at *); + refine ⟨?_, ?_, ?_, ?_⟩ <;> word_goal) + | (refine ⟨?_, ?_⟩ + · inv_goal + · first | exact True.intro | rank_goal) + | inv_goal + | (exfalso; bv_omega) + | (exfalso; sym_omega))) + +syntax "total_seg" : tactic +set_option hygiene false in +macro_rules + | `(tactic| total_seg) => `(tactic| ( + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + bump_norm [SegEnds, cut_enter, cut_resume] + repeat' (split_cond <;> bump_norm [SegEnds, cut_enter, cut_resume]) + all_goals total_leaf)) + +set_option maxHeartbeats 4000000 in +theorem tseg0 (o : Oracle) (call : Call) (hsel : IsBump call) : + ∃ k, SegEnds (Inferred.Inv call) (Post call) (fun _ => True) + (seg (MIR.Lowered.moduleBlock o call stage0) cut k ([], .enter stage0.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState stage0 (State.initial call))) := by + refine ⟨40, ?_⟩ + unfold IsBump at hsel + total_seg + +set_option maxHeartbeats 4000000 in +theorem tseg7 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) + (h : Inferred.at7 call env s) : + ∃ k, SegEnds (Inferred.Inv call) (Post call) + (fun y => Inferred.rank call y < Inferred.rank call ([], .enter 4 7 1, env, s)) + (seg (MIR.Lowered.moduleBlock o call stage0) cut k ([], .enter 4 7 1, env, s)) := by + refine ⟨40, ?_⟩ + unfold Inferred.at7 at h + repeat obtain ⟨_, h⟩ := h + total_seg + +set_option maxHeartbeats 4000000 in +theorem tseg10 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) + (h : Inferred.at10 call env s) : + ∃ k, SegEnds (Inferred.Inv call) (Post call) + (fun y => Inferred.rank call y < Inferred.rank call ([], .enter 4 10 1, env, s)) + (seg (MIR.Lowered.moduleBlock o call stage0) cut k ([], .enter 4 10 1, env, s)) := by + refine ⟨40, ?_⟩ + unfold Inferred.at10 at h + repeat obtain ⟨_, h⟩ := h + total_seg + +/-- **Every call of bump ends on solar's first lowered MIR, and meets bump's spec**, whatever +`n` is: the loop runs `n` times. -/ +theorem stage0_ends (o : Oracle) (call : Call) (hsel : IsBump call) : + ∃ r, MIR.Lowered.moduleLayer.Ends o stage0 call r ∧ Post call r := by + obtain ⟨n, r, ran, post⟩ := CutPoint.ends_of_start (Inferred.rank call) (tseg0 o call hsel) (by + rintro x (⟨env, s, rfl, h⟩ | ⟨env, s, rfl, h⟩) + · exact tseg7 o call env s h + · exact tseg10 o call env s h) + refine ⟨r, ⟨n, ?_⟩, post⟩ + change Machine.iterate _ n _ = some r + rw [CutPoint.iterate_eq] + exact ran + +theorem iterate_le {σ : Type} (step : σ → Option ((Halt × State) ⊕ σ)) {n m : Nat} (x : σ) + (r : Halt × State) (le : n ≤ m) (ran : Machine.iterate step n x = some r) : + Machine.iterate step m x = some r := by + induction le with + | refl => exact ran + | step _ ih => exact Machine.iterate_mono _ _ _ _ ih + +/-- **bump's spec of solar's first lowered MIR, on every call of bump, whatever number of times +its loop runs**: every end of stage0 on a call with bump's selector meets `Post`, since the one +`stage0_ends` finds is the only one. -/ +theorem stage0_post (o : Oracle) (call : Call) (hsel : IsBump call) (r : Halt × State) + (e : MIR.Lowered.moduleLayer.Ends o stage0 call r) : Post call r := by + obtain ⟨r0, ⟨n0, e0⟩, post⟩ := stage0_ends o call hsel + obtain ⟨n, e⟩ := e + change Machine.iterate _ n _ = some r at e + change Machine.iterate _ n0 _ = some r0 at e0 + have h1 := iterate_le _ _ _ (Nat.le_max_left n n0) e + have h2 := iterate_le _ _ _ (Nat.le_max_right n n0) e0 + rw [h1] at h2 + cases h2 + exact post + +/-- `Post` is read off what an observer sees: it holds of an end that agrees with one it holds +of. -/ +theorem Post.of_agree {call : Call} {r r' : Halt × State} (ag : Agree r r') (h : Post call r) : + Post call r' := by + obtain ⟨a, s⟩ := r + obtain ⟨b, t⟩ := r' + intro hb + have : (a = .stop ∨ ∃ d, a = .ret d) ∧ s.storage = t.storage := by + rcases hb with rfl | ⟨d, rfl⟩ <;> cases a <;> simp_all [Agree] + obtain ⟨ha, hst⟩ := this + simpa [← hst] using h ha + +/-- bump's spec carried along any program whose every end is matched by an agreeing end of +stage0 (`Certified … p stage0`). -/ +theorem post_of_certified {L : Layer} {p : L.Prog} (o : Oracle) + (cert : Certified L MIR.Lowered.moduleLayer o p stage0 anyCall) (call : Call) + (hsel : IsBump call) (r : Halt × State) (e : L.Ends o p call r) : Post call r := by + obtain ⟨r0, e0, ag⟩ := cert call trivial r e + exact (stage0_post o call hsel r0 e0).of_agree (CutPoint.Agree.symm ag) + +/-- bump's spec carried forward along any program whose ends match stage0's +(`Certified … stage0 p`): every call of bump ends there too, and meets the spec. -/ +theorem ends_of_certified {L : Layer} {p : L.Prog} (o : Oracle) + (cert : Certified MIR.Lowered.moduleLayer L o stage0 p anyCall) (call : Call) + (hsel : IsBump call) : ∃ r, L.Ends o p call r ∧ Post call r := by + obtain ⟨r0, e0, post⟩ := stage0_ends o call hsel + obtain ⟨r, e, ag⟩ := cert call trivial r0 e0 + exact ⟨r, e, post.of_agree ag⟩ + +/-- info: 'SolarTV.Milestone.VerifyCounter.Bump.post_of_certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms post_of_certified + +/-- info: 'SolarTV.Milestone.VerifyCounter.Bump.ends_of_certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms ends_of_certified + +end SolarTV.Milestone.VerifyCounter.Bump diff --git a/Contracts/VerifyCounter/BumpTotal.lean b/Contracts/VerifyCounter/BumpTotal.lean new file mode 100644 index 00000000..90ea8187 --- /dev/null +++ b/Contracts/VerifyCounter/BumpTotal.lean @@ -0,0 +1,99 @@ +import SolarTV.Termination +import Contracts.VerifyCounter.Bump + +/-! +# bump's loop: termination with an explicit bound from its ranking certificate + +`Bump.stage0_ends` shows every call of bump ends on solar's first lowered MIR. Here the same +certificate (the invariant and the measure `n - i` that `inferred.py` emits from +`solar-verify --show-inferred`, `Inferred.Inv` and `Inferred.rank`) is checked through the +generic termination checker `SolarTV.CutPoint.ends_within_start` with every segment's fuel +fixed at 40 blocks, which gives a bound read off the ranking: every call of bump ends within +`(n + 2) * 40` blocks of the MIR, whatever `n` is (`stage0_ends_within`). With each block +charged one unit (`stage0_gas`), a metered run with that much gas never runs out of it, and +its result is the unmetered run's (`SolarTV.CutPoint.runGas_done_run`). + +The segments are checked again, conjunct by conjunct, by the symbolic procedure of `Bump`; +the rank must fall on the back edge (`i` grows, `n` is fixed) or the segment from block 10 +fails by mismatch. +-/ + +namespace SolarTV.Milestone.VerifyCounter.Bump + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 +open SolarTV.CutPoint (seg SegEnds) + +/-- The first configuration of a call. -/ +def start (call : Call) : MIR.Lowered.Frame := + ([], .enter stage0.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState stage0 (State.initial call)) + +set_option maxHeartbeats 4000000 in +theorem wseg0 (o : Oracle) (call : Call) (hsel : IsBump call) : + SegEnds (Inferred.Inv call) (Post call) (fun _ => True) + (seg (MIR.Lowered.moduleBlock o call stage0) cut 40 (start call)) := by + unfold IsBump at hsel + unfold start + total_seg + +set_option maxHeartbeats 4000000 in +theorem wseg7 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) + (h : Inferred.at7 call env s) : + SegEnds (Inferred.Inv call) (Post call) + (fun y => Inferred.rank call y < Inferred.rank call ([], .enter 4 7 1, env, s)) + (seg (MIR.Lowered.moduleBlock o call stage0) cut 40 ([], .enter 4 7 1, env, s)) := by + unfold Inferred.at7 at h + repeat obtain ⟨_, h⟩ := h + total_seg + +set_option maxHeartbeats 4000000 in +theorem wseg10 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) + (h : Inferred.at10 call env s) : + SegEnds (Inferred.Inv call) (Post call) + (fun y => Inferred.rank call y < Inferred.rank call ([], .enter 4 10 1, env, s)) + (seg (MIR.Lowered.moduleBlock o call stage0) cut 40 ([], .enter 4 10 1, env, s)) := by + unfold Inferred.at10 at h + repeat obtain ⟨_, h⟩ := h + total_seg + +/-- Every segment from a cut point of the certificate. -/ +theorem wseg (o : Oracle) (call : Call) : + ∀ x, Inferred.Inv call x → SegEnds (Inferred.Inv call) (Post call) + (fun y => Inferred.rank call y < Inferred.rank call x) + (seg (MIR.Lowered.moduleBlock o call stage0) cut 40 x) := by + rintro x (⟨env, s, rfl, h⟩ | ⟨env, s, rfl, h⟩) + · exact wseg7 o call env s h + · exact wseg10 o call env s h + +/-- Every rank of the invariant is at most `n`. -/ +theorem rank_le (call : Call) : + ∀ y, Inferred.Inv call y → Inferred.rank call y ≤ (calldataWord call 4).toNat := by + rintro y (⟨env, s, rfl, h⟩ | ⟨env, s, rfl, h⟩) <;> simp only [Inferred.rank] <;> omega + +/-- **Every call of bump ends within `(n + 2) * 40` blocks of solar's first lowered MIR, and +meets bump's spec**, for the bound the ranking certificate gives. -/ +theorem stage0_ends_within (o : Oracle) (call : Call) (hsel : IsBump call) : + ∃ r, Machine.iterate (MIR.Lowered.moduleBlock o call stage0) + (((calldataWord call 4).toNat + 2) * 40) (start call) = some r ∧ Post call r := by + obtain ⟨r, ran, post⟩ := CutPoint.ends_within_start (Inferred.rank call) 40 + (calldataWord call 4).toNat (rank_le call) (wseg0 o call hsel) (wseg o call) + exact ⟨r, by rw [CutPoint.iterate_eq]; exact ran, post⟩ + +/-- **The resource form**: charging each block one unit, a run with `(n + 1) * 40` units from +a cut point of the certificate never runs out, and ends meeting bump's spec. -/ +theorem stage0_gas (o : Oracle) (call : Call) (x : MIR.Lowered.Frame) (hx : Inferred.Inv call x) + (g : Nat) (hg : ((calldataWord call 4).toNat + 1) * 40 ≤ g) : + ∃ n r left, CutPoint.runGas (MIR.Lowered.moduleBlock o call stage0) (fun _ => 1) n g x = + some (.done r left) ∧ Post call r := + CutPoint.gas_ends (cut := cut) (Inferred.rank call) 40 40 + (fun y hy => ⟨wseg o call y hy, CutPoint.segCost_one_le 40 y⟩) x hx g + (Nat.le_trans (Nat.mul_le_mul_right 40 (by have := rank_le call x hx; omega)) hg) + +/-- info: 'SolarTV.Milestone.VerifyCounter.Bump.stage0_ends_within' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage0_ends_within + +/-- info: 'SolarTV.Milestone.VerifyCounter.Bump.stage0_gas' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage0_gas + +end SolarTV.Milestone.VerifyCounter.Bump diff --git a/Contracts/VerifyCounter/BumpWrongRank.lean b/Contracts/VerifyCounter/BumpWrongRank.lean new file mode 100644 index 00000000..13ab3a42 --- /dev/null +++ b/Contracts/VerifyCounter/BumpWrongRank.lean @@ -0,0 +1,55 @@ +import Contracts.VerifyCounter.BumpTotal + +/-! +# A ranking certificate that does not fall is rejected + +The negative control for `BumpTotal`. The segment of bump's loop from its back edge is checked +twice by one script, which differs only in the rank it is given: + +* `falling`, `n - i` read off the frame (the inferred measure): accepted + (`falling_accepted`); +* `growing`, `i` read off the frame, which grows on every iteration: the rank obligation + `i + 2 < i + 1` is false, the leaf tactic fails at once (no timeout), and `fail_if_success` + makes this file build only while the wrong certificate is rejected (`growing_rejected`). +-/ + +namespace SolarTV.Milestone.VerifyCounter.Bump + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 +open SolarTV.CutPoint (seg SegEnds) + +/-- The loop variable `i` at the header, read off the frame: it grows. -/ +def growing (x : MIR.Lowered.Frame) : Nat := (x.2.2.1 20).toNat + +/-- `n - i`, read off the frame the same way: it falls. -/ +def falling (call : Call) (x : MIR.Lowered.Frame) : Nat := + (calldataWord call 4).toNat - (x.2.2.1 20).toNat + +/-- The segment obligation from the back edge with a rank `R`. -/ +def BackEdge (R : Call → MIR.Lowered.Frame → Nat) : Prop := + ∀ (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State), + Inferred.at10 call env s → + SegEnds (Inferred.Inv call) (Post call) + (fun y => R call y < R call ([], .enter 4 10 1, env, s)) + (seg (MIR.Lowered.moduleBlock o call stage0) cut 40 ([], .enter 4 10 1, env, s)) + +set_option maxHeartbeats 4000000 in +theorem falling_accepted : BackEdge falling := by + intro o call env s h + have hr : ∀ x, falling call x = (calldataWord call 4).toNat - (x.2.2.1 20).toNat := fun _ => rfl + unfold Inferred.at10 at h + repeat obtain ⟨_, h⟩ := h + total_seg + +set_option maxHeartbeats 4000000 in +theorem growing_rejected : True := by + fail_if_success + have : BackEdge (fun _ => growing) := by + intro o call env s h + have hr : ∀ x, growing x = (x.2.2.1 20).toNat := fun _ => rfl + unfold Inferred.at10 at h + repeat obtain ⟨_, h⟩ := h + total_seg + trivial + +end SolarTV.Milestone.VerifyCounter.Bump diff --git a/Contracts/VerifyCounter/Bytecode.lean b/Contracts/VerifyCounter/Bytecode.lean new file mode 100644 index 00000000..a1ae1f72 --- /dev/null +++ b/Contracts/VerifyCounter/Bytecode.lean @@ -0,0 +1,118 @@ +import Contracts.VerifyCounter.Holds +import Contracts.VerifyCounter.Bump +import verify_counter.Proofs.Stages +import Contracts.VerifyCounter.Assembly +import SolidCore.Refinement.Solar.EndToEnd + +/-! +# solar-verify's Counter: its specification holds of its bytecode at every gas + +The composition, with no hypotheses: solar-verify's specification of Counter (`spec`: the +invariant `count <= limit` and all five functions, `bump`'s loop included) holds of the 496 bytes +of runtime bytecode solar compiled (`code`, bound to `manifest` by `bound`) at every gas. + +* `Mir.holds_of_certified`: the specification holds of the first lowered MIR (`holds_stage0`, with + `bump`'s loop by its cut points) and is carried to the final EVM IR along solar-tv's backend + stages read backwards (`verify_counter_certified_back`). +* `VerifyCounterAsm.assembly`: the assembly stage of looping code, at every gas: every result of + the bytecode is the final EVM IR's or a failure that changes nothing + (`AssembleLoop.within_of_checkL` at the kernel's evaluation of the checker). +* `Final.Holds.of_within` composes them. + +`evm11_bump_post` and `evm11_bump_ends`: on the final EVM IR, every call of `bump` ends, and its +end meets bump's postcondition. `loopTarget_rejected`: the bytecode whose loop jumps back to the +wrong block is rejected by the checker, by a mismatch of the walk. +-/ + +namespace SolidCore.Refinement.Solar.VerifyCounter + +open SolarTV SolarTV.Machine SolidCore.Refinement.Final + +/-- bump's postcondition on the final EVM IR, on every call of bump, under every oracle. -/ +theorem evm11_bump_post (o : Oracle) (call : Call) (hsel : Milestone.VerifyCounter.Bump.IsBump call) + (r : Halt × Machine.State) (e : EVM.Program.layer.Ends o SolarTV.Export.Counter.evm11 call r) : + Milestone.VerifyCounter.Bump.Post call r := + Milestone.VerifyCounter.Bump.post_of_certified o + (Milestone.VerifyCounter.verify_counter_certified_back o) call hsel r e + +/-- Every call of bump ends on the final EVM IR, and meets bump's postcondition. -/ +theorem evm11_bump_ends (o : Oracle) (call : Call) (hsel : Milestone.VerifyCounter.Bump.IsBump call) : + ∃ r, EVM.Program.layer.Ends o SolarTV.Export.Counter.evm11 call r ∧ + Milestone.VerifyCounter.Bump.Post call r := + Milestone.VerifyCounter.Bump.ends_of_certified o + (Milestone.VerifyCounter.verify_counter_certified o) call hsel + +/-- An oracle. The EVM IR's specification holds under every one, and the bytecode reads none. -/ +def anyOracle : Oracle := + ⟨fun _ _ _ => 0, fun _ => 0, fun _ _ => 0, fun _ _ => 0, fun _ => 0, 0⟩ + +open EthLib.Execution.Evm.Logic in +/-- The bytes of a code stored in a number, by the number's bytes. -/ +theorem toList_ofNat (n size : Nat) : + (NatCode.ofNat n size).data.toList = (List.range size).map (NatCode.natByte n size) := by + apply List.ext_getElem <;> simp [NatCode.ofNat] + +/-- Two codes with the same bytes are the same. -/ +theorem bytesOf_inj {a b : ByteArray} (h : Assemble.bytesOf a = Assemble.bytesOf b) : a = b := by + have h' : a.data.toList = b.data.toList := + (List.map_injective_iff.2 (fun x y hxy => UInt8.toNat_inj.1 hxy)) h + cases a; cases b + simp only [ByteArray.mk.injEq] + exact Array.toList_inj.1 h' + +open EthLib.Execution.Evm.Logic in +/-- `runtimeNat`'s 496 bytes are the bytecode solar exported with its stages. -/ +theorem runtime_bytes : (List.range 496).map (fun i => (NatCode.natByte runtimeNat 496 i).toNat) = + SolarTV.Export.Counter.bytecode := by + decide +kernel + +/-- The assembly stage's bytes are the exported bytecode. -/ +theorem asm_bytes : Assemble.bytesOf VerifyCounterAsm.code = SolarTV.Export.Counter.bytecode := by + decide +kernel + +/-- The bytecode of the assembly stage is `code`, bound to the manifest (`bound`). -/ +theorem asm_code_eq : VerifyCounterAsm.code = code := by + apply bytesOf_inj + rw [asm_bytes] + unfold Assemble.bytesOf code + rw [toList_ofNat, List.map_map] + exact runtime_bytes.symm + +/-- The specification holds of the final EVM IR. -/ +theorem holds_evm11 (o : Oracle) : Holds (SolarTV.evmirSem o) SolarTV.Export.Counter.evm11 spec := + Mir.holds_of_certified o (Milestone.VerifyCounter.verify_counter_certified_back o) + +/-- **solar-verify's specification of Counter holds of its bytecode at every gas**, every function, +`bump`'s loop included, with no hypotheses. -/ +theorem spec_holds_of_bytecode (gas : Nat) : Holds (ethLibWith gas) code spec := by + rw [← asm_code_eq] + exact (holds_evm11 anyOracle).of_within (VerifyCounterAsm.assembly anyOracle spec.Calls gas) + +/-- The same theorem by the generic composition (`EndToEnd.holds_of_checkL`) that generated proofs +use: the specification on stage0, solar-tv's backend stages read backwards, and the checker of code +with loops. -/ +theorem spec_holds_of_bytecode_generic (gas : Nat) : Holds (ethLibWith gas) code spec := by + rw [← asm_code_eq] + exact EndToEnd.holds_of_checkL (Mir.holds_stage0 anyOracle) + (Milestone.VerifyCounter.verify_counter_certified_back anyOracle) (fun _ _ => trivial) + VerifyCounterAsm.check_ok (fun h => absurd h (by decide)) gas + +/-- The bytecode whose loop jumps back to block 7's JUMPDEST in place of block 8's is rejected. -/ +theorem loopTarget_rejected : + AssembleLoop.checkL SolarTV.Export.Counter.evm11 VerifyCounterAsm.loopTargetCode + VerifyCounterAsm.cert VerifyCounterAsm.maxs = false := + VerifyCounterAsm.loopTarget_check + +/-- info: 'SolidCore.Refinement.Solar.VerifyCounter.spec_holds_of_bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms spec_holds_of_bytecode + +/-- info: 'SolidCore.Refinement.Solar.VerifyCounter.evm11_bump_post' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms evm11_bump_post + +/-- info: 'SolidCore.Refinement.Solar.VerifyCounter.evm11_bump_ends' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms evm11_bump_ends + +end SolidCore.Refinement.Solar.VerifyCounter diff --git a/Contracts/VerifyCounter/EvmBound.lean b/Contracts/VerifyCounter/EvmBound.lean new file mode 100644 index 00000000..bb88de73 --- /dev/null +++ b/Contracts/VerifyCounter/EvmBound.lean @@ -0,0 +1,41 @@ +import Contracts.VerifyCounter.BumpTotal +import verify_counter.Proofs.Stages + +/-! +# bump: a block bound on the final EVM IR from the loop's rank + +Every stage from the first lowered MIR to the final EVM IR states its target segments' fuel +(`_bounded : CutPoint.BoundedSim … K'`, written by the certify driver). Chained +(`CutPoint.BoundedSim.trans`), the stages match the MIR's segments one for one with segments of +`evm11` of at most 22 blocks each. The MIR's ranking certificate for bump's loop (`n - i`, the +inferred measure, `Bump.wseg0`, `Bump.wseg`) then bounds the run of the final EVM IR +(`CutPoint.ends_within_sim_start`): every call of bump ends on `evm11` within `(n + 2) * 22` +blocks. This is the block count a gas bound on the bytecode multiplies by the most a block +costs; it is a step bound derived from the rank, not a chosen fuel. +-/ + +namespace SolarTV.Milestone.VerifyCounter.Bump + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 SolarTV.Milestone.VerifyCounter + +theorem evm11_ends_within (o : Oracle) (call : Call) (hsel : IsBump call) : + ∃ r, Machine.iterate (EVM.Program.block o call evm11) + (((calldataWord call 4).toNat + 2) * 22) (0, [], State.initial call) = some r := by + have chain := ((((((((((((mir1_bounded o call).trans (sched_bounded o call)).trans + (evm1_bounded o call)).trans (evm2_bounded o call)).trans (evm3_bounded o call)).trans + (evm4_bounded o call)).trans (evm5_bounded o call)).trans (evm6_bounded o call)).trans + (evm7_bounded o call)).trans (evm8_bounded o call)).trans (evm9_bounded o call)).trans + (evm10_bounded o call)).trans (evm11_bounded o call) + obtain ⟨r, ran, -⟩ := CutPoint.ends_within_sim_start (sim := chain) (Inferred.rank call) 40 22 + (calldataWord call 4).toNat (rank_le call) (x₀ := start call) + (x₀' := ((0, [], State.initial call) : Nat × EVM.Stack × State)) + (start := wseg0 o call hsel) (segment := wseg o call) + (rel := by + repeat' (first | exact ⟨_, List.Mem.head _, rfl, rfl⟩ | (apply Exists.intro; apply And.intro))) + exact ⟨r, by rw [CutPoint.iterate_eq]; exact ran⟩ + +/-- info: 'SolarTV.Milestone.VerifyCounter.Bump.evm11_ends_within' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms evm11_ends_within + +end SolarTV.Milestone.VerifyCounter.Bump diff --git a/Contracts/VerifyCounter/Gas.lean b/Contracts/VerifyCounter/Gas.lean new file mode 100644 index 00000000..d75f54eb --- /dev/null +++ b/Contracts/VerifyCounter/Gas.lean @@ -0,0 +1,52 @@ +import Contracts.VerifyCounter.EvmBound +import Contracts.VerifyCounter.Total +import SolidCore.Refinement.Solar.AssembleGasLoop + +/-! +# bump: a proved gas bound on the exact bytecode + +From the loop's rank to gas, all four pieces checked: + +* the MIR's ranking certificate (`n - i`, inferred) and the stages' stated segment fuel give a + block bound on the final EVM IR: every call of bump ends on `evm11` within `(n + 2) * 22` + blocks (`evm11_ends_within`); +* the assembly checker run forward (`AssembleLoop.forward_of_checkL`) turns a block bound into + gas: from `gasBoundL cert N = 22100 * (N * bmax cert) + memoryGasCost cert.top` on, the bytecode + shows exactly the EVM IR's result, reverts included. + +So at every gas from `G call = gasBoundL cert ((n + 2) * 22)` the exact bytecode runs `bump(n)` +to the observable of an end that meets bump's spec `Post` (`bump_gas`): it does not run out of +gas, and what it shows is the end the MIR's spec speaks of. The bound is linear in `n`, as the loop +is. Scope: the counter's bytecode reads no `GAS` and makes no call, so EIP-150 forwarding and +gas-dependent callees do not arise here; the oracle premises are the assembly certificate's +(`cert.env`, `cert.reads`). +-/ + +namespace SolarTV.Milestone.VerifyCounter.Bump + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 SolarTV.Milestone.VerifyCounter + +/-- The gas bump's bytecode needs on a call with argument `n`. -/ +def gasBound (call : Call) : Nat := + SolidCore.Refinement.Solar.AssembleLoop.gasBoundL cert (((calldataWord call 4).toNat + 2) * 22) + +/-- **bump's bytecode does not run out of gas from `gasBound call` on, and meets its spec.** -/ +theorem bump_gas (o : Oracle) + (ho : cert.env = true → SolidCore.Refinement.Solar.Assemble.OracleOk o) + (he : cert.reads = true → SolidCore.Refinement.Solar.Assemble.EnvOk o) + (call : Call) (hsel : IsBump call) {gas : Nat} (hg : gasBound call ≤ gas) : + ∃ r, SolidCore.Refinement.Final.Target.runWith gas code call = some (observe call r.2 r.1) ∧ + Post call r := by + obtain ⟨r, hit⟩ := evm11_ends_within o call hsel + refine ⟨r, SolidCore.Refinement.Solar.AssembleLoop.forward_of_checkL check_ok o ho he call _ r hit hg, + ?_⟩ + obtain ⟨-, ⟨r', e', post⟩, -⟩ := bump_total o ho he call hsel + have e : EVM.Program.layer.Ends o evm11 call r := ⟨((calldataWord call 4).toNat + 2) * 22, hit⟩ + rw [EVM.Program.layer.ends_unique e e'] + exact post + +/-- info: 'SolarTV.Milestone.VerifyCounter.Bump.bump_gas' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms bump_gas + +end SolarTV.Milestone.VerifyCounter.Bump diff --git a/Contracts/VerifyCounter/Holds.lean b/Contracts/VerifyCounter/Holds.lean new file mode 100644 index 00000000..55497923 --- /dev/null +++ b/Contracts/VerifyCounter/Holds.lean @@ -0,0 +1,273 @@ +import Contracts.VerifyCounter.Mir +import Contracts.Counter.Verify +import SolidCore.Refinement.Generic.Stage +import SolidCore.Refinement.Evm.WideStorage + +/-! +# solar-verify's spec of Counter holds of solar's first lowered MIR, and of the final EVM IR + +`holds_stage0`: `Final.Holds` of `VerifyCounter.spec` (`Contracts/Counter/Verify.lean`, the +NatSpec of solar's `crates/verify/examples/Counter.sol`: the getters, `increment`, `bump`'s loop +and `max`, the invariant `count <= limit`, nothing payable) for `stage0`, solar's first lowered +MIR of that contract, on every call of the spec: every function, every clean argument word, any +value, any storage meeting the invariant and the precondition, under every oracle. It reads the +per-function theorems of `Mir.lean` and `Bump.lean` through the call's ABI encoding. + +`holds_of_certified`: the same of every program whose ends stage0 matches with agreeing ends +(`Certified … p stage0`), such as the final EVM IR through solar-tv's backend stages read +backwards (`verify_counter_certified_back`). +-/ + +namespace SolidCore.Refinement.Solar.VerifyCounter.Mir + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Final EthLib.Base +open SolarTV.Milestone.VerifyCounter.Bump SolidCore.Refinement.Solar.VerifyCounter +open SolarTV.Export.Counter (stage0) + +/-! ## Return data -/ + +theorem byte_toNat (v : EvmRules.Word) (i : Nat) (hi : i < 32) : + (SolarTV.Memory.byte v i).toNat = v.toNat / 256 ^ (31 - i) % 256 := by + unfold SolarTV.Memory.byte + rw [BitVec.toNat_setWidth, BitVec.toNat_ushiftRight, Nat.shiftRight_eq_div_pow, Nat.pow_mul] + +theorem bytes_toNat (len n : Nat) : + (List.range len).map (fun i => (n / 256 ^ (len - 1 - i)) % 256) = + (natToBytes len n).map (·.toNat) := by + induction len generalizing n with + | zero => rfl + | succ len ih => + rw [natToBytes_succ, List.map_append, ← ih, List.range_succ, List.map_append] + congr 1 + · apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [Nat.div_div_eq_div_mul, ← Nat.pow_succ'] + congr 3 + omega + · simp + +/-- The word a store at 0 wrote, read back as its 32 bytes: its ABI word. -/ +theorem read_store0 (m : Mem) (v : EvmRules.Word) : + ((m.store 0 v).read 0 32).map BitVec.toNat = SolidCore.Verify.word v.toNat := by + have e : ((m.store 0 v).expand 0 32).read 0 32 = (m.store 0 v).read 0 32 := by + unfold Mem.expand; split <;> rfl + rw [← e, SolidCore.Verify.word, ← bytes_toNat] + simp only [Mem.read, Mem.expand, Mem.store, List.map_map] + simp only [show (32 = 0) = False from by decide, ite_false] + apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + simp only [Function.comp_apply, Nat.zero_add, Nat.zero_le, true_and, hi, ite_true, Nat.sub_zero] + rw [byte_toNat v i hi] + +/-! ## The call's words -/ + +theorem selector_of {sel : Nat} (hsel : sel < 2 ^ 32) {args : List Nat} + (hargs : ∀ a ∈ args, a < 2 ^ 256) (v : Nat) (σ : List (Nat × Nat)) : + EvmRules.Evm.shr 224 (calldataWord { calldata := Abi.calldata sel args, callvalue := v, storage := σ } 0) = + BitVec.ofNat 256 sel := + (Generic.callFacts sel hsel args hargs σ).selector + +theorem arg_of {sel : Nat} (hsel : sel < 2 ^ 32) {args : List Nat} + (hargs : ∀ a ∈ args, a < 2 ^ 256) (v : Nat) (σ : List (Nat × Nat)) (i : Nat) (hi : i < args.length) + (hi2 : i < 2) : + calldataWord { calldata := Abi.calldata sel args, callvalue := v, storage := σ } + (BitVec.ofNat 256 (4 + 32 * i)) = BitVec.ofNat 256 (args.getD i 0) := by + have h := (Generic.callFacts sel hsel args hargs σ).args i hi + (by simp only [Generic.wordSize]; omega) + apply BitVec.eq_of_toNat_eq + have hlt : args.getD i 0 < 2 ^ 256 := by + rw [List.getD_eq_getElem?_getD, List.getElem?_eq_getElem hi] + exact hargs _ (List.getElem_mem hi) + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt hlt] + refine h.trans ?_ + simp only [Generic.WExpr.eval, Generic.wordSize] + exact Nat.mod_eq_of_lt hlt + + +/-! ## Runs and what they show -/ + +theorem run_some {L : Layer} {o : Oracle} {p : L.Prog} {call : Call} {obs : Observable} + (h : (L.sem o).run p call = some obs) : + ∃ r, L.Ends o p call r ∧ obs = observe call r.2 r.1 := by + change (L.result o p call).map _ = some obs at h + obtain ⟨r, hr, rfl⟩ := Option.map_eq_some_iff.1 h + exact ⟨r, L.ends_of_result hr, rfl⟩ + +theorem succ_of {call : Call} {r : Halt × Machine.State} (h : (observe call r.2 r.1).success = true) : + Succ r := by + obtain ⟨a, s⟩ := r + cases a <;> simp [observe, Succ] at h ⊢ + +theorem storage_of_succ {call : Call} {r : Halt × Machine.State} (hs : Succ r) : + (observe call r.2 r.1).storage = storageOf r.2 := by + obtain ⟨a, s⟩ := r + rcases hs with h | ⟨d, h⟩ <;> simp only at h <;> subst h <;> rfl + +theorem fail_of {call : Call} {r : Halt × Machine.State} (h : (observe call r.2 r.1).success = false) : + (observe call r.2 r.1).storage = slotValue call.storage ∧ (observe call r.2 r.1).logs = [] := by + obtain ⟨hl, hst, -⟩ := observe_failure call r.2 r.1 h + exact ⟨hst, hl⟩ + +/-- A slot of the storage a call starts from, as SolarTV's state holds it. -/ +theorem toNat_initial (call : Call) (k : EvmRules.Word) : + ((Machine.State.initial call).storage k).toNat = slotValue call.storage k.toNat := by + simp only [Machine.State.initial, BitVec.toNat_ofNat] + exact Nat.mod_eq_of_lt (Evm.Wide.slotValue_lt _ _) + +theorem storageOf_eq {call : Call} {s : Machine.State} (h : s.storage = (Machine.State.initial call).storage) + (k : Nat) (hk : k < 2 ^ 256) : storageOf s k = slotValue call.storage k := by + unfold storageOf + rw [h, toNat_initial, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hk] + +theorem value_zero {o : Oracle} {call : Call} (hv : call.callvalue < 2 ^ 256) {r : Halt × Machine.State} + (e : MIR.Lowered.moduleLayer.Ends o stage0 call r) (hs : Succ r) : call.callvalue = 0 := by + by_contra h + have hw : BitVec.ofNat 256 call.callvalue ≠ 0 := by + intro h' + apply h + have := congrArg BitVec.toNat h' + rwa [BitVec.toNat_ofNat, Nat.mod_eq_of_lt hv] at this + exact value_post o call hw r e hs + +/-! ## The spec -/ + +theorem toNat0 (call : Call) : + ((Machine.State.initial call).storage 0).toNat = slotValue call.storage 0 := toNat_initial call 0 + +theorem toNat1 (call : Call) : + ((Machine.State.initial call).storage 1).toNat = slotValue call.storage 1 := toNat_initial call 1 + +set_option maxHeartbeats 1000000 in +/-- **solar-verify's spec of Counter holds of solar's first lowered MIR**, under every oracle. -/ +theorem holds_stage0 (o : Oracle) : Holds (MIR.Lowered.moduleSem o) stage0 spec := by + intro f hf args ht v hv σ hinv hreq obs hrun + obtain ⟨r, e, rfl⟩ := run_some hrun + refine ⟨fun hs => ?_, fun hs => fail_of hs⟩ + have hsucc := succ_of hs + have hcv : (f.call args v σ).callvalue = 0 := value_zero hv e hsucc + rw [storage_of_succ hsucc] + have h0 := toNat0 (f.call args v σ) + have h1 := toNat1 (f.call args v σ) + have hl0 := Evm.Wide.slotValue_lt σ 0 + have hl1 := Evm.Wide.slotValue_lt σ 1 + simp only [spec, List.mem_cons, List.not_mem_nil, or_false] at hf + simp only [spec, layout, ContractSpec.pre] at hinv hreq ⊢ + have w0 : (0#256 : EvmRules.Word) = 0 := rfl + have t1 : (1 : EvmRules.Word).toNat = 1 := rfl + have w1 : (1#256 : EvmRules.Word) = 1 := rfl + have w0' : (BitVec.ofNat 256 0 : EvmRules.Word) = 0 := rfl + have w1' : (BitVec.ofNat 256 1 : EvmRules.Word) = 1 := rfl + rcases hf with rfl | rfl | rfl | rfl | rfl + · -- count + cases ht + obtain ⟨hst, -⟩ := count_post o _ ((selector_of (by decide) (by simp) v σ).trans rfl) r e hsucc + refine ⟨trivial, ?_, fun _ => hcv⟩ + rw [storageOf_eq hst 0 (by decide), storageOf_eq hst 1 (by decide)] + exact hinv + · -- limit + cases ht + obtain ⟨hst, -⟩ := limit_post o _ ((selector_of (by decide) (by simp) v σ).trans rfl) r e hsucc + refine ⟨trivial, ?_, fun _ => hcv⟩ + rw [storageOf_eq hst 0 (by decide), storageOf_eq hst 1 (by decide)] + exact hinv + · -- increment + cases ht + simp only [FnSpec.call, incrementSpec] at * + obtain ⟨hst, -⟩ := increment_post o _ ((selector_of (by decide) (by simp) v σ).trans rfl) r e hsucc + refine ⟨?_, ?_, fun _ => hcv⟩ <;> unfold storageOf <;> rw [hst] <;> + simp only [update, BitVec.ofNat_eq_ofNat, ↓reduceIte, show (1 : EvmRules.Word) ≠ 0 by decide] + · rw [w0, BitVec.toNat_add, h0] + try simp only [BitVec.toNat_ofNat] + omega + · rw [w0, w1, ite_eq_right_iff.mpr (fun h => absurd h (by decide)), BitVec.toNat_add, h0, h1] + try simp only [BitVec.toNat_ofNat] + omega + · -- bump + obtain ⟨a, hta⟩ : ∃ a, args = [a] ∧ a < 2 ^ 256 := by + cases ht with + | cons h t => cases t; exact ⟨_, rfl, by simpa [Abi.Param.clean] using h⟩ + obtain ⟨rfl, ha⟩ := hta + simp only [FnSpec.call, bumpSpec, List.headD_cons] at * + have hsel := (selector_of (sel := 0xb20eb4c4) (by decide) (args := [a]) (by simpa using ha) v σ).trans rfl + have hn := arg_of (sel := 0xb20eb4c4) (by decide) (args := [a]) (by simpa using ha) v σ 0 (by simp) (by decide) + simp only [Nat.mul_zero, Nat.add_zero, List.getD_cons_zero] at hn + obtain ⟨hs0, hov, hlim, hother⟩ := stage0_post o _ hsel r e hsucc + have hnv : (calldataWord { calldata := Abi.calldata 0xb20eb4c4 [a], callvalue := v, storage := σ } 4).toNat = a := by + rw [show (4 : EvmRules.Word) = BitVec.ofNat 256 4 from rfl, hn, BitVec.toNat_ofNat, Nat.mod_eq_of_lt ha] + have hr1 := hother 1 (by decide) + refine ⟨?_, ?_, fun _ => hcv⟩ <;> unfold storageOf + · rw [w0', hs0] + rw [BitVec.le_def] at hov + rw [BitVec.toNat_add] at hov ⊢ + omega + · rw [w0', w1', hs0, hr1] + rw [BitVec.le_def] at hov hlim + rw [BitVec.toNat_add] at hov hlim ⊢ + omega + · -- max + obtain ⟨a, b, hab⟩ : ∃ a b, args = [a, b] ∧ a < 2 ^ 256 ∧ b < 2 ^ 256 := by + cases ht with + | cons h t => + cases t with + | cons h' t' => cases t'; exact ⟨_, _, rfl, by simpa [Abi.Param.clean] using h, + by simpa [Abi.Param.clean] using h'⟩ + obtain ⟨rfl, ha, hb⟩ := hab + simp only [FnSpec.call, maxSpec] at * + have hargs : ∀ x ∈ [a, b], x < 2 ^ 256 := by + intro x hx + simp only [List.mem_cons, List.not_mem_nil, or_false] at hx + rcases hx with rfl | rfl <;> assumption + have hsel := (selector_of (sel := 0x6d5433e6) (by decide) hargs v σ).trans rfl + have h4 := arg_of (sel := 0x6d5433e6) (by decide) hargs v σ 0 (by simp) (by decide) + have h36 := arg_of (sel := 0x6d5433e6) (by decide) hargs v σ 1 (by simp) (by decide) + simp only [Nat.mul_zero, Nat.add_zero, Nat.mul_one, Nat.reduceAdd, List.getD_cons_zero, + List.getD_cons_succ] at h4 h36 + obtain ⟨hst, m, hret⟩ := max_post o _ hsel r e hsucc + have e4 : (4 : EvmRules.Word) = BitVec.ofNat 256 4 := rfl + have e36 : (36 : EvmRules.Word) = BitVec.ofNat 256 36 := rfl + rw [e4, e36, h4, h36] at hret + refine ⟨?_, ?_, fun _ => hcv⟩ + · obtain ⟨a', s'⟩ := r + simp only at hret hst + subst hret + have key : (if BitVec.ofNat 256 a < BitVec.ofNat 256 b then BitVec.ofNat 256 b + else BitVec.ofNat 256 a).toNat = if a ≥ b then a else b := by + by_cases h : a < b + · have hl : BitVec.ofNat 256 a < BitVec.ofNat 256 b := by + rw [BitVec.lt_def, BitVec.toNat_ofNat, BitVec.toNat_ofNat, Nat.mod_eq_of_lt ha, + Nat.mod_eq_of_lt hb] + exact h + rw [if_pos hl, if_neg (by omega), BitVec.toNat_ofNat, Nat.mod_eq_of_lt hb] + · have hl : ¬BitVec.ofNat 256 a < BitVec.ofNat 256 b := by + rw [BitVec.lt_def, BitVec.toNat_ofNat, BitVec.toNat_ofNat, Nat.mod_eq_of_lt ha, + Nat.mod_eq_of_lt hb] + exact h + rw [if_neg hl, if_pos (by omega), BitVec.toNat_ofNat, Nat.mod_eq_of_lt ha] + refine ⟨if a ≥ b then a else b, ?_, rfl, ?_⟩ + · show List.map BitVec.toNat _ = _ + rw [read_store0, key] + · (try simp only [List.getD_cons_zero, List.getD_cons_succ]) + constructor <;> split <;> omega + · rw [storageOf_eq hst 0 (by decide), storageOf_eq hst 1 (by decide)] + exact hinv + +/-- info: 'SolidCore.Refinement.Solar.VerifyCounter.Mir.holds_stage0' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holds_stage0 + +/-- **The spec carried back along the backend.** Every program whose every end on a call is +matched by an agreeing end of stage0 (`Certified … p stage0`, which solar-tv's stages give read +backwards, `certified_back`) meets the spec too. -/ +theorem holds_of_certified (o : Oracle) {L : Layer} {p : L.Prog} + (cert : Certified L MIR.Lowered.moduleLayer o p stage0 SolarTV.Milestone.W1.anyCall) : + Holds (L.sem o) p spec := + fun f hf args ht v hv σ hinv hreq obs hrun => + holds_stage0 o f hf args ht v hv σ hinv hreq obs (stage_of_certified cert _ trivial obs hrun) + +/-- info: 'SolidCore.Refinement.Solar.VerifyCounter.Mir.holds_of_certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holds_of_certified + +end SolidCore.Refinement.Solar.VerifyCounter.Mir diff --git a/Contracts/VerifyCounter/Inferred.lean b/Contracts/VerifyCounter/Inferred.lean new file mode 100644 index 00000000..7ee3205b --- /dev/null +++ b/Contracts/VerifyCounter/Inferred.lean @@ -0,0 +1,80 @@ +-- Generated by solar-tv/milestone/inferred.py from what solar-verify --show-inferred printed +-- (sha256 936bae6c3adf0154d95c8104a22ff3db20e7a6a7766ef6ba0656dc2b9db79dab) and Stage0.lean (sha256 656d00f214539eeaa141a32cf03260162058e19bb0ba268dd260f06ee750b8f0); do not edit. +import W1Proofs.Stage +import verify_counter.gen.Counter.Stage0 + +/-! +# The inferred invariant of `bump`'s loop at its header + +solar-verify inferred, for the loop at line 23 of the source: + +* `count >= entry(count)` (guard) +* `count >= entry(i)` (guard) +* `count >= i` (guard) +* `i >= entry(i)` (guard) +* `i <= count` (guard) +* `i <= n` (guard) +* `count == old(count) + n [n := i]` (spec) +* `count <= limit` (spec) +* the measure `n - i` + +They are bound to bb1 of function 4 of the first lowered MIR as `i` to phi 13, `n` to `calldataWord call 4`, `count` to phi 55, `limit` to `(State.initial call).storage 1`; the +frame (storage, the values the loop reads from before it, the branches before the loop and +the facts the header checks of memory) is read off the MIR. The cut-point proof checks every +conjunct on every segment; none is assumed. +-/ + +namespace SolarTV.Milestone.VerifyCounter.Inferred + +open Machine SolarTV.Milestone.W1 + +/-- At bb1 entered from bb7 (the loop's entry), before its phis bind. -/ +def at7 (call : Call) (env : MIR.Lowered.Env) (s : State) : Prop := + (State.initial call).storage 0 ≤ env 2 ∧ + (0 : EvmRules.Word) ≤ env 2 ∧ + (0 : EvmRules.Word) ≤ env 2 ∧ + (0 : EvmRules.Word) ≤ (0 : EvmRules.Word) ∧ + (0 : EvmRules.Word) ≤ env 2 ∧ + (0 : EvmRules.Word) ≤ calldataWord call 4 ∧ + env 2 = (State.initial call).storage 0 ∧ + env 2 ≤ (State.initial call).storage 1 ∧ + env 2 = (State.initial call).storage 0 ∧ + s.storage = (State.initial call).storage ∧ + env 30 = (State.initial call).storage 0 ∧ + env 62 = calldataWord call 4 ∧ + (State.initial call).storage 0 ≤ ((State.initial call).storage 0 + calldataWord call 4) ∧ + ((State.initial call).storage 0 + calldataWord call 4) ≤ (State.initial call).storage 1 ∧ + s.memory.load 128 = env 2 ∧ + s.memory.load 160 = (0 : EvmRules.Word) + +/-- At bb1 entered from bb10 (the loop's back edge), before its phis bind. -/ +def at10 (call : Call) (env : MIR.Lowered.Env) (s : State) : Prop := + (State.initial call).storage 0 ≤ env 43 ∧ + (0 : EvmRules.Word) ≤ env 43 ∧ + env 20 ≤ env 43 ∧ + (0 : EvmRules.Word) ≤ env 20 ∧ + env 20 ≤ env 43 ∧ + env 20 ≤ calldataWord call 4 ∧ + env 43 = ((State.initial call).storage 0 + env 20) ∧ + env 43 ≤ (State.initial call).storage 1 ∧ + s.storage = (State.initial call).storage ∧ + env 30 = (State.initial call).storage 0 ∧ + env 62 = calldataWord call 4 ∧ + (State.initial call).storage 0 ≤ ((State.initial call).storage 0 + calldataWord call 4) ∧ + ((State.initial call).storage 0 + calldataWord call 4) ≤ (State.initial call).storage 1 ∧ + s.memory.load 128 = env 43 ∧ + s.memory.load 160 = (1 : EvmRules.Word) + +/-- The header invariant: the frame enters bb1 of function 4 from one of its predecessors, +and that predecessor's conjuncts hold. -/ +def Inv (call : Call) (x : MIR.Lowered.Frame) : Prop := + (∃ env s, x = ([], .enter 4 7 1, env, s) ∧ at7 call env s) ∨ + (∃ env s, x = ([], .enter 4 10 1, env, s) ∧ at10 call env s) + +/-- The measure `n - i` at the header, in Nat. -/ +def rank (call : Call) : MIR.Lowered.Frame → Nat + | (_, .enter _ 7 _, _, _) => ((calldataWord call 4).toNat - ((0 : EvmRules.Word)).toNat) + | (_, .enter _ 10 _, env, _) => ((calldataWord call 4).toNat - (env 20).toNat) + | _ => 0 + +end SolarTV.Milestone.VerifyCounter.Inferred diff --git a/Contracts/VerifyCounter/Mir.lean b/Contracts/VerifyCounter/Mir.lean new file mode 100644 index 00000000..891025f7 --- /dev/null +++ b/Contracts/VerifyCounter/Mir.lean @@ -0,0 +1,114 @@ +import Contracts.VerifyCounter.Bump + +/-! +# solar-verify's Counter on its first lowered MIR: every function + +`Bump` proves bump's loop. This file proves the other functions of +`crates/verify/examples/Counter.sol` on the same module, `stage0` (solar's first lowered MIR), +each on every call of its selector, through the same cut point (which their runs never reach): + +* `value_post`: a call with value does not succeed (nothing is payable); +* `count_post`, `limit_post`: the getters return slot 0 and slot 1 and leave the storage; +* `increment_post`: `increment` writes slot 0 plus one, which does not wrap; +* `max_post`: `max(a, b)` returns the larger argument and leaves the storage. + +Each is partial correctness at every fuel (`CutPoint.post_of_start`), from one symbolic +evaluation of the module from its entry. No sorry, native_decide or bv_decide. +-/ + +namespace SolarTV.Milestone.VerifyCounter.Bump + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 +open SolarTV.CutPoint (seg SegOk) + +/-- An end that succeeds: a stop or a return. -/ +def Succ (r : Halt × State) : Prop := r.1 = .stop ∨ ∃ d, r.1 = .ret d + +def PostValue (r : Halt × State) : Prop := ¬Succ r + +def PostCount (call : Call) (r : Halt × State) : Prop := + Succ r → r.2.storage = (State.initial call).storage ∧ + ∃ m : Mem, r.1 = .ret ((m.store 0 ((State.initial call).storage 0)).read 0 32) + +def PostLimit (call : Call) (r : Halt × State) : Prop := + Succ r → r.2.storage = (State.initial call).storage ∧ + ∃ m : Mem, r.1 = .ret ((m.store 0 ((State.initial call).storage 1)).read 0 32) + +def PostIncrement (call : Call) (r : Halt × State) : Prop := + Succ r → r.2.storage = update (State.initial call).storage 0 ((State.initial call).storage 0 + 1) ∧ + (State.initial call).storage 0 + 1 ≠ 0 + +def PostMax (call : Call) (r : Halt × State) : Prop := + Succ r → r.2.storage = (State.initial call).storage ∧ + ∃ m : Mem, r.1 = .ret ((m.store 0 + (if calldataWord call 4 < calldataWord call 36 then calldataWord call 36 else calldataWord call 4)).read 0 32) + +macro "fn_leaf" : tactic => `(tactic| ( + (try unfold PostValue at *); (try unfold PostCount); (try unfold PostLimit); (try unfold PostIncrement); + (try unfold PostMax); (try unfold Succ); dsimp only + first + | exact True.intro + | (intro h; rcases h with h | ⟨_, h⟩ <;> exact Halt.noConfusion h) + | (intro _; exact ⟨rfl, _, rfl⟩) + | (intro _; refine ⟨rfl, ?_⟩; first | (rw [if_pos (by bv_omega)]; exact ⟨_, rfl⟩) | (rw [if_neg (by bv_omega)]; exact ⟨_, rfl⟩)) + | (intro _; refine ⟨rfl, ?_⟩; simp only [EvmRules.Evm.add] at *; bv_omega) + | (intro _; refine ⟨rfl, ?_⟩; (try simp only [EvmRules.Evm.add] at *); intro h; apply_assumption; exact h.symm) + | (exfalso; bv_omega) + | (exfalso; sym_omega))) + +syntax "fn_seg" : tactic +set_option hygiene false in +macro_rules + | `(tactic| fn_seg) => `(tactic| ( + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + bump_norm [SegOk, cut_enter, cut_resume] + repeat' (split_cond <;> bump_norm [SegOk, cut_enter, cut_resume]) + all_goals fn_leaf)) + +/-- From the entry, with no cut point on the way, every end meets `Post`. -/ +theorem post_of_entry {o : Oracle} {call : Call} {Post : Halt × State → Prop} + (start : ∃ k, SegOk (fun _ => False) Post + (seg (MIR.Lowered.moduleBlock o call stage0) cut k ([], .enter stage0.entry 0 0, fun _ => 0, + MIR.Lowered.Module.startState stage0 (State.initial call)))) + (r : Halt × State) (e : MIR.Lowered.moduleLayer.Ends o stage0 call r) : Post r := by + obtain ⟨n, hn⟩ := e + change Machine.iterate _ n _ = some r at hn + rw [CutPoint.iterate_eq] at hn + exact CutPoint.post_of_start start (fun _ h => h.elim) n r hn + +set_option maxHeartbeats 2000000 in +theorem value_post (o : Oracle) (call : Call) (hv : BitVec.ofNat 256 call.callvalue ≠ 0) + (r : Halt × State) (e : MIR.Lowered.moduleLayer.Ends o stage0 call r) : PostValue r := by + refine post_of_entry ⟨40, ?_⟩ r e + fn_seg + +set_option maxHeartbeats 2000000 in +theorem count_post (o : Oracle) (call : Call) + (hsel : EvmRules.Evm.shr 224 (calldataWord call 0) = 0x06661abd) + (r : Halt × State) (e : MIR.Lowered.moduleLayer.Ends o stage0 call r) : PostCount call r := by + refine post_of_entry ⟨40, ?_⟩ r e + fn_seg + +set_option maxHeartbeats 2000000 in +theorem limit_post (o : Oracle) (call : Call) + (hsel : EvmRules.Evm.shr 224 (calldataWord call 0) = 0xa4d66daf) + (r : Halt × State) (e : MIR.Lowered.moduleLayer.Ends o stage0 call r) : PostLimit call r := by + refine post_of_entry ⟨40, ?_⟩ r e + fn_seg + +set_option maxHeartbeats 2000000 in +theorem increment_post (o : Oracle) (call : Call) + (hsel : EvmRules.Evm.shr 224 (calldataWord call 0) = 0xd09de08a) + (r : Halt × State) (e : MIR.Lowered.moduleLayer.Ends o stage0 call r) : PostIncrement call r := by + refine post_of_entry ⟨40, ?_⟩ r e + fn_seg + +set_option maxRecDepth 100000 in +set_option maxHeartbeats 2000000 in +theorem max_post (o : Oracle) (call : Call) + (hsel : EvmRules.Evm.shr 224 (calldataWord call 0) = 0x6d5433e6) + (r : Halt × State) (e : MIR.Lowered.moduleLayer.Ends o stage0 call r) : PostMax call r := by + refine post_of_entry ⟨40, ?_⟩ r e + fn_seg + +end SolarTV.Milestone.VerifyCounter.Bump diff --git a/Contracts/VerifyCounter/Shape.lean b/Contracts/VerifyCounter/Shape.lean new file mode 100644 index 00000000..37353432 --- /dev/null +++ b/Contracts/VerifyCounter/Shape.lean @@ -0,0 +1,99 @@ +import Verify.ShapeGeneric +import Contracts.VerifyCounter.Gas +import Contracts.VerifyCounter.Holds +import Contracts.VerifyCounter.ShapeSpec + +/-! +# VerifyCounter's bump: all four obligations, in the published shape + +The source of this statement is solar's first lowered MIR `stage0` of solar-verify's Counter +(crates/verify/examples/Counter.sol), under the oracle with EthLib's caller, Keccak-256 and +environment (`Shapes.oracle`). No SolidCore stage reaches loops yet, so the frontend trust boundary +is at the first lowered MIR. On every call of `bump(uint256)` (`IsBump`: its selector): + +* equivalence: every result of the exact bytecode at every gas is `stage0`'s, or a failure that + changes nothing (`Bump.bump_total`: the loop checker on the final EVM IR, cut-point stages read + backwards); +* termination: `stage0` ends within `(n + 2) * 40` blocks, by the ranking certificate the kernel + checks (`Bump.stage0_ends_within` on generated invariants, `Contracts/VerifyCounter/Inferred.lean`); +* the specification: solar-verify's `VerifyCounter.spec` of every result (`holds_stage0`). + +That is `functional`, on every argument. Resources (`resources`): the final EVM IR ends within +`(n + 2) * 22` blocks (`Bump.evm11_ends_within`: the rank carried along the bounded stage +simulations), so from `Bump.gasBound call = gasBoundL cert ((n + 2) * 22)` gas on the bytecode +gives exactly `stage0`'s result (`AssembleLoop.stage_of_checkL_gas` after the forward stages). The +bound grows with `n`; `Shapes.Resources` asks for a bound below `2 ^ 64`, so the published +statement (`published`, `Shapes.Certified`) declares the valid calls `ValidB`: bump with +`n < 2 ^ 32`, where the bound is below `2 ^ 64` (`gasBound_lt`). +-/ + +namespace Contracts.VerifyCounter.Shape + +open SolidCore.Refinement SolarTV.Milestone.VerifyCounter.Bump Contracts.VerifyCounter.ShapeSpec + +/-- A call of `bump(uint256)` exists: its selector on one zero word. -/ +theorem inhabited : ∃ call, IsBump call := + ⟨{ calldata := Abi.calldata 0xb20eb4c4 [0], callvalue := 0, storage := [] }, by + unfold IsBump; decide +kernel⟩ + +/-- Equivalence, termination and the specification on every call of `bump`. -/ +theorem functional : + Shapes.Functional (SolarTV.mirSem Shapes.oracle) SolarTV.Export.Counter.stage0 + SolarTV.Milestone.VerifyCounter.code IsBump (fun _ _ => True) + (Shapes.specPost SolidCore.Refinement.Solar.VerifyCounter.spec) := + Shapes.functional_of inhabited + (fun call h => (bump_total Shapes.oracle (fun _ => Shapes.oracle_ok.1) (fun _ => Shapes.oracle_ok.2) + call h).2.2.1) + (fun _ _ _ _ => trivial) + (fun gas call h obs hrun => (bump_total Shapes.oracle (fun _ => Shapes.oracle_ok.1) + (fun _ => Shapes.oracle_ok.2) call h).2.2.2 gas call rfl obs hrun) + (Shapes.meets_of_holds (SolidCore.Refinement.Solar.VerifyCounter.Mir.holds_stage0 Shapes.oracle)) + +theorem inhabitedB : ∃ call, ValidB call := + ⟨{ calldata := Abi.calldata 0xb20eb4c4 [0], callvalue := 0, storage := [] }, by + unfold ValidB IsBump; decide +kernel⟩ + +/-- On those calls the gas bound is below `2 ^ 64`. -/ +theorem gasBound_lt (call : SolarTV.Call) (h : (SolarTV.Machine.calldataWord call 4).toNat < 2 ^ 32) : + gasBound call < 2 ^ 64 := by + have hn : ((SolarTV.Machine.calldataWord call 4).toNat + 2) * 22 ≤ (2 ^ 32 + 2) * 22 := + Nat.mul_le_mul_right _ (by omega) + have hm : gasBound call ≤ + Solar.AssembleLoop.gasBoundL SolarTV.Milestone.VerifyCounter.cert ((2 ^ 32 + 2) * 22) := by + unfold gasBound Solar.AssembleLoop.gasBoundL + exact Nat.add_le_add_right (Nat.mul_le_mul_left 22100 (Nat.mul_le_mul_right _ hn)) _ + have hc : Solar.AssembleLoop.gasBoundL SolarTV.Milestone.VerifyCounter.cert ((2 ^ 32 + 2) * 22) < + 2 ^ 64 := by + decide +kernel + exact Nat.lt_of_le_of_lt hm hc + +/-- **Resources**: from `gasBound call` on, the exact bytecode gives `stage0`'s result. -/ +theorem resources : + Shapes.Resources (SolarTV.mirSem Shapes.oracle) SolarTV.Export.Counter.stage0 + SolarTV.Milestone.VerifyCounter.code ValidB gasBound := + Shapes.resources_of_forward (B := SolarTV.evmirSem Shapes.oracle) (q := SolarTV.Export.Counter.evm11) + (fun call h => Option.isSome_iff_exists.mp + (bump_total Shapes.oracle (fun _ => Shapes.oracle_ok.1) (fun _ => Shapes.oracle_ok.2) call h.1).2.2.1) + ((SolarTV.Milestone.VerifyCounter.verify_counter_mir_to_evmir Shapes.oracle).mono fun _ _ => trivial) + (fun call h => ⟨gasBound_lt call h.2, fun _ h1 _ obs hrun => + Solar.AssembleLoop.stage_of_checkL_gas SolarTV.Milestone.VerifyCounter.check_ok Shapes.oracle + (fun _ => Shapes.oracle_ok.1) (fun _ => Shapes.oracle_ok.2) call _ + (evm11_ends_within Shapes.oracle call h.1) h1 obs hrun⟩) + +/-- **What the published statement asks of this module**: all four obligations. -/ +theorem published : + Shapes.Certified (SolarTV.mirSem Shapes.oracle) SolarTV.Export.Counter.stage0 + SolarTV.Milestone.VerifyCounter.code ValidB (fun _ _ => True) + (Shapes.specPost SolidCore.Refinement.Solar.VerifyCounter.spec) gasBound := + ⟨inhabitedB, fun gas hg call h => functional.equiv gas hg call h.1, + fun call h => functional.terminates call h.1, fun call h => functional.meets call h.1, resources⟩ + +/-- info: 'Contracts.VerifyCounter.Shape.functional' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms functional + +/-- info: 'Contracts.VerifyCounter.Shape.published' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms published + +end Contracts.VerifyCounter.Shape diff --git a/Contracts/VerifyCounter/ShapeExport.lean b/Contracts/VerifyCounter/ShapeExport.lean new file mode 100644 index 00000000..c34aa1a0 --- /dev/null +++ b/Contracts/VerifyCounter/ShapeExport.lean @@ -0,0 +1,133 @@ +import Contracts.VerifyCounter.ShapeSource +import Verify.ShapeSpecExport +import verify_counter.gen.Counter.Spec + +/-! +# VerifyCounter's bump against solar-verify's own export of its spec + +`ShapeSource.published` states the four obligations of the exact bytecode against SolidCore's +checked `Counter` with `Shapes.specPost VerifyCounter.spec`, a Lean restatement of the NatSpec. +This file states the same with the postcondition read off solar-verify's export of +Certified/verify_counter/verify_counter.sol, written fresh by the certify driver +(`Certified.verify_counter.gen.Counter.Spec.Counter`, `Shapes.bundlePost`), so that the +specification of the statement is the tool's output, not a copy of it: + +* `meets`: every SolidCore result of a valid call (`bump(n)`, `n < 2 ^ 32`, no value, any + storage) meets the exported spec of every function: `increment` and `max` do not apply (their + selectors differ), and `bump`'s `count == old(count) + n` and the invariant `count <= limit` + hold of every success, from `Source.success_spec` (slot 0 is the old count plus `n`, at most + the limit in slot 1, which the call leaves as it was); +* `published`: `Shapes.Certified` with that postcondition, equivalence, termination and resources + from `ShapeSource.published`; +* `nonvacuous`: the exported spec rejects a success of `bump(1)` that leaves `count` at 0, and + the allowed statuses reject a revert with empty data. +-/ + +namespace Contracts.VerifyCounter.ShapeExport + +open SolidCore.Refinement SolarTV Contracts.VerifyCounter.Source Contracts.VerifyCounter.ShapeSource +open SolidCore.Refinement.Shapes SolidCore.Spec SolidCore.Refinement.Generic.Loop + +/-- The exported spec bundle. -/ +abbrev B : Bundle := Certified.verify_counter.gen.Counter.Spec.Counter + +/-- The postcondition of the statement: solar-verify's export of the source. -/ +def post : Call → Observable → Prop := bundlePost B ctxOfCall idStep + +theorem bumpSel_lt : bumpSel < 2 ^ 32 := by decide + +theorem slotValue_lt (σ : List (Nat × Nat)) (k : Nat) : slotValue σ k < 2 ^ 256 := by + unfold slotValue + suffices ∀ (l : List (Nat × Nat)) (a : Nat), a < 2 ^ 256 → + l.foldl (fun acc kv => if kv.1 % 2^256 = k % 2^256 then kv.2 % 2^256 else acc) a < 2 ^ 256 from + this σ 0 (by decide) + intro l + induction l with + | nil => intro a h; exact h + | cons kv l ih => + intro a h + simp only [List.foldl_cons] + apply ih + split + · exact Nat.mod_lt _ (by decide) + · exact h + +theorem decodes_bump {a : Nat} (ha : a < 2 ^ 256) {args : List Int} + (h : decodeWords [.uint 256] (words (((Abi.calldata bumpSel [a]).data.toList.map (·.toNat)).drop 4)) = some args) : + args = [(a : Int)] := by + rw [SolidCore.Spec.words_calldata bumpSel (by simpa using ha)] at h + simp only [Nat.reducePow] at ha + simpa [decodeWords, Ty.ofWord, ha, eq_comm] using h + +/-- **The exported spec of every SolidCore result of a valid call.** -/ +theorem meets {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Shapes.Meets (solidCoreRuntime fuel) c ValidS post := by + obtain ⟨T, hT⟩ := tree_ok + rintro _ ⟨σ, a, ha, rfl⟩ obs hrun fs hfs args pre hpre + change runtimeRun fuel c (bumpCall σ a) = some obs at hrun + have haw : a < 2 ^ 256 := by omega + simp only [B, Certified.verify_counter.gen.Counter.Spec.Counter, List.mem_cons, List.not_mem_nil, + or_false] at hfs + rcases hfs with rfl | rfl | rfl + · exact absurd hpre (not_pre_of_sel bumpSel_lt (by decide) [a] 0 σ) + · obtain ⟨⟨-, -, hd⟩, hst, -, -, hinv⟩ := hpre + have hargs := decodes_bump haw hd + subst hargs + refine ⟨fun hs => ?_, fun h => absurd rfl h⟩ + obtain ⟨h0, hle, hframe⟩ := success_spec hc hT σ a haw hrun hs + have h1 := hframe 1 (by decide) + have l0 := slotValue_lt σ 0 + have l1 := slotValue_lt σ 1 + simp only [Nat.reducePow] at l0 l1 + refine ⟨[], rfl, ?_, ?_⟩ <;> + simp only [Bundle.satAll, Bundle.sat, List.mem_cons, List.not_mem_nil, or_false, forall_eq, + eval, slotOf, mkEnv, Env.cur, BinOp.apply, Ty.ofBits, ofProp_ne_zero, hst, h0, h1, + ite_true, ite_false, Bool.false_eq_true, wordMod, toWord, List.getD_cons_zero, bumpCall, B, + Certified.verify_counter.gen.Counter.Spec.Counter, h1] <;> + (try simp only [Nat.mul_zero, pow_zero, Nat.div_one, Nat.reducePow, Nat.reduceMul, Nat.reduceMod, + Int.reduceMod, Int.zero_emod, Int.toNat_zero, Int.reduceToNat]) <;> + (try simp only [h1]) <;> + (try simp only [Nat.mod_eq_of_lt l0, Nat.mod_eq_of_lt l1]) <;> push_cast <;> omega + · exact absurd hpre (not_pre_of_sel bumpSel_lt (by decide) [a] 0 σ) + +/-- **The published statement, with solar-verify's export as its specification.** -/ +theorem published : ∃ c, contract? = .ok c ∧ + Shapes.Certified (solidCoreRuntime fuel) c SolarTV.Milestone.VerifyCounter.code ValidS Allowed post + SolarTV.Milestone.VerifyCounter.Bump.gasBound := by + obtain ⟨c, hc, h⟩ := ShapeSource.published + exact ⟨c, hc, ⟨h.inhabited, h.equiv, h.terminates, meets hc, h.resources⟩⟩ + +/-- The exported spec and the allowed statuses each reject a result of a valid call. -/ +theorem nonvacuous : + (∃ (call : Call) (obs : Observable), ValidS call ∧ ¬ post call obs) ∧ + (∃ (call : Call) (obs : Observable), ValidS call ∧ obs.success = false ∧ ¬ Allowed call obs) := by + refine ⟨⟨bumpCall [] 1, ⟨true, [], [], fun _ => 0⟩, ⟨[], 1, by decide, rfl⟩, fun h => ?_⟩, + ⟨bumpCall [] 0, ⟨false, [], [], fun _ => 0⟩, ⟨[], 0, by decide, rfl⟩, rfl, ?_⟩⟩ + · have hpre : Pre B (B.spec.specs[1]'(by decide)) (ctxOfCall (bumpCall [] 1)) + ⟨slotValue [], Ghost.zero, 1⟩ (bumpCall [] 1) [1] := by + refine ⟨⟨?_, ?_, ?_⟩, rfl, ?_, ?_, ?_⟩ + · decide + · exact selectorOf_calldata bumpSel_lt [1] 0 [] + · have := SolidCore.Spec.words_calldata bumpSel (args := [1]) (by simp) + simp only [bumpCall] at this ⊢ + rw [this]; decide + · simp [ctxOfCall] + · simp [Bundle.satAll, B, Certified.verify_counter.gen.Counter.Spec.Counter] + · simp [Bundle.satAll, Bundle.sat, B, Certified.verify_counter.gen.Counter.Spec.Counter, Holds', eval, + slotOf, mkEnv, Env.cur, BinOp.apply, Ty.ofBits, slotValue] + have := (h _ (List.getElem_mem _) _ _ hpre).1 rfl + obtain ⟨rets, -, hens, -⟩ := this + simp [Bundle.satAll, Bundle.sat, B, Certified.verify_counter.gen.Counter.Spec.Counter, Holds', eval, + slotOf, mkEnv, Env.cur, BinOp.apply, Ty.ofBits, slotValue] at hens + · simp only [Allowed, Bool.false_eq_true, false_or] + rintro (h | h) <;> simp at h <;> exact absurd h (by decide) + +/-- info: 'Contracts.VerifyCounter.ShapeExport.published' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms published + +/-- info: 'Contracts.VerifyCounter.ShapeExport.nonvacuous' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms nonvacuous + +end Contracts.VerifyCounter.ShapeExport diff --git a/Contracts/VerifyCounter/ShapeSource.lean b/Contracts/VerifyCounter/ShapeSource.lean new file mode 100644 index 00000000..b5654237 --- /dev/null +++ b/Contracts/VerifyCounter/ShapeSource.lean @@ -0,0 +1,85 @@ +import Contracts.VerifyCounter.Shape +import Contracts.VerifyCounter.StageSource + +/-! +# VerifyCounter's bump with a SolidCore source: all four obligations + +The source of this statement is SolidCore's checked `Counter` (`Source.contract?`: the type +checker on the solc AST of crates/verify/examples/Counter.sol, checked by the kernel), run by +`solidCoreRuntime fuel` (SolidCore's ABI dispatcher on the runtime code from the call's storage; +deployment and the constructor are outside the statement). The bytes are the exact runtime +bytecode solar emitted (`SolarTV.Milestone.VerifyCounter.code`), run by EthLib at an explicit gas +under `Shapes.oracle` (EthLib's caller, Keccak-256 and environment). + +The valid calls `ValidS`: `bump(n)` with ABI call data (selector and one word), no value, from +any storage, with `n < 2 ^ 32` (where the proved gas bound, linear in `n`, stays below +`2 ^ 64`). On them: + +* equivalence: every result of the bytecode at every gas below `2 ^ 256` is SolidCore's result, + or a failure that changes nothing (out of gas among them): the MIR-sourced equivalence + (`Shape.functional`) with the source stage `Source.mir_eq` (SolidCore and `stage0` give the + same observable); +* termination: SolidCore's run ends on every valid call (`Source.runs`, the loop by its kernel + checked ranking certificate `n - i`), with an allowed status: success, `Panic(0x11)` or + `Error("over")` (`Allowed`), never another revert; +* the specification: solar-verify's `VerifyCounter.spec` (`count == old(count) + n`, the + `require`) of every SolidCore result (`holds_stage0` carried by `mir_eq`); +* resources: from `Bump.gasBound call` gas on, the bytecode gives exactly SolidCore's result + (`Shape.resources`, then `mir_eq`). + +Trust boundary: SolidCore's semantics of the checked contract, the solc AST import (solc 0.8.35), +and EthLib's EVM. No hypothesis besides the oracle's definition. +-/ + +namespace Contracts.VerifyCounter.ShapeSource + +open SolidCore.Refinement SolarTV Contracts.VerifyCounter.Source SolidCore.Refinement.Generic.Loop + +/-- The declared valid calls: `bump(n)` with `n < 2 ^ 32`, no value, any storage. -/ +def ValidS (call : Call) : Prop := ∃ σ a, a < 2 ^ 32 ∧ call = bumpCall σ a + +/-- The statuses the statement allows: success, or one of bump's two declared reverts. -/ +def Allowed (_ : Call) (obs : Observable) : Prop := + obs.success = true ∨ + obs.output = SolarTV.Milestone.VerifyCounter.Bump.panicData.map BitVec.toNat ∨ + obs.output = SolarTV.Milestone.VerifyCounter.Bump.overData.map BitVec.toNat + +theorem validB {call : Call} (h : ValidS call) : ShapeSpec.ValidB call := by + obtain ⟨σ, a, ha, rfl⟩ := h + obtain ⟨hsel, hn⟩ := bumpCall_facts σ a (by omega) + refine ⟨hsel, ?_⟩ + rw [hn, toNat_ofNat_lt (by omega)] + exact ha + +theorem allowed_of {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) + (σ : List (Nat × Nat)) (a : Nat) (ha : a < 2 ^ 256) {obs : Observable} + (h : runtimeRun fuel c (bumpCall σ a) = some obs) : Allowed (bumpCall σ a) obs := + result_kinds Shapes.oracle hc σ a ha h + +/-- **The published statement, from SolidCore's source**: all four obligations on the exact +bytecode. -/ +theorem published : ∃ c, contract? = .ok c ∧ + Shapes.Certified (solidCoreRuntime fuel) c SolarTV.Milestone.VerifyCounter.code ValidS Allowed + (Shapes.specPost SolidCore.Refinement.Solar.VerifyCounter.spec) + SolarTV.Milestone.VerifyCounter.Bump.gasBound := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨T, hT⟩ := tree_ok + refine ⟨c, hc, ⟨⟨bumpCall [] 0, [], 0, by decide, rfl⟩, ?_, ?_, ?_, ?_⟩⟩ + · rintro gas hg _ ⟨σ, a, ha, rfl⟩ obs hrun + have h := Shape.functional.equiv gas hg _ (validB ⟨σ, a, ha, rfl⟩).1 obs hrun + rwa [mir_eq Shapes.oracle hc σ a (by omega)] at h + · rintro _ ⟨σ, a, ha, rfl⟩ + exact ⟨_, runs hc hT σ a (by omega), allowed_of hc σ a (by omega) (runs hc hT σ a (by omega))⟩ + · rintro _ ⟨σ, a, ha, rfl⟩ obs h + change runtimeRun fuel c (bumpCall σ a) = some obs at h + rw [← mir_eq Shapes.oracle hc σ a (by omega)] at h + exact Shape.functional.meets _ (validB ⟨σ, a, ha, rfl⟩).1 obs h + · rintro _ ⟨σ, a, ha, rfl⟩ + obtain ⟨hlt, hrun⟩ := Shape.resources _ (validB ⟨σ, a, ha, rfl⟩) + exact ⟨hlt, fun gas h1 h2 => (hrun gas h1 h2).trans (mir_eq Shapes.oracle hc σ a (by omega))⟩ + +/-- info: 'Contracts.VerifyCounter.ShapeSource.published' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms published + +end Contracts.VerifyCounter.ShapeSource diff --git a/Contracts/VerifyCounter/ShapeSpec.lean b/Contracts/VerifyCounter/ShapeSpec.lean new file mode 100644 index 00000000..7a1da2e0 --- /dev/null +++ b/Contracts/VerifyCounter/ShapeSpec.lean @@ -0,0 +1,19 @@ +import Contracts.VerifyCounter.Bump + +/-! +# VerifyCounter's bump: the declared valid calls of the published statement + +Reviewed input of `Certified/verify_counter/shape.json`, not proof: the valid calls are +`bump(n)` (`Bump.IsBump`, the selector) with `n < 2 ^ 32`, the range where the proved gas bound +`Bump.gasBound` (linear in `n`) stays below `2 ^ 64`. +-/ + +namespace Contracts.VerifyCounter.ShapeSpec + +open SolarTV.Milestone.VerifyCounter.Bump + +/-- The declared valid calls: `bump(n)` with `n < 2 ^ 32`. -/ +def ValidB (call : SolarTV.Call) : Prop := + IsBump call ∧ (SolarTV.Machine.calldataWord call 4).toNat < 2 ^ 32 + +end Contracts.VerifyCounter.ShapeSpec diff --git a/Contracts/VerifyCounter/Source.lean b/Contracts/VerifyCounter/Source.lean new file mode 100644 index 00000000..6419fe60 --- /dev/null +++ b/Contracts/VerifyCounter/Source.lean @@ -0,0 +1,222 @@ +import SolidCore.Refinement.KernelCopies +import SolidCore.Refinement.KernelRfl +import Contracts.VerifyCounter.SourceAst +import Contracts.VerifyCounter.SourceBump +import Verify.Shapes + +/-! +# solar-verify's Counter in SolidCore: bump terminates, by its ranking certificate + +SolidCore's checked `Counter` is `contract?`, the type checker on the solc AST of +crates/verify/examples/Counter.sol (`SourceAst.lean`, generated by +scripts/solc_ast_to_lean_source.py with solc 0.8.35). The kernel checks (`shape_eq`, `kernel_rfl`, +on copies of the type checker that read the five selectors from `selectorTable`, each selector +checked by Keccak-256 alone) that it type checks, that its storage fields are `vcFields`, that it +declares no events, and that its function of selector `bump(uint256)` is `bumpFn`, whose body is +`SourceBump.bumpBody`. + +The source semantics is `solidCoreRuntime` (`LoopRun.lean`): SolidCore's ABI dispatcher from the +call's storage. `solidCore` cannot be used: it first runs the constructor with no arguments, and +`Counter`'s constructor takes `uint256 _limit`, so `solidCore` has no run of `Counter` at all. +Deployment is outside the statement. + +* `runs`: every call of `bump(n)` (any argument word, no value, any storage) runs, at fuel + `2 ^ 256 + 8`, to the observable of the tree `brTree bumpFn [] bumpBr` (`runtime_run_clean` on + `SourceBump.body_runs`): `Panic(0x11)` when `count + n` wraps, `Error("over")` when it exceeds + `limit`, else success with slot 0 holding `count + n`. +* `terminates`: `Shapes.Terminates (solidCoreRuntime fuel) c BumpCall _`, the termination + obligation of the published shape, whose proof is the loop's ranking certificate `n - i` + (`SourceLoop.cert`) checked by the kernel; no fuel is chosen per call: `2 ^ 256 + 8` bounds + `rank + 8` for every word `n`. +-/ + +namespace Contracts.VerifyCounter.Source +open SolidCore.Solidity.Source SolidCore.Refinement SolidCore.Refinement.Generic +open SolidCore.Refinement.Generic.Loop + +/-- SolidCore's checked `Counter`. -/ +def contract? : Except SolidCore.Solidity.TypeCheck.TypeError SolidCore.Solidity.TypeCheck.CheckedContract := + SolidCore.Solidity.TypeCheck.CheckedInput.contract SolidCore.Refinement.Source.VerifyCounter.importedSourceUnit "Counter" + +/-- The selector of `bump(uint256)`. -/ +def bumpSel : Nat := 0xb20eb4c4 + +/-- `bump`, as the type checker leaves it. -/ +def bumpFn : FunctionDef := + { name := "bump", selector? := some 2987308228, payable := false, + params := [{ name := "n", ty := Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [AbiCleanup.uint 256], returns := [], body := bumpBody, dispatchId? := none } + +def selCount : SolidCore.Solidity.Shared.Word := ABI.selectorFromSignature "count()" +kernel_rfl selCount_eq selCount 107354813 +def selLimit : SolidCore.Solidity.Shared.Word := ABI.selectorFromSignature "limit()" +kernel_rfl selLimit_eq selLimit 2765516207 +def selIncrement : SolidCore.Solidity.Shared.Word := ABI.selectorFromSignature "increment()" +kernel_rfl selIncrement_eq selIncrement 3500007562 +def selBump : SolidCore.Solidity.Shared.Word := ABI.selectorFromSignature "bump(uint256)" +kernel_rfl selBump_eq selBump 2987308228 +def selMax : SolidCore.Solidity.Shared.Word := ABI.selectorFromSignature "max(uint256,uint256)" +kernel_rfl selMax_eq selMax 1834234854 + +/-- `ABI.selectorFromSignature`, with `Counter`'s signatures by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "count()" then 107354813 + else if s = "limit()" then 2765516207 + else if s = "increment()" then 3500007562 + else if s = "bump(uint256)" then 2987308228 + else if s = "max(uint256,uint256)" then 1834234854 + else ABI.selectorFromSignature s + +theorem selector_eq : ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + by_cases h0 : s = "count()" + · rw [if_pos h0, h0]; exact selCount_eq + rw [if_neg h0] + by_cases h1 : s = "limit()" + · rw [if_pos h1, h1]; exact selLimit_eq + rw [if_neg h1] + by_cases h2 : s = "increment()" + · rw [if_pos h2, h2]; exact selIncrement_eq + rw [if_neg h2] + by_cases h3 : s = "bump(uint256)" + · rw [if_pos h3, h3]; exact selBump_eq + rw [if_neg h3] + by_cases h4 : s = "max(uint256,uint256)" + · rw [if_pos h4, h4]; exact selMax_eq + rw [if_neg h4] + +/-- What the statement reads of the checked contract. -/ +def shape? : Option (List StorageField × List EventDecl × Option FunctionDef) := + match contract? with + | .ok c => some (c.core.storageFields, c.core.eventDecls, c.core.findFunctionBySelector? bumpSel) + | .error _ => none + +-- `Counter` type checks, with the storage fields `vcFields`, no events, and `bumpFn` at bump's +-- selector: one conversion check of the type checker's copies (selectors by `selector_eq`). +kernel_rfl shape_eq shape? (some (vcFields, [], some bumpFn)) using selector_eq + +theorem shape_of {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core.storageFields = vcFields ∧ c.core.eventDecls = [] ∧ + c.core.findFunctionBySelector? bumpSel = some bumpFn := by + have h := shape_eq + unfold shape? at h + rw [hc] at h + simp only [Option.some.injEq, Prod.mk.injEq] at h + exact h + +theorem contract_ok : ∃ c, contract? = .ok c := by + have h := shape_eq + unfold shape? at h + cases hc : contract? with + | ok c => exact ⟨c, rfl⟩ + | error _ => rw [hc] at h; simp at h + +/-- The statement's fuel: `rank + 8` for every word `n`. -/ +def fuel : Nat := 2 ^ 256 + 8 + +/-- The valid calls: `bump(n)` with any argument word, no value, from any storage. -/ +def BumpCall (call : Call) : Prop := + ∃ σ a, a < 2 ^ 256 ∧ call = { calldata := Abi.calldata bumpSel [a], callvalue := 0, storage := σ } + +theorem tree_ok : ∃ T, brTree bumpFn (argFacts [256] 0) bumpBr = some T := + Option.isSome_iff_exists.mp (by decide +kernel) + +/-- **Every call of `bump(n)` runs in SolidCore to its tree's observable.** -/ +theorem runs {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) {T : Tree} + (hT : brTree bumpFn (argFacts [256] 0) bumpBr = some T) (σ : List (Nat × Nat)) (a : Nat) + (ha : a < 2 ^ 256) : + runtimeRun fuel c { calldata := Abi.calldata bumpSel [a], callvalue := 0, storage := σ } = + some (T.eval ⟨[a], slotValue σ, solHash, SolidCore.Refinement.Generic.callerWord⟩).obs := by + obtain ⟨hf, hev, hfind⟩ := shape_of hc + have hw : widthsOf bumpFn.params bumpFn.paramAbiCleanups = some [256] := rfl + have hargs : ∀ x ∈ [a], x < 2 ^ 256 := by simpa using ha + have hclean : argsClean [256] [a] = true := by + show (decide (a < 2 ^ 256) && true) = true + simp only [Bool.and_true, decide_eq_true_eq] + exact ha + have hdec := decode_args hw [a] rfl hargs + rw [if_pos hclean] at hdec + have hE : ({ envOf c.core with facts := argFacts [256] 0 } : EraseEnv) = + env c.core.eventDecls c.core.table := by + simp only [envOf, env, hf] + rfl + have hb : BodyRuns { envOf c.core with facts := argFacts [256] 0 } fuel bumpFn bumpBr := by + rw [hE] + exact body_runs _ _ bumpFn rfl rfl fuel (by unfold fuel; omega) + exact runtime_run_clean (by decide) hfind hw rfl hb hT [a] rfl hargs hclean hdec + +/-- **bump terminates in SolidCore**, on every valid call: the termination obligation of the +published shape, proved by the loop's ranking certificate. -/ +theorem terminates : ∃ c, contract? = .ok c ∧ + Shapes.Terminates (solidCoreRuntime fuel) c BumpCall (fun _ _ => True) := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨T, hT⟩ := tree_ok + refine ⟨c, hc, ?_⟩ + rintro _ ⟨σ, a, ha, rfl⟩ + exact ⟨_, runs hc hT σ a ha, trivial⟩ + +/-- **bump's specification on SolidCore's runs** (solar-verify's `count == old(count) + n`, with +the `require`): a call of `bump(n)` that succeeds leaves slot 0 holding the old `count` plus `n`, +which did not wrap and is at most `limit` (slot 1), and every other slot as it was. -/ +theorem success_spec {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) {T : Tree} + (hT : brTree bumpFn (argFacts [256] 0) bumpBr = some T) (σ : List (Nat × Nat)) (a : Nat) + (ha : a < 2 ^ 256) {obs : Observable} + (h : runtimeRun fuel c { calldata := Abi.calldata bumpSel [a], callvalue := 0, storage := σ } = + some obs) (hs : obs.success = true) : + obs.storage 0 = slotValue σ 0 + a ∧ slotValue σ 0 + a ≤ slotValue σ 1 ∧ + ∀ k, k % Generic.wordSize ≠ 0 → obs.storage k = slotValue σ k := by + rw [runs hc hT σ a ha] at h + obtain rfl := Option.some.inj h + set ρ : Val := ⟨[a], slotValue σ, solHash, SolidCore.Refinement.Generic.callerWord⟩ with hρ + have hok : ρ.Ok := slotValue_store σ + obtain ⟨T', hT', hTe⟩ := brTree_eval bumpFn (argFacts [256] 0) ρ bumpBr T hT + simp only [Res.obs] at hs ⊢ + rw [← hTe] at hs ⊢ + unfold bumpBr at hT' + rw [guards_eval] at hT' + by_cases hg : [ovf].any (fun g => g.eval ρ != 0) = true + · rw [if_pos hg] at hT' + simp only [leafTree, Option.some.injEq] at hT' + subst hT' + simp [Tree.eval] at hs + rw [if_neg hg] at hT' + simp only [Br.eval] at hT' + by_cases hv : le.eval ρ = 0 + · rw [if_pos hv] at hT' + simp only [leafTree, Option.map_eq_some_iff] at hT' + obtain ⟨bs, _, rfl⟩ := hT' + simp [Tree.eval] at hs + rw [if_neg hv] at hT' + have hpre := require_passed ρ hok hg hv + have hn : nOf ρ = a := by + simp only [nOf, WExpr.eval, hρ, List.getD_cons_zero]; exact Nat.mod_eq_of_lt ha + rw [hn] at hpre + have h1w := hok.word 1 + have h0 := hok.word 0 + have hT2 : T' = .halt true [] [(.lit 0, .bin .add (.init 0) (.arg 0))] [] := by + simp [leafTree, bumpFn, SF, retsOk] at hT' + first | exact hT'.symm | exact hT' + subst hT2 + have h0' : slotValue σ 0 < Generic.wordSize := h0 + have h1' : slotValue σ 1 < Generic.wordSize := h1w + have ha' : a < Generic.wordSize := ha + have hpre' : slotValue σ 0 + a ≤ slotValue σ 1 := hpre + refine ⟨?_, hpre', ?_⟩ + · simp only [Tree.eval, ↓reduceIte, Writes.store, WExpr.eval, BinOp.eval, hρ, List.getD_cons_zero] + rw [Nat.mod_eq_of_lt h0', Nat.mod_eq_of_lt ha', Nat.mod_mod, Nat.mod_eq_of_lt (by omega)] + · intro k hk + simp only [Tree.eval, ↓reduceIte, Writes.store, WExpr.eval] + by_cases he : 0 % Generic.wordSize = k % Generic.wordSize + · rw [Nat.zero_mod] at he; exact absurd he.symm hk + · simp only [he, ↓reduceIte] <;> rfl + +/-- info: 'Contracts.VerifyCounter.Source.terminates' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms terminates + +/-- info: 'Contracts.VerifyCounter.Source.success_spec' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms success_spec + +end Contracts.VerifyCounter.Source diff --git a/Contracts/VerifyCounter/SourceAst.lean b/Contracts/VerifyCounter/SourceAst.lean new file mode 100644 index 00000000..7f980fb9 --- /dev/null +++ b/Contracts/VerifyCounter/SourceAst.lean @@ -0,0 +1,88 @@ +-- Generated by scripts/solc_ast_to_lean_source.py from Certified/verify_counter/verify_counter.sol with solc 0.8.35 (the certify driver's source binding). Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace VerifyCounter + +def importedSourceName : String := "Certified/verify_counter/verify_counter.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Counter" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "count", + ty := Ty.uint 256, + visibility := some Visibility.public_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "limit", + ty := Ty.uint 256, + visibility := some Visibility.public_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.function + { kind := FunctionKind.constructor, + name := none, + visibility := some Visibility.public_, + mutability := StateMutability.nonpayable, + params := [{ name := some "_limit", ty := Ty.uint 256, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "limit") AssignOp.assign (Expr.ident "_limit"))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "increment", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "count") AssignOp.addAssign (Expr.literal (Literal.number "1")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "bump", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "n", ty := Ty.uint 256, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.ident "require") [Arg.positional (Expr.binary BinaryOp.le (Expr.binary BinaryOp.add (Expr.ident "count") (Expr.ident "n")) (Expr.ident "limit")), Arg.positional (Expr.literal (Literal.string "over"))]), Stmt.forLoop (some (Stmt.varDecl [{ name := some "i", ty := Ty.uint 256, location := none }] (some (Expr.literal (Literal.number "0"))))) (some (Expr.binary BinaryOp.lt (Expr.ident "i") (Expr.ident "n"))) (some (Expr.unary UnaryOp.postIncrement (Expr.ident "i"))) (Stmt.block [Stmt.expr (Expr.unary UnaryOp.postIncrement (Expr.ident "count"))])]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "max", + visibility := some Visibility.public_, + mutability := StateMutability.pure, + params := [{ name := some "a", ty := Ty.uint 256, location := none }, { name := some "b", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.ifElse (Expr.binary BinaryOp.ge (Expr.ident "a") (Expr.ident "b")) (Stmt.returnValues (some (Expr.ident "a"))) none, Stmt.returnValues (some (Expr.ident "b"))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.20", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end VerifyCounter +end Source +end Refinement +end SolidCore diff --git a/Contracts/VerifyCounter/SourceBump.lean b/Contracts/VerifyCounter/SourceBump.lean new file mode 100644 index 00000000..880c96e5 --- /dev/null +++ b/Contracts/VerifyCounter/SourceBump.lean @@ -0,0 +1,202 @@ +import Contracts.VerifyCounter.SourceLoop +import SolidCore.Refinement.Generic.LoopRun + +/-! +# bump's body in SolidCore runs to its tree, the loop by its ranking certificate + +`bumpBody` is `bump(n)`'s body as SolidCore's type checker leaves it (see `SourceAst.lean` and +`Source.lean`, where the kernel checks that the checked contract's `bump` has this body): + + { n = n; { require(count + n <= limit, "over"); { uint256 i = 0; for (; i < n; i++) { count++; } } } } + +`body_runs` is `BodyRuns` of it, for the tree `bumpBr`: `Panic(0x11)` when `count + n` wraps, +`Error("over")` when it exceeds `limit`, and otherwise success with slot 0 holding `count + n` and +nothing else written. The statements around the loop run as their erasure (`eval_stmt`); the loop +runs by its ranking certificate (`SourceLoop.cert`, `forLoop_of_cert`) at every fuel from +`2 ^ 256 + 8` on: the rank `n - i` is below `2 ^ 256`, and each iteration spends one unit. +-/ + +namespace Contracts.VerifyCounter.Source +open SolidCore.Solidity.Source SolidCore.Refinement SolidCore.Refinement.Generic +open SolidCore.Refinement.Generic.Loop + +/-- A `uint256` storage field filling its slot, as the type checker leaves `count` and `limit`. -/ +def wordField (name : String) (slot : Nat) : StorageField := + { name := name, slot := slot, ty? := some Ty.uint256, layout? := some (StorageLayout.scalar Ty.uint256), + transient := false, packedOffset := 0, packedBytes := 32, packedSigned := false } + +/-- `Counter`'s storage fields. -/ +def vcFields : List StorageField := [wordField "count" 0, wordField "limit" 1] + +def s1 : Stmt := .assign (.var "n") (.castOp .uintCleanup 256 (.var "n")) + +def s2 : Stmt := + .requireStmt + (.binary .le + (.castOp .uintCleanup 256 (.castOp .uintCleanup 256 + (.binary .add (.castOp .uintCleanup 256 (.storageRead .ref "count" [])) + (.castOp .uintCleanup 256 (.var "n"))))) + (.castOp .uintCleanup 256 (.storageRead .ref "limit" []))) + (some "over") + +def s3 : Stmt := .varDecl .uint256 "i" (some (.word 0)) + +def loop : Stmt := .forLoop .skip cond post body + +/-- **bump's body.** -/ +def bumpBody : Stmt := .block [s1, .block [s2, .block [s3, loop]]] + +/-- The first symbolic state of a call of `bump`: `n` is argument 0. -/ +def S0 : SymState := { scopes := [[("n", .arg 0)]], writes := [], logs := [] } + +/-- `count + n` wraps. -/ +def ovf : WExpr := .bin .lt (.bin .add (.init 0) (.arg 0)) (.init 0) + +/-- `count + n <= limit`. -/ +def le : WExpr := .un .iszero (.bin .gt (.bin .add (.init 0) (.arg 0)) (.init 1)) + +/-- The state at the end of the body: slot 0 holds `count + n`. -/ +def SF : SymState := + { scopes := [[("n", .arg 0)]], writes := [(.lit 0, .bin .add (.init 0) (.arg 0))], logs := [] } + +/-- **bump's tree of leaves.** -/ +def bumpBr : Br := guards [ovf] (.ite le (.leaf (.normal SF)) (.leaf (.reverted (.error "over")))) + +/-- The erasure environment of bump's body. -/ +def env (ev : List EventDecl) (tbl : FunctionTable) : EraseEnv := + { fields := vcFields, events := ev, tbl := tbl, facts := [] } + +theorem e1 (ev : List EventDecl) (tbl : FunctionTable) : + eraseStmt (env ev tbl) 10 s1 S0.push = some (.leaf (.normal S0.push)) := rfl + +theorem e2 (ev : List EventDecl) (tbl : FunctionTable) : + eraseStmt (env ev tbl) 10 s2 S0.push.push = + some (guards [ovf] (.ite le (.leaf (.normal S0.push.push)) (.leaf (.reverted (.error "over"))))) := + rfl + +theorem e3 (ev : List EventDecl) (tbl : FunctionTable) : + eraseStmt (env ev tbl) 10 s3 S0.push.push.push = + some (.leaf (.normal { S0.push.push.push with scopes := [[("i", .lit 0)], [], [], [("n", .arg 0)]] })) := + rfl + +theorem leaf_normal {ρ : Val} {E : EraseEnv} {ctx : Context} {r : Result} {S : SymState} + (h : LeafRel ρ E ctx r (.normal S)) : ∃ rt, r = .normal rt ∧ StmtRel ρ E ctx rt S := by + cases r <;> simp only [LeafRel] at h + exact ⟨_, rfl, h⟩ + +/-- What the `require` passing says: `count + n` does not wrap and is at most `limit`. -/ +theorem require_passed (ρ : Val) (hok : ρ.Ok) (hg : ¬([ovf].any (fun g => g.eval ρ != 0) = true)) + (hv : ¬le.eval ρ = 0) : ρ.store 0 + nOf ρ ≤ ρ.store 1 := by + have h0 := hok.word 0 + have h1w := hok.word 1 + have hn := nOf_lt ρ + have hg' : ovf.eval ρ = 0 := by + simpa [bne_iff_ne] using hg + have eovf : ovf.eval ρ = if (ρ.store 0 + nOf ρ) % Generic.wordSize < ρ.store 0 then 1 else 0 := by + simp only [ovf, nOf, WExpr.eval, BinOp.eval, Nat.mod_eq_of_lt h0, Nat.mod_mod] + by_cases h : (ρ.store 0 + ρ.args.getD 0 0 % Generic.wordSize) % Generic.wordSize < ρ.store 0 <;> + simp only [h, ↓reduceIte] <;> decide + have ele : le.eval ρ = if ρ.store 1 < (ρ.store 0 + nOf ρ) % Generic.wordSize then 0 else 1 := by + simp only [le, nOf, WExpr.eval, BinOp.eval, UnOp.eval, Nat.mod_eq_of_lt h0, + Nat.mod_eq_of_lt h1w, Nat.mod_mod] + by_cases h : ρ.store 1 < (ρ.store 0 + ρ.args.getD 0 0 % Generic.wordSize) % Generic.wordSize <;> + simp only [h, ↓reduceIte] <;> decide + have hw : ρ.store 0 + nOf ρ < Generic.wordSize := by + by_contra hc + have : (ρ.store 0 + nOf ρ) % Generic.wordSize < ρ.store 0 := by + rw [Nat.mod_eq_sub_mod (by omega), Nat.mod_eq_of_lt (by omega)]; omega + rw [eovf, if_pos this] at hg'; cases hg' + rw [ele, Nat.mod_eq_of_lt hw] at hv + split at hv + · exact absurd rfl hv + · omega + +set_option maxHeartbeats 4000000 in +/-- **bump's body runs to `bumpBr`**, at every fuel from `2 ^ 256 + 8` on. -/ +theorem body_runs (ev : List EventDecl) (tbl : FunctionTable) (fn : FunctionDef) + (hbody : fn.body = bumpBody) (hinit : initState fn = S0) (fuel : Nat) + (hfuel : 2 ^ 256 + 8 ≤ fuel) : BodyRuns (env ev tbl) fuel fn bumpBr := by + intro ρ ctx rt hrel + rw [hinit] at hrel + rw [hbody] + obtain ⟨f, rfl⟩ : ∃ f, fuel = f + 4 := ⟨fuel - 4, by omega⟩ + have hok : ρ.Ok := hrel.ok + set E := env ev tbl with hE + -- n = n + obtain ⟨r1, h1, l1⟩ := eval_stmt ρ E ctx 10 s1 S0.push _ (e1 ev tbl) rt.pushScope hrel.pushScope + obtain ⟨rt1, rfl, hrel1⟩ := leaf_normal l1 + have h1' := eval_mono (by omega : 10 ≤ f + 3) h1 + -- require(count + n <= limit, "over") + obtain ⟨r2, h2, l2⟩ := eval_stmt ρ E ctx 10 s2 S0.push.push _ (e2 ev tbl) rt1.pushScope + hrel1.pushScope + have h2' := eval_mono (by omega : 10 ≤ f + 2) h2 + unfold bumpBr + rw [guards_eval] at l2 ⊢ + by_cases hg : [ovf].any (fun g => g.eval ρ != 0) = true + · -- count + n wraps: Panic(0x11) + rw [if_pos hg] at l2 ⊢ + cases r2 <;> simp only [LeafRel] at l2 + rename_i rt2 e + have hl2 := evalList_cons_stop (rest := [.block [s3, loop]]) h2' (fun _ h => by cases h) + have hb2 := eval_block_of hl2 + have hl1 := evalList_cons_stop (rest := []) hb2 (fun _ h => by cases h) + exact ⟨_, eval_block_of ((evalList_cons_normal h1').trans hl1), l2⟩ + rw [if_neg hg] at l2 ⊢ + simp only [Br.eval] at l2 ⊢ + by_cases hv : le.eval ρ = 0 + · -- count + n > limit: Error("over") + rw [if_pos hv] at l2 ⊢ + cases r2 <;> simp only [LeafRel] at l2 + have hl2 := evalList_cons_stop (rest := [.block [s3, loop]]) h2' (fun _ h => by cases h) + have hb2 := eval_block_of hl2 + have hl1 := evalList_cons_stop (rest := []) hb2 (fun _ h => by cases h) + exact ⟨_, eval_block_of ((evalList_cons_normal h1').trans hl1), l2⟩ + rw [if_neg hv] at l2 ⊢ + obtain ⟨rt2, rfl, hrel2⟩ := leaf_normal l2 + -- the require passed: count + n does not wrap and is at most limit + have h0 := hok.word 0 + have h1w := hok.word 1 + have hn := nOf_lt ρ + have hpre := require_passed ρ hok hg hv + -- uint256 i = 0 + obtain ⟨r3, h3, l3⟩ := eval_stmt ρ E ctx 10 s3 S0.push.push.push _ (e3 ev tbl) rt2.pushScope + hrel2.pushScope + obtain ⟨rt3, rfl, hrel3⟩ := leaf_normal l3 + have h3' := eval_mono (by omega : 10 ≤ f + 1) h3 + -- the loop, by its ranking certificate + have hrelh : StmtRel (hval ρ 0 (ρ.store 0 + 0)) E ctx rt3.pushScope headerS := by + refine StmtRel.congr hrel3.pushScope hrel3.hash hok (Facts.hold_nil _) ?_ ?_ rfl + · simp [SymState.push, S0, headerS, frameOf, WExpr.eval, hval] + · intro k hk + simp only [Writes.store, SymState.push, S0, headerS] + split_ifs with hk0 + · simp only [WExpr.eval, hval, List.getD_cons_succ, List.getD_cons_zero, Nat.add_zero] at hk0 ⊢ + rw [Nat.mod_eq_of_lt hk] at hk0 + rw [← hk0, Nat.mod_eq_of_lt h0, Nat.zero_mod] + · rfl + have hskip : Stmt.eval 1 E.tbl ctx rt3.pushScope .skip = .done (.ok (.normal rt3.pushScope)) := by + rw [Stmt.eval]; rfl + have hinv : Inv ρ E ctx rt3.pushScope := ⟨0, Nat.zero_le _, hrelh⟩ + obtain ⟨r, hr, hq⟩ := forLoop_of_cert (cert ρ E ctx rfl rfl hpre) hskip hinv (f + 1) + (by have hn2 : nOf ρ < 2 ^ 256 := hn; rw [rank_of hrelh (by decide)]; omega) (by omega) + obtain ⟨rtx, rfl, hrelx⟩ := hq + have hr' : Stmt.eval (f + 1) E.tbl ctx rt3 loop = .done (.ok (.normal rtx.popScope)) := hr + have hl3 : Stmt.evalList (f + 1) E.tbl ctx rt2.pushScope [s3, loop] = + .done (.ok (.normal rtx.popScope)) := by + rw [evalList_cons_normal h3', evalList_cons_normal hr', evalList_nil] + have hb3 : Stmt.eval (f + 2) E.tbl ctx rt2 (.block [s3, loop]) = _ := eval_block_of hl3 + have hl2 : Stmt.evalList (f + 2) E.tbl ctx rt1.pushScope [s2, .block [s3, loop]] = + .done (.ok (.normal rtx.popScope.popScope)) := by + rw [evalList_cons_normal h2', evalList_cons_normal hb3, evalList_nil] + have hb2 : Stmt.eval (f + 3) E.tbl ctx rt1 (.block [s2, .block [s3, loop]]) = _ := + eval_block_of hl2 + have hl1 : Stmt.evalList (f + 3) E.tbl ctx rt.pushScope [s1, .block [s2, .block [s3, loop]]] = + .done (.ok (.normal rtx.popScope.popScope.popScope)) := by + rw [evalList_cons_normal h1', evalList_cons_normal hb2, evalList_nil] + exact ⟨_, eval_block_of hl1, hrelx.popScope.popScope.popScope.popScope⟩ + +/-- info: 'Contracts.VerifyCounter.Source.body_runs' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms body_runs + +end Contracts.VerifyCounter.Source diff --git a/Contracts/VerifyCounter/SourceLoop.lean b/Contracts/VerifyCounter/SourceLoop.lean new file mode 100644 index 00000000..506bb60b --- /dev/null +++ b/Contracts/VerifyCounter/SourceLoop.lean @@ -0,0 +1,175 @@ +import SolidCore.Refinement.Generic.LoopStmt +import SolidCore.Refinement.Generic.LoopSeq + +/-! +# bump's loop in SolidCore: a ranking certificate + +`bump(n)` of solar-verify's `Counter` (crates/verify/examples/Counter.sol), + + require(count + n <= limit, "over"); + for (uint256 i = 0; i < n; i++) { count++; } + +as SolidCore's type checker leaves it (`bumpBody`, from `Contracts/VerifyCounter/SourceAst.lean`). +The loop's certificate (`cert`) is solar-verify's inferred invariant and measure for this loop, +`i <= n`, `count == old(count) + i` and `n - i`, stated of SolidCore's runtime at the header +(`Inv`, `rank`): the runtime is related (`StmtRel`) to the header state `headerS` whose words for +`n`, `i` and `count` are fresh (arguments 0, 1 and 2 of `hval ρ i (count0 + i)`). Each iteration is +run by SolidCore's interpreter (`eval_incField`, `eval_incVar`): the overflow guards of `count++` +and `i++` are false under the invariant and the `require`, the invariant comes back with `i + 1`, +and the rank falls by one; on exit `i = n` and `count` is `old(count) + n` (`exitS`). +-/ + +namespace Contracts.VerifyCounter.Source +open SolidCore.Solidity.Source SolidCore.Refinement SolidCore.Refinement.Generic +open SolidCore.Refinement.Generic.Loop + +/-- The loop's condition, `i < n`. -/ +def cond : Expr := .binary .lt (.castOp .uintCleanup 256 (.var "i")) (.castOp .uintCleanup 256 (.var "n")) + +/-- The loop's update, `i++`. -/ +def post : Stmt := .exprStmt (.incDec .add true (some (.uint 256)) (.var "i")) + +/-- The loop's body, `count++`. -/ +def body : Stmt := + .block [.exprStmt (.incDec .add true (some (.uint 256)) (.storageRead .header "count" []))] + +/-- The header state: `n` is argument 0, `i` argument 1 and `count` (slot 0) argument 2. -/ +def headerS : SymState := + { scopes := [[], [("i", .arg 1)], [], [], [("n", .arg 0)]], writes := [(.lit 0, .arg 2)], logs := [] } + +/-- The state at the loop's exit, over the call's words: `i = n`, `count = old(count) + n`. -/ +def exitS : SymState := + { scopes := [[], [("i", .arg 0)], [], [], [("n", .arg 0)]], + writes := [(.lit 0, .bin .add (.init 0) (.arg 0))], logs := [] } + +/-- The words of the header: the call's `n`, and `i` and `count`. -/ +def hval (ρ : Val) (i c : Nat) : Val := ⟨[ρ.args.getD 0 0, i, c], ρ.store, ρ.hash, ρ.caller⟩ + +/-- The call's `n`. -/ +def nOf (ρ : Val) : Nat := (WExpr.arg 0).eval ρ + +/-- **The invariant** (inferred: `i <= n`, `count == old(count) + i`). -/ +def Inv (ρ : Val) (E : EraseEnv) (ctx : Context) (rt : Runtime) : Prop := + ∃ i, i ≤ nOf ρ ∧ StmtRel (hval ρ i (ρ.store 0 + i)) E ctx rt headerS + +/-- **The rank** (inferred: `n - i`), read off the runtime's `i`. -/ +def rank (ρ : Val) (rt : Runtime) : Nat := + match rt.lookupLocal? "i" with + | some (.word v) => nOf ρ - v + | _ => 0 + +/-- What the loop ends in: normally, in the exit state. -/ +def Q (ρ : Val) (E : EraseEnv) (ctx : Context) (r : Result) : Prop := + ∃ rt, r = .normal rt ∧ StmtRel ρ E ctx rt exitS + +/-- The storage fields of `Counter`, as the type checker leaves them. -/ +def countOk (E : EraseEnv) : Prop := fieldOf? E.fields "count" = some (0, 0, 32) + +theorem nOf_lt (ρ : Val) : nOf ρ < wordSize := WExpr.eval_lt ρ _ + +theorem rank_of {ρ : Val} {E : EraseEnv} {ctx : Context} {rt : Runtime} {i c : Nat} + (h : StmtRel (hval ρ i c) E ctx rt headerS) (hi : i < wordSize) : rank ρ rt = nOf ρ - i := by + have := h.expr.locals "i" (.arg 1) rfl + simp only [rank, this, WExpr.eval, hval, List.getD_cons_succ, List.getD_cons_zero, + Nat.mod_eq_of_lt hi] + +set_option maxHeartbeats 4000000 in +/-- **bump's loop with any measure R that falls on every iteration is certified**: everything +but the rank's fall is checked here, against SolidCore's interpreter. -/ +theorem certWith (ρ : Val) (E : EraseEnv) (ctx : Context) (hcount : countOk E) + (hfacts : E.facts = []) (hpre : ρ.store 0 + nOf ρ ≤ ρ.store 1) (R : Runtime → Nat) + (hR : ∀ i rt rt', i < nOf ρ → StmtRel (hval ρ i (ρ.store 0 + i)) E ctx rt headerS → + StmtRel (hval ρ (i + 1) (ρ.store 0 + (i + 1))) E ctx rt' headerS → R rt' < R rt) : + ForCert 3 E.tbl ctx cond post body (Inv ρ E ctx) R (Q ρ E ctx) := by + constructor + rintro rt ⟨i, hi, hrel⟩ + have hok : ρ.Ok := hrel.ok + have hlim : ρ.store 1 < wordSize := hok.word 1 + have hn := nOf_lt ρ + have hiw : i < wordSize := by omega + have hcw : ρ.store 0 + i < wordSize := by omega + have hcond : eraseExpr E.fields headerS cond = some ([], .bin .lt (.arg 1) (.arg 0)) := rfl + have hev := eval_eq _ E.fields ctx rt headerS hrel.expr hcond + have hlt : (WExpr.bin .lt (.arg 1) (.arg 0)).eval (hval ρ i (ρ.store 0 + i)) = + if i < nOf ρ then 1 else 0 := by + simp only [WExpr.eval, BinOp.eval, hval, List.getD_cons_succ, List.getD_cons_zero, + Nat.mod_eq_of_lt hiw, nOf] + by_cases h : i < ρ.args.getD 0 0 % wordSize <;> simp only [h, ↓reduceIte] <;> decide + refine ⟨.ok (.word (if i < nOf ρ then 1 else 0), rt), ?_, ?_⟩ + · rw [hev, caught_exprResult] + simp only [List.any_nil, Bool.false_eq_true, ↓reduceIte, hlt] + dsimp only [Value.expectWord] + by_cases hin : i < nOf ρ + · rw [if_pos hin, if_pos (by decide)] + -- the body: count++ under the header state + have hk : fieldOf? E.fields "count" = some (0, 0, 32) := hcount + obtain ⟨r1, h1, hl1⟩ := eval_incField _ E ctx rt.pushScope headerS.push hrel.pushScope 1 true hk + have hbr : incFieldBr 0 0 32 headerS.push = + guards [.bin .lt (.bin .add (.arg 2) (.lit 1)) (.arg 2)] + (.leaf (.normal { headerS.push with writes := [(.lit 0, .bin .add (.arg 2) (.lit 1))] })) := rfl + rw [hbr, guards_eval] at hl1 + have hg : ([WExpr.bin .lt (.bin .add (.arg 2) (.lit 1)) (.arg 2)].any + (fun g => g.eval (hval ρ i (ρ.store 0 + i)) != 0)) = false := by + have h1' : ρ.store 0 + i + 1 < wordSize := by omega + simp [WExpr.eval, BinOp.eval, hval, Nat.mod_eq_of_lt hcw, Nat.mod_eq_of_lt h1'] + rw [hg] at hl1 + simp only [Bool.false_eq_true, ↓reduceIte, Br.eval] at hl1 + rcases r1 with rb | ⟨_, _⟩ | _ | ⟨_, _⟩ | _ | _ <;> simp only [LeafRel] at hl1 + have hlist : Stmt.evalList (1 + 1) E.tbl ctx rt.pushScope + [.exprStmt (.incDec .add true (some (.uint 256)) (.storageRead .header "count" []))] = + .done (.ok (.normal rb)) := by + rw [evalList_cons_normal h1, evalList_nil] + have hb := eval_block_of hlist + refine ⟨_, hb, ?_⟩ + -- the update: i++ + have hrelb := hl1.popScope + obtain ⟨r2, h2, hl2⟩ := eval_incVar _ E ctx rb.popScope _ hrelb 2 true (x := "i") + (old := .arg 1) (L' := [[], [("i", .bin .add (.arg 1) (.lit 1))], [], [], [("n", .arg 0)]]) + rfl rfl + simp only [ForRest, Result.mapRuntime] + refine ⟨r2, h2, ?_⟩ + have hi1 : i + 1 < wordSize := by omega + have hg2 : (overflow .add (.arg 1) (.lit 1)).toList.any + (fun g => g.eval (hval ρ i (ρ.store 0 + i)) != 0) = false := by + simp [overflow, WExpr.eval, BinOp.eval, hval, Nat.mod_eq_of_lt hiw, Nat.mod_eq_of_lt hi1] + simp only [incVarBr, guards_eval, hg2, Bool.false_eq_true, ↓reduceIte, Br.eval] at hl2 + rcases r2 with rp | ⟨_, _⟩ | _ | ⟨_, _⟩ | _ | _ <;> simp only [LeafRel] at hl2 + have hc1 : ρ.store 0 + (i + 1) < wordSize := by omega + have hrelp : StmtRel (hval ρ (i + 1) (ρ.store 0 + (i + 1))) E ctx rp headerS := by + refine StmtRel.congr hl2 hrel.hash hok (by rw [hfacts]; exact Facts.hold_nil _) ?_ ?_ rfl + · simp [headerS, SymState.pop, SymState.push, frameOf, WExpr.eval, BinOp.eval, hval, + Nat.mod_eq_of_lt hiw, Nat.mod_eq_of_lt hi1] + · intro k _ + simp only [Writes.store, SymState.pop, SymState.push, headerS, WExpr.eval, BinOp.eval, hval, + List.getD_cons_succ, List.getD_cons_zero] + split_ifs + · rw [Nat.mod_eq_of_lt hcw, show 1 % wordSize = 1 by decide, Nat.mod_mod, ← Nat.add_assoc] + · rfl + exact ⟨⟨i + 1, by omega, hrelp⟩, hR i rt rp hin hrel hrelp⟩ + · rw [if_neg hin, if_neg (by decide)] + have hie : i = nOf ρ := by omega + refine ⟨rt, rfl, StmtRel.congr hrel hrel.hash hok (by rw [hfacts]; exact Facts.hold_nil _) ?_ ?_ rfl⟩ + · simp [headerS, exitS, frameOf, WExpr.eval, hval, Nat.mod_eq_of_lt hiw, hie, nOf] + · intro k _ + have h0 := hok.word 0 + have hie' : ρ.args.getD 0 0 % wordSize = i := hie.symm + simp only [Writes.store, headerS, exitS, WExpr.eval, BinOp.eval, hval, List.getD_cons_succ, + List.getD_cons_zero] + by_cases hk0 : 0 % wordSize = k % wordSize <;> simp only [hk0, ↓reduceIte] + rw [Nat.mod_eq_of_lt h0, hie', Nat.mod_mod] + +/-- **bump's loop has a ranking certificate**: the inferred measure `n - i` falls by one on every +iteration. -/ +theorem cert (ρ : Val) (E : EraseEnv) (ctx : Context) (hcount : countOk E) + (hfacts : E.facts = []) (hpre : ρ.store 0 + nOf ρ ≤ ρ.store 1) : + ForCert 3 E.tbl ctx cond post body (Inv ρ E ctx) (rank ρ) (Q ρ E ctx) := + certWith ρ E ctx hcount hfacts hpre (rank ρ) fun i _ _ hin h h' => by + have hn := nOf_lt ρ + rw [rank_of h' (by omega), rank_of h (by omega)] + omega + +/-- info: 'Contracts.VerifyCounter.Source.cert' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms cert + +end Contracts.VerifyCounter.Source diff --git a/Contracts/VerifyCounter/SourceMutant.lean b/Contracts/VerifyCounter/SourceMutant.lean new file mode 100644 index 00000000..bc7e4006 --- /dev/null +++ b/Contracts/VerifyCounter/SourceMutant.lean @@ -0,0 +1,159 @@ +import SolidCore.Refinement.Generic.LoopErr +import Contracts.VerifyCounter.SourceMutantShape +import Contracts.VerifyCounter.ShapeSource + +/-! +# A negative control: bump without its loop's update does not terminate + +`SourceMutantAst.lean` is `Counter`'s solc AST with bump's loop update `i++` and its body +`count++` removed: `for (uint256 i = 0; i < n;) {}`. The kernel checks (`shapeM_eq`) that the type +checker accepts it, with the same storage fields and no events, and that its `bump` is `bumpFnM`, +whose loop is `loopM`. + +* `body_err`: from every runtime related to bump's first symbolic state, on every call whose + `require` passes and whose `n` is at least 1, the body **fails** at every fuel from 14 on (out of + fuel): the loop's condition always holds and nothing changes (`forLoop_err`). +* `never`: the call `bump(1)` from the storage with `count = 0` and `limit = 1` has **no result** + in `solidCoreRuntime fuel` at any fuel from 14 on (`runtime_run_err`). +* `not_terminates`, `not_certified`: so the mutant fails the termination obligation of the + published shape on `bump`'s valid calls, whatever statuses it allows, and never reaches the + strongest status (`Shapes.Certified`), whatever bytecode, specification and gas bound are named. +-/ + +namespace Contracts.VerifyCounter.Mutant +open SolidCore.Solidity.Source SolidCore.Refinement SolidCore.Refinement.Generic +open SolidCore.Refinement.Generic.Loop Contracts.VerifyCounter.Source + +theorem eval_zero_err (tbl : FunctionTable) (ctx : Context) (rt : Runtime) (st : Stmt) : + Stmt.eval 0 tbl ctx rt st = .done (.error .outOfFuel) := by + rw [Stmt.eval]; rfl + +set_option maxHeartbeats 2000000 in +/-- **The mutant's body fails at every fuel from 14 on**, on a call whose `require` passes and +whose `n` is at least 1. -/ +theorem body_err (ev : List EventDecl) (tbl : FunctionTable) (fn : FunctionDef) + (hbody : fn.body = bumpBodyM) (fuel : Nat) (hfuel : 14 ≤ fuel) + (ρ : Val) (ctx : Context) (rt : Runtime) (hrel : StmtRel ρ (env ev tbl) ctx rt S0) + (hg : ¬([ovf].any (fun g => g.eval ρ != 0) = true)) (hv : ¬le.eval ρ = 0) (hn1 : 0 < nOf ρ) : + ∃ e, Stmt.eval fuel tbl ctx rt fn.body = .done (.error e) := by + rw [hbody] + obtain ⟨f, rfl⟩ : ∃ f, fuel = f + 4 := ⟨fuel - 4, by omega⟩ + have hok : ρ.Ok := hrel.ok + set E := env ev tbl with hE + show ∃ e, Stmt.eval (f + 4) E.tbl ctx rt bumpBodyM = .done (.error e) + -- n = n + obtain ⟨r1, h1, l1⟩ := eval_stmt ρ E ctx 10 s1 S0.push _ (e1 ev tbl) rt.pushScope hrel.pushScope + obtain ⟨rt1, rfl, hrel1⟩ := leaf_normal l1 + have h1' := eval_mono (by omega : 10 ≤ f + 3) h1 + -- require(count + n <= limit, "over") passes + obtain ⟨r2, h2, l2⟩ := eval_stmt ρ E ctx 10 s2 S0.push.push _ (e2 ev tbl) rt1.pushScope + hrel1.pushScope + have h2' := eval_mono (by omega : 10 ≤ f + 2) h2 + rw [guards_eval, if_neg hg] at l2 + simp only [Br.eval, if_neg hv] at l2 + obtain ⟨rt2, rfl, hrel2⟩ := leaf_normal l2 + have h0 := hok.word 0 + have hn := nOf_lt ρ + -- uint256 i = 0 + obtain ⟨r3, h3, l3⟩ := eval_stmt ρ E ctx 10 s3 S0.push.push.push _ (e3 ev tbl) rt2.pushScope + hrel2.pushScope + obtain ⟨rt3, rfl, hrel3⟩ := leaf_normal l3 + have h3' := eval_mono (by omega : 10 ≤ f + 1) h3 + have hrelh : StmtRel (hval ρ 0 (ρ.store 0 + 0)) E ctx rt3.pushScope headerS := by + refine StmtRel.congr hrel3.pushScope hrel3.hash hok (Facts.hold_nil _) ?_ ?_ rfl + · simp [SymState.push, S0, headerS, frameOf, WExpr.eval, hval] + · intro k hk + simp only [Writes.store, SymState.push, S0, headerS] + split_ifs with hk0 + · simp only [WExpr.eval, hval, List.getD_cons_succ, List.getD_cons_zero, Nat.add_zero] at hk0 ⊢ + rw [Nat.mod_eq_of_lt hk] at hk0 + rw [← hk0, Nat.mod_eq_of_lt h0, Nat.zero_mod] + · rfl + -- the loop: its condition always holds and nothing changes + have hloop : ∀ g, ∃ e, Stmt.eval g E.tbl ctx rt3 loopM = .done (.error e) := by + refine forLoop_err (fun rt => StmtRel (hval ρ 0 (ρ.store 0 + 0)) E ctx rt headerS) ?_ ?_ + · intro rt h + have hcond : eraseExpr E.fields headerS cond = some ([], .bin .lt (.arg 1) (.arg 0)) := rfl + have hev := eval_eq _ E.fields ctx rt headerS h.expr hcond + refine ⟨1, rt, ?_, by decide, ?_⟩ + · have hval1 : (WExpr.bin .lt (.arg 1) (.arg 0)).eval (hval ρ 0 (ρ.store 0 + 0)) = 1 := by + simp only [WExpr.eval, BinOp.eval, hval, List.getD_cons_succ, List.getD_cons_zero, + Nat.zero_mod] + have : 0 < ρ.args.getD 0 0 % Generic.wordSize := hn1 + rw [if_pos this] + decide + rw [hev, caught_exprResult] + simp only [List.any_nil, Bool.false_eq_true, ↓reduceIte, hval1] + · intro g + cases g with + | zero => exact Or.inl ⟨_, eval_zero_err _ _ _ _⟩ + | succ g => + refine Or.inr ⟨rt.pushScope.popScope, ?_, ?_⟩ + · rw [eval_block_of (evalList_nil g E.tbl ctx rt.pushScope)] + rfl + · refine Or.inr ⟨rt.pushScope.popScope, ?_, h.pushScope.popScope⟩ + rw [Stmt.eval]; rfl + · intro g + cases g with + | zero => exact Or.inl ⟨_, eval_zero_err _ _ _ _⟩ + | succ g => + refine Or.inr ⟨rt3.pushScope, ?_, hrelh⟩ + rw [Stmt.eval]; rfl + obtain ⟨e, he⟩ := hloop (f + 1) + have hl3 : Stmt.evalList (f + 1) E.tbl ctx rt2.pushScope [s3, loopM] = .done (.error e) := by + rw [evalList_cons_normal h3', evalList_cons_err he] + have hl2 : Stmt.evalList (f + 2) E.tbl ctx rt1.pushScope [s2, .block [s3, loopM]] = + .done (.error e) := by + rw [evalList_cons_normal h2', evalList_cons_err (eval_block_err hl3)] + have hl1 : Stmt.evalList (f + 3) E.tbl ctx rt.pushScope [s1, .block [s2, .block [s3, loopM]]] = + .done (.error e) := by + rw [evalList_cons_normal h1', evalList_cons_err (eval_block_err hl2)] + exact ⟨e, eval_block_err hl1⟩ + +/-- The call `bump(1)` from `count = 0`, `limit = 1`: its `require` passes. -/ +def badCall : SolarTV.Call := bumpCall [(1, 1)] 1 + +/-- **The mutant has no result on `bump(1)`**, at every fuel from 14 on. -/ +theorem never {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contractM? = .ok c) + (fuel : Nat) (hfuel : 14 ≤ fuel) : runtimeRun fuel c badCall = none := by + obtain ⟨hf, hev, hfind⟩ := shapeM_of hc + have hw : widthsOf bumpFnM.params bumpFnM.paramAbiCleanups = some [256] := rfl + have hargs : ∀ x ∈ [1], x < 2 ^ 256 := by simp + have hclean : argsClean [256] [1] = true := by decide + have hdec := decode_args hw [1] rfl hargs + rw [if_pos hclean] at hdec + have hE : ({ envOf c.core with facts := argFacts [256] 0 } : EraseEnv) = + env c.core.eventDecls c.core.table := by + simp only [envOf, env, hf] + rfl + refine runtime_run_err (by decide) hfind hw rfl [1] rfl hargs hclean hdec ?_ + intro ctx rt hrel + rw [hE] at hrel + exact body_err _ _ bumpFnM rfl fuel hfuel _ ctx rt hrel (by decide) (by decide) (by decide) + +/-- **The mutant fails the termination obligation** on bump's valid calls, at every fuel from 14 +on (the statement's `fuel` among them), whatever statuses it allows. -/ +theorem not_terminates : ∃ c, contractM? = .ok c ∧ ∀ fuel, 14 ≤ fuel → + ∀ Allowed, ¬ Shapes.Terminates (solidCoreRuntime fuel) c BumpCall Allowed := by + obtain ⟨c, hc⟩ := contractM_ok + exact ⟨c, hc, fun fuel hf Allowed => + Shapes.not_terminates_of_none ⟨[(1, 1)], 1, by decide, rfl⟩ (never hc fuel hf)⟩ + +/-- **The mutant never reaches the strongest status** on the published valid calls, whatever +bytecode, statuses, specification and gas bound are named. -/ +theorem not_certified : ∃ c, contractM? = .ok c ∧ ∀ (code : ByteArray) Allowed Post G, + ¬ Shapes.Certified (solidCoreRuntime fuel) c code ShapeSource.ValidS Allowed Post G := by + obtain ⟨c, hc⟩ := contractM_ok + refine ⟨c, hc, fun code Allowed Post G h => ?_⟩ + exact Shapes.not_terminates_of_none (Valid := ShapeSource.ValidS) (Allowed := Allowed) + ⟨[(1, 1)], 1, by decide, rfl⟩ (never hc fuel (by unfold fuel; omega)) h.terminates + +/-- info: 'Contracts.VerifyCounter.Mutant.not_certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms not_certified + +/-- info: 'Contracts.VerifyCounter.Mutant.not_terminates' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms not_terminates + +end Contracts.VerifyCounter.Mutant diff --git a/Contracts/VerifyCounter/SourceMutantAst.lean b/Contracts/VerifyCounter/SourceMutantAst.lean new file mode 100644 index 00000000..ac913219 --- /dev/null +++ b/Contracts/VerifyCounter/SourceMutantAst.lean @@ -0,0 +1,88 @@ +-- A negative control: SourceAst.lean (solc 0.8.35 AST of solar crates/verify/examples/Counter.sol) +-- with bump's loop update i++ and its body count++ removed: for (uint256 i = 0; i < n;) {}. +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace VerifyCounterMutant + +def importedSourceName : String := "crates/verify/examples/Counter.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Counter" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "count", + ty := Ty.uint 256, + visibility := some Visibility.public_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "limit", + ty := Ty.uint 256, + visibility := some Visibility.public_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.function + { kind := FunctionKind.constructor, + name := none, + visibility := some Visibility.public_, + mutability := StateMutability.nonpayable, + params := [{ name := some "_limit", ty := Ty.uint 256, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "limit") AssignOp.assign (Expr.ident "_limit"))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "increment", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "count") AssignOp.addAssign (Expr.literal (Literal.number "1")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "bump", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "n", ty := Ty.uint 256, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.ident "require") [Arg.positional (Expr.binary BinaryOp.le (Expr.binary BinaryOp.add (Expr.ident "count") (Expr.ident "n")) (Expr.ident "limit")), Arg.positional (Expr.literal (Literal.string "over"))]), Stmt.forLoop (some (Stmt.varDecl [{ name := some "i", ty := Ty.uint 256, location := none }] (some (Expr.literal (Literal.number "0"))))) (some (Expr.binary BinaryOp.lt (Expr.ident "i") (Expr.ident "n"))) none (Stmt.block [])]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "max", + visibility := some Visibility.public_, + mutability := StateMutability.pure, + params := [{ name := some "a", ty := Ty.uint 256, location := none }, { name := some "b", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.ifElse (Expr.binary BinaryOp.ge (Expr.ident "a") (Expr.ident "b")) (Stmt.returnValues (some (Expr.ident "a"))) none, Stmt.returnValues (some (Expr.ident "b"))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.20", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end VerifyCounterMutant +end Source +end Refinement +end SolidCore diff --git a/Contracts/VerifyCounter/SourceMutantShape.lean b/Contracts/VerifyCounter/SourceMutantShape.lean new file mode 100644 index 00000000..4c2e0afd --- /dev/null +++ b/Contracts/VerifyCounter/SourceMutantShape.lean @@ -0,0 +1,54 @@ +import Contracts.VerifyCounter.Source +import Contracts.VerifyCounter.SourceMutantAst + +/-! +# The mutant `Counter` type checks, and its `bump` + +The kernel checks (`shapeM_eq`, `kernel_rfl` on the type checker's copies, selectors by +`Source.selector_eq`) that SolidCore's type checker accepts `SourceMutantAst.lean`, with +`Counter`'s storage fields and no events, and that its function of selector `bump(uint256)` is +`bumpFnM`: bump's body with the loop `for (; i < n;) {}` (`loopM`). See `SourceMutant.lean`. +-/ + +namespace Contracts.VerifyCounter.Mutant +open SolidCore.Solidity.Source SolidCore.Refinement SolidCore.Refinement.Generic +open Contracts.VerifyCounter.Source + +/-- The mutant's checked `Counter`. -/ +def contractM? : Except SolidCore.Solidity.TypeCheck.TypeError SolidCore.Solidity.TypeCheck.CheckedContract := + SolidCore.Solidity.TypeCheck.CheckedInput.contract + SolidCore.Refinement.Source.VerifyCounterMutant.importedSourceUnit "Counter" + +/-- The mutant's loop: `for (; i < n;) {}` (its `init` is the declaration before it). -/ +def loopM : Stmt := .forLoop .skip cond .skip (.block []) + +/-- The mutant's body. -/ +def bumpBodyM : Stmt := .block [s1, .block [s2, .block [s3, loopM]]] + +/-- The mutant's `bump`. -/ +def bumpFnM : FunctionDef := { bumpFn with body := bumpBodyM } + +def shapeM? : Option (List StorageField × List EventDecl × Option FunctionDef) := + match contractM? with + | .ok c => some (c.core.storageFields, c.core.eventDecls, c.core.findFunctionBySelector? bumpSel) + | .error _ => none + +kernel_rfl shapeM_eq shapeM? (some (vcFields, [], some bumpFnM)) using selector_eq + +theorem shapeM_of {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contractM? = .ok c) : + c.core.storageFields = vcFields ∧ c.core.eventDecls = [] ∧ + c.core.findFunctionBySelector? bumpSel = some bumpFnM := by + have h := shapeM_eq + unfold shapeM? at h + rw [hc] at h + simp only [Option.some.injEq, Prod.mk.injEq] at h + exact h + +theorem contractM_ok : ∃ c, contractM? = .ok c := by + have h := shapeM_eq + unfold shapeM? at h + cases hc : contractM? with + | ok c => exact ⟨c, rfl⟩ + | error _ => rw [hc] at h; simp at h + +end Contracts.VerifyCounter.Mutant diff --git a/Contracts/VerifyCounter/SourceNeg.lean b/Contracts/VerifyCounter/SourceNeg.lean new file mode 100644 index 00000000..24c79cb2 --- /dev/null +++ b/Contracts/VerifyCounter/SourceNeg.lean @@ -0,0 +1,73 @@ +import Contracts.VerifyCounter.SourceLoop + +/-! +# Negative controls of bump's source certificate + +* `growing_rejected`: the certificate of `SourceLoop.certWith` with the measure `i` (read off the + runtime as `rank` reads `n - i`) is refused: its one remaining obligation, that the measure falls + on an iteration, is `i + 1 < i`, which `omega` refutes at once; `fail_if_success` makes this file + build only while that certificate is rejected. The same script with `n - i` is `SourceLoop.cert`. +* `missing_update_never`: the loop with its update `i++` dropped and an empty body, + `for (; i < n;) {}`, from every header state with `i < n`, finishes at **no** fuel + (`evalFor_never`): no ranking certificate exists for it and no fuel ends it. (Dropping only + `i++` and keeping `count++` does end, by `count++`'s checked overflow, with `Panic(0x11)` on a call + whose `require` passed: a revert the specification does not allow; not proved here.) +-/ + +namespace Contracts.VerifyCounter.Source +open SolidCore.Solidity.Source SolidCore.Refinement SolidCore.Refinement.Generic +open SolidCore.Refinement.Generic.Loop + +/-- The measure `i`, read off the runtime: it grows. -/ +def growing (rt : Runtime) : Nat := + match rt.lookupLocal? "i" with + | some (.word v) => v + | _ => 0 + +theorem growing_of {ρ : Val} {E : EraseEnv} {ctx : Context} {rt : Runtime} {i c : Nat} + (h : StmtRel (hval ρ i c) E ctx rt headerS) (hi : i < wordSize) : growing rt = i := by + have := h.expr.locals "i" (.arg 1) rfl + simp only [growing, this, WExpr.eval, hval, List.getD_cons_succ, List.getD_cons_zero, + Nat.mod_eq_of_lt hi] + +theorem growing_rejected : True := by + fail_if_success + have : ∀ ρ E ctx (hc : countOk E) (hf : E.facts = []) (hp : ρ.store 0 + nOf ρ ≤ ρ.store 1), + ForCert 3 E.tbl ctx cond post body (Inv ρ E ctx) growing (Q ρ E ctx) := + fun ρ E ctx hc hf hp => certWith ρ E ctx hc hf hp growing fun i _ _ hin h h' => by + have hn := nOf_lt ρ + rw [growing_of h' (by omega), growing_of h (by omega)] + omega + trivial + +set_option maxHeartbeats 2000000 in +/-- **Without its update the loop finishes at no fuel.** -/ +theorem missing_update_never (ρ : Val) (E : EraseEnv) (ctx : Context) (i : Nat) + (hi : i < nOf ρ) (rt : Runtime) (hrel : StmtRel (hval ρ i (ρ.store 0 + i)) E ctx rt headerS) : + ∀ fuel r, Stmt.evalFor fuel E.tbl ctx rt cond .skip (.block []) ≠ .done (.ok r) := by + have hn := nOf_lt ρ + have hiw : i < wordSize := by omega + refine fun fuel => evalFor_never (fun rt => StmtRel (hval ρ i (ρ.store 0 + i)) E ctx rt headerS) ?_ fuel rt hrel + intro rt h + have hcond : eraseExpr E.fields headerS cond = some ([], .bin .lt (.arg 1) (.arg 0)) := rfl + have hev := eval_eq _ E.fields ctx rt headerS h.expr hcond + refine ⟨1, rt, ?_, by decide, 2, rt.pushScope.popScope, ?_, rt.pushScope.popScope, ?_, ?_⟩ + · have hv : (WExpr.bin .lt (.arg 1) (.arg 0)).eval (hval ρ i (ρ.store 0 + i)) = 1 := by + simp only [WExpr.eval, BinOp.eval, hval, List.getD_cons_succ, List.getD_cons_zero, + Nat.mod_eq_of_lt hiw] + have : i < ρ.args.getD 0 0 % Generic.wordSize := hi + rw [if_pos this] + decide + rw [hev, caught_exprResult] + simp only [List.any_nil, Bool.false_eq_true, ↓reduceIte, hv] + · rw [show (2 : Nat) = 1 + 1 from rfl, eval_block_of (evalList_nil 1 E.tbl ctx rt.pushScope)] + rfl + · rw [Stmt.eval]; rfl + · exact h.pushScope.popScope + +/-- info: 'Contracts.VerifyCounter.Source.missing_update_never' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms missing_update_never + +end Contracts.VerifyCounter.Source + diff --git a/Contracts/VerifyCounter/StageMir.lean b/Contracts/VerifyCounter/StageMir.lean new file mode 100644 index 00000000..cd334340 --- /dev/null +++ b/Contracts/VerifyCounter/StageMir.lean @@ -0,0 +1,119 @@ +import Contracts.VerifyCounter.Bump + +/-! +# bump's exact ends on solar's first lowered MIR + +`Bump.Post` says what bump's spec asks of a successful end. A source stage needs more: the +exact end of every call, so that its observable can be compared with SolidCore's. `PostX` is +that end, on every call of bump with no value and at least one argument word: + +* `count + n` wraps: a revert with `Panic(0x11)`'s data (`panicData`); +* otherwise `count + n > limit`: a revert with `Error("over")`'s data (`overData`); +* otherwise `stop`, with slot 0 holding `count + n` and every other slot as it was. + +It is proved through the same cut point and the same generated invariant (`Inferred.lean`) as +`Bump.stage0_ends`, with the same ranking certificate: only the leaves differ. +-/ + +namespace SolarTV.Milestone.VerifyCounter.Bump + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 +open SolarTV.CutPoint (seg SegEnds) + +/-- `Panic(0x11)`'s revert data as bump's MIR writes it. -/ +def panicData : List Memory.Byte := ((Mem.initial.store 32 17).store 0 0x4e487b71).read 28 36 + +/-- `Error("over")`'s revert data as bump's MIR writes it. -/ +def overData : List Memory.Byte := + ((((Mem.initial.store 32 32).store 64 4).store 96 + 0x6f76657200000000000000000000000000000000000000000000000000000000).store 0 0x8c379a0).read 28 100 + +/-- The exact end of a call of bump. -/ +def PostX (call : Call) (r : Halt × State) : Prop := + BitVec.ofNat 256 call.callvalue = 0 → ¬ BitVec.ofNat 256 call.calldata.size < 36 → + ((State.initial call).storage 0 + calldataWord call 4 < (State.initial call).storage 0 → + r.1 = .revert panicData) ∧ + (¬ (State.initial call).storage 0 + calldataWord call 4 < (State.initial call).storage 0 → + (State.initial call).storage 1 < (State.initial call).storage 0 + calldataWord call 4 → + r.1 = .revert overData) ∧ + (¬ (State.initial call).storage 0 + calldataWord call 4 < (State.initial call).storage 0 → + ¬ (State.initial call).storage 1 < (State.initial call).storage 0 + calldataWord call 4 → + r.1 = .stop ∧ r.2.storage 0 = (State.initial call).storage 0 + calldataWord call 4 ∧ + ∀ k, k ≠ 0 → r.2.storage k = (State.initial call).storage k) + +macro "exact_leaf" : tactic => `(tactic| ( + unfold PostX; dsimp only; intro _ _; (try simp only [EvmRules.Evm.add] at *) + refine ⟨?_, ?_, ?_⟩ <;> intros + all_goals first + | (exfalso; bv_omega) + | (exfalso; sym_omega) + | rfl + | (refine ⟨?_, ?_, ?_⟩ <;> first | exact True.intro | rfl | word_goal | (intro _ _; first | exact True.intro | rfl | word_goal) | bv_omega))) + +macro "xtotal_leaf" : tactic => `(tactic| ( + first + | exact_leaf + | (refine ⟨?_, ?_⟩ + · inv_goal + · first | exact True.intro | rank_goal) + | inv_goal + | (exfalso; bv_omega) + | (exfalso; sym_omega))) + +syntax "xtotal_seg" : tactic +set_option hygiene false in +macro_rules + | `(tactic| xtotal_seg) => `(tactic| ( + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + bump_norm [SegEnds, cut_enter, cut_resume] + repeat' (split_cond <;> bump_norm [SegEnds, cut_enter, cut_resume]) + all_goals xtotal_leaf)) + +set_option maxHeartbeats 4000000 in +theorem xseg0 (o : Oracle) (call : Call) (hsel : IsBump call) : + ∃ k, SegEnds (Inferred.Inv call) (PostX call) (fun _ => True) + (seg (MIR.Lowered.moduleBlock o call stage0) cut k ([], .enter stage0.entry 0 0, fun _ => 0, MIR.Lowered.Module.startState stage0 (State.initial call))) := by + refine ⟨40, ?_⟩ + unfold IsBump at hsel + xtotal_seg + +set_option maxHeartbeats 4000000 in +theorem xseg7 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) + (h : Inferred.at7 call env s) : + ∃ k, SegEnds (Inferred.Inv call) (PostX call) + (fun y => Inferred.rank call y < Inferred.rank call ([], .enter 4 7 1, env, s)) + (seg (MIR.Lowered.moduleBlock o call stage0) cut k ([], .enter 4 7 1, env, s)) := by + refine ⟨40, ?_⟩ + unfold Inferred.at7 at h + repeat obtain ⟨_, h⟩ := h + xtotal_seg + +set_option maxHeartbeats 4000000 in +theorem xseg10 (o : Oracle) (call : Call) (env : MIR.Lowered.Env) (s : State) + (h : Inferred.at10 call env s) : + ∃ k, SegEnds (Inferred.Inv call) (PostX call) + (fun y => Inferred.rank call y < Inferred.rank call ([], .enter 4 10 1, env, s)) + (seg (MIR.Lowered.moduleBlock o call stage0) cut k ([], .enter 4 10 1, env, s)) := by + refine ⟨40, ?_⟩ + unfold Inferred.at10 at h + repeat obtain ⟨_, h⟩ := h + xtotal_seg + +/-- **Every call of bump ends on solar's first lowered MIR in its exact end** (`PostX`), +through the generated invariant and the ranking certificate `n - i`. -/ +theorem xstage0_ends (o : Oracle) (call : Call) (hsel : IsBump call) : + ∃ r, MIR.Lowered.moduleLayer.Ends o stage0 call r ∧ PostX call r := by + obtain ⟨n, r, ran, post⟩ := CutPoint.ends_of_start (Inferred.rank call) (xseg0 o call hsel) (by + rintro x (⟨env, s, rfl, h⟩ | ⟨env, s, rfl, h⟩) + · exact xseg7 o call env s h + · exact xseg10 o call env s h) + refine ⟨r, ⟨n, ?_⟩, post⟩ + change Machine.iterate _ n _ = some r + rw [CutPoint.iterate_eq] + exact ran + +/-- info: 'SolarTV.Milestone.VerifyCounter.Bump.xstage0_ends' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms xstage0_ends + +end SolarTV.Milestone.VerifyCounter.Bump diff --git a/Contracts/VerifyCounter/StageSource.lean b/Contracts/VerifyCounter/StageSource.lean new file mode 100644 index 00000000..f0e62758 --- /dev/null +++ b/Contracts/VerifyCounter/StageSource.lean @@ -0,0 +1,248 @@ +import Contracts.VerifyCounter.Source +import Contracts.VerifyCounter.StageMir +import SolidCore.Refinement.Generic.MirNoLog +import SolidCore.Refinement.Generic.Stage +import SolarTV.Composition + +/-! +# bump's source stage: SolidCore's `Counter` to solar's first lowered MIR + +`mir_eq`: on every call of `bump(n)` (any argument word, no value, any storage), under every +oracle, solar's first lowered MIR `stage0` and SolidCore's runtime (`solidCoreRuntime fuel`, +`Source.lean`) give the **same observable**. Both sides are total on these calls, so this is +equality of results, not inclusion: + +* SolidCore runs the call to its tree's leaf (`Source.runs`, the loop by its ranking + certificate `n - i`); +* `stage0` ends in its exact end (`Bump.xstage0_ends`: the generated header invariant and the + same rank, checked segment by segment), with no logs (`Module.ends_logs`: `stage0` has no + `log` instruction, `stage0_noLog`); +* the three leaves agree: `Panic(0x11)` when `count + n` wraps, `Error("over")` when it + exceeds `limit` (the revert data byte for byte), else success with slot 0 holding + `count + n` and every other slot unchanged. + +`stage` restates it as `Stage (solidCoreRuntime fuel) (mirSem o) c stage0 BumpCall`, and +`stage_back` the converse stage. +-/ + +namespace Contracts.VerifyCounter.Source +open SolidCore.Solidity.Source SolidCore.Refinement SolidCore.Refinement.Generic +open SolidCore.Refinement.Generic.Loop +open SolarTV SolarTV.Machine + +theorem stage0_noLog : SolarTV.Export.Counter.stage0.noLog = true := by decide + +theorem lit_eval_map (ρ : Val) (ns : List Nat) : + (ns.map OByte.lit).map (OByte.eval ρ) = ns.map (· % 256) := by + simp [List.map_map, Function.comp_def, OByte.eval] + +theorem panic_out (ρ : Val) : + (panicBytes 0x11).map (OByte.eval ρ) = + SolarTV.Milestone.VerifyCounter.Bump.panicData.map BitVec.toNat := by + have e : panicBytes 0x11 = ((SolarTV.Milestone.VerifyCounter.Bump.panicData.map BitVec.toNat).map OByte.lit) := by + decide +kernel + rw [e, lit_eval_map, List.map_map] + apply List.map_congr_left + intro b _ + exact Nat.mod_eq_of_lt b.isLt + +theorem over_out (ρ : Val) {bs : List OByte} (h : errorBytes "over" = some bs) : + bs.map (OByte.eval ρ) = SolarTV.Milestone.VerifyCounter.Bump.overData.map BitVec.toNat := by + have e : errorBytes "over" = some ((SolarTV.Milestone.VerifyCounter.Bump.overData.map BitVec.toNat).map OByte.lit) := by + decide +kernel + rw [e, Option.some.injEq] at h + subst h + rw [lit_eval_map, List.map_map] + apply List.map_congr_left + intro b _ + exact Nat.mod_eq_of_lt b.isLt + +/-- The call of `bump(a)` from the storage `σ`. -/ +def bumpCall (σ : List (Nat × Nat)) (a : Nat) : Call := + { calldata := Abi.calldata bumpSel [a], callvalue := 0, storage := σ } + +theorem toNat_ofNat_lt {w n : Nat} (h : n < 2 ^ w) : (BitVec.ofNat w n).toNat = n := by + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt h] + +/-- The call of `bump(a)`: bump's selector, and `a` as its word. -/ +theorem bumpCall_facts (σ : List (Nat × Nat)) (a : Nat) (ha : a < 2 ^ 256) : + SolarTV.Milestone.VerifyCounter.Bump.IsBump (bumpCall σ a) ∧ + calldataWord (bumpCall σ a) 4 = BitVec.ofNat 256 a := by + have hf : CallFacts bumpSel 1 ⟨[a], slotValue σ, solHash, SolidCore.Refinement.Generic.callerWord⟩ (bumpCall σ a) := + callFacts bumpSel (by decide) [a] (by simpa using ha) σ + refine ⟨?_, ?_⟩ + · unfold SolarTV.Milestone.VerifyCounter.Bump.IsBump + rw [hf.selector] + rfl + · apply BitVec.eq_of_toNat_eq + have h4 := hf.args 0 (by decide) (by decide) + rw [toNat_ofNat_lt ha] + simpa [WExpr.eval, Nat.mod_eq_of_lt ha] using h4 + +/-- **bump's end on the first lowered MIR**, on the call of `bump(a)`: it exists, logs nothing, +and is the exact end `PostX` names, read on the call's words. -/ +theorem mir_end (o : Oracle) (σ : List (Nat × Nat)) (a : Nat) (ha : a < 2 ^ 256) : + ∃ r, MIR.Lowered.moduleLayer.Ends o SolarTV.Export.Counter.stage0 (bumpCall σ a) r ∧ + logs r.2 = [] ∧ + (BitVec.ofNat 256 (slotValue σ 0) + BitVec.ofNat 256 a < BitVec.ofNat 256 (slotValue σ 0) → + r.1 = .revert SolarTV.Milestone.VerifyCounter.Bump.panicData) ∧ + (¬ BitVec.ofNat 256 (slotValue σ 0) + BitVec.ofNat 256 a < BitVec.ofNat 256 (slotValue σ 0) → + BitVec.ofNat 256 (slotValue σ 1) < BitVec.ofNat 256 (slotValue σ 0) + BitVec.ofNat 256 a → + r.1 = .revert SolarTV.Milestone.VerifyCounter.Bump.overData) ∧ + (¬ BitVec.ofNat 256 (slotValue σ 0) + BitVec.ofNat 256 a < BitVec.ofNat 256 (slotValue σ 0) → + ¬ BitVec.ofNat 256 (slotValue σ 1) < BitVec.ofNat 256 (slotValue σ 0) + BitVec.ofNat 256 a → + r.1 = .stop ∧ r.2.storage 0 = BitVec.ofNat 256 (slotValue σ 0) + BitVec.ofNat 256 a ∧ + ∀ k, k ≠ 0 → r.2.storage k = (Machine.State.initial (bumpCall σ a)).storage k) := by + obtain ⟨hsel, hn⟩ := bumpCall_facts σ a ha + have hf : CallFacts bumpSel 1 ⟨[a], slotValue σ, solHash, SolidCore.Refinement.Generic.callerWord⟩ (bumpCall σ a) := + callFacts bumpSel (by decide) [a] (by simpa using ha) σ + obtain ⟨r, e, hpost⟩ := SolarTV.Milestone.VerifyCounter.Bump.xstage0_ends o _ hsel + have hsz : ¬ BitVec.ofNat 256 (bumpCall σ a).calldata.size < 36 := by + rw [hf.size]; decide + have hp := hpost rfl hsz + have hs0 : (Machine.State.initial (bumpCall σ a)).storage 0 = BitVec.ofNat 256 (slotValue σ 0) := rfl + have hs1 : (Machine.State.initial (bumpCall σ a)).storage 1 = BitVec.ofNat 256 (slotValue σ 1) := rfl + rw [hn, hs0, hs1] at hp + exact ⟨r, e, MIR.Lowered.Module.ends_logs stage0_noLog e, hp⟩ + +theorem mir_run {o : Oracle} {σ : List (Nat × Nat)} {a : Nat} {r : Halt × Machine.State} + (e : MIR.Lowered.moduleLayer.Ends o SolarTV.Export.Counter.stage0 (bumpCall σ a) r) : + (SolarTV.mirSem o).run SolarTV.Export.Counter.stage0 (bumpCall σ a) = + some (observe (bumpCall σ a) r.2 r.1) := by + show (MIR.Lowered.moduleLayer.result o _ _).map _ = _ + rw [MIR.Lowered.moduleLayer.result_of_ends e] + rfl + +set_option maxHeartbeats 1000000 in +/-- **bump's first lowered MIR shows SolidCore's observable**, on every call of `bump`, under +every oracle. -/ +theorem mir_eq (o : Oracle) {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) + (σ : List (Nat × Nat)) (a : Nat) (ha : a < 2 ^ 256) : + (SolarTV.mirSem o).run SolarTV.Export.Counter.stage0 (bumpCall σ a) = + runtimeRun fuel c (bumpCall σ a) := by + obtain ⟨T, hT⟩ := tree_ok + rw [show runtimeRun fuel c (bumpCall σ a) = _ from runs hc hT σ a ha] + obtain ⟨r, e, hl, hp1, hp2, hp3⟩ := mir_end o σ a ha + rw [mir_run e] + congr 1 + have h0lt : slotValue σ 0 < 2 ^ 256 := slotValue_lt σ 0 + have h1lt : slotValue σ 1 < 2 ^ 256 := slotValue_lt σ 1 + have c1 : (BitVec.ofNat 256 (slotValue σ 0) + BitVec.ofNat 256 a < BitVec.ofNat 256 (slotValue σ 0)) ↔ + (slotValue σ 0 + a) % 2 ^ 256 < slotValue σ 0 := by + rw [BitVec.lt_def, BitVec.toNat_add, toNat_ofNat_lt h0lt, toNat_ofNat_lt ha] + have c2 : (BitVec.ofNat 256 (slotValue σ 1) < BitVec.ofNat 256 (slotValue σ 0) + BitVec.ofNat 256 a) ↔ + slotValue σ 1 < (slotValue σ 0 + a) % 2 ^ 256 := by + rw [BitVec.lt_def, BitVec.toNat_add, toNat_ofNat_lt h0lt, toNat_ofNat_lt ha, toNat_ofNat_lt h1lt] + -- the tree's leaf + set ρ : Val := ⟨[a], slotValue σ, solHash, SolidCore.Refinement.Generic.callerWord⟩ with hρ + obtain ⟨T', hT', hTe⟩ := brTree_eval bumpFn (argFacts [256] 0) ρ bumpBr T hT + rw [← hTe] + have hna : nOf ρ = a := by + simp only [nOf, WExpr.eval, hρ, List.getD_cons_zero]; exact Nat.mod_eq_of_lt ha + have eovf : ovf.eval ρ = if (slotValue σ 0 + a) % 2 ^ 256 < slotValue σ 0 then 1 else 0 := by + simp only [ovf, WExpr.eval, BinOp.eval, hρ, List.getD_cons_zero, Nat.mod_eq_of_lt h0lt, + Nat.mod_eq_of_lt ha, Nat.mod_mod] + split <;> rfl + have ele : le.eval ρ = if slotValue σ 1 < (slotValue σ 0 + a) % 2 ^ 256 then 0 else 1 := by + simp only [le, WExpr.eval, BinOp.eval, UnOp.eval, hρ, List.getD_cons_zero, Nat.mod_eq_of_lt h0lt, + Nat.mod_eq_of_lt h1lt, Nat.mod_eq_of_lt ha, Nat.mod_mod] + split <;> rfl + obtain ⟨M, hM⟩ : ∃ M, (slotValue σ 0 + a) % 2 ^ 256 = M := ⟨_, rfl⟩ + rw [hM] at eovf ele c1 c2 + obtain ⟨h, st⟩ := r + unfold bumpBr at hT' + rw [guards_eval] at hT' + by_cases hg : [ovf].any (fun g => g.eval ρ != 0) = true + · -- count + n wraps: Panic(0x11) + rw [if_pos hg] at hT' + have hw : M < slotValue σ 0 := by + by_contra hw + simp [eovf, hw] at hg + have hh : h = .revert SolarTV.Milestone.VerifyCounter.Bump.panicData := hp1 (c1.mpr hw) + subst hh + simp only [leafTree, Option.some.injEq] at hT' + subst hT' + simp only [observe, Tree.eval, Res.obs, Bool.false_eq_true, ↓reduceIte, panic_out] + rfl + rw [if_neg hg] at hT' + have hw : ¬ M < slotValue σ 0 := by + intro hw + exact hg (by simp [eovf, hw]) + simp only [Br.eval] at hT' + by_cases hv : le.eval ρ = 0 + · -- count + n exceeds limit: Error("over") + rw [if_pos hv] at hT' + have hgt : slotValue σ 1 < M := by + by_contra hgt + simp [ele, hgt] at hv + have hh : h = .revert SolarTV.Milestone.VerifyCounter.Bump.overData := + hp2 (fun h' => hw (c1.mp h')) (c2.mpr hgt) + subst hh + simp only [leafTree, Option.map_eq_some_iff] at hT' + obtain ⟨bs, hbs, rfl⟩ := hT' + simp only [observe, Tree.eval, Res.obs, Bool.false_eq_true, ↓reduceIte, over_out ρ hbs] + rfl + rw [if_neg hv] at hT' + have hle : ¬ slotValue σ 1 < M := by + intro hgt + exact hv (by simp [ele, hgt]) + obtain ⟨hstop, hst0, hstk⟩ := hp3 (fun h' => hw (c1.mp h')) (fun h' => hle (c2.mp h')) + simp only at hstop hst0 hstk hl + subst hstop + have hT2 : T' = .halt true [] [(.lit 0, .bin .add (.init 0) (.arg 0))] [] := by + simp [leafTree, bumpFn, SF, retsOk] at hT' + first | exact hT'.symm | exact hT' + subst hT2 + simp only [observe, Tree.eval, Res.obs, ↓reduceIte, List.map_nil, hl] + congr 1 + funext k + simp only [storageOf, Writes.store, WExpr.eval, BinOp.eval, hρ, List.getD_cons_zero] + by_cases hk : k % 2 ^ 256 = 0 + · have hk' : BitVec.ofNat 256 k = 0 := by + apply BitVec.eq_of_toNat_eq; rw [BitVec.toNat_ofNat, hk]; rfl + rw [hk', hst0, BitVec.toNat_add, toNat_ofNat_lt h0lt, toNat_ofNat_lt ha, if_pos (by rw [hk]; rfl)] + rw [Nat.mod_eq_of_lt h0lt, Nat.mod_eq_of_lt ha, Nat.mod_mod] + · have hk' : BitVec.ofNat 256 k ≠ 0 := by + intro h0; apply hk + have := congrArg BitVec.toNat h0 + rwa [BitVec.toNat_ofNat] at this + rw [hstk _ hk', if_neg (by rw [Nat.zero_mod]; exact fun h => hk h.symm)] + show (BitVec.ofNat 256 (slotValue σ (BitVec.ofNat 256 k).toNat)).toNat = slotValue σ k + rw [toNat_ofNat_lt (slotValue_lt σ _), BitVec.toNat_ofNat] + exact slotValue_mod σ k + +/-- What a call of `bump` can show in SolidCore: success, `Panic(0x11)`'s data or +`Error("over")`'s data, never another revert. -/ +theorem result_kinds (o : Oracle) {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) + (σ : List (Nat × Nat)) (a : Nat) (ha : a < 2 ^ 256) {obs : Observable} + (h : runtimeRun fuel c (bumpCall σ a) = some obs) : + obs.success = true ∨ obs.output = SolarTV.Milestone.VerifyCounter.Bump.panicData.map BitVec.toNat ∨ + obs.output = SolarTV.Milestone.VerifyCounter.Bump.overData.map BitVec.toNat := by + rw [← mir_eq o hc σ a ha] at h + obtain ⟨r, e, -, hp1, hp2, hp3⟩ := mir_end o σ a ha + rw [mir_run e, Option.some.injEq] at h + subst h + obtain ⟨hh, st⟩ := r + by_cases w : BitVec.ofNat 256 (slotValue σ 0) + BitVec.ofNat 256 a < BitVec.ofNat 256 (slotValue σ 0) + · have := hp1 w; simp only at this; subst this; exact Or.inr (Or.inl rfl) + by_cases v : BitVec.ofNat 256 (slotValue σ 1) < BitVec.ofNat 256 (slotValue σ 0) + BitVec.ofNat 256 a + · have := hp2 w v; simp only at this; subst this; exact Or.inr (Or.inr rfl) + · have := (hp3 w v).1; simp only at this; subst this; exact Or.inl rfl + +/-- **The source stage of bump**, under every oracle. -/ +theorem stage (o : Oracle) {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCoreRuntime fuel) (SolarTV.mirSem o) c SolarTV.Export.Counter.stage0 BumpCall := by + rintro _ ⟨σ, a, ha, rfl⟩ obs h + exact (mir_eq o hc σ a ha).trans h + +/-- The converse stage: every result of `stage0` on a call of `bump` is SolidCore's. -/ +theorem stage_back (o : Oracle) {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (SolarTV.mirSem o) (solidCoreRuntime fuel) SolarTV.Export.Counter.stage0 c BumpCall := by + rintro _ ⟨σ, a, ha, rfl⟩ obs h + exact (mir_eq o hc σ a ha).symm.trans h + +/-- info: 'Contracts.VerifyCounter.Source.mir_eq' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms mir_eq + +end Contracts.VerifyCounter.Source diff --git a/Contracts/VerifyCounter/Total.lean b/Contracts/VerifyCounter/Total.lean new file mode 100644 index 00000000..ba4c64a3 --- /dev/null +++ b/Contracts/VerifyCounter/Total.lean @@ -0,0 +1,53 @@ +import Contracts.VerifyCounter.BumpTotal +import verify_counter.Proofs.Execution +import verify_counter.Proofs.Stages + +/-! +# bump: termination, spec and the exact bytecode in one statement + +`bump_total` puts together, for every call of `bump(n)` and every oracle the assembly +certificate admits: + +* termination with a bound from the ranking certificate: the first lowered MIR ends within + `(n + 2) * 40` blocks (`Bump.stage0_ends_within`, the generic checker + `CutPoint.ends_within_start`), in an end meeting bump's spec `Post`; +* the final EVM IR ends too, in an end meeting `Post`, through the backend stages read forwards + (`verify_counter_certified`, cut-point simulations, so the loop's iterations correspond); +* the exact bytecode, at every gas: each of its results is the MIR's, which exists, or a failure + that leaves storage and logs as they were (`verify_counter_bytecode`, `checkL`). + +What it does not say: that some gas makes the bytecode succeed. Running out of gas is the failure +branch of the last conjunct; a proved gas bound needs a forward per-block gas lemma of the +assembly checker, which no checker has yet (see `CutPoint.gas_ends` for the composition it would +feed). +-/ + +namespace SolarTV.Milestone.VerifyCounter.Bump + +open Machine SolarTV.Export.Counter SolarTV.Milestone.W1 + +theorem bump_total (o : Oracle) + (ho : cert.env = true → SolidCore.Refinement.Solar.Assemble.OracleOk o) + (he : cert.reads = true → SolidCore.Refinement.Solar.Assemble.EnvOk o) + (call : Call) (hsel : IsBump call) : + (∃ r, Machine.iterate (MIR.Lowered.moduleBlock o call stage0) + (((calldataWord call 4).toNat + 2) * 40) (start call) = some r ∧ Post call r) ∧ + (∃ r, EVM.Program.layer.Ends o evm11 call r ∧ Post call r) ∧ + ((mirSem o).run stage0 call).isSome ∧ + ∀ gas, SolidCore.Refinement.Final.Within (mirSem o) (SolidCore.Refinement.Final.ethLibWith gas) + stage0 code (· = call) := by + obtain ⟨r, ran, post⟩ := stage0_ends_within o call hsel + refine ⟨⟨r, ran, post⟩, ends_of_certified o (verify_counter_certified o) call hsel, ?_, fun gas => by + intro c _ obs h + exact verify_counter_bytecode o ho he gas c (show anyCall c from trivial) obs h⟩ + have e : MIR.Lowered.moduleLayer.Ends o stage0 call r := + ⟨_, by change Machine.iterate _ _ _ = some r; exact ran⟩ + change ((MIR.Lowered.moduleLayer.result o stage0 call).map _).isSome = true + rw [MIR.Lowered.moduleLayer.result_of_ends e] + rfl + +/-- info: 'SolarTV.Milestone.VerifyCounter.Bump.bump_total' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms bump_total + +end SolarTV.Milestone.VerifyCounter.Bump diff --git a/Loom.lean b/Loom.lean new file mode 100644 index 00000000..48e759e0 --- /dev/null +++ b/Loom.lean @@ -0,0 +1,12 @@ +import Loom.MonadUtil +import Loom.SpecMonad +import Loom.MonadAlgebras.Defs +import Loom.MonadAlgebras.Instances.Basic +import Loom.MonadAlgebras.Instances.StateT +import Loom.MonadAlgebras.Instances.ExceptT +import Loom.MonadAlgebras.Instances.ExceptTErr +import Loom.MonadAlgebras.Instances.ReaderT +import Loom.MonadAlgebras.Instances.Gen +import Loom.MonadAlgebras.WP.Basic +import Loom.MonadAlgebras.WP.Liberal +import Loom.MonadAlgebras.WP.Variant diff --git a/Loom/LICENSE b/Loom/LICENSE new file mode 100644 index 00000000..d5728852 --- /dev/null +++ b/Loom/LICENSE @@ -0,0 +1,191 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2024-2025 authors and contributors (see the file AUTHORS) + and their institutional affiliations. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Loom/MonadAlgebras/Defs.lean b/Loom/MonadAlgebras/Defs.lean new file mode 100644 index 00000000..cf5491a3 --- /dev/null +++ b/Loom/MonadAlgebras/Defs.lean @@ -0,0 +1,248 @@ +import Mathlib.Order.CompleteLattice.Basic + +import Loom.MonadUtil +import Loom.SpecMonad + +universe u v w + +/- Prop embedding into PartialOrder -/ + +open Classical in +noncomputable def LE.pure {l : Type u} [inst: LE l] [OrderTop l] [OrderBot l] : Prop -> l := fun p => + if p then ⊤ else ⊥ + +macro "⌜" p:term "⌝" : term => `(LE.pure $p) + +@[app_unexpander LE.pure] def unexpandPure : Lean.PrettyPrinter.Unexpander + | `($(_) $p:term) => `(⌜$p:term⌝) + | _ => throw () + +@[simp] +lemma trueE (l : Type v) [inst: LE l] [OrderTop l] [OrderBot l] : ⌜True⌝ = (⊤ : l) := by + simp [LE.pure] + +@[simp] +lemma falseE (l : Type v) [inst: LE l] [OrderTop l] [OrderBot l] : ⌜False⌝ = (⊥ : l) := by + simp [LE.pure] + +open Classical in +lemma LE.pure_imp {l : Type u} [inst: LE l] [OrderTop l] [OrderBot l] + (p₁ p₂ : Prop) : (p₁ -> p₂) -> ⌜p₁⌝ <= (⌜p₂⌝ : l) := by + simp [LE.pure]; split <;> aesop + +@[simp] +lemma LE.pure_intro {l : Type u} [inst: LE l] [OrderTop l] [OrderBot l] + (p : Prop) (h : l) : (⌜p⌝ <= h) = (p -> ⊤ <= h) := by + simp [LE.pure]; split <;> aesop + +@[simp] +lemma pure_intro_l {l : Type u} [CompleteLattice l] (x y : l) : + (x ⊓ ⌜ p ⌝ <= y) = (p -> x <= y) := by + by_cases h : p <;> simp [h, trueE, falseE] + +@[simp] +lemma pure_intro_r {l : Type u} [CompleteLattice l] (x y : l) : + (⌜ p ⌝ ⊓ x <= y) = (p -> x <= y) := by + by_cases h : p <;> simp [h, trueE, falseE] + +variable (m : Type v -> Type u) + +/- Monad Algebra typeclass for a Monad m and an assertion language l -/ +class MAlg [Monad m] (l : outParam (Type v)) where + μ : m l -> l + pure : ∀ l, μ (pure l) = l + bind : ∀ {α : Type v} (x : m α) (f g : α -> m l), + μ ∘ f = μ ∘ g -> + μ (x >>= f) = μ (x >>= g) + +abbrev MAlg.lift {m : Type u -> Type v} {l : Type u} [Monad m] [MAlg m l] : + {α : Type u} -> m α -> Cont l α := fun x f => μ $ f <$> x + +instance (l : Type u) {m : Type u -> Type v} [Monad m] [MAlg m l] : MonadLiftT m (Cont l) where + monadLift := MAlg.lift + +instance EffectObservationOfMAlg (l : Type u) {m : Type u -> Type v} [Monad m] [LawfulMonad m] [MAlg m l] : LawfulMonadLiftT m (Cont l) where + monadLift_pure := by + intro α x; simp [monadLift, pure]; unfold MAlg.lift; simp [map_pure, MAlg.pure] + monadLift_bind := by + intros α β x f; simp [monadLift, bind]; unfold MAlg.lift; ext g + rw (config := { occs := .pos [2] }) [map_eq_pure_bind] + simp only [map_bind]; apply MAlg.bind + ext; simp [MAlg.pure] + +/- Ordered Monad Algebra typeclass for a Monad m and an assertion language l -/ +class MAlgOrdered (l : outParam (Type v)) [Monad m] [CompleteLattice l] where + μ : m l -> l + μ_ord_pure : ∀ l, μ (pure l) = l + μ_ord_bind {α : Type v} : + ∀ (f g : α -> m l), μ ∘ f ≤ μ ∘ g -> + ∀ x : m α, μ (x >>= f) ≤ μ (x >>= g) + +/- Deriving Monad Algebra instance from an Ordered Monad Algebra instance -/ +instance OfMAlgPartialOrdered {m : Type u -> Type v} {l : Type u} [Monad m] [CompleteLattice l] [mprop : MAlgOrdered m l] : MAlg m l where + μ := MAlgOrdered.μ + pure := MAlgOrdered.μ_ord_pure + bind := by intros; apply PartialOrder.le_antisymm + <;> apply MAlgOrdered.μ_ord_bind + <;> simp_all only [le_refl] + +lemma MAlgOrdered.bind {α : Type u} {m} {l : Type u} [Monad m] [CompleteLattice l] [MAlgOrdered m l] : + ∀ (x : m α) (f g : α -> m l), μ ∘ f = μ ∘ g -> + μ (x >>= f) = μ (x >>= g) := MAlg.bind + +lemma Cont.monotone_lift {l : Type u} {m : Type u -> Type v} [Monad m] [LawfulMonad m] [CompleteLattice l] [MAlgOrdered m l] : + ∀ {α : Type u} (x : m α), MAlg.lift x |>.monotone := by + unfold Cont.monotone; intros; simp [MAlg.lift]; rw [map_eq_pure_bind, map_eq_pure_bind] + apply MAlgOrdered.μ_ord_bind; intro; simp [MAlgOrdered.μ_ord_pure, *] + +@[simp] +lemma MAlg.μ_eq {m l} [Monad m] [CompleteLattice l] [MAlgOrdered m l] : MAlg.μ (m := m) = MAlgOrdered.μ (m := m) := by rfl + +lemma MAlg.monadLift_bind {α β} {l : Type u} {m : Type u -> Type v} [Monad m] [LawfulMonad m] [CompleteLattice l] [MAlgOrdered m l] + (x : m α) (f g : α -> Cont l β) : + f <= g -> + (lift x >>= f) ≤ (lift x >>= g) := by + intro fLg h; simp [Bind.bind] + apply Cont.monotone_lift; intros h; apply fLg + +/-- Class for deterministic monadic algebras -/ +class MAlgDet (l : outParam (Type v)) [Monad m] [CompleteLattice l] [MAlgOrdered m l] where + /-- Demonic determinism -/ + demonic {α ι : Type v} (c : m α) (p : ι -> α -> l) [Nonempty ι] : + ⨅ i, MAlg.lift c (p i) ≤ MAlg.lift c (fun x => ⨅ i, p i x) + /-- Angelic determinism -/ + angelic {α ι : Type v} (c : m α) (p : ι -> α -> l) [Nonempty ι] : + ⨆ i, MAlg.lift c (p i) ≥ MAlg.lift c (fun x => ⨆ i, p i x) + +/-- Class for partial correctness monadic algebras -/ +class MAlgPartial (m : Type u -> Type v) [Monad m] [∀ α, Lean.Order.CCPO (m α)] + [CompleteLattice l] [MAlgOrdered m l] where + csup_lift {α : Type u} (xc : Set (m α)) (post : α -> l) (hc : Lean.Order.chain xc) : + ⨅ x ∈ xc, MAlg.lift x post <= MAlg.lift (Lean.Order.CCPO.csup hc) post + +/-- Class for total correctness monadic algebras -/ +class MAlgTotal (m : Type u -> Type v) [Monad m] [∀ α, Lean.Order.CCPO (m α)] + [CompleteLattice l] [MAlgOrdered m l] where + bot_lift {α : Type u} (post : α -> l) : + MAlg.lift (Lean.Order.bot : m α) post <= ⊥ + +class NoFailure (m : Type u -> Type v) [Monad m] [CompleteLattice l] [MAlgOrdered m l] where + noFailure {α : Type u} (c : m α) : + MAlg.lift c (fun _ => ⊤) = ⊤ + +class LogicLiftT (l : (Type u)) ( k : Type u) [CompleteLattice l] [CompleteLattice k] where + [lift : MonadLiftT (Cont l) (Cont k)] + lift_top {α : Type u} : + monadLift (m := Cont l) (n := Cont k) (fun (_ : α -> l) => ⊤) = ⊤ + lift_bot {α : Type u} : + monadLift (m := Cont l) (n := Cont k) (fun (_ : α -> l) => ⊥) = ⊥ + +class LogicLift (l : outParam (Type u)) ( k : Type u) [CompleteLattice l] [CompleteLattice k] where + [lift : MonadLift (Cont l) (Cont k)] + lift_top {α : Type u} : + monadLift (m := Cont l) (n := Cont k) (fun (_ : α -> l) => ⊤) = ⊤ + lift_bot {α : Type u} : + monadLift (m := Cont l) (n := Cont k) (fun (_ : α -> l) => ⊥) = ⊥ + +def LogicLift.refl [CompleteLattice l] : LogicLift l l where + lift := by exact ⟨id⟩ + lift_top := rfl + lift_bot := rfl + + +instance [CompleteLattice l] [CompleteLattice k] [LogicLiftT l k] : MonadLiftT (Cont l) (Cont k) where + monadLift := LogicLiftT.lift.monadLift + +instance [CompleteLattice l] [CompleteLattice k] [LogicLift l k] : MonadLift (Cont l) (Cont k) where + monadLift := LogicLift.lift.monadLift + + +@[simp] +lemma lift_cont_eq {l σ : Type u} [CompleteLattice l] [CompleteLattice σ] (c : Cont l α) : + liftM (m := Cont l) (n := Cont (σ -> l)) c = fun post s => c (post · s) := by + rfl + +instance {l} [CompleteLattice l] : LogicLiftT l l where + lift_top := by simp [monadLift]; intros; rfl + lift_bot := by simp [monadLift]; intros; rfl + +instance [CompleteLattice l] [CompleteLattice k] [CompleteLattice p] [linst₁ : LogicLiftT l k] [linst₂ : LogicLift k p] : LogicLiftT l p where + lift_top {α} := by + show monadLift (m := Cont k) (n := Cont p) + (monadLift (m := Cont l) (n := Cont k) (fun (_ : α -> l) => ⊤)) = ⊤ + rw [linst₁.lift_top] + exact linst₂.lift_top + lift_bot {α} := by + show monadLift (m := Cont k) (n := Cont p) + (monadLift (m := Cont l) (n := Cont k) (fun (_ : α -> l) => ⊥)) = ⊥ + rw [linst₁.lift_bot] + exact linst₂.lift_bot + + +instance {l σ : Type u} [CompleteLattice l] : LogicLift l (σ -> l) where + lift_top := by simp [monadLift, MonadLift.monadLift]; intros; rfl + lift_bot := by simp [monadLift, MonadLift.monadLift]; intros; rfl + + +/- Monad Transformer Algebra typeclass -/ +class MAlgLift + (m : semiOutParam (Type u -> Type v)) (l : semiOutParam (Type u)) [Monad m] [CompleteLattice l] [MAlgOrdered m l] + (n : (Type u -> Type w)) (k : outParam (Type u)) [Monad n] [CompleteLattice k] [MAlgOrdered n k] + [MonadLiftT m n] + where + [cl : LogicLift l k] + μ_lift (x : m α) : MAlg.lift (liftM (n := n) x) f = liftM (n := Cont k) (MAlg.lift x) f + +def MAlgLift.mk_rep (m : semiOutParam (Type u -> Type v)) (l : semiOutParam (Type u)) [Monad m] [CompleteLattice l] [MAlgOrdered m l] + (n : (Type u -> Type w)) (σ : Type u) [LawfulMonad m] [Monad n] [LawfulMonad n] [CompleteLattice k] [MAlgOrdered n (σ -> l)] + [MonadLiftT m n] [LawfulMonadLiftT m n] + (μ_lift : ∀ (x : m (σ → l)), + MAlgOrdered.μ (liftM (n := n) x) = + fun s => MAlgOrdered.μ ((· s) <$> x)) : MAlgLift m l n (σ → l) := by + constructor; intro α f x + simp [MAlg.lift]; rw [←lift_map] + rw [μ_lift (f <$> x)] + simp [Functor.map_map]; rfl + +def MAlgLift.mk_id (m : semiOutParam (Type u -> Type v)) (l : semiOutParam (Type u)) [Monad m] [CompleteLattice l] [MAlgOrdered m l] + (n : (Type u -> Type w)) [LawfulMonad m] [Monad n] [LawfulMonad n] [CompleteLattice k] [MAlgOrdered n l] + [MonadLiftT m n] [LawfulMonadLiftT m n] + (μ_lift : ∀ (x : m l), + MAlgOrdered.μ (liftM (n := n) x) = + MAlgOrdered.μ x) : MAlgLift m l n l := by + let cl := LogicLift.refl (l := l) + constructor; intro α f x + simp [MAlg.lift]; rw [<-lift_map]; apply μ_lift + +class MAlgLiftT + (m : (Type u -> Type v)) (l : (Type u)) [Monad m] [CompleteLattice l] [MAlgOrdered m l] + (n : (Type u -> Type w)) (k : outParam (Type u)) [Monad n] [CompleteLattice k] [MAlgOrdered n k] + [MonadLiftT m n] + where + [cl : LogicLiftT l k] + μ_lift (x : m α) : MAlg.lift (liftM (n := n) x) f = liftM (n := Cont k) (MAlg.lift x) f + + +instance MAlgLiftTRefl [Monad m] [CompleteLattice l] [LawfulMonad m] [MAlgOrdered m l] : + MAlgLiftT m l m l where + μ_lift := by simp + +instance MAlgLiftTTrans + [Monad m] [CompleteLattice l] [LawfulMonad m] [MAlgOrdered m l] + [Monad n] [CompleteLattice k] [LawfulMonad n] [MAlgOrdered n k] [MonadLiftT m n] + [Monad p] [CompleteLattice q] [LawfulMonad p] [MAlgOrdered p q] [MonadLift n p] + [inst': MAlgLiftT m l n k] [inst: MAlgLift n k p q] : + MAlgLiftT m l p q where + cl := by + let cl := inst.cl + let cl' := inst'.cl + refine instLogicLiftTOfLogicLift + μ_lift := by + intro α f x + simp only [liftM] + erw [inst.μ_lift] + letI := inst'.cl + have h : MAlg.lift (liftM (n := n) x) = liftM (n := Cont k) (MAlg.lift x) := + funext fun _ => inst'.μ_lift x + simp only [liftM] at h + erw [h]; rfl diff --git a/Loom/MonadAlgebras/Instances/Basic.lean b/Loom/MonadAlgebras/Instances/Basic.lean new file mode 100644 index 00000000..25af5d15 --- /dev/null +++ b/Loom/MonadAlgebras/Instances/Basic.lean @@ -0,0 +1,123 @@ +import Loom.MonadAlgebras.Defs +universe u v w + +instance : MAlgOrdered Id Prop where + μ := id + μ_ord_pure := by simp [pure] + μ_ord_bind := by solve_by_elim + +instance : MAlgDet Id Prop where + demonic := by + intros α c p q; + simp [MAlg.lift, MAlg.μ, MAlgOrdered.μ] + solve_by_elim + angelic := by + intros α c p q; + simp [MAlg.lift, MAlg.μ, MAlgOrdered.μ] + solve_by_elim + +inductive DivM (α : Type u) where + | res (x : α) + | div + +def DivM.run {α : Type u} [Inhabited α] : DivM α -> α + | DivM.res x => x + | DivM.div => default + +instance : Monad DivM where + pure := DivM.res + bind := fun x y => match x with + | DivM.res x => y x + | DivM.div => DivM.div + +class CCPOBot (m : Type u -> Type v) where + compBot {α} : m α + +class CCPOBotLawful (m : Type u -> Type v) [∀ α, Lean.Order.CCPO (m α)] [CCPOBot m] where + prop {α} : CCPOBot.compBot (m := m) (α := α) = Lean.Order.bot + +instance : LawfulMonad DivM := by + refine LawfulMonad.mk' _ ?_ ?_ ?_ + { introv; cases x <;> rfl } + { introv; rfl } + introv; cases x <;> rfl + +noncomputable instance : Lean.Order.CCPO (DivM α) := inferInstanceAs (Lean.Order.CCPO (Lean.Order.FlatOrder .div)) +/-- solidity-lean (Lean 4.35): the supremum of a chain of `DivM` is the flat order's. -/ +theorem DivM.csup_eq {α : Type u} (c : DivM α → Prop) (hc : Lean.Order.chain c) : + Lean.Order.CCPO.csup hc = Lean.Order.flat_csup (b := (DivM.div : DivM α)) c := + (Lean.Order.flat_csup_eq (b := (DivM.div : DivM α)) c hc).symm + +instance : CCPOBot DivM where + compBot := .div + +instance : CCPOBotLawful DivM where + prop {α} := by + show (DivM.div : DivM α) = Lean.Order.CCPO.csup (Lean.Order.chain_empty _) + rw [DivM.csup_eq] + simp [Lean.Order.flat_csup, Lean.Order.empty_chain]; rfl + +instance : Lean.Order.MonoBind DivM where + bind_mono_left := by + rintro _ _ (_|_) _ _ (_|_) <;> solve_by_elim + bind_mono_right := by + rintro _ _ (_|_) <;> solve_by_elim + +namespace PartialCorrectness + + +scoped instance : MAlgOrdered DivM Prop where + μ := fun x => match x with + | .res x => x + | .div => ⊤ + μ_ord_pure := by intro; rfl + μ_ord_bind {α} f g := by + rintro h (_|_) + · exact h _ + · exact le_refl _ + +scoped instance : MAlgDet DivM Prop where + demonic := by + rintro _ _ (_|_) <;> simp [MAlg.lift, MAlgOrdered.μ, Functor.map] + angelic := by + rintro _ _ (_|_) <;> simp [MAlg.lift, MAlgOrdered.μ, Functor.map] + +instance : MAlgPartial DivM where + csup_lift {α} chain := by + intro post hchain + erw [DivM.csup_eq] + simp only [Lean.Order.flat_csup] + split_ifs with ch + · exact iInf₂_le _ (Classical.choose_spec ch).1 + · exact fun _ => trivial + +instance : NoFailure DivM where + noFailure := by + rintro _ (_|_) <;> simp [MAlg.lift, MAlgOrdered.μ, Functor.map] + +end PartialCorrectness + +namespace TotalCorrectness + +scoped instance : MAlgOrdered DivM Prop where + μ := fun x => match x with + | .res x => ⌜x⌝ + | .div => ⊥ + μ_ord_pure := by intro l; show ⌜l⌝ = l; simp [LE.pure] + μ_ord_bind {α} f g := by + rintro h (_|_) + · exact h _ + · exact le_refl _ + +scoped instance : MAlgDet DivM Prop where + angelic := by + rintro _ _ (_|_) <;> simp [MAlg.lift, MAlgOrdered.μ, Functor.map, LE.pure] + demonic := by + rintro _ _ (_|_) <;> simp [MAlg.lift, MAlgOrdered.μ, Functor.map, LE.pure] + +instance : MAlgTotal DivM where + bot_lift {α} post := by + rw [← CCPOBotLawful.prop (m := DivM)] + exact fun h => h + +end TotalCorrectness diff --git a/Loom/MonadAlgebras/Instances/ExceptT.lean b/Loom/MonadAlgebras/Instances/ExceptT.lean new file mode 100644 index 00000000..7ca79332 --- /dev/null +++ b/Loom/MonadAlgebras/Instances/ExceptT.lean @@ -0,0 +1,150 @@ +import Loom.MonadAlgebras.Defs +import Loom.MonadAlgebras.Instances.Basic + +abbrev Except.getD {ε α} (default : ε -> α) : Except ε α -> α + | Except.ok p => p + | Except.error e => default e + +abbrev Except.bind' {m : Type u -> Type v} {ε α β} [Monad m] : Except ε α -> (α -> ExceptT ε m β) -> ExceptT ε m β := + fun x f => bind (m := ExceptT ε m) (pure (f := m) x) f + +lemma Except.bind'_bind {m : Type u -> Type v} {ε α β} [Monad m] [LawfulMonad m] (i : m (Except ε α)) (f : α -> ExceptT ε m β) : + (i >>= fun a => Except.bind' a f) = bind (m := ExceptT ε m) i f := by + simp [Except.bind', bind, ExceptT.bind]; rfl + +/- Ordered Monad Algebra instance for ExceptT -/ +noncomputable +def MAlgExcept (ε : Type u) (df : ε -> Prop) (l : Type u) (m : Type u -> Type v) + [CompleteLattice l] + [Monad m] [LawfulMonad m] [inst: MAlgOrdered m l] : MAlgOrdered (ExceptT ε m) l where + μ := fun e => inst.μ $ Except.getD (⌜df ·⌝) <$> e + μ_ord_pure := by + intro l + show inst.μ (Except.getD (⌜df ·⌝) <$> (pure (Except.ok l) : m _)) = l + rw [map_pure]; exact MAlgOrdered.μ_ord_pure _ + μ_ord_bind := by + intro α f g le x + have leM := inst.μ_ord_bind (α := Except ε α) + (fun x => Except.getD (⌜df ·⌝) <$> Except.bind' x f) + (fun x => Except.getD (⌜df ·⌝) <$> Except.bind' x g) ?_ x + · simp only [← map_bind, Except.bind'_bind] at leM; exact leM + · rintro (e | p) + · show inst.μ (Except.getD (⌜df ·⌝) <$> (ExceptT.mk (pure (Except.error e) >>= ExceptT.bindCont f) : m _)) ≤ + inst.μ (Except.getD (⌜df ·⌝) <$> (ExceptT.mk (pure (Except.error e) >>= ExceptT.bindCont g) : m _)) + simp only [ExceptT.mk, pure_bind, ExceptT.bindCont]; exact le_refl _ + · show inst.μ (Except.getD (⌜df ·⌝) <$> (ExceptT.mk (pure (Except.ok p) >>= ExceptT.bindCont f) : m _)) ≤ + inst.μ (Except.getD (⌜df ·⌝) <$> (ExceptT.mk (pure (Except.ok p) >>= ExceptT.bindCont g) : m _)) + simp only [ExceptT.mk, pure_bind, ExceptT.bindCont]; exact le p + +section ExeceptHandler + +variable (ε : Type u) (l : Type u) (m : Type u -> Type v) [Monad m] [LawfulMonad m] + +class IsHandler {ε : Type*} (handler : outParam (ε -> Prop)) where + +set_option linter.unusedVariables false in +noncomputable +instance OfHd {hd : ε -> Prop} [hdInst : IsHandler hd] + [CompleteLattice l] [inst: MAlgOrdered m l] : MAlgOrdered (ExceptT ε m) l := MAlgExcept ε hd l m + + +lemma MAlg.lift_ExceptT ε (hd : ε -> Prop) [IsHandler hd] [CompleteLattice l] [inst: MAlgOrdered m l] + (c : ExceptT ε m α) post : + MAlg.lift c post = MAlg.lift (m := m) c (fun | .ok x => post x | .error e => ⌜hd e⌝) := by + show MAlgOrdered.μ (Except.getD (⌜hd ·⌝) <$> (ExceptT.map post c : m _)) = + MAlgOrdered.μ ((fun (r : Except ε α) => match r with + | .ok x => post x | .error e => ⌜hd e⌝) <$> (c : m _)) + simp only [ExceptT.map, ExceptT.mk, map_bind] + rw [map_eq_pure_bind]; apply MAlgOrdered.bind; funext a; cases a <;> simp [Except.getD] + + +instance MAlgExceptHdDet (hd : ε -> Prop) + [CompleteLattice l] [inst: MAlgOrdered m l] [IsHandler hd] + [inst': MAlgDet m l] : MAlgDet (ExceptT ε m) l where + angelic := by + intro α ι c p _ + have h := inst'.angelic (α := Except ε α) (c := c) + (p := fun i e => match e with + | Except.ok a => p i a + | Except.error e => ⌜hd e⌝) + simp only [MAlg.lift_ExceptT (l := l) (m := m) (hd := hd)] + refine le_trans (le_of_eq ?_) (le_trans h (le_of_eq ?_)) + · congr 1; funext e; cases e <;> simp [iSup_const] + · congr 1; funext i; congr 1; funext e; cases e <;> rfl + demonic := by + intro α ι c p _ + have h := inst'.demonic (α := Except ε α) (c := c) + (p := fun i e => match e with + | Except.ok a => p i a + | Except.error e => ⌜hd e⌝) + simp only [MAlg.lift_ExceptT (l := l) (m := m) (hd := hd)] + refine le_trans (le_of_eq ?_) (le_trans h (le_of_eq ?_)) + · congr 1; funext i; congr 1; funext e; cases e <;> rfl + · congr 1; funext e; cases e <;> simp [iInf_const] + +instance + [CompleteLattice l] [inst: MAlgOrdered m l] [IsHandler (fun (_ : ε) => True)] + [inst': NoFailure m] : NoFailure (ExceptT ε m) where + noFailure := by + intro α c + rw [MAlg.lift_ExceptT (l := l) (m := m) (hd := fun _ => True)] + rw (occs := [2]) [← inst'.noFailure (c := c)] + congr 1; funext e; cases e <;> simp [LE.pure] + +/- Monad Transformer Algebra instance for ExceptT -/ +noncomputable +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] + [IsHandler (ε := ε) hd] + [inst: MAlgOrdered m l] : + MAlgLift m l (ExceptT ε m) l where + cl := by exact LogicLift.refl + μ_lift := by + intro α f x + rw [MAlg.lift_ExceptT (l := l) (m := m) (hd := hd)] + show MAlgOrdered.μ (_ <$> (Except.ok <$> x : m _)) = MAlgOrdered.μ (f <$> x) + rw [Functor.map_map] + +end ExeceptHandler + +namespace ExceptionAsSuccess +scoped instance PartialHandler {ε} : IsHandler (ε := ε) fun _ => True where +end ExceptionAsSuccess + +namespace ExceptionAsFailure +scoped instance TotalHandler {ε} : IsHandler (ε := ε) fun _ => False where +end ExceptionAsFailure + +open Lean.Order + +instance [Monad m] [inst : ∀ α, CCPO (m α)] : CCPO (ExceptT ε m α) := inst _ +instance [Monad m] [∀ α, CCPO (m α)] [MonoBind m] : MonoBind (ExceptT ε m) where + bind_mono_left h₁₂ := by + apply MonoBind.bind_mono_left (m := m) + exact h₁₂ + bind_mono_right h₁₂ := by + apply MonoBind.bind_mono_right (m := m) + intro x + cases x + · apply PartialOrder.rel_refl + · apply h₁₂ + +instance [Monad m] [CCPOBot m] : CCPOBot (ExceptT ε m) where + compBot := CCPOBot.compBot (m := m) + +instance [Monad m] [inst : ∀ α, Lean.Order.CCPO (m α)] [CCPOBot m] [CCPOBotLawful m] : CCPOBotLawful (ExceptT ε m) where + prop := CCPOBotLawful.prop (m := m) + +instance (hd : ε -> _) [IsHandler hd] [_root_.CompleteLattice l] [Monad m] [LawfulMonad m] [inst: MAlgOrdered m l] + [∀ α, CCPO (m α)] [MonoBind m] + [MAlgPartial m] : MAlgPartial (ExceptT ε m) where + csup_lift {α} chain := by + intro post hchain; simp [MAlg.lift_ExceptT] + solve_by_elim [MAlgPartial.csup_lift (m := m)] + +attribute [-simp] le_bot_iff in +instance (hd : ε -> _) [IsHandler hd] [_root_.CompleteLattice l] [Monad m] [LawfulMonad m] [inst: MAlgOrdered m l] + [∀ α, CCPO (m α)] [MonoBind m] + [MAlgTotal m] : MAlgTotal (ExceptT ε m) where + bot_lift := by + intro post hchain; simp [MAlg.lift_ExceptT] + solve_by_elim [MAlgTotal.bot_lift (m := m)] diff --git a/Loom/MonadAlgebras/Instances/ExceptTErr.lean b/Loom/MonadAlgebras/Instances/ExceptTErr.lean new file mode 100644 index 00000000..2830a940 --- /dev/null +++ b/Loom/MonadAlgebras/Instances/ExceptTErr.lean @@ -0,0 +1,102 @@ +import Loom.MonadAlgebras.Instances.ExceptT +import Loom.MonadAlgebras.Instances.StateT + +/-! +# An error-aware algebra for `ExceptT` + +Loom's `ExceptT` algebra (`MAlgExcept`) fixes, by a handler, what an exception means: +`ε → Prop` once and for all. Here the assertion instead takes the predicate an exception must +meet as an argument: over an algebra of `m` on `l`, `ExceptT ε m` has an ordered algebra on +`(ε → l) → l`. Its weakest precondition, given `herr`, is the weakest precondition of `m` +for the postcondition on a result and `herr` on an exception, so one weakest precondition +covers both outcomes, which is what a specification of a reverting call needs. + +The same construction is given directly for `Except ε`, the monad of a state program that +fails with data (`StateT σ (Except ε)`), whose assertions are then, by Loom's `StateT` +algebra, `σ → (ε → Prop) → Prop`. +-/ + +universe u v + +section ExceptTErr + +variable {ε : Type u} {l : Type u} {m : Type u → Type v} [Monad m] [LawfulMonad m] + [CompleteLattice l] [inst : MAlgOrdered m l] + +/-- What an outcome means for an error-aware assertion, given the exception predicate. -/ +def Except.errAssn (herr : ε → l) : Except ε ((ε → l) → l) → l + | .ok p => p herr + | .error e => herr e + +/-- The error-aware ordered algebra of `ExceptT ε m` on `(ε → l) → l`. -/ +noncomputable def MAlgExceptErr : MAlgOrdered (ExceptT ε m) ((ε → l) → l) where + μ x := fun herr => inst.μ (Except.errAssn herr <$> (x : m _)) + μ_ord_pure := by + intro p; funext herr + show inst.μ (Except.errAssn herr <$> (pure (Except.ok p) : m _)) = p herr + rw [map_pure]; exact MAlgOrdered.μ_ord_pure _ + μ_ord_bind := by + intro α f g hfg x herr + show inst.μ (Except.errAssn herr <$> ((x : m (Except ε α)) >>= ExceptT.bindCont f)) ≤ + inst.μ (Except.errAssn herr <$> ((x : m (Except ε α)) >>= ExceptT.bindCont g)) + rw [map_bind, map_bind] + apply inst.μ_ord_bind + rintro (e | a) + · exact le_refl _ + · exact hfg a herr + +attribute [local instance] MAlgExceptErr + +theorem MAlgExceptErr.lift_eq (c : ExceptT ε m α) (post : α → (ε → l) → l) (herr : ε → l) : + MAlg.lift c post herr = + MAlg.lift (m := m) (c : m (Except ε α)) (fun | .ok a => post a herr | .error e => herr e) := by + show inst.μ (Except.errAssn herr <$> (ExceptT.map post c : m _)) = inst.μ (_ <$> (c : m _)) + simp only [ExceptT.map, ExceptT.mk, map_bind] + rw [map_eq_pure_bind] + apply MAlgOrdered.bind; funext r; cases r <;> simp [Except.errAssn] + +end ExceptTErr + +/-! ## `Except ε` directly -/ + +section ExceptErr + +variable {ε : Type u} + +/-- What an outcome means for an error-aware assertion on `Prop`. -/ +def Except.errProp (herr : ε → Prop) : Except ε ((ε → Prop) → Prop) → Prop + | .ok p => p herr + | .error e => herr e + +/-- The error-aware ordered algebra of `Except ε` on `(ε → Prop) → Prop`. -/ +instance MAlgExceptErrProp : MAlgOrdered (Except ε) ((ε → Prop) → Prop) where + μ x := fun herr => Except.errProp herr x + μ_ord_pure := by intro p; rfl + μ_ord_bind := by + intro α f g hfg x herr + cases x with + | error e => exact le_refl _ + | ok a => exact hfg a herr + +theorem MAlgExceptErrProp.lift_eq (c : Except ε α) (post : α → (ε → Prop) → Prop) + (herr : ε → Prop) : + MAlg.lift c post herr = match c with + | .ok a => post a herr + | .error e => herr e := by + cases c <;> rfl + +instance : MAlgDet (Except ε) ((ε → Prop) → Prop) where + demonic := by + intro α ι c p _ herr + simp only [iInf_apply, MAlgExceptErrProp.lift_eq] + cases c with + | error e => simp + | ok a => simp + angelic := by + intro α ι c p _ herr + simp only [iSup_apply, MAlgExceptErrProp.lift_eq] + cases c with + | error e => simp + | ok a => simp + +end ExceptErr diff --git a/Loom/MonadAlgebras/Instances/Gen.lean b/Loom/MonadAlgebras/Instances/Gen.lean new file mode 100644 index 00000000..a3d1f8c2 --- /dev/null +++ b/Loom/MonadAlgebras/Instances/Gen.lean @@ -0,0 +1,19 @@ +import Loom.MonadAlgebras.Defs +import Loom.MonadAlgebras.Instances.Basic +import Loom.MonadAlgebras.Instances.ReaderT +import Loom.MonadAlgebras.Instances.StateT +import Plausible.Gen + +open Plausible + +universe u + +-- TODO: Fix this instance +/- Ordered Monad Algebra instance for Gen -/ +-- instance MAlgGenInst : MAlgOrdered Gen (ULift Nat -> ULift StdGen -> Prop) := +-- inferInstanceAs +-- (MAlgOrdered +-- (ReaderT (ULift Nat) +-- (StateT (ULift StdGen) Id)) +-- (ULift Nat -> +-- ULift StdGen -> Prop)) diff --git a/Loom/MonadAlgebras/Instances/ReaderT.lean b/Loom/MonadAlgebras/Instances/ReaderT.lean new file mode 100644 index 00000000..4a0a48e7 --- /dev/null +++ b/Loom/MonadAlgebras/Instances/ReaderT.lean @@ -0,0 +1,117 @@ +import Loom.MonadAlgebras.Defs +import Loom.MonadAlgebras.Instances.Basic + +/- Ordered Monad Algebra instance for ReaderT -/ +instance (σ : Type u) (l : Type u) (m : Type u -> Type v) + [CompleteLattice l] + [Monad m] [LawfulMonad m] [inst: MAlgOrdered m l] : MAlgOrdered (ReaderT σ m) (σ -> l) where + μ := fun rp r => inst.μ $ (· r) <$> rp r + μ_ord_pure := by + intros l; simp [pure, ReaderT.pure]; ext r + solve_by_elim [MAlgOrdered.μ_ord_pure] + μ_ord_bind := by + intro α f g le x r + have leM := inst.μ_ord_bind (α := α) (fun a => (fun y : σ → l => y r) <$> f a r) (fun a => (fun y : σ → l => y r) <$> g a r) + (fun a => le a r) (x r) + show MAlgOrdered.μ ((fun y : σ → l => y r) <$> (x r >>= fun a => f a r)) ≤ + MAlgOrdered.μ ((fun y : σ → l => y r) <$> (x r >>= fun a => g a r)) + rw [map_bind, map_bind]; exact leM + + +instance (σ : Type u) (l : Type u) (m : Type u -> Type v) + [CompleteLattice l] + [Monad m] [LawfulMonad m] [inst: MAlgOrdered m l] [inst': MAlgDet m l] + : MAlgDet (ReaderT σ m) (σ -> l) where + angelic := by + intros α ι c p _ s; + simp [MAlg.lift, MAlg.μ, MAlgOrdered.μ, Functor.map] + have h := inst'.angelic (α := α) (c := c s) (p := fun i x => p i x s) + simp [MAlg.lift, MAlg.μ] at h + apply h + demonic := by + intros α ι c p _ s; + simp [MAlg.lift, MAlg.μ, MAlgOrdered.μ, Functor.map] + have h := inst'.demonic (α := α) (c := c s) (p := fun i x => p i x s) + simp [MAlg.lift, MAlg.μ] at h + apply h + + +instance [Monad m] [inst : ∀ α, Lean.Order.CCPO (m α)] : Lean.Order.CCPO (ReaderT ε m α) := by + unfold ReaderT + infer_instance +instance [Monad m] [∀ α, Lean.Order.CCPO (m α)] [Lean.Order.MonoBind m] : Lean.Order.MonoBind (ReaderT ε m) where + bind_mono_left h₁₂ _ := by + simp [bind, ReaderT.bind] + apply Lean.Order.MonoBind.bind_mono_left (m := m) + apply h₁₂ + bind_mono_right h₁₂ _ := by + simp [bind] + apply Lean.Order.MonoBind.bind_mono_right (m := m) + intro x; apply h₁₂ + +/-- solidity-lean (Lean 4.35): the supremum of a chain of readers, at an environment, is the +supremum of their results there. -/ +theorem ReaderT.csup_apply [Monad m] [∀ α, Lean.Order.CCPO (m α)] {α : Type u} + (c : ReaderT ε m α → Prop) (hc : Lean.Order.chain c) (s : ε) : + (Lean.Order.CCPO.csup hc : ReaderT ε m α) s = + Lean.Order.CCPO.csup (Lean.Order.chain_apply (β := fun _ : ε => m α) hc s) := + congrFun (Lean.Order.fun_csup_eq (β := fun _ : ε => m α) c hc).symm s + +theorem ReaderT.bot_apply [Monad m] [∀ α, Lean.Order.CCPO (m α)] {α : Type u} (s : ε) : + (Lean.Order.bot : ReaderT ε m α) s = Lean.Order.bot := by + unfold Lean.Order.bot + rw [ReaderT.csup_apply] + apply Lean.Order.is_sup_unique (Lean.Order.CCPO.csup_spec _) + intro x; constructor + · intro _ y hy; obtain ⟨f, hf, _⟩ := hy; exact hf.elim + · intro _; apply Lean.Order.csup_le; intro y hy; exact hy.elim + +instance [Monad m] [CCPOBot m] : CCPOBot (ReaderT σ m) where + compBot := fun _ => CCPOBot.compBot + +instance [Monad m] [inst : ∀ α, Lean.Order.CCPO (m α)] [CCPOBot m] [CCPOBotLawful m] : CCPOBotLawful (ReaderT σ m) where + prop {α} := by + funext s + rw [ReaderT.bot_apply] + exact CCPOBotLawful.prop (m := m) + +lemma MAlg.lift_ReaderT [Monad m] [LawfulMonad m] [CompleteLattice l] [inst: MAlgOrdered m l] (x : ReaderT σ m α) : + MAlg.lift x post = fun s => MAlg.lift (x s) (fun xs => post xs s) := by + simp [MAlg.lift, Functor.map, MAlgOrdered.μ] + +open Lean.Order +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] [inst: MAlgOrdered m l] + [∀ α, CCPO (m α)] [MonoBind m] + [MAlgPartial m] : MAlgPartial (ReaderT σ m) where + csup_lift {α} chain := by + intro post hchain s + simp only [MAlg.lift_ReaderT, iInf_apply] + erw [ReaderT.csup_apply] + apply le_trans' (MAlgPartial.csup_lift (m := m) _ _ _) + refine le_iInf₂ ?_ + rintro y ⟨f, hf, rfl⟩ + exact iInf₂_le f hf + +attribute [-simp] le_bot_iff in +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] [inst: MAlgOrdered m l] + [∀ α, CCPO (m α)] [MonoBind m] + [MAlgTotal m] : MAlgTotal (ReaderT σ m) where + bot_lift {α} post := by + intro s + simp only [MAlg.lift_ReaderT] + rw [ReaderT.bot_apply] + exact MAlgTotal.bot_lift (m := m) _ + +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] [inst: MAlgOrdered m l] + [inst': NoFailure m] : NoFailure (ReaderT σ m) where + noFailure := by + intro _ _; simp [MAlg.lift_ReaderT, inst'.noFailure]; rfl + +/- Monad Transformer Algebra instance for ReaderT -/ +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] [inst: MAlgOrdered m l] : + MAlgLift m l (ReaderT σ m) (σ -> l) where + μ_lift := by + intro α f x + rw [MAlg.lift_ReaderT] + funext s + rfl diff --git a/Loom/MonadAlgebras/Instances/StateT.lean b/Loom/MonadAlgebras/Instances/StateT.lean new file mode 100644 index 00000000..98ee4e1d --- /dev/null +++ b/Loom/MonadAlgebras/Instances/StateT.lean @@ -0,0 +1,122 @@ +import Loom.MonadAlgebras.Defs +import Loom.MonadAlgebras.Instances.Basic + +/- Ordered Monad Algebra instance for StateT -/ +instance (σ : Type u) (l : Type u) (m : Type u -> Type v) + [CompleteLattice l] + [Monad m] [LawfulMonad m] [inst: MAlgOrdered m l] : MAlgOrdered (StateT σ m) (σ -> l) where + μ := (MAlgOrdered.μ $ (fun fs => fs.1 fs.2) <$> · ·) + μ_ord_pure := by + intro f; funext s₁ + show MAlgOrdered.μ ((fun fs : (σ → l) × σ => fs.1 fs.2) <$> (pure (f, s₁) : m _)) = f s₁ + rw [map_pure, MAlgOrdered.μ_ord_pure] + μ_ord_bind := by + intro α f g le x s + have leM := inst.μ_ord_bind (α := α × σ) + (fun as => (fun fs : (σ → l) × σ => fs.1 fs.2) <$> f as.1 as.2) + (fun as => (fun fs : (σ → l) × σ => fs.1 fs.2) <$> g as.1 as.2) + (fun as => le as.1 as.2) (x s) + show MAlgOrdered.μ ((fun fs : (σ → l) × σ => fs.1 fs.2) <$> (x s >>= fun p => f p.1 p.2)) ≤ + MAlgOrdered.μ ((fun fs : (σ → l) × σ => fs.1 fs.2) <$> (x s >>= fun p => g p.1 p.2)) + rw [map_bind, map_bind]; exact leM + +instance (σ : Type u) (l : Type u) (m : Type u -> Type v) + [CompleteLattice l] + [Monad m] [LawfulMonad m] [inst: MAlgOrdered m l] [inst': MAlgDet m l] + : MAlgDet (StateT σ m) (σ -> l) where + angelic := by + intros α ι c p _ s; + simp [MAlg.lift, MAlg.μ, MAlgOrdered.μ, Functor.map, StateT.map] + have h := inst'.angelic (α := α × σ) (c := c s) (ι := ι) (p := fun i x => p i x.1 x.2) + simp [MAlg.lift, MAlg.μ] at h + apply h + demonic := by + intros α ι c p _ s; + simp [MAlg.lift, MAlg.μ, MAlgOrdered.μ, Functor.map, StateT.map] + have h := inst'.demonic (α := α × σ) (c := c s) (ι := ι) (p := fun i x => p i x.1 x.2) + simp [MAlg.lift, MAlg.μ] at h + apply h + +instance [Monad m] [inst : ∀ α, Lean.Order.CCPO (m α)] : Lean.Order.CCPO (StateT ε m α) := by + unfold StateT + infer_instance +instance [Monad m] [∀ α, Lean.Order.CCPO (m α)] [Lean.Order.MonoBind m] : Lean.Order.MonoBind (StateT ε m) where + bind_mono_left h₁₂ _ := by + simp [bind, StateT.bind] + apply Lean.Order.MonoBind.bind_mono_left (m := m) + apply h₁₂ + bind_mono_right h₁₂ _ := by + simp [bind, StateT.bind] + apply Lean.Order.MonoBind.bind_mono_right (m := m) + intro x; apply h₁₂ + +/-- solidity-lean (Lean 4.35): the supremum of a chain of state transformers, at a state, is +the supremum of their results there; `CCPO.csup` is now a choice, so this replaces unfolding +it to `fun_csup`. -/ +theorem StateT.csup_apply [Monad m] [∀ α, Lean.Order.CCPO (m α)] {α : Type u} + (c : StateT ε m α → Prop) (hc : Lean.Order.chain c) (s : ε) : + (Lean.Order.CCPO.csup hc : StateT ε m α) s = + Lean.Order.CCPO.csup (Lean.Order.chain_apply (β := fun _ : ε => m (α × ε)) hc s) := + congrFun (Lean.Order.fun_csup_eq (β := fun _ : ε => m (α × ε)) c hc).symm s + +theorem StateT.bot_apply [Monad m] [∀ α, Lean.Order.CCPO (m α)] {α : Type u} (s : ε) : + (Lean.Order.bot : StateT ε m α) s = Lean.Order.bot := by + unfold Lean.Order.bot + rw [StateT.csup_apply] + apply Lean.Order.is_sup_unique (Lean.Order.CCPO.csup_spec _) + intro x; constructor + · intro _ y hy; obtain ⟨f, hf, _⟩ := hy; exact hf.elim + · intro _; apply Lean.Order.csup_le; intro y hy; exact hy.elim + +instance [Monad m] [CCPOBot m] : CCPOBot (StateT σ m) where + compBot := fun _ => CCPOBot.compBot + +instance [Monad m] [inst : ∀ α, Lean.Order.CCPO (m α)] [CCPOBot m] [CCPOBotLawful m] : CCPOBotLawful (StateT σ m) where + prop {α} := by + funext s + rw [StateT.bot_apply] + exact CCPOBotLawful.prop (m := m) + + +lemma MAlg.lift_StateT [Monad m] [LawfulMonad m] [CompleteLattice l] [inst: MAlgOrdered m l] (x : StateT σ m α) : + MAlg.lift x post = fun s => MAlg.lift (x s) (fun xs => post xs.1 xs.2) := by + simp [MAlg.lift, Functor.map, MAlgOrdered.μ, StateT.map] + +open Lean.Order +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] [inst: MAlgOrdered m l] + [∀ α, CCPO (m α)] [MonoBind m] + [MAlgPartial m] : MAlgPartial (StateT σ m) where + csup_lift {α} chain := by + intro post hchain s + simp only [MAlg.lift_StateT, iInf_apply] + erw [StateT.csup_apply] + apply le_trans' (MAlgPartial.csup_lift (m := m) _ _ _) + refine le_iInf₂ ?_ + rintro y ⟨f, hf, rfl⟩ + exact iInf₂_le f hf + +attribute [-simp] le_bot_iff in +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] [inst: MAlgOrdered m l] + [∀ α, CCPO (m α)] [MonoBind m] + [MAlgTotal m] : MAlgTotal (StateT σ m) where + bot_lift {α} post := by + intro s + simp only [MAlg.lift_StateT] + rw [StateT.bot_apply] + exact MAlgTotal.bot_lift (m := m) _ + +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] [inst: MAlgOrdered m l] + [inst': NoFailure m] : NoFailure (StateT σ m) where + noFailure := by + intro _ _; simp [MAlg.lift_StateT, inst'.noFailure]; rfl + +/- Monad Transformer Algebra instance for StateT -/ +instance [Monad m] [LawfulMonad m] [_root_.CompleteLattice l] [inst: MAlgOrdered m l] : + MAlgLift m l (StateT σ m) (σ -> l) where + μ_lift := by + intro α f x + rw [MAlg.lift_StateT] + funext s + show MAlg.lift (liftM (n := StateT σ m) x s) (fun xs => f xs.1 xs.2) = MAlg.lift x (f · s) + simp only [MAlg.lift, liftM, monadLift, MonadLift.monadLift, StateT.lift, map_bind, map_pure] + rw [map_eq_pure_bind] diff --git a/Loom/MonadAlgebras/WP/Basic.lean b/Loom/MonadAlgebras/WP/Basic.lean new file mode 100644 index 00000000..f52dd2ab --- /dev/null +++ b/Loom/MonadAlgebras/WP/Basic.lean @@ -0,0 +1,537 @@ +import Loom.MonadAlgebras.Defs + +import Loom.MonadAlgebras.Instances.Basic +import Loom.MonadAlgebras.Instances.ExceptT +import Loom.MonadAlgebras.Instances.StateT +import Loom.MonadAlgebras.Instances.ReaderT +import Loom.MonadAlgebras.Instances.Gen + +universe u v w + +variable {m : Type u -> Type v} [Monad m] [LawfulMonad m] {α : Type u} {l : Type u} + +section +variable [CompleteLattice l] +section +variable [mprop : MAlgOrdered m l] + +/- WP definition -/ +def wp (c : m α) (post : α -> l) : l := liftM (n := Cont l) c post +/- Hoare triple definition -/ +def triple (pre : l) (c : m α) (post : α -> l) : Prop := + pre ≤ wp c post + +/- WP of pure (defintion 4 from the paper) -/ +lemma wp_pure (x : α) (post : α -> l) : wp (m := m) (pure x) post = post x := by + simp [wp, liftM] + rfl + +/- WP of bind (defintion 5 from the paper) -/ +lemma triple_pure (pre : l) (x : α) (post : α -> l) : + triple pre (pure (f := m) x) post <-> pre ≤ (post x) + := by + rw [triple, wp]; simp [liftM]; rfl + +end + +variable [MAlgOrdered m l] + +lemma wp_bind {β} (x : m α) (f : α -> m β) (post : β -> l) : + wp (x >>= f) post = wp x (fun x => wp (f x) post) := by + simp [wp, liftM]; rfl + +lemma wp_map {β} (x : m α) (f : α -> β) (post : β -> l) : + wp (f <$> x) post = wp x (fun x => post (f x)) := by + rw [map_eq_pure_bind, wp_bind]; simp [wp_pure] + +/- monotonicity for WP (definition 9 from the paper) -/ +lemma wp_cons (x : m α) (post post' : α -> l) : + (∀ y, post y ≤ post' y) -> + wp x post ≤ wp x post' := by + intros h; simp [wp, liftM, monadLift]; apply Cont.monotone_lift; intros y + apply h + +lemma triple_cons (x : m α) {pre pre' : l} {post post' : α -> l} : + pre' ≤ pre -> + (∀ y, post y ≤ post' y) -> + triple pre x post -> + triple pre' x post' := by + intros hpre hpost h + apply le_trans'; apply wp_cons; apply hpost + solve_by_elim [le_trans] + +lemma triple_bind {β} (pre : l) (x : m α) (cut : α -> l) + (f : α -> m β) (post : β -> l) : + triple pre x cut -> + (∀ y, triple (cut y) (f y) post) -> + triple pre (x >>= f) post := by + intros; simp [triple, wp_bind] + solve_by_elim [le_trans', wp_cons] + +omit [LawfulMonad m] in +@[simp] +lemma wp_top (c : m α) [NoFailure m] : + wp c (fun _ => ⊤) = ⊤ := by + simp [wp, liftM, monadLift, NoFailure.noFailure] + +end + +section +variable [CompleteLattice l] [MAlgOrdered m l] + +noncomputable +def spec (pre : l) (post : α -> l) : Cont l α := + fun p => pre ⊓ ⌜post ≤ p⌝ + +lemma triple_spec (pre : l) (c : m α) (post : α -> l) : + spec pre post <= wp c <-> + triple pre c post := by + constructor + { intro h; unfold triple + specialize h post; apply le_trans'; apply h + unfold spec; simp [trueE] } + intro t p; unfold spec + by_cases h: post ≤ p + { apply inf_le_of_left_le; apply le_trans; apply t + solve_by_elim [Cont.monotone_lift (x := c)] } + have : (post ≤ p) = False := by simp [h] + simp [this, falseE] + +end + +section Determinism + +variable [inst: CompleteLattice l] [MAlgOrdered m l] + +lemma wp_iInf {ι : Type u} [Nonempty ι] [MAlgDet m l] (c : m α) (post : ι -> α -> l) : + wp c (fun x => ⨅ i, post i x) = ⨅ i, wp c (post i) := by + apply le_antisymm + { refine le_iInf ?_; intros i; apply wp_cons; intro y + exact iInf_le (fun i ↦ post i y) i } + apply MAlgDet.demonic + +lemma wp_and [MAlgDet m l] (c : m α) (post₁ post₂ : α -> l) : + wp c (fun x => post₁ x ⊓ post₂ x) = wp c post₁ ⊓ wp c post₂ := by + apply le_antisymm + { simp; constructor <;> apply wp_cons <;> simp } + have h := MAlgDet.demonic (l := l) (ι := ULift Bool) (c := c) (p := fun | .up true => post₁ | .up false => post₂) + simp at h + apply le_trans; apply le_trans'; apply h + { simp [wp]; constructor; exact inf_le_right + exact inf_le_left } + apply wp_cons (m := m); simp; intros; constructor + { refine iInf_le_of_le true ?_; simp } + refine iInf_le_of_le false ?_; simp + +lemma wp_iSup {ι : Type u} [Nonempty ι] [MAlgDet m l] (c : m α) (post : ι -> α -> l) : + wp c (fun x => ⨆ i, post i x) = ⨆ i, wp c (post i) := by + apply le_antisymm + { apply MAlgDet.angelic } + refine iSup_le ?_; intros i; apply wp_cons; intro y + exact le_iSup (fun i ↦ post i y) i + + +lemma wp_or [MAlgDet m l] (c : m α) (post₁ post₂ : α -> l) : + wp c (fun x => post₁ x ⊔ post₂ x) = wp c post₁ ⊔ wp c post₂ := by + apply le_antisymm + { have h := MAlgDet.angelic (l := l) (ι := ULift Bool) (c := c) (p := fun | .up true => post₁ | .up false => post₂) + simp [-iSup_le_iff] at h + apply le_trans; apply le_trans'; apply h + { apply wp_cons (m := m); simp; intros; constructor + { refine le_iSup_of_le true ?_; simp } + refine le_iSup_of_le false ?_; simp } + simp [wp]; constructor; exact le_sup_right + exact le_sup_left } + simp; constructor <;> apply wp_cons <;> simp + + +end Determinism + + +section Loops + +open Lean.Order + +/- partial loop from MonoBind and CCPO instances -/ +@[specialize, inline] +def Loop.forIn.loop {m : Type u -> Type v} [Monad m] [∀ α, CCPO (m α)] [MonoBind m] (f : Unit → β → m (ForInStep β)) (b : β) : m β := do + match ← f () b with + | ForInStep.done b => pure b + | ForInStep.yield b => loop f b + partial_fixpoint + +@[inline] +def Loop.forIn {β : Type u} [Monad m] [∀ α, CCPO (m α)] [MonoBind m] + (_ : Lean.Loop) (init : β) (f : Unit → β → m (ForInStep β)) : m β := + Loop.forIn.loop f init + +@[instance high] +instance [md : Monad m] [ccpo : ∀ α, CCPO (m α)] [mono : MonoBind m] : ForIn m Lean.Loop Unit where + forIn {β} := @Loop.forIn m β md ccpo mono + +variable [inst: _root_.CompleteLattice l] [MAlgOrdered m l] + +namespace PartialCorrectness + +variable [∀ α, CCPO (m α)] [MonoBind m] [MAlgPartial m] + +omit [MonoBind m] [LawfulMonad m] in +lemma wp_csup (xc : Set (m α)) (post : α -> l) (hc : Lean.Order.chain xc) : + ⨅ c ∈ xc, wp c post ≤ wp (Lean.Order.CCPO.csup hc) post := by + apply MAlgPartial.csup_lift + +omit [MonoBind m] [LawfulMonad m] in +lemma wp_bot : + wp (bot : m α) = fun _ => (⊤ : l) := by + ext post; refine eq_top_iff.mpr ?_ + apply le_trans' (wp_csup (empty_chain (m α)) post (chain_empty _)) + refine le_iInf₂ ?_ + intro _ h; exact h.elim + +lemma repeat_inv (f : Unit -> β -> m (ForInStep β)) + (inv : ForInStep β -> l) + init : + (∀ b, triple (inv (.yield b)) (f () b) (inv)) -> + triple (inv (.yield init)) (Loop.forIn.loop f init) (fun b => inv (.done b)) := by + intro hstep + revert init + apply Loop.forIn.loop.fixpoint_induct (f := f) (motive := + fun loop => ∀ init, triple (inv (.yield init)) (loop init) (fun b =>inv (.done b))) + { apply Lean.Order.admissible_pi_apply + (P := fun init loop => triple (inv (.yield init)) (loop) (fun b =>inv (.done b))) + intro init loops cl h + simp only [triple] at h ⊢ + apply le_trans' (wp_csup _ _ cl) + exact le_iInf₂ h } + intro loop ih init; simp [triple, wp_bind]; apply le_trans; apply hstep + apply wp_cons; rintro (_|_); simp [wp_pure] + apply ih + +lemma repeat_inv_split (f : Unit -> β -> m (ForInStep β)) + (inv : β -> l) (doneWith : β -> l) + init : + (∀ b, triple (inv b) (f () b) (fun | .yield b' => inv b' | .done b' => inv b' ⊓ doneWith b')) -> + triple (inv init) (Loop.forIn.loop f init) (fun b => inv b ⊓ doneWith b) := by + intro hstep + apply repeat_inv f (fun | .yield b => inv b | .done b => inv b ⊓ doneWith b) init + apply hstep + +end PartialCorrectness + +namespace TotalCorrectness + +variable [∀ α, CCPO (m α)] [MonoBind m] + +lemma repeat_inv (f : Unit -> β -> m (ForInStep β)) + (inv : ForInStep β -> l) (measure : β -> Nat) + init : + (∀ b, triple (inv (.yield b)) (f () b) (fun | .yield b' => inv (.yield b') ⊓ ⌜ measure b' < measure b ⌝ | .done b' => inv (.done b'))) -> + triple (inv (.yield init)) (Loop.forIn.loop f init) (fun b => inv (.done b)) := by + intro hstep + have induc (C : β → Prop) (a : β) (h : ∀ x, (∀ y, measure y < measure x → C y) → C x): C a := by + have lem: ∀ n: Nat, ∀ x, measure x ≤ n → C x := by + intro n + induction n with + | zero => + intro x hx + exact h x (fun y => by omega) + | succ m ih => + intro x hx + by_cases neq: measure x ≤ m + { exact ih x neq } + have eq: measure x = m + 1 := by omega + exact h x (fun y hy => ih y (by omega)) + exact lem (measure a) a (by simp) + apply induc + (fun ini => triple (inv (.yield ini)) (Loop.forIn.loop f ( ini)) (fun b => inv (.done b))) init + intro b ih; unfold Loop.forIn.loop; simp [triple, wp_bind]; apply le_trans + apply hstep; apply wp_cons; rintro (_|_) + { simp [wp_pure] } + rename_i a + match ForInStep.yield a with + | .yield b' => + simp; intro m_lt + have ihb := ih b' m_lt + simp [triple] at ihb + exact ihb + | .done b' => + simp + rw [wp_pure b' (fun s: β => inv (ForInStep.done s))] + + +lemma repeat_inv_split (f : Unit -> β -> m (ForInStep β)) + (inv : β -> l) (doneWith : β -> l) + init (measure: β -> Nat): + (∀ b, triple (inv b) (f () b) (fun | .yield b' => inv b' ⊓ ⌜ measure b' < measure b ⌝ | .done b' => inv b' ⊓ doneWith b')) -> + triple (inv init) (Loop.forIn.loop f init) (fun b => inv b ⊓ doneWith b) := by + intro hstep + apply repeat_inv f (fun | .yield b => inv b | .done b => inv b ⊓ doneWith b) measure init + apply hstep + +variable [MAlgTotal m] + +omit [LawfulMonad m] [MonoBind m] in +attribute [-simp] le_bot_iff in +@[simp] +lemma wp_bot : + wp (bot : m α) = fun _ => (⊥ : l) := by + ext post; refine eq_bot_iff.mpr ?_ + simp [wp, liftM, monadLift]; apply MAlgTotal.bot_lift + +end TotalCorrectness + +theorem triple_forIn_list {α β} + {xs : List α} {init : β} {f : α → β → m (ForInStep β)} + (inv : List α → β → l) + (hstep : ∀ hd tl b, + triple + (inv (hd :: tl) b) + (f hd b) + (fun | .yield b' => inv tl b' | .done b' => inv [] b')) : + triple (inv xs init) (forIn xs init f) (inv []) := by + induction xs generalizing init + { simp; rw [triple_pure] } + simp only [List.forIn_cons] + apply triple_bind; apply hstep; intros y + cases y <;> simp <;> solve_by_elim [(triple_pure ..).mpr, le_refl] + +theorem triple_forIn_range'_aux {β} + {xstart : ℕ} {step : ℕ} (n : ℕ) (init : β) {f : ℕ → β → m (ForInStep β)} + (inv : ℕ → β → l) + (hstep : ∀ i b, + triple + (inv i b) + (f i b) + (fun | .yield b' => inv (i + step) b' | .done b' => inv (xstart + n * step) b')) : + i <= n -> + triple (inv (xstart + (n - i) * step) init) (forIn (List.range' (xstart + (n - i) * step) i step) init f) (inv (xstart + n * step)) := by + unhygienic induction i generalizing init + { simp [triple_pure] } + intro le + simp [List.range']; apply triple_bind; apply hstep + rintro (_|_) <;> simp [triple_pure] + simp [Nat.add_assoc, <-Nat.add_one_mul] + have : (n - (n_1 + 1) + 1) = n - n_1 := by omega + rw [this]; apply a; omega + + +theorem triple_forIn_range' {β} + {xstart : ℕ} {step : ℕ} (n : ℕ) {init : β} {f : ℕ → β → m (ForInStep β)} + (inv : ℕ → β → l) + (hstep : ∀ i b, + triple + (inv i b) + (f i b) + (fun | .yield b' => inv (i + step) b' | .done b' => inv (xstart + n * step) b')) : + triple (inv xstart init) (forIn (List.range' xstart n step) init f) (inv (xstart + n * step)) := by + have := triple_forIn_range'_aux (i := n) (m := m) n init inv hstep (by omega) + simp_all only [Nat.sub_self, Nat.zero_mul, Nat.add_zero] + +theorem triple_forIn_range {β} + (xs : Std.Legacy.Range) (init : β) (f : ℕ → β → m (ForInStep β)) + (inv : ℕ → β → l) + (hstep : ∀ i b, + triple + (inv i b) + (f i b) + (fun | .yield b' => inv (i + xs.step) b' | .done b' => inv (xs.start + ((xs.stop - xs.start + xs.step - 1) / xs.step) * xs.step) b')) : + triple (inv xs.start init) (forIn xs init f) (inv (xs.start + ((xs.stop - xs.start + xs.step - 1) / xs.step) * xs.step)) := by + simp; apply triple_forIn_range'; apply hstep + +theorem triple_forIn_range_step1 {β} + {xs : Std.Legacy.Range} {init : β} {f : ℕ → β → m (ForInStep β)} + (inv : ℕ → β → l) + (hstep : ∀ i b, + triple + (inv i b) + (f i b) + (fun | .yield b' => inv (i + xs.step) b' | .done b' => inv xs.stop b')) : + xs.step = 1 -> + xs.start <= xs.stop -> + triple (inv xs.start init) (forIn xs init f) (inv xs.stop) := by + have := triple_forIn_range (m := m) xs init f inv + intro h eq; + simp [h] at * + rw [Nat.add_sub_of_le eq] at this; + solve_by_elim + +end Loops + + +section Lift + +variable [inst: CompleteLattice l] [MAlgOrdered m l] + +lemma wp_except_handler_eq ε (hd : ε -> Prop) [IsHandler hd] (c : ExceptT ε m α) post : + wp c post = wp (m := m) c (fun | .ok x => post x | .error e => ⌜hd e⌝) := by + apply MAlg.lift_ExceptT + + +open ExceptionAsSuccess in +lemma wp_part_eq ε (c : ExceptT ε m α) post : + wp c post = wp (m := m) c (fun | .ok x => post x | .error _ => ⊤) := by + simp [wp_except_handler_eq] + +open ExceptionAsFailure in +lemma wp_tot_eq ε (c : ExceptT ε m α) post : + wp c post = wp (m := m) c (fun | .ok x => post x | .error _ => ⊥) := by + simp [wp_except_handler_eq] + + +lemma ExceptT.wp_lift_hd {hd : ε -> Prop} (c : m α) (post : α -> l) [IsHandler hd] : + wp (liftM (n := ExceptT ε m) c) post = wp (m := m) c post := by + simp [wp_except_handler_eq, liftM, monadLift, MonadLift.monadLift, ExceptT.lift, mk] + rw [map_eq_pure_bind, wp_bind]; simp [wp_pure] + +lemma ExceptionAsSuccess.ExceptT.wp_lift (c : m α) (post : α -> l) : + wp (liftM (n := ExceptT ε m) c) post = wp (m := m) c post := by + apply ExceptT.wp_lift_hd + +lemma ExceptionAsFailure.ExceptT.wp_lift (c : m α) (post : α -> l) : + wp (liftM (n := ExceptT ε m) c) post = wp (m := m) c post := by + apply ExceptT.wp_lift_hd + +/- WP for DivM in TotalCorrectness -/ +open TotalCorrectness in +lemma TotalCorrectness.DivM.wp_eq (α : Type) (x : DivM α) (post : α -> Prop) : + wp x post = + match x with + | .div => False + | .res r => post r := by + cases x + · show ⌜post _⌝ = post _; simp [LE.pure] + · rfl + +/- WP for DivM in PartialCorrectness -/ +lemma PartialCorrectness.DivM.wp_eq (α : Type) (x : DivM α) (post : α -> Prop) : + wp x post = + match x with + | .div => True + | .res r => post r := by + cases x <;> rfl + +/- WP for StateT in underlying monad -/ +lemma StateT.wp_eq (c : StateT σ m α) (post : α -> σ -> l) : + wp c post = fun s => wp (m := m) (c s) (fun xs => post xs.1 xs.2) := by + simp [wp, liftM, monadLift, MAlg.lift_StateT]; + +/- WP for lift to StateT -/ +lemma StateT.wp_lift (c : m α) (post : α -> σ -> l) : + wp (liftM (n := StateT σ m) c) post = fun s => wp (m := m) c (post · s) := by + simp [wp, liftM, monadLift, MAlg.lift_StateT, MonadLift.monadLift, StateT.lift]; + have liftE : ∀ α, MAlg.lift (m := m) (α := α) = wp := by intros; ext; simp [wp, liftM, monadLift] + ext s; rw [map_eq_pure_bind, liftE, liftE, wp_bind]; simp [wp_pure] + +/- WP for ReaderT in underlying monad -/ +lemma ReaderT.wp_eq (c : ReaderT σ m α) (post : α -> σ -> l) : + wp c post = fun s => wp (m := m) (c s) (post · s) := by + simp [wp, liftM, monadLift, MAlg.lift_ReaderT]; + +/- WP for lift to ReaderT -/ +lemma ReaderT.wp_lift (c : m α) (post : α -> σ -> l) : + wp (liftM (n := ReaderT σ m) c) post = fun s => wp (m := m) c (post · s) := by + simp [wp, liftM, monadLift, MAlg.lift_ReaderT, MonadLift.monadLift] + +/- WP lift from MAlgLift-/ +omit [LawfulMonad m] in +lemma MAlgLift.wp_lift [Monad n] [CompleteLattice k] [MAlgOrdered n k] [MonadLiftT m n] + -- [MonadLiftT (Cont l) (Cont k)] + [mAlgLift : MAlgLiftT m l n k] (c : m α): + wp (liftM (n := n) c) = fun (post : α -> k) => mAlgLift.cl.lift.monadLift (wp c) post := by + ext; + apply MAlgLiftT.μ_lift + +end Lift + +section ExceptT + +variable [inst: CompleteLattice l] [MAlgOrdered m l] [IsHandler (ε := ε) hd] + +/- WP for exception in ExceptT -/ +lemma ExceptT.wp_throw (e : ε) : + wp (α := α) (throw (m := ExceptT ε m) e) = fun _ => ⌜hd e⌝ := by + ext; simp [wp_except_handler_eq, throw, throwThe, MonadExceptOf.throw, mk, wp_pure] + +/- WP lift from Monad Transformer Algebra -/ +lemma MAlgLift.wp_throw + [Monad n] [CompleteLattice k] [MAlgOrdered n k] [MonadLiftT m n] + [MonadLiftT (ExceptT ε m) n] + [inst: MAlgLiftT (ExceptT ε m) l n k] : + wp (liftM (n := n) (throw (m := ExceptT ε m) e)) post = ⌜hd e⌝ := by + rw [MAlgLift.wp_lift, ExceptT.wp_throw] + simp only [LE.pure]; split <;> simp [inst.cl.lift_top, inst.cl.lift_bot] + +end ExceptT + +section StateT + +variable [inst: CompleteLattice l] [MAlgOrdered m l] + +/- WP for get in StateT -/ +lemma StateT.wp_get (post : σ -> σ -> l) : + wp (get (m := StateT σ m)) post = fun s => post s s := by + simp [StateT.wp_eq, get, getThe, MonadStateOf.get, StateT.get, wp_pure] + +/- WP for set in StateT -/ +lemma StateT.wp_set {res: σ} (post : PUnit -> σ -> l) : + wp (set (m := StateT σ m) res) post = fun _ => post PUnit.unit res := by + simp [StateT.wp_eq, set, StateT.set, wp_pure] + +/- WP for modifyGet in StateT -/ +lemma StateT.wp_modifyGet (post : α -> σ -> l) : + wp (modifyGet (m := StateT σ m) f) post = fun s => post (f s).1 (f s).2 := by + simp [StateT.wp_eq, modifyGet, MonadStateOf.modifyGet, StateT.modifyGet, wp_pure] + +end StateT + +section ReaderT + +variable [inst: CompleteLattice l] [MAlgOrdered m l] + +/- WP for read in ReaderT -/ +lemma ReaderT.wp_read (post : σ -> σ -> l) : + wp (read (m := ReaderT σ m)) post = fun s => post s s := by + simp [ReaderT.wp_eq, read, readThe, MonadReaderOf.read, ReaderT.read, wp_pure] + + +end ReaderT + +section Gen + +open Plausible + +-- TODO: Fix this instance +/- WP for rand in Gen -/ +-- lemma Gen.wp_rand {α : Type} (c : Gen α) : +-- triple ⊤ c (fun _ => ⊤) := by +-- simp [triple, MAlgGenInst, ReaderT.wp_eq, StateT.wp_eq] +-- simp [wp, liftM, monadLift, MAlg.lift, MAlgOrdered.μ]; rfl + +end Gen + + +-- section StrongestPostcondition + +-- variable [inst: CompleteLattice l] [MAlgOrdered m l] + +-- def sp (x : m α) (pre : l) : α -> l := (sInf fun post => pre <= wp x post) + +-- lemma le_wp_sp_le (x : m α) [LawfulMonad m] [MAlgDet m l] : +-- post ≠ ⊤ -> +-- (sp x pre <= post -> pre <= wp x post) := by +-- intro pne +-- by_cases ex: Nonempty (Set.Elem fun post ↦ pre ≤ wp x post) +-- { have : pre <= wp x (sp x pre) := by { +-- unfold sp; simp [sInf]; rw [@wp_iInf] +-- revert ex; simp [Set.Elem, Set.Mem, Membership.mem] } +-- solve_by_elim [wp_cons, le_trans] } +-- rw [@Set.not_nonempty_iff_eq_empty'] at ex +-- simp [sp, ex, *] + +-- lemma sp_le_le_wp (x : m α) : +-- (pre <= wp x post -> sp x pre <= post) := by +-- intro a; --refine inf_le_of_left_le ?_ +-- exact CompleteSemilatticeInf.sInf_le (fun post ↦ pre ≤ wp x post) post a + + +-- end StrongestPostcondition diff --git a/Loom/MonadAlgebras/WP/Liberal.lean b/Loom/MonadAlgebras/WP/Liberal.lean new file mode 100644 index 00000000..0a27c3e0 --- /dev/null +++ b/Loom/MonadAlgebras/WP/Liberal.lean @@ -0,0 +1,222 @@ +import Mathlib.Order.CompleteBooleanAlgebra + +import Loom.MonadAlgebras.Defs +import Loom.MonadAlgebras.WP.Basic + +import Loom.MonadAlgebras.Instances.Basic +import Loom.MonadAlgebras.Instances.ExceptT + +variable {m : Type u -> Type v} [Monad m] [LawfulMonad m] {α : Type u} {l : Type u} +variable [inst: CompleteBooleanAlgebra l] [mprop: MAlgOrdered m l] + +attribute [simp] trueE falseE +@[local simp] +private lemma compl_fun {α} (x y : α -> l) : + (fun a => x a ⊔ y a)ᶜ = (fun a => (x a)ᶜ ⊓ (y a)ᶜ) := by simp [compl] + +@[local simp] +private lemma compl_fun' {α} (x y : α -> l) : + (fun a => x a ⊓ y a)ᶜ = (fun a => (x a)ᶜ ⊔ (y a)ᶜ) := by simp [compl] + +@[local simp] +private lemma compl_fun'' {α} (x : α -> l) : + (fun a => (x a)ᶜ) = xᶜ := by simp [compl] + + +@[local simp] +private lemma compl_fun_true {α} : + (fun (_ : α) => ⊤)ᶜ = fun _ => (⊥ : l) := by simp [compl] + +abbrev iwp (c : m α) : Cont l α := Cont.inv (wp c) + +omit [LawfulMonad m] in +@[simp] +lemma iwp_eq (c : m α) (post : α -> l) : + iwp c post = (wp c postᶜ)ᶜ := by + simp [iwp, Cont.inv] + +def wlp (c : m α) (post : α -> l) : l := iwp c post ⊔ wp c post + +@[simp] +lemma wlp_true (c : m α) : wlp c (fun _ => ⊤) = ⊤ := by + simp [wlp]; rw [@eq_top_iff, sup_comm, <-himp_eq]; simp + apply wp_cons; simp + +@[simp] +lemma wlp_pure (x : α) (post : α -> l) : + wlp (pure (f := m) x) post = post x := by + simp [wlp, wp_pure] + +omit [LawfulMonad m] in +lemma wp_wlp (c : m α) (post : α -> l) : + wp c post <= wlp c post := by + simp [wlp, wp] + +section Determinism +variable [MAlgDet m l] + +lemma wlp_and (c : m α) (post₁ post₂ : α -> l) : + wlp c (fun x => post₁ x ⊓ post₂ x) = wlp c post₁ ⊓ wlp c post₂ := by + simp [wlp]; apply le_antisymm + { simp [wp_or, wp_and] } + rw (occs := .pos [3]) [sup_comm]; rw [<-himp_eq]; simp + rw [inf_inf_distrib_right] + conv => + enter [1,1] + rw [inf_sup_right, <-wp_and]; + simp [inf_sup_left]; rw [wp_or, inf_sup_left]; simp + erw [wp_and, <-inf_sup_right] + conv => + enter [1,2] + rw [inf_sup_right, <-wp_and]; + simp [inf_sup_left]; rw [wp_or, inf_sup_left]; simp + erw [wp_and, <-inf_sup_right] + rw (occs := .pos [3]) [inf_comm] + rw [inf_assoc] + rw (occs := .pos [2]) [<-inf_assoc] + rw (occs := .pos [3]) [inf_comm] + repeat rw [<-inf_assoc] + rw [inf_sup_right, <-wp_and]; simp + apply inf_le_of_left_le + apply inf_le_of_left_le + apply wp_cons; simp + +lemma wlp_bind {β} (x : m α) (f : α -> m β) (post : β -> l) : + wlp (x >>= f) post = wlp x (fun x => wlp (f x) post) := by + simp [wlp, wp_bind]; apply le_antisymm + { simp [wp_and, wp_or]; constructor + { repeat apply le_sup_of_le_left; simp } + repeat apply le_sup_of_le_right; simp } + simp [wp_and, wp_or]; constructor + { rw [<-compl_compl (x := wp x fun a ↦ wp (f a) post)] + rw [<-himp_eq, le_himp_iff, ← compl_sup, <-wp_or] + simp; apply wp_cons; simp } + rw [sup_comm]; simp [<-himp_eq, <-wp_and] + apply wp_cons; simp + + +lemma wlp_himp (c : m α) (post post' : α -> l) : + wp c (fun x => post' x ⇨ post x) = wlp c post' ⇨ wp c post := by + rw [himp_eq, wlp]; simp [himp_eq, wp_or] + apply le_antisymm <;> simp + rw [<-compl_compl (x := wp c post'ᶜ ⊓ (wp c post')ᶜ)] + rw [<-himp_eq]; simp; rw [@inf_sup_left]; simp [<-wp_and] + apply wp_cons; simp + +lemma wlp_join_wp (c : m α) (post post' : α -> l) : + wlp c post ⊓ wp c post' = wp c (fun x => post x ⊓ post' x) := by + apply le_antisymm + { rw [← @le_himp_iff', <-wlp_himp]; + apply wp_cons; simp } + simp; constructor + { apply le_trans'; apply wp_wlp; apply wp_cons; simp } + apply wp_cons; simp + +lemma wp_top_wlp (c : m α) (post : α -> l) : + wp c ⊤ ⊓ wlp c post = wp c post := by + rw [inf_comm, wlp_join_wp]; simp + +omit [MAlgDet m l] in +lemma wlp_cons (c : m α) (post post' : α -> l) : + post <= post' -> + wlp c post <= wlp c post' := by + intro; unfold wlp iwp; simp; constructor + { refine le_sup_of_le_left ?_; simp; apply wp_cons; simp; solve_by_elim } + solve_by_elim [le_sup_of_le_right, wp_cons] + +lemma wp_top_iwp (c : m α) (post : α -> l) : + wp c ⊥ = ⊥ -> + wp c ⊤ ⊓ iwp c post = wp c post := by + intro wpb + apply le_antisymm + { simp; simp [<-le_himp_iff, himp_eq, <-wp_or]; rfl } + simp; constructor + { apply wp_cons; simp } + rw [@le_compl_iff_disjoint_left]; intro _ _ _ + apply le_trans'; rewrite [<- wpb]; + rw [<-compl_inf_eq_bot (a := post)] + erw [wp_and]; simp; solve_by_elim + +set_option quotPrecheck false in +notation "[totl|" t "]" => open ExceptionAsFailure in t +set_option quotPrecheck false in +notation "[part|" t "]" => open ExceptionAsSuccess in t +set_option quotPrecheck false in +notation "[handler" hd "|" t "]" => have : IsHandler hd := ⟨⟩; t + +lemma wp_tot_part ε (c : ExceptT ε m α) post : + [totl| wp c ⊤] ⊓ [part| wp c post] = [totl| wp c post] := by + rw [wp_part_eq, wp_tot_eq, wp_tot_eq, <-wp_and] + congr; ext x; cases x <;> simp + +lemma wp_compl (c : m α) post (wp_bot : ∀ α (c : m α), wp c ⊤ = ⊤) : + (wp c postᶜ)ᶜ <= wp c post := by + refine compl_le_iff_compl_le.mp ?_ + rw [← @codisjoint_iff_compl_le_right]; intro b + rw [<-wp_bot (c := c)]; intros; apply le_trans + apply wp_cons; intro a; apply BooleanAlgebra.top_le_sup_compl (x := post) + erw [wp_or]; simp_all + +lemma wp_compl' (c : m α) post (wp_bot : ∀ α (c : m α), wp c ⊥ = ⊥) : + wp c post <= (wp c postᶜ)ᶜ := by + have : wp c post = ⊤ ⊓ wp c post := by simp + rw [this, <-le_himp_iff, himp_eq]; rw [← @compl_inf, <-wp_and]; simp + solve_by_elim + +-- lemma wp_tot_eq_iwp_part ε (c : ExceptT ε m α) (post : α -> l) +-- (wp_bot : ∀ α (c : m α), wp c ⊥ = ⊥) +-- (wp_top : ∀ α (c : m α), wp c ⊤ = ⊤) : +-- [totl| wp c post] = [part| iwp c post] := by +-- simp only [iwp, wp_tot_eq, wp_part_eq] +-- apply le_antisymm <;> try simp +-- { apply le_trans; apply wp_compl'; simp [*] +-- simp; apply wp_cons (x := c); rintro (_|_) <;> simp } +-- apply le_trans'; apply wp_compl; simp [*] +-- simp; apply wp_cons; rintro (_|_) <;> simp + +private lemma le_coml_sup (x y z : l) : + y <= x ⊔ z -> xᶜ <= yᶜ ⊔ z := by + intro h; + rw [sup_comm, <-himp_eq]; simp + rw [inf_comm, <-le_himp_iff, himp_eq]; simp + rwa [sup_comm] + +lemma wlp_part_wlp_handler ε (α : Type u) (c : ExceptT ε m α) (post : α → l) (hd : ε -> Prop) : + [part| wlp c post] = + [handler hd| wlp c post] := by + simp [wlp, wp_part_eq, wp_except_handler_eq] + apply le_antisymm <;> simp + { constructor + { apply le_coml_sup; rw [<-wp_or]; apply wp_cons + rintro (_|_) <;> simp } + rw [sup_comm, <-himp_eq]; simp [<-wp_and] + apply wp_cons; rintro (_|_) <;> simp } + constructor + { apply le_coml_sup; rw [<-wp_or]; apply wp_cons + rintro (_|_) <;> simp } + rw [sup_comm, <-himp_eq]; simp [<-wp_and] + apply wp_cons; rintro (_|_) <;> simp + +lemma TotalCorrectness.DivM.wlp_eq (α : Type) (x : DivM α) (post : α -> Prop) : + (open TotalCorrectness in wlp x post) = (open PartialCorrectness in wp x post) := by + simp [wlp, TotalCorrectness.DivM.wp_eq, PartialCorrectness.DivM.wp_eq] + split <;> simp + +lemma PartialCorrectness.DivM.wlp_eq (α : Type) (x : DivM α) (post : α -> Prop) : + wlp x post = wp x post := by + simp [wlp, PartialCorrectness.DivM.wp_eq] + split <;> simp + +omit [MAlgDet m l] in +lemma StateT.wlp_eq (c : StateT σ m α) (post : α -> σ -> l) : + wlp c post = fun s => wlp (m := m) (c s) (fun xs => post xs.1 xs.2) := by + simp [wlp, StateT.wp_eq]; rfl + +omit [MAlgDet m l] in +lemma ReaderT.wlp_eq (c : ReaderT σ m α) (post : α -> σ -> l) : + wlp c post = fun s => wlp (m := m) (c s) (post · s) := by + simp [wlp, ReaderT.wp_eq]; rfl + +lemma ExceptT.wlp_eq (c : ExceptT ε m α) (post : α -> l) : + [totl| wlp c post] = [part| wlp c post] := by + rw [wlp_part_wlp_handler] diff --git a/Loom/MonadAlgebras/WP/Variant.lean b/Loom/MonadAlgebras/WP/Variant.lean new file mode 100644 index 00000000..4980004e --- /dev/null +++ b/Loom/MonadAlgebras/WP/Variant.lean @@ -0,0 +1,107 @@ +import Loom.MonadAlgebras.WP.Basic + +/-! +# Loops with an invariant and a variant, in any monad + +Loom's unbounded loop (`Loop.forIn.loop`) is a `partial_fixpoint`, so it needs a monad +that can diverge (`CCPO`, `MonoBind`), and its total-correctness rule +(`TotalCorrectness.repeat_inv`) an algebra that sends divergence to `⊥`. A monad without +divergence, such as a state program that fails with data, runs a loop for a number of +iterations it is given. `Loop.bounded exhaust f fuel b` runs `f` from `b` until it returns +`done`, at most `fuel` times, and runs `exhaust` on what it reached if it never did. + +`triple_bounded` is the total-correctness rule: an invariant that each step keeps, and a +natural-number variant that each step that continues decreases, give the loop's triple once +the fuel exceeds the initial variant, whatever `exhaust` does, since the loop then never +reaches it. `triple_while` is the same rule for a `while` loop with a condition and a body. +`bounded_eq_of_variant` says that such a loop does not depend on its fuel or `exhaust`. +-/ + +universe u v + +variable {m : Type u → Type v} [Monad m] [LawfulMonad m] {β : Type u} {l : Type u} + +/-- At most `fuel` iterations of `f` from `b`; `exhaust` on what is reached if `f` never +returned `done`. -/ +def Loop.bounded (exhaust : β → m β) (f : β → m (ForInStep β)) : Nat → β → m β + | 0, b => exhaust b + | n + 1, b => do + match ← f b with + | .done b => pure b + | .yield b => Loop.bounded exhaust f n b + +/-- A `while` loop: while `cond` holds, run `body`, at most `fuel` times. -/ +def Loop.whileBounded (exhaust : β → m β) (cond : β → Bool) (body : β → m β) + (fuel : Nat) (b : β) : m β := + Loop.bounded exhaust (fun b => if cond b then ForInStep.yield <$> body b else pure (.done b)) + fuel b + +section +variable [CompleteLattice l] [MAlgOrdered m l] + +/-- Total correctness of a bounded loop: an invariant each step keeps and a variant each +continuing step decreases give the triple once the fuel exceeds the variant. -/ +theorem triple_bounded (exhaust : β → m β) (f : β → m (ForInStep β)) + (inv : β → l) (doneWith : β → l) (measure : β → Nat) + (hstep : ∀ b, triple (inv b) (f b) (fun + | .yield b' => inv b' ⊓ ⌜measure b' < measure b⌝ + | .done b' => inv b' ⊓ doneWith b')) : + ∀ fuel init, measure init < fuel → + triple (inv init) (Loop.bounded exhaust f fuel init) (fun b => inv b ⊓ doneWith b) := by + intro fuel + induction fuel with + | zero => intro _ h; omega + | succ n ih => + intro init hlt + simp only [triple, Loop.bounded, wp_bind] + apply le_trans (hstep init) + apply wp_cons + rintro (b' | b') + · simp only [wp_pure]; exact le_refl _ + · simp only [pure_intro_l] + intro hm + exact ih b' (by omega) + +/-- Total correctness of a bounded `while` loop: the body keeps the invariant and decreases +the variant while the condition holds; the loop ends where the invariant holds and the +condition does not. -/ +theorem triple_while (exhaust : β → m β) (cond : β → Bool) (body : β → m β) + (inv : β → l) (measure : β → Nat) + (hbody : ∀ b, cond b = true → + triple (inv b) (body b) (fun b' => inv b' ⊓ ⌜measure b' < measure b⌝)) + (fuel : Nat) (init : β) (hfuel : measure init < fuel) : + triple (inv init) (Loop.whileBounded exhaust cond body fuel init) + (fun b => inv b ⊓ ⌜cond b = false⌝) := by + apply triple_bounded exhaust _ inv (fun b => ⌜cond b = false⌝) measure _ fuel init hfuel + intro b + by_cases hc : cond b = true + · simp only [hc, if_true, triple, wp_map] + exact hbody b hc + · have hc' : cond b = false := by simpa using hc + simp only [hc', triple, Bool.false_eq_true, if_false] + rw [wp_pure] + simp [LE.pure, hc'] + +end + +/-- A loop whose variant decreases does not depend on its fuel past the variant. -/ +theorem bounded_eq_of_variant (exhaust exhaust' : β → m β) (f : β → m (ForInStep β)) + (good : β → Prop) (measure : β → Nat) + (hstep : ∀ b, good b → ∃ r : ForInStep β, f b = pure r ∧ + match r with | .yield b' => good b' ∧ measure b' < measure b | .done _ => True) : + ∀ fuel fuel' b, good b → measure b < fuel → measure b < fuel' → + Loop.bounded exhaust f fuel b = Loop.bounded exhaust' f fuel' b := by + intro fuel + induction fuel with + | zero => intro _ _ _ h; omega + | succ n ih => + intro fuel' b hg h h' + cases fuel' with + | zero => omega + | succ n' => + obtain ⟨r, hr, hgood⟩ := hstep b hg + simp only [Loop.bounded, hr, pure_bind] + cases r with + | done b' => rfl + | yield b' => + exact ih n' b' hgood.1 (by have := hgood.2; omega) (by have := hgood.2; omega) diff --git a/Loom/MonadUtil.lean b/Loom/MonadUtil.lean new file mode 100644 index 00000000..23abfe44 --- /dev/null +++ b/Loom/MonadUtil.lean @@ -0,0 +1,40 @@ +import Mathlib.Order.Basic +import Mathlib.Order.CompleteLattice.Basic + +universe u v w + + +/- Continuation monad definition -/ +abbrev Cont (t : Type v) (α : Type u) := (α -> t) -> t + +instance (t : Type v) : Monad (Cont t) where + pure x := fun f => f x + bind x f := fun g => x (fun a => f a g) + +def Cont.inv {t : Type v} {α : Type u} [BooleanAlgebra t] (wp : Cont t α) : Cont t α := + fun f => (wp fun x => (f x)ᶜ)ᶜ + +@[simp] +def Cont.monotone {t : Type v} {α : Type u} [Preorder t] (wp : Cont t α) := + ∀ (f f' : α -> t), (∀ a, f a ≤ f' a) → wp f ≤ wp f' + +structure W (t : Type v) [Preorder t] (α : Type u) where + wp : Cont t α + wp_montone : wp.monotone + +@[ext] +lemma W_ext (t : Type v) (α : Type u) [Preorder t] (w w' : W t α) : + w.wp = w'.wp → w = w' := by intros; cases w; cases w'; simp_all + +instance (t : Type v) [Preorder t] : Monad (W t) where + pure x := ⟨fun f => f x, by solve_by_elim⟩ + bind x f := ⟨fun g => x.wp (fun a => (f a).wp g), by simp; intros; solve_by_elim [W.wp_montone]⟩ + +instance {l σ : Type u} : MonadLift (Cont l) (Cont (σ -> l)) where + monadLift x := fun f s => x (f · s) + + + +-- class Logic (t : Type u) extends SemilatticeInf t where +-- sat : t -> Prop +-- sat_monotone : ∀ {p₁ p₂ : t}, p₁ ≤ p₂ -> sat p₁ -> sat p₂ diff --git a/Loom/README.md b/Loom/README.md new file mode 100644 index 00000000..b19b3b9f --- /dev/null +++ b/Loom/README.md @@ -0,0 +1,61 @@ +# Loom, vendored + +**Port in progress (branch loom-4.35).** All of upstream Loom (and its case studies) is under +vendor/loom. Built on Lean 4.35 so far: Defs, Instances/Basic (with DivM and its partial and +total correctness algebras), Instances/StateT, ExceptT, ReaderT, Gen, WP/Basic (with the loop, +lifting, ExceptT, StateT and ReaderT sections) and WP/Liberal; the lean_lib Loom lists the +built modules as roots. The VC tactic layer (DoNames', Options, Gen, Attr, Matcher, Tactic), +NonDetT, Meta, TacticAsync and the SMT layer are not ported yet and nothing builds them. + +Statements changed by the Lean 4.35 API: + +* `MAlgPartial.csup_lift` and `PartialCorrectness.wp_csup` take the chain proof + (`Lean.Order.CCPO.csup` now takes a proof of `chain`, not the set). +* `triple_forIn_range` and `triple_forIn_range_step1` are on `Std.Legacy.Range` (Lean renamed + `Std.Range`). +* The `ForIn m Lean.Loop Unit` instance's `forIn` no longer takes the loop value separately + (`ForIn.forIn`'s signature changed). + +Added (not upstream; candidates for an upstream PR): + +* `DivM.csup_eq`, `StateT.csup_apply`, `StateT.bot_apply`, `ReaderT.csup_apply`, + `ReaderT.bot_apply`: the supremum of a chain, now a choice, as the flat or pointwise one. +* `Instances/ExceptTErr.lean`: an error-aware algebra, `MAlgExceptErr` on `ExceptT ε m` with + assertions `(ε → l) → l`, and `MAlgExceptErrProp` on `Except ε` with `(ε → Prop) → Prop` + (and `MAlgDet`), whose weakest precondition takes the predicate an exception must meet. +* `WP/Variant.lean`: `Loop.bounded`, `Loop.whileBounded`, and the total-correctness rules + `triple_bounded` and `triple_while` (invariant plus a natural-number variant) for monads + that cannot diverge, with `bounded_eq_of_variant`. + +The sections below describe the earlier, partial vendoring. + +## Kept + +* `Loom/MonadUtil.lean`, `Loom/SpecMonad.lean`: unchanged. +* `Loom/MonadAlgebras/Defs.lean`: monad algebras (`MAlg`, `MAlgOrdered`, `MAlgDet`), logic + lifts and monad-transformer algebras. +* `Loom/MonadAlgebras/Instances/Basic.lean`: the algebra of `Id` on `Prop`, and the + `CCPOBot` classes. +* `Loom/MonadAlgebras/WP/Basic.lean`: `wp`, `triple` and their generic rules (`wp_pure`, + `wp_bind`, `wp_map`, `wp_cons`, `triple_*`, `wp_and`, `wp_or`, ...). + +## Changed for Lean 4.35 + +* `MAlgPartial.csup_lift` takes the chain proof explicitly, since `Lean.Order.CCPO.csup` now + takes a proof of `chain` rather than the set. +* The `LogicLiftT` composition instance's `lift_top` and `lift_bot`, and `MAlgLiftTTrans`'s + `μ_lift`, are reproved: their `simp` calls no longer make progress. +* `Loom.lean` imports only what is kept. + +## Dropped + +* `Instances/StateT.lean`, `ExceptT.lean`, `ReaderT.lean`, `Gen.lean`, and the matching + sections of `WP/Basic.lean` (loops, lifting, `ExceptT`, `StateT`, `ReaderT`, `Gen`): their + proofs depend on Lean 4.24's `simp` normal forms and on the old `CCPO` API throughout. + `SolidCore/Verify/Basic.lean` gives its own ordered algebra for the one stack it needs, + `StateT Storage (Except Revert)`. +* `DivM` and its partial- and total-correctness algebras (`Instances/Basic.lean`). +* `WP/Liberal.lean`, `WP/Gen.lean`, `WP/Attr.lean`, `WP/Tactic.lean`, `WP/Matcher.lean`, + `WP/DoNames'.lean`, `WP/Options.lean`, `Meta.lean`, `TacticAsync.lean`, `SMT.lean` and + `NonDetT`: the VC tactic layer, SMT (lean-auto, z3, cvc5) and nondeterminism. SolidCore's + generator computes weakest preconditions with `simp` and Loom's `wp` rules instead. diff --git a/Loom/SpecMonad.lean b/Loom/SpecMonad.lean new file mode 100644 index 00000000..ac3d4a5d --- /dev/null +++ b/Loom/SpecMonad.lean @@ -0,0 +1,57 @@ +import Mathlib.Order.Basic + +universe u v w + +variable (m : Type u -> Type w) (w : Type u -> Type v) + +class PreOrderFunctor where preord : (α : Type u) -> Preorder (w α) +instance [inst: (α : Type u) -> Preorder (w α)] : PreOrderFunctor w := ⟨inst⟩ +instance (α : Type u) [inst: PreOrderFunctor w] : Preorder (w α) := inst.preord α + +class MonadOrder extends Monad w, PreOrderFunctor w where + bind_le {α : Type u} {β : Type u} (x y : w α) (f g : α -> w β) : + x ≤ y → (∀ a, f a ≤ g a) → bind x f ≤ bind y g + +lemma lift_map {α : Type u} {β : Type u} (f : α -> β) (x : m α) + [Monad m] [Monad n] [LawfulMonad m] [LawfulMonad n] [MonadLiftT m n] [LawfulMonadLiftT m n] : + liftM (f <$> x) = f <$> liftM (n := n) x := by + simp + +instance [Monad m] : LawfulMonadLiftT m m where + monadLift_pure := by simp + monadLift_bind := by simp + +instance [Monad m] [LawfulMonad m] : LawfulMonadLiftT m (StateT σ m) where + monadLift_pure := by simp + monadLift_bind := by simp + +instance [Monad m] [LawfulMonad m] : LawfulMonadLiftT m (ReaderT σ m) where + monadLift_pure := by simp + monadLift_bind := by simp + +instance [Monad m] [LawfulMonad m] : LawfulMonadLiftT m (ExceptT ε m) where + monadLift_pure := by simp + monadLift_bind := by simp + +instance [Monad m] [LawfulMonad m] + [Monad n] [LawfulMonad n] [MonadLiftT m n] [inst: LawfulMonadLiftT m n] + [Monad p] [LawfulMonad p] [MonadLift n p] [inst':LawfulMonadLiftT n p] + : LawfulMonadLiftT m p where + monadLift_pure := by simp + monadLift_bind := by simp + +alias EffectObservation := LawfulMonadLift + + +-- class abbrev SpecMonad (m : Type u -> Type w) (w : Type u -> Type v) [Monad m] := +-- MonadOrder w, MonadLiftT m w, EffectObservation m w + +/- + Spec for myM : + - (A + E -> State -> Prop) -> State -> Prop + - (A -> State -> Prop) -> State -> Prop + θ_tot + - (A -> State -> Prop) -> State -> Prop + θ_part + + (A -> L) -> L + +-/ diff --git a/README.md b/README.md index 26893c7e..c5b057f5 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,15 @@ gate — see the exclusion register for the precise, versioned list. The multi-contract responder (v2) has a documented seam but is not part of the contest today. +## Follow-ups + +- Two SMT term ASTs coexist: `Verify/Obligation/Smt.lean` (`Srt`, `Op`, `Term`, the + obligations the certified contracts discharge) and `Verify/VC/Term.lean` (`Srt`, `Tm`, `Cmd`, + solar-verify's SMT-LIB transcripts). They should become one AST with one evaluator. This is + deferred: the frozen VC manifests (`Contracts/{ArrayMax,Vault}/Vc/manifest.json`, + `Verify/Discharge/frozen/PINS`) record the sha256 of `Smt.lean`, so merging them means + regenerating and re-checking those obligations against the new hash in one change. + ## License Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or diff --git a/SolidCore.lean b/SolidCore.lean index b192303d..2c77273c 100644 --- a/SolidCore.lean +++ b/SolidCore.lean @@ -157,3 +157,6 @@ import SolidCore.Witness.TupleNestedPush import SolidCore.Witness.WideSignedStorageCopy import SolidCore.Witness.EnumMappingKeyCleanup import SolidCore.Witness.EnumMappingKeyContract +import SolidCore.Witness.BytesNShiftConversionWidth +import SolidCore.Witness.AddmodArgOrder +import SolidCore.Witness.TupleStorageCopyOrder diff --git a/SolidCore/Refinement.lean b/SolidCore/Refinement.lean new file mode 100644 index 00000000..bcd583d3 --- /dev/null +++ b/SolidCore/Refinement.lean @@ -0,0 +1,38 @@ +import SolidCore.Refinement.Statement +import SolidCore.Refinement.Corpus +import SolidCore.Refinement.Compose +import SolidCore.Refinement.Spec +import SolidCore.Refinement.Behaviours +import SolidCore.Refinement.Fuel +import SolidCore.Refinement.Headline +import SolidCore.Refinement.Seq.Corpus +import SolidCore.Refinement.Solar.W1 +import SolidCore.Refinement.Solar.Lowering +import SolidCore.Refinement.Solar.Milestone +import SolidCore.Refinement.Solar.LoweringGeneric +import SolidCore.Refinement.Generic.MulTest +import SolidCore.Refinement.Generic.Total +import SolidCore.Refinement.NonVacuity + +/-! +# Refinement of solar's bytecode against SolidCore + +`SolidCore.Refinement.Statement` states what it means for runtime bytecode to +implement a SolidCore contract. Each contract in `scripts/refinement/corpus/` has +a module that proves it for solar's bytecode at the commit in +`scripts/refinement/solar-rev`. `scripts/refinement/check.sh` regenerates the +bytecode and checks every proof. + +`SolidCore.Refinement.Corpus` holds one generated proof per corpus contract, with +no hand-written part: `agree` compares both semantics on one call, slot by slot +on the finite set of slots either side touches, and `refines_of_all` turns +agreement on a list of calls into `Refines`. `Abi.calls` lists every call with +clean argument words, which `native_decide` checks in parts. +A contract with a `bytes`, array or struct parameter instead gets `refines_full` +on `Dyn.dynScope` (`SolidCore.Refinement.Dyn`): every canonical encoding within a +bound, checked the same way, and every malformed call data of any length below +`2 ^ 32`, which both sides reject, proved symbolically. +`C1.Refinement` is the hand-written proof for c1, kernel-checked on the EthLib +side and covering dirty argument words too; its SolidCore side uses `native_decide`, so it is in +the `SolidCoreNative` library, not this one. +-/ diff --git a/SolidCore/Refinement/Abi.lean b/SolidCore/Refinement/Abi.lean new file mode 100644 index 00000000..75da52fd --- /dev/null +++ b/SolidCore/Refinement/Abi.lean @@ -0,0 +1,111 @@ +import SolidCore.Refinement.Check +import EthLib.Execution.Proofs.Evm.Logic.NatCode + +/-! +# ABI calls of a contract's functions + +A function of the corpus takes parameters of small ABI types. `Param.values` lists +every word a well-formed ABI encoding can give a parameter: the clean words. +`calls` lists every call of a function with clean argument words, from each of a list +of initial storages, with no value. A proof about a contract checks `agree` on all of +them and gets `Refines` for that scope from `refines_of_all`. +-/ + +namespace SolidCore.Refinement.Abi + +open EthLib.Base + +/-- The ABI type of a parameter, as far as cleaning its word goes. -/ +inductive Param where + /-- `uintN`, with `N` bits. -/ + | uint (bits : Nat) + /-- `intN`, with `N` bits. -/ + | int (bits : Nat) + /-- `bool`. -/ + | bool + /-- An enum with `n` members. -/ + | enum (n : Nat) + deriving Repr, DecidableEq + +/-- Whether `v` is a word the ABI encoding of the parameter can give. -/ +def Param.clean : Param → Nat → Bool + | .uint b, v => v < 2 ^ b + | .int b, v => v < 2 ^ (b - 1) || (2 ^ 256 - 2 ^ (b - 1) ≤ v && v < 2 ^ 256) + | .bool, v => v < 2 + | .enum n, v => v < n + +/-- Every clean word of the parameter, in increasing order of the value it encodes. -/ +def Param.values : Param → List Nat + | .uint b => List.range (2 ^ b) + | .int b => ((List.range (2 ^ (b - 1))).map fun i => 2 ^ 256 - 2 ^ (b - 1) + i) ++ + List.range (2 ^ (b - 1)) + | .bool => [0, 1] + | .enum n => List.range n + +/-- The call data of a call of the function with selector `sel` on the argument words +`args`: the selector, then each word big-endian. -/ +def calldata (sel : Nat) (args : List Nat) : ByteArray := + ⟨(natToBytes 4 sel ++ args.flatMap (natToBytes 32)).toArray⟩ + +/-- Every list of clean argument words for the parameters. -/ +def tuples : List Param → List (List Nat) + | [] => [[]] + | p :: ps => p.values.flatMap fun v => (tuples ps).map (v :: ·) + +instance : Inhabited Call := ⟨{ calldata := .empty, callvalue := 0, storage := [] }⟩ + +/-- A function of a contract: its selector and its parameters. -/ +structure Fn where + /-- The function's selector. -/ + sel : Nat + /-- Its parameters, in order. -/ + params : List Param + +/-- Every call of a function in `fns` with clean argument words, from each initial +storage in `storages`, with no value. -/ +def calls (fns : List Fn) (storages : List (List (Nat × Nat))) : List Call := + storages.flatMap fun storage => fns.flatMap fun fn => (tuples fn.params).map fun args => + { calldata := calldata fn.sel args, callvalue := 0, storage } + +end SolidCore.Refinement.Abi + +namespace SolidCore.Refinement.Abi + +open SolidCore.Solidity SolidCore.Solidity.Source + +/-- The storage SolidCore's constructor of `contract` leaves, as (slot, value) pairs +sorted by slot, or none when it does not return. A call from it is a call to the +freshly deployed contract. -/ +def deployedStorage (fuel : Nat) (contract : TypeCheck.CheckedContract) : + Option (List (Nat × Nat)) := + let base := contract.core.context + let context := { base with sender := callerAddress, self := selfAddress, value := 0 } + match TypeCheck.CheckedContract.constructWithContext? fuel contract context + State.empty selfAddress 0 [] with + | some (CallResult.returned deployed _) => + some ((deployed.storage.toList.filter (·.2 != 0)).mergeSort (fun a b => a.1 ≤ b.1)) + | _ => none + +end SolidCore.Refinement.Abi + +namespace SolidCore.Refinement.Abi + +/-- Whether `p` holds of every element of `arr` whose index is `i` modulo `parts`. +A long check splits into `parts` of these, which separate modules can run at once. -/ +def checkPart {α : Type} [Inhabited α] (p : α → Bool) (arr : Array α) (parts i : Nat) : Bool := + (List.range arr.size).all fun j => j % parts != i || p arr[j]! + +theorem all_of_parts {α : Type} [Inhabited α] {p : α → Bool} {l : List α} {parts : Nat} + (hp : 0 < parts) (h : ∀ i < parts, checkPart p l.toArray parts i = true) : + l.all p = true := by + rw [List.all_eq_true] + intro x hx + obtain ⟨j, hj, rfl⟩ := List.getElem_of_mem hx + have := h (j % parts) (Nat.mod_lt _ hp) + simp only [checkPart, List.all_eq_true, List.mem_range, List.size_toArray, bne_iff_ne, ne_eq, + Bool.or_eq_true] at this + rcases this j hj with h' | h' + · exact absurd rfl h' + · simpa [List.getElem!_toArray, hj] using h' + +end SolidCore.Refinement.Abi diff --git a/SolidCore/Refinement/Axioms/Audit.lean b/SolidCore/Refinement/Axioms/Audit.lean new file mode 100644 index 00000000..07be68fc --- /dev/null +++ b/SolidCore/Refinement/Axioms/Audit.lean @@ -0,0 +1,83 @@ +import Lean + +/-! +# Axiom audit + +`#axiom_audit "out" "prefix"*` collects, with one memoized pass over the environment, the +axioms of every theorem and definition declared in a module whose name starts with one of the +prefixes, reports every declaration that depends on an axiom other than `propext`, +`Classical.choice` and `Quot.sound` (`sorryAx` and `Lean.ofReduceBool` among them), and writes +the source path of every module the importing file's environment contains to `out`, for the +closure grep in `scripts/refinement/axiom-audit.sh`. `#print axioms` stays the authority on each +headline theorem; this sweep covers the rest of their modules. +-/ + +namespace SolidCore.Refinement.AxiomAudit + +open Lean Elab Command + +/-- The constants a declaration's type and value mention (an inductive's constructors are reached +through the constructors' own names). -/ +def deps (ci : ConstantInfo) : Array Name := + let ty := ci.type.getUsedConstants + match ci with + | .defnInfo v => ty ++ v.value.getUsedConstants + | .thmInfo v => ty ++ v.value.getUsedConstants + | .opaqueInfo v => ty ++ v.value.getUsedConstants + | _ => ty + +/-- Every reachable constant's axioms, by an iterative depth-first pass with one memo. -/ +def axiomsOf (env : Environment) (roots : Array Name) : Std.HashMap Name NameSet := Id.run do + let mut memo : Std.HashMap Name NameSet := {} + let mut stack : Array (Name × Bool) := roots.map (·, false) + while 0 < stack.size do + let (n, expanded) := stack.back! + stack := stack.pop + if memo.contains n then continue + let some ci := env.find? n | memo := memo.insert n {}; continue + let ds := deps ci + if expanded then + let mut acc : NameSet := if ci matches .axiomInfo _ then ({} : NameSet).insert n else {} + for d in ds do + for a in memo.getD d {} do acc := acc.insert a + memo := memo.insert n acc + else + stack := stack.push (n, true) + for d in ds do + if !memo.contains d then stack := stack.push (d, false) + return memo + +def allowed : List Name := [`propext, `Classical.choice, `Quot.sound] + +elab "#axiom_audit " out:str prefixes:str* : command => do + let env ← getEnv + let ps := prefixes.toList.map (·.getString) + let mods := env.header.moduleNames + let inScope (n : Name) : Bool := Id.run do + let some i := env.getModuleIdxFor? n | return false + let m := (mods[i.toNat]!).toString + return ps.any (m.startsWith ·) + let targets := env.constants.map₁.fold (init := #[]) fun acc n ci => + if !n.isInternal && inScope n && (ci matches .thmInfo _ || ci matches .defnInfo _) then + acc.push n else acc + let memo := axiomsOf env targets + let mut bad := 0 + let mut thms := 0 + for n in targets do + if env.find? n matches some (.thmInfo _) then thms := thms + 1 + let ax := memo.getD n {} + let extra := ax.toList.filter (!allowed.contains ·) + if !extra.isEmpty then + bad := bad + 1 + logInfo m!"AXIOM-VIOLATION {n}: {extra}" + logInfo m!"axiom sweep: {targets.size} declarations ({thms} theorems) under {ps}, {bad} with axioms outside [propext, Classical.choice, Quot.sound]" + let sp ← getSrcSearchPath + let mut lines := #[] + for m in mods do + match ← sp.findModuleWithExt "lean" m with + | some p => lines := lines.push s!"{m} {p}" + | none => lines := lines.push s!"{m} ?" + IO.FS.writeFile out.getString (String.intercalate "\n" lines.toList ++ "\n") + logInfo m!"closure: {mods.size} modules written to {out.getString}" + +end SolidCore.Refinement.AxiomAudit diff --git a/SolidCore/Refinement/Axioms/C4.lean b/SolidCore/Refinement/Axioms/C4.lean new file mode 100644 index 00000000..4520019f --- /dev/null +++ b/SolidCore/Refinement/Axioms/C4.lean @@ -0,0 +1,23 @@ +import SolidCore.Refinement.Axioms.Audit +import SolidCore.Refinement.Solar.C4.Certified + +/-! Axiom pass, part 2 of 4: c4 against solar's c4 export (see `Main.lean`). -/ + +#print axioms SolidCore.Refinement.Solar.C4.certified +#print axioms SolidCore.Refinement.Solar.C4.certified_at +#print axioms SolidCore.Refinement.Solar.C4.certified_deployed +#print axioms SolidCore.Refinement.Solar.C4.certified_deployed_value +#print axioms SolidCore.Refinement.Solar.C4.certified_at_value +#print axioms SolidCore.Refinement.Solar.C4.satisfies_at +#print axioms SolidCore.Refinement.Solar.C4.lowering +#print axioms SolidCore.Refinement.Solar.C4.loweringAt +#print axioms SolidCore.Refinement.Solar.C4.certifiedAt +#print axioms SolidCore.Refinement.Solar.C4.lowering_generic +#print axioms SolidCore.Refinement.Solar.C4.loweringAt_generic +#print axioms SolidCore.Refinement.Solar.C4.lowering_value +#print axioms SolidCore.Refinement.Solar.C4.loweringAt_value +#print axioms SolidCore.Refinement.Solar.C4.check_rejects_bad +#print axioms SolidCore.Refinement.Solar.C4.stage +#print axioms SolidCore.Refinement.Solar.C4.stageAll + +#axiom_audit ".lake/axiom-closure-c4.txt" "SolidCore.Refinement.Solar" "SolidCore.Refinement.Generic" diff --git a/SolidCore/Refinement/Axioms/Contracts.lean b/SolidCore/Refinement/Axioms/Contracts.lean new file mode 100644 index 00000000..aa41f55f --- /dev/null +++ b/SolidCore/Refinement/Axioms/Contracts.lean @@ -0,0 +1,61 @@ +import SolidCore.Refinement.Axioms.Audit +import Contracts.Counter.Headline +import Contracts.Counter.EndToEnd +import Contracts.Counter.Final +import Contracts.Counter.ShapeExport +import Contracts.Counter.Verdict +import Contracts.Counter.VC.Inc +import Contracts.Counter.VC.Get +import Contracts.Counter.VC.Mutants +import Contracts.Token.VC.Burn +import Contracts.Token.VC.Transfer +import Contracts.Token.VC.Mutants +import Contracts.Counter.Exports +import Contracts.Counter.SpecTree +import Contracts.Counter.VC.Discharged +import Contracts.Counter.VC.ScriptEndToEnd +import SolidCore.Refinement.Solar.EndToEnd +import Verify.LoomAxioms +import Verify.Spec.TrustedBase.Axioms + +/-! Axiom pass, part 6: the per-contract headlines under Contracts/ (Counter from source spec to +solar's bytecode, and the Counter and Token verification conditions), with the Loom and trusted +base pieces they build on. Every `#print axioms` below must report a subset of [propext, +Classical.choice, Quot.sound], and the sweep must report no violation. Run with +`scripts/refinement/axiom-audit.sh`. -/ + +-- Counter, source spec to bytecode. +#print axioms SolidCore.Refinement.Solar.Counter.Headline.spec_holds_of_bytecode +#print axioms SolidCore.Refinement.Solar.Counter.Headline.wrong_fails +#print axioms SolidCore.Refinement.Solar.Counter.EndToEnd.inc_spec_bytecode +#print axioms SolidCore.Refinement.Solar.Counter.EndToEnd.get_spec_bytecode +#print axioms SolidCore.Refinement.Solar.Counter.Final.certified +#print axioms SolidCore.Refinement.Solar.Counter.Final.certified_trace +#print axioms SolidCore.Refinement.Solar.Counter.ShapeExport.published +#print axioms SolidCore.Refinement.Solar.Counter.ShapeExport.nonvacuous +#print axioms SolidCore.Refinement.Solar.Counter.Verdict.bytecode_spec_of_verdict +#print axioms SolidCore.Refinement.Solar.Counter.Verdict.bytecode_of_triple + +-- Verification conditions. +#print axioms SolidCore.Verify.VC.Counter.inc_triple +#print axioms SolidCore.Verify.VC.Counter.get_triple +#print axioms SolidCore.Verify.VC.Counter.srcMut_rejected +#print axioms SolidCore.Verify.VC.Counter.specMut_rejected +#print axioms SolidCore.Verify.VC.Token.burn_triple +#print axioms SolidCore.Verify.VC.Token.transfer_triple + +-- Scripts discharged in the kernel and carried to bytecode. +#print axioms SolidCore.Verify.VC.dischargeScript_sound +#print axioms SolidCore.Verify.VC.bytecode_of_discharged +#print axioms SolidCore.Verify.VC.bytecode_of_checked +#print axioms SolidCore.Verify.VC.Counter.Discharged.script_valid +#print axioms SolidCore.Verify.VC.Counter.inc_bytecode_of_script +#print axioms SolidCore.Refinement.Solar.Counter.SpecTree.inc_spec_bytecode +#print axioms Contracts.Counter.deploys + +-- The generic composition of the backend stages with the assembler checks. +#print axioms SolidCore.Refinement.Solar.EndToEnd.stage_of_check +#print axioms SolidCore.Refinement.Solar.EndToEnd.within_of_checkL +#print axioms SolidCore.Refinement.Solar.EndToEnd.holds_of_checkL + +#axiom_audit ".lake/axiom-closure-contracts.txt" "Contracts" "Verify" "Loom" diff --git a/SolidCore/Refinement/Axioms/CounterGeneric.lean b/SolidCore/Refinement/Axioms/CounterGeneric.lean new file mode 100644 index 00000000..59ff490a --- /dev/null +++ b/SolidCore/Refinement/Axioms/CounterGeneric.lean @@ -0,0 +1,12 @@ +import SolidCore.Refinement.Axioms.Audit +import SolidCore.Refinement.Solar.Counter.LoweringGeneric + +/-! Axiom pass, part 5 of 5: counter's generic source stage, which declares names that +`Counter.SpecAt` and `Counter.LoweringAt` also declare (see `Main.lean`). -/ + +#print axioms SolidCore.Refinement.Solar.Counter.lowering_generic +#print axioms SolidCore.Refinement.Solar.Counter.loweringAt +#print axioms SolidCore.Refinement.Solar.Counter.loweringAtValue +#print axioms SolidCore.Refinement.Solar.Counter.check_rejects_bad + +#axiom_audit ".lake/axiom-closure-countergeneric.txt" "SolidCore.Refinement.Solar" "SolidCore.Refinement.Generic" diff --git a/SolidCore/Refinement/Axioms/Lanes.lean b/SolidCore/Refinement/Axioms/Lanes.lean new file mode 100644 index 00000000..391f0f93 --- /dev/null +++ b/SolidCore/Refinement/Axioms/Lanes.lean @@ -0,0 +1,133 @@ +import SolidCore.Refinement.Axioms.Audit +import SolidCore.Refinement.Generic.CallNode +import SolidCore.Refinement.Generic.Loop +import SolidCore.Refinement.Generic.LoopErr +import SolidCore.Refinement.Generic.LoopRun +import SolidCore.Refinement.Generic.LoopSeq +import SolidCore.Refinement.Generic.LoopStmt +import SolidCore.Refinement.Generic.MirNoLog +import SolidCore.Refinement.Solar.AssembleCallValue +import SolidCore.Refinement.Solar.AssembleCallValueEffect +import SolidCore.Refinement.Solar.AssembleCallValueZero +import SolidCore.Refinement.Solar.AssembleCodeCopy +import SolidCore.Refinement.Solar.AssembleCreate +import SolidCore.Refinement.Solar.AssembleCreateBack +import SolidCore.Refinement.Solar.AssembleCtx +import SolidCore.Refinement.Solar.AssembleCtxExample +import SolidCore.Refinement.Solar.AssembleCtxTrack +import SolidCore.Refinement.Solar.AssembleCtxCall +import SolidCore.Refinement.Solar.AssembleRevert +import SolidCore.Refinement.Solar.AssembleRevertCall +import SolidCore.Refinement.Solar.AssembleRevertCut +import SolidCore.Refinement.Solar.AssembleRevertCutExample +import SolidCore.Refinement.Solar.AssembleRevertExample +import SolidCore.Refinement.Solar.EthLibErr +import SolidCore.Refinement.Solar.EthLibErrLow +import SolidCore.Refinement.Solar.AssembleCreateExample +import SolidCore.Refinement.Solar.AssembleCreateCut +import SolidCore.Refinement.Solar.AssembleCreateRun +import SolidCore.Refinement.Solar.AssembleCallValueSeg +import SolidCore.Refinement.Solar.AssembleCallValueZeroSeg +import SolidCore.Refinement.Solar.AssembleCreateSeg +import SolidCore.Refinement.Solar.AssembleCreateSegOracle +import SolidCore.Refinement.Solar.AssembleCreateCutQ +import SolidCore.Refinement.Solar.AssembleCreateSegF +import SolidCore.Refinement.Solar.AssembleCreateRunF +import SolidCore.Solidity.StagedK +import SolidCore.Solidity.StagedL + +/-! Axiom pass for the reusable lane theorems: source loops with ranking certificates and their +error paths (`Generic/Loop*`), the low-level call node (`Generic/CallNode`), MIR runs without +logs (`Generic/MirNoLog`), the context-sensitive checker (`AssembleCtx*`), revert data +(`AssembleRevert*`, `EthLibErr*`), and CODECOPY, CREATE2 and CALL with value +(`AssembleCodeCopy`, `AssembleCreate*`, `AssembleCallValue*`). Every `#print axioms` below must +report a subset of [propext, Classical.choice, Quot.sound], and the sweep must report no +violation. Run with `scripts/refinement/axiom-audit.sh`. -/ + +-- Source loops: ranking certificates, termination and the error paths. +#print axioms SolidCore.Refinement.Generic.Loop.forLoop_of_cert +#print axioms SolidCore.Refinement.Generic.Loop.forLoop_never +#print axioms SolidCore.Refinement.Generic.Loop.forLoop_err +#print axioms SolidCore.Refinement.Generic.Loop.runtime_run_err +#print axioms SolidCore.Refinement.Generic.Loop.runtime_run_clean +#print axioms SolidCore.Refinement.Generic.Loop.eval_incField +#print axioms SolidCore.Refinement.Generic.Loop.eval_incVar + +-- Source call node and MIR without logs. +#print axioms SolidCore.Refinement.CallNode.eval_lowLevelCall +#print axioms SolarTV.MIR.Lowered.Module.ends_logs + +-- Context-sensitive checker. +#print axioms SolidCore.Refinement.Solar.AssembleCtx.withinRun_of_checkX +#print axioms SolidCore.Refinement.Solar.AssembleCtx.assembly_of_checkX +#print axioms SolidCore.Refinement.Solar.AssembleCtx.withinRun_mir_of_checkX +#print axioms SolidCore.Refinement.Solar.AssembleCtxExample.bytecode +#print axioms SolidCore.Refinement.Solar.AssembleCtx.assembly_of_checkXB +#print axioms SolidCore.Refinement.Solar.AssembleCtx.assembly_of_checkXB_norm + +-- Revert data. +#print axioms EthLib.Execution.Evm.RevertErr.step_good +#print axioms EthLib.Execution.Evm.RevertErr.SpecG.lowE +#print axioms SolidCore.Refinement.Solar.AssembleLoop.withinR_of_checkL +#print axioms SolidCore.Refinement.Solar.AssembleRevertCut.withinRunR_of_checkC +#print axioms SolidCore.Refinement.Solar.AssembleRevertCut.withinRunR_mir_of_checkC +#print axioms SolidCore.Refinement.Solar.AssembleRevertCall.runs_of_checkCBR +#print axioms SolidCore.Refinement.Solar.AssembleRevertExample.bytecode +#print axioms SolidCore.Refinement.Solar.AssembleRevertExample.mutant_fails +#print axioms SolidCore.Refinement.Solar.AssembleRevertCutExample.bytecode + +-- CODECOPY, CREATE2 and CALL with value. +#print axioms SolidCore.Refinement.Solar.AssembleCodeCopy.codecopy_dyn +#print axioms SolidCore.Refinement.Solar.AssembleCodeCopy.codeOracle_ok +#print axioms SolidCore.Refinement.Solar.AssembleCreate.create2Address_toU256 +#print axioms SolidCore.Refinement.Solar.AssembleCreateBack.create2_back +#print axioms SolidCore.Refinement.Solar.AssembleCallValue.callValue_back +#print axioms SolidCore.Refinement.Solar.AssembleCallValueZero.call0_back +#print axioms SolidCore.Refinement.Solar.AssembleCallValueEffect.call_effectW +#print axioms SolidCore.Refinement.Solar.AssembleCallValueEffect.create2_effectW + +-- CREATE2, CALL and CODECOPY as cuts of a run, and their run oracle. +#print axioms SolidCore.Refinement.Solar.AssembleCreateSeg.create2_cut +#print axioms SolidCore.Refinement.Solar.AssembleCreateSeg.create2_apply +#print axioms SolidCore.Refinement.Solar.AssembleCreateSeg.codecopy_cut +#print axioms SolidCore.Refinement.Solar.AssembleCallValueSeg.callValue_cut +#print axioms SolidCore.Refinement.Solar.AssembleCallValueZeroSeg.call0_cut +#print axioms SolidCore.Refinement.Solar.AssembleCreateSegOracle.apply_call_createOracle +#print axioms SolidCore.Refinement.Solar.AssembleCreateSegOracle.rdRel_read + +-- The checker cut at CALL, CREATE2 and CODECOPY, and runs with creations. +#print axioms SolidCore.Refinement.Solar.AssembleLoop.exec_simC +#print axioms SolidCore.Refinement.Solar.AssembleCreateCut.exec_codecopy +#print axioms SolidCore.Refinement.Solar.AssembleCreateRun.exec_F +#print axioms SolidCore.Refinement.Solar.AssembleCreateRun.FO_ok +#print axioms SolidCore.Refinement.Solar.AssembleCreateRun.exec_gasF +#print axioms SolidCore.Refinement.Solar.AssembleCreateRun.create2_table +#print axioms SolidCore.Refinement.Solar.AssembleCreateExample.check_ok +#print axioms SolidCore.Refinement.Solar.AssembleCreateExample.mutantSalt_fails +#print axioms SolidCore.Refinement.Solar.AssembleCreateExample.nocreates_fails + +-- Staged source-translation checks: kernel-cheap equal forms and the lemmas that assemble a +-- contract's translation from its separately checked context, function groups and assembly. +#print axioms SolidCore.Solidity.Executable.TypeEnv.shadowedStateNames_eq_K +#print axioms SolidCore.Solidity.Executable.stringDecEq_eq_K +#print axioms SolidCore.Solidity.Executable.toByteArray_eq_K +#print axioms SolidCore.Solidity.Executable.ContractDecl.toCoreFromOrders?_of_stages +#print axioms SolidCore.Solidity.Executable.FromOrdersCtx.group?_of_pairs +#print axioms SolidCore.Solidity.Executable.FunctionDecl.toCore_eq_staged +#print axioms SolidCore.Solidity.Executable.FromOrdersCtx.pairF_of_stages + +-- CALL and CREATE2 with callee frames pinned to the caller state, read segments over the run +-- oracle with creations, and the checker's runs with calls and creations (checkCF). +#print axioms SolidCore.Refinement.Solar.AssembleCreateCutQ.call0_cutQ +#print axioms SolidCore.Refinement.Solar.AssembleCreateCutQ.callValue_cutQ +#print axioms SolidCore.Refinement.Solar.AssembleCreateCutQ.create2_cutQ +#print axioms SolidCore.Refinement.Solar.AssembleCreateSegF.segF +#print axioms SolidCore.Refinement.Solar.AssembleCreateRunF.runs_of_checkCF +#print axioms SolidCore.Refinement.Solar.AssembleCreateRunF.withinRun_of_checkCF +#print axioms SolidCore.Refinement.Solar.AssembleCreateRunF.assembly_of_checkCF +#print axioms SolidCore.Refinement.Solar.AssembleCreateRunF.withinRun_mir_of_checkCF +#print axioms SolidCore.Refinement.Solar.AssembleCreateRunF.holds_of_checkCF +#print axioms SolidCore.Refinement.Solar.AssembleCreateRunF.example_runs +#print axioms SolidCore.Refinement.Solar.AssembleCreateRunF.example_mutants + +#axiom_audit ".lake/axiom-closure-lanes.txt" "SolidCore.Refinement.Solar" "SolidCore.Refinement.Generic" "SolarTV" "SolidCore.Solidity.Staged" diff --git a/SolidCore/Refinement/Axioms/Main.lean b/SolidCore/Refinement/Axioms/Main.lean new file mode 100644 index 00000000..7deebaa5 --- /dev/null +++ b/SolidCore/Refinement/Axioms/Main.lean @@ -0,0 +1,94 @@ +import SolidCore.Refinement.Axioms.Audit +import SolidCore.Refinement.Headline +import SolidCore.Refinement.Solar.Milestone +import SolidCore.Refinement.Solar.W1Value +import SolidCore.Refinement.Solar.LoweringGeneric +import SolidCore.Refinement.Solar.Sequences +import SolidCore.Refinement.Solar.Counter.Milestone +import SolidCore.Refinement.Solar.Counter.Sequences +import SolidCore.Refinement.Solar.Counter.Every +import SolidCore.Refinement.Solar.Counter.EverySeq +import SolidCore.Refinement.Solar.Counter.Value +import SolidCore.Refinement.Solar.Counter.NegativeAt +import SolidCore.Refinement.Solar.Counter.NegativeValue +import SolidCore.Refinement.Solar.Bank.Certified +import SolidCore.Refinement.Solar.Bank.Mutants +import SolidCore.Refinement.Solar.Events.Certified + +/-! Axiom pass, part 1 of 5: the headline theorems, w1/w5, counter, bank and events. The milestone +exports of w1, w4, c4 and mulx all declare `SolarTV.Export.Main`, so one environment can hold only +one of them: w1's is here, and `C4.lean`, `MulX.lean` and `W4.lean` hold the others. +counter's generic source stage (`Counter.LoweringGeneric`) declares names that +`Counter.SpecAt` and `Counter.LoweringAt` also declare, so `CounterGeneric.lean` holds it. Every +`#print axioms` below must report a subset of [propext, Classical.choice, Quot.sound], and the +sweep must report no violation. Run with `scripts/refinement/axiom-audit.sh`. -/ + +-- Headline. +#print axioms SolidCore.Refinement.Headline.c1 +#print axioms SolidCore.Refinement.Headline.w1 +#print axioms SolidCore.Refinement.Headline.w4 +#print axioms SolidCore.Refinement.Headline.c4 +#print axioms SolidCore.Refinement.Headline.w5 +#print axioms SolidCore.Refinement.Headline.w1_staged +-- w1 and w5 (solar's w1 export). +#print axioms SolidCore.Refinement.Solar.W1.certified +#print axioms SolidCore.Refinement.Solar.W1.certifiedAt +#print axioms SolidCore.Refinement.Solar.W1.certifiedValue +#print axioms SolidCore.Refinement.Solar.W1.certifiedSeq +#print axioms SolidCore.Refinement.Solar.W1.certifiedAt_single +#print axioms SolidCore.Refinement.Solar.W1.lowering +#print axioms SolidCore.Refinement.Solar.W1.loweringAt +#print axioms SolidCore.Refinement.Solar.W1.lowering_generic +#print axioms SolidCore.Refinement.Solar.W1.loweringAt_generic +#print axioms SolidCore.Refinement.Solar.W1.lowering_value +#print axioms SolidCore.Refinement.Solar.W1.loweringAt_value +#print axioms SolidCore.Refinement.Solar.W1.loweringValue +#print axioms SolidCore.Refinement.Solar.W1.lowering_rejects_bad +#print axioms SolidCore.Refinement.Solar.W1.loweringValue_rejects +#print axioms SolidCore.Refinement.Solar.W1.check_rejects_bad +-- counter. +#print axioms SolidCore.Refinement.Solar.Counter.certified +#print axioms SolidCore.Refinement.Solar.Counter.certifiedAt +#print axioms SolidCore.Refinement.Solar.Counter.certifiedValue +#print axioms SolidCore.Refinement.Solar.Counter.certifiedEvery +#print axioms SolidCore.Refinement.Solar.Counter.certifiedSeqEvery +#print axioms SolidCore.Refinement.Solar.Counter.certifiedSeq +#print axioms SolidCore.Refinement.Solar.Counter.certifiedAt_single +#print axioms SolidCore.Refinement.Solar.Counter.total +#print axioms SolidCore.Refinement.Solar.Counter.lowering +#print axioms SolidCore.Refinement.Solar.Counter.loweringAt +#print axioms SolidCore.Refinement.Solar.Counter.loweringEvery +#print axioms SolidCore.Refinement.Solar.Counter.loweringValue +#print axioms SolidCore.Refinement.Solar.Counter.stageAt +#print axioms SolidCore.Refinement.Solar.Counter.lowering_rejects_bad +#print axioms SolidCore.Refinement.Solar.Counter.loweringAt_rejects +#print axioms SolidCore.Refinement.Solar.Counter.stageAt_rejects +#print axioms SolidCore.Refinement.Solar.Counter.assemblyValue_rejects +#print axioms SolidCore.Refinement.Solar.Counter.mutantAdd_no_walk +#print axioms SolidCore.Refinement.Solar.Counter.mutantStore_no_walk +-- bank. +#print axioms SolidCore.Refinement.Solar.Bank.certified +#print axioms SolidCore.Refinement.Solar.Bank.certifiedValue +#print axioms SolidCore.Refinement.Solar.Bank.certifiedManifest +#print axioms SolidCore.Refinement.Solar.Bank.certified' +#print axioms SolidCore.Refinement.Solar.Bank.certifiedValue' +#print axioms SolidCore.Refinement.Solar.Bank.certifiedManifest' +#print axioms SolidCore.Refinement.Solar.Bank.ethKeccakAgree +#print axioms SolidCore.Refinement.Solar.Bank.lowering +#print axioms SolidCore.Refinement.Solar.Bank.loweringValue +#print axioms SolidCore.Refinement.Solar.Bank.mutant_hex_rejected +#print axioms SolidCore.Refinement.Solar.Bank.check_rejects_slot +#print axioms SolidCore.Refinement.Solar.Bank.check_rejects_caller +#print axioms SolidCore.Refinement.Solar.Bank.check_rejects_topic +-- events. +#print axioms SolidCore.Refinement.Solar.Events.certified +#print axioms SolidCore.Refinement.Solar.Events.certifiedValue +#print axioms SolidCore.Refinement.Solar.Events.certifiedManifest +#print axioms SolidCore.Refinement.Solar.Events.lowering +#print axioms SolidCore.Refinement.Solar.Events.loweringValue +#print axioms SolidCore.Refinement.Solar.Events.mutant_hex_rejected +#print axioms SolidCore.Refinement.Solar.Events.check_rejects_caller +#print axioms SolidCore.Refinement.Solar.Events.check_rejects_topic +#print axioms SolidCore.Refinement.Solar.Events.check_rejects_order + +#axiom_audit ".lake/axiom-closure-main.txt" "SolidCore.Refinement.Headline" "SolidCore.Refinement.Solar" "SolidCore.Refinement.Keccak" "SolidCore.Refinement.Generic" diff --git a/SolidCore/Refinement/Axioms/MulX.lean b/SolidCore/Refinement/Axioms/MulX.lean new file mode 100644 index 00000000..e9c19f45 --- /dev/null +++ b/SolidCore/Refinement/Axioms/MulX.lean @@ -0,0 +1,20 @@ +import SolidCore.Refinement.Axioms.Audit +import SolidCore.Refinement.Solar.MulX.Certified + +/-! Axiom pass, part 3 of 4: mulx against solar's mulx export (see `Main.lean`). -/ + +#print axioms SolidCore.Refinement.Solar.MulX.certified +#print axioms SolidCore.Refinement.Solar.MulX.certified_at +#print axioms SolidCore.Refinement.Solar.MulX.certified_deployed +#print axioms SolidCore.Refinement.Solar.MulX.certified_deployed_value +#print axioms SolidCore.Refinement.Solar.MulX.certified_at_value +#print axioms SolidCore.Refinement.Solar.MulX.lowering +#print axioms SolidCore.Refinement.Solar.MulX.loweringAt +#print axioms SolidCore.Refinement.Solar.MulX.loweringValue +#print axioms SolidCore.Refinement.Solar.MulX.loweringAtValue +#print axioms SolidCore.Refinement.Solar.MulX.check_rejects_unchecked +#print axioms SolidCore.Refinement.Solar.MulX.check_rejects_add +#print axioms SolidCore.Refinement.Solar.MulX.checkValue_rejects_payable +#print axioms SolidCore.Refinement.Solar.MulX.stageAll + +#axiom_audit ".lake/axiom-closure-mulx.txt" "SolidCore.Refinement.Solar" "SolidCore.Refinement.Generic" diff --git a/SolidCore/Refinement/Axioms/Token.lean b/SolidCore/Refinement/Axioms/Token.lean new file mode 100644 index 00000000..f9fb8e12 --- /dev/null +++ b/SolidCore/Refinement/Axioms/Token.lean @@ -0,0 +1,16 @@ +import SolidCore.Refinement.Axioms.Audit +import Contracts.Token.EndToEnd +import Contracts.Token.Exports +import Contracts.Token.VC.FromScript + +/-! Axiom pass, the Token headline from solar-verify's spec to solar's bytecode, in its own +environment (its exported stages share names with the other contracts'). Run with +`scripts/refinement/axiom-audit.sh`. -/ + +#print axioms Contracts.Token.spec_holds_of_bytecode +#print axioms Contracts.Token.burn_spec_bytecode +#print axioms Contracts.Token.certified +#print axioms SolidCore.Verify.VC.Token.Discharged.script_valid +#print axioms SolidCore.Verify.VC.Token.transfer_triple_of_script + +#axiom_audit ".lake/axiom-closure-token.txt" "Contracts.Token" "SolidCore.Refinement.Solar" diff --git a/SolidCore/Refinement/Axioms/VerifyCounter.lean b/SolidCore/Refinement/Axioms/VerifyCounter.lean new file mode 100644 index 00000000..130946bd --- /dev/null +++ b/SolidCore/Refinement/Axioms/VerifyCounter.lean @@ -0,0 +1,21 @@ +import SolidCore.Refinement.Axioms.Audit +import Contracts.VerifyCounter.Bytecode +import Contracts.VerifyCounter.StageMir +import Contracts.VerifyCounter.StageSource +import Contracts.VerifyCounter.ShapeSource +import Contracts.VerifyCounter.SourceMutant + +/-! Axiom pass, the VerifyCounter headline from solar-verify's spec to solar's bytecode, and the +bump shape certified from SolidCore's source (with the mutant that does not terminate), in its own +environment (its exported stages share names with the other contracts'). Run with +`scripts/refinement/axiom-audit.sh`. -/ + +#print axioms SolidCore.Refinement.Solar.VerifyCounter.spec_holds_of_bytecode +#print axioms SolidCore.Refinement.Solar.VerifyCounter.spec_holds_of_bytecode_generic +#print axioms SolarTV.Milestone.VerifyCounter.Bump.xstage0_ends +#print axioms Contracts.VerifyCounter.Source.mir_eq +#print axioms Contracts.VerifyCounter.ShapeSource.published +#print axioms Contracts.VerifyCounter.Mutant.not_terminates +#print axioms Contracts.VerifyCounter.Mutant.not_certified + +#axiom_audit ".lake/axiom-closure-verifycounter.txt" "Contracts.VerifyCounter" "SolidCore.Refinement.Solar" "SolidCore.Refinement.Generic" diff --git a/SolidCore/Refinement/Axioms/W4.lean b/SolidCore/Refinement/Axioms/W4.lean new file mode 100644 index 00000000..e75f5ffc --- /dev/null +++ b/SolidCore/Refinement/Axioms/W4.lean @@ -0,0 +1,15 @@ +import SolidCore.Refinement.Axioms.Audit +import SolidCore.Refinement.Solar.W4.Milestone + +/-! Axiom pass, part 4 of 4: w4 against solar's w4 export (see `Main.lean`). -/ + +#print axioms SolidCore.Refinement.Solar.W4.certified +#print axioms SolidCore.Refinement.Solar.W4.certifiedAt +#print axioms SolidCore.Refinement.Solar.W4.stage +#print axioms SolidCore.Refinement.Solar.W4.stageAt +#print axioms SolidCore.Refinement.Solar.W4.lowering +#print axioms SolidCore.Refinement.Solar.W4.loweringAt +#print axioms SolidCore.Refinement.Solar.W4.loweringValue +#print axioms SolidCore.Refinement.Solar.W4.loweringAtValue + +#axiom_audit ".lake/axiom-closure-w4.txt" "SolidCore.Refinement.Solar" "SolidCore.Refinement.Generic" diff --git a/SolidCore/Refinement/Behaviours.lean b/SolidCore/Refinement/Behaviours.lean new file mode 100644 index 00000000..2217f4a1 --- /dev/null +++ b/SolidCore/Refinement/Behaviours.lean @@ -0,0 +1,374 @@ +import SolidCore.Refinement.Spec + +/-! +# Behaviours, totality and the direction of refinement + +`Stage A B p q scope` (solar's `SolarTV.Stage`) is a forward, partial statement: every +observable the source `p` gives on a call in `scope`, the target `q` gives too. On a call +where `p` gives nothing (it runs out of fuel, diverges, or uses something its semantics leaves +undefined) a stage says nothing about `q` at all, so a stage from a source that never finishes +holds for every target (`Stage.of_never`). A chain of stages is therefore only as strong as +the totality of its first source. + +This module states what the end-to-end theorems actually need and proves how the three forms +relate, for semantics whose `run` is a function (every `Sem`), so each program has at most +one observable per call: + +* `Defined S p scope`: `p` finishes every call of `scope`. +* `Backward A B p q scope`: every observable of the target is an observable of the source + (target behaviours ⊆ source behaviours, the direction a user of compiled code relies on). Since + an `Observable` is success, output (return or revert data), logs and final storage, this + covers reverts and their data, return data, logs and storage at once. +* `Total A B p q scope`: on every call of `scope` both sides finish with the same observable. + `Refines` is `Total (solidCore fuel) ethLib` (`refines_iff_total`). + +`total_iff_stage` and `total_iff_backward`: `Total` is a stage whose source is defined on the +scope, and equally a backward simulation whose target is defined on it. `Total.trans` and +`Backward.trans` compose. `Satisfies.total_of_stage` is the point of the module: a stage whose +source satisfies a total specification is `Total` on the specified calls, so +`bytecode_total_of_stages` gives target ⊆ source end to end, with no vacuous case. + +Fuel. SolidCore's `Source.run fuel` returns `none` when the statement fuel runs out, so a run that +runs out of fuel refutes `Total`, `Refines` and `Satisfies` rather than satisfying them; solar's +MIR and EVM IR semantics take the end some fuel reaches (`SolarTV.Machine.Layer.result`), so they +have no fuel cut-off at all. EthLib's `Target.run` is bounded by gas: running out of gas is a failed +call, an `Observable` with `success = false`, never `none`; a theorem at `gasLimit` where the source +succeeds must show the bytecode does not run out. + +Failures. `ethLib` and `solidCore` both satisfy solar's `Sem.FailureConvention` (a failed call logs +nothing and keeps the call's storage; `ethLib_failureConvention`, `solidCore_failureConvention`), +and `Total` and `Backward` carry it from source to target. + +Discrimination. The relations are not trivial: on the semantics `Fixed` whose programs are their own +observables, a stage between two programs that differ in exactly one field of `Observable` +(success, output, logs or one storage slot) is false (`stage_rejects_*`). A relation that related +everything would prove those false statements' negations false, so these theorems would not check. +-/ + +namespace SolidCore.Refinement + +variable {A B C : Sem} + +/-- `p` finishes every call of `scope`. -/ +def Defined (S : Sem) (p : S.Prog) (scope : Call → Prop) : Prop := + ∀ call, scope call → (S.run p call).isSome + +/-- Every observable `q` gives on a call of `scope` is the observable `p` gives: the target's +behaviours are among the source's. -/ +def Backward (A B : Sem) (p : A.Prog) (q : B.Prog) (scope : Call → Prop) : Prop := + ∀ call, scope call → ∀ obs, B.run q call = some obs → A.run p call = some obs + +/-- On every call of `scope` both programs finish, with the same observable. -/ +def Total (A B : Sem) (p : A.Prog) (q : B.Prog) (scope : Call → Prop) : Prop := + ∀ call, scope call → ∃ obs, A.run p call = some obs ∧ B.run q call = some obs + +/-! ## The three forms -/ + +theorem Total.stage {p : A.Prog} {q : B.Prog} {scope : Call → Prop} (h : Total A B p q scope) : + Stage A B p q scope := by + intro call hc obs hrun + obtain ⟨obs', h1, h2⟩ := h call hc + rw [hrun] at h1 + cases h1 + exact h2 + +theorem Total.backward {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (h : Total A B p q scope) : Backward A B p q scope := by + intro call hc obs hrun + obtain ⟨obs', h1, h2⟩ := h call hc + rw [hrun] at h2 + cases h2 + exact h1 + +theorem Total.source_defined {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (h : Total A B p q scope) : Defined A p scope := by + intro call hc + obtain ⟨obs, h1, -⟩ := h call hc + simp [h1] + +theorem Total.target_defined {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (h : Total A B p q scope) : Defined B q scope := by + intro call hc + obtain ⟨obs, -, h2⟩ := h call hc + simp [h2] + +/-- A total refinement is exactly a stage whose source finishes on the scope. -/ +theorem total_iff_stage {p : A.Prog} {q : B.Prog} {scope : Call → Prop} : + Total A B p q scope ↔ Stage A B p q scope ∧ Defined A p scope := by + refine ⟨fun h => ⟨h.stage, h.source_defined⟩, fun ⟨st, df⟩ call hc => ?_⟩ + obtain ⟨obs, hobs⟩ := Option.isSome_iff_exists.mp (df call hc) + exact ⟨obs, hobs, st call hc obs hobs⟩ + +/-- A total refinement is exactly a backward simulation whose target finishes on the scope. -/ +theorem total_iff_backward {p : A.Prog} {q : B.Prog} {scope : Call → Prop} : + Total A B p q scope ↔ Backward A B p q scope ∧ Defined B q scope := by + refine ⟨fun h => ⟨h.backward, h.target_defined⟩, fun ⟨bw, df⟩ call hc => ?_⟩ + obtain ⟨obs, hobs⟩ := Option.isSome_iff_exists.mp (df call hc) + exact ⟨obs, bw call hc obs hobs, hobs⟩ + +/-- A stage from a source that finishes on the scope is a backward simulation: every target +observable is the source's. -/ +theorem Stage.backward_of_defined {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (st : Stage A B p q scope) (df : Defined A p scope) : Backward A B p q scope := + (total_iff_stage.mpr ⟨st, df⟩).backward + +/-! ## Composition -/ + +theorem Total.trans {p : A.Prog} {q : B.Prog} {r : C.Prog} {scope : Call → Prop} + (first : Total A B p q scope) (second : Total B C q r scope) : Total A C p r scope := by + intro call hc + obtain ⟨obs, h1, h2⟩ := first call hc + obtain ⟨obs', h2', h3⟩ := second call hc + rw [h2] at h2' + cases h2' + exact ⟨obs, h1, h3⟩ + +/-- A total first stage and plain stages after it compose to a total refinement: the +totality of the whole chain is the totality of its first source. -/ +theorem Total.trans_stage {p : A.Prog} {q : B.Prog} {r : C.Prog} {scope : Call → Prop} + (first : Total A B p q scope) (second : Stage B C q r scope) : Total A C p r scope := + total_iff_stage.mpr ⟨first.stage.trans second, first.source_defined⟩ + +theorem Backward.trans {p : A.Prog} {q : B.Prog} {r : C.Prog} {scope : Call → Prop} + (first : Backward A B p q scope) (second : Backward B C q r scope) : + Backward A C p r scope := + fun call hc obs h3 => first call hc obs (second call hc obs h3) + +theorem Total.refl (A : Sem) (p : A.Prog) {scope : Call → Prop} (df : Defined A p scope) : + Total A A p p scope := + total_iff_stage.mpr ⟨fun _ _ _ h => h, df⟩ + +theorem Total.mono {p : A.Prog} {q : B.Prog} {scope narrower : Call → Prop} + (h : Total A B p q scope) (within : ∀ call, narrower call → scope call) : + Total A B p q narrower := + fun call hc => h call (within call hc) + +theorem Backward.mono {p : A.Prog} {q : B.Prog} {scope narrower : Call → Prop} + (h : Backward A B p q scope) (within : ∀ call, narrower call → scope call) : + Backward A B p q narrower := + fun call hc => h call (within call hc) + +/-! ## Vacuity of a bare stage -/ + +/-- A stage from a source that finishes no call of the scope holds for every target. -/ +theorem Stage.of_never {p : A.Prog} (q : B.Prog) {scope : Call → Prop} + (never : ∀ call, scope call → A.run p call = none) : Stage A B p q scope := by + intro call hc obs hrun + rw [never call hc] at hrun + cases hrun + +/-- A total refinement rules that out: one call of the scope the source does not finish +refutes it, whatever the target. -/ +theorem Total.not_of_none {p : A.Prog} {q : B.Prog} {scope : Call → Prop} {call : Call} + (hc : scope call) (none_ : A.run p call = none) : ¬ Total A B p q scope := by + intro h + obtain ⟨obs, h1, -⟩ := h call hc + rw [none_] at h1 + cases h1 + +/-! ## Specifications -/ + +/-- A stage from a program that satisfies a total specification is a total refinement on the +calls the specification covers. -/ +theorem Satisfies.total_of_stage {p : A.Prog} {q : B.Prog} {scope pre : Call → Prop} + {post : Call → Observable → Prop} (spec : Satisfies A p scope pre post) + (st : Stage A B p q scope) : Total A B p q (fun call => scope call ∧ pre call) := by + intro call ⟨hc, hp⟩ + obtain ⟨obs, hrun, -⟩ := spec call hc hp + exact ⟨obs, hrun, st call hc obs hrun⟩ + +/-- A backward simulation onto a defined target carries a specification from the source to +the target. -/ +theorem Satisfies.of_backward {p : A.Prog} {q : B.Prog} {scope pre : Call → Prop} + {post : Call → Observable → Prop} (spec : Satisfies A p scope pre post) + (bw : Backward A B p q scope) (df : Defined B q scope) : Satisfies B q scope pre post := by + intro call hc hp + obtain ⟨obs, hrun, hpost⟩ := spec call hc hp + obtain ⟨obs', h'⟩ := Option.isSome_iff_exists.mp (df call hc) + have := bw call hc obs' h' + rw [hrun] at this + cases this + exact ⟨obs, h', hpost⟩ + +/-- The target of a specification-satisfying program meets the specification on every +observable it gives, not only on one. -/ +theorem Satisfies.post_of_target {S : Sem} {p : S.Prog} {scope pre : Call → Prop} + {post : Call → Observable → Prop} (spec : Satisfies S p scope pre post) {call : Call} + (hc : scope call) (hp : pre call) {obs : Observable} (hrun : S.run p call = some obs) : + post call obs := by + obtain ⟨obs', h', hpost⟩ := spec call hc hp + rw [hrun] at h' + cases h' + exact hpost + +/-! ## SolidCore to EthLib -/ + +theorem refines_iff_total {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {code : ByteArray} {scope : Call → Prop} : + Refines fuel contract code scope ↔ Total (solidCore fuel) ethLib contract code scope := + Iff.rfl + +/-- Every observable solar's bytecode gives on a call of the scope is SolidCore's for the +same call: its success, return or revert data, logs and final storage. -/ +theorem Refines.backward {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {code : ByteArray} {scope : Call → Prop} (h : Refines fuel contract code scope) {call : Call} + (hc : scope call) {obs : Observable} (hrun : Target.run code call = some obs) : + Source.run fuel contract call = some obs := + (refines_iff_total.mp h).backward call hc obs hrun + +/-- The end-to-end form through a compiler's stages, as `bytecode_of_stages` states it, gives a +total refinement from SolidCore to the bytecode on the specified calls, so the bytecode's +behaviours there are SolidCore's, and nothing in it is vacuous: SolidCore finishes each such +call (the specification says so), and each stage then forces the next language to finish it +with the same observable. -/ +theorem bytecode_total_of_stages {fuel : Nat} {mirSem evmirSem : Sem} + {contract : SolidCore.Solidity.TypeCheck.CheckedContract} {mir : mirSem.Prog} + {evmir : evmirSem.Prog} {code : ByteArray} {scope : Call → Prop} {pre : Call → Prop} + {post : Call → Observable → Prop} + (spec : Satisfies (solidCore fuel) contract scope pre post) + (lowering : Stage (solidCore fuel) mirSem contract mir scope) + (backend : Stage mirSem evmirSem mir evmir scope) + (assembly : Stage evmirSem ethLib evmir code scope) : + Refines fuel contract code (fun call => scope call ∧ pre call) ∧ + Satisfies ethLib code scope pre post := + ⟨spec.total_of_stage ((lowering.trans backend).trans assembly), + bytecode_of_stages spec lowering backend assembly⟩ + +/-! ## Failures roll back -/ + +theorem ethLib_failureConvention : ethLib.FailureConvention := by + intro code call obs hrun hfail + simp only [ethLib, Target.run] at hrun + split at hrun + · cases hrun + · cases hrun + simp only at hfail ⊢ + simp [hfail] + +theorem solidCore_failureConvention (fuel : Nat) : (solidCore fuel).FailureConvention := by + intro contract call obs hrun hfail + simp only [solidCore, Source.run, Option.map_eq_some_iff] at hrun + obtain ⟨r, -, rfl⟩ := hrun + simp only [Source.observe] at hfail ⊢ + simp [hfail] + +/-- A backward simulation from a semantics that rolls failures back gives a target whose +failures roll back too. -/ +theorem Backward.failure {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (bw : Backward A B p q scope) (conv : A.FailureConvention) {call : Call} (hc : scope call) + {obs : Observable} (hrun : B.run q call = some obs) (hfail : obs.success = false) : + obs.logs = [] ∧ obs.storage = slotValue call.storage := + conv p call obs (bw call hc obs hrun) hfail + +/-! ## The relations tell observables apart + +`Fixed` is the semantics whose program is the observable it gives on every call. A stage between two +of its programs holds exactly when they are equal, so each of the four fields of `Observable` +separates stages; a relation that related every pair would fail each `stage_rejects_*` below. -/ + +/-- Every call gives the program itself. -/ +def Fixed : Sem := { Prog := Observable, run := fun obs _ => some obs } + +/-- Some call is in scope. -/ +def Inhabited' (scope : Call → Prop) : Prop := ∃ call, scope call + +theorem Fixed.stage_iff {o o' : Observable} {scope : Call → Prop} (h : Inhabited' scope) : + Stage Fixed Fixed o o' scope ↔ o = o' := by + obtain ⟨call, hc⟩ := h + constructor + · intro st + have := st call hc o rfl + simp only [Fixed, Option.some.injEq] at this + exact this.symm + · rintro rfl + exact fun _ _ _ h => h + +theorem Fixed.total_iff {o o' : Observable} {scope : Call → Prop} (h : Inhabited' scope) : + Total Fixed Fixed o o' scope ↔ o = o' := by + constructor + · intro t + exact (Fixed.stage_iff h).mp t.stage + · rintro rfl + exact total_iff_stage.mpr ⟨(Fixed.stage_iff h).mpr rfl, fun _ _ => rfl⟩ + +theorem Fixed.backward_iff {o o' : Observable} {scope : Call → Prop} (h : Inhabited' scope) : + Backward Fixed Fixed o o' scope ↔ o = o' := by + have d : Defined Fixed o' scope := fun _ _ => rfl + constructor + · intro bw + exact (Fixed.total_iff h).mp (total_iff_backward.mpr ⟨bw, d⟩) + · rintro rfl + exact fun _ _ _ h => h + +/-- The call with no call data, no value and empty storage. -/ +def emptyCall : Call := ⟨.empty, 0, []⟩ + +theorem everywhere : Inhabited' (fun _ : Call => True) := ⟨emptyCall, trivial⟩ + +/-- A success and a failure with the same data are told apart. -/ +theorem stage_rejects_success : + ¬ Stage Fixed Fixed (⟨true, [], [], fun _ => 0⟩ : Observable) ⟨false, [], [], fun _ => 0⟩ + (fun _ => True) := by + intro st + have := (Fixed.stage_iff everywhere).mp st + simp at this + +/-- Two reverts with different revert data are told apart. -/ +theorem stage_rejects_output : + ¬ Stage Fixed Fixed (⟨false, [1], [], fun _ => 0⟩ : Observable) ⟨false, [2], [], fun _ => 0⟩ + (fun _ => True) := by + intro st + have := (Fixed.stage_iff everywhere).mp st + simp at this + +/-- Two successes that log differently are told apart. -/ +theorem stage_rejects_logs : + ¬ Stage Fixed Fixed (⟨true, [], [([1], [])], fun _ => 0⟩ : Observable) + ⟨true, [], [], fun _ => 0⟩ (fun _ => True) := by + intro st + have := (Fixed.stage_iff everywhere).mp st + simp at this + +/-- Two successes that leave one slot differently are told apart. -/ +theorem stage_rejects_storage : + ¬ Stage Fixed Fixed (⟨true, [], [], fun s => if s = 7 then 1 else 0⟩ : Observable) + ⟨true, [], [], fun _ => 0⟩ (fun _ => True) := by + intro st + have h := (Fixed.stage_iff everywhere).mp st + have := congrArg (fun o : Observable => o.storage 7) h + simp at this + +/-- A source that never finishes makes a bare stage hold of every target, and a total +refinement of none: here, the target that always succeeds. -/ +theorem never_stage_total : + Stage (⟨Unit, fun _ _ => none⟩ : Sem) Fixed () ⟨true, [], [], fun _ => 0⟩ (fun _ => True) ∧ + ¬ Total (⟨Unit, fun _ _ => none⟩ : Sem) Fixed () ⟨true, [], [], fun _ => 0⟩ + (fun _ => True) := + ⟨Stage.of_never _ (fun _ _ => rfl), Total.not_of_none (call := emptyCall) trivial rfl⟩ + + +/-- info: 'SolidCore.Refinement.total_iff_backward' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms total_iff_backward + +/-- info: 'SolidCore.Refinement.Total.trans_stage' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms Total.trans_stage + +/-- +info: 'SolidCore.Refinement.bytecode_total_of_stages' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms bytecode_total_of_stages + +/-- +info: 'SolidCore.Refinement.ethLib_failureConvention' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms ethLib_failureConvention + +/-- info: 'SolidCore.Refinement.stage_rejects_storage' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms stage_rejects_storage + +end SolidCore.Refinement diff --git a/SolidCore/Refinement/Bytecode/B1.lean b/SolidCore/Refinement/Bytecode/B1.lean new file mode 100644 index 00000000..41520886 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/B1.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/b1.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.B1 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x346034575f3560e01c80633120d434036034576024361060ff600435111760345760075f55600435601f1a60f81b5f5260205ff35b5f5ffd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 56 + +/-- Selector of `f(uint8)`. -/ +def Main.fSelector : Nat := 0x3120d434 + +end SolidCore.Refinement.Bytecode.B1 diff --git a/SolidCore/Refinement/Bytecode/B2.lean b/SolidCore/Refinement/Bytecode/B2.lean new file mode 100644 index 00000000..723a846f --- /dev/null +++ b/SolidCore/Refinement/Bytecode/B2.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/b2.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.B2 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x346039575f3560e01c806398c3a6c10360395760243610600160043511176039576001196004350260030160ff16600281146037575f555b005b5f5ffd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 61 + +/-- Selector of `f(bool)`. -/ +def Main.fSelector : Nat := 0x98c3a6c1 + +end SolidCore.Refinement.Bytecode.B2 diff --git a/SolidCore/Refinement/Bytecode/B3.lean b/SolidCore/Refinement/Bytecode/B3.lean new file mode 100644 index 00000000..b365bba3 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/B3.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/b3.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.B3 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x34602f575f3560e01c806398c3a6c103602f576024361060016004351117602f5760043560335760035f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 69 + +/-- Selector of `f(bool)`. -/ +def Main.fSelector : Nat := 0x98c3a6c1 + +end SolidCore.Refinement.Bytecode.B3 diff --git a/SolidCore/Refinement/Bytecode/B4.lean b/SolidCore/Refinement/Bytecode/B4.lean new file mode 100644 index 00000000..19a5c7c3 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/B4.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/b4.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.B4 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x346039575f3560e01c80633120d4340360395760a06040526024361060ff600435111760395760016004350160ff8111603d575f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 79 + +/-- Selector of `f(uint8)`. -/ +def Main.fSelector : Nat := 0x3120d434 + +end SolidCore.Refinement.Bytecode.B4 diff --git a/SolidCore/Refinement/Bytecode/B5.lean b/SolidCore/Refinement/Bytecode/B5.lean new file mode 100644 index 00000000..e4f592a1 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/B5.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/b5.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.B5 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x346065575f3560e01c806398c3a6c103606557608060405260243610600160043511176065575f545f5f558060051c90601f165f10015f5f5260205f20905f03816050565b5f815590600101906001015b816044575050600435607c575f545f5260205ff35b5f5ffd5b60415b602052634e487b715f526024601cfd5b5f548060401c60695760018101918160051c0190601f1660031b815460ff821b1916600790911b1790555f555f60ee5f5480603b1c6001820160051b60809081018060401c90821117909117606957818152925f5260205f20601f820160051c602085015f82811060ff575050505050565b51600101801561014f575f5260205ff35b808401548160051b80870360208110602080920302019060051b84015f610134565b838160031b1c60ff168260200192526001015b828110610121575050505060010182811060ff575050505050565b6011606c56 + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 341 + +/-- Selector of `f(bool)`. -/ +def Main.fSelector : Nat := 0x98c3a6c1 + +end SolidCore.Refinement.Bytecode.B5 diff --git a/SolidCore/Refinement/Bytecode/B6.lean b/SolidCore/Refinement/Bytecode/B6.lean new file mode 100644 index 00000000..26cab021 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/B6.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/b6.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.B6 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x346013575f3560e01c806398c3a6c114602a575b5f5ffd5b60415b602052634e487b715f526024601cfd5b60c060405260243610600160043511176013575f545f5f558060051c90601f165f10015f5f5260205f20905f03816068565b5f815590600101906001015b81605c575050600435607d575f545f5260205ff35b5f548060401c60175760018101918160051c0190601f1660031b815460ff821b1916600790911b1790555f555f60f05f5480603b1c60175780604060018151920160051b8201828110911c17601757818152925f5260205f20601f820160051c602085015f828110610101575050505050565b516001018015610152575f5260205ff35b808401548160051b80870360208110602080920302019060051b84015f610136565b838160031b1c60ff168260200192526001015b8281106101235750505050600101828110610101575050505050565b6011601a56 + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 344 + +/-- Selector of `f(bool)`. -/ +def Main.fSelector : Nat := 0x98c3a6c1 + +end SolidCore.Refinement.Bytecode.B6 diff --git a/SolidCore/Refinement/Bytecode/B7.lean b/SolidCore/Refinement/Bytecode/B7.lean new file mode 100644 index 00000000..7e66effc --- /dev/null +++ b/SolidCore/Refinement/Bytecode/B7.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/b7.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.B7 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x346065575f3560e01c806398c3a6c103606557608060405260243610600160043511176065575f545f5f558060051c90601f165f10015f5f5260205f20905f03816050565b5f815590600101906001015b816044575050600435607c575f545f5260205ff35b5f5ffd5b60415b602052634e487b715f526024601cfd5b5f548060401c60695760018101918160051c0190601f1660031b815460ff821b1916600790911b1790555f555f60ee5f5480603b1c6001820160051b60809081018060401c90821117909117606957818152925f5260205f20601f820160051c602085015f82811060ff575050505050565b51600101801561014f575f5260205ff35b808401548160051b80870360208110602080920302019060051b84015f610134565b838160031b1c60ff168260200192526001015b828110610121575050505060010182811060ff575050505050565b6011606c56 + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 341 + +/-- Selector of `f(bool)`. -/ +def Main.fSelector : Nat := 0x98c3a6c1 + +end SolidCore.Refinement.Bytecode.B7 diff --git a/SolidCore/Refinement/Bytecode/C1.lean b/SolidCore/Refinement/Bytecode/C1.lean new file mode 100644 index 00000000..d52607bc --- /dev/null +++ b/SolidCore/Refinement/Bytecode/C1.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/c1.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.C1 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x34603d575f3560e01c80633120d43403603d576024361060ff6004351117603d57600435600302806001019060ff108160ff10176041575f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 83 + +/-- Selector of `f(uint8)`. -/ +def Main.fSelector : Nat := 0x3120d434 + +end SolidCore.Refinement.Bytecode.C1 diff --git a/SolidCore/Refinement/Bytecode/C10.lean b/SolidCore/Refinement/Bytecode/C10.lean new file mode 100644 index 00000000..6e867447 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/C10.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/c10.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.C10 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x346037575f3560e01c80633120d434036037576024361060ff600435111760375761123460f01b6004351c5f1960f01b165f5260205ff35b5f5ffd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 59 + +/-- Selector of `f(uint8)`. -/ +def Main.fSelector : Nat := 0x3120d434 + +end SolidCore.Refinement.Bytecode.C10 diff --git a/SolidCore/Refinement/Bytecode/C11.lean b/SolidCore/Refinement/Bytecode/C11.lean new file mode 100644 index 00000000..d6f1ccdc --- /dev/null +++ b/SolidCore/Refinement/Bytecode/C11.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/c11.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.C11 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x34602c575f3560e01c80633120d43403602c576024361060ff6004351117602c576004355f0b5f5260205ff35b5f5ffd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 48 + +/-- Selector of `f(uint8)`. -/ +def Main.fSelector : Nat := 0x3120d434 + +end SolidCore.Refinement.Bytecode.C11 diff --git a/SolidCore/Refinement/Bytecode/C2.lean b/SolidCore/Refinement/Bytecode/C2.lean new file mode 100644 index 00000000..61435ad5 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/C2.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/c2.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.C2 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x346054575f3560e01c8063ac9fe8580360545760246004358036604411905f0b923591831817815f0b918218176054578015605857607f1982145f19821416606b578082075f0b91055f0b5f5260205260405ff35b5f5ffd5b60125b602052634e487b715f526024601cfd5b6011605b56 + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 113 + +/-- Selector of `f(int8,int8)`. -/ +def Main.fSelector : Nat := 0xac9fe858 + +end SolidCore.Refinement.Bytecode.C2 diff --git a/SolidCore/Refinement/Bytecode/C3.lean b/SolidCore/Refinement/Bytecode/C3.lean new file mode 100644 index 00000000..f671fbe0 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/C3.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/c3.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.C3 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x346058575f3560e01c80631ea70341036058576044361060ff600435111760ff602435111760585760243560043580821c81800260ff16825f0b600985061d5f0b9290931b60ff165f526020529060405260605260805ff35b5f5ffd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 92 + +/-- Selector of `f(uint8,uint8)`. -/ +def Main.fSelector : Nat := 0x1ea70341 + +end SolidCore.Refinement.Bytecode.C3 diff --git a/SolidCore/Refinement/Bytecode/C4.lean b/SolidCore/Refinement/Bytecode/C4.lean new file mode 100644 index 00000000..f13fa8d3 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/C4.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/c4.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.C4 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x346055575f3560e01c806302067e6a036055576024361060ff60043511176055576004355f5460ff8116820160ff81116059579060ff1916179081601e1a1860081b9061ff00191617805f5560ff165f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 107 + +/-- Selector of `add(uint8)`. -/ +def Main.addSelector : Nat := 0x02067e6a + +end SolidCore.Refinement.Bytecode.C4 diff --git a/SolidCore/Refinement/Bytecode/C5.lean b/SolidCore/Refinement/Bytecode/C5.lean new file mode 100644 index 00000000..6cd492dc --- /dev/null +++ b/SolidCore/Refinement/Bytecode/C5.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/c5.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.C5 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x34605f575f3560e01c8063fc5842bd03605f576024361060ff6004351117605f57600435805f525f60205260405f20805461ffff1661012c018060101c6063579055600181185f528060405f20555f5260405f205461ffff165f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 117 + +/-- Selector of `inc(uint8)`. -/ +def Main.incSelector : Nat := 0xfc5842bd + +end SolidCore.Refinement.Bytecode.C5 diff --git a/SolidCore/Refinement/Bytecode/C6.lean b/SolidCore/Refinement/Bytecode/C6.lean new file mode 100644 index 00000000..a68465d7 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/C6.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/c6.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.C6 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x346059575f3560e01c80639d4dcb83036059576024361060ff60043511176059576004355f5f5f5b83811015605f57600781066003146052578080028301928310606b5790600101620186a08311605d57905b6001016027565b5f5ffd5b905b50905f5260205260405ff35b6011602052634e487b715f526024601cfd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 125 + +/-- Selector of `sum(uint8)`. -/ +def Main.sumSelector : Nat := 0x9d4dcb83 + +end SolidCore.Refinement.Bytecode.C6 diff --git a/SolidCore/Refinement/Bytecode/C7.lean b/SolidCore/Refinement/Bytecode/C7.lean new file mode 100644 index 00000000..0694d5ae --- /dev/null +++ b/SolidCore/Refinement/Bytecode/C7.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/c7.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.C7 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x346040575f3560e01c8063918a3789036040576044361060026004351117600160243511176040576004356001811460243514159080015f5260205260405ff35b5f5ffd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 68 + +/-- Selector of `f(uint8,bool)`. -/ +def Main.fSelector : Nat := 0x918a3789 + +end SolidCore.Refinement.Bytecode.C7 diff --git a/SolidCore/Refinement/Bytecode/C8.lean b/SolidCore/Refinement/Bytecode/C8.lean new file mode 100644 index 00000000..e14ba13c --- /dev/null +++ b/SolidCore/Refinement/Bytecode/C8.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/c8.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.C8 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x34604a575f3560e01c80633120d43403604a5760806040526024361060ff6004351117604a5760043560188111606e57600d9006604e5b60028210606c576001820360ff1660556036565b5f5ffd5b5f5260205ff35b600290920360ff1660636036565b8201918210608e575b565b6262696760e81b6003602080526040526060526308c379a05f526064601cfd5b6011602052634e487b715f526024601cfd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 160 + +/-- Selector of `f(uint8)`. -/ +def Main.fSelector : Nat := 0x3120d434 + +end SolidCore.Refinement.Bytecode.C8 diff --git a/SolidCore/Refinement/Bytecode/C9.lean b/SolidCore/Refinement/Bytecode/C9.lean new file mode 100644 index 00000000..b61e231a --- /dev/null +++ b/SolidCore/Refinement/Bytecode/C9.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/c9.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.C9 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x346013575f3560e01c80633120d434146029575b5f5ffd5b6041602052634e487b715f526024601cfd5b6024361060ff60043511176013575f548060401c601757600435600182015f5f5260205f20928301829055805f558060401c60175760018101920160059055815f55905f5260205260405ff3 + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 118 + +/-- Selector of `f(uint8)`. -/ +def Main.fSelector : Nat := 0x3120d434 + +end SolidCore.Refinement.Bytecode.C9 diff --git a/SolidCore/Refinement/Bytecode/D1.lean b/SolidCore/Refinement/Bytecode/D1.lean new file mode 100644 index 00000000..dfb37b89 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/D1.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/d1.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.D1 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x34603b575f3560e01c8063d45754f803603b5760243610600435600481019060243603108135916020013603821117909117603b575f5260205ff35b5f5ffd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 63 + +/-- Selector of `f(bytes)`. -/ +def Main.fSelector : Nat := 0xd45754f8 + +end SolidCore.Refinement.Bytecode.D1 diff --git a/SolidCore/Refinement/Bytecode/D2.lean b/SolidCore/Refinement/Bytecode/D2.lean new file mode 100644 index 00000000..362eb904 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/D2.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/d2.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.D2 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x34604f575f3560e01c8063cbdb452603604f576004356024361060048201916024360310178135916020019081360360051c831117604f575f91156047573560ff8111604f575f5b505f5260205ff35b5f5ffd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 83 + +/-- Selector of `f(uint8[])`. -/ +def Main.fSelector : Nat := 0xcbdb4526 + +end SolidCore.Refinement.Bytecode.D2 diff --git a/SolidCore/Refinement/Bytecode/D3.lean b/SolidCore/Refinement/Bytecode/D3.lean new file mode 100644 index 00000000..6504d05a --- /dev/null +++ b/SolidCore/Refinement/Bytecode/D3.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/d3.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.D3 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x34603b575f3560e01c806369a406dd03603b576044361060016024351117603b5760036024351560345760043560ff8111603b575b5f5260205ff35b5f5ffd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 63 + +/-- Selector of `f((uint8,bool))`. -/ +def Main.fSelector : Nat := 0x69a406dd + +end SolidCore.Refinement.Bytecode.D3 diff --git a/SolidCore/Refinement/Bytecode/D4.lean b/SolidCore/Refinement/Bytecode/D4.lean new file mode 100644 index 00000000..8cba052f --- /dev/null +++ b/SolidCore/Refinement/Bytecode/D4.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/d4.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.D4 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x346039575f3560e01c806369a406dd036039576044361060ff60043511176039576004356080526024356001811160395760a05260406080f35b5f5ffd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 61 + +/-- Selector of `f((uint8,bool))`. -/ +def Main.fSelector : Nat := 0x69a406dd + +end SolidCore.Refinement.Bytecode.D4 diff --git a/SolidCore/Refinement/Bytecode/W1.lean b/SolidCore/Refinement/Bytecode/W1.lean new file mode 100644 index 00000000..8fdd29c8 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/W1.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/w1.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.W1 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x34602b575f3560e01c8063b3de648b03602b5760243610602b576001600435018015602f575f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 65 + +/-- Selector of `f(uint256)`. -/ +def Main.fSelector : Nat := 0xb3de648b + +end SolidCore.Refinement.Bytecode.W1 diff --git a/SolidCore/Refinement/Bytecode/W2.lean b/SolidCore/Refinement/Bytecode/W2.lean new file mode 100644 index 00000000..cadfd068 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/W2.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/w2.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.W2 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x346036575f3560e01c806313d1aa2e0360365760443610603657600435602435818110918181039103809103909102015f5260205ff35b5f5ffd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 58 + +/-- Selector of `f(uint256,uint256)`. -/ +def Main.fSelector : Nat := 0x13d1aa2e + +end SolidCore.Refinement.Bytecode.W2 diff --git a/SolidCore/Refinement/Bytecode/W3.lean b/SolidCore/Refinement/Bytecode/W3.lean new file mode 100644 index 00000000..e01aeb81 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/W3.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/w3.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.W3 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x34602d575f3560e01c8063fc68521a03602d5760043560a01c6024361017602d576001600435185f5260205ff35b5f5ffd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 49 + +/-- Selector of `f(address)`. -/ +def Main.fSelector : Nat := 0xfc68521a + +end SolidCore.Refinement.Bytecode.W3 diff --git a/SolidCore/Refinement/Bytecode/W4.lean b/SolidCore/Refinement/Bytecode/W4.lean new file mode 100644 index 00000000..86d20b76 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/W4.lean @@ -0,0 +1,20 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/w4.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +namespace SolidCore.Refinement.Bytecode.W4 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x346020575f3560e01c806360fe47b103602057602436106020576004355f55005b5f5ffd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 36 + +/-- Selector of `set(uint256)`. -/ +def Main.setSelector : Nat := 0x60fe47b1 + +end SolidCore.Refinement.Bytecode.W4 diff --git a/SolidCore/Refinement/Bytecode/W5.lean b/SolidCore/Refinement/Bytecode/W5.lean new file mode 100644 index 00000000..ddc8ceb9 --- /dev/null +++ b/SolidCore/Refinement/Bytecode/W5.lean @@ -0,0 +1,24 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. +-- Source: scripts/refinement/corpus/w5.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 +-- solar flags: -Ogas + +namespace SolidCore.Refinement.Bytecode.W5 + +def solarRev : String := "9688f21581717743806cb7bf3afae2ac3c156a08" + +/-- Runtime bytecode of `Main` as solar emits it, read big-endian. -/ +def Main.runtimeNat : Nat := + 0x34602e575f3560e01c806313d1aa2e03602e5760443610602e5760043560243581019081106032575f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd + +/-- Length of `Main`'s runtime bytecode in bytes. -/ +def Main.runtimeSize : Nat := 68 + +/-- SHA-256 of `Main`'s runtime bytecode, from solar with `-Ogas`. -/ +def Main.runtimeSha256 : String := "24d2438e4d77b39b2530aac7af63774b10576eabc3c093d282620ab44403778b" + +/-- Selector of `f(uint256,uint256)`. -/ +def Main.fSelector : Nat := 0x13d1aa2e + +end SolidCore.Refinement.Bytecode.W5 diff --git a/SolidCore/Refinement/C1/Refinement.lean b/SolidCore/Refinement/C1/Refinement.lean new file mode 100644 index 00000000..2ab143eb --- /dev/null +++ b/SolidCore/Refinement/C1/Refinement.lean @@ -0,0 +1,260 @@ +import SolidCore.Refinement.Statement +import SolidCore.Refinement.Source.C1 +import SolidCore.Refinement.C1.Target + +/-! +# c1: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code scope` for c1 +(`scripts/refinement/corpus/c1.sol`), where `contract` is SolidCore's checked +`Main` and `code` is solar's runtime bytecode at the pinned commit. The scope is +every call of `f(uint8)` with any 32-byte argument word, no value and empty +storage: 2^256 calls, including the dirty words a `uint8` decoder must reject. + +* The EthLib side, `target_run`, is a kernel-checked symbolic proof + (`C1.processMessage_spec`). +* The SolidCore side, `source_run`, evaluates the interpreter with + `native_decide` on the 256 clean words and on the dirty word 256, and shows + that every dirty word decodes, and so runs, exactly as 256 does. It trusts + Lean's compiler, as `native_decide` does. +-/ + +namespace SolidCore.Refinement.C1 + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.State +open SolidCore.Solidity + +/-- The interpreter fuel the refinement uses. -/ +def fuel : Nat := 4096 + +/-- SolidCore's checked `Main` of c1. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.C1.importedSourceUnit "Main" + +/-- The call of `f` with argument word `w`, no value and empty storage. -/ +def call (w : U256) : Call := { calldata := cd w, callvalue := 0, storage := [] } + +/-- The calls the theorem covers. -/ +def scope (c : Call) : Prop := ∃ w, c = call w + +/-- What both sides show for `f` on the word `w`: `spec w`, no logs, empty storage. -/ +def expected (w : U256) : Observable := + { success := (spec w).1.isNone, output := (spec w).2.toList.map (·.toNat), logs := [], + storage := fun _ => 0 } + +/-! ## EthLib -/ + +theorem precompileAddress_message (c : Call) : + precompileAddress .fusaka (Target.message code c) = none := by + simp only [precompileAddress, Target.message] + decide + +theorem getStorage_preState (w : U256) (k : Nat) : + (Target.preState code (call w)).getStorage (Target.address selfAddress) + (Target.storageKey k) = 0 := by + simp [Target.preState, call, TransactionState.getStorage, TransactionState.ofBlock, + StorageMap.slot, State.getStorage] + +/-- EthLib runs solar's bytecode on every call in scope as `expected` says. -/ +theorem target_run (w : U256) : Target.run code (call w) = some (expected w) := by + obtain ⟨evm, h, herr, hout, hsub, hst⟩ := processMessage_spec w (Target.message code (call w)) + rfl rfl rfl rfl (precompileAddress_message _) (Target.preState code (call w)) Substate.empty + simp only [Target.run, h, hsub, herr, hout, expected] + cases hs : (spec w).1 with + | none => + have hstate := hst hs + simp [hstate, getStorage_preState, Substate.empty] + | some e => + simp [call, slotValue] + +/-! ## SolidCore -/ + +/-- The call data of `call w`, byte by byte: the selector, then `w` big-endian. -/ +theorem bytes_call (w : U256) : + (call w).calldata.data.toList.map (·.toNat) = + [0x31, 0x20, 0xd4, 0x34] ++ (natToBytes 32 w.toNat).map (·.toNat) := by + simp [call, cd, sel, wordBytes] + rw [← EthLib.Base.U256.toList_toBeBytes] + rfl + +/-- A 256-bit word is already a SolidCore word. -/ +theorem norm_toNat (w : U256) : Shared.norm w.toNat = w.toNat := by + simp only [Shared.norm, Shared.wordModulus] + exact Nat.mod_eq_of_lt w.isLt + +open SolidCore.Solidity.Source in +/-- SolidCore reads the 32 big-endian bytes of `w` back as `w`. -/ +theorem bytesToWordBE_natToBytes (w : U256) : + ABI.bytesToWordBE (ABI.normalizeBytes ((natToBytes 32 w.toNat).map (·.toNat))) = w.toNat := by + have small : w.toNat < 256 ^ 32 := by + have := w.isLt + rwa [show (2 : Nat) ^ 256 = 256 ^ 32 by decide] at this + have hnorm : Shared.norm w.toNat = w.toNat := norm_toNat w + have hbyte : ∀ b : UInt8, normByte (Shared.External.byte b.toNat) = b.toNat := by + intro b + have := b.toNat_lt + simp [normByte, Shared.Account.byte, Shared.External.byte, Nat.mod_eq_of_lt this] + unfold ABI.bytesToWordBE ABI.normalizeBytes Shared.External.normalizeBytes + rw [List.map_map, List.foldl_map] + simp only [Function.comp_def, hbyte] + change Shared.norm (bytesToNat (natToBytes 32 w.toNat)) = _ + rw [EthLib.Base.bytesToNat_natToBytes_of_lt small, hnorm] + +open SolidCore.Solidity.Source in +/-- A `uint256` parameter cleaned as `uint8` rejects every word from 256 up. -/ +theorem decode_dirty (fn : FunctionDef) (hp : fn.params.map BindingDecl.ty = [Source.Ty.uint256]) + (hc : fn.paramAbiCleanups = [AbiCleanup.uint 8]) (w : U256) (hw : 256 ≤ w.toNat) : + ABI.decodeFunctionArgs? fn ((natToBytes 32 w.toNat).map (·.toNat)) = .error .empty := by + unfold ABI.decodeFunctionArgs? + simp only [hp, hc] + simp [ABI.decodeArgsWith?, ABI.decodeArgsAux?, ABI.decodeValueAt?, + ABI.decodeValueAtWithFuel?, ABI.readWord?, ABI.readBytes?, ABI.abiArgOpt, + AbiCleanups.lazyParamValues, AbiCleanup.lazyParamValue, AbiCleanup.accepts, ABI.AbiCleanup.decodeLazy, + natToBytes_length, ABI.Ty.listAbiHeadWords?, ABI.Ty.abiHeadWords?, ABI.Ty.abiDecodeFuel, + ABI.Ty.isDynamicAbi, ABI.Ty.staticAbiHeadWords?, ABI.wordBytes, bind, Except.bind, pure, + Except.pure] + have hlt := norm_toNat w + have htake : List.take 32 ((natToBytes 32 w.toNat).map (·.toNat)) = + (natToBytes 32 w.toNat).map (·.toNat) := + List.take_of_length_le (by simp [natToBytes_length]) + simp [htake, bytesToWordBE_natToBytes, hlt, show ¬ w.toNat < 256 by omega] + +open SolidCore.Solidity.Source in +/-- The ABI dispatcher sends every dirty word for `f` to the empty revert. -/ +theorem dispatch_dirty (k : Contract) (fn : FunctionDef) + (hsel : k.findFunctionBySelector? 0x3120d434 = some fn) + (hp : fn.params.map BindingDecl.ty = [Source.Ty.uint256]) + (hc : fn.paramAbiCleanups = [AbiCleanup.uint 8]) + (w : U256) (hw : 256 ≤ w.toNat) {fuel : Nat} {base : Source.Context} {st : Source.State} + {self sender value : Nat} : + ABI.Contract.callCalldataAtFromWithContext? fuel k base st self sender value + ([0x31, 0x20, 0xd4, 0x34] ++ (natToBytes 32 w.toNat).map (·.toNat)) = + ABI.Contract.revertedCall? k st .empty := by + have hsel' : ABI.readSelector? ([0x31, 0x20, 0xd4, 0x34] ++ (natToBytes 32 w.toNat).map (·.toNat)) = + some 0x3120d434 := by + simp [ABI.readSelector?, ABI.readBytes?, ABI.selectorBytes, natToBytes_length] + decide + unfold ABI.Contract.callCalldataAtFromWithContext? + simp only [hsel', hsel, ABI.selectorBytes, List.drop_left' (show [0x31, 0x20, 0xd4, 0x34].length = 4 from rfl)] + rw [decode_dirty fn hp hc w hw] + +/-- Whether `Main` dispatches selector `0x3120d434` to a function with one `uint256` +ABI parameter cleaned as `uint8`. -/ +def shapeOk : Bool := + match contract? with + | .ok c => + match c.core.findFunctionBySelector? 0x3120d434 with + | some fn => + match fn.params.map Source.BindingDecl.ty, fn.paramAbiCleanups with + | [Source.Ty.uint256], [Source.AbiCleanup.uint 8] => true + | _, _ => false + | none => false + | .error _ => false + +theorem shapeOk_eq_true : shapeOk = true := by native_decide + +/-- `Main` dispatches `f(uint8)` to a function whose one parameter is a `uint256` +cleaned as `uint8`. -/ +theorem shape {c : TypeCheck.CheckedContract} (h : contract? = .ok c) : + ∃ fn, c.core.findFunctionBySelector? 0x3120d434 = some fn ∧ + fn.params.map Source.BindingDecl.ty = [Source.Ty.uint256] ∧ + fn.paramAbiCleanups = [Source.AbiCleanup.uint 8] := by + have hs := shapeOk_eq_true + simp only [shapeOk, h] at hs + split at hs + next fn hf => + split at hs + next hp hc => exact ⟨fn, hf, hp, hc⟩ + next => exact absurd hs (by simp) + next => exact absurd hs (by simp) + +/-- SolidCore runs every dirty word exactly as it runs 256. -/ +theorem result_dirty {c : TypeCheck.CheckedContract} (h : contract? = .ok c) (w : U256) + (hw : 256 ≤ w.toNat) : + Source.result? fuel c (call w) = Source.result? fuel c (call (BitVec.ofNat 256 256)) := by + obtain ⟨fn, hsel, hp, hc⟩ := shape h + have h256 : 256 ≤ (BitVec.ofNat 256 256 : U256).toNat := by decide + simp only [Source.result?, TypeCheck.CheckedContract.callCalldataAtFromWithContext?, bytes_call, + dispatch_dirty c.core fn hsel hp hc w hw, dispatch_dirty c.core fn hsel hp hc _ h256] + rfl + +/-- Whether SolidCore's result for `call w` is `expected w`, read as data: the +success flag, the output, no logs and an empty storage map. -/ +def sourceAgrees (w : U256) : Bool := + match contract? with + | .ok contract => + match Source.result? fuel contract (call w) with + | some result => + result.success == (spec w).1.isNone && + result.output == (spec w).2.toList.map (·.toNat) && + (result.state.logEntries selfAddress).isEmpty && + result.state.storage.isEmpty + | none => false + | .error _ => false + +/-- SolidCore agrees on every clean argument word. -/ +theorem sourceAgrees_clean : ∀ v : Fin 256, sourceAgrees (BitVec.ofNat 256 v.val) = true := by + native_decide + +/-- SolidCore agrees on the dirty word 256. -/ +theorem sourceAgrees_256 : sourceAgrees (BitVec.ofNat 256 256) = true := by + native_decide + +/-- SolidCore agrees on every argument word. -/ +theorem sourceAgrees_all (w : U256) : sourceAgrees w = true := by + by_cases hw : w.toNat < 256 + · have := sourceAgrees_clean ⟨w.toNat, hw⟩ + simpa using this + · have h256 := sourceAgrees_256 + have hspec : spec w = spec (BitVec.ofNat 256 256) := by + rw [spec_dirty (by omega), spec_dirty (by decide)] + unfold sourceAgrees at h256 ⊢ + split + next c hc => + rw [hc] at h256 + simp only at h256 + rw [result_dirty hc w (by omega), hspec] + exact h256 + next => rw [‹contract? = _›] at h256; exact h256 + +open SolidCore.Solidity.Source in +/-- An empty storage map reads 0 everywhere. -/ +theorem loadSlot_of_isEmpty {st : Source.State} (h : st.storage.isEmpty = true) (slot : Nat) : + st.loadSlot slot = 0 := by + unfold State.loadSlot StorageMap.lookup? + rw [Std.HashMap.get?_eq_getElem?, + Std.HashMap.getElem?_eq_none (Std.HashMap.isEmpty_iff_forall_not_mem.mp h _)] + +/-- SolidCore runs every call in scope as `expected` says. -/ +theorem source_run {c : TypeCheck.CheckedContract} (h : contract? = .ok c) (w : U256) : + Source.run fuel c (call w) = some (expected w) := by + have ha := sourceAgrees_all w + simp only [sourceAgrees, h] at ha + split at ha + next r hr => + simp only [Bool.and_eq_true, beq_iff_eq, List.isEmpty_iff] at ha + obtain ⟨⟨⟨hs, ho⟩, hl⟩, hst⟩ := ha + simp only [Source.run, hr, Option.map_some, Source.observe, expected, hs, ho, hl] + have hstore : (fun slot => if (spec w).1.isNone = true then r.state.loadSlot slot + else slotValue (call w).storage slot) = fun _ => 0 := by + funext slot + split + · exact loadSlot_of_isEmpty hst slot + · simp [call, slotValue] + rw [hstore] + simp + next => exact absurd ha (by simp) + +/-! ## The refinement -/ + +/-- solar's runtime bytecode for c1 refines SolidCore's `Main` on every call of +`f(uint8)` with any argument word, no value and empty storage. -/ +theorem refines : ∃ contract, contract? = .ok contract ∧ Refines fuel contract code scope := by + match h : contract? with + | .ok contract => + exact ⟨contract, rfl, fun _ ⟨w, hw⟩ => hw ▸ ⟨expected w, source_run h w, target_run w⟩⟩ + | .error _ => + have hs := shapeOk_eq_true + simp [shapeOk, h] at hs + +end SolidCore.Refinement.C1 diff --git a/SolidCore/Refinement/C1/Spec.lean b/SolidCore/Refinement/C1/Spec.lean new file mode 100644 index 00000000..84522147 --- /dev/null +++ b/SolidCore/Refinement/C1/Spec.lean @@ -0,0 +1,46 @@ +import SolidCore.Refinement.Spec +import SolidCore.Refinement.C1.Refinement + +/-! +# c1's specification on bytecode + +c1's specification carried to solar's bytecode, directly from `C1.refines` and through a +compiler's stages. `C1.Refinement` evaluates SolidCore with `native_decide`, which trusts Lean's +compiler, so this module and it are the `SolidCoreNative` library, outside the default `SolidCore` +library, which uses none. +-/ + +namespace SolidCore.Refinement + +namespace C1 + +/-- c1's specification: `f(x)` returns `3 * x + 1` when it fits in `uint8`, reverts with +`Panic(0x11)` when it overflows, and reverts with no data for a dirty argument word; it +never logs and leaves storage empty. -/ +def post (call : Call) (obs : Observable) : Prop := + ∃ w, call = C1.call w ∧ obs = expected w + +/-- SolidCore's c1 meets its specification on every argument word. -/ +theorem satisfies_source {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (h : contract? = .ok c) : Satisfies (solidCore fuel) c scope (fun _ => True) post := by + rintro _ ⟨w, rfl⟩ - + exact ⟨expected w, source_run h w, w, rfl, rfl⟩ + +/-- solar's bytecode for c1 meets c1's specification on every argument word, with no +hypothesis. -/ +theorem satisfies_bytecode : Satisfies ethLib code scope (fun _ => True) post := by + obtain ⟨c, hc, href⟩ := refines + exact bytecode_of_refines (satisfies_source hc) href + +/-- The same through a compiler's stages, each a hypothesis. -/ +theorem satisfies_bytecode_staged {mirSem evmirSem : Sem} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {mir : mirSem.Prog} {evmir : evmirSem.Prog} (hc : contract? = .ok c) + (lowering : Stage (solidCore fuel) mirSem c mir scope) + (backend : Stage mirSem evmirSem mir evmir scope) + (assembly : Stage evmirSem ethLib evmir code scope) : + Satisfies ethLib code scope (fun _ => True) post := + bytecode_of_stages (satisfies_source hc) lowering backend assembly + +end C1 + +end SolidCore.Refinement diff --git a/SolidCore/Refinement/C1/Target.lean b/SolidCore/Refinement/C1/Target.lean new file mode 100644 index 00000000..e5d06b60 --- /dev/null +++ b/SolidCore/Refinement/C1/Target.lean @@ -0,0 +1,370 @@ +import SolidCore.Refinement.Evm.Lemmas +import SolidCore.Refinement.Bytecode.C1 +import EthLib.Execution.Evm.Call.MessageCall +/-! +# c1 on EthLib: solar's bytecode for `f(uint8 x) = x * 3 + 1` + +Source: `scripts/refinement/corpus/c1.sol` + + contract Main { function f(uint8 x) external pure returns (uint8) { return x * 3 + 1; } } + +The bytecode is `Bytecode.C1.Main.runtimeNat`, which `scripts/refinement/gen.sh` +writes from solar at the commit in `scripts/refinement/solar-rev`. The proofs +step through those exact bytes, so they stop checking if solar's output changes. + +At the pinned commit the code is 83 bytes (selector `f(uint8)` = 0x3120d434): + + pc opcode stack after, top first + 00 CALLVALUE [v] + 01 PUSH1 0x3d; JUMPI [] v ≠ 0 → revert(0, 0) + 04 PUSH0; CALLDATALOAD [cd[0:32]] + 06 PUSH1 0xe0; SHR [sel] + 09 DUP1; PUSH4 0x3120d434; SUB; PUSH1 0x3d; JUMPI + [sel] sel ≠ f → revert(0, 0) + 13 PUSH1 0x24; CALLDATASIZE; LT; PUSH1 0xff; PUSH1 0x04; CALLDATALOAD; GT; OR + PUSH1 0x3d; JUMPI [sel] short or x > 255 → revert(0, 0) + 21 PUSH1 0x04; CALLDATALOAD; PUSH1 0x03; MUL; DUP1; PUSH1 0x01; ADD; SWAP1 + PUSH1 0xff; LT; DUP2; PUSH1 0xff; LT; OR; PUSH1 0x41; JUMPI + [3x+1, sel] overflow → 0x41 + 37 PUSH0; MSTORE; PUSH1 0x20; PUSH0; RETURN return word(3x+1) + 3d JUMPDEST; PUSH0; PUSH0; REVERT revert(0, 0) + 41 JUMPDEST; mem[32:64] = 0x11; mem[0:32] = 0x4e487b71 + PUSH1 0x24; PUSH1 0x1c; REVERT revert Panic(0x11) + +Results, kernel-checked with no `sorry`, `native_decide` or `bv_decide`: + +* `frame_spec`: from pc 0, at any fork from Shanghai, with no value, call data + `cd w` and 10M gas, the frame stops with the error and output `spec w` and + leaves state and substate as they were. +* `processMessage_spec`: the same for the whole `processMessage` at Fusaka, from + any state and substate. +* `frame_spec_value`: a nonzero call value reverts with empty output. +* `processMessage_reject`: a wrong selector or call data shorter than 36 bytes + reverts with empty output. +-/ + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic +open SolidCore.Refinement.Evm SolidCore.Refinement.Evm.Logic +open SolidCore.Refinement.Bytecode.C1 + +namespace SolidCore.Refinement.C1 +/-- solar's runtime bytecode for `Main`, from the generated file. -/ +def codeNat : Nat := Main.runtimeNat + +/-- The bytecode as EthLib runs it. -/ +def code : ByteArray := NatCode.ofNat codeNat Main.runtimeSize +def sel : ByteArray := ⟨#[0x31, 0x20, 0xd4, 0x34]⟩ +def cd (w : U256) : ByteArray := sel ++ wordBytes w + +theorem size_cd (w : U256) : (cd w).size = 36 := by + simp [cd, ByteArray.size_append, size_wordBytes]; rfl +theorem shr_cd (w : U256) : bitwiseShr (224#256) (loadWord (cd w) 0 32) = 824235060#256 := by + have := bitwiseShr_loadWord_zero (cd w) 4 (by decide) (by decide) + rw [show BitVec.ofNat 256 (8 * (32 - 4)) = 224#256 from rfl] at this + rw [this, cd, bufferRead_append_of_le _ _ (by decide)] + rfl +theorem load4_cd (w : U256) : loadWord (cd w) 4 32 = w := loadWord_append_wordBytes sel w + +macro "c1_step" : tactic => `(tactic| first + | (refine' Triple.seq (push0 (by assumption) ?lt ?op ?gas ?room) ?next + case lt => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case op => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case gas => evm_gas + case room => evm_room + all_goals evm_tidy) + | evm_step [code, codeNat, Main.runtimeNat, Main.runtimeSize]) + +variable {fork : Fork} + +theorem Spec.close {P R Q : Evm fork Nat → Prop} (h : Spec fork P R) (imp : ∀ e, R e → Q e) : + Triple (Step fork) P (fun evm => evm.running = false ∧ Q evm) := + Spec.consequence h (fun _ h => h) imp + +def panicData : ByteArray := ⟨#[0x4e, 0x48, 0x7b, 0x71]⟩ ++ wordBytes 0x11 + +/-- The error and the output the spec gives for `f(w)`. -/ +def spec (w : U256) : Option EvmError × ByteArray := + if 256 ≤ w.toNat then (some .revert, .empty) + else if 255 < 3 * w.toNat + 1 then (some .revert, panicData) + else (none, wordBytes (3 * w + 1)) + +def Post (w : U256) (st : State.TransactionState) (ss : Substate) (evm : Evm fork Nat) : Prop := + evm.error = (spec w).1 ∧ evm.output = (spec w).2 ∧ evm.state = st ∧ evm.substate = ss + +theorem spec_dirty {w : U256} (h : 256 ≤ w.toNat) : spec w = (some .revert, .empty) := by + simp [spec, h] +theorem spec_panic {w : U256} (h : w.toNat < 256) (h2 : 255 < 3 * w.toNat + 1) : + spec w = (some .revert, panicData) := by + simp [spec, h2, show ¬ 256 ≤ w.toNat by omega] +theorem spec_ok {w : U256} (h2 : 3 * w.toNat + 1 ≤ 255) : + spec w = (none, wordBytes (3 * w + 1)) := by + simp [spec, show ¬ 255 < 3 * w.toNat + 1 by omega, show ¬ 256 ≤ w.toNat by omega] + +theorem byz (hf : Fork.shapella ≤ fork) : Fork.byzantium ≤ fork := by + refine' Nat.le_trans ?_ hf; decide + +theorem frame_spec (hf : Fork.shapella ≤ fork) (w : U256) (message : Message fork) + (hv : message.value = 0) (hd : message.data = cd w) (st ss) : + Spec fork (At code message 0 [] .empty 10000000 st ss .empty) (Post w st ss) := by + c1_step; c1_step; c1_step; c1_step; c1_step; c1_step; c1_step + rw [hd, shr_cd] + c1_step; c1_step; c1_step + c1_step; c1_step + c1_step; c1_step + rw [hd, size_cd] + c1_step; c1_step; c1_step; c1_step + rw [hd, load4_cd] + c1_step; c1_step; c1_step + by_cases hw : w.toNat < 256 + · have h0 : bitwiseOr (greaterThan w 255#256) (lessThan 36#256 36#256) = 0 := by + simp [bitwiseOr, greaterThan, lessThan]; bv_omega + c1_step + c1_step; c1_step + rw [hd, load4_cd] + c1_step; c1_step; c1_step; c1_step; c1_step; c1_step; c1_step; c1_step; c1_step; c1_step; c1_step; c1_step + have hm3 : (mul (3#256) w).toNat = 3 * w.toNat := by + simp only [mul, BitVec.toNat_mul]; rw [Nat.mod_eq_of_lt] <;> simp <;> omega + have hv3 : (add (1#256) (mul (3#256) w)).toNat = 1 + 3 * w.toNat := by + simp only [add, BitVec.toNat_add, hm3]; rw [Nat.mod_eq_of_lt] <;> simp <;> omega + by_cases ho : 3 * w.toNat + 1 ≤ 255 + · have h2 : bitwiseOr (lessThan (255#256) (add (1#256) (mul (3#256) w))) (lessThan (255#256) (mul (3#256) w)) = 0 := by + simp only [bitwiseOr, lessThan, hv3, hm3, BitVec.toNat_ofNat]; split <;> split <;> first | decide | omega + c1_step + c1_step + c1_step + refine' Triple.seq (mstore ?lt ?op ?gas) ?_ + case lt => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case op => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case gas => decide + have hext : extendMemory ByteArray.empty.size [((0 : U256), (32 : U256))] = ⟨3, 32⟩ := by decide + simp only [hext, show (0 : U256).toNat = 0 from rfl] + rw [memoryWrite_whole (by rw [size_memoryExtend, size_wordBytes]; rfl)] + c1_step; c1_step + refine Spec.close (Logic.«return» ?lt ?op ?gas) ?_ + case lt => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case op => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case gas => rw [size_wordBytes]; decide + rintro e ⟨-, herr, hout, -, hs, hss⟩ + refine ⟨?_, ?_, hs, hss⟩ + · rw [herr, spec_ok ho]; rfl + · rw [hout, size_wordBytes, show (extendMemory 32 [((0 : U256), 32#256)]).expandBy = 0 by decide, + memoryExtend_zero] + have := memoryReadBytes_whole (memory := wordBytes (add (1#256) (mul (3#256) w))) + rw [size_wordBytes] at this + rw [show (0 : U256).toNat = 0 from rfl, show (32#256).toNat = 32 from rfl, this, spec_ok ho] + show wordBytes _ = wordBytes _ + congr 1 + simp only [add, mul]; exact BitVec.add_comm _ _ + · have h2 : bitwiseOr (lessThan (255#256) (add (1#256) (mul (3#256) w))) (lessThan (255#256) (mul (3#256) w)) ≠ 0 := by + simp only [bitwiseOr, lessThan, hv3, hm3, BitVec.toNat_ofNat]; split <;> split <;> first | decide | omega + c1_step + c1_step; c1_step; c1_step + c1_step + refine' Triple.seq (mstore ?lt ?op ?gas) ?_ + case lt => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case op => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case gas => decide + have hext : extendMemory ByteArray.empty.size [(32#256, (32 : U256))] = ⟨6, 64⟩ := by decide + simp only [hext] + c1_step; c1_step + refine' Triple.seq (mstore ?lt ?op ?gas) ?_ + case lt => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case op => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case gas => decide + have hext2 : extendMemory (memoryWrite (memoryExtend ByteArray.empty 64) 32 (wordBytes 17#256)).size + [((0 : U256), (32 : U256))] = ⟨0, 0⟩ := by decide + simp only [hext2, memoryExtend_zero] + c1_step; c1_step + refine Spec.close (revert (byz hf) ?lt ?op ?gas) ?_ + case lt => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case op => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case gas => decide + rintro e ⟨-, herr, hout, -, hs, hss⟩ + refine ⟨?_, ?_, hs, hss⟩ + · rw [herr, spec_panic hw (by omega)]; rfl + · rw [hout, spec_panic hw (by omega)] + decide +kernel + · have h0 : bitwiseOr (greaterThan w 255#256) (lessThan 36#256 36#256) ≠ 0 := by + simp [bitwiseOr, greaterThan, lessThan]; bv_omega + c1_step + c1_step; c1_step; c1_step + refine Spec.close (revert (byz hf) ?lt ?op ?gas) ?_ + case lt => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case op => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case gas => decide + rintro e ⟨-, herr, hout, -, hs, hss⟩ + refine ⟨?_, ?_, hs, hss⟩ + · rw [herr, spec_dirty (by omega)]; rfl + · rw [hout, spec_dirty (by omega)] + decide +kernel + +/-- The interpreter loop, from the frame that `processMessage` starts, ends as the spec says. -/ +theorem runFrame_spec (hf : Fork.shapella ≤ fork) (w : U256) (message : Message fork) + (hcode : message.code = code) (hv : message.value = 0) (hd : message.data = cd w) + (st : State.TransactionState) (ss : Substate) (g : Nat) (hg : g = 10000000) {bound : Nat} + {runChild : MessageRunner fork Nat bound} + (within : GasMeter.gasHeld (startFrame message st ss g).gas ≤ bound) : + ∃ after, runFrame (step fork) (step_decreases fork) bound runChild + (startFrame message st ss g) within = .ok after ∧ + after.running = false ∧ after.error = (spec w).1 ∧ after.output = (spec w).2 ∧ + after.state = st ∧ after.substate = ss := by + obtain ⟨after, h, herr, hout, hs, hss⟩ := Spec.runFrame (frame_spec hf w message hv hd st ss) + (evm := startFrame message st ss g) + ⟨by simp [startFrame, hcode], by simp [startFrame, hcode], rfl, rfl, rfl, rfl, hg, rfl, rfl, + rfl, rfl, rfl, rfl⟩ within + exact ⟨after, h, running_runFrame h, herr, hout, hs, hss⟩ + +/-- Any spec of the frame at pc 0 gives the result of the interpreter loop, from any equation for +the run (general: any code, any postcondition). -/ +theorem runFrame_of_spec {c : ByteArray} {message : Message fork} {st : State.TransactionState} + {ss : Substate} {g : Nat} {Q : Evm fork Nat → Prop} (hcode : message.code = c) + (h : Spec fork (At c message 0 [] .empty g st ss .empty) Q) {bound : Nat} + {runChild : MessageRunner fork Nat bound} + {within : GasMeter.gasHeld (startFrame message st ss g).gas ≤ bound} {result} + (hr : runFrame (step fork) (step_decreases fork) bound runChild + (startFrame message st ss g) within = result) : + ∃ after, result = .ok after ∧ after.running = false ∧ Q after := by + obtain ⟨after, h', hq⟩ := Spec.runFrame h (evm := startFrame message st ss g) + ⟨by simp [startFrame, hcode], by simp [startFrame, hcode], rfl, rfl, rfl, rfl, rfl, rfl, rfl, + rfl, rfl, rfl, rfl⟩ within (runChild := runChild) + exact ⟨after, hr ▸ h', running_runFrame h', hq⟩ + +/-- A spec of the frame of a message with no value, that fixes the error and the output and +leaves state and substate alone, gives the result of `processMessage` at Fusaka (general: any +code that is no precompile). A failed call is rolled back, so the state is known only on success. -/ +theorem processMessage_of_spec {c : ByteArray} (message : Message .fusaka) + (hcode : message.code = c) (hv : message.value = 0) + (hpre : precompileAddress .fusaka message = none) {E : Option EvmError} {O : ByteArray} + {Q : State.TransactionState → Substate → Evm .fusaka Nat → Prop} + (h : ∀ st ss, Spec .fusaka (At c message 0 [] .empty message.gas st ss .empty) (Q st ss)) + (hQ : ∀ st ss e, Q st ss e → e.error = E ∧ e.output = O ∧ e.state = st ∧ e.substate = ss) + (st : State.TransactionState) (ss : Substate) : + ∃ evm, processMessage (Meter := Nat) .fusaka message st ss = .ok evm ∧ + evm.1.error = E ∧ evm.1.output = O ∧ evm.1.substate = ss ∧ + (E = none → evm.1.state = st) := by + rw [processMessage] + have hss : startState .fusaka message st = st := by + simp [startState, show ¬ (Fork.fusaka < Fork.paris) by decide] + simp only [hss, hpre] + split + · rename_i htr; exact absurd htr.2 (by simp [hv]) + simp only [pure, Except.pure, bind, Except.bind] + split + · rename_i e hr + obtain ⟨after, h', -⟩ := runFrame_of_spec hcode (h _ _) hr + cases h' + · rename_i after hr + obtain ⟨after', h', -, hq⟩ := runFrame_of_spec hcode (h _ _) hr + cases h' + obtain ⟨herr, hout, hst, hsub⟩ := hQ _ _ _ hq + refine ⟨_, rfl, ?_, ?_, ?_, ?_⟩ + · simp only [rollbackOnError]; split <;> simp [herr] + · simp only [rollbackOnError]; split <;> simp [hout] + · simp only [rollbackOnError]; split <;> simp [hsub, hv] + · intro hE + simp only [rollbackOnError, herr, hE, Option.isSome_none, Bool.false_eq_true, ↓reduceIte] + exact hst + +/-- The whole message call of `f` on call data `selector ++ toBeBytes w`, at Fusaka +with 10M gas and no value: for every 256-bit `w`, the error and the output are the spec. -/ +theorem processMessage_spec (w : U256) (message : Message .fusaka) + (hcode : message.code = code) (hv : message.value = 0) (hd : message.data = cd w) + (hgas : message.gas = 10000000) (hpre : precompileAddress .fusaka message = none) + (st : State.TransactionState) (ss : Substate) : + ∃ evm, processMessage (Meter := Nat) .fusaka message st ss = .ok evm ∧ + evm.1.error = (spec w).1 ∧ evm.1.output = (spec w).2 ∧ evm.1.substate = ss ∧ + ((spec w).1 = none → evm.1.state = st) := + processMessage_of_spec message hcode hv hpre + (fun st ss => hgas ▸ frame_spec (by decide) w message hv hd st ss) + (fun _ _ _ h => h) st ss + +/-- The empty revert, as a postcondition. -/ +def Rejected (st : State.TransactionState) (ss : Substate) (evm : Evm fork Nat) : Prop := + evm.error = some .revert ∧ evm.output = .empty ∧ evm.state = st ∧ evm.substate = ss + +theorem rejected_of_halted {st ss g} {e : Evm fork Nat} + (h : Halted true (memoryReadBytes (memoryExtend ByteArray.empty + (extendMemory ByteArray.empty.size [((0 : U256), (0 : U256))]).expandBy) (0 : U256).toNat + (0 : U256).toNat) g st ss e) : Rejected st ss e := by + obtain ⟨-, herr, hout, -, hs, hss⟩ := h + exact ⟨herr, by rw [hout]; decide +kernel, hs, hss⟩ + +/-- Nonzero call value: the non-payable function reverts with no data, for any call data. -/ +theorem frame_spec_value (hf : Fork.shapella ≤ fork) (message : Message fork) + (hv : message.value ≠ 0) (st ss) : + Spec fork (At code message 0 [] .empty 10000000 st ss .empty) (Rejected st ss) := by + c1_step; c1_step; c1_step; c1_step; c1_step; c1_step + refine Spec.close (revert (byz hf) ?lt ?op ?gas) ?_ + case lt => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case op => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case gas => decide + exact fun e h => rejected_of_halted h + +/-- No call value, and call data whose first 4 bytes are not `f`'s selector, or that is shorter +than 36 bytes: the call reverts with no data. -/ +theorem frame_spec_reject (hf : Fork.shapella ≤ fork) (message : Message fork) + (hv : message.value = 0) + (hbad : bytesToNat (bufferRead message.data 0 4) ≠ 0x3120d434 ∨ message.data.size < 36) + (st ss) : + Spec fork (At code message 0 [] .empty 10000000 st ss .empty) (Rejected st ss) := by + have hsel := bitwiseShr_loadWord_zero message.data 4 (by decide) (by decide) + rw [show BitVec.ofNat 256 (8 * (32 - 4)) = 224#256 from rfl] at hsel + have hlt4 := bytesToNat_lt (bufferRead message.data 0 4) + rw [bufferRead_length] at hlt4 + c1_step; c1_step; c1_step; c1_step; c1_step; c1_step; c1_step + rw [hsel] + c1_step; c1_step; c1_step + c1_step + by_cases hs : bytesToNat (bufferRead message.data 0 4) = 0x3120d434 + · have hsize : message.data.size < 36 := hbad.resolve_left (by simpa using hs) + rw [hs] + have h0 : sub (824235060#256) (BitVec.ofNat 256 0x3120d434) = 0 := by decide + c1_step + c1_step; c1_step; c1_step; c1_step; c1_step; c1_step; c1_step; c1_step + have h1 : bitwiseOr (greaterThan (loadWord message.data 4 32) 255#256) + (lessThan (BitVec.ofNat 256 message.data.size) 36#256) ≠ 0 := by + have : lessThan (BitVec.ofNat 256 message.data.size) 36#256 = 1 := by + unfold lessThan + rw [ite_eq_left] + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt (by omega)] + exact hsize + rw [this] + intro h + have := congrArg (BitVec.getLsbD · 0) h + simp [bitwiseOr] at this + c1_step; c1_step; c1_step; c1_step; c1_step + refine Spec.close (revert (byz hf) ?lt ?op ?gas) ?_ + case lt => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case op => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case gas => decide + exact fun e h => rejected_of_halted h + · have h0 : sub (824235060#256) (BitVec.ofNat 256 (bytesToNat (bufferRead message.data 0 4))) ≠ 0 := by + intro h + apply hs + have h' : BitVec.ofNat 256 (bytesToNat (bufferRead message.data 0 4)) = 824235060#256 := by + simp only [sub] at h; bv_omega + have := congrArg BitVec.toNat h' + rw [BitVec.toNat_ofNat, BitVec.toNat_ofNat, Nat.mod_eq_of_lt (by omega)] at this + simpa using this + c1_step + c1_step; c1_step; c1_step + refine Spec.close (revert (byz hf) ?lt ?op ?gas) ?_ + case lt => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case op => evm_code [code, codeNat, Main.runtimeNat, Main.runtimeSize] + case gas => decide + exact fun e h => rejected_of_halted h + +/-- Wrong selector or short call data, as a whole message call: it reverts with no data. -/ +theorem processMessage_reject (message : Message .fusaka) + (hcode : message.code = code) (hv : message.value = 0) (hgas : message.gas = 10000000) + (hpre : precompileAddress .fusaka message = none) + (hbad : bytesToNat (bufferRead message.data 0 4) ≠ 0x3120d434 ∨ message.data.size < 36) + (st : State.TransactionState) (ss : Substate) : + ∃ evm, processMessage (Meter := Nat) .fusaka message st ss = .ok evm ∧ + evm.1.error = some .revert ∧ evm.1.output = .empty ∧ evm.1.substate = ss ∧ + (some EvmError.revert = none → evm.1.state = st) := + processMessage_of_spec message hcode hv hpre + (fun st ss => hgas ▸ frame_spec_reject (by decide) message hv hbad st ss) + (fun _ _ _ h => h) st ss + +end SolidCore.Refinement.C1 diff --git a/SolidCore/Refinement/Check.lean b/SolidCore/Refinement/Check.lean new file mode 100644 index 00000000..d69a71c2 --- /dev/null +++ b/SolidCore/Refinement/Check.lean @@ -0,0 +1,200 @@ +import SolidCore.Refinement.Statement +import EthLib.Base.Proofs.BigEndian + +/-! +# Checking a refinement on a finite set of calls + +`Refines` is a statement about functions: the callee's final storage is a map from +every slot to a word, so it cannot be compared by evaluation. This module turns it +into one that can. + +`agree fuel contract code call` runs both semantics on `call` and compares the +success flag, the output, the logs, and the final storage on a finite list of slots: +every slot either side holds a word for, and every slot of the call's initial +storage. `agree_sound` shows that both sides keep every other slot at zero, and that +both read a slot modulo `2 ^ 256`, so agreement on that list is agreement on every +slot. `refines_of_all` lifts it to `Refines` for a list of calls, which a proof +about a contract then checks with `native_decide`. +-/ + +namespace SolidCore.Refinement + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.State +open SolidCore.Solidity + +/-! ## Storage functions that agree on finitely many slots -/ + +/-- The words a slot is read as on both sides. -/ +abbrev wordSize : Nat := 2 ^ 256 + +/-- Two storage functions that read slots modulo `2 ^ 256`, are zero off `keys` and +agree on `keys` are equal. -/ +theorem storage_ext {f g : Nat → Nat} (keys : List Nat) + (fp : ∀ s, f s = f (s % wordSize)) (gp : ∀ s, g s = g (s % wordSize)) + (fz : ∀ s, s % wordSize ∉ keys → f s = 0) (gz : ∀ s, s % wordSize ∉ keys → g s = 0) + (agree : ∀ k ∈ keys, f k = g k) : f = g := by + funext s + by_cases hk : s % wordSize ∈ keys + · rw [fp, gp]; exact agree _ hk + · rw [fz s hk, gz s hk] + +/-! ## SolidCore's storage -/ + +/-- The slots SolidCore's storage map holds a word for. -/ +def sourceKeys (st : Source.State) : List Nat := st.storage.keys + +theorem norm_mod (s : Nat) : Shared.norm (s % wordSize) = Shared.norm s := by + simp [Shared.norm, Shared.wordModulus, EvmYul.UInt256.size, wordSize] + +theorem loadSlot_mod (st : Source.State) (s : Nat) : + st.loadSlot s = st.loadSlot (s % wordSize) := by + simp only [Source.State.loadSlot, Source.StorageMap.lookup?, norm_mod] + +theorem loadSlot_of_not_mem (st : Source.State) (s : Nat) (h : s % wordSize ∉ sourceKeys st) : + st.loadSlot s = 0 := by + have hn : Shared.norm s = s % wordSize := by + simp [Shared.norm, Shared.wordModulus, EvmYul.UInt256.size, wordSize] + unfold Source.State.loadSlot Source.StorageMap.lookup? + rw [hn, Std.HashMap.get?_eq_getElem?, Std.HashMap.getElem?_eq_none] + intro hm + exact h (Std.HashMap.mem_keys.mpr hm) + +/-! ## The initial storage of a call -/ + +/-- The slots the call's initial storage names. -/ +def callKeys (call : Call) : List Nat := call.storage.map (·.1 % wordSize) + +theorem slotValue_mod (storage : List (Nat × Nat)) (s : Nat) : + slotValue storage s = slotValue storage (s % wordSize) := by + simp [slotValue, wordSize] + +theorem slotValue_of_not_mem (call : Call) (s : Nat) (h : s % wordSize ∉ callKeys call) : + slotValue call.storage s = 0 := by + unfold slotValue + unfold callKeys at h + generalize call.storage = l at h + suffices ∀ acc, acc = 0 → List.foldl (fun acc kv => + if kv.1 % 2 ^ 256 = s % 2 ^ 256 then kv.2 % 2 ^ 256 else acc) acc l = 0 from this 0 rfl + induction l with + | nil => intro acc h; simpa using h + | cons kv l ih => + intro acc hacc + simp only [List.map_cons, List.mem_cons, not_or] at h + simp only [List.foldl_cons] + apply ih h.2 + have hne : ¬ kv.1 % 2 ^ 256 = s % 2 ^ 256 := fun e => h.1 (by simpa [wordSize] using e.symm) + simp only [hne, ite_false, hacc] + +/-! ## EthLib's storage -/ + +/-- The slots one storage map holds a word for at an address, as numbers. -/ +def mapKeys (m : StorageMap) (a : Address) : List Nat := + match m[a]? with + | some slots => slots.keys.map fun k => bytesToNat k.toList + | none => [] + +/-- The slots any layer of a transaction's state holds a word for at an address. -/ +def targetKeys (tx : TransactionState) (a : Address) : List Nat := + mapKeys tx.storageWrites a ++ mapKeys tx.parent.storageWrites a ++ + mapKeys tx.parent.preState.storage a + +theorem toList_storageKey (s : Nat) : (Target.storageKey s).toList = natToBytes 32 s := by + simp [Target.storageKey, Vector.toList] + +theorem storageKey_mod (s : Nat) : Target.storageKey s = Target.storageKey (s % wordSize) := by + apply Vector.toList_inj.mp + rw [toList_storageKey, toList_storageKey] + have h := natToBytes_bytesToNat (natToBytes 32 s) + have h' := natToBytes_bytesToNat (natToBytes 32 (s % wordSize)) + rw [natToBytes_length, bytesToNat_natToBytes] at h h' + rw [← h, ← h', show (256 : Nat) ^ 32 = wordSize by decide, Nat.mod_mod] + +theorem slot_of_not_mem (m : StorageMap) (a : Address) (s : Nat) + (h : s % wordSize ∉ mapKeys m a) : m.slot a (Target.storageKey s) = none := by + unfold StorageMap.slot + unfold mapKeys at h + cases hm : m[a]? with + | none => rfl + | some slots => + rw [hm] at h + simp only [Option.bind_some] + rw [Std.ExtTreeMap.getElem?_eq_none] + intro hk + apply h + refine List.mem_map.mpr ⟨_, Std.ExtTreeMap.mem_keys.mpr hk, ?_⟩ + rw [toList_storageKey, bytesToNat_natToBytes] + rfl + +theorem getStorage_of_not_mem (tx : TransactionState) (a : Address) (s : Nat) + (h : s % wordSize ∉ targetKeys tx a) : tx.getStorage a (Target.storageKey s) = 0 := by + simp only [targetKeys, List.mem_append, not_or] at h + obtain ⟨⟨h1, h2⟩, h3⟩ := h + unfold TransactionState.getStorage State.getStorage + rw [slot_of_not_mem _ _ _ h1, slot_of_not_mem _ _ _ h2, slot_of_not_mem _ _ _ h3] + simp + +/-! ## The check -/ + +/-- The final storage of a successful call, slot by slot, as `Target.run` reads it. -/ +def targetSlot (tx : TransactionState) (s : Nat) : Nat := + (tx.getStorage (Target.address selfAddress) (Target.storageKey s)).toNat + +/-- Whether SolidCore with `fuel` and EthLib both finish `call` and show the same +success flag, output and logs, and the same final storage on every slot either side +or the call names. -/ +def agree (fuel : Nat) (contract : TypeCheck.CheckedContract) (code : ByteArray) + (call : Call) : Bool := + match Source.result? fuel contract call, + processMessage (Meter := Nat) .fusaka (Target.message code call) + (Target.preState code call) Substate.empty, Target.run code call with + | some r, .ok ⟨evm, _⟩, some tgt => + let src := Source.observe call r + src.success == tgt.success && src.output == tgt.output && src.logs == tgt.logs && + (sourceKeys r.state ++ targetKeys evm.state (Target.address selfAddress) ++ + callKeys call).all fun k => src.storage k == tgt.storage k + | _, _, _ => false + +theorem agree_sound {fuel : Nat} {contract : TypeCheck.CheckedContract} {code : ByteArray} + {call : Call} (h : agree fuel contract code call = true) : + ∃ obs, Source.run fuel contract call = some obs ∧ Target.run code call = some obs := by + unfold agree at h + split at h + next r evm sub tgt hr hpm htgt => + have hsrc : Source.run fuel contract call = some (Source.observe call r) := by + simp [Source.run, hr] + refine ⟨_, hsrc, ?_⟩ + rw [htgt] + simp only [Bool.and_eq_true, beq_iff_eq, List.all_eq_true] at h + obtain ⟨⟨⟨hs, ho⟩, hl⟩, hk⟩ := h + have htgt' := htgt + simp only [Target.run, hpm, Option.some.injEq] at htgt' + subst htgt' + congr 1 + symm + simp only [Source.observe] at hs ho hl hk ⊢ + rw [Observable.mk.injEq] + refine ⟨hs, ho, hl, ?_⟩ + rw [hs] at hk ⊢ + cases hsucc : evm.error.isNone + · rfl + · simp only [hsucc, ite_true] at hk ⊢ + apply storage_ext (sourceKeys r.state ++ targetKeys evm.state (Target.address selfAddress) ++ + callKeys call) (fun s => by rw [loadSlot_mod]) + (fun s => by rw [storageKey_mod]) + (fun s hs' => loadSlot_of_not_mem _ _ (fun m => hs' (List.mem_append_left _ + (List.mem_append_left _ m)))) + (fun s hs' => by + rw [getStorage_of_not_mem _ _ _ (fun m => hs' (List.mem_append_left _ + (List.mem_append_right _ m)))] + rfl) + intro k hk' + exact hk k hk' + next => exact absurd h (by simp) + +/-- `code` refines `contract` on every call of a list that `agree` accepts. -/ +theorem refines_of_all {fuel : Nat} {contract : TypeCheck.CheckedContract} {code : ByteArray} + {calls : List Call} (h : calls.all (agree fuel contract code) = true) : + Refines fuel contract code (· ∈ calls) := fun _ hc => + agree_sound (List.all_eq_true.mp h _ hc) + +end SolidCore.Refinement diff --git a/SolidCore/Refinement/Compose.lean b/SolidCore/Refinement/Compose.lean new file mode 100644 index 00000000..d4d68df8 --- /dev/null +++ b/SolidCore/Refinement/Compose.lean @@ -0,0 +1,58 @@ +import SolidCore.Refinement.Statement + +/-! +# Composing refinements across compiler stages + +`Refines` relates a SolidCore contract to EVM bytecode in one step. A compiler +proves it in stages: Solidity to MIR, each MIR pass, MIR to EVM IR, each EVM IR +pass, and assembly. This module fixes the interface every stage's certificate +states, so that the stages compose into `Refines`. + +A `Sem` is a language with a run function from a program and a `Call` to an +`Observable`, the same call and observable `Statement.lean` uses: the call data, +call value and initial storage go in; success, output bytes, logs and the final +storage function come out. `none` means the run did not finish: out of fuel, +or an error of the semantics itself. + +A stage from `A` to `B` certifies `Stage A B p q scope`: on every call in +`scope` on which the source program `p` finishes, the target `q` finishes with the +same observable. Termination and fuel are each semantics' own business; a stage +only promises to preserve a finished run. `Stage.trans` composes stages, and +`refines_of_stage` turns a chain ending at EthLib into `Refines` once the source +side is known to finish on the scope. +-/ + +namespace SolidCore.Refinement + +-- A language (Sem: programs and how one runs on a call) and a stage between two (Stage, +-- with Stage.trans) are solar's SolarTV.Sem definitions, used directly. +export SolarTV (Sem Sem.mk Stage Stage.trans) + +/-- SolidCore with fixed fuel, on checked contracts. -/ +def solidCore (fuel : Nat) : Sem := + { Prog := SolidCore.Solidity.TypeCheck.CheckedContract, run := Source.run fuel } + +/-- EthLib on runtime bytecode. -/ +def ethLib : Sem := { Prog := ByteArray, run := Target.run } + +/-- A chain of stages from SolidCore to EthLib gives `Refines` on the calls where +SolidCore finishes. -/ +theorem refines_of_stage {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {code : ByteArray} {scope : Call → Prop} + (h : Stage (solidCore fuel) ethLib contract code scope) + (fin : ∀ call, scope call → (Source.run fuel contract call).isSome) : + Refines fuel contract code scope := by + intro call hc + obtain ⟨obs, hobs⟩ := Option.isSome_iff_exists.mp (fin call hc) + exact ⟨obs, hobs, h call hc obs hobs⟩ + +/-- `Refines` is a stage from SolidCore to EthLib. -/ +theorem stage_of_refines {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {code : ByteArray} {scope : Call → Prop} (h : Refines fuel contract code scope) : + Stage (solidCore fuel) ethLib contract code scope := by + intro call hc obs hobs + obtain ⟨obs', h1, h2⟩ := h call hc + have : obs' = obs := Option.some.inj (h1.symm.trans hobs) + exact this ▸ h2 + +end SolidCore.Refinement diff --git a/SolidCore/Refinement/ComposeSeq.lean b/SolidCore/Refinement/ComposeSeq.lean new file mode 100644 index 00000000..4eb536f4 --- /dev/null +++ b/SolidCore/Refinement/ComposeSeq.lean @@ -0,0 +1,533 @@ +import SolidCore.Refinement.Spec +import SolidCore.Refinement.Sequence + +/-! +# Composing refinements across compiler stages, for sequences of calls + +\`Compose.lean\` relates one call: a \`Stage A B p q scope\` says that on every call of \`scope\` +on which \`p\` finishes, \`q\` finishes with the same observable. A deployed contract sees a +sequence of calls, each starting from the storage the previous one left. This module lifts +the single-call interface to sequences, additively: nothing of \`Compose.lean\`, \`Spec.lean\` +or SolarTV's \`Sem\` changes. + +## Carrying storage + +A \`Call\` takes its initial storage as a list of (slot, value) pairs, while +\`Observable.storage\` is a function of every slot. A sequence therefore runs with a +\`Carry\`: the list the next call starts from, given the call before it and what it +showed. \`runCalls\` runs a list of messages (\`Msg\`: call data and value) from an initial +storage list, giving the list of observables, or \`none\` when any call does not finish. +\`seqRun S p\` is that run in the language \`S\`. \`Carries carry call obs\` says the carried +list reads back, slot by slot through \`slotValue\`, as exactly the final storage of \`obs\`, +so the next call starts from the previous call's final storage. \`writeBack W\` carries the +previous call's list with the slots \`W\` overwritten by their final values, which is exact +for a call that changes only slots of \`W\` (\`carries_writeBack\`). + +## Stages, specifications and refinement of sequences + +A sequence scope is a predicate on the initial storage and the messages. + +* \`StageSeq A B p q carry scope\`: on every sequence of \`scope\` that \`p\` finishes, \`q\` + finishes with the same observables. \`StageSeq.trans\` composes stages. +* \`StageSeq.of_stage\`: a single-call stage holds on every sequence whose calls stay in its + scope (\`Along\`), so \`StageSeq.of_invariant\` lifts a stage to the sequences from a set of + storages \`St\` of messages of \`M\` when \`St\` is closed under the calls (every storage + a call from \`St\` produces is in \`St\`), and \`StageSeq.of_anyStorage\` lifts a stage + proved from any storage to every sequence. +* \`SatisfiesSeq\` is the sequence form of \`Satisfies\`, \`RefinesSeqOn\` the sequence form + of \`Refines\`; \`bytecodeSeq_of_refines\` and \`bytecodeSeq_of_stages\` carry a sequence + specification from SolidCore to bytecode, as \`bytecode_of_refines\` and + \`bytecode_of_stages\` do for one call. \`bytecodeSeq_of_stages_invariant\` is the form the + milestones use: single-call stages, a single-call specification and a storage set + closed under that specification give, on bytecode, every call of every sequence meeting + the specification (\`Each\`). +* Length 1: \`stageSeq_single_iff\`, \`satisfiesSeq_single_iff\` and + \`refinesSeqOn_single_iff\` recover \`Stage\`, \`Satisfies\` and \`Refines\` as the + sequences of one message (\`single\`). +* \`refinesSeqOn_of_refinesSeq\` and \`refinesSeq_of_refinesSeqOn\` relate \`RefinesSeqOn\` + to \`Sequence.lean\`'s \`RefinesSeq\`, whose carried list depends on the observable only. +-/ + +namespace SolidCore.Refinement + +/-! ## Runs of sequences -/ + +/-- How a sequence carries storage from one call to the next: the storage list the next call +starts from, given the call before it and what that call showed. -/ +abbrev Carry := Call → Observable → List (Nat × Nat) + +/-- Run the messages \`ms\` one after the other with \`run\`, the first from \`σ\` and each later +one from the storage \`carry\` gives for the call before it. \`none\` when any run is \`none\`. -/ +def runCalls (run : Call → Option Observable) (carry : Carry) : + List (Nat × Nat) → List Msg → Option (List Observable) + | _, [] => some [] + | σ, m :: ms => + match run (m.call σ) with + | some obs => (runCalls run carry (carry (m.call σ) obs) ms).map (obs :: ·) + | none => none + +/-- The run of the messages \`ms\` from \`σ\` with the program \`p\` of the language \`S\`. -/ +def seqRun (S : Sem) (p : S.Prog) (carry : Carry) (σ : List (Nat × Nat)) (ms : List Msg) : + Option (List Observable) := + runCalls (S.run p) carry σ ms + +/-- A sequence of messages finishes as its first call and the rest from its carried storage +do. -/ +theorem runCalls_cons_eq_some {run : Call → Option Observable} {carry : Carry} + {σ : List (Nat × Nat)} {m : Msg} {ms : List Msg} {obss : List Observable} : + runCalls run carry σ (m :: ms) = some obss ↔ + ∃ obs os, run (m.call σ) = some obs ∧ + runCalls run carry (carry (m.call σ) obs) ms = some os ∧ obss = obs :: os := by + simp only [runCalls] + cases h : run (m.call σ) with + | none => simp + | some obs => + simp only [Option.map_eq_some_iff, Option.some.injEq] + constructor + · rintro ⟨os, hos, rfl⟩ + exact ⟨obs, os, rfl, hos, rfl⟩ + · rintro ⟨_, os, rfl, hos, rfl⟩ + exact ⟨os, hos, rfl⟩ + +/-- A sequence of one message runs as its call. -/ +theorem runCalls_singleton (run : Call → Option Observable) (carry : Carry) + (σ : List (Nat × Nat)) (m : Msg) : + runCalls run carry σ [m] = (run (m.call σ)).map ([·]) := by + simp only [runCalls] + cases run (m.call σ) <;> rfl + +/-- A run carries one observable for each message. -/ +theorem length_of_runCalls {run : Call → Option Observable} {carry : Carry} : + ∀ {σ : List (Nat × Nat)} {ms : List Msg} {obss : List Observable}, + runCalls run carry σ ms = some obss → obss.length = ms.length + | _, [], _, h => by cases h; rfl + | _, _ :: _, _, h => by + obtain ⟨_, _, _, hos, rfl⟩ := runCalls_cons_eq_some.mp h + simp [length_of_runCalls hos] + +/-- The message of \`call\`: its call data and value, without its storage. -/ +def Msg.of (call : Call) : Msg := { calldata := call.calldata, callvalue := call.callvalue } + +/-- Every call is its message from its storage. -/ +theorem Msg.of_call (call : Call) : (Msg.of call).call call.storage = call := by + cases call + rfl + +/-! ## Carried storage -/ + +/-- The storage list \`carry\` gives after \`call\` reads as exactly the final storage of \`obs\`. -/ +def Carries (carry : Carry) (call : Call) (obs : Observable) : Prop := + slotValue (carry call obs) = obs.storage + +/-- Carry the previous call's storage list with the slots \`W\` overwritten by their final +values. -/ +def writeBack (W : List Nat) : Carry := + fun call obs => call.storage ++ W.map fun k => (k, obs.storage k) + +/-- A pair appended to a storage list wins for its slot. -/ +theorem slotValue_append_pair (σ : List (Nat × Nat)) (k v slot : Nat) : + slotValue (σ ++ [(k, v)]) slot = + if k % 2 ^ 256 = slot % 2 ^ 256 then v % 2 ^ 256 else slotValue σ slot := by + simp [slotValue, List.foldl_append] + +/-- \`writeBack W\` carries exactly the final storage of a call that keeps every slot outside +\`W\` (modulo \`2 ^ 256\`), whose final storage gives the same word for slots equal modulo +\`2 ^ 256\` and holds words below \`2 ^ 256\`. -/ +theorem carries_writeBack {W : List Nat} {call : Call} {obs : Observable} + (hkeep : ∀ slot, (∀ k ∈ W, k % 2 ^ 256 ≠ slot % 2 ^ 256) → + obs.storage slot = slotValue call.storage slot) + (hmod : ∀ slot, obs.storage slot = obs.storage (slot % 2 ^ 256)) + (hlt : ∀ slot, obs.storage slot < 2 ^ 256) : + Carries (writeBack W) call obs := by + have key : ∀ (V : List Nat) (σ : List (Nat × Nat)) (slot : Nat), + slotValue (σ ++ V.map fun k => (k, obs.storage k)) slot = + if ∃ k ∈ V, k % 2 ^ 256 = slot % 2 ^ 256 then obs.storage slot else slotValue σ slot := by + intro V + induction V with + | nil => intro σ slot; simp + | cons k V ih => + intro σ slot + rw [List.map_cons, show ∀ (l : List (Nat × Nat)) a, σ ++ a :: l = (σ ++ [a]) ++ l by simp, + ih, slotValue_append_pair] + by_cases hV : ∃ k' ∈ V, k' % 2 ^ 256 = slot % 2 ^ 256 + · obtain ⟨k', hk', e⟩ := hV + rw [ite_eq_left ⟨k', hk', e⟩, ite_eq_left ⟨k', List.mem_cons_of_mem _ hk', e⟩] + · rw [ite_eq_right hV] + by_cases e : k % 2 ^ 256 = slot % 2 ^ 256 + · rw [ite_eq_left e, ite_eq_left ⟨k, List.mem_cons_self, e⟩, Nat.mod_eq_of_lt (hlt k), hmod k, + hmod slot, e] + · have : ¬ ∃ k' ∈ k :: V, k' % 2 ^ 256 = slot % 2 ^ 256 := by + rintro ⟨k', hk', e'⟩ + rcases List.mem_cons.mp hk' with rfl | hk' + · exact e e' + · exact hV ⟨k', hk', e'⟩ + rw [ite_eq_right e, ite_eq_right this] + funext slot + unfold writeBack + rw [key W call.storage slot] + split + · rfl + · rename_i h + exact (hkeep slot fun k hk e => h ⟨k, hk, e⟩).symm + +/-! ## Stages of sequences -/ + +/-- A sequence scope: which initial storages and lists of messages a statement covers. -/ +abbrev SeqScope := List (Nat × Nat) → List Msg → Prop + +/-- Every call the run of \`run\` on \`ms\` from \`σ\` makes, as far as it finishes, is in +\`scope\`. -/ +def Along (run : Call → Option Observable) (carry : Carry) (scope : Call → Prop) : SeqScope + | _, [] => True + | σ, m :: ms => scope (m.call σ) ∧ + ∀ obs, run (m.call σ) = some obs → Along run carry scope (carry (m.call σ) obs) ms + +/-- The sequences of messages of \`M\` from a storage of \`St\`. -/ +def within (St : List (Nat × Nat) → Prop) (M : Msg → Prop) : SeqScope := + fun σ ms => St σ ∧ ∀ m ∈ ms, M m + +/-- The sequences of one message, whose call is in \`scope\`. -/ +def single (scope : Call → Prop) : SeqScope := fun σ ms => ∃ m, ms = [m] ∧ scope (m.call σ) + +/-- \`StageSeq A B p q carry scope\`: on every sequence of \`scope\` that \`p\` finishes, \`q\` +finishes with the same observables, each call carrying storage to the next with \`carry\`. -/ +def StageSeq (A B : Sem) (p : A.Prog) (q : B.Prog) (carry : Carry) (scope : SeqScope) : Prop := + ∀ σ ms, scope σ ms → ∀ obss, seqRun A p carry σ ms = some obss → seqRun B q carry σ ms = some obss + +theorem StageSeq.refl (A : Sem) (p : A.Prog) (carry : Carry) (scope : SeqScope) : + StageSeq A A p p carry scope := + fun _ _ _ _ h => h + +/-- Stages of sequences compose. -/ +theorem StageSeq.trans {A B C : Sem} {p : A.Prog} {q : B.Prog} {r : C.Prog} {carry : Carry} + {scope : SeqScope} (first : StageSeq A B p q carry scope) + (second : StageSeq B C q r carry scope) : StageSeq A C p r carry scope := + fun σ ms h obss ran => second σ ms h obss (first σ ms h obss ran) + +/-- A stage of sequences holds on any narrower scope. -/ +theorem StageSeq.mono {A B : Sem} {p : A.Prog} {q : B.Prog} {carry : Carry} + {scope narrower : SeqScope} (stage : StageSeq A B p q carry scope) + (hn : ∀ σ ms, narrower σ ms → scope σ ms) : StageSeq A B p q carry narrower := + fun σ ms h => stage σ ms (hn σ ms h) + +/-- A single-call stage holds on every sequence whose calls, as the source runs them, stay in +its scope. -/ +theorem StageSeq.of_stage {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (carry : Carry) (stage : Stage A B p q scope) : + StageSeq A B p q carry (Along (A.run p) carry scope) := by + intro σ ms + induction ms generalizing σ with + | nil => exact fun _ _ h => h + | cons m ms ih => + rintro ⟨hs, hrest⟩ obss hrun + obtain ⟨obs, os, h1, h2, rfl⟩ := runCalls_cons_eq_some.mp hrun + exact runCalls_cons_eq_some.mpr + ⟨obs, os, stage _ hs obs h1, ih _ (hrest obs h1) os h2, rfl⟩ + +/-- From a set of storages \`St\` closed under the calls of messages of \`M\` that \`run\` +finishes, inside \`scope\`, every call of every sequence stays in \`scope\`. -/ +theorem along_of_invariant {run : Call → Option Observable} {carry : Carry} + {scope : Call → Prop} {St : List (Nat × Nat) → Prop} {M : Msg → Prop} + (hin : ∀ σ m, St σ → M m → scope (m.call σ)) + (hclosed : ∀ σ m obs, St σ → M m → run (m.call σ) = some obs → St (carry (m.call σ) obs)) : + ∀ σ ms, within St M σ ms → Along run carry scope σ ms := by + intro σ ms + induction ms generalizing σ with + | nil => exact fun _ => trivial + | cons m ms ih => + rintro ⟨hσ, hms⟩ + have hm := hms m List.mem_cons_self + exact ⟨hin σ m hσ hm, fun obs h => + ih _ ⟨hclosed σ m obs hσ hm h, fun m' hm' => hms m' (List.mem_cons_of_mem _ hm')⟩⟩ + +/-- **A single-call stage on a storage-invariant scope lifts to sequences.** If every call of a +message of \`M\` from a storage of \`St\` is in the stage's scope, and every storage such a call +of the source leaves (as \`carry\` carries it) is in \`St\` again, the stage holds on every +sequence of messages of \`M\` from a storage of \`St\`. -/ +theorem StageSeq.of_invariant {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + {carry : Carry} {St : List (Nat × Nat) → Prop} {M : Msg → Prop} + (stage : Stage A B p q scope) (hin : ∀ σ m, St σ → M m → scope (m.call σ)) + (hclosed : ∀ σ m obs, St σ → M m → A.run p (m.call σ) = some obs → + St (carry (m.call σ) obs)) : + StageSeq A B p q carry (within St M) := + (StageSeq.of_stage carry stage).mono (along_of_invariant hin hclosed) + +/-- A single-call stage proved from any storage, on every call of a message of \`M\`, holds on +every sequence of messages of \`M\` from any storage, whatever \`carry\` carries. -/ +theorem StageSeq.of_anyStorage {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + {M : Msg → Prop} (carry : Carry) (stage : Stage A B p q scope) + (hin : ∀ σ m, M m → scope (m.call σ)) : + StageSeq A B p q carry (within (fun _ => True) M) := + StageSeq.of_invariant stage (fun σ m _ hm => hin σ m hm) fun _ _ _ _ _ _ => trivial + +/-- **Length 1.** A stage of the sequences of one message is a single-call stage. -/ +theorem stageSeq_single_iff {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (carry : Carry) : StageSeq A B p q carry (single scope) ↔ Stage A B p q scope := by + constructor + · intro h call hc obs hrun + have := h call.storage [Msg.of call] ⟨_, rfl, by rw [Msg.of_call]; exact hc⟩ [obs] + (by simp only [seqRun, runCalls_singleton, Msg.of_call, hrun]; rfl) + simp only [seqRun, runCalls_singleton, Msg.of_call, Option.map_eq_some_iff, + List.cons.injEq, and_true] at this + obtain ⟨o, ho, rfl⟩ := this + exact ho + · rintro h σ _ ⟨m, rfl, hc⟩ obss hrun + simp only [seqRun, runCalls_singleton, Option.map_eq_some_iff] at hrun ⊢ + obtain ⟨obs, hobs, rfl⟩ := hrun + exact ⟨obs, h _ hc obs hobs, rfl⟩ + +/-! ## Specifications of sequences -/ + +/-- Every call of a run, with its observable, meets \`post\`: \`Each post carry σ ms obss\` when +\`obss\` has one observable for each message of \`ms\` and each meets \`post\` with its call, the +first from \`σ\` and each later one from the storage \`carry\` carries. -/ +def Each (post : Call → Observable → Prop) (carry : Carry) : + List (Nat × Nat) → List Msg → List Observable → Prop + | _, [], [] => True + | σ, m :: ms, obs :: os => post (m.call σ) obs ∧ Each post carry (carry (m.call σ) obs) ms os + | _, _, _ => False + +/-- \`SatisfiesSeq S p carry scope pre post\`: \`p\` finishes every sequence of \`scope\` that +meets \`pre\`, with observables that meet \`post\`. -/ +def SatisfiesSeq (S : Sem) (p : S.Prog) (carry : Carry) (scope pre : SeqScope) + (post : List (Nat × Nat) → List Msg → List Observable → Prop) : Prop := + ∀ σ ms, scope σ ms → pre σ ms → ∃ obss, seqRun S p carry σ ms = some obss ∧ post σ ms obss + +/-- A stage of sequences carries a specification of sequences from its source to its +target. -/ +theorem SatisfiesSeq.of_stageSeq {A B : Sem} {p : A.Prog} {q : B.Prog} {carry : Carry} + {scope pre : SeqScope} {post : List (Nat × Nat) → List Msg → List Observable → Prop} + (h : SatisfiesSeq A p carry scope pre post) (stage : StageSeq A B p q carry scope) : + SatisfiesSeq B q carry scope pre post := by + intro σ ms hs hp + obtain ⟨obss, hrun, hpost⟩ := h σ ms hs hp + exact ⟨obss, stage σ ms hs obss hrun, hpost⟩ + +/-- The precondition of a sequence of one message: its call meets \`pre\`. -/ +def singlePre (pre : Call → Prop) : SeqScope := fun σ ms => ∀ m, ms = [m] → pre (m.call σ) + +/-- The postcondition of a sequence of one message: it shows one observable, which meets +\`post\` with its call. -/ +def singlePost (post : Call → Observable → Prop) : + List (Nat × Nat) → List Msg → List Observable → Prop := + fun σ ms obss => ∀ m, ms = [m] → ∃ obs, obss = [obs] ∧ post (m.call σ) obs + +/-- **Length 1.** A specification of the sequences of one message is a single-call +specification. -/ +theorem satisfiesSeq_single_iff {S : Sem} {p : S.Prog} {scope pre : Call → Prop} + {post : Call → Observable → Prop} (carry : Carry) : + SatisfiesSeq S p carry (single scope) (singlePre pre) (singlePost post) ↔ + Satisfies S p scope pre post := by + constructor + · intro h call hc hp + obtain ⟨obss, hrun, hpost⟩ := h call.storage [Msg.of call] + ⟨_, rfl, by rw [Msg.of_call]; exact hc⟩ + (fun m hm => by cases hm; rw [Msg.of_call]; exact hp) + obtain ⟨obs, rfl, hobs⟩ := hpost _ rfl + rw [Msg.of_call] at hobs + simp only [seqRun, runCalls_singleton, Msg.of_call, Option.map_eq_some_iff, + List.cons.injEq, and_true] at hrun + obtain ⟨o, ho, rfl⟩ := hrun + exact ⟨o, ho, hobs⟩ + · rintro h σ _ ⟨m, rfl, hc⟩ hp + obtain ⟨obs, hrun, hpost⟩ := h _ hc (hp m rfl) + refine ⟨[obs], by simp only [seqRun, runCalls_singleton, hrun]; rfl, ?_⟩ + rintro m' hm' + cases hm' + exact ⟨obs, rfl, hpost⟩ + +/-- A run of a program that satisfies a specification meets its postcondition. -/ +theorem Satisfies.post_of_run {S : Sem} {p : S.Prog} {scope pre : Call → Prop} + {post : Call → Observable → Prop} (h : Satisfies S p scope pre post) {call : Call} + (hc : scope call) (hp : pre call) {obs : Observable} (hrun : S.run p call = some obs) : + post call obs := by + obtain ⟨o, ho, hpost⟩ := h call hc hp + rw [hrun] at ho + cases ho + exact hpost + +/-- A specification holds with any weaker postcondition. -/ +theorem Satisfies.mono {S : Sem} {p : S.Prog} {scope pre : Call → Prop} + {post post' : Call → Observable → Prop} (h : Satisfies S p scope pre post) + (hpost : ∀ call obs, scope call → pre call → post call obs → post' call obs) : + Satisfies S p scope pre post' := by + intro call hc hp + obtain ⟨obs, hrun, hq⟩ := h call hc hp + exact ⟨obs, hrun, hpost call obs hc hp hq⟩ + +/-- **A single-call specification on a storage-invariant scope lifts to sequences.** If every +call of a message of \`M\` from a storage of \`St\` is in the scope and meets the precondition, +and every storage a call that meets the postcondition leaves (as \`carry\` carries it) is in +\`St\` again, then \`p\` finishes every sequence of messages of \`M\` from a storage of \`St\`, and +every call of it meets the postcondition. -/ +theorem Satisfies.toSeq {S : Sem} {p : S.Prog} {scope pre : Call → Prop} + {post : Call → Observable → Prop} {carry : Carry} {St : List (Nat × Nat) → Prop} + {M : Msg → Prop} (h : Satisfies S p scope pre post) + (hin : ∀ σ m, St σ → M m → scope (m.call σ) ∧ pre (m.call σ)) + (hclosed : ∀ σ m obs, St σ → M m → post (m.call σ) obs → St (carry (m.call σ) obs)) : + SatisfiesSeq S p carry (within St M) (fun _ _ => True) (Each post carry) := by + intro σ ms hs _ + induction ms generalizing σ with + | nil => exact ⟨[], rfl, trivial⟩ + | cons m ms ih => + obtain ⟨hσ, hms⟩ := hs + have hm := hms m List.mem_cons_self + obtain ⟨hc, hp⟩ := hin σ m hσ hm + obtain ⟨obs, hrun, hpost⟩ := h _ hc hp + obtain ⟨os, hos, heach⟩ := + ih _ ⟨hclosed σ m obs hσ hm hpost, fun m' hm' => hms m' (List.mem_cons_of_mem _ hm')⟩ + exact ⟨obs :: os, runCalls_cons_eq_some.mpr ⟨obs, os, hrun, hos, rfl⟩, hpost, heach⟩ + +/-- \`Each\` of a postcondition that implies another implies \`Each\` of the other. -/ +theorem Each.mono {post post' : Call → Observable → Prop} {carry : Carry} + (h : ∀ call obs, post call obs → post' call obs) : + ∀ {σ ms obss}, Each post carry σ ms obss → Each post' carry σ ms obss + | _, [], [], _ => trivial + | _, _ :: _, _ :: _, ⟨hp, hrest⟩ => ⟨h _ _ hp, Each.mono h hrest⟩ + +/-! ## Refinement of sequences, and specifications carried to bytecode -/ + +/-- \`code\` implements \`contract\` on every sequence of \`scope\`: SolidCore with \`fuel\` and +EthLib both finish every call and show the same observables, each call starting from the +storage \`carry\` carries from the one before. -/ +def RefinesSeqOn (fuel : Nat) (contract : SolidCore.Solidity.TypeCheck.CheckedContract) + (code : ByteArray) (carry : Carry) (scope : SeqScope) : Prop := + ∀ σ ms, scope σ ms → + ∃ obss, seqRun (solidCore fuel) contract carry σ ms = some obss ∧ + seqRun ethLib code carry σ ms = some obss + +/-- A stage of sequences from SolidCore to EthLib gives \`RefinesSeqOn\` on the sequences +SolidCore finishes. -/ +theorem refinesSeqOn_of_stageSeq {fuel : Nat} + {contract : SolidCore.Solidity.TypeCheck.CheckedContract} {code : ByteArray} + {carry : Carry} {scope : SeqScope} + (h : StageSeq (solidCore fuel) ethLib contract code carry scope) + (fin : ∀ σ ms, scope σ ms → (seqRun (solidCore fuel) contract carry σ ms).isSome) : + RefinesSeqOn fuel contract code carry scope := by + intro σ ms hs + obtain ⟨obss, hobss⟩ := Option.isSome_iff_exists.mp (fin σ ms hs) + exact ⟨obss, hobss, h σ ms hs obss hobss⟩ + +/-- \`RefinesSeqOn\` is a stage of sequences from SolidCore to EthLib. -/ +theorem stageSeq_of_refinesSeqOn {fuel : Nat} + {contract : SolidCore.Solidity.TypeCheck.CheckedContract} {code : ByteArray} + {carry : Carry} {scope : SeqScope} (h : RefinesSeqOn fuel contract code carry scope) : + StageSeq (solidCore fuel) ethLib contract code carry scope := by + intro σ ms hs obss hrun + obtain ⟨obss', h1, h2⟩ := h σ ms hs + have : obss' = obss := Option.some.inj (h1.symm.trans hrun) + exact this ▸ h2 + +/-- **Length 1.** Refinement of the sequences of one message is \`Refines\`. -/ +theorem refinesSeqOn_single_iff {fuel : Nat} + {contract : SolidCore.Solidity.TypeCheck.CheckedContract} {code : ByteArray} + {scope : Call → Prop} (carry : Carry) : + RefinesSeqOn fuel contract code carry (single scope) ↔ Refines fuel contract code scope := by + constructor + · intro h call hc + obtain ⟨obss, h1, h2⟩ := h call.storage [Msg.of call] ⟨_, rfl, by rw [Msg.of_call]; exact hc⟩ + simp only [seqRun, runCalls_singleton, Msg.of_call, Option.map_eq_some_iff] at h1 h2 + obtain ⟨o1, ho1, rfl⟩ := h1 + obtain ⟨o2, ho2, e⟩ := h2 + cases e + exact ⟨o1, ho1, ho2⟩ + · rintro h σ _ ⟨m, rfl, hc⟩ + obtain ⟨obs, h1, h2⟩ := h _ hc + refine ⟨[obs], ?_, ?_⟩ + · show runCalls _ _ _ _ = _ + simp only [runCalls_singleton] + exact congrArg (Option.map _) h1 + · show runCalls _ _ _ _ = _ + simp only [runCalls_singleton] + exact congrArg (Option.map _) h2 + +/-- A specification of sequences SolidCore satisfies holds of bytecode that refines it on +those sequences. -/ +theorem bytecodeSeq_of_refines {fuel : Nat} + {contract : SolidCore.Solidity.TypeCheck.CheckedContract} {code : ByteArray} + {carry : Carry} {scope pre : SeqScope} + {post : List (Nat × Nat) → List Msg → List Observable → Prop} + (spec : SatisfiesSeq (solidCore fuel) contract carry scope pre post) + (refines : RefinesSeqOn fuel contract code carry scope) : + SatisfiesSeq ethLib code carry scope pre post := + spec.of_stageSeq (stageSeq_of_refinesSeqOn refines) + +/-- A specification of sequences SolidCore satisfies holds of the bytecode a compiler produces +through lowered MIR and EVM IR, given each of its stages on those sequences; the sequence form +of \`bytecode_of_stages\`. -/ +theorem bytecodeSeq_of_stages {fuel : Nat} {mirSem evmirSem : Sem} + {contract : SolidCore.Solidity.TypeCheck.CheckedContract} {mir : mirSem.Prog} + {evmir : evmirSem.Prog} {code : ByteArray} {carry : Carry} {scope pre : SeqScope} + {post : List (Nat × Nat) → List Msg → List Observable → Prop} + (spec : SatisfiesSeq (solidCore fuel) contract carry scope pre post) + (lowering : StageSeq (solidCore fuel) mirSem contract mir carry scope) + (backend : StageSeq mirSem evmirSem mir evmir carry scope) + (assembly : StageSeq evmirSem ethLib evmir code carry scope) : + SatisfiesSeq ethLib code carry scope pre post := + spec.of_stageSeq ((lowering.trans backend).trans assembly) + +/-- **Single-call stages on a storage-invariant scope give the bytecode's sequences.** A +single-call specification SolidCore satisfies and single-call stages through lowered MIR and EVM +IR, with a set of storages \`St\` from which every call of a message of \`M\` is in the scope and +meets the precondition, and which every call meeting the postcondition leaves storage in, give: +the bytecode finishes every sequence of messages of \`M\` from a storage of \`St\`, and every call +of it meets the postcondition. -/ +theorem bytecodeSeq_of_stages_invariant {fuel : Nat} {mirSem evmirSem : Sem} + {contract : SolidCore.Solidity.TypeCheck.CheckedContract} {mir : mirSem.Prog} + {evmir : evmirSem.Prog} {code : ByteArray} {scope pre : Call → Prop} + {post : Call → Observable → Prop} {carry : Carry} {St : List (Nat × Nat) → Prop} + {M : Msg → Prop} + (spec : Satisfies (solidCore fuel) contract scope pre post) + (lowering : Stage (solidCore fuel) mirSem contract mir scope) + (backend : Stage mirSem evmirSem mir evmir scope) + (assembly : Stage evmirSem ethLib evmir code scope) + (hin : ∀ σ m, St σ → M m → scope (m.call σ) ∧ pre (m.call σ)) + (hclosed : ∀ σ m obs, St σ → M m → post (m.call σ) obs → St (carry (m.call σ) obs)) : + SatisfiesSeq ethLib code carry (within St M) (fun _ _ => True) (Each post carry) := + (spec.toSeq hin hclosed).of_stageSeq + (StageSeq.of_invariant ((lowering.trans backend).trans assembly) + (fun σ m hσ hm => (hin σ m hσ hm).1) fun σ m obs hσ hm hrun => + hclosed σ m obs hσ hm + (spec.post_of_run (hin σ m hσ hm).1 (hin σ m hσ hm).2 hrun)) + +/-! ## \`Sequence.lean\`'s sequences -/ + +/-- \`Sequence.lean\`'s \`runSeq\`, whose carried list depends on the observable only, is +\`runCalls\` with that carry. -/ +theorem runCalls_eq_runSeq (run : Call → Option Observable) + (next : Observable → List (Nat × Nat)) : + ∀ σ ms, runCalls run (fun _ obs => next obs) σ ms = runSeq run next σ ms + | _, [] => rfl + | σ, m :: ms => by + simp only [runCalls, runSeq] + cases run (m.call σ) with + | none => rfl + | some obs => simp only [runCalls_eq_runSeq run next _ ms] + +/-- \`Sequence.lean\`'s \`RefinesSeq\` from \`σ0\` gives \`RefinesSeqOn\` on the sequences from +\`σ0\`. -/ +theorem refinesSeqOn_of_refinesSeq {fuel : Nat} + {contract : SolidCore.Solidity.TypeCheck.CheckedContract} {code : ByteArray} + {next : Observable → List (Nat × Nat)} {σ0 : List (Nat × Nat)} {scope : Msg → Prop} + (h : RefinesSeq fuel contract code next σ0 scope) : + RefinesSeqOn fuel contract code (fun _ obs => next obs) (within (· = σ0) scope) := by + rintro σ ms ⟨rfl, hms⟩ + obtain ⟨obss, h1, h2, -⟩ := h ms.length ms (Nat.le_refl _) hms + exact ⟨obss, (runCalls_eq_runSeq _ _ _ _).trans h1, (runCalls_eq_runSeq _ _ _ _).trans h2⟩ + +/-- \`RefinesSeqOn\` on the sequences from \`σ0\` gives \`Sequence.lean\`'s \`RefinesSeq\` when +\`next\` carries every observable but the last of each run exactly. -/ +theorem refinesSeq_of_refinesSeqOn {fuel : Nat} + {contract : SolidCore.Solidity.TypeCheck.CheckedContract} {code : ByteArray} + {next : Observable → List (Nat × Nat)} {σ0 : List (Nat × Nat)} {scope : Msg → Prop} + (h : RefinesSeqOn fuel contract code (fun _ obs => next obs) (within (· = σ0) scope)) + (exact : ∀ ms obss, (∀ m ∈ ms, scope m) → + runSeq (Source.run fuel contract) next σ0 ms = some obss → + ∀ obs ∈ obss.dropLast, Exact next obs) : + RefinesSeq fuel contract code next σ0 scope := by + intro n ms _ hms + obtain ⟨obss, h1, h2⟩ := h σ0 ms ⟨rfl, hms⟩ + have h1' := (runCalls_eq_runSeq _ _ _ _).symm.trans h1 + exact ⟨obss, h1', (runCalls_eq_runSeq _ _ _ _).symm.trans h2, exact ms obss hms h1'⟩ + +end SolidCore.Refinement diff --git a/SolidCore/Refinement/Corpus.lean b/SolidCore/Refinement/Corpus.lean new file mode 100644 index 00000000..a8f8cc65 --- /dev/null +++ b/SolidCore/Refinement/Corpus.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh. Do not edit. + +import SolidCore.Refinement.Corpus.C1 +import SolidCore.Refinement.Corpus.C4 +import SolidCore.Refinement.Corpus.W1 +import SolidCore.Refinement.Corpus.W4 +import SolidCore.Refinement.Corpus.W5 + +/-! The refinement proofs of every contract in scripts/refinement/corpus/. -/ diff --git a/SolidCore/Refinement/Corpus/C1.lean b/SolidCore/Refinement/Corpus/C1.lean new file mode 100644 index 00000000..ad4faa58 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C1.lean @@ -0,0 +1,238 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c1.sol. Do not edit. + +import SolidCore.Refinement.Wide.Refines +import SolidCore.Refinement.Wide.Clean +import SolidCore.Refinement.Corpus.C1.Defs +import SolidCore.Refinement.Corpus.C1.Dirty +import SolidCore.Refinement.KernelCopies +import SolidCore.Refinement.KernelRfl + +/-! +# c1: solar's bytecode refines SolidCore's `Main`, symbolically + +`refines_full` proves `Refines fuel contract code (fullScope fns s)` for `Main` in +`scripts/refinement/corpus/c1.sol`, where `code` is solar's runtime bytecode at the pinned commit and `s` the +storage SolidCore's constructor leaves (none): every call of every function on any +argument words below `2 ^ 256`, clean or dirty, with no value. Each `call_*` theorem runs +one function symbolically in both semantics (`SolidCore.Refinement.Wide`): SolidCore's +interpreter by `wide_symex`, solar's bytecode on EthLib by `wide_tgt`, path by path, so no +call is run by `native_decide`. `refines`, on the clean calls of `scope s`, follows. + +The kernel checks `shape_eq` (`kernel_rfl`, `SolidCore.Refinement.KernelRfl`): that +SolidCore's checked contract has the core `coreLit`, the generator's print of it, and that +its constructor leaves no storage and no logs, by one conversion check that evaluates copies +of the type checker and the interpreter, which read each function's selector from +`selectorTable` (`selector_eq`, each selector checked by Keccak-256 on its own). `wide_tgt` decides branches by evaluation and `bv_omega`. +`shapeOk` and `Dirty.lean` serve the sequence proof (`Seq.lean`), not these theorems. +-/ + +namespace SolidCore.Refinement.Corpus.C1 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source + +/-- SolidCore's core contract of `Main`, as the generator printed it. -/ +def coreLit : Contract := + { storageFields := [], + immutableFields := [], + eventDecls := [], + errorDecls := [], + functions := [{ name := "f", + selector? := some 824235060, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.add) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.mul) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 8 + (SolidCore.Solidity.Source.Expr.word 3))))) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 8 + (SolidCore.Solidity.Source.Expr.word 1))))]]], + dispatchId? := none }, + { name := "__internal_f(uint8)#[SolidCore.Solidity.Ty.uint 8]", + selector? := none, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.add) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.mul) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 8 + (SolidCore.Solidity.Source.Expr.word 3))))) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 8 + (SolidCore.Solidity.Source.Expr.word 1))))]]], + dispatchId? := none }] } + +/-! ## The selectors + +The type checker computes each external function's selector by Keccak-256 of its +signature, which costs the kernel about 400 MB a hash. Each is checked once, alone, against +the bytecode file's, and the shape checks below run on copies that read them from +`selectorTable` (`selector_eq`). -/ + +/-- `f`'s selector, by Keccak-256 of its signature. -/ +def selF : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "f(uint8)" + +kernel_rfl selF_eq selF Bytecode.C1.Main.fSelector + +/-- `ABI.selectorFromSignature`, with `Main`'s signatures by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "f(uint8)" then Bytecode.C1.Main.fSelector + else SolidCore.Solidity.Source.ABI.selectorFromSignature s + +theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + by_cases h0 : s = "f(uint8)" + · rw [ite_eq_left h0, h0] + exact selF_eq + rw [ite_eq_right h0] + +/-- SolidCore's checked core of `Main`, the storage its constructor leaves and whether +it leaves no storage and no logs, when `Main` type checks. -/ +def shape? : Option (Contract × Option (List (Nat × Nat)) × Bool) := + match contract? with + | .ok c => some (c.core, deployedStorage fuel c, deployedEmpty fuel c) + | .error _ => none + +-- `shape_eq : shape? = some (coreLit, some [], true)`: `Main` type checks, its +-- core is `coreLit` and its constructor leaves no storage and no logs, by the kernel's +-- conversion check on the copy of `shape?` that reads the selectors from `selectorTable` +-- (`selector_eq`): one check evaluates the type checker once and hashes nothing, where a +-- `Bool` test of the core would need a decision procedure for equality of cores. +kernel_rfl shape_eq shape? (some (coreLit, some [], true)) using selector_eq + +/-- The checked contract has the core `coreLit`, and its constructor leaves no storage +and no logs. -/ +theorem shape_of {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core = coreLit ∧ deployedStorage fuel c = some [] ∧ deployedEmpty fuel c = true := by + have h := shape_eq + unfold shape? at h + rw [hc] at h + obtain ⟨hk, h⟩ := Prod.mk.inj (Option.some.inj h) + obtain ⟨hs, he⟩ := Prod.mk.inj h + exact ⟨hk, hs, he⟩ + +/-- `Main` type checks. -/ +theorem contract_ok : ∃ c, contract? = .ok c := by + have h := shape_eq + unfold shape? at h + cases hc : contract? with + | ok c => exact ⟨c, rfl⟩ + | error _ => rw [hc] at h; simp at h + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore and solar's bytecode agree on every call of `f` on any argument words. -/ +theorem call_f {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) (ws : List U256) (hl : ws.length = 1) : + ∃ obs, Source.run fuel c (callOf Bytecode.C1.Main.fSelector ws) = some obs ∧ + Target.run code (callOf Bytecode.C1.Main.fSelector ws) = some obs := by + rcases ws with _ | ⟨w1, _⟩ <;> simp at hl + rw [run_eq hd] + have hs := hd.storage + have hev := hd.events + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.C1.Main.fSelector] + all_goals + refine run_of_post code _ [w1] _ (by simp [Source.observe, State.logEntries, hev]) + (fun slot => by + simp [Source.observe, State.loadSlot, StorageMap.lookup?, getElem?_of_isEmpty hs, + slotValue, callOf]) ?_ + all_goals wide_tgt [code, Bytecode.C1.Main.runtimeNat, Bytecode.C1.Main.runtimeSize, Bytecode.C1.Main.fSelector] + +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on every call of every +function with any argument words below `2 ^ 256`, from the deployed storage. -/ +theorem refines_full : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + Refines fuel c code (fullScope fns s) := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hcore, hdep, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + refine ⟨c, [], hc, hdep, refines_of_calls fun fn hfn ws hl => ?_⟩ + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + rcases hfn with rfl + · exact call_f hcore hd ws hl + +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on every call of +the scope: every clean call. -/ +theorem refines : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + Refines fuel c code (· ∈ scope s) := by + obtain ⟨c, s, hc, hs, h⟩ := refines_full + exact ⟨c, s, hc, hs, refines_of_full (by decide) h⟩ + +/-- Whether every function of `fns` has the shape `Dirty.run_dirty` covers, in +SolidCore's checked `Main`. -/ +def shapeOk : Bool := + match contract? with + | .ok c => fns.all (Dirty.fnShapeOk c) + | .error _ => false + +kernel_rfl shapeOk_eq_true shapeOk true using selector_eq + +end SolidCore.Refinement.Corpus.C1 diff --git a/SolidCore/Refinement/Corpus/C1/Defs.lean b/SolidCore/Refinement/Corpus/C1/Defs.lean new file mode 100644 index 00000000..d6f6b9a3 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C1/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c1.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.C1 +import SolidCore.Refinement.Source.C1 + +/-! +# The scope of c1's refinement + +256 calls: every function of `Main` in `scripts/refinement/corpus/c1.sol` on every list of clean +argument words, with no value, from the storage SolidCore's constructor leaves. +The check runs in 1 part(s), each in its own module. +-/ + +namespace SolidCore.Refinement.Corpus.C1 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity + +/-- The interpreter fuel the refinement uses. -/ +def fuel : Nat := 4096 + +/-- solar's runtime bytecode of `Main`, from the generated file. -/ +def code : ByteArray := + EthLib.Execution.Evm.Logic.NatCode.ofNat Bytecode.C1.Main.runtimeNat + Bytecode.C1.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.C1.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.C1.Main.fSelector, [(.uint 8)]⟩] + +/-- The number of parts the check runs in. -/ +def parts : Nat := 1 + +/-- The calls the theorem covers, from the deployed storage `s`. -/ +def scope (s : List (Nat × Nat)) : List Call := calls fns [s] + +/-- Whether both semantics agree on every `parts`-th call of the scope, from the `i`-th. -/ +def partOk (i : Nat) : Bool := + match contract? with + | .ok c => + match deployedStorage fuel c with + | some s => checkPart (agree fuel c code) (scope s).toArray parts i + | none => false + | .error _ => false + +end SolidCore.Refinement.Corpus.C1 diff --git a/SolidCore/Refinement/Corpus/C1/Dirty.lean b/SolidCore/Refinement/Corpus/C1/Dirty.lean new file mode 100644 index 00000000..447b5ee0 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C1/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c1.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.C1.Defs + +/-! +# c1: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/c1.sol`, every call whose argument words are +below `2 ^ 256` but not all clean reverts with empty output in EthLib, from any +storage. Each case is one `dirty_symex` run over solar's bytecode, symbolic in +the argument words; `bv_omega` decides its branch conditions, a kernel-checked +proof (`symex_bv` falls back to `bv_decide` only where it fails). +-/ + +namespace SolidCore.Refinement.Corpus.C1 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm.Symex + +set_option maxHeartbeats 4000000 in +set_option maxRecDepth 8192 in +/-- EthLib rejects every dirty call of every function of `Main`. -/ +theorem target_dirty : Dirty.TargetDirty code fns := by + intro fn hfn + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + rcases hfn with rfl + · exact dirty_of_frame code Bytecode.C1.Main.fSelector [(.uint 8)] + (by dirty_symex [code, Bytecode.C1.Main.runtimeNat, Bytecode.C1.Main.runtimeSize, Bytecode.C1.Main.fSelector]) + +end SolidCore.Refinement.Corpus.C1 diff --git a/SolidCore/Refinement/Corpus/C1/Seq.lean b/SolidCore/Refinement/Corpus/C1/Seq.lean new file mode 100644 index 00000000..31055636 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C1/Seq.lean @@ -0,0 +1,54 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C1 +import SolidCore.Refinement.Corpus.C1.SeqDefs +import SolidCore.Refinement.Corpus.C1.SeqPart0 + +/-! +# c1: solar's bytecode refines SolidCore's `Main` on sequences of calls + +`refines_seq` proves that on every finite sequence of calls from the deployed storage, each +call of any function of `Main` in `scripts/refinement/corpus/c1.sol` on any argument words below +`2 ^ 256` with no value, and each starting from the storage the previous call +left, SolidCore and solar's bytecode on EthLib finish every call with the same +observables (`SolidCore.Refinement.RefinesSeq`). + +The certificate of reached storages is closed: 1 storage(s) in 1 level(s); every function is pure or view, so the deployed storage alone is closed. The +theorem covers every sequence of calls of any length. +Its clean calls run in both semantics by `native_decide` (which trusts Lean's +compiler), in `SeqPartI.lean`; its dirty calls reuse `Dirty.run_dirty` and +`target_dirty`, which hold from every storage, with one `native_decide` check of +the storages they keep (`seqDirtyOk_eq_true`). +-/ + +namespace SolidCore.Refinement.Corpus.C1 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem seq_parts_ok : ∀ i < seqParts, seqPartOk i = true := fun i hi => + match i, hi with + | 0, _ => seqPart0 + | n + 1, h => absurd h (by simp only [seqParts]; omega) + +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on every finite sequence of calls +of every function on any argument words from the deployed storage. -/ +theorem refines_seq : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + RefinesSeq fuel c code (seqNext s) s (Seq.fullMsg fns) := by + have h0 := seq_parts_ok 0 (by decide) + have hd := seqDirtyOk_eq_true + match hc : contract?, h0, hd with + | .ok c, h0, hd => + match hs : deployedStorage fuel c with + | some s => + have hsh := shapeOk_eq_true + simp only [shapeOk, hc] at hsh + refine ⟨c, s, rfl, hs, ?_⟩ + have h := Seq.refinesSeq_of_cert (levels := seqLevelsOf s) (next := seqNext s) hs ⟨[s], List.mem_cons_self, List.mem_singleton_self s⟩ + (all_of_parts (parts := seqParts) (by decide) fun i hi => by + simpa only [seqPartOk, seqClosed, hc, hs] using seq_parts_ok i hi) + (by simpa only [seqDirtyOk, seqClosed, hc, hs] using hd) hsh target_dirty + exact h + | none => simp [seqPartOk, hc, hs] at h0 + | .error _, h0, _ => simp [seqPartOk, hc] at h0 + +end SolidCore.Refinement.Corpus.C1 diff --git a/SolidCore/Refinement/Corpus/C1/SeqDefs.lean b/SolidCore/Refinement/Corpus/C1/SeqDefs.lean new file mode 100644 index 00000000..b0d81aee --- /dev/null +++ b/SolidCore/Refinement/Corpus/C1/SeqDefs.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c1.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.C1.Defs +import SolidCore.Refinement.Corpus.C1.SeqStates + +/-! +# The certificate of c1's sequence refinement + +The storages of `SeqStates.lean`, with the deployed storage `s` as level 0, are +closed: 1 storage(s) in 1 level(s); every function is pure or view, so the deployed storage alone is closed. The +theorem covers every sequence of calls of any length. +`seqNext s` turns a call's observable into the next call's storage list: every +slot of `seqKeys` or of the deployed storage whose final value is nonzero or that +the constructor wrote. The check runs every clean call from every storage of the +certificate, 256 calls, in 1 part(s), and every dirty call once +per storage. +-/ + +namespace SolidCore.Refinement.Corpus.C1 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity + +/-- The storage list the next call starts from. -/ +def seqNext (s : List (Nat × Nat)) : Observable → List (Nat × Nat) := + Seq.canon (Seq.normKeys (seqKeys ++ s.map (·.1))) (s.map (·.1)) + +/-- The certificate's levels, the deployed storage `s` alone at level 0. -/ +def seqLevelsOf (s : List (Nat × Nat)) : List (List (List (Nat × Nat))) := [s] :: seqLevels + +/-- Whether the certificate is closed under every call. -/ +def seqClosed : Bool := true + +/-- The number of parts the check runs in. -/ +def seqParts : Nat := 1 + +/-- Whether every `seqParts`-th clean call of the certificate, from the `i`-th, checks. -/ +def seqPartOk (i : Nat) : Bool := + match contract? with + | .ok c => + match deployedStorage fuel c with + | some s => + checkPart (Seq.itemOk fuel c code (seqNext s) (seqLevelsOf s) seqClosed) + (Seq.items fns (seqLevelsOf s)).toArray seqParts i + | none => false + | .error _ => false + +/-- Whether the dirty calls from every storage of the certificate check. -/ +def seqDirtyOk : Bool := + match contract? with + | .ok c => + match deployedStorage fuel c with + | some s => (Seq.states (seqLevelsOf s)).all (Seq.dirtyOk (seqNext s) (seqLevelsOf s) seqClosed) + | none => false + | .error _ => false + +theorem seqDirtyOk_eq_true : seqDirtyOk = true := by native_decide + +end SolidCore.Refinement.Corpus.C1 diff --git a/SolidCore/Refinement/Corpus/C1/SeqPart0.lean b/SolidCore/Refinement/Corpus/C1/SeqPart0.lean new file mode 100644 index 00000000..cae98460 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C1/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c1.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C1.SeqDefs + +namespace SolidCore.Refinement.Corpus.C1 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C1 diff --git a/SolidCore/Refinement/Corpus/C1/SeqStates.lean b/SolidCore/Refinement/Corpus/C1/SeqStates.lean new file mode 100644 index 00000000..6987394e --- /dev/null +++ b/SolidCore/Refinement/Corpus/C1/SeqStates.lean @@ -0,0 +1,21 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c1.sol. Do not edit. + +/-! +# The storages c1's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/c1.sol`, as +`SolidCore.Refinement.Seq.explore` found it: the slots any reached storage holds +(`seqKeys`) and the storages of every level after the deployed one (`seqLevels`), +each as its nonzero or constructor-written slots, sorted. Nothing here is +trusted: `SeqDefs.lean` checks it against both semantics. +-/ + +namespace SolidCore.Refinement.Corpus.C1 + +/-- The slots a reached storage holds a word for. -/ +def seqKeys : List Nat := [] + +/-- The reached storages, by level, from level 1. -/ +def seqLevels : List (List (List (Nat × Nat))) := [] + +end SolidCore.Refinement.Corpus.C1 diff --git a/SolidCore/Refinement/Corpus/C4.lean b/SolidCore/Refinement/Corpus/C4.lean new file mode 100644 index 00000000..3b531a73 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4.lean @@ -0,0 +1,251 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Wide.Refines +import SolidCore.Refinement.Wide.Clean +import SolidCore.Refinement.Corpus.C4.Defs +import SolidCore.Refinement.Corpus.C4.Dirty +import SolidCore.Refinement.KernelCopies +import SolidCore.Refinement.KernelRfl + +/-! +# c4: solar's bytecode refines SolidCore's `Main`, symbolically + +`refines_full` proves `Refines fuel contract code (fullScope fns s)` for `Main` in +`scripts/refinement/corpus/c4.sol`, where `code` is solar's runtime bytecode at the pinned commit and `s` the +storage SolidCore's constructor leaves (`[(0, 1792)]`): every call of every function on any +argument words below `2 ^ 256`, clean or dirty, with no value. Each `call_*` theorem runs +one function symbolically in both semantics (`SolidCore.Refinement.Wide`): SolidCore's +interpreter by `wide_symex`, solar's bytecode on EthLib by `wide_tgt_at`, path by path, so no +call is run by `native_decide`. `refines`, on the clean calls of `scope s`, follows. + +The kernel checks `shape_eq` (`kernel_rfl`, `SolidCore.Refinement.KernelRfl`): that +SolidCore's checked contract has the core `coreLit`, the generator's print of it, and that +its constructor leaves the storage `[(0, 1792)]` and no logs, by one conversion check that evaluates copies +of the type checker and the interpreter, which read each function's selector from +`selectorTable` (`selector_eq`, each selector checked by Keccak-256 on its own). `wide_tgt_at` decides branches by evaluation and +`bv_omega`, and compares the words left by evaluating them on every value of a small argument +word in the kernel (`word_decide`). +`shapeOk` and `Dirty.lean` serve the sequence proof (`Seq.lean`), not these theorems. +-/ + +namespace SolidCore.Refinement.Corpus.C4 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source + +/-- SolidCore's core contract of `Main`, as the generator printed it. -/ +def coreLit : Contract := + { storageFields := [{ name := "v", + slot := 0, + ty? := some (SolidCore.Solidity.Source.Ty.uint256), + layout? := some (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.uint256)), + transient := false, + packedOffset := 0, + packedBytes := 1, + packedSigned := false }, + { name := "w", + slot := 0, + ty? := some (SolidCore.Solidity.Source.Ty.uint256), + layout? := some (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.uint256)), + transient := false, + packedOffset := 1, + packedBytes := 1, + packedSigned := false }], + immutableFields := [], + eventDecls := [], + errorDecls := [], + functions := [{ name := "add", + selector? := some 33980010, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.add)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 8)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "v" + []) + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.bitXor)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 8)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "w" + []) + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.ref) + "v" + [])]]], + dispatchId? := none }, + { name := "__internal_add(uint8)#[SolidCore.Solidity.Ty.uint 8]", + selector? := none, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.add)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 8)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "v" + []) + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.bitXor)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 8)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "w" + []) + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.ref) + "v" + [])]]], + dispatchId? := none }] } + +/-! ## The selectors + +The type checker computes each external function's selector by Keccak-256 of its +signature, which costs the kernel about 400 MB a hash. Each is checked once, alone, against +the bytecode file's, and the shape checks below run on copies that read them from +`selectorTable` (`selector_eq`). -/ + +/-- `add`'s selector, by Keccak-256 of its signature. -/ +def selAdd : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "add(uint8)" + +kernel_rfl selAdd_eq selAdd Bytecode.C4.Main.addSelector + +/-- `ABI.selectorFromSignature`, with `Main`'s signatures by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "add(uint8)" then Bytecode.C4.Main.addSelector + else SolidCore.Solidity.Source.ABI.selectorFromSignature s + +theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + by_cases h0 : s = "add(uint8)" + · rw [ite_eq_left h0, h0] + exact selAdd_eq + rw [ite_eq_right h0] + +/-- SolidCore's checked core of `Main`, the storage its constructor leaves and whether +it leaves the storage `[(0, 1792)]` and no logs, when `Main` type checks. -/ +def shape? : Option (Contract × Option (List (Nat × Nat)) × Bool) := + match contract? with + | .ok c => some (c.core, deployedStorage fuel c, deployedAt fuel c [(0, 1792)]) + | .error _ => none + +-- `shape_eq : shape? = some (coreLit, some [(0, 1792)], true)`: `Main` type checks, its +-- core is `coreLit` and its constructor leaves the storage `[(0, 1792)]` and no logs, by the kernel's +-- conversion check on the copy of `shape?` that reads the selectors from `selectorTable` +-- (`selector_eq`): one check evaluates the type checker once and hashes nothing, where a +-- `Bool` test of the core would need a decision procedure for equality of cores. +kernel_rfl shape_eq shape? (some (coreLit, some [(0, 1792)], true)) using selector_eq + +/-- The checked contract has the core `coreLit`, and its constructor leaves the storage `[(0, 1792)]` +and no logs. -/ +theorem shape_of {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core = coreLit ∧ deployedStorage fuel c = some [(0, 1792)] ∧ deployedAt fuel c [(0, 1792)] = true := by + have h := shape_eq + unfold shape? at h + rw [hc] at h + obtain ⟨hk, h⟩ := Prod.mk.inj (Option.some.inj h) + obtain ⟨hs, he⟩ := Prod.mk.inj h + exact ⟨hk, hs, he⟩ + +/-- `Main` type checks. -/ +theorem contract_ok : ∃ c, contract? = .ok c := by + have h := shape_eq + unfold shape? at h + cases hc : contract? with + | ok c => exact ⟨c, rfl⟩ + | error _ => rw [hc] at h; simp at h + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore and solar's bytecode agree on every call of `add` on any argument words, from the +deployed storage. -/ +theorem call_add {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d [(0, 1792)]) (ws : List U256) (hl : ws.length = 1) : + ∃ obs, Source.run fuel c (callAt Bytecode.C4.Main.addSelector ws [(0, 1792)]) = some obs ∧ + Target.run code (callAt Bytecode.C4.Main.addSelector ws [(0, 1792)]) = some obs := by + rcases ws with _ | ⟨w1, _⟩ <;> simp at hl + rw [run_eq_at hd] + have hev := hd.events + have hnone : ∀ k, k ≠ 0 → d.storage[k]? = none := fun k h0 => + hd.getElem?_eq_none fun v hv => by simp at hv; omega + simp only [hcore, List.map_cons, List.map_nil, List.foldl_cons, List.foldl_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.C4.Main.addSelector, get?_insert] + all_goals + refine run_of_postS_at code _ [w1] _ _ (by simp [Source.observe, State.logEntries, hev]) + (fun hX slot => by simp_all [Source.observe, callAt]) ?_ + all_goals wide_tgt_at [code, Bytecode.C4.Main.runtimeNat, Bytecode.C4.Main.runtimeSize, Bytecode.C4.Main.addSelector] + +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on every call of every +function with any argument words below `2 ^ 256`, from the deployed storage. -/ +theorem refines_full : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + Refines fuel c code (fullScope fns s) := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hcore, hdep, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployedAt_of hemp + refine ⟨c, [(0, 1792)], hc, hdep, refines_of_calls_at fun fn hfn ws hl => ?_⟩ + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + rcases hfn with rfl + · exact call_add hcore hd ws hl + +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on every call of +the scope: every clean call. -/ +theorem refines : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + Refines fuel c code (· ∈ scope s) := by + obtain ⟨c, s, hc, hs, h⟩ := refines_full + exact ⟨c, s, hc, hs, refines_of_full (by decide) h⟩ + +/-- Whether every function of `fns` has the shape `Dirty.run_dirty` covers, in +SolidCore's checked `Main`. -/ +def shapeOk : Bool := + match contract? with + | .ok c => fns.all (Dirty.fnShapeOk c) + | .error _ => false + +kernel_rfl shapeOk_eq_true shapeOk true using selector_eq + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/Defs.lean b/SolidCore/Refinement/Corpus/C4/Defs.lean new file mode 100644 index 00000000..57500598 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/Defs.lean @@ -0,0 +1,50 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.C4 +import SolidCore.Refinement.Source.C4 + +/-! +# The scope of c4's refinement + +256 calls: every function of `Main` in `scripts/refinement/corpus/c4.sol` on every list of clean +argument words, with no value, from the storage SolidCore's constructor leaves. +The check runs in 1 part(s), each in its own module. +-/ + +namespace SolidCore.Refinement.Corpus.C4 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity + +/-- The interpreter fuel the refinement uses. -/ +def fuel : Nat := 4096 + +/-- solar's runtime bytecode of `Main`, from the generated file. -/ +def code : ByteArray := + EthLib.Execution.Evm.Logic.NatCode.ofNat Bytecode.C4.Main.runtimeNat + Bytecode.C4.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.C4.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [⟨Bytecode.C4.Main.addSelector, [(.uint 8)]⟩] + +/-- The number of parts the check runs in. -/ +def parts : Nat := 1 + +/-- The calls the theorem covers, from the deployed storage `s`. -/ +def scope (s : List (Nat × Nat)) : List Call := calls fns [s] + +/-- Whether both semantics agree on every `parts`-th call of the scope, from the `i`-th. -/ +def partOk (i : Nat) : Bool := + match contract? with + | .ok c => + match deployedStorage fuel c with + | some s => checkPart (agree fuel c code) (scope s).toArray parts i + | none => false + | .error _ => false + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/Dirty.lean b/SolidCore/Refinement/Corpus/C4/Dirty.lean new file mode 100644 index 00000000..7754b588 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/Dirty.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Corpus.C4.Defs + +/-! +# c4: EthLib rejects every dirty argument word + +For every function of `Main` in `scripts/refinement/corpus/c4.sol`, every call whose argument words are +below `2 ^ 256` but not all clean reverts with empty output in EthLib, from any +storage. Each case is one `dirty_symex` run over solar's bytecode, symbolic in +the argument words; `bv_omega` decides its branch conditions, a kernel-checked +proof (`symex_bv` falls back to `bv_decide` only where it fails). +-/ + +namespace SolidCore.Refinement.Corpus.C4 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm.Symex + +set_option maxHeartbeats 4000000 in +set_option maxRecDepth 8192 in +/-- EthLib rejects every dirty call of every function of `Main`. -/ +theorem target_dirty : Dirty.TargetDirty code fns := by + intro fn hfn + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + rcases hfn with rfl + · exact dirty_of_frame code Bytecode.C4.Main.addSelector [(.uint 8)] + (by dirty_symex [code, Bytecode.C4.Main.runtimeNat, Bytecode.C4.Main.runtimeSize, Bytecode.C4.Main.addSelector]) + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/Seq.lean b/SolidCore/Refinement/Corpus/C4/Seq.lean new file mode 100644 index 00000000..468c97b0 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/Seq.lean @@ -0,0 +1,87 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4 +import SolidCore.Refinement.Corpus.C4.SeqDefs +import SolidCore.Refinement.Corpus.C4.SeqPart0 +import SolidCore.Refinement.Corpus.C4.SeqPart1 +import SolidCore.Refinement.Corpus.C4.SeqPart2 +import SolidCore.Refinement.Corpus.C4.SeqPart3 +import SolidCore.Refinement.Corpus.C4.SeqPart4 +import SolidCore.Refinement.Corpus.C4.SeqPart5 +import SolidCore.Refinement.Corpus.C4.SeqPart6 +import SolidCore.Refinement.Corpus.C4.SeqPart7 +import SolidCore.Refinement.Corpus.C4.SeqPart8 +import SolidCore.Refinement.Corpus.C4.SeqPart9 +import SolidCore.Refinement.Corpus.C4.SeqPart10 +import SolidCore.Refinement.Corpus.C4.SeqPart11 +import SolidCore.Refinement.Corpus.C4.SeqPart12 +import SolidCore.Refinement.Corpus.C4.SeqPart13 +import SolidCore.Refinement.Corpus.C4.SeqPart14 +import SolidCore.Refinement.Corpus.C4.SeqPart15 + +/-! +# c4: solar's bytecode refines SolidCore's `Main` on sequences of calls + +`refines_seq` proves that on every sequence of at most 2 calls from the deployed storage, each +call of any function of `Main` in `scripts/refinement/corpus/c4.sol` on any argument words below +`2 ^ 256` with no value, and each starting from the storage the previous call +left, SolidCore and solar's bytecode on EthLib finish every call with the same +observables (`SolidCore.Refinement.RefinesSeq`). + +The certificate of reached storages is open: the closure did not fit 4096 storages and 131072 calls, +so the certificate keeps the first 2 level(s), 256 storage(s). The +theorem covers every sequence of at most 2 calls. +Its clean calls run in both semantics by `native_decide` (which trusts Lean's +compiler), in `SeqPartI.lean`; its dirty calls reuse `Dirty.run_dirty` and +`target_dirty`, which hold from every storage, with one `native_decide` check of +the storages they keep (`seqDirtyOk_eq_true`). +-/ + +namespace SolidCore.Refinement.Corpus.C4 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem seq_parts_ok : ∀ i < seqParts, seqPartOk i = true := fun i hi => + match i, hi with + | 0, _ => seqPart0 + | 1, _ => seqPart1 + | 2, _ => seqPart2 + | 3, _ => seqPart3 + | 4, _ => seqPart4 + | 5, _ => seqPart5 + | 6, _ => seqPart6 + | 7, _ => seqPart7 + | 8, _ => seqPart8 + | 9, _ => seqPart9 + | 10, _ => seqPart10 + | 11, _ => seqPart11 + | 12, _ => seqPart12 + | 13, _ => seqPart13 + | 14, _ => seqPart14 + | 15, _ => seqPart15 + | n + 16, h => absurd h (by simp only [seqParts]; omega) + +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on every sequence of at most 2 calls +of every function on any argument words from the deployed storage. -/ +theorem refines_seq : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + RefinesSeqUpTo fuel c code (seqNext s) s (Seq.fullMsg fns) 2 := by + have h0 := seq_parts_ok 0 (by decide) + have hd := seqDirtyOk_eq_true + match hc : contract?, h0, hd with + | .ok c, h0, hd => + match hs : deployedStorage fuel c with + | some s => + have hsh := shapeOk_eq_true + simp only [shapeOk, hc] at hsh + refine ⟨c, s, rfl, hs, ?_⟩ + have h := Seq.refinesSeqUpTo_of_cert (levels := seqLevelsOf s) (next := seqNext s) hs (List.mem_singleton_self s) + (all_of_parts (parts := seqParts) (by decide) fun i hi => by + simpa only [seqPartOk, seqClosed, hc, hs] using seq_parts_ok i hi) + (by simpa only [seqDirtyOk, seqClosed, hc, hs] using hd) hsh target_dirty + have hl : (seqLevelsOf s).length = 2 := rfl + rw [hl] at h + exact h + | none => simp [seqPartOk, hc, hs] at h0 + | .error _, h0, _ => simp [seqPartOk, hc] at h0 + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqDefs.lean b/SolidCore/Refinement/Corpus/C4/SeqDefs.lean new file mode 100644 index 00000000..f74b5378 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqDefs.lean @@ -0,0 +1,60 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Seq.Check +import SolidCore.Refinement.Corpus.C4.Defs +import SolidCore.Refinement.Corpus.C4.SeqStates + +/-! +# The certificate of c4's sequence refinement + +The storages of `SeqStates.lean`, with the deployed storage `s` as level 0, are +open: the closure did not fit 4096 storages and 131072 calls, +so the certificate keeps the first 2 level(s), 256 storage(s). The +theorem covers every sequence of at most 2 calls. +`seqNext s` turns a call's observable into the next call's storage list: every +slot of `seqKeys` or of the deployed storage whose final value is nonzero or that +the constructor wrote. The check runs every clean call from every storage of the +certificate, 65536 calls, in 16 part(s), and every dirty call once +per storage. +-/ + +namespace SolidCore.Refinement.Corpus.C4 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity + +/-- The storage list the next call starts from. -/ +def seqNext (s : List (Nat × Nat)) : Observable → List (Nat × Nat) := + Seq.canon (Seq.normKeys (seqKeys ++ s.map (·.1))) (s.map (·.1)) + +/-- The certificate's levels, the deployed storage `s` alone at level 0. -/ +def seqLevelsOf (s : List (Nat × Nat)) : List (List (List (Nat × Nat))) := [s] :: seqLevels + +/-- Whether the certificate is closed under every call. -/ +def seqClosed : Bool := false + +/-- The number of parts the check runs in. -/ +def seqParts : Nat := 16 + +/-- Whether every `seqParts`-th clean call of the certificate, from the `i`-th, checks. -/ +def seqPartOk (i : Nat) : Bool := + match contract? with + | .ok c => + match deployedStorage fuel c with + | some s => + checkPart (Seq.itemOk fuel c code (seqNext s) (seqLevelsOf s) seqClosed) + (Seq.items fns (seqLevelsOf s)).toArray seqParts i + | none => false + | .error _ => false + +/-- Whether the dirty calls from every storage of the certificate check. -/ +def seqDirtyOk : Bool := + match contract? with + | .ok c => + match deployedStorage fuel c with + | some s => (Seq.states (seqLevelsOf s)).all (Seq.dirtyOk (seqNext s) (seqLevelsOf s) seqClosed) + | none => false + | .error _ => false + +theorem seqDirtyOk_eq_true : seqDirtyOk = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqPart0.lean b/SolidCore/Refinement/Corpus/C4/SeqPart0.lean new file mode 100644 index 00000000..6c4a5af2 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqPart0.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4.SeqDefs + +namespace SolidCore.Refinement.Corpus.C4 + +theorem seqPart0 : seqPartOk 0 = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqPart1.lean b/SolidCore/Refinement/Corpus/C4/SeqPart1.lean new file mode 100644 index 00000000..84849581 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqPart1.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4.SeqDefs + +namespace SolidCore.Refinement.Corpus.C4 + +theorem seqPart1 : seqPartOk 1 = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqPart10.lean b/SolidCore/Refinement/Corpus/C4/SeqPart10.lean new file mode 100644 index 00000000..4c352b1f --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqPart10.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4.SeqDefs + +namespace SolidCore.Refinement.Corpus.C4 + +theorem seqPart10 : seqPartOk 10 = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqPart11.lean b/SolidCore/Refinement/Corpus/C4/SeqPart11.lean new file mode 100644 index 00000000..ae6760f5 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqPart11.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4.SeqDefs + +namespace SolidCore.Refinement.Corpus.C4 + +theorem seqPart11 : seqPartOk 11 = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqPart12.lean b/SolidCore/Refinement/Corpus/C4/SeqPart12.lean new file mode 100644 index 00000000..d31c13a5 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqPart12.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4.SeqDefs + +namespace SolidCore.Refinement.Corpus.C4 + +theorem seqPart12 : seqPartOk 12 = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqPart13.lean b/SolidCore/Refinement/Corpus/C4/SeqPart13.lean new file mode 100644 index 00000000..7f4c2130 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqPart13.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4.SeqDefs + +namespace SolidCore.Refinement.Corpus.C4 + +theorem seqPart13 : seqPartOk 13 = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqPart14.lean b/SolidCore/Refinement/Corpus/C4/SeqPart14.lean new file mode 100644 index 00000000..57b0d961 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqPart14.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4.SeqDefs + +namespace SolidCore.Refinement.Corpus.C4 + +theorem seqPart14 : seqPartOk 14 = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqPart15.lean b/SolidCore/Refinement/Corpus/C4/SeqPart15.lean new file mode 100644 index 00000000..538d2e4d --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqPart15.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4.SeqDefs + +namespace SolidCore.Refinement.Corpus.C4 + +theorem seqPart15 : seqPartOk 15 = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqPart2.lean b/SolidCore/Refinement/Corpus/C4/SeqPart2.lean new file mode 100644 index 00000000..471040d8 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqPart2.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4.SeqDefs + +namespace SolidCore.Refinement.Corpus.C4 + +theorem seqPart2 : seqPartOk 2 = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqPart3.lean b/SolidCore/Refinement/Corpus/C4/SeqPart3.lean new file mode 100644 index 00000000..c6dff532 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqPart3.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4.SeqDefs + +namespace SolidCore.Refinement.Corpus.C4 + +theorem seqPart3 : seqPartOk 3 = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqPart4.lean b/SolidCore/Refinement/Corpus/C4/SeqPart4.lean new file mode 100644 index 00000000..0be9da28 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqPart4.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4.SeqDefs + +namespace SolidCore.Refinement.Corpus.C4 + +theorem seqPart4 : seqPartOk 4 = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqPart5.lean b/SolidCore/Refinement/Corpus/C4/SeqPart5.lean new file mode 100644 index 00000000..2583a4ae --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqPart5.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4.SeqDefs + +namespace SolidCore.Refinement.Corpus.C4 + +theorem seqPart5 : seqPartOk 5 = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqPart6.lean b/SolidCore/Refinement/Corpus/C4/SeqPart6.lean new file mode 100644 index 00000000..eabd86b6 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqPart6.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4.SeqDefs + +namespace SolidCore.Refinement.Corpus.C4 + +theorem seqPart6 : seqPartOk 6 = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqPart7.lean b/SolidCore/Refinement/Corpus/C4/SeqPart7.lean new file mode 100644 index 00000000..28ee4f8f --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqPart7.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4.SeqDefs + +namespace SolidCore.Refinement.Corpus.C4 + +theorem seqPart7 : seqPartOk 7 = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqPart8.lean b/SolidCore/Refinement/Corpus/C4/SeqPart8.lean new file mode 100644 index 00000000..90c335a3 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqPart8.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4.SeqDefs + +namespace SolidCore.Refinement.Corpus.C4 + +theorem seqPart8 : seqPartOk 8 = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqPart9.lean b/SolidCore/Refinement/Corpus/C4/SeqPart9.lean new file mode 100644 index 00000000..26befe1a --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqPart9.lean @@ -0,0 +1,9 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +import SolidCore.Refinement.Corpus.C4.SeqDefs + +namespace SolidCore.Refinement.Corpus.C4 + +theorem seqPart9 : seqPartOk 9 = true := by native_decide + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/C4/SeqStates.lean b/SolidCore/Refinement/Corpus/C4/SeqStates.lean new file mode 100644 index 00000000..16d99d65 --- /dev/null +++ b/SolidCore/Refinement/Corpus/C4/SeqStates.lean @@ -0,0 +1,276 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol. Do not edit. + +/-! +# The storages c4's clean calls reach + +The certificate of the sequence refinement of `Main` in `scripts/refinement/corpus/c4.sol`, as +`SolidCore.Refinement.Seq.explore` found it: the slots any reached storage holds +(`seqKeys`) and the storages of every level after the deployed one (`seqLevels`), +each as its nonzero or constructor-written slots, sorted. Nothing here is +trusted: `SeqDefs.lean` checks it against both semantics. +-/ + +namespace SolidCore.Refinement.Corpus.C4 + +/-- The slots a reached storage holds a word for. -/ +def seqKeys : List Nat := [0] + +/-- The reached storages, by level, from level 1. -/ +def seqLevels : List (List (List (Nat × Nat))) := [ + [[(0, 1537)], + [(0, 1282)], + [(0, 1027)], + [(0, 772)], + [(0, 517)], + [(0, 262)], + [(0, 7)], + [(0, 3848)], + [(0, 3593)], + [(0, 3338)], + [(0, 3083)], + [(0, 2828)], + [(0, 2573)], + [(0, 2318)], + [(0, 2063)], + [(0, 5904)], + [(0, 5649)], + [(0, 5394)], + [(0, 5139)], + [(0, 4884)], + [(0, 4629)], + [(0, 4374)], + [(0, 4119)], + [(0, 7960)], + [(0, 7705)], + [(0, 7450)], + [(0, 7195)], + [(0, 6940)], + [(0, 6685)], + [(0, 6430)], + [(0, 6175)], + [(0, 10016)], + [(0, 9761)], + [(0, 9506)], + [(0, 9251)], + [(0, 8996)], + [(0, 8741)], + [(0, 8486)], + [(0, 8231)], + [(0, 12072)], + [(0, 11817)], + [(0, 11562)], + [(0, 11307)], + [(0, 11052)], + [(0, 10797)], + [(0, 10542)], + [(0, 10287)], + [(0, 14128)], + [(0, 13873)], + [(0, 13618)], + [(0, 13363)], + [(0, 13108)], + [(0, 12853)], + [(0, 12598)], + [(0, 12343)], + [(0, 16184)], + [(0, 15929)], + [(0, 15674)], + [(0, 15419)], + [(0, 15164)], + [(0, 14909)], + [(0, 14654)], + [(0, 14399)], + [(0, 18240)], + [(0, 17985)], + [(0, 17730)], + [(0, 17475)], + [(0, 17220)], + [(0, 16965)], + [(0, 16710)], + [(0, 16455)], + [(0, 20296)], + [(0, 20041)], + [(0, 19786)], + [(0, 19531)], + [(0, 19276)], + [(0, 19021)], + [(0, 18766)], + [(0, 18511)], + [(0, 22352)], + [(0, 22097)], + [(0, 21842)], + [(0, 21587)], + [(0, 21332)], + [(0, 21077)], + [(0, 20822)], + [(0, 20567)], + [(0, 24408)], + [(0, 24153)], + [(0, 23898)], + [(0, 23643)], + [(0, 23388)], + [(0, 23133)], + [(0, 22878)], + [(0, 22623)], + [(0, 26464)], + [(0, 26209)], + [(0, 25954)], + [(0, 25699)], + [(0, 25444)], + [(0, 25189)], + [(0, 24934)], + [(0, 24679)], + [(0, 28520)], + [(0, 28265)], + [(0, 28010)], + [(0, 27755)], + [(0, 27500)], + [(0, 27245)], + [(0, 26990)], + [(0, 26735)], + [(0, 30576)], + [(0, 30321)], + [(0, 30066)], + [(0, 29811)], + [(0, 29556)], + [(0, 29301)], + [(0, 29046)], + [(0, 28791)], + [(0, 32632)], + [(0, 32377)], + [(0, 32122)], + [(0, 31867)], + [(0, 31612)], + [(0, 31357)], + [(0, 31102)], + [(0, 30847)], + [(0, 34688)], + [(0, 34433)], + [(0, 34178)], + [(0, 33923)], + [(0, 33668)], + [(0, 33413)], + [(0, 33158)], + [(0, 32903)], + [(0, 36744)], + [(0, 36489)], + [(0, 36234)], + [(0, 35979)], + [(0, 35724)], + [(0, 35469)], + [(0, 35214)], + [(0, 34959)], + [(0, 38800)], + [(0, 38545)], + [(0, 38290)], + [(0, 38035)], + [(0, 37780)], + [(0, 37525)], + [(0, 37270)], + [(0, 37015)], + [(0, 40856)], + [(0, 40601)], + [(0, 40346)], + [(0, 40091)], + [(0, 39836)], + [(0, 39581)], + [(0, 39326)], + [(0, 39071)], + [(0, 42912)], + [(0, 42657)], + [(0, 42402)], + [(0, 42147)], + [(0, 41892)], + [(0, 41637)], + [(0, 41382)], + [(0, 41127)], + [(0, 44968)], + [(0, 44713)], + [(0, 44458)], + [(0, 44203)], + [(0, 43948)], + [(0, 43693)], + [(0, 43438)], + [(0, 43183)], + [(0, 47024)], + [(0, 46769)], + [(0, 46514)], + [(0, 46259)], + [(0, 46004)], + [(0, 45749)], + [(0, 45494)], + [(0, 45239)], + [(0, 49080)], + [(0, 48825)], + [(0, 48570)], + [(0, 48315)], + [(0, 48060)], + [(0, 47805)], + [(0, 47550)], + [(0, 47295)], + [(0, 51136)], + [(0, 50881)], + [(0, 50626)], + [(0, 50371)], + [(0, 50116)], + [(0, 49861)], + [(0, 49606)], + [(0, 49351)], + [(0, 53192)], + [(0, 52937)], + [(0, 52682)], + [(0, 52427)], + [(0, 52172)], + [(0, 51917)], + [(0, 51662)], + [(0, 51407)], + [(0, 55248)], + [(0, 54993)], + [(0, 54738)], + [(0, 54483)], + [(0, 54228)], + [(0, 53973)], + [(0, 53718)], + [(0, 53463)], + [(0, 57304)], + [(0, 57049)], + [(0, 56794)], + [(0, 56539)], + [(0, 56284)], + [(0, 56029)], + [(0, 55774)], + [(0, 55519)], + [(0, 59360)], + [(0, 59105)], + [(0, 58850)], + [(0, 58595)], + [(0, 58340)], + [(0, 58085)], + [(0, 57830)], + [(0, 57575)], + [(0, 61416)], + [(0, 61161)], + [(0, 60906)], + [(0, 60651)], + [(0, 60396)], + [(0, 60141)], + [(0, 59886)], + [(0, 59631)], + [(0, 63472)], + [(0, 63217)], + [(0, 62962)], + [(0, 62707)], + [(0, 62452)], + [(0, 62197)], + [(0, 61942)], + [(0, 61687)], + [(0, 65528)], + [(0, 65273)], + [(0, 65018)], + [(0, 64763)], + [(0, 64508)], + [(0, 64253)], + [(0, 63998)], + [(0, 63743)]]] + +end SolidCore.Refinement.Corpus.C4 diff --git a/SolidCore/Refinement/Corpus/W1.lean b/SolidCore/Refinement/Corpus/W1.lean new file mode 100644 index 00000000..270dfdc4 --- /dev/null +++ b/SolidCore/Refinement/Corpus/W1.lean @@ -0,0 +1,207 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/w1.sol. Do not edit. + +import SolidCore.Refinement.Wide.Refines +import SolidCore.Refinement.Bytecode.W1 +import SolidCore.Refinement.Source.W1 +import SolidCore.Refinement.KernelCopies +import SolidCore.Refinement.KernelRfl + +/-! +# w1: solar's bytecode refines SolidCore's `Main` on wide arguments + +`refines_full` proves `Refines fuel contract code (fullScope fns s)` for `Main` in +`scripts/refinement/corpus/w1.sol`, where `code` is solar's runtime bytecode at the pinned commit and `s` the +storage SolidCore's constructor leaves (none): every call of every function on any +argument words below `2 ^ 256`, with no value. Each `call_*` theorem runs one function +symbolically in both semantics (`SolidCore.Refinement.Wide`): SolidCore's interpreter by +`wide_symex`, solar's bytecode on EthLib by `wide_tgt`, path by path. + +The kernel checks `shape_eq` (`kernel_rfl`, `SolidCore.Refinement.KernelRfl`): that +SolidCore's checked contract has the core `coreLit`, the generator's print of it, and that +its constructor leaves no storage and no logs, by one conversion check that evaluates copies +of the type checker and the interpreter, which read each function's selector from +`selectorTable` (`selector_eq`, each selector checked by Keccak-256 on its own). +`wide_tgt` decides branches by evaluation and `bv_omega`. +-/ + +namespace SolidCore.Refinement.Corpus.W1 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source + +/-- The interpreter fuel the refinement uses. -/ +def fuel : Nat := 4096 + +/-- solar's runtime bytecode of `Main`, from the generated file. -/ +def code : ByteArray := + EthLib.Execution.Evm.Logic.NatCode.ofNat Bytecode.W1.Main.runtimeNat + Bytecode.W1.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.W1.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. A wide parameter counts as the +`Param` of its width; `fullScope` only counts them. -/ +def fns : List Fn := + [⟨Bytecode.W1.Main.fSelector, [(.uint 256)]⟩] + +/-- SolidCore's core contract of `Main`, as the generator printed it. -/ +def coreLit : Contract := + { storageFields := [], + immutableFields := [], + eventDecls := [], + errorDecls := [], + functions := [{ name := "f", + selector? := some 3017696395, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.add) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "x")) + (SolidCore.Solidity.Source.Expr.word 1)))]]], + dispatchId? := none }, + { name := "__internal_f(uint256)#[SolidCore.Solidity.Ty.uint 256]", + selector? := none, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.add) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "x")) + (SolidCore.Solidity.Source.Expr.word 1)))]]], + dispatchId? := none }] } + +/-! ## The selectors + +The type checker computes each external function's selector by Keccak-256 of its +signature, which costs the kernel about 400 MB a hash. Each is checked once, alone, against +the bytecode file's, and the shape checks below run on copies that read them from +`selectorTable` (`selector_eq`). -/ + +/-- `f`'s selector, by Keccak-256 of its signature. -/ +def selF : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "f(uint256)" + +kernel_rfl selF_eq selF Bytecode.W1.Main.fSelector + +/-- `ABI.selectorFromSignature`, with `Main`'s signatures by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "f(uint256)" then Bytecode.W1.Main.fSelector + else SolidCore.Solidity.Source.ABI.selectorFromSignature s + +theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + by_cases h0 : s = "f(uint256)" + · rw [ite_eq_left h0, h0] + exact selF_eq + rw [ite_eq_right h0] + +/-- SolidCore's checked core of `Main`, the storage its constructor leaves and whether +it leaves no storage and no logs, when `Main` type checks. -/ +def shape? : Option (Contract × Option (List (Nat × Nat)) × Bool) := + match contract? with + | .ok c => some (c.core, deployedStorage fuel c, deployedEmpty fuel c) + | .error _ => none + +-- `shape_eq : shape? = some (coreLit, some [], true)`: `Main` type checks, its +-- core is `coreLit` and its constructor leaves no storage and no logs, by the kernel's +-- conversion check on the copy of `shape?` that reads the selectors from `selectorTable` +-- (`selector_eq`): one check evaluates the type checker once and hashes nothing, where a +-- `Bool` test of the core would need a decision procedure for equality of cores. +kernel_rfl shape_eq shape? (some (coreLit, some [], true)) using selector_eq + +/-- The checked contract has the core `coreLit`, and its constructor leaves no storage +and no logs. -/ +theorem shape_of {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core = coreLit ∧ deployedStorage fuel c = some [] ∧ deployedEmpty fuel c = true := by + have h := shape_eq + unfold shape? at h + rw [hc] at h + obtain ⟨hk, h⟩ := Prod.mk.inj (Option.some.inj h) + obtain ⟨hs, he⟩ := Prod.mk.inj h + exact ⟨hk, hs, he⟩ + +/-- `Main` type checks. -/ +theorem contract_ok : ∃ c, contract? = .ok c := by + have h := shape_eq + unfold shape? at h + cases hc : contract? with + | ok c => exact ⟨c, rfl⟩ + | error _ => rw [hc] at h; simp at h + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore and solar's bytecode agree on every call of `f` on any argument words. -/ +theorem call_f {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) (ws : List U256) (hl : ws.length = 1) : + ∃ obs, Source.run fuel c (callOf Bytecode.W1.Main.fSelector ws) = some obs ∧ + Target.run code (callOf Bytecode.W1.Main.fSelector ws) = some obs := by + rcases ws with _ | ⟨w1, _⟩ <;> simp at hl + rw [run_eq hd] + have hs := hd.storage + have hev := hd.events + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.W1.Main.fSelector] + all_goals + refine run_of_post code _ [w1] _ (by simp [Source.observe, State.logEntries, hev]) + (fun slot => by + simp [Source.observe, State.loadSlot, StorageMap.lookup?, getElem?_of_isEmpty hs, + slotValue, callOf]) ?_ + all_goals wide_tgt [code, Bytecode.W1.Main.runtimeNat, Bytecode.W1.Main.runtimeSize, Bytecode.W1.Main.fSelector] + +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on every call of every +function with any argument words below `2 ^ 256`, from the deployed storage. -/ +theorem refines_full : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + Refines fuel c code (fullScope fns s) := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hcore, hdep, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + refine ⟨c, [], hc, hdep, refines_of_calls fun fn hfn ws hl => ?_⟩ + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + rcases hfn with rfl + · exact call_f hcore hd ws hl + +end SolidCore.Refinement.Corpus.W1 diff --git a/SolidCore/Refinement/Corpus/W4.lean b/SolidCore/Refinement/Corpus/W4.lean new file mode 100644 index 00000000..1fae7555 --- /dev/null +++ b/SolidCore/Refinement/Corpus/W4.lean @@ -0,0 +1,195 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/w4.sol. Do not edit. + +import SolidCore.Refinement.Wide.Refines +import SolidCore.Refinement.Bytecode.W4 +import SolidCore.Refinement.Source.W4 +import SolidCore.Refinement.KernelCopies +import SolidCore.Refinement.KernelRfl + +/-! +# w4: solar's bytecode refines SolidCore's `Main` on wide arguments + +`refines_full` proves `Refines fuel contract code (fullScope fns s)` for `Main` in +`scripts/refinement/corpus/w4.sol`, where `code` is solar's runtime bytecode at the pinned commit and `s` the +storage SolidCore's constructor leaves (none): every call of every function on any +argument words below `2 ^ 256`, with no value. Each `call_*` theorem runs one function +symbolically in both semantics (`SolidCore.Refinement.Wide`): SolidCore's interpreter by +`wide_symex`, solar's bytecode on EthLib by `wide_tgt`, path by path. + +The kernel checks `shape_eq` (`kernel_rfl`, `SolidCore.Refinement.KernelRfl`): that +SolidCore's checked contract has the core `coreLit`, the generator's print of it, and that +its constructor leaves no storage and no logs, by one conversion check that evaluates copies +of the type checker and the interpreter, which read each function's selector from +`selectorTable` (`selector_eq`, each selector checked by Keccak-256 on its own). +`wide_tgt` decides branches by evaluation and `bv_omega`. +-/ + +namespace SolidCore.Refinement.Corpus.W4 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source + +/-- The interpreter fuel the refinement uses. -/ +def fuel : Nat := 4096 + +/-- solar's runtime bytecode of `Main`, from the generated file. -/ +def code : ByteArray := + EthLib.Execution.Evm.Logic.NatCode.ofNat Bytecode.W4.Main.runtimeNat + Bytecode.W4.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.W4.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. A wide parameter counts as the +`Param` of its width; `fullScope` only counts them. -/ +def fns : List Fn := + [⟨Bytecode.W4.Main.setSelector, [(.uint 256)]⟩] + +/-- SolidCore's core contract of `Main`, as the generator printed it. -/ +def coreLit : Contract := + { storageFields := [{ name := "x", + slot := 0, + ty? := some (SolidCore.Solidity.Source.Ty.uint256), + layout? := some (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.uint256)), + transient := false, + packedOffset := 0, + packedBytes := 32, + packedSigned := false }], + immutableFields := [], + eventDecls := [], + errorDecls := [], + functions := [{ name := "set", + selector? := some 1627277233, + payable := false, + params := [{ name := "v", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "v") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "v")), + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.storage "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "v"))]], + dispatchId? := none }, + { name := "__internal_set(uint256)#[SolidCore.Solidity.Ty.uint 256]", + selector? := none, + payable := false, + params := [{ name := "v", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "v") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "v")), + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.storage "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "v"))]], + dispatchId? := none }] } + +/-! ## The selectors + +The type checker computes each external function's selector by Keccak-256 of its +signature, which costs the kernel about 400 MB a hash. Each is checked once, alone, against +the bytecode file's, and the shape checks below run on copies that read them from +`selectorTable` (`selector_eq`). -/ + +/-- `set`'s selector, by Keccak-256 of its signature. -/ +def selSet : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "set(uint256)" + +kernel_rfl selSet_eq selSet Bytecode.W4.Main.setSelector + +/-- `ABI.selectorFromSignature`, with `Main`'s signatures by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "set(uint256)" then Bytecode.W4.Main.setSelector + else SolidCore.Solidity.Source.ABI.selectorFromSignature s + +theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + by_cases h0 : s = "set(uint256)" + · rw [ite_eq_left h0, h0] + exact selSet_eq + rw [ite_eq_right h0] + +/-- SolidCore's checked core of `Main`, the storage its constructor leaves and whether +it leaves no storage and no logs, when `Main` type checks. -/ +def shape? : Option (Contract × Option (List (Nat × Nat)) × Bool) := + match contract? with + | .ok c => some (c.core, deployedStorage fuel c, deployedEmpty fuel c) + | .error _ => none + +-- `shape_eq : shape? = some (coreLit, some [], true)`: `Main` type checks, its +-- core is `coreLit` and its constructor leaves no storage and no logs, by the kernel's +-- conversion check on the copy of `shape?` that reads the selectors from `selectorTable` +-- (`selector_eq`): one check evaluates the type checker once and hashes nothing, where a +-- `Bool` test of the core would need a decision procedure for equality of cores. +kernel_rfl shape_eq shape? (some (coreLit, some [], true)) using selector_eq + +/-- The checked contract has the core `coreLit`, and its constructor leaves no storage +and no logs. -/ +theorem shape_of {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core = coreLit ∧ deployedStorage fuel c = some [] ∧ deployedEmpty fuel c = true := by + have h := shape_eq + unfold shape? at h + rw [hc] at h + obtain ⟨hk, h⟩ := Prod.mk.inj (Option.some.inj h) + obtain ⟨hs, he⟩ := Prod.mk.inj h + exact ⟨hk, hs, he⟩ + +/-- `Main` type checks. -/ +theorem contract_ok : ∃ c, contract? = .ok c := by + have h := shape_eq + unfold shape? at h + cases hc : contract? with + | ok c => exact ⟨c, rfl⟩ + | error _ => rw [hc] at h; simp at h + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore and solar's bytecode agree on every call of `set` on any argument words. -/ +theorem call_set {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) (ws : List U256) (hl : ws.length = 1) : + ∃ obs, Source.run fuel c (callOf Bytecode.W4.Main.setSelector ws) = some obs ∧ + Target.run code (callOf Bytecode.W4.Main.setSelector ws) = some obs := by + rcases ws with _ | ⟨w1, _⟩ <;> simp at hl + rw [run_eq hd] + have hs := hd.storage + have hev := hd.events + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.W4.Main.setSelector] + all_goals + refine run_of_postS code _ [w1] _ (by simp [Source.observe, State.logEntries, hev]) + (fun hX slot => by simp_all [Source.observe, slotValue, callOf]) ?_ + all_goals wide_tgt_s [code, Bytecode.W4.Main.runtimeNat, Bytecode.W4.Main.runtimeSize, Bytecode.W4.Main.setSelector] + +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on every call of every +function with any argument words below `2 ^ 256`, from the deployed storage. -/ +theorem refines_full : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + Refines fuel c code (fullScope fns s) := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hcore, hdep, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + refine ⟨c, [], hc, hdep, refines_of_calls fun fn hfn ws hl => ?_⟩ + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + rcases hfn with rfl + · exact call_set hcore hd ws hl + +end SolidCore.Refinement.Corpus.W4 diff --git a/SolidCore/Refinement/Corpus/W5.lean b/SolidCore/Refinement/Corpus/W5.lean new file mode 100644 index 00000000..1a212890 --- /dev/null +++ b/SolidCore/Refinement/Corpus/W5.lean @@ -0,0 +1,229 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/w5.sol. Do not edit. + +import SolidCore.Refinement.Wide.Refines +import SolidCore.Refinement.Bytecode.W5 +import SolidCore.Refinement.Source.W5 +import SolidCore.Refinement.KernelCopies +import SolidCore.Refinement.KernelRfl + +/-! +# w5: solar's bytecode refines SolidCore's `Main` on wide arguments + +`refines_full` proves `Refines fuel contract code (fullScope fns s)` for `Main` in +`scripts/refinement/corpus/w5.sol`, where `code` is solar's runtime bytecode at the pinned commit and `s` the +storage SolidCore's constructor leaves (none): every call of every function on any +argument words below `2 ^ 256`, with no value. Each `call_*` theorem runs one function +symbolically in both semantics (`SolidCore.Refinement.Wide`): SolidCore's interpreter by +`wide_symex`, solar's bytecode on EthLib by `wide_tgt`, path by path. + +The kernel checks `shape_eq` (`kernel_rfl`, `SolidCore.Refinement.KernelRfl`): that +SolidCore's checked contract has the core `coreLit`, the generator's print of it, and that +its constructor leaves no storage and no logs, by one conversion check that evaluates copies +of the type checker and the interpreter, which read each function's selector from +`selectorTable` (`selector_eq`, each selector checked by Keccak-256 on its own). +`wide_tgt` decides branches by evaluation and `bv_omega`. +-/ + +namespace SolidCore.Refinement.Corpus.W5 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source + +/-- The interpreter fuel the refinement uses. -/ +def fuel : Nat := 4096 + +/-- solar's runtime bytecode of `Main`, from the generated file. -/ +def code : ByteArray := + EthLib.Execution.Evm.Logic.NatCode.ofNat Bytecode.W5.Main.runtimeNat + Bytecode.W5.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.W5.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. A wide parameter counts as the +`Param` of its width; `fullScope` only counts them. -/ +def fns : List Fn := + [⟨Bytecode.W5.Main.fSelector, [(.uint 256), (.uint 256)]⟩] + +/-- SolidCore's core contract of `Main`, as the generator printed it. -/ +def coreLit : Contract := + { storageFields := [], + immutableFields := [], + eventDecls := [], + errorDecls := [], + functions := [{ name := "f", + selector? := some 332507694, + payable := false, + params := [{ name := "a", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }, + { name := "b", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256, + SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "a") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "a")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "b") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "b")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.add) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "a")) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "b"))))]]], + dispatchId? := none }, + { name := "__internal_f(uint256,uint256)#[SolidCore.Solidity.Ty.uint 256, SolidCore.Solidity.Ty.uint 256]", + selector? := none, + payable := false, + params := [{ name := "a", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }, + { name := "b", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256, + SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "a") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "a")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "b") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "b")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.add) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "a")) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "b"))))]]], + dispatchId? := none }] } + +/-! ## The selectors + +The type checker computes each external function's selector by Keccak-256 of its +signature, which costs the kernel about 400 MB a hash. Each is checked once, alone, against +the bytecode file's, and the shape checks below run on copies that read them from +`selectorTable` (`selector_eq`). -/ + +/-- `f`'s selector, by Keccak-256 of its signature. -/ +def selF : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "f(uint256,uint256)" + +kernel_rfl selF_eq selF Bytecode.W5.Main.fSelector + +/-- `ABI.selectorFromSignature`, with `Main`'s signatures by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "f(uint256,uint256)" then Bytecode.W5.Main.fSelector + else SolidCore.Solidity.Source.ABI.selectorFromSignature s + +theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + by_cases h0 : s = "f(uint256,uint256)" + · rw [ite_eq_left h0, h0] + exact selF_eq + rw [ite_eq_right h0] + +/-- SolidCore's checked core of `Main`, the storage its constructor leaves and whether +it leaves no storage and no logs, when `Main` type checks. -/ +def shape? : Option (Contract × Option (List (Nat × Nat)) × Bool) := + match contract? with + | .ok c => some (c.core, deployedStorage fuel c, deployedEmpty fuel c) + | .error _ => none + +-- `shape_eq : shape? = some (coreLit, some [], true)`: `Main` type checks, its +-- core is `coreLit` and its constructor leaves no storage and no logs, by the kernel's +-- conversion check on the copy of `shape?` that reads the selectors from `selectorTable` +-- (`selector_eq`): one check evaluates the type checker once and hashes nothing, where a +-- `Bool` test of the core would need a decision procedure for equality of cores. +kernel_rfl shape_eq shape? (some (coreLit, some [], true)) using selector_eq + +/-- The checked contract has the core `coreLit`, and its constructor leaves no storage +and no logs. -/ +theorem shape_of {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core = coreLit ∧ deployedStorage fuel c = some [] ∧ deployedEmpty fuel c = true := by + have h := shape_eq + unfold shape? at h + rw [hc] at h + obtain ⟨hk, h⟩ := Prod.mk.inj (Option.some.inj h) + obtain ⟨hs, he⟩ := Prod.mk.inj h + exact ⟨hk, hs, he⟩ + +/-- `Main` type checks. -/ +theorem contract_ok : ∃ c, contract? = .ok c := by + have h := shape_eq + unfold shape? at h + cases hc : contract? with + | ok c => exact ⟨c, rfl⟩ + | error _ => rw [hc] at h; simp at h + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore and solar's bytecode agree on every call of `f` on any argument words. -/ +theorem call_f {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) (ws : List U256) (hl : ws.length = 2) : + ∃ obs, Source.run fuel c (callOf Bytecode.W5.Main.fSelector ws) = some obs ∧ + Target.run code (callOf Bytecode.W5.Main.fSelector ws) = some obs := by + rcases ws with _ | ⟨w1, _ | ⟨w2, _⟩⟩ <;> simp at hl + rw [run_eq hd] + have hs := hd.storage + have hev := hd.events + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.W5.Main.fSelector] + all_goals + refine run_of_post code _ [w1, w2] _ (by simp [Source.observe, State.logEntries, hev]) + (fun slot => by + simp [Source.observe, State.loadSlot, StorageMap.lookup?, getElem?_of_isEmpty hs, + slotValue, callOf]) ?_ + all_goals wide_tgt [code, Bytecode.W5.Main.runtimeNat, Bytecode.W5.Main.runtimeSize, Bytecode.W5.Main.fSelector] + +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on every call of every +function with any argument words below `2 ^ 256`, from the deployed storage. -/ +theorem refines_full : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + Refines fuel c code (fullScope fns s) := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hcore, hdep, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + refine ⟨c, [], hc, hdep, refines_of_calls fun fn hfn ws hl => ?_⟩ + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + rcases hfn with rfl + · exact call_f hcore hd ws hl + +end SolidCore.Refinement.Corpus.W5 diff --git a/SolidCore/Refinement/Deploy.lean b/SolidCore/Refinement/Deploy.lean new file mode 100644 index 00000000..88af272c --- /dev/null +++ b/SolidCore/Refinement/Deploy.lean @@ -0,0 +1,37 @@ +import SolidCore.Refinement.Compose + +/-! +# Deployment + +\`Deploys initcode code storage\`: EthLib runs the init code \`initcode\` as a creation does (one frame +with no value and no call data, from the empty storage, the code at the contract's address being +the init code) to success, and the frame returns exactly the runtime bytecode \`code\` and leaves the +storage \`storage\` (\`SolarTV.slotValue\`: the last write of each slot, unwritten slots 0). It is the +fact a deployment theorem proves of solar's init code (\`Counter.deploys\`, Contracts/Counter/Deploys.lean), +and what ties the bytecode a headline is about to the contract that a creation installs. + +Not covered, as in Contracts/Counter/Deploy.lean: the creation message's address derivation and the +code deposit (EIP-3541's \`0xef\` check and the 24576-byte limit), which \`deposit_ok\` checks of the +runtime bytecode separately. +-/ + +namespace SolidCore.Refinement + +/-- The creation frame: no call data, no value, the empty storage. -/ +def deployCall : Call := { calldata := .empty, callvalue := 0, storage := [] } + +/-- EthLib runs \`initcode\` in the creation frame to success, returning \`code\` and leaving +\`storage\`. -/ +def Deploys (initcode code : ByteArray) (storage : List (Nat × Nat)) : Prop := + ∃ o, ethLib.run initcode deployCall = some o ∧ o.success = true ∧ + o.output = code.data.toList.map (·.toNat) ∧ ∀ k, o.storage k = SolarTV.slotValue storage k + +/-- A run of the init code that returns the runtime bytecode and writes no storage deploys it with +the empty storage. -/ +theorem deploys_of_run {initcode code : ByteArray} {o : Observable} + (h : Target.run initcode deployCall = some o) (hs : o.success = true) + (ho : o.output = code.data.toList.map (·.toNat)) (hst : ∀ k, o.storage k = 0) : + Deploys initcode code [] := + ⟨o, h, hs, ho, fun k => by rw [hst k]; rfl⟩ + +end SolidCore.Refinement diff --git a/SolidCore/Refinement/Dirty.lean b/SolidCore/Refinement/Dirty.lean new file mode 100644 index 00000000..564e6561 --- /dev/null +++ b/SolidCore/Refinement/Dirty.lean @@ -0,0 +1,22 @@ +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source + +/-! +# Dirty argument words + +A call of a corpus function whose argument words are below `2 ^ 256` but not all +clean for their ABI types is rejected on both sides: SolidCore and solar's bytecode +on EthLib both revert with empty output and keep the storage. + +* `SolidCore.Refinement.Evm.Calldata`: the call data `cdOf`, `Abi.Dirty`, + cleanliness on bit vectors and the rules a symbolic run reads call data with. +* `SolidCore.Refinement.Evm.Symex`: the tactic `dirty_symex` and the lemma + `dirty_of_frame` that turns its frame result into one about `Target.run`. +* `SolidCore.Refinement.Dirty.Source`: SolidCore's side, `run_dirty`, for every + function whose shape `fnShapeOk` accepts, and `refines_full`, which joins the + clean and dirty calls into one refinement. + +Each corpus contract's `Corpus//Dirty.lean`, written by +`scripts/refinement/gen_proof.py`, proves EthLib's side with one `dirty_symex` +call per function, and `Corpus/.lean` states `refines_full` for it. +-/ diff --git a/SolidCore/Refinement/Dirty/Source.lean b/SolidCore/Refinement/Dirty/Source.lean new file mode 100644 index 00000000..f8edcb31 --- /dev/null +++ b/SolidCore/Refinement/Dirty/Source.lean @@ -0,0 +1,479 @@ +import SolidCore.Refinement.Evm.Calldata + +/-! +# SolidCore rejects dirty argument words + +SolidCore lowers a narrow ABI parameter to a `uint256`, `int256` or `bool` +word with an `AbiCleanup` (`uint b`, `int b`, `none`, `enum (n - 1)`). Its +decoder reads every word first, then applies the cleanups, and every failure on +the way is the empty revert. `decode_dirty` shows that a function of that shape, +`fitsAll`, decodes any argument list with a dirty word to `RevertData.empty`, +and `run_dirty` lifts it to `Source.run`: the call shows `Abi.rejected`. + +`fnShapeOk` checks the shape of one function of a checked contract as a `Bool`, +so a proof about a contract establishes it with `native_decide`. + +`refines_full` joins the two halves of a contract's proof: the refinement on the +clean calls `Abi.calls` (checked by evaluation) and EthLib's rejection of dirty +calls (`TargetDirty`, proved symbolically by `dirty_symex`) give the refinement +on `Abi.fullScope`, every call on any argument words below `2 ^ 256`. The +`Abi` section at the top shows that a clean argument list is one of +`Abi.calls` (`mem_calls`). +-/ + +namespace SolidCore.Refinement.Abi + +/-! ## Membership of clean calls -/ + +/-- A clean word of a parameter is one of its values. -/ +theorem mem_values {p : Param} {v : Nat} (hv : v < 2 ^ 256) (h : p.clean v = true) : + v ∈ p.values := by + cases p with + | uint b => simpa [Param.clean, Param.values] using h + | int b => + simp only [Param.clean, Bool.or_eq_true, Bool.and_eq_true, decide_eq_true_eq] at h + simp only [Param.values, List.mem_append, List.mem_map, List.mem_range] + generalize 2 ^ (b - 1) = Q at * + rcases h with h | ⟨h1, -⟩ + · exact Or.inr h + · left + refine ⟨v - (2 ^ 256 - Q), by omega, by omega⟩ + | bool => + simp only [Param.clean, decide_eq_true_eq] at h + simp only [Param.values, List.mem_cons, List.not_mem_nil, or_false] + omega + | enum n => simpa [Param.clean, Param.values] using h + +/-- A list of clean words for the parameters is one of their tuples. -/ +theorem mem_tuples : ∀ {ps : List Param} {args : List Nat}, args.length = ps.length → + (∀ a ∈ args, a < 2 ^ 256) → + (∀ i (hp : i < ps.length) (ha : i < args.length), ps[i].clean args[i] = true) → + args ∈ tuples ps + | [], [], _, _, _ => by simp [tuples] + | p :: ps, a :: args, hlen, hargs, hc => by + simp only [tuples, List.mem_flatMap, List.mem_map] + refine ⟨a, mem_values (hargs a List.mem_cons_self) (hc 0 (by simp) (by simp)), args, + mem_tuples (by simpa using hlen) (fun b hb => hargs b (List.mem_cons_of_mem _ hb)) + (fun i hp ha => hc (i + 1) (by simpa using hp) (by simpa using ha)), rfl⟩ + | [], _ :: _, hlen, _, _ | _ :: _, [], hlen, _, _ => by simp at hlen + +/-- A call of a function of `fns` on clean words, from `s`, is one of `calls fns [s]`. -/ +theorem mem_calls {fns : List Fn} {fn : Fn} (hfn : fn ∈ fns) {s : List (Nat × Nat)} + {args : List Nat} (hlen : args.length = fn.params.length) (hargs : ∀ a ∈ args, a < 2 ^ 256) + (hc : ∀ i (hp : i < fn.params.length) (ha : i < args.length), + fn.params[i].clean args[i] = true) : + { calldata := calldata fn.sel args, callvalue := 0, storage := s } ∈ calls fns [s] := by + simp only [calls, List.flatMap_cons, List.flatMap_nil, List.append_nil, List.mem_flatMap, + List.mem_map] + exact ⟨fn, hfn, args, mem_tuples hlen hargs hc, rfl⟩ + +/-- Every call of a function of `fns` on any argument words below `2 ^ 256`, clean or not, +with no value, from the storage `s`. -/ +def fullScope (fns : List Fn) (s : List (Nat × Nat)) (call : Call) : Prop := + ∃ fn ∈ fns, ∃ args : List Nat, args.length = fn.params.length ∧ (∀ a ∈ args, a < 2 ^ 256) ∧ + call = { calldata := calldata fn.sel args, callvalue := 0, storage := s } + +end SolidCore.Refinement.Abi + +namespace SolidCore.Refinement.Dirty + +open EthLib.Base SolidCore.Refinement.Abi +open SolidCore.Solidity SolidCore.Solidity.Source + +/-! ## The shape of a function -/ + +/-- Whether SolidCore's parameter type `ty` and cleanup `c` are the lowering of the ABI +parameter `p`. -/ +def paramFits : Param → Source.Ty → AbiCleanup → Bool + | .uint b, .uint256, .uint b' => b == b' && 0 < b && b ≤ 256 + | .int b, .int256, .int b' => b == b' && 0 < b && b ≤ 256 + | .bool, .bool, .none => true + | .enum n, .uint256, .enum m => m + 1 == n && m < 2 ^ 256 + | _, _, _ => false + +/-- Whether the parameter types and cleanups of a function are the lowering of `ps`. -/ +def fitsAll : List Param → List Source.Ty → List AbiCleanup → Bool + | p :: ps, ty :: tys, c :: cs => paramFits p ty c && fitsAll ps tys cs + | [], [], [] => true + | _, _, _ => false + +/-- Whether the checked contract dispatches the selector of `fn` to a function whose +parameters are the lowering of `fn`'s. -/ +def fnShapeOk (c : TypeCheck.CheckedContract) (fn : Fn) : Bool := + decide (fn.sel < 2 ^ 32) && + match c.core.findFunctionBySelector? fn.sel with + | some f => fitsAll fn.params (f.params.map BindingDecl.ty) f.paramAbiCleanups + | none => false + +/-! ## Reading the argument words -/ + +/-- The bytes SolidCore reads after the selector. -/ +def argBytes (args : List Nat) : List Nat := args.flatMap fun a => (natToBytes 32 a).map (·.toNat) + +theorem norm_of_lt {a : Nat} (h : a < 2 ^ 256) : Shared.norm a = a := by + simp only [Shared.norm, Shared.wordModulus] + exact Nat.mod_eq_of_lt h + +/-- SolidCore reads `n` big-endian bytes of `a` back as `a`. -/ +theorem bytesToWordBE_natToBytes (n a : Nat) (ha : a < 256 ^ n) (hn : n ≤ 32) : + ABI.bytesToWordBE (ABI.normalizeBytes ((natToBytes n a).map (·.toNat))) = a := by + have h256 : 256 ^ n ≤ 2 ^ 256 := by + rw [show (256 : Nat) = 2 ^ 8 by rfl, ← Nat.pow_mul] + exact Nat.pow_le_pow_right (by decide) (by omega) + have hbyte : ∀ b : UInt8, normByte (Shared.External.byte b.toNat) = b.toNat := by + intro b + have := b.toNat_lt + simp [normByte, Shared.Account.byte, Shared.External.byte, Nat.mod_eq_of_lt this] + unfold ABI.bytesToWordBE ABI.normalizeBytes Shared.External.normalizeBytes + rw [List.map_map, List.foldl_map] + simp only [Function.comp_def, hbyte] + change Shared.norm (bytesToNat (natToBytes n a)) = _ + rw [EthLib.Base.bytesToNat_natToBytes_of_lt ha, norm_of_lt (by omega)] + +theorem length_argBytes (args : List Nat) : (argBytes args).length = 32 * args.length := by + induction args with + | nil => rfl + | cons a rest ih => + simp only [argBytes, List.flatMap_cons, List.length_append, List.length_map, + natToBytes_length] at ih ⊢ + rw [ih, List.length_cons]; omega + +/-- The word at index `i` of the argument bytes is argument `i`. -/ +theorem readWord_argBytes (args : List Nat) (hargs : ∀ a ∈ args, a < 2 ^ 256) (i : Nat) + (hi : i < args.length) : ABI.readWord? (argBytes args) (32 * i) = some args[i] := by + induction args generalizing i with + | nil => simp at hi + | cons a rest ih => + have hchunk : ((natToBytes 32 a).map (·.toNat)).length = 32 := by + simp [natToBytes_length] + have hsplit : argBytes (a :: rest) = (natToBytes 32 a).map (·.toNat) ++ argBytes rest := by + simp [argBytes] + cases i with + | zero => + have ha : a < 256 ^ 32 := by + have := hargs a List.mem_cons_self + rwa [show (2 : Nat) ^ 256 = 256 ^ 32 by decide] at this + simp only [ABI.readWord?, ABI.readBytes?, ABI.wordBytes, Nat.mul_zero, List.drop_zero, + hsplit, List.length_append, hchunk] + rw [ite_eq_left (by omega), List.take_append_of_le_length (by omega), + List.take_of_length_le (by omega)] + simp only [bytesToWordBE_natToBytes 32 a ha (by decide), List.getElem_cons_zero] + | succ i => + have := ih (fun b hb => hargs b (List.mem_cons_of_mem _ hb)) i (by simp at hi; omega) + have hd : ((natToBytes 32 a).map (·.toNat) ++ argBytes rest).drop (32 + 32 * i) = + (argBytes rest).drop (32 * i) := by + rw [List.drop_append, List.drop_eq_nil_of_le (by omega), hchunk, List.nil_append] + congr 1; omega + rw [hsplit, show 32 * (i + 1) = 32 + 32 * i by omega] + simp only [ABI.readWord?, ABI.readBytes?, List.getElem_cons_succ] at this ⊢ + rw [hd] + exact this + +/-! ## Decoding one word -/ + +/-- The value SolidCore decodes from the word `a` of type `ty`, before its cleanup. -/ +def wordValue : Source.Ty → Nat → Value + | .int256, a => .int a + | _, a => .word a + +theorem headWords_of_fits {p : Param} {ty : Source.Ty} {c : AbiCleanup} + (h : paramFits p ty c = true) : ABI.Ty.abiHeadWords? ty = some 1 := by + unfold paramFits at h + split at h <;> first | (simp at h; done) | rfl + +/-- A parameter of the shape decodes its word, or fails with the empty revert. -/ +theorem decode_of_fits {p : Param} {ty : Source.Ty} {c : AbiCleanup} + (h : paramFits p ty c = true) {lazy : Bool} {data : List Nat} {idx a : Nat} + (hr : ABI.readWord? data (ABI.wordBytes * idx) = some a) : + ABI.decodeValueAt? lazy data idx ty = .error .empty ∨ + ABI.decodeValueAt? lazy data idx ty = .ok (wordValue ty a) := by + unfold paramFits at h + split at h <;> first | (simp at h; done) | skip + all_goals simp only [ABI.decodeValueAt?, ABI.Ty.abiDecodeFuel, ABI.decodeValueAtWithFuel?, hr, + ABI.abiArgOpt, bind, Except.bind, pure, Except.pure, wordValue] + all_goals first | (right; rfl) | simp | (split <;> simp) + +/-- The empty revert, or the decoded word's cleanup rejecting it, when the word is dirty. -/ +theorem rejects_of_fits {p : Param} {ty : Source.Ty} {c : AbiCleanup} + (h : paramFits p ty c = true) {lazy : Bool} {data : List Nat} {idx a : Nat} + (hr : ABI.readWord? data (ABI.wordBytes * idx) = some a) (ha : a < 2 ^ 256) + (hd : p.clean a = false) : + ABI.decodeValueAt? lazy data idx ty = .error .empty ∨ + c.lazyParamValue (wordValue ty a) = none := by + have hn := norm_of_lt ha + unfold paramFits at h + split at h <;> first | (simp at h; done) | skip + · -- uintN + right + rename_i b b' + simp only [Bool.and_eq_true, beq_iff_eq, decide_eq_true_eq] at h + obtain ⟨⟨rfl, -⟩, -⟩ := h + simp only [Param.clean, decide_eq_false_iff_not, Nat.not_lt] at hd + simp [wordValue, AbiCleanup.lazyParamValue, AbiCleanup.accepts, hn] + intros; omega + · -- intN + right + rename_i b b' + simp only [Bool.and_eq_true, beq_iff_eq, decide_eq_true_eq] at h + obtain ⟨⟨rfl, hb0⟩, hb⟩ := h + simp only [Param.clean, Bool.or_eq_false_iff, decide_eq_false_iff_not, Nat.not_lt, + Bool.and_eq_false_iff] at hd + have hq : 0 < 2 ^ (b - 1) := Nat.two_pow_pos _ + have hpq : 2 ^ b = 2 * 2 ^ (b - 1) := by + conv_lhs => rw [show b = (b - 1) + 1 by omega] + rw [Nat.pow_succ]; omega + have hp : 2 ^ b ≤ 2 ^ 256 := Nat.pow_le_pow_right (by decide) hb + have hlow : a % 2 ^ b < 2 ^ b := Nat.mod_lt _ (Nat.two_pow_pos _) + have hlow' : a % 2 ^ b ≤ a := Nat.mod_le _ _ + simp only [wordValue, AbiCleanup.lazyParamValue, AbiCleanup.accepts, hb0, hb, decide_true, + Bool.and_self, ite_true] + rw [ite_eq_right_iff] + intro heq + exfalso + have hW : wordModulus = 2 ^ 256 := rfl + simp only [wordEq, beq_iff_eq, Shared.norm, Shared.wordModulus, EvmYul.UInt256.size, hW] + at heq hn + generalize 2 ^ (b - 1) = Q at * + generalize 2 ^ b = P at * + have hQle : Q ≤ 2 ^ 256 := by omega + have hS := Nat.sub_add_cancel hQle + generalize 2 ^ 256 - Q = R at * + rw [hn] at heq + split at heq + · rename_i hs + have hT := Nat.sub_add_cancel hp + generalize 2 ^ 256 - P = T at * + rw [Nat.mod_eq_of_lt (by omega), Nat.mod_eq_of_lt (by omega)] at heq + have h1 : T + a % P = a := heq + have h2 : Q ≤ a % P := hs + omega + · rename_i hs + rw [Nat.mod_eq_of_lt (by omega), Nat.mod_eq_of_lt (by omega)] at heq + have h1 : a % P = a := heq + have h2 : ¬ Q ≤ a % P := hs + omega + · -- bool + left + simp only [Param.clean, decide_eq_false_iff_not, Nat.not_lt] at hd + simp only [ABI.decodeValueAt?, ABI.Ty.abiDecodeFuel, ABI.decodeValueAtWithFuel?, hr, + ABI.abiArgOpt, bind, Except.bind, pure, Except.pure] + simp [wordEq, hn, norm_of_lt (show (0 : Nat) < 2 ^ 256 by decide), + norm_of_lt (show (1 : Nat) < 2 ^ 256 by decide)] + exact ⟨by rintro rfl; exact absurd hd (by decide), by rintro rfl; exact absurd hd (by decide)⟩ + · -- enum + right + rename_i n m + simp only [Bool.and_eq_true, beq_iff_eq, decide_eq_true_eq] at h + obtain ⟨rfl, hm⟩ := h + simp only [Param.clean, decide_eq_false_iff_not, Nat.not_lt] at hd + simp [wordValue, AbiCleanup.lazyParamValue, AbiCleanup.accepts, hn, norm_of_lt hm] + exact hd + +/-! ## Decoding the argument list -/ + +/-- Under the shape, every decoding failure is the empty revert, and an argument list with +a dirty word that decodes has a cleanup that rejects it. -/ +theorem decodeAux_of_fits (data : List Nat) : ∀ (ps : List Param) (tys : List Source.Ty) + (cs : List AbiCleanup) (flags : List Bool) (args : List Nat) (idx : Nat), + fitsAll ps tys cs = true → flags.length = tys.length → args.length = ps.length → + (∀ a ∈ args, a < 2 ^ 256) → + (∀ i (h : i < args.length), ABI.readWord? data (ABI.wordBytes * (idx + i)) = some args[i]) → + (∀ e, ABI.decodeArgsAux? data (flags.zip tys) idx = .error e → e = .empty) ∧ + (Dirty ps args → ∀ vs, ABI.decodeArgsAux? data (flags.zip tys) idx = .ok vs → + AbiCleanups.lazyParamValues cs vs = none) + | [], [], [], [], [], _, _, _, _, _, _ => by + refine ⟨fun e h => by simp [ABI.decodeArgsAux?] at h, fun ⟨i, hp, _, _⟩ => by simp at hp⟩ + | p :: ps, ty :: tys, c :: cs, f :: flags, a :: args, idx, hfit, hfl, hlen, hargs, hread => by + simp only [fitsAll, Bool.and_eq_true] at hfit + obtain ⟨hp, hfit⟩ := hfit + have ih := decodeAux_of_fits data ps tys cs flags args (idx + 1) hfit + (by simpa using hfl) (by simpa using hlen) + (fun b hb => hargs b (List.mem_cons_of_mem _ hb)) + (fun i h => by + rw [show idx + 1 + i = idx + (i + 1) by omega] + exact hread (i + 1) (by simp; omega)) + have hr0 : ABI.readWord? data (ABI.wordBytes * idx) = some a := by + have := hread 0 (by simp) + rw [Nat.add_zero] at this + exact this + have hw := headWords_of_fits hp + have hdec := decode_of_fits (lazy := f) hp hr0 + simp only [List.zip_cons_cons, ABI.decodeArgsAux?, hw, ABI.abiArgOpt, bind, Except.bind, + pure, Except.pure] + refine ⟨fun e h => ?_, fun hd vs h => ?_⟩ + · rcases hdec with hdec | hdec <;> rw [hdec] at h + · simpa using h.symm + · simp only at h + split at h + · rename_i err herr + obtain rfl : err = e := by simpa using h + exact ih.1 _ herr + · simp at h + · rcases hdec with hdec | hdec <;> rw [hdec] at h + · simp at h + simp only at h + split at h + · simp at h + rename_i vs' hvs' + simp only [Except.ok.injEq] at h + subst h + obtain ⟨i, hip, hia, hcl⟩ := hd + simp only [AbiCleanups.lazyParamValues, bind, Option.bind] + cases i with + | zero => + have := rejects_of_fits (lazy := f) hp hr0 (hargs a List.mem_cons_self) (by simpa using hcl) + rw [hdec] at this + rcases this with h' | h' + · simp at h' + · rw [h'] + | succ i => + have := ih.2 ⟨i, by simpa using hip, by simpa using hia, by simpa using hcl⟩ vs' hvs' + split + · rfl + · rw [this] + | [], [], [], _ :: _, _, _, _, hfl, _, _, _ => by simp at hfl + | [], [], [], [], _ :: _, _, _, _, hlen, _, _ => by simp at hlen + | p :: ps, ty :: tys, c :: cs, [], _, _, _, hfl, _, _, _ => by simp at hfl + | p :: ps, ty :: tys, c :: cs, _ :: _, [], _, _, _, hlen, _, _ => by simp at hlen + | [], _ :: _, _, _, _, _, hfit, _, _, _, _ => by simp [fitsAll] at hfit + | [], [], _ :: _, _, _, _, hfit, _, _, _, _ => by simp [fitsAll] at hfit + | _ :: _, [], _, _, _, _, hfit, _, _, _, _ => by simp [fitsAll] at hfit + | _ :: _, _ :: _, [], _, _, _, hfit, _, _, _, _ => by simp [fitsAll] at hfit + +theorem length_of_fitsAll : ∀ {ps : List Param} {tys : List Source.Ty} {cs : List AbiCleanup}, + fitsAll ps tys cs = true → tys.length = ps.length ∧ cs.length = ps.length + | [], [], [], _ => ⟨rfl, rfl⟩ + | _ :: _, _ :: _, _ :: _, h => by + simp only [fitsAll, Bool.and_eq_true] at h + have := length_of_fitsAll h.2 + simp [this.1, this.2] + | [], _ :: _, _, h | [], [], _ :: _, h | _ :: _, [], _, h | _ :: _, _ :: _, [], h => by + simp [fitsAll] at h + +theorem listHeadWords_of_fitsAll : ∀ {ps : List Param} {tys : List Source.Ty} + {cs : List AbiCleanup}, fitsAll ps tys cs = true → + ABI.Ty.listAbiHeadWords? tys = some tys.length + | [], [], [], _ => rfl + | _ :: _, _ :: _, _ :: _, h => by + simp only [fitsAll, Bool.and_eq_true] at h + simp [ABI.Ty.listAbiHeadWords?, headWords_of_fits h.1, listHeadWords_of_fitsAll h.2, + Nat.add_comm] + | [], _ :: _, _, h | [], [], _ :: _, h | _ :: _, [], _, h | _ :: _, _ :: _, [], h => by + simp [fitsAll] at h + +/-- A function of the shape decodes every argument list with a dirty word to the empty +revert. -/ +theorem decode_dirty (fn : FunctionDef) (ps : List Param) + (hfit : fitsAll ps (fn.params.map BindingDecl.ty) fn.paramAbiCleanups = true) + (args : List Nat) (hlen : args.length = ps.length) (hargs : ∀ a ∈ args, a < 2 ^ 256) + (hd : Dirty ps args) : ABI.decodeFunctionArgs? fn (argBytes args) = .error .empty := by + obtain ⟨htl, hcl⟩ := length_of_fitsAll hfit + have hne : fn.paramAbiCleanups.isEmpty = false := by + obtain ⟨i, hip, -, -⟩ := hd + cases h : fn.paramAbiCleanups with + | nil => rw [h] at hcl; simp at hcl; omega + | cons _ _ => rfl + have hflags : (fn.paramAbiCleanups.map ABI.AbiCleanup.decodeLazy).length = + (fn.params.map BindingDecl.ty).length := by simp [htl, hcl] + have hread : ∀ i (h : i < args.length), + ABI.readWord? (argBytes args) (ABI.wordBytes * (0 + i)) = some args[i] := by + intro i h + simpa [ABI.wordBytes] using readWord_argBytes args hargs i h + have hh := decodeAux_of_fits (argBytes args) ps _ _ _ args 0 hfit hflags hlen hargs hread + have hz : List.map Prod.snd ((fn.paramAbiCleanups.map ABI.AbiCleanup.decodeLazy).zip + (fn.params.map BindingDecl.ty)) = fn.params.map BindingDecl.ty := + List.map_snd_zip (le_of_eq hflags.symm) + unfold ABI.decodeFunctionArgs? ABI.decodeArgsWith? + simp only [hz, listHeadWords_of_fitsAll hfit, ABI.abiArgOpt, + length_argBytes, htl, hcl, hlen, beq_self_eq_true, ite_true, hne, bind, Except.bind, pure, + Except.pure, ABI.wordBytes, Nat.lt_irrefl, ite_false] + split + · rename_i e he + rw [hh.1 e he] + · rename_i vs hvs + simp [hh.2 hd vs hvs] + +/-! ## The call -/ + +/-- The call data of `Abi.calldata`, byte by byte as SolidCore reads it. -/ +theorem bytes_calldata (sel : Nat) (args : List Nat) : + (calldata sel args).data.toList.map (·.toNat) = + (natToBytes 4 sel).map (·.toNat) ++ argBytes args := by + simp [calldata, argBytes, List.map_flatMap] + +theorem readSelector_calldata (sel : Nat) (hsel : sel < 2 ^ 32) (args : List Nat) : + ABI.readSelector? ((natToBytes 4 sel).map (·.toNat) ++ argBytes args) = some sel := by + have hlen : ((natToBytes 4 sel).map (·.toNat)).length = 4 := by simp [natToBytes_length] + simp only [ABI.readSelector?, ABI.readBytes?, ABI.selectorBytes, List.drop_zero, + List.length_append, hlen] + rw [ite_eq_left (by omega), List.take_append_of_le_length (by omega), + List.take_of_length_le (by omega)] + simp only [bytesToWordBE_natToBytes 4 sel (by simpa using hsel) (by decide)] + +/-- SolidCore's run of a call of a function of the shape, from any storage, on argument +words with a dirty one: the empty revert, which keeps the call's storage. -/ +theorem run_dirty {fuel : Nat} {c : TypeCheck.CheckedContract} {s0 : List (Nat × Nat)} + (hdep : deployedStorage fuel c = some s0) (fn : Fn) (hshape : fnShapeOk c fn = true) + (σ : List (Nat × Nat)) (args : List Nat) (hlen : args.length = fn.params.length) + (hargs : ∀ a ∈ args, a < 2 ^ 256) (hd : Dirty fn.params args) : + Source.run fuel c { calldata := calldata fn.sel args, callvalue := 0, storage := σ } = + some (rejected σ) := by + simp only [fnShapeOk, Bool.and_eq_true, decide_eq_true_eq] at hshape + obtain ⟨hsel, hshape⟩ := hshape + split at hshape + case h_2 => simp at hshape + rename_i f hf + unfold deployedStorage at hdep + dsimp only at hdep + split at hdep + case h_2 => simp at hdep + rename_i deployed st hcons + simp only [Source.run, Source.result?, hcons, TypeCheck.CheckedContract.callCalldataAtFromWithContext?, + ABI.Contract.callCalldataAtFromWithContext?, bytes_calldata, readSelector_calldata _ hsel, hf] + rw [show ((natToBytes 4 fn.sel).map (·.toNat) ++ argBytes args).drop ABI.selectorBytes = + argBytes args by simp [ABI.selectorBytes, natToBytes_length], + decode_dirty f fn.params hshape args hlen hargs hd] + simp only [ABI.Contract.revertedCall?, ABI.Contract.encodeRevertData?, bind, Option.bind, + Option.map_some, Source.observe, rejected] + simp + +/-! ## The full scope -/ + +/-- EthLib rejects every call of a function of `fns` with a dirty argument word, from any +storage: the per-contract fact `dirty_symex` proves. -/ +def TargetDirty (code : ByteArray) (fns : List Fn) : Prop := + ∀ fn ∈ fns, ∀ (σ : List (Nat × Nat)) (args : List Nat), args.length = fn.params.length → + (∀ a ∈ args, a < 2 ^ 256) → Dirty fn.params args → + Target.run code { calldata := calldata fn.sel args, callvalue := 0, storage := σ } = + some (rejected σ) + +/-- The refinement on clean calls, the shape of every function and EthLib's rejection of +dirty calls give the refinement on every argument word. -/ +theorem refines_full {fuel : Nat} {c : TypeCheck.CheckedContract} {code : ByteArray} + {s : List (Nat × Nat)} {fns : List Fn} (hdep : deployedStorage fuel c = some s) + (hclean : Refines fuel c code (· ∈ calls fns [s])) (hshape : fns.all (fnShapeOk c) = true) + (htgt : TargetDirty code fns) : Refines fuel c code (fullScope fns s) := by + rintro _ ⟨fn, hfn, args, hlen, hargs, rfl⟩ + by_cases hd : Dirty fn.params args + · exact ⟨_, run_dirty hdep fn (List.all_eq_true.mp hshape fn hfn) s args hlen hargs hd, + htgt fn hfn s args hlen hargs hd⟩ + · refine hclean _ (mem_calls hfn hlen hargs fun i hp ha => ?_) + cases h : fn.params[i].clean args[i] + · exact absurd ⟨i, hp, ha, h⟩ hd + · rfl + +end SolidCore.Refinement.Dirty + + + + + + + + + + + + + + diff --git a/SolidCore/Refinement/Dyn.lean b/SolidCore/Refinement/Dyn.lean new file mode 100644 index 00000000..38939416 --- /dev/null +++ b/SolidCore/Refinement/Dyn.lean @@ -0,0 +1,24 @@ +import SolidCore.Refinement.Dyn.Refines + +/-! +# Dynamic ABI parameters and malformed call data + +The refinement of a corpus function with a `bytes calldata`, `T[] calldata` or +struct parameter, on call data that is not a list of words. + +* `SolidCore.Refinement.Dyn.Abi`: the parameters `DParam`, the canonical encodings + `encodings` within a bound, `Malformed` call data and the scope `dynScope`. +* `SolidCore.Refinement.Dyn.Source`: SolidCore's side, `run_malformed`: for every + function whose shape `dfnShapeOk` accepts, SolidCore's ABI decoder rejects every + malformed call data with the empty revert. +* `SolidCore.Refinement.Dyn.Evm`: the tactic `dyn_symex`, which runs solar's bytecode + on free call data (its size and every word it loads are symbols), and the lemma + `malformed_of_frame` that turns its frame result into one about `Target.run`. +* `SolidCore.Refinement.Dyn.Refines`: `refines_dyn`, which joins the canonical + encodings (checked by evaluation) and the malformed call data into one refinement + on `dynScope`. + +Each such corpus contract's `Corpus//Malformed.lean`, written by +`scripts/refinement/gen_proof.py`, proves EthLib's side with one `dyn_symex` call per +function, and `Corpus/.lean` states `refines_full` on `dynScope` for it. +-/ diff --git a/SolidCore/Refinement/Dyn/Abi.lean b/SolidCore/Refinement/Dyn/Abi.lean new file mode 100644 index 00000000..0ea3e44d --- /dev/null +++ b/SolidCore/Refinement/Dyn/Abi.lean @@ -0,0 +1,161 @@ +import SolidCore.Refinement.Evm.Calldata + +/-! +# Calls with dynamic ABI parameters and malformed call data + +`Abi.lean` describes a call as its selector followed by one clean word per +parameter. A function with dynamic parameters (`bytes calldata`, `T[] calldata`) +or a static struct takes call data of any length, so this module describes a call +as its selector followed by any bytes, and splits the call data a function can be +given into two scopes: + +* `encodings`: the canonical ABI encoding of every argument tuple up to a bound: + every byte string of length at most `n` for `bytes`, every array of clean words + of length at most `n` for `T[]`, every tuple of clean words for a struct. Each + dynamic argument's tail follows the heads in order, at the offset its head + word names. These calls are finitely many and a proof checks them by evaluation. +* `Malformed`: call data no ABI decoder accepts: shorter than the heads, or with a + dynamic argument whose offset word points past the end of the call data, or + whose length word runs its tail past the end. Every such call data, of any + length below `2 ^ 32` and with any bytes, is in scope; a proof shows both + semantics revert on it with empty output, symbolically. + +Call data that the decoders accept but that is not a canonical encoding within +the bound (another offset, trailing bytes, nonzero padding, a longer tail, dirty +words) is in neither scope. + +Words are read as CALLDATALOAD reads them, `wordAt`: 32 bytes big-endian, zero +past the end. +-/ + +namespace SolidCore.Refinement.Dyn + +open EthLib.Base EthLib.Execution.Evm SolidCore.Refinement.Abi + +/-- A parameter of a function, static or dynamic, with the bound of its encodings. -/ +inductive DParam where + /-- A word of a static ABI type. -/ + | word (p : Param) + /-- `bytes calldata`, encoded up to `bound` bytes. -/ + | bytes (bound : Nat) + /-- `T[] calldata` of a static word type `p`, encoded up to `bound` elements. -/ + | array (p : Param) (bound : Nat) + /-- A struct of static words, in the head. -/ + | struct (ps : List Param) + deriving Repr, DecidableEq + +/-- The words a parameter takes in the head. -/ +def DParam.headWords : DParam → Nat + | .struct ps => ps.length + | _ => 1 + +/-- The bytes per element of a dynamic parameter's tail, or none for a static one. -/ +def DParam.stride? : DParam → Option Nat + | .bytes _ => some 1 + | .array _ _ => some 32 + | _ => none + +/-- The words the parameters take in the head. -/ +def headWords : List DParam → Nat + | [] => 0 + | p :: ps => p.headWords + headWords ps + +/-- The word at byte `p` of `data`, as CALLDATALOAD reads it: 32 bytes big-endian, zero +past the end. -/ +def wordAt (data : ByteArray) (p : Nat) : Nat := (loadWord data p 32).toNat + +/-- Whether the dynamic argument whose head word is at byte `pos` points past the end of +`data`: its offset leaves no room for its length word, or its length runs its tail of +`stride`-byte elements past the end. -/ +def TailPastEnd (data : ByteArray) (pos stride : Nat) : Prop := + data.size < wordAt data pos + 32 ∨ + data.size < wordAt data pos + 32 + wordAt data (wordAt data pos) * stride + +/-- The byte position of the head word and the element stride of each dynamic parameter, +for parameters whose heads start at byte `pos`. -/ +def dynHeads : List DParam → Nat → List (Nat × Nat) + | [], _ => [] + | p :: ps, pos => + (match p.stride? with + | some k => [(pos, k)] + | none => []) ++ dynHeads ps (pos + 32 * p.headWords) + +/-- Call data, after the selector, that no ABI decoder of `ps` accepts: shorter than the +heads, or with a dynamic argument that points past the end. -/ +def Malformed (ps : List DParam) (data : ByteArray) : Prop := + data.size < 32 * headWords ps ∨ ∃ e ∈ dynHeads ps 0, TailPastEnd data e.1 e.2 + +/-! ## Canonical encodings -/ + +/-- Every list of length at most `n` of elements of `xs`, shortest first. -/ +def upTo {α : Type} (xs : List α) : Nat → List (List α) + | 0 => [[]] + | n + 1 => [] :: xs.flatMap fun x => (upTo xs n).map (x :: ·) + +/-- The 32 big-endian bytes of a word. -/ +def word32 (v : Nat) : List UInt8 := natToBytes 32 v + +/-- An argument's encoding: its head bytes for a static one, its tail for a dynamic one. -/ +structure Piece where + /-- Whether the bytes are a tail that the head points to. -/ + tail : Bool + /-- The bytes. -/ + bytes : List UInt8 + +/-- Every encoding of the parameter within its bound. -/ +def DParam.pieces : DParam → List Piece + | .word p => p.values.map fun v => ⟨false, word32 v⟩ + | .struct ps => (tuples ps).map fun vs => ⟨false, vs.flatMap word32⟩ + | .bytes n => (upTo ((List.range 256).map Nat.toUInt8) n).map fun bs => + ⟨true, word32 bs.length ++ bs ++ List.replicate ((32 - bs.length % 32) % 32) 0⟩ + | .array p n => (upTo p.values n).map fun vs => + ⟨true, word32 vs.length ++ vs.flatMap word32⟩ + +/-- The heads of the arguments, with each tail's offset counted from `off`, and the tails. -/ +def assemble : List Piece → Nat → List UInt8 × List UInt8 + | [], _ => ([], []) + | p :: ps, off => + if p.tail then + let r := assemble ps (off + p.bytes.length) + (word32 off ++ r.1, p.bytes ++ r.2) + else + let r := assemble ps off + (p.bytes ++ r.1, r.2) + +/-- The ABI encoding of the arguments: the heads, then the tails in order. -/ +def encode (ps : List DParam) (pieces : List Piece) : ByteArray := + let r := assemble pieces (32 * headWords ps) + ⟨(r.1 ++ r.2).toArray⟩ + +/-- Every list of one encoding per parameter. -/ +def pieceTuples : List DParam → List (List Piece) + | [] => [[]] + | p :: ps => p.pieces.flatMap fun x => (pieceTuples ps).map (x :: ·) + +/-- A function of a contract: its selector and its parameters. -/ +structure DFn where + /-- The function's selector. -/ + sel : Nat + /-- Its parameters, in order. -/ + params : List DParam + +/-- The call of the function with selector `sel` on the call data `data` after the +selector, with no value, from storage `s`. -/ +def callOn (sel : Nat) (data : ByteArray) (s : List (Nat × Nat)) : Call := + { calldata := Evm.selectorOf sel ++ data, callvalue := 0, storage := s } + +/-- Every call of a function of `fns` on the canonical encoding of an argument tuple within +the bounds, from each storage of `storages`. -/ +def encodings (fns : List DFn) (storages : List (List (Nat × Nat))) : List Call := + storages.flatMap fun s => fns.flatMap fun fn => + (pieceTuples fn.params).map fun pcs => callOn fn.sel (encode fn.params pcs) s + +/-- Every call of a function of `fns` from storage `s` with no value whose call data is a +canonical encoding within the bounds, or the selector followed by any malformed bytes +shorter than `2 ^ 32`. -/ +def dynScope (fns : List DFn) (s : List (Nat × Nat)) (call : Call) : Prop := + call ∈ encodings fns [s] ∨ + ∃ fn ∈ fns, ∃ data : ByteArray, data.size < 2 ^ 32 ∧ Malformed fn.params data ∧ + call = callOn fn.sel data s + +end SolidCore.Refinement.Dyn diff --git a/SolidCore/Refinement/Dyn/Evm.lean b/SolidCore/Refinement/Dyn/Evm.lean new file mode 100644 index 00000000..9a7440cb --- /dev/null +++ b/SolidCore/Refinement/Dyn/Evm.lean @@ -0,0 +1,225 @@ +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dyn.Abi + +/-! +# Symbolic execution of a dispatcher on malformed call data + +A per-contract theorem that solar's bytecode rejects malformed call data +(`Dyn.Malformed`) is one call of the tactic `dyn_symex` under the generic lemma +`malformed_of_frame`, which reduces `Target.run` to a frame specification: from +pc 0 with no value, 10M gas and call data `selectorOf s ++ data`, where `data` is +any malformed byte string shorter than `2 ^ 32`, the frame halts with `Reverted`. + +Unlike `dirty_symex`, the call data is not a list of words: its size and its +bytes are free. The run keeps CALLDATASIZE as `BitVec.ofNat 256 (4 + data.size)` +and every CALLDATALOAD as the word `loadWord msg.data x.toNat 32` at its offset `x`, +which EthLib reads as 32 bytes zero-padded past the end. Only the selector is +evaluated (`shr_selectorOf_append`). `tailPastEnd_iff` restates the malformed +hypothesis on those words: an offset word `o` at byte `4 + pos` of the call data, +and the length word at `o + 4`, the offset of the tail in the call data. + +At each JUMPI the tactic turns the condition, an OR of comparisons, into one +proposition (`ite_or_ite`, `ite_eq_zero`) and decides the branch, or refutes it, +with `bv_omega` from the size bound and the malformed hypothesis, or with +`bv_decide` where `bv_omega` fails. A path that reaches RETURN or STOP, or an +opcode no rule covers, is left as an unsolved goal. MSTORE at a known offset grows the +memory as in `dirty_symex`. +-/ + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Logic SolidCore.Refinement.Evm.Symex + +namespace SolidCore.Refinement.Dyn + +/-! ## The call data -/ + +/-- `SHR 224` of the first word of the call data is its selector, whatever follows it. -/ +theorem shr_selectorOf_append (s : Nat) (hs : s < 2 ^ 32) (data : ByteArray) : + bitwiseShr 224#256 (loadWord (Evm.selectorOf s ++ data) 0 32) = BitVec.ofNat 256 s := by + have h := SolidCore.Refinement.Evm.bitwiseShr_loadWord_zero (Evm.selectorOf s ++ data) 4 (by decide) (by decide) + rw [show BitVec.ofNat 256 (8 * (32 - 4)) = 224#256 from rfl] at h + rw [h, SolidCore.Refinement.Evm.bufferRead_append_of_le _ _ (by simp [Evm.size_selectorOf])] + have h4 := Evm.size_selectorOf s + have : bufferRead (Evm.selectorOf s) 0 4 = (Evm.selectorOf s).data.toList := by + rw [← h4]; exact bufferRead_zero_size _ + rw [this, Evm.bytesToNat_selectorOf s hs] + +/-- CALLDATALOAD past the selector reads the bytes after it. -/ +theorem loadWord_selectorOf_append (s : Nat) (data : ByteArray) (p : Nat) : + loadWord (Evm.selectorOf s ++ data) (4 + p) 32 = loadWord data p 32 := by + have h := Evm.bufferRead_append_add (Evm.selectorOf s) data p 32 + rw [Evm.size_selectorOf] at h + simp only [loadWord, h] + +theorem size_selectorOf_append (s : Nat) (data : ByteArray) : + (Evm.selectorOf s ++ data).size = 4 + data.size := by + simp [ByteArray.size_append, Evm.size_selectorOf] + +/-- A dynamic argument that points past the end, stated on the words the bytecode reads: +the offset word at byte `4 + pos` of the call data, and the length word at the offset plus +4, read only once the offset leaves room for it. -/ +theorem tailPastEnd_iff {s : Nat} {data cd : ByteArray} (hd : cd = Evm.selectorOf s ++ data) + (hsz : data.size < 2 ^ 32) (pos k : Nat) : + TailPastEnd data pos k ↔ + data.size < (loadWord cd (4 + pos) 32).toNat + 32 ∨ + ((loadWord cd (4 + pos) 32).toNat + 32 ≤ data.size ∧ + data.size < (loadWord cd (4 + pos) 32).toNat + 32 + + (loadWord cd (loadWord cd (4 + pos) 32 + 4#256).toNat 32).toNat * k) := by + subst hd + simp only [TailPastEnd, wordAt, loadWord_selectorOf_append] + generalize ho : loadWord data pos 32 = o + constructor + · rintro (h | h) + · exact Or.inl h + · by_cases hlt : data.size < o.toNat + 32 + · exact Or.inl hlt + · refine Or.inr ⟨by omega, ?_⟩ + have : (o + 4#256).toNat = 4 + o.toNat := by + rw [BitVec.toNat_add, BitVec.toNat_ofNat] + omega + rw [this, loadWord_selectorOf_append] + exact h + · rintro (h | ⟨h1, h2⟩) + · exact Or.inl h + · right + have : (o + 4#256).toNat = 4 + o.toNat := by + rw [BitVec.toNat_add, BitVec.toNat_ofNat] + omega + rw [this, loadWord_selectorOf_append] at h2 + exact h2 + +/-! ## Branch conditions -/ + +theorem ite_or_ite (p q : Prop) [Decidable p] [Decidable q] : + ((if p then 1#256 else 0#256) ||| (if q then 1#256 else 0#256)) = if p ∨ q then 1#256 else 0#256 := by + by_cases hp : p <;> by_cases hq : q <;> simp [hp, hq] + +theorem ite_eq_zero (p : Prop) [Decidable p] : ((if p then 1#256 else 0#256) = 0#256) ↔ ¬ p := by + by_cases hp : p <;> simp [hp] + +theorem ite_ne_zero (p : Prop) [Decidable p] : ((if p then 1#256 else 0#256) ≠ 0#256) ↔ p := by + by_cases hp : p <;> simp [hp] + +theorem ite_zero_eq_zero (p : Prop) [Decidable p] : + ((if p then 0#256 else 1#256) = 0#256) ↔ p := by + by_cases hp : p <;> simp [hp] + +theorem ite_eq_zero' (p : Prop) [Decidable p] : ((if p then 1#256 else 0#256) = (0 : U256)) ↔ ¬ p := by + by_cases hp : p <;> simp [hp] + +theorem ite_ne_zero' (p : Prop) [Decidable p] : ((if p then 1#256 else 0#256) ≠ (0 : U256)) ↔ p := by + by_cases hp : p <;> simp [hp] + +theorem ite_zero_eq_zero' (p : Prop) [Decidable p] : + ((if p then 0#256 else 1#256) = (0 : U256)) ↔ p := by + by_cases hp : p <;> simp [hp] + +/-! ## From the frame to `Target.run` -/ + +/-- The generic malformed-call-data theorem: if, for every malformed `data` shorter than +`2 ^ 32`, the frame of every message with no value and call data `selectorOf s ++ data` +reverts with empty output, then every such call shows the rejection, from any storage. -/ +theorem malformed_of_frame (code : ByteArray) (s : Nat) (ps : List DParam) + (h : ∀ data : ByteArray, data.size < 2 ^ 32 → Malformed ps data → + ∀ msg : Message .fusaka, msg.value = 0 → msg.data = Evm.selectorOf s ++ data → + ∀ st ss, Spec .fusaka (At code msg 0 [] .empty 10000000 st ss .empty) Reverted) + (σ : List (Nat × Nat)) (data : ByteArray) (hsz : data.size < 2 ^ 32) + (hm : Malformed ps data) : + Target.run code (callOn s data σ) = some (Abi.rejected σ) := + run_of_reverts code _ rfl fun st ss => h data hsz hm _ rfl rfl st ss + +/-! ## The tactic -/ + +open Lean.Parser.Tactic + +/-- Closes a goal about the words of a run: by `bv_omega` once the conditions are +propositions, or by `bv_decide`. -/ +syntax "dyn_close" ident : tactic + +macro_rules + | `(tactic| dyn_close $hf) => `(tactic| ( + (try simp only [ite_or_ite, ite_ne_zero, ite_ne_zero', ite_eq_zero, ite_eq_zero', ite_zero_eq_zero, + ite_zero_eq_zero', not_or, not_and, + not_lt, ne_eq, Decidable.not_not] at *) + first + | bv_omega + | symex_bv $hf)) + +/-- One step of a symbolic run on free call data: `symex_one` with `dyn_close` deciding the +branches. -/ +syntax "dyn_one" " [" simpLemma,* "]" " [" simpLemma,* "]" ident : tactic + +macro_rules + | `(tactic| dyn_one [$ls,*] [$ns,*] $hf) => `(tactic| ((try unfold Spec) <;> first + | (refine revert_empty (by decide) ?lt ?op + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*]) + | ((refine' Triple.seq (push0 (by decide) ?lt ?op ?gas ?room) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => evm_gas + case room => evm_room) <;> evm_tidy) + | ((refine' Triple.seq (jumpi_of_eq_zero ?lt ?op ?gas ?zero) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => evm_gas + case zero => first | assumption | decide) <;> evm_tidy) + | ((refine' Triple.seq (jumpi_taken ?lt ?op ?gas ?nz ?dest) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => evm_gas + case nz => first | assumption | decide + case dest => evm_dest [$ls,*]) <;> evm_tidy) + | ((refine' Triple.seq (jumpi_of_eq_zero ?lt ?op ?gas ?zero) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => evm_gas + case zero => dyn_close $hf) <;> evm_tidy) + | ((refine' Triple.seq (jumpi_taken ?lt ?op ?gas ?nz ?dest) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => evm_gas + case nz => dyn_close $hf + case dest => evm_dest [$ls,*]) <;> evm_tidy) + | ((refine jumpi_split ?lt ?op ?gas ?dest (fun _ => ?zero) (fun _ => ?taken) + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => evm_gas + case dest => evm_dest [$ls,*] + case zero => try (exfalso; dyn_close $hf) + case taken => try (exfalso; dyn_close $hf)) <;> evm_tidy) + | ((refine' Triple.seq (mstore ?lt ?op ?gas) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => simp only [extendMemory, memoryGasCost, wordCount, ceil32, MEMORY_PER_WORD, + WORD_BYTES, ByteArray.size_empty, size_memoryExtend, BitVec.reduceToNat, BitVec.reduceEq, + ↓reduceIte, Nat.reduceAdd, Nat.reduceDiv, Nat.reduceMul, Nat.reduceSub, Nat.reducePow, + Nat.reduceLeDiff, Nat.reduceMod, Nat.reduceLT, Nat.reduceEqDiff] <;> omega) <;> + (try simp only [extendMemory, memoryGasCost, wordCount, ceil32, MEMORY_PER_WORD, + WORD_BYTES, ByteArray.size_empty, size_memoryExtend, BitVec.reduceToNat, BitVec.reduceEq, + ↓reduceIte, Nat.reduceAdd, Nat.reduceDiv, Nat.reduceMul, Nat.reduceSub, Nat.reducePow, + Nat.reduceLeDiff, Nat.reduceMod, Nat.reduceLT, Nat.reduceEqDiff]) <;> evm_tidy) + | evm_step [$ls,*]) <;> (try symex_norm [$ns,*])) + +/-- Proves the frame hypothesis of `malformed_of_frame` for a code: every path of the code +on malformed call data reverts with empty output. `ls` are the rules that turn the code into +numbers, as for `evm_step`, and the definition of the selector. -/ +syntax "dyn_symex" " [" simpLemma,* "]" : tactic + +macro_rules + | `(tactic| dyn_symex [$ls,*]) => `(tactic| ( + intro data hsz hmal msg hv hd st ss + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + have hsel := hd ▸ shr_selectorOf_append _ (by simp only [$ls,*]; decide) data + have hsize : msg.data.size = 4 + data.size := by rw [hd, size_selectorOf_append] + simp only [Malformed, dynHeads, DParam.stride?, DParam.headWords, headWords, + List.take, List.mem_append, List.mem_cons, List.mem_nil_iff, List.nil_append, + List.append_nil, or_false, exists_eq_or_imp, exists_eq_left, Nat.mul_zero, Nat.mul_one, + List.length_cons, List.length_nil, false_and, exists_const, exists_false, + Nat.add_zero, Nat.zero_add, Nat.reduceMul, Nat.reduceAdd, + tailPastEnd_iff hd hsz] at hmal + try simp only [$ls,*] at hsel + clear hd + repeat dyn_one [$ls,*] [hsel, hsize, hv] hfork)) + +end SolidCore.Refinement.Dyn diff --git a/SolidCore/Refinement/Dyn/Refines.lean b/SolidCore/Refinement/Dyn/Refines.lean new file mode 100644 index 00000000..346ff1ab --- /dev/null +++ b/SolidCore/Refinement/Dyn/Refines.lean @@ -0,0 +1,44 @@ +import SolidCore.Refinement.Dyn.Evm +import SolidCore.Refinement.Dyn.Source + +/-! +# The refinement on dynamic parameters and malformed call data + +`refines_dyn` joins the two halves of a contract's proof on `Dyn.dynScope`: the +refinement on the canonical encodings `Dyn.encodings` (checked by evaluation, with +`native_decide`) and, for malformed call data, SolidCore's rejection +(`run_malformed`, once `native_decide` checks each function's shape) and EthLib's +(`TargetMalformed`, proved symbolically by `dyn_symex`). + +The statement is +``` +Refines fuel c code (dynScope fns s) +``` +for the deployed storage `s`: every call of every function of `fns` on a canonical +encoding within the bounds, and every call of one of them on its selector followed by +malformed bytes of any length below `2 ^ 32`. +-/ + +namespace SolidCore.Refinement.Dyn + +open SolidCore.Refinement.Abi SolidCore.Solidity + +/-- EthLib rejects every call of a function of `fns` on malformed call data shorter than +`2 ^ 32`, from any storage: the per-contract fact `dyn_symex` proves. -/ +def TargetMalformed (code : ByteArray) (fns : List DFn) : Prop := + ∀ fn ∈ fns, ∀ (σ : List (Nat × Nat)) (data : ByteArray), data.size < 2 ^ 32 → + Malformed fn.params data → Target.run code (callOn fn.sel data σ) = some (rejected σ) + +/-- The refinement on the canonical encodings, the shape of every function and EthLib's +rejection of malformed call data give the refinement on `dynScope`. -/ +theorem refines_dyn {fuel : Nat} {c : TypeCheck.CheckedContract} {code : ByteArray} + {s : List (Nat × Nat)} {fns : List DFn} (hdep : deployedStorage fuel c = some s) + (henc : Refines fuel c code (· ∈ encodings fns [s])) + (hshape : fns.all (dfnShapeOk c) = true) (htgt : TargetMalformed code fns) : + Refines fuel c code (dynScope fns s) := by + rintro _ (hc | ⟨fn, hfn, data, hsz, hm, rfl⟩) + · exact henc _ hc + · exact ⟨_, run_malformed hdep fn (List.all_eq_true.mp hshape fn hfn) s data hm, + htgt fn hfn s data hsz hm⟩ + +end SolidCore.Refinement.Dyn diff --git a/SolidCore/Refinement/Dyn/Source.lean b/SolidCore/Refinement/Dyn/Source.lean new file mode 100644 index 00000000..860c0dfe --- /dev/null +++ b/SolidCore/Refinement/Dyn/Source.lean @@ -0,0 +1,457 @@ +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Dyn.Abi + +/-! +# SolidCore rejects malformed call data + +SolidCore's ABI decoder reads the call data after the selector as a list of byte +values. For a function whose parameters are the lowering of `Dyn.DParam`s +(`dfnShapeOk`: `bytes calldata` as `Ty.bytesCalldata`, `T[] calldata` as +`Ty.dynamicArray` of a word type, a struct as `Ty.tuple` of word types, a word as in +`Dirty.paramFits`), every decoding failure is the empty revert (`decode_error`), and +the decoder accepts no call data that `Malformed` describes: + +* it first checks that the heads are present (`decodeArgsWith?`); +* a `bytes` argument reads its offset word `o`, its length word at `o`, and needs the + `o + 32 + length` bytes; an array needs `o + 32 + 32 * length` (`tail_of_ok`). + +`run_malformed` lifts it to `Source.run`: the call shows `Abi.rejected`. +-/ + +namespace SolidCore.Refinement.Dyn + +open EthLib.Base EthLib.Execution.Evm SolidCore.Refinement.Abi +open SolidCore.Solidity SolidCore.Solidity.Source + +/-! ## The shape of a function -/ + +/-- Whether SolidCore's parameter type `ty` and cleanup `c` are the lowering of `p`. -/ +def dparamFits : DParam → Source.Ty → AbiCleanup → Bool + | .word p, ty, c => Dirty.paramFits p ty c + | .bytes _, .bytesCalldata, .none => true + | .array p _, .dynamicArray ty, .dynamicArray c => Dirty.paramFits p ty c + | .struct ps, .tuple tys, .tuple cs => Dirty.fitsAll ps tys cs + | _, _, _ => false + +/-- Whether the parameter types and cleanups of a function are the lowering of `ps`. -/ +def dfitsAll : List DParam → List Source.Ty → List AbiCleanup → Bool + | p :: ps, ty :: tys, c :: cs => dparamFits p ty c && dfitsAll ps tys cs + | [], [], [] => true + | _, _, _ => false + +/-- Whether the checked contract dispatches the selector of `fn` to a function whose +parameters are the lowering of `fn`'s. -/ +def dfnShapeOk (c : TypeCheck.CheckedContract) (fn : DFn) : Bool := + decide (fn.sel < 2 ^ 32) && + match c.core.findFunctionBySelector? fn.sel with + | some f => dfitsAll fn.params (f.params.map BindingDecl.ty) f.paramAbiCleanups + | none => false + +/-! ## Reading words -/ + +/-- The call data after the selector, as SolidCore reads it. -/ +def srcBytes (data : ByteArray) : List Nat := data.data.toList.map (·.toNat) + +theorem length_srcBytes (data : ByteArray) : (srcBytes data).length = data.size := by + simp only [srcBytes, List.length_map, Array.length_toList] + rfl + +/-- SolidCore reads big-endian bytes as EthLib does, modulo `2 ^ 256`. -/ +theorem bytesToWordBE_map (l : List UInt8) : + ABI.bytesToWordBE (ABI.normalizeBytes (l.map (·.toNat))) = bytesToNat l % 2 ^ 256 := by + have hbyte : ∀ b : UInt8, normByte (Shared.External.byte b.toNat) = b.toNat := by + intro b + have := b.toNat_lt + simp [normByte, Shared.Account.byte, Shared.External.byte, Nat.mod_eq_of_lt this] + unfold ABI.bytesToWordBE ABI.normalizeBytes Shared.External.normalizeBytes + rw [List.map_map, List.foldl_map] + simp only [Function.comp_def, hbyte] + rfl + +theorem bufferRead_eq_take (data : ByteArray) (p n : Nat) (h : p + n ≤ data.size) : + bufferRead data p n = (data.data.toList.drop p).take n := by + have hs : data.data.toList.length = data.size := by + simp only [Array.length_toList]; rfl + apply List.ext_getElem + · rw [bufferRead_length, List.length_take, List.length_drop]; omega + · intro i h1 h2 + rw [bufferRead_length] at h1 + simp only [bufferRead, List.getElem_map, List.getElem_range, List.getElem_take, + List.getElem_drop, byteAt] + have : p + i < data.size := by omega + rw [dif_pos this] + rfl + +/-- A word SolidCore reads is the word CALLDATALOAD reads, and lies within the call data. -/ +theorem readWord_srcBytes {data : ByteArray} {p w : Nat} + (h : ABI.readWord? (srcBytes data) p = some w) : + p + 32 ≤ data.size ∧ w = wordAt data p := by + simp only [ABI.readWord?, ABI.readBytes?] at h + by_cases hle : ABI.wordBytes ≤ (List.drop p (srcBytes data)).length + · rw [if_pos hle] at h + simp only [Option.some.injEq] at h + subst h + have hl : p + 32 ≤ data.size := by + rw [List.length_drop, length_srcBytes] at hle; simp only [ABI.wordBytes] at hle; omega + refine ⟨hl, ?_⟩ + simp only [wordAt, loadWord, BitVec.toNat_ofNat, bufferRead_eq_take data p 32 hl] + rw [← bytesToWordBE_map] + simp only [srcBytes, List.map_take, List.map_drop, ABI.wordBytes] + · rw [if_neg hle] at h + simp at h + +theorem readBytes_some {bs : List Nat} {p n : Nat} {v : ABI.Bytes} + (h : ABI.readBytes? bs p n = some v) : n ≤ bs.length - p := by + simp only [ABI.readBytes?] at h + by_cases hle : n ≤ (List.drop p bs).length + · rw [List.length_drop] at hle; exact hle + · rw [if_neg hle] at h; simp at h + +/-! ## Decoding one argument -/ + +open ABI in +theorem types_of_fits {p : Param} {ty : Source.Ty} {c : AbiCleanup} + (h : Dirty.paramFits p ty c = true) : + ty = .uint256 ∨ ty = .int256 ∨ ty = .bool := by + unfold Dirty.paramFits at h + split at h <;> simp_all + +/-- A word argument fails to decode only with the empty revert. -/ +theorem word_error {p : Param} {ty : Source.Ty} {c : AbiCleanup} + (h : Dirty.paramFits p ty c = true) {lazy : Bool} {bs : List Nat} {idx : Nat} + {e : RevertData} (he : ABI.decodeValueAt? lazy bs idx ty = .error e) : e = .empty := by + rcases types_of_fits h with rfl | rfl | rfl <;> + simp only [ABI.decodeValueAt?, ABI.Ty.abiDecodeFuel, ABI.decodeValueAtWithFuel?, bind, + Except.bind, pure, Except.pure] at he <;> + cases hr : ABI.readWord? bs (ABI.wordBytes * idx) <;> + simp only [hr, ABI.abiArgOpt, Except.error.injEq, reduceCtorEq] at he + · exact he.symm + · exact he.symm + · exact he.symm + · split at he + · simp at he + · simpa using he.symm + +/-- A `bytes calldata` argument decodes only when its tail lies within the call data, and +fails only with the empty revert. -/ +theorem bytes_decode (data : ByteArray) (idx : Nat) : + (∀ v, ABI.decodeValueAt? true (srcBytes data) idx .bytesCalldata = .ok v → + ¬ TailPastEnd data (32 * idx) 1) ∧ + (∀ e, ABI.decodeValueAt? true (srcBytes data) idx .bytesCalldata = .error e → e = .empty) := by + simp only [ABI.decodeValueAt?, ABI.Ty.abiDecodeFuel, ABI.decodeValueAtWithFuel?] + cases h1 : ABI.readWord? (srcBytes data) (ABI.wordBytes * idx) with + | none => simp [ABI.abiArgOpt, bind, Except.bind] + | some o => + cases h2 : ABI.readWord? (srcBytes data) o with + | none => simp [h2, ABI.abiArgOpt, bind, Except.bind] + | some n => + cases h3 : ABI.readBytes? (srcBytes data) (o + ABI.wordBytes) n with + | none => simp [h2, h3, ABI.abiArgOpt, bind, Except.bind, pure, Except.pure] + | some bs => + obtain ⟨-, rfl⟩ := readWord_srcBytes h1 + obtain ⟨h5, rfl⟩ := readWord_srcBytes h2 + have h4 := readBytes_some h3 + rw [length_srcBytes] at h4 + refine ⟨fun _ _ => ?_, fun e he => by simp [h2, h3, ABI.abiArgOpt, bind, Except.bind, pure, + Except.pure] at he⟩ + simp only [TailPastEnd, ABI.wordBytes] at h4 h5 ⊢ + omega + +/-- Values decoded in a row fail only with the empty revert, when each one does. -/ +theorem seq_error {f : Nat → Except RevertData Value} {step : Option Nat} + (hf : ∀ i e, f i = .error e → e = .empty) : + ∀ n i e, ABI.decodeValueSeq? f step n i = .error e → e = .empty + | 0, i, e, h => by simp [ABI.decodeValueSeq?] at h + | n + 1, i, e, h => by + simp only [ABI.decodeValueSeq?, bind, Except.bind, pure, Except.pure] at h + cases h1 : f i with + | error e' => rw [h1] at h; simp at h; subst h; exact hf i e' h1 + | ok v => + rw [h1] at h + cases step with + | none => simp [ABI.abiArgOpt] at h; exact h.symm + | some k => + simp only [ABI.abiArgOpt] at h + cases h2 : ABI.decodeValueSeq? f (some k) n (i + k) with + | error e' => rw [h2] at h; simp at h; subst h; exact seq_error hf n _ _ h2 + | ok vs => rw [h2] at h; simp at h + +/-- A `T[] calldata` argument of a word type decodes only when its tail lies within the +call data, and fails only with the empty revert. -/ +theorem array_decode {ty : Source.Ty} (hty : ty = .uint256 ∨ ty = .int256 ∨ ty = .bool) + (data : ByteArray) (idx : Nat) : + (∀ v, ABI.decodeValueAt? true (srcBytes data) idx (.dynamicArray ty) = .ok v → + ¬ TailPastEnd data (32 * idx) 32) ∧ + (∀ e, ABI.decodeValueAt? true (srcBytes data) idx (.dynamicArray ty) = .error e → + e = .empty) := by + have hw : ABI.Ty.abiHeadWords? ty = some 1 := by + rcases hty with rfl | rfl | rfl <;> rfl + rcases hty with rfl | rfl | rfl <;> + simp only [ABI.decodeValueAt?, ABI.Ty.abiDecodeFuel, ABI.decodeValueAtWithFuel?] <;> + simp only [hw] at * <;> + cases h1 : ABI.readWord? (srcBytes data) (ABI.wordBytes * idx) <;> + simp [ABI.abiArgOpt, bind, Except.bind, pure, Except.pure] + all_goals + rename_i o + cases h2 : ABI.readWord? (srcBytes data) o with + | none => simp [h2] + | some n => + obtain ⟨-, rfl⟩ := readWord_srcBytes h1 + obtain ⟨h5, rfl⟩ := readWord_srcBytes h2 + simp only [h2] + by_cases hb : ABI.readBytes? (List.drop (wordAt data (ABI.wordBytes * idx) + ABI.wordBytes) + (srcBytes data)) 0 (wordAt data (wordAt data (ABI.wordBytes * idx)) * ABI.wordBytes) = none + · simp [hb] + · simp only [hb, ite_false] + obtain ⟨bs, hbs⟩ := Option.ne_none_iff_exists'.mp hb + have h4 := readBytes_some hbs + rw [List.length_drop, length_srcBytes] at h4 + refine ⟨fun _ _ => ?_, fun e he => ?_⟩ + · simp only [TailPastEnd, ABI.wordBytes] at h4 h5 ⊢ + omega + · split at he + · rename_i e' he' + simp only [Except.error.injEq] at he + subst he + exact seq_error (fun i e h => by split at h <;> simp at h) _ _ _ he' + · simp at he + +/-- Values of a list of types decoded in a row fail only with the empty revert, when each +one does. -/ +theorem list_error {f : Source.Ty → Nat → Except RevertData Value} + (hf : ∀ ty i e, f ty i = .error e → e = .empty) : + ∀ tys i e, ABI.decodeValueList? f tys i = .error e → e = .empty + | [], i, e, h => by simp [ABI.decodeValueList?] at h + | ty :: tys, i, e, h => by + simp only [ABI.decodeValueList?, bind, Except.bind, pure, Except.pure] at h + cases h1 : f ty i with + | error e' => rw [h1] at h; simp at h; subst h; exact hf ty i e' h1 + | ok v => + rw [h1] at h + simp only [ABI.abiArgOpt] at h + cases hw : ABI.Ty.abiHeadWords? ty with + | none => rw [hw] at h; simp at h; exact h.symm + | some k => + rw [hw] at h + simp only at h + cases h2 : ABI.decodeValueList? f tys (i + k) with + | error e' => rw [h2] at h; simp at h; subst h; exact list_error hf tys _ _ h2 + | ok vs => rw [h2] at h; simp at h + +theorem listHeadWords_of_fitsAll' : ∀ {ps : List Param} {tys : List Source.Ty} + {cs : List AbiCleanup}, Dirty.fitsAll ps tys cs = true → + ABI.Ty.listHasDynamicAbi tys = false ∧ ABI.Ty.listStaticAbiHeadWords? tys = some ps.length + | [], [], [], _ => ⟨rfl, rfl⟩ + | _ :: _, _ :: _, _ :: _, h => by + simp only [Dirty.fitsAll, Bool.and_eq_true] at h + have ih := listHeadWords_of_fitsAll' h.2 + rcases types_of_fits h.1 with rfl | rfl | rfl <;> + simp [ABI.Ty.listHasDynamicAbi, ABI.Ty.isDynamicAbi, ABI.Ty.listStaticAbiHeadWords?, + ABI.Ty.staticAbiHeadWords?, ih.1, ih.2, Nat.add_comm] + | [], _ :: _, _, h | [], [], _ :: _, h | _ :: _, [], _, h | _ :: _, _ :: _, [], h => by + simp [Dirty.fitsAll] at h + +/-- A struct argument of word types fails only with the empty revert. -/ +theorem struct_error {ps : List Param} {tys : List Source.Ty} {cs : List AbiCleanup} + (h : Dirty.fitsAll ps tys cs = true) (bs : List Nat) (idx : Nat) (e : RevertData) + (he : ABI.decodeValueAt? true bs idx (.tuple tys) = .error e) : e = .empty := by + obtain ⟨hd, hw⟩ := listHeadWords_of_fitsAll' h + have hw' : ABI.Ty.listAbiHeadWords? tys = some ps.length := by + rw [Dirty.listHeadWords_of_fitsAll h, (Dirty.length_of_fitsAll h).1] + simp only [ABI.decodeValueAt?, ABI.Ty.abiDecodeFuel, ABI.decodeValueAtWithFuel?, hd, + hw', ABI.abiArgOpt, bind, Except.bind, Bool.false_eq_true, ite_false, Bool.true_and] at he + split at he + · simp at he; exact he.symm + · split at he + · rename_i e' he' + simp only [Except.error.injEq] at he + subst he + exact list_error (fun ty i e h => by split at h <;> simp at h) _ _ _ he' + · simp at he + +theorem decodeLazy_of_fits {p : Param} {ty : Source.Ty} {c : AbiCleanup} + (h : Dirty.paramFits p ty c = true) : ABI.AbiCleanup.decodeLazy c = true := by + unfold Dirty.paramFits at h + split at h <;> first | (simp at h; done) | rfl + +/-- One argument of the shape: decoded on the calldata path, it takes its head words, it +decodes only when its tail lies within the call data, and it fails only with the empty +revert. -/ +theorem param_decode {p : DParam} {ty : Source.Ty} {c : AbiCleanup} + (h : dparamFits p ty c = true) (data : ByteArray) (idx : Nat) : + ABI.AbiCleanup.decodeLazy c = true ∧ ABI.Ty.abiHeadWords? ty = some p.headWords ∧ + (∀ v, ABI.decodeValueAt? true (srcBytes data) idx ty = .ok v → + ∀ k, p.stride? = some k → ¬ TailPastEnd data (32 * idx) k) ∧ + (∀ e, ABI.decodeValueAt? true (srcBytes data) idx ty = .error e → e = .empty) := by + unfold dparamFits at h + split at h + · rename_i q ty c + exact ⟨decodeLazy_of_fits h, Dirty.headWords_of_fits h, fun _ _ k hk => by + simp [DParam.stride?] at hk, fun e he => word_error h he⟩ + · have hb := bytes_decode data idx + refine ⟨rfl, rfl, fun v hv k hk => ?_, hb.2⟩ + simp only [DParam.stride?, Option.some.injEq] at hk + subst hk + exact hb.1 v hv + · rename_i q n ty c + have ha := array_decode (types_of_fits h) data idx + refine ⟨rfl, rfl, fun v hv k hk => ?_, ha.2⟩ + simp only [DParam.stride?, Option.some.injEq] at hk + subst hk + exact ha.1 v hv + · rename_i ps tys cs + obtain ⟨hd, hw⟩ := listHeadWords_of_fitsAll' h + refine ⟨rfl, ?_, fun _ _ k hk => by simp [DParam.stride?] at hk, + fun e he => struct_error h _ _ e he⟩ + simp [ABI.Ty.abiHeadWords?, ABI.Ty.isDynamicAbi, ABI.Ty.staticAbiHeadWords?, hd, hw, + DParam.headWords] + · simp at h + +/-! ## Decoding the argument list -/ + +theorem dfitsAll_cons {p : DParam} {ps : List DParam} {ty : Source.Ty} {tys : List Source.Ty} + {c : AbiCleanup} {cs : List AbiCleanup} (h : dfitsAll (p :: ps) (ty :: tys) (c :: cs) = true) : + dparamFits p ty c = true ∧ dfitsAll ps tys cs = true := by + simpa [dfitsAll] using h + +theorem lengths_of_dfitsAll : ∀ {ps : List DParam} {tys : List Source.Ty} + {cs : List AbiCleanup}, dfitsAll ps tys cs = true → + tys.length = ps.length ∧ cs.length = ps.length + | [], [], [], _ => ⟨rfl, rfl⟩ + | _ :: _, _ :: _, _ :: _, h => by + have := lengths_of_dfitsAll (dfitsAll_cons h).2 + simp [this.1, this.2] + | [], _ :: _, _, h | [], [], _ :: _, h | _ :: _, [], _, h | _ :: _, _ :: _, [], h => by + simp [dfitsAll] at h + +theorem listHeadWords_of_dfitsAll : ∀ {ps : List DParam} {tys : List Source.Ty} + {cs : List AbiCleanup}, dfitsAll ps tys cs = true → + ABI.Ty.listAbiHeadWords? tys = some (headWords ps) + | [], [], [], _ => rfl + | _ :: _, _ :: _, _ :: _, h => by + have h1 := (param_decode (dfitsAll_cons h).1 .empty 0).2.1 + simp [ABI.Ty.listAbiHeadWords?, h1, listHeadWords_of_dfitsAll (dfitsAll_cons h).2, headWords] + | [], _ :: _, _, h | [], [], _ :: _, h | _ :: _, [], _, h | _ :: _, _ :: _, [], h => by + simp [dfitsAll] at h + +theorem lazy_of_dfitsAll : ∀ {ps : List DParam} {tys : List Source.Ty} + {cs : List AbiCleanup}, dfitsAll ps tys cs = true → + cs.map ABI.AbiCleanup.decodeLazy = cs.map fun _ => true + | [], [], [], _ => rfl + | _ :: _, _ :: _, _ :: _, h => by + have h1 := (param_decode (dfitsAll_cons h).1 .empty 0).1 + simp [h1, lazy_of_dfitsAll (dfitsAll_cons h).2] + | [], _ :: _, _, h | [], [], _ :: _, h | _ :: _, [], _, h | _ :: _, _ :: _, [], h => by + simp [dfitsAll] at h + +/-- Under the shape, the decoder of the argument list fails only with the empty revert, and +decodes only when every dynamic argument's tail lies within the call data. -/ +theorem aux_decode (data : ByteArray) : ∀ (ps : List DParam) (tys : List Source.Ty) + (cs : List AbiCleanup) (idx : Nat), dfitsAll ps tys cs = true → + (∀ vs, ABI.decodeArgsAux? (srcBytes data) ((cs.map fun _ => true).zip tys) idx = .ok vs → + ∀ e ∈ dynHeads ps (32 * idx), ¬ TailPastEnd data e.1 e.2) ∧ + (∀ e, ABI.decodeArgsAux? (srcBytes data) ((cs.map fun _ => true).zip tys) idx = .error e → + e = .empty) + | [], [], [], _, _ => by simp [ABI.decodeArgsAux?, dynHeads] + | p :: ps, ty :: tys, c :: cs, idx, h => by + obtain ⟨h1, h2⟩ := dfitsAll_cons h + obtain ⟨-, hw, hok, herr⟩ := param_decode h1 data idx + have ih := aux_decode data ps tys cs (idx + p.headWords) h2 + simp only [List.map_cons, List.zip_cons_cons, ABI.decodeArgsAux?, bind, Except.bind, hw, + ABI.abiArgOpt, pure, Except.pure] + cases hv : ABI.decodeValueAt? true (srcBytes data) idx ty with + | error e' => simp only; exact ⟨fun _ h => by simp at h, fun e he => by + simp at he; subst he; exact herr e' hv⟩ + | ok v => + simp only + cases hr : ABI.decodeArgsAux? (srcBytes data) ((cs.map fun _ => true).zip tys) + (idx + p.headWords) with + | error e' => simp only; exact ⟨fun _ h => by simp at h, fun e he => by + simp at he; subst he; exact ih.2 e' hr⟩ + | ok vs => + simp only + refine ⟨fun _ _ e he => ?_, fun e he => by simp at he⟩ + simp only [dynHeads, List.mem_append] at he + rcases he with he | he + · split at he + · rename_i k hk + simp only [List.mem_singleton] at he + subst he + exact hok v hv k hk + · simp at he + · rw [show 32 * idx + 32 * p.headWords = 32 * (idx + p.headWords) by omega] at he + exact ih.1 vs hr e he + | [], _ :: _, _, _, h | [], [], _ :: _, _, h | _ :: _, [], _, _, h + | _ :: _, _ :: _, [], _, h => by simp [dfitsAll] at h + +/-- A function of the shape decodes every malformed call data to the empty revert. -/ +theorem decode_malformed (f : FunctionDef) (ps : List DParam) + (hfit : dfitsAll ps (f.params.map BindingDecl.ty) f.paramAbiCleanups = true) + (data : ByteArray) (hm : Malformed ps data) : + ABI.decodeFunctionArgs? f (srcBytes data) = .error .empty := by + obtain ⟨htl, hcl⟩ := lengths_of_dfitsAll hfit + have hlazy := lazy_of_dfitsAll hfit + have hz : List.map Prod.snd ((f.paramAbiCleanups.map fun _ => true).zip + (f.params.map BindingDecl.ty)) = f.params.map BindingDecl.ty := + List.map_snd_zip (by simp [htl, hcl]) + have hh := aux_decode data ps _ _ 0 hfit + unfold ABI.decodeFunctionArgs? ABI.decodeArgsWith? + simp only [htl, hcl, beq_self_eq_true, ite_true, hlazy, hz, listHeadWords_of_dfitsAll hfit, + ABI.abiArgOpt, bind, Except.bind, pure, Except.pure, length_srcBytes, ABI.wordBytes, + Nat.mul_zero] + simp only [Nat.mul_zero] at hh + rcases hm with hm | ⟨e, he, ht⟩ + · simp [hm] + · split + · rename_i err heq + split at heq + · simp at heq; rw [← heq] + · rw [hh.2 err heq] + · rename_i vs heq + split at heq + · simp at heq + · exact absurd ht (hh.1 vs heq e he) + +/-! ## The call -/ + +theorem bytes_callOn (sel : Nat) (data : ByteArray) : + (Evm.selectorOf sel ++ data).data.toList.map (·.toNat) = + (natToBytes 4 sel).map (·.toNat) ++ srcBytes data := by + simp [Evm.selectorOf, srcBytes] + +theorem readSelector_append (sel : Nat) (hsel : sel < 2 ^ 32) (rest : List Nat) : + ABI.readSelector? ((natToBytes 4 sel).map (·.toNat) ++ rest) = some sel := by + have hlen : ((natToBytes 4 sel).map (·.toNat)).length = 4 := by simp [natToBytes_length] + simp only [ABI.readSelector?, ABI.readBytes?, ABI.selectorBytes, List.drop_zero, + List.length_append, hlen] + rw [ite_eq_left (by omega), List.take_append_of_le_length (by omega), + List.take_of_length_le (by omega)] + simp only [Dirty.bytesToWordBE_natToBytes 4 sel (by simpa using hsel) (by decide)] + +/-- SolidCore's run of a call of a function of the shape, from any storage, on malformed call +data: the empty revert, which keeps the call's storage. -/ +theorem run_malformed {fuel : Nat} {c : TypeCheck.CheckedContract} {s0 : List (Nat × Nat)} + (hdep : deployedStorage fuel c = some s0) (fn : DFn) (hshape : dfnShapeOk c fn = true) + (σ : List (Nat × Nat)) (data : ByteArray) (hm : Malformed fn.params data) : + Source.run fuel c (callOn fn.sel data σ) = some (rejected σ) := by + simp only [dfnShapeOk, Bool.and_eq_true, decide_eq_true_eq] at hshape + obtain ⟨hsel, hshape⟩ := hshape + split at hshape + case h_2 => simp at hshape + rename_i f hf + unfold deployedStorage at hdep + dsimp only at hdep + split at hdep + case h_2 => simp at hdep + rename_i deployed st hcons + simp only [callOn, Source.run, Source.result?, hcons, + TypeCheck.CheckedContract.callCalldataAtFromWithContext?, + ABI.Contract.callCalldataAtFromWithContext?, bytes_callOn, readSelector_append _ hsel, hf] + rw [show ((natToBytes 4 fn.sel).map (·.toNat) ++ srcBytes data).drop ABI.selectorBytes = + srcBytes data by simp [ABI.selectorBytes, natToBytes_length], + decode_malformed f fn.params hshape data hm] + simp only [ABI.Contract.revertedCall?, ABI.Contract.encodeRevertData?, bind, Option.bind, + Option.map_some, Source.observe, rejected] + simp + +end SolidCore.Refinement.Dyn diff --git a/SolidCore/Refinement/Evm/Calldata.lean b/SolidCore/Refinement/Evm/Calldata.lean new file mode 100644 index 00000000..f5066577 --- /dev/null +++ b/SolidCore/Refinement/Evm/Calldata.lean @@ -0,0 +1,226 @@ +import SolidCore.Refinement.Evm.Lemmas +import SolidCore.Refinement.Abi + +/-! +# ABI call data for the dirty-argument proofs + +The call data of an external call with static arguments is a 4-byte selector +followed by one 32-byte word per argument. This module defines it, `cdOf`, +and the rules a symbolic run of a dispatcher needs on it: its size, the word +CALLDATALOAD reads at the offset of each argument, and the selector that +`SHR 224` of the first word gives. + +It defines `Abi.Dirty` over the interface of `Abi.lean` (`Abi.calldata`, +`Abi.Param`, `Abi.Param.clean`) and restates cleanliness on bit vectors, +`cleanBv`, so `bv_decide` and `bv_omega` read it directly; `calldata_eq_cdOf` +and `not_cleanAllBv` carry a dirty call of the interface over to `cdOf`. +-/ + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm + +namespace SolidCore.Refinement.Abi + +/-- Some argument word is not clean for its parameter. -/ +def Dirty (params : List Param) (args : List Nat) : Prop := + ∃ i, ∃ (hp : i < params.length) (ha : i < args.length), params[i].clean args[i] = false + +/-- What a rejected call shows on both sides: failure, no output, no logs and the +call's initial storage. -/ +def rejected (storage : List (Nat × Nat)) : Observable := + { success := false, output := [], logs := [], storage := slotValue storage } + +end SolidCore.Refinement.Abi + +namespace SolidCore.Refinement.Evm + +/-! ## Call data -/ + +/-- The 32-byte words of `args`, one after another. -/ +def wordsBytes : List U256 → ByteArray + | [] => .empty + | a :: rest => wordBytes a ++ wordsBytes rest + +/-- The call data of a call with selector bytes `sel` and argument words `args`. -/ +def cdOf (sel : ByteArray) (args : List U256) : ByteArray := sel ++ wordsBytes args + +/-- The four big-endian bytes of a selector. -/ +def selectorOf (s : Nat) : ByteArray := ⟨(natToBytes 4 s).toArray⟩ + +theorem size_selectorOf (s : Nat) : (selectorOf s).size = 4 := by + simp [selectorOf, ByteArray.size, natToBytes_length] + +theorem size_wordsBytes (args : List U256) : (wordsBytes args).size = 32 * args.length := by + induction args with + | nil => rfl + | cons a rest ih => + simp only [wordsBytes, ByteArray.size_append, size_wordBytes, ih, List.length_cons] + omega + +theorem size_cdOf (sel : ByteArray) (args : List U256) : + (cdOf sel args).size = sel.size + 32 * args.length := by + simp [cdOf, ByteArray.size_append, size_wordsBytes] + +/-- A read past a prefix reads the rest at the offset past it. -/ +theorem bufferRead_append_add (pre b : ByteArray) (o size : Nat) : + bufferRead (pre ++ b) (pre.size + o) size = bufferRead b o size := by + simp only [bufferRead] + apply List.map_congr_left + intro i _ + rw [byteAt_append, ite_eq_right (by omega)] + congr 1 + omega + +/-- The `i`th word of `wordsBytes args` reads back as the `i`th argument. -/ +theorem loadWord_wordsBytes (args : List U256) (i : Nat) (hi : i < args.length) : + loadWord (wordsBytes args) (32 * i) 32 = args[i] := by + induction args generalizing i with + | nil => simp at hi + | cons a rest ih => + cases i with + | zero => + simp only [wordsBytes, Nat.mul_zero, List.getElem_cons_zero] + rw [loadWord, bufferRead_append_of_le _ _ (by simp [size_wordBytes]), ← loadWord, + loadWord_wordBytes] + | succ i => + simp only [wordsBytes, List.getElem_cons_succ] + have h := bufferRead_append_add (wordBytes a) (wordsBytes rest) (32 * i) 32 + rw [size_wordBytes] at h + rw [loadWord, show 32 * (i + 1) = 32 + 32 * i by omega, h, ← loadWord] + exact ih i (by simp at hi; omega) + +/-- CALLDATALOAD at the offset of argument `i` reads argument `i`. -/ +theorem loadWord_cdOf (sel : ByteArray) (args : List U256) (i : Nat) (hi : i < args.length) : + loadWord (cdOf sel args) (sel.size + 32 * i) 32 = args[i] := by + rw [cdOf, loadWord, bufferRead_append_add, ← loadWord, loadWord_wordsBytes _ _ hi] + +/-- CALLDATALOAD at any offset `n` of an argument word, in the form `simp` uses: the side +conditions are closed numerals once `sel.size` and `n` are. -/ +theorem loadWord_cdOf_getD (sel : ByteArray) (args : List U256) (n : Nat) + (hle : sel.size ≤ n) (hmod : (n - sel.size) % 32 = 0) + (hlt : (n - sel.size) / 32 < args.length) : + loadWord (cdOf sel args) n 32 = args.getD ((n - sel.size) / 32) 0 := by + have hn : n = sel.size + 32 * ((n - sel.size) / 32) := by omega + rw [List.getD_eq_getElem?_getD, List.getElem?_eq_getElem hlt, Option.getD_some, + ← loadWord_cdOf sel args _ hlt, ← hn] + +/-- `SHR 224` of the first word of call data is its 4-byte selector. -/ +theorem shr_cdOf (sel : ByteArray) (args : List U256) (hs : sel.size = 4) : + bitwiseShr 224#256 (loadWord (cdOf sel args) 0 32) = + BitVec.ofNat 256 (bytesToNat sel.data.toList) := by + have h := bitwiseShr_loadWord_zero (cdOf sel args) 4 (by decide) (by decide) + rw [show BitVec.ofNat 256 (8 * (32 - 4)) = 224#256 from rfl] at h + rw [h, cdOf, bufferRead_append_of_le _ _ (by omega), ← hs, bufferRead_zero_size] + +theorem bytesToNat_selectorOf (s : Nat) (hs : s < 2 ^ 32) : + bytesToNat (selectorOf s).data.toList = s := by + show bytesToNat (natToBytes 4 s).toArray.toList = s + rw [List.toList_toArray] + exact EthLib.Base.bytesToNat_natToBytes_of_lt (by simpa using hs) + +/-- `SHR 224` of the first word of call data with selector `s` is `s`. -/ +theorem shr_cdOf_selectorOf (s : Nat) (args : List U256) (hs : s < 2 ^ 32) : + bitwiseShr 224#256 (loadWord (cdOf (selectorOf s) args) 0 32) = BitVec.ofNat 256 s := by + rw [shr_cdOf _ _ (size_selectorOf s), bytesToNat_selectorOf s hs] + +/-! ## Clean arguments, as bit vectors -/ + +/-- Whether `w` encodes a value of the parameter kind `p`, stated on bit vectors so that +`bv_decide` reads it. `cleanBv_iff` shows it agrees with `Abi.Param.clean`. -/ +def cleanBv : Abi.Param → U256 → Prop + | .uint bits, w => if bits < 256 then w < BitVec.ofNat 256 (2 ^ bits) else True + | .int bits, w => + if 1 ≤ bits ∧ bits ≤ 256 then + w < BitVec.ofNat 256 (2 ^ (bits - 1)) ∨ BitVec.ofNat 256 (2 ^ 256 - 2 ^ (bits - 1)) ≤ w + else Abi.Param.clean (.int bits) w.toNat = true + | .bool, w => w < 2#256 + | .enum n, w => if n < 2 ^ 256 then w < BitVec.ofNat 256 n else True + +/-- Whether every word of `ws` is clean for its parameter in `ps`, as bit vectors. -/ +def cleanAllBv : List Abi.Param → List U256 → Prop + | p :: ps, w :: ws => cleanBv p w ∧ cleanAllBv ps ws + | _, _ => True + +theorem cleanBv_iff (p : Abi.Param) (w : U256) : cleanBv p w ↔ p.clean w.toNat = true := by + have hw := w.isLt + cases p with + | uint bits => + simp only [cleanBv, Abi.Param.clean, decide_eq_true_eq] + split + · rename_i hb + have : 2 ^ bits < 2 ^ 256 := Nat.pow_lt_pow_right (by decide) hb + rw [BitVec.lt_def, BitVec.toNat_ofNat, Nat.mod_eq_of_lt this] + · rename_i hb + have : 2 ^ 256 ≤ 2 ^ bits := Nat.pow_le_pow_right (by decide) (by omega) + simp only [true_iff]; omega + | int bits => + simp only [cleanBv] + split + · rename_i hb + have h1 : 2 ^ (bits - 1) ≤ 2 ^ 255 := Nat.pow_le_pow_right (by decide) (by omega) + have h2 : (2 : Nat) ^ 255 < 2 ^ 256 := by decide + have h3 : 0 < 2 ^ (bits - 1) := Nat.two_pow_pos _ + simp only [Abi.Param.clean, Bool.or_eq_true, Bool.and_eq_true, decide_eq_true_eq, + BitVec.lt_def, BitVec.le_def, BitVec.toNat_ofNat] + rw [Nat.mod_eq_of_lt (by omega), Nat.mod_eq_of_lt (by omega)] + omega + · exact Iff.rfl + | bool => + simp only [cleanBv, Abi.Param.clean, decide_eq_true_eq, BitVec.lt_def] + rfl + | enum n => + simp only [cleanBv, Abi.Param.clean, decide_eq_true_eq] + split + · rename_i hn + rw [BitVec.lt_def, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hn] + · simp only [true_iff]; omega + +/-- The call data of `Abi.calldata` is `cdOf` on the argument words. -/ +theorem calldata_eq_cdOf (sel : Nat) (args : List Nat) (hargs : ∀ a ∈ args, a < 2 ^ 256) : + Abi.calldata sel args = cdOf (selectorOf sel) (args.map (BitVec.ofNat 256)) := by + have hw : ∀ (ws : List Nat), (∀ a ∈ ws, a < 2 ^ 256) → + (wordsBytes (ws.map (BitVec.ofNat 256))).data.toList = ws.flatMap (natToBytes 32) := by + intro ws + induction ws with + | nil => intro _; rfl + | cons a rest ih => + intro h + simp only [List.map_cons, wordsBytes, ByteArray.data_append, Array.toList_append, + List.flatMap_cons] + have bytes : (wordBytes (BitVec.ofNat 256 a)).data.toList = + natToBytes 32 (BitVec.ofNat 256 a).toNat := + EthLib.Base.U256.toList_toBeBytes _ + rw [ih (fun b hb => h b (List.mem_cons_of_mem _ hb)), bytes, BitVec.toNat_ofNat, + Nat.mod_eq_of_lt (h a List.mem_cons_self)] + apply ByteArray.ext + apply Array.ext' + simp only [Abi.calldata, cdOf, selectorOf, ByteArray.data_append, Array.toList_append, + List.toList_toArray] + rw [hw args hargs] + +/-- A dirty argument list gives argument words that are not all clean. -/ +theorem not_cleanAllBv (ps : List Abi.Param) (args : List Nat) + (hargs : ∀ a ∈ args, a < 2 ^ 256) (hd : Abi.Dirty ps args) : + ¬ cleanAllBv ps (args.map (BitVec.ofNat 256)) := by + obtain ⟨i, hp, ha, hc⟩ := hd + induction ps generalizing args i with + | nil => simp at hp + | cons p ps ih => + cases args with + | nil => simp at ha + | cons a args => + intro hcl + simp only [List.map_cons, cleanAllBv] at hcl + cases i with + | zero => + have := (cleanBv_iff p _).mp hcl.1 + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt (hargs a List.mem_cons_self)] at this + simp at hc + rw [this] at hc + exact absurd hc (by simp) + | succ i => + exact ih args (fun b hb => hargs b (List.mem_cons_of_mem _ hb)) i + (by simp at hp; omega) (by simp at ha; omega) (by simpa using hc) hcl.2 + +end SolidCore.Refinement.Evm + + diff --git a/SolidCore/Refinement/Evm/Lemmas.lean b/SolidCore/Refinement/Evm/Lemmas.lean new file mode 100644 index 00000000..648bf9e4 --- /dev/null +++ b/SolidCore/Refinement/Evm/Lemmas.lean @@ -0,0 +1,127 @@ +import EthLib.Execution.Proofs.Evm.Logic.Steps +import EthLib.Execution.Proofs.Evm.Logic.Symbolic + +/-! +# EVM lemmas for the refinement proofs + +Rules about EthLib's EVM that the bytecode proofs use and EthLib does not have +yet: PUSH0 as a Hoare triple, and how CALLDATALOAD and SHR read a selector and +an argument word out of call data. +-/ + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts + +namespace SolidCore.Refinement.Evm.Logic + +variable {fork : Fork} {code : ByteArray} {message : Message fork} {pc : Nat} {stack : List U256} + {memory : ByteArray} {gas : Nat} {state : State.TransactionState} {substate : Substate} + {returnData : ByteArray} + +/-- From Shanghai, PUSH0 pushes the word 0, for 2 gas (GA form). -/ +theorem push0GA (hfork : .shapella ≤ fork) (hlt : pc < code.size) (hbyte : code[pc] = 0x5f) + (hgas : 2 ≤ gas) (hstack : stack.length < STACK_LIMIT) : + HoareGA fork (At code message pc stack memory gas state substate returnData) + (At code message (pc + 1) (0 :: stack) memory (gas - 2) state substate returnData) := by + apply At.ruleGA hlt hbyte + (ofByte_of_decode (op := .push 0) rfl (by simpa [Op.since] using hfork)) (instruction_push 0) + (runMono_pushN 0) (noAbort_pushN 0) + rintro evm ⟨hcode, hj, hm, hpc, hst, hmem, hg, hrun, herr, hout, hs, hss, hrd⟩ + have hlen : evm.stack.val.length < STACK_LIMIT := by rw [hst]; exact hstack + rw [pushN_of_length_lt hlen] + simp only [Fin.val_zero, ↓reduceIte] + rw [show OPCODE_PUSH0 = 2 from rfl, charge_nat (by rw [hg]; exact hgas)] + refine ⟨_, rfl, hcode, hj, hm, by simp [hpc], ?_, hmem, by simp [hg], hrun, herr, hout, hs, hss, + hrd⟩ + simp [hst, pushData, bufferRead, bytesToNat] + +/-- From Shanghai, PUSH0 pushes the word 0, for 2 gas. -/ +theorem push0 (hfork : .shapella ≤ fork) (hlt : pc < code.size) (hbyte : code[pc] = 0x5f) + (hgas : 2 ≤ gas) (hstack : stack.length < STACK_LIMIT) : + Hoare fork (At code message pc stack memory gas state substate returnData) + (At code message (pc + 1) (0 :: stack) memory (gas - 2) state substate returnData) := + (push0GA hfork hlt hbyte hgas hstack).toG.toHoare + +end SolidCore.Refinement.Evm.Logic + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm +namespace SolidCore.Refinement.Evm + +/-- A read of `a + b` bytes is the read of `a` bytes followed by the read of `b` more. -/ +theorem bufferRead_add (data : ByteArray) (start a b : Nat) : + bufferRead data start (a + b) = bufferRead data start a ++ bufferRead data (start + a) b := by + simp [bufferRead, List.range_add, List.map_append, List.map_map, Function.comp_def, + Nat.add_assoc] + +/-- A read of `size` bytes past a prefix reads the suffix. -/ +theorem bufferRead_append_size (pre b : ByteArray) (size : Nat) : + bufferRead (pre ++ b) pre.size size = bufferRead b 0 size := by + simp only [bufferRead] + apply List.map_congr_left + intro i _ + rw [byteAt_append, ite_eq_right (by omega), Nat.add_sub_cancel_left, Nat.zero_add] + +/-- A read inside a prefix reads the prefix. -/ +theorem bufferRead_append_of_le (pre b : ByteArray) {start size : Nat} + (h : start + size ≤ pre.size) : + bufferRead (pre ++ b) start size = bufferRead pre start size := by + simp only [bufferRead] + apply List.map_congr_left + intro i hi + rw [byteAt_append, ite_eq_left (by simp at hi; omega)] + +/-- The 32 bytes of a word read back as the word. -/ +theorem loadWord_wordBytes (w : U256) : loadWord (wordBytes w) 0 32 = w := by + have hsize := size_wordBytes w + rw [loadWord, ← hsize, bufferRead_zero_size] + have bytes : (wordBytes w).data.toList = natToBytes 32 w.toNat := + EthLib.Base.U256.toList_toBeBytes w + have small : w.toNat < 256 ^ 32 := by + have := w.isLt + rwa [show (2 : Nat) ^ 256 = 256 ^ 32 by decide] at this + rw [bytes, EthLib.Base.bytesToNat_natToBytes_of_lt small] + apply BitVec.eq_of_toNat_eq + simp + +/-- CALLDATALOAD right after a prefix, on call data that ends with a word, reads that word. -/ +theorem loadWord_append_wordBytes (pre : ByteArray) (w : U256) : + loadWord (pre ++ wordBytes w) pre.size 32 = w := by + rw [loadWord, bufferRead_append_size, ← loadWord, loadWord_wordBytes] + +/-- SHR by `8 * (32 - k)` of the word at offset 0 keeps the first `k` bytes of call data. + +This is how a dispatcher reads its 4-byte selector. -/ +theorem bitwiseShr_loadWord_zero (data : ByteArray) (k : Nat) (hk : k ≤ 32) (hk1 : 0 < k) : + bitwiseShr (BitVec.ofNat 256 (8 * (32 - k))) (loadWord data 0 32) = + BitVec.ofNat 256 (bytesToNat (bufferRead data 0 k)) := by + have hsplit := bufferRead_add data 0 k (32 - k) + rw [show k + (32 - k) = 32 by omega] at hsplit + have hlt := bytesToNat_lt (bufferRead data 0 k) + have hlt2 := bytesToNat_lt (bufferRead data (0 + k) (32 - k)) + simp only [bufferRead_length] at hlt hlt2 + have hsh : (BitVec.ofNat 256 (8 * (32 - k))).toNat = 8 * (32 - k) := by + rw [BitVec.toNat_ofNat]; apply Nat.mod_eq_of_lt + have : 8 * (32 - k) ≤ 256 := by omega + have : 256 < 2 ^ 256 := by decide + omega + have h256 : (256 : Nat) ^ k ≤ 2 ^ 256 := by + rw [show (256 : Nat) = 2 ^ 8 by rfl, ← Nat.pow_mul] + exact Nat.pow_le_pow_right (by decide) (by omega) + have hpow : (256 : Nat) ^ (32 - k) = 2 ^ (8 * (32 - k)) := by + rw [show (256 : Nat) = 2 ^ 8 by rfl, ← Nat.pow_mul] + unfold bitwiseShr loadWord + rw [hsh] + rw [ite_eq_left (by omega), hsplit, bytesToNat_append, bufferRead_length] + apply BitVec.eq_of_toNat_eq + rw [BitVec.toNat_ushiftRight, BitVec.toNat_ofNat, BitVec.toNat_ofNat, + Nat.shiftRight_eq_div_pow, ← hpow] + have hbig : bytesToNat (bufferRead data 0 k) * 256 ^ (32 - k) + + bytesToNat (bufferRead data (0 + k) (32 - k)) < 2 ^ 256 := by + have : (256 : Nat) ^ k * 256 ^ (32 - k) = 2 ^ 256 := by + rw [← Nat.pow_add, show k + (32 - k) = 32 by omega] + have := Nat.mul_le_mul_right (256 ^ (32 - k)) (Nat.succ_le_of_lt hlt) + rw [Nat.succ_mul] at this + omega + rw [Nat.mod_eq_of_lt hbig, Nat.mod_eq_of_lt (by omega), + Nat.add_comm, Nat.add_mul_div_right _ _ (Nat.pow_pos (by decide)), Nat.div_eq_of_lt hlt2, Nat.zero_add] + +end SolidCore.Refinement.Evm diff --git a/SolidCore/Refinement/Evm/Symex.lean b/SolidCore/Refinement/Evm/Symex.lean new file mode 100644 index 00000000..eebabe00 --- /dev/null +++ b/SolidCore/Refinement/Evm/Symex.lean @@ -0,0 +1,397 @@ +import SolidCore.Refinement.Evm.Calldata +import SolidCore.Refinement.Statement +import Std.Tactic.BVDecide + +/-! +# Symbolic execution of a dispatcher on dirty call data + +A per-contract theorem that solar's bytecode rejects dirty ABI arguments is one +call of the tactic `dirty_symex` here, under the generic lemma `dirty_of_frame`. + +`dirty_of_frame` reduces the statement about `Target.run` (as +`Statement.lean` runs a call) to a frame specification: from pc 0 with no value, +10M gas and call data `cdOf (selectorOf s) ws`, where the argument words `ws` +are not all clean, the frame halts with `Reverted` (the revert error and empty +output). It goes through `processMessage_reverts`, the generic form of C1's +`processMessage_of_spec` for a frame that reverts. + +`dirty_symex [code rules]` proves that frame specification: + +1. it splits the argument list into as many words as there are parameters and + turns the dirty hypothesis into one fact about one word per case, stated on + bit vectors (`cleanBv`); +2. it steps the bytecode with EthLib's `evm_step`, and PUSH0 with `push0`, + rewriting after each step the frame's words with the call-data rules of + `Calldata.lean` (selector, argument words, size), the call value 0 and the + EVM's comparison, shift and sign-extension operations as bit-vector terms, + which `simp` evaluates when they are ground; +3. at each JUMPI it takes the branch the condition decides, by `decide` or + from the dirty fact, and otherwise splits on the condition (`jumpi_split`) + and closes the branches whose path condition the dirty fact refutes; both + go through `symex_bv`, which rewrites the condition into comparisons of + the words' values (`symex_bits`) and closes it by `bv_omega`, a + kernel-checked proof, and falls back to `bv_decide` only where that fails; +4. it steps MSTORE, evaluating the growth of a memory of known size; +5. it closes a REVERT of 0 bytes with `revert_empty`. + +A path that reaches RETURN or STOP, or an opcode no rule covers, is left as an +unsolved goal, so the theorem fails rather than claim a rejection it has not +shown. + +`bv_decide` trusts Lean's compiler through `Lean.ofReduceBool`, as +`native_decide` does, so a theorem proved without it depends on the standard +axioms only; on the corpus every branch `dirty_symex` meets closes by +`bv_omega`. +-/ + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Logic + +namespace SolidCore.Refinement.Evm.Symex + +variable {fork : Fork} + +/-! ## The postcondition and the rules the tactic adds -/ + +/-- The frame reverted with empty output. -/ +def Reverted (evm : Evm fork Nat) : Prop := evm.error = some .revert ∧ evm.output = .empty + +theorem extendMemory_size_zero (n : Nat) (start : U256) : + extendMemory n [(start, 0)] = ⟨0, 0⟩ := by + simp [extendMemory] + +/-- REVERT of 0 bytes, from any offset, reverts with empty output. -/ +theorem revert_empty (hfork : .byzantium ≤ fork) {code : ByteArray} {message : Message fork} + {pc : Nat} {start : U256} {rest : List U256} {memory : ByteArray} {gas : Nat} + {state : State.TransactionState} {substate : Substate} {returnData : ByteArray} + (hlt : pc < code.size) (hbyte : code[pc] = 0xfd) : + Spec fork (At code message pc (start :: 0 :: rest) memory gas state substate returnData) + Reverted := by + refine Spec.consequence (revert hfork hlt hbyte ?_) (fun _ h => h) ?_ + · rw [extendMemory_size_zero]; exact Nat.zero_le _ + · rintro e ⟨-, herr, hout, -⟩ + exact ⟨herr, by rw [hout]; simp [memoryReadBytes]⟩ + +/-- JUMPI on any condition: the specification holds when it holds after the fall-through +for a zero condition and after the jump for a nonzero one. -/ +theorem jumpi_split {code : ByteArray} {message : Message fork} {pc : Nat} + {destination condition : U256} {rest : List U256} {memory : ByteArray} {gas : Nat} + {state : State.TransactionState} {substate : Substate} {returnData : ByteArray} + {Q : Evm fork Nat → Prop} + (hlt : pc < code.size) (hbyte : code[pc] = 0x57) (hgas : 10 ≤ gas) + (valid : isValidJumpDest (validJumpDestinations code) destination.toNat = true) + (zero : condition = 0 → + Spec fork (At code message (pc + 1) rest memory (gas - 10) state substate returnData) Q) + (taken : condition ≠ 0 → + Spec fork (At code message destination.toNat rest memory (gas - 10) state substate + returnData) Q) : + Spec fork (At code message pc (destination :: condition :: rest) memory gas state substate + returnData) Q := by + by_cases h : condition = 0 + · exact Spec.seq (jumpi_of_eq_zero hlt hbyte hgas h) (zero h) + · exact Spec.seq (jumpi_taken hlt hbyte hgas h valid) (taken h) + +/-- LT as a bit-vector comparison. -/ +theorem lessThan_eq (a b : U256) : lessThan a b = if a < b then 1 else 0 := by + simp [lessThan, BitVec.lt_def] + +/-- GT as a bit-vector comparison. -/ +theorem greaterThan_eq (a b : U256) : greaterThan a b = if b < a then 1 else 0 := by + simp [greaterThan, BitVec.lt_def] + +/-- SIGNEXTEND by a byte index below 31 is `BitVec.signExtend` of the low bytes. -/ +theorem signextend_eq (b : Nat) (hb : b < 31) (x : U256) : + signextend (BitVec.ofNat 256 b) x = BitVec.signExtend 256 (x.setWidth (8 * (b + 1))) := by + have hbn : (BitVec.ofNat 256 b).toNat = b := by + rw [BitVec.toNat_ofNat]; exact Nat.mod_eq_of_lt (by omega) + have hk : 8 * (b + 1) ≤ 248 := by omega + have hk1 : 8 * (b + 1) - 1 + 1 = 8 * (b + 1) := by omega + have hpk : 2 ^ (8 * (b + 1)) ≤ 2 ^ 248 := Nat.pow_le_pow_right (by decide) hk + have hpk1 : 2 ^ (8 * (b + 1)) = 2 * 2 ^ (8 * (b + 1) - 1) := by + conv_lhs => rw [← hk1] + rw [Nat.pow_succ]; omega + have h248 : (2 : Nat) ^ 248 < 2 ^ 256 := by decide + have hlow : x.toNat % 2 ^ (8 * (b + 1)) < 2 ^ (8 * (b + 1)) := Nat.mod_lt _ (Nat.two_pow_pos _) + apply BitVec.eq_of_toNat_eq + rw [BitVec.toNat_signExtend, BitVec.toNat_setWidth, BitVec.toNat_setWidth, + BitVec.msb_eq_decide, BitVec.toNat_setWidth] + unfold signextend + rw [hbn, ite_eq_right (by omega)] + simp only + rw [Nat.mod_eq_of_lt (a := x.toNat % 2 ^ (8 * (b + 1))) (by omega)] + split + · rename_i h + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt (by omega)] + simp [show ¬ 2 ^ (8 * (b + 1) - 1) ≤ x.toNat % 2 ^ (8 * (b + 1)) by omega] + · rename_i h + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt (by omega)] + simp [show 2 ^ (8 * (b + 1) - 1) ≤ x.toNat % 2 ^ (8 * (b + 1)) by omega] + omega + +/-! ## Branch conditions as comparisons + +A dispatcher checks an argument word against its type by an OR of one word per +argument: `GT` against the type's maximum for an unsigned or enum word, and the +XOR of the word with its sign extension for a signed one. The rules below turn +such a condition, compared with zero, into a proposition on the words' values, +which `bv_omega` decides from the dirty fact. -/ + +theorem or_eq_zero' {w : Nat} (x y : BitVec w) : x ||| y = 0 ↔ x = 0 ∧ y = 0 := + BitVec.or_eq_zero_iff + +theorem xor_eq_zero' {w : Nat} (x y : BitVec w) : x ^^^ y = 0 ↔ x = y := + BitVec.xor_eq_zero_iff + +theorem ite_one_zero_eq_zero (p : Prop) [Decidable p] : + ((if p then 1#256 else 0#256) = 0) ↔ ¬ p := by + split <;> simp_all + +/-- A word is its sign extension from its low `k` bits, a whole number of bytes, exactly when +its value is below `2 ^ (k - 1)` or at least `2 ^ 256 - 2 ^ (k - 1)`. -/ +theorem signExtend_setWidth_eq_iff {k : Nat} (hk : 0 < k ∧ k < 256 ∧ k % 8 = 0) (a : U256) : + BitVec.signExtend 256 (a.setWidth k) = a ↔ + a.toNat < 2 ^ (k - 1) ∨ 2 ^ 256 - 2 ^ (k - 1) ≤ a.toNat := by + rw [← BitVec.toNat_inj, BitVec.toNat_signExtend, BitVec.msb_eq_decide, BitVec.toNat_setWidth, + BitVec.toNat_setWidth] + have ha := a.isLt + obtain ⟨h0, h1, h2⟩ := hk + obtain ⟨b, rfl⟩ : ∃ b, k = 8 * (b + 1) := ⟨k / 8 - 1, by omega⟩ + have hb : b < 31 := by omega + clear h0 h1 h2 + iterate 31 + rcases b with _ | b + · simp only [Nat.reduceMul, Nat.reduceAdd, Nat.reduceSub, Nat.reducePow, decide_eq_true_eq] at * + split <;> omega + omega + +/-- The value of a sign extension from the low `k` bits, as an `if` on the sign bit, which +`omega` reads once the `if` is split. -/ +theorem toNat_signExtend_setWidth {k : Nat} (hk : 0 < k ∧ k ≤ 256) (x : U256) : + (BitVec.signExtend 256 (x.setWidth k)).toNat = + if 2 ^ (k - 1) ≤ x.toNat % 2 ^ k then x.toNat % 2 ^ k + (2 ^ 256 - 2 ^ k) + else x.toNat % 2 ^ k := by + rw [BitVec.toNat_signExtend, BitVec.msb_eq_decide, BitVec.toNat_setWidth, BitVec.toNat_setWidth] + have hk2 : 2 ^ k ≤ 2 ^ 256 := Nat.pow_le_pow_right (by decide) hk.2 + have hlt : x.toNat % 2 ^ k < 2 ^ k := Nat.mod_lt _ (Nat.two_pow_pos _) + rw [Nat.mod_eq_of_lt (by omega : x.toNat % 2 ^ k < 2 ^ 256)] + by_cases h : 2 ^ (k - 1) ≤ x.toNat % 2 ^ k <;> simp [h] + +/-! ## From the frame to `Target.run` -/ + +/-- Any spec of the frame at pc 0 gives the result of the interpreter loop. -/ +theorem runFrame_of_spec {c : ByteArray} {message : Message fork} {st : State.TransactionState} + {ss : Substate} {g : Nat} {Q : Evm fork Nat → Prop} (hcode : message.code = c) + (h : Spec fork (At c message 0 [] .empty g st ss .empty) Q) {bound : Nat} + {runChild : MessageRunner fork Nat bound} + {within : GasMeter.gasHeld (startFrame message st ss g).gas ≤ bound} {result} + (hr : runFrame (step fork) (step_decreases fork) bound runChild + (startFrame message st ss g) within = result) : + ∃ after, result = .ok after ∧ after.running = false ∧ Q after := by + obtain ⟨after, h', hq⟩ := Spec.runFrame h (evm := startFrame message st ss g) + ⟨by simp [startFrame, hcode], by simp [startFrame, hcode], rfl, rfl, rfl, rfl, rfl, rfl, rfl, + rfl, rfl, rfl, rfl⟩ within (runChild := runChild) + exact ⟨after, hr ▸ h', running_runFrame h', hq⟩ + +/-- A message with no value, to code that is no precompile, whose frame reverts with empty +output from every state: `processMessage` at Fusaka returns the revert with empty output. -/ +theorem processMessage_reverts {c : ByteArray} (message : Message .fusaka) + (hcode : message.code = c) (hv : message.value = 0) + (hpre : precompileAddress .fusaka message = none) + (h : ∀ st ss, Spec .fusaka (At c message 0 [] .empty message.gas st ss .empty) Reverted) + (st : State.TransactionState) (ss : Substate) : + ∃ evm, processMessage (Meter := Nat) .fusaka message st ss = .ok evm ∧ + evm.1.error = some .revert ∧ evm.1.output = .empty := by + rw [processMessage] + have hss : startState .fusaka message st = st := by + simp [startState, show ¬ (Fork.fusaka < Fork.paris) by decide] + simp only [hss, hpre] + split + · rename_i htr; exact absurd htr.2 (by simp [hv]) + simp only [pure, Except.pure, bind, Except.bind] + split + · rename_i e hr + obtain ⟨after, h', -⟩ := runFrame_of_spec hcode (h _ _) hr + cases h' + · rename_i after hr + obtain ⟨after', h', -, herr, hout⟩ := runFrame_of_spec hcode (h _ _) hr + cases h' + refine ⟨_, rfl, ?_, ?_⟩ + · simp only [rollbackOnError]; split <;> simp [herr] + · simp only [rollbackOnError]; split <;> simp [hout] + +theorem precompileAddress_message (code : ByteArray) (c : Call) : + precompileAddress .fusaka (Target.message code c) = none := by + simp only [precompileAddress, Target.message] + decide + +/-- A call with no value whose frame reverts with empty output from every state: `Target.run` +shows the rejection, `Abi.rejected`. -/ +theorem run_of_reverts (code : ByteArray) (c : Call) (hv : c.callvalue = 0) + (h : ∀ st ss, Spec .fusaka (At code (Target.message code c) 0 [] .empty 10000000 st ss .empty) + Reverted) : + Target.run code c = some (Abi.rejected c.storage) := by + obtain ⟨evm, hr, herr, hout⟩ := processMessage_reverts (Target.message code c) rfl + (by simp [Target.message, hv]) + (precompileAddress_message code c) h (Target.preState code c) Substate.empty + simp [Target.run, hr, herr, hout, Abi.rejected] + +/-- The generic dirty-argument theorem: if, for every list of argument words that are not +all clean for `ps`, the frame of every message with no value and call data +`cdOf (selectorOf s) ws` reverts with empty output, then every dirty call of the ABI +interface shows the rejection `Abi.rejected`, from any storage. -/ +theorem dirty_of_frame (code : ByteArray) (s : Nat) (ps : List Abi.Param) + (h : ∀ ws : List U256, ws.length = ps.length → ¬ cleanAllBv ps ws → + ∀ msg : Message .fusaka, msg.value = 0 → msg.data = cdOf (selectorOf s) ws → + ∀ st ss, Spec .fusaka (At code msg 0 [] .empty 10000000 st ss .empty) Reverted) + (σ : List (Nat × Nat)) (args : List Nat) (hlen : args.length = ps.length) + (hargs : ∀ a ∈ args, a < 2 ^ 256) (hd : Abi.Dirty ps args) : + Target.run code { calldata := Abi.calldata s args, callvalue := 0, storage := σ } = + some (Abi.rejected σ) := + run_of_reverts code _ rfl fun st ss => + h (args.map (BitVec.ofNat 256)) (by simpa using hlen) (not_cleanAllBv ps args hargs hd) + _ rfl (calldata_eq_cdOf s args hargs) st ss + +/-! ## The tactic -/ + +open Lean.Parser.Tactic + +/-- Rewrites branch conditions, in the goal and the hypotheses, into comparisons of the words' +values: an OR or XOR compared with zero, a comparison's `if` compared with zero, and a sign +extension compared with its word. -/ +syntax "symex_bits" : tactic + +macro_rules + | `(tactic| symex_bits) => `(tactic| (simp only [ne_eq, BitVec.or_zero, BitVec.zero_or, + or_eq_zero', xor_eq_zero', ite_one_zero_eq_zero, signExtend_setWidth_eq_iff, Nat.reduceSub, + Nat.reducePow, Nat.reduceMod, Nat.reduceLT, _root_.and_self, true_and] at *)) + +/-- Closes a goal about the words of a run by linear arithmetic on their values, a +kernel-checked proof: `bv_omega`, after `symex_bits` when it needs it, and else the same with +every `x % n` whose `x < n` `omega` shows from the hypotheses (such as a path condition that +bounds an argument word) replaced by `x`, which spares `omega` the large moduli it cannot +eliminate. -/ +syntax "symex_omega" : tactic + +macro_rules + | `(tactic| symex_omega) => `(tactic| first + | bv_omega + | ((try symex_bits) <;> bv_omega) + | ((try symex_bits) <;> + (try simp only [toNat_signExtend_setWidth, Nat.reduceLT, Nat.reduceLeDiff, Nat.reducePow, + Nat.reduceSub, Nat.reduceMod, Nat.lt_irrefl, _root_.and_self] at *) <;> + (try simp -implicitDefEqProofs only [bitvec_to_nat] at *) <;> + (repeat (simp (disch := omega) only [Nat.mod_eq_of_lt] at *)) <;> + (repeat' split) <;> omega)) + +/-- Closes a goal about the words of a run, without the hypothesis `hf` about the fork: by +`symex_omega`, a kernel-checked proof, or else by `bv_decide` without its enum preprocessing. +That preprocessing would add an auxiliary declaration for the enum `Fork` to the environment, +which then clashes between two modules that both use the tactic. -/ +syntax "symex_bv" ident : tactic + +macro_rules + | `(tactic| symex_bv $hf) => `(tactic| (clear $hf; first + | symex_omega + | bv_decide (config := { enums := false }))) + +/-- Rewrites the words of the frame: call data, call value and the EVM's operations as +bit-vector terms, evaluated when ground. `ns` are the facts about the message. -/ +syntax "symex_norm" " [" simpLemma,* "]" : tactic + +macro_rules + | `(tactic| symex_norm [$ns,*]) => `(tactic| ( + (try simp only [$ns,*, loadWord_cdOf_getD, shr_cdOf_selectorOf, size_cdOf, size_selectorOf, + List.length_cons, List.length_nil, List.getD_cons_zero, List.getD_cons_succ, + Nat.reduceLT, Nat.reduceLeDiff, Nat.reduceAdd, Nat.reduceSub, Nat.reduceMul, Nat.reduceDiv, + Nat.reduceMod, Nat.reducePow, BitVec.reduceToNat, Nat.reduceEqDiff]) + try simp only [sub, add, mul, bitwiseOr, + bitwiseAnd, bitwiseXor, bitwiseNot, lessThan_eq, greaterThan_eq, equal, isZero, + signextend_eq, bitwiseShr, ↓reduceIte, ite_true, ite_false, BitVec.ofNat_eq_ofNat, + Nat.reduceLT, Nat.reduceGT, Nat.reduceLeDiff, Nat.reduceEqDiff, Nat.reduceAdd, Nat.reduceSub, + Nat.reduceMul, Nat.reduceDiv, Nat.reduceMod, Nat.reducePow, BitVec.reduceToNat, + BitVec.reduceOfNat, BitVec.reduceAdd, BitVec.reduceSub, BitVec.reduceMul, BitVec.reduceAnd, + BitVec.reduceOr, BitVec.reduceXOr, BitVec.reduceNot, BitVec.reduceLT, BitVec.reduceEq, + BitVec.reduceNe, BitVec.reduceHShiftRight, BitVec.reduceHShiftLeft, BitVec.reduceSetWidth, + BitVec.reduceSignExtend])) + +/-- Runs one step of a symbolic run: closes an empty REVERT, or steps one opcode, taking or +splitting a JUMPI. `ls` are the rules of the code, `ns` the facts about the message and +`hf` the hypothesis that names the fork. -/ +syntax "symex_one" " [" simpLemma,* "]" " [" simpLemma,* "]" ident : tactic + +macro_rules + | `(tactic| symex_one [$ls,*] [$ns,*] $hf) => `(tactic| ((try unfold Spec) <;> first + | (refine revert_empty (by decide) ?lt ?op + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*]) + | ((refine' Triple.seq (push0 (by decide) ?lt ?op ?gas ?room) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => evm_gas + case room => evm_room) <;> evm_tidy) + | ((refine' Triple.seq (jumpi_of_eq_zero ?lt ?op ?gas ?zero) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => evm_gas + case zero => first | assumption | decide) <;> evm_tidy) + | ((refine' Triple.seq (jumpi_taken ?lt ?op ?gas ?nz ?dest) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => evm_gas + case nz => first | assumption | decide + case dest => evm_dest [$ls,*]) <;> evm_tidy) + | ((refine' Triple.seq (jumpi_of_eq_zero ?lt ?op ?gas ?zero) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => evm_gas + case zero => symex_bv $hf) <;> evm_tidy) + | ((refine' Triple.seq (jumpi_taken ?lt ?op ?gas ?nz ?dest) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => evm_gas + case nz => symex_bv $hf + case dest => evm_dest [$ls,*]) <;> evm_tidy) + | ((refine jumpi_split ?lt ?op ?gas ?dest (fun _ => ?zero) (fun _ => ?taken) + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => evm_gas + case dest => evm_dest [$ls,*] + case zero => try (exfalso; symex_bv $hf) + case taken => try (exfalso; symex_bv $hf)) <;> evm_tidy) + | ((refine' Triple.seq (mstore ?lt ?op ?gas) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => simp only [extendMemory, memoryGasCost, wordCount, ceil32, MEMORY_PER_WORD, + WORD_BYTES, ByteArray.size_empty, size_memoryExtend, BitVec.reduceToNat, BitVec.reduceEq, + ↓reduceIte, Nat.reduceAdd, Nat.reduceDiv, Nat.reduceMul, Nat.reduceSub, Nat.reducePow, + Nat.reduceLeDiff, Nat.reduceMod, Nat.reduceLT, Nat.reduceEqDiff] <;> omega) <;> + (try simp only [extendMemory, memoryGasCost, wordCount, ceil32, MEMORY_PER_WORD, + WORD_BYTES, ByteArray.size_empty, size_memoryExtend, BitVec.reduceToNat, BitVec.reduceEq, + ↓reduceIte, Nat.reduceAdd, Nat.reduceDiv, Nat.reduceMul, Nat.reduceSub, Nat.reducePow, + Nat.reduceLeDiff, Nat.reduceMod, Nat.reduceLT, Nat.reduceEqDiff]) <;> evm_tidy) + | evm_step [$ls,*]) <;> (try symex_norm [$ns,*])) + +/-- Proves the frame hypothesis of `dirty_of_frame` for a code: every path of the code on +dirty call data reverts with empty output. `ls` are the rules that turn the code into numbers, +as for `evm_step`, and the definitions of the selectors, which are unfolded in the call data. Handles up to 6 parameters. -/ +syntax "dirty_symex" " [" simpLemma,* "]" : tactic + +macro_rules + | `(tactic| dirty_symex [$ls,*]) => `(tactic| ( + intro ws hl hdirty msg hv hd st ss + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + try simp only [$ls,*] at hd + rcases ws with _ | ⟨a1, _ | ⟨a2, _ | ⟨a3, _ | ⟨a4, _ | ⟨a5, _ | ⟨a6, _ | ⟨a7, _⟩⟩⟩⟩⟩⟩⟩ <;> + try (simp at hl; done) + all_goals + simp only [cleanAllBv, cleanBv, and_true, not_and_or, Nat.reduceLT, Nat.reduceLeDiff, + Nat.reducePow, Nat.reduceSub, Nat.reduceAdd, and_self, ite_true, ite_false, + BitVec.ofNat_eq_ofNat, Abi.Param.clean, decide_eq_true_eq] at hdirty + try rcases hdirty with hdirty | hdirty | hdirty | hdirty | hdirty | hdirty + all_goals repeat symex_one [$ls,*] [hd, hv] hfork)) + +end SolidCore.Refinement.Evm.Symex + + + + diff --git a/SolidCore/Refinement/Evm/Wide.lean b/SolidCore/Refinement/Evm/Wide.lean new file mode 100644 index 00000000..47f91287 --- /dev/null +++ b/SolidCore/Refinement/Evm/Wide.lean @@ -0,0 +1,286 @@ +import SolidCore.Refinement.Evm.Symex + +/-! +# Symbolic execution of a dispatcher to its outputs + +`Symex.lean`'s `dirty_symex` proves that a dispatcher rejects dirty call data: every +path it follows ends in an empty REVERT. A function with wide parameters (`uint256`, +`address`, `int256`, `bytes32`) has 2^256 clean argument words per parameter, so its +results must be proved symbolically too, on every path to RETURN or REVERT. + +The statement for one path is a frame specification with the postcondition +`Post X st ss`: the frame stops with the error and the output the observable `X` +shows (no error and `X.output` when `X.success`, the revert error otherwise), and with +the state and substate it started from. `X` is SolidCore's observable for the same +call, which the source side evaluates first, so the bytecode is checked against the +source directly, with no specification in between. + +* `return_post` and `revert_post` close a path at RETURN or REVERT: the output read + from memory must be `X.output`, byte for byte. +* `processMessage_post` lifts a frame specification to `processMessage` at Fusaka, as + `C1.processMessage_of_spec` does for one contract. +* `run_of_post` turns it into `Target.run code call = some X` for a call with no value + and empty storage, when `X` shows no logs and an empty storage, as a function + that writes no storage does. +* `wide_tgt [rules]` proves the frame hypothesis of `run_of_post` for one path of the + source: it steps the code with `symex_one` (whose JUMPI rule decides a branch by + `bv_decide` or splits it), deciding the branches the source's path conditions fix by + `bv_omega`, and closes RETURN and REVERT with `return_post` and `revert_post`. + +`bv_decide` trusts Lean's compiler through `Lean.ofReduceBool`, as `native_decide` does. +-/ + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Logic SolidCore.Refinement.Evm.Symex + +namespace SolidCore.Refinement.Evm.Wide + +variable {fork : Fork} + +/-- The error of a frame that shows the observable `X`. -/ +def errorOf (X : Observable) : Option EvmError := if X.success then none else some .revert + +/-- The frame stopped as `X` shows, from state `st` and substate `ss`, which it kept. -/ +def Post (X : Observable) (st : State.TransactionState) (ss : Substate) (evm : Evm fork Nat) : + Prop := + evm.error = errorOf X ∧ evm.output.toList.map (·.toNat) = X.output ∧ evm.state = st ∧ + evm.substate = ss + +/-- RETURN of the range of memory that reads as `X.output` shows `X`, when `X` succeeds. -/ +theorem return_post {X : Observable} {code : ByteArray} {message : Message fork} {pc : Nat} + {start size : U256} {rest : List U256} {memory : ByteArray} {gas : Nat} + {state : State.TransactionState} {substate : Substate} {returnData : ByteArray} + (hlt : pc < code.size) (hbyte : code[pc] = 0xf3) + (hgas : (extendMemory memory.size [(start, size)]).cost ≤ gas) (hs : X.success = true) + (hout : (memoryReadBytes (memoryExtend memory (extendMemory memory.size [(start, size)]).expandBy) + start.toNat size.toNat).toList.map (·.toNat) = X.output) : + Spec fork (At code message pc (start :: size :: rest) memory gas state substate returnData) + (Post X state substate) := + Spec.consequence (Logic.«return» hlt hbyte hgas) (fun _ h => h) + (fun _ ⟨_, herr, hout', _, hst, hss⟩ => + ⟨by rw [herr]; simp [errorOf, hs], by rw [hout']; exact hout, hst, hss⟩) + +/-- REVERT of the range of memory that reads as `X.output` shows `X`, when `X` fails. -/ +theorem revert_post {X : Observable} {code : ByteArray} {message : Message fork} {pc : Nat} + {start size : U256} {rest : List U256} {memory : ByteArray} {gas : Nat} + {state : State.TransactionState} {substate : Substate} {returnData : ByteArray} + (hfork : .byzantium ≤ fork) (hlt : pc < code.size) (hbyte : code[pc] = 0xfd) + (hgas : (extendMemory memory.size [(start, size)]).cost ≤ gas) (hs : X.success = false) + (hout : (memoryReadBytes (memoryExtend memory (extendMemory memory.size [(start, size)]).expandBy) + start.toNat size.toNat).toList.map (·.toNat) = X.output) : + Spec fork (At code message pc (start :: size :: rest) memory gas state substate returnData) + (Post X state substate) := + Spec.consequence (revert hfork hlt hbyte hgas) (fun _ h => h) + (fun _ ⟨_, herr, hout', _, hst, hss⟩ => + ⟨by rw [herr]; simp [errorOf, hs], by rw [hout']; exact hout, hst, hss⟩) + +/-- A message with no value, to code that is no precompile, whose frame stops as `X` shows +from every state: `processMessage` at Fusaka shows `X`'s error and output, keeps the +substate, and on success the state. -/ +theorem processMessage_post {c : ByteArray} (message : Message .fusaka) + (hcode : message.code = c) (hv : message.value = 0) + (hpre : precompileAddress .fusaka message = none) (X : Observable) + (h : ∀ st ss, Spec .fusaka (At c message 0 [] .empty message.gas st ss .empty) (Post X st ss)) + (st : State.TransactionState) (ss : Substate) : + ∃ evm, processMessage (Meter := Nat) .fusaka message st ss = .ok evm ∧ + evm.1.error = errorOf X ∧ evm.1.output.toList.map (·.toNat) = X.output ∧ + evm.1.substate = ss ∧ (X.success = true → evm.1.state = st) := by + rw [processMessage] + have hss : startState .fusaka message st = st := by + simp [startState, show ¬ (Fork.fusaka < Fork.paris) by decide] + simp only [hss, hpre] + split + · rename_i htr; exact absurd htr.2 (by simp [hv]) + simp only [pure, Except.pure, bind, Except.bind] + split + · rename_i e hr + obtain ⟨after, h', -⟩ := runFrame_of_spec hcode (h _ _) hr + cases h' + · rename_i after hr + obtain ⟨after', h', -, herr, hout, hst, hsub⟩ := runFrame_of_spec hcode (h _ _) hr + cases h' + refine ⟨_, rfl, ?_, ?_, ?_, ?_⟩ + · simp only [rollbackOnError]; split <;> simp [herr] + · simp only [rollbackOnError]; split <;> exact hout + · simp only [rollbackOnError]; split <;> simp [hsub, hv] + · intro hX + have hE : errorOf X = none := by simp [errorOf, hX] + simp only [rollbackOnError, herr, hE, Option.isSome_none, Bool.false_eq_true, ↓reduceIte] + exact hst + +open EthLib.Execution.State in +theorem getStorage_preState_nil (code : ByteArray) (c : Call) (hst : c.storage = []) (k : Nat) : + (Target.preState code c).getStorage (Target.address selfAddress) (Target.storageKey k) = 0 := by + simp [Target.preState, hst, State.TransactionState.getStorage, State.TransactionState.ofBlock, + StorageMap.slot, State.getStorage] + +/-- The call with selector `s`, argument words `ws`, no value and empty storage. -/ +def callOf (s : Nat) (ws : List U256) : Call := + { calldata := Abi.calldata s (ws.map BitVec.toNat), callvalue := 0, storage := [] } + +/-- The frame of every message with no value and call data `cdOf (selectorOf s) ws` stops as +`X` shows: `Target.run` of the call with argument words `ws`, no value and empty storage is +`X`, when `X` shows no logs and an empty storage. -/ +theorem run_of_post (code : ByteArray) (s : Nat) (ws : List U256) (X : Observable) + (hlogs : X.logs = []) (hstore : ∀ slot, X.storage slot = 0) + (h : ∀ msg : Message .fusaka, msg.value = 0 → msg.data = cdOf (selectorOf s) ws → + ∀ st ss, Spec .fusaka (At code msg 0 [] .empty 10000000 st ss .empty) (Post X st ss)) : + Target.run code (callOf s ws) = some X := by + have hd : Abi.calldata s (ws.map BitVec.toNat) = cdOf (selectorOf s) ws := by + rw [calldata_eq_cdOf s _ (by simpa using fun a _ => a.isLt)] + simp [List.map_map, Function.comp_def] + let c := callOf s ws + obtain ⟨evm, hr, herr, hout, hsub, hst⟩ := processMessage_post (Target.message code c) rfl rfl + (precompileAddress_message code c) X + (fun st ss => h _ rfl (by simp [Target.message, c, callOf, hd]) st ss) (Target.preState code c) + Substate.empty + show Target.run code c = some X + simp only [Target.run, hr] + have hsucc : evm.1.error.isNone = X.success := by + rw [herr]; cases hX : X.success <;> simp [errorOf, hX] + congr 1 + cases X with + | mk success output logs storage => + simp only at hsucc hout hlogs hstore hst ⊢ + subst hlogs + rw [Observable.mk.injEq] + refine ⟨hsucc, hout, by simp [hsub, Substate.empty], ?_⟩ + funext slot + rw [hstore slot, hsucc] + cases hs : success + · simp [slotValue, c, callOf] + · simp only [ite_true] + rw [hst hs, getStorage_preState_nil code c (by simp [c, callOf])] + rfl + +/-- A read of the 32 bytes of a word is the word. -/ +theorem memoryReadBytes_wordBytes (v : U256) : memoryReadBytes (wordBytes v) 0 32 = wordBytes v := by + have := memoryReadBytes_whole (memory := wordBytes v) + rwa [size_wordBytes] at this + +/-- The bytes of a word, as a list, are its 32 big-endian bytes. -/ +theorem toList_wordBytes (v : U256) : + (wordBytes v).toList.map (·.toNat) = (natToBytes 32 v.toNat).map (·.toNat) := by + have : (wordBytes v).data.toList = natToBytes 32 v.toNat := EthLib.Base.U256.toList_toBeBytes v + simp [this] + +/-- A word written just past the end of a memory, into the 32 bytes it grew by, appends it. -/ +theorem memoryWrite_extend_word {m : ByteArray} {n : Nat} (v : U256) (h : m.size = n) : + memoryWrite (memoryExtend m 32) n (wordBytes v) = m ++ wordBytes v := by + subst h + have := memoryWrite_extend_end (memory := m) (value := wordBytes v) + rwa [size_wordBytes] at this + +/-- A read of a whole memory, of a size given by a hypothesis, is the memory. -/ +theorem memoryReadBytes_whole_of {m : ByteArray} {n : Nat} (h : m.size = n) : + memoryReadBytes m 0 n = m := by + subst h; exact memoryReadBytes_whole + +/-- The bytes of two byte arrays one after the other. -/ +theorem toList_append_map (a b : ByteArray) (f : UInt8 → Nat) : + (a ++ b).toList.map f = a.toList.map f ++ b.toList.map f := by + simp + +/-! ## The tactic -/ + +open Lean.Parser.Tactic + +/-- The rules that evaluate memory and its growth on the way to RETURN or REVERT: the price of +growth, the size of memory after a write that fits, and a write of a whole word-sized memory. -/ +syntax "wide_mem" : tactic + +macro_rules + | `(tactic| wide_mem) => `(tactic| (simp only [extendMemory, memoryGasCost, wordCount, ceil32, + MEMORY_PER_WORD, WORD_BYTES, ByteArray.size_empty, size_memoryExtend, size_wordBytes, + size_memoryWrite, memoryWrite_whole, memoryReadBytes_wordBytes, BitVec.reduceToNat, + BitVec.reduceEq, ↓reduceIte, Nat.reduceAdd, Nat.reduceDiv, Nat.reduceMul, Nat.reduceSub, + Nat.reducePow, Nat.reduceLeDiff, Nat.reduceMod, Nat.reduceLT, Nat.reduceEqDiff, + memoryExtend_zero, Nat.zero_add, Nat.add_zero, ByteArray.size_append, memoryWrite_extend_word, + memoryReadBytes_whole_of])) + +/-- Proves that the output a RETURN or REVERT reads from memory is the observable's. -/ +syntax "wide_out" : tactic + +macro_rules + | `(tactic| wide_out) => `(tactic| ((try wide_mem) <;> first + | rfl + | (simp only [Source.observe]; decide +kernel) + | (simp only [toList_wordBytes, Source.observe, BitVec.toNat_add, BitVec.toNat_xor, + BitVec.toNat_and, BitVec.toNat_or, BitVec.toNat_ofNat, BitVec.reduceToNat, Nat.reducePow, + Nat.reduceMod]; done) + | (simp [*, toList_wordBytes, Source.observe, BitVec.toNat_add, BitVec.toNat_sub, + BitVec.toNat_mul, BitVec.toNat_xor, BitVec.lt_def]; done) + | (simp only [toList_wordBytes, Source.observe] + congr 2 + (repeat' split) <;> simp_all [BitVec.toNat_add, BitVec.toNat_sub, BitVec.lt_def] <;> + bv_omega) + | (simp only [toList_wordBytes, Source.observe] + congr 2 + (repeat' split) <;> symex_omega) + | (simp only [toList_append_map, toList_wordBytes, Source.observe, List.append_assoc] + repeat' (first + | refine congrArg₂ (· ++ ·) ?_ ?_ + | refine congrArg (List.map _) ?_ + | refine congrArg (natToBytes 32) ?_) + all_goals first | rfl | ((repeat' split) <;> symex_omega)))) + +/-- Decides the condition of a JUMPI from the path conditions in context, which are facts about +the values of the argument words: it splits the `if`s of the condition and closes each case by +evaluation or by `bv_omega`. -/ +syntax "wide_dec" : tactic + +macro_rules + | `(tactic| wide_dec) => `(tactic| first + | decide + | assumption + | ((try simp only [BitVec.zero_or, BitVec.or_zero, BitVec.zero_and, BitVec.and_zero]) <;> + (repeat' split) <;> first | rfl | decide | (exfalso; bv_omega) | bv_omega)) + +/-- Steps one opcode of a path to its outputs: RETURN and REVERT close the path against the +observable of the postcondition, every other opcode goes to `symex_one`. -/ +syntax "wide_one" " [" simpLemma,* "]" " [" simpLemma,* "]" ident : tactic + +macro_rules + | `(tactic| wide_one [$ls,*] [$ns,*] $hf) => `(tactic| ((try unfold Spec) <;> first + | (refine return_post ?lt ?op ?gas ?succ ?out + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => (try wide_mem) <;> first | decide | omega | decide +kernel + case succ => first | rfl | simp [Source.observe] + case out => wide_out) + | (refine revert_post (by decide) ?lt ?op ?gas ?succ ?out + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => (try wide_mem) <;> first | decide | omega | decide +kernel + case succ => first | rfl | simp [Source.observe] + case out => wide_out) + | ((refine' Triple.seq (mstore ?lt ?op ?gas) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => wide_mem <;> omega) <;> (try wide_mem) <;> evm_tidy) + | ((refine' Triple.seq (jumpi_of_eq_zero ?lt ?op ?gas ?zero) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => evm_gas + case zero => wide_dec) <;> evm_tidy) + | ((refine' Triple.seq (jumpi_taken ?lt ?op ?gas ?nz ?dest) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => evm_gas + case nz => wide_dec + case dest => evm_dest [$ls,*]) <;> evm_tidy) + | symex_one [$ls,*] [$ns,*] $hf)) + +/-- Proves the frame hypothesis of `run_of_post` on one path of the source: every path of the +code that the hypotheses in context allow stops as the observable says. `ls` are the rules of +the code, as for `dirty_symex`. -/ +syntax "wide_tgt" " [" simpLemma,* "]" : tactic + +macro_rules + | `(tactic| wide_tgt [$ls,*]) => `(tactic| ( + intro msg hv hd st ss + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + try simp only [$ls,*] at hd + repeat wide_one [$ls,*] [hd, hv] hfork)) + +end SolidCore.Refinement.Evm.Wide diff --git a/SolidCore/Refinement/Evm/WideStorage.lean b/SolidCore/Refinement/Evm/WideStorage.lean new file mode 100644 index 00000000..07c17feb --- /dev/null +++ b/SolidCore/Refinement/Evm/WideStorage.lean @@ -0,0 +1,690 @@ +import SolidCore.Refinement.Evm.Wide +import SolidCore.Refinement.Check + +/-! +# Symbolic execution of a function that writes storage + +`Evm.Wide`'s `Post` asks a frame to keep the state it started from, so it covers +functions that only compute. A function that writes storage changes the state: SSTORE +records the write in the transaction state and the access and refund in the substate. +This module states what such a call shows and steps SSTORE and STOP. + +* `PostS X ss`: the frame stops with `X`'s error and output, its logs are those of `ss`, + and, when `X` succeeds, every slot of the callee's storage holds `X.storage`'s word. +* `run_of_postS` turns a frame specification from `Target.preState` into + `Target.run code call = some X`, as `run_of_post` does for a frame that keeps its state. +* `sstoreCost_le` bounds the price of SSTORE at Fusaka, and `setStorage_ok` gives the + state a write to an account that exists leaves, `writeOf`. +* `getStorage_writeOf` reads the storage after one write from the empty storage of the + call, which `stop_postS` compares with SolidCore's storage slot by slot. +* `getStorage_preState` reads the callee's storage before the call as the call's, and + `run_of_post_at` is `run_of_post` from any storage, for a frame that keeps its state. +* `wide_tgt_s [rules]` is `wide_tgt` with SSTORE and STOP: it proves the frame hypothesis + of `run_of_postS` for a function that writes one slot and stops. + +A contract whose constructor leaves storage is called from it, `callAt sel ws σ`: + +* `run_of_postS_at` is `run_of_postS` for such a call, whose failure keeps the words of `σ`; +* `getStorage_preState_ofNat` reads a slot of the callee's storage before the call as the + word `slotValue σ`, and `getStorage_writeOf_of` the storage after a write to any state; +* `sload_then` and `sstore_then` step SLOAD and SSTORE, each at a price bounded by its most + expensive case, so that the rest of a path may spend the gas left; +* `wide_tgt_at [rules]` is `wide_tgt_s` with SLOAD, for such a call. Where evaluation and + `bv_omega` leave a word to compare that depends on bit operations of an argument word whose + path condition bounds it below `2 ^ 8`, `word_decide` evaluates it on every such word in the + kernel. +-/ + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open EthLib.Execution.State +open SolidCore.Refinement.Evm.Logic SolidCore.Refinement.Evm.Symex + +namespace SolidCore.Refinement.Evm.Wide + +variable {fork : Fork} + +/-- The frame stopped as `X` shows, with the logs of `ss`, and on success with `X`'s storage at +the callee. -/ +def PostS (X : Observable) (ss : Substate) (evm : Evm fork Nat) : Prop := + evm.error = errorOf X ∧ evm.output.toList.map (·.toNat) = X.output ∧ + evm.substate.logs = ss.logs ∧ + (X.success = true → ∀ slot, (evm.state.getStorage (Target.address selfAddress) + (Target.storageKey slot)).toNat = X.storage slot) + +/-- `processMessage` at Fusaka of a message with no value, to code that is no precompile, whose +frame from `st` and `ss` stops as `PostS X ss` says. -/ +theorem processMessage_postS {c : ByteArray} (message : Message .fusaka) + (hcode : message.code = c) (hv : message.value = 0) + (hpre : precompileAddress .fusaka message = none) (X : Observable) + (st : State.TransactionState) (ss : Substate) + (h : Spec .fusaka (At c message 0 [] .empty message.gas st ss .empty) (PostS X ss)) : + ∃ evm, processMessage (Meter := Nat) .fusaka message st ss = .ok evm ∧ + evm.1.error = errorOf X ∧ evm.1.output.toList.map (·.toNat) = X.output ∧ + (X.success = true → evm.1.substate.logs = ss.logs ∧ ∀ slot, + (evm.1.state.getStorage (Target.address selfAddress) (Target.storageKey slot)).toNat = + X.storage slot) := by + rw [processMessage] + have hss : startState .fusaka message st = st := by + simp [startState, show ¬ (Fork.fusaka < Fork.paris) by decide] + simp only [hss, hpre] + split + · rename_i htr; exact absurd htr.2 (by simp [hv]) + simp only [pure, Except.pure, bind, Except.bind] + split + · rename_i e hr + simp only [hv, ne_eq, not_true_eq_false, and_false, ite_false] at hr + obtain ⟨after, h', -⟩ := runFrame_of_spec hcode h hr + cases h' + · rename_i after hr + simp only [hv, ne_eq, not_true_eq_false, and_false, ite_false] at hr + obtain ⟨after', h', -, herr, hout, hlogs, hst⟩ := runFrame_of_spec hcode h hr + cases h' + refine ⟨_, rfl, ?_, ?_, ?_⟩ + · simp only [rollbackOnError]; split <;> simp [herr] + · simp only [rollbackOnError]; split <;> exact hout + · intro hX + have hE : errorOf X = none := by simp [errorOf, hX] + simp only [rollbackOnError, herr, hE, Option.isSome_none, Bool.false_eq_true, ↓reduceIte] + exact ⟨hlogs, hst hX⟩ + +/-- The frame of every message of the call, from the call's state before it, stops as `PostS X` +says: `Target.run` of the call is `X`, when `X` shows no logs and keeps the empty storage when it +fails. -/ +theorem run_of_postS (code : ByteArray) (s : Nat) (ws : List U256) (X : Observable) + (hlogs : X.logs = []) (hfail : X.success = false → ∀ slot, X.storage slot = 0) + (h : ∀ msg : Message .fusaka, msg.value = 0 → msg.data = cdOf (selectorOf s) ws → + msg.isStatic = false → msg.currentTarget = Target.address selfAddress → + Spec .fusaka (At code msg 0 [] .empty 10000000 (Target.preState code (callOf s ws)) + Substate.empty .empty) (PostS X Substate.empty)) : + Target.run code (callOf s ws) = some X := by + have hd : Abi.calldata s (ws.map BitVec.toNat) = cdOf (selectorOf s) ws := by + rw [calldata_eq_cdOf s _ (by simpa using fun a _ => a.isLt)] + simp [List.map_map, Function.comp_def] + let c := callOf s ws + obtain ⟨evm, hr, herr, hout, hst⟩ := processMessage_postS (Target.message code c) rfl rfl + (precompileAddress_message code c) X (Target.preState code c) Substate.empty + (h _ rfl (by simp [Target.message, c, callOf, hd]) rfl rfl) + show Target.run code c = some X + simp only [Target.run, hr] + have hsucc : evm.1.error.isNone = X.success := by + rw [herr]; cases hX : X.success <;> simp [errorOf, hX] + congr 1 + cases X with + | mk success output logs storage => + simp only at hsucc hout hlogs hfail hst ⊢ + subst hlogs + rw [Observable.mk.injEq] + refine ⟨hsucc, hout, ?_, ?_⟩ + · rw [hsucc] + cases hs : success + · rfl + · simp [(hst hs).1, Substate.empty] + · funext slot + rw [hsucc] + cases hs : success + · simp [slotValue, c, callOf, hfail hs slot] + · simp only [ite_true] + exact (hst hs).2 slot + +/-- SSTORE at Fusaka costs at most a cold access and a new slot. -/ +theorem sstoreCost_le (o c n : U256) (cold : Bool) : sstoreCost .fusaka o c n cold ≤ 22100 := by + unfold sstoreCost sstoreResetCost sstoreReadCost + simp only [show ¬ (Fork.fusaka ≥ Fork.glamsterdam) by decide, show Fork.fusaka ≥ Fork.istanbul by decide, + show Fork.fusaka ≥ Fork.berlin by decide, ite_true, ite_false] + simp only [COLD_STORAGE_ACCESS, STORAGE_SET, COLD_STORAGE_WRITE, WARM_ACCESS] + split <;> split <;> (try split) <;> omega + +/-- The state a write of `v` at key `k` of an account that exists leaves. -/ +def writeOf (tx : TransactionState) (a : Address) (k : Bytes32) (v : U256) : TransactionState := + let tx := tx.recordAccountRead a + { tx with storageWrites := tx.storageWrites.insert a ((tx.storageWrites.getD a ∅).insert k v) } + +theorem setStorage_ok {tx : TransactionState} {a : Address} (k : Bytes32) (v : U256) + (h : tx.getAccountOptional a ≠ none) : tx.setStorage a k v = .ok (writeOf tx a k v) := by + unfold TransactionState.setStorage + simp [h, writeOf] + +theorem account_preState (code : ByteArray) (c : Call) : + (Target.preState code c).getAccountOptional (Target.address selfAddress) ≠ none := by + simp only [Target.preState, TransactionState.getAccountOptional, TransactionState.ofBlock, + State.getAccountOptional] + rw [Std.ExtTreeMap.getElem?_insert, ite_eq_right (by decide +kernel), Std.ExtTreeMap.getElem?_insert, + ite_eq_left (by decide +kernel)] + simp + +/-- The storage after one write to the account of the call, from the empty storage of a call +with no initial storage: the written word at its key, zero elsewhere. -/ +theorem getStorage_writeOf (code : ByteArray) (c : Call) (hst : c.storage = []) (a : Address) + (k : Bytes32) (v : U256) (a' : Address) (k' : Bytes32) : + (writeOf ((Target.preState code c).recordStorageRead a k) a k v).getStorage a' k' = + if a' = a ∧ k' = k then v else 0 := by + simp only [writeOf, TransactionState.getStorage, TransactionState.recordAccountRead, + TransactionState.recordStorageRead, Target.preState, hst, List.foldl_nil, + TransactionState.ofBlock, StorageMap.slot] + by_cases ha : a' = a + · subst ha + by_cases hk : k' = k + · subst hk; simp + · simp [hk, Std.ExtTreeMap.getElem?_insert, State.getStorage, StorageMap.slot] + simp only [show (k = k') = False from eq_false (fun h => hk h.symm), ite_false] + by_cases h : Target.address selfAddress = a' <;> simp [h] + · simp [ha, Std.ExtTreeMap.getElem?_insert, State.getStorage, StorageMap.slot] + simp only [show (a = a') = False from eq_false (fun h => ha h.symm), ite_false, + Option.bind_none] + by_cases h : Target.address selfAddress = a' <;> simp [h] + +/-- The storage key of a slot is the key of a word when the slot is the word modulo 2^256. -/ +theorem storageKey_eq_toBeBytes (slot : Nat) (key : U256) : + Target.storageKey slot = U256.toBeBytes key ↔ slot % 2 ^ 256 = key.toNat := by + rw [SolidCore.Refinement.storageKey_mod] + constructor + · intro h + have := congrArg (fun v : Bytes32 => bytesToNat v.toList) h + simp only [SolidCore.Refinement.toList_storageKey, EthLib.Base.U256.toList_toBeBytes, + bytesToNat_natToBytes] at this + have hk := key.isLt + simp [SolidCore.Refinement.wordSize] at this + omega + · intro h + apply Vector.toList_inj.mp + rw [SolidCore.Refinement.toList_storageKey, EthLib.Base.U256.toList_toBeBytes] + exact congrArg _ h + +/-- STOP shows `X` when `X` succeeds with no output, the frame's logs are those of `ss`, and +its storage is `X`'s. -/ +theorem stop_postS {X : Observable} {ss : Substate} {code : ByteArray} {message : Message fork} + {pc : Nat} {stack : List U256} {memory : ByteArray} {gas : Nat} + {state : State.TransactionState} {substate : Substate} {returnData : ByteArray} + (hlt : pc < code.size) (hbyte : code[pc] = 0x00) (hs : X.success = true) (hout : X.output = []) + (hlogs : substate.logs = ss.logs) + (hstore : ∀ slot, (state.getStorage (Target.address selfAddress) + (Target.storageKey slot)).toNat = X.storage slot) : + Spec fork (At code message pc stack memory gas state substate returnData) (PostS X ss) := + Spec.consequence (stop hlt hbyte) (fun _ h => h) + (fun _ ⟨_, herr, hout', _, hst, hss⟩ => + ⟨by rw [herr]; simp [errorOf, hs], by rw [hout', hout]; decide +kernel, by rw [hss, hlogs], + fun _ slot => by rw [hst]; exact hstore slot⟩) + +/-- RETURN shows §X§ when §X§ succeeds with the bytes it reads, the logs are §ss§'s and the +storage is §X§'s. -/ +theorem return_postS {X : Observable} {ss : Substate} {code : ByteArray} {message : Message fork} + {pc : Nat} {start size : U256} {rest : List U256} {memory : ByteArray} {gas : Nat} + {state : State.TransactionState} {substate : Substate} {returnData : ByteArray} + (hlt : pc < code.size) (hbyte : code[pc] = 0xf3) + (hgas : (extendMemory memory.size [(start, size)]).cost ≤ gas) (hs : X.success = true) + (hout : (memoryReadBytes (memoryExtend memory (extendMemory memory.size [(start, size)]).expandBy) + start.toNat size.toNat).toList.map (·.toNat) = X.output) + (hlogs : substate.logs = ss.logs) + (hstore : ∀ slot, (state.getStorage (Target.address selfAddress) + (Target.storageKey slot)).toNat = X.storage slot) : + Spec fork (At code message pc (start :: size :: rest) memory gas state substate returnData) + (PostS X ss) := + Spec.consequence (Logic.«return» hlt hbyte hgas) (fun _ h => h) + (fun _ ⟨_, herr, hout', _, hst, hss⟩ => + ⟨by rw [herr]; simp [errorOf, hs], by rw [hout']; exact hout, by rw [hss, hlogs], + fun _ slot => by rw [hst]; exact hstore slot⟩) + +/-- REVERT shows §X§ when §X§ fails with the bytes it reads and the logs are §ss§'s. -/ +theorem revert_postS {X : Observable} {ss : Substate} {code : ByteArray} {message : Message fork} + {pc : Nat} {start size : U256} {rest : List U256} {memory : ByteArray} {gas : Nat} + {state : State.TransactionState} {substate : Substate} {returnData : ByteArray} + (hfork : .byzantium ≤ fork) (hlt : pc < code.size) (hbyte : code[pc] = 0xfd) + (hgas : (extendMemory memory.size [(start, size)]).cost ≤ gas) (hs : X.success = false) + (hout : (memoryReadBytes (memoryExtend memory (extendMemory memory.size [(start, size)]).expandBy) + start.toNat size.toNat).toList.map (·.toNat) = X.output) + (hlogs : substate.logs = ss.logs) : + Spec fork (At code message pc (start :: size :: rest) memory gas state substate returnData) + (PostS X ss) := + Spec.consequence (revert hfork hlt hbyte hgas) (fun _ h => h) + (fun _ ⟨_, herr, hout', _, _, hss⟩ => + ⟨by rw [herr]; simp [errorOf, hs], by rw [hout']; exact hout, by rw [hss, hlogs], + fun h => by rw [hs] at h; cases h⟩) + +theorem hashMap_getElem?_of_isEmpty {m : Std.HashMap Nat Nat} (h : m.isEmpty = true) (k : Nat) : + m[k]? = none := + Std.HashMap.getElem?_eq_none (Std.HashMap.isEmpty_iff_forall_not_mem.mp h _) + +/-! ## Storage before the call + +The callee's storage before a call is the call's (`getStorage_preState`), and +`run_of_post_at` is `run_of_post` from it. -/ + + +/-- Two slots have the same storage key exactly when they agree modulo 2^256. -/ +theorem storageKey_eq_iff (a b : Nat) : + Target.storageKey a = Target.storageKey b ↔ a % 2 ^ 256 = b % 2 ^ 256 := by + constructor + · intro h + have := congrArg (fun v : Bytes32 => bytesToNat v.toList) h + simpa [SolidCore.Refinement.toList_storageKey, bytesToNat_natToBytes] using this + · intro h + rw [SolidCore.Refinement.storageKey_mod a, SolidCore.Refinement.storageKey_mod b] + simp only [SolidCore.Refinement.wordSize, h] + +/-- A key of a storage tree after the entries `σ` are written over it reads as `slotValue`'s +fold of `σ` from the tree's own word. -/ +theorem getD_foldl_insert (σ : List (Nat × Nat)) (m : Std.ExtTreeMap Bytes32 EthLib.Base.U256) + (k b : Nat) (h : BitVec.toNat (m[Target.storageKey k]?.getD (0 : EthLib.Base.U256)) = b) : + ((σ.foldl (fun m kv => m.insert (Target.storageKey kv.1) (BitVec.ofNat 256 kv.2)) m)[ + Target.storageKey k]?.getD (0 : EthLib.Base.U256)).toNat = + σ.foldl (fun acc kv => if kv.1 % 2 ^ 256 = k % 2 ^ 256 then kv.2 % 2 ^ 256 else acc) b := by + induction σ generalizing m b with + | nil => simpa using h + | cons kv σ ih => + simp only [List.foldl_cons] + apply ih + rw [Std.ExtTreeMap.getElem?_insert] + by_cases hk : kv.1 % 2 ^ 256 = k % 2 ^ 256 + · have : compare (Target.storageKey kv.1) (Target.storageKey k) = .eq := by + rw [Std.compare_eq_iff_eq (α := Bytes32)]; exact (storageKey_eq_iff _ _).2 hk + simp only [hk, ↓reduceIte]; simp [this] + · have : compare (Target.storageKey kv.1) (Target.storageKey k) ≠ .eq := by + rw [ne_eq, Std.compare_eq_iff_eq (α := Bytes32)] + exact fun e => hk ((storageKey_eq_iff _ _).1 e) + simp only [hk, ↓reduceIte]; simpa [this] using h + +/-- A slot of a call's storage is a word. -/ +theorem slotValue_lt (σ : List (Nat × Nat)) (k : Nat) : slotValue σ k < 2 ^ 256 := by + unfold slotValue + suffices h : ∀ b < 2 ^ 256, σ.foldl + (fun acc kv => if kv.1 % 2 ^ 256 = k % 2 ^ 256 then kv.2 % 2 ^ 256 else acc) b < 2 ^ 256 from + h 0 (by decide) + induction σ with + | nil => exact fun b hb => hb + | cons kv σ ih => + intro b hb + simp only [List.foldl_cons] + apply ih + split + · exact Nat.mod_lt _ (by decide) + · exact hb + +/-- A slot of a call's storage depends on the slot modulo 2^256 only. -/ +theorem slotValue_mod (σ : List (Nat × Nat)) (k : Nat) : slotValue σ (k % 2 ^ 256) = slotValue σ k := by + simp only [slotValue, Nat.mod_mod] + +/-- A slot of a call's storage read at the slot modulo 2^256, as a word, is the slot's. -/ +theorem slotValue_mod_mod (σ : List (Nat × Nat)) (k : Nat) : + slotValue σ (k % 2 ^ 256) % 2 ^ 256 = slotValue σ k := by + rw [slotValue_mod, Nat.mod_eq_of_lt (slotValue_lt σ k)] + +/-- A slot of the callee's storage before the call is the call's: `slotValue` of its storage. -/ +theorem getStorage_preState (code : ByteArray) (c : Call) (k : Nat) : + ((Target.preState code c).getStorage (Target.address selfAddress) (Target.storageKey k)).toNat = + slotValue c.storage k := by + simp only [Target.preState, TransactionState.getStorage, TransactionState.ofBlock, + StorageMap.slot, State.getStorage] + simp + exact getD_foldl_insert _ _ _ _ (by simp) + +/-- `run_of_post` from any storage `σ`: the frame of every message with no value and call data +`cdOf (selectorOf s) ws` stops as `X` shows from every state, so `Target.run` of the call with +argument words `ws`, no value and storage `σ` is `X`, when `X` shows no logs and keeps `σ`. -/ +theorem run_of_post_at (code : ByteArray) (s : Nat) (ws : List U256) (σ : List (Nat × Nat)) + (X : Observable) (hlogs : X.logs = []) (hstore : ∀ slot, X.storage slot = slotValue σ slot) + (h : ∀ msg : Message .fusaka, msg.value = 0 → msg.data = cdOf (selectorOf s) ws → + ∀ st ss, Spec .fusaka (At code msg 0 [] .empty 10000000 st ss .empty) (Post X st ss)) : + Target.run code + { calldata := Abi.calldata s (ws.map BitVec.toNat), callvalue := 0, storage := σ } = + some X := by + have hd : Abi.calldata s (ws.map BitVec.toNat) = cdOf (selectorOf s) ws := by + rw [calldata_eq_cdOf s _ (by simpa using fun a _ => a.isLt)] + simp [List.map_map, Function.comp_def] + let c : Call := { calldata := Abi.calldata s (ws.map BitVec.toNat), callvalue := 0, storage := σ } + obtain ⟨evm, hr, herr, hout, hsub, hst⟩ := processMessage_post (Target.message code c) rfl rfl + (precompileAddress_message code c) X + (fun st ss => h _ rfl (by simp [Target.message, c, hd]) st ss) (Target.preState code c) + Substate.empty + show Target.run code c = some X + simp only [Target.run, hr] + have hsucc : evm.1.error.isNone = X.success := by + rw [herr]; cases hX : X.success <;> simp [errorOf, hX] + congr 1 + cases X with + | mk success output logs storage => + simp only at hsucc hout hlogs hstore hst ⊢ + subst hlogs + rw [Observable.mk.injEq] + refine ⟨hsucc, hout, by simp [hsub, Substate.empty], ?_⟩ + funext slot + rw [hstore slot, hsucc] + cases hs : success + · simp [c] + · simp only [ite_true] + rw [hst hs, getStorage_preState code c slot] + +/-! ## Calls from a given storage + +A contract whose constructor leaves storage is called from it: `callAt sel ws σ` is the call of +selector `sel` on the argument words `ws` from the storage `σ`. Its frame starts from +`Target.preState`, whose storage holds the words of `σ` (`getStorage_preState`), so SLOAD reads +them (`sload_then`), and a failing call keeps them (`run_of_postS_at`). -/ + +/-- The call of selector `sel` on the argument words `ws` from the storage `σ`, with no value. -/ +def callAt (sel : Nat) (ws : List U256) (σ : List (Nat × Nat)) : Call := + { calldata := Abi.calldata sel (ws.map BitVec.toNat), callvalue := 0, storage := σ } + +theorem storage_callAt (sel : Nat) (ws : List U256) (σ : List (Nat × Nat)) : + (callAt sel ws σ).storage = σ := rfl + +/-- A slot of the callee's storage before the call holds the call's word for it, as a word. -/ +theorem getStorage_preState_ofNat (code : ByteArray) (c : Call) (k : Nat) : + (Target.preState code c).getStorage (Target.address selfAddress) (Target.storageKey k) = + BitVec.ofNat 256 (slotValue c.storage k) := by + apply BitVec.eq_of_toNat_eq + rw [getStorage_preState, BitVec.toNat_ofNat, Nat.mod_eq_of_lt (slotValue_lt _ _)] + +/-- `getStorage_preState` at the key SLOAD reads for a word. -/ +theorem getStorage_preState_toBeBytes (code : ByteArray) (c : Call) (key : U256) : + (Target.preState code c).getStorage (Target.address selfAddress) (U256.toBeBytes key) = + BitVec.ofNat 256 (slotValue c.storage key.toNat) := by + rw [← (storageKey_eq_toBeBytes key.toNat key).mpr (Nat.mod_eq_of_lt key.isLt)] + exact getStorage_preState_ofNat code c key.toNat + +/-- Recording a read keeps the storage. -/ +theorem getStorage_recordStorageRead (tx : TransactionState) (a : Address) (k : Bytes32) + (a' : Address) (k' : Bytes32) : + (tx.recordStorageRead a k).getStorage a' k' = tx.getStorage a' k' := rfl + +theorem getD_getElem? (m : StorageMap) (a : Address) (k : Bytes32) : + (m.getD a ∅)[k]? = m.slot a k := by + simp only [StorageMap.slot, Std.ExtTreeMap.getD_eq_getD_getElem?] + cases m[a]? <;> simp + +theorem slot_writeOf (tx : TransactionState) (a : Address) (k : Bytes32) (v : U256) + (a' : Address) (k' : Bytes32) : + (writeOf tx a k v).storageWrites.slot a' k' = + if a' = a ∧ k' = k then some v else tx.storageWrites.slot a' k' := by + by_cases ha : a' = a + · subst ha + by_cases hk : k' = k + · subst hk + simp [writeOf, TransactionState.recordAccountRead, StorageMap.slot] + · simp only [writeOf, TransactionState.recordAccountRead, StorageMap.slot, + Std.ExtTreeMap.getElem?_insert_self, Option.bind_some, Std.ExtTreeMap.getElem?_insert] + have hc : compare k k' ≠ .eq := fun h => hk (Std.LawfulEqCmp.eq_of_compare h).symm + simp only [hc, true_and, hk, ↓reduceIte] + exact getD_getElem? _ _ _ + · simp only [writeOf, TransactionState.recordAccountRead, StorageMap.slot, + Std.ExtTreeMap.getElem?_insert] + simp [show (a = a') = False from eq_false (fun h => ha h.symm), ha] + +/-- The storage after a write to any state: the written word at its key, the state's elsewhere. -/ +theorem getStorage_writeOf_of (tx : TransactionState) (a : Address) (k : Bytes32) (v : U256) + (a' : Address) (k' : Bytes32) : + (writeOf tx a k v).getStorage a' k' = if a' = a ∧ k' = k then v else tx.getStorage a' k' := by + unfold TransactionState.getStorage + rw [slot_writeOf] + by_cases h : a' = a ∧ k' = k + · simp only [h, and_self, ↓reduceIte] + · simp only [h, ↓reduceIte] + rfl + +/-- The frame of every message of the call from the storage `σ`, from the call's state before +it, stops as `PostS X` says: `Target.run` of the call is `X`, when `X` shows no logs and keeps +the words of `σ` when it fails. -/ +theorem run_of_postS_at (code : ByteArray) (s : Nat) (ws : List U256) (σ : List (Nat × Nat)) + (X : Observable) (hlogs : X.logs = []) + (hfail : X.success = false → ∀ slot, X.storage slot = slotValue σ slot) + (h : ∀ msg : Message .fusaka, msg.value = 0 → msg.data = cdOf (selectorOf s) ws → + msg.isStatic = false → msg.currentTarget = Target.address selfAddress → + Spec .fusaka (At code msg 0 [] .empty 10000000 (Target.preState code (callAt s ws σ)) + Substate.empty .empty) (PostS X Substate.empty)) : + Target.run code (callAt s ws σ) = some X := by + have hd : Abi.calldata s (ws.map BitVec.toNat) = cdOf (selectorOf s) ws := by + rw [calldata_eq_cdOf s _ (by simpa using fun a _ => a.isLt)] + simp [List.map_map, Function.comp_def] + let c := callAt s ws σ + obtain ⟨evm, hr, herr, hout, hst⟩ := processMessage_postS (Target.message code c) rfl rfl + (precompileAddress_message code c) X (Target.preState code c) Substate.empty + (h _ rfl (by simp [Target.message, c, callAt, hd]) rfl rfl) + show Target.run code c = some X + simp only [Target.run, hr] + have hsucc : evm.1.error.isNone = X.success := by + rw [herr]; cases hX : X.success <;> simp [errorOf, hX] + congr 1 + cases X with + | mk success output logs storage => + simp only at hsucc hout hlogs hfail hst ⊢ + subst hlogs + rw [Observable.mk.injEq] + refine ⟨hsucc, hout, ?_, ?_⟩ + · rw [hsucc] + cases hs : success + · rfl + · simp [(hst hs).1, Substate.empty] + · funext slot + rw [hsucc] + cases hs : success + · simp [c, callAt, hfail hs slot] + · simp only [ite_true] + exact (hst hs).2 slot + +/-- SLOAD of a slot of the callee, as a step of a specification: it reads the word of the state, +at a price of at most a cold access. -/ +theorem sload_then {Q : Evm fork Nat → Prop} {code : ByteArray} {message : Message fork} + {pc : Nat} {key : U256} {rest : List U256} {memory : ByteArray} {gas : Nat} + {state : TransactionState} {substate : Substate} {returnData : ByteArray} + (hfork : .berlin ≤ fork) (hlt : pc < code.size) (hbyte : code[pc] = 0x54) + (htgt : message.currentTarget = Target.address selfAddress) (hgas : 2100 ≤ gas) + (h : ∀ g, g ≤ 2100 → Spec fork (At code message (pc + 1) + (state.getStorage (Target.address selfAddress) (U256.toBeBytes key) :: rest) memory + (gas - g) (state.recordStorageRead message.currentTarget (U256.toBeBytes key)) + { substate with + accessedStorageKeys := (substate.accessedStorageKeys.insert message.currentTarget + ((substate.accessedStorageKeys.getD message.currentTarget ∅).insert + (U256.toBeBytes key))) } returnData) Q) : + Spec fork (At code message pc (key :: rest) memory gas state substate returnData) Q := + Spec.seq (sload hfork hlt hbyte rfl (by split <;> omega)) + (Spec.reshape (by rw [htgt]) rfl rfl (h _ (by split <;> omega))) + +/-- SSTORE at Fusaka, as a step of a specification: it writes the word, at a price of at most a +cold access and a new slot (`sstoreCost_le`), which the rest of the path may spend. -/ +theorem sstore_then {Q : Evm .fusaka Nat → Prop} {code : ByteArray} {message : Message .fusaka} + {pc : Nat} {key new : U256} {rest : List U256} {memory : ByteArray} {gas : Nat} + {state state' : TransactionState} {substate : Substate} {returnData : ByteArray} + (hlt : pc < code.size) (hbyte : code[pc] = 0x55) (hstatic : message.isStatic = false) + (hgas : 22100 ≤ gas) + (hset : (state.recordStorageRead message.currentTarget (U256.toBeBytes key)).setStorage + message.currentTarget (U256.toBeBytes key) new = .ok state') + (h : ∀ g, g ≤ 22100 → Spec .fusaka (At code message (pc + 1) rest memory (gas - g) state' + { substate with + accessedStorageKeys := substate.accessedStorageKeys.insert message.currentTarget + ((substate.accessedStorageKeys.getD message.currentTarget ∅).insert + (U256.toBeBytes key)) + refundCounter := substate.refundCounter + sstoreRefund .fusaka + (state.getStorageOriginal message.currentTarget (U256.toBeBytes key)) + (state.getStorage message.currentTarget (U256.toBeBytes key)) new } returnData) Q) : + Spec .fusaka (At code message pc (key :: new :: rest) memory gas state substate returnData) + Q := + Spec.seq (sstore (by decide) (by decide) hlt hbyte hstatic rfl + (by simp only [CALL_STIPEND]; omega) (Nat.le_trans (sstoreCost_le _ _ _ _) hgas) hset) + (h _ (sstoreCost_le _ _ _ _)) + +/-- A statement about every word below `N` follows from it on the words of every number below +`N`, which the kernel can evaluate one by one. -/ +theorem forall_of_lt_ofNat {N : Nat} {P : U256 → Prop} + (h : ∀ n, n < N → P (BitVec.ofNat 256 n)) : ∀ w : U256, w.toNat < N → P w := fun w hw => by + simpa using h w.toNat hw + +/-! ## The tactic -/ + +open Lean.Parser.Tactic + +/-- Proves that a slot of the storage after the write is SolidCore's: both are the written +word on the slot of its key and zero elsewhere. -/ +syntax "wide_store" : tactic + +macro_rules + | `(tactic| wide_store) => `(tactic| ( + simp [*, Source.observe, SolidCore.Solidity.Source.State.loadSlot, + SolidCore.Solidity.Source.StorageMap.lookup?, Std.HashMap.getElem?_insert, + hashMap_getElem?_of_isEmpty, storageKey_eq_toBeBytes, SolidCore.Solidity.Shared.norm, + SolidCore.Solidity.Shared.wordModulus, EvmYul.UInt256.size] + try ((repeat' split) <;> simp_all <;> omega))) + +/-- Proves that a slot of the callee's storage at a stop is SolidCore's, after one write or +none. -/ +syntax "wide_slot" ident : tactic + +macro_rules + | `(tactic| wide_slot $htgt) => `(tactic| first + | (rw [$htgt:ident, getStorage_writeOf _ _ rfl]; wide_store) + | (rw [getStorage_preState_nil _ _ rfl]; wide_store)) + +/-- Steps one opcode of a path of a function that writes storage: SSTORE to the callee's account, +which exists, STOP against the observable of `PostS`, and every other opcode as `wide_one`. -/ +syntax "wide_one_s" " [" simpLemma,* "]" " [" simpLemma,* "]" ident ident ident : tactic + +macro_rules + | `(tactic| wide_one_s [$ls,*] [$ns,*] $hf $hstat $htgt) => `(tactic| ((try unfold Spec) <;> first + | (refine' Triple.seq (sstore (by decide) (by decide) ?lt ?op $hstat rfl ?stip ?gas + (setStorage_ok _ _ ?acc)) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case stip => simp only [CALL_STIPEND]; omega + case gas => exact Nat.le_trans (sstoreCost_le _ _ _ _) (by omega) + case acc => rw [$htgt:ident]; exact account_preState _ _) <;> evm_tidy + | (refine stop_postS ?lt ?op ?succ ?out rfl ?store + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case succ => simp [Source.observe] + case out => simp [Source.observe] + case store => intro slot; wide_slot $htgt) + | (refine return_postS ?lt ?op ?gas ?succ ?out rfl ?store + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => (try wide_mem) <;> first | decide | omega | decide +kernel + case succ => first | rfl | simp [Source.observe] + case out => wide_out + case store => intro slot; wide_slot $htgt) + | (refine revert_postS (by decide) ?lt ?op ?gas ?succ ?out rfl + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => (try wide_mem) <;> first | decide | omega | decide +kernel + case succ => first | rfl | simp [Source.observe] + case out => wide_out) + | wide_one [$ls,*] [$ns,*] $hf)) + +/-- Proves the frame hypothesis of `run_of_postS` on one path of the source, for a function +that writes storage. `ls` are the rules of the code, as for `wide_tgt`. -/ +syntax "wide_tgt_s" " [" simpLemma,* "]" : tactic + +macro_rules + | `(tactic| wide_tgt_s [$ls,*]) => `(tactic| ( + intro msg hv hd hstat htgt + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + try simp only [$ls,*] at hd + repeat wide_one_s [$ls,*] [hd, hv] hfork hstat htgt)) + +open Lean Meta Elab Tactic in +/-- Closes a goal about one word that a hypothesis `w.toNat < N` bounds by `N ≤ 2 ^ 8`, such as +a path condition on a `uint8` argument, by evaluating it on every word below `N` in the kernel +(`forall_of_lt_ofNat` and `decide +kernel`). It fails when the goal mentions another local. -/ +elab "word_decide" : tactic => withMainContext do + let goal ← getMainGoal + for decl in ← getLCtx do + if decl.isImplementationDetail then continue + let ty ← instantiateMVars decl.type + let_expr LT.lt _ _ lhs rhs := ty | continue + let_expr BitVec.toNat _ w := lhs | continue + unless w.isFVar do continue + let some n ← (Meta.evalNat rhs).run | continue + unless n ≤ 256 do continue + let g ← instantiateMVars (← goal.getType) + unless g.containsFVar w.fvarId! do continue + let motive ← mkLambdaFVars #[w] g + -- The goal `∀ n, n < N → motive (BitVec.ofNat 256 n)`, which the kernel decides. + let hty ← withLocalDeclD `n (mkConst `Nat) fun k => do + let lt ← mkAppM `LT.lt #[k, rhs] + let body := (mkApp motive (← mkAppM `BitVec.ofNat #[mkNatLit 256, k])).headBeta + mkForallFVars #[k] (← mkArrow lt body) + let hm ← mkFreshExprSyntheticOpaqueMVar hty + let [] ← Term.TermElabM.run' <| + Tactic.run hm.mvarId! (evalTactic (← `(tactic| decide +kernel))) + | throwError "word_decide: the kernel check left goals" + goal.assign (← mkAppOptM `SolidCore.Refinement.Evm.Wide.forall_of_lt_ofNat + #[rhs, motive, hm, w, decl.toExpr]) + replaceMainGoal [] + return + throwError "word_decide: no word with a small bound that the goal mentions" + +/-- Proves that a slot of the callee's storage at a stop is SolidCore's, for a call from a given +storage (`callAt`): the target's word is the last write's at its key and the call's word +elsewhere (`getStorage_writeOf_of`, `getStorage_preState_ofNat`). After a split on the slot, the +words left to compare go to `word_decide`. -/ +syntax "wide_slot_at" ident : tactic + +macro_rules + | `(tactic| wide_slot_at $htgt) => `(tactic| ( + simp only [$htgt:ident, getStorage_writeOf_of, getStorage_recordStorageRead, + getStorage_preState_ofNat, storage_callAt] + simp [*, Source.observe, SolidCore.Solidity.Source.State.loadSlot, + SolidCore.Solidity.Source.StorageMap.lookup?, Std.HashMap.getElem?_insert, + storageKey_eq_toBeBytes, slotValue, SolidCore.Solidity.Shared.norm, + SolidCore.Solidity.Shared.wordModulus, EvmYul.UInt256.size] + all_goals (split <;> (try simp_all) <;> (try split) <;> (try simp_all) <;> (try omega) <;> + word_decide))) + +/-- Proves that the output a RETURN or REVERT reads is the observable's: `wide_out`, and else +`word_decide` on the output words. -/ +syntax "wide_out_at" : tactic + +macro_rules + | `(tactic| wide_out_at) => `(tactic| first + | wide_out + | ((try wide_mem) <;> simp only [toList_wordBytes, Source.observe] <;> word_decide)) + +/-- Steps one opcode of a path of a call from a given storage: SLOAD reads the call's word +(`sload_then`, `getStorage_preState_toBeBytes`), SSTORE writes (`sstore_then`), STOP, RETURN +and REVERT close the path against the observable of `PostS`, and every other opcode is +`wide_one`'s. -/ +syntax "wide_one_at" " [" simpLemma,* "]" " [" simpLemma,* "]" ident ident ident : tactic + +macro_rules + | `(tactic| wide_one_at [$ls,*] [$ns,*] $hf $hstat $htgt) => `(tactic| ((try unfold Spec) <;> first + | ((refine sload_then (by decide) ?lt ?op $htgt ?gas (fun _ _ => ?next) + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => omega) <;> + simp only [getStorage_recordStorageRead, getStorage_preState_toBeBytes, storage_callAt, + slotValue, List.foldl_cons, List.foldl_nil, BitVec.reduceToNat, Nat.reduceMod, + Nat.reducePow, ↓reduceIte, Nat.reduceEqDiff, BitVec.reduceOfNat] <;> evm_tidy) + | ((refine sstore_then ?lt ?op $hstat ?gas (setStorage_ok _ _ ?acc) (fun _ _ => ?next) + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => omega + case acc => rw [$htgt:ident]; exact account_preState _ _) <;> evm_tidy) + | (refine stop_postS ?lt ?op ?succ ?out rfl ?store + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case succ => simp [Source.observe] + case out => simp [Source.observe] + case store => intro slot; wide_slot_at $htgt) + | (refine return_postS ?lt ?op ?gas ?succ ?out rfl ?store + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => (try wide_mem) <;> first | decide | omega | decide +kernel + case succ => first | rfl | simp [Source.observe] + case out => wide_out_at + case store => intro slot; wide_slot_at $htgt) + | (refine revert_postS (by decide) ?lt ?op ?gas ?succ ?out rfl + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => (try wide_mem) <;> first | decide | omega | decide +kernel + case succ => first | rfl | simp [Source.observe] + case out => wide_out_at) + | wide_one [$ls,*] [$ns,*] $hf)) + +/-- Proves the frame hypothesis of `run_of_postS_at` on one path of the source, for a call from +a given storage. `ls` are the rules of the code, as for `wide_tgt`. -/ +syntax "wide_tgt_at" " [" simpLemma,* "]" : tactic + +macro_rules + | `(tactic| wide_tgt_at [$ls,*]) => `(tactic| ( + intro msg hv hd hstat htgt + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + try simp only [$ls,*] at hd + repeat wide_one_at [$ls,*] [hd, hv] hfork hstat htgt)) + +end SolidCore.Refinement.Evm.Wide diff --git a/SolidCore/Refinement/Evm/WideStorageAt.lean b/SolidCore/Refinement/Evm/WideStorageAt.lean new file mode 100644 index 00000000..ced880c3 --- /dev/null +++ b/SolidCore/Refinement/Evm/WideStorageAt.lean @@ -0,0 +1,41 @@ +import SolidCore.Refinement.Evm.WideStorage + +/-! +# Symbolic execution of a function that writes storage, from any storage + +`Evm.WideStorage` reads the callee's storage before the call (`getStorage_preState_toBeBytes`, +`getStorage_recordStorageRead`) and runs a function that writes storage from any storage +(`run_of_postS_at`). This module adds `getStorage_writeOf_any`: the storage after one write +over any state, the written word at its key and the state's own word elsewhere. +-/ + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open EthLib.Execution.State +open SolidCore.Refinement.Evm.Logic SolidCore.Refinement.Evm.Symex + +namespace SolidCore.Refinement.Evm.Wide + +/-- The storage after one write over any state: the written word at its key, the state's own +word elsewhere. -/ +theorem getStorage_writeOf_any (tx : TransactionState) (a : Address) (k : Bytes32) (v : U256) + (a' : Address) (k' : Bytes32) : + (writeOf tx a k v).getStorage a' k' = if a' = a ∧ k' = k then v else tx.getStorage a' k' := by + simp only [writeOf, TransactionState.getStorage, TransactionState.recordAccountRead, + StorageMap.slot] + by_cases ha : a' = a + · subst ha + by_cases hk : k' = k + · subst hk; simp + · have hk' : (k = k') = False := eq_false (fun h => hk h.symm) + simp only [Std.ExtTreeMap.getElem?_insert_self, Option.bind_some, hk, and_false, + ↓reduceIte, Std.ExtTreeMap.getElem?_insert, Std.compare_eq_iff_eq, hk'] + cases h : tx.storageWrites[a']? <;> simp [h, Std.ExtTreeMap.getD_eq_getD_getElem?] <;> rfl + · have ha' : (a = a') = False := eq_false (fun h => ha h.symm) + simp [ha, ha', Std.ExtTreeMap.getElem?_insert] + rfl + +/-- info: 'SolidCore.Refinement.Evm.Wide.getStorage_writeOf_any' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms getStorage_writeOf_any + +end SolidCore.Refinement.Evm.Wide diff --git a/SolidCore/Refinement/Facts.lean b/SolidCore/Refinement/Facts.lean new file mode 100644 index 00000000..77fa59a0 --- /dev/null +++ b/SolidCore/Refinement/Facts.lean @@ -0,0 +1,36 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. + +import SolidCore.Refinement.Facts.B1 +import SolidCore.Refinement.Facts.B2 +import SolidCore.Refinement.Facts.B3 +import SolidCore.Refinement.Facts.B4 +import SolidCore.Refinement.Facts.B5 +import SolidCore.Refinement.Facts.B6 +import SolidCore.Refinement.Facts.B7 +import SolidCore.Refinement.Facts.C1 +import SolidCore.Refinement.Facts.C2 +import SolidCore.Refinement.Facts.C3 +import SolidCore.Refinement.Facts.C4 +import SolidCore.Refinement.Facts.C5 +import SolidCore.Refinement.Facts.C6 +import SolidCore.Refinement.Facts.C7 +import SolidCore.Refinement.Facts.C8 +import SolidCore.Refinement.Facts.C9 +import SolidCore.Refinement.Facts.D1 +import SolidCore.Refinement.Facts.D2 +import SolidCore.Refinement.Facts.D3 +import SolidCore.Refinement.Facts.D4 +import SolidCore.Refinement.Facts.W1 +import SolidCore.Refinement.Facts.W2 +import SolidCore.Refinement.Facts.W3 +import SolidCore.Refinement.Facts.W4 +import SolidCore.Refinement.Facts.W5 +import SolidCore.Refinement.Facts.C10 +import SolidCore.Refinement.Facts.C11 + +/-! +# solar's analysis facts on the refinement corpus + +One module per `scripts/refinement/corpus` contract, each theorem one recorded MIR fact; +see `scripts/refinement/FACTS.md` for what they mean. +-/ diff --git a/SolidCore/Refinement/Facts/B1.lean b/SolidCore/Refinement/Facts/B1.lean new file mode 100644 index 00000000..43f70127 --- /dev/null +++ b/SolidCore/Refinement/Facts/B1.lean @@ -0,0 +1,113 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/b1.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `b1.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 3. Proved by Z3: 3. Checked in Lean by the prover and +emitted here: 3. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +- `cse`: a memory, storage or transient read CSE forwarded from an earlier value. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.B1 + +/-- Contract `Main`, function `#0 f`, fact 0: `cse v21 eq v21 at the end of bb2`, its left operand +defined by `calldataload`. Query `Main-f0-bb2-v21-cse-0.smt2`. -/ +theorem f0_f_bb2_v21_cse_0 («$v14» : BitVec 256) («$v15» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v20» : BitVec 256) («$v21» : BitVec 256) («$v19» : BitVec 256) («$v8» : BitVec 256) («$v6» : BitVec 256) («$v7» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$sto4» : (BitVec 256 → BitVec 256)) («$mem5» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v14» = «$input_calldatasize»)) + (h1 : («$v14» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v15» = (if («$v14» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v16» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v17» = (if («$v16» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v20» = («$v15» ||| «$v17»))) + (h6 : («$v21» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v19» = («$v21» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v21»))) + (h9 : («$v8» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h10 : («$sto4» = (store «$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256) (0x0000000000000000000000000000000000000000000000000000000000000007#256)))) + (h11 : («$v6» = (if ((0x000000000000000000000000000000000000000000000000000000000000001f#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((«$v21» >>> (((0x000000000000000000000000000000000000000000000000000000000000001f#256) - (0x000000000000000000000000000000000000000000000000000000000000001f#256)) * (0x0000000000000000000000000000000000000000000000000000000000000008#256))) &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256))))) + (h12 : («$v7» = (if ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v6» <<< (0x00000000000000000000000000000000000000000000000000000000000000f8#256))))) + (h13 : («$mem5» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v7»)))) + (h14 : («$v20» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h15 : (¬(«$v21» = «$v21»))) + : False := by + try subst h8 + try subst h10 + try subst h13 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 1: `cse v8 eq v21 at the end of bb2`, its left operand +defined by `sload`. Query `Main-f0-bb2-v8-cse-1.smt2`. -/ +theorem f0_f_bb2_v8_cse_1 («$v14» : BitVec 256) («$v15» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v20» : BitVec 256) («$v21» : BitVec 256) («$v19» : BitVec 256) («$v8» : BitVec 256) («$v6» : BitVec 256) («$v7» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$sto4» : (BitVec 256 → BitVec 256)) («$mem5» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v14» = «$input_calldatasize»)) + (h1 : («$v14» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v15» = (if («$v14» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v16» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v17» = (if («$v16» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v20» = («$v15» ||| «$v17»))) + (h6 : («$v21» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v19» = («$v21» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v21»))) + (h9 : («$v8» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h10 : («$sto4» = (store «$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256) (0x0000000000000000000000000000000000000000000000000000000000000007#256)))) + (h11 : («$v6» = (if ((0x000000000000000000000000000000000000000000000000000000000000001f#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((«$v21» >>> (((0x000000000000000000000000000000000000000000000000000000000000001f#256) - (0x000000000000000000000000000000000000000000000000000000000000001f#256)) * (0x0000000000000000000000000000000000000000000000000000000000000008#256))) &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256))))) + (h12 : («$v7» = (if ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v6» <<< (0x00000000000000000000000000000000000000000000000000000000000000f8#256))))) + (h13 : («$mem5» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v7»)))) + (h14 : («$v20» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h15 : («$v21» = «$v21»)) + (h16 : (¬(«$v8» = «$v21»))) + : False := by + try subst h8 + try subst h10 + try subst h13 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 2: `check_elim v19 eq v21 at the end of bb2`, its left +operand defined by `and`. Query `Main-f0-bb2-v19-check_elim-2.smt2`. -/ +theorem f0_f_bb2_v19_check_elim_2 («$v14» : BitVec 256) («$v15» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v20» : BitVec 256) («$v21» : BitVec 256) («$v19» : BitVec 256) («$v8» : BitVec 256) («$v6» : BitVec 256) («$v7» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$sto4» : (BitVec 256 → BitVec 256)) («$mem5» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v14» = «$input_calldatasize»)) + (h1 : («$v14» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v15» = (if («$v14» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v16» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v17» = (if («$v16» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v20» = («$v15» ||| «$v17»))) + (h6 : («$v21» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v19» = («$v21» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v21»))) + (h9 : («$v8» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h10 : («$sto4» = (store «$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256) (0x0000000000000000000000000000000000000000000000000000000000000007#256)))) + (h11 : («$v6» = (if ((0x000000000000000000000000000000000000000000000000000000000000001f#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((«$v21» >>> (((0x000000000000000000000000000000000000000000000000000000000000001f#256) - (0x000000000000000000000000000000000000000000000000000000000000001f#256)) * (0x0000000000000000000000000000000000000000000000000000000000000008#256))) &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256))))) + (h12 : («$v7» = (if ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v6» <<< (0x00000000000000000000000000000000000000000000000000000000000000f8#256))))) + (h13 : («$mem5» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v7»)))) + (h14 : («$v20» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h15 : («$v21» = «$v21»)) + (h16 : («$v8» = «$v21»)) + (h17 : (¬(«$v19» = «$v21»))) + : False := by + try subst h8 + try subst h10 + try subst h13 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.B1 diff --git a/SolidCore/Refinement/Facts/B2.lean b/SolidCore/Refinement/Facts/B2.lean new file mode 100644 index 00000000..307aed27 --- /dev/null +++ b/SolidCore/Refinement/Facts/B2.lean @@ -0,0 +1,52 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/b2.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `b2.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 1. Proved by Z3: 1. Checked in Lean by the prover and +emitted here: 1. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.B2 + +/-- Contract `Main`, function `#0 f`, fact 0: `check_elim v14 eq v18 at the end of bb4`, its left +operand defined by `and`. Query `Main-f0-bb4-v14-check_elim-0.smt2`. -/ +theorem f0_f_bb4_v14_check_elim_0 («$v9» : BitVec 256) («$v10» : BitVec 256) («$v11» : BitVec 256) («$v12» : BitVec 256) («$v17» : BitVec 256) («$v18» : BitVec 256) («$v14» : BitVec 256) («$v6» : BitVec 256) («$v7» : BitVec 256) («$v16» : BitVec 256) («$v1» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v9» = «$input_calldatasize»)) + (h1 : («$v9» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v10» = (if («$v9» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v11» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v12» = (if («$v11» > (0x0000000000000000000000000000000000000000000000000000000000000001#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v17» = («$v10» ||| «$v12»))) + (h6 : («$v18» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v14» = («$v18» &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h8 : («$v6» = («$v18» * (0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe#256)))) + (h9 : («$v7» = («$v6» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)))) + (h10 : («$v16» = («$v7» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h11 : («$v1» = (if («$v16» = (0x0000000000000000000000000000000000000000000000000000000000000002#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h12 : («$v17» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h13 : (¬(«$v14» = «$v18»))) + : False := by + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.B2 diff --git a/SolidCore/Refinement/Facts/B3.lean b/SolidCore/Refinement/Facts/B3.lean new file mode 100644 index 00000000..379f18a7 --- /dev/null +++ b/SolidCore/Refinement/Facts/B3.lean @@ -0,0 +1,49 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/b3.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `b3.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 1. Proved by Z3: 1. Checked in Lean by the prover and +emitted here: 1. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.B3 + +/-- Contract `Main`, function `#0 f`, fact 0: `check_elim v11 eq v14 at the end of bb4`, its left +operand defined by `and`. Query `Main-f0-bb4-v11-check_elim-0.smt2`. -/ +theorem f0_f_bb4_v11_check_elim_0 («$v6» : BitVec 256) («$v7» : BitVec 256) («$v8» : BitVec 256) («$v9» : BitVec 256) («$v13» : BitVec 256) («$v14» : BitVec 256) («$v11» : BitVec 256) («$v12» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v6» = «$input_calldatasize»)) + (h1 : («$v6» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v7» = (if («$v6» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v8» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v9» = (if («$v8» > (0x0000000000000000000000000000000000000000000000000000000000000001#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v13» = («$v7» ||| «$v9»))) + (h6 : («$v14» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v11» = («$v14» &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h8 : («$v12» = (if («$v14» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h9 : («$v13» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h10 : (¬(«$v11» = «$v14»))) + : False := by + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.B3 diff --git a/SolidCore/Refinement/Facts/B4.lean b/SolidCore/Refinement/Facts/B4.lean new file mode 100644 index 00000000..373b8b79 --- /dev/null +++ b/SolidCore/Refinement/Facts/B4.lean @@ -0,0 +1,142 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/b4.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `b4.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 4. Proved by Z3: 4. Checked in Lean by the prover and +emitted here: 4. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +- `cse`: a memory, storage or transient read CSE forwarded from an earlier value. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.B4 + +/-- Contract `Main`, function `#0 f`, fact 0: `cse v6 eq v6 at the end of bb2`, its left operand +defined by `add`. Query `Main-f0-bb2-v6-cse-0.smt2`. The query assumes the backend axioms +`allocation`. -/ +theorem f0_f_bb2_v6_cse_0 («$v9» : BitVec 256) («$v10» : BitVec 256) («$v11» : BitVec 256) («$v12» : BitVec 256) («$v17» : BitVec 256) («$v18» : BitVec 256) («$v16» : BitVec 256) («$v0» : BitVec 256) («$fmp1» : BitVec 256) («$v6» : BitVec 256) («$v7» : BitVec 256) («$v15» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$mem4» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v9» = «$input_calldatasize»)) + (h1 : («$v9» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v10» = (if («$v9» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v11» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v12» = (if («$v11» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v17» = («$v10» ||| «$v12»))) + (h6 : («$v18» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v16» = («$v18» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : (True ∧ ((«$v0» ≥ (0x0000000000000000000000000000000000000000000000000000000000000080#256)) ∧ («$v0» ≤ (0x000000000000000000000000000000000000000000000003ffffffffffffffff#256))))) + (h9 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$fmp1»)))) + (h10 : («$v6» = («$v18» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h11 : («$v7» = (if («$v6» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h12 : («$v17» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h13 : («$v15» = («$v6» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h14 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v6»)))) + (h15 : («$v7» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h16 : («$v16» = «$v18»)) + (h17 : (¬(«$v6» = «$v6»))) + : False := by + try subst h9 + try subst h14 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 1: `cse v6 eq v6 at the end of bb2`, its left operand +defined by `add`. Query `Main-f0-bb2-v6-cse-1.smt2`. The query assumes the backend axioms +`allocation`. -/ +theorem f0_f_bb2_v6_cse_1 («$v9» : BitVec 256) («$v10» : BitVec 256) («$v11» : BitVec 256) («$v12» : BitVec 256) («$v17» : BitVec 256) («$v18» : BitVec 256) («$v16» : BitVec 256) («$v0» : BitVec 256) («$fmp1» : BitVec 256) («$v6» : BitVec 256) («$v7» : BitVec 256) («$v15» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$mem4» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v9» = «$input_calldatasize»)) + (h1 : («$v9» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v10» = (if («$v9» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v11» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v12» = (if («$v11» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v17» = («$v10» ||| «$v12»))) + (h6 : («$v18» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v16» = («$v18» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : (True ∧ ((«$v0» ≥ (0x0000000000000000000000000000000000000000000000000000000000000080#256)) ∧ («$v0» ≤ (0x000000000000000000000000000000000000000000000003ffffffffffffffff#256))))) + (h9 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$fmp1»)))) + (h10 : («$v6» = («$v18» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h11 : («$v7» = (if («$v6» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h12 : («$v17» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h13 : («$v15» = («$v6» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h14 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v6»)))) + (h15 : («$v7» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h16 : («$v6» = «$v6»)) + (h17 : («$v16» = «$v18»)) + (h18 : (¬(«$v6» = «$v6»))) + : False := by + try subst h9 + try subst h14 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 2: `check_elim v15 eq v6 at the end of bb2`, its left +operand defined by `and`. Query `Main-f0-bb2-v15-check_elim-2.smt2`. The query assumes the backend +axioms `allocation`. -/ +theorem f0_f_bb2_v15_check_elim_2 («$v9» : BitVec 256) («$v10» : BitVec 256) («$v11» : BitVec 256) («$v12» : BitVec 256) («$v17» : BitVec 256) («$v18» : BitVec 256) («$v16» : BitVec 256) («$v0» : BitVec 256) («$fmp1» : BitVec 256) («$v6» : BitVec 256) («$v7» : BitVec 256) («$v15» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$mem4» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v9» = «$input_calldatasize»)) + (h1 : («$v9» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v10» = (if («$v9» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v11» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v12» = (if («$v11» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v17» = («$v10» ||| «$v12»))) + (h6 : («$v18» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v16» = («$v18» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : (True ∧ ((«$v0» ≥ (0x0000000000000000000000000000000000000000000000000000000000000080#256)) ∧ («$v0» ≤ (0x000000000000000000000000000000000000000000000003ffffffffffffffff#256))))) + (h9 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$fmp1»)))) + (h10 : («$v6» = («$v18» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h11 : («$v7» = (if («$v6» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h12 : («$v17» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h13 : («$v15» = («$v6» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h14 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v6»)))) + (h15 : («$v7» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h16 : («$v6» = «$v6»)) + (h17 : («$v6» = «$v6»)) + (h18 : («$v16» = «$v18»)) + (h19 : (¬(«$v15» = «$v6»))) + : False := by + try subst h9 + try subst h14 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 3: `check_elim v16 eq v18 at the end of bb4`, its left +operand defined by `and`. Query `Main-f0-bb4-v16-check_elim-3.smt2`. The query assumes the backend +axioms `allocation`. -/ +theorem f0_f_bb4_v16_check_elim_3 («$v9» : BitVec 256) («$v10» : BitVec 256) («$v11» : BitVec 256) («$v12» : BitVec 256) («$v17» : BitVec 256) («$v18» : BitVec 256) («$v16» : BitVec 256) («$v0» : BitVec 256) («$fmp1» : BitVec 256) («$v6» : BitVec 256) («$v7» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v9» = «$input_calldatasize»)) + (h1 : («$v9» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v10» = (if («$v9» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v11» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v12» = (if («$v11» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v17» = («$v10» ||| «$v12»))) + (h6 : («$v18» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v16» = («$v18» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : (True ∧ ((«$v0» ≥ (0x0000000000000000000000000000000000000000000000000000000000000080#256)) ∧ («$v0» ≤ (0x000000000000000000000000000000000000000000000003ffffffffffffffff#256))))) + (h9 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$fmp1»)))) + (h10 : («$v6» = («$v18» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h11 : («$v7» = (if («$v6» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h12 : («$v17» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h13 : (¬(«$v16» = «$v18»))) + : False := by + try subst h9 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.B4 diff --git a/SolidCore/Refinement/Facts/B5.lean b/SolidCore/Refinement/Facts/B5.lean new file mode 100644 index 00000000..4a785175 --- /dev/null +++ b/SolidCore/Refinement/Facts/B5.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/b5.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `b5.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 1. Proved by Z3: 1. Checked in Lean by the prover and +emitted here: 1. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.B5 + +/-- Contract `Main`, function `#0 f`, fact 0: `check_elim v43 eq v47 at the end of bb11`, its left +operand defined by `and`. Query `Main-f0-bb11-v43-check_elim-0.smt2`. -/ +theorem f0_f_bb11_v43_check_elim_0 («$v36» : BitVec 256) («$v37» : BitVec 256) («$v38» : BitVec 256) («$v39» : BitVec 256) («$v46» : BitVec 256) («$v47» : BitVec 256) («$v43» : BitVec 256) («$v0» : BitVec 256) («$v1» : BitVec 256) («$v2» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v5» : BitVec 256) («$v41» : BitVec 256) («$v45» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$mem4» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v36» = «$input_calldatasize»)) + (h1 : («$v36» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v37» = (if («$v36» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v38» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v39» = (if («$v38» > (0x0000000000000000000000000000000000000000000000000000000000000001#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v46» = («$v37» ||| «$v39»))) + (h6 : («$v47» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v43» = («$v47» &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h8 : («$v0» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h10 : («$v1» = (if ((0x0000000000000000000000000000000000000000000000000000000000000005#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v0» >>> (0x0000000000000000000000000000000000000000000000000000000000000005#256))))) + (h11 : («$v2» = («$v0» &&& (0x000000000000000000000000000000000000000000000000000000000000001f#256)))) + (h12 : («$v3» = (if («$v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$v4» = «$v3»)) + (h14 : («$v5» = («$v1» + «$v4»))) + (h15 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))))) + (h16 : («$v45» = ((0x0000000000000000000000000000000000000000000000000000000000000000#256) - «$v5»))) + (h17 : («$v46» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h18 : (¬(«$v43» = «$v47»))) + : False := by + try subst h9 + try subst h15 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.B5 diff --git a/SolidCore/Refinement/Facts/B6.lean b/SolidCore/Refinement/Facts/B6.lean new file mode 100644 index 00000000..d2dbd892 --- /dev/null +++ b/SolidCore/Refinement/Facts/B6.lean @@ -0,0 +1,193 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/b6.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `b6.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 3. Proved by Z3: 3. Checked in Lean by the prover and +emitted here: 3. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +- `cse`: a memory, storage or transient read CSE forwarded from an earlier value. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.B6 + +/-- Contract `Main`, function `#0 f`, fact 0: `cse v9 eq v9 at the end of bb4`, its left operand +defined by `icall`. Query `Main-f0-bb4-v9-cse-0.smt2`. The query assumes the backend axioms +`allocation`. Its goal depends on the unconstrained values `v9`. -/ +theorem f0_f_bb4_v9_cse_0 («$v44» : BitVec 256) («$v45» : BitVec 256) («$v46» : BitVec 256) («$v47» : BitVec 256) («$v58» : BitVec 256) («$v59» : BitVec 256) («$v55» : BitVec 256) («$v0» : BitVec 256) («$v1» : BitVec 256) («$v2» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v5» : BitVec 256) («$v49» : BitVec 256) («$v57» : BitVec 256) («$j5_0_v37» : BitVec 256) («$j5_0_in70_1» : BitVec 256) («$j5_0_v38» : BitVec 256) («$j5_0_in71_1» : BitVec 256) («$j5_0_v39» : BitVec 256) («$j5_0_v40» : BitVec 256) («$j5_0_v41» : BitVec 256) («$v37» : BitVec 256) («$v38» : BitVec 256) («$v39» : BitVec 256) («$v56» : BitVec 256) («$v6» : BitVec 256) («$fmp1» : BitVec 256) («$v20» : BitVec 256) («$v60» : BitVec 256) («$v21» : BitVec 256) («$v22» : BitVec 256) («$v24» : BitVec 256) («$v25» : BitVec 256) («$v26» : BitVec 256) («$v27» : BitVec 256) («$v28» : BitVec 256) («$v29» : BitVec 256) («$v30» : BitVec 256) («$v31» : BitVec 256) («$v32» : BitVec 256) («$v33» : BitVec 256) («$v9» : BitVec 256) («$v13» : BitVec 256) («$word2» : BitVec 256) («$v42» : BitVec 256) («$v43» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$mem4» : (BitVec 256 → BitVec 8)) («$mem5» : (BitVec 256 → BitVec 8)) («$sto6» : (BitVec 256 → BitVec 256)) («$tra7» : (BitVec 256 → BitVec 256)) («$j5_0_mem8» : (BitVec 256 → BitVec 8)) («$j5_0_sto9» : (BitVec 256 → BitVec 256)) («$j5_0_tra10» : (BitVec 256 → BitVec 256)) («$j5_0_sto11» : (BitVec 256 → BitVec 256)) («$mem12» : (BitVec 256 → BitVec 8)) («$sto13» : (BitVec 256 → BitVec 256)) («$sto14» : (BitVec 256 → BitVec 256)) («$mem15» : (BitVec 256 → BitVec 8)) («$sto16» : (BitVec 256 → BitVec 256)) («$tra17» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v44» = «$input_calldatasize»)) + (h1 : («$v44» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v45» = (if («$v44» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v46» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v47» = (if («$v46» > (0x0000000000000000000000000000000000000000000000000000000000000001#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v58» = («$v45» ||| «$v47»))) + (h6 : («$v59» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v55» = («$v59» &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h8 : («$v0» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h10 : («$v1» = (if ((0x0000000000000000000000000000000000000000000000000000000000000005#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v0» >>> (0x0000000000000000000000000000000000000000000000000000000000000005#256))))) + (h11 : («$v2» = («$v0» &&& (0x000000000000000000000000000000000000000000000000000000000000001f#256)))) + (h12 : («$v3» = (if («$v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$v4» = «$v3»)) + (h14 : («$v5» = («$v1» + «$v4»))) + (h15 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))))) + (h16 : («$v57» = ((0x0000000000000000000000000000000000000000000000000000000000000000#256) - «$v5»))) + (h17 : («$v58» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h18 : (False ∨ ((True ∧ ((False ∨ ((«$j5_0_v37» = «$v57») ∨ (True ∧ («$j5_0_v37» = «$j5_0_in70_1»)))) ∧ ((False ∨ ((«$j5_0_v38» = «$v49») ∨ (True ∧ («$j5_0_v38» = «$j5_0_in71_1»)))) ∧ ((«$j5_0_v39» = (if («$j5_0_v37» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((«$j5_0_sto11» = (store «$j5_0_sto9» «$j5_0_v38» (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j5_0_v40» = («$j5_0_v37» + (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((«$j5_0_v41» = («$j5_0_v38» + (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((¬(«$j5_0_v39» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$mem5» = «$j5_0_mem8») ∧ ((«$sto6» = «$j5_0_sto11») ∧ ((«$tra7» = «$j5_0_tra10») ∧ ((«$v37» = «$j5_0_v40») ∧ («$v38» = «$j5_0_v41»))))))))))))) ∨ (True ∧ ((«$mem5» = «$mem4») ∧ ((«$sto6» = «$sto3») ∧ ((«$tra7» = «$tra0») ∧ ((«$v37» = «$v57») ∧ («$v38» = «$v49»))))))))) + (h19 : («$v39» = (if («$v37» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h20 : («$v56» = (if («$v59» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h21 : («$v39» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h22 : (True ∧ ((«$v6» ≥ (0x0000000000000000000000000000000000000000000000000000000000000080#256)) ∧ («$v6» ≤ (0x000000000000000000000000000000000000000000000003ffffffffffffffff#256))))) + (h23 : («$mem12» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem5» ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$fmp1»)))) + (h24 : («$v20» = («$sto6» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h25 : («$v60» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v20» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h26 : («$v21» = (if («$v60» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h27 : (¬(«$v56» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h28 : («$v22» = («$v20» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h29 : («$v24» = (if ((0x0000000000000000000000000000000000000000000000000000000000000005#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v20» >>> (0x0000000000000000000000000000000000000000000000000000000000000005#256))))) + (h30 : («$v25» = («$v49» + «$v24»))) + (h31 : («$v26» = («$v20» &&& (0x000000000000000000000000000000000000000000000000000000000000001f#256)))) + (h32 : («$v27» = (if ((0x0000000000000000000000000000000000000000000000000000000000000003#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v26» <<< (0x0000000000000000000000000000000000000000000000000000000000000003#256))))) + (h33 : («$v28» = (if («$v27» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((0x00000000000000000000000000000000000000000000000000000000000000ff#256) <<< «$v27»)))) + (h34 : («$v29» = («$sto6» «$v25»))) + (h35 : («$v30» = (~~~«$v28»))) + (h36 : («$v31» = («$v29» &&& «$v30»))) + (h37 : («$v32» = (if («$v27» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((0x0000000000000000000000000000000000000000000000000000000000000007#256) <<< «$v27»)))) + (h38 : («$v33» = («$v31» ||| «$v32»))) + (h39 : («$sto13» = (store «$sto6» «$v25» «$v33»))) + (h40 : («$sto14» = (store «$sto13» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v22»))) + (h41 : («$v13» = «$word2»)) + (h42 : («$v42» = («$v13» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h43 : («$v43» = (if («$v42» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h44 : («$v21» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h45 : («$v55» = «$v59»)) + (h46 : (¬(«$v9» = «$v9»))) + : False := by + have v18 : (False ∨ ((True ∧ ((False ∨ ((«$j5_0_v37» = «$v57») ∨ (True ∧ («$j5_0_v37» = «$j5_0_in70_1»)))) ∧ ((False ∨ ((«$j5_0_v38» = «$v49») ∨ (True ∧ («$j5_0_v38» = «$j5_0_in71_1»)))) ∧ ((«$j5_0_v39» = (if («$j5_0_v37» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((((«$j5_0_sto11» (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = ((store «$j5_0_sto9» «$j5_0_v38» (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j5_0_sto11» «$v25») = ((store «$j5_0_sto9» «$j5_0_v38» (0x0000000000000000000000000000000000000000000000000000000000000000#256)) «$v25»))) ∧ ((«$j5_0_v40» = («$j5_0_v37» + (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((«$j5_0_v41» = («$j5_0_v38» + (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((¬(«$j5_0_v39» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ (True ∧ ((((«$sto6» (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = («$j5_0_sto11» (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$sto6» «$v25») = («$j5_0_sto11» «$v25»))) ∧ (True ∧ ((«$v37» = «$j5_0_v40») ∧ («$v38» = «$j5_0_v41»))))))))))))) ∨ (True ∧ (True ∧ ((((«$sto6» (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$sto6» «$v25») = («$sto3» «$v25»))) ∧ (True ∧ ((«$v37» = «$v57») ∧ («$v38» = «$v49»)))))))) := (Or.imp id (Or.imp (fun ⟨w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13⟩ => ⟨id w1, id w2, id w3, id w4, (fun e => ⟨congrFun e (0x0000000000000000000000000000000000000000000000000000000000000000#256), congrFun e «$v25»⟩) w5, id w6, id w7, id w8, (fun _ => trivial) w9, (fun e => ⟨congrFun e (0x0000000000000000000000000000000000000000000000000000000000000000#256), congrFun e «$v25»⟩) w10, (fun _ => trivial) w11, id w12, id w13⟩) (fun ⟨w14, w15, w16, w17, w18, w19⟩ => ⟨id w14, (fun _ => trivial) w15, (fun e => ⟨congrFun e (0x0000000000000000000000000000000000000000000000000000000000000000#256), congrFun e «$v25»⟩) w16, (fun _ => trivial) w17, id w18, id w19⟩))) h18 + clear h18 + have ack0 : (0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$v25» → «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$sto0» «$v25» := fun e0 => congrArg «$sto0» e0 + have ack1 : (0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$v25» → «$sto6» (0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$sto6» «$v25» := fun e0 => congrArg «$sto6» e0 + have ack2 : (0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$v25» → «$j5_0_sto11» (0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$j5_0_sto11» «$v25» := fun e0 => congrArg «$j5_0_sto11» e0 + have ack3 : (0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$v25» → «$j5_0_sto9» (0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$j5_0_sto9» «$v25» := fun e0 => congrArg «$j5_0_sto9» e0 + try subst h9 + try subst h15 + try subst h23 + try subst h39 + try subst h40 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 1: `cse v9 eq v9 at the end of bb4`, its left operand +defined by `icall`. Query `Main-f0-bb4-v9-cse-1.smt2`. The query assumes the backend axioms +`allocation`. Its goal depends on the unconstrained values `v9`. -/ +theorem f0_f_bb4_v9_cse_1 («$v44» : BitVec 256) («$v45» : BitVec 256) («$v46» : BitVec 256) («$v47» : BitVec 256) («$v58» : BitVec 256) («$v59» : BitVec 256) («$v55» : BitVec 256) («$v0» : BitVec 256) («$v1» : BitVec 256) («$v2» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v5» : BitVec 256) («$v49» : BitVec 256) («$v57» : BitVec 256) («$j5_0_v37» : BitVec 256) («$j5_0_in70_1» : BitVec 256) («$j5_0_v38» : BitVec 256) («$j5_0_in71_1» : BitVec 256) («$j5_0_v39» : BitVec 256) («$j5_0_v40» : BitVec 256) («$j5_0_v41» : BitVec 256) («$v37» : BitVec 256) («$v38» : BitVec 256) («$v39» : BitVec 256) («$v56» : BitVec 256) («$v6» : BitVec 256) («$fmp1» : BitVec 256) («$v20» : BitVec 256) («$v60» : BitVec 256) («$v21» : BitVec 256) («$v22» : BitVec 256) («$v24» : BitVec 256) («$v25» : BitVec 256) («$v26» : BitVec 256) («$v27» : BitVec 256) («$v28» : BitVec 256) («$v29» : BitVec 256) («$v30» : BitVec 256) («$v31» : BitVec 256) («$v32» : BitVec 256) («$v33» : BitVec 256) («$v9» : BitVec 256) («$v13» : BitVec 256) («$word2» : BitVec 256) («$v42» : BitVec 256) («$v43» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$mem4» : (BitVec 256 → BitVec 8)) («$mem5» : (BitVec 256 → BitVec 8)) («$sto6» : (BitVec 256 → BitVec 256)) («$tra7» : (BitVec 256 → BitVec 256)) («$j5_0_mem8» : (BitVec 256 → BitVec 8)) («$j5_0_sto9» : (BitVec 256 → BitVec 256)) («$j5_0_tra10» : (BitVec 256 → BitVec 256)) («$j5_0_sto11» : (BitVec 256 → BitVec 256)) («$mem12» : (BitVec 256 → BitVec 8)) («$sto13» : (BitVec 256 → BitVec 256)) («$sto14» : (BitVec 256 → BitVec 256)) («$mem15» : (BitVec 256 → BitVec 8)) («$sto16» : (BitVec 256 → BitVec 256)) («$tra17» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v44» = «$input_calldatasize»)) + (h1 : («$v44» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v45» = (if («$v44» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v46» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v47» = (if («$v46» > (0x0000000000000000000000000000000000000000000000000000000000000001#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v58» = («$v45» ||| «$v47»))) + (h6 : («$v59» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v55» = («$v59» &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h8 : («$v0» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h10 : («$v1» = (if ((0x0000000000000000000000000000000000000000000000000000000000000005#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v0» >>> (0x0000000000000000000000000000000000000000000000000000000000000005#256))))) + (h11 : («$v2» = («$v0» &&& (0x000000000000000000000000000000000000000000000000000000000000001f#256)))) + (h12 : («$v3» = (if («$v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$v4» = «$v3»)) + (h14 : («$v5» = («$v1» + «$v4»))) + (h15 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))))) + (h16 : («$v57» = ((0x0000000000000000000000000000000000000000000000000000000000000000#256) - «$v5»))) + (h17 : («$v58» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h18 : (False ∨ ((True ∧ ((False ∨ ((«$j5_0_v37» = «$v57») ∨ (True ∧ («$j5_0_v37» = «$j5_0_in70_1»)))) ∧ ((False ∨ ((«$j5_0_v38» = «$v49») ∨ (True ∧ («$j5_0_v38» = «$j5_0_in71_1»)))) ∧ ((«$j5_0_v39» = (if («$j5_0_v37» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((«$j5_0_sto11» = (store «$j5_0_sto9» «$j5_0_v38» (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j5_0_v40» = («$j5_0_v37» + (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((«$j5_0_v41» = («$j5_0_v38» + (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((¬(«$j5_0_v39» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$mem5» = «$j5_0_mem8») ∧ ((«$sto6» = «$j5_0_sto11») ∧ ((«$tra7» = «$j5_0_tra10») ∧ ((«$v37» = «$j5_0_v40») ∧ («$v38» = «$j5_0_v41»))))))))))))) ∨ (True ∧ ((«$mem5» = «$mem4») ∧ ((«$sto6» = «$sto3») ∧ ((«$tra7» = «$tra0») ∧ ((«$v37» = «$v57») ∧ («$v38» = «$v49»))))))))) + (h19 : («$v39» = (if («$v37» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h20 : («$v56» = (if («$v59» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h21 : («$v39» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h22 : (True ∧ ((«$v6» ≥ (0x0000000000000000000000000000000000000000000000000000000000000080#256)) ∧ («$v6» ≤ (0x000000000000000000000000000000000000000000000003ffffffffffffffff#256))))) + (h23 : («$mem12» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem5» ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$fmp1»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$fmp1»)))) + (h24 : («$v20» = («$sto6» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h25 : («$v60» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v20» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h26 : («$v21» = (if («$v60» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h27 : (¬(«$v56» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h28 : («$v22» = («$v20» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h29 : («$v24» = (if ((0x0000000000000000000000000000000000000000000000000000000000000005#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v20» >>> (0x0000000000000000000000000000000000000000000000000000000000000005#256))))) + (h30 : («$v25» = («$v49» + «$v24»))) + (h31 : («$v26» = («$v20» &&& (0x000000000000000000000000000000000000000000000000000000000000001f#256)))) + (h32 : («$v27» = (if ((0x0000000000000000000000000000000000000000000000000000000000000003#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v26» <<< (0x0000000000000000000000000000000000000000000000000000000000000003#256))))) + (h33 : («$v28» = (if («$v27» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((0x00000000000000000000000000000000000000000000000000000000000000ff#256) <<< «$v27»)))) + (h34 : («$v29» = («$sto6» «$v25»))) + (h35 : («$v30» = (~~~«$v28»))) + (h36 : («$v31» = («$v29» &&& «$v30»))) + (h37 : («$v32» = (if («$v27» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((0x0000000000000000000000000000000000000000000000000000000000000007#256) <<< «$v27»)))) + (h38 : («$v33» = («$v31» ||| «$v32»))) + (h39 : («$sto13» = (store «$sto6» «$v25» «$v33»))) + (h40 : («$sto14» = (store «$sto13» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v22»))) + (h41 : («$v13» = «$word2»)) + (h42 : («$v42» = («$v13» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h43 : («$v43» = (if («$v42» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h44 : («$v21» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h45 : («$v9» = «$v9»)) + (h46 : («$v55» = «$v59»)) + (h47 : (¬(«$v9» = «$v9»))) + : False := by + have v18 : (False ∨ ((True ∧ ((False ∨ ((«$j5_0_v37» = «$v57») ∨ (True ∧ («$j5_0_v37» = «$j5_0_in70_1»)))) ∧ ((False ∨ ((«$j5_0_v38» = «$v49») ∨ (True ∧ («$j5_0_v38» = «$j5_0_in71_1»)))) ∧ ((«$j5_0_v39» = (if («$j5_0_v37» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((((«$j5_0_sto11» (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = ((store «$j5_0_sto9» «$j5_0_v38» (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j5_0_sto11» «$v25») = ((store «$j5_0_sto9» «$j5_0_v38» (0x0000000000000000000000000000000000000000000000000000000000000000#256)) «$v25»))) ∧ ((«$j5_0_v40» = («$j5_0_v37» + (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((«$j5_0_v41» = («$j5_0_v38» + (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((¬(«$j5_0_v39» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ (True ∧ ((((«$sto6» (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = («$j5_0_sto11» (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$sto6» «$v25») = («$j5_0_sto11» «$v25»))) ∧ (True ∧ ((«$v37» = «$j5_0_v40») ∧ («$v38» = «$j5_0_v41»))))))))))))) ∨ (True ∧ (True ∧ ((((«$sto6» (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$sto6» «$v25») = («$sto3» «$v25»))) ∧ (True ∧ ((«$v37» = «$v57») ∧ («$v38» = «$v49»)))))))) := (Or.imp id (Or.imp (fun ⟨w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13⟩ => ⟨id w1, id w2, id w3, id w4, (fun e => ⟨congrFun e (0x0000000000000000000000000000000000000000000000000000000000000000#256), congrFun e «$v25»⟩) w5, id w6, id w7, id w8, (fun _ => trivial) w9, (fun e => ⟨congrFun e (0x0000000000000000000000000000000000000000000000000000000000000000#256), congrFun e «$v25»⟩) w10, (fun _ => trivial) w11, id w12, id w13⟩) (fun ⟨w14, w15, w16, w17, w18, w19⟩ => ⟨id w14, (fun _ => trivial) w15, (fun e => ⟨congrFun e (0x0000000000000000000000000000000000000000000000000000000000000000#256), congrFun e «$v25»⟩) w16, (fun _ => trivial) w17, id w18, id w19⟩))) h18 + clear h18 + have ack0 : (0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$v25» → «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$sto0» «$v25» := fun e0 => congrArg «$sto0» e0 + have ack1 : (0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$v25» → «$sto6» (0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$sto6» «$v25» := fun e0 => congrArg «$sto6» e0 + have ack2 : (0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$v25» → «$j5_0_sto11» (0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$j5_0_sto11» «$v25» := fun e0 => congrArg «$j5_0_sto11» e0 + have ack3 : (0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$v25» → «$j5_0_sto9» (0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$j5_0_sto9» «$v25» := fun e0 => congrArg «$j5_0_sto9» e0 + try subst h9 + try subst h15 + try subst h23 + try subst h39 + try subst h40 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 2: `check_elim v55 eq v59 at the end of bb11`, its left +operand defined by `and`. Query `Main-f0-bb11-v55-check_elim-2.smt2`. -/ +theorem f0_f_bb11_v55_check_elim_2 («$v44» : BitVec 256) («$v45» : BitVec 256) («$v46» : BitVec 256) («$v47» : BitVec 256) («$v58» : BitVec 256) («$v59» : BitVec 256) («$v55» : BitVec 256) («$v0» : BitVec 256) («$v1» : BitVec 256) («$v2» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v5» : BitVec 256) («$v49» : BitVec 256) («$v57» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$mem4» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v44» = «$input_calldatasize»)) + (h1 : («$v44» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v45» = (if («$v44» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v46» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v47» = (if («$v46» > (0x0000000000000000000000000000000000000000000000000000000000000001#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v58» = («$v45» ||| «$v47»))) + (h6 : («$v59» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v55» = («$v59» &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h8 : («$v0» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h10 : («$v1» = (if ((0x0000000000000000000000000000000000000000000000000000000000000005#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v0» >>> (0x0000000000000000000000000000000000000000000000000000000000000005#256))))) + (h11 : («$v2» = («$v0» &&& (0x000000000000000000000000000000000000000000000000000000000000001f#256)))) + (h12 : («$v3» = (if («$v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$v4» = «$v3»)) + (h14 : («$v5» = («$v1» + «$v4»))) + (h15 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))))) + (h16 : («$v57» = ((0x0000000000000000000000000000000000000000000000000000000000000000#256) - «$v5»))) + (h17 : («$v58» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h18 : (¬(«$v55» = «$v59»))) + : False := by + try subst h9 + try subst h15 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.B6 diff --git a/SolidCore/Refinement/Facts/B7.lean b/SolidCore/Refinement/Facts/B7.lean new file mode 100644 index 00000000..cc9f25e7 --- /dev/null +++ b/SolidCore/Refinement/Facts/B7.lean @@ -0,0 +1,59 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/b7.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `b7.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 1. Proved by Z3: 1. Checked in Lean by the prover and +emitted here: 1. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.B7 + +/-- Contract `Main`, function `#0 f`, fact 0: `check_elim v48 eq v52 at the end of bb11`, its left +operand defined by `and`. Query `Main-f0-bb11-v48-check_elim-0.smt2`. -/ +theorem f0_f_bb11_v48_check_elim_0 («$v41» : BitVec 256) («$v42» : BitVec 256) («$v43» : BitVec 256) («$v44» : BitVec 256) («$v51» : BitVec 256) («$v52» : BitVec 256) («$v48» : BitVec 256) («$v0» : BitVec 256) («$v1» : BitVec 256) («$v2» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v5» : BitVec 256) («$v46» : BitVec 256) («$v50» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$mem4» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v41» = «$input_calldatasize»)) + (h1 : («$v41» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v42» = (if («$v41» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v43» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v44» = (if («$v43» > (0x0000000000000000000000000000000000000000000000000000000000000001#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v51» = («$v42» ||| «$v44»))) + (h6 : («$v52» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v48» = («$v52» &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h8 : («$v0» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h10 : («$v1» = (if ((0x0000000000000000000000000000000000000000000000000000000000000005#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v0» >>> (0x0000000000000000000000000000000000000000000000000000000000000005#256))))) + (h11 : («$v2» = («$v0» &&& (0x000000000000000000000000000000000000000000000000000000000000001f#256)))) + (h12 : («$v3» = (if («$v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$v4» = «$v3»)) + (h14 : («$v5» = («$v1» + «$v4»))) + (h15 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))))) + (h16 : («$v50» = ((0x0000000000000000000000000000000000000000000000000000000000000000#256) - «$v5»))) + (h17 : («$v51» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h18 : (¬(«$v48» = «$v52»))) + : False := by + try subst h9 + try subst h15 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.B7 diff --git a/SolidCore/Refinement/Facts/C1.lean b/SolidCore/Refinement/Facts/C1.lean new file mode 100644 index 00000000..6c9e9507 --- /dev/null +++ b/SolidCore/Refinement/Facts/C1.lean @@ -0,0 +1,103 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/c1.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `c1.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 3. Proved by Z3: 3. Checked in Lean by the prover and +emitted here: 3. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.C1 + +/-- Contract `Main`, function `#0 f`, fact 0: `check_elim v16 eq v3 at the end of bb2`, its left +operand defined by `and`. Query `Main-f0-bb2-v16-check_elim-0.smt2`. -/ +theorem f0_f_bb2_v16_check_elim_0 («$v10» : BitVec 256) («$v11» : BitVec 256) («$v12» : BitVec 256) («$v13» : BitVec 256) («$v19» : BitVec 256) («$v20» : BitVec 256) («$v18» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v16» : BitVec 256) («$v7» : BitVec 256) («$v8» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v10» = «$input_calldatasize»)) + (h1 : («$v10» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v11» = (if («$v10» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v12» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v13» = (if («$v12» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v19» = («$v11» ||| «$v13»))) + (h6 : («$v20» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v18» = («$v20» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v3» = («$v20» * (0x0000000000000000000000000000000000000000000000000000000000000003#256)))) + (h9 : («$v4» = (if («$v3» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h10 : («$v19» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h11 : («$v16» = («$v3» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h12 : («$v7» = («$v3» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$v8» = (if («$v7» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h14 : («$v4» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h15 : («$v18» = «$v20»)) + (h16 : (¬(«$v16» = «$v3»))) + : False := by + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 1: `check_elim v17 eq v7 at the end of bb3`, its left +operand defined by `and`. Query `Main-f0-bb3-v17-check_elim-1.smt2`. -/ +theorem f0_f_bb3_v17_check_elim_1 («$v10» : BitVec 256) («$v11» : BitVec 256) («$v12» : BitVec 256) («$v13» : BitVec 256) («$v19» : BitVec 256) («$v20» : BitVec 256) («$v18» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v16» : BitVec 256) («$v7» : BitVec 256) («$v8» : BitVec 256) («$v17» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v10» = «$input_calldatasize»)) + (h1 : («$v10» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v11» = (if («$v10» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v12» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v13» = (if («$v12» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v19» = («$v11» ||| «$v13»))) + (h6 : («$v20» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v18» = («$v20» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v3» = («$v20» * (0x0000000000000000000000000000000000000000000000000000000000000003#256)))) + (h9 : («$v4» = (if («$v3» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h10 : («$v19» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h11 : («$v16» = («$v3» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h12 : («$v7» = («$v3» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$v8» = (if («$v7» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h14 : («$v4» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h15 : («$v17» = («$v7» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h16 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v7»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v7»)))) + (h17 : («$v8» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h18 : («$v16» = «$v3»)) + (h19 : («$v18» = «$v20»)) + (h20 : (¬(«$v17» = «$v7»))) + : False := by + try subst h16 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 2: `check_elim v18 eq v20 at the end of bb5`, its left +operand defined by `and`. Query `Main-f0-bb5-v18-check_elim-2.smt2`. -/ +theorem f0_f_bb5_v18_check_elim_2 («$v10» : BitVec 256) («$v11» : BitVec 256) («$v12» : BitVec 256) («$v13» : BitVec 256) («$v19» : BitVec 256) («$v20» : BitVec 256) («$v18» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v10» = «$input_calldatasize»)) + (h1 : («$v10» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v11» = (if («$v10» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v12» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v13» = (if («$v12» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v19» = («$v11» ||| «$v13»))) + (h6 : («$v20» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v18» = («$v20» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v3» = («$v20» * (0x0000000000000000000000000000000000000000000000000000000000000003#256)))) + (h9 : («$v4» = (if («$v3» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h10 : («$v19» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h11 : (¬(«$v18» = «$v20»))) + : False := by + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.C1 diff --git a/SolidCore/Refinement/Facts/C10.lean b/SolidCore/Refinement/Facts/C10.lean new file mode 100644 index 00000000..38ebbda5 --- /dev/null +++ b/SolidCore/Refinement/Facts/C10.lean @@ -0,0 +1,52 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/c10.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `c10.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 1. Proved by Z3: 1. Checked in Lean by the prover and +emitted here: 1. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.C10 + +/-- Contract `Main`, function `#0 f`, fact 0: `check_elim v8 eq v10 at the end of bb2`, its left +operand defined by `and`. Query `Main-f0-bb2-v8-check_elim-0.smt2`. -/ +theorem f0_f_bb2_v8_check_elim_0 («$v3» : BitVec 256) («$v4» : BitVec 256) («$v5» : BitVec 256) («$v6» : BitVec 256) («$v9» : BitVec 256) («$v10» : BitVec 256) («$v8» : BitVec 256) («$v1» : BitVec 256) («$v2» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v3» = «$input_calldatasize»)) + (h1 : («$v3» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v4» = (if («$v3» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v5» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v6» = (if («$v5» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v9» = («$v4» ||| «$v6»))) + (h6 : («$v10» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v8» = («$v10» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v1» = (if («$v10» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((0x1234000000000000000000000000000000000000000000000000000000000000#256) >>> «$v10»)))) + (h9 : («$v2» = («$v1» &&& (0xffff000000000000000000000000000000000000000000000000000000000000#256)))) + (h10 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v2»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v2»)))) + (h11 : («$v9» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h12 : (¬(«$v8» = «$v10»))) + : False := by + try subst h10 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.C10 diff --git a/SolidCore/Refinement/Facts/C11.lean b/SolidCore/Refinement/Facts/C11.lean new file mode 100644 index 00000000..b732a232 --- /dev/null +++ b/SolidCore/Refinement/Facts/C11.lean @@ -0,0 +1,51 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/c11.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `c11.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 1. Proved by Z3: 1. Checked in Lean by the prover and +emitted here: 1. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.C11 + +/-- Contract `Main`, function `#0 f`, fact 0: `check_elim v7 eq v9 at the end of bb2`, its left +operand defined by `and`. Query `Main-f0-bb2-v7-check_elim-0.smt2`. -/ +theorem f0_f_bb2_v7_check_elim_0 («$v0» : BitVec 256) («$v1» : BitVec 256) («$v2» : BitVec 256) («$v3» : BitVec 256) («$v8» : BitVec 256) («$v9» : BitVec 256) («$v7» : BitVec 256) («$v6» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v0» = «$input_calldatasize»)) + (h1 : («$v0» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v1» = (if («$v0» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v2» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v3» = (if («$v2» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v8» = («$v1» ||| «$v3»))) + (h6 : («$v9» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v7» = («$v9» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v6» = (if ((0x0000000000000000000000000000000000000000000000000000000000000000#256) ≥ (0x000000000000000000000000000000000000000000000000000000000000001f#256)) then «$v9» else (BitVec.sshiftRight' («$v9» <<< ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256))))))) + (h9 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v6»)))) + (h10 : («$v8» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h11 : (¬(«$v7» = «$v9»))) + : False := by + try subst h9 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.C11 diff --git a/SolidCore/Refinement/Facts/C2.lean b/SolidCore/Refinement/Facts/C2.lean new file mode 100644 index 00000000..a946137e --- /dev/null +++ b/SolidCore/Refinement/Facts/C2.lean @@ -0,0 +1,67 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/c2.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `c2.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 1. Proved by Z3: 1. Checked in Lean by the prover and +emitted here: 1. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.C2 + +/-- Contract `Main`, function `#0 f`, fact 0: `check_elim v6 ne 0x0 at the end of bb4`, its left +operand defined by `ne`. Query `Main-f0-bb4-v6-check_elim-0.smt2`. -/ +theorem f0_f_bb4_v6_check_elim_0 («$v18» : BitVec 256) («$v19» : BitVec 256) («$v20» : BitVec 256) («$v21» : BitVec 256) («$v38» : BitVec 256) («$v39» : BitVec 256) («$v40» : BitVec 256) («$v23» : BitVec 256) («$v24» : BitVec 256) («$v42» : BitVec 256) («$v43» : BitVec 256) («$v44» : BitVec 256) («$v6» : BitVec 256) («$v7» : BitVec 256) («$v8» : BitVec 256) («$v9» : BitVec 256) («$v11» : BitVec 256) («$v16» : BitVec 256) («$v29» : BitVec 256) («$v31» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$mem4» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v18» = «$input_calldatasize»)) + (h1 : («$v18» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v19» = (if («$v18» < (0x0000000000000000000000000000000000000000000000000000000000000044#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v20» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v21» = (if ((0x0000000000000000000000000000000000000000000000000000000000000000#256) ≥ (0x000000000000000000000000000000000000000000000000000000000000001f#256)) then «$v20» else (BitVec.sshiftRight' («$v20» <<< ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256))))))) + (h5 : («$v38» = «$v19»)) + (h6 : («$v39» = («$v20» ^^^ «$v21»))) + (h7 : («$v40» = («$v39» ||| «$v38»))) + (h8 : («$v23» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h9 : («$v24» = (if ((0x0000000000000000000000000000000000000000000000000000000000000000#256) ≥ (0x000000000000000000000000000000000000000000000000000000000000001f#256)) then «$v23» else (BitVec.sshiftRight' («$v23» <<< ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256))))))) + (h10 : («$v42» = («$v23» ^^^ «$v24»))) + (h11 : («$v43» = («$v40» ||| «$v42»))) + (h12 : («$v44» = (if («$v43» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$v6» = (if («$v24» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h14 : («$v44» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h15 : («$v7» = (if («$v21» = (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff80#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h16 : («$v8» = (if («$v24» = (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h17 : («$v9» = («$v7» &&& «$v8»))) + (h18 : (¬(«$v6» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h19 : («$v11» = (if («$v24» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtSDiv «$v21» «$v24»)))) + (h20 : («$v16» = (if («$v24» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.srem «$v21» «$v24»)))) + (h21 : («$v29» = (if ((0x0000000000000000000000000000000000000000000000000000000000000000#256) ≥ (0x000000000000000000000000000000000000000000000000000000000000001f#256)) then «$v11» else (BitVec.sshiftRight' («$v11» <<< ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256))))))) + (h22 : («$v31» = (if ((0x0000000000000000000000000000000000000000000000000000000000000000#256) ≥ (0x000000000000000000000000000000000000000000000000000000000000001f#256)) then «$v16» else (BitVec.sshiftRight' («$v16» <<< ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256))))))) + (h23 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v29»)))) + (h24 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v31»)))) + (h25 : («$v9» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h26 : (¬(¬(«$v6» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))))) + : False := by + try subst h23 + try subst h24 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.C2 diff --git a/SolidCore/Refinement/Facts/C3.lean b/SolidCore/Refinement/Facts/C3.lean new file mode 100644 index 00000000..240b8d0e --- /dev/null +++ b/SolidCore/Refinement/Facts/C3.lean @@ -0,0 +1,154 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/c3.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `c3.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 3. Proved by Z3: 3. Checked in Lean by the prover and +emitted here: 3. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.C3 + +/-- Contract `Main`, function `#0 f`, fact 0: `check_elim v25 eq v40 at the end of bb2`, its left +operand defined by `and`. Query `Main-f0-bb2-v25-check_elim-0.smt2`. -/ +theorem f0_f_bb2_v25_check_elim_0 («$v12» : BitVec 256) («$v13» : BitVec 256) («$v14» : BitVec 256) («$v15» : BitVec 256) («$v38» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v39» : BitVec 256) («$v41» : BitVec 256) («$v40» : BitVec 256) («$v25» : BitVec 256) («$v26» : BitVec 256) («$v27» : BitVec 256) («$v28» : BitVec 256) («$v29» : BitVec 256) («$v30» : BitVec 256) («$v31» : BitVec 256) («$v32» : BitVec 256) («$v33» : BitVec 256) («$v35» : BitVec 256) («$v36» : BitVec 256) («$v21» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$mem4» : (BitVec 256 → BitVec 8)) («$mem5» : (BitVec 256 → BitVec 8)) («$mem6» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v12» = «$input_calldatasize»)) + (h1 : («$v12» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v13» = (if («$v12» < (0x0000000000000000000000000000000000000000000000000000000000000044#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v14» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v15» = (if («$v14» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v38» = («$v13» ||| «$v15»))) + (h6 : («$v16» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h7 : («$v17» = (if («$v16» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h8 : («$v39» = («$v38» ||| «$v17»))) + (h9 : («$v41» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h10 : («$v40» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h11 : («$v25» = («$v40» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h12 : («$v26» = («$v41» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h13 : («$v27» = (if («$v41» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v40» <<< «$v41»)))) + (h14 : («$v28» = («$v27» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h15 : («$v29» = (if («$v41» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v40» >>> «$v41»)))) + (h16 : («$v30» = («$v29» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h17 : («$v31» = («$v40» * «$v40»))) + (h18 : («$v32» = («$v31» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h19 : («$v33» = (if ((0x0000000000000000000000000000000000000000000000000000000000000009#256) = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$v41» (0x0000000000000000000000000000000000000000000000000000000000000009#256))))) + (h20 : («$v35» = (if ((0x0000000000000000000000000000000000000000000000000000000000000000#256) ≥ (0x000000000000000000000000000000000000000000000000000000000000001f#256)) then «$v40» else (BitVec.sshiftRight' («$v40» <<< ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256))))))) + (h21 : («$v36» = (if («$v33» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (BitVec.sshiftRight' «$v35» (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) else (BitVec.sshiftRight' «$v35» «$v33»)))) + (h22 : («$v21» = (if ((0x0000000000000000000000000000000000000000000000000000000000000000#256) ≥ (0x000000000000000000000000000000000000000000000000000000000000001f#256)) then «$v36» else (BitVec.sshiftRight' («$v36» <<< ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256))))))) + (h23 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v28»)))) + (h24 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v29»)))) + (h25 : («$mem5» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem4» ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v32»)))) + (h26 : («$mem6» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem5» ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v21»)))) + (h27 : («$v39» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h28 : (¬(«$v25» = «$v40»))) + : False := by + try subst h23 + try subst h24 + try subst h25 + try subst h26 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 1: `check_elim v26 eq v41 at the end of bb2`, its left +operand defined by `and`. Query `Main-f0-bb2-v26-check_elim-1.smt2`. -/ +theorem f0_f_bb2_v26_check_elim_1 («$v12» : BitVec 256) («$v13» : BitVec 256) («$v14» : BitVec 256) («$v15» : BitVec 256) («$v38» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v39» : BitVec 256) («$v41» : BitVec 256) («$v40» : BitVec 256) («$v25» : BitVec 256) («$v26» : BitVec 256) («$v27» : BitVec 256) («$v28» : BitVec 256) («$v29» : BitVec 256) («$v30» : BitVec 256) («$v31» : BitVec 256) («$v32» : BitVec 256) («$v33» : BitVec 256) («$v35» : BitVec 256) («$v36» : BitVec 256) («$v21» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$mem4» : (BitVec 256 → BitVec 8)) («$mem5» : (BitVec 256 → BitVec 8)) («$mem6» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v12» = «$input_calldatasize»)) + (h1 : («$v12» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v13» = (if («$v12» < (0x0000000000000000000000000000000000000000000000000000000000000044#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v14» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v15» = (if («$v14» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v38» = («$v13» ||| «$v15»))) + (h6 : («$v16» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h7 : («$v17» = (if («$v16» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h8 : («$v39» = («$v38» ||| «$v17»))) + (h9 : («$v41» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h10 : («$v40» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h11 : («$v25» = («$v40» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h12 : («$v26» = («$v41» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h13 : («$v27» = (if («$v41» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v40» <<< «$v41»)))) + (h14 : («$v28» = («$v27» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h15 : («$v29» = (if («$v41» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v40» >>> «$v41»)))) + (h16 : («$v30» = («$v29» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h17 : («$v31» = («$v40» * «$v40»))) + (h18 : («$v32» = («$v31» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h19 : («$v33» = (if ((0x0000000000000000000000000000000000000000000000000000000000000009#256) = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$v41» (0x0000000000000000000000000000000000000000000000000000000000000009#256))))) + (h20 : («$v35» = (if ((0x0000000000000000000000000000000000000000000000000000000000000000#256) ≥ (0x000000000000000000000000000000000000000000000000000000000000001f#256)) then «$v40» else (BitVec.sshiftRight' («$v40» <<< ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256))))))) + (h21 : («$v36» = (if («$v33» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (BitVec.sshiftRight' «$v35» (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) else (BitVec.sshiftRight' «$v35» «$v33»)))) + (h22 : («$v21» = (if ((0x0000000000000000000000000000000000000000000000000000000000000000#256) ≥ (0x000000000000000000000000000000000000000000000000000000000000001f#256)) then «$v36» else (BitVec.sshiftRight' («$v36» <<< ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256))))))) + (h23 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v28»)))) + (h24 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v29»)))) + (h25 : («$mem5» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem4» ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v32»)))) + (h26 : («$mem6» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem5» ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v21»)))) + (h27 : («$v39» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h28 : («$v25» = «$v40»)) + (h29 : (¬(«$v26» = «$v41»))) + : False := by + try subst h23 + try subst h24 + try subst h25 + try subst h26 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 2: `check_elim v30 eq v29 at the end of bb2`, its left +operand defined by `and`. Query `Main-f0-bb2-v30-check_elim-2.smt2`. -/ +theorem f0_f_bb2_v30_check_elim_2 («$v12» : BitVec 256) («$v13» : BitVec 256) («$v14» : BitVec 256) («$v15» : BitVec 256) («$v38» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v39» : BitVec 256) («$v41» : BitVec 256) («$v40» : BitVec 256) («$v25» : BitVec 256) («$v26» : BitVec 256) («$v27» : BitVec 256) («$v28» : BitVec 256) («$v29» : BitVec 256) («$v30» : BitVec 256) («$v31» : BitVec 256) («$v32» : BitVec 256) («$v33» : BitVec 256) («$v35» : BitVec 256) («$v36» : BitVec 256) («$v21» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$mem4» : (BitVec 256 → BitVec 8)) («$mem5» : (BitVec 256 → BitVec 8)) («$mem6» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v12» = «$input_calldatasize»)) + (h1 : («$v12» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v13» = (if («$v12» < (0x0000000000000000000000000000000000000000000000000000000000000044#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v14» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v15» = (if («$v14» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v38» = («$v13» ||| «$v15»))) + (h6 : («$v16» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h7 : («$v17» = (if («$v16» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h8 : («$v39» = («$v38» ||| «$v17»))) + (h9 : («$v41» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h10 : («$v40» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h11 : («$v25» = («$v40» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h12 : («$v26» = («$v41» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h13 : («$v27» = (if («$v41» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v40» <<< «$v41»)))) + (h14 : («$v28» = («$v27» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h15 : («$v29» = (if («$v41» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v40» >>> «$v41»)))) + (h16 : («$v30» = («$v29» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h17 : («$v31» = («$v40» * «$v40»))) + (h18 : («$v32» = («$v31» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h19 : («$v33» = (if ((0x0000000000000000000000000000000000000000000000000000000000000009#256) = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$v41» (0x0000000000000000000000000000000000000000000000000000000000000009#256))))) + (h20 : («$v35» = (if ((0x0000000000000000000000000000000000000000000000000000000000000000#256) ≥ (0x000000000000000000000000000000000000000000000000000000000000001f#256)) then «$v40» else (BitVec.sshiftRight' («$v40» <<< ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256))))))) + (h21 : («$v36» = (if («$v33» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (BitVec.sshiftRight' «$v35» (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) else (BitVec.sshiftRight' «$v35» «$v33»)))) + (h22 : («$v21» = (if ((0x0000000000000000000000000000000000000000000000000000000000000000#256) ≥ (0x000000000000000000000000000000000000000000000000000000000000001f#256)) then «$v36» else (BitVec.sshiftRight' («$v36» <<< ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * (0x0000000000000000000000000000000000000000000000000000000000000000#256))))))) + (h23 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v28»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v28»)))) + (h24 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v29»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v29»)))) + (h25 : («$mem5» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem4» ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v32»)) ((0x0000000000000000000000000000000000000000000000000000000000000040#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v32»)))) + (h26 : («$mem6» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem5» ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v21»)) ((0x0000000000000000000000000000000000000000000000000000000000000060#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v21»)))) + (h27 : («$v39» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h28 : («$v25» = «$v40»)) + (h29 : («$v26» = «$v41»)) + (h30 : (¬(«$v30» = «$v29»))) + : False := by + try subst h23 + try subst h24 + try subst h25 + try subst h26 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.C3 diff --git a/SolidCore/Refinement/Facts/C4.lean b/SolidCore/Refinement/Facts/C4.lean new file mode 100644 index 00000000..6d8c1fce --- /dev/null +++ b/SolidCore/Refinement/Facts/C4.lean @@ -0,0 +1,467 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/c4.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `c4.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 10. Proved by Z3: 10. Checked in Lean by the prover and +emitted here: 10. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +- `cse`: a memory, storage or transient read CSE forwarded from an earlier value. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.C4 + +/-- Contract `Main`, function `#0 add`, fact 0: `cse v0 eq v0 at the end of bb2`, its left operand +defined by `sload`. Query `Main-f0-bb2-v0-cse-0.smt2`. -/ +theorem f0_add_bb2_v0_cse_0 («$v25» : BitVec 256) («$v26» : BitVec 256) («$v27» : BitVec 256) («$v28» : BitVec 256) («$v38» : BitVec 256) («$v39» : BitVec 256) («$v36» : BitVec 256) («$v0» : BitVec 256) («$v37» : BitVec 256) («$v22» : BitVec 256) («$v23» : BitVec 256) («$v31» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v7» : BitVec 256) («$v8» : BitVec 256) («$v32» : BitVec 256) («$v33» : BitVec 256) («$v12» : BitVec 256) («$v13» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v18» : BitVec 256) («$v35» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$sto4» : (BitVec 256 → BitVec 256)) («$mem5» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v25» = «$input_calldatasize»)) + (h1 : («$v25» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v26» = (if («$v25» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v27» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v28» = (if («$v27» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v38» = («$v26» ||| «$v28»))) + (h6 : («$v39» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v36» = («$v39» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v0» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v37» = («$v0» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h10 : («$v22» = («$v37» + «$v39»))) + (h11 : («$v23» = (if («$v22» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h12 : («$v38» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h13 : («$v31» = («$v22» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h14 : («$v3» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h15 : («$v4» = («$v0» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00#256)))) + (h16 : («$v7» = («$v4» ||| «$v22»))) + (h17 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v7»))) + (h18 : («$v8» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h19 : («$v32» = (if ((0x000000000000000000000000000000000000000000000000000000000000001e#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((«$v7» >>> (((0x000000000000000000000000000000000000000000000000000000000000001f#256) - (0x000000000000000000000000000000000000000000000000000000000000001e#256)) * (0x0000000000000000000000000000000000000000000000000000000000000008#256))) &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256))))) + (h20 : («$v33» = («$v32» ^^^ «$v39»))) + (h21 : («$v12» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h22 : («$v13» = («$v7» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff#256)))) + (h23 : («$v16» = (if ((0x0000000000000000000000000000000000000000000000000000000000000008#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v33» <<< (0x0000000000000000000000000000000000000000000000000000000000000008#256))))) + (h24 : («$v17» = («$v13» ||| «$v16»))) + (h25 : («$sto4» = (store «$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v17»))) + (h26 : («$v18» = («$sto4» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h27 : («$v35» = («$v17» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h28 : («$mem5» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v35»)))) + (h29 : («$v23» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h30 : («$v36» = «$v39»)) + (h31 : (¬(«$v0» = «$v0»))) + : False := by + try subst h17 + try subst h25 + try subst h28 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 add`, fact 1: `cse v7 eq v7 at the end of bb2`, its left operand +defined by `or`. Query `Main-f0-bb2-v7-cse-1.smt2`. -/ +theorem f0_add_bb2_v7_cse_1 («$v25» : BitVec 256) («$v26» : BitVec 256) («$v27» : BitVec 256) («$v28» : BitVec 256) («$v38» : BitVec 256) («$v39» : BitVec 256) («$v36» : BitVec 256) («$v0» : BitVec 256) («$v37» : BitVec 256) («$v22» : BitVec 256) («$v23» : BitVec 256) («$v31» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v7» : BitVec 256) («$v8» : BitVec 256) («$v32» : BitVec 256) («$v33» : BitVec 256) («$v12» : BitVec 256) («$v13» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v18» : BitVec 256) («$v35» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$sto4» : (BitVec 256 → BitVec 256)) («$mem5» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v25» = «$input_calldatasize»)) + (h1 : («$v25» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v26» = (if («$v25» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v27» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v28» = (if («$v27» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v38» = («$v26» ||| «$v28»))) + (h6 : («$v39» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v36» = («$v39» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v0» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v37» = («$v0» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h10 : («$v22» = («$v37» + «$v39»))) + (h11 : («$v23» = (if («$v22» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h12 : («$v38» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h13 : («$v31» = («$v22» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h14 : («$v3» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h15 : («$v4» = («$v0» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00#256)))) + (h16 : («$v7» = («$v4» ||| «$v22»))) + (h17 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v7»))) + (h18 : («$v8» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h19 : («$v32» = (if ((0x000000000000000000000000000000000000000000000000000000000000001e#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((«$v7» >>> (((0x000000000000000000000000000000000000000000000000000000000000001f#256) - (0x000000000000000000000000000000000000000000000000000000000000001e#256)) * (0x0000000000000000000000000000000000000000000000000000000000000008#256))) &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256))))) + (h20 : («$v33» = («$v32» ^^^ «$v39»))) + (h21 : («$v12» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h22 : («$v13» = («$v7» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff#256)))) + (h23 : («$v16» = (if ((0x0000000000000000000000000000000000000000000000000000000000000008#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v33» <<< (0x0000000000000000000000000000000000000000000000000000000000000008#256))))) + (h24 : («$v17» = («$v13» ||| «$v16»))) + (h25 : («$sto4» = (store «$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v17»))) + (h26 : («$v18» = («$sto4» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h27 : («$v35» = («$v17» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h28 : («$mem5» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v35»)))) + (h29 : («$v23» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h30 : («$v0» = «$v0»)) + (h31 : («$v36» = «$v39»)) + (h32 : (¬(«$v7» = «$v7»))) + : False := by + try subst h17 + try subst h25 + try subst h28 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 add`, fact 2: `cse v7 eq v7 at the end of bb2`, its left operand +defined by `or`. Query `Main-f0-bb2-v7-cse-2.smt2`. -/ +theorem f0_add_bb2_v7_cse_2 («$v25» : BitVec 256) («$v26» : BitVec 256) («$v27» : BitVec 256) («$v28» : BitVec 256) («$v38» : BitVec 256) («$v39» : BitVec 256) («$v36» : BitVec 256) («$v0» : BitVec 256) («$v37» : BitVec 256) («$v22» : BitVec 256) («$v23» : BitVec 256) («$v31» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v7» : BitVec 256) («$v8» : BitVec 256) («$v32» : BitVec 256) («$v33» : BitVec 256) («$v12» : BitVec 256) («$v13» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v18» : BitVec 256) («$v35» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$sto4» : (BitVec 256 → BitVec 256)) («$mem5» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v25» = «$input_calldatasize»)) + (h1 : («$v25» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v26» = (if («$v25» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v27» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v28» = (if («$v27» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v38» = («$v26» ||| «$v28»))) + (h6 : («$v39» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v36» = («$v39» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v0» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v37» = («$v0» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h10 : («$v22» = («$v37» + «$v39»))) + (h11 : («$v23» = (if («$v22» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h12 : («$v38» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h13 : («$v31» = («$v22» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h14 : («$v3» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h15 : («$v4» = («$v0» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00#256)))) + (h16 : («$v7» = («$v4» ||| «$v22»))) + (h17 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v7»))) + (h18 : («$v8» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h19 : («$v32» = (if ((0x000000000000000000000000000000000000000000000000000000000000001e#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((«$v7» >>> (((0x000000000000000000000000000000000000000000000000000000000000001f#256) - (0x000000000000000000000000000000000000000000000000000000000000001e#256)) * (0x0000000000000000000000000000000000000000000000000000000000000008#256))) &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256))))) + (h20 : («$v33» = («$v32» ^^^ «$v39»))) + (h21 : («$v12» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h22 : («$v13» = («$v7» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff#256)))) + (h23 : («$v16» = (if ((0x0000000000000000000000000000000000000000000000000000000000000008#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v33» <<< (0x0000000000000000000000000000000000000000000000000000000000000008#256))))) + (h24 : («$v17» = («$v13» ||| «$v16»))) + (h25 : («$sto4» = (store «$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v17»))) + (h26 : («$v18» = («$sto4» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h27 : («$v35» = («$v17» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h28 : («$mem5» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v35»)))) + (h29 : («$v23» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h30 : («$v0» = «$v0»)) + (h31 : («$v7» = «$v7»)) + (h32 : («$v36» = «$v39»)) + (h33 : (¬(«$v7» = «$v7»))) + : False := by + try subst h17 + try subst h25 + try subst h28 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 add`, fact 3: `cse v17 eq v17 at the end of bb2`, its left operand +defined by `or`. Query `Main-f0-bb2-v17-cse-3.smt2`. -/ +theorem f0_add_bb2_v17_cse_3 («$v25» : BitVec 256) («$v26» : BitVec 256) («$v27» : BitVec 256) («$v28» : BitVec 256) («$v38» : BitVec 256) («$v39» : BitVec 256) («$v36» : BitVec 256) («$v0» : BitVec 256) («$v37» : BitVec 256) («$v22» : BitVec 256) («$v23» : BitVec 256) («$v31» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v7» : BitVec 256) («$v8» : BitVec 256) («$v32» : BitVec 256) («$v33» : BitVec 256) («$v12» : BitVec 256) («$v13» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v18» : BitVec 256) («$v35» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$sto4» : (BitVec 256 → BitVec 256)) («$mem5» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v25» = «$input_calldatasize»)) + (h1 : («$v25» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v26» = (if («$v25» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v27» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v28» = (if («$v27» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v38» = («$v26» ||| «$v28»))) + (h6 : («$v39» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v36» = («$v39» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v0» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v37» = («$v0» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h10 : («$v22» = («$v37» + «$v39»))) + (h11 : («$v23» = (if («$v22» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h12 : («$v38» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h13 : («$v31» = («$v22» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h14 : («$v3» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h15 : («$v4» = («$v0» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00#256)))) + (h16 : («$v7» = («$v4» ||| «$v22»))) + (h17 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v7»))) + (h18 : («$v8» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h19 : («$v32» = (if ((0x000000000000000000000000000000000000000000000000000000000000001e#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((«$v7» >>> (((0x000000000000000000000000000000000000000000000000000000000000001f#256) - (0x000000000000000000000000000000000000000000000000000000000000001e#256)) * (0x0000000000000000000000000000000000000000000000000000000000000008#256))) &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256))))) + (h20 : («$v33» = («$v32» ^^^ «$v39»))) + (h21 : («$v12» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h22 : («$v13» = («$v7» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff#256)))) + (h23 : («$v16» = (if ((0x0000000000000000000000000000000000000000000000000000000000000008#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v33» <<< (0x0000000000000000000000000000000000000000000000000000000000000008#256))))) + (h24 : («$v17» = («$v13» ||| «$v16»))) + (h25 : («$sto4» = (store «$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v17»))) + (h26 : («$v18» = («$sto4» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h27 : («$v35» = («$v17» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h28 : («$mem5» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v35»)))) + (h29 : («$v23» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h30 : («$v0» = «$v0»)) + (h31 : («$v7» = «$v7»)) + (h32 : («$v7» = «$v7»)) + (h33 : («$v36» = «$v39»)) + (h34 : (¬(«$v17» = «$v17»))) + : False := by + try subst h17 + try subst h25 + try subst h28 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 add`, fact 4: `cse v3 eq v0 at the end of bb2`, its left operand +defined by `sload`. Query `Main-f0-bb2-v3-cse-4.smt2`. -/ +theorem f0_add_bb2_v3_cse_4 («$v25» : BitVec 256) («$v26» : BitVec 256) («$v27» : BitVec 256) («$v28» : BitVec 256) («$v38» : BitVec 256) («$v39» : BitVec 256) («$v36» : BitVec 256) («$v0» : BitVec 256) («$v37» : BitVec 256) («$v22» : BitVec 256) («$v23» : BitVec 256) («$v31» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v7» : BitVec 256) («$v8» : BitVec 256) («$v32» : BitVec 256) («$v33» : BitVec 256) («$v12» : BitVec 256) («$v13» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v18» : BitVec 256) («$v35» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$sto4» : (BitVec 256 → BitVec 256)) («$mem5» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v25» = «$input_calldatasize»)) + (h1 : («$v25» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v26» = (if («$v25» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v27» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v28» = (if («$v27» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v38» = («$v26» ||| «$v28»))) + (h6 : («$v39» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v36» = («$v39» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v0» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v37» = («$v0» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h10 : («$v22» = («$v37» + «$v39»))) + (h11 : («$v23» = (if («$v22» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h12 : («$v38» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h13 : («$v31» = («$v22» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h14 : («$v3» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h15 : («$v4» = («$v0» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00#256)))) + (h16 : («$v7» = («$v4» ||| «$v22»))) + (h17 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v7»))) + (h18 : («$v8» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h19 : («$v32» = (if ((0x000000000000000000000000000000000000000000000000000000000000001e#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((«$v7» >>> (((0x000000000000000000000000000000000000000000000000000000000000001f#256) - (0x000000000000000000000000000000000000000000000000000000000000001e#256)) * (0x0000000000000000000000000000000000000000000000000000000000000008#256))) &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256))))) + (h20 : («$v33» = («$v32» ^^^ «$v39»))) + (h21 : («$v12» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h22 : («$v13» = («$v7» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff#256)))) + (h23 : («$v16» = (if ((0x0000000000000000000000000000000000000000000000000000000000000008#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v33» <<< (0x0000000000000000000000000000000000000000000000000000000000000008#256))))) + (h24 : («$v17» = («$v13» ||| «$v16»))) + (h25 : («$sto4» = (store «$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v17»))) + (h26 : («$v18» = («$sto4» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h27 : («$v35» = («$v17» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h28 : («$mem5» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v35»)))) + (h29 : («$v23» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h30 : («$v0» = «$v0»)) + (h31 : («$v7» = «$v7»)) + (h32 : («$v7» = «$v7»)) + (h33 : («$v17» = «$v17»)) + (h34 : («$v36» = «$v39»)) + (h35 : (¬(«$v3» = «$v0»))) + : False := by + try subst h17 + try subst h25 + try subst h28 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 add`, fact 5: `cse v8 eq v7 at the end of bb2`, its left operand +defined by `sload`. Query `Main-f0-bb2-v8-cse-5.smt2`. -/ +theorem f0_add_bb2_v8_cse_5 («$v25» : BitVec 256) («$v26» : BitVec 256) («$v27» : BitVec 256) («$v28» : BitVec 256) («$v38» : BitVec 256) («$v39» : BitVec 256) («$v36» : BitVec 256) («$v0» : BitVec 256) («$v37» : BitVec 256) («$v22» : BitVec 256) («$v23» : BitVec 256) («$v31» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v7» : BitVec 256) («$v8» : BitVec 256) («$v32» : BitVec 256) («$v33» : BitVec 256) («$v12» : BitVec 256) («$v13» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v18» : BitVec 256) («$v35» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$sto4» : (BitVec 256 → BitVec 256)) («$mem5» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v25» = «$input_calldatasize»)) + (h1 : («$v25» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v26» = (if («$v25» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v27» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v28» = (if («$v27» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v38» = («$v26» ||| «$v28»))) + (h6 : («$v39» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v36» = («$v39» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v0» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v37» = («$v0» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h10 : («$v22» = («$v37» + «$v39»))) + (h11 : («$v23» = (if («$v22» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h12 : («$v38» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h13 : («$v31» = («$v22» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h14 : («$v3» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h15 : («$v4» = («$v0» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00#256)))) + (h16 : («$v7» = («$v4» ||| «$v22»))) + (h17 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v7»))) + (h18 : («$v8» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h19 : («$v32» = (if ((0x000000000000000000000000000000000000000000000000000000000000001e#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((«$v7» >>> (((0x000000000000000000000000000000000000000000000000000000000000001f#256) - (0x000000000000000000000000000000000000000000000000000000000000001e#256)) * (0x0000000000000000000000000000000000000000000000000000000000000008#256))) &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256))))) + (h20 : («$v33» = («$v32» ^^^ «$v39»))) + (h21 : («$v12» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h22 : («$v13» = («$v7» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff#256)))) + (h23 : («$v16» = (if ((0x0000000000000000000000000000000000000000000000000000000000000008#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v33» <<< (0x0000000000000000000000000000000000000000000000000000000000000008#256))))) + (h24 : («$v17» = («$v13» ||| «$v16»))) + (h25 : («$sto4» = (store «$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v17»))) + (h26 : («$v18» = («$sto4» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h27 : («$v35» = («$v17» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h28 : («$mem5» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v35»)))) + (h29 : («$v23» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h30 : («$v0» = «$v0»)) + (h31 : («$v7» = «$v7»)) + (h32 : («$v7» = «$v7»)) + (h33 : («$v17» = «$v17»)) + (h34 : («$v3» = «$v0»)) + (h35 : («$v36» = «$v39»)) + (h36 : (¬(«$v8» = «$v7»))) + : False := by + try subst h17 + try subst h25 + try subst h28 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 add`, fact 6: `cse v12 eq v7 at the end of bb2`, its left operand +defined by `sload`. Query `Main-f0-bb2-v12-cse-6.smt2`. -/ +theorem f0_add_bb2_v12_cse_6 («$v25» : BitVec 256) («$v26» : BitVec 256) («$v27» : BitVec 256) («$v28» : BitVec 256) («$v38» : BitVec 256) («$v39» : BitVec 256) («$v36» : BitVec 256) («$v0» : BitVec 256) («$v37» : BitVec 256) («$v22» : BitVec 256) («$v23» : BitVec 256) («$v31» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v7» : BitVec 256) («$v8» : BitVec 256) («$v32» : BitVec 256) («$v33» : BitVec 256) («$v12» : BitVec 256) («$v13» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v18» : BitVec 256) («$v35» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$sto4» : (BitVec 256 → BitVec 256)) («$mem5» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v25» = «$input_calldatasize»)) + (h1 : («$v25» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v26» = (if («$v25» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v27» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v28» = (if («$v27» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v38» = («$v26» ||| «$v28»))) + (h6 : («$v39» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v36» = («$v39» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v0» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v37» = («$v0» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h10 : («$v22» = («$v37» + «$v39»))) + (h11 : («$v23» = (if («$v22» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h12 : («$v38» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h13 : («$v31» = («$v22» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h14 : («$v3» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h15 : («$v4» = («$v0» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00#256)))) + (h16 : («$v7» = («$v4» ||| «$v22»))) + (h17 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v7»))) + (h18 : («$v8» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h19 : («$v32» = (if ((0x000000000000000000000000000000000000000000000000000000000000001e#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((«$v7» >>> (((0x000000000000000000000000000000000000000000000000000000000000001f#256) - (0x000000000000000000000000000000000000000000000000000000000000001e#256)) * (0x0000000000000000000000000000000000000000000000000000000000000008#256))) &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256))))) + (h20 : («$v33» = («$v32» ^^^ «$v39»))) + (h21 : («$v12» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h22 : («$v13» = («$v7» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff#256)))) + (h23 : («$v16» = (if ((0x0000000000000000000000000000000000000000000000000000000000000008#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v33» <<< (0x0000000000000000000000000000000000000000000000000000000000000008#256))))) + (h24 : («$v17» = («$v13» ||| «$v16»))) + (h25 : («$sto4» = (store «$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v17»))) + (h26 : («$v18» = («$sto4» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h27 : («$v35» = («$v17» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h28 : («$mem5» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v35»)))) + (h29 : («$v23» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h30 : («$v0» = «$v0»)) + (h31 : («$v7» = «$v7»)) + (h32 : («$v7» = «$v7»)) + (h33 : («$v17» = «$v17»)) + (h34 : («$v3» = «$v0»)) + (h35 : («$v8» = «$v7»)) + (h36 : («$v36» = «$v39»)) + (h37 : (¬(«$v12» = «$v7»))) + : False := by + try subst h17 + try subst h25 + try subst h28 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 add`, fact 7: `cse v18 eq v17 at the end of bb2`, its left operand +defined by `sload`. Query `Main-f0-bb2-v18-cse-7.smt2`. -/ +theorem f0_add_bb2_v18_cse_7 («$v25» : BitVec 256) («$v26» : BitVec 256) («$v27» : BitVec 256) («$v28» : BitVec 256) («$v38» : BitVec 256) («$v39» : BitVec 256) («$v36» : BitVec 256) («$v0» : BitVec 256) («$v37» : BitVec 256) («$v22» : BitVec 256) («$v23» : BitVec 256) («$v31» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v7» : BitVec 256) («$v8» : BitVec 256) («$v32» : BitVec 256) («$v33» : BitVec 256) («$v12» : BitVec 256) («$v13» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v18» : BitVec 256) («$v35» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$sto4» : (BitVec 256 → BitVec 256)) («$mem5» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v25» = «$input_calldatasize»)) + (h1 : («$v25» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v26» = (if («$v25» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v27» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v28» = (if («$v27» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v38» = («$v26» ||| «$v28»))) + (h6 : («$v39» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v36» = («$v39» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v0» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v37» = («$v0» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h10 : («$v22» = («$v37» + «$v39»))) + (h11 : («$v23» = (if («$v22» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h12 : («$v38» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h13 : («$v31» = («$v22» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h14 : («$v3» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h15 : («$v4» = («$v0» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00#256)))) + (h16 : («$v7» = («$v4» ||| «$v22»))) + (h17 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v7»))) + (h18 : («$v8» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h19 : («$v32» = (if ((0x000000000000000000000000000000000000000000000000000000000000001e#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((«$v7» >>> (((0x000000000000000000000000000000000000000000000000000000000000001f#256) - (0x000000000000000000000000000000000000000000000000000000000000001e#256)) * (0x0000000000000000000000000000000000000000000000000000000000000008#256))) &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256))))) + (h20 : («$v33» = («$v32» ^^^ «$v39»))) + (h21 : («$v12» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h22 : («$v13» = («$v7» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff#256)))) + (h23 : («$v16» = (if ((0x0000000000000000000000000000000000000000000000000000000000000008#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v33» <<< (0x0000000000000000000000000000000000000000000000000000000000000008#256))))) + (h24 : («$v17» = («$v13» ||| «$v16»))) + (h25 : («$sto4» = (store «$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v17»))) + (h26 : («$v18» = («$sto4» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h27 : («$v35» = («$v17» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h28 : («$mem5» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v35»)))) + (h29 : («$v23» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h30 : («$v0» = «$v0»)) + (h31 : («$v7» = «$v7»)) + (h32 : («$v7» = «$v7»)) + (h33 : («$v17» = «$v17»)) + (h34 : («$v3» = «$v0»)) + (h35 : («$v8» = «$v7»)) + (h36 : («$v12» = «$v7»)) + (h37 : («$v36» = «$v39»)) + (h38 : (¬(«$v18» = «$v17»))) + : False := by + try subst h17 + try subst h25 + try subst h28 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 add`, fact 8: `check_elim v31 eq v22 at the end of bb2`, its left +operand defined by `and`. Query `Main-f0-bb2-v31-check_elim-8.smt2`. -/ +theorem f0_add_bb2_v31_check_elim_8 («$v25» : BitVec 256) («$v26» : BitVec 256) («$v27» : BitVec 256) («$v28» : BitVec 256) («$v38» : BitVec 256) («$v39» : BitVec 256) («$v36» : BitVec 256) («$v0» : BitVec 256) («$v37» : BitVec 256) («$v22» : BitVec 256) («$v23» : BitVec 256) («$v31» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v7» : BitVec 256) («$v8» : BitVec 256) («$v32» : BitVec 256) («$v33» : BitVec 256) («$v12» : BitVec 256) («$v13» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v18» : BitVec 256) («$v35» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$sto3» : (BitVec 256 → BitVec 256)) («$sto4» : (BitVec 256 → BitVec 256)) («$mem5» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v25» = «$input_calldatasize»)) + (h1 : («$v25» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v26» = (if («$v25» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v27» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v28» = (if («$v27» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v38» = («$v26» ||| «$v28»))) + (h6 : («$v39» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v36» = («$v39» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v0» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v37» = («$v0» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h10 : («$v22» = («$v37» + «$v39»))) + (h11 : («$v23» = (if («$v22» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h12 : («$v38» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h13 : («$v31» = («$v22» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h14 : («$v3» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h15 : («$v4» = («$v0» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00#256)))) + (h16 : («$v7» = («$v4» ||| «$v22»))) + (h17 : («$sto3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v7»))) + (h18 : («$v8» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h19 : («$v32» = (if ((0x000000000000000000000000000000000000000000000000000000000000001e#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((«$v7» >>> (((0x000000000000000000000000000000000000000000000000000000000000001f#256) - (0x000000000000000000000000000000000000000000000000000000000000001e#256)) * (0x0000000000000000000000000000000000000000000000000000000000000008#256))) &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256))))) + (h20 : («$v33» = («$v32» ^^^ «$v39»))) + (h21 : («$v12» = («$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h22 : («$v13» = («$v7» &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff#256)))) + (h23 : («$v16» = (if ((0x0000000000000000000000000000000000000000000000000000000000000008#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v33» <<< (0x0000000000000000000000000000000000000000000000000000000000000008#256))))) + (h24 : («$v17» = («$v13» ||| «$v16»))) + (h25 : («$sto4» = (store «$sto3» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v17»))) + (h26 : («$v18» = («$sto4» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h27 : («$v35» = («$v17» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h28 : («$mem5» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v35»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v35»)))) + (h29 : («$v23» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h30 : («$v0» = «$v0»)) + (h31 : («$v7» = «$v7»)) + (h32 : («$v7» = «$v7»)) + (h33 : («$v17» = «$v17»)) + (h34 : («$v3» = «$v0»)) + (h35 : («$v8» = «$v7»)) + (h36 : («$v12» = «$v7»)) + (h37 : («$v18» = «$v17»)) + (h38 : («$v36» = «$v39»)) + (h39 : (¬(«$v31» = «$v22»))) + : False := by + try subst h17 + try subst h25 + try subst h28 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 add`, fact 9: `check_elim v36 eq v39 at the end of bb4`, its left +operand defined by `and`. Query `Main-f0-bb4-v36-check_elim-9.smt2`. -/ +theorem f0_add_bb4_v36_check_elim_9 («$v25» : BitVec 256) («$v26» : BitVec 256) («$v27» : BitVec 256) («$v28» : BitVec 256) («$v38» : BitVec 256) («$v39» : BitVec 256) («$v36» : BitVec 256) («$v0» : BitVec 256) («$v37» : BitVec 256) («$v22» : BitVec 256) («$v23» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v25» = «$input_calldatasize»)) + (h1 : («$v25» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v26» = (if («$v25» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v27» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v28» = (if («$v27» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v38» = («$v26» ||| «$v28»))) + (h6 : («$v39» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v36» = («$v39» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v0» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v37» = («$v0» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h10 : («$v22» = («$v37» + «$v39»))) + (h11 : («$v23» = (if («$v22» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h12 : («$v38» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h13 : (¬(«$v36» = «$v39»))) + : False := by + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.C4 diff --git a/SolidCore/Refinement/Facts/C5.lean b/SolidCore/Refinement/Facts/C5.lean new file mode 100644 index 00000000..868f75f3 --- /dev/null +++ b/SolidCore/Refinement/Facts/C5.lean @@ -0,0 +1,103 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/c5.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `c5.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 2. Proved by Z3: 2. Checked in Lean by the prover and +emitted here: 2. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.C5 + +/-- Contract `Main`, function `#0 inc`, fact 0: `check_elim v30 eq v18 at the end of bb2`, its left +operand defined by `and`. Query `Main-f0-bb2-v30-check_elim-0.smt2`. Its goal depends on the +unconstrained values `v29`. -/ +theorem f0_inc_bb2_v30_check_elim_0 («$v21» : BitVec 256) («$v22» : BitVec 256) («$v23» : BitVec 256) («$v24» : BitVec 256) («$v36» : BitVec 256) («$v37» : BitVec 256) («$v34» : BitVec 256) («$v29» : BitVec 256) («$v2» : BitVec 256) («$v35» : BitVec 256) («$v18» : BitVec 256) («$v38» : BitVec 256) («$v19» : BitVec 256) («$v30» : BitVec 256) («$v31» : BitVec 256) («$v27» : BitVec 256) («$v28» : BitVec 256) («$v15» : BitVec 256) («$v33» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$mem4» : (BitVec 256 → BitVec 8)) («$sto5» : (BitVec 256 → BitVec 256)) («$mem6» : (BitVec 256 → BitVec 8)) («$mem7» : (BitVec 256 → BitVec 8)) («$sto8» : (BitVec 256 → BitVec 256)) («$mem9» : (BitVec 256 → BitVec 8)) («$mem10» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v21» = «$input_calldatasize»)) + (h1 : («$v21» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v22» = (if («$v21» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v23» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v24» = (if («$v23» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v36» = («$v22» ||| «$v24»))) + (h6 : («$v37» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v34» = («$v37» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v37»)))) + (h9 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))))) + (h10 : («$v2» = («$sto0» «$v29»))) + (h11 : («$v35» = («$v2» &&& (0x000000000000000000000000000000000000000000000000000000000000ffff#256)))) + (h12 : («$v18» = («$v35» + (0x000000000000000000000000000000000000000000000000000000000000012c#256)))) + (h13 : («$v38» = (if ((0x0000000000000000000000000000000000000000000000000000000000000010#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v18» >>> (0x0000000000000000000000000000000000000000000000000000000000000010#256))))) + (h14 : («$v19» = (if («$v38» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h15 : («$v36» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h16 : («$v30» = («$v18» &&& (0x000000000000000000000000000000000000000000000000000000000000ffff#256)))) + (h17 : («$sto5» = (store «$sto0» «$v29» «$v18»))) + (h18 : («$v31» = («$v37» ^^^ (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h19 : («$mem6» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem4» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v31»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v31»)))) + (h20 : («$mem7» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem6» ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))))) + (h21 : («$sto8» = (store «$sto5» «$v27» «$v37»))) + (h22 : («$mem9» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem7» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v37»)))) + (h23 : («$v15» = («$sto8» «$v28»))) + (h24 : («$v33» = («$v15» &&& (0x000000000000000000000000000000000000000000000000000000000000ffff#256)))) + (h25 : («$mem10» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem9» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v33»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v33»)))) + (h26 : («$v19» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h27 : («$v34» = «$v37»)) + (h28 : (¬(«$v30» = «$v18»))) + : False := by + have ack0 : «$v29» = «$v28» → «$sto0» «$v29» = «$sto0» «$v28» := fun e0 => congrArg «$sto0» e0 + try subst h8 + try subst h9 + try subst h17 + try subst h19 + try subst h20 + try subst h21 + try subst h22 + try subst h25 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 inc`, fact 1: `check_elim v34 eq v37 at the end of bb4`, its left +operand defined by `and`. Query `Main-f0-bb4-v34-check_elim-1.smt2`. -/ +theorem f0_inc_bb4_v34_check_elim_1 («$v21» : BitVec 256) («$v22» : BitVec 256) («$v23» : BitVec 256) («$v24» : BitVec 256) («$v36» : BitVec 256) («$v37» : BitVec 256) («$v34» : BitVec 256) («$v29» : BitVec 256) («$v2» : BitVec 256) («$v35» : BitVec 256) («$v18» : BitVec 256) («$v38» : BitVec 256) («$v19» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$mem4» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v21» = «$input_calldatasize»)) + (h1 : («$v21» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v22» = (if («$v21» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v23» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v24» = (if («$v23» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v36» = («$v22» ||| «$v24»))) + (h6 : («$v37» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v34» = («$v37» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v37»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v37»)))) + (h9 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))))) + (h10 : («$v2» = («$sto0» «$v29»))) + (h11 : («$v35» = («$v2» &&& (0x000000000000000000000000000000000000000000000000000000000000ffff#256)))) + (h12 : («$v18» = («$v35» + (0x000000000000000000000000000000000000000000000000000000000000012c#256)))) + (h13 : («$v38» = (if ((0x0000000000000000000000000000000000000000000000000000000000000010#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v18» >>> (0x0000000000000000000000000000000000000000000000000000000000000010#256))))) + (h14 : («$v19» = (if («$v38» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h15 : («$v36» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h16 : (¬(«$v34» = «$v37»))) + : False := by + try subst h8 + try subst h9 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.C5 diff --git a/SolidCore/Refinement/Facts/C6.lean b/SolidCore/Refinement/Facts/C6.lean new file mode 100644 index 00000000..d6bd8bb0 --- /dev/null +++ b/SolidCore/Refinement/Facts/C6.lean @@ -0,0 +1,127 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/c6.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `c6.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 4. Proved by Z3: 3. Checked in Lean by the prover and +emitted here: 3. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.C6 + +/-- Contract `Main`, function `#0 sum`, fact 0: `check_elim v29 eq 0x0 at the end of bb3`, its left +operand defined by `eq`. Query `Main-f0-bb3-v29-check_elim-0.smt2`. Its goal depends on the +unconstrained values `j1_0_in7_1`. -/ +theorem f0_sum_bb3_v29_check_elim_0 («$v34» : BitVec 256) («$v35» : BitVec 256) («$v36» : BitVec 256) («$v37» : BitVec 256) («$v40» : BitVec 256) («$v41» : BitVec 256) («$v39» : BitVec 256) («$j1_0_v1» : BitVec 256) («$j1_0_in5_1» : BitVec 256) («$j1_0_v2» : BitVec 256) («$j1_0_in6_1» : BitVec 256) («$j1_0_v3» : BitVec 256) («$j1_0_in7_1» : BitVec 256) («$j1_0_v5» : BitVec 256) («$j1_0_v6» : BitVec 256) («$j1_0_v7» : BitVec 256) («$j1_0_v12» : BitVec 256) («$j1_0_in20_0» : BitVec 256) («$j1_0_v13» : BitVec 256) («$j1_0_in21_0» : BitVec 256) («$j1_0_v14» : BitVec 256) («$j1_0_v29» : BitVec 256) («$v1» : BitVec 256) («$v2» : BitVec 256) («$v3» : BitVec 256) («$v5» : BitVec 256) («$v6» : BitVec 256) («$v7» : BitVec 256) («$v12» : BitVec 256) («$v13» : BitVec 256) («$j3_1_v8» : BitVec 256) («$j3_1_v30» : BitVec 256) («$j3_1_v31» : BitVec 256) («$j3_1_v32» : BitVec 256) («$j3_1_v33» : BitVec 256) («$j3_1_v11» : BitVec 256) («$j3_1_v22» : BitVec 256) («$j3_1_v23» : BitVec 256) («$j3_1_v24» : BitVec 256) («$j3_1_v25» : BitVec 256) («$j3_1_v27» : BitVec 256) («$v14» : BitVec 256) («$v29» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$sto4» : (BitVec 256 → BitVec 256)) («$tra5» : (BitVec 256 → BitVec 256)) («$j1_0_mem6» : (BitVec 256 → BitVec 8)) («$j1_0_sto7» : (BitVec 256 → BitVec 256)) («$j1_0_tra8» : (BitVec 256 → BitVec 256)) («$j1_0_mem9» : (BitVec 256 → BitVec 8)) («$j1_0_sto10» : (BitVec 256 → BitVec 256)) («$j1_0_tra11» : (BitVec 256 → BitVec 256)) («$mem12» : (BitVec 256 → BitVec 8)) («$sto13» : (BitVec 256 → BitVec 256)) («$tra14» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v34» = «$input_calldatasize»)) + (h1 : («$v34» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v35» = (if («$v34» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v36» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v37» = (if («$v36» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v40» = («$v35» ||| «$v37»))) + (h6 : («$v41» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v39» = («$v41» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v40» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h9 : (False ∨ ((True ∧ ((False ∨ ((«$j1_0_v1» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∨ (True ∧ («$j1_0_v1» = «$j1_0_in5_1»)))) ∧ ((False ∨ ((«$j1_0_v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∨ (True ∧ («$j1_0_v2» = «$j1_0_in6_1»)))) ∧ ((False ∨ ((«$j1_0_v3» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∨ (True ∧ («$j1_0_v3» = «$j1_0_in7_1»)))) ∧ ((«$j1_0_v5» = (if («$j1_0_v3» < «$v41») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j1_0_v6» = (if ((0x0000000000000000000000000000000000000000000000000000000000000007#256) = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$j1_0_v3» (0x0000000000000000000000000000000000000000000000000000000000000007#256)))) ∧ ((«$j1_0_v7» = (if («$j1_0_v6» = (0x0000000000000000000000000000000000000000000000000000000000000003#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((¬(«$j1_0_v5» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((False ∨ ((True ∧ («$j1_0_v12» = «$j1_0_in20_0»)) ∨ («$j1_0_v12» = «$j1_0_v1»))) ∧ ((False ∨ ((True ∧ («$j1_0_v13» = «$j1_0_in21_0»)) ∨ («$j1_0_v13» = «$j1_0_v2»))) ∧ ((«$j1_0_v14» = («$j1_0_v3» + (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((«$j1_0_v29» = (if («$j1_0_v3» = (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j1_0_v29» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ ((«$mem3» = «$j1_0_mem9») ∧ ((«$sto4» = «$j1_0_sto10») ∧ ((«$tra5» = «$j1_0_tra11») ∧ ((«$v1» = «$j1_0_v12») ∧ ((«$v2» = «$j1_0_v13») ∧ («$v3» = «$j1_0_v14»))))))))))))))))))) ∨ (True ∧ ((«$mem3» = «$mem0») ∧ ((«$sto4» = «$sto0») ∧ ((«$tra5» = «$tra0») ∧ ((«$v1» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ ((«$v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ («$v3» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))))))))))) + (h10 : («$v5» = (if («$v3» < «$v41») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h11 : («$v6» = (if ((0x0000000000000000000000000000000000000000000000000000000000000007#256) = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$v3» (0x0000000000000000000000000000000000000000000000000000000000000007#256))))) + (h12 : («$v7» = (if («$v6» = (0x0000000000000000000000000000000000000000000000000000000000000003#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h13 : (¬(«$v5» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h14 : (False ∨ ((True ∧ ((¬(«$v7» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$mem12» = «$mem3») ∧ ((«$sto13» = «$sto4») ∧ ((«$tra14» = «$tra5») ∧ ((«$v12» = «$v1») ∧ («$v13» = «$v2»))))))) ∨ (True ∧ ((«$j3_1_v8» = («$v3» * «$v3»)) ∧ ((«$j3_1_v30» = («$j3_1_v8» + «$v1»)) ∧ ((«$j3_1_v31» = (if («$j3_1_v30» < «$v1») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$v7» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ ((«$j3_1_v32» = («$v2» + (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((«$j3_1_v33» = (if («$j3_1_v32» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j3_1_v11» = (if («$j3_1_v30» > (0x00000000000000000000000000000000000000000000000000000000000186a0#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j3_1_v22» = (if («$v3» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j3_1_v23» = (if («$v3» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtUDiv «$j3_1_v8» «$v3»))) ∧ ((«$j3_1_v24» = (if («$j3_1_v23» = «$v3») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j3_1_v25» = («$j3_1_v22» ||| «$j3_1_v24»)) ∧ ((«$j3_1_v27» = (if («$j3_1_v25» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j3_1_v31» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ ((«$j3_1_v33» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ ((«$j3_1_v27» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ ((«$j3_1_v11» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ ((«$mem12» = «$mem3») ∧ ((«$sto13» = «$sto4») ∧ ((«$tra14» = «$tra5») ∧ ((«$v12» = «$j3_1_v30») ∧ («$v13» = «$j3_1_v32»))))))))))))))))))))))))) + (h15 : («$v14» = («$v3» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h16 : («$v29» = (if («$v3» = (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h17 : («$v39» = «$v41»)) + (h18 : (¬(«$v29» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + : False := by + have v9 : (False ∨ ((True ∧ ((False ∨ ((«$j1_0_v1» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∨ (True ∧ («$j1_0_v1» = «$j1_0_in5_1»)))) ∧ ((False ∨ ((«$j1_0_v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∨ (True ∧ («$j1_0_v2» = «$j1_0_in6_1»)))) ∧ ((False ∨ ((«$j1_0_v3» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∨ (True ∧ («$j1_0_v3» = «$j1_0_in7_1»)))) ∧ ((«$j1_0_v5» = (if («$j1_0_v3» < «$v41») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j1_0_v6» = (if ((0x0000000000000000000000000000000000000000000000000000000000000007#256) = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$j1_0_v3» (0x0000000000000000000000000000000000000000000000000000000000000007#256)))) ∧ ((«$j1_0_v7» = (if («$j1_0_v6» = (0x0000000000000000000000000000000000000000000000000000000000000003#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((¬(«$j1_0_v5» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((False ∨ ((True ∧ («$j1_0_v12» = «$j1_0_in20_0»)) ∨ («$j1_0_v12» = «$j1_0_v1»))) ∧ ((False ∨ ((True ∧ («$j1_0_v13» = «$j1_0_in21_0»)) ∨ («$j1_0_v13» = «$j1_0_v2»))) ∧ ((«$j1_0_v14» = («$j1_0_v3» + (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((«$j1_0_v29» = (if («$j1_0_v3» = (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j1_0_v29» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ (True ∧ (True ∧ (True ∧ ((«$v1» = «$j1_0_v12») ∧ ((«$v2» = «$j1_0_v13») ∧ («$v3» = «$j1_0_v14»))))))))))))))))))) ∨ (True ∧ (True ∧ (True ∧ (True ∧ ((«$v1» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ ((«$v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ («$v3» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))))))))) := (Or.imp id (Or.imp (fun ⟨w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15, w16, w17, w18, w19⟩ => ⟨id w1, id w2, id w3, id w4, id w5, id w6, id w7, id w8, id w9, id w10, id w11, id w12, id w13, (fun _ => trivial) w14, (fun _ => trivial) w15, (fun _ => trivial) w16, id w17, id w18, id w19⟩) (fun ⟨w20, w21, w22, w23, w24, w25, w26⟩ => ⟨id w20, (fun _ => trivial) w21, (fun _ => trivial) w22, (fun _ => trivial) w23, id w24, id w25, id w26⟩))) h9 + clear h9 + have v14 : (False ∨ ((True ∧ ((¬(«$v7» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ (True ∧ (True ∧ (True ∧ ((«$v12» = «$v1») ∧ («$v13» = «$v2»))))))) ∨ (True ∧ ((«$j3_1_v8» = («$v3» * «$v3»)) ∧ ((«$j3_1_v30» = («$j3_1_v8» + «$v1»)) ∧ ((«$j3_1_v31» = (if («$j3_1_v30» < «$v1») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$v7» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ ((«$j3_1_v32» = («$v2» + (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((«$j3_1_v33» = (if («$j3_1_v32» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j3_1_v11» = (if («$j3_1_v30» > (0x00000000000000000000000000000000000000000000000000000000000186a0#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j3_1_v22» = (if («$v3» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j3_1_v23» = (if («$v3» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtUDiv «$j3_1_v8» «$v3»))) ∧ ((«$j3_1_v24» = (if («$j3_1_v23» = «$v3») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j3_1_v25» = («$j3_1_v22» ||| «$j3_1_v24»)) ∧ ((«$j3_1_v27» = (if («$j3_1_v25» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j3_1_v31» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ ((«$j3_1_v33» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ ((«$j3_1_v27» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ ((«$j3_1_v11» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ (True ∧ (True ∧ (True ∧ ((«$v12» = «$j3_1_v30») ∧ («$v13» = «$j3_1_v32»)))))))))))))))))))))))) := (Or.imp id (Or.imp (fun ⟨w27, w28, w29, w30, w31, w32, w33⟩ => ⟨id w27, id w28, (fun _ => trivial) w29, (fun _ => trivial) w30, (fun _ => trivial) w31, id w32, id w33⟩) (fun ⟨w34, w35, w36, w37, w38, w39, w40, w41, w42, w43, w44, w45, w46, w47, w48, w49, w50, w51, w52, w53, w54, w55⟩ => ⟨id w34, id w35, id w36, id w37, id w38, id w39, id w40, id w41, id w42, id w43, id w44, id w45, id w46, id w47, id w48, id w49, id w50, (fun _ => trivial) w51, (fun _ => trivial) w52, (fun _ => trivial) w53, id w54, id w55⟩))) h14 + clear h14 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/- Not emitted: f0_sum_bb7_v33_check_elim_1. Contract `Main`, function `#0 sum`, fact 1: `check_elim +v33 eq 0x0 at the end of bb7`, its left operand defined by `eq`. Query +`Main-f0-bb7-v33-check_elim-1.smt2`. Its goal depends on the unconstrained values `j1_0_in21_0 +j1_0_in6_1`. Not proved: sat-opaque, Z3 model ((v33 +#x0000000000000000000000000000000000000000000000000000000000000001) +(#x0000000000000000000000000000000000000000000000000000000000000000 +#x0000000000000000000000000000000000000000000000000000000000000000)). -/ + +/-- Contract `Main`, function `#0 sum`, fact 2: `check_elim v27 eq 0x0 at the end of bb7`, its left +operand defined by `eq`. Query `Main-f0-bb7-v27-check_elim-2.smt2`. Its goal depends on the +unconstrained values `j1_0_in7_1`. -/ +theorem f0_sum_bb7_v27_check_elim_2 («$v34» : BitVec 256) («$v35» : BitVec 256) («$v36» : BitVec 256) («$v37» : BitVec 256) («$v40» : BitVec 256) («$v41» : BitVec 256) («$v39» : BitVec 256) («$j1_0_v1» : BitVec 256) («$j1_0_in5_1» : BitVec 256) («$j1_0_v2» : BitVec 256) («$j1_0_in6_1» : BitVec 256) («$j1_0_v3» : BitVec 256) («$j1_0_in7_1» : BitVec 256) («$j1_0_v5» : BitVec 256) («$j1_0_v6» : BitVec 256) («$j1_0_v7» : BitVec 256) («$j1_0_v12» : BitVec 256) («$j1_0_in20_0» : BitVec 256) («$j1_0_v13» : BitVec 256) («$j1_0_in21_0» : BitVec 256) («$j1_0_v14» : BitVec 256) («$j1_0_v29» : BitVec 256) («$v1» : BitVec 256) («$v2» : BitVec 256) («$v3» : BitVec 256) («$v5» : BitVec 256) («$v6» : BitVec 256) («$v7» : BitVec 256) («$v8» : BitVec 256) («$v30» : BitVec 256) («$v31» : BitVec 256) («$v32» : BitVec 256) («$v33» : BitVec 256) («$v11» : BitVec 256) («$v22» : BitVec 256) («$v23» : BitVec 256) («$v24» : BitVec 256) («$v25» : BitVec 256) («$v27» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$sto4» : (BitVec 256 → BitVec 256)) («$tra5» : (BitVec 256 → BitVec 256)) («$j1_0_mem6» : (BitVec 256 → BitVec 8)) («$j1_0_sto7» : (BitVec 256 → BitVec 256)) («$j1_0_tra8» : (BitVec 256 → BitVec 256)) («$j1_0_mem9» : (BitVec 256 → BitVec 8)) («$j1_0_sto10» : (BitVec 256 → BitVec 256)) («$j1_0_tra11» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v34» = «$input_calldatasize»)) + (h1 : («$v34» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v35» = (if («$v34» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v36» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v37» = (if («$v36» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v40» = («$v35» ||| «$v37»))) + (h6 : («$v41» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v39» = («$v41» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v40» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h9 : (False ∨ ((True ∧ ((False ∨ ((«$j1_0_v1» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∨ (True ∧ («$j1_0_v1» = «$j1_0_in5_1»)))) ∧ ((False ∨ ((«$j1_0_v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∨ (True ∧ («$j1_0_v2» = «$j1_0_in6_1»)))) ∧ ((False ∨ ((«$j1_0_v3» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∨ (True ∧ («$j1_0_v3» = «$j1_0_in7_1»)))) ∧ ((«$j1_0_v5» = (if («$j1_0_v3» < «$v41») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j1_0_v6» = (if ((0x0000000000000000000000000000000000000000000000000000000000000007#256) = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$j1_0_v3» (0x0000000000000000000000000000000000000000000000000000000000000007#256)))) ∧ ((«$j1_0_v7» = (if («$j1_0_v6» = (0x0000000000000000000000000000000000000000000000000000000000000003#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((¬(«$j1_0_v5» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((False ∨ ((True ∧ («$j1_0_v12» = «$j1_0_in20_0»)) ∨ («$j1_0_v12» = «$j1_0_v1»))) ∧ ((False ∨ ((True ∧ («$j1_0_v13» = «$j1_0_in21_0»)) ∨ («$j1_0_v13» = «$j1_0_v2»))) ∧ ((«$j1_0_v14» = («$j1_0_v3» + (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((«$j1_0_v29» = (if («$j1_0_v3» = (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j1_0_v29» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ ((«$mem3» = «$j1_0_mem9») ∧ ((«$sto4» = «$j1_0_sto10») ∧ ((«$tra5» = «$j1_0_tra11») ∧ ((«$v1» = «$j1_0_v12») ∧ ((«$v2» = «$j1_0_v13») ∧ («$v3» = «$j1_0_v14»))))))))))))))))))) ∨ (True ∧ ((«$mem3» = «$mem0») ∧ ((«$sto4» = «$sto0») ∧ ((«$tra5» = «$tra0») ∧ ((«$v1» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ ((«$v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ («$v3» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))))))))))) + (h10 : («$v5» = (if («$v3» < «$v41») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h11 : («$v6» = (if ((0x0000000000000000000000000000000000000000000000000000000000000007#256) = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$v3» (0x0000000000000000000000000000000000000000000000000000000000000007#256))))) + (h12 : («$v7» = (if («$v6» = (0x0000000000000000000000000000000000000000000000000000000000000003#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h13 : (¬(«$v5» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h14 : («$v8» = («$v3» * «$v3»))) + (h15 : («$v30» = («$v8» + «$v1»))) + (h16 : («$v31» = (if («$v30» < «$v1») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h17 : («$v7» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h18 : («$v32» = («$v2» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h19 : («$v33» = (if («$v32» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h20 : («$v11» = (if («$v30» > (0x00000000000000000000000000000000000000000000000000000000000186a0#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h21 : («$v22» = (if («$v3» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h22 : («$v23» = (if («$v3» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtUDiv «$v8» «$v3»)))) + (h23 : («$v24» = (if («$v23» = «$v3») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h24 : («$v25» = («$v22» ||| «$v24»))) + (h25 : («$v27» = (if («$v25» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h26 : («$v31» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h27 : («$v33» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h28 : («$v39» = «$v41»)) + (h29 : (¬(«$v27» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + : False := by + have v9 : (False ∨ ((True ∧ ((False ∨ ((«$j1_0_v1» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∨ (True ∧ («$j1_0_v1» = «$j1_0_in5_1»)))) ∧ ((False ∨ ((«$j1_0_v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∨ (True ∧ («$j1_0_v2» = «$j1_0_in6_1»)))) ∧ ((False ∨ ((«$j1_0_v3» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∨ (True ∧ («$j1_0_v3» = «$j1_0_in7_1»)))) ∧ ((«$j1_0_v5» = (if («$j1_0_v3» < «$v41») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j1_0_v6» = (if ((0x0000000000000000000000000000000000000000000000000000000000000007#256) = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$j1_0_v3» (0x0000000000000000000000000000000000000000000000000000000000000007#256)))) ∧ ((«$j1_0_v7» = (if («$j1_0_v6» = (0x0000000000000000000000000000000000000000000000000000000000000003#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((¬(«$j1_0_v5» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((False ∨ ((True ∧ («$j1_0_v12» = «$j1_0_in20_0»)) ∨ («$j1_0_v12» = «$j1_0_v1»))) ∧ ((False ∨ ((True ∧ («$j1_0_v13» = «$j1_0_in21_0»)) ∨ («$j1_0_v13» = «$j1_0_v2»))) ∧ ((«$j1_0_v14» = («$j1_0_v3» + (0x0000000000000000000000000000000000000000000000000000000000000001#256))) ∧ ((«$j1_0_v29» = (if («$j1_0_v3» = (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$j1_0_v29» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ (True ∧ (True ∧ (True ∧ ((«$v1» = «$j1_0_v12») ∧ ((«$v2» = «$j1_0_v13») ∧ («$v3» = «$j1_0_v14»))))))))))))))))))) ∨ (True ∧ (True ∧ (True ∧ (True ∧ ((«$v1» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ ((«$v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∧ («$v3» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))))))))) := (Or.imp id (Or.imp (fun ⟨w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15, w16, w17, w18, w19⟩ => ⟨id w1, id w2, id w3, id w4, id w5, id w6, id w7, id w8, id w9, id w10, id w11, id w12, id w13, (fun _ => trivial) w14, (fun _ => trivial) w15, (fun _ => trivial) w16, id w17, id w18, id w19⟩) (fun ⟨w20, w21, w22, w23, w24, w25, w26⟩ => ⟨id w20, (fun _ => trivial) w21, (fun _ => trivial) w22, (fun _ => trivial) w23, id w24, id w25, id w26⟩))) h9 + clear h9 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 sum`, fact 3: `check_elim v39 eq v41 at the end of bb9`, its left +operand defined by `and`. Query `Main-f0-bb9-v39-check_elim-3.smt2`. -/ +theorem f0_sum_bb9_v39_check_elim_3 («$v34» : BitVec 256) («$v35» : BitVec 256) («$v36» : BitVec 256) («$v37» : BitVec 256) («$v40» : BitVec 256) («$v41» : BitVec 256) («$v39» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v34» = «$input_calldatasize»)) + (h1 : («$v34» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v35» = (if («$v34» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v36» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v37» = (if («$v36» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v40» = («$v35» ||| «$v37»))) + (h6 : («$v41» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v39» = («$v41» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v40» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h9 : (¬(«$v39» = «$v41»))) + : False := by + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.C6 diff --git a/SolidCore/Refinement/Facts/C7.lean b/SolidCore/Refinement/Facts/C7.lean new file mode 100644 index 00000000..403f9842 --- /dev/null +++ b/SolidCore/Refinement/Facts/C7.lean @@ -0,0 +1,169 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/c7.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `c7.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 4. Proved by Z3: 4. Checked in Lean by the prover and +emitted here: 4. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.C7 + +/-- Contract `Main`, function `#0 f`, fact 0: `check_elim v7 eq 0x0 at the end of bb2`, its left +operand defined by `gt`. Query `Main-f0-bb2-v7-check_elim-0.smt2`. -/ +theorem f0_f_bb2_v7_check_elim_0 («$v9» : BitVec 256) («$v10» : BitVec 256) («$v11» : BitVec 256) («$v12» : BitVec 256) («$v25» : BitVec 256) («$v13» : BitVec 256) («$v14» : BitVec 256) («$v26» : BitVec 256) («$v28» : BitVec 256) («$v27» : BitVec 256) («$v20» : BitVec 256) («$v21» : BitVec 256) («$v6» : BitVec 256) («$v7» : BitVec 256) («$v23» : BitVec 256) («$v1» : BitVec 256) («$v24» : BitVec 256) («$v2» : BitVec 256) («$v19» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$mem4» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v9» = «$input_calldatasize»)) + (h1 : («$v9» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v10» = (if («$v9» < (0x0000000000000000000000000000000000000000000000000000000000000044#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v11» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v12» = (if («$v11» > (0x0000000000000000000000000000000000000000000000000000000000000002#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v25» = («$v10» ||| «$v12»))) + (h6 : («$v13» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h7 : («$v14» = (if («$v13» > (0x0000000000000000000000000000000000000000000000000000000000000001#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h8 : («$v26» = («$v25» ||| «$v14»))) + (h9 : («$v28» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h10 : («$v27» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h11 : («$v20» = («$v27» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h12 : («$v21» = («$v28» &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$v6» = («$v27» + «$v27»))) + (h14 : («$v7» = (if («$v6» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h15 : («$v23» = («$v6» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h16 : («$v1» = (if («$v27» = (0x0000000000000000000000000000000000000000000000000000000000000001#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h17 : («$v24» = «$v1»)) + (h18 : («$v2» = (if («$v28» = «$v24») then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h19 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v6»)))) + (h20 : («$v19» = «$v2»)) + (h21 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v19»)))) + (h22 : («$v26» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h23 : (¬(«$v7» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + : False := by + try subst h19 + try subst h21 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 1: `check_elim v20 eq v27 at the end of bb2`, its left +operand defined by `and`. Query `Main-f0-bb2-v20-check_elim-1.smt2`. -/ +theorem f0_f_bb2_v20_check_elim_1 («$v9» : BitVec 256) («$v10» : BitVec 256) («$v11» : BitVec 256) («$v12» : BitVec 256) («$v25» : BitVec 256) («$v13» : BitVec 256) («$v14» : BitVec 256) («$v26» : BitVec 256) («$v28» : BitVec 256) («$v27» : BitVec 256) («$v20» : BitVec 256) («$v21» : BitVec 256) («$v6» : BitVec 256) («$v7» : BitVec 256) («$v23» : BitVec 256) («$v1» : BitVec 256) («$v24» : BitVec 256) («$v2» : BitVec 256) («$v19» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$mem4» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v9» = «$input_calldatasize»)) + (h1 : («$v9» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v10» = (if («$v9» < (0x0000000000000000000000000000000000000000000000000000000000000044#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v11» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v12» = (if («$v11» > (0x0000000000000000000000000000000000000000000000000000000000000002#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v25» = («$v10» ||| «$v12»))) + (h6 : («$v13» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h7 : («$v14» = (if («$v13» > (0x0000000000000000000000000000000000000000000000000000000000000001#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h8 : («$v26» = («$v25» ||| «$v14»))) + (h9 : («$v28» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h10 : («$v27» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h11 : («$v20» = («$v27» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h12 : («$v21» = («$v28» &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$v6» = («$v27» + «$v27»))) + (h14 : («$v7» = (if («$v6» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h15 : («$v23» = («$v6» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h16 : («$v1» = (if («$v27» = (0x0000000000000000000000000000000000000000000000000000000000000001#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h17 : («$v24» = «$v1»)) + (h18 : («$v2» = (if («$v28» = «$v24») then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h19 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v6»)))) + (h20 : («$v19» = «$v2»)) + (h21 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v19»)))) + (h22 : («$v26» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h23 : («$v7» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h24 : (¬(«$v20» = «$v27»))) + : False := by + try subst h19 + try subst h21 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 2: `check_elim v21 eq v28 at the end of bb2`, its left +operand defined by `and`. Query `Main-f0-bb2-v21-check_elim-2.smt2`. -/ +theorem f0_f_bb2_v21_check_elim_2 («$v9» : BitVec 256) («$v10» : BitVec 256) («$v11» : BitVec 256) («$v12» : BitVec 256) («$v25» : BitVec 256) («$v13» : BitVec 256) («$v14» : BitVec 256) («$v26» : BitVec 256) («$v28» : BitVec 256) («$v27» : BitVec 256) («$v20» : BitVec 256) («$v21» : BitVec 256) («$v6» : BitVec 256) («$v7» : BitVec 256) («$v23» : BitVec 256) («$v1» : BitVec 256) («$v24» : BitVec 256) («$v2» : BitVec 256) («$v19» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$mem4» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v9» = «$input_calldatasize»)) + (h1 : («$v9» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v10» = (if («$v9» < (0x0000000000000000000000000000000000000000000000000000000000000044#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v11» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v12» = (if («$v11» > (0x0000000000000000000000000000000000000000000000000000000000000002#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v25» = («$v10» ||| «$v12»))) + (h6 : («$v13» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h7 : («$v14» = (if («$v13» > (0x0000000000000000000000000000000000000000000000000000000000000001#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h8 : («$v26» = («$v25» ||| «$v14»))) + (h9 : («$v28» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h10 : («$v27» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h11 : («$v20» = («$v27» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h12 : («$v21» = («$v28» &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$v6» = («$v27» + «$v27»))) + (h14 : («$v7» = (if («$v6» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h15 : («$v23» = («$v6» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h16 : («$v1» = (if («$v27» = (0x0000000000000000000000000000000000000000000000000000000000000001#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h17 : («$v24» = «$v1»)) + (h18 : («$v2» = (if («$v28» = «$v24») then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h19 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v6»)))) + (h20 : («$v19» = «$v2»)) + (h21 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v19»)))) + (h22 : («$v26» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h23 : («$v7» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h24 : («$v20» = «$v27»)) + (h25 : (¬(«$v21» = «$v28»))) + : False := by + try subst h19 + try subst h21 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 3: `check_elim v23 eq v6 at the end of bb2`, its left +operand defined by `and`. Query `Main-f0-bb2-v23-check_elim-3.smt2`. -/ +theorem f0_f_bb2_v23_check_elim_3 («$v9» : BitVec 256) («$v10» : BitVec 256) («$v11» : BitVec 256) («$v12» : BitVec 256) («$v25» : BitVec 256) («$v13» : BitVec 256) («$v14» : BitVec 256) («$v26» : BitVec 256) («$v28» : BitVec 256) («$v27» : BitVec 256) («$v20» : BitVec 256) («$v21» : BitVec 256) («$v6» : BitVec 256) («$v7» : BitVec 256) («$v23» : BitVec 256) («$v1» : BitVec 256) («$v24» : BitVec 256) («$v2» : BitVec 256) («$v19» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$mem4» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v9» = «$input_calldatasize»)) + (h1 : («$v9» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v10» = (if («$v9» < (0x0000000000000000000000000000000000000000000000000000000000000044#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v11» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v12» = (if («$v11» > (0x0000000000000000000000000000000000000000000000000000000000000002#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v25» = («$v10» ||| «$v12»))) + (h6 : («$v13» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h7 : («$v14» = (if («$v13» > (0x0000000000000000000000000000000000000000000000000000000000000001#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h8 : («$v26» = («$v25» ||| «$v14»))) + (h9 : («$v28» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h10 : («$v27» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h11 : («$v20» = («$v27» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h12 : («$v21» = («$v28» &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$v6» = («$v27» + «$v27»))) + (h14 : («$v7» = (if («$v6» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h15 : («$v23» = («$v6» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h16 : («$v1» = (if («$v27» = (0x0000000000000000000000000000000000000000000000000000000000000001#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h17 : («$v24» = «$v1»)) + (h18 : («$v2» = (if («$v28» = «$v24») then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h19 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v6»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v6»)))) + (h20 : («$v19» = «$v2»)) + (h21 : («$mem4» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v19»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v19»)))) + (h22 : («$v26» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h23 : («$v7» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h24 : («$v20» = «$v27»)) + (h25 : («$v21» = «$v28»)) + (h26 : (¬(«$v23» = «$v6»))) + : False := by + try subst h19 + try subst h21 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.C7 diff --git a/SolidCore/Refinement/Facts/C8.lean b/SolidCore/Refinement/Facts/C8.lean new file mode 100644 index 00000000..59485cba --- /dev/null +++ b/SolidCore/Refinement/Facts/C8.lean @@ -0,0 +1,86 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/c8.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `c8.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 3. Proved by Z3: 3. Checked in Lean by the prover and +emitted here: 3. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.C8 + +/-- Contract `Main`, function `#0 fib`, fact 0: `check_elim v10 eq 0x0 at the end of bb4`, its left +operand defined by `eq`. Query `Main-f0-bb4-v10-check_elim-0.smt2`. -/ +theorem f0_fib_bb4_v10_check_elim_0 («$v0» : BitVec 256) («$arg0» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v3» : BitVec 256) («$v18» : BitVec 256) («$v19» : BitVec 256) («$v5» : BitVec 256) («$v14» : BitVec 256) («$v15» : BitVec 256) («$v10» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$sto4» : (BitVec 256 → BitVec 256)) («$tra5» : (BitVec 256 → BitVec 256)) («$mem6» : (BitVec 256 → BitVec 8)) («$sto7» : (BitVec 256 → BitVec 256)) («$tra8» : (BitVec 256 → BitVec 256)) + (h0 : («$v0» = (if («$arg0» < (0x0000000000000000000000000000000000000000000000000000000000000002#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h1 : («$v16» = («$arg0» - (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h2 : («$v17» = («$v16» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h3 : («$v18» = («$arg0» - (0x0000000000000000000000000000000000000000000000000000000000000002#256)))) + (h4 : («$v19» = («$v18» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h5 : («$v14» = («$v3» + «$v5»))) + (h6 : («$v15» = (if («$v14» < «$v3») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h7 : («$v0» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h8 : («$v10» = (if («$arg0» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v15» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h10 : (¬(«$v10» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + : False := by + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 fib`, fact 1: `check_elim v0 eq 0x0 at the end of bb4`, its left +operand defined by `lt`. Query `Main-f0-bb4-v0-check_elim-1.smt2`. -/ +theorem f0_fib_bb4_v0_check_elim_1 («$v0» : BitVec 256) («$arg0» : BitVec 256) («$v16» : BitVec 256) («$v17» : BitVec 256) («$v3» : BitVec 256) («$v18» : BitVec 256) («$v19» : BitVec 256) («$v5» : BitVec 256) («$v14» : BitVec 256) («$v15» : BitVec 256) («$v10» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$sto4» : (BitVec 256 → BitVec 256)) («$tra5» : (BitVec 256 → BitVec 256)) («$mem6» : (BitVec 256 → BitVec 8)) («$sto7» : (BitVec 256 → BitVec 256)) («$tra8» : (BitVec 256 → BitVec 256)) + (h0 : («$v0» = (if («$arg0» < (0x0000000000000000000000000000000000000000000000000000000000000002#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h1 : («$v16» = («$arg0» - (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h2 : («$v17» = («$v16» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h3 : («$v18» = («$arg0» - (0x0000000000000000000000000000000000000000000000000000000000000002#256)))) + (h4 : («$v19» = («$v18» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h5 : («$v14» = («$v3» + «$v5»))) + (h6 : («$v15» = (if («$v14» < «$v3») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h7 : («$v0» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h8 : («$v10» = (if («$arg0» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v15» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h10 : («$v10» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h11 : (¬(«$v0» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + : False := by + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#1 f`, fact 0: `check_elim v13 eq v15 at the end of bb4`, its left +operand defined by `and`. Query `Main-f1-bb4-v13-check_elim-0.smt2`. -/ +theorem f1_f_bb4_v13_check_elim_0 («$v6» : BitVec 256) («$v7» : BitVec 256) («$v8» : BitVec 256) («$v9» : BitVec 256) («$v14» : BitVec 256) («$v15» : BitVec 256) («$v13» : BitVec 256) («$v0» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v6» = «$input_calldatasize»)) + (h1 : («$v6» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v7» = (if («$v6» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v8» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v9» = (if («$v8» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v14» = («$v7» ||| «$v9»))) + (h6 : («$v15» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v13» = («$v15» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v0» = (if («$v15» < (0x0000000000000000000000000000000000000000000000000000000000000019#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v14» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h10 : (¬(«$v13» = «$v15»))) + : False := by + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.C8 diff --git a/SolidCore/Refinement/Facts/C9.lean b/SolidCore/Refinement/Facts/C9.lean new file mode 100644 index 00000000..34fce3cf --- /dev/null +++ b/SolidCore/Refinement/Facts/C9.lean @@ -0,0 +1,407 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/c9.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `c9.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 7. Proved by Z3: 7. Checked in Lean by the prover and +emitted here: 7. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +- `cse`: a memory, storage or transient read CSE forwarded from an earlier value. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.C9 + +/-- Contract `Main`, function `#0 f`, fact 0: `cse v9 eq 0x3 at the end of bb3`, its left operand +defined by `mload`. Query `Main-f0-bb3-v9-cse-0.smt2`. The query assumes the backend axioms +`heap-floor`. -/ +theorem f0_f_bb3_v9_cse_0 («$v29» : BitVec 256) («$v30» : BitVec 256) («$v31» : BitVec 256) («$v32» : BitVec 256) («$v50» : BitVec 256) («$v51» : BitVec 256) («$v49» : BitVec 256) («$v1» : BitVec 256) («$v57» : BitVec 256) («$v2» : BitVec 256) («$v3» : BitVec 256) («$v34» : BitVec 256) («$v5» : BitVec 256) («$v43» : BitVec 256) («$v44» : BitVec 256) («$v45» : BitVec 256) («$v52» : BitVec 256) («$v54» : BitVec 256) («$v55» : BitVec 256) («$v47» : BitVec 256) («$v23» : BitVec 256) («$v59» : BitVec 256) («$v24» : BitVec 256) («$v25» : BitVec 256) («$v27» : BitVec 256) («$v9» : BitVec 256) («$v37» : BitVec 256) («$v15» : BitVec 256) («$v16» : BitVec 256) («$word1» : BitVec 256) («$word2» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$sto4» : (BitVec 256 → BitVec 256)) («$sto5» : (BitVec 256 → BitVec 256)) («$mem6» : (BitVec 256 → BitVec 8)) («$sto7» : (BitVec 256 → BitVec 256)) («$sto8» : (BitVec 256 → BitVec 256)) («$mem9» : (BitVec 256 → BitVec 8)) («$mem10» : (BitVec 256 → BitVec 8)) («$mem11» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v29» = «$input_calldatasize»)) + (h1 : («$v29» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v30» = (if («$v29» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v31» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v32» = (if («$v31» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v50» = («$v30» ||| «$v32»))) + (h6 : («$v51» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v49» = («$v51» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v1» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v57» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v1» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h10 : («$v2» = (if («$v57» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h11 : («$v50» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h12 : («$v3» = («$v1» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))))) + (h14 : («$v5» = («$v34» + «$v1»))) + (h15 : («$sto4» = (store «$sto0» «$v5» «$v51»))) + (h16 : («$sto5» = (store «$sto4» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v3»))) + (h17 : (True ∧ ((«$v43» ≥ (0x0000000000000000000000000000000000000000000000000000000000000080#256)) ∧ («$v43» ≤ (0x000000000000000000000000000000000000000000000003ffffffffffffffff#256))))) + (h18 : («$v44» = («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000080#256)))) + (h19 : («$v45» = (if («$v44» < «$v43») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h20 : («$v52» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v44» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h21 : («$v54» = «$v45»)) + (h22 : («$v55» = («$v52» ||| «$v54»))) + (h23 : («$v47» = (if («$v55» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h24 : («$v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h25 : («$mem6» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))))) + (h26 : («$v23» = («$sto5» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h27 : («$v59» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v3» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h28 : («$v24» = (if («$v59» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h29 : («$v47» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h30 : («$v25» = («$v3» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h31 : («$v27» = («$v34» + «$v3»))) + (h32 : («$sto7» = (store «$sto5» «$v27» (0x0000000000000000000000000000000000000000000000000000000000000005#256)))) + (h33 : («$sto8» = (store «$sto7» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v25»))) + (h34 : («$v9» = (0x0000000000000000000000000000000000000000000000000000000000000003#256))) + (h35 : («$v37» = («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000040#256)))) + (h36 : («$mem9» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem6» («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v51»)))) + (h37 : («$v15» = («$sto8» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h38 : («$v16» = (0x0000000000000000000000000000000000000000000000000000000000000003#256))) + (h39 : («$mem10» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem9» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v25»)))) + (h40 : («$word1» = (if ((0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$v43») then «$v25» else (if ((((0x0000000000000000000000000000000000000000000000000000000000000000#256) - «$v43») ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) ∧ ((«$v43» - (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256))) then (0x0000000000000000000000000000000000000000000000000000000000000003#256) else ((((((((((((((((((((((((((((((((«$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)))))))) + (h41 : («$mem11» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem10» ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v51»)))) + (h42 : («$word2» = (if ((0x0000000000000000000000000000000000000000000000000000000000000020#256) = «$v43») then «$v51» else (if ((((0x0000000000000000000000000000000000000000000000000000000000000020#256) - «$v43») ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) ∧ ((«$v43» - (0x0000000000000000000000000000000000000000000000000000000000000020#256)) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256))) then «$word1» else ((((((((((((((((((((((((((((((((«$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)))))))) + (h43 : («$v24» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h44 : («$v49» = «$v51»)) + (h45 : («$v3» = «$v3»)) + (h46 : («$v23» = «$v3»)) + (h47 : (¬(«$v9» = (0x0000000000000000000000000000000000000000000000000000000000000003#256)))) + : False := by + try subst h13 + try subst h15 + try subst h16 + try subst h25 + try subst h32 + try subst h33 + try subst h36 + try subst h39 + try subst h41 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 1: `cse v15 eq v25 at the end of bb3`, its left operand +defined by `sload`. Query `Main-f0-bb3-v15-cse-1.smt2`. The query assumes the backend axioms +`heap-floor`. Its goal depends on the unconstrained values `v34`. -/ +theorem f0_f_bb3_v15_cse_1 («$v29» : BitVec 256) («$v30» : BitVec 256) («$v31» : BitVec 256) («$v32» : BitVec 256) («$v50» : BitVec 256) («$v51» : BitVec 256) («$v49» : BitVec 256) («$v1» : BitVec 256) («$v57» : BitVec 256) («$v2» : BitVec 256) («$v3» : BitVec 256) («$v34» : BitVec 256) («$v5» : BitVec 256) («$v43» : BitVec 256) («$v44» : BitVec 256) («$v45» : BitVec 256) («$v52» : BitVec 256) («$v54» : BitVec 256) («$v55» : BitVec 256) («$v47» : BitVec 256) («$v23» : BitVec 256) («$v59» : BitVec 256) («$v24» : BitVec 256) («$v25» : BitVec 256) («$v27» : BitVec 256) («$v9» : BitVec 256) («$v37» : BitVec 256) («$v15» : BitVec 256) («$v16» : BitVec 256) («$word1» : BitVec 256) («$word2» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$sto4» : (BitVec 256 → BitVec 256)) («$sto5» : (BitVec 256 → BitVec 256)) («$mem6» : (BitVec 256 → BitVec 8)) («$sto7» : (BitVec 256 → BitVec 256)) («$sto8» : (BitVec 256 → BitVec 256)) («$mem9» : (BitVec 256 → BitVec 8)) («$mem10» : (BitVec 256 → BitVec 8)) («$mem11» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v29» = «$input_calldatasize»)) + (h1 : («$v29» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v30» = (if («$v29» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v31» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v32» = (if («$v31» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v50» = («$v30» ||| «$v32»))) + (h6 : («$v51» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v49» = («$v51» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v1» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v57» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v1» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h10 : («$v2» = (if («$v57» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h11 : («$v50» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h12 : («$v3» = («$v1» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))))) + (h14 : («$v5» = («$v34» + «$v1»))) + (h15 : («$sto4» = (store «$sto0» «$v5» «$v51»))) + (h16 : («$sto5» = (store «$sto4» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v3»))) + (h17 : (True ∧ ((«$v43» ≥ (0x0000000000000000000000000000000000000000000000000000000000000080#256)) ∧ («$v43» ≤ (0x000000000000000000000000000000000000000000000003ffffffffffffffff#256))))) + (h18 : («$v44» = («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000080#256)))) + (h19 : («$v45» = (if («$v44» < «$v43») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h20 : («$v52» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v44» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h21 : («$v54» = «$v45»)) + (h22 : («$v55» = («$v52» ||| «$v54»))) + (h23 : («$v47» = (if («$v55» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h24 : («$v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h25 : («$mem6» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))))) + (h26 : («$v23» = («$sto5» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h27 : («$v59» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v3» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h28 : («$v24» = (if («$v59» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h29 : («$v47» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h30 : («$v25» = («$v3» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h31 : («$v27» = («$v34» + «$v3»))) + (h32 : («$sto7» = (store «$sto5» «$v27» (0x0000000000000000000000000000000000000000000000000000000000000005#256)))) + (h33 : («$sto8» = (store «$sto7» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v25»))) + (h34 : («$v9» = (0x0000000000000000000000000000000000000000000000000000000000000003#256))) + (h35 : («$v37» = («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000040#256)))) + (h36 : («$mem9» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem6» («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v51»)))) + (h37 : («$v15» = («$sto8» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h38 : («$v16» = (0x0000000000000000000000000000000000000000000000000000000000000003#256))) + (h39 : («$mem10» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem9» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v25»)))) + (h40 : («$word1» = (if ((0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$v43») then «$v25» else (if ((((0x0000000000000000000000000000000000000000000000000000000000000000#256) - «$v43») ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) ∧ ((«$v43» - (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256))) then (0x0000000000000000000000000000000000000000000000000000000000000003#256) else ((((((((((((((((((((((((((((((((«$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)))))))) + (h41 : («$mem11» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem10» ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v51»)))) + (h42 : («$word2» = (if ((0x0000000000000000000000000000000000000000000000000000000000000020#256) = «$v43») then «$v51» else (if ((((0x0000000000000000000000000000000000000000000000000000000000000020#256) - «$v43») ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) ∧ ((«$v43» - (0x0000000000000000000000000000000000000000000000000000000000000020#256)) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256))) then «$word1» else ((((((((((((((((((((((((((((((((«$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)))))))) + (h43 : («$v24» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h44 : («$v9» = (0x0000000000000000000000000000000000000000000000000000000000000003#256))) + (h45 : («$v49» = «$v51»)) + (h46 : («$v3» = «$v3»)) + (h47 : («$v23» = «$v3»)) + (h48 : (¬(«$v15» = «$v25»))) + : False := by + try subst h13 + try subst h15 + try subst h16 + try subst h25 + try subst h32 + try subst h33 + try subst h36 + try subst h39 + try subst h41 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 2: `cse v16 eq 0x3 at the end of bb3`, its left operand +defined by `mload`. Query `Main-f0-bb3-v16-cse-2.smt2`. The query assumes the backend axioms +`heap-floor`. -/ +theorem f0_f_bb3_v16_cse_2 («$v29» : BitVec 256) («$v30» : BitVec 256) («$v31» : BitVec 256) («$v32» : BitVec 256) («$v50» : BitVec 256) («$v51» : BitVec 256) («$v49» : BitVec 256) («$v1» : BitVec 256) («$v57» : BitVec 256) («$v2» : BitVec 256) («$v3» : BitVec 256) («$v34» : BitVec 256) («$v5» : BitVec 256) («$v43» : BitVec 256) («$v44» : BitVec 256) («$v45» : BitVec 256) («$v52» : BitVec 256) («$v54» : BitVec 256) («$v55» : BitVec 256) («$v47» : BitVec 256) («$v23» : BitVec 256) («$v59» : BitVec 256) («$v24» : BitVec 256) («$v25» : BitVec 256) («$v27» : BitVec 256) («$v9» : BitVec 256) («$v37» : BitVec 256) («$v15» : BitVec 256) («$v16» : BitVec 256) («$word1» : BitVec 256) («$word2» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$sto4» : (BitVec 256 → BitVec 256)) («$sto5» : (BitVec 256 → BitVec 256)) («$mem6» : (BitVec 256 → BitVec 8)) («$sto7» : (BitVec 256 → BitVec 256)) («$sto8» : (BitVec 256 → BitVec 256)) («$mem9» : (BitVec 256 → BitVec 8)) («$mem10» : (BitVec 256 → BitVec 8)) («$mem11» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v29» = «$input_calldatasize»)) + (h1 : («$v29» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v30» = (if («$v29» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v31» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v32» = (if («$v31» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v50» = («$v30» ||| «$v32»))) + (h6 : («$v51» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v49» = («$v51» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v1» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v57» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v1» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h10 : («$v2» = (if («$v57» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h11 : («$v50» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h12 : («$v3» = («$v1» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))))) + (h14 : («$v5» = («$v34» + «$v1»))) + (h15 : («$sto4» = (store «$sto0» «$v5» «$v51»))) + (h16 : («$sto5» = (store «$sto4» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v3»))) + (h17 : (True ∧ ((«$v43» ≥ (0x0000000000000000000000000000000000000000000000000000000000000080#256)) ∧ («$v43» ≤ (0x000000000000000000000000000000000000000000000003ffffffffffffffff#256))))) + (h18 : («$v44» = («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000080#256)))) + (h19 : («$v45» = (if («$v44» < «$v43») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h20 : («$v52» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v44» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h21 : («$v54» = «$v45»)) + (h22 : («$v55» = («$v52» ||| «$v54»))) + (h23 : («$v47» = (if («$v55» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h24 : («$v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h25 : («$mem6» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))))) + (h26 : («$v23» = («$sto5» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h27 : («$v59» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v3» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h28 : («$v24» = (if («$v59» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h29 : («$v47» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h30 : («$v25» = («$v3» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h31 : («$v27» = («$v34» + «$v3»))) + (h32 : («$sto7» = (store «$sto5» «$v27» (0x0000000000000000000000000000000000000000000000000000000000000005#256)))) + (h33 : («$sto8» = (store «$sto7» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v25»))) + (h34 : («$v9» = (0x0000000000000000000000000000000000000000000000000000000000000003#256))) + (h35 : («$v37» = («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000040#256)))) + (h36 : («$mem9» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem6» («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v51»)))) + (h37 : («$v15» = («$sto8» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h38 : («$v16» = (0x0000000000000000000000000000000000000000000000000000000000000003#256))) + (h39 : («$mem10» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem9» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v25»)))) + (h40 : («$word1» = (if ((0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$v43») then «$v25» else (if ((((0x0000000000000000000000000000000000000000000000000000000000000000#256) - «$v43») ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) ∧ ((«$v43» - (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256))) then (0x0000000000000000000000000000000000000000000000000000000000000003#256) else ((((((((((((((((((((((((((((((((«$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)))))))) + (h41 : («$mem11» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem10» ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v51»)))) + (h42 : («$word2» = (if ((0x0000000000000000000000000000000000000000000000000000000000000020#256) = «$v43») then «$v51» else (if ((((0x0000000000000000000000000000000000000000000000000000000000000020#256) - «$v43») ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) ∧ ((«$v43» - (0x0000000000000000000000000000000000000000000000000000000000000020#256)) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256))) then «$word1» else ((((((((((((((((((((((((((((((((«$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)))))))) + (h43 : («$v24» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h44 : («$v9» = (0x0000000000000000000000000000000000000000000000000000000000000003#256))) + (h45 : («$v15» = «$v25»)) + (h46 : («$v49» = «$v51»)) + (h47 : («$v3» = «$v3»)) + (h48 : («$v23» = «$v3»)) + (h49 : (¬(«$v16» = (0x0000000000000000000000000000000000000000000000000000000000000003#256)))) + : False := by + try subst h13 + try subst h15 + try subst h16 + try subst h25 + try subst h32 + try subst h33 + try subst h36 + try subst h39 + try subst h41 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 3: `cse v51 eq v51 at the end of bb3`, its left operand +defined by `calldataload`. Query `Main-f0-bb3-v51-cse-3.smt2`. The query assumes the backend axioms +`heap-floor`. -/ +theorem f0_f_bb3_v51_cse_3 («$v29» : BitVec 256) («$v30» : BitVec 256) («$v31» : BitVec 256) («$v32» : BitVec 256) («$v50» : BitVec 256) («$v51» : BitVec 256) («$v49» : BitVec 256) («$v1» : BitVec 256) («$v57» : BitVec 256) («$v2» : BitVec 256) («$v3» : BitVec 256) («$v34» : BitVec 256) («$v5» : BitVec 256) («$v43» : BitVec 256) («$v44» : BitVec 256) («$v45» : BitVec 256) («$v52» : BitVec 256) («$v54» : BitVec 256) («$v55» : BitVec 256) («$v47» : BitVec 256) («$v23» : BitVec 256) («$v59» : BitVec 256) («$v24» : BitVec 256) («$v25» : BitVec 256) («$v27» : BitVec 256) («$v9» : BitVec 256) («$v37» : BitVec 256) («$v15» : BitVec 256) («$v16» : BitVec 256) («$word1» : BitVec 256) («$word2» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$sto4» : (BitVec 256 → BitVec 256)) («$sto5» : (BitVec 256 → BitVec 256)) («$mem6» : (BitVec 256 → BitVec 8)) («$sto7» : (BitVec 256 → BitVec 256)) («$sto8» : (BitVec 256 → BitVec 256)) («$mem9» : (BitVec 256 → BitVec 8)) («$mem10» : (BitVec 256 → BitVec 8)) («$mem11» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v29» = «$input_calldatasize»)) + (h1 : («$v29» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v30» = (if («$v29» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v31» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v32» = (if («$v31» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v50» = («$v30» ||| «$v32»))) + (h6 : («$v51» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v49» = («$v51» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v1» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v57» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v1» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h10 : («$v2» = (if («$v57» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h11 : («$v50» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h12 : («$v3» = («$v1» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))))) + (h14 : («$v5» = («$v34» + «$v1»))) + (h15 : («$sto4» = (store «$sto0» «$v5» «$v51»))) + (h16 : («$sto5» = (store «$sto4» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v3»))) + (h17 : (True ∧ ((«$v43» ≥ (0x0000000000000000000000000000000000000000000000000000000000000080#256)) ∧ («$v43» ≤ (0x000000000000000000000000000000000000000000000003ffffffffffffffff#256))))) + (h18 : («$v44» = («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000080#256)))) + (h19 : («$v45» = (if («$v44» < «$v43») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h20 : («$v52» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v44» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h21 : («$v54» = «$v45»)) + (h22 : («$v55» = («$v52» ||| «$v54»))) + (h23 : («$v47» = (if («$v55» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h24 : («$v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h25 : («$mem6» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))))) + (h26 : («$v23» = («$sto5» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h27 : («$v59» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v3» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h28 : («$v24» = (if («$v59» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h29 : («$v47» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h30 : («$v25» = («$v3» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h31 : («$v27» = («$v34» + «$v3»))) + (h32 : («$sto7» = (store «$sto5» «$v27» (0x0000000000000000000000000000000000000000000000000000000000000005#256)))) + (h33 : («$sto8» = (store «$sto7» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v25»))) + (h34 : («$v9» = (0x0000000000000000000000000000000000000000000000000000000000000003#256))) + (h35 : («$v37» = («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000040#256)))) + (h36 : («$mem9» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem6» («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v51»)) («$v37» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v51»)) («$v37» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v51»)))) + (h37 : («$v15» = («$sto8» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h38 : («$v16» = (0x0000000000000000000000000000000000000000000000000000000000000003#256))) + (h39 : («$mem10» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem9» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v25»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v25»)))) + (h40 : («$word1» = (if ((0x0000000000000000000000000000000000000000000000000000000000000000#256) = «$v43») then «$v25» else (if ((((0x0000000000000000000000000000000000000000000000000000000000000000#256) - «$v43») ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) ∧ ((«$v43» - (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256))) then (0x0000000000000000000000000000000000000000000000000000000000000003#256) else ((((((((((((((((((((((((((((((((«$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)))) ++ («$mem10» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)))) ++ («$mem10» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)))))))) + (h41 : («$mem11» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem10» ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v51»)) ((0x0000000000000000000000000000000000000000000000000000000000000020#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v51»)))) + (h42 : («$word2» = (if ((0x0000000000000000000000000000000000000000000000000000000000000020#256) = «$v43») then «$v51» else (if ((((0x0000000000000000000000000000000000000000000000000000000000000020#256) - «$v43») ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) ∧ ((«$v43» - (0x0000000000000000000000000000000000000000000000000000000000000020#256)) ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256))) then «$word1» else ((((((((((((((((((((((((((((((((«$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)))) ++ («$mem11» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)))) ++ («$mem11» («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)))))))) + (h43 : («$v24» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h44 : («$v9» = (0x0000000000000000000000000000000000000000000000000000000000000003#256))) + (h45 : («$v15» = «$v25»)) + (h46 : («$v16» = (0x0000000000000000000000000000000000000000000000000000000000000003#256))) + (h47 : («$v49» = «$v51»)) + (h48 : («$v3» = «$v3»)) + (h49 : («$v23» = «$v3»)) + (h50 : (¬(«$v51» = «$v51»))) + : False := by + try subst h13 + try subst h15 + try subst h16 + try subst h25 + try subst h32 + try subst h33 + try subst h36 + try subst h39 + try subst h41 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 4: `check_elim v49 eq v51 at the end of bb5`, its left +operand defined by `and`. Query `Main-f0-bb5-v49-check_elim-4.smt2`. -/ +theorem f0_f_bb5_v49_check_elim_4 («$v29» : BitVec 256) («$v30» : BitVec 256) («$v31» : BitVec 256) («$v32» : BitVec 256) («$v50» : BitVec 256) («$v51» : BitVec 256) («$v49» : BitVec 256) («$v1» : BitVec 256) («$v57» : BitVec 256) («$v2» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v29» = «$input_calldatasize»)) + (h1 : («$v29» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v30» = (if («$v29» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v31» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v32» = (if («$v31» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v50» = («$v30» ||| «$v32»))) + (h6 : («$v51» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v49» = («$v51» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v1» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v57» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v1» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h10 : («$v2» = (if («$v57» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h11 : («$v50» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h12 : (¬(«$v49» = «$v51»))) + : False := by + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 5: `cse v3 eq v3 at the end of bb6`, its left operand +defined by `add`. Query `Main-f0-bb6-v3-cse-5.smt2`. The query assumes the backend axioms +`heap-floor`. -/ +theorem f0_f_bb6_v3_cse_5 («$v29» : BitVec 256) («$v30» : BitVec 256) («$v31» : BitVec 256) («$v32» : BitVec 256) («$v50» : BitVec 256) («$v51» : BitVec 256) («$v49» : BitVec 256) («$v1» : BitVec 256) («$v57» : BitVec 256) («$v2» : BitVec 256) («$v3» : BitVec 256) («$v34» : BitVec 256) («$v5» : BitVec 256) («$v43» : BitVec 256) («$v44» : BitVec 256) («$v45» : BitVec 256) («$v52» : BitVec 256) («$v54» : BitVec 256) («$v55» : BitVec 256) («$v47» : BitVec 256) («$v23» : BitVec 256) («$v59» : BitVec 256) («$v24» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$sto4» : (BitVec 256 → BitVec 256)) («$sto5» : (BitVec 256 → BitVec 256)) («$mem6» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v29» = «$input_calldatasize»)) + (h1 : («$v29» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v30» = (if («$v29» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v31» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v32» = (if («$v31» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v50» = («$v30» ||| «$v32»))) + (h6 : («$v51» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v49» = («$v51» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v1» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v57» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v1» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h10 : («$v2» = (if («$v57» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h11 : («$v50» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h12 : («$v3» = («$v1» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))))) + (h14 : («$v5» = («$v34» + «$v1»))) + (h15 : («$sto4» = (store «$sto0» «$v5» «$v51»))) + (h16 : («$sto5» = (store «$sto4» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v3»))) + (h17 : (True ∧ ((«$v43» ≥ (0x0000000000000000000000000000000000000000000000000000000000000080#256)) ∧ («$v43» ≤ (0x000000000000000000000000000000000000000000000003ffffffffffffffff#256))))) + (h18 : («$v44» = («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000080#256)))) + (h19 : («$v45» = (if («$v44» < «$v43») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h20 : («$v52» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v44» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h21 : («$v54» = «$v45»)) + (h22 : («$v55» = («$v52» ||| «$v54»))) + (h23 : («$v47» = (if («$v55» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h24 : («$v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h25 : («$mem6» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))))) + (h26 : («$v23» = («$sto5» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h27 : («$v59» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v3» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h28 : («$v24» = (if («$v59» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h29 : («$v47» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h30 : («$v49» = «$v51»)) + (h31 : (¬(«$v3» = «$v3»))) + : False := by + try subst h13 + try subst h15 + try subst h16 + try subst h25 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 6: `cse v23 eq v3 at the end of bb6`, its left operand +defined by `sload`. Query `Main-f0-bb6-v23-cse-6.smt2`. The query assumes the backend axioms +`heap-floor`. Its goal depends on the unconstrained values `v34`. -/ +theorem f0_f_bb6_v23_cse_6 («$v29» : BitVec 256) («$v30» : BitVec 256) («$v31» : BitVec 256) («$v32» : BitVec 256) («$v50» : BitVec 256) («$v51» : BitVec 256) («$v49» : BitVec 256) («$v1» : BitVec 256) («$v57» : BitVec 256) («$v2» : BitVec 256) («$v3» : BitVec 256) («$v34» : BitVec 256) («$v5» : BitVec 256) («$v43» : BitVec 256) («$v44» : BitVec 256) («$v45» : BitVec 256) («$v52» : BitVec 256) («$v54» : BitVec 256) («$v55» : BitVec 256) («$v47» : BitVec 256) («$v23» : BitVec 256) («$v59» : BitVec 256) («$v24» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$sto4» : (BitVec 256 → BitVec 256)) («$sto5» : (BitVec 256 → BitVec 256)) («$mem6» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v29» = «$input_calldatasize»)) + (h1 : («$v29» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v30» = (if («$v29» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v31» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v32» = (if («$v31» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v50» = («$v30» ||| «$v32»))) + (h6 : («$v51» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h7 : («$v49» = («$v51» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h8 : («$v1» = («$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : («$v57» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v1» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h10 : («$v2» = (if («$v57» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h11 : («$v50» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h12 : («$v3» = («$v1» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h13 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000000#256))))) + (h14 : («$v5» = («$v34» + «$v1»))) + (h15 : («$sto4» = (store «$sto0» «$v5» «$v51»))) + (h16 : («$sto5» = (store «$sto4» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$v3»))) + (h17 : (True ∧ ((«$v43» ≥ (0x0000000000000000000000000000000000000000000000000000000000000080#256)) ∧ («$v43» ≤ (0x000000000000000000000000000000000000000000000003ffffffffffffffff#256))))) + (h18 : («$v44» = («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000080#256)))) + (h19 : («$v45» = (if («$v44» < «$v43») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h20 : («$v52» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v44» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h21 : («$v54» = «$v45»)) + (h22 : («$v55» = («$v52» ||| «$v54»))) + (h23 : («$v47» = (if («$v55» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h24 : («$v2» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h25 : («$mem6» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem3» («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))) («$v43» + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 (0x0000000000000000000000000000000000000000000000000000000000000003#256))))) + (h26 : («$v23» = («$sto5» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h27 : («$v59» = (if ((0x0000000000000000000000000000000000000000000000000000000000000040#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v3» >>> (0x0000000000000000000000000000000000000000000000000000000000000040#256))))) + (h28 : («$v24» = (if («$v59» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h29 : («$v47» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h30 : («$v49» = «$v51»)) + (h31 : («$v3» = «$v3»)) + (h32 : (¬(«$v23» = «$v3»))) + : False := by + try subst h13 + try subst h15 + try subst h16 + try subst h25 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.C9 diff --git a/SolidCore/Refinement/Facts/D1.lean b/SolidCore/Refinement/Facts/D1.lean new file mode 100644 index 00000000..ddf81754 --- /dev/null +++ b/SolidCore/Refinement/Facts/D1.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/d1.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `d1.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 0. Proved by Z3: 0. Checked in Lean by the prover and +emitted here: 0. + +Fact kinds in this module: +- none: no optimization of this contract relied on a recorded fact. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.D1 + +end SolidCore.Refinement.Facts.D1 diff --git a/SolidCore/Refinement/Facts/D2.lean b/SolidCore/Refinement/Facts/D2.lean new file mode 100644 index 00000000..67f01c09 --- /dev/null +++ b/SolidCore/Refinement/Facts/D2.lean @@ -0,0 +1,98 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/d2.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `d2.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 2. Proved by Z3: 2. Checked in Lean by the prover and +emitted here: 2. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.D2 + +/-- Contract `Main`, function `#0 f`, fact 0: `check_elim v3 ne 0x0 at the end of bb4`, its left +operand defined by `ne`. Query `Main-f0-bb4-v3-check_elim-0.smt2`. -/ +theorem f0_f_bb4_v3_check_elim_0 («$v13» : BitVec 256) («$v14» : BitVec 256) («$v15» : BitVec 256) («$v16» : BitVec 256) («$v18» : BitVec 256) («$v19» : BitVec 256) («$v28» : BitVec 256) («$v20» : BitVec 256) («$v21» : BitVec 256) («$v22» : BitVec 256) («$v23» : BitVec 256) («$v24» : BitVec 256) («$v29» : BitVec 256) («$v1» : BitVec 256) («$v3» : BitVec 256) («$v8» : BitVec 256) («$v9» : BitVec 256) («$v27» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v13» = «$input_calldatasize»)) + (h1 : («$v13» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v14» = (if («$v13» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v15» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v16» = («$v15» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h5 : («$v18» = («$v13» - (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h6 : («$v19» = (if («$v18» < «$v15») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h7 : («$v28» = («$v14» ||| «$v19»))) + (h8 : («$v20» = («$input_calldataload» «$v16»))) + (h9 : («$v21» = («$v16» + (0x0000000000000000000000000000000000000000000000000000000000000020#256)))) + (h10 : («$v22» = («$v13» - «$v21»))) + (h11 : («$v23» = (if ((0x0000000000000000000000000000000000000000000000000000000000000005#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v22» >>> (0x0000000000000000000000000000000000000000000000000000000000000005#256))))) + (h12 : («$v24» = (if («$v23» < «$v20») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h13 : («$v29» = («$v28» ||| «$v24»))) + (h14 : («$v1» = (if («$v20» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h15 : («$v29» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h16 : («$v3» = (if («$v20» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h17 : («$v8» = («$input_calldataload» «$v21»))) + (h18 : («$v9» = (if («$v8» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h19 : («$v1» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h20 : («$v27» = («$v8» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h21 : («$v9» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h22 : (¬(¬(«$v3» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))))) + : False := by + have ack0 : (0x0000000000000000000000000000000000000000000000000000000000000004#256) = «$v16» → «$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256) = «$input_calldataload» «$v16» := fun e0 => congrArg «$input_calldataload» e0 + have ack1 : (0x0000000000000000000000000000000000000000000000000000000000000004#256) = «$v21» → «$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256) = «$input_calldataload» «$v21» := fun e0 => congrArg «$input_calldataload» e0 + have ack2 : «$v16» = «$v21» → «$input_calldataload» «$v16» = «$input_calldataload» «$v21» := fun e0 => congrArg «$input_calldataload» e0 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 1: `check_elim v27 eq v8 at the end of bb4`, its left +operand defined by `and`. Query `Main-f0-bb4-v27-check_elim-1.smt2`. -/ +theorem f0_f_bb4_v27_check_elim_1 («$v13» : BitVec 256) («$v14» : BitVec 256) («$v15» : BitVec 256) («$v16» : BitVec 256) («$v18» : BitVec 256) («$v19» : BitVec 256) («$v28» : BitVec 256) («$v20» : BitVec 256) («$v21» : BitVec 256) («$v22» : BitVec 256) («$v23» : BitVec 256) («$v24» : BitVec 256) («$v29» : BitVec 256) («$v1» : BitVec 256) («$v3» : BitVec 256) («$v8» : BitVec 256) («$v9» : BitVec 256) («$v27» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v13» = «$input_calldatasize»)) + (h1 : («$v13» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v14» = (if («$v13» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v15» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v16» = («$v15» + (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h5 : («$v18» = («$v13» - (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h6 : («$v19» = (if («$v18» < «$v15») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h7 : («$v28» = («$v14» ||| «$v19»))) + (h8 : («$v20» = («$input_calldataload» «$v16»))) + (h9 : («$v21» = («$v16» + (0x0000000000000000000000000000000000000000000000000000000000000020#256)))) + (h10 : («$v22» = («$v13» - «$v21»))) + (h11 : («$v23» = (if ((0x0000000000000000000000000000000000000000000000000000000000000005#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v22» >>> (0x0000000000000000000000000000000000000000000000000000000000000005#256))))) + (h12 : («$v24» = (if («$v23» < «$v20») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h13 : («$v29» = («$v28» ||| «$v24»))) + (h14 : («$v1» = (if («$v20» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h15 : («$v29» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h16 : («$v3» = (if («$v20» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h17 : («$v8» = («$input_calldataload» «$v21»))) + (h18 : («$v9» = (if («$v8» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h19 : («$v1» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h20 : («$v27» = («$v8» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h21 : («$v9» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h22 : (¬(«$v3» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h23 : (¬(«$v27» = «$v8»))) + : False := by + have ack0 : (0x0000000000000000000000000000000000000000000000000000000000000004#256) = «$v16» → «$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256) = «$input_calldataload» «$v16» := fun e0 => congrArg «$input_calldataload» e0 + have ack1 : (0x0000000000000000000000000000000000000000000000000000000000000004#256) = «$v21» → «$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256) = «$input_calldataload» «$v21» := fun e0 => congrArg «$input_calldataload» e0 + have ack2 : «$v16» = «$v21» → «$input_calldataload» «$v16» = «$input_calldataload» «$v21» := fun e0 => congrArg «$input_calldataload» e0 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.D2 diff --git a/SolidCore/Refinement/Facts/D3.lean b/SolidCore/Refinement/Facts/D3.lean new file mode 100644 index 00000000..6bae2e23 --- /dev/null +++ b/SolidCore/Refinement/Facts/D3.lean @@ -0,0 +1,53 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/d3.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `d3.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 1. Proved by Z3: 1. Checked in Lean by the prover and +emitted here: 1. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.D3 + +/-- Contract `Main`, function `#0 f`, fact 0: `check_elim v17 eq v9 at the end of bb5`, its left +operand defined by `and`. Query `Main-f0-bb5-v17-check_elim-0.smt2`. -/ +theorem f0_f_bb5_v17_check_elim_0 («$v14» : BitVec 256) («$v15» : BitVec 256) («$v3» : BitVec 256) («$v4» : BitVec 256) («$v18» : BitVec 256) («$v19» : BitVec 256) («$v5» : BitVec 256) («$v9» : BitVec 256) («$v10» : BitVec 256) («$v17» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v14» = «$input_calldatasize»)) + (h1 : («$v14» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v15» = (if («$v14» < (0x0000000000000000000000000000000000000000000000000000000000000044#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v3» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h4 : («$v4» = (if («$v3» > (0x0000000000000000000000000000000000000000000000000000000000000001#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h5 : («$v18» = («$v15» ||| «$v4»))) + (h6 : («$v19» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h7 : («$v5» = (if («$v19» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h8 : («$v18» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h9 : («$v9» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h10 : («$v10» = (if («$v9» > (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h11 : (¬(«$v5» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h12 : («$v17» = («$v9» &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256)))) + (h13 : («$v10» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h14 : (¬(«$v17» = «$v9»))) + : False := by + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.D3 diff --git a/SolidCore/Refinement/Facts/D4.lean b/SolidCore/Refinement/Facts/D4.lean new file mode 100644 index 00000000..3d6e9f8b --- /dev/null +++ b/SolidCore/Refinement/Facts/D4.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/d4.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `d4.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 0. Proved by Z3: 0. Checked in Lean by the prover and +emitted here: 0. + +Fact kinds in this module: +- none: no optimization of this contract relied on a recorded fact. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.D4 + +end SolidCore.Refinement.Facts.D4 diff --git a/SolidCore/Refinement/Facts/Prelude.lean b/SolidCore/Refinement/Facts/Prelude.lean new file mode 100644 index 00000000..3d755a90 --- /dev/null +++ b/SolidCore/Refinement/Facts/Prelude.lean @@ -0,0 +1,14 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. + +import Std.Tactic.BVDecide + +/-! The definitions shared by the theorems solar's Lean translator writes. -/ + +namespace SolidCore.Refinement.Facts + +/-- An SMT-LIB array `store`: `m` with index `i` mapped to `v`. -/ +def store {a b : Nat} (m : BitVec a → BitVec b) (i : BitVec a) (v : BitVec b) : + BitVec a → BitVec b := + fun j => if j = i then v else m j + +end SolidCore.Refinement.Facts diff --git a/SolidCore/Refinement/Facts/W1.lean b/SolidCore/Refinement/Facts/W1.lean new file mode 100644 index 00000000..98a3cc2b --- /dev/null +++ b/SolidCore/Refinement/Facts/W1.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/w1.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `w1.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 0. Proved by Z3: 0. Checked in Lean by the prover and +emitted here: 0. + +Fact kinds in this module: +- none: no optimization of this contract relied on a recorded fact. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.W1 + +end SolidCore.Refinement.Facts.W1 diff --git a/SolidCore/Refinement/Facts/W2.lean b/SolidCore/Refinement/Facts/W2.lean new file mode 100644 index 00000000..852b3f9b --- /dev/null +++ b/SolidCore/Refinement/Facts/W2.lean @@ -0,0 +1,66 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/w2.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `w2.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 2. Proved by Z3: 2. Checked in Lean by the prover and +emitted here: 2. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.W2 + +/-- Contract `Main`, function `#0 f`, fact 0: `check_elim v7 eq 0x0 at the end of bb1`, its left +operand defined by `lt`. Query `Main-f0-bb1-v7-check_elim-0.smt2`. -/ +theorem f0_f_bb1_v7_check_elim_0 («$v8» : BitVec 256) («$v9» : BitVec 256) («$v10» : BitVec 256) («$v11» : BitVec 256) («$v0» : BitVec 256) («$v1» : BitVec 256) («$v7» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v8» = «$input_calldatasize»)) + (h1 : («$v8» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v9» = (if («$v8» < (0x0000000000000000000000000000000000000000000000000000000000000044#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v10» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v11» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h5 : («$v0» = (if («$v11» < «$v10») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h6 : («$v9» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h7 : («$v1» = («$v10» - «$v11»))) + (h8 : («$v7» = (if («$v10» < «$v11») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h9 : (¬(«$v0» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h10 : (¬(«$v7» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + : False := by + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +/-- Contract `Main`, function `#0 f`, fact 1: `check_elim v0 eq 0x0 at the end of bb2`, its left +operand defined by `lt`. Query `Main-f0-bb2-v0-check_elim-1.smt2`. -/ +theorem f0_f_bb2_v0_check_elim_1 («$v8» : BitVec 256) («$v9» : BitVec 256) («$v10» : BitVec 256) («$v11» : BitVec 256) («$v0» : BitVec 256) («$v2» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v8» = «$input_calldatasize»)) + (h1 : («$v8» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v9» = (if («$v8» < (0x0000000000000000000000000000000000000000000000000000000000000044#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v10» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v11» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000024#256)))) + (h5 : («$v0» = (if («$v11» < «$v10») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h6 : («$v9» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h7 : («$v2» = («$v11» - «$v10»))) + (h8 : («$v0» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h9 : (¬(«$v0» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + : False := by + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.W2 diff --git a/SolidCore/Refinement/Facts/W3.lean b/SolidCore/Refinement/Facts/W3.lean new file mode 100644 index 00000000..8eb64efc --- /dev/null +++ b/SolidCore/Refinement/Facts/W3.lean @@ -0,0 +1,53 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/w3.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `w3.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 1. Proved by Z3: 1. Checked in Lean by the prover and +emitted here: 1. + +Fact kinds in this module: +- `check_elim`: a branch, check, overflow test or equality that check elimination decided. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.W3 + +/-- Contract `Main`, function `#0 f`, fact 0: `check_elim v7 eq v11 at the end of bb2`, its left +operand defined by `and`. Query `Main-f0-bb2-v7-check_elim-0.smt2`. -/ +theorem f0_f_bb2_v7_check_elim_0 («$v1» : BitVec 256) («$v2» : BitVec 256) («$v3» : BitVec 256) («$v12» : BitVec 256) («$v14» : BitVec 256) («$v15» : BitVec 256) («$v10» : BitVec 256) («$v11» : BitVec 256) («$v7» : BitVec 256) («$v8» : BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) («$mem3» : (BitVec 256 → BitVec 8)) («$input_calldatasize» : BitVec 256) («$input_calldataload» : BitVec 256 → BitVec 256) + (h0 : («$v1» = «$input_calldatasize»)) + (h1 : («$v1» ≤ (0x000000000000000000000000000000000000000000000000ffffffffffffffff#256))) + (h2 : («$v2» = (if («$v1» < (0x0000000000000000000000000000000000000000000000000000000000000024#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h3 : («$v3» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h4 : («$v12» = (if ((0x00000000000000000000000000000000000000000000000000000000000000a0#256) ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$v3» >>> (0x00000000000000000000000000000000000000000000000000000000000000a0#256))))) + (h5 : («$v14» = «$v2»)) + (h6 : («$v15» = («$v12» ||| «$v14»))) + (h7 : («$v10» = (if («$v15» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h8 : («$v11» = («$input_calldataload» (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) + (h9 : («$v7» = («$v11» &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)))) + (h10 : («$v8» = («$v11» ^^^ (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) + (h11 : («$mem3» = (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store «$mem0» ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000000#256)) (BitVec.extractLsb' 248 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000001#256)) (BitVec.extractLsb' 240 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000002#256)) (BitVec.extractLsb' 232 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000003#256)) (BitVec.extractLsb' 224 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000004#256)) (BitVec.extractLsb' 216 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000005#256)) (BitVec.extractLsb' 208 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000006#256)) (BitVec.extractLsb' 200 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000007#256)) (BitVec.extractLsb' 192 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000008#256)) (BitVec.extractLsb' 184 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000009#256)) (BitVec.extractLsb' 176 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000a#256)) (BitVec.extractLsb' 168 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000b#256)) (BitVec.extractLsb' 160 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000c#256)) (BitVec.extractLsb' 152 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000d#256)) (BitVec.extractLsb' 144 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000e#256)) (BitVec.extractLsb' 136 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000000f#256)) (BitVec.extractLsb' 128 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000010#256)) (BitVec.extractLsb' 120 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000011#256)) (BitVec.extractLsb' 112 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000012#256)) (BitVec.extractLsb' 104 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000013#256)) (BitVec.extractLsb' 96 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000014#256)) (BitVec.extractLsb' 88 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000015#256)) (BitVec.extractLsb' 80 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000016#256)) (BitVec.extractLsb' 72 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000017#256)) (BitVec.extractLsb' 64 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000018#256)) (BitVec.extractLsb' 56 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x0000000000000000000000000000000000000000000000000000000000000019#256)) (BitVec.extractLsb' 48 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001a#256)) (BitVec.extractLsb' 40 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001b#256)) (BitVec.extractLsb' 32 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001c#256)) (BitVec.extractLsb' 24 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001d#256)) (BitVec.extractLsb' 16 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001e#256)) (BitVec.extractLsb' 8 8 «$v8»)) ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + (0x000000000000000000000000000000000000000000000000000000000000001f#256)) (BitVec.extractLsb' 0 8 «$v8»)))) + (h12 : («$v10» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) + (h13 : (¬(«$v7» = «$v11»))) + : False := by + try subst h11 + try simp only [store] at * + all_goals bv_decide (timeout := 600) + +end SolidCore.Refinement.Facts.W3 diff --git a/SolidCore/Refinement/Facts/W4.lean b/SolidCore/Refinement/Facts/W4.lean new file mode 100644 index 00000000..509fb108 --- /dev/null +++ b/SolidCore/Refinement/Facts/W4.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/w4.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `w4.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 0. Proved by Z3: 0. Checked in Lean by the prover and +emitted here: 0. + +Fact kinds in this module: +- none: no optimization of this contract relied on a recorded fact. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.W4 + +end SolidCore.Refinement.Facts.W4 diff --git a/SolidCore/Refinement/Facts/W5.lean b/SolidCore/Refinement/Facts/W5.lean new file mode 100644 index 00000000..329f299f --- /dev/null +++ b/SolidCore/Refinement/Facts/W5.lean @@ -0,0 +1,31 @@ +-- Generated by scripts/refinement/facts.sh. Do not edit. +-- Source: scripts/refinement/corpus/w5.sol +-- solar: solar 0.3.0-dev+commit.9688f215 +-- solar commit: 9688f21581717743806cb7bf3afae2ac3c156a08 + +import SolidCore.Refinement.Facts.Prelude + +/-! +# solar's analysis facts for `w5.sol` + +Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the +query `-Zprove-analyses` writes for one fact an optimization relied on in contract +`Main`, compiled at `-O gas`: the definitions of the values in the blocks that +dominate the fact's program point, with EVM word semantics, the branch conditions into +them and the facts checked before it, together with the fact's negation, imply `False`. +They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode. + +Facts recorded: 0. Proved by Z3: 0. Checked in Lean by the prover and +emitted here: 0. + +Fact kinds in this module: +- none: no optimization of this contract relied on a recorded fact. +-/ + +set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false + +namespace SolidCore.Refinement.Facts.W5 + +end SolidCore.Refinement.Facts.W5 diff --git a/SolidCore/Refinement/Fuel.lean b/SolidCore/Refinement/Fuel.lean new file mode 100644 index 00000000..dd39dbda --- /dev/null +++ b/SolidCore/Refinement/Fuel.lean @@ -0,0 +1,87 @@ +import SolidCore.Refinement.Behaviours +import SolidCore.Solidity.FuelExtension + +/-! +# Fuel never makes a SolidCore result + +`Source.run fuel` runs the constructor, then the ABI dispatcher, both with statement fuel `fuel`. +`SolidCore.Solidity.Source.ABI.Contract.callCalldataAtFromWithContext?_fuel_mono` +(`Solidity/FuelExtension.lean`) proves the dispatcher fuel-monotone along every path, so a +dispatched call that gives a result at some fuel gives the same result at every higher fuel: +running out of statement fuel only withholds a result (`none`), never produces one. + +`run_fuel_mono` lifts that to `Source.run` for a contract whose constructor gives the same +result at both fuels (`CtorStable`). The constructor runs under a self-dispatch hook whose depth +is the fuel itself (`CheckedContract.constructWithContext?`), so its tree is not literally the same +function of the fuel; the hook is unreachable during construction (a self-call there reverts or +fails closed before reaching it), but that is not proved here, so `CtorStable` stays a hypothesis. + +`Refines.fuel_mono` and `Satisfies.fuel_mono` carry the end-to-end statements to every higher +fuel under the same hypothesis: a theorem proved at the fuel the corpus fixes is not an artefact +of that fuel. +-/ + +namespace SolidCore.Refinement + +open SolidCore.Solidity SolidCore.Solidity.Source + +/-- The context `Source.result?` runs `contract` in for `call`. -/ +def Source.contextOf (contract : TypeCheck.CheckedContract) (call : Call) : Context := + { contract.core.context with sender := callerAddress, self := selfAddress, value := call.callvalue } + +/-- The constructor gives the same result at fuels `n` and `m`. -/ +def CtorStable (n m : Nat) (contract : TypeCheck.CheckedContract) (call : Call) : Prop := + TypeCheck.CheckedContract.constructWithContext? n contract (Source.contextOf contract call) + State.empty selfAddress 0 [] = + TypeCheck.CheckedContract.constructWithContext? m contract (Source.contextOf contract call) + State.empty selfAddress 0 [] + +theorem Source.result?_fuel_mono {n m : Nat} (hnm : n ≤ m) + {contract : TypeCheck.CheckedContract} {call : Call} (hctor : CtorStable n m contract call) + {r : TypeCheck.CoreAbiCallResult} (h : Source.result? n contract call = some r) : + Source.result? m contract call = some r := by + unfold Source.result? at h ⊢ + unfold CtorStable Source.contextOf at hctor + dsimp only at h hctor ⊢ + rw [← hctor] + split at h + next deployed _ hdep => + unfold TypeCheck.CheckedContract.callCalldataAtFromWithContext? at h ⊢ + exact ABI.Contract.callCalldataAtFromWithContext?_fuel_mono hnm h + next => cases h + +/-- **A finished SolidCore run is the run at every higher fuel**, for a stable constructor. -/ +theorem Source.run_fuel_mono {n m : Nat} (hnm : n ≤ m) + {contract : TypeCheck.CheckedContract} {call : Call} (hctor : CtorStable n m contract call) + {obs : Observable} (h : Source.run n contract call = some obs) : + Source.run m contract call = some obs := by + unfold Source.run at h ⊢ + obtain ⟨r, hr, rfl⟩ := Option.map_eq_some_iff.mp h + rw [Source.result?_fuel_mono hnm hctor hr] + rfl + +theorem Refines.fuel_mono {n m : Nat} (hnm : n ≤ m) + {contract : TypeCheck.CheckedContract} {code : ByteArray} {scope : Call → Prop} + (hctor : ∀ call, scope call → CtorStable n m contract call) + (h : Refines n contract code scope) : Refines m contract code scope := by + intro call hc + obtain ⟨obs, h1, h2⟩ := h call hc + exact ⟨obs, Source.run_fuel_mono hnm (hctor call hc) h1, h2⟩ + +theorem Satisfies.fuel_mono {n m : Nat} (hnm : n ≤ m) + {contract : TypeCheck.CheckedContract} {scope pre : Call → Prop} + {post : Call → Observable → Prop} + (hctor : ∀ call, scope call → CtorStable n m contract call) + (h : Satisfies (solidCore n) contract scope pre post) : + Satisfies (solidCore m) contract scope pre post := by + intro call hc hp + obtain ⟨obs, h1, h2⟩ := h call hc hp + exact ⟨obs, Source.run_fuel_mono hnm (hctor call hc) h1, h2⟩ + +/-- +info: 'SolidCore.Refinement.Source.run_fuel_mono' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms Source.run_fuel_mono + +end SolidCore.Refinement diff --git a/SolidCore/Refinement/Generic/CallNode.lean b/SolidCore/Refinement/Generic/CallNode.lean new file mode 100644 index 00000000..827cea35 --- /dev/null +++ b/SolidCore/Refinement/Generic/CallNode.lean @@ -0,0 +1,456 @@ +import SolidCore.Refinement.SourceOracle +import SolidCore.Solidity.AdoptionLaws + +/-! +# The call node of SolidCore's source semantics + +`eval_tryCall`: a `tryExternalCall` statement whose target is not the contract itself (no +self-dispatch), with no gas option and no `extcodesize` guard (solc skips it for a call that +expects return data), evaluates to one request node: the query of an external call of the +sent world (`snapshotWorld`), continued by the interpreter's own continuation (`tryTail`) on the +decoded response and the adopted world. +-/ + +namespace SolidCore.Refinement.CallNode + +open SolidCore.Solidity.Source EvmCompiler.Simulation + +/-- The interpreter's continuation of a `tryExternalCall` after the call answered. -/ +def tryTail (fuel : Nat) (table : FunctionTable) (context : Context) (runtime''' : Runtime) + (returns : List BindingDecl) (returnAbiCleanups : List AbiCleanup) (successBody : Stmt) + (catchClauses : List TryCatchClause) (callResult : LowLevelCallResult) (adoptedState : State) : + SolI Result := + let runtimeWithInteraction := + { runtime''' with state := adoptedState }.recordExternalInteraction + (ExternalInteraction.lowLevelCall callResult) + let success := callResult.success + let output := callResult.output.map normByte + if success then + match abiDecodeValuesExcept? (returns.map BindingDecl.ty) output with + | Except.ok decoded => + if AbiCleanups.acceptOrUnspecified returnAbiCleanups decoded then + match BindingDecl.bindArgs? returns decoded with + | some frame => do + let result ← Stmt.eval fuel table context (runtimeWithInteraction.withFrame frame) + successBody + pure (result.mapRuntime Runtime.popScope) + | none => pure (Result.reverted runtimeWithInteraction RevertData.typeMismatch) + else pure (Result.reverted runtimeWithInteraction RevertData.empty) + | Except.error revertData => pure (Result.reverted runtimeWithInteraction revertData) + else + match TryCatchClause.findMatch? output catchClauses with + | some (frame, body) => do + let result ← Stmt.eval fuel table context (runtimeWithInteraction.withFrame frame) body + pure (result.mapRuntime Runtime.popScope) + | none => pure (Result.reverted runtimeWithInteraction (RevertData.fromRawBytes output)) + +/-- **The call node**: a `tryExternalCall` of a target other than the contract itself, with no gas +option and no code guard, asks the external call of the sent world and continues with `tryTail`. -/ +theorem eval_tryCall (n : Nat) (table : FunctionTable) (context : Context) (rt : Runtime) + (kind : LowLevelCallKind) (tgt cdE valE : Expr) (gasFirst : Bool) (returns : List BindingDecl) + (cleanups : List AbiCleanup) (succ : Stmt) (catches : List TryCatchClause) + {tv vv cdv : Value} {rt1 rt2 rt3 : Runtime} {t v : Word} {cd : List Byte} + (ht : tgt.evalWithRuntimeByContext context rt = .ok (tv, rt1)) (htw : tv.expectWord = .ok t) + (hv : valE.evalWithRuntimeByContext context rt1 = .ok (vv, rt2)) (hvw : vv.expectWord = .ok v) + (hc : cdE.evalWithRuntimeByContext context rt2 = .ok (cdv, rt3)) (hcb : cdv.asBytes? = some cd) + (hself : wordEq t context.self = false) : + Stmt.eval (n + 1) table context rt + (.tryExternalCall kind tgt cdE valE none gasFirst false returns cleanups succ catches) = + .request (.external (snapshotWorld context rt3.state) + (.call (buildCallRequest context kind t cd v none))) + (fun resp => tryTail n table context rt3 returns cleanups succ catches + (decodeCallResponse resp kind t cd v none) (adoptWorld resp.postWorld context rt3.state)) := by + rw [Stmt.eval] + simp only [ht, htw, hv, hvw, hc, hcb, hself, Bool.and_false, Bool.false_and, Bool.or_false, + Bool.not_false, Bool.true_and, Bool.and_self, Bool.false_eq_true, if_false] + simp only [selfDispatchCall, hself, Bool.and_false, Bool.false_eq_true, if_false, emitLowLevelCall] + rfl + + +theorem eval_block (n : Nat) (table : FunctionTable) (context : Context) (rt : Runtime) + (ss : List Stmt) : + Stmt.eval (n + 1) table context rt (.block ss) = + (Stmt.evalList n table context rt.pushScope ss >>= fun r => + pure (r.mapRuntime Runtime.popScope)) := by + rw [Stmt.eval] + +theorem eval_varDecl_none (n : Nat) (table : FunctionTable) (context : Context) (rt : Runtime) + (ty : Ty) (x : String) : + Stmt.eval (n + 1) table context rt (.varDecl ty x none) = + pure (Result.normal (rt.declareLocal x ty.defaultValue)) := by + rw [Stmt.eval] + +theorem evalList_nil (n : Nat) (table : FunctionTable) (context : Context) (rt : Runtime) : + Stmt.evalList n table context rt [] = pure (Result.normal rt) := by + rw [Stmt.evalList] + +theorem evalList_cons (n : Nat) (table : FunctionTable) (context : Context) (rt : Runtime) + (s : Stmt) (ss : List Stmt) : + Stmt.evalList n table context rt (s :: ss) = + (Stmt.eval n table context rt s >>= fun r => + match r with + | Result.normal rt' => Stmt.evalList n table context rt' ss + | r => pure r) := by + rw [Stmt.evalList] + rfl + +theorem bind_request {α β : Type} (q : Query) (k : Answer q → SolI α) (f : α → SolI β) : + (Interaction.request q k >>= f) = Interaction.request q (fun a => k a >>= f) := rfl + +theorem sbind_pure {α β : Type} (a : α) (f : α → SolI β) : ((pure a : SolI α) >>= f) = f a := rfl + +theorem map_request {α β : Type} (q : Query) (k : Answer q → SolI α) (f : α → β) : + (f <$> Interaction.request q k : SolI β) = Interaction.request q (fun a => f <$> k a) := rfl + +theorem foldAns_request {α : Type} (ans : Ans) (h : List Interaction.Exchange) (q : Query) + (k : Answer q → SolI α) : + foldAns ans h (.request q k) = + match ans h q with + | some a => foldAns ans (h ++ [⟨q, a⟩]) (k a) + | none => none := by + rw [foldAns] + cases ans h q <;> rfl + +theorem foldAns_pure {α : Type} (ans : Ans) (h : List Interaction.Exchange) (a : α) : + foldAns ans h (pure a : SolI α) = some a := rfl + + +/-! ## Pieces of a call's evaluation -/ + +theorem ipure_bind {ε α β : Type} (a : α) (f : α → Interaction ε β) : + (Interaction.pure a).bind f = f a := rfl + +theorem mat_word (ctx : Context) (rt : Runtime) (w : Word) : + rt.materializeForValueUse ctx (.word w) = .ok (.word w) := by + unfold Runtime.materializeForValueUse + rw [Runtime.materializeForValueUseFuel] + all_goals intros + all_goals contradiction + +theorem word0_eval (ctx : Context) (rt : Runtime) : + (Expr.word 0).evalWithRuntimeByContext ctx rt = .ok (.word 0, rt) := rfl + +theorem headWords_uint256 : + (if Ty.uint256.isDynamicAbi = true then some 1 else Ty.uint256.staticAbiHeadWords?) = some 1 := + rfl + +theorem wordBytes_eq : SolidCore.Solidity.Source.wordBytes = 32 := rfl + +/-- A one-word return shorter than a word fails to decode, with empty revert data. -/ +theorem decode_short (bs : List Byte) (h : bs.length < 32) : + abiDecodeValuesExcept? [Ty.uint256] bs = .error .empty := by + simp [abiDecodeValuesExcept?, Ty.listAbiHeadWords?, Ty.abiHeadWords?, abiDecodeOpt, bind, + Except.bind, pure, Except.pure, headWords_uint256, wordBytes_eq, h] + +/-- A one-word return of at least a word decodes to its first word, big-endian. -/ +theorem decode_word (bs : List Byte) (h : 32 ≤ bs.length) : + abiDecodeValuesExcept? [Ty.uint256] bs = + .ok [.word (bytesToWordBE ((bs.map normByte).take 32))] := by + have : ¬ bs.length < 32 := by omega + simp [abiDecodeValuesExcept?, Ty.listAbiHeadWords?, Ty.abiHeadWords?, abiDecodeOpt, bind, + Except.bind, pure, Except.pure, abiDecodeValuesAux?, abiDecodeValueAt?, headWords_uint256, + wordBytes_eq, this] + rw [show Ty.uint256.abiDecodeFuel = 1 from rfl] + simp [abiDecodeValueAtWithFuel?, readWord?, readBytes?, wordBytes_eq, h, this, abiDecodeOpt] + rfl + +/-- With no catch clause, a failed call matches none. -/ +theorem findMatch_nil (raw : List Byte) : TryCatchClause.findMatch? raw [] = none := by + unfold TryCatchClause.findMatch? + cases revertClassify raw <;> rfl + + +theorem toList_loop (bs : ByteArray) : ∀ n i r, bs.size - i = n → + ByteArray.toList.loop bs i r = r.reverse ++ (List.range' i n).map bs.get! := by + intro n + induction n with + | zero => + intro i r h + rw [ByteArray.toList.loop] + rw [if_neg (by omega)] + simp + | succ n ih => + intro i r h + rw [ByteArray.toList.loop, if_pos (by omega), ih (i + 1) _ (by omega)] + simp [List.range'_succ] + +theorem byteArrayToBytes_eq (rd : ByteArray) : + byteArrayToBytes rd = (List.range rd.size).map (fun j => (rd.get! j).toNat) := by + unfold byteArrayToBytes ByteArray.toList + rw [toList_loop rd rd.size 0 [] (by omega), List.range_eq_range'] + simp + +theorem normByte_bytes (rd : ByteArray) : (byteArrayToBytes rd).map normByte = byteArrayToBytes rd := by + unfold byteArrayToBytes + simp only [List.map_map] + apply List.map_congr_left + intro x _ + simp [normByte, SolidCore.Solidity.Shared.Account.byte, Nat.mod_eq_of_lt (UInt8.toNat_lt x)] + +theorem map_pure' {α β : Type} (a : α) (f : α → β) : (f <$> (pure a : SolI α)) = pure (f a) := rfl + + +theorem toList_eq_data (bs : ByteArray) : bs.toList = bs.data.toList := by + unfold ByteArray.toList + rw [toList_loop bs bs.size 0 [] (by omega)] + obtain ⟨arr⟩ := bs + apply List.ext_getElem + · simp only [List.reverse_nil, List.nil_append, List.length_map, List.length_range', + Array.length_toList] + rfl + · intro i h1 h2 + simp only [List.reverse_nil, List.nil_append, List.getElem_map, List.getElem_range', + Array.getElem_toList, ByteArray.get!] + have : i < arr.size := by simpa using h2 + rw [getElem!_pos arr (0 + 1 * i) (by omega)] + simp + + +theorem norm_norm (x : Word) : + SolidCore.Solidity.Shared.norm (SolidCore.Solidity.Shared.norm x) = + SolidCore.Solidity.Shared.norm x := by + simp [SolidCore.Solidity.Shared.norm] + +theorem wf_insertLoop (m : StorageMap) (hm : StorageMap.WF m) (k v : Word) : + StorageMap.WF (m.insertLoop k v) := by + intro p hp + unfold StorageMap.insertLoop at hp + rw [Std.HashMap.mem_toList_iff_getElem?_eq_some, Std.HashMap.getElem?_insert] at hp + split at hp + · rename_i he + simp only [beq_iff_eq] at he + simp only [Option.some.injEq] at hp + rw [← he, ← hp] + exact ⟨norm_norm k, norm_norm v⟩ + · exact hm p (Std.HashMap.mem_toList_iff_getElem?_eq_some.mpr hp) + +theorem wf_foldl : ∀ (σ : List (Nat × Nat)) (m : StorageMap), StorageMap.WF m → + StorageMap.WF (σ.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) m) + | [], _, hm => hm + | kv :: σ, m, hm => wf_foldl σ _ (wf_insertLoop m hm kv.1 kv.2) + +theorem wf_of_toList_nil (m : StorageMap) (h : m.toList = []) : StorageMap.WF m := by + intro p hp + rw [h] at hp + cases hp + +/-! ## The code a sent world shows -/ + +theorem addr_val (x : Word) (hx : x < 2 ^ 160) : (wordToAddress x).val = x := by + simp [wordToAddress, wordToU256, EvmYul.AccountAddress.ofUInt256, EvmYul.UInt256.ofNat, Id.run, + EvmYul.UInt256.size, Fin.ofNat, EvmYul.AccountAddress.size] + omega + +theorem addr_eq {x y : Word} (hx : x < 2 ^ 160) (hy : y < 2 ^ 160) : + compare (wordToAddress x) (wordToAddress y) = .eq ↔ x = y := by + rw [Std.LawfulEqCmp.compare_eq_iff_eq] + constructor + · intro h + have := congrArg Fin.val h + rwa [addr_val x hx, addr_val y hy] at this + · intro h; rw [h] + +theorem find_fold (mk : Word → OpenAccount) (x : Word) (hx : x < 2 ^ 160) : + ∀ (cs : List (Word × OpenAccount)) (M : EvmYul.AddrMap OpenAccount), + (∀ e ∈ cs, e.1 < 2 ^ 160 ∧ e.2 = mk e.1) → + (cs.foldl (fun (acc : EvmYul.AddrMap OpenAccount) entry => acc.insert (wordToAddress entry.1) entry.2) + M).find? (wordToAddress x) = if x ∈ cs.map Prod.fst then some (mk x) else M.find? (wordToAddress x) + | [], M, _ => by simp + | e :: cs, M, hcs => by + simp only [List.foldl_cons, List.map_cons, List.mem_cons] + rw [find_fold mk x hx cs _ (fun e he => hcs e (List.mem_cons_of_mem _ he))] + obtain ⟨he1, he2⟩ := hcs e (List.mem_cons_self ..) + by_cases hin : x ∈ cs.map Prod.fst + · simp [hin] + · simp only [hin, or_false, if_false] + rw [RBTree.RBMap.find?_insert] + by_cases hxe : x = e.1 + · rw [if_pos ((addr_eq hx he1).mpr hxe), if_pos hxe, he2, hxe] + · rw [if_neg (fun h => hxe ((addr_eq hx he1).mp h)), if_neg hxe] + +theorem mem_dedup (x : Word) : ∀ (l acc : List Word), + x ∈ l.foldl (fun acc a => if acc.contains a then acc else acc ++ [a]) acc ↔ x ∈ acc ∨ x ∈ l + | [], acc => by simp + | a :: l, acc => by + simp only [List.foldl_cons] + rw [mem_dedup x l] + split + · rename_i h + have : a ∈ acc := by simpa using h + constructor + · rintro (h1 | h1) + · exact Or.inl h1 + · exact Or.inr (List.mem_cons_of_mem _ h1) + · rintro (h1 | h1) + · exact Or.inl h1 + · rcases List.mem_cons.mp h1 with h2 | h2 + · exact Or.inl (h2 ▸ this) + · exact Or.inr h2 + · simp only [List.mem_append, List.mem_singleton, List.mem_cons] + tauto + +theorem wm : SolidCore.Solidity.Shared.wordModulus = 2 ^ 256 := rfl + +theorem lookupBytes_none (x : Word) (hx : x < 2 ^ 160) : ∀ (cs : List (Word × List Nat)), + (∀ p ∈ cs, p.1 < 2 ^ 160) → x ∉ cs.map Prod.fst → + SolidCore.Solidity.Shared.Account.lookupBytes? cs x = none + | [], _, _ => rfl + | p :: cs, hk, hn => by + have hp := hk p (List.mem_cons_self ..) + have hne : p.1 ≠ x := fun h => hn (by simp [← h]) + simp only [SolidCore.Solidity.Shared.Account.lookupBytes?] + rw [if_neg] + · exact lookupBytes_none x hx cs (fun q hq => hk q (List.mem_cons_of_mem _ hq)) + (fun h => hn (List.mem_cons_of_mem _ h)) + · simp only [SolidCore.Solidity.Shared.Account.wordEq, SolidCore.Solidity.Shared.norm, beq_iff_eq] + rw [Nat.mod_eq_of_lt (lt_trans hp (by decide)), Nat.mod_eq_of_lt (lt_trans hx (by decide))] + exact hne + +theorem isEmpty_bytes (l : List Nat) : (byteArrayToBytes (bytesToByteArray l)).isEmpty = l.isEmpty := by + simp [byteArrayToBytes, toList_eq_data, bytesToByteArray] + +theorem codeIn_snapshot (ctx : Context) (st : State) (henv : st.envWorld? = none) + (hb : ctx.accountBalances = []) (hh : ctx.accountCodehashes = []) + (hk : ∀ p ∈ ctx.accountCodes, p.1 < 2 ^ 160) (hself : ctx.self < 2 ^ 160) + (x : Word) (hx : x < 2 ^ 160) : + (codeIn (snapshotWorld ctx st) x).isEmpty = + (SolidCore.Solidity.Shared.Account.codeAt ctx.accountCodes x).isEmpty := by + unfold codeIn accountIn snapshotWorld + rw [henv] + simp only [snapshotWorldSeed] + rw [RBTree.RBMap.find?_insert] + by_cases hxs : x = ctx.self + · rw [if_pos ((addr_eq hx hself).mpr hxs)] + simp only [Option.getD_some, snapshotSelfAccount, henv, isEmpty_bytes, hxs] + · rw [if_neg (fun h => hxs ((addr_eq hx hself).mp h))] + have hnorm : ∀ p ∈ ctx.accountCodes, SolidCore.Solidity.Shared.norm p.1 = p.1 := by + intro p hp + have := hk p hp + simp only [SolidCore.Solidity.Shared.norm] + exact Nat.mod_eq_of_lt (lt_trans this (by decide)) + have hmem : ∀ a, a ∈ (snapshotOtherAccounts ctx).map Prod.fst ↔ + (a ∈ ctx.accountCodes.map Prod.fst ∧ ¬ wordEq a ctx.self = true) := by + intro a + simp only [snapshotOtherAccounts, hb, hh, List.map_nil, List.nil_append, List.append_nil, + List.map_map, List.mem_map, List.mem_filter, Function.comp] + constructor + · rintro ⟨b, ⟨hb1, hb2⟩, rfl⟩ + rw [mem_dedup] at hb1 + simp only [List.not_mem_nil, false_or, List.mem_map] at hb1 + obtain ⟨p, hp, rfl⟩ := hb1 + refine ⟨⟨p, hp, (hnorm p hp).symm⟩, by simpa using hb2⟩ + · rintro ⟨⟨p, hp, rfl⟩, h2⟩ + refine ⟨p.1, ⟨?_, by simpa using h2⟩, rfl⟩ + rw [mem_dedup] + simp only [List.not_mem_nil, false_or, List.mem_map] + exact ⟨p, hp, hnorm p hp⟩ + rw [find_fold (fun a => { nonce := wordToU256 0, balance := wordToU256 (SolidCore.Solidity.Shared.Account.balanceAt ctx.accountBalances a), storage := default, transientStorage := default, codeBytes := bytesToByteArray (SolidCore.Solidity.Shared.Account.codeAt ctx.accountCodes a) }) + x hx] + · have hwe : wordEq x ctx.self = false := by + simp only [wordEq, SolidCore.Solidity.Shared.norm, beq_eq_false_iff_ne] + rw [Nat.mod_eq_of_lt (lt_trans hx (by decide)), Nat.mod_eq_of_lt (lt_trans hself (by decide))] + exact hxs + by_cases hin : x ∈ List.map Prod.fst (snapshotOtherAccounts ctx) + · rw [if_pos hin] + simp only [Option.getD_some, isEmpty_bytes] + · rw [if_neg hin] + have hnk : x ∉ ctx.accountCodes.map Prod.fst := fun h => hin ((hmem x).mpr ⟨h, by simp [hwe]⟩) + have hcode : SolidCore.Solidity.Shared.Account.codeAt ctx.accountCodes x = [] := by + simp only [SolidCore.Solidity.Shared.Account.codeAt, lookupBytes_none x hx _ hk hnk, Option.getD_none] + rw [hcode, show RBTree.RBMap.find? (default : EvmYul.AddrMap OpenAccount) (wordToAddress x) = none from rfl] + simp [byteArrayToBytes, toList_eq_data] + rfl + · intro e he + have he1 : e.1 ∈ List.map Prod.fst (snapshotOtherAccounts ctx) := List.mem_map_of_mem he + obtain ⟨hk1, -⟩ := (hmem e.1).mp he1 + obtain ⟨q, hq, hqe⟩ := List.mem_map.mp hk1 + refine ⟨hqe ▸ hk q hq, ?_⟩ + simp only [snapshotOtherAccounts, List.mem_map, List.mem_filter] at he + obtain ⟨a, -, rfl⟩ := he + rfl + +/-! ## The expression-level call node: a low-level CALL + +eval_lowLevelCall: (bool ok, bytes ret) = target.call(data) of a target other than the contract +itself, with no gas option and outside construction, evaluates to one request node of the sent +world (snapshotWorld), continued by the pair of the decoded success flag and return bytes and the +adopted world with the interaction recorded (lowLevelTail). The expression-level counterpart of +eval_tryCall, for _safeTransfer-style transfers. -/ + +/-- The value and runtime a low-level call continues with once it answered. -/ +def lowLevelTail (context : Context) (rt : Runtime) (t : Word) (cd : List Byte) (v : Word) + (resp : CallResponse) : Value × Runtime := + ( Value.tuple [ Value.word (boolWord (decodeCallResponse resp .call t cd v none).success) + , Value.bytes (decodeCallResponse resp .call t cd v none).output ] + , { rt with state := adoptWorld resp.postWorld context rt.state }.recordExternalInteraction + (ExternalInteraction.lowLevelCall (decodeCallResponse resp .call t cd v none)) ) + +theorem idone_bind {α β : Type} (a : α) (f : α → SolI β) : + (Interaction.done (Except.ok a) >>= f : SolI β) = f a := rfl + +theorem eval_lowLevelCall (n : Nat) (context : Context) (rt : Runtime) + (tgt cdE valE : Expr) (gasFirst : Bool) + {tv vv cdv : Value} {rt1 rt2 rt3 : Runtime} {t v : Word} {cd : List Byte} + (ht : Expr.evalFuel n context rt tgt = pure (tv, rt1)) (htw : tv.expectWord = .ok t) + (hv : Expr.evalFuel n context rt1 valE = pure (vv, rt2)) (hvw : vv.expectWord = .ok v) + (hc : Expr.evalFuel n context rt2 cdE = pure (cdv, rt3)) (hcb : cdv.asBytes? = some cd) + (hcons : context.construction = false) (hself : wordEq t context.self = false) : + Expr.evalFuel (n + 1) context rt (.lowLevelCall .call tgt cdE valE none gasFirst) = + .request (.external (snapshotWorld context rt3.state) + (.call (buildCallRequest context .call t cd v none))) + (fun resp => pure (lowLevelTail context rt3 t cd v resp)) := by + rw [Expr.evalFuel] + simp only [ht, htw, hv, hvw, hcons, Bool.false_or, sbind_pure] + simp only [liftM, monadLift, MonadLift.monadLift, SolI.ofExcept, ipure_bind, sbind_pure, hc, hcb] + simp only [idone_bind, sbind_pure, hc, hcb] + simp only [selfDispatchCall, selfDispatchKindOk, hself, Bool.and_false, Bool.false_eq_true, ite_false, + emitLowLevelCall, bind_request, beq_self_eq_true, Bool.not_true, idone_bind] + rfl + +/-- info: 'SolidCore.Refinement.CallNode.eval_lowLevelCall' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms eval_lowLevelCall + +/-! ## The internal call node + +eval_internalCall: a statement-position internal call whose arguments evaluate (by reference) to +argValues and whose callee the table holds runs the callee's body, checked, in a fresh frame of +its parameters, and finishes with internalCallFinish (no query of its own: the callee's queries +are the call's). eval_captureReturn_nil: a capture with no names passes a callee's result on, a +return as a normal end. finish_normal_nil: a callee with no returns that ends normally gives the +caller back its locals with the callee's state. -/ + +theorem eval_internalCall (n : Nat) (tbl : FunctionTable) (ctx : Context) (rt : Runtime) + (targets : List String) (name : String) (args : List Expr) (fn : InternalFunction) + (argValues : List Value) (rt' : Runtime) (frame : Frame) + (hargs : Expr.evalRefArgList ctx rt args = EvmCompiler.Simulation.Interaction.done (.ok (argValues, rt'))) + (hfn : tbl.lookup? name = some fn) (hframe : fn.initialFrame? argValues = some frame) : + Stmt.eval (n + 1) tbl ctx rt (.internalCall targets name args) = + (Stmt.eval n tbl { ctx with checked := true } { rt' with locals := [frame] } fn.body >>= + internalCallFinish fn targets rt'.locals) := by + rw [Stmt.eval]; dsimp only + rw [hargs, show SolI.caught (EvmCompiler.Simulation.Interaction.done (.ok (argValues, rt')) : + SolI (List Value × Runtime)) = EvmCompiler.Simulation.Interaction.done (.ok (.ok (argValues, rt'))) from rfl, + idone_bind] + simp only [internalCallEnter?, hframe, hfn] + +theorem eval_captureReturn_nil (n : Nat) (tbl : FunctionTable) (ctx : Context) (rt : Runtime) (s : Stmt) : + Stmt.eval (n + 1) tbl ctx rt (.captureReturn [] s) = + (Stmt.eval n tbl ctx rt s >>= fun r => + match r with + | Result.returned rt' _ => pure (Result.normal rt') + | r => pure r) := by + rw [Stmt.eval]; dsimp only + congr 1 + funext r + cases r <;> simp + +theorem finish_normal_nil (fn : InternalFunction) (hret : fn.returns = []) (saved : LocalEnv) (r : Runtime) : + internalCallFinish fn [] saved (Result.normal r) = pure (Result.normal { r with locals := saved }) := by + simp [internalCallFinish, hret, collectReturnBindingsRef, collectReturnBindingsRef.collect, internalCallAssign] + +theorem finish_reverted (fn : InternalFunction) (targets : List String) (saved : LocalEnv) (r : Runtime) + (e : RevertData) : + internalCallFinish fn targets saved (Result.reverted r e) = pure (Result.reverted r e) := rfl + +end SolidCore.Refinement.CallNode diff --git a/SolidCore/Refinement/Generic/CreateNode.lean b/SolidCore/Refinement/Generic/CreateNode.lean new file mode 100644 index 00000000..14242e94 --- /dev/null +++ b/SolidCore/Refinement/Generic/CreateNode.lean @@ -0,0 +1,113 @@ +import SolidCore.Solidity.Interpreter +import EthLib.Execution.Evm.Call.ContractAddress + +/-! +# The create node of SolidCore's source semantics + +`eval_create2Bytes`: inline assembly's `create2(value, add(code, 32), mload(code), salt)` +(`Expr.create2Bytes`), whose operands evaluate without a request, evaluates to one request node: +the CREATE2 of the sent world (`snapshotWorld`) from the contract, with the bytes of `code` as +init code (`create2BytesRequest`), continued by the answered address as a word and the adopted +world. It is the source-side piece a source-to-MIR check of a function with CREATE2 (as +UniswapV2Factory.createPair) composes, as `CallNode.eval_tryCall` is for calls. + +What the environment answers is the open world's: `EvmCreate2 req resp` says the answer is the +EVM's, the address 0 (a failed creation) or EIP-1014's address of the request's creator, salt and +init code (`create2Word`, by EthLib's `create2Address` and its Keccak-256), so `answer_word` +gives the address `create2Bytes` returns under such an environment. The premise is about the +environment, never about the hash: it names no collision freedom. +-/ + +namespace SolidCore.Refinement.CreateNode + +open SolidCore.Solidity.Source EvmCompiler.Simulation + +theorem ibind_pure {ε α β : Type} (a : α) (f : α → Interaction ε β) : + (Interaction.pure a).bind f = f a := rfl + +theorem ibind_done {ε α β : Type} (a : α) (f : α → Interaction ε β) : + (Interaction.done (Except.ok a)).bind f = f a := rfl + +/-- **The create node**: CREATE2 of the evaluated init code asks one creation of the sent world +and returns the answered address as a word, with the adopted world. Yul evaluates the salt, +then the init code, then the value. -/ +theorem eval_create2Bytes (n : Nat) (context : Context) (rt : Runtime) (v c s : Expr) + {sv cv cv' vv : Value} {rt1 rt2 rt3 : Runtime} {salt value : Word} {code : List Byte} + (hs : Expr.evalFuel n context rt s = .pure (sv, rt1)) (hsw : sv.expectWord = .ok salt) + (hc : Expr.evalFuel n context rt1 c = .pure (cv, rt2)) + (hd : rt2.derefMemoryValue cv = .ok cv') (hcb : cv'.asBytes? = some code) + (hv : Expr.evalFuel n context rt2 v = .pure (vv, rt3)) (hvw : vv.expectWord = .ok value) : + Expr.evalFuel (n + 1) context rt (.create2Bytes v c s) = + .request (.external (snapshotWorld context rt3.state) + (.create (create2BytesRequest context code value salt))) + (fun resp => .pure (Value.word (u256ToWord resp.address), + { rt3 with state := adoptWorld resp.postWorld context rt3.state })) := by + rw [Expr.evalFuel] + simp only [hs, hsw, hc, hd, hv, hvw, ibind_pure, bind, pure, liftM, monadLift, + MonadLift.monadLift, SolI.ofExcept, emitCreate2Bytes] + simp only [ibind_done, hcb] + rfl + +/-- The request asks CREATE2. -/ +theorem request_kind (context : Context) (code : List Byte) (value salt : Word) : + (create2BytesRequest context code value salt).kind = .create2 := rfl + +/-- The request's creator is the contract. -/ +theorem request_creator (context : Context) (code : List Byte) (value salt : Word) : + (create2BytesRequest context code value salt).creator = wordToAddress context.self := rfl + +/-- The request's init code is the bytes of `code`. -/ +theorem request_initCode (context : Context) (code : List Byte) (value salt : Word) : + (create2BytesRequest context code value salt).initCode = bytesToByteArray code := rfl + +/-- The request's salt is the salt word. -/ +theorem request_salt (context : Context) (code : List Byte) (value salt : Word) : + (create2BytesRequest context code value salt).salt = some (wordToU256 salt) := rfl + +/-! ## The EVM's answer -/ + +/-- The 20-byte address of the low 160 bits of a word, big-endian. -/ +def addressOfWord (w : Nat) : EthLib.Base.Address := + Vector.ofFn (fun i : Fin 20 => UInt8.ofNat (w / 256 ^ (19 - i.val))) + +/-- EIP-1014's address of the creator, salt and init code, as a word: EthLib's +`create2Address` (the last 20 bytes of Keccak-256 of `0xff ++ creator ++ salt ++ +keccak256(initCode)`). -/ +def create2Word (creator salt : Nat) (initCode : ByteArray) : Nat := + EthLib.Base.bytesToNat (EthLib.Execution.Evm.create2Address (addressOfWord creator) + (BitVec.ofNat 256 salt) initCode).toList + +/-- **The environment answers a CREATE2 as the EVM does**: with the address 0 (the creation +failed: the init code reverted or ran out of gas, the address had code or a nonce, the value +exceeded the balance, the depth limit) or with EIP-1014's address. A premise about the open +world's answer, not about the hash. -/ +def EvmCreate2 (req : CreateRequest) (resp : CreateResponse) : Prop := + req.kind = .create2 → + u256ToWord resp.address = 0 ∨ + u256ToWord resp.address = create2Word (addressToWord req.creator) + ((req.salt.map u256ToWord).getD 0) req.initCode + +/-- Under an EVM answer, `create2Bytes` returns 0 or EIP-1014's address of the contract, the salt +and the bytes of the init code. -/ +theorem answer_word (context : Context) (code : List Byte) (value salt : Word) (resp : CreateResponse) + (h : EvmCreate2 (create2BytesRequest context code value salt) resp) : + u256ToWord resp.address = 0 ∨ + u256ToWord resp.address = create2Word (addressToWord (wordToAddress context.self)) + (u256ToWord (wordToU256 salt)) (bytesToByteArray code) := by + have h := h (request_kind context code value salt) + rwa [request_initCode, request_salt, Option.map_some, Option.getD_some, request_creator] at h + +/-- Not vacuous: the failed creation (the open world's default answer) is an EVM answer. -/ +theorem evmCreate2_failed (req : CreateRequest) (w : OpenWorld) : + EvmCreate2 req (Query.defaultAnswer (.external w (.create req))) := + fun _ => Or.inl rfl + +/-- info: 'SolidCore.Refinement.CreateNode.eval_create2Bytes' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms eval_create2Bytes + +/-- info: 'SolidCore.Refinement.CreateNode.answer_word' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms answer_word + +end SolidCore.Refinement.CreateNode diff --git a/SolidCore/Refinement/Generic/Event.lean b/SolidCore/Refinement/Generic/Event.lean new file mode 100644 index 00000000..013820e3 --- /dev/null +++ b/SolidCore/Refinement/Generic/Event.lean @@ -0,0 +1,154 @@ +import SolidCore.Refinement.Generic.Source +import SolidCore.Refinement.Generic.Simp + +/-! +# Events of the fragment: SolidCore's encoding of a log + +A log of the fragment has a non-anonymous event's signature topic, then its indexed fields' +words as topics, and its other fields' words, ABI-encoded, as data. Each field is a `uint256` +word, or an `address` word that fits in 160 bits on every path the facts `K` hold on (`evOk K`: +its upper bound `bound K w` is below `2 ^ 160`, as for a constant such as `msg.sender`'s +`callerWord`, an `address` parameter, whose argument check `K` records, or a masked storage +read; SolidCore reverts on an address that does not fit, which the fragment leaves out). `encode_ok` and `encodeValues_ok` +compute SolidCore's `EventDecl.encodeFields?` on such words: the topics are the indexed words +(`evTopics`), the data the 32-byte big-endian encodings of the others (`evData`). +-/ + +namespace SolidCore.Refinement.Generic +open SolidCore.Solidity.Source + +theorem fold_wordToBytesBE : ∀ (n v a : Nat), + (wordToBytesBE n v).foldl (fun acc b => acc * 256 + normByte b) a = a * 256 ^ n + v % 256 ^ n + | 0, v, a => by simp [wordToBytesBE, Nat.mod_one] + | n + 1, v, a => by + rw [wordToBytesBE, List.foldl_append, fold_wordToBytesBE n (v / 256) a] + simp only [List.foldl_cons, List.foldl_nil, normByte, SolidCore.Solidity.Shared.Account.byte, + Nat.mod_mod, Nat.pow_succ] + have h1 : v % (256 ^ n * 256) = v % 256 + 256 * (v / 256 % 256 ^ n) := by + rw [Nat.mul_comm, Nat.mod_mul] + rw [h1, Nat.add_mul, Nat.mul_assoc, Nat.mul_comm (v / 256 % 256 ^ n) 256, Nat.add_assoc, + Nat.add_comm (256 * (v / 256 % 256 ^ n))] + +theorem bytesToWord_wordToBytes {v : Nat} (hv : v < wordSize) : + bytesToWordBE (wordToBytesBE wordBytes v) = v := by + simp only [bytesToWordBE, fold_wordToBytesBE, Nat.zero_mul, Nat.zero_add, + show (256 : Nat) ^ wordBytes = wordSize from rfl, Nat.mod_eq_of_lt hv, norm_mod] + +theorem evWordToBytesBE_eq : ∀ (n v : Nat), + wordToBytesBE n v = (List.range n).map fun i => v / 256 ^ (n - 1 - i) % 256 + | 0, _ => rfl + | n + 1, v => by + rw [wordToBytesBE, evWordToBytesBE_eq n (v / 256), List.range_succ, List.map_append] + congr 1 + · apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [Nat.div_div_eq_div_mul, ← Nat.pow_succ', show (n - 1 - i).succ = n + 1 - 1 - i by omega] + · simp [normByte, SolidCore.Solidity.Shared.Account.byte] + +theorem wordBytes_eval (ρ : Val) (e : WExpr) : + wordToBytesBE wordBytes (e.eval ρ) = (wordOBytes e).map (OByte.eval ρ) := by + rw [evWordToBytesBE_eq, wordOBytes, List.map_map] + apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + simp [OByte.eval, wordBytes, show 32 - 1 - i = 31 - i by omega] + +/-- A field the fragment logs, with its word: any `uint256` word, or an `address` word whose bound +on the facts `K` fits in 160 bits. -/ +def evFieldOk (K : Facts) (f : EventField) (w : WExpr) : Bool := + match f.ty with + | .uint256 => true + | .address => decide (bound K w < 2 ^ 160) + | _ => false + +/-- Whether every field is one the fragment logs, with its word. -/ +def evOk (K : Facts) : List EventField → List WExpr → Bool + | [], [] => true + | f :: fs, w :: ws => evFieldOk K f w && evOk K fs ws + | _, _ => false + +/-- The words of the indexed fields: the log's topics after the signature's. -/ +def evTopics : List EventField → List WExpr → List WExpr + | f :: fs, w :: ws => if f.indexed then w :: evTopics fs ws else evTopics fs ws + | _, _ => [] + +/-- The words of the other fields: the log's data, ABI-encoded. -/ +def evData : List EventField → List WExpr → List WExpr + | f :: fs, w :: ws => if f.indexed then evData fs ws else w :: evData fs ws + | _, _ => [] + +/-- The types of the other fields. -/ +def evDataTys : List EventField → List WExpr → List Ty + | f :: fs, _ :: ws => if f.indexed then evDataTys fs ws else f.ty :: evDataTys fs ws + | _, _ => [] + +theorem evFieldOk_static (ρ : Val) {K : Facts} (hK : K.Hold ρ) {f : EventField} {w : WExpr} + (h : evFieldOk K f w = true) : + abiStaticBytes? f.ty (.word (w.eval ρ)) = some (wordToBytesBE wordBytes (w.eval ρ)) ∧ + abiEncodeStaticValue? f.ty (.word (w.eval ρ)) = some (wordToBytesBE wordBytes (w.eval ρ)) ∧ + Ty.isHashedEventIndexed f.ty = false ∧ Ty.isDynamicAbi f.ty = false ∧ + Ty.staticAbiHeadWords? f.ty = some 1 := by + unfold evFieldOk at h + split at h + · rename_i hty + rw [hty] + exact ⟨rfl, rfl, rfl, rfl, rfl⟩ + · rename_i hty + simp only [decide_eq_true_eq] at h + have hn : w.eval ρ < 1461501637330902918203684832716283019655932542976 := + Nat.lt_of_le_of_lt (bound_sound hK w) h + rw [hty] + have hb : abiStaticBytes? Ty.address (.word (w.eval ρ)) = + some (wordToBytesBE wordBytes (w.eval ρ)) := by + simp [abiStaticBytes?, abiAddressFits, norm_mod, Nat.mod_eq_of_lt (w.eval_lt ρ), hn] + exact ⟨hb, hb, rfl, rfl, rfl⟩ + · simp at h + +theorem encode_ok (ρ : Val) {K : Facts} (hK : K.Hold ρ) : + ∀ (fs : List EventField) (ws : List WExpr), evOk K fs ws = true → + ∃ a b, EventDecl.encodeFields?.encode fs (ws.map fun e => Value.word (e.eval ρ)) = + some ((evTopics fs ws).map (WExpr.eval ρ), evDataTys fs ws, + (evData fs ws).map (fun e => Value.word (e.eval ρ)), a, b) + | [], [], _ => ⟨[], [], rfl⟩ + | f :: fs, w :: ws, h => by + simp only [evOk, Bool.and_eq_true] at h + obtain ⟨a, b, ih⟩ := encode_ok ρ hK fs ws h.2 + obtain ⟨hs, -, hh, -, -⟩ := evFieldOk_static ρ hK h.1 + simp only [List.map_cons, EventDecl.encodeFields?.encode, ih, bind, Option.bind] + by_cases hi : f.indexed = true + · simp only [hi, ↓reduceIte, evTopics, evDataTys, evData, abiEventTopic?, hh, + Bool.false_eq_true, hs, bytesToWord_wordToBytes (w.eval_lt ρ), List.map_cons] + exact ⟨_, _, rfl⟩ + · simp only [hi, Bool.false_eq_true, ↓reduceIte, evTopics, evDataTys, evData, List.map_cons] + exact ⟨_, _, rfl⟩ + | [], _ :: _, h | _ :: _, [], h => by simp [evOk] at h + +theorem evData_ok {K : Facts} : ∀ (fs : List EventField) (ws : List WExpr), evOk K fs ws = true → + ∀ (ρ : Val), K.Hold ρ → ∀ (off : Nat), + Ty.listAbiHeadWords? (evDataTys fs ws) = some (evData fs ws).length ∧ + abiEncodeValuesAux? (evDataTys fs ws) ((evData fs ws).map fun e => Value.word (e.eval ρ)) off = + some (((evData fs ws).flatMap wordOBytes).map (OByte.eval ρ), [], off) + | [], [], _, _, _, _ => ⟨rfl, rfl⟩ + | f :: fs, w :: ws, h, ρ, hK, off => by + simp only [evOk, Bool.and_eq_true] at h + obtain ⟨ih1, ih2⟩ := evData_ok fs ws h.2 ρ hK off + obtain ⟨-, hs, -, hd, hw⟩ := evFieldOk_static ρ hK h.1 + by_cases hi : f.indexed = true + · simp only [evDataTys, evData, hi, ↓reduceIte] + exact ⟨ih1, ih2⟩ + · simp only [evDataTys, evData, hi, Bool.false_eq_true, ↓reduceIte, List.map_cons, + List.length_cons, List.flatMap_cons, List.map_append] + refine ⟨?_, ?_⟩ + · simp [Ty.listAbiHeadWords?, Ty.abiHeadWords?, hd, hw, ih1, bind, Option.bind, Nat.add_comm] + · simp only [abiEncodeValuesAux?, hd, Bool.false_eq_true, ↓reduceIte, hs, ih2, wordBytes_eval] + | [], _ :: _, h, _, _, _ | _ :: _, [], h, _, _, _ => by simp [evOk] at h + +theorem encodeValues_ok (ρ : Val) {K : Facts} (hK : K.Hold ρ) (fs : List EventField) + (ws : List WExpr) (h : evOk K fs ws = true) : + abiEncodeValues? (evDataTys fs ws) ((evData fs ws).map fun e => Value.word (e.eval ρ)) = + some (((evData fs ws).flatMap wordOBytes).map (OByte.eval ρ)) := by + obtain ⟨h1, h2⟩ := evData_ok fs ws h ρ hK (wordBytes * (evData fs ws).length) + simp [abiEncodeValues?, h1, h2, bind, Option.bind] + +end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Generic/Loop.lean b/SolidCore/Refinement/Generic/Loop.lean new file mode 100644 index 00000000..011593b6 --- /dev/null +++ b/SolidCore/Refinement/Generic/Loop.lean @@ -0,0 +1,281 @@ +import SolidCore.Refinement.Generic.SourceStmt +import SolidCore.Solidity.FuelMonotonicity + +/-! +# Loops of SolidCore under ranking certificates + +The generic source stage erases loop-free statements (`eraseStmt`, `eval_stmt`). This file adds +what a loop needs: a **ranking certificate** checked by the kernel, and the theorem that a loop with +one ends, at every fuel from a bound the certificate gives, in an end its certificate names. + +A certificate of `for (init; cond; post) body` (`ForCert`) or `while (cond) body` (`WhileCert`) +is an invariant `Inv` of the runtime at the loop's header, a measure `rank` into `Nat`, a body fuel +`k` and the property `Q` of the loop's result. From every runtime of `Inv` the condition must +evaluate; when it is false, or reverts, or the body breaks, returns or reverts, the result meets +`Q`; when an iteration goes on, it must come back to `Inv` with a strictly smaller rank. Nothing +else is assumed: the condition, the body and `post` run in SolidCore's interpreter +(`Stmt.eval`), and the rank's fall is part of the obligation, so a certificate whose rank does not +fall is not one. + +* `evalFor_of_cert`, `evalWhile_of_cert`: from a runtime of `Inv` with rank below `N`, the loop + ends in a result meeting `Q` at every fuel from `N + k` on. The bound is linear in the rank: + each iteration spends one unit of the loop's fuel, and SolidCore's fuel monotonicity + (`Stmt.eval_fuel_mono`) keeps the body's result when later iterations run it with less fuel + than the first. +* `forLoop_of_cert`, `whileLoop_of_cert`: the same of the statements, the `for` loop's scope and + `init` included. +* `evalFor_never`, `forLoop_never`: the converse control. A loop that makes no progress (from + every runtime of `P` the condition holds and a finished iteration comes back to `P`) finishes at + no fuel at all: no ranking certificate exists for it, and no fuel ends it. +-/ + +namespace SolidCore.Refinement.Generic.Loop +open SolidCore.Solidity.Source +open EvmCompiler.Simulation (Interaction) + +theorem noFuelStop_done {α : Type} (a : α) : + SolI.NoFuelStop (Interaction.done (.ok a) : SolI α) := + Interaction.AllDone.done (by intro h; cases h) + +/-- A statement that ends at some fuel ends the same way at every larger fuel. -/ +theorem eval_mono {n m : Nat} (hnm : n ≤ m) {tbl : FunctionTable} {ctx : Context} {rt : Runtime} + {s : Stmt} {r : Result} (h : Stmt.eval n tbl ctx rt s = .done (.ok r)) : + Stmt.eval m tbl ctx rt s = .done (.ok r) := by + rw [Stmt.eval_fuel_mono hnm (by rw [h]; exact noFuelStop_done r), h] + +/-- A bind that ends had a prefix that ended. -/ +theorem bind_eq_done {α β : Type} {t : SolI α} {k : α → SolI β} {b : β} + (h : (t >>= k) = .done (.ok b)) : ∃ a, t = .done (.ok a) ∧ k a = .done (.ok b) := by + cases t with + | done o => + cases o with + | ok a => exact ⟨a, rfl, h⟩ + | error e => cases h + | request q r => cases h + +/-- What the condition of a loop does from the header runtime `rt`: it evaluates, and when it is +false or reverts the result meets `Q`, while when it holds the runtime after it meets `Go`. -/ +def CondStep (ctx : Context) (cond : Expr) (rt : Runtime) (Q : Result → Prop) + (Go : Runtime → Prop) : Prop := + ∃ c, (Expr.eval ctx rt cond).caught = .done (.ok c) ∧ + match c with + | .error err => Q (.reverted rt err) + | .ok (v, rt') => + match v.expectWord with + | .error err => Q (.reverted rt' err) + | .ok w => if wordTruthy w then Go rt' else Q (.normal rt') + +/-- What the rest of a `for` iteration does after the body's result: `post` runs (fuel `k`) after a +normal or `continue` end and either comes back to `Next` or ends the loop meeting `Q`; a `break` +ends the loop normally, and every other end of the body is the loop's. -/ +def ForRest (k : Nat) (tbl : FunctionTable) (ctx : Context) (post : Stmt) + (Next : Runtime → Prop) (Q : Result → Prop) : Result → Prop + | .normal rb => ∃ r2, Stmt.eval k tbl ctx rb post = .done (.ok r2) ∧ + match r2 with + | .normal rp => Next rp + | r => Q r + | .continued rb => ∃ r2, Stmt.eval k tbl ctx rb post = .done (.ok r2) ∧ + match r2 with + | .normal rp => Next rp + | r => Q r + | .broke rb => Q (.normal rb) + | .returned rt vs => Q (.returned rt vs) + | .selfdestructed rt => Q (.selfdestructed rt) + | .reverted rt e => Q (.reverted rt e) + +/-- **A ranking certificate of `for (…; cond; post) body`**: from every runtime of `Inv`, the +condition evaluates; an iteration runs its body and `post` within fuel `k` and either ends the +loop meeting `Q` or comes back to `Inv` with a strictly smaller `rank`. -/ +structure ForCert (k : Nat) (tbl : FunctionTable) (ctx : Context) (cond : Expr) (post body : Stmt) + (Inv : Runtime → Prop) (rank : Runtime → Nat) (Q : Result → Prop) : Prop where + step : ∀ rt, Inv rt → CondStep ctx cond rt Q (fun rt' => + ∃ r1, Stmt.eval k tbl ctx rt' body = .done (.ok r1) ∧ + ForRest k tbl ctx post (fun rp => Inv rp ∧ rank rp < rank rt) Q r1) + +/-- **A `for` loop with a ranking certificate ends**, from a runtime of the invariant whose rank is +below `N`, at every fuel from `N + k` on, in a result meeting `Q`. -/ +theorem evalFor_of_cert {k : Nat} {tbl : FunctionTable} {ctx : Context} {cond : Expr} + {post body : Stmt} {Inv : Runtime → Prop} {rank : Runtime → Nat} {Q : Result → Prop} + (h : ForCert k tbl ctx cond post body Inv rank Q) : + ∀ N rt, Inv rt → rank rt < N → ∀ fuel, N + k ≤ fuel → + ∃ r, Stmt.evalFor fuel tbl ctx rt cond post body = .done (.ok r) ∧ Q r := by + intro N + induction N with + | zero => intro rt _ hr; omega + | succ N ih => + intro rt hinv hr fuel hf + obtain ⟨f, rfl⟩ : ∃ f, fuel = f + 1 := ⟨fuel - 1, by omega⟩ + obtain ⟨c, hc, hstep⟩ := h.step rt hinv + simp only [Stmt.evalFor] + rw [hc, bind_done_ok] + rcases c with err | ⟨v, rt'⟩ + · exact ⟨_, rfl, hstep⟩ + dsimp only at hstep ⊢ + rcases hv : v.expectWord with err | w <;> simp only [hv] at hstep ⊢ + · exact ⟨_, rfl, hstep⟩ + by_cases ht : wordTruthy w = true + · rw [if_pos ht] at hstep ⊢ + obtain ⟨r1, hb, hrest⟩ := hstep + rw [eval_mono (by omega) hb, bind_done_ok] + rcases r1 with rb | ⟨rt1, vs⟩ | rt1 | ⟨rt1, e⟩ | rb | rb <;> dsimp only [ForRest] at hrest ⊢ + · obtain ⟨r2, hp, hn⟩ := hrest + rw [eval_mono (by omega) hp, bind_done_ok] + rcases r2 with rp | ⟨rt2, vs⟩ | rt2 | ⟨rt2, e⟩ | rt2 | rt2 <;> dsimp only at hn ⊢ + · exact ih rp hn.1 (by omega) f (by omega) + all_goals exact ⟨_, rfl, hn⟩ + · exact ⟨_, rfl, hrest⟩ + · exact ⟨_, rfl, hrest⟩ + · exact ⟨_, rfl, hrest⟩ + · exact ⟨_, rfl, hrest⟩ + · obtain ⟨r2, hp, hn⟩ := hrest + rw [eval_mono (by omega) hp, bind_done_ok] + rcases r2 with rp | ⟨rt2, vs⟩ | rt2 | ⟨rt2, e⟩ | rt2 | rt2 <;> dsimp only at hn ⊢ + · exact ih rp hn.1 (by omega) f (by omega) + all_goals exact ⟨_, rfl, hn⟩ + · rw [if_neg ht] at hstep ⊢ + exact ⟨_, rfl, hstep⟩ + +/-- **The `for` statement with a ranking certificate ends**: its scope opens, `init` runs (fuel +`k0`) to a runtime of the invariant, and from `rank + k + 1` more fuel on, the loop ends meeting +`Q`, its scope closed. -/ +theorem forLoop_of_cert {k k0 : Nat} {tbl : FunctionTable} {ctx : Context} {init : Stmt} + {cond : Expr} {post body : Stmt} {Inv : Runtime → Prop} {rank : Runtime → Nat} + {Q : Result → Prop} (h : ForCert k tbl ctx cond post body Inv rank Q) {rt rt1 : Runtime} + (hinit : Stmt.eval k0 tbl ctx rt.pushScope init = .done (.ok (.normal rt1))) (hinv : Inv rt1) + (fuel : Nat) (hf : rank rt1 + 1 + k + 1 ≤ fuel) (hk0 : k0 + 1 ≤ fuel) : + ∃ r, Stmt.eval fuel tbl ctx rt (.forLoop init cond post body) = + .done (.ok (r.mapRuntime Runtime.popScope)) ∧ Q r := by + obtain ⟨f, rfl⟩ : ∃ f, fuel = f + 1 := ⟨fuel - 1, by omega⟩ + obtain ⟨r, hr, hq⟩ := evalFor_of_cert h (rank rt1 + 1) rt1 hinv (by omega) f (by omega) + refine ⟨r, ?_, hq⟩ + simp only [Stmt.eval] + rw [eval_mono (by omega) hinit, bind_done_ok] + dsimp only + rw [hr, bind_done_ok] + rfl + +/-- What the rest of a `while` iteration does after the body's result. -/ +def WhileRest (Next : Runtime → Prop) (Q : Result → Prop) : Result → Prop + | .normal rb => Next rb + | .continued rb => Next rb + | .broke rb => Q (.normal rb) + | .returned rt vs => Q (.returned rt vs) + | .selfdestructed rt => Q (.selfdestructed rt) + | .reverted rt e => Q (.reverted rt e) + +/-- **A ranking certificate of `while (cond) body`.** -/ +structure WhileCert (k : Nat) (tbl : FunctionTable) (ctx : Context) (cond : Expr) (body : Stmt) + (Inv : Runtime → Prop) (rank : Runtime → Nat) (Q : Result → Prop) : Prop where + step : ∀ rt, Inv rt → CondStep ctx cond rt Q (fun rt' => + ∃ r1, Stmt.eval k tbl ctx rt' body = .done (.ok r1) ∧ + WhileRest (fun rb => Inv rb ∧ rank rb < rank rt) Q r1) + +/-- **A `while` loop with a ranking certificate ends**, at every fuel from `N + k` on. -/ +theorem evalWhile_of_cert {k : Nat} {tbl : FunctionTable} {ctx : Context} {cond : Expr} + {body : Stmt} {Inv : Runtime → Prop} {rank : Runtime → Nat} {Q : Result → Prop} + (h : WhileCert k tbl ctx cond body Inv rank Q) : + ∀ N rt, Inv rt → rank rt < N → ∀ fuel, N + k ≤ fuel → + ∃ r, Stmt.evalWhile fuel tbl ctx rt cond body = .done (.ok r) ∧ Q r := by + intro N + induction N with + | zero => intro rt _ hr; omega + | succ N ih => + intro rt hinv hr fuel hf + obtain ⟨f, rfl⟩ : ∃ f, fuel = f + 1 := ⟨fuel - 1, by omega⟩ + obtain ⟨c, hc, hstep⟩ := h.step rt hinv + simp only [Stmt.evalWhile] + rw [hc, bind_done_ok] + rcases c with err | ⟨v, rt'⟩ + · exact ⟨_, rfl, hstep⟩ + dsimp only at hstep ⊢ + rcases hv : v.expectWord with err | w <;> simp only [hv] at hstep ⊢ + · exact ⟨_, rfl, hstep⟩ + by_cases ht : wordTruthy w = true + · rw [if_pos ht] at hstep ⊢ + obtain ⟨r1, hb, hrest⟩ := hstep + rw [eval_mono (by omega) hb, bind_done_ok] + rcases r1 with rb | ⟨rt1, vs⟩ | rt1 | ⟨rt1, e⟩ | rb | rb <;> dsimp only [WhileRest] at hrest ⊢ + · exact ih rb hrest.1 (by omega) f (by omega) + · exact ⟨_, rfl, hrest⟩ + · exact ⟨_, rfl, hrest⟩ + · exact ⟨_, rfl, hrest⟩ + · exact ⟨_, rfl, hrest⟩ + · exact ih rb hrest.1 (by omega) f (by omega) + · rw [if_neg ht] at hstep ⊢ + exact ⟨_, rfl, hstep⟩ + +theorem whileLoop_of_cert {k : Nat} {tbl : FunctionTable} {ctx : Context} {cond : Expr} + {body : Stmt} {Inv : Runtime → Prop} {rank : Runtime → Nat} {Q : Result → Prop} + (h : WhileCert k tbl ctx cond body Inv rank Q) {rt : Runtime} (hinv : Inv rt) (fuel : Nat) + (hf : rank rt + 1 + k + 1 ≤ fuel) : + ∃ r, Stmt.eval fuel tbl ctx rt (.whileLoop cond body) = .done (.ok r) ∧ Q r := by + obtain ⟨f, rfl⟩ : ∃ f, fuel = f + 1 := ⟨fuel - 1, by omega⟩ + simp only [Stmt.eval] + exact evalWhile_of_cert h (rank rt + 1) rt hinv (by omega) f (by omega) + +/-! ## A loop without progress ends at no fuel -/ + +theorem wordTruthy_norm (w : Nat) : + wordTruthy (SolidCore.Solidity.Shared.norm w) = wordTruthy w := by + simp [wordTruthy, SolidCore.Solidity.Shared.norm] + +/-- **A `for` loop that makes no progress finishes at no fuel.** From every runtime of `P` the +condition holds and some fuel finishes the body and `post` normally, back in `P`. -/ +theorem evalFor_never {tbl : FunctionTable} {ctx : Context} {cond : Expr} {post body : Stmt} + (P : Runtime → Prop) + (h : ∀ rt, P rt → ∃ w rt', (Expr.eval ctx rt cond).caught = .done (.ok (.ok (.word w, rt'))) ∧ + wordTruthy w = true ∧ ∃ k rb, Stmt.eval k tbl ctx rt' body = .done (.ok (.normal rb)) ∧ + ∃ rp, Stmt.eval k tbl ctx rb post = .done (.ok (.normal rp)) ∧ P rp) : + ∀ fuel rt, P rt → ∀ r, Stmt.evalFor fuel tbl ctx rt cond post body ≠ .done (.ok r) := by + intro fuel + induction fuel with + | zero => intro rt _ r hr; simp only [Stmt.evalFor] at hr; cases hr + | succ f ih => + intro rt hp r hr + obtain ⟨w, rt', hc, ht, k, rb, hb, rp, hpo, hp'⟩ := h rt hp + simp only [Stmt.evalFor] at hr + rw [hc, bind_done_ok] at hr + simp only [Value.expectWord, wordTruthy_norm, ht, ite_true] at hr + obtain ⟨r1, hb1, hr⟩ := bind_eq_done hr + have e1 : r1 = .normal rb := by + have := (eval_mono (Nat.le_max_left f k) hb1).symm.trans (eval_mono (Nat.le_max_right f k) hb) + cases this; rfl + subst e1 + obtain ⟨r2, hp2, hr⟩ := bind_eq_done hr + have e2 : r2 = .normal rp := by + have := (eval_mono (Nat.le_max_left f k) hp2).symm.trans (eval_mono (Nat.le_max_right f k) hpo) + cases this; rfl + subst e2 + exact ih rp hp' r hr + +/-- **The `for` statement of a loop without progress finishes at no fuel.** -/ +theorem forLoop_never {tbl : FunctionTable} {ctx : Context} {init : Stmt} {cond : Expr} + {post body : Stmt} (P : Runtime → Prop) + (h : ∀ rt, P rt → ∃ w rt', (Expr.eval ctx rt cond).caught = .done (.ok (.ok (.word w, rt'))) ∧ + wordTruthy w = true ∧ ∃ k rb, Stmt.eval k tbl ctx rt' body = .done (.ok (.normal rb)) ∧ + ∃ rp, Stmt.eval k tbl ctx rb post = .done (.ok (.normal rp)) ∧ P rp) + {rt rt1 : Runtime} {k0 : Nat} + (hinit : Stmt.eval k0 tbl ctx rt.pushScope init = .done (.ok (.normal rt1))) (hp : P rt1) : + ∀ fuel r, Stmt.eval fuel tbl ctx rt (.forLoop init cond post body) ≠ .done (.ok r) := by + intro fuel r hr + cases fuel with + | zero => simp only [Stmt.eval] at hr; cases hr + | succ f => + simp only [Stmt.eval] at hr + obtain ⟨r0, h0, hr⟩ := bind_eq_done hr + have e0 : r0 = .normal rt1 := by + have := (eval_mono (Nat.le_max_left f k0) h0).symm.trans (eval_mono (Nat.le_max_right f k0) hinit) + cases this; rfl + subst e0 + obtain ⟨r1, h1, -⟩ := bind_eq_done hr + exact evalFor_never P h f rt1 hp r1 h1 + +/-- info: 'SolidCore.Refinement.Generic.Loop.forLoop_of_cert' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms forLoop_of_cert + +/-- info: 'SolidCore.Refinement.Generic.Loop.forLoop_never' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms forLoop_never + +end SolidCore.Refinement.Generic.Loop diff --git a/SolidCore/Refinement/Generic/LoopErr.lean b/SolidCore/Refinement/Generic/LoopErr.lean new file mode 100644 index 00000000..64fe7cc8 --- /dev/null +++ b/SolidCore/Refinement/Generic/LoopErr.lean @@ -0,0 +1,184 @@ +import SolidCore.Refinement.Generic.LoopRun + +/-! +# Loops that end at no fuel, and calls whose body fails + +The converse of the ranking certificates of `Loop.lean`, strong enough to reach a call's +result. `evalFor_never` says a loop without progress never finishes normally; a call's result +needs more, since the dispatcher folds the body's interaction tree: these lemmas say the run +**fails** (`.done (.error e)`, out of fuel among them), at every fuel. + +* `evalFor_err`: a `for` loop whose condition holds from every runtime of `P`, and whose body and + update, at every fuel, either fail or come back to `P`, fails at every fuel. +* `forLoop_err`, `evalList_cons_err`, `eval_block_err`: the failure through the `for` statement, + statement lists and blocks. +* `runtime_run_err`: a call of a function with clean argument words whose body fails, from every + runtime related to its first symbolic state, has no result in `runtimeRun`: no fuel ends it. +-/ + +namespace SolidCore.Refinement.Generic.Loop +open SolidCore.Solidity.Source +open EvmCompiler.Simulation (Interaction) + +/-- What a body or an update does at a fuel: it fails, or it finishes normally in `Q`. -/ +def ErrOr (t : SolI Result) (Q : Runtime → Prop) : Prop := + (∃ e, t = .done (.error e)) ∨ ∃ rt, t = .done (.ok (.normal rt)) ∧ Q rt + +/-- **A `for` loop without progress fails at every fuel.** -/ +theorem evalFor_err {tbl : FunctionTable} {ctx : Context} {cond : Expr} {post body : Stmt} + (P : Runtime → Prop) + (h : ∀ rt, P rt → ∃ w rt', (Expr.eval ctx rt cond).caught = .done (.ok (.ok (.word w, rt'))) ∧ + wordTruthy w = true ∧ ∀ f, ErrOr (Stmt.eval f tbl ctx rt' body) fun rb => + ErrOr (Stmt.eval f tbl ctx rb post) P) : + ∀ fuel rt, P rt → ∃ e, Stmt.evalFor fuel tbl ctx rt cond post body = .done (.error e) := by + intro fuel + induction fuel with + | zero => + intro rt _ + refine ⟨SolidityFailure.outOfFuel, ?_⟩ + first | rfl | (simp only [Stmt.evalFor]; done) | (simp only [Stmt.evalFor]; rfl) + | succ f ih => + intro rt hp + obtain ⟨w, rt', hc, ht, hb⟩ := h rt hp + simp only [Stmt.evalFor] + rw [hc, bind_done_ok] + simp only [Value.expectWord, wordTruthy_norm, ht, ite_true] + rcases hb f with ⟨e, he⟩ | ⟨rb, hb1, hpost⟩ + · rw [he]; exact ⟨e, rfl⟩ + · rw [hb1, bind_done_ok] + dsimp only + rcases hpost with ⟨e, he⟩ | ⟨rp, hp1, hP⟩ + · rw [he]; exact ⟨e, rfl⟩ + · rw [hp1, bind_done_ok] + dsimp only + exact ih rp hP + +/-- **The `for` statement of a loop without progress fails at every fuel.** -/ +theorem forLoop_err {tbl : FunctionTable} {ctx : Context} {init : Stmt} {cond : Expr} + {post body : Stmt} (P : Runtime → Prop) + (h : ∀ rt, P rt → ∃ w rt', (Expr.eval ctx rt cond).caught = .done (.ok (.ok (.word w, rt'))) ∧ + wordTruthy w = true ∧ ∀ f, ErrOr (Stmt.eval f tbl ctx rt' body) fun rb => + ErrOr (Stmt.eval f tbl ctx rb post) P) + {rt : Runtime} (hinit : ∀ f, ErrOr (Stmt.eval f tbl ctx rt.pushScope init) P) : + ∀ fuel, ∃ e, Stmt.eval fuel tbl ctx rt (.forLoop init cond post body) = .done (.error e) := by + intro fuel + cases fuel with + | zero => + refine ⟨SolidityFailure.outOfFuel, ?_⟩ + first | rfl | (simp only [Stmt.eval]; done) | (simp only [Stmt.eval]; rfl) + | succ f => + simp only [Stmt.eval] + rcases hinit f with ⟨e, he⟩ | ⟨rt1, h1, hP⟩ + · rw [he]; exact ⟨e, rfl⟩ + · rw [h1, bind_done_ok] + dsimp only + obtain ⟨e, he⟩ := evalFor_err P h f rt1 hP + rw [he] + exact ⟨e, rfl⟩ + +theorem evalList_cons_err {n : Nat} {tbl : FunctionTable} {ctx : Context} {rt : Runtime} + {s : Stmt} {rest : List Stmt} {e : SolidityFailure} + (h : Stmt.eval n tbl ctx rt s = .done (.error e)) : + Stmt.evalList n tbl ctx rt (s :: rest) = .done (.error e) := by + simp only [Stmt.evalList] + rw [h] + rfl + +theorem eval_block_err {n : Nat} {tbl : FunctionTable} {ctx : Context} {rt : Runtime} + {ss : List Stmt} {e : SolidityFailure} (h : Stmt.evalList n tbl ctx rt.pushScope ss = .done (.error e)) : + Stmt.eval (n + 1) tbl ctx rt (.block ss) = .done (.error e) := by + rw [Stmt.eval] + simp only [h, bind, EvmCompiler.Simulation.Interaction.bind] + +open SolidCore.Solidity SolidCore.Refinement SolidCore.Refinement.Generic + +/-- **A call whose body fails at the fuel has no result**: the dispatcher folds the body's +interaction tree fail-closed, so an error (out of fuel among them) leaves `runtimeRun` empty. -/ +theorem runtime_run_err {fuel : Nat} {c : TypeCheck.CheckedContract} {σ : List (Nat × Nat)} + {sel : Nat} (hsel : sel < 2 ^ 32) {fn : FunctionDef} + (hfind : c.core.findFunctionBySelector? sel = some fn) {ws : List Nat} + (hw : widthsOf fn.params fn.paramAbiCleanups = some ws) + (hret : fn.returns.all wordBinding = true) + (args : List Nat) + (hlen : args.length = fn.params.length) (hargs : ∀ a ∈ args, a < 2 ^ 256) + (hclean : argsClean ws args = true) + (hdec : ABI.decodeFunctionArgs? fn (Dirty.argBytes args) = .ok (args.map .word)) + (hb : ∀ ctx rt, StmtRel ⟨args, slotValue σ, solHash, callerWord⟩ { envOf c.core with facts := argFacts ws 0 } ctx rt + (initState fn) → ∃ e, Stmt.eval fuel c.core.table ctx rt fn.body = .done (.error e)) : + runtimeRun fuel c { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } = none := by + unfold runtimeRun runtimeResult? + simp only [Dirty.bytes_calldata] + rw [show ({ c.core.context with sender := callerAddress, self := selfAddress, value := 0 } : + Source.Context) = Wide.ctxOf c from rfl] + have hdrop : ((EthLib.Base.natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes args).drop + ABI.selectorBytes = Dirty.argBytes args := by + simp [ABI.selectorBytes, EthLib.Base.natToBytes_length] + simp only [ABI.Contract.callCalldataAtFromWithContext?, Dirty.readSelector_calldata _ hsel, hfind, + hdrop, hdec] + have hp := (widthsOf_spec hw).2.2.1 + have hr : ∀ r ∈ fn.returns, RetTy r.ty ∧ r.isStorageRef = false := + fun r hr => wordBinding_ty (List.all_eq_true.mp hret r hr) + generalize hctx : ABI.Contract.callContextAtWithBase c.core (Wide.ctxOf c) selfAddress callerAddress 0 + ((EthLib.Base.natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes args) = ctx + generalize hst : ({ State.empty with + storage := σ.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) State.empty.storage } : + Source.State) = st0 + have hacc : fn.acceptsValue 0 = true := by + simp [FunctionDef.acceptsValue, wordEq] + have hctxv : ctx.value = 0 := by + subst hctx; simp [ABI.Contract.callContextAtWithBase, SolidCore.Solidity.Shared.norm] + set ρ : Val := ⟨args, slotValue σ, solHash, callerWord⟩ with hρ + have hρok : ρ.Ok := slotValue_store σ + set K := argFacts ws 0 with hK + have hKρ : K.Hold ρ := argFacts_hold ρ hargs ws 0 (by simpa [hρ] using hclean) + set E : EraseEnv := { envOf c.core with facts := K } with hE + have hframe : fn.initialFrame? (args.map .word) = + some (frameOf ρ (paramLocals fn.params 0 ++ fn.returns.map fun r => (r.name, .lit 0))) := by + have h0 : BindingDecl.bindArgs? fn.params (args.map .word) = + some (frameOf ρ (paramLocals fn.params 0)) := + bindArgs_words ρ hargs fn.params 0 hp (by simp [hρ, hlen]) + simp only [FunctionDef.initialFrame?, h0, FunctionDef.returnDefaultBindings, + defaults_words ρ fn.returns hr, frameOf, List.map_append] + have hrel : StmtRel ρ E ctx + { state := { st0 with + selfBalance := SolidCore.Solidity.Shared.addWord + (SolidCore.Solidity.Shared.Account.balanceAt ctx.accountBalances ctx.self) ctx.value + worldMutatedSinceAdoption := true }, + locals := [frameOf ρ (paramLocals fn.params 0 ++ fn.returns.map fun r => (r.name, .lit 0))] } + (initState fn) := + { fields := by subst hctx; rfl + events := by subst hctx; rfl + checked := by subst hctx; rfl + sender := by subst hctx; rfl + hash := rfl + ok := hρok + frames := rfl + store := by + intro k hk + have := getD_storage_empty σ k + subst hst + simp only [State.loadSlot, StorageMap.lookup?, initState, Writes.store, hρ] + rw [← this] + simp only [SolidCore.Solidity.Shared.norm, modulus_eq, Std.HashMap.get?_eq_getElem?] + cases (List.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) State.empty.storage σ)[k % wordSize]? <;> rfl + logs := by subst hst; simp [State.empty, initState] + facts := hKρ } + obtain ⟨e, he⟩ := hb ctx _ hrel + have hcall : fn.call? fuel c.core.table ctx st0 (args.map .word) = none := by + have hacc' : fn.acceptsValue ctx.value = true := hctxv ▸ hacc + simp only [FunctionDef.call?, FunctionDef.call, FunctionDef.evalBodyEntry, hacc', hframe, + if_true, Option.map_some, Option.bind_some] + rw [he] + rfl + rw [hacc, if_pos rfl, hcall] + first | rfl | simp + +/-- info: 'SolidCore.Refinement.Generic.Loop.runtime_run_err' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms runtime_run_err + +/-- info: 'SolidCore.Refinement.Generic.Loop.forLoop_err' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms forLoop_err + +end SolidCore.Refinement.Generic.Loop diff --git a/SolidCore/Refinement/Generic/LoopRun.lean b/SolidCore/Refinement/Generic/LoopRun.lean new file mode 100644 index 00000000..d65de2a6 --- /dev/null +++ b/SolidCore/Refinement/Generic/LoopRun.lean @@ -0,0 +1,225 @@ +import SolidCore.Refinement.Generic.Loop +import SolidCore.Refinement.Generic.SourceRun + +/-! +# SolidCore's runtime code, and calls of functions whose body is not loop-free + +Two pieces the generic source stage needs before a function with a loop can join it. + +* `solidCoreRuntime fuel`: SolidCore on the runtime code alone. `solidCore` (`Source.run`) first + runs the constructor **with no arguments**, so a contract whose constructor takes parameters + (solar-verify's `Counter`, `constructor(uint256 _limit)`) has no run at all there. Here the call + runs through the same ABI dispatcher (`ABI.Contract.callCalldataAtFromWithContext?`) from the + state whose storage is the call's, with no constructor: deployment is outside the statement, as + it is outside every runtime-bytecode statement (`Target.run` runs the runtime code from the + call's storage too). +* `BodyRuns E fuel fn b`: the body of `fn` runs, from every runtime related to the function's + first symbolic state, to the leaf of `b` the call's words select. `eval_stmt` gives it of an + erased (loop-free) body; a loop's ranking certificate (`Loop.lean`) gives it of a body with + loops. `runtime_run` is `source_run` with that as its only premise about the body: the call shows + the observable of the tree `brTree` makes of `b`, whatever its argument words. +-/ + +namespace SolidCore.Refinement.Generic.Loop +open SolidCore.Solidity SolidCore.Solidity.Source SolidCore.Refinement SolidCore.Refinement.Generic + +/-- SolidCore's result of `call` on the runtime code of `c` alone: the ABI dispatcher from the state +whose storage is the call's. -/ +def runtimeResult? (fuel : Nat) (c : TypeCheck.CheckedContract) (call : Call) : + Option TypeCheck.CoreAbiCallResult := + ABI.Contract.callCalldataAtFromWithContext? fuel c.core + { c.core.context with sender := callerAddress, self := selfAddress, value := call.callvalue } + { State.empty with + storage := call.storage.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) + State.empty.storage } + selfAddress callerAddress call.callvalue (call.calldata.data.toList.map (·.toNat)) + +/-- SolidCore on the runtime code alone, observed as `Source.run` observes. -/ +def runtimeRun (fuel : Nat) (c : TypeCheck.CheckedContract) (call : Call) : Option Observable := + (runtimeResult? fuel c call).map (Source.observe call) + +/-- **SolidCore's runtime code**, with statement fuel `fuel`. -/ +def solidCoreRuntime (fuel : Nat) : Sem := + { Prog := TypeCheck.CheckedContract, run := runtimeRun fuel } + +/-- The body of `fn` runs to the leaf of `b` from every runtime related to its first state. -/ +def BodyRuns (E : EraseEnv) (fuel : Nat) (fn : FunctionDef) (b : Br) : Prop := + ∀ ρ ctx rt, StmtRel ρ E ctx rt (initState fn) → + ∃ r, Stmt.eval fuel E.tbl ctx rt fn.body = .done (.ok r) ∧ LeafRel ρ E ctx r (b.eval ρ) + +/-- An erased body runs as its erasure. -/ +theorem bodyRuns_of_erase {E : EraseEnv} {fuel : Nat} {fn : FunctionDef} {b : Br} + (h : eraseStmt E fuel fn.body (initState fn) = some b) : BodyRuns E fuel fn b := + fun ρ ctx rt hrel => eval_stmt ρ E ctx fuel fn.body (initState fn) b h rt hrel + +theorem getD_storage_empty (σ : List (Nat × Nat)) (k : Nat) : + ((σ.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) State.empty.storage)[k % 2 ^ 256]?).getD 0 = + slotValue σ k := by + rw [Verify.getElem?_foldl_insertLoop] + apply getD_foldl_cover k σ _ 0 + left + simp [State.empty] + +/-- **A call of a function with clean argument words runs as the tree of its body's leaves.** -/ +theorem runtime_run_clean {fuel : Nat} {c : TypeCheck.CheckedContract} {σ : List (Nat × Nat)} + {sel : Nat} (hsel : sel < 2 ^ 32) {fn : FunctionDef} + (hfind : c.core.findFunctionBySelector? sel = some fn) {ws : List Nat} + (hw : widthsOf fn.params fn.paramAbiCleanups = some ws) + (hret : fn.returns.all wordBinding = true) {b : Br} + (hb : BodyRuns { envOf c.core with facts := argFacts ws 0 } fuel fn b) + {T : Tree} (hT : brTree fn (argFacts ws 0) b = some T) (args : List Nat) + (hlen : args.length = fn.params.length) (hargs : ∀ a ∈ args, a < 2 ^ 256) + (hclean : argsClean ws args = true) + (hdec : ABI.decodeFunctionArgs? fn (Dirty.argBytes args) = .ok (args.map .word)) : + runtimeRun fuel c { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } = + some (T.eval ⟨args, slotValue σ, solHash, callerWord⟩).obs := by + unfold runtimeRun runtimeResult? + simp only [Dirty.bytes_calldata] + rw [show ({ c.core.context with sender := callerAddress, self := selfAddress, value := 0 } : + Source.Context) = Wide.ctxOf c from rfl] + have hdrop : ((EthLib.Base.natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes args).drop + ABI.selectorBytes = Dirty.argBytes args := by + simp [ABI.selectorBytes, EthLib.Base.natToBytes_length] + simp only [ABI.Contract.callCalldataAtFromWithContext?, Dirty.readSelector_calldata _ hsel, hfind, + hdrop, hdec] + have hp := (widthsOf_spec hw).2.2.1 + have hr : ∀ r ∈ fn.returns, RetTy r.ty ∧ r.isStorageRef = false := + fun r hr => wordBinding_ty (List.all_eq_true.mp hret r hr) + generalize hctx : ABI.Contract.callContextAtWithBase c.core (Wide.ctxOf c) selfAddress callerAddress 0 + ((EthLib.Base.natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes args) = ctx + generalize hst : ({ State.empty with + storage := σ.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) State.empty.storage } : + Source.State) = st0 + have hacc : fn.acceptsValue 0 = true := by + simp [FunctionDef.acceptsValue, wordEq] + have hctxv : ctx.value = 0 := by + subst hctx; simp [ABI.Contract.callContextAtWithBase, SolidCore.Solidity.Shared.norm] + set ρ : Val := ⟨args, slotValue σ, solHash, callerWord⟩ with hρ + have hρok : ρ.Ok := slotValue_store σ + set K := argFacts ws 0 with hK + have hKρ : K.Hold ρ := argFacts_hold ρ hargs ws 0 (by simpa [hρ] using hclean) + set E : EraseEnv := { envOf c.core with facts := K } with hE + have hframe : fn.initialFrame? (args.map .word) = + some (frameOf ρ (paramLocals fn.params 0 ++ fn.returns.map fun r => (r.name, .lit 0))) := by + have h0 : BindingDecl.bindArgs? fn.params (args.map .word) = + some (frameOf ρ (paramLocals fn.params 0)) := + bindArgs_words ρ hargs fn.params 0 hp (by simp [hρ, hlen]) + simp only [FunctionDef.initialFrame?, h0, FunctionDef.returnDefaultBindings, + defaults_words ρ fn.returns hr, frameOf, List.map_append] + have hrel : StmtRel ρ E ctx + { state := { st0 with + selfBalance := SolidCore.Solidity.Shared.addWord + (SolidCore.Solidity.Shared.Account.balanceAt ctx.accountBalances ctx.self) ctx.value + worldMutatedSinceAdoption := true }, + locals := [frameOf ρ (paramLocals fn.params 0 ++ fn.returns.map fun r => (r.name, .lit 0))] } + (initState fn) := + { fields := by subst hctx; rfl + events := by subst hctx; rfl + checked := by subst hctx; rfl + sender := by subst hctx; rfl + hash := rfl + ok := hρok + frames := rfl + store := by + intro k hk + have := getD_storage_empty σ k + subst hst + simp only [State.loadSlot, StorageMap.lookup?, initState, Writes.store, hρ] + rw [← this] + simp only [SolidCore.Solidity.Shared.norm, modulus_eq, Std.HashMap.get?_eq_getElem?] + cases (List.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) State.empty.storage σ)[k % wordSize]? <;> rfl + logs := by subst hst; simp [State.empty, initState] + facts := hKρ } + obtain ⟨r, hrun, hleaf⟩ := hb ρ ctx _ hrel + have hcall : fn.call? fuel c.core.table ctx st0 (args.map .word) = + some (fn.callBodyResult st0 r) := by + have hacc' : fn.acceptsValue ctx.value = true := hctxv ▸ hacc + simp only [FunctionDef.call?, FunctionDef.call, FunctionDef.evalBodyEntry, hacc', hframe, + if_true, Option.map_some, Option.bind_some] + rw [show c.core.table = E.tbl from rfl, hrun] + rfl + obtain ⟨T', hT', hTe⟩ := brTree_eval fn K ρ b T hT + rw [hacc, if_pos rfl, hcall, ← hTe] + generalize b.eval ρ = l at hT' hleaf + cases l with + | normal S => + cases r <;> simp only [LeafRel] at hleaf + rename_i rt + simp only [leafTree, Option.bind_eq_bind, Option.bind_eq_some_iff] at hT' + obtain ⟨ws, hws, hT'⟩ := hT' + split at hT' + case isFalse => simp at hT' + rename_i hok + simp only [Option.some.injEq] at hT' + subst hT' + simp only [FunctionDef.callBodyResult, FunctionDef.collectReturns, collectReturnBindings, + collect_words ρ rt S hKρ hleaf.expr.locals fn.returns ws hok hws, untag_words, + encode_words ρ hKρ fn.returns ws hok, bind, Option.bind, Option.map_some] + simp only [Source.observe, Tree.eval, Res.obs, if_true, ↓reduceIte, logEntries_map, + hleaf.logs, Option.some.injEq, Observable.mk.injEq, true_and] + funext slot + exact loadSlot_eq _ S.writes ρ hρok hleaf.store slot + | returned S vs => + cases r <;> simp only [LeafRel] at hleaf + rename_i rt vals + obtain ⟨hst', rfl⟩ := hleaf + by_cases hv : vs = [] + · subst hv + simp only [leafTree, if_true, Option.bind_eq_bind, Option.bind_eq_some_iff] at hT' + obtain ⟨ws, hws, hT'⟩ := hT' + split at hT' + case isFalse => simp at hT' + rename_i hok + simp only [Option.some.injEq] at hT' + subst hT' + simp only [FunctionDef.callBodyResult, List.map_nil, List.isEmpty_nil, if_true, + FunctionDef.collectReturns, collectReturnBindings, + collect_words ρ rt S hKρ hst'.expr.locals fn.returns ws hok hws, untag_words, + encode_words ρ hKρ fn.returns ws hok, bind, Option.bind, Option.map_some] + simp only [Source.observe, Tree.eval, Res.obs, if_true, ↓reduceIte, logEntries_map, + hst'.logs, Option.some.injEq, Observable.mk.injEq, true_and] + funext slot + exact loadSlot_eq _ S.writes ρ hρok hst'.store slot + · simp only [leafTree, hv, if_false] at hT' + split at hT' + case isFalse => simp at hT' + rename_i hok + simp only [Option.some.injEq] at hT' + subst hT' + have hne : (vs.map fun e => Value.word (e.eval ρ)).isEmpty = false := by + cases vs with + | nil => exact absurd rfl hv + | cons _ _ => rfl + simp only [FunctionDef.callBodyResult, hne, Bool.false_eq_true, if_false, + FunctionDef.coerceReturnValues, coerceReturnBindings, + coerce_words ρ rt hKρ fn.returns vs hok, untag_words, + encode_words ρ hKρ fn.returns vs hok, bind, Option.bind, Option.map_some] + simp only [Source.observe, Tree.eval, Res.obs, if_true, ↓reduceIte, logEntries_map, + hst'.logs, Option.some.injEq, Observable.mk.injEq, true_and] + funext slot + exact loadSlot_eq _ S.writes ρ hρok hst'.store slot + | reverted p => + cases r <;> simp only [LeafRel] at hleaf + subst hleaf + cases p with + | empty => + simp only [leafTree, Option.some.injEq] at hT' + subst hT' + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, Fail.data, + ABI.Contract.encodeRevertData?, Source.observe, Tree.eval, Res.obs, hρ] + | panic c => + simp only [leafTree, Option.some.injEq] at hT' + subst hT' + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, Fail.data, encode_panic ρ, + Source.observe, Tree.eval, Res.obs, hρ] + | error m => + simp only [leafTree, Option.map_eq_some_iff] at hT' + obtain ⟨bs, hbs, rfl⟩ := hT' + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, Fail.data, encode_error ρ _ hbs, + Source.observe, Tree.eval, Res.obs, hρ] + +/-- info: 'SolidCore.Refinement.Generic.Loop.runtime_run_clean' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms runtime_run_clean + +end SolidCore.Refinement.Generic.Loop diff --git a/SolidCore/Refinement/Generic/LoopSeq.lean b/SolidCore/Refinement/Generic/LoopSeq.lean new file mode 100644 index 00000000..720c7277 --- /dev/null +++ b/SolidCore/Refinement/Generic/LoopSeq.lean @@ -0,0 +1,42 @@ +import SolidCore.Refinement.Generic.Loop + +/-! # Blocks and statement lists, for composing a body around a loop -/ + +namespace SolidCore.Refinement.Generic.Loop +open SolidCore.Solidity.Source SolidCore.Refinement.Generic + +theorem eval_block_of {n : Nat} {tbl : FunctionTable} {ctx : Context} {rt : Runtime} + {ss : List Stmt} {r : Result} (h : Stmt.evalList n tbl ctx rt.pushScope ss = .done (.ok r)) : + Stmt.eval (n + 1) tbl ctx rt (.block ss) = .done (.ok (r.mapRuntime Runtime.popScope)) := by + rw [Stmt.eval] + simp only [h, bind, EvmCompiler.Simulation.Interaction.bind] + rfl + +theorem evalList_nil (n : Nat) (tbl : FunctionTable) (ctx : Context) (rt : Runtime) : + Stmt.evalList n tbl ctx rt [] = .done (.ok (.normal rt)) := by + simp only [Stmt.evalList] + rfl + +theorem evalList_cons_normal {n : Nat} {tbl : FunctionTable} {ctx : Context} {rt rt' : Runtime} + {s : Stmt} {rest : List Stmt} (h : Stmt.eval n tbl ctx rt s = .done (.ok (.normal rt'))) : + Stmt.evalList n tbl ctx rt (s :: rest) = Stmt.evalList n tbl ctx rt' rest := by + simp only [Stmt.evalList] + rw [h, bind_done_ok] + +/-- A statement that does not end normally ends the list it starts. -/ +theorem evalList_cons_stop {n : Nat} {tbl : FunctionTable} {ctx : Context} {rt : Runtime} + {s : Stmt} {rest : List Stmt} {r : Result} (h : Stmt.eval n tbl ctx rt s = .done (.ok r)) + (hr : ∀ rt', r ≠ .normal rt') : + Stmt.evalList n tbl ctx rt (s :: rest) = .done (.ok r) := by + simp only [Stmt.evalList] + rw [h, bind_done_ok] + cases r with + | normal rt' => exact absurd rfl (hr rt') + | _ => rfl + +theorem Result.mapRuntime_reverted (f : Runtime → Runtime) (rt : Runtime) (e : RevertData) : + (Result.reverted rt e).mapRuntime f = .reverted (f rt) e := rfl + +theorem Facts.hold_nil (ρ : Val) : Facts.Hold ρ [] := fun _ h => absurd h List.not_mem_nil + +end SolidCore.Refinement.Generic.Loop diff --git a/SolidCore/Refinement/Generic/LoopStmt.lean b/SolidCore/Refinement/Generic/LoopStmt.lean new file mode 100644 index 00000000..253e1bea --- /dev/null +++ b/SolidCore/Refinement/Generic/LoopStmt.lean @@ -0,0 +1,168 @@ +import SolidCore.Refinement.Generic.Loop + +/-! +# Increments of the loop fragment, and moving a relation between symbolic states + +`i++` and `count++` on `uint256` words, the updates of most loops, as erasure leaves: +`eval_incVar` (a local word) and `eval_incField` (a word storage field) run SolidCore's +`Expr.incDec` statement under `StmtRel` to the leaf the overflow guard selects: `Panic(0x11)` +when the old word is `2 ^ 256 - 1`, else the old word plus one written back. + +`StmtRel.congr` moves `StmtRel` to another valuation and symbolic state that show the same +locals, storage, logs and caller: what a loop's invariant needs to name the state at its header with +fresh words for the values the loop changes. +-/ + +namespace SolidCore.Refinement.Generic.Loop +open SolidCore.Solidity.Source SolidCore.Refinement.Generic + +/-- **`StmtRel` depends only on what the symbolic state shows.** -/ +theorem StmtRel.congr {ρ ρ' : Val} {E : EraseEnv} {ctx : Context} {rt : Runtime} {S S' : SymState} + (h : StmtRel ρ E ctx rt S) (hash : ρ'.hash = solHash) (ok : ρ'.Ok) (facts : E.facts.Hold ρ') + (frames : S.scopes.map (frameOf ρ) = S'.scopes.map (frameOf ρ')) + (store : ∀ k, k < wordSize → Writes.store ρ S.writes k = Writes.store ρ' S'.writes k) + (logs : S.logs.map (Log.eval ρ) = S'.logs.map (Log.eval ρ')) + (caller : S.caller.eval ρ = S'.caller.eval ρ' := by rfl) : + StmtRel ρ' E ctx rt S' := + { fields := h.fields + events := h.events + checked := h.checked + sender := h.sender.trans caller + hash := hash + ok := ok + frames := h.frames.trans frames + store := fun k hk => (h.store k hk).trans (store k hk) + logs := h.logs.trans logs + facts := facts } + +/-- The leaf of `x++` on a local word `x` whose word is `old`, `L'` the scopes with `x` set. -/ +def incVarBr (old : WExpr) (L' : Scopes) (S : SymState) : Br := + guards (overflow .add old (.lit 1)).toList (.leaf (.normal { S with scopes := L' })) + +theorem one_eq (ρ : Val) : (Value.word 1 : Value) = .word ((WExpr.lit 1).eval ρ) := rfl + +theorem binOf_add : binOf .add = some .add := rfl + +theorem pure_bind_sol {α β : Type} (a : α) (k : α → SolI β) : ((pure a : SolI α) >>= k) = k a := rfl + +set_option maxHeartbeats 2000000 in +/-- **`x++` on a local word.** -/ +theorem eval_incVar (ρ : Val) (E : EraseEnv) (ctx : Context) (rt : Runtime) (S : SymState) + (hrel : StmtRel ρ E ctx rt S) (n : Nat) (post : Bool) {x : String} {old : WExpr} {L' : Scopes} + (hold : Scopes.get? S.scopes x = some old) + (hL : Scopes.set S.scopes x (.bin .add old (.lit 1)) = some L') : + ∃ r, Stmt.eval (n + 1) E.tbl ctx rt + (.exprStmt (.incDec .add post (some (.uint 256)) (.var x))) = .done (.ok r) ∧ + LeafRel ρ E ctx r ((incVarBr old L' S).eval ρ) := by + obtain ⟨old', hold'⟩ := Scopes.get?_of_set hL + have hx : rt.lookupLocal? x = some (.word (old.eval ρ)) := hrel.expr.locals x old hold + have hbase : rt.lookupStorageBase? x = none := by simp [Runtime.lookupStorageBase?, hx] + have hassign : rt.assignLocal? x (.word ((WExpr.bin .add old (.lit 1)).eval ρ)) = + some { rt with locals := L'.map (frameOf ρ) } := by + simp [Runtime.assignLocal?, hx, Value.coerceLike?, hrel.frames, env_assign ρ S.scopes x _, hL] + have hrel' : StmtRel ρ E ctx { rt with locals := L'.map (frameOf ρ) } { S with scopes := L' } := + { hrel with frames := rfl } + have hread : ResolvedLValue.read ctx rt (.local x) = .ok (.word (old.eval ρ)) := by + simp [ResolvedLValue.read, ResolvedLValue.readRaw, hx, Runtime.derefMemoryValue, bind, + Except.bind] + have hcl : ∀ w, w < wordSize → ValueCleanup.apply true (.uint 256) (.word w) = .ok (.word w) := + fun w hw => uintCleanup_256 w hw + have happ := apply_erased ρ binOf_add old (.lit 1) + rw [← one_eq] at happ + have hcleq : ctx.checked = true := hrel.checked + rw [Stmt.eval] + simp only [Expr.eval, Expr.orderFuel] + rw [Expr.evalFuel] + simp only [Expr.resolveLValueFuel, hbase, hx, pure_bind_sol] + unfold incVarBr + rw [guards_eval] + by_cases hg : (overflow .add old (.lit 1)).toList.any (fun g => g.eval ρ != 0) = true + · have hE : ResolvedLValue.applyIncDecCleanup ctx rt (.local x) .add post (.uint 256) = + .error (.panic 0x11) := by + simp only [ResolvedLValue.applyIncDecCleanup, hread, hcleq, bind, Except.bind, + Value.oneLike?, happ, hg, ↓reduceIte] + rw [hE] + simp only [hg, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · have hE : ∃ v, ResolvedLValue.applyIncDecCleanup ctx rt (.local x) .add post (.uint 256) = + .ok (v, { rt with locals := L'.map (frameOf ρ) }) := by + simp only [ResolvedLValue.applyIncDecCleanup, hread, hcleq, bind, Except.bind, + Value.oneLike?, happ, hg, Bool.false_eq_true, ↓reduceIte, hcl _ (WExpr.eval_lt ρ _), + ResolvedLValue.write, hassign] + cases post <;> exact ⟨_, rfl⟩ + obtain ⟨v, hv⟩ := hE + rw [hv] + simp only [hg, Bool.false_eq_true, ↓reduceIte] + exact ⟨_, rfl, hrel'⟩ + +/-- The leaf of `x++` on a word field of slot `k` at byte offset `off` of `bytes` bytes. -/ +def incFieldBr (k off bytes : Nat) (S : SymState) : Br := + guards (overflow .add (readField (S.writes.read (.lit k)) off bytes) (.lit 1)).toList + (.leaf (.normal { S with writes := (S.writes.set (.lit k) + (writeField (S.writes.read (.lit k)) (.bin .add (readField (S.writes.read (.lit k)) off bytes) + (.lit 1)) off bytes)) })) + +set_option maxHeartbeats 2000000 in +/-- **`x++` on a word storage field.** -/ +theorem eval_incField (ρ : Val) (E : EraseEnv) (ctx : Context) (rt : Runtime) (S : SymState) + (hrel : StmtRel ρ E ctx rt S) (n : Nat) (post : Bool) {x : String} {k off bytes : Nat} + (hk : fieldOf? E.fields x = some (k, off, bytes)) : + ∃ r, Stmt.eval (n + 1) E.tbl ctx rt + (.exprStmt (.incDec .add post (some (.uint 256)) (.storageRead .header x []))) = + .done (.ok r) ∧ LeafRel ρ E ctx r ((incFieldBr k off bytes S).eval ρ) := by + obtain ⟨f, hfx, rfl, rfl, rfl⟩ := fieldOf?_spec hrel.fields hk + have hsl : rt.state.loadSlot f.slot = (S.writes.read (.lit f.slot)).eval ρ := + slot_read hrel.expr hfx.slot + have hslw : rt.state.loadSlot f.slot < wordSize := hsl ▸ WExpr.eval_lt _ _ + have hst : ∀ w : WExpr, ResolvedLValue.write ctx rt (.storageField x) (.word (w.eval ρ)) = + .ok { rt with state := (rt.state.storeSlot f.slot + ((writeField (S.writes.read (.lit f.slot)) w f.packedOffset f.packedBytes).eval ρ)) } := by + intro w + simp only [ResolvedLValue.write, store_field hfx hslw _ (w.eval_lt ρ), + writeField_eval ρ _ _ hfx.fits hfx.bytes, hsl] + have hread : ResolvedLValue.read ctx rt (.storageField x) = + .ok (.word ((readField (S.writes.read (.lit f.slot)) f.packedOffset f.packedBytes).eval ρ)) := by + simp [ResolvedLValue.read, ResolvedLValue.readRaw, load_field hfx hslw, hsl, + Runtime.derefMemoryValue, bind, Except.bind, readField_eval ρ _ hfx.fits hfx.bytes] + have hcl : ∀ w, w < wordSize → ValueCleanup.apply true (.uint 256) (.word w) = .ok (.word w) := + fun w hw => uintCleanup_256 w hw + have happ := apply_erased ρ binOf_add + (readField (S.writes.read (.lit f.slot)) f.packedOffset f.packedBytes) (.lit 1) + rw [← one_eq] at happ + have hcleq : ctx.checked = true := hrel.checked + rw [Stmt.eval] + simp only [Expr.eval, Expr.orderFuel, Expr.listEvalFuel] + rw [Expr.evalFuel] + simp only [Expr.resolveLValueFuel, pure_bind_sol] + unfold incFieldBr + rw [guards_eval] + by_cases hg : (overflow .add (readField (S.writes.read (.lit f.slot)) f.packedOffset f.packedBytes) + (.lit 1)).toList.any (fun g => g.eval ρ != 0) = true + · have hE : ResolvedLValue.applyIncDecCleanup ctx rt (.storageField x) .add post (.uint 256) = + .error (.panic 0x11) := by + simp only [ResolvedLValue.applyIncDecCleanup, hread, hcleq, bind, Except.bind, + Value.oneLike?, happ, hg, ↓reduceIte] + rw [hE] + simp only [hg, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · have hE : ∃ v, ResolvedLValue.applyIncDecCleanup ctx rt (.storageField x) .add post (.uint 256) = + .ok (v, { rt with state := (rt.state.storeSlot f.slot + ((writeField (S.writes.read (.lit f.slot)) (.bin .add (readField (S.writes.read (.lit f.slot)) + f.packedOffset f.packedBytes) (.lit 1)) f.packedOffset f.packedBytes).eval ρ)) }) := by + simp only [ResolvedLValue.applyIncDecCleanup, hread, hcleq, bind, Except.bind, + Value.oneLike?, happ, hg, Bool.false_eq_true, ↓reduceIte, hcl _ (WExpr.eval_lt ρ _), hst] + cases post <;> exact ⟨_, rfl⟩ + obtain ⟨v, hv⟩ := hE + rw [hv] + simp only [hg, Bool.false_eq_true, ↓reduceIte] + exact ⟨_, rfl, hrel.writeField hfx _⟩ + +/-- info: 'SolidCore.Refinement.Generic.Loop.eval_incField' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms eval_incField + +/-- info: 'SolidCore.Refinement.Generic.Loop.eval_incVar' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms eval_incVar + +end SolidCore.Refinement.Generic.Loop diff --git a/SolidCore/Refinement/Generic/Mir.lean b/SolidCore/Refinement/Generic/Mir.lean new file mode 100644 index 00000000..aaa0f27f --- /dev/null +++ b/SolidCore/Refinement/Generic/Mir.lean @@ -0,0 +1,447 @@ +import SolarTV.MIR.Program +import SolidCore.Refinement.Generic.Simp + +/-! +# Solar's first lowered MIR, run symbolically + +`symTree m sel n fuel env` runs the lowered MIR module `m` (SolarTV.MIR.Lowered, the module after +`lower-evm-shaped`) on a symbolic call of selector `sel` with `n` argument words, no value and +any storage, and gives the call's outcome as a `Tree`, the object the source side computes too. +`symTreeValue m sel n fuel env` runs it the same way on a call with a value other than 0. + +The run mirrors SolarTV's `moduleBlock` and `segment` step by step, with `fuel` steps along each path, +from a symbolic frame: the returns of the internal calls in progress (`SReturn`, innermost first), +the position (SolarTV's `Pos`), the symbolic values, the symbolic state and the facts of the path: + +* a value is a symbolic word (`SV.w`), the first call data word (`SV.cd0`), which only its + selector, `shr(224, ·)`, may read, or the call's value when it is not 0 (`SV.paid`), which only + `iszero`, `eq` and `ne` against 0 and a branch may read; +* the call's inputs are known words: `callvalue` is the run's `cv` (the word 0 in `symTree`, + `SV.paid` in `symTreeValue`), `calldatasize` is `4 + 32 * n`, the word at `4 + 32 * i` is + argument `i`; +* pure operations of the fragment (`binOfOp`: arithmetic, comparisons, `and`, `or`, `xor`, + `shl`, `shr`, `byte`; `iszero`, `not`, `ne`) build words, folding constants + (`mkBin`, `mkUn`), and a widening cast (`Inst.word`: `zext` to 256 bits) keeps its word; memory is a function from byte offsets to `OByte`s, written by `mstore` at + constant offsets; +* storage is the writes of the run (`Writes`): `sload` and `sstore` take any slot word, `sload` + reading `Writes.read` and `sstore` writing `Writes.set`; +* a log (`log0` to `log4`) with a constant offset and size appends its topic words and its data + bytes to the logs of the state (`SState.logs`, oldest first); +* with the environment flags `env` (`EnvFlags`), `caller` is `callerWord` when they read the + caller, and `keccak256` of 64 bytes at a constant offset whose memory holds two words + (`memWord`) is `WExpr.hash` of them when they hash, as an oracle that `MirRun.EnvAsk` + describes computes them; otherwise neither has a run; +* an `assume` needs its word, simplified on the facts of the path (`WExpr.simp`), to be a + constant of the side it states; +* an internal call runs the instructions before it, pushes its return and enters the callee's + block 0 with its parameters bound; a `leave` pops the innermost return and binds the call's + result (`symBindResult`), as SolarTV's `bindResult` does; a tail call enters the callee and + keeps the returns; entering a function stores its entry heap (`Function.entryHeap`, a constant + word codegen placed) at `0x40` (`symStart`), a `heap_floor` is its constant word, and an + `mload` at a constant offset whose memory holds one word (`memWord`) reads it; a call that + binds or publishes further results (a callee returning several words) and `alloc` are outside + the fragment; +* a branch on a constant takes its side, a branch on `SV.paid` its nonzero side, a branch on any + other word becomes a `Tree.ite` whose sides run with the word as one more fact (`Facts.add`), + a switch needs a constant key and constant cases; +* `return` and `revert` with constant offsets and sizes read the bytes of memory; a success keeps + the writes and the logs. + +Anything else (another effect, a symbolic memory offset, phis without the predecessor, a +`leave` with no call in progress, running out of fuel) makes the run `none`, so the check that +uses it fails rather than trusting it. `MirRun.symTree_sound` and `MirRun.symTreeValue_sound` +prove that the module's run shows the tree's result. +-/ + +namespace SolidCore.Refinement.Generic +open SolarTV SolarTV.Machine SolarTV.MIR.Lowered EvmRules + +/-! ## Symbolic values and states -/ + +/-- A symbolic value: a word of the call, the first word of its call data, or its value when +that is not 0. -/ +inductive SV where + | w (e : WExpr) + | cd0 + | paid + deriving DecidableEq, Repr + +abbrev SEnv := Nat → SV + +def SEnv.set (env : SEnv) (id : Nat) (v : SV) : SEnv := fun j => if j = id then v else env j + +def SV.ofOperand (env : SEnv) : Operand → SV + | .value id => env id + | .const word => .w (.lit word.toNat) + +/-- A symbolic machine state: memory bytes, the storage writes (newest first) and the logs +(oldest first). -/ +structure SState where + mem : Nat → OByte + writes : Writes + logs : List Log + +/-- The state a call starts in: zero memory, no writes, no logs. -/ +def SState.initial : SState := ⟨fun _ => .lit 0, [], []⟩ + +def storeBytes (mem : Nat → OByte) (off : Nat) (e : WExpr) : Nat → OByte := + fun i => if off ≤ i ∧ i < off + 32 then .byteOf e (i - off) else mem i + +/-- The word the 32 bytes of memory at `off` are, when they are the bytes of one word in order. -/ +def memWord (mem : Nat → OByte) (off : Nat) : Option WExpr := + match mem off with + | .byteOf e _ => + if (List.range 32).all (fun i => mem (off + i) == .byteOf e i) then some e else none + | .lit _ => none + +/-- The words of symbolic values that are all words. -/ +def svWords : List SV → Option (List WExpr) + | [] => some [] + | .w e :: rest => (svWords rest).map (e :: ·) + | _ :: _ => none + +def calldataArg (n off : Nat) : Option SV := + if off = 0 then some .cd0 + else if 4 ≤ off ∧ (off - 4) % 32 = 0 ∧ (off - 4) / 32 < n then some (.w (.arg ((off - 4) / 32))) + else none + +def binOfOp : EVM.Op → Option BinOp + | .add => some .add + | .sub => some .sub + | .mul => some .mul + | .div => some .div + | .lt => some .lt + | .gt => some .gt + | .eq => some .eq + | .and => some .and + | .or => some .or + | .xor => some .xor + | .shl => some .shl + | .shr => some .shr + | .byte => some .byte + | _ => none + +def symPure (sel : Nat) : EVM.Op → List SV → Option SV + | .shr, [.w (.lit 224), .cd0] => some (.w (.lit sel)) + | .iszero, [.w a] => some (.w (mkUn .iszero a)) + | .not, [.w a] => some (.w (mkUn .not a)) + | op, [.w a, .w b] => (binOfOp op).map fun o => .w (mkBin o a b) + -- A value other than 0: `iszero` is 0, and so is `eq` against 0. + | .iszero, [.paid] => some (.w (.lit 0)) + | .eq, [.paid, .w (.lit z)] => if z % wordSize = 0 then some (.w (.lit 0)) else none + | .eq, [.w (.lit z), .paid] => if z % wordSize = 0 then some (.w (.lit 0)) else none + | _, _ => none + +def outBytes (mem : Nat → OByte) (off size : Nat) : List OByte := + (List.range size).map fun i => mem (off + i) + +/-- The environment reads the symbolic run may take: `caller` (as `callerWord`) and +`keccak256` of two words (as `hash`). -/ +structure EnvFlags where + caller : Bool + hash : Bool + /-- Whether `caller` reads the symbolic caller `WExpr.caller` rather than `callerWord`. -/ + sym : Bool := false + deriving DecidableEq, Repr + +/-- No environment read. -/ +def EnvFlags.off : EnvFlags := { caller := false, hash := false } + +/-- The caller and the hash of two words. -/ +def EnvFlags.all : EnvFlags := { caller := true, hash := true } + +/-- The caller only. -/ +def EnvFlags.callerOnly : EnvFlags := { caller := true, hash := false } + +/-- The symbolic caller and the hash of two words: the flags of a check for every caller. -/ +def EnvFlags.allSym : EnvFlags := { caller := true, hash := true, sym := true } + +/-- The word `caller` reads under the flags: the symbolic caller, or `callerWord`. -/ +def EnvFlags.callerExpr (ev : EnvFlags) : WExpr := if ev.sym then .caller else .lit callerWord + +/-- An effect on symbolic operands: its result and the state after it. `ev` says which +environment reads `caller` and `keccak256` may take. -/ +def symEffect (ev : EnvFlags) (cv : SV) (n : Nat) : Effect → List SV → SState → Option (Option SV × SState) + | .calldatasize, [], st => some (some (.w (.lit (4 + 32 * n))), st) + | .callvalue, [], st => some (some cv, st) + | .calldataload, [.w (.lit off)], st => (calldataArg n (off % wordSize)).map fun v => (some v, st) + | .sload, [.w k], st => some (some (.w (st.writes.read k)), st) + | .sstore, [.w k, .w e], st => some (none, { st with writes := st.writes.set k e }) + | .mstore, [.w (.lit off), .w e], st => + some (none, { st with mem := storeBytes st.mem (off % wordSize) e }) + | .mload, [.w (.lit off)], st => + match memWord st.mem (off % wordSize) with + | some e => some (some (.w e), st) + | none => none + | .caller, [], st => if ev.caller = true then some (some (.w ev.callerExpr), st) else none + | .keccak256, [.w (.lit off), .w (.lit size)], st => + if ev.hash = true ∧ size % wordSize = 64 then + match memWord st.mem (off % wordSize), memWord st.mem (off % wordSize + 32) with + | some a, some b => some (some (.w (.hash a b)), st) + | _, _ => none + else none + | .log k, .w (.lit off) :: .w (.lit size) :: topics, st => + if topics.length = k then + match svWords topics with + | some ts => + some (none, { st with + logs := st.logs ++ [⟨ts, outBytes st.mem (off % wordSize) (size % wordSize)⟩] }) + | none => none + else none + | _, _, _ => none + +/-- The value an `assume` reads off its simplified word: a constant, or `eq a 0` with the side of +`a` that the path's facts record (solar's `assume` of a branch word it already took). -/ +def WExpr.decided (K : Facts) : WExpr → Option Nat + | .lit n => some n + | .bin .eq a (.lit 0) => + match K.lookup a with + | some false => some 1 + | some true => some 0 + | none => none + | _ => none + +theorem WExpr.decided_sound {ρ : Val} {K : Facts} (h : K.Hold ρ) {e : WExpr} {v : Nat} + (hd : e.decided K = some v) : e.eval ρ = v % wordSize := by + match e, hd with + | .lit n, hd => + simp only [WExpr.decided, Option.some.injEq] at hd + subst hd + rfl + | .bin .eq a (.lit 0), hd => + simp only [WExpr.decided] at hd + split at hd + · rename_i hl + simp only [Option.some.injEq] at hd + subst hd + have ha := (Facts.lookup_sound h hl).mpr rfl + simp [WExpr.eval, BinOp.eval, ha] + · rename_i hl + simp only [Option.some.injEq] at hd + subst hd + have ha : ¬ a.eval ρ = 0 := fun h0 => by simpa using (Facts.lookup_sound h hl).mp h0 + simp [WExpr.eval, BinOp.eval, ha] + · simp at hd + +/-- The instructions of a block up to its first internal call, on the facts `K` of the path. -/ +def symInsts (ev : EnvFlags) (cv : SV) (sel n : Nat) (K : Facts) : + List Inst → SEnv → SState → Option (SEnv × SState) + | [], env, st => some (env, st) + | .pure dst op args :: rest, env, st => + match symPure sel op (args.map (SV.ofOperand env)) with + | some v => symInsts ev cv sel n K rest (env.set dst v) st + | none => none + | .effect dst eff args :: rest, env, st => + match symEffect ev cv n eff (args.map (SV.ofOperand env)) st with + | some (res, st') => + let env := match dst, res with + | some d, some v => env.set d v + | _, _ => env + symInsts ev cv sel n K rest env st' + | none => none + | .ne dst a b :: rest, env, st => + match SV.ofOperand env a, SV.ofOperand env b with + | .w x, .w y => symInsts ev cv sel n K rest (env.set dst (.w (mkUn .iszero (mkBin .eq x y)))) st + -- A value other than 0 is not 0. + | .paid, .w (.lit z) => + if z % wordSize = 0 then symInsts ev cv sel n K rest (env.set dst (.w (.lit 1))) st else none + | .w (.lit z), .paid => + if z % wordSize = 0 then symInsts ev cv sel n K rest (env.set dst (.w (.lit 1))) st else none + | _, _ => none + | .assume negated op args :: rest, env, st => + match symPure sel op (args.map (SV.ofOperand env)) with + | some (.w e) => + match (e.simp K).decided K with + | some v => + if v % wordSize = 0 then (if negated then symInsts ev cv sel n K rest env st else none) + else (if negated then none else symInsts ev cv sel n K rest env st) + | none => none + | _ => none + -- A widening cast (`zext`, `inttoptr`, `ptrtoint` to 256 bits) keeps its word. + | .word dst a :: rest, env, st => + match SV.ofOperand env a with + | .w e => symInsts ev cv sel n K rest (env.set dst (.w e)) st + | _ => none + -- The heap floor codegen placed: a constant word. + | .heapFloor dst floor :: rest, env, st => + symInsts ev cv sel n K rest (env.set dst (.w (.lit floor.toNat))) st + -- Outside the fragment (a low-bits mask, a select, an allocation) or an + -- internal call, which + -- `symSegment` splits off first: no run. + | _ :: _, _, _ => none + +def symPhis (incoming : SEnv) (pred : Nat) : + List (Nat × List (Nat × Operand)) → SEnv → Option SEnv + | [], env => some env + | (dst, arms) :: rest, env => + match arms.find? (fun arm => arm.1 == pred) with + | some (_, op) => symPhis incoming pred rest (env.set dst (SV.ofOperand incoming op)) + | none => none + +def symSwitch (env : SEnv) (key default : Nat) : List (Operand × Nat) → Option Nat + | [] => some default + | (c, t) :: rest => + match SV.ofOperand env c with + | .w (.lit v) => if v % wordSize = key % wordSize then some t else symSwitch env key default rest + | _ => none + +def symBindParams : List Nat → List SV → SEnv → Option SEnv + | [], [], env => some env + | p :: ps, a :: as, env => symBindParams ps as (env.set p a) + | _, _, _ => none + +/-- The caller's values after a return, as SolarTV's `bindResult`. -/ +def symBindResult (env : SEnv) : Option Nat → List SV → Option SEnv + | none, [] => some env + | some dst, [v] => some (env.set dst v) + | _, _ => none + +/-! ## Frames and steps -/ + +/-- Where an internal call returns, as SolarTV's `Return`, with symbolic values. -/ +structure SReturn where + fn : Nat + block : Nat + dst : Option Nat + rest : List Inst + term : Terminator + env : SEnv + +/-- The state a function starts in, as SolarTV's `Function.start`: its entry heap, a constant +word codegen placed, stored in the free memory pointer's slot `0x40`. -/ +def symStart (g : Function) (st : SState) : SState := + match g.entryHeap with + | none => st + | some heap => { st with mem := storeBytes st.mem 64 (.lit heap.toNat) } + +/-- The callee of an internal or tail call, when the module has it; entering it stores its entry +heap (`symStart`). -/ +def symCallee (m : Module) (callee : Nat) : Option Function := + m.functions[callee]? + +/-- The state the module's entry function starts the run in (`Module.startState`). -/ +def symEntryStart (m : Module) (st : SState) : SState := + match m.functions[m.entry]? with + | some f => symStart f st + | none => st + +/-- What one step of the symbolic run gives: an end, the next frame, or a branch on a word to +block `yes` or `no` of function `fn` from block `b`. -/ +inductive SNext where + | done (T : Tree) + | go (stack : List SReturn) (pos : Pos) (env : SEnv) (st : SState) + | fork (e : WExpr) (stack : List SReturn) (fn b yes no : Nat) (env : SEnv) (st : SState) + +/-- A block's terminator after its instructions. -/ +def symTerm (m : Module) (stack : List SReturn) (fn b : Nat) (env : SEnv) (st : SState) : + Terminator → Option SNext + | .jump t => some (.go stack (.enter fn b t) env st) + | .branch c yes no => + match SV.ofOperand env c with + | .w e => + match e.lit? with + | some v => some (.go stack (.enter fn b (if v % wordSize = 0 then no else yes)) env st) + | none => some (.fork e stack fn b yes no env st) + | .cd0 => none + | .paid => some (.go stack (.enter fn b yes) env st) + | .switch k d cs => + match SV.ofOperand env k with + | .w (.lit kv) => + match symSwitch env kv d cs with + | some t => some (.go stack (.enter fn b t) env st) + | none => none + | _ => none + | .tailCall callee args => + match symCallee m callee with + | none => none + | some g => + match symBindParams g.params (args.map (SV.ofOperand env)) (fun _ => .w (.lit 0)) with + | none => none + | some env' => some (.go stack (.enter callee 0 0) env' (symStart g st)) + | .leave values => + match stack with + | [] => none + | ret :: stack => + match symBindResult ret.env ret.dst (values.map (SV.ofOperand env)) with + | none => none + | some env' => some (.go stack (.resume ret.fn ret.block ret.rest ret.term) env' st) + | .ret off size => + match SV.ofOperand env off, SV.ofOperand env size with + | .w (.lit o), .w (.lit s) => + some (.done (.halt true (outBytes st.mem (o % wordSize) (s % wordSize)) st.writes st.logs)) + | _, _ => none + | .revert off size => + match SV.ofOperand env off, SV.ofOperand env size with + | .w (.lit o), .w (.lit s) => + some (.done (.halt false (outBytes st.mem (o % wordSize) (s % wordSize)) [] [])) + | _, _ => none + | .stop => some (.done (.halt true [] st.writes st.logs)) + | .invalid => some (.done (.halt false [] [] [])) + +/-- The rest of a block from its instructions, as SolarTV's `segment`. -/ +def symSegment (ev : EnvFlags) (cv : SV) (m : Module) (sel n : Nat) (K : Facts) (stack : List SReturn) + (fn b : Nat) (insts : List Inst) (term : Terminator) (env : SEnv) (st : SState) : + Option SNext := + match splitCall insts with + | (before, some (dst, callee, args, [], none, rest)) => + match symInsts ev cv sel n K before env st with + | none => none + | some (env, st) => + match symCallee m callee with + | none => none + | some g => + match symBindParams g.params (args.map (SV.ofOperand env)) (fun _ => .w (.lit 0)) with + | none => none + | some inner => + some (.go (⟨fn, b, dst, rest, term, env⟩ :: stack) (.enter callee 0 0) inner (symStart g st)) + -- A call that binds or publishes further results (a callee returning several words): + -- outside the fragment. + | (_, some _) => none + | (before, none) => + match symInsts ev cv sel n K before env st with + | none => none + | some (env, st) => symTerm m stack fn b env st term + +/-- One step of the module, as SolarTV's `moduleBlock`. -/ +def symStep (ev : EnvFlags) (cv : SV) (m : Module) (sel n : Nat) (K : Facts) : + List SReturn → Pos → SEnv → SState → Option SNext + | stack, .enter fn pred b, env, st => + match m.functions[fn]? with + | none => none + | some f => + match f.blocks[b]? with + | none => none + | some blk => + match symPhis env pred blk.phis env with + | none => none + | some env => symSegment ev cv m sel n K stack fn b blk.insts blk.term env st + | stack, .resume fn b insts term, env, st => symSegment ev cv m sel n K stack fn b insts term env st + +/-- The symbolic run, one step per unit of fuel; a branch on a word runs both sides, each with +the word's side as one more fact. -/ +def symRun (ev : EnvFlags) (cv : SV) (m : Module) (sel n : Nat) : + Nat → List SReturn → Pos → SEnv → SState → Facts → Option Tree + | 0, _, _, _, _, _ => none + | fuel + 1, stack, pos, env, st, K => + match symStep ev cv m sel n K stack pos env st with + | none => none + | some (.done T) => some T + | some (.go stack pos env st) => symRun ev cv m sel n fuel stack pos env st K + | some (.fork e stack fn b yes no env st) => + match symRun ev cv m sel n fuel stack (.enter fn b yes) env st (K.add e true), + symRun ev cv m sel n fuel stack (.enter fn b no) env st (K.add e false) with + | some t, some f => some (.ite e t f) + | _, _ => none + +/-- The tree of a call of selector `sel` on `n` argument words, from the module's entry. -/ +def symTree (m : Module) (sel n fuel : Nat) (env : EnvFlags := .off) : Option Tree := + symRun env (.w (.lit 0)) m sel n fuel [] (.enter m.entry 0 0) (fun _ => .w (.lit 0)) + (symEntryStart m SState.initial) [] + +/-- The tree of a call of selector `sel` on `n` argument words with a value other than 0, from +the module's entry. -/ +def symTreeValue (m : Module) (sel n fuel : Nat) (env : EnvFlags := .off) : Option Tree := + symRun env .paid m sel n fuel [] (.enter m.entry 0 0) (fun _ => .w (.lit 0)) + (symEntryStart m SState.initial) [] + +end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Generic/MirNoLog.lean b/SolidCore/Refinement/Generic/MirNoLog.lean new file mode 100644 index 00000000..ece2cd81 --- /dev/null +++ b/SolidCore/Refinement/Generic/MirNoLog.lean @@ -0,0 +1,273 @@ +import SolarTV.MIR.Program + +/-! +# A lowered MIR module without `LOG` logs nothing + +`Module.noLog m` checks that no instruction of `m` is a `log` effect. Then every end of `m` +on every call, under every oracle, has no logs (`Module.run_logs`, `Module.ends_logs`): +every other effect leaves the logs as they were (external calls, creations and `GAS` append +events to the world, but none is a log), and so do internal calls, returns and halts. + +The proof is one invariant of `moduleBlock`'s frames (`FrameOk`): the state has no logs, and +the instructions still to run (in the frame and in every pending return) are free of `log`, +since they are suffixes of `m`'s blocks. +-/ + +namespace SolarTV.MIR.Lowered + +open SolarTV.Machine + +/-- An instruction that is not a `log` effect. -/ +def Inst.noLog : Inst → Bool + | .effect _ (.log _) _ => false + | _ => true + +/-- No instruction of the module is a `log` effect. -/ +def Module.noLog (m : Module) : Bool := + m.functions.all fun f => f.blocks.all fun b => b.insts.all Inst.noLog + +/-- The log an event is, if it is one. -/ +def logOf : Event → Option (List Nat × List Nat) + | .log topics data => some (topics.map BitVec.toNat, data.map BitVec.toNat) + | _ => none + +theorem logs_eq (s : State) : logs s = s.world.filterMap logOf := by + unfold logs + congr 1 + funext e + cases e <;> rfl + +/-- Every effect but `log` leaves the logs as they were. -/ +theorem Effect.apply_logs {o : Oracle} {call : Call} {e : Effect} {args : List EvmRules.Word} {s s' : State} + {r : Option EvmRules.Word} (he : ∀ n, e ≠ .log n) (h : e.apply o call args s = some (r, s')) : + logs s' = logs s := by + unfold Effect.apply at h + split at h + all_goals first + | exact absurd rfl (he _) + | skip + all_goals (repeat' split at h) + all_goals (cases h) + all_goals first + | rfl + | (simp [logs_eq, List.filterMap_append, logOf]; done) + | (unfold called; split <;> simp [logs_eq, List.filterMap_append, logOf]) + +theorem Inst.noLog_effect {dst : Option Nat} {e : Effect} {args : List Operand} + (h : Inst.noLog (.effect dst e args) = true) : ∀ n, e ≠ .log n := by + rintro n rfl + simp [Inst.noLog] at h + +/-- Instructions without `log` leave the logs as they were. -/ +theorem execInsts_logs {o : Oracle} {call : Call} : + ∀ {is : List Inst} {env : Env} {s : State} {env' : Env} {s' : State}, + is.all Inst.noLog = true → execInsts o call is env s = some (env', s') → logs s' = logs s + | [], _, _, _, _, _, h => by + simp only [execInsts, Option.some.injEq, Prod.mk.injEq] at h + rw [h.2] + | i :: is, env, s, env', s', hno, h => by + simp only [List.all_cons, Bool.and_eq_true] at hno + obtain ⟨hi, hno⟩ := hno + cases i with + | effect dst e args => + simp only [execInsts] at h + split at h + · rename_i res s1 hres + exact (execInsts_logs hno h).trans (Effect.apply_logs (Inst.noLog_effect hi) hres) + · cases h + | call => simp [execInsts] at h + | alloc dst p => + cases p with + | static a => exact execInsts_logs hno h + | dynamic size => + simp only [execInsts] at h + have := execInsts_logs hno h + exact this + | pure dst op args => + simp only [execInsts] at h + split at h + · exact execInsts_logs hno h + · cases h + | assume neg op args => + simp only [execInsts] at h + split at h + · split at h <;> split at h + all_goals first | cases h | exact execInsts_logs hno h + · cases h + | ne => exact execInsts_logs hno h + | word => exact execInsts_logs hno h + | low => exact execInsts_logs hno h + | select => exact execInsts_logs hno h + | heapFloor => exact execInsts_logs hno h + +theorem splitCall_cons_of (i : Inst) (hi : ∀ d c a x p, i ≠ .call d c a x p) (is : List Inst) : + splitCall (i :: is) = (i :: (splitCall is).1, (splitCall is).2) := by + cases i <;> first | rfl | exact absurd rfl (hi _ _ _ _ _) + +theorem splitCall_noLog : ∀ {is : List Inst}, is.all Inst.noLog = true → + (splitCall is).1.all Inst.noLog = true ∧ + ∀ d c a x p rest, (splitCall is).2 = some (d, c, a, x, p, rest) → rest.all Inst.noLog = true + | [], _ => ⟨rfl, fun _ _ _ _ _ _ h => by cases h⟩ + | i :: is, hno => by + simp only [List.all_cons, Bool.and_eq_true] at hno + by_cases hc : ∃ d c a x p, i = .call d c a x p + · obtain ⟨d, c, a, x, p, rfl⟩ := hc + refine ⟨rfl, ?_⟩ + intro d' c' a' x' p' rest' hn + have hn' : some (d, c, a, x, p, is) = some (d', c', a', x', p', rest') := hn + simp only [Option.some.injEq, Prod.mk.injEq] at hn' + obtain ⟨-, -, -, -, -, rfl⟩ := hn' + exact hno.2 + · have hi : ∀ d c a x p, i ≠ .call d c a x p := fun d c a x p h => hc ⟨d, c, a, x, p, h⟩ + rw [splitCall_cons_of i hi] + obtain ⟨h1, h2⟩ := splitCall_noLog hno.2 + exact ⟨by simp only [List.all_cons, hno.1, h1, Bool.and_self], h2⟩ + +theorem splitCall_noLog_eq {is before : List Inst} + {next : Option (Option Nat × Nat × List Operand × List (Option Nat) × Option EvmRules.Word × List Inst)} + (hno : is.all Inst.noLog = true) (h : splitCall is = (before, next)) : + before.all Inst.noLog = true ∧ + ∀ d c a x p rest, next = some (d, c, a, x, p, rest) → rest.all Inst.noLog = true := by + have := splitCall_noLog hno + rw [h] at this + exact this + +theorem logs_start (f : Function) (s : State) : logs (f.start s) = logs s := by + unfold Function.start + split <;> rfl + +theorem logs_publish (s : State) (p : Option EvmRules.Word) (vs : List EvmRules.Word) : + logs (publishResults s p vs) = logs s := by + unfold publishResults + split <;> rfl + +/-- What still runs in a frame is free of `log`, and its state has no logs. -/ +def FrameOk (x : Frame) : Prop := + logs x.2.2.2 = [] ∧ (∀ r ∈ x.1, r.rest.all Inst.noLog = true) ∧ + match x.2.1 with + | .resume _ _ is _ => is.all Inst.noLog = true + | .enter .. => True + +/-- An outcome of a step: an end without logs, or a frame that keeps the invariant. -/ +def StepOk : (Halt × State) ⊕ Frame → Prop + | .inl r => logs r.2 = [] + | .inr x => FrameOk x + +theorem segment_ok {o : Oracle} {call : Call} {m : Module} {stack : List Return} {fn b : Nat} + {insts : List Inst} {term : Terminator} {env : Env} {s : State} {y : (Halt × State) ⊕ Frame} + (hl : logs s = []) (hst : ∀ r ∈ stack, r.rest.all Inst.noLog = true) + (hno : insts.all Inst.noLog = true) + (h : segment o call m stack fn b insts term env s = some y) : StepOk y := by + unfold segment at h + split at h + · rename_i before dst callee args extras publish rest hsplit + obtain ⟨hb, hr⟩ := splitCall_noLog_eq hno hsplit + split at h + · cases h + · rename_i env1 s1 hex + have hl1 : logs s1 = [] := (execInsts_logs hb hex).trans hl + split at h + · cases h + · split at h + · cases h + · obtain rfl := Option.some.inj h + refine ⟨(logs_start _ _).trans hl1, ?_, trivial⟩ + intro r hr' + simp only [List.mem_cons] at hr' + rcases hr' with rfl | hr' + · exact hr dst callee args extras publish rest rfl + · exact hst r hr' + · rename_i before hsplit + obtain ⟨hb, -⟩ := splitCall_noLog_eq hno hsplit + split at h + · cases h + · rename_i env1 s1 hex + have hl1 : logs s1 = [] := (execInsts_logs hb hex).trans hl + split at h + all_goals first + | (obtain rfl := Option.some.inj h; exact ⟨hl1, hst, trivial⟩) + | (obtain rfl := Option.some.inj h; exact hl1) + | skip + · -- tailCall + split at h + · cases h + · split at h + · cases h + · obtain rfl := Option.some.inj h + exact ⟨(logs_start _ _).trans hl1, hst, trivial⟩ + · -- leave + cases stack with + | nil => cases h + | cons ret stack' => + simp only at h + split at h + · cases h + · obtain rfl := Option.some.inj h + refine ⟨(logs_publish _ _ _).trans hl1, fun r hr => hst r (List.mem_cons_of_mem _ hr), ?_⟩ + exact hst ret List.mem_cons_self + +theorem block_noLog {m : Module} (hm : m.noLog = true) {fn b : Nat} {f : Function} {blk : Block} + (hf : m.functions[fn]? = some f) (hb : f.blocks[b]? = some blk) : blk.insts.all Inst.noLog = true := by + unfold Module.noLog at hm + rw [List.all_eq_true] at hm + have h1 := hm f (List.mem_of_getElem? hf) + rw [List.all_eq_true] at h1 + exact h1 blk (List.mem_of_getElem? hb) + +theorem step_ok {o : Oracle} {call : Call} {m : Module} (hm : m.noLog = true) {x : Frame} + {y : (Halt × State) ⊕ Frame} (hx : FrameOk x) (h : moduleBlock o call m x = some y) : StepOk y := by + obtain ⟨stack, pos, env, s⟩ := x + obtain ⟨hl, hst, hpos⟩ := hx + cases pos with + | enter fn p b => + simp only [moduleBlock] at h + split at h + · cases h + · rename_i f hf + split at h + · cases h + · rename_i blk hb + split at h + · cases h + · exact segment_ok hl hst (block_noLog hm hf hb) h + | resume fn b is term => + simp only [moduleBlock] at h + exact segment_ok hl hst hpos h + +theorem iterate_ok {o : Oracle} {call : Call} {m : Module} (hm : m.noLog = true) : + ∀ (n : Nat) (x : Frame) (r : Halt × State), FrameOk x → + iterate (moduleBlock o call m) n x = some r → logs r.2 = [] + | 0, _, _, _, h => by simp [iterate] at h + | n + 1, x, r, hx, h => by + unfold iterate at h + split at h + · rename_i res hs + obtain rfl := Option.some.inj h + exact step_ok hm hx hs + · rename_i next hs + exact iterate_ok hm n next r (step_ok hm hx hs) h + · cases h + +/-- **A module without `log` ends with no logs**, on every call under every oracle. -/ +theorem Module.run_logs {o : Oracle} {call : Call} {m : Module} (hm : m.noLog = true) {n : Nat} + {r : Halt × State} (h : Module.run o m call n = some r) : logs r.2 = [] := by + refine iterate_ok hm n ([], .enter m.entry 0 0, fun _ => 0, m.startState (State.initial call)) r ?_ h + unfold FrameOk + dsimp only + refine ⟨?_, fun _ h => by simp at h, trivial⟩ + show logs (m.startState (State.initial call)) = [] + unfold Module.startState + split + · exact (logs_start _ _).trans rfl + · rfl + +theorem Module.ends_logs {o : Oracle} {call : Call} {m : Module} (hm : m.noLog = true) + {r : Halt × State} (h : moduleLayer.Ends o m call r) : logs r.2 = [] := by + obtain ⟨n, hn⟩ := h + exact Module.run_logs hm hn + +/-- info: 'SolarTV.MIR.Lowered.Module.ends_logs' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Module.ends_logs + +end SolarTV.MIR.Lowered diff --git a/SolidCore/Refinement/Generic/MirRun.lean b/SolidCore/Refinement/Generic/MirRun.lean new file mode 100644 index 00000000..ecc20064 --- /dev/null +++ b/SolidCore/Refinement/Generic/MirRun.lean @@ -0,0 +1,1241 @@ +import SolidCore.Refinement.Generic.Mir + +/-! +# The symbolic run of lowered MIR is sound + +`symTree_sound`: on a call that gives the symbolic run what `CallFacts` says (no value, call +data of `4 + 32 * n` bytes whose words are the arguments and whose selector is `sel`, storage +`ρ.store`, which reads every slot as a word), SolarTV's lowered MIR semantics `moduleSem o` runs +the module, under every oracle `o`, to the result of the tree `symTree` computes; with the +environment flag set, the oracle must be one `EnvOk` describes: its caller is `callerWord` and its +hash of the 64 bytes of two words is `ρ.hash` of them. `symTreeValue_sound` is the same for a call +with a value other than 0 and the tree `symTreeValue` computes. Both are cases of one run whose +value is a symbolic value `cv` (`CallFactsAt`). + +The proof relates each machine word to its symbolic value (`SV.Rel`), the environment pointwise +(`EnvRel`), the returns of the internal calls in progress one by one (`StackRel`) and the +machine state to the symbolic state (`StRel`: memory bytes, storage through the writes, the logs +of its world), and shows each step keeps them: pure operations (`symPure_sound`, on the word +semantics of `EvmRules.Evm`), effects (`symEffect_sound`), instructions (`symInsts_sound`, where +an `assume` holds by the facts of the path, `WExpr.eval_simp`), terminators (`symTerm_sound`), the +rest of a block (`symSegment_sound`) and a step of the module (`symStep_sound`), then the whole +run by induction on the fuel (`symRun_sound`), where a branch on a symbolic word follows the side +the call's words take and that side's facts hold (`Facts.Hold.add`). +-/ + +namespace SolidCore.Refinement.Generic +open SolarTV SolarTV.Machine SolarTV.MIR.Lowered EvmRules + +/-! ## Relations -/ + +/-- A word holds a symbolic value; `SV.paid` holds every word but 0. -/ +def SV.Rel (ρ : Val) (call : Call) (v : Word) : SV → Prop + | .w e => v.toNat = e.eval ρ + | .cd0 => v = calldataWord call 0 + | .paid => v ≠ 0 + +/-- The 32 bytes of a word, big-endian. -/ +def wordBytes (v : Nat) : List (BitVec 8) := + (List.range 32).map fun i => BitVec.ofNat 8 (v / 256 ^ (31 - i)) + +/-- An oracle whose environment the symbolic run with the environment flag takes: its caller +is `callerWord`, and its hash of the 64 bytes of two words is `ρ.hash` of them. -/ +structure EnvOk (o : Oracle) (ρ : Val) : Prop where + caller : (o.caller.setWidth 256).toNat = callerWord + hash : ∀ a b, a < wordSize → b < wordSize → + (o.keccak (wordBytes a ++ wordBytes b)).toNat = ρ.hash a b % wordSize + +/-- What the flags `ev` ask of the oracle: its caller when they read the caller, its hash of two +words when they hash. -/ +structure EnvAsk (ev : EnvFlags) (o : Oracle) (ρ : Val) : Prop where + caller : ev.caller = true → (o.caller.setWidth 256).toNat = ev.callerExpr.eval ρ + hash : ev.hash = true → ∀ a b, a < wordSize → b < wordSize → + (o.keccak (wordBytes a ++ wordBytes b)).toNat = ρ.hash a b % wordSize + +/-- An oracle `EnvOk` describes gives every flag what it asks. -/ +theorem EnvOk.ask {o : Oracle} {ρ : Val} (h : EnvOk o ρ) (hρ : ρ.caller = callerWord) (ev : EnvFlags) : + EnvAsk ev o ρ := + ⟨fun _ => by unfold EnvFlags.callerExpr; split <;> simp [WExpr.eval, hρ, h.caller, callerWord] <;> rfl, fun _ => h.hash⟩ + +/-- The flags off ask nothing. -/ +theorem EnvAsk.off (o : Oracle) (ρ : Val) : EnvAsk .off o ρ := + ⟨fun h => by simp [EnvFlags.off] at h, fun h => by simp [EnvFlags.off] at h⟩ + +/-- What the call gives the symbolic run: no value, `4 + 32 * n` bytes of call data whose word at +`4 + 32 * i` is argument `i` and whose first four bytes are the selector `sel`, and the +storage `ρ.store`, which reads every slot as a word. -/ +structure CallFacts (sel n : Nat) (ρ : Val) (call : Call) : Prop where + value : call.callvalue = 0 + size : call.calldata.size = 4 + 32 * n + args : ∀ i, i < n → 4 + 32 * i < wordSize → + (calldataWord call (BitVec.ofNat 256 (4 + 32 * i))).toNat = (WExpr.arg i).eval ρ + selector : Evm.shr 224 (calldataWord call 0) = BitVec.ofNat 256 sel + store : ρ.store = slotValue call.storage + ok : ρ.Ok + +/-- What the call gives the symbolic run whose value is `cv`: its value word holds `cv`, and +the rest is `CallFacts`'s. -/ +structure CallFactsAt (cv : SV) (sel n : Nat) (ρ : Val) (call : Call) : Prop where + value : SV.Rel ρ call (BitVec.ofNat 256 call.callvalue) cv + size : call.calldata.size = 4 + 32 * n + args : ∀ i, i < n → 4 + 32 * i < wordSize → + (calldataWord call (BitVec.ofNat 256 (4 + 32 * i))).toNat = (WExpr.arg i).eval ρ + selector : Evm.shr 224 (calldataWord call 0) = BitVec.ofNat 256 sel + store : ρ.store = slotValue call.storage + ok : ρ.Ok + +/-- A call with no value gives the run whose value is the word 0 its facts. -/ +theorem CallFacts.at {sel n : Nat} {ρ : Val} {call : Call} (hc : CallFacts sel n ρ call) : + CallFactsAt (.w (.lit 0)) sel n ρ call where + value := by simp [SV.Rel, WExpr.eval, hc.value] + size := hc.size + args := hc.args + selector := hc.selector + store := hc.store + ok := hc.ok + +def EnvRel (ρ : Val) (call : Call) (env : Env) (senv : SEnv) : Prop := + ∀ j, SV.Rel ρ call (env j) (senv j) + +def ArgsRel (ρ : Val) (call : Call) : List Word → List SV → Prop + | [], [] => True + | a :: as, s :: ss => SV.Rel ρ call a s ∧ ArgsRel ρ call as ss + | _, _ => False + +def OptRel (ρ : Val) (call : Call) : Option Word → Option SV → Prop + | none, none => True + | some v, some s => SV.Rel ρ call v s + | _, _ => False + +/-- A machine state holds a symbolic state: its memory bytes, its storage (the writes over the +storage before the call) and the logs of its world. -/ +structure StRel (ρ : Val) (s : State) (st : SState) : Prop where + mem : ∀ i, (s.memory.bytes i).toNat = (st.mem i).eval ρ + store : ∀ k : Word, (s.storage k).toNat = Writes.store ρ st.writes k.toNat + world : logs s = st.logs.map (Log.eval ρ) + +/-- The returns of the calls in progress hold the symbolic ones: the same places, the caller's +values related. -/ +def StackRel (ρ : Val) (call : Call) : List Return → List SReturn → Prop + | [], [] => True + | r :: rs, q :: qs => + r.fn = q.fn ∧ r.block = q.block ∧ r.dst = q.dst ∧ r.rest = q.rest ∧ r.term = q.term ∧ + r.extras = [] ∧ r.publish = none ∧ EnvRel ρ call r.env q.env ∧ StackRel ρ call rs qs + | _, _ => False + +theorem eq_ofNat_of_rel {ρ : Val} {call : Call} {v : Word} {n : Nat} + (h : SV.Rel ρ call v (.w (.lit n))) : v = BitVec.ofNat 256 n := by + apply BitVec.eq_of_toNat_eq + simp only [SV.Rel, WExpr.eval] at h + simp [h] + +theorem toNat_of_rel {ρ : Val} {call : Call} {v : Word} {n : Nat} + (h : SV.Rel ρ call v (.w (.lit n))) : v.toNat = n % wordSize := h + +theorem EnvRel.set {ρ : Val} {call : Call} {env : Env} {senv : SEnv} (h : EnvRel ρ call env senv) + {v : Word} {s : SV} (hv : SV.Rel ρ call v s) (d : Nat) : + EnvRel ρ call (env.set d v) (senv.set d s) := by + intro j + simp only [Env.set, SEnv.set] + split + · exact hv + · exact h j + +theorem rel_operand {ρ : Val} {call : Call} {env : Env} {senv : SEnv} (h : EnvRel ρ call env senv) + (op : Operand) : SV.Rel ρ call (op.eval env) (SV.ofOperand senv op) := by + cases op with + | value id => exact h id + | const word => + simp only [Operand.eval, SV.ofOperand, SV.Rel, WExpr.eval] + exact (Nat.mod_eq_of_lt word.isLt).symm + +theorem rel_args {ρ : Val} {call : Call} {env : Env} {senv : SEnv} (h : EnvRel ρ call env senv) : + ∀ ops : List Operand, ArgsRel ρ call (ops.map (Operand.eval env)) (ops.map (SV.ofOperand senv)) + | [] => trivial + | op :: ops => ⟨rel_operand h op, rel_args h ops⟩ + +/-! ## Word operations -/ + +theorem shl_toNat_eval (a b : Word) : + (Evm.shl a b).toNat = BinOp.shl.eval a.toNat b.toNat % wordSize := by + simp only [Evm.shl, BinOp.eval, BitVec.ult] + have h' : (256 : BitVec 256).toNat = 256 := rfl + by_cases h : a.toNat < 256 + · simp [h, BitVec.toNat_shiftLeft, Nat.shiftLeft_eq] + · simp [h] + +theorem shr_toNat_eval (a b : Word) : + (Evm.shr a b).toNat = BinOp.shr.eval a.toNat b.toNat % wordSize := by + simp only [Evm.shr, BinOp.eval, BitVec.ult] + have h' : (256 : BitVec 256).toNat = 256 := rfl + by_cases h : a.toNat < 256 + · simp only [h', h, decide_true, Bool.cond_true, ↓reduceIte, BitVec.ushiftRight_eq', + BitVec.toNat_ushiftRight, Nat.shiftRight_eq_div_pow] + exact (Nat.mod_eq_of_lt (Nat.lt_of_le_of_lt (Nat.div_le_self _ _) b.isLt)).symm + · simp [h] + +theorem byte_toNat_eval (a b : Word) : + (Evm.byte a b).toNat = BinOp.byte.eval a.toNat b.toNat % wordSize := by + simp only [Evm.byte, BinOp.eval, BitVec.ult] + have h' : (32 : BitVec 256).toNat = 32 := rfl + by_cases h : a.toNat < 32 + · simp only [h', h, decide_true, Bool.cond_true, ↓reduceIte] + have hmul : (((31 : BitVec 256) - a) * 8).toNat = (31 - a.toNat) * 8 := by + simp only [BitVec.toNat_mul, BitVec.toNat_sub] + have h31 : (31 : BitVec 256).toNat = 31 := rfl + have h8 : (8 : BitVec 256).toNat = 8 := rfl + simp only [h31, h8] + omega + have h255 : (255 : BitVec 256).toNat = 2 ^ 8 - 1 := rfl + rw [BitVec.toNat_and, BitVec.ushiftRight_eq', BitVec.toNat_ushiftRight, hmul, + Nat.shiftRight_eq_div_pow, h255, Nat.and_two_pow_sub_one_eq_mod] + have hpow : (2 : Nat) ^ ((31 - a.toNat) * 8) = 256 ^ (31 - a.toNat) := by + rw [Nat.mul_comm, Nat.pow_mul] + rw [hpow] + exact (Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (by decide))).symm + · simp [h] + +theorem evalPure_bin {op : EVM.Op} {o : BinOp} (h : binOfOp op = some o) (a b : Word) : + ∃ w, evalPure op [a, b] = some w ∧ w.toNat = o.eval a.toNat b.toNat % wordSize := by + have ha := a.isLt + have hb := b.isLt + cases op <;> simp only [binOfOp, reduceCtorEq, Option.some.injEq] at h <;> subst h <;> + refine ⟨_, rfl, ?_⟩ + · simp [Evm.eq, BinOp.eval, BitVec.toNat_eq]; split <;> simp + · simp [Evm.sub, BinOp.eval, BitVec.toNat_sub, Nat.add_comm] + · simp [Evm.add, BinOp.eval, BitVec.toNat_add] + · simp [Evm.mul, BinOp.eval, BitVec.toNat_mul] + · simp only [Evm.and, BinOp.eval, BitVec.toNat_and] + exact (Nat.mod_eq_of_lt (Nat.lt_of_le_of_lt Nat.and_le_left ha)).symm + · simp only [Evm.or, BinOp.eval, BitVec.toNat_or] + exact (Nat.mod_eq_of_lt (Nat.or_lt_two_pow ha hb)).symm + · simp only [Evm.xor, BinOp.eval, BitVec.toNat_xor] + exact (Nat.mod_eq_of_lt (Nat.xor_lt_two_pow ha hb)).symm + · simp only [Evm.div, BinOp.eval, BitVec.toNat_udiv] + split + · rename_i h0; simp [h0] + · exact (Nat.mod_eq_of_lt (Nat.lt_of_le_of_lt (Nat.div_le_self _ _) ha)).symm + · simp only [Evm.lt, BinOp.eval, BitVec.ult] + by_cases h : a.toNat < b.toNat <;> simp [h] + · simp only [Evm.gt, BinOp.eval, BitVec.ult] + by_cases h : b.toNat < a.toNat <;> simp [h] + · exact byte_toNat_eval a b + · exact shl_toNat_eval a b + · exact shr_toNat_eval a b + +theorem evalPure_iszero (a : Word) : + evalPure .iszero [a] = some (Evm.iszero a) ∧ + (Evm.iszero a).toNat = UnOp.iszero.eval a.toNat % wordSize := by + refine ⟨rfl, ?_⟩ + simp only [Evm.iszero, UnOp.eval] + by_cases h : a = 0 + · subst h; simp + · have : a.toNat ≠ 0 := fun h' => h (BitVec.eq_of_toNat_eq (by simpa using h')) + have h' : ¬ a = 0#256 := h + simp [h', this] + +theorem evalPure_not (a : Word) : + evalPure .not [a] = some (Evm.not a) ∧ + (Evm.not a).toNat = UnOp.not.eval a.toNat % wordSize := by + refine ⟨rfl, ?_⟩ + have ha := a.isLt + simp only [Evm.not, UnOp.eval, BitVec.toNat_not] + exact (Nat.mod_eq_of_lt (by simp only [wordSize]; omega)).symm + +theorem ne_toNat (a b : Word) : + (Evm.ne a b).toNat = UnOp.iszero.eval (BinOp.eq.eval a.toNat b.toNat % wordSize) % wordSize := by + simp only [Evm.ne, UnOp.eval, BinOp.eval] + by_cases h : a = b + · subst h; simp + · have : a.toNat ≠ b.toNat := fun h' => h (BitVec.eq_of_toNat_eq h') + simp [h, this] + +theorem symPure_sound {cv : SV} {sel n : Nat} {ρ : Val} {call : Call} + (hc : CallFactsAt cv sel n ρ call) + {op : EVM.Op} {args : List Word} {sargs : List SV} {sv : SV} + (h : symPure sel op sargs = some sv) (hr : ArgsRel ρ call args sargs) : + ∃ v, evalPure op args = some v ∧ SV.Rel ρ call v sv := by + unfold symPure at h + split at h + · simp only [Option.some.injEq] at h + subst h + match args, hr with + | [a, c], ⟨ha, hc0, _⟩ => + rw [eq_ofNat_of_rel ha] + simp only [SV.Rel] at hc0 + subst hc0 + refine ⟨Evm.shr 224 (calldataWord call 0), rfl, ?_⟩ + simp only [SV.Rel, hc.selector, WExpr.eval, BitVec.toNat_ofNat] + · simp only [Option.some.injEq] at h + subst h + match args, hr with + | [x], ⟨hx, _⟩ => + obtain ⟨h1, h2⟩ := evalPure_iszero x + refine ⟨_, h1, ?_⟩ + simp only [SV.Rel] at hx ⊢ + rw [eval_mkUn, h2] + simp only [WExpr.eval, hx] + · simp only [Option.some.injEq] at h + subst h + match args, hr with + | [x], ⟨hx, _⟩ => + obtain ⟨h1, h2⟩ := evalPure_not x + refine ⟨_, h1, ?_⟩ + simp only [SV.Rel] at hx ⊢ + rw [eval_mkUn, h2] + simp only [WExpr.eval, hx] + · obtain ⟨o, ho, rfl⟩ := Option.map_eq_some_iff.mp h + match args, hr with + | [x, y], ⟨hx, hy, _⟩ => + obtain ⟨w, hw, hwv⟩ := evalPure_bin ho x y + refine ⟨w, hw, ?_⟩ + simp only [SV.Rel] at hx hy ⊢ + rw [eval_mkBin, hwv] + simp only [WExpr.eval, hx, hy] + · -- iszero of a value other than 0 + simp only [Option.some.injEq] at h + subst h + match args, hr with + | [x], ⟨hx, _⟩ => + obtain ⟨h1, h2⟩ := evalPure_iszero x + refine ⟨_, h1, ?_⟩ + have hx' : x.toNat ≠ 0 := fun h0 => hx (BitVec.eq_of_toNat_eq (by simpa using h0)) + simp only [SV.Rel, WExpr.eval] + rw [h2] + simp [UnOp.eval, hx'] + · -- eq of a value other than 0 and 0 + split at h + · rename_i hz + simp only [Option.some.injEq] at h + subst h + match args, hr with + | [x, y], ⟨hx, hy, _⟩ => + obtain ⟨w, hw, hwv⟩ := evalPure_bin (op := .eq) (o := .eq) rfl x y + refine ⟨w, hw, ?_⟩ + have hx' : x.toNat ≠ 0 := fun h0 => hx (BitVec.eq_of_toNat_eq (by simpa using h0)) + simp only [SV.Rel, WExpr.eval, hz] at hy ⊢ + rw [hwv] + simp [BinOp.eval, hy, hx'] + · simp at h + · -- eq of 0 and a value other than 0 + split at h + · rename_i hz + simp only [Option.some.injEq] at h + subst h + match args, hr with + | [x, y], ⟨hx, hy, _⟩ => + obtain ⟨w, hw, hwv⟩ := evalPure_bin (op := .eq) (o := .eq) rfl x y + refine ⟨w, hw, ?_⟩ + have hy' : y.toNat ≠ 0 := fun h0 => hy (BitVec.eq_of_toNat_eq (by simpa using h0)) + simp only [SV.Rel, WExpr.eval, hz] at hx ⊢ + rw [hwv] + simp [BinOp.eval, hx, Ne.symm hy'] + · simp at h + · simp at h + + +/-! ## Effects -/ + +theorem byte_toNat (v : Word) (j : Nat) : + (Memory.byte v j).toNat = v.toNat / 256 ^ (31 - j) % 256 := by + simp only [Memory.byte, BitVec.toNat_setWidth, BitVec.toNat_ushiftRight, Nat.shiftRight_eq_div_pow] + rw [show (256 : Nat) ^ (31 - j) = 2 ^ (8 * (31 - j)) by rw [Nat.pow_mul]] + + +theorem calldataArg_sound {cv : SV} {sel n : Nat} {ρ : Val} {call : Call} + (hc : CallFactsAt cv sel n ρ call) + {ow : Word} {off : Nat} (how : ow.toNat = off % wordSize) {v : SV} + (h : calldataArg n (off % wordSize) = some v) : SV.Rel ρ call (calldataWord call ow) v := by + unfold calldataArg at h + split at h + · rename_i h0 + simp only [Option.some.injEq] at h + subst h + have : ow = 0 := BitVec.eq_of_toNat_eq (by rw [how, h0]; rfl) + subst this + rfl + · split at h + · rename_i h0 hi + simp only [Option.some.injEq] at h + subst h + obtain ⟨h4, hm, hlt⟩ := hi + have hoff : off % wordSize = 4 + 32 * ((off % wordSize - 4) / 32) := by omega + have : ow = BitVec.ofNat 256 (4 + 32 * ((off % wordSize - 4) / 32)) := by + apply BitVec.eq_of_toNat_eq + rw [how, BitVec.toNat_ofNat, ← hoff, Nat.mod_mod] + rw [this] + exact hc.args _ hlt (by rw [← hoff]; exact Nat.mod_lt _ (by decide)) + · simp at h + + +theorem bytes_expand (m : Mem) (o sz : Nat) : (m.expand o sz).bytes = m.bytes := by + unfold Mem.expand; split <;> rfl + +theorem callerWord_lt : callerWord < wordSize := by decide + +/-- Memory bytes that hold the symbolic bytes of one word are its bytes. -/ +theorem memWord_bytes {ρ : Val} {bytes : Nat → BitVec 8} {mem : Nat → OByte} + (hm : ∀ i, (bytes i).toNat = (mem i).eval ρ) {off : Nat} {e : WExpr} + (h : memWord mem off = some e) : + ∀ i, i < 32 → bytes (off + i) = BitVec.ofNat 8 (e.eval ρ / 256 ^ (31 - i)) := by + intro i hi + unfold memWord at h + split at h + · rename_i e' j _ + split at h + · rename_i hall + simp only [Option.some.injEq] at h + subst h + have hi' := List.all_eq_true.mp hall i (List.mem_range.mpr hi) + simp only [beq_iff_eq] at hi' + apply BitVec.eq_of_toNat_eq + rw [hm, hi', BitVec.toNat_ofNat] + rfl + · simp at h + · simp at h + +/-- 64 bytes that hold two words are the bytes the oracle hashes for them. -/ +theorem read_two_words {bytes : Nat → BitVec 8} {off a b : Nat} + (ha : ∀ i, i < 32 → bytes (off + i) = BitVec.ofNat 8 (a / 256 ^ (31 - i))) + (hb : ∀ i, i < 32 → bytes (off + 32 + i) = BitVec.ofNat 8 (b / 256 ^ (31 - i))) : + (List.range 64).map (fun i => bytes (off + i)) = wordBytes a ++ wordBytes b := by + rw [show 64 = 32 + 32 from rfl, List.range_add, List.map_append, List.map_map] + unfold wordBytes + congr 1 + · exact List.map_congr_left fun i hi => ha i (List.mem_range.mp hi) + · apply List.map_congr_left + intro i hi + simp only [Function.comp, ← Nat.add_assoc] + exact hb i (List.mem_range.mp hi) + +/-- The words of symbolic values that are all words are the machine words' values. -/ +theorem svWords_sound {ρ : Val} {call : Call} : ∀ {args : List Word} {sargs : List SV} + {ts : List WExpr}, svWords sargs = some ts → ArgsRel ρ call args sargs → + args.length = sargs.length ∧ args.map BitVec.toNat = ts.map (WExpr.eval ρ) + | [], [], ts, h, _ => by + simp only [svWords, Option.some.injEq] at h + subst h + simp + | a :: as, .w e :: ss, ts, h, hr => by + simp only [svWords, Option.map_eq_some_iff] at h + obtain ⟨ts', h', rfl⟩ := h + obtain ⟨h1, h2⟩ := svWords_sound h' hr.2 + refine ⟨by simp [h1], ?_⟩ + simp only [List.map_cons, h2, List.cons.injEq, and_true] + exact hr.1 + | _ :: _, .cd0 :: _, _, h, _ => by simp [svWords] at h + | _ :: _, .paid :: _, _, h, _ => by simp [svWords] at h + | [], _ :: _, _, _, hr => by simp [ArgsRel] at hr + | _ :: _, [], _, _, hr => by simp [ArgsRel] at hr + +theorem logs_append_log (s : State) (mem : Mem) (topics : List Word) (data : List Memory.Byte) : + logs ⟨mem, s.storage, s.transient, s.world ++ [.log topics data]⟩ = + logs s ++ [(topics.map BitVec.toNat, data.map BitVec.toNat)] := by + simp [logs, List.filterMap_append] + +theorem read_eq {ρ : Val} {s : State} {st : SState} (hs : StRel ρ s st) (m : Mem) + (hm : m.bytes = s.memory.bytes) (o sz : Nat) : + (m.read o sz).map BitVec.toNat = (outBytes st.mem o sz).map (OByte.eval ρ) := by + simp only [Mem.read, outBytes, List.map_map, hm] + apply List.map_congr_left + intro i _ + exact hs.mem (o + i) + +/-- A state whose memory only grew holds the same symbolic state. -/ +theorem StRel.expand {ρ : Val} {s : State} {st : SState} (hs : StRel ρ s st) (o sz : Nat) : + StRel ρ { s with memory := s.memory.expand o sz } st where + mem i := by simp only [bytes_expand]; exact hs.mem i + store := hs.store + world := hs.world + +/-- A byte of a word below \`2 ^ 256\`, as \`wordBytes\` writes it, is the machine's byte of it. -/ +theorem ofNat_byte (v i : Nat) (hv : v < wordSize) : + BitVec.ofNat 8 (v / 256 ^ (31 - i)) = Memory.byte (BitVec.ofNat 256 v) i := by + apply BitVec.eq_of_toNat_eq + simp only [Memory.byte, BitVec.toNat_setWidth, BitVec.toNat_ushiftRight, BitVec.toNat_ofNat, + Nat.mod_eq_of_lt hv, Nat.shiftRight_eq_div_pow] + rw [show (256 : Nat) = 2 ^ 8 from rfl, ← Nat.pow_mul] + +/-- A load of 32 bytes that are a word's, in order, reads the word. -/ +theorem load_of_bytes (m : Mem) (off : Nat) (w : Word) + (h : ∀ i, i < 32 → m.bytes (off + i) = Memory.byte w i) : m.load off = w := by + have e : m.load off = (m.store off w).load off := by + unfold Mem.load Mem.read + congr 1 + apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [h i hi] + simp only [Mem.store, bytes_expand] + have c : off ≤ off + i ∧ off + i < off + 32 := by omega + simp [c] + rw [e, Mem.load_store_same] + +/-- Entering a function stores its entry heap on both sides. -/ +theorem StRel.start {ρ : Val} {s : State} {st : SState} (hs : StRel ρ s st) (g : Function) : + StRel ρ (g.start s) (symStart g st) := by + unfold Function.start symStart + cases hg : g.entryHeap with + | none => exact hs + | some heap => + exact { store := hs.store, world := hs.world + mem := fun i => by + simp only [Mem.store, bytes_expand, storeBytes] + by_cases hi : 64 ≤ i ∧ i < 64 + 32 + · simp only [hi, and_self, ite_true, OByte.eval, byte_toNat, WExpr.eval, + Nat.mod_eq_of_lt heap.isLt] + · simp only [hi, ite_false] + exact hs.mem i } + +theorem symEffect_sound {ev : EnvFlags} {cv : SV} {sel n : Nat} {ρ : Val} {call : Call} + (hc : CallFactsAt cv sel n ρ call) {o : Oracle} (henv : EnvAsk ev o ρ) + {eff : Effect} {args : List Word} {sargs : List SV} {s : State} {st st' : SState} + {res : Option SV} (h : symEffect ev cv n eff sargs st = some (res, st')) + (hr : ArgsRel ρ call args sargs) (hs : StRel ρ s st) : + ∃ res' s', eff.apply o call args s = some (res', s') ∧ OptRel ρ call res' res ∧ StRel ρ s' st' := by + unfold symEffect at h + split at h + · -- calldatasize + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + match args, hr with + | [], _ => + refine ⟨_, _, rfl, ?_, hs⟩ + simp [OptRel, SV.Rel, WExpr.eval, hc.size] + · -- callvalue + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + match args, hr with + | [], _ => + refine ⟨_, _, rfl, ?_, hs⟩ + exact hc.value + · -- calldataload + rename_i off + obtain ⟨v, hv, h⟩ := Option.map_eq_some_iff.mp h + simp only [Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + match args, hr with + | [ow], ⟨how, _⟩ => + exact ⟨_, _, rfl, calldataArg_sound hc (toNat_of_rel how) hv, hs⟩ + · -- sload + rename_i k + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + match args, hr with + | [kw], ⟨hk, _⟩ => + refine ⟨_, _, rfl, ?_, hs⟩ + simp only [OptRel, SV.Rel] at hk ⊢ + rw [hs.store kw, hk, Writes.eval_read hc.ok] + · -- sstore + rename_i k e + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + match args, hr with + | [kw, vw], ⟨hk, hv, _⟩ => + refine ⟨_, _, rfl, trivial, ?_⟩ + simp only [SV.Rel] at hk hv + exact { mem := hs.mem, world := hs.world + store := fun q => by + simp only [update, Writes.store_set, Nat.mod_eq_of_lt q.isLt, ← hk] + by_cases hq : q = kw + · subst hq; simp [hv] + · have : ¬ kw.toNat = q.toNat := fun h' => hq (BitVec.eq_of_toNat_eq h'.symm) + simp only [hq, this, ite_false]; exact hs.store q } + · -- mstore + rename_i off e + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + match args, hr with + | [ow, vw], ⟨ho, hv, _⟩ => + refine ⟨_, _, rfl, trivial, ?_⟩ + have hon := toNat_of_rel ho + exact { store := hs.store, world := hs.world + mem := fun i => by + simp only [Mem.store, bytes_expand, storeBytes, hon] + by_cases hi : off % wordSize ≤ i ∧ i < off % wordSize + 32 + · simp only [hi, and_self, ite_true, OByte.eval, byte_toNat] + simp only [SV.Rel] at hv + rw [hv] + · simp only [hi, ite_false] + exact hs.mem i } + · -- mload + rename_i off + split at h + · rename_i e he + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + match args, hr with + | [ow], ⟨ho, _⟩ => + refine ⟨_, _, rfl, ?_, hs.expand _ _⟩ + have hon := toNat_of_rel ho + have hl : s.memory.load ow.toNat = BitVec.ofNat 256 (e.eval ρ) := by + rw [hon] + exact load_of_bytes s.memory _ _ fun i hi => by + rw [memWord_bytes hs.mem he i hi, ofNat_byte _ _ (e.eval_lt ρ)] + simp only [OptRel, SV.Rel, hl, BitVec.toNat_ofNat, Nat.mod_eq_of_lt (e.eval_lt ρ)] + · simp at h + · -- caller + split at h + · rename_i hev + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + match args, hr with + | [], _ => + refine ⟨_, _, rfl, ?_, hs⟩ + simp only [OptRel, SV.Rel] + exact henv.caller hev + · simp at h + · -- keccak256 + rename_i off size + split at h + · rename_i hcond + obtain ⟨hev, h64⟩ := hcond + split at h + · rename_i a b ha hb + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + match args, hr with + | [ow, sw], ⟨ho, hsz, _⟩ => + refine ⟨_, _, rfl, ?_, hs.expand _ _⟩ + have hread : (s.memory.expand ow.toNat sw.toNat).read ow.toNat sw.toNat = + wordBytes (a.eval ρ) ++ wordBytes (b.eval ρ) := by + unfold Mem.read + rw [bytes_expand, toNat_of_rel hsz, h64, toNat_of_rel ho] + exact read_two_words (memWord_bytes hs.mem ha) (memWord_bytes hs.mem hb) + simp only [OptRel, SV.Rel, WExpr.eval] + rw [hread, henv.hash hev _ _ (a.eval_lt ρ) (b.eval_lt ρ)] + · simp at h + · simp at h + · -- log + rename_i k off size topics + split at h + · rename_i hlen + split at h + · rename_i ts hts + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + match args, hr with + | ow :: sw :: mts, ⟨ho, hsz, hts'⟩ => + obtain ⟨hl, hmap⟩ := svWords_sound hts hts' + have happ : Effect.apply o call (.log k) (ow :: sw :: mts) s = + some (none, ⟨s.memory.expand ow.toNat sw.toNat, s.storage, s.transient, + s.world ++ [.log mts ((s.memory.expand ow.toNat sw.toNat).read ow.toNat sw.toNat)]⟩) := by + simp only [Effect.apply, hl, hlen, ite_true] + refine ⟨_, _, happ, trivial, ?_⟩ + exact { mem := fun i => by simp only [bytes_expand]; exact hs.mem i + store := hs.store + world := by + rw [logs_append_log, hs.world, List.map_append, List.map_cons, List.map_nil, + read_eq hs _ (bytes_expand _ _ _), toNat_of_rel ho, toNat_of_rel hsz, hmap] + rfl } + · simp at h + · simp at h + · simp at h + + + +/-! ## Blocks -/ + +theorem symInsts_sound {ev : EnvFlags} {cv : SV} {sel n : Nat} {ρ : Val} {call : Call} + (hc : CallFactsAt cv sel n ρ call) {o : Oracle} (henv : EnvAsk ev o ρ) {K : Facts} + (hK : K.Hold ρ) : ∀ (insts : List Inst) (senv senv' : SEnv) (st st' : SState), + symInsts ev cv sel n K insts senv st = some (senv', st') → ∀ env s, EnvRel ρ call env senv → + StRel ρ s st → ∃ env' s', execInsts o call insts env s = some (env', s') ∧ + EnvRel ρ call env' senv' ∧ StRel ρ s' st' + | [], senv, senv', st, st', h, env, s, he, hs => by + simp only [symInsts, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + exact ⟨env, s, rfl, he, hs⟩ + | .pure dst op args :: rest, senv, senv', st, st', h, env, s, he, hs => by + simp only [symInsts] at h + split at h + · rename_i v hv + obtain ⟨w, hw, hwv⟩ := symPure_sound hc hv (rel_args he args) + obtain ⟨env', s', h1, h2, h3⟩ := + symInsts_sound hc henv hK rest _ _ _ _ h _ s (he.set hwv dst) hs + exact ⟨env', s', by simp only [execInsts, hw]; exact h1, h2, h3⟩ + · simp at h + | .effect dst eff args :: rest, senv, senv', st, st', h, env, s, he, hs => by + simp only [symInsts] at h + split at h + · rename_i res st1 hv + obtain ⟨res', s1, h1, hr1, hs1⟩ := symEffect_sound hc henv hv (rel_args he args) hs + have key : ∀ (env1 : Env) (senv1 : SEnv), EnvRel ρ call env1 senv1 → + symInsts ev cv sel n K rest senv1 st1 = some (senv', st') → ∃ env' s', + execInsts o call rest env1 s1 = some (env', s') ∧ EnvRel ρ call env' senv' ∧ + StRel ρ s' st' := + fun env1 senv1 he1 h' => symInsts_sound hc henv hK rest _ _ _ _ h' _ s1 he1 hs1 + simp only [execInsts, h1] + cases dst <;> cases res' <;> cases res <;> simp only [OptRel] at hr1 <;> dsimp only at h ⊢ + all_goals first + | exact key _ _ he h + | exact key _ _ (he.set hr1 _) h + · simp at h + | .ne dst a b :: rest, senv, senv', st, st', h, env, s, he, hs => by + simp only [symInsts] at h + split at h + · rename_i x y hx hy + have ha := rel_operand he a + have hb := rel_operand he b + rw [hx] at ha + rw [hy] at hb + have hv : SV.Rel ρ call (Evm.ne (a.eval env) (b.eval env)) (.w (mkUn .iszero (mkBin .eq x y))) := by + simp only [SV.Rel] at ha hb ⊢ + rw [eval_mkUn, ne_toNat] + simp only [WExpr.eval, eval_mkBin, ha, hb] + obtain ⟨env', s', h1, h2, h3⟩ := + symInsts_sound hc henv hK rest _ _ _ _ h _ s (he.set hv dst) hs + exact ⟨env', s', by simp only [execInsts]; exact h1, h2, h3⟩ + · -- a value other than 0 against 0 + rename_i z hx hy + split at h + · rename_i hz + have ha := rel_operand he a + have hb := rel_operand he b + rw [hx] at ha + rw [hy] at hb + have ha' : (a.eval env).toNat ≠ 0 := fun h0 => + ha (BitVec.eq_of_toNat_eq (by simpa using h0)) + simp only [SV.Rel, WExpr.eval, hz] at hb + have hv : SV.Rel ρ call (Evm.ne (a.eval env) (b.eval env)) (.w (.lit 1)) := by + simp only [SV.Rel, WExpr.eval] + rw [ne_toNat, hb] + simp [BinOp.eval, UnOp.eval, ha'] + obtain ⟨env', s', h1, h2, h3⟩ := + symInsts_sound hc henv hK rest _ _ _ _ h _ s (he.set hv dst) hs + exact ⟨env', s', by simp only [execInsts]; exact h1, h2, h3⟩ + · simp at h + · -- 0 against a value other than 0 + rename_i z hx hy + split at h + · rename_i hz + have ha := rel_operand he a + have hb := rel_operand he b + rw [hx] at ha + rw [hy] at hb + have hb' : (b.eval env).toNat ≠ 0 := fun h0 => + hb (BitVec.eq_of_toNat_eq (by simpa using h0)) + simp only [SV.Rel, WExpr.eval, hz] at ha + have hv : SV.Rel ρ call (Evm.ne (a.eval env) (b.eval env)) (.w (.lit 1)) := by + simp only [SV.Rel, WExpr.eval] + rw [ne_toNat, ha] + simp [BinOp.eval, UnOp.eval, Ne.symm hb'] + obtain ⟨env', s', h1, h2, h3⟩ := + symInsts_sound hc henv hK rest _ _ _ _ h _ s (he.set hv dst) hs + exact ⟨env', s', by simp only [execInsts]; exact h1, h2, h3⟩ + · simp at h + · simp at h + | .assume negated op args :: rest, senv, senv', st, st', h, env, s, he, hs => by + simp only [symInsts] at h + split at h + · rename_i e hv + split at h + · rename_i v hl + obtain ⟨w, hw, hwv⟩ := symPure_sound hc hv (rel_args he args) + have hwn : w.toNat = v % wordSize := by + have hse := WExpr.eval_simp hK e + rw [WExpr.decided_sound hK hl] at hse + simp only [SV.Rel] at hwv + rw [hwv, ← hse] + have hz : (w = 0) ↔ (v % wordSize = 0) := by + constructor + · intro h0; rw [← hwn, h0]; rfl + · intro h0; exact BitVec.eq_of_toNat_eq (by rw [hwn, h0]; rfl) + simp only [execInsts, hw] + by_cases h0 : v % wordSize = 0 + · have hw0 := hz.mpr h0 + simp only [h0, ite_true] at h + simp only [hw0, ite_true] + cases negated <;> simp only [Bool.false_eq_true, ite_false, ite_true, reduceCtorEq] at h ⊢ + exact symInsts_sound hc henv hK rest _ _ _ _ h env s he hs + · have hw0 : ¬ w = 0 := fun h' => h0 (hz.mp h') + simp only [h0, ite_false] at h + simp only [hw0, ite_false] + cases negated <;> simp only [Bool.false_eq_true, ite_false, ite_true, reduceCtorEq] at h ⊢ + exact symInsts_sound hc henv hK rest _ _ _ _ h env s he hs + · simp at h + · simp at h + | .word dst a :: rest, senv, senv', st, st', h, env, s, he, hs => by + simp only [symInsts] at h + split at h + · rename_i e hx + have ha := rel_operand he a + rw [hx] at ha + obtain ⟨env', s', h1, h2, h3⟩ := + symInsts_sound hc henv hK rest _ _ _ _ h _ s (he.set ha dst) hs + exact ⟨env', s', by simp only [execInsts]; exact h1, h2, h3⟩ + · simp at h + | .heapFloor dst floor :: rest, senv, senv', st, st', h, env, s, he, hs => by + simp only [symInsts] at h + have hv : SV.Rel ρ call floor (.w (.lit floor.toNat)) := by + simp only [SV.Rel, WExpr.eval, Nat.mod_eq_of_lt floor.isLt] + obtain ⟨env', s', h1, h2, h3⟩ := + symInsts_sound hc henv hK rest _ _ _ _ h _ s (he.set hv dst) hs + exact ⟨env', s', by simp only [execInsts]; exact h1, h2, h3⟩ + | .low .. :: _, _, _, _, _, h, _, _, _, _ => by simp [symInsts] at h + | .select .. :: _, _, _, _, _, h, _, _, _, _ => by simp [symInsts] at h + | .call .. :: _, _, _, _, _, h, _, _, _, _ => by simp [symInsts] at h + | .alloc .. :: _, _, _, _, _, h, _, _, _, _ => by simp [symInsts] at h + +theorem symPhis_sound {ρ : Val} {call : Call} {envI : Env} {senvI : SEnv} + (hI : EnvRel ρ call envI senvI) (pred : Nat) : + ∀ (phis : List (Nat × List (Nat × Operand))) (senv senv' : SEnv) (env : Env), + symPhis senvI pred phis senv = some senv' → EnvRel ρ call env senv → + ∃ env', bindPhis envI pred phis env = some env' ∧ EnvRel ρ call env' senv' + | [], senv, senv', env, h, he => by + simp only [symPhis, Option.some.injEq] at h + subst h + exact ⟨env, rfl, he⟩ + | (dst, arms) :: rest, senv, senv', env, h, he => by + simp only [symPhis] at h + split at h + · rename_i x op hf + obtain ⟨env', h1, h2⟩ := symPhis_sound hI pred rest _ _ _ h (he.set (rel_operand hI op) dst) + exact ⟨env', by simp only [bindPhis, hf]; exact h1, h2⟩ + · simp at h + +theorem symSwitch_sound {ρ : Val} {call : Call} {env : Env} {senv : SEnv} + (he : EnvRel ρ call env senv) {key : Word} {kv : Nat} (hk : key.toNat = kv % wordSize) + (d : Nat) : ∀ (cs : List (Operand × Nat)) (t : Nat), symSwitch senv kv d cs = some t → + switchTarget env key d cs = t + | [], t, h => by simp only [symSwitch, Option.some.injEq] at h; subst h; rfl + | (c, t') :: rest, t, h => by + simp only [symSwitch] at h + split at h + · rename_i v hv + have hc := rel_operand he c + rw [hv] at hc + have hcn := toNat_of_rel hc + simp only [switchTarget] + by_cases heq : v % wordSize = kv % wordSize + · simp only [heq, ite_true, Option.some.injEq] at h + subst h + have : c.eval env = key := BitVec.eq_of_toNat_eq (by rw [hcn, hk, heq]) + simp [this] + · simp only [heq, ite_false] at h + have : ¬ c.eval env = key := fun h' => heq (by rw [← hcn, ← hk, h']) + simp only [this, ite_false] + exact symSwitch_sound he hk d rest t h + · simp at h + +theorem symBindParams_sound {ρ : Val} {call : Call} : + ∀ (ps : List Nat) (args : List Word) (sargs : List SV) (env : Env) (senv senv' : SEnv), + symBindParams ps sargs senv = some senv' → ArgsRel ρ call args sargs → + EnvRel ρ call env senv → ∃ env', bindParams ps args env = some env' ∧ EnvRel ρ call env' senv' + | [], [], [], env, senv, senv', h, _, he => by + simp only [symBindParams, Option.some.injEq] at h + subst h + exact ⟨env, rfl, he⟩ + | p :: ps, a :: as, s :: ss, env, senv, senv', h, ⟨ha, hr⟩, he => by + simp only [symBindParams] at h + obtain ⟨env', h1, h2⟩ := symBindParams_sound ps as ss _ _ _ h hr (he.set ha p) + exact ⟨env', by simp only [bindParams]; exact h1, h2⟩ + | [], [], _ :: _, _, _, _, h, _, _ => by simp [symBindParams] at h + | [], _ :: _, _, _, _, _, _, hr, _ => by cases ‹List SV› <;> simp_all [ArgsRel, symBindParams] + | _ :: _, [], _, _, _, _, h, hr, _ => by cases ‹List SV› <;> simp_all [ArgsRel, symBindParams] + | _ :: _, _ :: _, [], _, _, _, h, _, _ => by simp [symBindParams] at h + + +theorem symBindResult_sound {ρ : Val} {call : Call} {env : Env} {senv : SEnv} + (he : EnvRel ρ call env senv) : ∀ (dst : Option Nat) (args : List Word) (sargs : List SV) + (senv' : SEnv), symBindResult senv dst sargs = some senv' → ArgsRel ρ call args sargs → + ∃ env', bindResult env dst args = some env' ∧ EnvRel ρ call env' senv' + | none, [], [], senv', h, _ => by + simp only [symBindResult, Option.some.injEq] at h + subst h + exact ⟨env, rfl, he⟩ + | some d, [a], [v], senv', h, hr => by + simp only [symBindResult, Option.some.injEq] at h + subst h + exact ⟨_, rfl, he.set hr.1 d⟩ + | none, _ :: _, _, _, h, hr => by + cases ‹List SV› <;> simp_all [ArgsRel, symBindResult] + | none, [], _ :: _, _, h, hr => by simp [ArgsRel] at hr + | some _, [], _, _, h, hr => by cases ‹List SV› <;> simp_all [ArgsRel, symBindResult] + | some _, _ :: _ :: _, sargs, _, h, hr => by + match sargs, hr with + | _ :: _ :: _, _ => simp [symBindResult] at h + | some _, [_], [], _, h, hr => by simp [ArgsRel] at hr + | some _, [_], _ :: _ :: _, _, h, hr => by simp [ArgsRel] at hr + +/-! ## Steps -/ + +theorem storageOf_eq {cv : SV} {sel n : Nat} {ρ : Val} {call : Call} + (hc : CallFactsAt cv sel n ρ call) {s : State} + {st : SState} (hs : StRel ρ s st) : storageOf s = Writes.store ρ st.writes := by + funext slot + simp only [storageOf, hs.store, BitVec.toNat_ofNat] + exact Writes.store_mod ρ hc.ok slot st.writes + +theorem iterate_inr {σ : Type} {step : σ → Option ((Halt × State) ⊕ σ)} {x next : σ} + (h : step x = some (.inr next)) (k : Nat) : iterate step (k + 1) x = iterate step k next := by + simp [iterate, h] + +theorem iterate_inl {σ : Type} {step : σ → Option ((Halt × State) ⊕ σ)} {x : σ} {r : Halt × State} + (h : step x = some (.inl r)) : iterate step 1 x = some r := by + simp [iterate, h] + +theorem rel_zero_iff {ρ : Val} {call : Call} {v : Word} {e : WExpr} (h : SV.Rel ρ call v (.w e)) : + v = 0 ↔ e.eval ρ = 0 := by + simp only [SV.Rel] at h + constructor + · intro h0; rw [← h, h0]; rfl + · intro h0; exact BitVec.eq_of_toNat_eq (by rw [h, h0]; rfl) + +theorem symCallee_some {m : Module} {callee : Nat} {g : Function} (h : symCallee m callee = some g) : + m.functions[callee]? = some g := h + +/-- The module's entry function stores its entry heap on both sides. -/ +theorem StRel.entryStart {ρ : Val} {s : State} {st : SState} (hs : StRel ρ s st) (m : Module) : + StRel ρ (m.startState s) (symEntryStart m st) := by + unfold Module.startState symEntryStart + cases hf : m.functions[m.entry]? with + | some f => exact hs.start f + | none => exact hs + +/-- What a machine step gives, held by what a symbolic step gives: the same end, or the next +frame related, or for a branch on a word the side the call's words take. -/ +def NextOk (ρ : Val) (call : Call) (x : Option ((Halt × State) ⊕ Frame)) : SNext → Prop + | .done T => ∃ r, x = some (.inl r) ∧ observe call r.2 r.1 = (T.eval ρ).obs + | .go stack pos senv st => ∃ ms env s, x = some (.inr (ms, pos, env, s)) ∧ + StackRel ρ call ms stack ∧ EnvRel ρ call env senv ∧ StRel ρ s st + | .fork e stack fn b yes no senv st => ∃ ms env s, + x = some (.inr (ms, .enter fn b (if e.eval ρ = 0 then no else yes), env, s)) ∧ + StackRel ρ call ms stack ∧ EnvRel ρ call env senv ∧ StRel ρ s st + +theorem symTerm_sound {cv : SV} {sel n : Nat} {ρ : Val} {call : Call} + (hc : CallFactsAt cv sel n ρ call) (o : Oracle) (m : Module) {stack : List SReturn} + {fn b : Nat} {senv : SEnv} {st : SState} {term : Terminator} {r : SNext} + (h : symTerm m stack fn b senv st term = some r) {ms : List Return} {env : Env} {s : State} + (hst : StackRel ρ call ms stack) (he : EnvRel ρ call env senv) (hs : StRel ρ s st) : + NextOk ρ call (segment o call m ms fn b [] term env s) r := by + cases term with + | jump t => + simp only [symTerm, Option.some.injEq] at h + subst h + exact ⟨ms, env, s, rfl, hst, he, hs⟩ + | branch c yes no => + simp only [symTerm] at h + have hcr := rel_operand he c + have hseg : segment o call m ms fn b [] (.branch c yes no) env s = + some (.inr (ms, .enter fn b (if c.eval env = 0 then no else yes), env, s)) := rfl + rw [hseg] + cases hsv : SV.ofOperand senv c with + | cd0 => simp [hsv] at h + | paid => + simp only [hsv, Option.some.injEq] at h + subst h + rw [hsv] at hcr + have hc0 : ¬ c.eval env = 0 := hcr + exact ⟨ms, env, s, by simp only [hc0, ↓reduceIte], hst, he, hs⟩ + | w e => + simp only [hsv] at h + rw [hsv] at hcr + have hz := rel_zero_iff hcr + cases hl : e.lit? with + | some v => + simp only [hl, Option.some.injEq] at h + subst h + have hev : e.eval ρ = v % wordSize := by rw [WExpr.eq_of_lit? hl]; rfl + refine ⟨ms, env, s, ?_, hst, he, hs⟩ + by_cases h0 : v % wordSize = 0 + · have hc0 : c.eval env = 0 := hz.mpr (by rw [hev, h0]) + simp only [hc0, h0, ↓reduceIte] + · have hc0 : ¬ c.eval env = 0 := fun h' => h0 (by rw [← hev]; exact hz.mp h') + simp only [hc0, h0, ↓reduceIte] + | none => + simp only [hl, Option.some.injEq] at h + subst h + refine ⟨ms, env, s, ?_, hst, he, hs⟩ + by_cases h0 : e.eval ρ = 0 + · have hc0 : c.eval env = 0 := hz.mpr h0 + simp only [hc0, h0, ↓reduceIte] + · have hc0 : ¬ c.eval env = 0 := fun h' => h0 (hz.mp h') + simp only [hc0, h0, ↓reduceIte] + | switch key d cs => + simp only [symTerm] at h + split at h + · rename_i kv hkv + cases hs' : symSwitch senv kv d cs with + | none => simp [hs'] at h + | some t => + simp only [hs', Option.some.injEq] at h + subst h + have hk := rel_operand he key + rw [hkv] at hk + have htg := symSwitch_sound he (toNat_of_rel hk) d cs t hs' + exact ⟨ms, env, s, by simp [segment, splitCall, execInsts, htg], hst, he, hs⟩ + · simp at h + | tailCall callee args => + simp only [symTerm] at h + cases hg : symCallee m callee with + | none => simp [hg] at h + | some g => + simp only [hg] at h + have hg' := symCallee_some hg + cases hbp : symBindParams g.params (args.map (SV.ofOperand senv)) (fun _ => .w (.lit 0)) with + | none => simp [hbp] at h + | some senv3 => + simp only [hbp, Option.some.injEq] at h + subst h + have hz : EnvRel ρ call (fun _ => 0) (fun _ => .w (.lit 0)) := fun _ => by + simp [SV.Rel, WExpr.eval] + obtain ⟨env3, hbp', he3⟩ := symBindParams_sound g.params _ _ _ _ _ hbp (rel_args he args) hz + exact ⟨ms, env3, g.start s, by simp only [segment, splitCall, execInsts, hg', hbp'], hst, he3, + hs.start g⟩ + | leave values => + simp only [symTerm] at h + cases stack with + | nil => simp at h + | cons q qs => + match ms, hst with + | r :: rs, ⟨hfn, hb, hdst, hrest, hterm, hextras, hpublish, henvr, hst'⟩ => + simp only at h + cases hbr : symBindResult q.env q.dst (values.map (SV.ofOperand senv)) with + | none => simp [hbr] at h + | some env' => + simp only [hbr, Option.some.injEq] at h + subst h + rw [← hdst] at hbr + obtain ⟨env'', hbr', he''⟩ := + symBindResult_sound henvr r.dst _ _ _ hbr (rel_args he values) + have hbr2 : bindResults r.env r.dst r.extras (values.map (Operand.eval env)) = some env'' := by + rw [hextras]; exact hbr' + exact ⟨rs, env'', s, by + simp [segment, splitCall, execInsts, hbr2, hfn, hb, hrest, hterm, hpublish, + publishResults], + hst', he'', hs⟩ + | ret off size => + simp only [symTerm] at h + split at h + · rename_i ov sv hov hsv + simp only [Option.some.injEq] at h + subst h + have h1 := rel_operand he off + have h2 := rel_operand he size + rw [hov] at h1 + rw [hsv] at h2 + refine ⟨_, rfl, ?_⟩ + simp only [halt, observe, Tree.eval, Res.obs, Bool.false_eq_true, ↓reduceIte, + toNat_of_rel h1, toNat_of_rel h2] + congr 1 + · exact read_eq hs _ (bytes_expand _ _ _) _ _ + · exact hs.world + · exact storageOf_eq hc (s := s) hs + · simp at h + | revert off size => + simp only [symTerm] at h + split at h + · rename_i ov sv hov hsv + simp only [Option.some.injEq] at h + subst h + have h1 := rel_operand he off + have h2 := rel_operand he size + rw [hov] at h1 + rw [hsv] at h2 + refine ⟨_, rfl, ?_⟩ + simp only [halt, observe, Tree.eval, Res.obs, ↓reduceIte, toNat_of_rel h1, toNat_of_rel h2, + hc.store, Bool.false_eq_true] + congr 1 + exact read_eq hs _ (bytes_expand _ _ _) _ _ + · simp at h + | stop => + simp only [symTerm, Option.some.injEq] at h + subst h + refine ⟨_, rfl, ?_⟩ + simp only [observe, Tree.eval, Res.obs, ite_true, hs.world, storageOf_eq hc hs, List.map_nil] + | invalid => + simp only [symTerm, Option.some.injEq] at h + subst h + refine ⟨_, rfl, ?_⟩ + simp only [observe, Tree.eval, Res.obs, hc.store, Bool.false_eq_true, ite_false, List.map_nil] + +theorem symSegment_sound {ev : EnvFlags} {cv : SV} {sel n : Nat} {ρ : Val} {call : Call} + (hc : CallFactsAt cv sel n ρ call) {o : Oracle} (henv : EnvAsk ev o ρ) (m : Module) + {K : Facts} (hK : K.Hold ρ) {stack : List SReturn} {fn b : Nat} {insts : List Inst} + {term : Terminator} {senv : SEnv} {st : SState} {r : SNext} + (h : symSegment ev cv m sel n K stack fn b insts term senv st = some r) {ms : List Return} + {env : Env} {s : State} (hst : StackRel ρ call ms stack) (he : EnvRel ρ call env senv) + (hs : StRel ρ s st) : NextOk ρ call (segment o call m ms fn b insts term env s) r := by + unfold symSegment at h + cases hsp : splitCall insts with + | mk before next => + rw [hsp] at h + cases next with + | some c => + obtain ⟨dst, callee, args, extras, publish, rest⟩ := c + cases extras with + | cons _ _ => simp at h + | nil => + cases publish with + | some _ => simp at h + | none => + simp only at h + cases hi : symInsts ev cv sel n K before senv st with + | none => simp [hi] at h + | some p => + obtain ⟨senv2, st2⟩ := p + simp only [hi] at h + obtain ⟨env2, s2, hexec, he2, hs2⟩ := symInsts_sound hc henv hK before _ _ _ _ hi env s he hs + cases hg : symCallee m callee with + | none => simp [hg] at h + | some g => + simp only [hg] at h + have hg' := symCallee_some hg + cases hbp : symBindParams g.params (args.map (SV.ofOperand senv2)) (fun _ => .w (.lit 0)) with + | none => simp [hbp] at h + | some inner => + simp only [hbp, Option.some.injEq] at h + subst h + have hz : EnvRel ρ call (fun _ => 0) (fun _ => .w (.lit 0)) := fun _ => by + simp [SV.Rel, WExpr.eval] + obtain ⟨env3, hbp', he3⟩ := + symBindParams_sound g.params _ _ _ _ _ hbp (rel_args he2 args) hz + exact ⟨⟨fn, b, dst, rest, term, env2, [], none⟩ :: ms, env3, g.start s2, + by simp only [segment, hsp, hexec, hg', hbp'], + ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, he2, hst⟩, he3, hs2.start g⟩ + | none => + simp only at h + cases hi : symInsts ev cv sel n K before senv st with + | none => simp [hi] at h + | some p => + obtain ⟨senv2, st2⟩ := p + simp only [hi] at h + obtain ⟨env2, s2, hexec, he2, hs2⟩ := symInsts_sound hc henv hK before _ _ _ _ hi env s he hs + have hseg : segment o call m ms fn b insts term env s = segment o call m ms fn b [] term env2 s2 := by + simp only [segment, hsp, hexec, splitCall, execInsts] + rw [hseg] + exact symTerm_sound hc o m h hst he2 hs2 + +theorem symStep_sound {ev : EnvFlags} {cv : SV} {sel n : Nat} {ρ : Val} {call : Call} + (hc : CallFactsAt cv sel n ρ call) {o : Oracle} (henv : EnvAsk ev o ρ) (m : Module) + {K : Facts} (hK : K.Hold ρ) {stack : List SReturn} {pos : Pos} {senv : SEnv} {st : SState} + {r : SNext} (h : symStep ev cv m sel n K stack pos senv st = some r) {ms : List Return} + {env : Env} {s : State} (hst : StackRel ρ call ms stack) (he : EnvRel ρ call env senv) + (hs : StRel ρ s st) : NextOk ρ call (moduleBlock o call m (ms, pos, env, s)) r := by + cases pos with + | enter fn pred b => + simp only [symStep] at h + simp only [moduleBlock] + cases hf : m.functions[fn]? with + | none => simp [hf] at h + | some f => + simp only [hf] at h ⊢ + cases hb : f.blocks[b]? with + | none => simp [hb] at h + | some blk => + simp only [hb] at h ⊢ + cases hp : symPhis senv pred blk.phis senv with + | none => simp [hp] at h + | some senv1 => + simp only [hp] at h + obtain ⟨env1, hbind, he1⟩ := symPhis_sound he pred blk.phis senv senv1 env hp he + simp only [hbind] + exact symSegment_sound hc henv m hK h hst he1 hs + | resume fn b insts term => exact symSegment_sound hc henv m hK h hst he hs + +/-- **The symbolic run is sound**: a tree the symbolic run of a module computes from a frame is +the end the module's run reaches from any frame that holds it, on a path whose facts hold, +under every oracle the environment flag allows. -/ +theorem symRun_sound {ev : EnvFlags} {cv : SV} {sel n : Nat} {ρ : Val} {call : Call} + (hc : CallFactsAt cv sel n ρ call) (o : Oracle) (henv : EnvAsk ev o ρ) (m : Module) : + ∀ (fuel : Nat) (stack : List SReturn) (pos : Pos) (senv : SEnv) (st : SState) (K : Facts) + (T : Tree), symRun ev cv m sel n fuel stack pos senv st K = some T → + ∀ ms env s, StackRel ρ call ms stack → EnvRel ρ call env senv → StRel ρ s st → K.Hold ρ → + ∃ k r, iterate (moduleBlock o call m) k (ms, pos, env, s) = some r ∧ + observe call r.2 r.1 = (T.eval ρ).obs + | 0, _, _, _, _, _, _, h, _, _, _, _, _, _, _ => by simp [symRun] at h + | fuel + 1, stack, pos, senv, st, K, T, h, ms, env, s, hst, he, hs, hK => by + simp only [symRun] at h + cases hx : symStep ev cv m sel n K stack pos senv st with + | none => simp [hx] at h + | some x => + have hn := symStep_sound hc henv m hK hx hst he hs + simp only [hx] at h + cases x with + | done T' => + simp only [Option.some.injEq] at h + subst h + obtain ⟨r, hr, hobs⟩ := hn + exact ⟨1, r, iterate_inl hr, hobs⟩ + | go stack' pos' senv' st' => + obtain ⟨ms', env', s', hr, hst', he', hs'⟩ := hn + obtain ⟨k, r, hk, hobs⟩ := + symRun_sound hc o henv m fuel stack' pos' senv' st' K T h ms' env' s' hst' he' hs' hK + exact ⟨k + 1, r, by rw [iterate_inr hr]; exact hk, hobs⟩ + | fork e stack' fn b yes no senv' st' => + obtain ⟨ms', env', s', hr, hst', he', hs'⟩ := hn + cases ht : symRun ev cv m sel n fuel stack' (.enter fn b yes) senv' st' (K.add e true) with + | none => simp [ht] at h + | some t => + cases hf : symRun ev cv m sel n fuel stack' (.enter fn b no) senv' st' (K.add e false) with + | none => simp [ht, hf] at h + | some f => + simp only [ht, hf, Option.some.injEq] at h + subst h + by_cases h0 : e.eval ρ = 0 + · simp only [h0, ite_true] at hr + obtain ⟨k, r, hk, hobs⟩ := symRun_sound hc o henv m fuel stack' _ senv' st' _ f hf + ms' env' s' hst' he' hs' (hK.add e false (by simp [h0])) + refine ⟨k + 1, r, by rw [iterate_inr hr]; exact hk, ?_⟩ + simp only [Tree.eval, h0, ite_true] + exact hobs + · simp only [h0, ite_false] at hr + obtain ⟨k, r, hk, hobs⟩ := symRun_sound hc o henv m fuel stack' _ senv' st' _ t ht + ms' env' s' hst' he' hs' (hK.add e true (by simp [h0])) + refine ⟨k + 1, r, by rw [iterate_inr hr]; exact hk, ?_⟩ + simp only [Tree.eval, h0, ite_false] + exact hobs + +theorem StRel.initial {ρ : Val} (call : Call) (h : ρ.store = slotValue call.storage) (hok : ρ.Ok) : + StRel ρ (State.initial call) SState.initial where + mem _ := rfl + store k := by + have := hok k.toNat + rw [Nat.mod_eq_of_lt k.isLt] at this + simp only [State.initial, SState.initial, Writes.store, BitVec.toNat_ofNat, ← h] + exact this + world := rfl + +/-- The run from the module's entry, whose value is `cv`, is sound on a call that gives it what +`CallFactsAt` says. -/ +theorem symRun_entry_sound {ev : EnvFlags} {cv : SV} {sel n : Nat} {ρ : Val} {call : Call} + (hc : CallFactsAt cv sel n ρ call) (o : Oracle) (henv : EnvAsk ev o ρ) (m : Module) + {fuel : Nat} {T : Tree} + (h : symRun ev cv m sel n fuel [] (.enter m.entry 0 0) (fun _ => .w (.lit 0)) + (symEntryStart m SState.initial) [] = some T) : + (moduleSem o).run m call = some (T.eval ρ).obs := by + have hz : EnvRel ρ call (fun _ => 0) (fun _ => .w (.lit 0)) := fun _ => by + simp [SV.Rel, WExpr.eval] + obtain ⟨k, r, hk, hr⟩ := symRun_sound hc o henv m fuel _ _ _ _ _ T h [] _ _ trivial hz + ((StRel.initial call hc.store hc.ok).entryStart m) (fun _ hp => absurd hp List.not_mem_nil) + have e : moduleLayer.result o m call = some r := moduleLayer.result_of_ends ⟨k, hk⟩ + show (moduleLayer.result o m call).map _ = _ + rw [e, ← hr] + rfl + +/-- **SolarTV's lowered MIR runs a module as its symbolic tree**: on a call that gives the +symbolic run what `CallFacts` says, under every oracle (one `EnvOk` describes when the environment +flag is set), the fuel-free semantics shows the tree's result. -/ +theorem symTree_sound {sel n : Nat} {ρ : Val} {call : Call} (hc : CallFacts sel n ρ call) + (o : Oracle) (m : Module) {fuel : Nat} {env : EnvFlags} (henv : EnvAsk env o ρ) {T : Tree} + (h : symTree m sel n fuel env = some T) : + (moduleSem o).run m call = some (T.eval ρ).obs := by + unfold symTree at h + exact symRun_entry_sound hc.at o henv m h + +/-- **SolarTV's lowered MIR runs a module as its symbolic tree with a value**: on a call with a +value other than 0 that gives the symbolic run the rest of what `CallFacts` says, under every +oracle (one that gives the flags what `EnvAsk` says they ask), the fuel-free semantics shows the +result of the tree `symTreeValue` computes. -/ +theorem symTreeValue_sound {sel n : Nat} {ρ : Val} {call : Call} + (hc : CallFactsAt .paid sel n ρ call) (o : Oracle) (m : Module) {fuel : Nat} {env : EnvFlags} + (henv : EnvAsk env o ρ) {T : Tree} (h : symTreeValue m sel n fuel env = some T) : + (moduleSem o).run m call = some (T.eval ρ).obs := by + unfold symTreeValue at h + exact symRun_entry_sound hc o henv m h + +end SolidCore.Refinement.Generic + + + diff --git a/SolidCore/Refinement/Generic/MulTest.lean b/SolidCore/Refinement/Generic/MulTest.lean new file mode 100644 index 00000000..c43eb894 --- /dev/null +++ b/SolidCore/Refinement/Generic/MulTest.lean @@ -0,0 +1,314 @@ +import SolidCore.Refinement.Generic.Stage + +/-! +# The generic check on checked multiplication + +A test of the generic check's checked multiplication, which no corpus instance of the generic +stage exercises. The contract + + contract Main { uint8 a; uint256 c; + function f(uint8 x) external returns (uint8) { a *= x; return a; } + function g(uint256 x) external { c *= x; } } + +has a `uint8` compound multiplication into a packed field and a `uint256` one. `coreLit` is +the core SolidCore's type checker leaves for it (solc 0.8.35's AST through +scripts/solc_ast_to_lean_source.py and `TypeCheck.CheckedInput.contract`, printed and copied). +`mulStage0` is a lowered MIR module written by hand in the shape of solar's first lowered MIR +(c4's Stage0.lean for the dispatcher, the argument checks and the packed write), with the +overflow checks solar's `lower-arithmetic` pass emits (crates/codegen/src/mir/transform/ +lower_arithmetic.rs, `mul_overflow`): for `uint8`, whose operands' exact product fits in a +word, the range check `gt (mul a x) 255`; for `uint256`, +`iszero (or (iszero x) (eq (div (mul c x) x) c))`. solar's exporter is not part of this +checkout, so the module is not solar's output (Solar/MulX/Lowering.lean runs the check on +solar's own export of a narrow-mul contract); it checks that the canonical forms meet +SolidCore's checked `uint256` multiplication followed by its `uint8` cleanup: + +* `check_mul`: `Generic.check` accepts `mulStage0` for both functions (`decide +kernel`); +* `check_rejects_wide`: it rejects the module with `uint8`'s range check against `2 ^ 16 - 1`; +* `check_rejects_quotient`: it rejects the module whose `uint256` check compares the quotient + with `x` instead of `c`. +-/ + +namespace SolidCore.Refinement.Generic.MulTest + +open SolidCore.Solidity.Source SolarTV.MIR.Lowered + +/-- SolidCore's core contract of the test, as the type checker leaves it. -/ +def coreLit : Contract := + { storageFields := [{ name := "a", + slot := 0, + ty? := some (SolidCore.Solidity.Source.Ty.uint256), + layout? := some (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.uint256)), + transient := false, + packedOffset := 0, + packedBytes := 1, + packedSigned := false }, + { name := "c", + slot := 1, + ty? := some (SolidCore.Solidity.Source.Ty.uint256), + layout? := some (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.uint256)), + transient := false, + packedOffset := 0, + packedBytes := 32, + packedSigned := false }], + immutableFields := [], + eventDecls := [], + errorDecls := [], + functions := [{ name := "f", + selector? := some 824235060, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.mul)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 8)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "a" + []) + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.ref) + "a" + [])]]], + dispatchId? := none }, + { name := "g", + selector? := some 3827312202, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.mul)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 256)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "c" + []) + (SolidCore.Solidity.Source.Expr.var "x"))]], + dispatchId? := none }, + { name := "__internal_f(uint8)#[SolidCore.Solidity.Ty.uint 8]", + selector? := none, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.mul)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 8)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "a" + []) + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.ref) + "a" + [])]]], + dispatchId? := none }, + { name := "__internal_g(uint256)#[SolidCore.Solidity.Ty.uint 256]", + selector? := none, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.mul)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 256)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "c" + []) + (SolidCore.Solidity.Source.Expr.var "x"))]], + dispatchId? := none }] } + +/-- The selector of `f(uint8)`. -/ +abbrev fSel : Nat := 824235060 + +/-- The selector of `g(uint256)`. -/ +abbrev gSel : Nat := 3827312202 + +/-- Both functions and their parameters. -/ +def fns : List SolidCore.Refinement.Abi.Fn := [⟨fSel, [.uint 8]⟩, ⟨gSel, [.uint 256]⟩] + +/-- A lowered MIR module for the test, in the shape of solar's: `f` (function 0) checks the call +data size and `x`'s cleanliness, multiplies the low byte of slot 0 by `x` with the `uint8` +range check, writes the product back into the low byte and returns it; `g` (function 1) +multiplies slot 1 by `x` with the `uint256` check. -/ +def mulStage0 : Module := + { entry := 2, + functions := [ + -- @f + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 45) .calldatasize [], + .pure 47 .lt [.value 45, .const 36], + .effect (some 49) .calldataload [.const 4], + .pure 51 .gt [.value 49, .const 255], + .pure 71 .or [.value 47, .value 51]], + .branch (.value 71) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.pure 8 .and [.value 2, .const 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00], + .pure 11 .or [.value 8, .value 34], + .effect none .sstore [.const 0, .value 11], + .pure 65 .and [.value 11, .const 255], + .effect none .mstore [.const 0, .value 65]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 2) .sload [.const 0], + .pure 69 .and [.value 2, .const 255], + .pure 34 .mul [.value 69, .value 49], + .pure 36 .gt [.value 34, .const 255]], + .branch (.value 36) 1 2⟩] }, + -- @g + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 45) .calldatasize [], + .pure 47 .lt [.value 45, .const 36]], + .branch (.value 47) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 1, .value 34]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 49) .calldataload [.const 4], + .effect (some 2) .sload [.const 1], + .pure 34 .mul [.value 2, .value 49], + .pure 40 .iszero [.value 49], + .pure 41 .div [.value 34, .value 49], + .pure 42 .eq [.value 41, .value 2], + .pure 43 .or [.value 40, .value 42], + .pure 44 .iszero [.value 43]], + .branch (.value 44) 1 2⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 4 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 4 [(.const fSel, 2), (.const gSel, 3)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +/-- `mulStage0` with each instruction changed by `f`. -/ +def mapInsts (f : Inst → Inst) : Module := + { mulStage0 with + functions := mulStage0.functions.map fun fn => + { fn with blocks := fn.blocks.map fun b => { b with insts := b.insts.map f } } } + +/-- `uint8`'s range check against `2 ^ 16 - 1`, the product's bound, instead of `255`. -/ +def wideCheck : Inst → Inst + | .pure 36 .gt [a, .const 255] => .pure 36 .gt [a, .const 65535] + | i => i + +/-- `uint256`'s check comparing the quotient with `x` instead of `c`. -/ +def quotientCheck : Inst → Inst + | .pure 42 .eq [a, .value 2] => .pure 42 .eq [a, .value 49] + | i => i + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts the module for both functions. -/ +theorem check_mul : check 4096 16 coreLit mulStage0 fns = true := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects a `uint8` product checked against `2 ^ 16 - 1`. -/ +theorem check_rejects_wide : check 4096 16 coreLit (mapInsts wideCheck) fns = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects a `uint256` check against the wrong operand. -/ +theorem check_rejects_quotient : check 4096 16 coreLit (mapInsts quotientCheck) fns = false := by + decide +kernel + +end SolidCore.Refinement.Generic.MulTest diff --git a/SolidCore/Refinement/Generic/Packed.lean b/SolidCore/Refinement/Generic/Packed.lean new file mode 100644 index 00000000..99f87ac0 --- /dev/null +++ b/SolidCore/Refinement/Generic/Packed.lean @@ -0,0 +1,107 @@ +import SolidCore.Refinement.Generic.Tree + +/-! +# Packed storage fields on words + +A field of `w` bits at bit offset `o` of its slot (`o + w ≤ 256`) reads as +`slot / 2 ^ o % 2 ^ w`, and SolidCore writes it by arithmetic (`wordReplaceBitRange`): +`slot - (slot / 2 ^ o % 2 ^ w) * 2 ^ o + (v % 2 ^ w) * 2 ^ o`. solar writes it with masks: +`or (and slot (clearMask o w)) (shl o v)`. `replace_eq` shows the two agree: the clearing mask +keeps the bits below `o` and from `o + w` on (`and_clearMask`), and the parts of the word, +on disjoint bits, add as they `or`. +-/ + +namespace SolidCore.Refinement.Generic + +/-- The mask that clears bits `o` to `o + w - 1` of a word. -/ +def clearMask (o w : Nat) : Nat := ((2 ^ (256 - (o + w)) - 1) <<< (o + w)) ||| (2 ^ o - 1) + +theorem testBit_word {x : Nat} (hx : x < 2 ^ 256) {i : Nat} (hi : 256 ≤ i) : x.testBit i = false := + Nat.testBit_lt_two_pow (Nat.lt_of_lt_of_le hx (Nat.pow_le_pow_right (by decide) hi)) + +theorem testBit_clearMask (o w i : Nat) (h : o + w ≤ 256) : + (clearMask o w).testBit i = (decide (i < o) || (decide (o + w ≤ i) && decide (i < 256))) := by + simp only [clearMask, Nat.testBit_or, Nat.testBit_shiftLeft, Nat.testBit_two_pow_sub_one] + by_cases h1 : i < o + · simp [h1] + · by_cases h2 : o + w ≤ i + · by_cases h3 : i < 256 + · simp [h1, h2, h3] <;> omega + · simp [h1, h2, h3] <;> omega + · simp [h1, h2] <;> omega + +theorem clearMask_lt (o w : Nat) (h : o + w ≤ 256) : clearMask o w < 2 ^ 256 := by + have : clearMask o w = clearMask o w % 2 ^ 256 := by + apply Nat.eq_of_testBit_eq + intro i + rw [Nat.testBit_mod_two_pow, testBit_clearMask o w i h] + by_cases hi : i < 256 + · simp [hi] + · simp [hi]; omega + rw [this] + exact Nat.mod_lt _ (Nat.two_pow_pos _) + +theorem and_clearMask {x : Nat} (hx : x < 2 ^ 256) (o w : Nat) (h : o + w ≤ 256) : + x &&& clearMask o w = ((x >>> (o + w)) <<< (o + w)) ||| (x % 2 ^ o) := by + apply Nat.eq_of_testBit_eq + intro i + simp only [Nat.testBit_and, Nat.testBit_or, testBit_clearMask o w i h, Nat.testBit_shiftLeft, + Nat.testBit_shiftRight, Nat.testBit_mod_two_pow] + by_cases h1 : i < o + · have : ¬ i ≥ o + w := by omega + simp [h1, this] + · by_cases h2 : o + w ≤ i + · by_cases h3 : i < 256 + · have e : o + w + (i - (o + w)) = i := by omega + simp [h1, h2, h3, e] + · have e : o + w + (i - (o + w)) = i := by omega + simp [h1, h2, h3, e, testBit_word hx (Nat.le_of_not_lt h3)] + · have : ¬ i ≥ o + w := by omega + simp [h1, h2, this] + +/-- SolidCore's arithmetic write of a packed field is the masked write. -/ +theorem replace_eq {cur : Nat} (hcur : cur < 2 ^ 256) (v o w : Nat) (h : o + w ≤ 256) : + cur - cur / 2 ^ o % 2 ^ w * 2 ^ o + v % 2 ^ w * 2 ^ o = + (cur &&& clearMask o w) ||| ((v % 2 ^ w) <<< o) := by + rw [and_clearMask hcur o w h, Nat.or_assoc, Nat.or_comm (cur % 2 ^ o), + ← Nat.shiftLeft_add_eq_or_of_lt (Nat.mod_lt _ (Nat.two_pow_pos o))] + have hV : v % 2 ^ w < 2 ^ w := Nat.mod_lt _ (Nat.two_pow_pos w) + have hlow : (v % 2 ^ w) <<< o + cur % 2 ^ o < 2 ^ (o + w) := by + rw [Nat.shiftLeft_eq, Nat.pow_add] + have h1 : cur % 2 ^ o < 2 ^ o := Nat.mod_lt _ (Nat.two_pow_pos o) + have h2 : (v % 2 ^ w + 1) * 2 ^ o ≤ 2 ^ w * 2 ^ o := Nat.mul_le_mul_right _ hV + rw [Nat.add_mul, Nat.one_mul, Nat.mul_comm (2 ^ w)] at h2 + omega + rw [← Nat.shiftLeft_add_eq_or_of_lt hlow] + have hdec : cur = 2 ^ (o + w) * (cur / 2 ^ (o + w)) + 2 ^ o * (cur / 2 ^ o % 2 ^ w) + cur % 2 ^ o := by + have e1 := Nat.div_add_mod cur (2 ^ o) + have e2 := Nat.div_add_mod (cur / 2 ^ o) (2 ^ w) + rw [Nat.div_div_eq_div_mul, ← Nat.pow_add] at e2 + have e4 : 2 ^ (o + w) * (cur / 2 ^ (o + w)) = 2 ^ o * (2 ^ w * (cur / 2 ^ (o + w))) := by + rw [Nat.pow_add, Nat.mul_assoc] + generalize cur / 2 ^ (o + w) = H at e2 e4 ⊢ + generalize cur / 2 ^ o = q at e1 e2 ⊢ + rw [e4] + rw [← e2, Nat.mul_add] at e1 + omega + simp only [Nat.shiftLeft_eq, Nat.shiftRight_eq_div_pow] + generalize cur / 2 ^ (o + w) = H at hdec ⊢ + generalize cur / 2 ^ o % 2 ^ w = M at hdec ⊢ + rw [Nat.mul_comm M, Nat.mul_comm H] + omega + +theorem replace_lt {cur : Nat} (hcur : cur < 2 ^ 256) (v o w : Nat) (h : o + w ≤ 256) : + (cur &&& clearMask o w) ||| ((v % 2 ^ w) <<< o) < 2 ^ 256 := by + have h1 : cur &&& clearMask o w < 2 ^ 256 := Nat.lt_of_le_of_lt Nat.and_le_left hcur + have h2 : (v % 2 ^ w) <<< o < 2 ^ 256 := by + rw [Nat.shiftLeft_eq] + have hV : v % 2 ^ w < 2 ^ w := Nat.mod_lt _ (Nat.two_pow_pos w) + have h3 : (v % 2 ^ w + 1) * 2 ^ o ≤ 2 ^ w * 2 ^ o := Nat.mul_le_mul_right _ hV + have h4 : 2 ^ w * 2 ^ o ≤ 2 ^ 256 := by + rw [← Nat.pow_add]; exact Nat.pow_le_pow_right (by decide) (by omega) + rw [Nat.add_mul, Nat.one_mul] at h3 + have := Nat.two_pow_pos o + omega + exact Nat.or_lt_two_pow h1 h2 + +end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Generic/Simp.lean b/SolidCore/Refinement/Generic/Simp.lean new file mode 100644 index 00000000..4d1ae36f --- /dev/null +++ b/SolidCore/Refinement/Generic/Simp.lean @@ -0,0 +1,748 @@ +import SolidCore.Refinement.Generic.Tree + +/-! +# Canonical forms of trees: split disjunctions and negations, path facts and bounds + +The two sides of the generic source stage spell the same call differently where a narrow type +meets a word: SolidCore checks a `uint8` sum with `uint256`'s overflow check and then its +cleanup, solar with one range check; SolidCore cleans a word that solar knows is clean; solar +reads a packed byte with `byte`, the source with a shift and a mask; solar joins its argument +checks with `or`. `canon` brings both trees to one form, which the kernel then compares by `=`: + +* `Tree.split` turns a branch on `or a b` into a branch on `a`, then on `b` (`splitCond`); +* `Tree.simp K` simplifies every word bottom up (`WExpr.simp`): constants fold, `or` with zero + and shifts by zero drop, `byte i v` becomes `and (shr (8 * (31 - i)) v) 255`, a mask + `and a (2 ^ k - 1)` drops when `a` is at most the mask, and a comparison that cannot hold + (`gt a c` with `a ≤ c`, `uint256`'s add and mul overflow checks on operands too small to + overflow) becomes zero. Upper bounds (`bound`) come from the words' shapes and from the facts + `K` of the path: each branch taken records its word and side, so a word known to be at most + `c` (`gt a c` taken as zero) bounds `a`, a branch on a word already decided takes its side, + and `sub a b` with `lt a b` taken as zero is at most `a`; +* `Tree.splitNeg` then turns a branch on a negation (`iszero a`, `eq a 0`) into a branch on + `a` with its sides swapped, a branch on `not a` (solar's `a != type(uint256).max`) into a + branch on `eq a maxWord` with its sides swapped, and splits the disjunctions the simplification left, such as + `uint256`'s mul overflow check `iszero (or (iszero r) …)` against solar's branch on + `or (eq r 0) …`; a second `Tree.simp` simplifies along the new paths. + +`Tree.eval_canon`: a tree and its canonical form give every call the same result. Every rule is +proved on the words' values (`WExpr.eval_simp`, `bound_sound`), so the check stays sound +whatever the trees are; a rule that does not apply leaves the word as it is. +-/ + +namespace SolidCore.Refinement.Generic + +/-- The largest word. -/ +abbrev maxWord : Nat := wordSize - 1 + +theorem WExpr.eval_le (ρ : Val) (e : WExpr) : e.eval ρ ≤ maxWord := by + have := e.eval_lt ρ + simp only [maxWord] + omega + +/-! ## Splitting disjunctions -/ + +/-- A branch on `c`, with a disjunction `or a b` split into a branch on `a`, then on `b`. -/ +def splitCond : WExpr → Tree → Tree → Tree + | .bin .or a b, t, e => splitCond a t (splitCond b t e) + | c, t, e => .ite c t e + +/-- Every branch of a tree, its disjunctions split. -/ +def Tree.split : Tree → Tree + | .halt ok out ws ls => .halt ok out ws ls + | .ite c t e => splitCond c t.split e.split + +theorem or_eval_eq_zero (ρ : Val) (a b : WExpr) : + (WExpr.bin .or a b).eval ρ = 0 ↔ a.eval ρ = 0 ∧ b.eval ρ = 0 := by + have ha := a.eval_lt ρ + have hb := b.eval_lt ρ + simp only [WExpr.eval, BinOp.eval] + rw [Nat.mod_eq_of_lt (Nat.or_lt_two_pow ha hb)] + exact Nat.or_eq_zero_iff + +theorem splitCond_eval (ρ : Val) (c : WExpr) : ∀ t e : Tree, + (splitCond c t e).eval ρ = if c.eval ρ = 0 then e.eval ρ else t.eval ρ := by + induction c with + | bin op a b iha ihb => + cases op + case or => + intro t e + simp only [splitCond, iha, ihb, or_eval_eq_zero] + by_cases ha : a.eval ρ = 0 <;> by_cases hb : b.eval ρ = 0 <;> simp [ha, hb] + all_goals intro t e; rfl + | _ => intro t e; rfl + +theorem Tree.eval_split (ρ : Val) : ∀ T : Tree, T.split.eval ρ = T.eval ρ + | .halt _ _ _ _ => rfl + | .ite c t e => by + rw [Tree.split, splitCond_eval, Tree.eval_split ρ t, Tree.eval_split ρ e] + rfl + +/-! ## Facts of a path -/ + +/-- The branches a path took: each word, and whether it was not zero. -/ +abbrev Facts := List (WExpr × Bool) + +/-- The call's words agree with the facts. -/ +def Facts.Hold (ρ : Val) (K : Facts) : Prop := ∀ p ∈ K, (p.1.eval ρ = 0 ↔ p.2 = false) + +/-- The side the facts give a word, if they record it. -/ +def Facts.lookup : Facts → WExpr → Option Bool + | [], _ => none + | (c', b) :: K, c => if c' = c then some b else Facts.lookup K c + +theorem Facts.lookup_sound {ρ : Val} {K : Facts} (h : K.Hold ρ) {c : WExpr} {b : Bool} + (hl : K.lookup c = some b) : (c.eval ρ = 0 ↔ b = false) := by + induction K with + | nil => simp [Facts.lookup] at hl + | cons p K ih => + obtain ⟨c', b'⟩ := p + simp only [Facts.lookup] at hl + split at hl + · rename_i he + subst he + simp only [Option.some.injEq] at hl + subst hl + exact h _ List.mem_cons_self + · exact ih (fun q hq => h q (List.mem_cons_of_mem _ hq)) hl + +theorem Facts.Hold.cons {ρ : Val} {K : Facts} (h : K.Hold ρ) {c : WExpr} {b : Bool} + (hc : c.eval ρ = 0 ↔ b = false) : Facts.Hold ρ ((c, b) :: K) := by + intro p hp + rcases List.mem_cons.mp hp with rfl | hp + · exact hc + · exact h p hp + +/-- The facts with one more: a word and its side, a disjunction taken as zero recorded as both +of its operands taken as zero. -/ +def Facts.add : Facts → WExpr → Bool → Facts + | K, .bin .or a b, false => Facts.add (Facts.add K a false) b false + | K, c, s => (c, s) :: K + +theorem Facts.Hold.add {ρ : Val} {K : Facts} (c : WExpr) (s : Bool) (h : K.Hold ρ) + (hc : c.eval ρ = 0 ↔ s = false) : (K.add c s).Hold ρ := by + induction K, c, s using Facts.add.induct with + | case1 K a b iha ihb => + have h0 := (or_eval_eq_zero ρ a b).mp (hc.mpr rfl) + simp only [Facts.add] + exact ihb (iha h (by simp [h0.1])) (by simp [h0.2]) + | case2 K c s hne => + rw [Facts.add] + · exact h.cons hc + · exact hne + +/-! ## Upper bounds -/ + +/-- The bound one fact gives a word: `gt e c` taken as zero bounds `e` by `c`. -/ +def factBound1 (p : WExpr × Bool) (e : WExpr) : Nat := + match p with + | (.bin .gt e' (.lit c), false) => if e' = e then c % wordSize else maxWord + | _ => maxWord + +/-- The bound the facts give a word. -/ +def Facts.bound : Facts → WExpr → Nat + | [], _ => maxWord + | p :: K, e => min (factBound1 p e) (Facts.bound K e) + +theorem factBound1_sound {ρ : Val} {p : WExpr × Bool} (hp : p.1.eval ρ = 0 ↔ p.2 = false) + (e : WExpr) : e.eval ρ ≤ factBound1 p e := by + unfold factBound1 + split + · rename_i e' c + split + · rename_i he + subst he + have h0 := hp.mpr rfl + simp only [WExpr.eval, BinOp.eval] at h0 + by_cases hc : c % wordSize < e'.eval ρ + · simp [hc] at h0 + · omega + · exact e.eval_le ρ + · exact e.eval_le ρ + +theorem Facts.bound_sound {ρ : Val} {K : Facts} (h : K.Hold ρ) (e : WExpr) : + e.eval ρ ≤ K.bound e := by + induction K with + | nil => exact e.eval_le ρ + | cons p K ih => + exact Nat.le_min.mpr ⟨factBound1_sound (h p List.mem_cons_self) e, + ih (fun q hq => h q (List.mem_cons_of_mem _ hq))⟩ + +/-- The least `k` from `k` on with `n < 2 ^ k`, within `f` steps. -/ +def bitLenGo (n : Nat) : Nat → Nat → Nat + | 0, k => k + | f + 1, k => if n < 2 ^ k then k else bitLenGo n f (k + 1) + +/-- The number of bits of `n`, for a word. -/ +def bitLen (n : Nat) : Nat := bitLenGo n 257 0 + +/-- A bound of `a ||| b` and `a ^^^ b` for `a ≤ x` and `b ≤ y`. -/ +def orBound (x y : Nat) : Nat := + if max x y < 2 ^ bitLen (max x y) then 2 ^ bitLen (max x y) - 1 else maxWord + +/-- The bound of a binary operation from bounds `x` and `y` of its operands. -/ +def binBound (K : Facts) (op : BinOp) (a b : WExpr) (x y : Nat) : Nat := + match op with + | .and => min x y + | .or => orBound x y + | .xor => orBound x y + | .add => if x + y < wordSize then x + y else maxWord + | .mul => if x * y < wordSize then x * y else maxWord + | .sub => if K.lookup (.bin .lt a b) = some false then x else maxWord + | .div => x + | .shr => + match a with + | .lit s => if s % wordSize < 256 then y / 2 ^ (s % wordSize) else 0 + | _ => maxWord + | .byte => 255 + | .lt => 1 + | .gt => 1 + | .eq => 1 + | .shl => maxWord + +/-- An upper bound of a word on the paths the facts hold on. -/ +def bound (K : Facts) : WExpr → Nat + | .lit n => n % wordSize + | .arg i => K.bound (.arg i) + | .init k => K.bound (.init k) + | .un .iszero _ => 1 + | .un .not a => K.bound (.un .not a) + | .bin op a b => min (K.bound (.bin op a b)) (binBound K op a b (bound K a) (bound K b)) + | .sinit k => K.bound (.sinit k) + | .sel _ a b => max (bound K a) (bound K b) + | .hash a b => K.bound (.hash a b) + | .caller => K.bound .caller + +theorem orBound_sound {a b x y : Nat} (ha : a ≤ x) (hb : b ≤ y) {f : Nat → Nat → Nat} + (hf : ∀ n, a < 2 ^ n → b < 2 ^ n → f a b < 2 ^ n) (v : Nat) (hv : v < wordSize) + (hvf : v ≤ f a b) : v ≤ orBound x y := by + unfold orBound + split + · rename_i hk + have h1 : a < 2 ^ bitLen (max x y) := by omega + have h2 : b < 2 ^ bitLen (max x y) := by omega + have := hf _ h1 h2 + omega + · simp only [maxWord]; omega + +theorem mod_word_le {v n : Nat} (h : v ≤ n) : v % wordSize ≤ n := + Nat.le_trans (Nat.mod_le _ _) h + +theorem binBound_sound {ρ : Val} {K : Facts} (h : K.Hold ρ) (op : BinOp) (a b : WExpr) (x y : Nat) + (hx : a.eval ρ ≤ x) (hy : b.eval ρ ≤ y) : + (WExpr.bin op a b).eval ρ ≤ binBound K op a b x y := by + have ha := a.eval_lt ρ + have hb := b.eval_lt ρ + have hle := (WExpr.bin op a b).eval_le ρ + have hlt := (WExpr.bin op a b).eval_lt ρ + cases op + case shr => + simp only [binBound] + split + · rename_i s + rw [show (WExpr.bin .shr (.lit s) b).eval ρ = + (if s % wordSize < 256 then b.eval ρ / 2 ^ (s % wordSize) else 0) % wordSize by + rfl] + split + · exact mod_word_le (Nat.div_le_div_right hy) + · simp + · exact hle + case sub => + simp only [binBound] + split + · rename_i hl + have h0 := (Facts.lookup_sound h hl).mpr rfl + simp only [WExpr.eval, BinOp.eval] at h0 hx ⊢ + by_cases hc : a.eval ρ < b.eval ρ + · simp [hc] at h0 + · rw [Nat.mod_mod, show a.eval ρ + (wordSize - b.eval ρ) = (a.eval ρ - b.eval ρ) + wordSize by omega, + Nat.add_mod_right, Nat.mod_eq_of_lt (by omega)] + omega + · exact hle + all_goals + simp only [WExpr.eval] at hle hlt ⊢ + generalize a.eval ρ = u at * + generalize b.eval ρ = w at * + simp only [binBound, BinOp.eval] at hle hlt ⊢ + case add => + split + · rw [Nat.mod_mod, Nat.mod_eq_of_lt (by omega)]; omega + · exact hle + case mul => + split + · rename_i hxy + have : u * w < wordSize := Nat.lt_of_le_of_lt (Nat.mul_le_mul hx hy) hxy + rw [Nat.mod_mod, Nat.mod_eq_of_lt this] + exact Nat.mul_le_mul hx hy + · exact hle + case div => + split + · simp + · exact mod_word_le (Nat.le_trans (Nat.div_le_self _ _) hx) + case lt => split <;> simp + case gt => split <;> simp + case eq => split <;> simp + case and => + exact Nat.le_min.mpr ⟨mod_word_le (Nat.le_trans Nat.and_le_left hx), + mod_word_le (Nat.le_trans Nat.and_le_right hy)⟩ + case or => exact orBound_sound hx hy (fun n h1 h2 => Nat.or_lt_two_pow h1 h2) _ hlt (Nat.mod_le _ _) + case xor => exact orBound_sound hx hy (fun n h1 h2 => Nat.xor_lt_two_pow h1 h2) _ hlt (Nat.mod_le _ _) + case shl => exact hle + case byte => + split + · have := Nat.mod_lt (w / 256 ^ (31 - u)) (show 0 < 256 by decide) + exact mod_word_le (by omega) + · simp + +theorem bound_sound {ρ : Val} {K : Facts} (h : K.Hold ρ) : ∀ e : WExpr, e.eval ρ ≤ bound K e + | .lit n => by simp [bound, WExpr.eval] + | .arg i => Facts.bound_sound h _ + | .init k => Facts.bound_sound h _ + | .un .iszero a => by + simp only [bound, WExpr.eval, UnOp.eval] + split <;> simp + | .un .not a => Facts.bound_sound h _ + | .bin op a b => Nat.le_min.mpr ⟨Facts.bound_sound h _, + binBound_sound h op a b _ _ (bound_sound h a) (bound_sound h b)⟩ + | .sinit k => Facts.bound_sound h _ + | .hash a b => Facts.bound_sound h _ + | .caller => Facts.bound_sound h _ + | .sel c a b => by + simp only [bound, WExpr.eval] + have := bound_sound h a + have := bound_sound h b + split <;> omega + +/-! ## Simplifying words -/ + +/-- `and a (lit m)`, without the mask when `m` is `2 ^ k - 1` and `a ≤ m`. -/ +def sAndLit (K : Facts) (a : WExpr) (m : Nat) : WExpr := + if m = 2 ^ bitLen m - 1 ∧ bound K a ≤ m then a else .bin .and a (.lit m) + +/-- `or a b` without a zero operand. -/ +def sOr (a b : WExpr) : WExpr := if a = .lit 0 then b else if b = .lit 0 then a else .bin .or a b + +/-- `and a b`, a constant mask through `sAndLit`. -/ +def sAnd (K : Facts) (a b : WExpr) : WExpr := + match b with + | .lit m => sAndLit K a (m % wordSize) + | _ => .bin .and a b + +/-- `gt a c`, zero when `a ≤ c`. -/ +def sGt (K : Facts) (a b : WExpr) : WExpr := + match b with + | .lit c => if bound K a ≤ c % wordSize then .lit 0 else .bin .gt a b + | _ => .bin .gt a b + +/-- `lt (add x y) x`, `uint256`'s add overflow check, zero when `x + y` cannot overflow. -/ +def sLt (K : Facts) (a b : WExpr) : WExpr := + match a with + | .bin .add x y => if x = b ∧ bound K x + bound K y < wordSize then .lit 0 else .bin .lt a b + | _ => .bin .lt a b + +/-- A shift by zero is its value. -/ +def sShift (op : BinOp) (a b : WExpr) : WExpr := if a = .lit 0 then b else .bin op a b + +/-- `byte i v` as `and (shr (8 * (31 - i)) v) 255`. -/ +def sByte (K : Facts) (a b : WExpr) : WExpr := + match a with + | .lit i => + if i % wordSize < 32 then + sAndLit K (if i % wordSize = 31 then b else .bin .shr (.lit (8 * (31 - i % wordSize))) b) 255 + else .bin .byte a b + | _ => .bin .byte a b + +/-- A binary operation on simplified operands. -/ +def sBin (K : Facts) (op : BinOp) (a b : WExpr) : WExpr := + match a, b with + | .lit x, .lit y => .lit (op.eval (x % wordSize) (y % wordSize) % wordSize) + | _, _ => + match op with + | .or => sOr a b + | .and => sAnd K a b + | .gt => sGt K a b + | .lt => sLt K a b + | .shl => sShift .shl a b + | .shr => sShift .shr a b + | .byte => sByte K a b + | .eq => if a = b then .lit 1 else .bin .eq a b + | _ => .bin op a b + +/-- A unary operation on a simplified operand: `uint256`'s multiplication overflow check +`iszero (or (iszero r) (eq (div (mul l r) r) l))` is zero when `l * r` cannot overflow. -/ +def sUn (K : Facts) (op : UnOp) (a : WExpr) : WExpr := + match a with + | .lit x => .lit (op.eval (x % wordSize) % wordSize) + | .bin .or (.un .iszero r) (.bin .eq (.bin .div (.bin .mul l r') r'') l') => + if op = .iszero ∧ r = r' ∧ r = r'' ∧ l = l' ∧ bound K l * bound K r < wordSize then .lit 0 + else .un op a + | _ => .un op a + +/-- A word simplified on the paths the facts hold on. -/ +def WExpr.simp (K : Facts) : WExpr → WExpr + | .lit n => .lit (n % wordSize) + | .arg i => .arg i + | .init k => .init k + | .un op a => sUn K op (a.simp K) + | .bin op a b => sBin K op (a.simp K) (b.simp K) + | .sinit k => .sinit (k.simp K) + | .sel c a b => + match (c.simp K).lit? with + | some n => if n % wordSize = 0 then b.simp K else a.simp K + | none => + match K.lookup (c.simp K) with + | some true => a.simp K + | some false => b.simp K + | none => .sel (c.simp K) (a.simp K) (b.simp K) + | .hash a b => .hash (a.simp K) (b.simp K) + | .caller => .caller + +theorem eval_sAndLit {ρ : Val} {K : Facts} (h : K.Hold ρ) (a : WExpr) {m : Nat} + (hm : m < wordSize) : (sAndLit K a m).eval ρ = (WExpr.bin .and a (.lit m)).eval ρ := by + unfold sAndLit + split + · rename_i hc + obtain ⟨hk, hb⟩ := hc + have hle := Nat.le_trans (bound_sound h a) hb + rw [eval_bin, eval_lit, Nat.mod_eq_of_lt hm] + generalize bitLen m = k at hk + subst hk + have hP := Nat.two_pow_pos k + simp only [BinOp.eval] + rw [Nat.and_two_pow_sub_one_eq_mod, Nat.mod_eq_of_lt (show a.eval ρ < 2 ^ k by omega), + Nat.mod_eq_of_lt (a.eval_lt ρ)] + · rfl + +theorem eval_sOr (ρ : Val) (a b : WExpr) : (sOr a b).eval ρ = (WExpr.bin .or a b).eval ρ := by + unfold sOr + split + · rename_i he; subst he + rw [eval_bin, eval_lit] + simp [BinOp.eval, Nat.mod_eq_of_lt (b.eval_lt ρ)] + · split + · rename_i _ he; subst he + rw [eval_bin, eval_lit] + simp [BinOp.eval, Nat.mod_eq_of_lt (a.eval_lt ρ)] + · rfl + +theorem eval_sAnd {ρ : Val} {K : Facts} (h : K.Hold ρ) (a b : WExpr) : + (sAnd K a b).eval ρ = (WExpr.bin .and a b).eval ρ := by + unfold sAnd + split + · next m => + rw [eval_sAndLit h a (Nat.mod_lt _ (by decide)), eval_bin, eval_bin, eval_lit, eval_lit, + Nat.mod_mod] + · rfl + +theorem eval_sGt {ρ : Val} {K : Facts} (h : K.Hold ρ) (a b : WExpr) : + (sGt K a b).eval ρ = (WExpr.bin .gt a b).eval ρ := by + unfold sGt + split + · next c => + split + · rename_i hc + have := bound_sound h a + rw [eval_bin, eval_lit, eval_lit] + simp only [BinOp.eval] + split + · omega + · rfl + · rfl + · rfl + +theorem eval_sLt {ρ : Val} {K : Facts} (h : K.Hold ρ) (a b : WExpr) : + (sLt K a b).eval ρ = (WExpr.bin .lt a b).eval ρ := by + unfold sLt + split + · next x y => + split + · rename_i hc + obtain ⟨rfl, hc⟩ := hc + have hx := bound_sound h x + have hy := bound_sound h y + rw [eval_bin, eval_bin, eval_lit] + simp only [BinOp.eval, Nat.mod_mod] + rw [Nat.mod_eq_of_lt (show x.eval ρ + y.eval ρ < wordSize by omega)] + split + · omega + · rfl + · rfl + · rfl + +theorem eval_sShift (ρ : Val) (op : BinOp) (hop : op = .shl ∨ op = .shr) (a b : WExpr) : + (sShift op a b).eval ρ = (WExpr.bin op a b).eval ρ := by + unfold sShift + split + · rename_i he; subst he + rw [eval_bin, eval_lit] + rcases hop with rfl | rfl <;> simp [BinOp.eval, Nat.mod_eq_of_lt (b.eval_lt ρ)] + · rfl + +theorem eval_sByte {ρ : Val} {K : Facts} (h : K.Hold ρ) (a b : WExpr) : + (sByte K a b).eval ρ = (WExpr.bin .byte a b).eval ρ := by + have hb := b.eval_lt ρ + unfold sByte + split + · next i => + split + · rename_i hi + rw [eval_sAndLit h _ (by decide)] + have hpow : (256 : Nat) ^ (31 - i % wordSize) = 2 ^ (8 * (31 - i % wordSize)) := by + rw [Nat.pow_mul] + have hlt8 : 8 * (31 - i % wordSize) < 256 := by omega + have h255 : (255 : Nat) % wordSize = 2 ^ 8 - 1 := by decide + have hbyte : ∀ v : Nat, v % 2 ^ 8 % wordSize = v % 2 ^ 8 := fun v => + Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (by decide)) + rw [eval_bin, eval_bin, eval_lit, eval_lit, h255] + simp only [BinOp.eval, Nat.and_two_pow_sub_one_eq_mod] + rw [if_pos hi] + split + · rename_i h31 + rw [h31, Nat.sub_self, Nat.pow_zero, Nat.div_one] + · rw [eval_bin, eval_lit, + Nat.mod_eq_of_lt (show 8 * (31 - i % wordSize) < wordSize from Nat.lt_of_lt_of_le hlt8 (by decide))] + simp only [BinOp.eval] + rw [if_pos hlt8, Nat.mod_eq_of_lt (Nat.lt_of_le_of_lt (Nat.div_le_self _ _) hb), hpow, + show (256 : Nat) = 2 ^ 8 by decide, hbyte] + · rfl + · rfl + +theorem eval_sBin {ρ : Val} {K : Facts} (h : K.Hold ρ) (op : BinOp) (a b : WExpr) : + (sBin K op a b).eval ρ = (WExpr.bin op a b).eval ρ := by + unfold sBin + split + · simp [WExpr.eval, Nat.mod_mod] + · cases op + case or => exact eval_sOr ρ a b + case and => exact eval_sAnd h a b + case gt => exact eval_sGt h a b + case lt => exact eval_sLt h a b + case shl => exact eval_sShift ρ .shl (.inl rfl) a b + case shr => exact eval_sShift ρ .shr (.inr rfl) a b + case byte => exact eval_sByte h a b + case eq => + show (if a = b then WExpr.lit 1 else .bin .eq a b).eval ρ = _ + by_cases hab : a = b + · subst hab; simp [WExpr.eval, BinOp.eval] + · rw [if_neg hab] + all_goals rfl + +theorem eval_sUn {ρ : Val} {K : Facts} (h : K.Hold ρ) (op : UnOp) (a : WExpr) : + (sUn K op a).eval ρ = (WExpr.un op a).eval ρ := by + unfold sUn + split + · simp [WExpr.eval, Nat.mod_mod] + · next r l r' r'' l' => + split + · rename_i hc + obtain ⟨rfl, rfl, rfl, rfl, hb⟩ := hc + have hl := bound_sound h l + have hr := bound_sound h r + have hlr : l.eval ρ * r.eval ρ < wordSize := + Nat.lt_of_le_of_lt (Nat.mul_le_mul hl hr) hb + have hlt := l.eval_lt ρ + have hor : (WExpr.bin .or (.un .iszero r) (.bin .eq (.bin .div (.bin .mul l r) r) l)).eval ρ + ≠ 0 := by + rw [Ne, or_eval_eq_zero] + intro ⟨h1, h2⟩ + by_cases hw : r.eval ρ = 0 + · simp [WExpr.eval, UnOp.eval, hw] at h1 + · have : (WExpr.bin .eq (.bin .div (.bin .mul l r) r) l).eval ρ = 1 := by + simp only [WExpr.eval, BinOp.eval, Nat.mod_mod, hw, ↓reduceIte, Nat.mod_eq_of_lt hlr, + Nat.mul_div_cancel _ (Nat.pos_of_ne_zero hw), Nat.mod_eq_of_lt hlt] + rfl + omega + rw [show (WExpr.un .iszero (.bin .or (.un .iszero r) + (.bin .eq (.bin .div (.bin .mul l r) r) l))).eval ρ = + (if (WExpr.bin .or (.un .iszero r) (.bin .eq (.bin .div (.bin .mul l r) r) l)).eval ρ = 0 + then 1 else 0) % wordSize from rfl, if_neg hor] + rfl + · rfl + · rfl + +theorem WExpr.eval_simp {ρ : Val} {K : Facts} (h : K.Hold ρ) : ∀ e : WExpr, (e.simp K).eval ρ = e.eval ρ + | .lit n => by simp [WExpr.simp, WExpr.eval, Nat.mod_mod] + | .arg i => rfl + | .init k => rfl + | .un op a => by + rw [WExpr.simp, eval_sUn h] + simp only [WExpr.eval, WExpr.eval_simp h a] + | .bin op a b => by + rw [WExpr.simp, eval_sBin h] + simp only [WExpr.eval, WExpr.eval_simp h a, WExpr.eval_simp h b] + | .sinit k => by simp only [WExpr.simp, WExpr.eval, WExpr.eval_simp h k] + | .hash a b => by simp only [WExpr.simp, WExpr.eval, WExpr.eval_simp h a, WExpr.eval_simp h b] + | .caller => rfl + | .sel c a b => by + have hc := WExpr.eval_simp h c + simp only [WExpr.simp] + split + · rename_i n hn + rw [WExpr.eq_of_lit? hn] at hc + simp only [WExpr.eval] at hc + simp only [WExpr.eval, ← hc] + split + · exact WExpr.eval_simp h b + · exact WExpr.eval_simp h a + · split + · rename_i hl + have := Facts.lookup_sound h hl + simp only [WExpr.eval, ← hc] + rw [if_neg (by simpa using this)] + exact WExpr.eval_simp h a + · rename_i hl + have := Facts.lookup_sound h hl + simp only [WExpr.eval, ← hc] + rw [if_pos (by simpa using this)] + exact WExpr.eval_simp h b + · simp only [WExpr.eval, hc, WExpr.eval_simp h a, WExpr.eval_simp h b] + +/-! ## Simplifying trees -/ + +/-- A byte of output, its word simplified. -/ +def OByte.simp (K : Facts) : OByte → OByte + | .lit b => .lit (b % 256) + | .byteOf e i => + match e.simp K with + | .lit n => .lit (n % wordSize / 256 ^ (31 - i) % 256) + | e' => .byteOf e' i + +theorem OByte.eval_simp {ρ : Val} {K : Facts} (h : K.Hold ρ) (b : OByte) : + (b.simp K).eval ρ = b.eval ρ := by + cases b with + | lit b => simp [OByte.simp, OByte.eval, Nat.mod_mod] + | byteOf e i => + have he := WExpr.eval_simp h e + simp only [OByte.simp] + split + · rename_i n hn + rw [hn] at he + simp only [OByte.eval, ← he, WExpr.eval, Nat.mod_mod] + · simp only [OByte.eval, he] + +/-- A tree simplified on the paths the facts hold on: every word simplified, a branch on a +constant or on a word the facts decide takes its side, and each side of any other branch is +simplified with its word's side as one more fact. -/ +def Tree.simp (K : Facts) : Tree → Tree + | .halt ok out ws ls => + .halt ok (out.map (OByte.simp K)) (ws.mapW (WExpr.simp K)) + (ls.map (Log.mapL (WExpr.simp K) (OByte.simp K))) + | .ite c t e => + match (c.simp K).lit? with + | some n => if n % wordSize = 0 then e.simp K else t.simp K + | none => + match K.lookup (c.simp K) with + | some true => t.simp K + | some false => e.simp K + | none => .ite (c.simp K) (t.simp ((c.simp K, true) :: K)) (e.simp ((c.simp K, false) :: K)) + +theorem Tree.eval_simp {ρ : Val} : ∀ {K : Facts}, K.Hold ρ → ∀ T : Tree, (T.simp K).eval ρ = T.eval ρ + | K, h, .halt ok out ws ls => by + simp only [Tree.simp, Tree.eval, List.map_map, Writes.store_mapW ρ _ (WExpr.eval_simp h)] + congr 2 + · funext b + exact OByte.eval_simp h b + · congr 1 + funext l + exact Log.eval_mapL ρ _ _ (WExpr.eval_simp h) (OByte.eval_simp h) l + | K, h, .ite c t e => by + have hc := WExpr.eval_simp h c + simp only [Tree.simp] + split + · rename_i n hn + rw [WExpr.eq_of_lit? hn] at hc + simp only [WExpr.eval] at hc + simp only [Tree.eval, ← hc] + split + · exact Tree.eval_simp h e + · exact Tree.eval_simp h t + · split + · rename_i hl + have := Facts.lookup_sound h hl + simp only [Tree.eval, ← hc] + rw [if_neg (by simpa using this)] + exact Tree.eval_simp h t + · rename_i hl + have := Facts.lookup_sound h hl + simp only [Tree.eval, ← hc] + rw [if_pos (by simpa using this)] + exact Tree.eval_simp h e + · simp only [Tree.eval, hc] + split + · rename_i h0 + exact Tree.eval_simp (h.cons (by simp [hc, h0])) e + · rename_i h0 + exact Tree.eval_simp (h.cons (by simp [hc, h0])) t + +/-! ## Negations -/ + +/-- A branch on `c`, a negation `iszero a`, `eq a 0` or `eq 0 a` turned into a branch on `a` +with its sides swapped, a branch on `not a` (zero exactly when `a` is the largest word) into a +branch on `eq a maxWord` with its sides swapped, and a disjunction split as `splitCond` does. -/ +def splitNeg : WExpr → Tree → Tree → Tree + | .un .iszero a, t, e => splitNeg a e t + | .bin .eq a (.lit 0), t, e => splitNeg a e t + | .bin .eq (.lit 0) a, t, e => splitNeg a e t + | .bin .or a b, t, e => splitNeg a t (splitNeg b t e) + | .un .not a, t, e => .ite (.bin .eq a (.lit maxWord)) e t + | c, t, e => .ite c t e + +/-- Every branch of a tree, its negations and disjunctions split. -/ +def Tree.splitNeg : Tree → Tree + | .halt ok out ws ls => .halt ok out ws ls + | .ite c t e => Generic.splitNeg c t.splitNeg e.splitNeg + +theorem splitNeg_eval (ρ : Val) (c : WExpr) (t e : Tree) : + (splitNeg c t e).eval ρ = if c.eval ρ = 0 then e.eval ρ else t.eval ρ := by + fun_induction splitNeg c t e with + | case1 a t e ih => + rw [ih] + have ha := a.eval_lt ρ + by_cases h : a.eval ρ = 0 <;> simp [WExpr.eval, UnOp.eval, h] + | case2 a t e ih => + rw [ih] + by_cases h : a.eval ρ = 0 <;> simp [WExpr.eval, BinOp.eval, h] + | case3 a t e _ ih => + rw [ih] + have : (0 : Nat) = a.eval ρ ↔ a.eval ρ = 0 := eq_comm + by_cases h : a.eval ρ = 0 <;> simp [WExpr.eval, BinOp.eval, h, this] + | case4 a b t e ihb iha => + rw [iha, ihb] + simp only [or_eval_eq_zero] + by_cases ha : a.eval ρ = 0 <;> by_cases hb : b.eval ρ = 0 <;> simp [ha, hb] + | case5 a t e => + have ha := a.eval_le ρ + have hm : maxWord % wordSize = maxWord := Nat.mod_eq_of_lt (by decide) + simp only [Tree.eval, WExpr.eval, BinOp.eval, UnOp.eval, hm] + by_cases h : a.eval ρ = maxWord + · simp [h] + · have hlt := a.eval_lt ρ + have h3 : (wordSize - 1 - a.eval ρ) % wordSize ≠ 0 := by + rw [Nat.mod_eq_of_lt (by omega)] + simp only [maxWord] at h + omega + have h4 : (if a.eval ρ = maxWord then 1 else 0) % wordSize = 0 := by + split + · exact absurd ‹_› h + · rfl + rw [h4, if_pos rfl] + exact (ite_cond_eq_false _ _ (eq_false h3)).symm + | case6 => rfl + +theorem Tree.eval_splitNeg (ρ : Val) : ∀ T : Tree, T.splitNeg.eval ρ = T.eval ρ + | .halt _ _ _ _ => rfl + | .ite c t e => by + rw [Tree.splitNeg, splitNeg_eval, Tree.eval_splitNeg ρ t, Tree.eval_splitNeg ρ e] + rfl + +/-! ## The canonical form -/ + +/-- The canonical form of a tree: constants folded (`Tree.norm`), disjunctions split, and +words simplified along each path; then negations and the disjunctions the simplification left +split (`Tree.splitNeg`), and the words simplified again along the new paths. -/ +def Tree.canon (T : Tree) : Tree := (((T.norm.split).simp []).splitNeg).simp [] + +theorem Tree.eval_canon (ρ : Val) (T : Tree) : T.canon.eval ρ = T.eval ρ := by + rw [Tree.canon, Tree.eval_simp (fun _ h => absurd h (List.not_mem_nil)), Tree.eval_splitNeg, + Tree.eval_simp (fun _ h => absurd h (List.not_mem_nil)), Tree.eval_split, Tree.eval_norm] + +end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Generic/Source.lean b/SolidCore/Refinement/Generic/Source.lean new file mode 100644 index 00000000..cd6af2fd --- /dev/null +++ b/SolidCore/Refinement/Generic/Source.lean @@ -0,0 +1,1313 @@ +import SolidCore.Solidity.Checked +import SolidCore.Refinement.Generic.Tree +import SolidCore.Refinement.Generic.Packed + +/-! +# Expressions of the fragment: erasure and simulation + +`eraseExpr` erases a SolidCore expression of the fragment (word literals, locals, unsigned +cleanups `uintCleanup b` and truncating casts `uintCast b` for `0 < b ≤ 256`, the latter to +`and v (2 ^ b - 1)`, checked `+`, `-`, `*`, the bitwise `&`, `|`, `^`, the comparisons `<`, +`>`, `==`, and reads of unsigned storage fields, alone in their slot or packed with others) to +its overflow conditions and its word, over a symbolic state of locals and storage writes +(`SymState`). Each overflow condition is a word whose being nonzero makes +SolidCore revert with `Panic(0x11)`: solar's check of a checked `uint256` operation +(`overflow`), or a narrow cleanup's range check `gt v (2 ^ b - 1)`. A field of `bytes` bytes +at byte offset `off` of its slot reads as `readField` (a shift and a mask) and is written by +`writeField` (the slot's other bits kept by `clearMask`, the value masked and shifted in). +`eval_erase` proves that SolidCore's interpreter evaluates the expression to `exprResult`: +the panic when a condition holds, else the word, whenever the runtime holds the symbolic state +(`ExprRel`). +-/ + +namespace SolidCore.Refinement.Generic +open SolidCore.Solidity.Source + +/-- A storage field the fragment reads and writes: an unsigned scalar (`uint256` in SolidCore's +core) of `packedBytes` bytes at byte offset `packedOffset` of its slot, not transient. -/ +def fieldOk (f : StorageField) : Bool := + (match f.layout? with | some (.scalar .uint256) => true | _ => false) && !f.transient && + decide (0 < f.packedBytes) && decide (f.packedOffset + f.packedBytes ≤ 32) && + decide (f.slot < wordSize) + +/-- A mapping the fragment reads and writes: from `address` or `uint256` keys to `uint256` +words, not transient. -/ +def mapOk (f : StorageField) : Bool := + (match f.layout? with + | some (.mapping .address (.scalar .uint256)) => true + | some (.mapping .uint256 (.scalar .uint256)) => true + | _ => false) && !f.transient && decide (f.slot < wordSize) + +/-- The slot of the mapping `x`, when the fragment reads and writes it. -/ +def mapOf? (fields : List StorageField) (x : String) : Option Nat := + match fields.find? (fun f => f.name == x) with + | some f => if mapOk f then some f.slot else none + | none => none + +/-- A mapping from `address` or `uint256` keys to `bool` values, not transient. -/ +def boolMapOk (f : StorageField) : Bool := + (match f.layout? with + | some (.mapping .address (.scalar .bool)) => true + | some (.mapping .uint256 (.scalar .bool)) => true + | _ => false) && !f.transient && decide (f.slot < wordSize) + +/-- The slot of the mapping to `bool` `x`, when the fragment reads and writes it. -/ +def boolMapOf? (fields : List StorageField) (x : String) : Option Nat := + match fields.find? (fun f => f.name == x) with + | some f => if boolMapOk f then some f.slot else none + | none => none + +/-- A mapping from `address` keys to mappings from `address` keys to `uint256` words, as +an ERC-20 allowance table, not transient. -/ +def map2Ok (f : StorageField) : Bool := + (match f.layout? with + | some (.mapping .address (.mapping .address (.scalar .uint256))) => true + | _ => false) && !f.transient && decide (f.slot < wordSize) + +/-- The slot of the nested mapping `x`, when the fragment reads and writes it. -/ +def map2Of? (fields : List StorageField) (x : String) : Option Nat := + match fields.find? (fun f => f.name == x) with + | some f => if map2Ok f then some f.slot else none + | none => none + +/-- An `address` field the fragment reads: 20 bytes at byte offset `packedOffset` of its +slot, not transient. -/ +def addrFieldOk (f : StorageField) : Bool := + (match f.layout? with | some (.scalar .address) => true | _ => false) && !f.transient && + decide (f.packedBytes = 20) && decide (f.packedOffset + 20 ≤ 32) && decide (f.slot < wordSize) + +/-- The slot and byte offset of the `address` field `x`, when the fragment reads it. -/ +def addrFieldOf? (fields : List StorageField) (x : String) : Option (Nat × Nat) := + match fields.find? (fun f => f.name == x) with + | some f => if addrFieldOk f then some (f.slot, f.packedOffset) else none + | none => none + +/-- The `bool` SolidCore reads from a storage word: whether its low byte is not zero, spelled +as solar's `ne (and w 255) 0`. -/ +def boolOfWord (w : WExpr) : WExpr := .un .iszero (.bin .eq (.bin .and w (.lit 255)) (.lit 0)) + +/-- The slot, byte offset and size of the storage field `x`, when the fragment reads and +writes it. -/ +def fieldOf? (fields : List StorageField) (x : String) : Option (Nat × Nat × Nat) := + match fields.find? (fun f => f.name == x) with + | some f => if fieldOk f then some (f.slot, f.packedOffset, f.packedBytes) else none + | none => none + +/-- The mask of a field of `bytes` bytes. -/ +def fieldMask (bytes : Nat) : Nat := 2 ^ (bytes * 8) - 1 + +/-- The field at byte offset `off` of `bytes` bytes of the slot word `w`: the word itself +when the field fills its slot, else `and (shr (off * 8) w) mask` (no shift at offset 0). -/ +def readField (w : WExpr) (off bytes : Nat) : WExpr := + if off = 0 ∧ bytes = 32 then w + else if off = 0 then .bin .and w (.lit (fieldMask bytes)) + else .bin .and (.bin .shr (.lit (off * 8)) w) (.lit (fieldMask bytes)) + +/-- The slot word `old` with the field at byte offset `off` of `bytes` bytes set to `v`: +`v` itself when the field fills its slot, else +`or (and old (clearMask (off * 8) (bytes * 8))) (shl (off * 8) (and v mask))`. -/ +def writeField (old v : WExpr) (off bytes : Nat) : WExpr := + if off = 0 ∧ bytes = 32 then v + else + let val := WExpr.bin .and v (.lit (fieldMask bytes)) + .bin .or (.bin .and old (.lit (clearMask (off * 8) (bytes * 8)))) + (if off = 0 then val else .bin .shl (.lit (off * 8)) val) + +/-- What SolidCore reads from the field in the slot word `w`. -/ +def fieldValue (w off bytes : Nat) : Nat := + if off = 0 ∧ bytes = 32 then w else w / 2 ^ (off * 8) % 2 ^ (bytes * 8) + +/-- What SolidCore leaves in the slot word `cur` when it writes `v` to the field. -/ +def fieldWrite (cur v off bytes : Nat) : Nat := + if off = 0 ∧ bytes = 32 then v + else (cur &&& clearMask (off * 8) (bytes * 8)) ||| ((v % 2 ^ (bytes * 8)) <<< (off * 8)) + +/-- A local the fragment knows: its name and its word. -/ +abbrev Locals := List (String × WExpr) + +def Locals.get? : Locals → String → Option WExpr + | [], _ => none + | (y, e) :: rest, x => if y = x then some e else Locals.get? rest x + +/-- The locals of a function body by scope, the innermost first and the function's frame last, +as SolidCore's `LocalEnv` holds them. -/ +abbrev Scopes := List Locals + +/-- The word of the local `x`, from the innermost scope that has it. -/ +def Scopes.get? : Scopes → String → Option WExpr + | [], _ => none + | L :: rest, x => + match L.get? x with + | some e => some e + | none => Scopes.get? rest x + +/-- The symbolic state of a function body: its locals by scope, its storage writes so far and +the logs it emitted, the oldest first. -/ +structure SymState where + scopes : Scopes + writes : Writes + logs : List Log + /-- The word `msg.sender` erases to: `callerWord`, or the symbolic `WExpr.caller`. -/ + caller : WExpr := .lit callerWord + deriving DecidableEq, Repr + +/-- SolidCore's slot of a mapping's entry: Keccak-256 of the key's word and the mapping's slot, +as `mappingStorageSlot slot key` computes it. -/ +def solHash (key slot : Nat) : Nat := keccakWord (storageWordBytes key ++ storageWordBytes slot) + +theorem mappingStorageSlot_eq (slot key : Nat) : mappingStorageSlot slot key = solHash key slot := rfl + +/-- The overflow condition of a checked unsigned operation, as solar lowers it. -/ +def overflow : BinOp → WExpr → WExpr → Option WExpr + | .add, l, r => some (.bin .lt (.bin .add l r) l) + | .sub, l, r => some (.bin .lt l r) + | .mul, l, r => some (.un .iszero (.bin .or (.un .iszero r) (.bin .eq (.bin .div (.bin .mul l r) r) l))) + | _, _, _ => none + +/-- The fragment's binary operators: SolidCore's operator and the word operation. -/ +def binOf : BinaryOp → Option BinOp + | .add => some .add + | .sub => some .sub + | .mul => some .mul + | .lt => some .lt + | .gt => some .gt + | .eq => some .eq + | .bitAnd => some .and + | .bitOr => some .or + | .bitXor => some .xor + | _ => none + +/-- The fragment's negated comparisons: `a >= b` is `iszero (lt a b)`, `a <= b` is +`iszero (gt a b)`, `a != b` is `iszero (eq a b)`. -/ +def negOf : BinaryOp → Option BinOp + | .ge => some .lt + | .le => some .gt + | .ne => some .eq + | _ => none + +/-- An atom of the fragment: a word literal, a local or `msg.sender`, erased to its word. -/ +def eraseAtom (S : SymState) : Expr → Option WExpr + | .word n => some (.lit n) + | .var x => Scopes.get? S.scopes x + | .caller => some S.caller + | _ => none + +/-- `uint256(keccak256(abi.encode(x, y)))` of two `uint256` atoms: the hash of their two words, +`WExpr.hash`, which SolidCore computes as its slot hash `solHash` (Keccak-256 of the 64 bytes of +the two words) and the module as the oracle's Keccak-256 of the same 64 bytes of memory. -/ +def hashPair? (S : SymState) (b : Nat) (e : Expr) : Option WExpr := + if b = 256 then + match e with + | .keccak256 (.encode .plain none [] [.uint256, .uint256] [x, y]) => + match eraseAtom S x, eraseAtom S y with + | some vx, some vy => some (.hash vx vy) + | _, _ => none + | _ => none + else none + +/-- The erasure of an expression of the fragment: the overflow conditions it checks, each +reverting with `Panic(0x11)` when not zero, and its word. -/ +def eraseExpr (fields : List StorageField) (S : SymState) : Expr → Option (List WExpr × WExpr) + | .word n => some ([], .lit n) + | .var x => (Scopes.get? S.scopes x).map fun e => ([], e) + | .caller => some ([], S.caller) + | .castOp .uintCleanup b e => do + let (gs, v) ← eraseExpr fields S e + if b = 256 then some (gs, v) + else if 0 < b ∧ b < 256 then some (gs ++ [.bin .gt v (.lit (2 ^ b - 1))], v) + else none + | .castOp .uintCast b e => + match hashPair? S b e with + | some v => some ([], v) + | none => do + let (gs, v) ← eraseExpr fields S e + if b = 256 then some (gs, v) + else if 0 < b ∧ b < 256 then some (gs, .bin .and v (.lit (2 ^ b - 1))) + else none + | .binary op l r => + match binOf op with + | some o => do + let (gl, vl) ← eraseExpr fields S l + let (gr, vr) ← eraseExpr fields S r + match overflow o vl vr with + | some g => some (gl ++ gr ++ [g], .bin o vl vr) + | none => some (gl ++ gr, .bin o vl vr) + | none => do + let o ← negOf op + let (gl, vl) ← eraseExpr fields S l + let (gr, vr) ← eraseExpr fields S r + some (gl ++ gr, .un .iszero (.bin o vl vr)) + | .unary .logicalNot e => do + let (gs, v) ← eraseExpr fields S e + some (gs, .un .iszero v) + | .storageRead .header x [] => + match fieldOf? fields x with + | some (k, off, bytes) => some ([], readField (S.writes.read (.lit k)) off bytes) + | none => (addrFieldOf? fields x).map fun (k, off) => ([], readField (S.writes.read (.lit k)) off 20) + | .storageRead .ref x [] => + match fieldOf? fields x with + | some (k, off, bytes) => some ([], readField (S.writes.read (.lit k)) off bytes) + | none => (addrFieldOf? fields x).map fun (k, off) => ([], readField (S.writes.read (.lit k)) off 20) + | .storageRead .element x [idx] => + match mapOf? fields x with + | some k => do + let (gs, v) ← eraseExpr fields S idx + some (gs, S.writes.read (.hash v (.lit k))) + | none => do + let k ← boolMapOf? fields x + let (gs, v) ← eraseExpr fields S idx + some (gs, boolOfWord (S.writes.read (.hash v (.lit k)))) + | .index (.storageRead .element x [i1]) i2 => do + let k ← map2Of? fields x + let (g1, v1) ← eraseExpr fields S i1 + let (g2, v2) ← eraseExpr fields S i2 + some (g1 ++ g2, S.writes.read (.hash v2 (.hash v1 (.lit k)))) + | _ => none + + +/-! ## Words: SolidCore's word operations on words below `2 ^ 256` -/ + +theorem norm_lt {a : Nat} (h : a < wordSize) : SolidCore.Solidity.Shared.norm a = a := by + simp only [SolidCore.Solidity.Shared.norm, SolidCore.Solidity.Shared.wordModulus] + exact Nat.mod_eq_of_lt h + +theorem size_eq : EvmYul.UInt256.size = wordSize := rfl +theorem modulus_eq : SolidCore.Solidity.Shared.wordModulus = wordSize := rfl + +theorem toNat_ofNat_u256 (n : Nat) : (EvmYul.UInt256.ofNat n).toNat = n % wordSize := + Fin.val_ofNat _ _ +theorem toNat_add_u256 (x y : EvmYul.UInt256) : (x.add y).toNat = (x.toNat + y.toNat) % wordSize := + Fin.val_add _ _ +theorem toNat_sub_u256 (x y : EvmYul.UInt256) : + (x.sub y).toNat = (wordSize - y.toNat + x.toNat) % wordSize := + Fin.val_sub _ _ +theorem toNat_mul_u256 (x y : EvmYul.UInt256) : (x.mul y).toNat = (x.toNat * y.toNat) % wordSize := + Fin.val_mul _ _ + +open SolidCore.Solidity.Shared in +theorem addWord_eq (a b : Nat) : addWord a b = (a + b) % wordSize := by + simp only [addWord, liftEvmBinary, ofEvmWord, toEvmWord, norm, modulus_eq, toNat_add_u256, + toNat_ofNat_u256, Nat.mod_mod, Nat.add_mod_mod, Nat.mod_add_mod] + +open SolidCore.Solidity.Shared in +theorem subWord_eq (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + subWord a b = (a + (wordSize - b)) % wordSize := by + simp only [subWord, liftEvmBinary, ofEvmWord, toEvmWord, norm, modulus_eq, toNat_sub_u256, + toNat_ofNat_u256, Nat.mod_mod, Nat.mod_eq_of_lt hb, Nat.mod_eq_of_lt ha] + rw [Nat.add_comm] + +open SolidCore.Solidity.Shared in +theorem mulWord_eq (a b : Nat) : mulWord a b = (a * b) % wordSize := by + simp only [mulWord, liftEvmBinary, ofEvmWord, toEvmWord, norm, modulus_eq, toNat_mul_u256, + toNat_ofNat_u256, Nat.mod_mod, Nat.mul_mod_mod, Nat.mod_mul_mod] + +open SolidCore.Solidity.Shared in +theorem ltWord_eq (a b : Nat) : ltWord a b = if a % wordSize < b % wordSize then 1 else 0 := by + have key : (EvmYul.UInt256.ofNat (norm a) < EvmYul.UInt256.ofNat (norm b)) ↔ + a % wordSize < b % wordSize := by + show (EvmYul.UInt256.ofNat (norm a)).toNat < (EvmYul.UInt256.ofNat (norm b)).toNat ↔ _ + rw [toNat_ofNat_u256, toNat_ofNat_u256] + simp [norm, modulus_eq] + unfold ltWord liftEvmBinary ofEvmWord toEvmWord EvmYul.UInt256.lt EvmYul.UInt256.fromBool + Bool.toUInt256 + by_cases h : a % wordSize < b % wordSize + · rw [ite_eq_left_of_eq_true _ _ (eq_true (decide_eq_true (key.mpr h))), ite_eq_left_of_eq_true _ _ (eq_true h)]; rfl + · rw [ite_eq_right_of_eq_false _ _ (eq_false (by simpa using fun h' => h (key.mp h'))), ite_eq_right_of_eq_false _ _ (eq_false h)]; rfl + +open SolidCore.Solidity.Shared in +theorem gtWord_eq (a b : Nat) : gtWord a b = if b % wordSize < a % wordSize then 1 else 0 := by + rw [← ltWord_eq]; rfl + +theorem apply_add (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply true .add (.word a) (.word b) = + if wordSize ≤ a + b then .error (.panic 0x11) else .ok (.word ((a + b) % wordSize)) := by + by_cases h : wordSize ≤ a + b <;> + simp [BinaryOp.apply, Value.forceAbiLazy, BinaryOp.applyWord, checkedAdd, norm_lt ha, norm_lt hb, + bind, Except.bind, Functor.map, Except.map, wordModulus, RevertData.overflow, addWord_eq, h, + size_eq, modulus_eq] + +theorem apply_sub (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply true .sub (.word a) (.word b) = + if a < b then .error (.panic 0x11) else .ok (.word ((a + (wordSize - b)) % wordSize)) := by + by_cases h : a < b <;> + simp [BinaryOp.apply, Value.forceAbiLazy, BinaryOp.applyWord, checkedSub, norm_lt ha, norm_lt hb, + bind, Except.bind, Functor.map, Except.map, RevertData.overflow, subWord_eq a b ha hb, h] + +theorem apply_mul (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply true .mul (.word a) (.word b) = + if wordSize ≤ a * b then .error (.panic 0x11) else .ok (.word ((a * b) % wordSize)) := by + by_cases h : wordSize ≤ a * b <;> + simp [BinaryOp.apply, Value.forceAbiLazy, BinaryOp.applyWord, checkedMul, norm_lt ha, norm_lt hb, + bind, Except.bind, Functor.map, Except.map, wordModulus, RevertData.overflow, mulWord_eq, h, + modulus_eq] + +theorem apply_lt (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply true .lt (.word a) (.word b) = .ok (.word (if a < b then 1 else 0)) := by + simp [BinaryOp.apply, Value.forceAbiLazy, BinaryOp.applyWord, bind, Except.bind, Functor.map, + Except.map, ltWord_eq, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb] + +theorem apply_gt (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply true .gt (.word a) (.word b) = .ok (.word (if b < a then 1 else 0)) := by + simp [BinaryOp.apply, Value.forceAbiLazy, BinaryOp.applyWord, bind, Except.bind, Functor.map, + Except.map, gtWord_eq, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb] + +theorem apply_eq (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply true .eq (.word a) (.word b) = .ok (.word (if a = b then 1 else 0)) := by + simp [BinaryOp.apply, Value.forceAbiLazy, bind, Except.bind, Functor.map, Except.map, boolWord, wordEq, + norm_lt ha, norm_lt hb] + +theorem apply_ne (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply true .ne (.word a) (.word b) = .ok (.word (if a = b then 0 else 1)) := by + by_cases h : a = b <;> + simp [BinaryOp.apply, Value.forceAbiLazy, bind, Except.bind, Functor.map, Except.map, boolWord, wordEq, + norm_lt ha, norm_lt hb, h] + +theorem apply_ge (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply true .ge (.word a) (.word b) = .ok (.word (if a < b then 0 else 1)) := by + by_cases h : a < b <;> + simp [BinaryOp.apply, Value.forceAbiLazy, BinaryOp.applyWord, bind, Except.bind, Functor.map, + Except.map, ltWord_eq, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb, boolWord, wordTruthy, h, + SolidCore.Solidity.Shared.norm, modulus_eq] + +theorem apply_le (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply true .le (.word a) (.word b) = .ok (.word (if b < a then 0 else 1)) := by + by_cases h : b < a <;> + simp [BinaryOp.apply, Value.forceAbiLazy, BinaryOp.applyWord, bind, Except.bind, Functor.map, + Except.map, gtWord_eq, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb, boolWord, wordTruthy, h, + SolidCore.Solidity.Shared.norm, modulus_eq] + +/-- SolidCore's \`!\` on a word is \`iszero\`. -/ +theorem apply_not (a : Nat) (ha : a < wordSize) : + UnaryOp.apply true .logicalNot (.word a) = .ok (.word (if a = 0 then 1 else 0)) := by + by_cases h : a = 0 <;> + simp [UnaryOp.apply, boolWord, wordTruthy, SolidCore.Solidity.Shared.norm, modulus_eq, + Nat.mod_eq_of_lt ha, h] + +theorem fieldOk_spec {f : StorageField} (h : fieldOk f = true) : + f.layout? = some (.scalar .uint256) ∧ f.transient = false ∧ 0 < f.packedBytes ∧ + f.packedOffset + f.packedBytes ≤ 32 ∧ f.slot < wordSize := by + unfold fieldOk at h + simp only [Bool.and_eq_true, Bool.not_eq_true', decide_eq_true_eq] at h + obtain ⟨⟨⟨⟨hl, ht⟩, hb⟩, ho⟩, hs⟩ := h + refine ⟨?_, ht, hb, ho, hs⟩ + split at hl + · rename_i h; exact h + · simp at hl + +/-- What the fragment knows of a field it reads and writes. -/ +structure FieldOk (ctx : Context) (x : String) (f : StorageField) : Prop where + find : ctx.storageField? x = some f + layout : f.layout? = some (.scalar .uint256) + transient : f.transient = false + bytes : 0 < f.packedBytes + fits : f.packedOffset + f.packedBytes ≤ 32 + slot : f.slot < wordSize + +theorem fieldOf?_spec {fields : List StorageField} {ctx : Context} (hf : ctx.storageFields = fields) + {x : String} {k off bytes : Nat} (h : fieldOf? fields x = some (k, off, bytes)) : + ∃ f, FieldOk ctx x f ∧ f.slot = k ∧ f.packedOffset = off ∧ f.packedBytes = bytes := by + unfold fieldOf? at h + split at h + · rename_i f hfind + split at h + · rename_i hs + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl, rfl⟩ := h + obtain ⟨h1, h2, h3, h4, h5⟩ := fieldOk_spec hs + exact ⟨f, ⟨by simp [Context.storageField?, hf, hfind], h1, h2, h3, h4, h5⟩, rfl, rfl, rfl⟩ + · simp at h + · simp at h + +theorem toNat_land_u256 (x y : EvmYul.UInt256) : + (x.land y).toNat = (x.toNat &&& y.toNat) % wordSize := rfl +theorem toNat_lor_u256 (x y : EvmYul.UInt256) : + (x.lor y).toNat = (x.toNat ||| y.toNat) % wordSize := rfl +theorem toNat_xor_u256 (x y : EvmYul.UInt256) : + (x.xor y).toNat = (x.toNat ^^^ y.toNat) % wordSize := rfl + +theorem apply_bitAnd (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply true .bitAnd (.word a) (.word b) = .ok (.word ((a &&& b) % wordSize)) := by + simp [BinaryOp.apply, Value.forceAbiLazy, BinaryOp.applyWord, bind, Except.bind, Functor.map, + Except.map, SolidCore.Solidity.Shared.andWord, SolidCore.Solidity.Shared.liftEvmBinary, + SolidCore.Solidity.Shared.ofEvmWord, SolidCore.Solidity.Shared.toEvmWord, toNat_land_u256, + toNat_ofNat_u256, norm_lt ha, norm_lt hb, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb, + SolidCore.Solidity.Shared.norm, modulus_eq, Nat.mod_mod] + +theorem apply_bitOr (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply true .bitOr (.word a) (.word b) = .ok (.word ((a ||| b) % wordSize)) := by + simp [BinaryOp.apply, Value.forceAbiLazy, BinaryOp.applyWord, bind, Except.bind, Functor.map, + Except.map, SolidCore.Solidity.Shared.orWord, SolidCore.Solidity.Shared.liftEvmBinary, + SolidCore.Solidity.Shared.ofEvmWord, SolidCore.Solidity.Shared.toEvmWord, toNat_lor_u256, + toNat_ofNat_u256, norm_lt ha, norm_lt hb, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb, + SolidCore.Solidity.Shared.norm, modulus_eq, Nat.mod_mod] + +theorem apply_bitXor (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply true .bitXor (.word a) (.word b) = .ok (.word ((a ^^^ b) % wordSize)) := by + simp [BinaryOp.apply, Value.forceAbiLazy, BinaryOp.applyWord, bind, Except.bind, Functor.map, + Except.map, SolidCore.Solidity.Shared.xorWord, SolidCore.Solidity.Shared.liftEvmBinary, + SolidCore.Solidity.Shared.ofEvmWord, SolidCore.Solidity.Shared.toEvmWord, toNat_xor_u256, + toNat_ofNat_u256, norm_lt ha, norm_lt hb, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb, + SolidCore.Solidity.Shared.norm, modulus_eq, Nat.mod_mod] + +/-- SolidCore's checked cleanup to `b` bits keeps a word below `2 ^ b` and panics on any other. -/ +theorem uintCleanup_lt (w b : Nat) (hw : w < wordSize) (hb0 : 0 < b) (hb : b ≤ 256) : + uintCleanup? true b (.word w) = if w < 2 ^ b then .ok (.word w) else .error (.panic 0x11) := by + simp [uintCleanup?, Value.forceAbiLazy, Value.asStorageWord?, norm_lt hw, uintCast?, bind, + Except.bind, hb0, hb, RevertData.overflow] + by_cases h : w < 2 ^ b + · simp [h, Nat.mod_eq_of_lt h, Nat.not_le.mpr h] + · simp [h, Nat.le_of_not_lt h] + +theorem fieldMask_lt {bytes : Nat} (h : bytes ≤ 32) : fieldMask bytes < wordSize := by + unfold fieldMask + have := Nat.pow_le_pow_right (show 0 < 2 by decide) (show bytes * 8 ≤ 256 by omega) + have := Nat.two_pow_pos (bytes * 8) + simp only [wordSize]; omega + +theorem eval_and_mask (ρ : Val) (e : WExpr) {bytes : Nat} (h : bytes ≤ 32) : + (WExpr.bin .and e (.lit (fieldMask bytes))).eval ρ = e.eval ρ % 2 ^ (bytes * 8) := by + simp only [WExpr.eval, BinOp.eval, Nat.mod_eq_of_lt (fieldMask_lt h)] + rw [fieldMask, Nat.and_two_pow_sub_one_eq_mod] + exact Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le (Nat.mod_lt _ (Nat.two_pow_pos _)) + (Nat.pow_le_pow_right (by decide) (by omega))) + +theorem readField_eval (ρ : Val) (e : WExpr) {off bytes : Nat} (h : off + bytes ≤ 32) + (hb : 0 < bytes) : (readField e off bytes).eval ρ = fieldValue (e.eval ρ) off bytes := by + unfold readField fieldValue + by_cases h1 : off = 0 ∧ bytes = 32 + · simp only [h1, and_self, ↓reduceIte] + · simp only [h1, ↓reduceIte] + by_cases h0 : off = 0 + · subst h0 + simp only [↓reduceIte, eval_and_mask ρ e (show bytes ≤ 32 by omega), Nat.zero_mul, + Nat.pow_zero, Nat.div_one] + · simp only [h0, ↓reduceIte, eval_and_mask ρ _ (show bytes ≤ 32 by omega)] + have hs : off * 8 < 256 := by omega + simp only [WExpr.eval, BinOp.eval, Nat.mod_eq_of_lt (show off * 8 < wordSize from + Nat.lt_of_lt_of_le hs (by decide)), hs, ↓reduceIte] + rw [Nat.mod_eq_of_lt (Nat.lt_of_le_of_lt (Nat.div_le_self _ _) (e.eval_lt ρ))] + +theorem writeField_eval (ρ : Val) (old v : WExpr) {off bytes : Nat} (h : off + bytes ≤ 32) + (hb : 0 < bytes) : + (writeField old v off bytes).eval ρ = fieldWrite (old.eval ρ) (v.eval ρ) off bytes := by + unfold writeField fieldWrite + by_cases h1 : off = 0 ∧ bytes = 32 + · simp only [h1, and_self, ↓reduceIte] + · simp only [h1, ↓reduceIte] + have hob8 : off * 8 + bytes * 8 ≤ 256 := by omega + have hcl := clearMask_lt (off * 8) (bytes * 8) hob8 + have hlt := replace_lt (old.eval_lt ρ) (v.eval ρ) _ _ hob8 + have hshl : (v.eval ρ % 2 ^ (bytes * 8)) <<< (off * 8) < wordSize := by + exact Nat.lt_of_le_of_lt Nat.right_le_or hlt + have hval : (if off = 0 then WExpr.bin .and v (.lit (fieldMask bytes)) + else .bin .shl (.lit (off * 8)) (.bin .and v (.lit (fieldMask bytes)))).eval ρ = + (v.eval ρ % 2 ^ (bytes * 8)) <<< (off * 8) := by + split + · rename_i h0 + subst h0 + rw [eval_and_mask ρ v (by omega)] + simp + · rename_i h0 + have hs : off * 8 < 256 := by omega + rw [eval_bin, eval_and_mask ρ v (by omega), eval_lit, Nat.mod_eq_of_lt (show off * 8 < wordSize from + Nat.lt_of_lt_of_le hs (by decide))] + simp only [BinOp.eval, hs, ↓reduceIte] + rw [Nat.shiftLeft_eq] at hshl ⊢ + rw [Nat.mod_mod, Nat.mod_eq_of_lt hshl] + rw [eval_bin, hval, eval_bin, eval_lit, Nat.mod_eq_of_lt hcl] + simp only [BinOp.eval] + rw [Nat.mod_eq_of_lt (Nat.lt_of_le_of_lt Nat.and_le_left (old.eval_lt ρ)), Nat.mod_eq_of_lt hlt] + +/-- What SolidCore's runtime holds of a symbolic state, for an expression: the context's +storage fields are the contract's, arithmetic is checked, every local the state knows holds +its word, and every slot holds the word the writes leave there. -/ +structure ExprRel (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : Runtime) + (S : SymState) : Prop where + fields : ctx.storageFields = fields + checked : ctx.checked = true + sender : ctx.sender = S.caller.eval ρ + hash : ρ.hash = solHash + ok : ρ.Ok + locals : ∀ x e, Scopes.get? S.scopes x = some e → rt.lookupLocal? x = some (.word (e.eval ρ)) + store : ∀ k, k < wordSize → rt.state.loadSlot k = Writes.store ρ S.writes k + +/-- What SolidCore's evaluation of an erased expression gives: `Panic(0x11)` when one of its +overflow conditions holds, and otherwise its word, with the runtime unchanged. -/ +def exprResult (ρ : Val) (gs : List WExpr) (v : WExpr) (rt : Runtime) : SolI (Value × Runtime) := + if gs.any (fun g => g.eval ρ != 0) then .done (.error (.revert (.panic 0x11))) + else .done (.ok (.word (v.eval ρ), rt)) + +theorem load_field {ctx : Context} {rt : Runtime} {x : String} {f : StorageField} + (hf : FieldOk ctx x f) (hw : rt.state.loadSlot f.slot < wordSize) : + rt.loadStorageField ctx x = + .ok (.word (fieldValue (rt.state.loadSlot f.slot) f.packedOffset f.packedBytes)) := by + have := hf.bytes + have := hf.fits + simp [Runtime.loadStorageField, hf.find, hf.layout, StorageField.storageValueFromWord?, + Ty.storageValueFromWord?, State.loadFieldWord, StorageField.isPacked, + SolidCore.Solidity.Source.wordBytes, State.loadFieldSlot, hf.transient, fieldValue, wordBitRange, + StorageField.packedBitWidth, StorageField.packedBitOffset, norm_lt hw] + by_cases h : f.packedOffset = 0 ∧ f.packedBytes = 32 + · simp [h] + · have hlt : rt.state.loadSlot f.slot / 2 ^ (f.packedOffset * 8) % 2 ^ (f.packedBytes * 8) < + wordSize := + Nat.lt_of_lt_of_le (Nat.mod_lt _ (Nat.two_pow_pos _)) + (Nat.pow_le_pow_right (by decide) (by omega)) + rw [if_pos (by omega), if_neg h, if_neg (by omega), norm_lt hlt] + +theorem loadHeader_field {ctx : Context} {rt : Runtime} {x : String} {f : StorageField} + (hf : FieldOk ctx x f) (hw : rt.state.loadSlot f.slot < wordSize) : + rt.loadStorageFieldHeader ctx x = + .ok (.word (fieldValue (rt.state.loadSlot f.slot) f.packedOffset f.packedBytes)) := by + simp only [Runtime.loadStorageFieldHeader, hf.find, hf.layout] + exact load_field hf hw + +theorem guard_add (ρ : Val) (l r : WExpr) : + ((WExpr.bin .lt (.bin .add l r) l).eval ρ != 0) = decide (wordSize ≤ l.eval ρ + r.eval ρ) := by + have hl := l.eval_lt ρ + have hr := r.eval_lt ρ + simp only [WExpr.eval, BinOp.eval, Nat.mod_mod] + by_cases h : wordSize ≤ l.eval ρ + r.eval ρ + · have : (l.eval ρ + r.eval ρ) % wordSize < l.eval ρ := by + rw [Nat.mod_eq_sub_mod h, Nat.mod_eq_of_lt (by omega)]; omega + simp [this, h] + · have : ¬ (l.eval ρ + r.eval ρ) % wordSize < l.eval ρ := by + rw [Nat.mod_eq_of_lt (by omega)]; omega + simp [this, h] + +theorem guard_sub (ρ : Val) (l r : WExpr) : + ((WExpr.bin .lt l r).eval ρ != 0) = decide (l.eval ρ < r.eval ρ) := by + simp only [WExpr.eval, BinOp.eval] + by_cases h : l.eval ρ < r.eval ρ <;> simp [h] + +theorem guard_mul (ρ : Val) (l r : WExpr) : + ((WExpr.un .iszero (.bin .or (.un .iszero r) (.bin .eq (.bin .div (.bin .mul l r) r) l))).eval ρ + != 0) = decide (wordSize ≤ l.eval ρ * r.eval ρ) := by + have hl := l.eval_lt ρ + have hr := r.eval_lt ρ + simp only [WExpr.eval] + generalize l.eval ρ = a at * + generalize r.eval ρ = b at * + by_cases hb0 : b = 0 + · subst hb0 + by_cases ha0 : a = 0 + · subst ha0; simp [UnOp.eval, BinOp.eval] + · have : (0 = a) = False := propext ⟨fun h => ha0 h.symm, False.elim⟩ + simp [UnOp.eval, BinOp.eval, this] + · have key : (a * b % wordSize) / b = a ↔ a * b < wordSize := by + constructor + · intro h + by_contra h' + have h1 : a * b % wordSize < wordSize := Nat.mod_lt _ (by decide) + have h2 : (a * b % wordSize) / b * b ≤ a * b % wordSize := Nat.div_mul_le_self _ _ + rw [h] at h2 + omega + · intro h + rw [Nat.mod_eq_of_lt h, Nat.mul_div_cancel _ (Nat.pos_of_ne_zero hb0)] + have hdiv : a * b % wordSize / b < wordSize := + Nat.lt_of_le_of_lt (Nat.div_le_self _ _) (Nat.mod_lt _ (by decide)) + simp only [UnOp.eval, BinOp.eval, hb0, ↓reduceIte, Nat.mod_mod, Nat.mod_eq_of_lt hdiv, + Nat.zero_mod, Nat.zero_or] + by_cases h : a * b % wordSize / b = a + · have := key.mp h + simp [h, Nat.not_le.mpr this] + · have : wordSize ≤ a * b := Nat.not_lt.mp (fun h' => h (key.mpr h')) + simp [h, this] + +theorem bind_done_ok' {α β : Type} (a : α) (k : α → SolI β) : + ((.done (.ok a) : SolI α) >>= k) = k a := rfl + +theorem bind_exprResult {α : Type} (ρ : Val) (gs : List WExpr) (v : WExpr) (rt : Runtime) + (k : Value × Runtime → SolI α) : + (exprResult ρ gs v rt >>= k) = + if gs.any (fun g => g.eval ρ != 0) then .done (.error (.revert (.panic 0x11))) + else k (.word (v.eval ρ), rt) := by + unfold exprResult + split <;> rfl + + +theorem add_wrap_lt {a b : Nat} (ha : a < wordSize) (hb : b < wordSize) (h : wordSize ≤ a + b) : + (a + b) % wordSize < a := by + rw [Nat.mod_eq_sub_mod h, Nat.mod_eq_of_lt (by omega)]; omega + +theorem add_nowrap_le {a b : Nat} (h : a + b < wordSize) : a ≤ (a + b) % wordSize := by + rw [Nat.mod_eq_of_lt h]; omega + +theorem any_append (p : WExpr → Bool) (a b : List WExpr) : + (a ++ b).any p = (a.any p || b.any p) := List.any_append + +theorem uintCleanup_256 (w : Nat) (hw : w < wordSize) : + uintCleanup? true 256 (.word w) = .ok (.word w) := by + simp [uintCleanup?, Value.forceAbiLazy, Value.asStorageWord?, norm_lt hw, uintCast?, bind, + Except.bind, Nat.mod_eq_of_lt hw] + exact hw + +/-- SolidCore's truncating cast to `b` bits keeps the word's low `b` bits. -/ +theorem uintCast_word (w b : Nat) (hw : w < wordSize) (hb0 : 0 < b) (hb : b ≤ 256) : + uintCast? b (.word w) = .ok (.word (w % 2 ^ b)) := by + simp [uintCast?, Value.forceAbiLazy, Value.asStorageWord?, norm_lt hw, bind, Except.bind, hb0, hb] + +/-- The word `and e (2 ^ b - 1)` is `e`'s low `b` bits. -/ +theorem eval_and_pow (ρ : Val) (e : WExpr) {b : Nat} (hb : b ≤ 256) : + (WExpr.bin .and e (.lit (2 ^ b - 1))).eval ρ = e.eval ρ % 2 ^ b := by + have hle : 2 ^ b ≤ wordSize := Nat.pow_le_pow_right (by decide) hb + have hlt : 2 ^ b - 1 < wordSize := + Nat.lt_of_lt_of_le (Nat.sub_lt (Nat.two_pow_pos b) (by decide)) hle + simp only [WExpr.eval, BinOp.eval, Nat.mod_eq_of_lt hlt] + rw [Nat.and_two_pow_sub_one_eq_mod] + exact Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le (Nat.mod_lt _ (Nat.two_pow_pos _)) hle) + +/-- The word a constant slot holds is the writes' read of it. -/ +theorem slot_read {ρ : Val} {fields : List StorageField} {ctx : Context} {rt : Runtime} {S : SymState} + (hrel : ExprRel ρ fields ctx rt S) {k : Nat} (hk : k < wordSize) : + rt.state.loadSlot k = (S.writes.read (.lit k)).eval ρ := by + rw [Writes.eval_read hrel.ok, hrel.store k hk] + simp only [WExpr.eval, Nat.mod_eq_of_lt hk] + +theorem norm_mod (n : Nat) : SolidCore.Solidity.Shared.norm n = n % wordSize := rfl + +theorem loadSlot_mod (st : State) (k : Nat) : st.loadSlot (k % wordSize) = st.loadSlot k := by + simp only [State.loadSlot, StorageMap.lookup?, norm_mod, Nat.mod_mod] + +/-- SolidCore hashes an `address` or `uint256` mapping key word as itself. -/ +theorem key_word {ty : Ty} (hty : ty = .address ∨ ty = .uint256) {w : Nat} (h : w < wordSize) : + coerceMappingKeyWordAs ty (.word w) = .ok w := by + rcases hty with rfl | rfl <;> + simp [coerceMappingKeyWordAs, Value.forceAbiLazy, Ty.coerceValue?, Value.asStorageWord?, norm_lt h, + bind, Except.bind] + +/-- The slot of a mapping's entry at an `address` or `uint256` key word: `solHash key slot`. -/ +theorem slot_key (slot : Nat) {ty : Ty} (hty : ty = .address ∨ ty = .uint256) {w : Nat} + (h : w < wordSize) : mappingStorageSlotForKey slot ty (.word w) = .ok (solHash w slot) := by + have hk := key_word hty h + rcases hty with rfl | rfl <;> + simp only [mappingStorageSlotForKey, hk, bind, Except.bind, mappingStorageSlot_eq] + +/-- One key of a storage path through a mapping. -/ +theorem resolve_step (st : State) (slot : Nat) {ty : Ty} (hty : ty = .address ∨ ty = .uint256) + (l : StorageLayout) (rest : List Value) {w : Nat} (h : w < wordSize) : + st.resolveStoragePathSlot slot (.mapping ty l) (.word w :: rest) = + st.resolveStoragePathSlot (solHash w slot) l rest := by + rw [State.resolveStoragePathSlot.eq_2, slot_key _ hty h] + rfl + +/-- SolidCore's slot hash is a word. -/ +theorem solHash_lt (a b : Nat) : solHash a b < wordSize := by + simp only [solHash, keccakWord, bytesToWordBE, norm_mod] + exact Nat.mod_lt _ (by decide) + +/-- What the fragment knows of a nested mapping it reads and writes. -/ +structure Map2Ok (ctx : Context) (x : String) (f : StorageField) : Prop where + find : ctx.storageField? x = some f + layout : f.layout? = some (.mapping .address (.mapping .address (.scalar .uint256))) + transient : f.transient = false + slot : f.slot < wordSize + +theorem map2Of?_spec {fields : List StorageField} {ctx : Context} (hf : ctx.storageFields = fields) + {x : String} {k : Nat} (h : map2Of? fields x = some k) : + ∃ f, Map2Ok ctx x f ∧ f.slot = k := by + unfold map2Of? at h + split at h + · rename_i f hfind + split at h + · rename_i hs + simp only [Option.some.injEq] at h + subst h + unfold map2Ok at hs + simp only [Bool.and_eq_true, Bool.not_eq_true', decide_eq_true_eq] at hs + obtain ⟨⟨hl, ht⟩, hsl⟩ := hs + refine ⟨f, ⟨by simp [Context.storageField?, hf, hfind], ?_, ht, hsl⟩, rfl⟩ + split at hl + · rename_i h; exact h + · simp at hl + · simp at h + · simp at h + +/-- The slot of the entry of a nested mapping at two key words. -/ +theorem resolve_map2 {ctx : Context} {rt : Runtime} {x : String} {f : StorageField} + (hf : Map2Ok ctx x f) {w1 w2 : Nat} (h1 : w1 < wordSize) (h2 : w2 < wordSize) : + rt.resolveStorageBasePath ctx (.field x) [.word w1, .word w2] = + .ok (solHash w2 (solHash w1 f.slot), .scalar .uint256) := by + have ha : (Ty.address = .address ∨ Ty.address = .uint256) := .inl rfl + simp only [Runtime.resolveStorageBasePath, Runtime.storageBaseAnchor, hf.find, hf.layout, + hf.transient, Bool.false_and, Bool.false_eq_true, ↓reduceIte, bind, Except.bind, pure, + Except.pure] + rw [resolve_step _ _ ha _ _ h1, resolve_step _ _ ha _ _ h2, State.resolveStoragePathSlot.eq_1] + +/-- SolidCore reads the entry of a nested mapping at two key words as the writes' read of the slot +word `hash key2 (hash key1 slot)`. -/ +theorem loadPath_map2 {ρ : Val} {fields : List StorageField} {ctx : Context} {rt : Runtime} + {S : SymState} (hrel : ExprRel ρ fields ctx rt S) {x : String} {k : Nat} + (hk : map2Of? fields x = some k) {w1 w2 : Nat} (h1 : w1 < wordSize) (h2 : w2 < wordSize) : + rt.loadStorageBasePath ctx (.field x) [.word w1, .word w2] = + .ok (.word (Writes.store ρ S.writes (solHash w2 (solHash w1 k % wordSize) % wordSize))) := by + obtain ⟨f, hf, rfl⟩ := map2Of?_spec hrel.fields hk + rw [Runtime.loadStorageBasePath, resolve_map2 hf h1 h2] + simp only [bind, Except.bind, State.loadStorageLayoutAt, StorageLayout.depth, + State.loadStorageLayoutAtFuel, loadStorageWordAs, Ty.storageValueFromWord?] + rw [Nat.mod_eq_of_lt (solHash_lt w1 f.slot), ← loadSlot_mod, + hrel.store _ (Nat.mod_lt _ (by decide))] + +/-- What the fragment knows of a mapping it reads and writes. -/ +structure MapOk (ctx : Context) (x : String) (f : StorageField) : Prop where + find : ctx.storageField? x = some f + layout : f.layout? = some (.mapping .address (.scalar .uint256)) ∨ + f.layout? = some (.mapping .uint256 (.scalar .uint256)) + transient : f.transient = false + slot : f.slot < wordSize + +theorem mapOf?_spec {fields : List StorageField} {ctx : Context} (hf : ctx.storageFields = fields) + {x : String} {k : Nat} (h : mapOf? fields x = some k) : + ∃ f, MapOk ctx x f ∧ f.slot = k := by + unfold mapOf? at h + split at h + · rename_i f hfind + split at h + · rename_i hs + simp only [Option.some.injEq] at h + subst h + unfold mapOk at hs + simp only [Bool.and_eq_true, Bool.not_eq_true', decide_eq_true_eq] at hs + obtain ⟨⟨hl, ht⟩, hsl⟩ := hs + refine ⟨f, ⟨by simp [Context.storageField?, hf, hfind], ?_, ht, hsl⟩, rfl⟩ + split at hl + · rename_i h; exact .inl h + · rename_i h; exact .inr h + · simp at hl + · simp at h + · simp at h + + +/-- SolidCore reads the entry of a mapping at a key word as the writes' read of the slot word +`hash key slot`. -/ +theorem loadIndex_map {ρ : Val} {fields : List StorageField} {ctx : Context} {rt : Runtime} + {S : SymState} (hrel : ExprRel ρ fields ctx rt S) {x : String} {k : Nat} + (hk : mapOf? fields x = some k) {w : Nat} (hw : w < wordSize) : + rt.loadStorageIndex ctx x (.word w) = + .ok (.word (Writes.store ρ S.writes (solHash w k % wordSize))) := by + obtain ⟨f, hf, rfl⟩ := mapOf?_spec hrel.fields hk + have hsl : rt.state.loadSlot (solHash w f.slot) = Writes.store ρ S.writes (solHash w f.slot % wordSize) := by + rw [← loadSlot_mod, hrel.store _ (Nat.mod_lt _ (by decide))] + rcases hf.layout with hl | hl <;> + simp [Runtime.loadStorageIndex, hf.find, hl, mappingStorageSlotForKey, coerceMappingKeyWordAs, + Value.forceAbiLazy, Ty.coerceValue?, Value.asStorageWord?, norm_lt hw, bind, Except.bind, + State.loadStorageLayoutAt, State.loadStorageLayoutAtFuel, loadStorageWordAs, + Ty.storageValueFromWord?, mappingStorageSlot_eq, hsl, pure, Except.pure, StorageLayout.depth] + +/-- What the fragment knows of a mapping to `bool` it reads and writes. -/ +structure BoolMapOk (ctx : Context) (x : String) (f : StorageField) : Prop where + find : ctx.storageField? x = some f + layout : f.layout? = some (.mapping .address (.scalar .bool)) ∨ + f.layout? = some (.mapping .uint256 (.scalar .bool)) + transient : f.transient = false + slot : f.slot < wordSize + +theorem boolMapOf?_spec {fields : List StorageField} {ctx : Context} (hf : ctx.storageFields = fields) + {x : String} {k : Nat} (h : boolMapOf? fields x = some k) : + ∃ f, BoolMapOk ctx x f ∧ f.slot = k := by + unfold boolMapOf? at h + split at h + · rename_i f hfind + split at h + · rename_i hs + simp only [Option.some.injEq] at h + subst h + unfold boolMapOk at hs + simp only [Bool.and_eq_true, Bool.not_eq_true', decide_eq_true_eq] at hs + obtain ⟨⟨hl, ht⟩, hsl⟩ := hs + refine ⟨f, ⟨by simp [Context.storageField?, hf, hfind], ?_, ht, hsl⟩, rfl⟩ + split at hl + · rename_i h; exact .inl h + · rename_i h; exact .inr h + · simp at hl + · simp at h + · simp at h + +/-- The `bool` of a storage word, as `boolOfWord` computes it: whether its low byte is not zero. -/ +theorem boolOfWord_eval (ρ : Val) (w : WExpr) : + (boolOfWord w).eval ρ = if w.eval ρ % 256 = 0 then 0 else 1 := by + have hm : (w.eval ρ &&& 255 % wordSize) % wordSize = w.eval ρ % 256 := by + rw [Nat.mod_eq_of_lt (show 255 < wordSize by decide), show (255 : Nat) = 2 ^ 8 - 1 from rfl, + Nat.and_two_pow_sub_one_eq_mod] + exact Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (by decide)) + simp only [boolOfWord, WExpr.eval, BinOp.eval, UnOp.eval, hm, Nat.zero_mod] + by_cases h : w.eval ρ % 256 = 0 <;> simp [h] + +/-- SolidCore reads the entry of a mapping to `bool` at a key word as whether the low byte of the +writes' read of the slot word `hash key slot` is not zero. -/ +theorem loadIndex_boolMap {ρ : Val} {fields : List StorageField} {ctx : Context} {rt : Runtime} + {S : SymState} (hrel : ExprRel ρ fields ctx rt S) {x : String} {k : Nat} + (hk : boolMapOf? fields x = some k) {w : Nat} (hw : w < wordSize) : + rt.loadStorageIndex ctx x (.word w) = + .ok (.word (if Writes.store ρ S.writes (solHash w k % wordSize) % 256 = 0 then 0 else 1)) := by + obtain ⟨f, hf, rfl⟩ := boolMapOf?_spec hrel.fields hk + have hsl : rt.state.loadSlot (solHash w f.slot) = Writes.store ρ S.writes (solHash w f.slot % wordSize) := by + rw [← loadSlot_mod, hrel.store _ (Nat.mod_lt _ (by decide))] + have hlt : Writes.store ρ S.writes (solHash w f.slot % wordSize) < wordSize := + Writes.store_word hrel.ok _ _ + rcases hf.layout with hl | hl <;> + simp [Runtime.loadStorageIndex, hf.find, hl, mappingStorageSlotForKey, coerceMappingKeyWordAs, + Value.forceAbiLazy, Ty.coerceValue?, Value.asStorageWord?, norm_lt hw, bind, Except.bind, + State.loadStorageLayoutAt, State.loadStorageLayoutAtFuel, loadStorageWordAs, + Ty.storageValueFromWord?, mappingStorageSlot_eq, hsl, StorageLayout.depth, norm_lt hlt] + +/-- What the fragment knows of an `address` field it reads. -/ +structure AddrFieldOk (ctx : Context) (x : String) (f : StorageField) : Prop where + find : ctx.storageField? x = some f + layout : f.layout? = some (.scalar .address) + transient : f.transient = false + bytes : f.packedBytes = 20 + fits : f.packedOffset + 20 ≤ 32 + slot : f.slot < wordSize + +theorem addrFieldOf?_spec {fields : List StorageField} {ctx : Context} (hf : ctx.storageFields = fields) + {x : String} {k off : Nat} (h : addrFieldOf? fields x = some (k, off)) : + ∃ f, AddrFieldOk ctx x f ∧ f.slot = k ∧ f.packedOffset = off := by + unfold addrFieldOf? at h + split at h + · rename_i f hfind + split at h + · rename_i hs + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + unfold addrFieldOk at hs + simp only [Bool.and_eq_true, Bool.not_eq_true', decide_eq_true_eq] at hs + obtain ⟨⟨⟨⟨hl, ht⟩, hb⟩, ho⟩, hsl⟩ := hs + refine ⟨f, ⟨by simp [Context.storageField?, hf, hfind], ?_, ht, hb, ho, hsl⟩, rfl, rfl⟩ + split at hl + · rename_i h; exact h + · simp at hl + · simp at h + · simp at h + +theorem load_addrField {ctx : Context} {rt : Runtime} {x : String} {f : StorageField} + (hf : AddrFieldOk ctx x f) (hw : rt.state.loadSlot f.slot < wordSize) : + rt.loadStorageField ctx x = + .ok (.word (fieldValue (rt.state.loadSlot f.slot) f.packedOffset 20)) := by + have := hf.fits + have hv : fieldValue (rt.state.loadSlot f.slot) f.packedOffset 20 < 2 ^ 160 := by + unfold fieldValue + simp only [show ¬ (f.packedOffset = 0 ∧ (20 : Nat) = 32) by omega, ↓reduceIte] + exact Nat.mod_lt _ (by decide) + simp [Runtime.loadStorageField, hf.find, hf.layout, StorageField.storageValueFromWord?, + Ty.storageValueFromWord?, State.loadFieldWord, StorageField.isPacked, + SolidCore.Solidity.Source.wordBytes, State.loadFieldSlot, hf.transient, fieldValue, wordBitRange, + StorageField.packedBitWidth, StorageField.packedBitOffset, norm_lt hw, hf.bytes, + SolidCore.Solidity.Shared.Account.addressWord] + have hx : rt.state.loadSlot f.slot / 2 ^ (f.packedOffset * 8) % + 1461501637330902918203684832716283019655932542976 < wordSize := + Nat.lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (by decide) + rw [norm_lt hx, norm_lt hx, SolidCore.Solidity.Shared.Account.addressModulus, + show (2 : Nat) ^ 160 = 1461501637330902918203684832716283019655932542976 from rfl, Nat.mod_mod] + +theorem loadHeader_addrField {ctx : Context} {rt : Runtime} {x : String} {f : StorageField} + (hf : AddrFieldOk ctx x f) (hw : rt.state.loadSlot f.slot < wordSize) : + rt.loadStorageFieldHeader ctx x = + .ok (.word (fieldValue (rt.state.loadSlot f.slot) f.packedOffset 20)) := by + simp only [Runtime.loadStorageFieldHeader, hf.find, hf.layout] + exact load_addrField hf hw + + +/-! ## The hash of two words -/ + +theorem uintCast_fixed (sz w : Nat) : uintCast? 256 (.fixedBytes sz w) = .ok (.word (w % wordSize)) := by + simp [uintCast?, Value.forceAbiLazy, Value.asStorageWord?, SolidCore.Solidity.Shared.norm, bind, + Except.bind, SolidCore.Solidity.Shared.wordModulus] + rw [size_eq] + show w % wordSize % wordSize = _ + rw [Nat.mod_mod] + +theorem materialize_word (ctx : Context) (rt : Runtime) (a : Nat) : + rt.materializeForValueUse ctx (.word a) = .ok (.word a) := by + simp [Runtime.materializeForValueUse, Runtime.materializeForValueUseFuel] + +theorem materialize_bytes (ctx : Context) (rt : Runtime) (bs : List Byte) : + rt.materializeForValueUse ctx (.bytes bs) = .ok (.bytes bs) := by + simp [Runtime.materializeForValueUse, Runtime.materializeForValueUseFuel] + +/-- The ABI encoding of two `uint256` words is their 64 bytes, as the slot hash hashes them. -/ +theorem encode2_words (a b : Nat) : + abiEncodeValues? [.uint256, .uint256] [.word a, .word b] = + some (storageWordBytes a ++ storageWordBytes b) := by + simp [abiEncodeValues?, Ty.listAbiHeadWords?, Ty.abiHeadWords?, abiEncodeValuesAux?, Ty.isDynamicAbi, + Ty.staticAbiHeadWords?, abiEncodeStaticValue?, abiStaticBytes?, storageWordBytes] + +theorem normByte_wordToBytesBE : ∀ (k a : Nat), (wordToBytesBE k a).map normByte = wordToBytesBE k a + | 0, _ => rfl + | k + 1, a => by + simp only [wordToBytesBE, List.map_append, normByte_wordToBytesBE k, List.map_cons, List.map_nil] + simp [normByte, SolidCore.Solidity.Shared.Account.byte] + +/-- SolidCore evaluates `uint256(keccak256(abi.encode(x, y)))` of two `uint256` words to the hash +of their words: `Panic(0x11)` when an overflow condition of either holds, else `solHash` of them. -/ +theorem eval_hash_pair (ρ : Val) (hash : ρ.hash = solHash) (n m k : Nat) (hn : n = m + 1) + (hm : m = k + 1) (ctx : Context) (rt : Runtime) (x y : Expr) (gx gy : List WExpr) (vx vy : WExpr) + (ihx : Expr.evalFuel n ctx rt x = exprResult ρ gx vx rt) + (ihy : Expr.evalFuel m ctx rt y = exprResult ρ gy vy rt) : + Expr.evalFuel (n + 4) ctx rt + (.castOp .uintCast 256 (.keccak256 (.encode .plain none [] [.uint256, .uint256] [x, y]))) = + exprResult ρ (gx ++ gy) (.hash vx vy) rt := by + simp only [Expr.evalFuel, Expr.evalListFuel] + rw [ihx, bind_exprResult] + by_cases hgx : (gx.any fun g => WExpr.eval ρ g != 0) = true + · simp only [hgx, ite_true] + unfold exprResult + simp only [any_append, hgx, Bool.true_or, ite_true] + rfl + · simp only [hgx, Bool.false_eq_true, ite_false] + rw [Expr.evalListFuel.eq_def] + subst hn + simp only + rw [ihy, bind_exprResult] + by_cases hgy : (gy.any fun g => WExpr.eval ρ g != 0) = true + · simp only [hgy, ite_true] + unfold exprResult + simp only [any_append, hgy, Bool.or_true, ite_true] + rfl + · simp only [hgy, Bool.false_eq_true, ite_false] + rw [Expr.evalListFuel.eq_def] + unfold exprResult + simp only [any_append, hgx, hgy, Bool.false_or, Bool.false_eq_true, ite_false] + simp only [pure, EvmCompiler.Simulation.Interaction.pure, bind, + EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, MonadLift.monadLift, + materialize_bytes, encode2_words, Value.asBytes?, uintCast_fixed, SolI.ofExcept, Except.bind] + subst hm + simp only [EvmCompiler.Simulation.Interaction.bind, Runtime.materializeForValueUseList, + materialize_word, materialize_bytes, encode2_words, uintCast_fixed, Except.bind] + simp [EvmCompiler.Simulation.Interaction.bind, Runtime.materializeForValueUseList, + materialize_word, materialize_bytes, encode2_words, uintCast_fixed, bind, Except.bind, pure, + Except.pure, WExpr.eval, hash, solHash, storageWordBytes, normByte_wordToBytesBE] + +/-- An atom evaluates to its word at any fuel. -/ +theorem eval_atom {ρ : Val} {fields : List StorageField} {ctx : Context} {rt : Runtime} {S : SymState} + (hrel : ExprRel ρ fields ctx rt S) {x : Expr} {v : WExpr} (h : eraseAtom S x = some v) (k : Nat) : + Expr.evalFuel (k + 1) ctx rt x = exprResult ρ [] v rt := by + cases x with + | word w => + simp only [eraseAtom, Option.some.injEq] at h + subst h + simp [Expr.evalFuel, exprResult, WExpr.eval, normWord, SolidCore.Solidity.Shared.norm, modulus_eq] + rfl + | var x => + simp only [eraseAtom] at h + have hl := hrel.locals x v h + simp [Expr.evalFuel, exprResult, Runtime.lookupStorageBase?, hl, Runtime.derefMemoryValue] + rfl + | caller => + simp only [eraseAtom, Option.some.injEq] at h + subst h + simp only [Expr.evalFuel, exprResult, List.any_nil, Bool.false_eq_true, ↓reduceIte, + hrel.sender] + rfl + | _ => simp [eraseAtom] at h + +theorem hashPair?_spec {S : SymState} {b : Nat} {e : Expr} {v : WExpr} (h : hashPair? S b e = some v) : + b = 256 ∧ ∃ x y vx vy, e = .keccak256 (.encode .plain none [] [.uint256, .uint256] [x, y]) ∧ + eraseAtom S x = some vx ∧ eraseAtom S y = some vy ∧ v = .hash vx vy := by + unfold hashPair? at h + split at h + · rename_i hb + refine ⟨hb, ?_⟩ + split at h + · rename_i x y + split at h + · rename_i vx vy hx hy + simp only [Option.some.injEq] at h + exact ⟨x, y, vx, vy, rfl, hx, hy, h.symm⟩ + · simp at h + · simp at h + · simp at h + +theorem eval_erase (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : Runtime) + (S : SymState) (hrel : ExprRel ρ fields ctx rt S) (e : Expr) : + ∀ (gs : List WExpr) (v : WExpr) (fuel : Nat), eraseExpr fields S e = some (gs, v) → + Expr.orderFuel e < fuel → Expr.evalFuel fuel ctx rt e = exprResult ρ gs v rt := by + intro gs v fuel h hf + obtain ⟨n, rfl⟩ : ∃ n, fuel = n + 1 := ⟨fuel - 1, by omega⟩ + cases e with + | word w => + simp only [eraseExpr, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + simp [Expr.evalFuel, exprResult, WExpr.eval, normWord, SolidCore.Solidity.Shared.norm, modulus_eq] + rfl + | var x => + simp only [eraseExpr, Option.map_eq_some_iff, Prod.mk.injEq] at h + obtain ⟨e, he, rfl, rfl⟩ := h + have hl := hrel.locals x e he + simp [Expr.evalFuel, exprResult, Runtime.lookupStorageBase?, hl, Runtime.derefMemoryValue] + rfl + | castOp k b e => + cases k + case uintCleanup => + cases he : eraseExpr fields S e with + | none => simp [eraseExpr, he] at h + | some p => + obtain ⟨gs0, v0⟩ := p + have ih := eval_erase ρ fields ctx rt S hrel e gs0 v0 n he + (by simp [Expr.orderFuel] at hf; omega) + have hv0 := v0.eval_lt ρ + by_cases hb : b = 256 + · subst hb + simp only [eraseExpr, he, Option.bind_eq_bind, Option.bind_some, ↓reduceIte, + Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + simp only [Expr.evalFuel, ih, hrel.checked] + unfold exprResult + split + · rfl + · simp only [bind, EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, + MonadLift.monadLift, uintCleanup_256 _ hv0, SolI.ofExcept] + rfl + · by_cases hb2 : 0 < b ∧ b < 256 + · simp only [eraseExpr, he, Option.bind_eq_bind, Option.bind_some, hb, hb2, and_self, + ↓reduceIte, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + simp only [Expr.evalFuel, ih, hrel.checked] + unfold exprResult + simp only [any_append, List.any_cons, List.any_nil, Bool.or_false] + by_cases hg : gs0.any (fun g => g.eval ρ != 0) = true + · simp only [hg, Bool.true_or, ↓reduceIte] + rfl + · simp only [hg, Bool.false_or, Bool.false_eq_true, ↓reduceIte] + simp only [bind, EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, + MonadLift.monadLift, uintCleanup_lt _ _ hv0 hb2.1 (by omega), SolI.ofExcept] + have hpos := Nat.two_pow_pos b + have hm : (2 ^ b - 1) % wordSize = 2 ^ b - 1 := + Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le (Nat.sub_lt hpos (by decide)) + (Nat.pow_le_pow_right (by decide) (by omega))) + by_cases hc : v0.eval ρ < 2 ^ b + · have hc' : ¬ 2 ^ b - 1 < v0.eval ρ := by omega + simp [hc, WExpr.eval, BinOp.eval, hm, hc'] + try rfl + · have hc' : 2 ^ b - 1 < v0.eval ρ := by omega + simp [hc, WExpr.eval, BinOp.eval, hm, hc'] + try rfl + · simp [eraseExpr, he, hb, hb2] at h + case uintCast => + cases hh : hashPair? S b e with + | some v' => + obtain ⟨rfl, x, y, vx, vy, rfl, hx, hy, rfl⟩ := hashPair?_spec hh + simp only [eraseExpr, hh, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + have hn : 5 ≤ n := by simp [Expr.orderFuel, Expr.listEvalFuel] at hf; omega + obtain ⟨k, rfl⟩ : ∃ k, n = k + 5 := ⟨n - 5, by omega⟩ + have := eval_hash_pair ρ hrel.hash (k + 2) (k + 1) k rfl rfl ctx rt x y [] [] vx vy + (eval_atom hrel hx (k + 1)) (eval_atom hrel hy k) + simpa using this + | none => + cases he : eraseExpr fields S e with + | none => simp [eraseExpr, hh, he] at h + | some p => + obtain ⟨gs0, v0⟩ := p + have ih := eval_erase ρ fields ctx rt S hrel e gs0 v0 n he + (by simp [Expr.orderFuel] at hf; omega) + have hv0 := v0.eval_lt ρ + by_cases hb : b = 256 + · subst hb + simp only [eraseExpr, hh, he, Option.bind_eq_bind, Option.bind_some, ↓reduceIte, + Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + simp only [Expr.evalFuel, ih] + unfold exprResult + split + · rfl + · simp only [bind, EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, + MonadLift.monadLift, uintCast_word _ _ hv0 (by decide) (Nat.le_refl _), + Nat.mod_eq_of_lt hv0, SolI.ofExcept] + rfl + · by_cases hb2 : 0 < b ∧ b < 256 + · simp only [eraseExpr, hh, he, Option.bind_eq_bind, Option.bind_some, hb, hb2, and_self, + ↓reduceIte, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + simp only [Expr.evalFuel, ih] + unfold exprResult + split + · rfl + · simp only [bind, EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, + MonadLift.monadLift, uintCast_word _ _ hv0 hb2.1 (by omega), SolI.ofExcept, + eval_and_pow ρ v0 (show b ≤ 256 by omega)] + rfl + · simp [eraseExpr, hh, he, hb, hb2] at h + all_goals simp [eraseExpr] at h + | binary op l r => + cases hl : eraseExpr fields S l with + | none => cases op <;> simp [eraseExpr, hl, binOf, negOf] at h + | some pl => + cases hr : eraseExpr fields S r with + | none => cases op <;> simp [eraseExpr, hl, hr, binOf, negOf] at h + | some pr => + obtain ⟨gl, vl⟩ := pl + obtain ⟨gr, vr⟩ := pr + have hfl : Expr.orderFuel l < n := by simp [Expr.orderFuel] at hf; omega + have hfr : Expr.orderFuel r < n := by simp [Expr.orderFuel] at hf; omega + have ihl := eval_erase ρ fields ctx rt S hrel l gl vl n hl hfl + have ihr := eval_erase ρ fields ctx rt S hrel r gr vr n hr hfr + have hal := vl.eval_lt ρ + have har := vr.eval_lt ρ + cases op <;> simp only [eraseExpr, hl, hr, binOf, negOf, overflow, Option.bind_eq_bind, + Option.bind_some, Option.some.injEq, Prod.mk.injEq, reduceCtorEq, Option.bind_none] at h + all_goals first + | (simp at h; done) + | skip + all_goals + obtain ⟨rfl, rfl⟩ := h + simp only [Expr.evalFuel, ihr, bind_exprResult, hrel.checked] + unfold exprResult + by_cases hgr : gr.any (fun g => g.eval ρ != 0) = true + · simp [hgr, any_append] + · simp only [hgr, Bool.false_eq_true, ↓reduceIte, ihl, bind_exprResult] + by_cases hgl : gl.any (fun g => g.eval ρ != 0) = true + · simp [hgl, any_append] + · simp only [hgl, Bool.false_eq_true, ↓reduceIte] + simp only [any_append, hgl, hgr, Bool.false_or, List.any_cons, List.any_nil, + Bool.or_false, guard_add, guard_sub, guard_mul] + simp only [pure, EvmCompiler.Simulation.Interaction.pure, bind, + EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, MonadLift.monadLift, + apply_add _ _ hal har, apply_sub _ _ hal har, apply_mul _ _ hal har, apply_lt _ _ hal har, + apply_gt _ _ hal har, apply_eq _ _ hal har, apply_bitAnd _ _ hal har, + apply_bitOr _ _ hal har, apply_bitXor _ _ hal har, apply_ge _ _ hal har, + apply_le _ _ hal har, apply_ne _ _ hal har] + split <;> simp_all [SolI.ofExcept, WExpr.eval, BinOp.eval, UnOp.eval, Nat.mod_mod] + all_goals first + | exact add_wrap_lt hal har (by assumption) + | exact add_nowrap_le (by assumption) + | (split <;> simp_all <;> omega) + | (split <;> simp_all) + | unary op e => + cases op + case logicalNot => + cases he : eraseExpr fields S e with + | none => simp [eraseExpr, he] at h + | some p => + obtain ⟨gs0, v0⟩ := p + simp only [eraseExpr, he, Option.bind_eq_bind, Option.bind_some, Option.some.injEq, + Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + have ih := eval_erase ρ fields ctx rt S hrel e gs0 v0 n he + (by simp [Expr.orderFuel] at hf; omega) + simp only [Expr.evalFuel, ih, bind_exprResult, hrel.checked] + unfold exprResult + split + · rfl + · simp only [bind, EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, + MonadLift.monadLift, apply_not _ (v0.eval_lt ρ), SolI.ofExcept, pure, + EvmCompiler.Simulation.Interaction.pure] + simp only [WExpr.eval, UnOp.eval] + split <;> rfl + all_goals simp [eraseExpr] at h + | caller => + simp only [eraseExpr, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + simp only [Expr.evalFuel, exprResult, List.any_nil, Bool.false_eq_true, ↓reduceIte, + hrel.sender] + rfl + | storageRead m x idx => + cases m + case element => + match idx, h with + | [i], h => + cases hk : mapOf? fields x with + | some k => + simp only [eraseExpr, hk, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq, + Prod.mk.injEq] at h + obtain ⟨⟨gs0, v0⟩, hi, rfl, rfl⟩ := h + have ih := eval_erase ρ fields ctx rt S hrel i gs0 v0 n hi + (by simp [Expr.orderFuel, Expr.listEvalFuel] at hf; omega) + simp only [Expr.evalFuel, ih, bind_exprResult] + unfold exprResult + split + · rfl + · obtain ⟨f, hf, rfl⟩ := mapOf?_spec hrel.fields hk + rw [loadIndex_map hrel hk (v0.eval_lt ρ), Writes.eval_read hrel.ok] + simp only [WExpr.eval, hrel.hash, Nat.mod_eq_of_lt hf.slot] + rfl + | none => + simp only [eraseExpr, hk, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq, + Prod.mk.injEq] at h + obtain ⟨k, hk', ⟨gs0, v0⟩, hi, rfl, rfl⟩ := h + have ih := eval_erase ρ fields ctx rt S hrel i gs0 v0 n hi + (by simp [Expr.orderFuel, Expr.listEvalFuel] at hf; omega) + simp only [Expr.evalFuel, ih, bind_exprResult] + unfold exprResult + split + · rfl + · obtain ⟨f, hf, rfl⟩ := boolMapOf?_spec hrel.fields hk' + rw [loadIndex_boolMap hrel hk' (v0.eval_lt ρ), boolOfWord_eval, Writes.eval_read hrel.ok] + simp only [WExpr.eval, hrel.hash, Nat.mod_eq_of_lt hf.slot] + rfl + all_goals + cases idx <;> simp only [eraseExpr] at h + all_goals first + | (simp at h; done) + | skip + all_goals + cases hk : fieldOf? fields x with + | some p => + obtain ⟨k, off, bytes⟩ := p + simp only [hk, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + obtain ⟨f, hfx, rfl, rfl, rfl⟩ := fieldOf?_spec hrel.fields hk + have hsl := slot_read hrel hfx.slot + have hw : rt.state.loadSlot f.slot < wordSize := by + rw [hsl]; exact WExpr.eval_lt _ _ + simp only [Expr.evalFuel, loadHeader_field hfx hw, load_field hfx hw, bind, + EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, MonadLift.monadLift, SolI.ofExcept, + exprResult, List.any_nil, Bool.false_eq_true, ↓reduceIte, hsl, + readField_eval ρ _ hfx.fits hfx.bytes] + try rfl + | none => + simp only [hk, Option.map_eq_some_iff, Prod.mk.injEq] at h + obtain ⟨⟨k, off⟩, hk', rfl, rfl⟩ := h + obtain ⟨f, hfx, rfl, rfl⟩ := addrFieldOf?_spec hrel.fields hk' + have hsl := slot_read hrel hfx.slot + have hw : rt.state.loadSlot f.slot < wordSize := by + rw [hsl]; exact WExpr.eval_lt _ _ + simp only [Expr.evalFuel, loadHeader_addrField hfx hw, load_addrField hfx hw, bind, + EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, MonadLift.monadLift, SolI.ofExcept, + exprResult, List.any_nil, Bool.false_eq_true, ↓reduceIte, hsl, + readField_eval ρ _ hfx.fits (by decide)] + try rfl + | index base i2 => + cases base + case storageRead m x idx => + cases m + case element => + rcases idx with _ | ⟨i1, _ | ⟨_, _⟩⟩ + · simp [eraseExpr] at h + · simp only [eraseExpr, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq, + Prod.mk.injEq] at h + obtain ⟨k, hk, ⟨g1, v1⟩, h1, ⟨g2, v2⟩, h2, rfl, rfl⟩ := h + obtain ⟨m, rfl⟩ : ∃ m, n = m + 1 := + ⟨n - 1, by simp [Expr.orderFuel, Expr.listEvalFuel] at hf; omega⟩ + have ih1 := eval_erase ρ fields ctx rt S hrel i1 g1 v1 m h1 + (by simp [Expr.orderFuel, Expr.listEvalFuel] at hf; omega) + have ih2 := eval_erase ρ fields ctx rt S hrel i2 g2 v2 (m + 1) h2 + (by simp [Expr.orderFuel, Expr.listEvalFuel] at hf; omega) + rw [Expr.evalFuel] + rotate_left + · intro _ h; cases h + simp only [Expr.hasStorageRoot, ↓reduceIte, Expr.resolveLValueFuel, ih1, bind_exprResult] + unfold exprResult + by_cases hg1 : g1.any (fun g => g.eval ρ != 0) = true + · simp only [hg1, any_append, Bool.true_or, ↓reduceIte] + rfl + · simp only [hg1, Bool.false_eq_true, ↓reduceIte, bind_done_ok', pure, + EvmCompiler.Simulation.Interaction.pure, ResolvedLValue.asStoragePath?, ih2, + bind_exprResult] + by_cases hg2 : g2.any (fun g => g.eval ρ != 0) = true + · simp only [hg2, any_append, Bool.or_true, ↓reduceIte] + · simp only [hg2, Bool.false_eq_true, ↓reduceIte, any_append, hg1, Bool.false_or, + List.cons_append, List.nil_append] + obtain ⟨f, hf, rfl⟩ := map2Of?_spec hrel.fields hk + simp only [bind, EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, + MonadLift.monadLift, SolI.ofExcept, + loadPath_map2 hrel hk (v1.eval_lt ρ) (v2.eval_lt ρ)] + rw [Writes.eval_read hrel.ok] + simp only [WExpr.eval, hrel.hash, Nat.mod_eq_of_lt hf.slot] + · simp [eraseExpr] at h + all_goals simp [eraseExpr] at h + all_goals simp [eraseExpr] at h + | _ => simp [eraseExpr] at h + +end SolidCore.Refinement.Generic + diff --git a/SolidCore/Refinement/Generic/SourceCall.lean b/SolidCore/Refinement/Generic/SourceCall.lean new file mode 100644 index 00000000..a144a8df --- /dev/null +++ b/SolidCore/Refinement/Generic/SourceCall.lean @@ -0,0 +1,147 @@ +import SolidCore.Refinement.Generic.SourceStmt + +/-! +# Functions and the dispatcher of the fragment + +`eraseFn` erases a SolidCore function of the fragment to the `Tree` of one external call of it. +Its parameters are words: a `uint256` with a `uint b` ABI cleanup, `0 < b ≤ 256`, or an `address` +with no cleanup, as SolidCore's type checker gives a Solidity `address` parameter; each has a +width (`paramWidth`: `b`, or 160 for an address). Its returns are `uint256`, `address` or `bool` +words, and none of its bindings is a storage reference. The tree is the argument checks +(`paramGuards`: a word at or above `2 ^ w` for a parameter of width `w < 256` reverts with empty +data, as SolidCore's decoder, its address check or its `uint b` cleanup, and solar's `lower-abi` +do), then the body's branch tree run from `initState`, with each leaf turned into the call's end +by `leafTree`: the returned words ABI-encoded with the body's storage writes and logs, or a +revert's data (empty, `Panic(code)` or `Error(msg)`) with neither. + +Past the argument checks every argument word fits its width, which the facts `argFacts` record +(`gt (arg i) (2 ^ w - 1)` taken as zero). The erasure reads them through the `EraseEnv`'s +`facts` and `leafTree` through its own: a returned `address` word must be below `2 ^ 160` and a +`bool` word at most 1 on every call (`retOk`: its `bound` on the facts), as SolidCore's encoder +asks, so an `address` parameter, `msg.sender`, a masked storage read or a comparison returns +as it is. +-/ + +namespace SolidCore.Refinement.Generic +open SolidCore.Solidity.Source + +/-- A return binding of the fragment: a `uint256`, an `address` or a `bool`, not a storage +reference. -/ +def wordBinding (b : BindingDecl) : Bool := + (match b.ty with | .uint256 => true | .address => true | .bool => true | _ => false) && + !b.isStorageRef + +/-- The width of the argument word of a parameter of the fragment, from its binding and its ABI +cleanup: `b` for a `uint256` with the cleanup `uint b`, `0 < b ≤ 256`, and 160 for an `address` with +no cleanup. -/ +def paramWidth (p : BindingDecl) (c : AbiCleanup) : Option Nat := + if p.isStorageRef then none + else + match p.ty, c with + | .uint256, .uint b => if 0 < b ∧ b ≤ 256 then some b else none + | .address, .none => some 160 + | _, _ => none + +/-- The widths of the parameters of the fragment, one per parameter and its ABI cleanup. -/ +def widthsOf : List BindingDecl → List AbiCleanup → Option (List Nat) + | [], [] => some [] + | p :: ps, c :: cs => do + let w ← paramWidth p c + let ws ← widthsOf ps cs + some (w :: ws) + | _, _ => none + +/-- The checks of the argument words from parameter `i` on, given their widths: a word of a +parameter of width `w < 256` above `2 ^ w - 1` reverts with empty data. -/ +def paramGuards : List Nat → Nat → Tree → Tree + | [], _, t => t + | w :: ws, i, t => + if w < 256 then + .ite (.bin .gt (.arg i) (.lit (2 ^ w - 1))) (.halt false [] [] []) (paramGuards ws (i + 1) t) + else paramGuards ws (i + 1) t + +/-- What the argument checks from parameter `i` on leave known: each word of a parameter of +width `w < 256` is at most `2 ^ w - 1`. -/ +def argFacts : List Nat → Nat → Facts + | [], _ => [] + | w :: ws, i => + if w < 256 then (.bin .gt (.arg i) (.lit (2 ^ w - 1)), false) :: argFacts ws (i + 1) + else argFacts ws (i + 1) + +/-- The parameters as locals: parameter `i` holds argument word `i`. -/ +def paramLocals : List BindingDecl → Nat → Locals + | [], _ => [] + | p :: ps, i => (p.name, .arg i) :: paramLocals ps (i + 1) + +/-- The state a call of `fn` starts in: one scope with its parameters and its returns at zero, +no writes and no logs. -/ +def initState (fn : FunctionDef) : SymState := + { scopes := [paramLocals fn.params 0 ++ fn.returns.map (fun r => (r.name, .lit 0))] + writes := [] + logs := [] } + +/-- A returned word SolidCore's encoder takes for its type on every call the facts hold on: any +word for a `uint256`, one below `2 ^ 160` for an `address`, at most 1 for a `bool`. -/ +def retOk (K : Facts) (ty : Ty) (w : WExpr) : Bool := + match ty with + | .uint256 => true + | .address => decide (bound K w < 2 ^ 160) + | .bool => decide (bound K w ≤ 1) + | _ => false + +/-- Every returned word is one SolidCore's encoder takes for its return's type. -/ +def retsOk (K : Facts) : List BindingDecl → List WExpr → Bool + | [], [] => true + | r :: rs, w :: ws => retOk K r.ty w && retsOk K rs ws + | _, _ => false + +/-- The bytes of SolidCore's `Error(msg)` revert data: the selector `0x08c379a0` and the ABI +encoding of the message, when every byte is one. -/ +def errorBytes (msg : String) : Option (List OByte) := + match ABI.encodeValues? [.bytesCalldata] [.bytes (ABI.stringBytes msg)] with + | some p => + let bs := ABI.encodeSelector ABI.errorSelector ++ p + if bs.all (· < 256) then some (bs.map .lit) else none + | none => none + +/-- How a call ends, from how its body ends: the returned words, ABI-encoded, or the named +returns when the body falls through or returns nothing, with the body's writes and logs; a +revert's data, with no writes and no logs. -/ +def leafTree (fn : FunctionDef) (K : Facts) : Leaf → Option Tree + | .normal S => do + let ws ← fn.returns.mapM fun r => Scopes.get? S.scopes r.name + if retsOk K fn.returns ws then some (.halt true (ws.flatMap wordOBytes) S.writes S.logs) + else none + | .returned S vs => + if vs = [] then do + let ws ← fn.returns.mapM fun r => Scopes.get? S.scopes r.name + if retsOk K fn.returns ws then some (.halt true (ws.flatMap wordOBytes) S.writes S.logs) + else none + else if retsOk K fn.returns vs then + some (.halt true (vs.flatMap wordOBytes) S.writes S.logs) + else none + | .reverted .empty => some (.halt false [] [] []) + | .reverted (.panic c) => some (.halt false (panicBytes c) [] []) + | .reverted (.error m) => (errorBytes m).map fun bs => .halt false bs [] [] + +/-- The call's tree from its body's branch tree. -/ +def brTree (fn : FunctionDef) (K : Facts) : Br → Option Tree + | .leaf l => leafTree fn K l + | .ite c t e => do + let t' ← brTree fn K t + let e' ← brTree fn K e + some (.ite c t' e') + +/-- The erasure of an external call of `fn` in the contract `E` describes: its argument checks, +then its body run with fuel `fuel`, knowing the facts the checks leave. -/ +def eraseFn (E : EraseEnv) (fuel : Nat) (fn : FunctionDef) : Option Tree := + match widthsOf fn.params fn.paramAbiCleanups with + | none => none + | some ws => + if fn.returns.all wordBinding then do + let b ← eraseStmt { E with facts := argFacts ws 0 } fuel fn.body (initState fn) + let t ← brTree fn (argFacts ws 0) b + some (paramGuards ws 0 t) + else none + +end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Generic/SourceRun.lean b/SolidCore/Refinement/Generic/SourceRun.lean new file mode 100644 index 00000000..2c3f714d --- /dev/null +++ b/SolidCore/Refinement/Generic/SourceRun.lean @@ -0,0 +1,938 @@ +import SolidCore.Refinement.Generic.SourceCall +import Verify.Run +import SolidCore.Refinement.Dirty.Source + +/-! +# SolidCore runs an external call of a function of the fragment as its tree + +`source_run` is the source half of the generic source stage: on a call of the function `fn` with +selector `sel` (call data `Abi.calldata sel args`, any argument words below `2 ^ 256`, no value, +initial storage `σ`) to a contract whose constructor leaves the storage entries `s` and no logs, +when `σ` writes every slot `s` does (`Covers s σ`), SolidCore's `Source.run` shows +`(T.eval ⟨args, slotValue σ, solHash, callerWord⟩).obs`, where `T` is the erasure `eraseFn` of `fn` in the +contract's `EraseEnv` (`envOf`: its storage fields, events and function table): the call's +argument words, its storage, and SolidCore's slot hash `solHash`. + +The proof follows SolidCore's ABI dispatcher. The decoder reads each argument word, rejecting an +`address` word at or above `2 ^ 160` with empty data, then applies the `uint b` cleanups, which +reject a word at or above `2 ^ b` with empty data (`decode_args`): so a call with an argument word +dirty for its parameter's width reverts with empty data (`run_rejected`), as the tree's argument +checks do (`paramGuards_eval`). Otherwise the selector reads back (`readSelector_calldata`), the +parameters decode to their words, the frame binds each parameter to its word and each return to +zero (`bindArgs_words`, `defaults_words`), the body runs as its branch tree (`eval_stmt`, from a +runtime that `StmtRel` relates to `initState`: the context's caller is `callerWord` and its events +are the contract's), and the end of the body is encoded as the leaf of the tree says: the returned +words (`collect_words`, `coerce_words`, `encode_words`) or the revert data (`encode_panic`). A +success keeps the body's storage, which `loadSlot_eq` reads as the tree's writes over `σ`, and its +events, which `logEntries_map` reads as the tree's logs; a failure keeps `σ` and logs nothing. +The call's storage reads as `slotValue σ` in every slot, the constructor's entries included, +because `σ` writes each of them (`getD_storage_cover`). +-/ + +namespace SolidCore.Refinement.Generic +open SolidCore.Solidity SolidCore.Solidity.Source SolidCore.Refinement + +/-- The erasure environment of a contract: its storage fields, its events and its function +table. -/ +def envOf (core : Contract) : EraseEnv := + { fields := core.storageFields, events := core.eventDecls, tbl := core.table } + +/-! ## The shape of the parameters -/ + +theorem paramWidth_spec {p : BindingDecl} {c : AbiCleanup} {w : Nat} (h : paramWidth p c = some w) : + p.isStorageRef = false ∧ + ((p.ty = .uint256 ∧ c = .uint w ∧ 0 < w ∧ w ≤ 256) ∨ (p.ty = .address ∧ c = .none ∧ w = 160)) := by + unfold paramWidth at h + split at h + · simp at h + rename_i hs + refine ⟨by simpa using hs, ?_⟩ + split at h + · split at h + · rename_i hb + simp only [Option.some.injEq] at h + subst h + exact .inl ⟨by assumption, rfl, hb⟩ + · simp at h + · simp only [Option.some.injEq] at h + exact .inr ⟨by assumption, rfl, h.symm⟩ + · simp at h + +theorem widthsOf_spec : ∀ {ps : List BindingDecl} {cs : List AbiCleanup} {ws : List Nat}, + widthsOf ps cs = some ws → + cs.length = ps.length ∧ ws.length = ps.length ∧ + (∀ p ∈ ps, (p.ty = .uint256 ∨ p.ty = .address) ∧ p.isStorageRef = false) ∧ + (∀ c ∈ cs, c = .none ∨ ∃ b, c = .uint b ∧ 0 < b ∧ b ≤ 256) + | [], [], ws, h => by + simp only [widthsOf, Option.some.injEq] at h + subst h + simp + | p :: ps, c :: cs, ws, h => by + simp only [widthsOf, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨w, hw, ws', hws', rfl⟩ := h + obtain ⟨h1, h2, h3, h4⟩ := widthsOf_spec hws' + obtain ⟨hs, hk⟩ := paramWidth_spec hw + refine ⟨by simp [h1], by simp [h2], ?_, ?_⟩ + · intro q hq + rcases List.mem_cons.mp hq with rfl | hq + · rcases hk with ⟨ht, -⟩ | ⟨ht, -⟩ + · exact ⟨.inl ht, hs⟩ + · exact ⟨.inr ht, hs⟩ + · exact h3 q hq + · intro d hd + rcases List.mem_cons.mp hd with rfl | hd + · rcases hk with ⟨-, hc, hb⟩ | ⟨-, hc, -⟩ + · exact .inr ⟨w, hc, hb⟩ + · exact .inl hc + · exact h4 d hd + | [], _ :: _, _, h | _ :: _, [], _, h => by simp [widthsOf] at h + +/-! ## Decoding the argument words -/ + +/-- Whether SolidCore's decoder accepts the word `a` for the type `ty`: an `address` word must be +below `2 ^ 160`. -/ +def decodeClean : Source.Ty → Nat → Bool + | .address, a => decide (a < 2 ^ 160) + | _, _ => true + +/-- Whether SolidCore's decoder accepts every argument word for its parameter's type. -/ +def decodeCleanAll : List Source.Ty → List Nat → Bool + | ty :: tys, a :: as => decodeClean ty a && decodeCleanAll tys as + | _, _ => true + +/-- Whether the word `a` passes the ABI cleanup `c`. -/ +def cleanArg : AbiCleanup → Nat → Bool + | .uint b, a => decide (a < 2 ^ b) + | _, _ => true + +/-- Whether every argument word passes its parameter's ABI cleanup. -/ +def cleanupsClean : List AbiCleanup → List Nat → Bool + | c :: cs, a :: as => cleanArg c a && cleanupsClean cs as + | _, _ => true + +/-- Whether every argument word fits its parameter's width. -/ +def argsClean : List Nat → List Nat → Bool + | w :: ws, a :: as => decide (a < 2 ^ w) && argsClean ws as + | _, _ => true + +theorem headWords_word {ty : Source.Ty} (h : ty = .uint256 ∨ ty = .address) : + ABI.Ty.abiHeadWords? ty = some 1 := by + rcases h with rfl | rfl <;> + simp [ABI.Ty.abiHeadWords?, ABI.Ty.isDynamicAbi, ABI.Ty.staticAbiHeadWords?] + +theorem listHeadWords_words : ∀ (tys : List Source.Ty), (∀ t ∈ tys, t = .uint256 ∨ t = .address) → + ABI.Ty.listAbiHeadWords? tys = some tys.length + | [], _ => rfl + | t :: ts, h => by + simp [ABI.Ty.listAbiHeadWords?, headWords_word (h t List.mem_cons_self), + listHeadWords_words ts (fun u hu => h u (List.mem_cons_of_mem _ hu)), Nat.add_comm] + +theorem decodeAux_words (args : List Nat) (hargs : ∀ a ∈ args, a < wordSize) : + ∀ (ps : List (Bool × Source.Ty)) (idx : Nat), (∀ p ∈ ps, p.2 = .uint256 ∨ p.2 = .address) → + idx + ps.length = args.length → + ABI.decodeArgsAux? (Dirty.argBytes args) ps idx = + if decodeCleanAll (ps.map Prod.snd) (args.drop idx) then .ok ((args.drop idx).map .word) + else .error .empty + | [], idx, _, hlen => by + simp only [List.length_nil, Nat.add_zero] at hlen + subst hlen + simp [ABI.decodeArgsAux?, decodeCleanAll] + | (lazy, ty) :: ps, idx, hps, hlen => by + have hi : idx < args.length := by simp at hlen; omega + have hr := Dirty.readWord_argBytes args hargs idx hi + have ih := decodeAux_words args hargs ps (idx + 1) + (fun p hp => hps p (List.mem_cons_of_mem _ hp)) (by simp at hlen; omega) + have hty : ty = .uint256 ∨ ty = .address := hps _ List.mem_cons_self + have ha := hargs _ (List.getElem_mem hi) + rw [List.drop_eq_getElem_cons hi] + rcases hty with rfl | rfl + · simp only [ABI.decodeArgsAux?, ABI.decodeValueAt?, ABI.Ty.abiDecodeFuel, + ABI.decodeValueAtWithFuel?, ABI.wordBytes, hr, ABI.abiArgOpt, + headWords_word (Or.inl rfl), bind, Except.bind, pure, Except.pure, ih, List.map_cons, + decodeCleanAll, decodeClean, Bool.true_and] + by_cases hc : decodeCleanAll (List.map Prod.snd ps) (List.drop (idx + 1) args) = true <;> + simp [hc] + · simp only [ABI.decodeArgsAux?, ABI.decodeValueAt?, ABI.Ty.abiDecodeFuel, + ABI.decodeValueAtWithFuel?, ABI.wordBytes, hr, ABI.abiArgOpt, ABI.addressFits, norm_lt ha, + headWords_word (Or.inr rfl), bind, Except.bind, pure, Except.pure, ih, List.map_cons, + decodeCleanAll, decodeClean] + by_cases h1 : args[idx] < 2 ^ 160 + · simp only [h1, decide_true, Bool.true_and, ↓reduceIte] + by_cases hc : decodeCleanAll (List.map Prod.snd ps) (List.drop (idx + 1) args) = true <;> + simp [hc] + · simp only [h1, decide_false, Bool.false_and, Bool.false_eq_true, ↓reduceIte] + +theorem lazyParamValues_words : ∀ (cs : List AbiCleanup) (args : List Nat), + (∀ c ∈ cs, c = .none ∨ ∃ b, c = .uint b ∧ 0 < b ∧ b ≤ 256) → cs.length = args.length → + (∀ a ∈ args, a < wordSize) → + AbiCleanups.lazyParamValues cs (args.map .word) = + if cleanupsClean cs args then some (args.map .word) else none + | [], [], _, _, _ => rfl + | c :: cs, a :: args, hc, hl, ha => by + have ih := lazyParamValues_words cs args (fun d hd => hc d (List.mem_cons_of_mem _ hd)) + (by simpa using hl) (fun b hb => ha b (List.mem_cons_of_mem _ hb)) + have hlt := ha a List.mem_cons_self + rcases hc c List.mem_cons_self with rfl | ⟨b, rfl, hb0, hb⟩ + · simp only [List.map_cons, AbiCleanups.lazyParamValues, AbiCleanup.lazyParamValue, ih, + cleanupsClean, cleanArg, Bool.true_and, bind, Option.bind] + by_cases hc : cleanupsClean cs args = true <;> simp [hc] + · by_cases h : a < 2 ^ b + · simp only [List.map_cons, AbiCleanups.lazyParamValues, ih, cleanupsClean, cleanArg, h, + decide_true, Bool.true_and] + by_cases hc : cleanupsClean cs args = true <;> + simp [AbiCleanup.lazyParamValue, AbiCleanup.accepts, norm_lt hlt, h, hb0, hb, bind, + Option.bind, hc] + · simp [AbiCleanups.lazyParamValues, AbiCleanup.lazyParamValue, AbiCleanup.accepts, + norm_lt hlt, h, hb0, hb, bind, Option.bind, cleanupsClean, cleanArg] + | [], _ :: _, _, hl, _ | _ :: _, [], _, hl, _ => by simp at hl + +theorem argsClean_widths : ∀ {ps : List BindingDecl} {cs : List AbiCleanup} {ws : List Nat} + (args : List Nat), widthsOf ps cs = some ws → args.length = ps.length → + argsClean ws args = (decodeCleanAll (ps.map BindingDecl.ty) args && cleanupsClean cs args) + | [], [], ws, [], h, _ => by + simp only [widthsOf, Option.some.injEq] at h + subst h + rfl + | p :: ps, c :: cs, ws, a :: args, h, hl => by + simp only [widthsOf, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨w, hw, ws', hws', rfl⟩ := h + have ih := argsClean_widths args hws' (by simpa using hl) + obtain ⟨-, hk⟩ := paramWidth_spec hw + simp only [argsClean, ih, List.map_cons, decodeCleanAll, cleanupsClean] + rcases hk with ⟨ht, rfl, -⟩ | ⟨ht, rfl, rfl⟩ + · simp only [ht, decodeClean, cleanArg, Bool.true_and] + cases decide (a < 2 ^ w) <;> cases decodeCleanAll (ps.map BindingDecl.ty) args <;> + cases cleanupsClean cs args <;> rfl + · simp only [ht, decodeClean, cleanArg, Bool.and_true] + cases decide (a < 2 ^ 160) <;> cases decodeCleanAll (ps.map BindingDecl.ty) args <;> + cases cleanupsClean cs args <;> rfl + | [], [], _, _ :: _, _, hl | _ :: _, _ :: _, _, [], _, hl => by simp at hl + | [], _ :: _, _, _, h, _ | _ :: _, [], _, _, h, _ => by simp [widthsOf] at h + +/-- **SolidCore decodes the argument words of a function of the fragment** to themselves when +each fits its parameter's width, and otherwise reverts with empty data. -/ +theorem decode_args {fn : FunctionDef} {ws : List Nat} + (hw : widthsOf fn.params fn.paramAbiCleanups = some ws) (args : List Nat) + (hlen : args.length = fn.params.length) (hargs : ∀ a ∈ args, a < wordSize) : + ABI.decodeFunctionArgs? fn (Dirty.argBytes args) = + if argsClean ws args then .ok (args.map .word) else .error .empty := by + obtain ⟨hcl, -, hp, hc⟩ := widthsOf_spec hw + have hflags : (fn.paramAbiCleanups.length == (fn.params.map BindingDecl.ty).length) = true := by + simp [hcl] + have hps : ∀ p ∈ (fn.paramAbiCleanups.map ABI.AbiCleanup.decodeLazy).zip + (fn.params.map BindingDecl.ty), p.2 = .uint256 ∨ p.2 = .address := by + intro p hp' + have := List.of_mem_zip hp' + obtain ⟨b, hb, he⟩ := List.mem_map.mp this.2 + rw [← he]; exact (hp b hb).1 + have hzl : ((fn.paramAbiCleanups.map ABI.AbiCleanup.decodeLazy).zip + (fn.params.map BindingDecl.ty)).length = args.length := by + simp [hcl, hlen] + have hsnd : ((fn.paramAbiCleanups.map ABI.AbiCleanup.decodeLazy).zip + (fn.params.map BindingDecl.ty)).map Prod.snd = fn.params.map BindingDecl.ty := + List.map_snd_zip (by simp [hcl]) + have hhw : ABI.Ty.listAbiHeadWords? (fn.params.map BindingDecl.ty) = some args.length := by + rw [listHeadWords_words _ (fun t ht => by + obtain ⟨b, hb, rfl⟩ := List.mem_map.mp ht + exact (hp b hb).1)] + simp [hlen] + have hdec := decodeAux_words args hargs _ 0 hps (by omega) + simp only [List.drop_zero, hsnd] at hdec + rw [argsClean_widths args hw hlen] + unfold ABI.decodeFunctionArgs? ABI.decodeArgsWith? + simp only [hflags, ↓reduceIte, hsnd, hhw, ABI.abiArgOpt, Dirty.length_argBytes, + ABI.wordBytes, Nat.lt_irrefl, bind, Except.bind, pure, Except.pure, hdec] + by_cases hd : decodeCleanAll (fn.params.map BindingDecl.ty) args = true + · simp only [hd, ↓reduceIte, Bool.true_and] + rw [lazyParamValues_words _ _ hc (by omega) hargs] + split + · rename_i hnil + have : args = [] := by + rw [List.isEmpty_iff] at hnil + rw [hnil] at hcl + simp at hcl + exact List.eq_nil_of_length_eq_zero (by omega) + subst this + cases fn.paramAbiCleanups <;> rfl + · by_cases hcc : cleanupsClean fn.paramAbiCleanups args = true <;> simp [hcc] + · simp only [hd, Bool.false_eq_true, ↓reduceIte, Bool.false_and] + +/-! ## The frame a call starts with -/ + +theorem coerce_word (v : Nat) : Source.Ty.uint256.coerceValue? (.word v) = some (.word v) := by + simp [Source.Ty.coerceValue?] + +theorem coerce_param {ty : Source.Ty} (h : ty = .uint256 ∨ ty = .address) (v : Nat) : + ty.coerceValue? (.word v) = some (.word v) := + (wordTy_coerce (by rcases h with rfl | rfl <;> rfl) v).1 + +/-- The parameters bind to the argument words, as `paramLocals` says. -/ +theorem bindArgs_words (ρ : Val) (hρ : ∀ a ∈ ρ.args, a < wordSize) : + ∀ (ps : List BindingDecl) (i : Nat), + (∀ p ∈ ps, (p.ty = .uint256 ∨ p.ty = .address) ∧ p.isStorageRef = false) → + i + ps.length = ρ.args.length → + BindingDecl.bindArgs? ps ((ρ.args.drop i).map .word) = some (frameOf ρ (paramLocals ps i)) + | [], i, _, h => by + simp only [List.length_nil, Nat.add_zero] at h + subst h + simp [BindingDecl.bindArgs?, paramLocals, frameOf] + | p :: ps, i, hps, h => by + have hi : i < ρ.args.length := by simp at h; omega + have ih := bindArgs_words ρ hρ ps (i + 1) (fun q hq => hps q (List.mem_cons_of_mem _ hq)) + (by simp at h; omega) + have hty := (hps p List.mem_cons_self).1 + have hlt := hρ _ (List.getElem_mem hi) + rw [List.drop_eq_getElem_cons hi] + simp only [List.map_cons, BindingDecl.bindArgs?, BindingDecl.bindArg?, coerce_param hty, ih, + bind, Option.bind, paramLocals, frameOf, List.map_cons, WExpr.eval, List.getD_eq_getElem?_getD, + List.getElem?_eq_getElem hi, Option.getD_some, Nat.mod_eq_of_lt hlt] + +/-- A return the fragment encodes: a `uint256`, `address` or `bool`. -/ +abbrev RetTy (ty : Source.Ty) : Prop := ty = .uint256 ∨ ty = .address ∨ ty = .bool + +theorem defaults_words (ρ : Val) (rs : List BindingDecl) + (hrs : ∀ r ∈ rs, RetTy r.ty ∧ r.isStorageRef = false) : + rs.map BindingDecl.defaultBinding = frameOf ρ (rs.map fun r => (r.name, WExpr.lit 0)) := by + induction rs with + | nil => rfl + | cons r rs ih => + have h := hrs r List.mem_cons_self + simp only [List.map_cons, frameOf] at ih ⊢ + rw [ih (fun q hq => hrs q (List.mem_cons_of_mem _ hq))] + rcases h.1 with h1 | h1 | h1 <;> + simp [BindingDecl.defaultBinding, h1, h.2, Source.Ty.defaultValue, WExpr.eval] + +/-- A word `retOk` accepts is one SolidCore coerces to its return's type and encodes as its +32-byte word. -/ +theorem retOk_spec {ρ : Val} {K : Facts} (hK : K.Hold ρ) {ty : Source.Ty} {w : WExpr} + (h : retOk K ty w = true) : + ty.coerceValue? (.word (w.eval ρ)) = some (.word (w.eval ρ)) ∧ + ABI.Ty.isDynamicAbi ty = false ∧ ABI.Ty.staticAbiHeadWords? ty = some 1 ∧ + ABI.encodeStaticValue? ty (.word (w.eval ρ)) = some (ABI.encodeWord (w.eval ρ)) := by + have hlt := w.eval_lt ρ + unfold retOk at h + split at h + · exact ⟨by simp [Source.Ty.coerceValue?], rfl, rfl, rfl⟩ + · simp only [decide_eq_true_eq] at h + have hn : w.eval ρ < 1461501637330902918203684832716283019655932542976 := + Nat.lt_of_le_of_lt (bound_sound hK w) h + exact ⟨by simp [Source.Ty.coerceValue?], rfl, rfl, + by simp [ABI.encodeStaticValue?, ABI.addressFits, norm_lt hlt, hn]⟩ + · simp only [decide_eq_true_eq] at h + have hn : w.eval ρ ≤ 1 := Nat.le_trans (bound_sound hK w) h + have hv : w.eval ρ = 0 ∨ w.eval ρ = 1 := by omega + rcases hv with hv | hv <;> + exact ⟨by simp [Source.Ty.coerceValue?, wordEq, hv], rfl, rfl, + by simp [ABI.encodeStaticValue?, wordEq, hv]⟩ + · simp at h + +theorem retsOk_length {K : Facts} : ∀ {rs : List BindingDecl} {ws : List WExpr}, + retsOk K rs ws = true → ws.length = rs.length + | [], [], _ => rfl + | _ :: rs, _ :: ws, h => by + simp only [retsOk, Bool.and_eq_true] at h + simp [retsOk_length h.2] + | [], _ :: _, h | _ :: _, [], h => by simp [retsOk] at h + +/-! ## Reading the returned words -/ + +theorem deref_word (rt : Runtime) (v : Nat) : rt.derefMemoryValueDeep (.word v) = .ok (.word v) := by + simp [Runtime.derefMemoryValueDeep, Runtime.derefMemoryValueWithFuel] + +theorem collect_words (ρ : Val) (rt : Runtime) (S : SymState) {K : Facts} (hK : K.Hold ρ) + (hl : ∀ x e, Scopes.get? S.scopes x = some e → rt.lookupLocal? x = some (.word (e.eval ρ))) : + ∀ (rs : List BindingDecl) (ws : List WExpr), retsOk K rs ws = true → + rs.mapM (fun r => Scopes.get? S.scopes r.name) = some ws → + collectReturnBindings.collect rt rs = .ok (ws.map fun e => .word (e.eval ρ)) + | [], ws, _, h => by + simp only [List.mapM_nil, Option.pure_def, Option.some.injEq] at h + subst h; rfl + | r :: rs, ws, hrs, h => by + simp only [List.mapM_cons, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.pure_def, + Option.some.injEq] at h + obtain ⟨e, he, ws', hws', rfl⟩ := h + simp only [retsOk, Bool.and_eq_true] at hrs + have ih := collect_words ρ rt S hK hl rs ws' hrs.2 hws' + simp [collectReturnBindings.collect, hl _ _ he, deref_word, (retOk_spec hK hrs.1).1, ih, bind, + Except.bind, pure, Except.pure] + +theorem coerce_words (ρ : Val) (rt : Runtime) {K : Facts} (hK : K.Hold ρ) : + ∀ (rs : List BindingDecl) (ws : List WExpr), retsOk K rs ws = true → + coerceReturnBindings.coerce rt rs (ws.map fun e => .word (e.eval ρ)) = + .ok (ws.map fun e => .word (e.eval ρ)) + | [], [], _ => rfl + | r :: rs, e :: ws, hrs => by + simp only [retsOk, Bool.and_eq_true] at hrs + have ih := coerce_words ρ rt hK rs ws hrs.2 + simp only [List.map_cons] at ih ⊢ + simp [coerceReturnBindings.coerce, deref_word, (retOk_spec hK hrs.1).1, ih, + bind, Except.bind, pure, Except.pure] + | [], _ :: _, h | _ :: _, [], h => by simp [retsOk] at h + +/-! ## Encoding the output -/ + +theorem wordToBytesBE_eq : ∀ (n v : Nat), + ABI.wordToBytesBE n v = (List.range n).map fun i => v / 256 ^ (n - 1 - i) % 256 + | 0, _ => rfl + | n + 1, v => by + rw [ABI.wordToBytesBE, wordToBytesBE_eq n (v / 256), List.range_succ, List.map_append] + congr 1 + · apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [Nat.div_div_eq_div_mul, ← Nat.pow_succ', show (n - 1 - i).succ = n + 1 - 1 - i by omega] + · simp [normByte, SolidCore.Solidity.Shared.Account.byte] + +theorem div_pow_mod (v k : Nat) (hk : k < 32) : v % wordSize / 256 ^ k % 256 = v / 256 ^ k % 256 := by + have hw : wordSize = 256 ^ k * 256 ^ (32 - k) := by + rw [← Nat.pow_add, show k + (32 - k) = 32 by omega] + rw [hw, Nat.mod_mul_right_div_self, Nat.mod_mod_of_dvd] + have := Nat.pow_dvd_pow 256 (show 1 ≤ 32 - k by omega) + simpa using this + +theorem encodeWord_eq (v : Nat) : + ABI.encodeWord v = (List.range 32).map fun i => v / 256 ^ (31 - i) % 256 := by + rw [ABI.encodeWord, ABI.wordBytes, wordToBytesBE_eq] + apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + simp only [SolidCore.Solidity.Shared.norm, modulus_eq, show 32 - 1 - i = 31 - i by omega] + exact div_pow_mod v _ (by omega) + +theorem encodeWord_eval (ρ : Val) (e : WExpr) : + ABI.encodeWord (e.eval ρ) = (wordOBytes e).map (OByte.eval ρ) := by + rw [encodeWord_eq, wordOBytes, List.map_map] + rfl + +theorem litBytes_eval (ρ : Val) (n : Nat) : + (litBytes 32 n).map (OByte.eval ρ) = ABI.encodeWord n := by + rw [encodeWord_eq, litBytes, List.map_map] + apply List.map_congr_left + intro i hi + simp [OByte.eval, show 32 - 1 - i = 31 - i by omega] + +theorem encodeAux_words (ρ : Val) {K : Facts} (hK : K.Hold ρ) : + ∀ (rs : List BindingDecl) (ws : List WExpr) (off : Nat), retsOk K rs ws = true → + ABI.encodeValuesAux? (rs.map BindingDecl.ty) (ws.map fun e => .word (e.eval ρ)) off = + some ((ws.flatMap wordOBytes).map (OByte.eval ρ), [], off) + | [], [], _, _ => rfl + | r :: rs, e :: ws, off, hrs => by + simp only [retsOk, Bool.and_eq_true] at hrs + have ih := encodeAux_words ρ hK rs ws off hrs.2 + obtain ⟨-, hd, -, he⟩ := retOk_spec hK hrs.1 + simp only [List.map_cons, ABI.encodeValuesAux?, hd, he, ih, Bool.false_eq_true, ↓reduceIte, + List.flatMap_cons, List.map_append, encodeWord_eval] + | [], _ :: _, _, h | _ :: _, [], _, h => by simp [retsOk] at h + +theorem encode_words (ρ : Val) {K : Facts} (hK : K.Hold ρ) (rs : List BindingDecl) (ws : List WExpr) + (hrs : retsOk K rs ws = true) : + ABI.encodeValues? (rs.map BindingDecl.ty) (ws.map fun e => .word (e.eval ρ)) = + some ((ws.flatMap wordOBytes).map (OByte.eval ρ)) := by + have hhw : ∀ (rs : List BindingDecl) (ws : List WExpr), retsOk K rs ws = true → + ABI.Ty.listAbiHeadWords? (rs.map BindingDecl.ty) = some rs.length := by + intro rs + induction rs with + | nil => intro ws _; rfl + | cons r rs ih => + intro ws h + cases ws with + | nil => simp [retsOk] at h + | cons w ws => + simp only [retsOk, Bool.and_eq_true] at h + obtain ⟨-, hd, hw, -⟩ := retOk_spec (ρ := ρ) hK h.1 + simp [ABI.Ty.listAbiHeadWords?, ABI.Ty.abiHeadWords?, hd, hw, ih ws h.2, Nat.add_comm] + simp [ABI.encodeValues?, hhw rs ws hrs, encodeAux_words ρ hK rs ws _ hrs, bind, Option.bind] + +theorem encode_panic (ρ : Val) (core : Contract) (c : Nat) : + ABI.Contract.encodeRevertData? core (.panic c) = some ((panicBytes c).map (OByte.eval ρ)) := by + have h2 : ABI.encodeValues? [Source.Ty.uint256] [Value.word c] = + some ((litBytes 32 c).map (OByte.eval ρ)) := by + rw [litBytes_eval] + simp [ABI.encodeValues?, ABI.Ty.listAbiHeadWords?, ABI.Ty.abiHeadWords?, ABI.Ty.isDynamicAbi, + ABI.Ty.staticAbiHeadWords?, ABI.encodeValuesAux?, ABI.encodeStaticValue?, bind, Option.bind] + simp only [ABI.Contract.encodeRevertData?, h2, panicBytes, List.map_append] + congr 2 + +/-- SolidCore's `Error(msg)` revert data are `errorBytes msg`. -/ +theorem encode_error (ρ : Val) (core : Contract) {m : String} {bs : List OByte} + (h : errorBytes m = some bs) : + ABI.Contract.encodeRevertData? core (.error m) = some (bs.map (OByte.eval ρ)) := by + unfold errorBytes at h + split at h + · rename_i p hp + dsimp only at h + split at h + · rename_i hall + simp only [Option.some.injEq] at h + subst h + simp only [ABI.Contract.encodeRevertData?, hp, List.map_map, Option.some.injEq] + symm + have hid : ∀ b ∈ ABI.encodeSelector ABI.errorSelector ++ p, (OByte.eval ρ ∘ OByte.lit) b = id b := + fun b hb => by + simp only [Function.comp, OByte.eval, id] + exact Nat.mod_eq_of_lt (by simpa using List.all_eq_true.mp hall b hb) + rw [List.map_congr_left hid, List.map_id] + · simp at h + · simp at h + +/-! ## The call -/ + +theorem brTree_eval (fn : FunctionDef) (K : Facts) (ρ : Val) : + ∀ (b : Br) (T : Tree), brTree fn K b = some T → + ∃ T', leafTree fn K (b.eval ρ) = some T' ∧ T'.eval ρ = T.eval ρ + | .leaf l, T, h => ⟨T, h, rfl⟩ + | .ite c t e, T, h => by + simp only [brTree, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨t', ht, e', he, rfl⟩ := h + simp only [Br.eval, Tree.eval] + split + · exact brTree_eval fn K ρ e e' he + · exact brTree_eval fn K ρ t t' ht + +theorem slotValue_lt (σ : List (Nat × Nat)) (k : Nat) : slotValue σ k < wordSize := by + unfold slotValue + have key : ∀ a, a < wordSize → σ.foldl (fun acc kv => if kv.1 % 2 ^ 256 = k % 2 ^ 256 then + kv.2 % 2 ^ 256 else acc) a < wordSize := by + induction σ with + | nil => intro a h; exact h + | cons kv σ ih => + intro a h + simp only [List.foldl_cons] + apply ih + split + · exact Nat.mod_lt _ (by decide) + · exact h + exact key 0 (by decide) + +theorem slotValue_mod (σ : List (Nat × Nat)) (k : Nat) : slotValue σ (k % wordSize) = slotValue σ k := by + simp only [slotValue, Nat.mod_mod] + +theorem length_of_mapM {α β : Type} (f : α → Option β) : + ∀ (l : List α) (ws : List β), l.mapM f = some ws → ws.length = l.length + | [], ws, h => by simp at h; subst h; rfl + | a :: l, ws, h => by + simp only [List.mapM_cons, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.pure_def, + Option.some.injEq] at h + obtain ⟨b, -, ws', h', rfl⟩ := h + simp [length_of_mapM f l ws' h'] + +theorem slotValue_store (σ : List (Nat × Nat)) (k : Nat) : + slotValue σ (k % wordSize) % wordSize = slotValue σ k := by + rw [slotValue_mod, Nat.mod_eq_of_lt (slotValue_lt σ k)] + +/-- A storage that holds, in every slot below `2 ^ 256`, the word the writes leave there reads so +in every slot. -/ +theorem loadSlot_eq (st : State) (ws : Writes) (ρ : Val) (hρ : ρ.Ok) + (h : ∀ k, k < wordSize → st.loadSlot k = Writes.store ρ ws k) (slot : Nat) : + st.loadSlot slot = Writes.store ρ ws slot := by + rw [← loadSlot_mod, h _ (Nat.mod_lt _ (by decide)), Writes.store_mod ρ hρ] + +/-- What SolidCore's state shows of its events as logs. -/ +theorem logEntries_map (st : State) (self : Nat) : + (st.logEntries self).map (fun e => (e.topics, e.data)) = st.events.map logOf := by + simp [State.logEntries, Event.toLogEntry, logOf] + +theorem untag_words (ρ : Val) (ws : List WExpr) : + (ws.map fun e => Value.word (e.eval ρ)).map Value.untagFixedBytes = + ws.map fun e => Value.word (e.eval ρ) := by + simp [Value.untagFixedBytes] + +/-! ## The deployed storage -/ + +/-- The call's storage `σ` writes every slot the constructor's entries `s` write. -/ +def Covers (s σ : List (Nat × Nat)) : Prop := ∀ kv ∈ s, ∃ kv' ∈ σ, kv'.1 % wordSize = kv.1 % wordSize + +theorem getD_foldl_cover (k : Nat) : ∀ (σ : List (Nat × Nat)) (a : Option Nat) (b : Nat), + (a.getD 0 = b ∨ ∃ kv ∈ σ, kv.1 % wordSize = k % wordSize) → + (σ.foldl (fun acc kv => if SolidCore.Solidity.Shared.norm kv.1 = k % 2 ^ 256 then + some (SolidCore.Solidity.Shared.norm kv.2) else acc) a).getD 0 = + σ.foldl (fun acc kv => if kv.1 % 2 ^ 256 = k % 2 ^ 256 then kv.2 % 2 ^ 256 else acc) b + | [], a, b, h => by + rcases h with h | ⟨_, h, _⟩ + · simpa using h + · simp at h + | kv :: σ, a, b, h => by + simp only [List.foldl_cons] + apply getD_foldl_cover k σ + by_cases hk : kv.1 % wordSize = k % wordSize + · left + have hk' : SolidCore.Solidity.Shared.norm kv.1 = k % 2 ^ 256 := hk + rw [if_pos hk', if_pos hk] + rfl + · have hk' : ¬ SolidCore.Solidity.Shared.norm kv.1 = k % 2 ^ 256 := hk + rw [if_neg hk', if_neg hk] + rcases h with h | ⟨kv', hm, he⟩ + · exact Or.inl h + · rcases List.mem_cons.mp hm with rfl | hm + · exact absurd he hk + · exact Or.inr ⟨kv', hm, he⟩ + +/-- A slot of the storage a call writes over the deployed storage reads as `slotValue`, when +the call's storage writes every slot of the deployed one. -/ +theorem getD_storage_cover {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {σ : List (Nat × Nat)} + (hcov : Covers s σ) (k : Nat) : + ((σ.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) d.storage)[k % 2 ^ 256]?).getD 0 = + slotValue σ k := by + rw [Verify.getElem?_foldl_insertLoop] + apply getD_foldl_cover k σ _ 0 + cases h : d.storage[k % 2 ^ 256]? with + | none => exact Or.inl rfl + | some v => + right + have hm : (k % 2 ^ 256, v) ∈ s := hd.storage ▸ Std.HashMap.mem_toList_iff_getElem?_eq_some.mpr h + obtain ⟨kv', hkv', he⟩ := hcov _ hm + exact ⟨kv', hkv', by rw [he]; exact Nat.mod_mod _ _⟩ + +theorem deployedStorage_of {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) : + ∃ s0, Abi.deployedStorage fuel c = some s0 := by + obtain ⟨vs, hc⟩ := hd.cons + unfold Abi.deployedStorage + have hc' : TypeCheck.CheckedContract.constructWithContext? fuel c + { c.core.context with sender := callerAddress, self := selfAddress, value := 0 } State.empty + selfAddress 0 [] = some (CallResult.returned d vs) := hc + simp only [hc'] + exact ⟨_, rfl⟩ + + +/-! ## Dirty argument words -/ + +/-- The tree of a call with argument checks: their revert when an argument word is dirty for its +width, else the tree they guard. -/ +theorem paramGuards_eval (ρ : Val) (t : Tree) (hρ : ∀ a ∈ ρ.args, a < wordSize) : + ∀ (ws : List Nat) (i : Nat), + (paramGuards ws i t).eval ρ = + if argsClean ws (ρ.args.drop i) then t.eval ρ + else { success := false, output := [], logs := [], store := ρ.store } + | [], i => by simp [paramGuards, argsClean] + | w :: ws, i => by + have ih := paramGuards_eval ρ t hρ ws (i + 1) + cases hdrop : ρ.args.drop i with + | nil => + have hge : ρ.args.length ≤ i := by simpa using hdrop + have hd1 : ρ.args.drop (i + 1) = [] := by simp; omega + have harg : (WExpr.arg i).eval ρ = 0 := by + simp [WExpr.eval, List.getD_eq_getElem?_getD, List.getElem?_eq_none hge] + rw [hd1] at ih + simp only [argsClean] at ih ⊢ + simp only [paramGuards] + split + · simp only [Tree.eval, ih, ite_true] + rw [if_pos] + simp only [eval_bin, harg, eval_lit, BinOp.eval] + simp + · simpa using ih + | cons a as => + have hi : i < ρ.args.length := by + have := congrArg List.length hdrop; simp at this; omega + have ha : ρ.args.getD i 0 = a := by + rw [List.getD_eq_getElem?_getD, ← List.head?_drop, hdrop]; rfl + have hd1 : ρ.args.drop (i + 1) = as := by + rw [← List.drop_drop, hdrop]; rfl + have halt : a < wordSize := by + rw [← ha, List.getD_eq_getElem?_getD, List.getElem?_eq_getElem hi] + exact hρ _ (List.getElem_mem hi) + rw [hd1] at ih + simp only [argsClean, paramGuards] + split + · rename_i hw256 + have hpos := Nat.two_pow_pos w + have hm : (2 ^ w - 1) % wordSize = 2 ^ w - 1 := + Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le (Nat.sub_lt hpos (by decide)) + (Nat.pow_le_pow_right (by decide) (by omega))) + simp only [Tree.eval, ih, eval_bin, eval_lit, WExpr.eval, ha, Nat.mod_eq_of_lt halt, hm, + BinOp.eval] + by_cases hc2 : a < 2 ^ w + · have : ¬ 2 ^ w - 1 < a := by omega + simp [this, hc2] + · have : 2 ^ w - 1 < a := by omega + simp [this, hc2] + · rename_i hw256 + have : a < 2 ^ w := Nat.lt_of_lt_of_le halt (Nat.pow_le_pow_right (by decide) (by omega)) + simp [ih, this] + +/-- Past the argument checks, the facts they leave hold. -/ +theorem argFacts_hold (ρ : Val) (hρ : ∀ a ∈ ρ.args, a < wordSize) : + ∀ (ws : List Nat) (i : Nat), argsClean ws (ρ.args.drop i) = true → (argFacts ws i).Hold ρ + | [], _, _ => by simp [argFacts, Facts.Hold] + | w :: ws, i, h => by + have key : ∀ a, (WExpr.arg i).eval ρ = a → a < 2 ^ w → argsClean ws (ρ.args.drop (i + 1)) = true → + (argFacts (w :: ws) i).Hold ρ := by + intro a ha haw hrest + have ih := argFacts_hold ρ hρ ws (i + 1) hrest + simp only [argFacts] + split + · rename_i hw256 + refine Facts.Hold.cons ih ?_ + have hpos := Nat.two_pow_pos w + have hm : (2 ^ w - 1) % wordSize = 2 ^ w - 1 := + Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le (Nat.sub_lt hpos (by decide)) + (Nat.pow_le_pow_right (by decide) (by omega))) + have : ¬ 2 ^ w - 1 < a := by omega + simp only [eval_bin, eval_lit, ha, hm, BinOp.eval] + simp [this] + · exact ih + cases hdrop : ρ.args.drop i with + | nil => + have hge : ρ.args.length ≤ i := by simpa using hdrop + have hd1 : ρ.args.drop (i + 1) = [] := by simp; omega + have harg : (WExpr.arg i).eval ρ = 0 := by + simp [WExpr.eval, List.getD_eq_getElem?_getD, List.getElem?_eq_none hge] + refine key 0 harg (Nat.two_pow_pos w) ?_ + rw [hd1]; cases ws <;> rfl + | cons a as => + have hi : i < ρ.args.length := by + have := congrArg List.length hdrop; simp at this; omega + have ha : ρ.args.getD i 0 = a := by + rw [List.getD_eq_getElem?_getD, ← List.head?_drop, hdrop]; rfl + have hd1 : ρ.args.drop (i + 1) = as := by + rw [← List.drop_drop, hdrop]; rfl + have halt : a < wordSize := by + rw [← ha, List.getD_eq_getElem?_getD, List.getElem?_eq_getElem hi] + exact hρ _ (List.getElem_mem hi) + rw [hdrop] at h + simp only [argsClean, Bool.and_eq_true, decide_eq_true_eq] at h + refine key a ?_ h.1 (by rw [hd1]; exact h.2) + have ha' : ρ.args[i]?.getD 0 = a := by rw [← List.getD_eq_getElem?_getD]; exact ha + simp [WExpr.eval, ha', Nat.mod_eq_of_lt halt] + +/-- **SolidCore rejects dirty argument words**: a call whose argument words SolidCore's decoder +rejects with empty data reverts with empty output and keeps the call's storage. -/ +theorem run_rejected {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {sel : Nat} (hsel : sel < 2 ^ 32) + {fn : FunctionDef} (hfind : c.core.findFunctionBySelector? sel = some fn) (args : List Nat) + (hdec : ABI.decodeFunctionArgs? fn (Dirty.argBytes args) = .error .empty) + (σ : List (Nat × Nat)) : + Source.run fuel c { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } = + some (Abi.rejected σ) := by + obtain ⟨s0, hdep⟩ := deployedStorage_of hd + unfold Abi.deployedStorage at hdep + dsimp only at hdep + split at hdep + case h_2 => simp at hdep + rename_i deployed st hcons + simp only [Source.run, Source.result?, hcons, + TypeCheck.CheckedContract.callCalldataAtFromWithContext?, + ABI.Contract.callCalldataAtFromWithContext?, Dirty.bytes_calldata, + Dirty.readSelector_calldata _ hsel, hfind] + rw [show ((EthLib.Base.natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes args).drop + ABI.selectorBytes = Dirty.argBytes args by + simp [ABI.selectorBytes, EthLib.Base.natToBytes_length], hdec] + simp only [ABI.Contract.revertedCall?, ABI.Contract.encodeRevertData?, bind, Option.bind, + Option.map_some, Source.observe, Abi.rejected] + simp + +/-! ## The call -/ + +theorem wordBinding_ty {b : BindingDecl} (h : wordBinding b = true) : + RetTy b.ty ∧ b.isStorageRef = false := by + unfold wordBinding at h + simp only [Bool.and_eq_true, Bool.not_eq_true'] at h + refine ⟨?_, h.2⟩ + have := h.1 + split at this + · rename_i h'; exact .inl h' + · rename_i h'; exact .inr (.inl h') + · rename_i h'; exact .inr (.inr h') + · simp at this + +/-- The parameter widths of a function the erasure accepts. -/ +theorem eraseFn_widths {E : EraseEnv} {fuel : Nat} {fn : FunctionDef} {T : Tree} + (h : eraseFn E fuel fn = some T) : ∃ ws, widthsOf fn.params fn.paramAbiCleanups = some ws := by + unfold eraseFn at h + split at h + · simp at h + · rename_i ws hw + exact ⟨ws, hw⟩ + +/-- SolidCore runs a call of a function of the fragment on clean argument words as its body's +tree. -/ +theorem source_run_clean {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {σ : List (Nat × Nat)} + (hcov : Covers s σ) {sel : Nat} (hsel : sel < 2 ^ 32) {fn : FunctionDef} + (hfind : c.core.findFunctionBySelector? sel = some fn) {ws : List Nat} + (hw : widthsOf fn.params fn.paramAbiCleanups = some ws) + (hret : fn.returns.all wordBinding = true) {b : Br} + (hb : eraseStmt { envOf c.core with facts := argFacts ws 0 } fuel fn.body (initState fn) = some b) + {T : Tree} (hT : brTree fn (argFacts ws 0) b = some T) (args : List Nat) + (hlen : args.length = fn.params.length) (hargs : ∀ a ∈ args, a < 2 ^ 256) + (hclean : argsClean ws args = true) + (hdec : ABI.decodeFunctionArgs? fn (Dirty.argBytes args) = .ok (args.map .word)) : + Source.run fuel c { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } = + some (T.eval ⟨args, slotValue σ, solHash, callerWord⟩).obs := by + rw [SolidCore.Refinement.Wide.callAt_of_args sel args hargs σ, + SolidCore.Refinement.Wide.run_eq_at hd, SolidCore.Refinement.Wide.map_ofNat_toNat args hargs] + have hdrop : ((EthLib.Base.natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes args).drop + ABI.selectorBytes = Dirty.argBytes args := by + simp [ABI.selectorBytes, EthLib.Base.natToBytes_length] + simp only [ABI.Contract.callCalldataAtFromWithContext?, Dirty.readSelector_calldata _ hsel, hfind, + hdrop, hdec] + have hp := (widthsOf_spec hw).2.2.1 + have hr : ∀ r ∈ fn.returns, RetTy r.ty ∧ r.isStorageRef = false := + fun r hr => wordBinding_ty (List.all_eq_true.mp hret r hr) + generalize hctx : ABI.Contract.callContextAtWithBase c.core (Wide.ctxOf c) selfAddress callerAddress 0 + ((EthLib.Base.natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes args) = ctx + generalize hst : ({ d with storage := σ.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) d.storage } : + Source.State) = st0 + have hacc : fn.acceptsValue 0 = true := by + simp [FunctionDef.acceptsValue, wordEq] + have hctxv : ctx.value = 0 := by + subst hctx; simp [ABI.Contract.callContextAtWithBase, SolidCore.Solidity.Shared.norm] + set ρ : Val := ⟨args, slotValue σ, solHash, callerWord⟩ with hρ + have hρok : ρ.Ok := slotValue_store σ + set K := argFacts ws 0 with hK + have hKρ : K.Hold ρ := argFacts_hold ρ hargs ws 0 (by simpa [hρ] using hclean) + set E : EraseEnv := { envOf c.core with facts := K } with hE + have hframe : fn.initialFrame? (args.map .word) = + some (frameOf ρ (paramLocals fn.params 0 ++ fn.returns.map fun r => (r.name, .lit 0))) := by + have h0 : BindingDecl.bindArgs? fn.params (args.map .word) = + some (frameOf ρ (paramLocals fn.params 0)) := + bindArgs_words ρ hargs fn.params 0 hp (by simp [hρ, hlen]) + simp only [FunctionDef.initialFrame?, h0, FunctionDef.returnDefaultBindings, + defaults_words ρ fn.returns hr, frameOf, List.map_append] + have hrel : StmtRel ρ E ctx + { state := { st0 with + selfBalance := SolidCore.Solidity.Shared.addWord + (SolidCore.Solidity.Shared.Account.balanceAt ctx.accountBalances ctx.self) ctx.value + worldMutatedSinceAdoption := true }, + locals := [frameOf ρ (paramLocals fn.params 0 ++ fn.returns.map fun r => (r.name, .lit 0))] } + (initState fn) := + { fields := by subst hctx; rfl + events := by subst hctx; rfl + checked := by subst hctx; rfl + sender := by subst hctx; rfl + hash := rfl + ok := hρok + frames := rfl + store := by + intro k hk + have := getD_storage_cover hd hcov k + subst hst + simp only [State.loadSlot, StorageMap.lookup?, initState, Writes.store, hρ] + rw [← this] + simp only [SolidCore.Solidity.Shared.norm, modulus_eq, Std.HashMap.get?_eq_getElem?] + cases (List.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) d.storage σ)[k % wordSize]? <;> rfl + logs := by subst hst; simp [hd.events, initState] + facts := hKρ } + obtain ⟨r, hrun, hleaf⟩ := eval_stmt ρ E ctx fuel fn.body (initState fn) b hb _ hrel + have hcall : fn.call? fuel c.core.table ctx st0 (args.map .word) = + some (fn.callBodyResult st0 r) := by + have hacc' : fn.acceptsValue ctx.value = true := hctxv ▸ hacc + simp only [FunctionDef.call?, FunctionDef.call, FunctionDef.evalBodyEntry, hacc', hframe, + if_true, Option.map_some, Option.bind_some] + rw [show c.core.table = E.tbl from rfl, hrun] + rfl + obtain ⟨T', hT', hTe⟩ := brTree_eval fn K ρ b T hT + rw [hacc, if_pos rfl, hcall, ← hTe] + generalize b.eval ρ = l at hT' hleaf + cases l with + | normal S => + cases r <;> simp only [LeafRel] at hleaf + rename_i rt + simp only [leafTree, Option.bind_eq_bind, Option.bind_eq_some_iff] at hT' + obtain ⟨ws, hws, hT'⟩ := hT' + split at hT' + case isFalse => simp at hT' + rename_i hok + simp only [Option.some.injEq] at hT' + subst hT' + simp only [FunctionDef.callBodyResult, FunctionDef.collectReturns, collectReturnBindings, + collect_words ρ rt S hKρ hleaf.expr.locals fn.returns ws hok hws, untag_words, + encode_words ρ hKρ fn.returns ws hok, bind, Option.bind, Option.map_some] + simp only [Source.observe, Tree.eval, Res.obs, if_true, ↓reduceIte, logEntries_map, + hleaf.logs, Option.some.injEq, Observable.mk.injEq, true_and] + funext slot + exact loadSlot_eq _ S.writes ρ hρok hleaf.store slot + | returned S vs => + cases r <;> simp only [LeafRel] at hleaf + rename_i rt vals + obtain ⟨hst', rfl⟩ := hleaf + by_cases hv : vs = [] + · subst hv + simp only [leafTree, if_true, Option.bind_eq_bind, Option.bind_eq_some_iff] at hT' + obtain ⟨ws, hws, hT'⟩ := hT' + split at hT' + case isFalse => simp at hT' + rename_i hok + simp only [Option.some.injEq] at hT' + subst hT' + simp only [FunctionDef.callBodyResult, List.map_nil, List.isEmpty_nil, if_true, + FunctionDef.collectReturns, collectReturnBindings, + collect_words ρ rt S hKρ hst'.expr.locals fn.returns ws hok hws, untag_words, + encode_words ρ hKρ fn.returns ws hok, bind, Option.bind, Option.map_some] + simp only [Source.observe, Tree.eval, Res.obs, if_true, ↓reduceIte, logEntries_map, + hst'.logs, Option.some.injEq, Observable.mk.injEq, true_and] + funext slot + exact loadSlot_eq _ S.writes ρ hρok hst'.store slot + · simp only [leafTree, hv, if_false] at hT' + split at hT' + case isFalse => simp at hT' + rename_i hok + simp only [Option.some.injEq] at hT' + subst hT' + have hne : (vs.map fun e => Value.word (e.eval ρ)).isEmpty = false := by + cases vs with + | nil => exact absurd rfl hv + | cons _ _ => rfl + simp only [FunctionDef.callBodyResult, hne, Bool.false_eq_true, if_false, + FunctionDef.coerceReturnValues, coerceReturnBindings, + coerce_words ρ rt hKρ fn.returns vs hok, untag_words, + encode_words ρ hKρ fn.returns vs hok, bind, Option.bind, Option.map_some] + simp only [Source.observe, Tree.eval, Res.obs, if_true, ↓reduceIte, logEntries_map, + hst'.logs, Option.some.injEq, Observable.mk.injEq, true_and] + funext slot + exact loadSlot_eq _ S.writes ρ hρok hst'.store slot + | reverted p => + cases r <;> simp only [LeafRel] at hleaf + subst hleaf + cases p with + | empty => + simp only [leafTree, Option.some.injEq] at hT' + subst hT' + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, Fail.data, + ABI.Contract.encodeRevertData?, Source.observe, Tree.eval, Res.obs, hρ, + SolidCore.Refinement.Evm.Wide.callAt] + | panic c => + simp only [leafTree, Option.some.injEq] at hT' + subst hT' + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, Fail.data, encode_panic ρ, + Source.observe, Tree.eval, Res.obs, hρ, SolidCore.Refinement.Evm.Wide.callAt] + | error m => + simp only [leafTree, Option.map_eq_some_iff] at hT' + obtain ⟨bs, hbs, rfl⟩ := hT' + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, Fail.data, encode_error ρ _ hbs, + Source.observe, Tree.eval, Res.obs, hρ, SolidCore.Refinement.Evm.Wide.callAt] + +/-- **SolidCore runs a call of a function of the fragment as its erased tree**, from any storage +`σ` that writes every slot the constructor's entries `s` write, on any argument words below +`2 ^ 256`, clean or dirty. -/ +theorem source_run {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {σ : List (Nat × Nat)} + (hcov : Covers s σ) {sel : Nat} (hsel : sel < 2 ^ 32) {fn : FunctionDef} + (hfind : c.core.findFunctionBySelector? sel = some fn) {T : Tree} + (hT : eraseFn (envOf c.core) fuel fn = some T) (args : List Nat) + (hlen : args.length = fn.params.length) (hargs : ∀ a ∈ args, a < 2 ^ 256) : + Source.run fuel c { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } = + some (T.eval ⟨args, slotValue σ, solHash, callerWord⟩).obs := by + unfold eraseFn at hT + split at hT + · simp at hT + rename_i ws hw + split at hT + case isFalse => simp at hT + rename_i hret + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at hT + obtain ⟨b, hb, t, ht, rfl⟩ := hT + rw [paramGuards_eval ⟨args, slotValue σ, solHash, callerWord⟩ t hargs ws 0, List.drop_zero] + have hdec := decode_args hw args hlen hargs + by_cases hclean : argsClean ws args = true + · rw [if_pos hclean] + rw [if_pos hclean] at hdec + exact source_run_clean hd hcov hsel hfind hw hret hb ht args hlen hargs hclean hdec + · rw [if_neg hclean] + rw [if_neg hclean] at hdec + rw [run_rejected hd hsel hfind args hdec σ] + rfl + +end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Generic/SourceStmt.lean b/SolidCore/Refinement/Generic/SourceStmt.lean new file mode 100644 index 00000000..e3d32e26 --- /dev/null +++ b/SolidCore/Refinement/Generic/SourceStmt.lean @@ -0,0 +1,1991 @@ +import SolidCore.Refinement.Generic.Source +import SolidCore.Refinement.Generic.Event + +/-! +# Statements of the fragment: erasure and simulation + +`eraseStmt` erases a SolidCore statement of the fragment to a `Br`, a tree of branches on words +whose leaves say how the statement ends: normally with a new symbolic state, by returning words, +or by reverting (empty, or `Panic(code)`). `eval_stmt` proves that SolidCore's interpreter runs +the statement to the leaf the call's words select, with the runtime related to the leaf's +symbolic state by `StmtRel`: its locals scope by scope (`frameOf`), its storage as the writes +over the call's storage, and its logs. + +The erasure reads the contract through an `EraseEnv`: its storage fields, its events and its +table of internal functions, which the relation asks to be the context's and the interpreter's. +-/ + +namespace SolidCore.Refinement.Generic +open SolidCore.Solidity.Source + +/-- Why a statement of the fragment reverts: with empty data, with `Panic(code)`, or with +`Error(msg)`, as `require(c, msg)` and `revert(msg)` do. -/ +inductive Fail where + | empty + | panic (code : Nat) + | error (msg : String) + deriving DecidableEq, Repr + +/-- SolidCore's revert data of a revert. -/ +def Fail.data : Fail → RevertData + | .empty => .empty + | .panic c => .panic c + | .error m => .error m + +/-- The revert of a `require` or `revert` with the reason `r`, if any. -/ +def failOf : Option String → Fail + | none => .empty + | some m => .error m + +/-- How a statement of the fragment ends. -/ +inductive Leaf where + | normal (S : SymState) + | returned (S : SymState) (vals : List WExpr) + | reverted (f : Fail) + deriving DecidableEq, Repr + +/-- A statement's outcome as a tree of branches on words. -/ +inductive Br where + | leaf (l : Leaf) + | ite (c : WExpr) (t e : Br) + deriving DecidableEq, Repr + +def Br.eval (ρ : Val) : Br → Leaf + | .leaf l => l + | .ite c t e => if c.eval ρ = 0 then e.eval ρ else t.eval ρ + +/-- Revert with `Panic(0x11)` when one of the overflow conditions holds, else go on. -/ +def guards (gs : List WExpr) (rest : Br) : Br := + gs.foldr (fun g acc => .ite g (.leaf (.reverted (.panic 0x11))) acc) rest + +theorem guards_eval (ρ : Val) (gs : List WExpr) (rest : Br) : + (guards gs rest).eval ρ = + if gs.any (fun g => g.eval ρ != 0) then .reverted (.panic 0x11) else rest.eval ρ := by + induction gs with + | nil => rfl + | cons g gs ih => + simp only [guards, List.foldr_cons] at ih ⊢ + simp only [Br.eval, ih, List.any_cons] + by_cases h : g.eval ρ = 0 <;> simp [h] + +/-- A leaf with `f` applied to its state, if it has one. -/ +def Leaf.mapS (f : SymState → SymState) : Leaf → Leaf + | .normal S => .normal (f S) + | .returned S vs => .returned (f S) vs + | l => l + +/-- Every leaf's state changed by `f`. -/ +def Br.mapS (f : SymState → SymState) : Br → Br + | .leaf l => .leaf (l.mapS f) + | .ite c t e => .ite c (t.mapS f) (e.mapS f) + +theorem Br.eval_mapS (ρ : Val) (f : SymState → SymState) : ∀ b : Br, + (b.mapS f).eval ρ = (b.eval ρ).mapS f + | .leaf _ => rfl + | .ite c t e => by + simp only [Br.mapS, Br.eval] + split + · exact Br.eval_mapS ρ f e + · exact Br.eval_mapS ρ f t + +/-- Run `k` on every leaf. -/ +def Br.bindLeaf : Br → (Leaf → Option Br) → Option Br + | .leaf l, k => k l + | .ite c t e, k => do + let t' ← t.bindLeaf k + let e' ← e.bindLeaf k + some (.ite c t' e') + +theorem Br.bindLeaf_eval (ρ : Val) {k : Leaf → Option Br} : ∀ {b b' : Br}, b.bindLeaf k = some b' → + ∃ c, k (b.eval ρ) = some c ∧ b'.eval ρ = c.eval ρ + | .leaf l, b', h => ⟨b', h, rfl⟩ + | .ite c t e, b', h => by + simp only [Br.bindLeaf, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨t', ht, e', he, rfl⟩ := h + simp only [Br.eval] + split + · exact Br.bindLeaf_eval ρ he + · exact Br.bindLeaf_eval ρ ht + +/-- Run `k` on the state of every normal end. -/ +def Br.bind : Br → (SymState → Option Br) → Option Br + | .leaf (.normal S), k => k S + | .leaf l, _ => some (.leaf l) + | .ite c t e, k => do + let t' ← t.bind k + let e' ← e.bind k + some (.ite c t' e') + +/-- Assign the word `e` to the first local named `x`. -/ +def Locals.set : Locals → String → WExpr → Option Locals + | [], _, _ => none + | (y, e') :: rest, x, e => + if y = x then some ((y, e) :: rest) + else (Locals.set rest x e).map ((y, e') :: ·) + +/-- Assign the word `e` to the local `x` of the innermost scope that has it. -/ +def Scopes.set : Scopes → String → WExpr → Option Scopes + | [], _, _ => none + | L :: rest, x, e => + match L.set x e with + | some L' => some (L' :: rest) + | none => (Scopes.set rest x e).map (L :: ·) + +/-- Declare the local `x` with the word `e` in the innermost scope. -/ +def Scopes.declare : Scopes → String → WExpr → Scopes + | [], x, e => [[(x, e)]] + | L :: rest, x, e => ((x, e) :: L) :: rest + +/-- The state with a new innermost scope, as a block enters. -/ +def SymState.push (S : SymState) : SymState := { S with scopes := [] :: S.scopes } + +/-- The state without its innermost scope, as a block leaves. -/ +def SymState.pop (S : SymState) : SymState := { S with scopes := S.scopes.drop 1 } + +/-- A type whose values the fragment holds as words: `uint256` and `address`. -/ +def wordTy : Ty → Bool + | .uint256 => true + | .address => true + | _ => false + +theorem wordTy_coerce {ty : Ty} (h : wordTy ty = true) (v : Nat) : + ty.coerceValue? (.word v) = some (.word v) ∧ ty.defaultValue = .word 0 := by + cases ty <;> simp_all [wordTy, Ty.coerceValue?, Ty.defaultValue] + +/-- What the erasure reads of the contract: its storage fields, its events and the table of its +internal functions, with the facts that hold of every call it erases (`facts`: the argument +checks of the external function, which bound its `address` words for logs). -/ +structure EraseEnv where + fields : List StorageField + events : List EventDecl + tbl : FunctionTable + facts : Facts := [] + +/-- The erasure of a list of expressions: their overflow conditions and their words. -/ +def eraseExprs (fields : List StorageField) (S : SymState) : List Expr → Option (List WExpr × List WExpr) + | [] => some ([], []) + | e :: es => do + let (g, v) ← eraseExpr fields S e + let (gs, vs) ← eraseExprs fields S es + some (g ++ gs, v :: vs) + +/-- A statement list, each statement erased by `f`. -/ +def eraseSeq (f : Stmt → SymState → Option Br) : List Stmt → SymState → Option Br + | [], S => some (.leaf (.normal S)) + | s :: rest, S => do + let b ← f s S + b.bind (eraseSeq f rest) + +/-- The range check of a checked cleanup to `b` bits of the word `w`: none for `uint256`. -/ +def cleanupGuard (b : Nat) (w : WExpr) : Option (List WExpr) := + if b = 256 then some [] + else if 0 < b ∧ b < 256 then some [.bin .gt w (.lit (2 ^ b - 1))] + else none + +/-- A binding the fragment holds as a word: a `uint256` or an `address`, not a storage +reference. -/ +def wordDecl (b : BindingDecl) : Bool := wordTy b.ty && !b.isStorageRef + +/-- An internal function's frame on entry: its parameters bound to the argument words, its +returns at zero. -/ +def callFrame (fn : InternalFunction) (vs : List WExpr) : Locals := + (fn.params.zip vs).map (fun p => (p.1.name, p.2)) ++ fn.returns.map (fun r => (r.name, .lit 0)) + +/-- Assign words to locals, one after the other. -/ +def Scopes.setMany : Scopes → List String → List WExpr → Option Scopes + | sc, [], [] => some sc + | sc, x :: xs, v :: vs => do + let sc' ← Scopes.set sc x v + Scopes.setMany sc' xs vs + | _, _, _ => none + +/-- The caller's state after an internal call returned the words `ws`: the call's targets +assigned, the callee's writes and logs. -/ +def callAssign (targets : List String) (S S1 : SymState) (ws : List WExpr) : Option Br := + if targets = [] then some (.leaf (.normal { S with writes := S1.writes, logs := S1.logs })) + else do + let sc ← Scopes.setMany S.scopes targets ws + some (.leaf (.normal { scopes := sc, writes := S1.writes, logs := S1.logs, caller := S.caller })) + +/-- The end of an internal call from the end of its callee's body: its named returns or its +returned words assigned to the targets, or the callee's revert. -/ +def callLeaf (fn : InternalFunction) (targets : List String) (S : SymState) : Leaf → Option Br + | .normal S1 => do + let ws ← fn.returns.mapM fun r => Scopes.get? S1.scopes r.name + callAssign targets S S1 ws + | .returned S1 vs => + if vs = [] then do + let ws ← fn.returns.mapM fun r => Scopes.get? S1.scopes r.name + callAssign targets S S1 ws + else if vs.length = fn.returns.length then callAssign targets S S1 vs + else none + | .reverted p => some (.leaf (.reverted p)) + +/-- The end of a `captureReturn`: a return of words assigned to its names. -/ +def captureLeaf (names : List String) : Leaf → Option Br + | .returned S1 vs => + if vs = [] ∨ names = [] then some (.leaf (.normal S1)) + else do + let sc ← Scopes.setMany S1.scopes names vs + some (.leaf (.normal { S1 with scopes := sc })) + | l => some (.leaf l) + +/-- Which arguments of an event SolidCore takes as indexed, as `Stmt.emitEvent` computes it. -/ +def emitFlags (decl? : Option EventDecl) (es : List Expr) : List Bool := + match decl? with + | some decl => + if decl.fields.length == es.length then + decl.fields.map (fun field => field.indexed) + else if decl.fields.isEmpty then + (List.range es.length).map (fun i => decide (i < decl.indexedCount)) + else + List.replicate es.length false + | none => List.replicate es.length false + +/-- The order SolidCore evaluates an event's arguments in: the indexed ones last to first, then +the others first to last. -/ +def emitSchedule (flags : List Bool) (n : Nat) : List Nat := + let positions := (List.range n).zip flags + ((positions.filter (fun p => p.2)).reverse ++ positions.filter (fun p => !p.2)).map Prod.fst + +/-- The values of an event's arguments in their positions, from the values in the order they +were evaluated in. -/ +def unschedule {α : Type} (sched : List Nat) (vals : List α) (n : Nat) : List α := + (List.range n).filterMap (fun i => ((sched.zip vals).find? (fun p => p.1 == i)).map Prod.snd) + +theorem unschedule_map {α β : Type} (f : α → β) (sched : List Nat) (vals : List α) (n : Nat) : + unschedule sched (vals.map f) n = (unschedule sched vals n).map f := by + simp only [unschedule, List.map_filterMap, List.zip_map_right, List.find?_map, Option.map_map] + rfl + +/-! ## `unchecked` blocks of the fragment + +An `unchecked` block of the fragment is SafeMath's check of a wrapped result: one +`require((z = a op b) cmp c, msg)` whose local `z` takes the wrapped `a op b` (`+` or `-` +of locals, no overflow check) and whose condition compares it with `c` (`>=`, `<=` or +`!=`). SolidCore evaluates the right operand `c` first, then the assignment. -/ + +/-- The wrapping operators of an `unchecked` block of the fragment. -/ +def wrapOf : BinaryOp → Option BinOp + | .add => some .add + | .sub => some .sub + | _ => none + +/-- The word of an expression of an `unchecked` block of the fragment: locals under `uint256` +cleanups and wrapping `+` and `-` of them, none of which reverts. -/ +def wrapRead (S : SymState) : Expr → Option WExpr + | .var x => Scopes.get? S.scopes x + | .castOp .uintCleanup 256 e => wrapRead S e + | .binary op l r => do + let o ← wrapOf op + let vl ← wrapRead S l + let vr ← wrapRead S r + some (.bin o vl vr) + | _ => none + +/-- The word of `a >= b`, `a <= b` or `a != b`, with `<=` as solar compares, by `lt` of the +swapped operands. -/ +def cmpOf : BinaryOp → WExpr → WExpr → Option WExpr + | .ge, a, b => some (.un .iszero (.bin .lt a b)) + | .le, a, b => some (.un .iszero (.bin .lt b a)) + | .ne, a, b => some (.un .iszero (.bin .eq a b)) + | _, _, _ => none + +/-- A `require` condition `(z = rhs) cmp c` of an `unchecked` block of the fragment: the local `z`, +its new word and the condition's word. -/ +def uncheckedCond (S : SymState) : Expr → Option (String × WExpr × WExpr) + | .binary cmp (.castOp .uintCleanup 256 (.assignment none none (.var z) rhs)) c => do + let vc ← wrapRead S c + let w ← wrapRead S rhs + let v ← cmpOf cmp w vc + some (z, w, v) + | _ => none + +/-- The erasure of the body of an `unchecked` block of the fragment: a block of one `require` +whose condition assigns a local, as SafeMath's `add` and `sub` check their wrapped result. -/ +def eraseUnchecked (S : SymState) : Stmt → Option Br + | .block [.requireStmt c r] => do + let (z, w, v) ← uncheckedCond S.push c + let L ← Scopes.set S.push.scopes z w + some (Br.mapS SymState.pop + (.ite v (.leaf (.normal { S.push with scopes := L })) (.leaf (.reverted (failOf r))))) + | _ => none + +/-- The erasure of a statement of the fragment with fuel `n`, the fuel SolidCore runs it with: +skips, blocks (a scope each), assignments to locals and to storage fields, compound assignments +to storage fields (`v += x`, `w ^= x`: the operation's overflow check, then the cleanup's range +check), returns, `if`, panics and SafeMath's `unchecked` blocks (`eraseUnchecked`). -/ +def eraseStmt (E : EraseEnv) : Nat → Stmt → SymState → Option Br + | 0, _, _ => none + | n + 1, s, S => + match s with + | .skip => some (.leaf (.normal S)) + | .block ss => do + let b ← eraseSeq (eraseStmt E n) ss S.push + some (b.mapS SymState.pop) + | .assign (.var x) e => do + let (gs, v) ← eraseExpr E.fields S e + let L ← Scopes.set S.scopes x v + some (guards gs (.leaf (.normal { S with scopes := L }))) + | .assign (.storage x) e => do + let (k, off, bytes) ← fieldOf? E.fields x + let (gs, v) ← eraseExpr E.fields S e + some (guards gs (.leaf (.normal + { S with writes := S.writes.set (.lit k) (writeField (S.writes.read (.lit k)) v off bytes) }))) + | .exprStmt (.assignment op? cleanup? (.storageRead .header x []) rhs) => do + let (k, off, bytes) ← fieldOf? E.fields x + let (gs, v) ← eraseExpr E.fields S rhs + match op?, cleanup? with + | none, none => + some (guards gs (.leaf (.normal + { S with writes := S.writes.set (.lit k) (writeField (S.writes.read (.lit k)) v off bytes) }))) + | some op, some (.uint b) => do + let o ← binOf op + let w := WExpr.bin o (readField (S.writes.read (.lit k)) off bytes) v + let cg ← cleanupGuard b w + some (guards (gs ++ (overflow o (readField (S.writes.read (.lit k)) off bytes) v).toList ++ cg) + (.leaf (.normal + { S with writes := S.writes.set (.lit k) (writeField (S.writes.read (.lit k)) w off bytes) }))) + | _, _ => none + | .exprStmt (.assignment (some op) (some (.uint b)) (.storageRead .element x [idx]) rhs) => do + let k ← mapOf? E.fields x + let (gs, v) ← eraseExpr E.fields S rhs + let (gi, key) ← eraseExpr E.fields S idx + let o ← binOf op + let w := WExpr.bin o (S.writes.read (.hash key (.lit k))) v + let cg ← cleanupGuard b w + some (guards (gs ++ gi ++ (overflow o (S.writes.read (.hash key (.lit k))) v).toList ++ cg) + (.leaf (.normal { S with writes := S.writes.set (.hash key (.lit k)) w }))) + | .varDecl ty x init => + if wordTy ty then + match init with + | none => some (.leaf (.normal { S with scopes := S.scopes.declare x (.lit 0) })) + | some e => do + let (gs, v) ← eraseExpr E.fields S e + some (guards gs (.leaf (.normal { S with scopes := S.scopes.declare x v }))) + else none + | .returnValues es => do + let (gs, vs) ← eraseExprs E.fields S es + some (guards gs (.leaf (.returned S vs))) + | .ifElse c t e => do + let (gs, v) ← eraseExpr E.fields S c + let bt ← eraseStmt E n t S + let be ← eraseStmt E n e S + some (guards gs (.ite v bt be)) + | .panic code => some (.leaf (.reverted (.panic code))) + | .requireStmt c r => do + let (gs, v) ← eraseExpr E.fields S c + some (guards gs (.ite v (.leaf (.normal S)) (.leaf (.reverted (failOf r))))) + | .revertError r => some (.leaf (.reverted (failOf r))) + | .assign (.storageIndex x i) e => do + let (gs, v) ← eraseExpr E.fields S e + let (gi, key) ← eraseExpr E.fields S i + match mapOf? E.fields x with + | some k => + some (guards (gs ++ gi) (.leaf (.normal { S with writes := S.writes.set (.hash key (.lit k)) v }))) + | none => do + let k ← boolMapOf? E.fields x + if bound E.facts v ≤ 1 then + some (guards (gs ++ gi) + (.leaf (.normal { S with writes := S.writes.set (.hash key (.lit k)) v }))) + else none + | .assign (.index (.storageIndex x i1) i2) e => do + let k ← map2Of? E.fields x + let (gs, v) ← eraseExpr E.fields S e + let (g1, k1) ← eraseExpr E.fields S i1 + let (g2, k2) ← eraseExpr E.fields S i2 + some (guards (gs ++ g1 ++ g2) + (.leaf (.normal { S with writes := S.writes.set (.hash k2 (.hash k1 (.lit k))) v }))) + | .internalCall targets callee args => do + let fn ← E.tbl.lookup? callee + if fn.params.all wordDecl && fn.returns.all wordDecl && args.length = fn.params.length then + let (gs, vs) ← eraseExprs E.fields S args + let b ← eraseStmt E n fn.body { scopes := [callFrame fn vs], writes := S.writes, logs := S.logs, caller := S.caller } + let b' ← b.bindLeaf (callLeaf fn targets S) + some (guards gs b') + else none + | .captureReturn names body => do + let b ← eraseStmt E n body S + b.bindLeaf (captureLeaf names) + | .emitEvent name es => do + let decl ← E.events.find? (fun d => d.name == name) + let t ← decl.topic? + let sched := emitSchedule (emitFlags (some decl) es) es.length + let (gs, svs) ← eraseExprs E.fields S (sched.filterMap (fun i => es[i]?)) + let ws := unschedule sched svs es.length + if evOk E.facts decl.fields ws then + some (guards gs (.leaf (.normal { S with logs := S.logs ++ + [⟨.lit t :: evTopics decl.fields ws, (evData decl.fields ws).flatMap wordOBytes⟩] }))) + else none + | .unchecked body => if 2 ≤ n then eraseUnchecked S body else none + | _ => none + + +/-! ## The relation between SolidCore's runtime and a symbolic state -/ + +/-- A scope of a function's locals, as SolidCore holds it. -/ +def frameOf (ρ : Val) (L : Locals) : Frame := L.map fun p => (p.1, Value.word (p.2.eval ρ)) + +/-- What an event of SolidCore's state shows as a log: its topics and its data bytes. -/ +def logOf (ev : Event) : List Nat × List Nat := + (ev.topics.map SolidCore.Solidity.Shared.norm, + SolidCore.Solidity.Shared.Account.normalizeBytes ev.dataBytes) + +/-- What SolidCore's runtime holds of a symbolic state inside a function body: the context's +storage fields and events are the erasure's, arithmetic is checked, the caller is `callerWord`, +the hash is SolidCore's, the locals are the state's scopes, every slot holds the word the writes +leave there, and the events are the state's logs. -/ +structure StmtRel (ρ : Val) (E : EraseEnv) (ctx : Context) (rt : Runtime) (S : SymState) : Prop where + fields : ctx.storageFields = E.fields + events : ctx.eventDecls = E.events + checked : ctx.checked = true + sender : ctx.sender = S.caller.eval ρ + hash : ρ.hash = solHash + ok : ρ.Ok + frames : rt.locals = S.scopes.map (frameOf ρ) + store : ∀ k, k < wordSize → rt.state.loadSlot k = Writes.store ρ S.writes k + logs : rt.state.events.map logOf = S.logs.map (Log.eval ρ) + facts : E.facts.Hold ρ + +theorem frame_lookup (ρ : Val) (L : Locals) (x : String) : + Frame.lookup? (frameOf ρ L) x = (L.get? x).map fun e => Value.word (e.eval ρ) := by + induction L with + | nil => rfl + | cons p L ih => + obtain ⟨y, e⟩ := p + simp only [frameOf, List.map_cons, Frame.lookup?, Locals.get?] at ih ⊢ + by_cases h : y = x <;> simp [h, ih] + +theorem env_lookup (ρ : Val) : ∀ (sc : Scopes) (x : String), + LocalEnv.lookup? (sc.map (frameOf ρ)) x = (Scopes.get? sc x).map fun e => Value.word (e.eval ρ) + | [], _ => rfl + | L :: rest, x => by + simp only [List.map_cons, LocalEnv.lookup?, frame_lookup, Scopes.get?] + cases L.get? x with + | some e => rfl + | none => exact env_lookup ρ rest x + +theorem frame_assign (ρ : Val) (L : Locals) (x : String) (v : WExpr) : + Frame.assign? (frameOf ρ L) x (Value.word (v.eval ρ)) = (L.set x v).map (frameOf ρ) := by + induction L with + | nil => rfl + | cons p L ih => + obtain ⟨y, e⟩ := p + by_cases hy : y = x + · subst hy; simp [frameOf, Frame.assign?, Locals.set] + · simp only [frameOf, List.map_cons, Frame.assign?, Locals.set, hy, ↓reduceIte] at ih ⊢ + rw [ih] + cases Locals.set L x v <;> rfl + +theorem env_assign (ρ : Val) : ∀ (sc : Scopes) (x : String) (v : WExpr), + LocalEnv.assign? (sc.map (frameOf ρ)) x (Value.word (v.eval ρ)) = + (Scopes.set sc x v).map (·.map (frameOf ρ)) + | [], _, _ => rfl + | L :: rest, x, v => by + simp only [List.map_cons, LocalEnv.assign?, frame_assign, Scopes.set] + cases L.set x v with + | some L' => rfl + | none => + simp only [Option.map_none, env_assign ρ rest x v] + cases Scopes.set rest x v <;> rfl + +theorem env_declare (ρ : Val) (sc : Scopes) (x : String) (v : WExpr) : + LocalEnv.declare (sc.map (frameOf ρ)) x (Value.word (v.eval ρ)) = + (sc.declare x v).map (frameOf ρ) := by + cases sc <;> rfl + +theorem Locals.get?_of_set {L L' : Locals} {x : String} {v : WExpr} (h : L.set x v = some L') : + ∃ e, L.get? x = some e := by + induction L generalizing L' with + | nil => simp [Locals.set] at h + | cons p L ih => + obtain ⟨y, e⟩ := p + simp only [Locals.set] at h + by_cases hy : y = x + · exact ⟨e, by simp [Locals.get?, hy]⟩ + · simp only [hy, ↓reduceIte, Option.map_eq_some_iff] at h + obtain ⟨L'', h'', rfl⟩ := h + obtain ⟨e', he'⟩ := ih h'' + exact ⟨e', by simp [Locals.get?, hy, he']⟩ + +theorem Scopes.get?_of_set : ∀ {sc sc' : Scopes} {x : String} {v : WExpr}, Scopes.set sc x v = some sc' → + ∃ e, Scopes.get? sc x = some e + | [], _, _, _, h => by simp [Scopes.set] at h + | L :: rest, sc', x, v, h => by + simp only [Scopes.set] at h + cases hL : L.set x v with + | some L' => + obtain ⟨e, he⟩ := Locals.get?_of_set hL + exact ⟨e, by simp [Scopes.get?, he]⟩ + | none => + simp only [hL, Option.map_eq_some_iff] at h + obtain ⟨r, hr, rfl⟩ := h + obtain ⟨e, he⟩ := Scopes.get?_of_set hr + have : L.get? x = none := by + cases hg : L.get? x with + | none => rfl + | some e' => + exfalso + clear hr he + induction L with + | nil => simp [Locals.get?] at hg + | cons p L ih => + obtain ⟨y, e''⟩ := p + simp only [Locals.get?, Locals.set] at hg hL + by_cases hy : y = x + · simp [hy] at hL + · simp only [hy, ↓reduceIte, Option.map_eq_none_iff] at hg hL + exact ih hL hg + exact ⟨e, by simp [Scopes.get?, this, he]⟩ + +theorem StmtRel.expr {ρ : Val} {E : EraseEnv} {ctx : Context} {rt : Runtime} {S : SymState} + (h : StmtRel ρ E ctx rt S) : ExprRel ρ E.fields ctx rt S where + fields := h.fields + checked := h.checked + sender := h.sender + hash := h.hash + ok := h.ok + locals x e he := by + simp [Runtime.lookupLocal?, h.frames, env_lookup, he] + store := h.store + +theorem loadSlot_storeSlot (st : State) (k w q : Nat) (hk : k < wordSize) (hw : w < wordSize) + (hq : q < wordSize) : (st.storeSlot k w).loadSlot q = if q = k then w else st.loadSlot q := by + simp only [State.storeSlot, State.loadSlot, StorageMap.lookup?, StorageMap.insertLoop, + norm_lt hk, norm_lt hw, norm_lt hq, Std.HashMap.get?_eq_getElem?, Std.HashMap.getElem?_insert, + beq_iff_eq] + by_cases h : q = k + · simp [h] + · have : ¬ k = q := fun e => h e.symm + simp [h, this] + +/-- Writing the word `v` to the slot `k` names keeps the relation, with the writes set. -/ +theorem StmtRel.write {ρ : Val} {E : EraseEnv} {ctx : Context} {rt : Runtime} {S : SymState} + (hrel : StmtRel ρ E ctx rt S) (k v : WExpr) : + StmtRel ρ E ctx { rt with state := rt.state.storeSlot (k.eval ρ) (v.eval ρ) } + { S with writes := S.writes.set k v } := + { fields := hrel.fields, events := hrel.events, checked := hrel.checked, sender := hrel.sender + hash := hrel.hash, ok := hrel.ok, frames := hrel.frames + store := fun q hq => by + rw [loadSlot_storeSlot _ _ _ _ (k.eval_lt ρ) (v.eval_lt ρ) hq, Writes.store_set, + hrel.store q hq, Nat.mod_eq_of_lt hq] + by_cases h : q = k.eval ρ + · simp [h] + · simp [h, Ne.symm h] + logs := by simp [State.storeSlot, hrel.logs] + facts := hrel.facts } + +/-- Writing a field keeps the relation, with the field's slot set to `writeField`. -/ +theorem StmtRel.writeField {ρ : Val} {E : EraseEnv} {ctx : Context} + {rt : Runtime} {S : SymState} (hrel : StmtRel ρ E ctx rt S) {x : String} + {f : StorageField} (hfx : FieldOk ctx x f) (w : WExpr) : + StmtRel ρ E ctx + { rt with state := (rt.state.storeSlot f.slot + ((writeField (S.writes.read (.lit f.slot)) w f.packedOffset f.packedBytes).eval ρ)) } + { S with writes := (S.writes.set (.lit f.slot) + (writeField (S.writes.read (.lit f.slot)) w f.packedOffset f.packedBytes)) } := by + have h := hrel.write (.lit f.slot) (Generic.writeField (S.writes.read (.lit f.slot)) w f.packedOffset f.packedBytes) + simp only [WExpr.eval, Nat.mod_eq_of_lt hfx.slot] at h + exact h + +/-! ## Simulation -/ + +/-- What SolidCore's result of a statement holds of the leaf it erases to. -/ +def LeafRel (ρ : Val) (E : EraseEnv) (ctx : Context) : Result → Leaf → Prop + | .normal rt, .normal S => StmtRel ρ E ctx rt S + | .returned rt vs, .returned S ws => + StmtRel ρ E ctx rt S ∧ vs = ws.map fun e => Value.word (e.eval ρ) + | .reverted _ r, .reverted f => r = f.data + | _, _ => False + +theorem caught_exprResult (ρ : Val) (gs : List WExpr) (v : WExpr) (rt : Runtime) : + (exprResult ρ gs v rt).caught = + .done (.ok (if gs.any (fun g => g.eval ρ != 0) then .error (.panic 0x11) + else .ok (.word (v.eval ρ), rt))) := by + unfold exprResult + split <;> rfl + +theorem eval_eq (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : Runtime) (S : SymState) + (hrel : ExprRel ρ fields ctx rt S) {e : Expr} {gs : List WExpr} {v : WExpr} + (h : eraseExpr fields S e = some (gs, v)) : Expr.eval ctx rt e = exprResult ρ gs v rt := + eval_erase ρ fields ctx rt S hrel e gs v _ h (Nat.lt_succ_self _) + +theorem Br.bind_eval (ρ : Val) {b b' : Br} {k : SymState → Option Br} (h : b.bind k = some b') : + match b.eval ρ with + | .normal S => ∃ c, k S = some c ∧ b'.eval ρ = c.eval ρ + | l => b'.eval ρ = l := by + induction b generalizing b' with + | leaf l => + cases l with + | normal S => exact ⟨b', h, rfl⟩ + | returned S vs => simp only [Br.bind, Option.some.injEq] at h; subst h; rfl + | reverted p => simp only [Br.bind, Option.some.injEq] at h; subst h; rfl + | ite c t e iht ihe => + simp only [Br.bind, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨t', ht, e', he, rfl⟩ := h + simp only [Br.eval] + by_cases hc : c.eval ρ = 0 + · simp only [hc, ↓reduceIte]; exact ihe he + · simp only [hc, ↓reduceIte]; exact iht ht + +theorem eval_seq_of (ρ : Val) (E : EraseEnv) (ctx : Context) (n : Nat) + (ih : ∀ s S b, eraseStmt E n s S = some b → ∀ rt, StmtRel ρ E ctx rt S → + ∃ r, Stmt.eval n E.tbl ctx rt s = .done (.ok r) ∧ LeafRel ρ E ctx r (b.eval ρ)) : + ∀ ss S b, eraseSeq (eraseStmt E n) ss S = some b → ∀ rt, StmtRel ρ E ctx rt S → + ∃ r, Stmt.evalList n E.tbl ctx rt ss = .done (.ok r) ∧ LeafRel ρ E ctx r (b.eval ρ) := by + intro ss + induction ss with + | nil => + intro S b h rt hrel + simp only [eraseSeq, Option.some.injEq] at h + subst h + exact ⟨.normal rt, by rw [Stmt.evalList]; rfl, hrel⟩ + | cons s rest ihs => + intro S b h rt hrel + simp only [eraseSeq, Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨b1, h1, hb⟩ := h + obtain ⟨r1, hr1, hl1⟩ := ih s S b1 h1 rt hrel + have hbe := Br.bind_eval ρ hb + simp only [Stmt.evalList, hr1, bind, EvmCompiler.Simulation.Interaction.bind] + revert hl1 hbe + cases b1.eval ρ with + | normal S1 => + intro hl1 hbe + obtain ⟨c, hc, hce⟩ := hbe + cases r1 <;> simp only [LeafRel] at hl1 + rename_i rt1 + obtain ⟨r, hr, hl⟩ := ihs S1 c hc rt1 hl1 + exact ⟨r, hr, hce ▸ hl⟩ + | returned S1 vs => + intro hl1 hbe + cases r1 <;> simp only [LeafRel] at hl1 + exact ⟨_, rfl, hbe ▸ hl1⟩ + | reverted p => + intro hl1 hbe + cases p <;> cases r1 <;> simp only [LeafRel] at hl1 + all_goals exact ⟨_, rfl, by rw [hbe]; exact hl1⟩ + +theorem StmtRel.popScope {ρ : Val} {E : EraseEnv} {ctx : Context} {rt : Runtime} {S : SymState} + (hr : StmtRel ρ E ctx rt S) : StmtRel ρ E ctx rt.popScope S.pop := + { hr with frames := by simp [Runtime.popScope, SymState.pop, hr.frames, List.map_drop] } + +theorem LeafRel.popScope {ρ : Val} {E : EraseEnv} {ctx : Context} + {r : Result} {l : Leaf} (h : LeafRel ρ E ctx r l) : + LeafRel ρ E ctx (r.mapRuntime Runtime.popScope) (l.mapS SymState.pop) := by + cases r <;> cases l <;> simp only [LeafRel, Result.mapRuntime, Leaf.mapS] at h ⊢ + · exact h.popScope + · exact ⟨h.1.popScope, h.2⟩ + all_goals (rename_i p; cases p <;> simp_all [LeafRel]) + +theorem StmtRel.pushScope {ρ : Val} {E : EraseEnv} {ctx : Context} {rt : Runtime} {S : SymState} + (h : StmtRel ρ E ctx rt S) : StmtRel ρ E ctx rt.pushScope S.push := + { h with frames := by simp [Runtime.pushScope, SymState.push, h.frames, frameOf] } + +theorem caught_done_ok {α : Type} (a : α) : + SolI.caught (EvmCompiler.Simulation.Interaction.done (.ok a) : SolI α) = + EvmCompiler.Simulation.Interaction.done (.ok (.ok a)) := rfl + +theorem bind_done_ok {α β : Type} (a : α) (k : α → SolI β) : + ((EvmCompiler.Simulation.Interaction.done (.ok a) : SolI α) >>= k) = k a := rfl + +theorem fieldWrite_lt {cur v off bytes : Nat} (hc : cur < wordSize) (hv : v < wordSize) + (h : off + bytes ≤ 32) : fieldWrite cur v off bytes < wordSize := by + unfold fieldWrite + split + · exact hv + · exact replace_lt hc v _ _ (by omega) + +theorem store_field {ctx : Context} {rt : Runtime} {x : String} {f : StorageField} + (hf : FieldOk ctx x f) (hw : rt.state.loadSlot f.slot < wordSize) (v : Nat) + (hv : v < wordSize) (sx : Bool) : + rt.storeStorageFieldWithDeepClear ctx x (.word v) sx = + .ok { rt with state := (rt.state.storeSlot f.slot + (fieldWrite (rt.state.loadSlot f.slot) v f.packedOffset f.packedBytes)) } := by + have := hf.bytes + have := hf.fits + simp [Runtime.storeStorageFieldWithDeepClear, hf.find, hf.layout, Runtime.storageMaterializedValue, + Runtime.derefMemoryValueDeep, Runtime.derefMemoryValueWithFuel, Runtime.storeStorageField, + coerceStorageWordAs, Value.forceAbiLazy, Ty.coerceValue?, Value.asStorageWord?, norm_lt hv, + State.storeFieldWord, StorageField.isPacked, SolidCore.Solidity.Source.wordBytes, + State.storeFieldSlot, hf.transient, bind, Except.bind, pure, Except.pure, State.loadFieldSlot, + fieldWrite, wordReplaceBitRange, StorageField.packedBitWidth, StorageField.packedBitOffset, + norm_lt hw] + by_cases h : f.packedOffset = 0 ∧ f.packedBytes = 32 + · simp [h] + · have hob8 : f.packedOffset * 8 + f.packedBytes * 8 ≤ 256 := by omega + rw [if_pos (by omega), if_neg h, if_neg (by omega), + replace_eq hw v _ _ hob8, norm_lt (replace_lt hw v _ _ hob8)] + +/-- The overflow check of a checked binary operation of the fragment on two words. -/ +theorem apply_erased (ρ : Val) {op : BinaryOp} {o : BinOp} (ho : binOf op = some o) (l r : WExpr) : + BinaryOp.apply true op (.word (l.eval ρ)) (.word (r.eval ρ)) = + if (overflow o l r).toList.any (fun g => g.eval ρ != 0) then .error (.panic 0x11) + else .ok (.word ((WExpr.bin o l r).eval ρ)) := by + have hl := l.eval_lt ρ + have hr := r.eval_lt ρ + cases op <;> simp only [binOf, reduceCtorEq, Option.some.injEq] at ho <;> subst ho + · rw [apply_add _ _ hl hr] + simp only [overflow, Option.toList_some, List.any_cons, List.any_nil, Bool.or_false, guard_add] + by_cases h : wordSize ≤ l.eval ρ + r.eval ρ <;> simp [h, WExpr.eval, BinOp.eval, Nat.mod_mod] + · rw [apply_sub _ _ hl hr] + simp only [overflow, Option.toList_some, List.any_cons, List.any_nil, Bool.or_false, guard_sub] + by_cases h : l.eval ρ < r.eval ρ <;> simp [h, WExpr.eval, BinOp.eval, Nat.mod_mod] + · rw [apply_mul _ _ hl hr] + simp only [overflow, Option.toList_some, List.any_cons, List.any_nil, Bool.or_false, guard_mul] + by_cases h : wordSize ≤ l.eval ρ * r.eval ρ <;> simp [h, WExpr.eval, BinOp.eval, Nat.mod_mod] + · rw [apply_bitAnd _ _ hl hr] + simp [overflow, WExpr.eval, BinOp.eval, Nat.mod_mod] + · rw [apply_bitOr _ _ hl hr] + simp [overflow, WExpr.eval, BinOp.eval, Nat.mod_mod] + · rw [apply_bitXor _ _ hl hr] + simp [overflow, WExpr.eval, BinOp.eval, Nat.mod_mod] + · rw [apply_lt _ _ hl hr] + simp only [overflow, Option.toList_none, List.any_nil, Bool.false_eq_true, ↓reduceIte] + congr 2 + simp only [WExpr.eval, BinOp.eval] + split <;> rfl + · rw [apply_gt _ _ hl hr] + simp only [overflow, Option.toList_none, List.any_nil, Bool.false_eq_true, ↓reduceIte] + congr 2 + simp only [WExpr.eval, BinOp.eval] + split <;> rfl + · rw [apply_eq _ _ hl hr] + simp only [overflow, Option.toList_none, List.any_nil, Bool.false_eq_true, ↓reduceIte] + congr 2 + simp only [WExpr.eval, BinOp.eval] + split <;> rfl + +theorem cleanupGuard_spec (ρ : Val) {b : Nat} {w : WExpr} {cg : List WExpr} + (h : cleanupGuard b w = some cg) : + 0 < b ∧ b ≤ 256 ∧ cg.any (fun g => g.eval ρ != 0) = !decide (w.eval ρ < 2 ^ b) := by + have hw := w.eval_lt ρ + unfold cleanupGuard at h + split at h + · rename_i hb + subst hb + simp only [Option.some.injEq] at h + subst h + simp [hw] + · split at h + · rename_i _ hb + simp only [Option.some.injEq] at h + subst h + refine ⟨hb.1, by omega, ?_⟩ + have hpos := Nat.two_pow_pos b + have hm : (2 ^ b - 1) % wordSize = 2 ^ b - 1 := + Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le (Nat.sub_lt hpos (by decide)) + (Nat.pow_le_pow_right (by decide) (by omega))) + by_cases hc : w.eval ρ < 2 ^ b + · have : ¬ 2 ^ b - 1 < w.eval ρ := by omega + simp [WExpr.eval, BinOp.eval, hm, this, hc] + · have : 2 ^ b - 1 < w.eval ρ := by omega + simp [WExpr.eval, BinOp.eval, hm, this, hc] + · simp at h + +theorem eval_returnList (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : Runtime) + (S : SymState) (hrel : ExprRel ρ fields ctx rt S) : + ∀ (es : List Expr) (gs vs : List WExpr) (fuel : Nat), eraseExprs fields S es = some (gs, vs) → + es.length < fuel → + Expr.evalReturnListFuel fuel ctx rt es = + if gs.any (fun g => g.eval ρ != 0) then .done (.error (.revert (.panic 0x11))) + else .done (.ok (vs.map (fun e => Value.word (e.eval ρ)), rt)) := by + intro es + induction es with + | nil => + intro gs vs fuel h hf + obtain ⟨n, rfl⟩ : ∃ n, fuel = n + 1 := ⟨fuel - 1, by simp at hf; omega⟩ + simp only [eraseExprs, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + rw [Expr.evalReturnListFuel] + rfl + | cons e es ih => + intro gs vs fuel h hf + obtain ⟨n, rfl⟩ : ∃ n, fuel = n + 1 := ⟨fuel - 1, by simp at hf; omega⟩ + simp only [eraseExprs, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨⟨g, v⟩, he, ⟨gs', vs'⟩, hes, h⟩ := h + simp only [Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + have hv : Expr.evalReturnValue ctx rt e = exprResult ρ g v rt := by + have := eval_eq ρ fields ctx rt S hrel he + unfold Expr.evalReturnValue + split + · rename_i x + have hx : ∃ ex, Scopes.get? S.scopes x = some ex := by + simp only [eraseExpr, Option.map_eq_some_iff] at he + obtain ⟨ex, hex, -⟩ := he + exact ⟨ex, hex⟩ + obtain ⟨ex, hex⟩ := hx + have hmem : rt.lookupMemoryRef? x = none := by + simp [Runtime.lookupMemoryRef?, hrel.locals x ex hex] + simp only [hmem] + exact this + · exact this + rw [Expr.evalReturnListFuel] + simp only [hv, bind_exprResult, List.any_append] + by_cases h1 : g.any (fun g => g.eval ρ != 0) = true + · simp [h1] + · simp only [h1, Bool.false_eq_true, ↓reduceIte, Bool.false_or] + rw [ih gs' vs' n hes (by simp at hf; omega)] + by_cases h2 : gs'.any (fun g => g.eval ρ != 0) = true + · simp [h2]; rfl + · simp [h2]; rfl + +theorem storeSlot_mod (st : State) (k w : Nat) : st.storeSlot (k % wordSize) w = st.storeSlot k w := by + simp only [State.storeSlot, StorageMap.insertLoop, norm_mod, Nat.mod_mod] + +/-- SolidCore writes the entry of a mapping at a key word to the slot `solHash key slot`. -/ +theorem storeIndex_map {ρ : Val} {E : EraseEnv} {ctx : Context} {rt : Runtime} {S : SymState} + (hrel : StmtRel ρ E ctx rt S) {x : String} {k : Nat} + (hk : mapOf? E.fields x = some k) {w v : Nat} (hw : w < wordSize) (hv : v < wordSize) : + rt.storeStorageIndexWithDeepClear ctx x (.word w) (.word v) = + .ok { rt with state := rt.state.storeSlot (solHash w k) v } := by + obtain ⟨f, hf, rfl⟩ := mapOf?_spec hrel.fields hk + rcases hf.layout with hl | hl <;> + simp [Runtime.storeStorageIndexWithDeepClear, hf.find, hl, mappingStorageSlotForKey, + coerceMappingKeyWordAs, Value.forceAbiLazy, Ty.coerceValue?, Value.asStorageWord?, norm_lt hw, + norm_lt hv, bind, Except.bind, State.storeStorageLayoutAtWithDeepClear, + State.storeStorageLayoutAtWithDeepClearFuelMode, State.storeStorageLayoutAt, coerceStorageWordAs, + Runtime.storageMaterializedValue, Runtime.derefMemoryValueDeep, Runtime.derefMemoryValueWithFuel, + StorageLayout.clearDepth, mappingStorageSlot_eq, pure, Except.pure] + +/-- A compound assignment to a mapping's entry, `m[i] op= rhs` with a `uint b` cleanup: the +right side's and the key's overflow conditions, the operation's, the cleanup's range check, then +the write of the entry's slot word. -/ +theorem eval_mapAssign (ρ : Val) (E : EraseEnv) (ctx : Context) (rt : Runtime) (S : SymState) + (hrel : StmtRel ρ E ctx rt S) (n : Nat) {op : BinaryOp} {b : Nat} {x : String} {i rhs : Expr} + {k : Nat} {gs gi : List WExpr} {v key : WExpr} {o : BinOp} {cg : List WExpr} + (hk : mapOf? E.fields x = some k) (hv : eraseExpr E.fields S rhs = some (gs, v)) + (hi : eraseExpr E.fields S i = some (gi, key)) (ho : binOf op = some o) + (hcg : cleanupGuard b (.bin o (S.writes.read (.hash key (.lit k))) v) = some cg) : + ∃ r, Stmt.eval (n + 1) E.tbl ctx rt + (.exprStmt (.assignment (some op) (some (.uint b)) (.storageRead .element x [i]) rhs)) = + .done (.ok r) ∧ + LeafRel ρ E ctx r ((guards (gs ++ gi ++ (overflow o (S.writes.read (.hash key (.lit k))) v).toList ++ cg) + (.leaf (.normal { S with writes := (S.writes.set (.hash key (.lit k)) + (.bin o (S.writes.read (.hash key (.lit k))) v)) }))).eval ρ) := by + have hk' := hk + obtain ⟨f, hf, rfl⟩ := mapOf?_spec hrel.fields hk' + have hread : (S.writes.read (.hash key (.lit f.slot))).eval ρ = + Writes.store ρ S.writes (solHash (key.eval ρ) f.slot % wordSize) := by + rw [Writes.eval_read hrel.ok] + simp only [WExpr.eval, hrel.hash, Nat.mod_eq_of_lt hf.slot] + rw [Stmt.eval] + simp only [Expr.eval, Expr.orderFuel, Expr.listEvalFuel] + rw [Expr.evalFuel] + rw [eval_erase ρ E.fields ctx rt S hrel.expr rhs gs v _ hv (by omega)] + rw [bind_exprResult] + rw [guards_eval] + have hrd : ResolvedLValue.read ctx rt (.storageIndex x (.word (key.eval ρ))) = + .ok (.word ((S.writes.read (.hash key (.lit f.slot))).eval ρ)) := by + simp [ResolvedLValue.read, ResolvedLValue.readRaw, loadIndex_map hrel.expr hk (key.eval_lt ρ), + hread, Runtime.derefMemoryValue, bind, Except.bind] + have hsl : (WExpr.hash key (.lit f.slot)).eval ρ = solHash (key.eval ρ) f.slot % wordSize := by + simp only [WExpr.eval, hrel.hash, Nat.mod_eq_of_lt hf.slot] + have hwr : ∀ w : WExpr, ResolvedLValue.write ctx rt (.storageIndex x (.word (key.eval ρ))) + (.word (w.eval ρ)) = + .ok { rt with state := (rt.state.storeSlot ((WExpr.hash key (.lit f.slot)).eval ρ) (w.eval ρ)) } := by + intro w + simp only [ResolvedLValue.write, storeIndex_map hrel hk (key.eval_lt ρ) (w.eval_lt ρ), hsl, + storeSlot_mod] + obtain ⟨hb0, hb, hcgv⟩ := cleanupGuard_spec ρ hcg + have hcl : ∀ w : WExpr, ValueCleanup.apply true (.uint b) (.word (w.eval ρ)) = + if w.eval ρ < 2 ^ b then .ok (.word (w.eval ρ)) else .error (.panic 0x11) := + fun w => uintCleanup_lt _ _ (w.eval_lt ρ) hb0 hb + simp only [any_append] + by_cases hg : gs.any (fun g => g.eval ρ != 0) = true + · simp only [hg, ↓reduceIte, Bool.true_or] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hg, Bool.false_eq_true, ↓reduceIte, Bool.false_or] + rw [Expr.resolveLValueFuel] + simp only [] + rw [eval_erase ρ E.fields ctx rt S hrel.expr i gi key _ hi (by omega), bind_exprResult] + by_cases hgi : gi.any (fun g => g.eval ρ != 0) = true + · simp only [hgi, ↓reduceIte, Bool.true_or] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hgi, Bool.false_eq_true, ↓reduceIte, Bool.false_or, bind_done_ok, pure, + EvmCompiler.Simulation.Interaction.pure, liftM, monadLift, MonadLift.monadLift, + SolI.ofExcept, hrd, hrel.checked, apply_erased ρ ho, hcgv] + by_cases ho' : (overflow o (S.writes.read (.hash key (.lit f.slot))) v).toList.any + (fun g => g.eval ρ != 0) = true + · simp only [ho', Bool.true_or, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [ho', Bool.false_or, Bool.false_eq_true, ↓reduceIte, bind_done_ok] + have hcl' := hcl (.bin o (S.writes.read (.hash key (.lit f.slot))) v) + cases op + all_goals first | (simp [binOf] at ho; done) | skip + all_goals + dsimp only + rw [hcl'] + by_cases hc : (WExpr.bin o (S.writes.read (.hash key (.lit f.slot))) v).eval ρ < 2 ^ b + · simp only [hc, decide_true, Bool.not_true, Bool.false_eq_true, ↓reduceIte, + bind_done_ok, hwr] + exact ⟨_, rfl, hrel.write _ _⟩ + · simp only [hc, decide_false, Bool.not_false, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + + +/-- A plain write of a `bool` word to a mapping to `bool`'s entry stores the word in the entry's +slot. -/ +theorem storeIndex_boolMap {ρ : Val} {E : EraseEnv} {ctx : Context} {rt : Runtime} {S : SymState} + (hrel : StmtRel ρ E ctx rt S) {x : String} {k : Nat} + (hk : boolMapOf? E.fields x = some k) {w v : Nat} (hw : w < wordSize) (hv : v ≤ 1) : + rt.storeStorageIndexWithDeepClear ctx x (.word w) (.word v) = + .ok { rt with state := rt.state.storeSlot (solHash w k) v } := by + obtain ⟨f, hf, rfl⟩ := boolMapOf?_spec hrel.fields hk + have hv' : v = 0 ∨ v = 1 := by omega + rcases hf.layout with hl | hl <;> rcases hv' with rfl | rfl <;> + simp [Runtime.storeStorageIndexWithDeepClear, hf.find, hl, mappingStorageSlotForKey, + coerceMappingKeyWordAs, Value.forceAbiLazy, Ty.coerceValue?, Value.asStorageWord?, norm_lt hw, + bind, Except.bind, State.storeStorageLayoutAtWithDeepClear, + State.storeStorageLayoutAtWithDeepClearFuelMode, State.storeStorageLayoutAt, coerceStorageWordAs, + Runtime.storageMaterializedValue, Runtime.derefMemoryValueDeep, Runtime.derefMemoryValueWithFuel, + StorageLayout.clearDepth, mappingStorageSlot_eq, pure, Except.pure, wordEq, + SolidCore.Solidity.Shared.norm, modulus_eq, Nat.mod_eq_of_lt hw] + +/-- A plain write of a word to a nested mapping's entry stores the word in the entry's slot. -/ +theorem storePath_map2 {ρ : Val} {E : EraseEnv} {ctx : Context} {rt : Runtime} {S : SymState} + (hrel : StmtRel ρ E ctx rt S) {x : String} {k : Nat} + (hk : map2Of? E.fields x = some k) {w1 w2 v : Nat} (h1 : w1 < wordSize) (h2 : w2 < wordSize) + (hv : v < wordSize) : + rt.storeStoragePathWithDeepClear ctx x [.word w1, .word w2] (.word v) = + .ok { rt with state := rt.state.storeSlot (solHash w2 (solHash w1 k)) v } := by + obtain ⟨f, hf, rfl⟩ := map2Of?_spec hrel.fields hk + rw [Runtime.storeStoragePathWithDeepClear, Runtime.storeStorageBasePathWithDeepClear] + simp only [Runtime.storageMaterializedValue, Runtime.derefMemoryValueDeep, + Runtime.derefMemoryValueWithFuel, bind, Except.bind, pure, Except.pure] + rw [resolve_map2 hf h1 h2] + simp [State.storeStorageLayoutAtWithDeepClear, State.storeStorageLayoutAtWithDeepClearFuelMode, + State.storeStorageLayoutAt, coerceStorageWordAs, Value.forceAbiLazy, Ty.coerceValue?, + Value.asStorageWord?, norm_lt hv, StorageLayout.clearDepth, bind, Except.bind, pure, Except.pure] + +/-- SolidCore resolves the target `m[i]` to the entry at `i`'s word, after `i`'s overflow +checks. -/ +theorem resolve_storageIndex (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : Runtime) + (S : SymState) (hrel : ExprRel ρ fields ctx rt S) (x : String) {i : Expr} {gi : List WExpr} + {key : WExpr} (hi : eraseExpr fields S i = some (gi, key)) : + (LValue.resolveWithRuntime (.storageIndex x i) ctx rt).caught = + .done (.ok (if gi.any (fun g => g.eval ρ != 0) then .error (.panic 0x11) + else .ok (.storageIndex x (.word (key.eval ρ)), rt))) := by + simp only [LValue.resolveWithRuntime, Expr.resolveLValue, LValue.toExpr, Expr.storageIndex, + Expr.orderFuel, Expr.listEvalFuel] + rw [Expr.resolveLValueFuel] + rw [eval_erase ρ fields ctx rt S hrel i gi key _ hi (by omega)] + unfold exprResult + split <;> rfl + +/-- SolidCore resolves the target `m[i1][i2]` to the path of the two keys' words, after their +overflow checks. -/ +theorem resolve_index2 (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : Runtime) + (S : SymState) (hrel : ExprRel ρ fields ctx rt S) (x : String) {i1 i2 : Expr} + {g1 g2 : List WExpr} {k1 k2 : WExpr} (h1 : eraseExpr fields S i1 = some (g1, k1)) + (h2 : eraseExpr fields S i2 = some (g2, k2)) : + (LValue.resolveWithRuntime (.index (.storageIndex x i1) i2) ctx rt).caught = + .done (.ok (if (g1 ++ g2).any (fun g => g.eval ρ != 0) then .error (.panic 0x11) + else .ok (.storagePath x [.word (k1.eval ρ), .word (k2.eval ρ)], rt))) := by + simp only [LValue.resolveWithRuntime, Expr.resolveLValue, LValue.toExpr, Expr.storageIndex, + Expr.orderFuel, Expr.listEvalFuel] + rw [Expr.resolveLValueFuel] + rw [Expr.resolveLValueFuel] + rw [eval_erase ρ fields ctx rt S hrel i1 g1 k1 _ h1 (by omega), bind_exprResult] + by_cases hg1 : g1.any (fun g => g.eval ρ != 0) = true + · simp only [hg1, any_append, Bool.true_or, ↓reduceIte] + rfl + · simp only [hg1, Bool.false_eq_true, ↓reduceIte, bind_done_ok, pure, + EvmCompiler.Simulation.Interaction.pure] + rw [eval_erase ρ fields ctx rt S hrel i2 g2 k2 _ h2 (by omega), bind_exprResult] + by_cases hg2 : g2.any (fun g => g.eval ρ != 0) = true + · simp only [hg2, any_append, Bool.or_true, ↓reduceIte] + rfl + · simp only [hg2, any_append, hg1, Bool.or_false, Bool.false_eq_true, ↓reduceIte] + rfl + +theorem eval_exprList (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : Runtime) + (S : SymState) (hrel : ExprRel ρ fields ctx rt S) : + ∀ (es : List Expr) (gs vs : List WExpr) (fuel : Nat), eraseExprs fields S es = some (gs, vs) → + Expr.listEvalFuel es ≤ fuel → + Expr.evalListFuel fuel ctx rt es = + if gs.any (fun g => g.eval ρ != 0) then .done (.error (.revert (.panic 0x11))) + else .done (.ok (vs.map (fun e => Value.word (e.eval ρ)), rt)) := by + intro es + induction es with + | nil => + intro gs vs fuel h hf + obtain ⟨n, rfl⟩ : ∃ n, fuel = n + 1 := ⟨fuel - 1, by simp [Expr.listEvalFuel] at hf; omega⟩ + simp only [eraseExprs, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + rw [Expr.evalListFuel] + rfl + | cons e es ih => + intro gs vs fuel h hf + obtain ⟨n, rfl⟩ : ∃ n, fuel = n + 1 := ⟨fuel - 1, by simp [Expr.listEvalFuel] at hf; omega⟩ + simp only [eraseExprs, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨⟨g, v⟩, he, ⟨gs', vs'⟩, hes, h⟩ := h + simp only [Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + simp only [Expr.listEvalFuel] at hf + have hpos : 1 ≤ Expr.listEvalFuel es := by cases es <;> simp [Expr.listEvalFuel] + rw [Expr.evalListFuel] + simp only [eval_erase ρ fields ctx rt S hrel e g v n he (by omega), bind_exprResult, + List.any_append] + by_cases h1 : g.any (fun g => g.eval ρ != 0) = true + · simp [h1] + · simp only [h1, Bool.false_eq_true, ↓reduceIte, Bool.false_or] + rw [ih gs' vs' n hes (by omega)] + by_cases h2 : gs'.any (fun g => g.eval ρ != 0) = true + · simp [h2]; rfl + · simp [h2]; rfl + +theorem materialize_words (ctx : Context) (rt : Runtime) (ρ : Val) : ∀ ws : List WExpr, + rt.materializeForValueUseList ctx (ws.map fun e => Value.word (e.eval ρ)) = + .ok (ws.map fun e => Value.word (e.eval ρ)) + | [] => rfl + | w :: ws => by + simp [Runtime.materializeForValueUseList, Runtime.materializeForValueUse, + Runtime.materializeForValueUseFuel, materialize_words ctx rt ρ ws, bind, Except.bind, pure, + Except.pure] + +/-- SolidCore emits a log of the fragment as the log the erasure appends. -/ +theorem emit_words (ρ : Val) (ctx : Context) (rt : Runtime) {name : String} {decl : EventDecl} + {t : Nat} (hfind : ctx.eventDecl? name = some decl) (ht : decl.topic? = some t) + {K : Facts} (hK : K.Hold ρ) {ws : List WExpr} (hok : evOk K decl.fields ws = true) : + ∃ ev rt', rt.emitEvent ctx name (ws.map fun e => Value.word (e.eval ρ)) = .ok rt' ∧ + rt'.state.events = rt.state.events ++ [ev] ∧ rt'.locals = rt.locals ∧ + rt'.state.storage = rt.state.storage ∧ + logOf ev = Log.eval ρ ⟨.lit t :: evTopics decl.fields ws, (evData decl.fields ws).flatMap wordOBytes⟩ := by + obtain ⟨a, b, henc⟩ := encode_ok ρ hK decl.fields ws hok + have hdata := encodeValues_ok ρ hK decl.fields ws hok + have hun : (ws.map fun e => Value.word (e.eval ρ)).map Value.untagFixedBytes = + ws.map fun e => Value.word (e.eval ρ) := by + simp [Value.untagFixedBytes] + simp only [Runtime.emitEvent, hun, hfind, ht, Option.isNone_some, Bool.and_false, + Bool.false_eq_true, ↓reduceIte, EventDecl.encodeFields?, henc, hdata, + SolidCore.Solidity.Shared.Log.append] + refine ⟨?ev, ?rt', ?h0, ?ha, ?hb, ?hc, ?hd⟩ + case h0 => exact rfl + case ha => exact rfl + case hb => first | exact rfl | trivial + case hc => first | exact rfl | trivial + simp only [logOf, Log.eval, Option.toList_some, List.cons_append, List.nil_append, List.map_cons, + WExpr.eval, norm_mod, List.map_map] + refine Prod.ext ?_ ?_ + · simp only [List.cons.injEq] + refine ⟨by first | rfl | trivial, ?_⟩ + apply List.map_congr_left + intro e _ + simp [norm_mod, Nat.mod_eq_of_lt (e.eval_lt ρ)] + · simp only [SolidCore.Solidity.Shared.Account.normalizeBytes, List.map_map] + apply List.map_congr_left + intro b _ + simp only [Function.comp, SolidCore.Solidity.Shared.Account.byte] + cases b <;> simp [OByte.eval, Nat.mod_mod] + +theorem eraseExprs_length {fields : List StorageField} {S : SymState} : + ∀ {es : List Expr} {gs vs : List WExpr}, eraseExprs fields S es = some (gs, vs) → + vs.length = es.length + | [], gs, vs, h => by + simp only [eraseExprs, Option.some.injEq, Prod.mk.injEq] at h + rw [← h.2]; rfl + | e :: es, gs, vs, h => by + simp only [eraseExprs, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨⟨g, v⟩, -, ⟨gs', vs'⟩, hes, h⟩ := h + simp only [Prod.mk.injEq] at h + rw [← h.2, List.length_cons, List.length_cons, eraseExprs_length hes] + +theorem assignLocal_word {ρ : Val} {rt : Runtime} {sc sc' : Scopes} {x : String} {v : WExpr} + (hfr : rt.locals = sc.map (frameOf ρ)) (h : Scopes.set sc x v = some sc') : + rt.assignLocal? x (.word (v.eval ρ)) = some { rt with locals := sc'.map (frameOf ρ) } := by + obtain ⟨old, hold⟩ := Scopes.get?_of_set h + have hx : rt.lookupLocal? x = some (.word (old.eval ρ)) := by + simp [Runtime.lookupLocal?, hfr, env_lookup, hold] + simp [Runtime.assignLocal?, hx, Value.coerceLike?, hfr, env_assign ρ sc x v, h] + +theorem assignMany_words {ρ : Val} : ∀ (xs : List String) (ws : List WExpr) (rt : Runtime) + (sc sc' : Scopes), rt.locals = sc.map (frameOf ρ) → Scopes.setMany sc xs ws = some sc' → + rt.assignNamedValues? xs (ws.map fun e => .word (e.eval ρ)) = + some { rt with locals := sc'.map (frameOf ρ) } ∧ + rt.assignNamedValuesRef? xs (ws.map fun e => .word (e.eval ρ)) = + some { rt with locals := sc'.map (frameOf ρ) } + | [], [], rt, sc, sc', hfr, h => by + simp only [Scopes.setMany, Option.some.injEq] at h + subst h + rw [← hfr] + exact ⟨rfl, rfl⟩ + | x :: xs, w :: ws, rt, sc, sc', hfr, h => by + simp only [Scopes.setMany, Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨sc1, h1, h2⟩ := h + have ha := assignLocal_word hfr h1 + obtain ⟨ih1, ih2⟩ := assignMany_words xs ws { rt with locals := sc1.map (frameOf ρ) } sc1 sc' rfl h2 + simp only [List.map_cons, Runtime.assignNamedValues?, Runtime.assignNamedValuesRef?, + Runtime.assignLocalRefAware?, ha] + exact ⟨ih1, ih2⟩ + | [], _ :: _, _, _, _, _, h | _ :: _, [], _, _, _, _, h => by simp [Scopes.setMany] at h + +theorem eval_refArgs (ρ : Val) (fields : List StorageField) (ctx : Context) (rt : Runtime) + (S : SymState) (hrel : ExprRel ρ fields ctx rt S) : + ∀ (es : List Expr) (gs vs : List WExpr) (fuel : Nat), eraseExprs fields S es = some (gs, vs) → + Expr.listEvalFuel es ≤ fuel → + Expr.evalRefArgListFuel fuel ctx rt es = + if gs.any (fun g => g.eval ρ != 0) then .done (.error (.revert (.panic 0x11))) + else .done (.ok (vs.map (fun e => Value.word (e.eval ρ)), rt)) := by + intro es + induction es with + | nil => + intro gs vs fuel h hf + obtain ⟨n, rfl⟩ : ∃ n, fuel = n + 1 := ⟨fuel - 1, by simp [Expr.listEvalFuel] at hf; omega⟩ + simp only [eraseExprs, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + rw [Expr.evalRefArgListFuel] + rfl + | cons e es ih => + intro gs vs fuel h hf + obtain ⟨n, rfl⟩ : ∃ n, fuel = n + 1 := ⟨fuel - 1, by simp [Expr.listEvalFuel] at hf; omega⟩ + simp only [eraseExprs, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨⟨g, v⟩, he, ⟨gs', vs'⟩, hes, h⟩ := h + simp only [Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + simp only [Expr.listEvalFuel] at hf + have hpos : 1 ≤ Expr.listEvalFuel es := by cases es <;> simp [Expr.listEvalFuel] + have hv : Expr.evalRefArg ctx rt e = exprResult ρ g v rt := by + have := eval_eq ρ fields ctx rt S hrel he + unfold Expr.evalRefArg + split + · rename_i x + have hx : ∃ ex, Scopes.get? S.scopes x = some ex := by + simp only [eraseExpr, Option.map_eq_some_iff] at he + obtain ⟨ex, hex, -⟩ := he + exact ⟨ex, hex⟩ + obtain ⟨ex, hex⟩ := hx + have hl := hrel.locals x ex hex + have hb : rt.lookupStorageBase? x = none := by simp [Runtime.lookupStorageBase?, hl] + have hm : rt.lookupMemoryRef? x = none := by simp [Runtime.lookupMemoryRef?, hl] + simp only [hb, hm] + exact this + · exact this + rw [Expr.evalRefArgListFuel] + simp only [hv, bind_exprResult, List.any_append] + by_cases h1 : g.any (fun g => g.eval ρ != 0) = true + · simp [h1] + · simp only [h1, Bool.false_eq_true, ↓reduceIte, Bool.false_or] + rw [ih gs' vs' n hes (by omega)] + by_cases h2 : gs'.any (fun g => g.eval ρ != 0) = true + · simp [h2]; rfl + · simp [h2]; rfl + +theorem wordDecl_spec {b : BindingDecl} (h : wordDecl b = true) (v : Nat) : + b.ty.coerceValue? (.word v) = some (.word v) ∧ b.defaultBinding = (b.name, .word 0) := by + simp only [wordDecl, Bool.and_eq_true, Bool.not_eq_true'] at h + have := wordTy_coerce h.1 v + refine ⟨this.1, ?_⟩ + simp [BindingDecl.defaultBinding, h.2, (wordTy_coerce h.1 0).2] + +theorem bindArgsRef_words (ρ : Val) : ∀ (ps : List BindingDecl) (vs : List WExpr), + ps.all wordDecl = true → vs.length = ps.length → + BindingDecl.bindArgsRef? ps (vs.map fun e => .word (e.eval ρ)) = + some ((ps.zip vs).map fun p => (p.1.name, Value.word (p.2.eval ρ))) + | [], [], _, _ => rfl + | p :: ps, v :: vs, hp, hl => by + simp only [List.all_cons, Bool.and_eq_true] at hp + have ih := bindArgsRef_words ρ ps vs hp.2 (by simpa using hl) + simp [BindingDecl.bindArgsRef?, BindingDecl.bindArgRef?, BindingDecl.bindArg?, + (wordDecl_spec hp.1 _).1, ih, bind, Option.bind] + | [], _ :: _, _, hl | _ :: _, [], _, hl => by simp at hl + +theorem initialFrame_words (ρ : Val) (fn : InternalFunction) (vs : List WExpr) + (hp : fn.params.all wordDecl = true) (hr : fn.returns.all wordDecl = true) + (hl : vs.length = fn.params.length) : + fn.initialFrame? (vs.map fun e => .word (e.eval ρ)) = some (frameOf ρ (callFrame fn vs)) := by + have hd : fn.returnDefaultBindings = fn.returns.map fun r => (r.name, Value.word 0) := by + simp only [InternalFunction.returnDefaultBindings] + apply List.map_congr_left + intro r hrm + exact (wordDecl_spec (List.all_eq_true.mp hr r hrm) 0).2 + simp only [InternalFunction.initialFrame?, bindArgsRef_words ρ fn.params vs hp hl, hd, callFrame, + frameOf, List.map_append, List.map_map] + rfl + +theorem deref_word' (rt : Runtime) (v : Nat) : rt.derefMemoryValueDeep (.word v) = .ok (.word v) := by + simp [Runtime.derefMemoryValueDeep, Runtime.derefMemoryValueWithFuel] + +theorem collectRef_words (ρ : Val) (rt : Runtime) (sc : Scopes) + (hfr : rt.locals = sc.map (frameOf ρ)) : ∀ (rs : List BindingDecl) (ws : List WExpr), + rs.all wordDecl = true → rs.mapM (fun r => Scopes.get? sc r.name) = some ws → + collectReturnBindingsRef.collect rt rs = .ok (ws.map fun e => .word (e.eval ρ)) + | [], ws, _, h => by + simp only [List.mapM_nil, Option.pure_def, Option.some.injEq] at h + subst h; rfl + | r :: rs, ws, hr, h => by + simp only [List.all_cons, Bool.and_eq_true] at hr + simp only [List.mapM_cons, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.pure_def, + Option.some.injEq] at h + obtain ⟨w, hw, ws', hws', rfl⟩ := h + have hl : rt.lookupLocal? r.name = some (.word (w.eval ρ)) := by + simp [Runtime.lookupLocal?, hfr, env_lookup, hw] + simp [collectReturnBindingsRef.collect, hl, deref_word', (wordDecl_spec hr.1 _).1, + collectRef_words ρ rt sc hfr rs ws' hr.2 hws', bind, Except.bind, pure, Except.pure] + +theorem coerceRef_words (ρ : Val) (rt : Runtime) : ∀ (rs : List BindingDecl) (vs : List WExpr), + rs.all wordDecl = true → vs.length = rs.length → + coerceReturnBindingsRef.coerce rt rs (vs.map fun e => .word (e.eval ρ)) = + .ok (vs.map fun e => .word (e.eval ρ)) + | [], [], _, _ => rfl + | r :: rs, v :: vs, hr, hl => by + simp only [List.all_cons, Bool.and_eq_true] at hr + simp [coerceReturnBindingsRef.coerce, deref_word', (wordDecl_spec hr.1 _).1, + coerceRef_words ρ rt rs vs hr.2 (by simpa using hl), bind, Except.bind, pure, Except.pure] + | [], _ :: _, _, hl | _ :: _, [], _, hl => by simp at hl + +theorem callAssign_ok {ρ : Val} {E : EraseEnv} {ctx : Context} {rt rt1 : Runtime} {S S1 : SymState} + (hrel : StmtRel ρ E ctx rt S) (hrel1 : StmtRel ρ E ctx rt1 S1) {targets : List String} + {ws : List WExpr} {c : Br} (h : callAssign targets S S1 ws = some c) : + ∃ r, internalCallAssign { rt1 with locals := rt.locals } targets + (ws.map fun e => .word (e.eval ρ)) = .done (.ok r) ∧ LeafRel ρ E ctx r (c.eval ρ) := by + unfold callAssign at h + split at h + · rename_i ht + subst ht + simp only [Option.some.injEq] at h + subst h + exact ⟨_, rfl, { hrel1 with frames := hrel.frames, sender := hrel.sender }⟩ + · rename_i ht + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨sc, hsc, rfl⟩ := h + have := (assignMany_words targets ws { rt1 with locals := rt.locals } S.scopes sc hrel.frames hsc).2 + have hne : targets.isEmpty = false := by cases targets <;> simp_all + refine ⟨.normal { rt1 with locals := sc.map (frameOf ρ) }, ?_, + (show StmtRel ρ E ctx { rt1 with locals := sc.map (frameOf ρ) } + { scopes := sc, writes := S1.writes, logs := S1.logs, caller := S.caller } from { hrel1 with frames := rfl, sender := hrel.sender })⟩ + simp only [internalCallAssign, hne, Bool.false_eq_true, ↓reduceIte, this] + rfl + +theorem finish_call {ρ : Val} {E : EraseEnv} {ctx : Context} {rt : Runtime} {S : SymState} + (hrel : StmtRel ρ E ctx rt S) {fn : InternalFunction} {targets : List String} + (hr : fn.returns.all wordDecl = true) : + ∀ (rc : Result) (l : Leaf) (c : Br), LeafRel ρ E ctx rc l → callLeaf fn targets S l = some c → + ∃ r, internalCallFinish fn targets rt.locals rc = .done (.ok r) ∧ LeafRel ρ E ctx r (c.eval ρ) + | .normal rt1, .normal S1, c, h1, h => by + simp only [LeafRel] at h1 + simp only [callLeaf, Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨ws, hws, h⟩ := h + simp only [internalCallFinish, collectReturnBindingsRef, + collectRef_words ρ rt1 S1.scopes h1.frames fn.returns ws hr hws] + exact callAssign_ok hrel h1 h + | .returned rt1 vals, .returned S1 vs, c, h1, h => by + simp only [LeafRel] at h1 + obtain ⟨h1, rfl⟩ := h1 + simp only [callLeaf] at h + split at h + · rename_i hv + subst hv + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨ws, hws, h⟩ := h + simp only [internalCallFinish, List.map_nil, List.isEmpty_nil, ↓reduceIte, collectReturnBindingsRef, + collectRef_words ρ rt1 S1.scopes h1.frames fn.returns ws hr hws] + exact callAssign_ok hrel h1 h + · rename_i hv + split at h + · rename_i hl + have hne : (vs.map fun e => Value.word (e.eval ρ)).isEmpty = false := by + cases vs with + | nil => exact absurd rfl hv + | cons _ _ => rfl + simp only [internalCallFinish, hne, Bool.false_eq_true, ↓reduceIte, coerceReturnBindingsRef, + coerceRef_words ρ rt1 fn.returns vs hr hl] + exact callAssign_ok hrel h1 h + · simp at h + | .reverted rt1 err, .reverted p, c, h1, h => by + simp only [callLeaf, Option.some.injEq] at h + subst h + exact ⟨.reverted rt1 err, rfl, h1⟩ + | .normal _, .returned _ _, _, h1, _ | .normal _, .reverted _, _, h1, _ + | .returned _ _, .normal _, _, h1, _ | .returned _ _, .reverted _, _, h1, _ + | .reverted _ _, .normal _, _, h1, _ | .reverted _ _, .returned _ _, _, h1, _ + | .broke _, _, _, h1, _ | .continued _, _, _, h1, _ | .selfdestructed _, _, _, h1, _ => by + first | (cases h1) | (rename_i l; cases l <;> cases h1) | skip + +theorem capture_ok {ρ : Val} {E : EraseEnv} {ctx : Context} (names : List String) : + ∀ (rc : Result) (l : Leaf) (c : Br), LeafRel ρ E ctx rc l → captureLeaf names l = some c → + ∃ r, (match rc with + | Result.returned runtime' values => + if values.isEmpty || names.isEmpty then (pure (Result.normal runtime') : SolI Result) + else + match runtime'.assignNamedValues? names values with + | some updated => pure (Result.normal updated) + | none => pure (Result.reverted runtime' RevertData.typeMismatch) + | result => pure result) = .done (.ok r) ∧ LeafRel ρ E ctx r (c.eval ρ) + | .returned rt1 vals, .returned S1 vs, c, h1, h => by + simp only [LeafRel] at h1 + obtain ⟨h1, rfl⟩ := h1 + simp only [captureLeaf] at h + split at h + · rename_i hv + simp only [Option.some.injEq] at h + subst h + have : ((vs.map fun e => Value.word (e.eval ρ)).isEmpty || names.isEmpty) = true := by + rcases hv with rfl | rfl <;> simp + simp only [this, ↓reduceIte] + exact ⟨_, rfl, h1⟩ + · rename_i hv + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨sc, hsc, rfl⟩ := h + have : ((vs.map fun e => Value.word (e.eval ρ)).isEmpty || names.isEmpty) = false := by + cases vs <;> cases names <;> simp_all + have ha := (assignMany_words names vs rt1 S1.scopes sc h1.frames hsc).1 + simp only [this, Bool.false_eq_true, ↓reduceIte, ha] + exact ⟨_, rfl, { h1 with frames := rfl }⟩ + | .normal rt1, .normal S1, c, h1, h => by + simp only [captureLeaf, Option.some.injEq] at h + subst h + exact ⟨_, rfl, h1⟩ + | .reverted rt1 err, .reverted p, c, h1, h => by + simp only [captureLeaf, Option.some.injEq] at h + subst h + exact ⟨_, rfl, h1⟩ + | .normal _, .returned _ _, _, h1, _ | .normal _, .reverted _, _, h1, _ + | .returned _ _, .normal _, _, h1, _ | .returned _ _, .reverted _, _, h1, _ + | .reverted _ _, .normal _, _, h1, _ | .reverted _ _, .returned _ _, _, h1, _ + | .broke _, _, _, h1, _ | .continued _, _, _, h1, _ | .selfdestructed _, _, _, h1, _ => by + first | (cases h1) | (rename_i l; cases l <;> cases h1) | skip + +theorem uintCleanup_256_unchecked (w : Nat) (hw : w < wordSize) : + uintCleanup? false 256 (.word w) = .ok (.word w) := by + simp [uintCleanup?, Value.forceAbiLazy, Value.asStorageWord?, norm_lt hw, uintCast?, bind, + Except.bind, Nat.mod_eq_of_lt hw] + +theorem apply_add_wrap (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply false .add (.word a) (.word b) = .ok (.word ((a + b) % wordSize)) := by + simp [BinaryOp.apply, Value.forceAbiLazy, BinaryOp.applyWord, norm_lt ha, norm_lt hb, + bind, Except.bind, Functor.map, Except.map, checkedAdd, addWord_eq] + +theorem apply_sub_wrap (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply false .sub (.word a) (.word b) = .ok (.word ((a + (wordSize - b)) % wordSize)) := by + simp [BinaryOp.apply, Value.forceAbiLazy, BinaryOp.applyWord, norm_lt ha, norm_lt hb, + bind, Except.bind, Functor.map, Except.map, checkedSub, subWord_eq a b ha hb] + +theorem apply_ge_unchecked (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply false .ge (.word a) (.word b) = .ok (.word (if a < b then 0 else 1)) := by + by_cases h : a < b <;> + simp [BinaryOp.apply, Value.forceAbiLazy, BinaryOp.applyWord, bind, Except.bind, Functor.map, + Except.map, ltWord_eq, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb, boolWord, wordTruthy, h, + SolidCore.Solidity.Shared.norm, modulus_eq] + +theorem apply_le_unchecked (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply false .le (.word a) (.word b) = .ok (.word (if b < a then 0 else 1)) := by + by_cases h : b < a <;> + simp [BinaryOp.apply, Value.forceAbiLazy, BinaryOp.applyWord, bind, Except.bind, Functor.map, + Except.map, gtWord_eq, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb, boolWord, wordTruthy, h, + SolidCore.Solidity.Shared.norm, modulus_eq] + +theorem apply_ne_unchecked (a b : Nat) (ha : a < wordSize) (hb : b < wordSize) : + BinaryOp.apply false .ne (.word a) (.word b) = .ok (.word (if a = b then 0 else 1)) := by + by_cases h : a = b <;> + simp [BinaryOp.apply, Value.forceAbiLazy, bind, Except.bind, Functor.map, Except.map, boolWord, wordEq, + norm_lt ha, norm_lt hb, h] + +theorem eval_wrapRead (ρ : Val) (ctx : Context) (rt : Runtime) (S : SymState) + (hchk : ctx.checked = false) + (hloc : ∀ x e, Scopes.get? S.scopes x = some e → rt.lookupLocal? x = some (.word (e.eval ρ))) : + ∀ (e : Expr) (w : WExpr) (fuel : Nat), wrapRead S e = some w → Expr.orderFuel e < fuel → + Expr.evalFuel fuel ctx rt e = .done (.ok (.word (w.eval ρ), rt)) := by + intro e w fuel h hf + obtain ⟨n, rfl⟩ : ∃ n, fuel = n + 1 := ⟨fuel - 1, by omega⟩ + cases e + case var x => + simp only [wrapRead] at h + have hl := hloc x w h + simp [Expr.evalFuel, Runtime.lookupStorageBase?, hl, Runtime.derefMemoryValue] + rfl + case castOp k b e => + cases k + case uintCleanup => + by_cases hb : b = 256 + · subst hb + simp only [wrapRead] at h + have ih := eval_wrapRead ρ ctx rt S hchk hloc e w n h (by simp [Expr.orderFuel] at hf; omega) + simp only [Expr.evalFuel, ih, hchk] + simp only [bind, EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, + MonadLift.monadLift, uintCleanup_256_unchecked _ (w.eval_lt ρ), SolI.ofExcept] + rfl + · simp [wrapRead, hb] at h + all_goals simp [wrapRead] at h + case binary op l r => + cases hl : wrapRead S l with + | none => simp [wrapRead, hl] at h + | some vl => + cases hr : wrapRead S r with + | none => simp [wrapRead, hl, hr] at h + | some vr => + have ihl := eval_wrapRead ρ ctx rt S hchk hloc l vl n hl (by simp [Expr.orderFuel] at hf; omega) + have ihr := eval_wrapRead ρ ctx rt S hchk hloc r vr n hr (by simp [Expr.orderFuel] at hf; omega) + have hal := vl.eval_lt ρ + have har := vr.eval_lt ρ + cases op <;> simp only [wrapRead, wrapOf, hl, hr, Option.bind_eq_bind, Option.bind_some, + Option.some.injEq, reduceCtorEq, Option.bind_none] at h + all_goals + subst h + simp only [Expr.evalFuel, ihr, ihl, hchk] + simp only [pure, EvmCompiler.Simulation.Interaction.pure, bind, + EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, MonadLift.monadLift, ihl, ihr, + apply_add_wrap _ _ hal har, apply_sub_wrap _ _ hal har, SolI.ofExcept] + simp [WExpr.eval, BinOp.eval, Nat.mod_mod] + all_goals simp [wrapRead] at h + +theorem eval_uncheckedCond (ρ : Val) (ctx : Context) (rt : Runtime) (S : SymState) + (hchk : ctx.checked = false) (hframes : rt.locals = S.scopes.map (frameOf ρ)) + (hloc : ∀ x e, Scopes.get? S.scopes x = some e → rt.lookupLocal? x = some (.word (e.eval ρ))) + {c : Expr} {z : String} {w v : WExpr} {L : Scopes} + (h : uncheckedCond S c = some (z, w, v)) (hL : Scopes.set S.scopes z w = some L) : + ∀ fuel, Expr.orderFuel c < fuel → + Expr.evalFuel fuel ctx rt c = .done (.ok (.word (v.eval ρ), { rt with locals := L.map (frameOf ρ) })) := by + intro fuel hf + unfold uncheckedCond at h + split at h + case h_2 => simp at h + rename_i cmp z' rhs c2 + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨vc, hc, w', hw, v', ho, rfl, rfl, rfl⟩ := h + obtain ⟨old, hold⟩ := Scopes.get?_of_set hL + have hx := hloc z' old hold + have hbase : rt.lookupStorageBase? z' = none := by simp [Runtime.lookupStorageBase?, hx] + have hassign : rt.assignLocal? z' (.word (w'.eval ρ)) = some { rt with locals := L.map (frameOf ρ) } := by + simp [Runtime.assignLocal?, hx, Value.coerceLike?, hframes, env_assign ρ S.scopes z' w', hL] + simp only [Expr.orderFuel] at hf + obtain ⟨n, rfl⟩ : ∃ n, fuel = n + 1 := ⟨fuel - 1, by omega⟩ + obtain ⟨m, rfl⟩ : ∃ m, n = m + 1 := ⟨n - 1, by omega⟩ + obtain ⟨k, rfl⟩ : ∃ k, m = k + 1 := ⟨m - 1, by omega⟩ + obtain ⟨j, rfl⟩ : ∃ j, k = j + 1 := ⟨k - 1, by omega⟩ + have hvc := eval_wrapRead ρ ctx rt S hchk hloc c2 vc (j + 1 + 1 + 1) hc (by omega) + have hvw := eval_wrapRead ρ ctx rt S hchk hloc rhs w' (j + 1) hw (by omega) + have hres : Expr.resolveLValueFuel (j + 1) ctx rt (.var z') = .done (.ok (.local z', rt)) := by + simp [Expr.resolveLValueFuel, hbase, hx] + rfl + have hwv := w'.eval_lt ρ + have hcv := vc.eval_lt ρ + have hA : Expr.evalFuel (j + 1 + 1) ctx rt (.assignment none none (.var z') rhs) = + .done (.ok (.word (w'.eval ρ), { rt with locals := L.map (frameOf ρ) })) := by + rw [Expr.evalFuel] + simp only [pure, EvmCompiler.Simulation.Interaction.pure, bind, + EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, MonadLift.monadLift, hvw, hres, + ResolvedLValue.write, hassign, SolI.ofExcept] + have hC : Expr.evalFuel (j + 1 + 1 + 1) ctx rt + (.castOp .uintCleanup 256 (.assignment none none (.var z') rhs)) = + .done (.ok (.word (w'.eval ρ), { rt with locals := L.map (frameOf ρ) })) := by + rw [Expr.evalFuel] + simp only [pure, EvmCompiler.Simulation.Interaction.pure, bind, + EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, MonadLift.monadLift, hA, hchk, + uintCleanup_256_unchecked _ hwv, SolI.ofExcept] + cases cmp <;> simp [cmpOf] at ho + all_goals + subst ho + rw [Expr.evalFuel] <;> try (intro h; cases h) + simp only [pure, EvmCompiler.Simulation.Interaction.pure, bind, + EvmCompiler.Simulation.Interaction.bind, liftM, monadLift, MonadLift.monadLift, hvc, hC, hchk, + SolI.ofExcept, apply_ge_unchecked _ _ hwv hcv, apply_le_unchecked _ _ hwv hcv, + apply_ne_unchecked _ _ hwv hcv] + simp only [WExpr.eval, BinOp.eval, UnOp.eval] + split <;> simp_all + +theorem eval_unchecked (ρ : Val) (E : EraseEnv) (ctx : Context) (k : Nat) (body : Stmt) + (S : SymState) (b : Br) (h : eraseUnchecked S body = some b) (rt : Runtime) + (hrel : StmtRel ρ E ctx rt S) : + ∃ r, Stmt.eval (k + 2) E.tbl { ctx with checked := false } rt body = .done (.ok r) ∧ + LeafRel ρ E ctx r (b.eval ρ) := by + unfold eraseUnchecked at h + split at h + case h_2 => simp at h + rename_i c rs + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨⟨z, w, v⟩, hc, L, hL, rfl⟩ := h + have hrel' := hrel.pushScope + have hcond : Expr.eval { ctx with checked := false } rt.pushScope c = + .done (.ok (.word (v.eval ρ), { rt.pushScope with locals := L.map (frameOf ρ) })) := + eval_uncheckedCond ρ _ rt.pushScope S.push rfl hrel'.frames + (fun x e he => hrel'.expr.locals x e he) hc hL _ (Nat.lt_succ_self _) + have hrelL : StmtRel ρ E ctx { rt.pushScope with locals := L.map (frameOf ρ) } + { S.push with scopes := L } := { hrel' with frames := rfl } + have hinner : ∃ r, Stmt.evalList (k + 1) E.tbl { ctx with checked := false } rt.pushScope + [.requireStmt c rs] = .done (.ok r) ∧ + LeafRel ρ E ctx r ((Br.ite v (.leaf (.normal { S.push with scopes := L })) + (.leaf (.reverted (failOf rs)))).eval ρ) := by + rw [Stmt.evalList, Stmt.eval] + simp only [hcond, caught_done_ok, bind_done_ok, Value.expectWord, norm_lt (v.eval_lt ρ), Br.eval, + wordTruthy] + by_cases hv : v.eval ρ = 0 + · cases rs + case none => + refine ⟨.reverted { rt.pushScope with locals := L.map (frameOf ρ) } .empty, ?_, by simp only [hv, ↓reduceIte, LeafRel]; rfl⟩ + simp [hv, Stmt.evalList] + rfl + case some m => + refine ⟨.reverted { rt.pushScope with locals := L.map (frameOf ρ) } (.error m), ?_, by simp only [hv, ↓reduceIte, LeafRel]; rfl⟩ + simp [hv, Stmt.evalList] + rfl + · refine ⟨.normal { rt.pushScope with locals := L.map (frameOf ρ) }, ?_, by simp only [hv, ↓reduceIte, LeafRel]; exact hrelL⟩ + simp [hv, SolidCore.Solidity.Shared.norm, modulus_eq, Nat.mod_eq_of_lt (v.eval_lt ρ), + Stmt.evalList] + rfl + obtain ⟨r, hr, hl⟩ := hinner + refine ⟨r.mapRuntime Runtime.popScope, ?_, ?_⟩ + · rw [Stmt.eval] + simp only [hr, bind, EvmCompiler.Simulation.Interaction.bind] + rfl + · rw [Br.eval_mapS] + exact hl.popScope + +theorem eval_stmt (ρ : Val) (E : EraseEnv) (ctx : Context) : + ∀ n s S b, eraseStmt E n s S = some b → ∀ rt, StmtRel ρ E ctx rt S → + ∃ r, Stmt.eval n E.tbl ctx rt s = .done (.ok r) ∧ LeafRel ρ E ctx r (b.eval ρ) := by + intro n + induction n with + | zero => intro s S b h; simp [eraseStmt] at h + | succ n ih => + intro s S b h rt hrel + cases s + case skip => + simp only [eraseStmt, Option.some.injEq] at h + subst h + exact ⟨.normal rt, by rw [Stmt.eval]; rfl, hrel⟩ + case block ss => + simp only [eraseStmt, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨b0, h0, rfl⟩ := h + obtain ⟨r, hr, hl⟩ := eval_seq_of ρ E ctx n ih ss S.push b0 h0 rt.pushScope hrel.pushScope + refine ⟨r.mapRuntime Runtime.popScope, ?_, ?_⟩ + · rw [Stmt.eval] + simp only [hr, bind, EvmCompiler.Simulation.Interaction.bind] + rfl + · rw [Br.eval_mapS] + exact hl.popScope + case varDecl ty x init => + simp only [eraseStmt] at h + split at h + case isFalse => simp at h + rename_i hty + have hco := fun v => (wordTy_coerce hty v).1 + have hdef := (wordTy_coerce hty 0).2 + cases init with + | none => + simp only [Option.some.injEq] at h + subst h + refine ⟨.normal (rt.declareLocal x (.word 0)), ?_, ?_⟩ + · rw [Stmt.eval] + simp only [hdef] + rfl + · have hf : (rt.declareLocal x (.word 0)).locals = + (S.scopes.declare x (.lit 0)).map (frameOf ρ) := by + rw [Runtime.declareLocal, hrel.frames] + exact env_declare ρ S.scopes x (.lit 0) + exact { hrel with frames := hf } + | some e => + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨⟨gs, v⟩, he, rfl⟩ := h + have heval := eval_eq ρ E.fields ctx rt S hrel.expr he + rw [Stmt.eval] + simp only [heval, caught_exprResult, guards_eval] + by_cases hg : gs.any (fun g => g.eval ρ != 0) = true + · simp only [hg, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hg, Bool.false_eq_true, ↓reduceIte, bind_done_ok, hco] + refine ⟨.normal (rt.declareLocal x (.word (v.eval ρ))), rfl, ?_⟩ + have hf : (rt.declareLocal x (.word (v.eval ρ))).locals = + (S.scopes.declare x v).map (frameOf ρ) := by + rw [Runtime.declareLocal, hrel.frames, env_declare] + exact { hrel with frames := hf } + case emitEvent name es => + simp only [eraseStmt, Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨decl, hdecl, t, ht, ⟨gs, svs⟩, hes, h⟩ := h + split at h + case isFalse => simp at h + rename_i hok + simp only [Option.some.injEq] at h + subst h + have hfind : ctx.eventDecl? name = some decl := by + simp [Context.eventDecl?, hrel.events, hdecl] + have hlist := eval_exprList ρ E.fields ctx rt S hrel.expr _ gs svs _ hes (Nat.le_refl _) + have hlog := emit_words ρ ctx rt hfind ht hrel.facts hok + have heq : Stmt.eval (n + 1) E.tbl ctx rt (.emitEvent name es) = + (do + match ← (Expr.evalList ctx rt + ((emitSchedule (emitFlags (some decl) es) es.length).filterMap + (fun i => es[i]?))).caught with + | Except.ok (scheduled, runtime') => + match runtime'.materializeForValueUseList ctx + (unschedule (emitSchedule (emitFlags (some decl) es) es.length) scheduled + es.length) with + | Except.ok values => + match runtime'.emitEvent ctx name values with + | Except.ok updated => pure (Result.normal updated) + | Except.error err => pure (Result.reverted rt err) + | Except.error err => pure (Result.reverted rt err) + | Except.error err => pure (Result.reverted rt err)) := by + rw [Stmt.eval] + simp only [hfind] + rfl + rw [heq, Expr.evalList, hlist] + rw [guards_eval] + by_cases hg : gs.any (fun g => g.eval ρ != 0) = true + · simp only [hg, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hg, Bool.false_eq_true, ↓reduceIte, caught_done_ok, bind_done_ok, + unschedule_map, materialize_words] + obtain ⟨ev, rt', hrt, hev, hloc, hsto, hl⟩ := hlog + simp only [hrt] + refine ⟨.normal rt', rfl, ?_⟩ + exact { hrel with + frames := by rw [hloc, hrel.frames] + store := fun k hk => by + rw [← hrel.store k hk] + simp only [State.loadSlot, hsto] + logs := by + rw [hev, List.map_append, hrel.logs, List.map_append] + simp only [List.map_cons, List.map_nil, hl] } + case captureReturn names body => + simp only [eraseStmt, Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨b0, hb0, h⟩ := h + obtain ⟨r0, hr0, hl0⟩ := ih body S b0 hb0 rt hrel + obtain ⟨c, hc, hce⟩ := Br.bindLeaf_eval ρ h + obtain ⟨r, hr, hl⟩ := capture_ok names r0 (b0.eval ρ) c hl0 hc + refine ⟨r, ?_, hce ▸ hl⟩ + rw [Stmt.eval] + simp only [hr0, bind_done_ok] + exact hr + case internalCall targets callee args => + simp only [eraseStmt, Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨fn, hfn, h⟩ := h + split at h + case isFalse => simp at h + rename_i hshape + simp only [Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨⟨gs, vs⟩, hargs, b0, hb0, b1, hb1, rfl⟩ := h + simp only [Bool.and_eq_true, decide_eq_true_eq] at hshape + have hp : fn.params.all wordDecl = true := hshape.1.1 + have hr : fn.returns.all wordDecl = true := hshape.1.2 + have hvl : vs.length = fn.params.length := (eraseExprs_length hargs).trans hshape.2 + have hev := eval_refArgs ρ E.fields ctx rt S hrel.expr args gs vs _ hargs (Nat.le_refl _) + rw [Stmt.eval] + simp only [Expr.evalRefArgList, hev] + rw [guards_eval] + by_cases hg : gs.any (fun g => g.eval ρ != 0) = true + · simp only [hg, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hg, Bool.false_eq_true, ↓reduceIte, caught_done_ok, bind_done_ok, hfn, + internalCallEnter?, initialFrame_words ρ fn vs hp hr hvl] + have hctx : ({ ctx with checked := true } : Context) = ctx := by + rw [show true = ctx.checked from hrel.checked.symm] + have hrel0 : StmtRel ρ E ctx { rt with locals := [frameOf ρ (callFrame fn vs)] } + { scopes := [callFrame fn vs], writes := S.writes, logs := S.logs, caller := S.caller } := + { hrel with frames := rfl } + obtain ⟨r0, hr0, hl0⟩ := ih fn.body _ b0 hb0 _ hrel0 + rw [hctx, hr0, bind_done_ok] + obtain ⟨c, hc, hce⟩ := Br.bindLeaf_eval ρ hb1 + rw [hce] + exact finish_call hrel hr r0 _ c hl0 hc + case panic code => + simp only [eraseStmt, Option.some.injEq] at h + subst h + exact ⟨.reverted rt (.panic code), by rw [Stmt.eval]; rfl, rfl⟩ + case requireStmt c r => + simp only [eraseStmt, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨⟨gs, v⟩, hc, rfl⟩ := h + have heval := eval_eq ρ E.fields ctx rt S hrel.expr hc + rw [Stmt.eval] + simp only [heval, caught_exprResult, guards_eval] + by_cases hg : gs.any (fun g => g.eval ρ != 0) = true + · simp only [hg, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hg, Bool.false_eq_true, ↓reduceIte, bind_done_ok, Value.expectWord, + norm_lt (v.eval_lt ρ), Br.eval, wordTruthy] + by_cases hv : v.eval ρ = 0 + · cases r + case none => + refine ⟨.reverted rt .empty, ?_, by simp only [hv, ↓reduceIte, LeafRel]; rfl⟩ + simp [hv] + rfl + case some m => + refine ⟨.reverted rt (.error m), ?_, by simp only [hv, ↓reduceIte, LeafRel]; rfl⟩ + simp [hv] + rfl + · refine ⟨.normal rt, ?_, by simp only [hv, ↓reduceIte, LeafRel]; exact hrel⟩ + simp [hv, SolidCore.Solidity.Shared.norm, modulus_eq, Nat.mod_eq_of_lt (v.eval_lt ρ)] + rfl + case revertError r => + simp only [eraseStmt, Option.some.injEq] at h + subst h + cases r + case none => exact ⟨.reverted rt .empty, by rw [Stmt.eval]; rfl, rfl⟩ + case some m => exact ⟨.reverted rt (.error m), by rw [Stmt.eval]; rfl, rfl⟩ + + case assign target e => + cases target + case var x => + simp only [eraseStmt, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨⟨gs, v⟩, he, L', hL, rfl⟩ := h + obtain ⟨old, hold⟩ := Scopes.get?_of_set hL + have hx : rt.lookupLocal? x = some (.word (old.eval ρ)) := hrel.expr.locals x old hold + have hmem : rt.lookupMemoryRef? x = none := by simp [Runtime.lookupMemoryRef?, hx] + have hbase : rt.lookupStorageBase? x = none := by simp [Runtime.lookupStorageBase?, hx] + have heval := eval_eq ρ E.fields ctx rt S hrel.expr he + have hres : LValue.resolveWithRuntime (.var x) ctx rt = .done (.ok (.local x, rt)) := by + simp [LValue.resolveWithRuntime, Expr.resolveLValue, LValue.toExpr, Expr.orderFuel, + Expr.resolveLValueFuel, hbase, hx] + rfl + have hassign : rt.assignLocal? x (.word (v.eval ρ)) = + some { rt with locals := L'.map (frameOf ρ) } := by + simp [Runtime.assignLocal?, hx, Value.coerceLike?, hrel.frames, env_assign ρ S.scopes x v, hL] + have hrel' : StmtRel ρ E ctx { rt with locals := L'.map (frameOf ρ) } + { S with scopes := L' } := { hrel with frames := rfl } + rw [Stmt.eval] + simp only [LValue.wantsMemoryRefRhs, hmem, Option.isSome_none, Bool.false_eq_true, + ↓reduceIte, heval, caught_exprResult] + rw [guards_eval] + by_cases hg : gs.any (fun g => g.eval ρ != 0) = true + · simp only [hg, ↓reduceIte] + refine ⟨.reverted rt (.panic 0x11), ?_, rfl⟩ + split <;> (try split) <;> first | rfl | simp_all + · simp only [hg, Bool.false_eq_true, ↓reduceIte] + refine ⟨.normal { rt with locals := L'.map (frameOf ρ) }, ?_, hrel'⟩ + split + · split + · simp_all + · simp only [bind_done_ok, hres, caught_done_ok, ite_self, ResolvedLValue.write, hassign] + rfl + · simp only [bind_done_ok, hres, caught_done_ok, ite_self, ResolvedLValue.write, hassign] + rfl + case storageIndex x i => + simp only [eraseStmt, Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨⟨gs, v⟩, he, ⟨gi, key⟩, hi, h⟩ := h + obtain ⟨k, hk, hst, rfl⟩ : ∃ k, k < wordSize ∧ + rt.storeStorageIndexWithDeepClear ctx x (.word (key.eval ρ)) (.word (v.eval ρ)) = + .ok { rt with state := rt.state.storeSlot (solHash (key.eval ρ) k) (v.eval ρ) } ∧ + b = guards (gs ++ gi) + (.leaf (.normal { S with writes := S.writes.set (.hash key (.lit k)) v })) := by + split at h + · rename_i k hk + simp only [Option.some.injEq] at h + obtain ⟨f, hf, rfl⟩ := mapOf?_spec hrel.fields hk + exact ⟨f.slot, hf.slot, storeIndex_map hrel hk (key.eval_lt ρ) (v.eval_lt ρ), h.symm⟩ + · simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨k, hk, h⟩ := h + split at h + · rename_i hb + simp only [Option.some.injEq] at h + obtain ⟨f, hf, rfl⟩ := boolMapOf?_spec hrel.fields hk + exact ⟨f.slot, hf.slot, storeIndex_boolMap hrel hk (key.eval_lt ρ) + (Nat.le_trans (bound_sound hrel.facts v) hb), h.symm⟩ + · simp at h + have heval := eval_eq ρ E.fields ctx rt S hrel.expr he + have hres := resolve_storageIndex ρ E.fields ctx rt S hrel.expr x hi + have hsl : (WExpr.hash key (.lit k)).eval ρ = solHash (key.eval ρ) k % wordSize := by + simp only [WExpr.eval, hrel.hash, Nat.mod_eq_of_lt hk] + have hw := hrel.write (.hash key (.lit k)) v + rw [hsl, storeSlot_mod] at hw + rw [Stmt.eval] + simp only [LValue.wantsMemoryRefRhs, Bool.false_eq_true, ↓reduceIte, heval, caught_exprResult] + rw [guards_eval] + simp only [any_append] + by_cases hg : gs.any (fun g => g.eval ρ != 0) = true + · simp only [hg, Bool.true_or, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hg, Bool.false_or, Bool.false_eq_true, ↓reduceIte, bind_done_ok, hres] + by_cases hgi : gi.any (fun g => g.eval ρ != 0) = true + · simp only [hgi, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hgi, Bool.false_eq_true, ↓reduceIte, bind_done_ok, ResolvedLValue.write, hst, + ite_self] + exact ⟨_, rfl, hw⟩ + case index base i2 => + cases base + case storageIndex x i1 => + simp only [eraseStmt, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨k, hk, ⟨gs, v⟩, he, ⟨g1, k1⟩, h1, ⟨g2, k2⟩, h2, rfl⟩ := h + obtain ⟨f, hf, rfl⟩ := map2Of?_spec hrel.fields hk + have heval := eval_eq ρ E.fields ctx rt S hrel.expr he + have hres := resolve_index2 ρ E.fields ctx rt S hrel.expr x h1 h2 + simp only [any_append] at hres + have hsl : (WExpr.hash k2 (.hash k1 (.lit f.slot))).eval ρ = + solHash (k2.eval ρ) (solHash (k1.eval ρ) f.slot) % wordSize := by + simp only [WExpr.eval, hrel.hash, Nat.mod_eq_of_lt hf.slot, + Nat.mod_eq_of_lt (solHash_lt _ _)] + have hw := hrel.write (.hash k2 (.hash k1 (.lit f.slot))) v + rw [hsl, storeSlot_mod] at hw + have hst := storePath_map2 hrel hk (k1.eval_lt ρ) (k2.eval_lt ρ) (v.eval_lt ρ) + rw [Stmt.eval] + simp only [LValue.wantsMemoryRefRhs, LValue.toExpr, Expr.hasStorageRoot, Bool.true_or, + Bool.not_true, Bool.false_eq_true, ↓reduceIte, heval, caught_exprResult] + rw [guards_eval] + simp only [any_append] + by_cases hg : gs.any (fun g => g.eval ρ != 0) = true + · simp only [hg, Bool.true_or, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hg, Bool.false_or, Bool.false_eq_true, ↓reduceIte, bind_done_ok, hres] + by_cases hgi : (g1.any (fun g => g.eval ρ != 0) || g2.any (fun g => g.eval ρ != 0)) = true + · simp only [hgi, ↓reduceIte, Bool.or_assoc] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hgi, Bool.or_assoc, Bool.false_eq_true, ↓reduceIte, bind_done_ok, + ResolvedLValue.write, hst, ite_self] + exact ⟨_, rfl, hw⟩ + all_goals simp [eraseStmt] at h + case storage x => + simp only [eraseStmt, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨⟨k, off, bytes⟩, hk, ⟨gs, v⟩, he, rfl⟩ := h + obtain ⟨f, hfx, rfl, rfl, rfl⟩ := fieldOf?_spec hrel.fields hk + have heval := eval_eq ρ E.fields ctx rt S hrel.expr he + have hres : LValue.resolveWithRuntime (.storage x) ctx rt = + .done (.ok (.storageField x, rt)) := by + simp [LValue.resolveWithRuntime, Expr.resolveLValue, LValue.toExpr, Expr.orderFuel, + Expr.resolveLValueFuel] + rfl + have hw := v.eval_lt ρ + have hsl : rt.state.loadSlot f.slot = (S.writes.read (.lit f.slot)).eval ρ := + slot_read hrel.expr hfx.slot + have hslw : rt.state.loadSlot f.slot < wordSize := hsl ▸ WExpr.eval_lt _ _ + have hrelw := hrel.writeField hfx v + rw [Stmt.eval] + simp only [LValue.wantsMemoryRefRhs, Bool.false_eq_true, ↓reduceIte, heval, caught_exprResult] + rw [guards_eval] + by_cases hg : gs.any (fun g => g.eval ρ != 0) = true + · simp only [hg, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), by split <;> rfl, rfl⟩ + · simp only [hg, Bool.false_eq_true, ↓reduceIte] + refine ⟨.normal _, ?_, hrelw⟩ + simp only [bind_done_ok, hres, caught_done_ok, ResolvedLValue.write, + store_field hfx hslw _ hw, ite_self, writeField_eval ρ _ _ hfx.fits hfx.bytes, hsl] + rfl + all_goals simp [eraseStmt] at h + case returnValues es => + simp only [eraseStmt, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨⟨gs, vs⟩, hes, rfl⟩ := h + have hlen : es.length < Expr.listEvalFuel es := by + clear hes + induction es with + | nil => simp [Expr.listEvalFuel] + | cons e es ihl => simp only [List.length_cons, Expr.listEvalFuel]; omega + have hl := eval_returnList ρ E.fields ctx rt S hrel.expr es gs vs _ hes hlen + rw [Stmt.eval] + simp only [Expr.evalReturnList, hl, guards_eval] + by_cases hg : gs.any (fun g => g.eval ρ != 0) = true + · simp only [hg, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hg, Bool.false_eq_true, ↓reduceIte] + exact ⟨.returned rt (vs.map fun e => Value.word (e.eval ρ)), rfl, hrel, rfl⟩ + case ifElse c t e => + simp only [eraseStmt, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨⟨gs, v⟩, hc, bt, hbt, be, hbe, rfl⟩ := h + have heval := eval_eq ρ E.fields ctx rt S hrel.expr hc + rw [Stmt.eval] + simp only [heval, caught_exprResult, guards_eval] + by_cases hg : gs.any (fun g => g.eval ρ != 0) = true + · simp only [hg, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hg, Bool.false_eq_true, ↓reduceIte, bind_done_ok, Value.expectWord, + norm_lt (v.eval_lt ρ), Br.eval, wordTruthy] + by_cases hv : v.eval ρ = 0 + · obtain ⟨r, hr, hl⟩ := ih e S be hbe rt hrel + refine ⟨r, ?_, by simpa [hv] using hl⟩ + simp [hv, hr] + · obtain ⟨r, hr, hl⟩ := ih t S bt hbt rt hrel + refine ⟨r, ?_, by simpa [hv] using hl⟩ + simp [hv, hr] + case exprStmt ex => + cases ex + case assignment op? cleanup? target rhs => + cases target + case storageRead m x idx => + cases m + case element => + rcases idx with _ | ⟨i, _ | ⟨_, _⟩⟩ <;> rcases op? with _ | op <;> + rcases cleanup? with _ | c + all_goals first | (simp [eraseStmt] at h; done) | skip + cases c <;> (try (simp [eraseStmt] at h; done)) + simp only [eraseStmt, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h + obtain ⟨k, hk, ⟨gs, v⟩, hv, ⟨gi, key⟩, hi, o, ho, cg, hcg, rfl⟩ := h + exact eval_mapAssign ρ E ctx rt S hrel n hk hv hi ho hcg + all_goals cases idx <;> simp only [eraseStmt] at h + all_goals first | (simp at h; done) | skip + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨⟨k, off, bytes⟩, hk, ⟨gs, v⟩, hv, h⟩ := h + obtain ⟨f, hfx, rfl, rfl, rfl⟩ := fieldOf?_spec hrel.fields hk + have heval := eval_erase ρ E.fields ctx rt S hrel.expr rhs gs v + ((Expr.storageRead .header x []).orderFuel + rhs.orderFuel + 1) hv (by omega) + have hres : Expr.resolveLValueFuel ((Expr.storageRead .header x []).orderFuel + + rhs.orderFuel + 1) ctx rt (.storageRead .header x []) = + .done (.ok (.storageField x, rt)) := by + simp [Expr.orderFuel, Expr.listEvalFuel, Expr.resolveLValueFuel] + rfl + rw [Stmt.eval] + simp only [Expr.eval, Expr.orderFuel] at heval hres ⊢ + generalize Expr.listEvalFuel [] + 1 + rhs.orderFuel + 1 = F at heval hres ⊢ + rw [Expr.evalFuel] + simp only [heval, bind_exprResult, hres, bind_done_ok] + have hw := v.eval_lt ρ + have hsl : rt.state.loadSlot f.slot = (S.writes.read (.lit f.slot)).eval ρ := + slot_read hrel.expr hfx.slot + have hslw : rt.state.loadSlot f.slot < wordSize := hsl ▸ WExpr.eval_lt _ _ + have hst : ∀ w : WExpr, ResolvedLValue.write ctx rt (.storageField x) (.word (w.eval ρ)) = + .ok { rt with state := (rt.state.storeSlot f.slot + ((writeField (S.writes.read (.lit f.slot)) w f.packedOffset f.packedBytes).eval ρ)) } := by + intro w + simp only [ResolvedLValue.write, store_field hfx hslw _ (w.eval_lt ρ), + writeField_eval ρ _ _ hfx.fits hfx.bytes, hsl] + cases op? <;> cases cleanup? <;> simp only [Option.some.injEq, reduceCtorEq] at h + case none.none => + subst h + rw [guards_eval] + by_cases hg : gs.any (fun g => g.eval ρ != 0) = true + · simp only [hg, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hg, Bool.false_eq_true, ↓reduceIte, hst v] + exact ⟨_, rfl, hrel.writeField hfx v⟩ + case some.some op c => + cases c <;> simp only [reduceCtorEq] at h + rename_i b + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨o, ho, cg, hcg, h⟩ := h + simp only [Option.some.injEq] at h + subst h + obtain ⟨hb0, hb, hcgv⟩ := cleanupGuard_spec ρ hcg + have hread : ResolvedLValue.read ctx rt (.storageField x) = + .ok (.word ((readField (S.writes.read (.lit f.slot)) f.packedOffset f.packedBytes).eval ρ)) := by + simp [ResolvedLValue.read, ResolvedLValue.readRaw, load_field hfx hslw, hsl, + Runtime.derefMemoryValue, bind, Except.bind, readField_eval ρ _ hfx.fits hfx.bytes] + have hcl : ∀ w : WExpr, ValueCleanup.apply true (.uint b) (.word (w.eval ρ)) = + if w.eval ρ < 2 ^ b then .ok (.word (w.eval ρ)) else .error (.panic 0x11) := + fun w => uintCleanup_lt _ _ (w.eval_lt ρ) hb0 hb + rw [guards_eval] + simp only [any_append, hread, hrel.checked, liftM, monadLift, MonadLift.monadLift, + SolI.ofExcept, bind_done_ok, apply_erased ρ ho, hcgv] + by_cases hg : gs.any (fun g => g.eval ρ != 0) = true + · simp only [hg, Bool.true_or, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [hg, Bool.false_or, Bool.false_eq_true, ↓reduceIte] + by_cases ho' : (overflow o (readField (S.writes.read (.lit f.slot)) f.packedOffset f.packedBytes) + v).toList.any (fun g => g.eval ρ != 0) = true + · simp only [ho', Bool.true_or, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + · simp only [ho', Bool.false_or, Bool.false_eq_true, ↓reduceIte, bind_done_ok] + have hcl' := hcl (.bin o (readField (S.writes.read (.lit f.slot)) f.packedOffset f.packedBytes) v) + cases op + all_goals first | (simp [binOf] at ho; done) | skip + all_goals + dsimp only + rw [hcl'] + by_cases hc : (WExpr.bin o (readField (S.writes.read (.lit f.slot)) f.packedOffset f.packedBytes) + v).eval ρ < 2 ^ b + · simp only [hc, decide_true, Bool.not_true, Bool.false_eq_true, ↓reduceIte, + bind_done_ok, hst] + exact ⟨_, rfl, hrel.writeField hfx _⟩ + · simp only [hc, decide_false, Bool.not_false, ↓reduceIte] + exact ⟨.reverted rt (.panic 0x11), rfl, rfl⟩ + all_goals simp [eraseStmt] at h + all_goals simp [eraseStmt] at h + all_goals simp [eraseStmt] at h + case unchecked body => + simp only [eraseStmt] at h + split at h + case isFalse => simp at h + rename_i hn + obtain ⟨k, rfl⟩ : ∃ k, n = k + 2 := ⟨n - 2, by omega⟩ + obtain ⟨r, hr, hl⟩ := eval_unchecked ρ E ctx k body S b h rt hrel + exact ⟨r, by rw [Stmt.eval]; exact hr, hl⟩ + all_goals simp [eraseStmt] at h + + +end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Generic/Stage.lean b/SolidCore/Refinement/Generic/Stage.lean new file mode 100644 index 00000000..6fc119f4 --- /dev/null +++ b/SolidCore/Refinement/Generic/Stage.lean @@ -0,0 +1,298 @@ +import SolidCore.Refinement.Generic.SourceRun +import SolidCore.Refinement.Generic.MirRun +import SolidCore.Refinement.Generic.Simp +import SolidCore.Refinement.Compose +import SolidCore.Refinement.Evm.Calldata + +/-! +# The generic source stage: SolidCore to solar's first lowered MIR + +`stageAt` is one theorem for every contract of the fragment: given SolidCore's checked contract +`c`, whose constructor leaves the storage entries `s` and no logs, and a lowered MIR module `m` +(solar's module after `lower-evm-shaped`, so with lower-abi's decoding and lower-dispatch's +dispatcher), if the kernel's evaluation of `check fuel mirFuel c.core m fns` is `true`, then + + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c m + (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) + +under every oracle `o`: on every call of a function of `fns` on any argument words below +`2 ^ 256`, with no value, from any storage that writes every slot the constructor wrote, `m` +shows what SolidCore shows, its logs included. `stageDeployed` is the case of the deployed +storage itself, and `stage` the case of a constructor that leaves no storage, from any storage. + +The symbolic run of `m` reads the oracle's caller and Keccak-256 only with the environment flags +(`EnvFlags`; `check ... .all`), which a module that reads `msg.sender` or a mapping needs. +`stageAtEnv`, `stageDeployedEnv` and `stageEnv` are the same stages for that check, under every +oracle that `SourceEnvOk` describes: its caller is SolidCore's `callerAddress` (`CallerOk`), and +its Keccak-256 of the 64 bytes of two words is SolidCore's slot hash `solHash` of them +(`HashOk`). `stageAtCaller` and `stageCaller` are the stages for `check ... .callerOnly`, for a +module that reads the caller and hashes nothing, under every oracle with SolidCore's caller. +Nothing else of the oracle is assumed. + +The fragment is what `eraseFn` and `symTree` accept: parameters that are unsigned words of +`0 < b ≤ 256` bits or addresses (a dirty argument word reverts), `uint256`, `address` and `bool` +returns, checked `+`, `-`, `*` with narrow cleanups, truncating casts such as `uint256(a)`, +bitwise `&`, `|`, `^`, comparisons and `!`, scoped locals, `msg.sender`, unsigned storage fields +alone in their slot or packed with others and mappings to `uint256` (reads, writes and compound +assignments such as `v += x` and `w ^= x`), `address` fields (reads), mappings to `bool` and +nested mappings `m[k1][k2]` to `uint256` (reads and writes), `if` and `else if`, blocks, +returns, `require(c)`, `require(c, msg)`, `revert(msg)` and reverts with `Panic`, logs with +indexed `address` topics, and the other statements `eraseStmt` erases, dispatched by selector +with static call data. `check` asks, for each function of `fns`, that its selector fits in four +bytes, that SolidCore dispatches it to a function with that many parameters, and that the two trees +agree: the erasure of the SolidCore function in the contract's `envOf` and the symbolic run of +the MIR module on its selector, compared by `Tree.beq` (equality) on their canonical forms +(`Tree.canon`). + +The proof joins the two halves: `source_run` (SolidCore runs the call as the erased tree, with +the call's argument words, storage and `solHash`) and `symTree_sound` (the module runs the call as +its symbolic tree), with `callFacts` giving the symbolic run's facts about the call data, and +`Tree.eval_canon` the agreement of the trees. + +`calldataWord_eq` and its two helpers are Solar.W1's, restated here so that the generic stage +does not depend on a milestone's artifacts. +-/ + +namespace SolidCore.Refinement.Generic +open EthLib.Base EthLib.Execution EthLib.Execution.Evm +open SolarTV SolarTV.Machine SolarTV.MIR.Lowered SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm + +/-! ## The call data the symbolic run reads -/ + +theorem shl_or_ofNat (acc b : Nat) (hb : b < 256) : + (BitVec.ofNat 256 acc <<< 8) ||| BitVec.ofNat 256 b = BitVec.ofNat 256 (acc * 256 + b) := by + have hand : (BitVec.ofNat 256 acc <<< 8) &&& BitVec.ofNat 256 b = 0 := by + ext i hi + rw [BitVec.getElem_and, BitVec.getElem_shiftLeft, ← BitVec.getLsbD_eq_getElem, + ← BitVec.getLsbD_eq_getElem, BitVec.getLsbD_ofNat] + by_cases h8 : i < 8 + · simp [h8] + · have : b.testBit i = false := + Nat.testBit_lt_two_pow (Nat.lt_of_lt_of_le hb + (by simpa using Nat.pow_le_pow_right (by decide : 0 < 2) (Nat.le_of_not_lt h8))) + simp [BitVec.getLsbD_ofNat, this] + rw [← BitVec.add_eq_or_of_and_eq_zero _ _ hand] + apply BitVec.eq_of_toNat_eq + simp only [BitVec.toNat_add, BitVec.toNat_shiftLeft, BitVec.toNat_ofNat, Nat.shiftLeft_eq] + omega + +theorem foldl_word (data : ByteArray) (off : Nat) : ∀ (l : List Nat) (acc : Nat), + l.foldl (fun (acc : BitVec 256) i => + (acc <<< 8) ||| BitVec.ofNat 256 (data.data.getD (off + i) 0).toNat) + (BitVec.ofNat 256 acc) = + BitVec.ofNat 256 (l.foldl (fun acc i => acc * 256 + (byteAt data (off + i)).toNat) acc) + | [], _ => rfl + | i :: l, acc => by + simp only [List.foldl_cons] + have hget : (data.data.getD (off + i) 0) = byteAt data (off + i) := rfl + rw [hget, shl_or_ofNat _ _ (byteAt data (off + i)).toNat_lt, foldl_word data off l] + +/-- CALLDATALOAD in SolarTV is EthLib's: the big-endian word of 32 bytes of call data from the +offset, zero past its end. -/ +theorem calldataWord_eq (call : Call) (off : BitVec 256) : + calldataWord call off = loadWord call.calldata off.toNat 32 := by + unfold calldataWord loadWord bufferRead bytesToNat + rw [show (0 : BitVec 256) = BitVec.ofNat 256 0 from rfl, foldl_word, List.foldl_map] + +/-- The call of selector `sel` on the argument words `args` from the storage `σ` gives the +symbolic run its facts, with the argument words, the storage and SolidCore's slot hash +`⟨args, slotValue σ, solHash, callerWord⟩`. -/ +theorem callFacts (sel : Nat) (hsel : sel < 2 ^ 32) (args : List Nat) + (hargs : ∀ a ∈ args, a < 2 ^ 256) (σ : List (Nat × Nat)) : + CallFacts sel args.length ⟨args, slotValue σ, solHash, callerWord⟩ + { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } := by + have hcd := calldata_eq_cdOf sel args hargs + refine ⟨rfl, ?_, ?_, ?_, rfl, slotValue_store σ⟩ + · show (Abi.calldata sel args).size = _ + rw [hcd, size_cdOf, size_selectorOf] + simp + · intro i hi hw + rw [calldataWord_eq] + show (loadWord (Abi.calldata sel args) _ 32).toNat = _ + rw [hcd, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hw] + rw [loadWord_cdOf_getD _ _ _ (by simp [size_selectorOf]) (by simp [size_selectorOf]) + (by simp [size_selectorOf]; omega)] + simp only [size_selectorOf, show 4 + 32 * i - 4 = 32 * i by omega, + show 32 * i / 32 = i by omega, WExpr.eval] + rw [List.getD_eq_getElem?_getD, List.getElem?_map, List.getElem?_eq_getElem hi] + simp [List.getD_eq_getElem?_getD, List.getElem?_eq_getElem hi] + · rw [calldataWord_eq] + show EvmRules.Evm.shr 224 (loadWord (Abi.calldata sel args) _ 32) = _ + rw [hcd] + have := shr_cdOf_selectorOf sel (args.map (BitVec.ofNat 256)) hsel + simpa [EvmRules.Evm.shr, bitwiseShr] using this + +/-! ## The oracle's environment -/ + +/-- The oracle's caller is SolidCore's `callerAddress`, `callerWord`. -/ +def CallerOk (o : Oracle) : Prop := (o.caller.setWidth 256).toNat = callerWord + +/-- The oracle's Keccak-256 of the 64 bytes of two words is SolidCore's slot hash of them, the +hash of the same bytes. -/ +def HashOk (o : Oracle) : Prop := + ∀ a b, a < 2 ^ 256 → b < 2 ^ 256 → (o.keccak (wordBytes a ++ wordBytes b)).toNat = solHash a b % 2 ^ 256 + +/-- What the stages with the environment flag ask of the oracle: `CallerOk` and `HashOk`. -/ +structure SourceEnvOk (o : Oracle) : Prop where + caller : CallerOk o + hash : HashOk o + +/-- An oracle `SourceEnvOk` describes is one the symbolic run with the environment flag takes, for +every call whose hash is `solHash`. -/ +theorem SourceEnvOk.envOk {o : Oracle} (h : SourceEnvOk o) (args : List Nat) (store : Nat → Nat) : + EnvOk o ⟨args, store, solHash, callerWord⟩ := + ⟨h.caller, h.hash⟩ + +/-- What the flags `env` ask of the oracle: SolidCore's caller when they read the caller, and +SolidCore's hash of two words when they hash. -/ +structure SourceAsk (env : EnvFlags) (o : Oracle) : Prop where + caller : env.caller = true → CallerOk o + hash : env.hash = true → HashOk o + +/-- The flags off ask nothing. -/ +theorem SourceAsk.off {o : Oracle} : SourceAsk .off o := + ⟨fun h => by simp [EnvFlags.off] at h, fun h => by simp [EnvFlags.off] at h⟩ + +/-- An oracle `SourceEnvOk` describes gives every flag what it asks. -/ +theorem SourceEnvOk.ask {o : Oracle} (h : SourceEnvOk o) {env : EnvFlags} : SourceAsk env o := + ⟨fun _ => h.caller, fun _ => h.hash⟩ + +/-- An oracle with SolidCore's caller gives the caller-only flags what they ask. -/ +theorem CallerOk.ask {o : Oracle} (h : CallerOk o) : SourceAsk .callerOnly o := + ⟨fun _ => h, fun h => by simp [EnvFlags.callerOnly] at h⟩ + +/-- What the flags ask of the oracle, for the symbolic run on a call whose hash is `solHash`. -/ +theorem SourceAsk.envAsk {env : EnvFlags} {o : Oracle} (h : SourceAsk env o) (args : List Nat) + (store : Nat → Nat) : EnvAsk env o ⟨args, store, solHash, callerWord⟩ := + ⟨fun hc => by + have := h.caller hc + unfold CallerOk at this + unfold EnvFlags.callerExpr; split <;> simp [WExpr.eval, this, callerWord] <;> rfl, h.hash⟩ + +/-! ## The check and the stage -/ + +/-- Whether the function of `fns` with selector `f.sel` lowers to `m`: SolidCore dispatches the +selector to a function with `f`'s parameter count, and its erased tree and the symbolic run of +`m` on the selector, with `mirFuel` blocks along each path and the environment flag `env`, agree in +canonical form (`Tree.beq`). -/ +def checkFn (fuel mirFuel : Nat) (core : Contract) (m : Module) (env : EnvFlags) (f : Fn) : Bool := + decide (f.sel < 2 ^ 32) && + match core.findFunctionBySelector? f.sel with + | none => false + | some fn => + decide (fn.params.length = f.params.length) && + match eraseFn (envOf core) fuel fn, symTree m f.sel f.params.length mirFuel env with + | some t1, some t2 => t1.canon.beq t2.canon + | _, _ => false + +/-- Whether every function of `fns` lowers to `m`, with the environment flag `env` (off by +default). -/ +def check (fuel mirFuel : Nat) (core : Contract) (m : Module) (fns : List Fn) (env : EnvFlags := .off) : + Bool := + fns.all (checkFn fuel mirFuel core m env) + +/-- The generic source stage for `check` with the environment flag `env`, under every oracle when +the flag is off and every oracle `SourceEnvOk` describes when it is on. -/ +theorem stageAtWith (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} + {d : Source.State} {s : List (Nat × Nat)} (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) + {m : Module} {fns : List Fn} {env : EnvFlags} (henv : SourceAsk env o) + (hchk : check fuel mirFuel c.core m fns env = true) : + Stage (solidCore fuel) (moduleSem o) c m (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) := by + rintro _ ⟨σ, hcov, f, hf, args, hlen, hargs, rfl⟩ obs hrun + have hcf := List.all_eq_true.mp hchk f hf + unfold checkFn at hcf + cases hfind : c.core.findFunctionBySelector? f.sel with + | none => simp [hfind] at hcf + | some fn => + cases ht1 : eraseFn (envOf c.core) fuel fn with + | none => simp [hfind, ht1] at hcf + | some t1 => + cases ht2 : symTree m f.sel f.params.length mirFuel env with + | none => simp [hfind, ht1, ht2] at hcf + | some t2 => + simp only [hfind, ht1, ht2, Bool.and_eq_true, decide_eq_true_eq] at hcf + obtain ⟨hsel, hpl, hcf⟩ := hcf + have hcf := Tree.eq_of_beq hcf + have hsrc := source_run hd hcov hsel hfind ht1 args (by rw [hlen, hpl]) hargs + change Source.run fuel c _ = some obs at hrun + rw [hsrc] at hrun + cases hrun + rw [← hlen] at ht2 + rw [symTree_sound (callFacts f.sel hsel args hargs σ) o m (henv.envAsk _ _) ht2, + ← Tree.eval_canon, ← hcf, Tree.eval_canon] + +/-- **The generic source stage**: a checked contract whose constructor leaves the storage entries +`s` and no logs and a lowered MIR module that `check` accepts give the stage from SolidCore to the +module's lowered MIR semantics, under every oracle, on every call of a function of `fns` on any +argument words below `2 ^ 256`, with no value, from any storage that writes every slot of `s`. -/ +theorem stageAt (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} + {fns : List Fn} (hchk : check fuel mirFuel c.core m fns = true) : + Stage (solidCore fuel) (moduleSem o) c m (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) := + stageAtWith o hd (env := .off) SourceAsk.off hchk + +/-- The generic source stage from the deployed storage `s`. -/ +theorem stageDeployed (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} + {d : Source.State} {s : List (Nat × Nat)} (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) + {m : Module} {fns : List Fn} (hchk : check fuel mirFuel c.core m fns = true) : + Stage (solidCore fuel) (moduleSem o) c m (fullScope fns s) := + SolarTV.Stage.mono (stageAt o hd hchk) fun _ h => ⟨s, fun kv hkv => ⟨kv, hkv, rfl⟩, h⟩ + +/-- The generic source stage for a contract whose constructor leaves no storage, from any +storage. -/ +theorem stage (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d []) {m : Module} {fns : List Fn} + (hchk : check fuel mirFuel c.core m fns = true) : + Stage (solidCore fuel) (moduleSem o) c m (fun call => ∃ σ, fullScope fns σ call) := + SolarTV.Stage.mono (stageAt o hd hchk) fun _ ⟨σ, h⟩ => + ⟨σ, fun _ hkv => absurd hkv List.not_mem_nil, h⟩ + +/-- **The generic source stage with the environment flag**: `stageAt` for a module that +`check ... true` accepts, which may read the caller and hash two words, under every oracle whose +caller is `callerWord` and whose Keccak-256 of two words is `solHash` (`SourceEnvOk`). -/ +theorem stageAtEnv (o : Oracle) (henv : SourceEnvOk o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} {s : List (Nat × Nat)} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} {fns : List Fn} + (hchk : check fuel mirFuel c.core m fns .all = true) : + Stage (solidCore fuel) (moduleSem o) c m (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) := + stageAtWith o hd henv.ask hchk + +/-- The generic source stage with the environment flag from the deployed storage `s`. -/ +theorem stageDeployedEnv (o : Oracle) (henv : SourceEnvOk o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} {s : List (Nat × Nat)} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} {fns : List Fn} + (hchk : check fuel mirFuel c.core m fns .all = true) : + Stage (solidCore fuel) (moduleSem o) c m (fullScope fns s) := + SolarTV.Stage.mono (stageAtEnv o henv hd hchk) fun _ h => ⟨s, fun kv hkv => ⟨kv, hkv, rfl⟩, h⟩ + +/-- The generic source stage with the environment flag for a contract whose constructor leaves no +storage, from any storage. -/ +theorem stageEnv (o : Oracle) (henv : SourceEnvOk o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d []) {m : Module} {fns : List Fn} + (hchk : check fuel mirFuel c.core m fns .all = true) : + Stage (solidCore fuel) (moduleSem o) c m (fun call => ∃ σ, fullScope fns σ call) := + SolarTV.Stage.mono (stageAtEnv o henv hd hchk) fun _ ⟨σ, h⟩ => + ⟨σ, fun _ hkv => absurd hkv List.not_mem_nil, h⟩ + +/-- The generic source stage with the caller-only flags (a contract that reads `msg.sender` but +hashes nothing), from any storage that writes every slot of `s`, under every oracle with +SolidCore's caller. -/ +theorem stageAtCaller (o : Oracle) (henv : CallerOk o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} {s : List (Nat × Nat)} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} {fns : List Fn} + (hchk : check fuel mirFuel c.core m fns .callerOnly = true) : + Stage (solidCore fuel) (moduleSem o) c m (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) := + stageAtWith o hd henv.ask hchk + +/-- The caller-only stage for a contract whose constructor leaves no storage, from any storage. -/ +theorem stageCaller (o : Oracle) (henv : CallerOk o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d []) {m : Module} {fns : List Fn} + (hchk : check fuel mirFuel c.core m fns .callerOnly = true) : + Stage (solidCore fuel) (moduleSem o) c m (fun call => ∃ σ, fullScope fns σ call) := + SolarTV.Stage.mono (stageAtCaller o henv hd hchk) fun _ ⟨σ, h⟩ => + ⟨σ, fun _ hkv => absurd hkv List.not_mem_nil, h⟩ + +end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Generic/StageFrom.lean b/SolidCore/Refinement/Generic/StageFrom.lean new file mode 100644 index 00000000..9c418f49 --- /dev/null +++ b/SolidCore/Refinement/Generic/StageFrom.lean @@ -0,0 +1,434 @@ +import SolidCore.Refinement.Generic.Stage + +/-! +# The generic source stage for every caller + +`Stage.lean`'s stages fix the caller: SolidCore's `Source.run` calls from `callerAddress` and the check +erases `msg.sender` to the constant `callerWord`. This module proves the stage once for every caller, +with the caller a symbolic word on both sides: + +* `Source.runFrom a` is SolidCore's run of a call sent by the account `a` (the contract deployed, as in + `Source.run`, by `callerAddress`); `Source.runFrom callerAddress` is `Source.run` (`runFrom_callerAddress`). + `solidCoreFrom a` is its `Sem`. +* `eraseFnSym` erases a function with `msg.sender` as the symbolic word `WExpr.caller` (whose value is + `Val.caller`), knowing that it fits in 160 bits (`callerFact`); the MIR side reads `caller` as the same + word under `EnvFlags.allSym`. +* `checkSym` compares the two trees, once, for the symbolic caller; `stageFrom` gives, for every + address `a < 2 ^ 160` and every oracle whose caller is `a` and whose Keccak-256 of two words is + SolidCore's (`FromOk a o`), the stage from `solidCoreFrom a` to the module. +-/ + +namespace SolidCore.Refinement + +namespace Source + +open SolidCore.Solidity SolidCore.Solidity.Source + +/-- SolidCore's result for `call` sent by `caller`: the contract constructed by `callerAddress` as in +`result?`, its storage replaced with the call's, and called through the ABI dispatcher from `caller`. -/ +def resultFrom? (caller : Nat) (fuel : Nat) (contract : TypeCheck.CheckedContract) (call : Call) : + Option TypeCheck.CoreAbiCallResult := + let base := contract.core.context + let context := + { base with sender := callerAddress, self := selfAddress, value := call.callvalue } + match TypeCheck.CheckedContract.constructWithContext? fuel contract context + State.empty selfAddress 0 [] with + | some (CallResult.returned deployed _) => + let storage := call.storage.foldl + (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) deployed.storage + TypeCheck.CheckedContract.callCalldataAtFromWithContext? fuel contract context + { deployed with storage := storage } selfAddress caller call.callvalue + (call.calldata.data.toList.map (·.toNat)) + | _ => none + +/-- Run `call`, sent by `caller`, against `contract` in SolidCore with `fuel`. -/ +def runFrom (caller : Nat) (fuel : Nat) (contract : TypeCheck.CheckedContract) (call : Call) : + Option Observable := + (resultFrom? caller fuel contract call).map (observe call) + +/-- From `callerAddress`, `runFrom` is `run`. -/ +theorem runFrom_callerAddress (fuel : Nat) (contract : TypeCheck.CheckedContract) (call : Call) : + runFrom callerAddress fuel contract call = run fuel contract call := rfl + +end Source + +/-- SolidCore with fixed fuel, on calls sent by `caller`. -/ +def solidCoreFrom (caller fuel : Nat) : Sem := + { Prog := SolidCore.Solidity.TypeCheck.CheckedContract, run := Source.runFrom caller fuel } + +/-- From `callerAddress`, `solidCoreFrom` is `solidCore`. -/ +theorem solidCoreFrom_callerAddress (fuel : Nat) : solidCoreFrom callerAddress fuel = solidCore fuel := rfl + +namespace Generic + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm +open SolarTV SolarTV.Machine SolarTV.MIR.Lowered SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm + +/-! ## The erasure with a symbolic caller -/ + +/-- What the erasure knows of the symbolic caller: it fits in 160 bits. -/ +def callerFact : WExpr × Bool := (.bin .gt .caller (.lit (2 ^ 160 - 1)), false) + +theorem callerFact_eval (ρ : Val) (h : ρ.caller < 2 ^ 160) : + (callerFact.1.eval ρ = 0 ↔ callerFact.2 = false) := by + have h1 : ρ.caller < wordSize := Nat.lt_of_lt_of_le h (by decide) + have h2 : (2 ^ 160 - 1 : Nat) < wordSize := by decide + simp only [callerFact, WExpr.eval, BinOp.eval, Nat.mod_eq_of_lt h1, Nat.mod_eq_of_lt h2, iff_true] + rw [if_neg (by omega)] + rfl + +/-- The state a call of `fn` starts in, with `msg.sender` the symbolic caller. -/ +def initFrom (fn : FunctionDef) : SymState := { initState fn with caller := .caller } + +/-- `eraseFn` with `msg.sender` the symbolic caller `WExpr.caller`, which the facts bound by +`2 ^ 160 - 1`. -/ +def eraseFnSym (E : EraseEnv) (fuel : Nat) (fn : FunctionDef) : Option Tree := + match widthsOf fn.params fn.paramAbiCleanups with + | none => none + | some ws => + if fn.returns.all wordBinding then do + let b ← eraseStmt { E with facts := callerFact :: argFacts ws 0 } fuel fn.body (initFrom fn) + let t ← brTree fn (callerFact :: argFacts ws 0) b + some (paramGuards ws 0 t) + else none + +/-! ## SolidCore's run from any caller as the erased tree -/ + +theorem run_eq_at_from (a : Nat) {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) (sel : Nat) (ws : List U256) + (σ : List (Nat × Nat)) : + Source.runFrom a fuel c (SolidCore.Refinement.Evm.Wide.callAt sel ws σ) = + Option.map (Source.observe (SolidCore.Refinement.Evm.Wide.callAt sel ws σ)) + (ABI.Contract.callCalldataAtFromWithContext? fuel c.core (Wide.ctxOf c) + { d with storage := σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage } + selfAddress a 0 + ((natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes (ws.map (·.toNat)))) := by + obtain ⟨vs, hc⟩ := hd.cons + simp only [Source.runFrom, Source.resultFrom?, show (SolidCore.Refinement.Evm.Wide.callAt sel ws σ).callvalue = 0 from rfl, + show (SolidCore.Refinement.Evm.Wide.callAt sel ws σ).storage = σ from rfl, + show (SolidCore.Refinement.Evm.Wide.callAt sel ws σ).calldata = Abi.calldata sel (ws.map (·.toNat)) from rfl] + rw [show ({ c.core.context with sender := callerAddress, self := selfAddress, value := 0 } : + Source.Context) = Wide.ctxOf c from rfl, hc] + simp only [TypeCheck.CheckedContract.callCalldataAtFromWithContext?, Dirty.bytes_calldata] + + +theorem run_rejected_from (a : Nat) {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {sel : Nat} (hsel : sel < 2 ^ 32) + {fn : FunctionDef} (hfind : c.core.findFunctionBySelector? sel = some fn) (args : List Nat) + (hdec : ABI.decodeFunctionArgs? fn (Dirty.argBytes args) = .error .empty) + (σ : List (Nat × Nat)) : + Source.runFrom a fuel c { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } = + some (Abi.rejected σ) := by + obtain ⟨s0, hdep⟩ := deployedStorage_of hd + unfold Abi.deployedStorage at hdep + dsimp only at hdep + split at hdep + case h_2 => simp at hdep + rename_i deployed st hcons + simp only [Source.runFrom, Source.resultFrom?, hcons, + TypeCheck.CheckedContract.callCalldataAtFromWithContext?, + ABI.Contract.callCalldataAtFromWithContext?, Dirty.bytes_calldata, + Dirty.readSelector_calldata _ hsel, hfind] + rw [show ((EthLib.Base.natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes args).drop + ABI.selectorBytes = Dirty.argBytes args by + simp [ABI.selectorBytes, EthLib.Base.natToBytes_length], hdec] + simp only [ABI.Contract.revertedCall?, ABI.Contract.encodeRevertData?, bind, Option.bind, + Option.map_some, Source.observe, Abi.rejected] + simp + + +theorem source_run_clean_from (a : Nat) (ha : a < 2 ^ 160) {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {σ : List (Nat × Nat)} + (hcov : Covers s σ) {sel : Nat} (hsel : sel < 2 ^ 32) {fn : FunctionDef} + (hfind : c.core.findFunctionBySelector? sel = some fn) {ws : List Nat} + (hw : widthsOf fn.params fn.paramAbiCleanups = some ws) + (hret : fn.returns.all wordBinding = true) {b : Br} + (hb : eraseStmt { envOf c.core with facts := callerFact :: argFacts ws 0 } fuel fn.body (initFrom fn) = some b) + {T : Tree} (hT : brTree fn (callerFact :: argFacts ws 0) b = some T) (args : List Nat) + (hlen : args.length = fn.params.length) (hargs : ∀ a ∈ args, a < 2 ^ 256) + (hclean : argsClean ws args = true) + (hdec : ABI.decodeFunctionArgs? fn (Dirty.argBytes args) = .ok (args.map .word)) : + Source.runFrom a fuel c { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } = + some (T.eval ⟨args, slotValue σ, solHash, a⟩).obs := by + rw [SolidCore.Refinement.Wide.callAt_of_args sel args hargs σ, + run_eq_at_from a hd, SolidCore.Refinement.Wide.map_ofNat_toNat args hargs] + have hdrop : ((EthLib.Base.natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes args).drop + ABI.selectorBytes = Dirty.argBytes args := by + simp [ABI.selectorBytes, EthLib.Base.natToBytes_length] + simp only [ABI.Contract.callCalldataAtFromWithContext?, Dirty.readSelector_calldata _ hsel, hfind, + hdrop, hdec] + have hp := (widthsOf_spec hw).2.2.1 + have hr : ∀ r ∈ fn.returns, RetTy r.ty ∧ r.isStorageRef = false := + fun r hr => wordBinding_ty (List.all_eq_true.mp hret r hr) + generalize hctx : ABI.Contract.callContextAtWithBase c.core (Wide.ctxOf c) selfAddress a 0 + ((EthLib.Base.natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes args) = ctx + generalize hst : ({ d with storage := σ.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) d.storage } : + Source.State) = st0 + have hacc : fn.acceptsValue 0 = true := by + simp [FunctionDef.acceptsValue, wordEq] + have hctxv : ctx.value = 0 := by + subst hctx; simp [ABI.Contract.callContextAtWithBase, SolidCore.Solidity.Shared.norm] + set ρ : Val := ⟨args, slotValue σ, solHash, a⟩ with hρ + have hρok : ρ.Ok := slotValue_store σ + set K : Facts := callerFact :: argFacts ws 0 with hK + have hKρ : K.Hold ρ := (argFacts_hold ρ hargs ws 0 (by simpa [hρ] using hclean)).cons (callerFact_eval ρ ha) + set E : EraseEnv := { envOf c.core with facts := K } with hE + have hframe : fn.initialFrame? (args.map .word) = + some (frameOf ρ (paramLocals fn.params 0 ++ fn.returns.map fun r => (r.name, .lit 0))) := by + have h0 : BindingDecl.bindArgs? fn.params (args.map .word) = + some (frameOf ρ (paramLocals fn.params 0)) := + bindArgs_words ρ hargs fn.params 0 hp (by simp [hρ, hlen]) + simp only [FunctionDef.initialFrame?, h0, FunctionDef.returnDefaultBindings, + defaults_words ρ fn.returns hr, frameOf, List.map_append] + have hrel : StmtRel ρ E ctx + { state := { st0 with + selfBalance := SolidCore.Solidity.Shared.addWord + (SolidCore.Solidity.Shared.Account.balanceAt ctx.accountBalances ctx.self) ctx.value + worldMutatedSinceAdoption := true }, + locals := [frameOf ρ (paramLocals fn.params 0 ++ fn.returns.map fun r => (r.name, .lit 0))] } + (initFrom fn) := + { fields := by subst hctx; rfl + events := by subst hctx; rfl + checked := by subst hctx; rfl + sender := by subst hctx; rfl + hash := rfl + ok := hρok + frames := rfl + store := by + intro k hk + have := getD_storage_cover hd hcov k + subst hst + simp only [State.loadSlot, StorageMap.lookup?, initFrom, initState, Writes.store, hρ] + rw [← this] + simp only [SolidCore.Solidity.Shared.norm, modulus_eq, Std.HashMap.get?_eq_getElem?] + cases (List.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) d.storage σ)[k % wordSize]? <;> rfl + logs := by subst hst; simp [hd.events, initFrom, initState] + facts := hKρ } + obtain ⟨r, hrun, hleaf⟩ := eval_stmt ρ E ctx fuel fn.body (initFrom fn) b hb _ hrel + have hcall : fn.call? fuel c.core.table ctx st0 (args.map .word) = + some (fn.callBodyResult st0 r) := by + have hacc' : fn.acceptsValue ctx.value = true := hctxv ▸ hacc + simp only [FunctionDef.call?, FunctionDef.call, FunctionDef.evalBodyEntry, hacc', hframe, + if_true, Option.map_some, Option.bind_some] + rw [show c.core.table = E.tbl from rfl, hrun] + rfl + obtain ⟨T', hT', hTe⟩ := brTree_eval fn K ρ b T hT + rw [hacc, if_pos rfl, hcall, ← hTe] + generalize b.eval ρ = l at hT' hleaf + cases l with + | normal S => + cases r <;> simp only [LeafRel] at hleaf + rename_i rt + simp only [leafTree, Option.bind_eq_bind, Option.bind_eq_some_iff] at hT' + obtain ⟨ws, hws, hT'⟩ := hT' + split at hT' + case isFalse => simp at hT' + rename_i hok + simp only [Option.some.injEq] at hT' + subst hT' + simp only [FunctionDef.callBodyResult, FunctionDef.collectReturns, collectReturnBindings, + collect_words ρ rt S hKρ hleaf.expr.locals fn.returns ws hok hws, untag_words, + encode_words ρ hKρ fn.returns ws hok, bind, Option.bind, Option.map_some] + simp only [Source.observe, Tree.eval, Res.obs, if_true, ↓reduceIte, logEntries_map, + hleaf.logs, Option.some.injEq, Observable.mk.injEq, true_and] + funext slot + exact loadSlot_eq _ S.writes ρ hρok hleaf.store slot + | returned S vs => + cases r <;> simp only [LeafRel] at hleaf + rename_i rt vals + obtain ⟨hst', rfl⟩ := hleaf + by_cases hv : vs = [] + · subst hv + simp only [leafTree, if_true, Option.bind_eq_bind, Option.bind_eq_some_iff] at hT' + obtain ⟨ws, hws, hT'⟩ := hT' + split at hT' + case isFalse => simp at hT' + rename_i hok + simp only [Option.some.injEq] at hT' + subst hT' + simp only [FunctionDef.callBodyResult, List.map_nil, List.isEmpty_nil, if_true, + FunctionDef.collectReturns, collectReturnBindings, + collect_words ρ rt S hKρ hst'.expr.locals fn.returns ws hok hws, untag_words, + encode_words ρ hKρ fn.returns ws hok, bind, Option.bind, Option.map_some] + simp only [Source.observe, Tree.eval, Res.obs, if_true, ↓reduceIte, logEntries_map, + hst'.logs, Option.some.injEq, Observable.mk.injEq, true_and] + funext slot + exact loadSlot_eq _ S.writes ρ hρok hst'.store slot + · simp only [leafTree, hv, if_false] at hT' + split at hT' + case isFalse => simp at hT' + rename_i hok + simp only [Option.some.injEq] at hT' + subst hT' + have hne : (vs.map fun e => Value.word (e.eval ρ)).isEmpty = false := by + cases vs with + | nil => exact absurd rfl hv + | cons _ _ => rfl + simp only [FunctionDef.callBodyResult, hne, Bool.false_eq_true, if_false, + FunctionDef.coerceReturnValues, coerceReturnBindings, + coerce_words ρ rt hKρ fn.returns vs hok, untag_words, + encode_words ρ hKρ fn.returns vs hok, bind, Option.bind, Option.map_some] + simp only [Source.observe, Tree.eval, Res.obs, if_true, ↓reduceIte, logEntries_map, + hst'.logs, Option.some.injEq, Observable.mk.injEq, true_and] + funext slot + exact loadSlot_eq _ S.writes ρ hρok hst'.store slot + | reverted p => + cases r <;> simp only [LeafRel] at hleaf + subst hleaf + cases p with + | empty => + simp only [leafTree, Option.some.injEq] at hT' + subst hT' + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, Fail.data, + ABI.Contract.encodeRevertData?, Source.observe, Tree.eval, Res.obs, hρ, + SolidCore.Refinement.Evm.Wide.callAt] + | panic c => + simp only [leafTree, Option.some.injEq] at hT' + subst hT' + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, Fail.data, encode_panic ρ, + Source.observe, Tree.eval, Res.obs, hρ, SolidCore.Refinement.Evm.Wide.callAt] + | error m => + simp only [leafTree, Option.map_eq_some_iff] at hT' + obtain ⟨bs, hbs, rfl⟩ := hT' + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, Fail.data, encode_error ρ _ hbs, + Source.observe, Tree.eval, Res.obs, hρ, SolidCore.Refinement.Evm.Wide.callAt] + + +theorem source_run_from (a : Nat) (ha : a < 2 ^ 160) {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {σ : List (Nat × Nat)} + (hcov : Covers s σ) {sel : Nat} (hsel : sel < 2 ^ 32) {fn : FunctionDef} + (hfind : c.core.findFunctionBySelector? sel = some fn) {T : Tree} + (hT : eraseFnSym (envOf c.core) fuel fn = some T) (args : List Nat) + (hlen : args.length = fn.params.length) (hargs : ∀ a ∈ args, a < 2 ^ 256) : + Source.runFrom a fuel c { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } = + some (T.eval ⟨args, slotValue σ, solHash, a⟩).obs := by + unfold eraseFnSym at hT + split at hT + · simp at hT + rename_i ws hw + split at hT + case isFalse => simp at hT + rename_i hret + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at hT + obtain ⟨b, hb, t, ht, rfl⟩ := hT + rw [paramGuards_eval ⟨args, slotValue σ, solHash, a⟩ t hargs ws 0, List.drop_zero] + have hdec := decode_args hw args hlen hargs + by_cases hclean : argsClean ws args = true + · rw [if_pos hclean] + rw [if_pos hclean] at hdec + exact source_run_clean_from a ha hd hcov hsel hfind hw hret hb ht args hlen hargs hclean hdec + · rw [if_neg hclean] + rw [if_neg hclean] at hdec + rw [run_rejected_from a hd hsel hfind args hdec σ] + rfl + + +/-! ## The check and the stage for every caller -/ + +/-- `checkFn` with the symbolic caller on both sides. -/ +def checkFnSym (fuel mirFuel : Nat) (core : Contract) (m : Module) (f : Fn) : Bool := + decide (f.sel < 2 ^ 32) && + match core.findFunctionBySelector? f.sel with + | none => false + | some fn => + decide (fn.params.length = f.params.length) && + match eraseFnSym (envOf core) fuel fn, symTree m f.sel f.params.length mirFuel .allSym with + | some t1, some t2 => t1.canon.beq t2.canon + | _, _ => false + +/-- Whether every function of `fns` lowers to `m` for the symbolic caller. -/ +def checkSym (fuel mirFuel : Nat) (core : Contract) (m : Module) (fns : List Fn) : Bool := + fns.all (checkFnSym fuel mirFuel core m) + +/-- What the stage for the caller `a` asks of the oracle: its caller is `a` and its Keccak-256 of two +words is SolidCore's slot hash (`HashOk`). -/ +structure FromOk (a : Nat) (o : Oracle) : Prop where + caller : (o.caller.setWidth 256).toNat = a + hash : HashOk o + +theorem FromOk.envAsk {a : Nat} {o : Oracle} (h : FromOk a o) (ha : a < 2 ^ 160) (args : List Nat) + (store : Nat → Nat) : EnvAsk .allSym o ⟨args, store, solHash, a⟩ := + ⟨fun _ => by + have : a < wordSize := Nat.lt_of_lt_of_le ha (by decide) + simp [EnvFlags.callerExpr, EnvFlags.allSym, WExpr.eval, h.caller, Nat.mod_eq_of_lt this], + fun _ => h.hash⟩ + +/-- The call facts do not read the caller. -/ +theorem callFactsFrom (sel : Nat) (hsel : sel < 2 ^ 32) (args : List Nat) + (hargs : ∀ a ∈ args, a < 2 ^ 256) (σ : List (Nat × Nat)) (a : Nat) : + CallFacts sel args.length ⟨args, slotValue σ, solHash, a⟩ + { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } := + have h := callFacts sel hsel args hargs σ + ⟨h.value, h.size, h.args, h.selector, h.store, h.ok⟩ + +/-- **The generic source stage for every caller**: a checked contract whose constructor leaves the +storage entries `s` and no logs and a lowered MIR module that `checkSym` accepts give, for every +address `a < 2 ^ 160` and every oracle whose caller is `a` and whose Keccak-256 of two words is +SolidCore's, the stage from SolidCore's run sent by `a` to the module's lowered MIR semantics, on +every call of a function of `fns` on any argument words below `2 ^ 256`, with no value, from any +storage that writes every slot of `s`. -/ +theorem stageFrom (a : Nat) (ha : a < 2 ^ 160) (o : Oracle) (ho : FromOk a o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} {s : List (Nat × Nat)} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} {fns : List Fn} + (hchk : checkSym fuel mirFuel c.core m fns = true) : + Stage (solidCoreFrom a fuel) (moduleSem o) c m (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) := by + rintro _ ⟨σ, hcov, f, hf, args, hlen, hargs, rfl⟩ obs hrun + have hcf := List.all_eq_true.mp hchk f hf + unfold checkFnSym at hcf + cases hfind : c.core.findFunctionBySelector? f.sel with + | none => simp [hfind] at hcf + | some fn => + cases ht1 : eraseFnSym (envOf c.core) fuel fn with + | none => simp [hfind, ht1] at hcf + | some t1 => + cases ht2 : symTree m f.sel f.params.length mirFuel .allSym with + | none => simp [hfind, ht1, ht2] at hcf + | some t2 => + simp only [hfind, ht1, ht2, Bool.and_eq_true, decide_eq_true_eq] at hcf + obtain ⟨hsel, hpl, hcf⟩ := hcf + have hcf := Tree.eq_of_beq hcf + have hsrc := source_run_from a ha hd hcov hsel hfind ht1 args (by rw [hlen, hpl]) hargs + change Source.runFrom a fuel c _ = some obs at hrun + rw [hsrc] at hrun + cases hrun + rw [← hlen] at ht2 + rw [symTree_sound (callFactsFrom f.sel hsel args hargs σ a) o m (ho.envAsk ha _ _) ht2, + ← Tree.eval_canon, ← hcf, Tree.eval_canon] + +/-- `stageFrom` from the deployed storage `s`. -/ +theorem stageDeployedFrom (a : Nat) (ha : a < 2 ^ 160) (o : Oracle) (ho : FromOk a o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} {s : List (Nat × Nat)} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} {fns : List Fn} + (hchk : checkSym fuel mirFuel c.core m fns = true) : + Stage (solidCoreFrom a fuel) (moduleSem o) c m (fullScope fns s) := + SolarTV.Stage.mono (stageFrom a ha o ho hd hchk) fun _ h => ⟨s, fun kv hkv => ⟨kv, hkv, rfl⟩, h⟩ + +/-- Every valid call has a source result from the caller `a`: the source half of `stageFrom`. -/ +theorem definedFrom (a : Nat) (ha : a < 2 ^ 160) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} {s : List (Nat × Nat)} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} {fns : List Fn} + (hchk : checkSym fuel mirFuel c.core m fns = true) : + ∀ call, (∃ σ, Covers s σ ∧ fullScope fns σ call) → ((solidCoreFrom a fuel).run c call).isSome := by + rintro _ ⟨σ, hcov, f, hf, args, hlen, hargs, rfl⟩ + have hcf := List.all_eq_true.mp hchk f hf + unfold checkFnSym at hcf + cases hfind : c.core.findFunctionBySelector? f.sel with + | none => simp [hfind] at hcf + | some fn => + cases ht1 : eraseFnSym (envOf c.core) fuel fn with + | none => simp [hfind, ht1] at hcf + | some t1 => + cases ht2 : symTree m f.sel f.params.length mirFuel .allSym with + | none => simp [hfind, ht1, ht2] at hcf + | some t2 => + simp only [hfind, ht1, ht2, Bool.and_eq_true, decide_eq_true_eq] at hcf + obtain ⟨hsel, hpl, -⟩ := hcf + have hsrc := source_run_from a ha hd hcov hsel hfind ht1 args (by rw [hlen, hpl]) hargs + change (Source.runFrom a fuel c _).isSome = true + rw [hsrc] + rfl + +end Generic + +end SolidCore.Refinement diff --git a/SolidCore/Refinement/Generic/StageIn.lean b/SolidCore/Refinement/Generic/StageIn.lean new file mode 100644 index 00000000..833e532c --- /dev/null +++ b/SolidCore/Refinement/Generic/StageIn.lean @@ -0,0 +1,412 @@ +import SolidCore.Refinement.Generic.Stage +import SolidCore.Refinement.SourceOracle + +/-! +# The generic source stage in every world + +`stageInAtWith` is the generic source stage (`Generic.stageAtWith`) with SolidCore run in a world +`W` (`solidCoreIn W`, SolidCore/Refinement/SourceOracle.lean): any call oracle and any other accounts' +code. A function the erasure accepts makes no external call, so its body's interaction tree is a +finished one (`eval_stmt` gives `.done` in every context, the other accounts' code included) and +every call oracle folds it to the same result; SolidCore then runs the call as the erased tree in +every world (`source_runIn`), and the stage holds for every world and every MIR oracle, with no +hypothesis on either (in particular no `CallsAgree`). So the call-free functions of a contract that +calls out elsewhere (a pair's `getReserves`, a token's `approve`) get their stage in the open world that +`Verify/SourceOracle.lean`'s `holds_of_runs` asks of the lowering, `stageIn_runs`. +-/ + +namespace SolidCore.Refinement.Generic +open SolarTV SolarTV.Machine SolarTV.MIR.Lowered SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm + +/-- The context of a call in the world `W`: the deployed context with `W`'s account code. -/ +def ctxIn (W : World) (c : TypeCheck.CheckedContract) : Source.Context := + { Wide.ctxOf c with accountCodes := W.codes.getD c.core.context.accountCodes } + +/-- A finished interaction tree folds to its result under every call oracle. -/ +theorem callAns_done {ans : Ans} {fuel : Nat} {table : FunctionTable} {context : Context} + {fn : FunctionDef} {st : Source.State} {args : List Value} {r : CallResult} + (h : fn.call fuel table context st args = some (.done (.ok r))) : + Source.callAns ans fuel table context fn st args = some r := by + simp only [Source.callAns, h, Option.bind_some] + rfl + +/-- `Source.runIn W` of a call from the storage `σ`, once the constructor's result is known. -/ +theorem runIn_eq_at (W : World) {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) (sel : Nat) (ws : List EthLib.Base.U256) + (σ : List (Nat × Nat)) : + Source.runIn W fuel c (Wide.callAt sel ws σ) = + Option.map (Source.observe (Wide.callAt sel ws σ)) + (Source.ABI.Oracle.callCalldata W.ans fuel c.core (ctxIn W c) + { d with storage := σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage } + selfAddress callerAddress 0 + ((EthLib.Base.natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes (ws.map (·.toNat)))) := by + obtain ⟨vs, hc⟩ := hd.cons + simp only [Source.runIn, Source.resultIn?, show (Wide.callAt sel ws σ).callvalue = 0 from rfl, + show (Wide.callAt sel ws σ).storage = σ from rfl, + show (Wide.callAt sel ws σ).calldata = Abi.calldata sel (ws.map (·.toNat)) from rfl] + rw [show ({ c.core.context with sender := callerAddress, self := selfAddress, value := 0 } : + Source.Context) = Wide.ctxOf c from rfl, hc] + simp only [Dirty.bytes_calldata] + rfl + +/-- SolidCore in every world rejects dirty argument words as `Source.run` does. -/ +theorem runIn_rejected (W : World) {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {sel : Nat} (hsel : sel < 2 ^ 32) + {fn : FunctionDef} (hfind : c.core.findFunctionBySelector? sel = some fn) (args : List Nat) + (hargs : ∀ a ∈ args, a < 2 ^ 256) + (hdec : ABI.decodeFunctionArgs? fn (Dirty.argBytes args) = .error .empty) + (σ : List (Nat × Nat)) : + Source.runIn W fuel c { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } = + some (Abi.rejected σ) := by + rw [Wide.callAt_of_args sel args hargs σ, runIn_eq_at W hd, Wide.map_ofNat_toNat args hargs] + simp only [Source.ABI.Oracle.callCalldata, Dirty.readSelector_calldata _ hsel, hfind] + rw [show ((EthLib.Base.natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes args).drop + ABI.selectorBytes = Dirty.argBytes args by + simp [ABI.selectorBytes, EthLib.Base.natToBytes_length], hdec] + simp only [ABI.Contract.revertedCall?, ABI.Contract.encodeRevertData?, bind, Option.bind, + Option.map_some, Source.observe, Abi.rejected] + simp [Wide.callAt] + +/-- SolidCore in the world `W` runs a call of a function of the fragment on clean argument words as +its body's tree. -/ +theorem source_runIn_clean (W : World) {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {σ : List (Nat × Nat)} + (hcov : Covers s σ) {sel : Nat} (hsel : sel < 2 ^ 32) {fn : FunctionDef} + (hfind : c.core.findFunctionBySelector? sel = some fn) {ws : List Nat} + (hw : widthsOf fn.params fn.paramAbiCleanups = some ws) + (hret : fn.returns.all wordBinding = true) {b : Br} + (hb : eraseStmt { envOf c.core with facts := argFacts ws 0 } fuel fn.body (initState fn) = some b) + {T : Tree} (hT : brTree fn (argFacts ws 0) b = some T) (args : List Nat) + (hlen : args.length = fn.params.length) (hargs : ∀ a ∈ args, a < 2 ^ 256) + (hclean : argsClean ws args = true) + (hdec : ABI.decodeFunctionArgs? fn (Dirty.argBytes args) = .ok (args.map .word)) : + Source.runIn W fuel c { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } = + some (T.eval ⟨args, slotValue σ, solHash, callerWord⟩).obs := by + rw [SolidCore.Refinement.Wide.callAt_of_args sel args hargs σ, + runIn_eq_at W hd, SolidCore.Refinement.Wide.map_ofNat_toNat args hargs] + have hdrop : ((EthLib.Base.natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes args).drop + ABI.selectorBytes = Dirty.argBytes args := by + simp [ABI.selectorBytes, EthLib.Base.natToBytes_length] + simp only [Source.ABI.Oracle.callCalldata, Dirty.readSelector_calldata _ hsel, hfind, + hdrop, hdec] + have hp := (widthsOf_spec hw).2.2.1 + have hr : ∀ r ∈ fn.returns, RetTy r.ty ∧ r.isStorageRef = false := + fun r hr => wordBinding_ty (List.all_eq_true.mp hret r hr) + generalize hctx : ABI.Contract.callContextAtWithBase c.core (ctxIn W c) selfAddress callerAddress 0 + ((EthLib.Base.natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes args) = ctx + generalize hst : ({ d with storage := σ.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) d.storage } : + Source.State) = st0 + have hacc : fn.acceptsValue 0 = true := by + simp [FunctionDef.acceptsValue, wordEq] + have hctxv : ctx.value = 0 := by + subst hctx; simp [ABI.Contract.callContextAtWithBase, SolidCore.Solidity.Shared.norm] + set ρ : Val := ⟨args, slotValue σ, solHash, callerWord⟩ with hρ + have hρok : ρ.Ok := slotValue_store σ + set K := argFacts ws 0 with hK + have hKρ : K.Hold ρ := argFacts_hold ρ hargs ws 0 (by simpa [hρ] using hclean) + set E : EraseEnv := { envOf c.core with facts := K } with hE + have hframe : fn.initialFrame? (args.map .word) = + some (frameOf ρ (paramLocals fn.params 0 ++ fn.returns.map fun r => (r.name, .lit 0))) := by + have h0 : BindingDecl.bindArgs? fn.params (args.map .word) = + some (frameOf ρ (paramLocals fn.params 0)) := + bindArgs_words ρ hargs fn.params 0 hp (by simp [hρ, hlen]) + simp only [FunctionDef.initialFrame?, h0, FunctionDef.returnDefaultBindings, + defaults_words ρ fn.returns hr, frameOf, List.map_append] + have hrel : StmtRel ρ E ctx + { state := { st0 with + selfBalance := SolidCore.Solidity.Shared.addWord + (SolidCore.Solidity.Shared.Account.balanceAt ctx.accountBalances ctx.self) ctx.value + worldMutatedSinceAdoption := true }, + locals := [frameOf ρ (paramLocals fn.params 0 ++ fn.returns.map fun r => (r.name, .lit 0))] } + (initState fn) := + { fields := by subst hctx; rfl + events := by subst hctx; rfl + checked := by subst hctx; rfl + sender := by subst hctx; rfl + hash := rfl + ok := hρok + frames := rfl + store := by + intro k hk + have := getD_storage_cover hd hcov k + subst hst + simp only [State.loadSlot, StorageMap.lookup?, initState, Writes.store, hρ] + rw [← this] + simp only [SolidCore.Solidity.Shared.norm, modulus_eq, Std.HashMap.get?_eq_getElem?] + cases (List.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) d.storage σ)[k % wordSize]? <;> rfl + logs := by subst hst; simp [hd.events, initState] + facts := hKρ } + obtain ⟨r, hrun, hleaf⟩ := eval_stmt ρ E ctx fuel fn.body (initState fn) b hb _ hrel + have hcall : Source.callAns W.ans fuel c.core.table ctx fn st0 (args.map .word) = + some (fn.callBodyResult st0 r) := by + have hacc' : fn.acceptsValue ctx.value = true := hctxv ▸ hacc + apply callAns_done + simp only [FunctionDef.call, FunctionDef.evalBodyEntry, hacc', hframe, if_true, + Option.map_some] + rw [show c.core.table = E.tbl from rfl, hrun] + rfl + obtain ⟨T', hT', hTe⟩ := brTree_eval fn K ρ b T hT + rw [hacc, if_pos rfl, hcall, ← hTe] + generalize b.eval ρ = l at hT' hleaf + cases l with + | normal S => + cases r <;> simp only [LeafRel] at hleaf + rename_i rt + simp only [leafTree, Option.bind_eq_bind, Option.bind_eq_some_iff] at hT' + obtain ⟨ws, hws, hT'⟩ := hT' + split at hT' + case isFalse => simp at hT' + rename_i hok + simp only [Option.some.injEq] at hT' + subst hT' + simp only [FunctionDef.callBodyResult, FunctionDef.collectReturns, collectReturnBindings, + collect_words ρ rt S hKρ hleaf.expr.locals fn.returns ws hok hws, untag_words, + encode_words ρ hKρ fn.returns ws hok, bind, Option.bind, Option.map_some] + simp only [Source.observe, Tree.eval, Res.obs, if_true, ↓reduceIte, logEntries_map, + hleaf.logs, Option.some.injEq, Observable.mk.injEq, true_and] + funext slot + exact loadSlot_eq _ S.writes ρ hρok hleaf.store slot + | returned S vs => + cases r <;> simp only [LeafRel] at hleaf + rename_i rt vals + obtain ⟨hst', rfl⟩ := hleaf + by_cases hv : vs = [] + · subst hv + simp only [leafTree, if_true, Option.bind_eq_bind, Option.bind_eq_some_iff] at hT' + obtain ⟨ws, hws, hT'⟩ := hT' + split at hT' + case isFalse => simp at hT' + rename_i hok + simp only [Option.some.injEq] at hT' + subst hT' + simp only [FunctionDef.callBodyResult, List.map_nil, List.isEmpty_nil, if_true, + FunctionDef.collectReturns, collectReturnBindings, + collect_words ρ rt S hKρ hst'.expr.locals fn.returns ws hok hws, untag_words, + encode_words ρ hKρ fn.returns ws hok, bind, Option.bind, Option.map_some] + simp only [Source.observe, Tree.eval, Res.obs, if_true, ↓reduceIte, logEntries_map, + hst'.logs, Option.some.injEq, Observable.mk.injEq, true_and] + funext slot + exact loadSlot_eq _ S.writes ρ hρok hst'.store slot + · simp only [leafTree, hv, if_false] at hT' + split at hT' + case isFalse => simp at hT' + rename_i hok + simp only [Option.some.injEq] at hT' + subst hT' + have hne : (vs.map fun e => Value.word (e.eval ρ)).isEmpty = false := by + cases vs with + | nil => exact absurd rfl hv + | cons _ _ => rfl + simp only [FunctionDef.callBodyResult, hne, Bool.false_eq_true, if_false, + FunctionDef.coerceReturnValues, coerceReturnBindings, + coerce_words ρ rt hKρ fn.returns vs hok, untag_words, + encode_words ρ hKρ fn.returns vs hok, bind, Option.bind, Option.map_some] + simp only [Source.observe, Tree.eval, Res.obs, if_true, ↓reduceIte, logEntries_map, + hst'.logs, Option.some.injEq, Observable.mk.injEq, true_and] + funext slot + exact loadSlot_eq _ S.writes ρ hρok hst'.store slot + | reverted p => + cases r <;> simp only [LeafRel] at hleaf + subst hleaf + cases p with + | empty => + simp only [leafTree, Option.some.injEq] at hT' + subst hT' + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, Fail.data, + ABI.Contract.encodeRevertData?, Source.observe, Tree.eval, Res.obs, hρ, + SolidCore.Refinement.Evm.Wide.callAt] + | panic c => + simp only [leafTree, Option.some.injEq] at hT' + subst hT' + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, Fail.data, encode_panic ρ, + Source.observe, Tree.eval, Res.obs, hρ, SolidCore.Refinement.Evm.Wide.callAt] + | error m => + simp only [leafTree, Option.map_eq_some_iff] at hT' + obtain ⟨bs, hbs, rfl⟩ := hT' + simp [FunctionDef.callBodyResult, RevertData.untagFixedBytes, Fail.data, encode_error ρ _ hbs, + Source.observe, Tree.eval, Res.obs, hρ, SolidCore.Refinement.Evm.Wide.callAt] + +/-- **SolidCore runs a call of a function of the fragment as its erased tree, in every world**, from any storage +`σ` that writes every slot the constructor's entries `s` write, on any argument words below +`2 ^ 256`, clean or dirty. -/ +theorem source_runIn (W : World) {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {σ : List (Nat × Nat)} + (hcov : Covers s σ) {sel : Nat} (hsel : sel < 2 ^ 32) {fn : FunctionDef} + (hfind : c.core.findFunctionBySelector? sel = some fn) {T : Tree} + (hT : eraseFn (envOf c.core) fuel fn = some T) (args : List Nat) + (hlen : args.length = fn.params.length) (hargs : ∀ a ∈ args, a < 2 ^ 256) : + Source.runIn W fuel c { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } = + some (T.eval ⟨args, slotValue σ, solHash, callerWord⟩).obs := by + unfold eraseFn at hT + split at hT + · simp at hT + rename_i ws hw + split at hT + case isFalse => simp at hT + rename_i hret + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at hT + obtain ⟨b, hb, t, ht, rfl⟩ := hT + rw [paramGuards_eval ⟨args, slotValue σ, solHash, callerWord⟩ t hargs ws 0, List.drop_zero] + have hdec := decode_args hw args hlen hargs + by_cases hclean : argsClean ws args = true + · rw [if_pos hclean] + rw [if_pos hclean] at hdec + exact source_runIn_clean W hd hcov hsel hfind hw hret hb ht args hlen hargs hclean hdec + · rw [if_neg hclean] + rw [if_neg hclean] at hdec + rw [runIn_rejected W hd hsel hfind args hargs hdec σ] + rfl + +/-! ## The stage in every world -/ + +/-- The generic source stage for `check` with the environment flag `env`, under every oracle when +the flag is off and every oracle `SourceEnvOk` describes when it is on. -/ +theorem stageInAtWith (W : World) (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} + {d : Source.State} {s : List (Nat × Nat)} (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) + {m : Module} {fns : List Fn} {env : EnvFlags} (henv : SourceAsk env o) + (hchk : check fuel mirFuel c.core m fns env = true) : + Stage (solidCoreIn W fuel) (moduleSem o) c m (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) := by + rintro _ ⟨σ, hcov, f, hf, args, hlen, hargs, rfl⟩ obs hrun + have hcf := List.all_eq_true.mp hchk f hf + unfold checkFn at hcf + cases hfind : c.core.findFunctionBySelector? f.sel with + | none => simp [hfind] at hcf + | some fn => + cases ht1 : eraseFn (envOf c.core) fuel fn with + | none => simp [hfind, ht1] at hcf + | some t1 => + cases ht2 : symTree m f.sel f.params.length mirFuel env with + | none => simp [hfind, ht1, ht2] at hcf + | some t2 => + simp only [hfind, ht1, ht2, Bool.and_eq_true, decide_eq_true_eq] at hcf + obtain ⟨hsel, hpl, hcf⟩ := hcf + have hcf := Tree.eq_of_beq hcf + have hsrc := source_runIn W hd hcov hsel hfind ht1 args (by rw [hlen, hpl]) hargs + change Source.runIn W fuel c _ = some obs at hrun + rw [hsrc] at hrun + cases hrun + rw [← hlen] at ht2 + rw [symTree_sound (callFacts f.sel hsel args hargs σ) o m (henv.envAsk _ _) ht2, + ← Tree.eval_canon, ← hcf, Tree.eval_canon] + +/-- **The generic source stage**: a checked contract whose constructor leaves the storage entries +`s` and no logs and a lowered MIR module that `check` accepts give the stage from SolidCore in every world `W` to the +module's lowered MIR semantics, under every oracle, on every call of a function of `fns` on any +argument words below `2 ^ 256`, with no value, from any storage that writes every slot of `s`. -/ +theorem stageInAt (W : World) (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} + {fns : List Fn} (hchk : check fuel mirFuel c.core m fns = true) : + Stage (solidCoreIn W fuel) (moduleSem o) c m (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) := + stageInAtWith W o hd (env := .off) SourceAsk.off hchk + +/-- The generic source stage from the deployed storage `s`. -/ +theorem stageInDeployed (W : World) (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} + {d : Source.State} {s : List (Nat × Nat)} (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) + {m : Module} {fns : List Fn} (hchk : check fuel mirFuel c.core m fns = true) : + Stage (solidCoreIn W fuel) (moduleSem o) c m (fullScope fns s) := + SolarTV.Stage.mono (stageInAt W o hd hchk) fun _ h => ⟨s, fun kv hkv => ⟨kv, hkv, rfl⟩, h⟩ + +/-- The generic source stage for a contract whose constructor leaves no storage, from any +storage. -/ +theorem stageIn (W : World) (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d []) {m : Module} {fns : List Fn} + (hchk : check fuel mirFuel c.core m fns = true) : + Stage (solidCoreIn W fuel) (moduleSem o) c m (fun call => ∃ σ, fullScope fns σ call) := + SolarTV.Stage.mono (stageInAt W o hd hchk) fun _ ⟨σ, h⟩ => + ⟨σ, fun _ hkv => absurd hkv List.not_mem_nil, h⟩ + +/-- **The generic source stage with the environment flag**: `stageAt` for a module that +`check ... true` accepts, which may read the caller and hash two words, under every oracle whose +caller is `callerWord` and whose Keccak-256 of two words is `solHash` (`SourceEnvOk`). -/ +theorem stageInAtEnv (W : World) (o : Oracle) (henv : SourceEnvOk o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} {s : List (Nat × Nat)} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} {fns : List Fn} + (hchk : check fuel mirFuel c.core m fns .all = true) : + Stage (solidCoreIn W fuel) (moduleSem o) c m (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) := + stageInAtWith W o hd henv.ask hchk + +/-- The generic source stage with the environment flag from the deployed storage `s`. -/ +theorem stageInDeployedEnv (W : World) (o : Oracle) (henv : SourceEnvOk o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} {s : List (Nat × Nat)} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} {fns : List Fn} + (hchk : check fuel mirFuel c.core m fns .all = true) : + Stage (solidCoreIn W fuel) (moduleSem o) c m (fullScope fns s) := + SolarTV.Stage.mono (stageInAtEnv W o henv hd hchk) fun _ h => ⟨s, fun kv hkv => ⟨kv, hkv, rfl⟩, h⟩ + +/-- The generic source stage with the environment flag for a contract whose constructor leaves no +storage, from any storage. -/ +theorem stageInEnv (W : World) (o : Oracle) (henv : SourceEnvOk o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d []) {m : Module} {fns : List Fn} + (hchk : check fuel mirFuel c.core m fns .all = true) : + Stage (solidCoreIn W fuel) (moduleSem o) c m (fun call => ∃ σ, fullScope fns σ call) := + SolarTV.Stage.mono (stageInAtEnv W o henv hd hchk) fun _ ⟨σ, h⟩ => + ⟨σ, fun _ hkv => absurd hkv List.not_mem_nil, h⟩ + +/-- The generic source stage with the caller-only flags (a contract that reads `msg.sender` but +hashes nothing), from any storage that writes every slot of `s`, under every oracle with +SolidCore's caller. -/ +theorem stageInAtCaller (W : World) (o : Oracle) (henv : CallerOk o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} {s : List (Nat × Nat)} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} {fns : List Fn} + (hchk : check fuel mirFuel c.core m fns .callerOnly = true) : + Stage (solidCoreIn W fuel) (moduleSem o) c m (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) := + stageInAtWith W o hd henv.ask hchk + +/-- The caller-only stage for a contract whose constructor leaves no storage, from any storage. -/ +theorem stageInCaller (W : World) (o : Oracle) (henv : CallerOk o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d []) {m : Module} {fns : List Fn} + (hchk : check fuel mirFuel c.core m fns .callerOnly = true) : + Stage (solidCoreIn W fuel) (moduleSem o) c m (fun call => ∃ σ, fullScope fns σ call) := + SolarTV.Stage.mono (stageInAtCaller W o henv hd hchk) fun _ ⟨σ, h⟩ => + ⟨σ, fun _ hkv => absurd hkv List.not_mem_nil, h⟩ + + +/-- **The lowering of `holds_of_runs`, for the call-free functions of a contract**: the generic stage +in every world, for every oracle that agrees with it (and every other). -/ +theorem stageIn_runs {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} + {fns : List Fn} (hchk : check fuel mirFuel c.core m fns = true) : + ∀ o W, CallsAgree o W → + Stage (solidCoreIn W fuel) (moduleSem o) c m (fullScope fns s) := + fun o W _ => stageInDeployed W o hd hchk + +/-- info: 'SolidCore.Refinement.Generic.stageInAtWith' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stageInAtWith + +/-- info: 'SolidCore.Refinement.Generic.stageIn_runs' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stageIn_runs + +/-! ## The same run in every world -/ + +/-- **A function the check accepts runs the same in every world**: on every call of the check's +scope, SolidCore in the world `W` shows what `Source.run` shows. -/ +theorem runIn_eq_run (W : World) {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} + {d : Source.State} {s : List (Nat × Nat)} (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) + {m : Module} {fns : List Fn} {env : EnvFlags} + (hchk : check fuel mirFuel c.core m fns env = true) : + ∀ call, (∃ σ, Covers s σ ∧ fullScope fns σ call) → + Source.runIn W fuel c call = Source.run fuel c call := by + rintro _ ⟨σ, hcov, f, hf, args, hlen, hargs, rfl⟩ + have hcf := List.all_eq_true.mp hchk f hf + unfold checkFn at hcf + cases hfind : c.core.findFunctionBySelector? f.sel with + | none => simp [hfind] at hcf + | some fn => + cases ht1 : eraseFn (envOf c.core) fuel fn with + | none => simp [hfind, ht1] at hcf + | some t1 => + simp only [hfind, ht1, Bool.and_eq_true, decide_eq_true_eq] at hcf + obtain ⟨hsel, hpl, -⟩ := hcf + rw [source_runIn W hd hcov hsel hfind ht1 args (by rw [hlen, hpl]) hargs, + source_run hd hcov hsel hfind ht1 args (by rw [hlen, hpl]) hargs] + +/-- info: 'SolidCore.Refinement.Generic.runIn_eq_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms runIn_eq_run + +end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Generic/Total.lean b/SolidCore/Refinement/Generic/Total.lean new file mode 100644 index 00000000..e9a5ac08 --- /dev/null +++ b/SolidCore/Refinement/Generic/Total.lean @@ -0,0 +1,89 @@ +import SolidCore.Refinement.Generic.Stage +import SolidCore.Refinement.Behaviours + +/-! +# The generic source stage is total + +`Generic.stageAtWith` is a forward stage, so on its own it would say nothing about a call SolidCore +does not finish. Its proof shows more: on every call of its scope SolidCore finishes, with the +observable of the erased function tree (`source_run`). `definedAt` records that, and +`totalAtWith` (with its corollaries for each environment flag) states the stage as a total +refinement (`SolidCore.Refinement.Total`): on every call of the scope both SolidCore and the lowered MIR +module finish, with the same observable, so the module's behaviours there are SolidCore's +(`Total.backward`). A chain that starts with this stage is total whatever stages follow it +(`Total.trans_stage`). +-/ + +namespace SolidCore.Refinement.Generic +open SolarTV SolarTV.Machine SolarTV.MIR.Lowered SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement SolidCore.Refinement.Abi + +/-- SolidCore finishes every call of the generic stage's scope that `check` accepts. -/ +theorem definedAt {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} + {fns : List Fn} {env : EnvFlags} (hchk : check fuel mirFuel c.core m fns env = true) : + Defined (solidCore fuel) c (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) := by + rintro _ ⟨σ, hcov, f, hf, args, hlen, hargs, rfl⟩ + have hcf := List.all_eq_true.mp hchk f hf + unfold checkFn at hcf + cases hfind : c.core.findFunctionBySelector? f.sel with + | none => simp [hfind] at hcf + | some fn => + cases ht1 : eraseFn (envOf c.core) fuel fn with + | none => simp [hfind, ht1] at hcf + | some t1 => + cases ht2 : symTree m f.sel f.params.length mirFuel env with + | none => simp [hfind, ht1, ht2] at hcf + | some t2 => + simp only [hfind, ht1, ht2, Bool.and_eq_true, decide_eq_true_eq] at hcf + obtain ⟨hsel, hpl, -⟩ := hcf + have hsrc := source_run hd hcov hsel hfind ht1 args (by rw [hlen, hpl]) hargs + change (Source.run fuel c _).isSome = true + rw [hsrc] + rfl + +/-- SolidCore finishes every call of the scope from any storage, for a constructor that leaves no +storage. -/ +theorem defined {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d []) {m : Module} {fns : List Fn} + {env : EnvFlags} (hchk : check fuel mirFuel c.core m fns env = true) : + Defined (solidCore fuel) c (fun call => ∃ σ, fullScope fns σ call) := + fun call ⟨σ, h⟩ => definedAt hd hchk call ⟨σ, fun _ hkv => absurd hkv List.not_mem_nil, h⟩ + +/-- **The generic source stage, total**: on every call of the scope, SolidCore and the module +both finish, with the same observable. -/ +theorem totalAtWith (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} + {d : Source.State} {s : List (Nat × Nat)} (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) + {m : Module} {fns : List Fn} {env : EnvFlags} (henv : SourceAsk env o) + (hchk : check fuel mirFuel c.core m fns env = true) : + Total (solidCore fuel) (moduleSem o) c m (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) := + total_iff_stage.mpr ⟨stageAtWith o hd henv hchk, definedAt hd hchk⟩ + +theorem totalAt (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} + {fns : List Fn} (hchk : check fuel mirFuel c.core m fns = true) : + Total (solidCore fuel) (moduleSem o) c m (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) := + totalAtWith o hd SourceAsk.off hchk + +theorem totalAtEnv (o : Oracle) (henv : SourceEnvOk o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} {s : List (Nat × Nat)} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} {fns : List Fn} + (hchk : check fuel mirFuel c.core m fns .all = true) : + Total (solidCore fuel) (moduleSem o) c m (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) := + totalAtWith o hd henv.ask hchk + +theorem totalAtCaller (o : Oracle) (henv : CallerOk o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} {s : List (Nat × Nat)} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} {fns : List Fn} + (hchk : check fuel mirFuel c.core m fns .callerOnly = true) : + Total (solidCore fuel) (moduleSem o) c m (fun call => ∃ σ, Covers s σ ∧ fullScope fns σ call) := + totalAtWith o hd henv.ask hchk + + +/-- +info: 'SolidCore.Refinement.Generic.totalAtWith' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms totalAtWith + +end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Generic/Tree.lean b/SolidCore/Refinement/Generic/Tree.lean new file mode 100644 index 00000000..7f36751d --- /dev/null +++ b/SolidCore/Refinement/Generic/Tree.lean @@ -0,0 +1,509 @@ +import SolarTV.Sem + +/-! +# Symbolic outcomes of a call: the interface of the generic source stage + +The generic source stage (`Generic.Stage`) relates SolidCore and solar's first lowered MIR +through one object both sides compute for a function of the fragment: a `Tree`, the outcome +of one external call as a function of its argument words, the callee's storage before the +call and the hash of two words. + +* `WExpr` is a word over the call: a literal, an argument word, the initial value of a + storage slot (`init` at a constant slot, `sinit` at a computed one), an EVM word operation of + others, a select (`sel c a b` is `a` when `c` is not zero, else `b`), or the Keccak-256 hash + of the 64 bytes of two words (`hash a b`, a mapping's slot `keccak256(abi.encode(key, slot))`), + which is the call's `Val.hash`: each side says what it is (SolidCore's Keccak-256, the MIR + oracle's). Every word is below `2 ^ 256` by construction (`WExpr.eval_lt`). +* `OByte` is one byte of output: a literal byte, or byte `i` (big-endian) of a word. +* `Tree` branches on words (`ite c t e` takes `t` when `c` is not zero) and ends in a + `halt`: success or failure, the output bytes, the storage writes and the logs; a failure + rolls its writes and logs back. + +Storage writes (`Writes`) are (slot word, value word) pairs, the newest that writes a slot +first: a slot holds the value of the first pair whose slot word is it (`Writes.store`). +`Writes.set` drops the pairs of the same slot word and inserts the new pair, after the pairs of +smaller constant slots when its slot is constant, so that a list of constant slots is sorted +with one entry per slot. `Writes.read` is the word a slot holds after the writes: the value of a +pair of the same slot word, past pairs of other constant slots, and a select on the equality of +the slot words otherwise, since a computed slot may be any slot (`Writes.eval_read`). + +`Tree.eval` gives the `Res` of a call: success, output, logs and the storage after it. The +source side (`Generic.Source`) proves that SolidCore's interpreter runs a function of the +fragment as the tree its erasure computes; the target side (`Generic.Mir`) proves that the +lowered MIR runs as the tree its symbolic execution computes. The two trees are compared by +`Tree.canon` (Simp.lean, after `Tree.norm` here) and `Tree.beq`, equality as a `Bool`, which the +kernel evaluates. +-/ + +namespace SolidCore.Refinement.Generic + +/-- The number of 256-bit words. -/ +abbrev wordSize : Nat := 2 ^ 256 + +/-- The account that sends every call, as both sides of the stage take it: SolidCore's +`callerAddress`, and the MIR oracle's caller under `CallerOk`. -/ +def callerWord : Nat := 0x2000 + +/-- The binary word operations of the fragment. -/ +inductive BinOp where + | add | sub | mul | div | lt | gt | eq | and | or | xor | shl | shr | byte + deriving DecidableEq, Repr + +/-- The unary word operations of the fragment. -/ +inductive UnOp where + | iszero | not + deriving DecidableEq, Repr + +/-- A binary operation on words below `2 ^ 256`, as the EVM computes it: `shl s v`, `shr s v` +and `byte i v` take the shift or the byte index first. -/ +def BinOp.eval : BinOp → Nat → Nat → Nat + | .add, a, b => (a + b) % wordSize + | .sub, a, b => (a + (wordSize - b)) % wordSize + | .mul, a, b => (a * b) % wordSize + | .div, a, b => if b = 0 then 0 else a / b + | .lt, a, b => if a < b then 1 else 0 + | .gt, a, b => if b < a then 1 else 0 + | .eq, a, b => if a = b then 1 else 0 + | .and, a, b => a &&& b + | .or, a, b => a ||| b + | .xor, a, b => a ^^^ b + | .shl, a, b => if a < 256 then b * 2 ^ a % wordSize else 0 + | .shr, a, b => if a < 256 then b / 2 ^ a else 0 + | .byte, a, b => if a < 32 then b / 256 ^ (31 - a) % 256 else 0 + +/-- A unary operation on a word below `2 ^ 256`. -/ +def UnOp.eval : UnOp → Nat → Nat + | .iszero, a => if a = 0 then 1 else 0 + | .not, a => wordSize - 1 - a + +/-- A word of the call. -/ +inductive WExpr where + | lit (n : Nat) + | arg (i : Nat) + | init (slot : Nat) + | un (op : UnOp) (a : WExpr) + | bin (op : BinOp) (a b : WExpr) + /-- The initial value of the slot the word names. -/ + | sinit (k : WExpr) + /-- The second word when the first is not zero, else the third. -/ + | sel (c a b : WExpr) + /-- The hash of the 64 bytes of the two words, big-endian (`Val.hash`). -/ + | hash (a b : WExpr) + /-- The account that sent the call (`msg.sender`), symbolic: `Val.caller`. -/ + | caller + deriving DecidableEq, Repr + +/-- What a call reads: its argument words, the callee's storage before it, and the hash of two +words, `keccak256(abi.encode(a, b))` (SolidCore's on the source side, the oracle's on the target +side, which agree under `HashOk`). -/ +structure Val where + args : List Nat + store : Nat → Nat + hash : Nat → Nat → Nat + /-- The caller's address, the value of `WExpr.caller`. -/ + caller : Nat + +/-- The value of a word of the call, below `2 ^ 256`. -/ +def WExpr.eval (ρ : Val) : WExpr → Nat + | .lit n => n % wordSize + | .arg i => ρ.args.getD i 0 % wordSize + | .init k => ρ.store k % wordSize + | .un op a => op.eval (a.eval ρ) % wordSize + | .bin op a b => op.eval (a.eval ρ) (b.eval ρ) % wordSize + | .sinit k => ρ.store (k.eval ρ) % wordSize + | .sel c a b => if c.eval ρ = 0 then b.eval ρ else a.eval ρ + | .hash a b => ρ.hash (a.eval ρ) (b.eval ρ) % wordSize + | .caller => ρ.caller % wordSize + +theorem WExpr.eval_lt (ρ : Val) : ∀ e : WExpr, e.eval ρ < wordSize + | .sel c a b => by + simp only [WExpr.eval] + split + · exact WExpr.eval_lt ρ b + · exact WExpr.eval_lt ρ a + | .lit _ | .arg _ | .init _ | .un _ _ | .bin _ _ _ | .sinit _ | .hash _ _ | .caller => + Nat.mod_lt _ (by decide) + +theorem eval_bin (ρ : Val) (op : BinOp) (a b : WExpr) : + (WExpr.bin op a b).eval ρ = op.eval (a.eval ρ) (b.eval ρ) % wordSize := rfl + +theorem eval_lit (ρ : Val) (n : Nat) : (WExpr.lit n).eval ρ = n % wordSize := rfl + +/-- The storage a call starts from reads every slot modulo `2 ^ 256` as a word. -/ +def Val.Ok (ρ : Val) : Prop := ∀ k, ρ.store (k % wordSize) % wordSize = ρ.store k + +theorem Val.Ok.word {ρ : Val} (h : ρ.Ok) (k : Nat) : ρ.store k < wordSize := by + rw [← h k]; exact Nat.mod_lt _ (by decide) + +theorem Val.Ok.mod {ρ : Val} (h : ρ.Ok) (k : Nat) : ρ.store (k % wordSize) = ρ.store k := by + rw [← h k, Nat.mod_eq_of_lt (h.word _)] + +/-! ## Storage writes -/ + +/-- Storage writes: (slot word, value word) pairs, the newest of a slot first. -/ +abbrev Writes := List (WExpr × WExpr) + +/-- Two slot words that are constants, the first below the second. -/ +def litLt : WExpr → WExpr → Bool + | .lit a, .lit b => decide (a % wordSize < b % wordSize) + | _, _ => false + +/-- Two slot words that are different constants. -/ +def litNe : WExpr → WExpr → Bool + | .lit a, .lit b => decide (a % wordSize ≠ b % wordSize) + | _, _ => false + +theorem litLt_ne (ρ : Val) {a b : WExpr} (h : litLt a b = true) : a.eval ρ ≠ b.eval ρ := by + unfold litLt at h + split at h + · simp only [decide_eq_true_eq] at h + simp only [WExpr.eval] + omega + · simp at h + +theorem litNe_ne (ρ : Val) {a b : WExpr} (h : litNe a b = true) : a.eval ρ ≠ b.eval ρ := by + unfold litNe at h + split at h + · simp only [decide_eq_true_eq] at h + simpa [WExpr.eval] using h + · simp at h + +/-- Insert the newest write of slot `k` among writes of other slots: after the writes of smaller +constant slots. -/ +def Writes.ins : Writes → WExpr → WExpr → Writes + | [], k, e => [(k, e)] + | (k', e') :: rest, k, e => + if litLt k' k then (k', e') :: Writes.ins rest k e else (k, e) :: (k', e') :: rest + +/-- Write `e` to the slot `k` names. -/ +def Writes.set (ws : Writes) (k e : WExpr) : Writes := + Writes.ins (ws.filter fun p => p.1 != k) k e + +/-- The storage after the writes, over the storage `ρ.store` before them; slots are words, so +slot `n` is slot `n % 2 ^ 256`. -/ +def Writes.store (ρ : Val) : Writes → Nat → Nat + | [], n => ρ.store n + | (k, e) :: rest, n => if k.eval ρ = n % wordSize then e.eval ρ else Writes.store ρ rest n + +/-- The word the slot `k` names holds after the writes. -/ +def Writes.read : Writes → WExpr → WExpr + | [], .lit n => .init (n % wordSize) + | [], k => .sinit k + | (k', e') :: rest, k => + if k' = k then e' + else if litNe k' k then Writes.read rest k + else .sel (.bin .eq k k') e' (Writes.read rest k) + +theorem Writes.store_ins (ρ : Val) (k e : WExpr) (n : Nat) : ∀ ws : Writes, + Writes.store ρ (ws.ins k e) n = + if k.eval ρ = n % wordSize then e.eval ρ else Writes.store ρ ws n + | [] => rfl + | (k', e') :: rest => by + simp only [Writes.ins] + split + · rename_i hlt + have hne := litLt_ne ρ hlt + simp only [Writes.store, Writes.store_ins ρ k e n rest] + by_cases h1 : k'.eval ρ = n % wordSize + · have : ¬ k.eval ρ = n % wordSize := fun h2 => hne (h1.trans h2.symm) + simp [h1, this] + · simp [h1] + · rfl + +theorem Writes.store_filter (ρ : Val) (k : WExpr) (n : Nat) (hn : ¬ k.eval ρ = n % wordSize) : + ∀ ws : Writes, Writes.store ρ (ws.filter fun p => p.1 != k) n = Writes.store ρ ws n + | [] => rfl + | (k', e') :: rest => by + simp only [List.filter_cons] + split + · simp only [Writes.store, Writes.store_filter ρ k n hn rest] + · rename_i h + simp only [bne_iff_ne, ne_eq, Decidable.not_not] at h + subst h + simp only [Writes.store, hn, ↓reduceIte, Writes.store_filter ρ k' n hn rest] + +theorem Writes.store_set (ρ : Val) (ws : Writes) (k e : WExpr) (n : Nat) : + Writes.store ρ (ws.set k e) n = + if k.eval ρ = n % wordSize then e.eval ρ else Writes.store ρ ws n := by + unfold Writes.set + rw [Writes.store_ins] + split + · rfl + · rename_i h + exact Writes.store_filter ρ k n h ws + +theorem Writes.store_word {ρ : Val} (hρ : ρ.Ok) (n : Nat) : ∀ ws : Writes, + Writes.store ρ ws n < wordSize + | [] => hρ.word n + | (k, e) :: rest => by + simp only [Writes.store] + split + · exact e.eval_lt ρ + · exact Writes.store_word hρ n rest + +theorem Writes.store_mod (ρ : Val) (hρ : ρ.Ok) (n : Nat) : ∀ ws : Writes, + Writes.store ρ ws (n % wordSize) = Writes.store ρ ws n + | [] => hρ.mod n + | (k, e) :: rest => by + simp only [Writes.store, Nat.mod_mod, Writes.store_mod ρ hρ n rest] + +theorem Writes.eval_read {ρ : Val} (hρ : ρ.Ok) (k : WExpr) : ∀ ws : Writes, + (ws.read k).eval ρ = Writes.store ρ ws (k.eval ρ) + | [] => by + have hk := k.eval_lt ρ + cases k with + | lit n => + simp only [Writes.read, WExpr.eval, Writes.store] + exact Nat.mod_eq_of_lt (hρ.word _) + | _ => + simp only [Writes.read, WExpr.eval, Writes.store] + first + | exact Nat.mod_eq_of_lt (hρ.word _) + | skip + | (k', e') :: rest => by + have hk := k.eval_lt ρ + simp only [Writes.read, Writes.store, Nat.mod_eq_of_lt hk] + split + · rename_i h; subst h; simp + · split + · rename_i _ hne + have := litNe_ne ρ hne + rw [if_neg this, Writes.eval_read hρ k rest] + · simp only [WExpr.eval, BinOp.eval, Writes.eval_read hρ k rest] + by_cases h : k.eval ρ = k'.eval ρ + · simp [h] + · simp [h, Ne.symm h] + +/-! ## Output and logs -/ + +/-- One byte of output. -/ +inductive OByte where + | lit (b : Nat) + | byteOf (e : WExpr) (i : Nat) + deriving DecidableEq, Repr + +/-- The value of a byte of output: byte `i` of a word counts from the most significant. -/ +def OByte.eval (ρ : Val) : OByte → Nat + | .lit b => b % 256 + | .byteOf e i => e.eval ρ / 256 ^ (31 - i) % 256 + +/-- The 32 bytes of a word, big-endian. -/ +def wordOBytes (e : WExpr) : List OByte := (List.range 32).map (OByte.byteOf e) + +/-- The 32 bytes of a literal word, big-endian. -/ +def litBytes (len n : Nat) : List OByte := + (List.range len).map fun i => OByte.lit (n / 256 ^ (len - 1 - i) % 256) + +/-- The revert data of `Panic(code)`: its selector and the code as a word. -/ +def panicBytes (code : Nat) : List OByte := litBytes 4 0x4e487b71 ++ litBytes 32 code + +/-- A log: its topics and its data. -/ +structure Log where + topics : List WExpr + data : List OByte + deriving DecidableEq, Repr + +/-- What a log shows: its topics' words and its data bytes. -/ +def Log.eval (ρ : Val) (l : Log) : List Nat × List Nat := + (l.topics.map (WExpr.eval ρ), l.data.map (OByte.eval ρ)) + +/-- The outcome of a call of a function of the fragment. -/ +inductive Tree where + | halt (success : Bool) (out : List OByte) (writes : Writes) (logs : List Log) + | ite (c : WExpr) (t e : Tree) + deriving DecidableEq, Repr + +/-- Equality of trees as a `Bool`, by structural recursion on both: the kernel evaluates it on the +large trees of a call where it gets stuck on the derived `DecidableEq Tree`. -/ +def Tree.beq : Tree → Tree → Bool + | .halt s o w l, .halt s' o' w' l' => s == s' && decide (o = o') && decide (w = w') && decide (l = l') + | .ite c t e, .ite c' t' e' => decide (c = c') && Tree.beq t t' && Tree.beq e e' + | _, _ => false + +theorem Tree.eq_of_beq : ∀ {a b : Tree}, Tree.beq a b = true → a = b + | .halt _ _ _ _, .halt _ _ _ _, h => by + simp only [Tree.beq, Bool.and_eq_true, beq_iff_eq, decide_eq_true_eq] at h + obtain ⟨⟨⟨rfl, rfl⟩, rfl⟩, rfl⟩ := h + rfl + | .ite _ _ _, .ite _ _ _, h => by + simp only [Tree.beq, Bool.and_eq_true, decide_eq_true_eq] at h + obtain ⟨⟨rfl, ht⟩, he⟩ := h + rw [Tree.eq_of_beq ht, Tree.eq_of_beq he] + | .halt _ _ _ _, .ite _ _ _, h => by simp [Tree.beq] at h + | .ite _ _ _, .halt _ _ _ _, h => by simp [Tree.beq] at h + +/-- What a call shows: whether it succeeded, its output, its logs and the storage after it. -/ +structure Res where + success : Bool + output : List Nat + logs : List (List Nat × List Nat) + store : Nat → Nat + +/-- The result of a call: the tree's branch the call's words take. A failure keeps the storage +before the call and logs nothing. -/ +def Tree.eval (ρ : Val) : Tree → Res + | .halt ok out ws ls => + { success := ok, output := out.map (OByte.eval ρ), + logs := if ok then ls.map (Log.eval ρ) else [], + store := if ok then Writes.store ρ ws else ρ.store } + | .ite c t e => if c.eval ρ = 0 then e.eval ρ else t.eval ρ + +/-- What a call shows outside, from its result. -/ +def Res.obs (R : Res) : SolarTV.Observable := + { success := R.success, output := R.output, logs := R.logs, storage := R.store } + +/-! ## Normal forms + +Both sides of the generic source stage compute a tree; `Tree.norm` folds the constant words +of a tree (`mkBin`, `mkUn`, selects on constants), the bytes of constant words and the branches +on constants, so that the kernel compares two trees by `=` on their normal forms. +`Tree.eval_norm`: a tree and its normal form give every call the same result. -/ + +/-- A binary operation, folded when both operands are constants. -/ +def mkBin (op : BinOp) : WExpr → WExpr → WExpr + | .lit a, .lit b => .lit (op.eval (a % wordSize) (b % wordSize) % wordSize) + | a, b => .bin op a b + +/-- A unary operation, folded on a constant. -/ +def mkUn (op : UnOp) : WExpr → WExpr + | .lit a => .lit (op.eval (a % wordSize) % wordSize) + | a => .un op a + +theorem eval_mkBin (ρ : Val) (op : BinOp) (a b : WExpr) : + (mkBin op a b).eval ρ = (WExpr.bin op a b).eval ρ := by + unfold mkBin + split <;> simp [WExpr.eval, Nat.mod_mod] + +theorem eval_mkUn (ρ : Val) (op : UnOp) (a : WExpr) : + (mkUn op a).eval ρ = (WExpr.un op a).eval ρ := by + unfold mkUn + split <;> simp [WExpr.eval, Nat.mod_mod] + +/-- The constant a word is, if it is one. -/ +def WExpr.lit? : WExpr → Option Nat + | .lit n => some n + | _ => none + +theorem WExpr.eq_of_lit? {e : WExpr} {n : Nat} (h : e.lit? = some n) : e = .lit n := by + cases e <;> simp_all [WExpr.lit?] + +/-- A select, taken when its condition is a constant. -/ +def mkSel (c a b : WExpr) : WExpr := + match c with + | .lit n => if n % wordSize = 0 then b else a + | _ => .sel c a b + +theorem eval_mkSel (ρ : Val) (c a b : WExpr) : (mkSel c a b).eval ρ = (WExpr.sel c a b).eval ρ := by + unfold mkSel + split + · simp only [WExpr.eval] + split <;> simp_all + · rfl + +/-- A word with its constant operations folded. -/ +def WExpr.norm : WExpr → WExpr + | .lit n => .lit (n % wordSize) + | .arg i => .arg i + | .init k => .init k + | .un op a => mkUn op a.norm + | .bin op a b => mkBin op a.norm b.norm + | .sinit k => .sinit k.norm + | .sel c a b => mkSel c.norm a.norm b.norm + | .hash a b => .hash a.norm b.norm + | .caller => .caller + +theorem WExpr.eval_norm (ρ : Val) : ∀ e : WExpr, e.norm.eval ρ = e.eval ρ + | .lit n => by simp [WExpr.norm, WExpr.eval, Nat.mod_mod] + | .arg i => rfl + | .init k => rfl + | .un op a => by rw [WExpr.norm, eval_mkUn]; simp only [WExpr.eval, WExpr.eval_norm ρ a] + | .bin op a b => by + rw [WExpr.norm, eval_mkBin]; simp only [WExpr.eval, WExpr.eval_norm ρ a, WExpr.eval_norm ρ b] + | .sinit k => by simp only [WExpr.norm, WExpr.eval, WExpr.eval_norm ρ k] + | .sel c a b => by + rw [WExpr.norm, eval_mkSel] + simp only [WExpr.eval, WExpr.eval_norm ρ c, WExpr.eval_norm ρ a, WExpr.eval_norm ρ b] + | .hash a b => by simp only [WExpr.norm, WExpr.eval, WExpr.eval_norm ρ a, WExpr.eval_norm ρ b] + | .caller => rfl + +/-- A byte of output, a literal when its word is a constant. -/ +def OByte.norm : OByte → OByte + | .lit b => .lit (b % 256) + | .byteOf e i => + match e.norm with + | .lit n => .lit (n % wordSize / 256 ^ (31 - i) % 256) + | e' => .byteOf e' i + +theorem OByte.eval_norm (ρ : Val) (b : OByte) : b.norm.eval ρ = b.eval ρ := by + cases b with + | lit b => simp [OByte.norm, OByte.eval, Nat.mod_mod] + | byteOf e i => + have h := WExpr.eval_norm ρ e + simp only [OByte.norm] + split + · rename_i n hn + rw [hn] at h + simp only [OByte.eval, ← h, WExpr.eval, Nat.mod_mod] + · simp only [OByte.eval, h] + +/-- The writes with `f` applied to their slot and value words. -/ +def Writes.mapW (f : WExpr → WExpr) (ws : Writes) : Writes := ws.map fun p => (f p.1, f p.2) + +theorem Writes.store_mapW (ρ : Val) (f : WExpr → WExpr) (hf : ∀ e, (f e).eval ρ = e.eval ρ) : + ∀ ws : Writes, Writes.store ρ (ws.mapW f) = Writes.store ρ ws + | [] => rfl + | (k, e) :: rest => by + funext n + have ih := Writes.store_mapW ρ f hf rest + simp only [Writes.mapW, List.map_cons, Writes.store, hf] at ih ⊢ + rw [ih] + +/-- Storage writes with their words in normal form. -/ +def Writes.norm (ws : Writes) : Writes := ws.mapW WExpr.norm + +theorem Writes.store_norm (ρ : Val) (ws : Writes) : Writes.store ρ ws.norm = Writes.store ρ ws := + Writes.store_mapW ρ _ (WExpr.eval_norm ρ) ws + +/-- A log with `f` applied to its topics and `g` to its data bytes. -/ +def Log.mapL (f : WExpr → WExpr) (g : OByte → OByte) (l : Log) : Log := + ⟨l.topics.map f, l.data.map g⟩ + +theorem Log.eval_mapL (ρ : Val) (f : WExpr → WExpr) (g : OByte → OByte) + (hf : ∀ e, (f e).eval ρ = e.eval ρ) (hg : ∀ b, (g b).eval ρ = b.eval ρ) (l : Log) : + (l.mapL f g).eval ρ = l.eval ρ := by + simp only [Log.mapL, Log.eval, List.map_map] + congr 1 + · exact List.map_congr_left fun e _ => hf e + · exact List.map_congr_left fun b _ => hg b + +/-- A tree in normal form: constants folded, branches on constants taken. -/ +def Tree.norm : Tree → Tree + | .halt ok out ws ls => .halt ok (out.map OByte.norm) ws.norm (ls.map (Log.mapL WExpr.norm OByte.norm)) + | .ite c t e => + match c.norm.lit? with + | some n => if n % wordSize = 0 then e.norm else t.norm + | none => .ite c.norm t.norm e.norm + +theorem Tree.eval_norm (ρ : Val) : ∀ T : Tree, T.norm.eval ρ = T.eval ρ + | .halt ok out ws ls => by + simp only [Tree.norm, Tree.eval, List.map_map, Writes.store_norm] + congr 2 + · funext b + exact OByte.eval_norm ρ b + · congr 1 + funext l + exact Log.eval_mapL ρ _ _ (WExpr.eval_norm ρ) (OByte.eval_norm ρ) l + | .ite c t e => by + have hc := WExpr.eval_norm ρ c + simp only [Tree.norm] + split + · rename_i n hn + rw [WExpr.eq_of_lit? hn] at hc + simp only [WExpr.eval] at hc + simp only [Tree.eval, ← hc] + split + · exact Tree.eval_norm ρ e + · exact Tree.eval_norm ρ t + · simp only [Tree.eval, hc, Tree.eval_norm ρ t, Tree.eval_norm ρ e] + +end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Generic/Value.lean b/SolidCore/Refinement/Generic/Value.lean new file mode 100644 index 00000000..e162ea1c --- /dev/null +++ b/SolidCore/Refinement/Generic/Value.lean @@ -0,0 +1,285 @@ +import SolidCore.Refinement.Generic.Stage + +/-! +# The generic source stage on calls with a value + +`Generic.stageAt` covers the calls of the functions of `fns` with no value. This module adds +the calls with any value `v < 2 ^ 256`: `stageAtValue` is the same stage on the scope + + fun call => ∃ σ v, Covers s σ ∧ fullScopeValue fns σ v call + +where `fullScopeValue fns σ v` is `fullScope fns σ` with the call's value `v` (the same call +data, `Abi.calldata`). `stageDeployedValue` is the case of the deployed storage, and +`stageValue` the case of a constructor that leaves no storage. + +Every function of the fragment is non-payable, and a call of a non-payable function with a value +other than 0 reverts with empty data: + +* in SolidCore (`ABI.Contract.callCalldataAtFromWithContext?`), the dispatcher reads the + selector, finds the function, decodes the arguments and then checks the value: a dirty argument + word reverts with `RevertData.empty` before the value check, a clean one reaches it and + `rejectedValueCall?` reverts with `RevertData.empty`, so both revert with empty output + (`source_run_value`); the constructor runs with no value whatever the call's, so the call + still runs against the deployed contract; +* in solar's module, the dispatcher checks the value first (`ne(callvalue, 0)`, then a branch to + `revert(0, 0)`); the symbolic run `symTreeValue` runs the module with the value an unknown + word other than 0 (`SV.paid`), which decides that branch. + +`checkValue mirFuel core m fns` asks, for each function of `fns`, that SolidCore's function of +its selector is not payable and that `symTreeValue` gives a tree all of whose leaves revert +with empty output (`Tree.revertsEmpty`), so with no storage change and no logs. With `check` it +gives the stage at every value: `check` at value 0, `checkValue` at every other. + +`stageAtValueEnv`, `stageDeployedValueEnv` and `stageValueEnv` are the same stages for `check` and +`checkValue` with the environment flag, under every oracle `SourceEnvOk` describes, as +`Generic.stageAtEnv` is for `stageAt`. +-/ + +namespace SolidCore.Refinement.Generic +open EthLib.Base EthLib.Execution EthLib.Execution.Evm +open SolarTV SolarTV.Machine SolarTV.MIR.Lowered SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm + +/-! ## The scope -/ + +/-- Every call of a function of `fns` on any argument words below `2 ^ 256`, clean or not, +with the value `v < 2 ^ 256`, from the storage `s`: `fullScope fns s` with the value `v`. -/ +def fullScopeValue (fns : List Fn) (s : List (Nat × Nat)) (v : Nat) (call : Call) : Prop := + v < 2 ^ 256 ∧ ∃ fn ∈ fns, ∃ args : List Nat, args.length = fn.params.length ∧ + (∀ a ∈ args, a < 2 ^ 256) ∧ + call = { calldata := calldata fn.sel args, callvalue := v, storage := s } + +/-- The calls with value 0 are the calls of `fullScope`. -/ +theorem fullScopeValue_zero (fns : List Fn) (s : List (Nat × Nat)) (call : Call) : + fullScopeValue fns s 0 call ↔ fullScope fns s call := by + constructor + · rintro ⟨-, h⟩ + exact h + · intro h + exact ⟨by decide, h⟩ + +/-! ## SolidCore rejects a value -/ + +/-- **SolidCore rejects a value**: a call with a value other than 0 of a non-payable function of +the fragment, on any argument words, reverts with empty output and leaves the storage. -/ +theorem source_run_value {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {sel : Nat} (hsel : sel < 2 ^ 32) + {fn : FunctionDef} (hfind : c.core.findFunctionBySelector? sel = some fn) + {ws : List Nat} (hw : widthsOf fn.params fn.paramAbiCleanups = some ws) + (hpay : fn.payable = false) (args : List Nat) + (hlen : args.length = fn.params.length) (hargs : ∀ a ∈ args, a < 2 ^ 256) {v : Nat} + (hv0 : v ≠ 0) (hv : v < 2 ^ 256) (σ : List (Nat × Nat)) : + Source.run fuel c { calldata := Abi.calldata sel args, callvalue := v, storage := σ } = + some (rejected σ) := by + obtain ⟨s0, hdep⟩ := deployedStorage_of hd + unfold Abi.deployedStorage at hdep + dsimp only at hdep + split at hdep + case h_2 => simp at hdep + rename_i deployed st hcons + -- The constructor runs with no value, whatever the call's. + have hcons' : TypeCheck.CheckedContract.constructWithContext? fuel c + { c.core.context with sender := callerAddress, self := selfAddress, value := v } + State.empty selfAddress 0 [] = some (CallResult.returned deployed st) := hcons + -- The arguments decode, or a dirty word reverts with empty data. + have hdec : ABI.decodeFunctionArgs? fn (Dirty.argBytes args) = .ok (args.map .word) ∨ + ABI.decodeFunctionArgs? fn (Dirty.argBytes args) = .error .empty := by + rw [decode_args hw args hlen hargs] + by_cases hclean : argsClean ws args = true + · exact Or.inl (if_pos hclean) + · exact Or.inr (if_neg hclean) + have hvm : v % SolidCore.Solidity.Shared.wordModulus = v := Nat.mod_eq_of_lt hv + have hacc : fn.acceptsValue v = false := by + simp [FunctionDef.acceptsValue, hpay, wordEq, SolidCore.Solidity.Shared.norm, hvm, hv0] + simp only [Source.run, Source.result?, hcons', + TypeCheck.CheckedContract.callCalldataAtFromWithContext?, + ABI.Contract.callCalldataAtFromWithContext?, Dirty.bytes_calldata, + Dirty.readSelector_calldata _ hsel, hfind] + rw [show ((natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes args).drop ABI.selectorBytes = + Dirty.argBytes args by simp [ABI.selectorBytes, natToBytes_length]] + rcases hdec with hdec | hdec <;> rw [hdec] <;> + simp only [hacc, Bool.false_eq_true, ↓reduceIte, ABI.Contract.rejectedValueCall?, + ABI.Contract.revertedEmptyCall?, ABI.Contract.revertedCall?, + ABI.Contract.encodeRevertData?, bind, Option.bind, Option.map_some, Source.observe, + rejected] + +/-! ## The check -/ + +/-- Whether every leaf of the tree reverts with empty output. -/ +def Tree.revertsEmpty : Tree → Bool + | .halt ok out _ _ => !ok && out.isEmpty + | .ite _ t e => t.revertsEmpty && e.revertsEmpty + +/-- A tree whose leaves all revert with empty output gives every call a revert with empty output, +no logs and the storage before it. -/ +theorem Tree.eval_revertsEmpty (ρ : Val) : + ∀ T : Tree, T.revertsEmpty = true → + T.eval ρ = { success := false, output := [], logs := [], store := ρ.store } + | .halt ok out ws ls, h => by + simp only [Tree.revertsEmpty, Bool.and_eq_true, Bool.not_eq_true', List.isEmpty_iff] at h + obtain ⟨rfl, rfl⟩ := h + rfl + | .ite c t e, h => by + simp only [Tree.revertsEmpty, Bool.and_eq_true] at h + simp only [Tree.eval] + split + · exact Tree.eval_revertsEmpty ρ e h.2 + · exact Tree.eval_revertsEmpty ρ t h.1 + +/-- Whether a call of the function of `fns` with selector `f.sel` and a value other than 0 +reverts in `m` as in SolidCore: SolidCore's function of the selector is not payable, and the +symbolic run of `m` on the selector with a value other than 0 (`symTreeValue`, `mirFuel` +blocks along each path, the environment flag `env`) reverts with empty output on every path. -/ +def checkValueFn (mirFuel : Nat) (core : Contract) (m : Module) (env : EnvFlags) (f : Fn) : Bool := + match core.findFunctionBySelector? f.sel with + | none => false + | some fn => + !fn.payable && + match symTreeValue m f.sel f.params.length mirFuel env with + | some t => t.revertsEmpty + | none => false + +/-- Whether every function of `fns` rejects a value in `m` as in SolidCore, with the environment +flag `env` (off by default). -/ +def checkValue (mirFuel : Nat) (core : Contract) (m : Module) (fns : List Fn) (env : EnvFlags := .off) : + Bool := + fns.all (checkValueFn mirFuel core m env) + +/-! ## The stage -/ + +/-- The generic source stage at every value for `check` and `checkValue` with the environment flag +`env`, under every oracle when the flag is off and every oracle `SourceEnvOk` describes when it is +on. -/ +theorem stageAtValueWith (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} + {d : Source.State} {s : List (Nat × Nat)} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) + {m : Module} {fns : List Fn} {env : EnvFlags} (henv : SourceAsk env o) + (hchk : check fuel mirFuel c.core m fns env = true) + (hval : checkValue mirFuel c.core m fns env = true) : + Stage (solidCore fuel) (moduleSem o) c m + (fun call => ∃ σ v, Covers s σ ∧ fullScopeValue fns σ v call) := by + rintro _ ⟨σ, v, hcov, hv, f, hf, args, hlen, hargs, rfl⟩ obs hrun + by_cases hv0 : v = 0 + · subst hv0 + exact stageAtWith o hd henv hchk _ ⟨σ, hcov, f, hf, args, hlen, hargs, rfl⟩ obs hrun + have hcf := List.all_eq_true.mp hchk f hf + have hcv := List.all_eq_true.mp hval f hf + unfold checkFn at hcf + unfold checkValueFn at hcv + cases hfind : c.core.findFunctionBySelector? f.sel with + | none => simp [hfind] at hcf + | some fn => + cases ht1 : eraseFn (envOf c.core) fuel fn with + | none => simp [hfind, ht1] at hcf + | some t1 => + cases ht2 : symTreeValue m f.sel f.params.length mirFuel env with + | none => simp [hfind, ht2] at hcv + | some T => + simp only [hfind, ht1, Bool.and_eq_true, decide_eq_true_eq] at hcf + obtain ⟨hsel, hpl, -⟩ := hcf + simp only [hfind, ht2, Bool.and_eq_true, Bool.not_eq_true'] at hcv + obtain ⟨hpay, hrev⟩ := hcv + obtain ⟨ws, hw⟩ := eraseFn_widths ht1 + have hsrc := source_run_value hd hsel hfind hw hpay args (by rw [hlen, hpl]) hargs hv0 hv σ + change Source.run fuel c _ = some obs at hrun + rw [hsrc] at hrun + cases hrun + have hc0 := callFacts f.sel hsel args hargs σ + have hcfv : CallFactsAt .paid f.sel args.length ⟨args, slotValue σ, solHash, callerWord⟩ + { calldata := Abi.calldata f.sel args, callvalue := v, storage := σ } := + { value := by + show BitVec.ofNat 256 v ≠ 0 + intro h + apply hv0 + have := congrArg BitVec.toNat h + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt hv] at this + simpa using this + size := hc0.size + args := hc0.args + selector := hc0.selector + store := hc0.store + ok := hc0.ok } + rw [← hlen] at ht2 + rw [symTreeValue_sound hcfv o m (henv.envAsk _ _) ht2, Tree.eval_revertsEmpty _ _ hrev] + rfl + +/-- **The generic source stage at every value**: a checked contract whose constructor leaves the +storage entries `s` and no logs and a lowered MIR module that `check` and `checkValue` accept give +the stage from SolidCore to the module's lowered MIR semantics, under every oracle, on every call +of a function of `fns` on any argument words below `2 ^ 256`, with any value below `2 ^ 256`, from +any storage that writes every slot of `s`. -/ +theorem stageAtValue (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} + {d : Source.State} {s : List (Nat × Nat)} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) + {m : Module} {fns : List Fn} (hchk : check fuel mirFuel c.core m fns = true) + (hval : checkValue mirFuel c.core m fns = true) : + Stage (solidCore fuel) (moduleSem o) c m + (fun call => ∃ σ v, Covers s σ ∧ fullScopeValue fns σ v call) := + stageAtValueWith o hd (env := .off) SourceAsk.off hchk hval + +/-- The generic source stage at every value from the deployed storage `s`. -/ +theorem stageDeployedValue (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} + {d : Source.State} {s : List (Nat × Nat)} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) + {m : Module} {fns : List Fn} (hchk : check fuel mirFuel c.core m fns = true) + (hval : checkValue mirFuel c.core m fns = true) : + Stage (solidCore fuel) (moduleSem o) c m (fun call => ∃ v, fullScopeValue fns s v call) := + SolarTV.Stage.mono (stageAtValue o hd hchk hval) fun _ ⟨v, h⟩ => + ⟨s, v, fun kv hkv => ⟨kv, hkv, rfl⟩, h⟩ + +/-- The generic source stage at every value for a contract whose constructor leaves no storage, +from any storage. -/ +theorem stageValue (o : Oracle) {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} + {d : Source.State} (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d []) {m : Module} + {fns : List Fn} (hchk : check fuel mirFuel c.core m fns = true) + (hval : checkValue mirFuel c.core m fns = true) : + Stage (solidCore fuel) (moduleSem o) c m (fun call => ∃ σ v, fullScopeValue fns σ v call) := + SolarTV.Stage.mono (stageAtValue o hd hchk hval) fun _ ⟨σ, v, h⟩ => + ⟨σ, v, fun _ hkv => absurd hkv List.not_mem_nil, h⟩ + +/-- **The generic source stage at every value with the environment flag**: `stageAtValue` for a +module that `check ... true` and `checkValue ... true` accept, under every oracle `SourceEnvOk` +describes. -/ +theorem stageAtValueEnv (o : Oracle) (henv : SourceEnvOk o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} {s : List (Nat × Nat)} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) + {m : Module} {fns : List Fn} (hchk : check fuel mirFuel c.core m fns .all = true) + (hval : checkValue mirFuel c.core m fns .all = true) : + Stage (solidCore fuel) (moduleSem o) c m + (fun call => ∃ σ v, Covers s σ ∧ fullScopeValue fns σ v call) := + stageAtValueWith o hd henv.ask hchk hval + +/-- The generic source stage at every value with the environment flag from the deployed storage +`s`. -/ +theorem stageDeployedValueEnv (o : Oracle) (henv : SourceEnvOk o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} {s : List (Nat × Nat)} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) + {m : Module} {fns : List Fn} (hchk : check fuel mirFuel c.core m fns .all = true) + (hval : checkValue mirFuel c.core m fns .all = true) : + Stage (solidCore fuel) (moduleSem o) c m (fun call => ∃ v, fullScopeValue fns s v call) := + SolarTV.Stage.mono (stageAtValueEnv o henv hd hchk hval) fun _ ⟨v, h⟩ => + ⟨s, v, fun kv hkv => ⟨kv, hkv, rfl⟩, h⟩ + +/-- The generic source stage at every value with the environment flag for a contract whose +constructor leaves no storage, from any storage. -/ +theorem stageValueEnv (o : Oracle) (henv : SourceEnvOk o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d []) {m : Module} + {fns : List Fn} (hchk : check fuel mirFuel c.core m fns .all = true) + (hval : checkValue mirFuel c.core m fns .all = true) : + Stage (solidCore fuel) (moduleSem o) c m (fun call => ∃ σ v, fullScopeValue fns σ v call) := + SolarTV.Stage.mono (stageAtValueEnv o henv hd hchk hval) fun _ ⟨σ, v, h⟩ => + ⟨σ, v, fun _ hkv => absurd hkv List.not_mem_nil, h⟩ + +/-- The caller-only stage at every value for a contract whose constructor leaves no storage, from +any storage, under every oracle with SolidCore's caller. -/ +theorem stageValueCaller (o : Oracle) (henv : CallerOk o) {fuel mirFuel : Nat} + {c : TypeCheck.CheckedContract} {d : Source.State} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d []) {m : Module} + {fns : List Fn} (hchk : check fuel mirFuel c.core m fns .callerOnly = true) + (hval : checkValue mirFuel c.core m fns .callerOnly = true) : + Stage (solidCore fuel) (moduleSem o) c m (fun call => ∃ σ v, fullScopeValue fns σ v call) := + SolarTV.Stage.mono (stageAtValueWith o hd henv.ask hchk hval) fun _ ⟨σ, v, h⟩ => + ⟨σ, v, fun _ hkv => absurd hkv List.not_mem_nil, h⟩ + +end SolidCore.Refinement.Generic diff --git a/SolidCore/Refinement/Headline.lean b/SolidCore/Refinement/Headline.lean new file mode 100644 index 00000000..0923f037 --- /dev/null +++ b/SolidCore/Refinement/Headline.lean @@ -0,0 +1,101 @@ +import SolidCore.Refinement.Spec +import SolidCore.Refinement.Corpus.C1 +import SolidCore.Refinement.Corpus.W1 +import SolidCore.Refinement.Corpus.W4 +import SolidCore.Refinement.Corpus.C4 +import SolidCore.Refinement.Corpus.W5 +import Verify +import Verify.C4 +import Verify.W5 + +/-! +# Verified source, verified bytecode + +The end-to-end theorem for contracts the VC generator verifies: a specification proved +of SolidCore with the Loom-based generator (`SolidCore.Verify`) holds of solar's runtime +bytecode on EthLib. + +For c1, c4, w1, w4 and w5 it holds with no hypothesis, through each contract's generated +refinement proof (`Corpus..refines`, `refines_full`). The staged forms reach the +same conclusion through a compiler's stages instead, each stated as a hypothesis named +after the obligation that discharges it: + +* `lowering`: SolidCore to lowered MIR, including ABI decoding and dispatch; +* `backend`: solar's `mir_to_evmir_certified` (MIR pass, stack scheduling and EVM IR pass + certificates); +* `assembly`: solar's `AssemblyStage`, EVM IR to bytecode on EthLib. +-/ + +namespace SolidCore.Refinement.Headline + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem satisfies_iff {S : Sem} {p : S.Prog} {scope : Call → Prop} {pre : Call → Prop} + {post : Call → Observable → Prop} : + SolidCore.Verify.Satisfies S p scope pre post ↔ Satisfies S p scope pre post := Iff.rfl + +/-- c1's verified specification holds of solar's bytecode. -/ +theorem c1 : Satisfies ethLib Corpus.C1.code Verify.C1.scope Verify.C1.pre Verify.C1.post := by + obtain ⟨c, hc, hs, hspec⟩ := Verify.C1.satisfies + obtain ⟨c', s, hc', hs', href⟩ := Corpus.C1.refines + rw [hc] at hc' + cases hc' + rw [hs] at hs' + cases hs' + exact bytecode_of_refines (satisfies_iff.mp hspec) href + +/-- w1's verified specification holds of solar's bytecode, on every argument word. -/ +theorem w1 : Satisfies ethLib Corpus.W1.code Verify.W1.scope Verify.W1.pre Verify.W1.post := by + obtain ⟨c, hc, hspec⟩ := Verify.W1.satisfies + obtain ⟨c', s, hc', hs', href⟩ := Corpus.W1.refines_full + rw [hc] at hc' + cases hc' + rw [(Corpus.W1.shape_of hc).2.1] at hs' + cases hs' + exact bytecode_of_refines (satisfies_iff.mp hspec) href + +/-- w4's verified specification holds of solar's bytecode, on every argument word. -/ +theorem w4 : Satisfies ethLib Corpus.W4.code Verify.W4.scope Verify.W4.pre Verify.W4.post := by + obtain ⟨c, hc, hspec⟩ := Verify.W4.satisfies + obtain ⟨c', s, hc', hs', href⟩ := Corpus.W4.refines_full + rw [hc] at hc' + cases hc' + rw [(Corpus.W4.shape_of hc).2.1] at hs' + cases hs' + exact bytecode_of_refines (satisfies_iff.mp hspec) href + +/-- c4's verified specification holds of solar's bytecode, on every argument word, from the +deployed storage (`v = 0` and `w = 7` packed in slot 0). -/ +theorem c4 : Satisfies ethLib Corpus.C4.code Verify.C4.scope Verify.C4.pre Verify.C4.post := by + obtain ⟨c, hc, hs, hspec⟩ := Verify.C4.satisfies + obtain ⟨c', s, hc', hs', href⟩ := Corpus.C4.refines_full + rw [hc] at hc' + cases hc' + rw [hs] at hs' + cases hs' + exact bytecode_of_refines (satisfies_iff.mp hspec) href + +/-- w5's verified specification holds of solar's `-Ogas` bytecode, on every pair of argument +words: `f(a, b)` returns `a + b` when it fits in 256 bits and otherwise reverts with +`Panic(0x11)`, with no logs and storage unchanged. Its proof uses neither `native_decide` nor +`bv_decide`: the kernel checks the type checker's output (`Corpus.W5.shape_eq`). -/ +theorem w5 : Satisfies ethLib Corpus.W5.code Verify.W5.scope Verify.W5.pre Verify.W5.post := by + obtain ⟨c, hc, hspec⟩ := Verify.W5.satisfies + obtain ⟨c', s, hc', hs', href⟩ := Corpus.W5.refines_full + rw [hc] at hc' + cases hc' + rw [(Corpus.W5.shape_of hc).2.1] at hs' + cases hs' + exact bytecode_of_refines (satisfies_iff.mp hspec) href + +/-- The same for w1 through a compiler's stages, each a hypothesis. -/ +theorem w1_staged {mirSem evmirSem : Sem} {mir : mirSem.Prog} {evmir : evmirSem.Prog} + (lowering : ∀ c, Corpus.W1.contract? = .ok c → + Stage (solidCore Corpus.W1.fuel) mirSem c mir Verify.W1.scope) + (backend : Stage mirSem evmirSem mir evmir Verify.W1.scope) + (assembly : Stage evmirSem ethLib evmir Corpus.W1.code Verify.W1.scope) : + Satisfies ethLib Corpus.W1.code Verify.W1.scope Verify.W1.pre Verify.W1.post := by + obtain ⟨c, hc, hspec⟩ := Verify.W1.satisfies + exact bytecode_of_stages (satisfies_iff.mp hspec) (lowering c hc) backend assembly + +end SolidCore.Refinement.Headline diff --git a/SolidCore/Refinement/Keccak/Agree.lean b/SolidCore/Refinement/Keccak/Agree.lean new file mode 100644 index 00000000..9f2986fe --- /dev/null +++ b/SolidCore/Refinement/Keccak/Agree.lean @@ -0,0 +1,307 @@ +import EthLib.Cryptography.Hash.Keccak +import EvmYul.SpongeHash.Keccak256 + +/-! +# EthLib's Keccak-256 and evmyul's agree on 64 bytes + +SolidCore hashes with evmyul's pure Keccak-256 (`EvmYul.SpongeHash.Keccak256`: lanes as `Nat`s in a +list of 25, bitwise operations reduced mod 2^64) and EthLib with its own (`Hash.Keccak`: a record of +25 `UInt64` lanes). The two are separate definitions; this file proves them equal, structurally: + +1. lanes: each of evmyul's lane operations (`bxor`, `band`, `bnot`, `rotl64`) on the `toNat` of + `UInt64`s is the `toNat` of EthLib's (`toNat_xor'`, `toNat_and'`, `toNat_not'`, `toNat_rotl`); +2. the permutation: with EthLib's state read as evmyul's list (`toL`), each step mapping agrees + (`theta_toL`; evmyul's `rhoPi` is EthLib's `pi ∘ rho`, `rhoPi_toL`; `chi_toL`; `iota_toL`), so + every round does (`round_toL`), evmyul's round constants are EthLib's (`rc_get`) and the two + Keccak-f[1600] agree on every state (`keccakF1600_toL`); +3. the sponge on a 64-byte message: both pad to the same one block of 136 bytes (`pad64`), absorb + it into the same lanes (`absorb64`, each lane the little-endian number of its 8 bytes on both + sides: `chainE`, `laneAt_toNat`), permute once, and squeeze the same first 32 bytes + (`squeeze_toL`): `keccak256_64`. + +The sponge is proved for 64-byte messages, the inputs a mapping's slot hashes (two words); the +permutation for every state. No sorry, native_decide or bv_decide; `decide +kernel` only on closed +tables. +-/ + + +namespace SolidCore.Refinement.Keccak + +open EthLib.Cryptography.Hash.Keccak +namespace E +export EvmYul.SpongeHash.Keccak256 (absorbBlockFrom absorbByte byteShift squeezeBytes laneBytesLE laneByte padKeccak chunksOf chunksOfWithFuel absorbBlocks absorbBlock keccak256Bytes rateBytes bxor band bnot rotl64 u64 word64 mask64 getD setD lane laneIndex + xorList columnXor theta rhoPi rhoPiSet chi iota round permute keccakF1600 roundConstants rhoOffset) +end E + +/-- EthLib's state as evmyul's list of 25 lanes. -/ +def toL (A : State) : List Nat := + [A.a0.toNat, A.a1.toNat, A.a2.toNat, A.a3.toNat, A.a4.toNat, A.a5.toNat, A.a6.toNat, A.a7.toNat, + A.a8.toNat, A.a9.toNat, A.a10.toNat, A.a11.toNat, A.a12.toNat, A.a13.toNat, A.a14.toNat, + A.a15.toNat, A.a16.toNat, A.a17.toNat, A.a18.toNat, A.a19.toNat, A.a20.toNat, A.a21.toNat, + A.a22.toNat, A.a23.toNat, A.a24.toNat] + +theorem u64_toNat (a : UInt64) : E.u64 a.toNat = a.toNat := + Nat.mod_eq_of_lt a.toNat_lt + +theorem toNat_xor' (a b : UInt64) : (a ^^^ b).toNat = E.bxor a.toNat b.toNat := by + simp only [E.bxor, u64_toNat, UInt64.toNat_xor] + exact (Nat.mod_eq_of_lt (Nat.xor_lt_two_pow a.toNat_lt b.toNat_lt)).symm + +theorem toNat_and' (a b : UInt64) : (a &&& b).toNat = E.band a.toNat b.toNat := by + simp only [E.band, u64_toNat, UInt64.toNat_and] + exact (Nat.mod_eq_of_lt (Nat.and_lt_two_pow _ b.toNat_lt)).symm + +theorem toNat_not' (a : UInt64) : (~~~a).toNat = E.bnot a.toNat := by + simp only [E.bnot, u64_toNat, UInt64.toNat_not]; rfl + +theorem toNat_rotl (a r : UInt64) (hr : r.toNat < 64) : (rotl a r).toNat = E.rotl64 a.toNat r.toNat := by + have ha := a.toNat_lt + simp only [rotl, E.rotl64, u64_toNat, UInt64.toNat_or, UInt64.toNat_shiftLeft, UInt64.toNat_shiftRight] + by_cases h0 : r.toNat = 0 + · have : (64 - r).toNat = 64 := by + rw [UInt64.toNat_sub_of_le] <;> simp_all [UInt64.le_iff_toNat_le] + simp [h0, this, Nat.mod_eq_of_lt ha] + · have h64 : (64 - r).toNat = 64 - r.toNat := by + rw [UInt64.toNat_sub_of_le]; · rfl + rw [UInt64.le_iff_toNat_le]; simp; omega + have hn : r.toNat % 64 = r.toNat := Nat.mod_eq_of_lt hr + have hm : (64 - r.toNat) % 64 = 64 - r.toNat := Nat.mod_eq_of_lt (by omega) + have hb : (r.toNat == 0) = false := by simp [h0] + simp only [h64, hn, hm, hb, Bool.false_eq_true, ite_false] + generalize r.toNat = n at * + generalize a.toNat = x at * + have hw : (2:Nat) ^ 64 = 2 ^ (64 - n) * 2 ^ n := by rw [← Nat.pow_add]; congr 1; omega + have hsl : x <<< n % 2 ^ 64 = (x % 2 ^ (64 - n)) <<< n := by + rw [Nat.shiftLeft_eq, Nat.shiftLeft_eq, hw, Nat.mul_mod_mul_right] + have hlt : x >>> (64 - n) < 2 ^ n := by + rw [Nat.shiftRight_eq_div_pow, Nat.div_lt_iff_lt_mul ((Nat.two_pow_pos _)), ← Nat.pow_add] + calc x < 2 ^ 64 := ha + _ = _ := by congr 1; omega + rw [hsl, ← Nat.shiftLeft_add_eq_or_of_lt hlt, ← hsl, Nat.shiftLeft_eq, ← Nat.shiftRight_eq_div_pow] + show _ = (x * 2 ^ n % 2 ^ 64 + x >>> (64 - n)) % 18446744073709551616 + symm; apply Nat.mod_eq_of_lt + have h1 : x * 2 ^ n % 2 ^ 64 = (x % 2 ^ (64 - n)) * 2 ^ n := by rw [hw, Nat.mul_mod_mul_right] + have h2 : x % 2 ^ (64 - n) + 1 ≤ 2 ^ (64 - n) := Nat.mod_lt _ ((Nat.two_pow_pos _)) + have h3 : (x % 2 ^ (64 - n) + 1) * 2 ^ n ≤ 2 ^ 64 := by rw [hw]; exact Nat.mul_le_mul_right _ h2 + rw [h1]; show _ < 2 ^ 64 + have : (x % 2 ^ (64 - n) + 1) * 2 ^ n = x % 2 ^ (64 - n) * 2 ^ n + 2 ^ n := Nat.succ_mul _ _ + omega + +theorem nat_xor_eq (a b : Nat) : Nat.xor a b = a ^^^ b := rfl + +theorem bxor_assoc (a b c : Nat) : E.bxor (E.bxor a b) c = E.bxor a (E.bxor b c) := by + apply Nat.eq_of_testBit_eq; intro i + simp only [E.bxor, E.u64, E.word64, show (18446744073709551616 : Nat) = 2 ^ 64 from rfl, nat_xor_eq, + Nat.testBit_mod_two_pow, Nat.testBit_xor] + cases decide (i < 64) <;> simp + +theorem bxor_zero (a : UInt64) : E.bxor a.toNat 0 = a.toNat := by + rw [← UInt64.toNat_zero, ← toNat_xor', UInt64.xor_zero] + +theorem range5 : List.range 5 = [0, 1, 2, 3, 4] := rfl +theorem range25 : List.range 25 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, + 19, 20, 21, 22, 23, 24] := rfl + +attribute [local simp] toNat_xor' toNat_and' toNat_not' bxor_assoc bxor_zero +attribute [-simp] UInt64.toNat_xor UInt64.toNat_and UInt64.toNat_not + +theorem theta_toL (A : State) : E.theta (toL A) = toL (theta A) := by + simp [E.theta, theta, toL, E.columnXor, E.xorList, E.lane, E.laneIndex, E.getD, range5, range25, + toNat_rotl] + +theorem rhoPi_toL (A : State) : E.rhoPi (toL A) = toL (pi (rho A)) := by + simp [E.rhoPi, E.rhoPiSet, pi, rho, toL, E.lane, E.laneIndex, E.getD, E.setD, range5, toNat_rotl, + E.rhoOffset] + +theorem chi_toL (A : State) : E.chi (toL A) = toL (chi A) := by + simp [E.chi, chi, toL, E.lane, E.laneIndex, E.getD, range25] + +theorem iota_toL (ir : Fin ROUNDS) (A : State) : E.iota (toL A) (RC[ir]).toNat = toL (iota ir A) := by + simp [E.iota, iota, toL, E.getD, E.setD] + +theorem round_toL (ir : Fin ROUNDS) (A : State) : + E.round (toL A) (RC[ir]).toNat = toL (round ir A) := by + rw [E.round, round, theta_toL, rhoPi_toL, chi_toL, iota_toL] + +theorem rc_get : ∀ i (h : i < 24), E.roundConstants[i]? = some (RC[i]'h).toNat := by + decide +kernel + +theorem permute_drop : ∀ n i, i + n = 24 → ∀ A, + E.permute (toL A) (E.roundConstants.drop i) = toL (keccakF.roundsFrom i A) + | 0, i, h, A => by + obtain rfl : i = 24 := by omega + rw [keccakF.roundsFrom]; simp [ROUNDS]; rfl + | n + 1, i, h, A => by + have hi : i < 24 := by omega + have hl : i < E.roundConstants.length := by show i < 24; omega + rw [List.drop_eq_getElem_cons hl] + have hv : E.roundConstants[i] = (RC[i]'hi).toNat := by + have := rc_get i hi; rw [List.getElem?_eq_getElem hl] at this; exact Option.some.inj this + rw [hv, E.permute, show E.round (toL A) (RC[i]'hi).toNat = toL (round ⟨i, hi⟩ A) from round_toL ⟨i, hi⟩ A, + permute_drop n (i + 1) (by omega)] + conv => rhs; rw [keccakF.roundsFrom] + simp [ROUNDS, hi] + +theorem keccakF1600_toL (A : State) : E.keccakF1600 (toL A) = toL (keccakF A) := + permute_drop 24 0 rfl A + +theorem range8 : List.range 8 = [0, 1, 2, 3, 4, 5, 6, 7] := rfl + +theorem squeeze_toL (A : State) : + E.squeezeBytes (toL A) = (Internal.squeeze A).toList.map UInt8.toNat := by + simp [E.squeezeBytes, E.laneBytesLE, E.laneByte, E.getD, toL, Internal.squeeze, Internal.bytesOfLane, + range25, range8, Nat.shiftRight_eq_div_pow] + +theorem toNat_lt256 (b : UInt8) : b.toNat < 256 := b.toNat_lt + +theorem byteAt_mk (l : List UInt8) (i : Nat) : EthLib.Base.byteAt ⟨l.toArray⟩ i = l.getD i 0 := by + simp only [EthLib.Base.byteAt, ByteArray.size, List.size_toArray, List.getD_eq_getElem?_getD] + split + · rename_i h; simp [h, ByteArray.getElem_eq_getElem_data] + · rename_i h; simp [List.getElem?_eq_none (Nat.le_of_not_lt h)] + +theorem xor_shift (x y m : Nat) (hx : x < 2 ^ m) : x ^^^ y * 2 ^ m = x + y * 2 ^ m := by + rw [Nat.add_comm, ← Nat.shiftLeft_eq, Nat.shiftLeft_add_eq_or_of_lt hx] + apply Nat.eq_of_testBit_eq; intro i + simp only [Nat.testBit_xor, Nat.testBit_or, Nat.testBit_shiftLeft] + by_cases hi : m ≤ i + · have : x.testBit i = false := Nat.testBit_lt_two_pow + (Nat.lt_of_lt_of_le hx (Nat.pow_le_pow_right (by decide) hi)) + simp [this, hi] + · simp [hi] + +theorem or_shift (x y m : Nat) (hx : x < 2 ^ m) : x ||| y <<< m = x + y * 2 ^ m := by + rw [Nat.add_comm, ← Nat.shiftLeft_eq, Nat.shiftLeft_add_eq_or_of_lt hx, Nat.or_comm] + +theorem bxor_shift (x y N m : Nat) (hN : N = 2 ^ m) (hx : x < N) (h : x + y * N < 2 ^ 64) : + E.bxor x (y * N) = x + y * N := by + subst hN + have hy : y * 2 ^ m < 2 ^ 64 := by omega + have hx64 : x < 2 ^ 64 := by omega + simp only [E.bxor, E.u64, E.word64, show (18446744073709551616 : Nat) = 2 ^ 64 from rfl, + Nat.mod_eq_of_lt hx64, Nat.mod_eq_of_lt hy, nat_xor_eq, xor_shift x y m hx, Nat.mod_eq_of_lt h] + +theorem bxor_zero_left (x : Nat) (h : x < 2 ^ 64) : E.bxor 0 x = x := by + simp only [E.bxor, E.u64, E.word64, show (18446744073709551616 : Nat) = 2 ^ 64 from rfl, Nat.zero_mod, + Nat.mod_eq_of_lt h, nat_xor_eq, Nat.zero_xor] + +theorem chainE (c0 c1 c2 c3 c4 c5 c6 c7 : Nat) (h0 : c0 < 256) (h1 : c1 < 256) (h2 : c2 < 256) + (h3 : c3 < 256) (h4 : c4 < 256) (h5 : c5 < 256) (h6 : c6 < 256) (h7 : c7 < 256) : + E.bxor 0 (E.bxor c0 (E.bxor (c1 * 256) (E.bxor (c2 * 65536) (E.bxor (c3 * 16777216) + (E.bxor (c4 * 4294967296) (E.bxor (c5 * 1099511627776) + (E.bxor (c6 * 281474976710656) (c7 * 72057594037927936)))))))) = + c0 + c1 * 256 + c2 * 65536 + c3 * 16777216 + c4 * 4294967296 + c5 * 1099511627776 + + c6 * 281474976710656 + c7 * 72057594037927936 := by + simp only [← bxor_assoc] + rw [bxor_zero_left c0 (by omega), + bxor_shift _ _ 256 8 rfl (by omega) (by omega), + bxor_shift _ _ 65536 16 rfl (by omega) (by omega), + bxor_shift _ _ 16777216 24 rfl (by omega) (by omega), + bxor_shift _ _ 4294967296 32 rfl (by omega) (by omega), + bxor_shift _ _ 1099511627776 40 rfl (by omega) (by omega), + bxor_shift _ _ 281474976710656 48 rfl (by omega) (by omega), + bxor_shift _ _ 72057594037927936 56 rfl (by omega) (by omega)] + +theorem laneAt_toNat (bytes : ByteArray) (s : Nat) : + (Internal.laneAt bytes s).toNat = + (EthLib.Base.byteAt bytes s).toNat + (EthLib.Base.byteAt bytes (s + 1)).toNat * 256 + + (EthLib.Base.byteAt bytes (s + 2)).toNat * 65536 + + (EthLib.Base.byteAt bytes (s + 3)).toNat * 16777216 + + (EthLib.Base.byteAt bytes (s + 4)).toNat * 4294967296 + + (EthLib.Base.byteAt bytes (s + 5)).toNat * 1099511627776 + + (EthLib.Base.byteAt bytes (s + 6)).toNat * 281474976710656 + + (EthLib.Base.byteAt bytes (s + 7)).toNat * 72057594037927936 := by + have h0 := toNat_lt256 (EthLib.Base.byteAt bytes s) + have h1 := toNat_lt256 (EthLib.Base.byteAt bytes (s + 1)) + have h2 := toNat_lt256 (EthLib.Base.byteAt bytes (s + 2)) + have h3 := toNat_lt256 (EthLib.Base.byteAt bytes (s + 3)) + have h4 := toNat_lt256 (EthLib.Base.byteAt bytes (s + 4)) + have h5 := toNat_lt256 (EthLib.Base.byteAt bytes (s + 5)) + have h6 := toNat_lt256 (EthLib.Base.byteAt bytes (s + 6)) + have h7 := toNat_lt256 (EthLib.Base.byteAt bytes (s + 7)) + simp only [Internal.laneAt, UInt64.toNat_or, UInt64.toNat_shiftLeft, UInt8.toNat_toUInt64] + generalize (EthLib.Base.byteAt bytes s).toNat = c0 at * + generalize (EthLib.Base.byteAt bytes (s + 1)).toNat = c1 at * + generalize (EthLib.Base.byteAt bytes (s + 2)).toNat = c2 at * + generalize (EthLib.Base.byteAt bytes (s + 3)).toNat = c3 at * + generalize (EthLib.Base.byteAt bytes (s + 4)).toNat = c4 at * + generalize (EthLib.Base.byteAt bytes (s + 5)).toNat = c5 at * + generalize (EthLib.Base.byteAt bytes (s + 6)).toNat = c6 at * + generalize (EthLib.Base.byteAt bytes (s + 7)).toNat = c7 at * + simp only [UInt64.reduceToNat, Nat.reduceMod] + rw [Nat.mod_eq_of_lt (show c1 <<< 8 < 2 ^ 64 by rw [Nat.shiftLeft_eq]; omega), + Nat.mod_eq_of_lt (show c2 <<< 16 < 2 ^ 64 by rw [Nat.shiftLeft_eq]; omega), + Nat.mod_eq_of_lt (show c3 <<< 24 < 2 ^ 64 by rw [Nat.shiftLeft_eq]; omega), + Nat.mod_eq_of_lt (show c4 <<< 32 < 2 ^ 64 by rw [Nat.shiftLeft_eq]; omega), + Nat.mod_eq_of_lt (show c5 <<< 40 < 2 ^ 64 by rw [Nat.shiftLeft_eq]; omega), + Nat.mod_eq_of_lt (show c6 <<< 48 < 2 ^ 64 by rw [Nat.shiftLeft_eq]; omega), + Nat.mod_eq_of_lt (show c7 <<< 56 < 2 ^ 64 by rw [Nat.shiftLeft_eq]; omega)] + rw [or_shift c0 c1 8 (by omega), or_shift _ c2 16 (by omega), + or_shift _ c3 24 (by omega), + or_shift _ c4 32 (by omega), + or_shift _ c5 40 (by omega), + or_shift _ c6 48 (by omega), + or_shift _ c7 56 (by omega)] + +theorem padding64 : (padding 136 64).data = #[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128] := by decide + +theorem pad64 (b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 b11 b12 b13 b14 b15 b16 b17 b18 b19 b20 b21 b22 b23 b24 b25 b26 b27 b28 b29 b30 b31 b32 b33 b34 b35 b36 b37 b38 b39 b40 b41 b42 b43 b44 b45 b46 b47 b48 b49 b50 b51 b52 b53 b54 b55 b56 b57 b58 b59 b60 b61 b62 b63 : UInt8) : + pad 136 ⟨#[b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49, b50, b51, b52, b53, b54, b55, b56, b57, b58, b59, b60, b61, b62, b63]⟩ = ⟨#[b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49, b50, b51, b52, b53, b54, b55, b56, b57, b58, b59, b60, b61, b62, b63, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128]⟩ := by + apply ByteArray.ext + rw [pad, ByteArray.data_append, show ByteArray.size ⟨#[b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49, b50, b51, b52, b53, b54, b55, b56, b57, b58, b59, b60, b61, b62, b63]⟩ = 64 from rfl, padding64] + simp only [List.append_toArray, List.cons_append, List.nil_append] + +set_option maxRecDepth 100000 in +set_option maxHeartbeats 4000000 in +theorem absorb64 (b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 b11 b12 b13 b14 b15 b16 b17 b18 b19 b20 b21 b22 b23 b24 b25 b26 b27 b28 b29 b30 b31 b32 b33 b34 b35 b36 b37 b38 b39 b40 b41 b42 b43 b44 b45 b46 b47 b48 b49 b50 b51 b52 b53 b54 b55 b56 b57 b58 b59 b60 b61 b62 b63 : UInt8) : + E.absorbBlockFrom (List.replicate 25 0) 0 (E.padKeccak [b0.toNat, b1.toNat, b2.toNat, b3.toNat, b4.toNat, b5.toNat, b6.toNat, b7.toNat, b8.toNat, b9.toNat, b10.toNat, b11.toNat, b12.toNat, b13.toNat, b14.toNat, b15.toNat, b16.toNat, b17.toNat, b18.toNat, b19.toNat, b20.toNat, b21.toNat, b22.toNat, b23.toNat, b24.toNat, b25.toNat, b26.toNat, b27.toNat, b28.toNat, b29.toNat, b30.toNat, b31.toNat, b32.toNat, b33.toNat, b34.toNat, b35.toNat, b36.toNat, b37.toNat, b38.toNat, b39.toNat, b40.toNat, b41.toNat, b42.toNat, b43.toNat, b44.toNat, b45.toNat, b46.toNat, b47.toNat, b48.toNat, b49.toNat, b50.toNat, b51.toNat, b52.toNat, b53.toNat, b54.toNat, b55.toNat, b56.toNat, b57.toNat, b58.toNat, b59.toNat, b60.toNat, b61.toNat, b62.toNat, b63.toNat]) = + toL (Internal.absorbBlock 136 State.zero (pad 136 ⟨#[b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49, b50, b51, b52, b53, b54, b55, b56, b57, b58, b59, b60, b61, b62, b63]⟩) 0) := by + rw [pad64] + simp [E.padKeccak, E.rateBytes, E.absorbBlockFrom, E.absorbByte, E.byteShift, E.getD, E.setD, toL, Internal.absorbBlock, + Internal.blockLane, laneAt_toNat, byteAt_mk, State.zero, chainE, toNat_lt256] + all_goals decide + +theorem chunksOf_single (bs : List Nat) (h : bs.length = 136) : E.chunksOf 136 bs = [bs] := by + simp only [E.chunksOf, h] + show E.chunksOfWithFuel (136 + 1) 136 bs = [bs] + cases bs with + | nil => simp at h + | cons x xs => + rw [E.chunksOfWithFuel, List.take_of_length_le (Nat.le_of_eq h), + List.drop_of_length_le (Nat.le_of_eq h)] + all_goals first | rfl | simp + +theorem keccak64_explicit (b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 b11 b12 b13 b14 b15 b16 b17 b18 b19 b20 b21 b22 b23 b24 b25 b26 b27 b28 b29 b30 b31 b32 b33 b34 b35 b36 b37 b38 b39 b40 b41 b42 b43 b44 b45 b46 b47 b48 b49 b50 b51 b52 b53 b54 b55 b56 b57 b58 b59 b60 b61 b62 b63 : UInt8) : + E.keccak256Bytes [b0.toNat, b1.toNat, b2.toNat, b3.toNat, b4.toNat, b5.toNat, b6.toNat, b7.toNat, b8.toNat, b9.toNat, b10.toNat, b11.toNat, b12.toNat, b13.toNat, b14.toNat, b15.toNat, b16.toNat, b17.toNat, b18.toNat, b19.toNat, b20.toNat, b21.toNat, b22.toNat, b23.toNat, b24.toNat, b25.toNat, b26.toNat, b27.toNat, b28.toNat, b29.toNat, b30.toNat, b31.toNat, b32.toNat, b33.toNat, b34.toNat, b35.toNat, b36.toNat, b37.toNat, b38.toNat, b39.toNat, b40.toNat, b41.toNat, b42.toNat, b43.toNat, b44.toNat, b45.toNat, b46.toNat, b47.toNat, b48.toNat, b49.toNat, b50.toNat, b51.toNat, b52.toNat, b53.toNat, b54.toNat, b55.toNat, b56.toNat, b57.toNat, b58.toNat, b59.toNat, b60.toNat, b61.toNat, b62.toNat, b63.toNat] = + (keccak256 ⟨#[b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49, b50, b51, b52, b53, b54, b55, b56, b57, b58, b59, b60, b61, b62, b63]⟩).toList.map UInt8.toNat := by + rw [E.keccak256Bytes, show E.rateBytes = 136 from rfl, chunksOf_single _ (by simp [E.padKeccak, E.rateBytes])] + simp only [E.absorbBlocks, E.absorbBlock] + rw [absorb64, keccakF1600_toL, squeeze_toL, keccak256, spongeAbsorb] + have hc : blockCount RATE (ByteArray.size ⟨#[b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49, b50, b51, b52, b53, b54, b55, b56, b57, b58, b59, b60, b61, b62, b63]⟩) = 1 := by + simp [blockCount, RATE, ByteArray.size] + rw [hc] + rfl + +theorem keccak256_64 (bs : List UInt8) (h : bs.length = 64) : + E.keccak256Bytes (bs.map UInt8.toNat) = (keccak256 ⟨bs.toArray⟩).toList.map UInt8.toNat := by + match bs, h with + | b0 :: b1 :: b2 :: b3 :: b4 :: b5 :: b6 :: b7 :: b8 :: b9 :: b10 :: b11 :: b12 :: b13 :: b14 :: b15 :: b16 :: b17 :: b18 :: b19 :: b20 :: b21 :: b22 :: b23 :: b24 :: b25 :: b26 :: b27 :: b28 :: b29 :: b30 :: b31 :: b32 :: b33 :: b34 :: b35 :: b36 :: b37 :: b38 :: b39 :: b40 :: b41 :: b42 :: b43 :: b44 :: b45 :: b46 :: b47 :: b48 :: b49 :: b50 :: b51 :: b52 :: b53 :: b54 :: b55 :: b56 :: b57 :: b58 :: b59 :: b60 :: b61 :: b62 :: b63 :: [], _ => exact keccak64_explicit b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 b11 b12 b13 b14 b15 b16 b17 b18 b19 b20 b21 b22 b23 b24 b25 b26 b27 b28 b29 b30 b31 b32 b33 b34 b35 b36 b37 b38 b39 b40 b41 b42 b43 b44 b45 b46 b47 b48 b49 b50 b51 b52 b53 b54 b55 b56 b57 b58 b59 b60 b61 b62 b63 + +#print axioms keccak256_64 + +/-! Concrete agreement, checked by the kernel, on messages the 64-byte theorem does not cover: the +empty message, one byte short of a block, a whole block (the padding a block of its own) and two +blocks. Evidence for the general statement, which is not proved here. -/ + +example : (keccak256 ⟨#[]⟩).toList.map UInt8.toNat = E.keccak256Bytes [] := by decide +kernel + +example : (keccak256 ⟨(List.range 135).toArray.map UInt8.ofNat⟩).toList.map UInt8.toNat = + E.keccak256Bytes (List.range 135) := by decide +kernel + +example : (keccak256 ⟨(List.range 136).toArray.map UInt8.ofNat⟩).toList.map UInt8.toNat = + E.keccak256Bytes (List.range 136) := by decide +kernel + +example : (keccak256 ⟨(List.range 200).toArray.map UInt8.ofNat⟩).toList.map UInt8.toNat = + E.keccak256Bytes (List.range 200) := by decide +kernel + +end SolidCore.Refinement.Keccak diff --git a/SolidCore/Refinement/Keccak/TwoWords.lean b/SolidCore/Refinement/Keccak/TwoWords.lean new file mode 100644 index 00000000..19190184 --- /dev/null +++ b/SolidCore/Refinement/Keccak/TwoWords.lean @@ -0,0 +1,53 @@ +import SolidCore.Refinement.Keccak.Agree +import SolidCore.Refinement.Generic.Event +import SolidCore.Refinement.Generic.MirRun +import EthLib.Execution.Evm.Instructions.Keccak + +/-! +# EthLib's KECCAK256 of two words is SolidCore's mapping-slot hash + +The KECCAK256 word EthLib pushes for the 64 bytes of two words (\`Generic.wordBytes\`, big-endian) +is SolidCore's \`Generic.solHash\` of them, reduced to a word: the 64-byte agreement of the two +Keccak-256 implementations (Agree.lean, \`keccak256_64\`), with both sides reading the digest as a +big-endian number. It holds for every pair of numbers; a word's bytes keep its low 256 bits. +-/ + +namespace SolidCore.Refinement.Keccak + +open SolidCore.Solidity.Source + +/-- The bytes of two words, as EthLib's memory holds them, are SolidCore's storage bytes. -/ +theorem twoWords_bytes (a b : Nat) : + ((Generic.wordBytes a ++ Generic.wordBytes b).map UInt8.ofBitVec).map UInt8.toNat = + storageWordBytes a ++ storageWordBytes b := by + have h (v : BitVec 8) : (UInt8.ofBitVec v).toNat = v.toNat := rfl + simp [Generic.wordBytes, storageWordBytes, Generic.evWordToBytesBE_eq, wordBytes, Function.comp_def, h] + +/-- EthLib's word of 32 bytes, big-endian. -/ +theorem fromBeBytes_toNat (v : Vector UInt8 32) : + (EthLib.Base.U256.fromBeBytes v).toNat = EthLib.Base.bytesToNat v.toList % 2 ^ 256 := by + simp only [EthLib.Base.U256.fromBeBytes, BitVec.toNat_ofNat] + +/-- SolidCore's word of a list of bytes is EthLib's, reduced to a word. -/ +theorem bytesToWordBE_map (l : List UInt8) : + bytesToWordBE (l.map UInt8.toNat) = EthLib.Base.bytesToNat l % 2 ^ 256 := by + have hb (b : UInt8) : b.toNat % 256 = b.toNat := Nat.mod_eq_of_lt b.toNat_lt + have hw : SolidCore.Solidity.Shared.wordModulus = 2 ^ 256 := rfl + simp only [bytesToWordBE, SolidCore.Solidity.Shared.norm, hw, List.foldl_map, normByte, + SolidCore.Solidity.Shared.Account.byte, hb, EthLib.Base.bytesToNat] + +/-- **EthLib's Keccak-256 of the 64 bytes of two words is SolidCore's mapping-slot hash**. -/ +theorem ethKeccak_twoWords (a b : Nat) : + (EthLib.Execution.Evm.keccak + ⟨((Generic.wordBytes a ++ Generic.wordBytes b).map UInt8.ofBitVec).toArray⟩).toNat = + Generic.solHash a b % 2 ^ 256 := by + have hlen : ((Generic.wordBytes a ++ Generic.wordBytes b).map UInt8.ofBitVec).length = 64 := by + simp [Generic.wordBytes] + rw [Generic.solHash, keccakWord, ← twoWords_bytes, + show Keccak.keccak256Bytes = EvmYul.SpongeHash.Keccak256.keccak256Bytes from rfl, keccak256_64 _ hlen, + bytesToWordBE_map, Nat.mod_mod, EthLib.Execution.Evm.keccak] + exact fromBeBytes_toNat _ + +#print axioms ethKeccak_twoWords + +end SolidCore.Refinement.Keccak diff --git a/SolidCore/Refinement/Kernel.lean b/SolidCore/Refinement/Kernel.lean new file mode 100644 index 00000000..1ab2c2d4 --- /dev/null +++ b/SolidCore/Refinement/Kernel.lean @@ -0,0 +1,378 @@ +import Lean + +/-! +# Kernel evaluation through well-founded recursion + +The kernel cannot unfold a definition by well-founded recursion on anything but a +`Nat` measure: the elaborator wraps its well-foundedness proof in `Lean.opaqueId`, so +`WellFounded.fix` never reduces. `kernel_clone c` lets the kernel evaluate a closed +term `c` anyway. For every definition `d` that `c` reaches and that reaches such a +fixpoint, it adds a copy `d.kclone` that calls the copies instead, and replaces each +fixpoint `fun ps => WellFounded.fix wf F` by `fun ps => unroll F (d ps) depth`: +`depth` unfoldings of the functional, over the original fixpoint below. Evaluation that +recurses less than `depth` deep never reaches the original, so the kernel evaluates +the copy. With each copy comes `d.kclone_eq : d = d.kclone`, by `fix_eq_unroll` and +congruence, so a fact the kernel decides of `c.kclone` holds of `c`. + +Copies are shared: a definition already copied in an imported module is reused. +-/ + +namespace SolidCore.Refinement.Kernel + +universe u v + +/-- `n` unfoldings of the functional `F` of a well-founded fixpoint, over `g` below. -/ +noncomputable def unroll {α : Sort u} {C : α → Sort v} {r : α → α → Prop} + (F : ∀ x, (∀ y, r y x → C y) → C x) (g : ∀ x, C x) (n : Nat) : ∀ x, C x := + Nat.rec (motive := fun _ => ∀ x, C x) g (fun _ ih x => F x (fun y _ => ih y)) n + +/-- A well-founded fixpoint is its own `n`-fold unfolding. -/ +theorem fix_eq_unroll {α : Sort u} {C : α → Sort v} {r : α → α → Prop} + (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (n : Nat) : + WellFounded.fix hwf F = unroll F (WellFounded.fix hwf F) n := by + induction n with + | zero => rfl + | succ n ih => + funext x + show WellFounded.fix hwf F x = F x (fun y _ => unroll F (WellFounded.fix hwf F) n y) + rw [← ih] + exact WellFounded.fix_eq hwf F x + +open Lean Meta Elab Command + +/-- The unfolding depth of every copied fixpoint. -/ +def depth : Nat := 1000000 + +/-- The body under a term's leading lambdas. -/ +def lamBody : Expr → Expr + | .lam _ _ b _ => lamBody b + | e => e + +/-- Whether a definition's value is a well-founded fixpoint under lambdas. -/ +def isWFFix (v : Expr) : Bool := + (lamBody v).getAppFn.isConstOf ``WellFounded.fix + +/-- The copy's name of a constant at universe levels `ls`. -/ +def cloneName (c : Name) (ls : List Level) : Name := + if ls.isEmpty then c ++ `kclone + else c ++ Name.mkSimple ("kclone_" ++ String.intercalate "_" (ls.map (toString ·.normalize))) + +/-- The name of the copy's equation. -/ +def eqName (clone : Name) : Name := clone ++ `eq + +structure CloneState where + /-- The prefix of the names of new copies: empty for shared copies, a module's own + namespace otherwise, so that two modules never add the same name. -/ + pre : Name := .anonymous + /-- Affected instances, by copy name: `some` copy or `none` when unaffected. -/ + done : Std.HashMap Name (Option Name) := {} + added : Nat := 0 + +abbrev CloneM := StateRefT CloneState MetaM + +/-- The instance `c.{ls}`'s definition, its levels instantiated. -/ +def instDefn? (c : Name) (ls : List Level) : MetaM (Option (Expr × Expr)) := do + match (← getEnv).find? c with + | some (.defnInfo d) => + if d.safety != .safe then return none + return some (d.type.instantiateLevelParams d.levelParams ls, + d.value.instantiateLevelParams d.levelParams ls) + | _ => return none + +/-- The distinct constant instances `e` mentions. -/ +partial def constInsts (e : Expr) : Array Expr := + (go e).run ({}, #[]) |>.2.2 +where + go (e : Expr) : StateM (Std.HashSet Expr × Array Expr) Unit := do + if (← get).1.contains e then return + modify fun (s, a) => (s.insert e, a) + match e with + | .const .. => modify fun (s, a) => (s, if a.contains e then a else a.push e) + | .app f a => go f; go a + | .lam _ t b _ | .forallE _ t b _ => go t; go b + | .letE _ t v b _ => go t; go v; go b + | .mdata _ b => go b + | .proj _ _ b => go b + | _ => pure () + +/-- Replace the constant instances `subst` maps, keeping the term's sharing: a memo on +every subterm, where `Expr.replace`'s bounded cache would unshare a large term. -/ +partial def replaceConsts (e : Expr) (subst : Std.HashMap Expr Expr) : Expr := + (go e).run' {} +where + go (e : Expr) : StateM (Std.HashMap Expr Expr) Expr := do + if let some r := (← get)[e]? then return r + let r ← match e with + | .const .. => pure (subst[e]?.getD e) + | .app f a => return e.updateApp! (← go f) (← go a) + | .lam _ t b _ => return e.updateLambdaE! (← go t) (← go b) + | .forallE _ t b _ => return e.updateForallE! (← go t) (← go b) + | .letE _ t v b _ => return e.updateLetE! (← go t) (← go v) (← go b) + | .mdata _ b => return e.updateMData! (← go b) + | .proj _ _ b => return e.updateProj! (← go b) + | _ => pure e + modify (·.insert e r) + return r + +/-- Trace the copying on stderr. -/ +def debugClone : Bool := false + +/-- The leading lambdas' binders (name, domain, info) and the body under them. -/ +def lamBinders : Expr → Array (Name × Expr × BinderInfo) → Array (Name × Expr × BinderInfo) × Expr + | .lam n t b bi, acc => lamBinders b (acc.push (n, t, bi)) + | e, acc => (acc, e) + +/-- Wrap `body` in lambdas with binders `bs`. -/ +def wrapLams (bs : Array (Name × Expr × BinderInfo)) (body : Expr) : Expr := + bs.foldr (fun (n, t, bi) e => .lam n t e bi) body + +/-- `hs[i] : as[i] = bs[i]` and `M : types → type` give `M as = M bs`. Built by hand, +not by `mkCongr`, which would infer the type of `M`. -/ +def congrN (M : Expr) (types : Array Expr) (type : Expr) (as bs hs : Array Expr) : + MetaM Expr := do + -- `rest[j]`: the type of `M` applied to its first `j` arguments. + let mut rest := #[type] + for t in types.reverse do + rest := rest.push (← mkArrow t rest.back!) + rest := rest.reverse + let mut h := mkApp2 (mkConst ``Eq.refl [← getLevel rest[0]!]) rest[0]! M + let mut f1 := M + let mut f2 := M + for j in [:hs.size] do + let α := types[j]! + let β := rest[j + 1]! + h := mkAppN (mkConst ``congr [← getLevel α, ← getLevel β]) + #[α, β, f1, f2, as[j]!, bs[j]!, h, hs[j]!] + f1 := mkApp f1 as[j]! + f2 := mkApp f2 bs[j]! + return h + +/-- The pieces of a fixpoint body `WellFounded.fix α C r hwf F es` (at most one `e`). -/ +def fixParts (body : Expr) : MetaM (List Level × Array Expr × Array Expr) := do + let args := body.getAppArgs + let extra := args[5:].toArray + if extra.size > 1 then throwError "kernel_clone: a fixpoint applied to {extra.size} arguments" + return (body.getAppFn.constLevels!, args[:5].toArray, extra) + +/-- `unroll F' (WellFounded.fix α C r hwf F) depth es`, from the original's pieces and +the copy's functional `F'`. -/ +def unrolled (lvls : List Level) (args extra : Array Expr) (F' : Expr) : Expr := + let fixFn := mkAppN (mkConst ``WellFounded.fix lvls) args + mkAppN (mkAppN (mkConst ``unroll lvls) #[args[0]!, args[1]!, args[2]!, F', fixFn, mkNatLit depth]) + extra + +/-- For `value = fun ps => WellFounded.fix α C r hwf F es` of type `type`, a proof of +`value = fun ps => unroll F (WellFounded.fix α C r hwf F) depth es`, built on the +value's own subterms (with loose bound variables) so that `F` is shared, not copied. -/ +def unrollProof (value type : Expr) : MetaM Expr := do + let (bs, body) := lamBinders value #[] + let (lvls, args, extra) ← fixParts body + let fixFn := mkAppN (mkConst ``WellFounded.fix lvls) args + let n := mkNatLit depth + let unr := mkAppN (mkConst ``unroll lvls) #[args[0]!, args[1]!, args[2]!, args[4]!, fixFn, n] + let mut pf := mkAppN (mkConst ``fix_eq_unroll lvls) #[args[0]!, args[1]!, args[2]!, args[3]!, args[4]!, n] + let mut lhs := mkAppN fixFn extra + let mut rhs := mkAppN unr extra + -- `B`: the type of `lhs`. + let mut B := match extra[0]? with + | some e => mkApp args[1]! e + | none => .forallE `x args[0]! (mkApp (args[1]!.liftLooseBVars 0 1) (.bvar 0)) .default + for e in extra do + pf := mkAppN (mkConst ``congrFun lvls) #[args[0]!, args[1]!, fixFn, unr, pf, e] + -- Levels of the domains and of `B` under them, on free variables. + let k := bs.size + let levels ← forallBoundedTelescope type (some k) fun ps _ => do + let mut out := #[] + let mut Bi := B + for i' in [:k] do + let i := k - 1 - i' + let D := bs[i]!.2.1.instantiateRev ps[:i] + out := out.push (← getLevel D, ← getLevel (Bi.instantiateRev ps[:i + 1])) + Bi := .forallE bs[i]!.1 bs[i]!.2.1 Bi bs[i]!.2.2 + return out + for i' in [:k] do + let i := k - 1 - i' + let (nm, D, bi) := bs[i]! + let (u, v) := levels[i']! + let f := Expr.lam nm D lhs bi + let g := Expr.lam nm D rhs bi + pf := mkAppN (mkConst ``funext [u, v]) #[D, .lam nm D B bi, f, g, .lam nm D pf bi] + B := .forallE nm D B bi + lhs := f + rhs := g + return pf + +mutual + +/-- The copy of the instance `x` (a constant), when it reaches a well-founded fixpoint. -/ +partial def cloneInst (x : Expr) : CloneM (Option Expr) := do + let c := x.constName! + let ls := x.constLevels! + let shared := cloneName c ls + let name := (← get).pre ++ shared + if let some r := (← get).done[name]? then return r.map (mkConst ·) + for n in [shared, name] do + if (← getEnv).contains n then + modify fun s => { s with done := s.done.insert name (some n) } + return some (mkConst n) + -- Constants are acyclic, so this placeholder is never read for `x` itself. + modify fun s => { s with done := s.done.insert name none } + let some (type, value) ← instDefn? c ls | return none + let target := isWFFix value + let mut as := #[] + let mut bs := #[] + let mut others := #[] + for y in constInsts value do + if let some b ← cloneInst y then + as := as.push y + bs := bs.push b + else others := others.push y + if !target && as.isEmpty then return none + -- Unaffected constants whose types mention affected ones (the proofs of a + -- well-founded definition's decreasing obligations) are cast along the equations. + let mut casts := #[] + for y in others do + let ty ← inferType y + let mut uses := #[] + for t in constInsts ty do + if let some b ← cloneInst t then + uses := uses.push t + unless as.contains t do + as := as.push t + bs := bs.push b + unless uses.isEmpty do casts := casts.push y + build x name type value target as bs casts + modify fun s => { s with done := s.done.insert name (some name), added := s.added + 1 } + return some (mkConst name) + +/-- Add `name`, the copy of the instance `x` with value `value`, and its equation +`x = name`. The copy is `name.gen b₁ h₁ … bₙ hₙ`, where `name.gen z₁ e₁ … zₙ eₙ` +(`eᵢ : aᵢ = zᵢ`) is the value (for a fixpoint, its unfolding) with each affected +constant `aᵢ` replaced by `zᵢ`, and each constant of `casts` cast along the `eᵢ` its +type mentions; `hᵢ : aᵢ = bᵢ` is the equation of `aᵢ`'s copy `bᵢ`. The large value is +copied once, and the equation follows by `Eq.rec` on each `hᵢ`. -/ +partial def build (x : Expr) (name : Name) (type value : Expr) (target : Bool) + (as bs casts : Array Expr) : CloneM Unit := do + if debugClone then + let st ← IO.FS.readFile "/proc/self/status" + let rss := (st.splitOn " +").filter (·.startsWith "VmRSS") |>.headD "" + IO.eprintln s!"build {name} ({as.size} copies used, {casts.size} casts) {rss}" + let hs := bs.map fun b => mkConst (eqName b.constName!) + let types ← as.mapM fun a => (inferType a : MetaM Expr) + let lvls ← types.mapM fun t => (getLevel t : MetaM Level) + let zs ← as.mapM fun _ => do return mkFVar (← mkFreshFVarId) + let es ← as.mapM fun _ => do return mkFVar (← mkFreshFVarId) + let eqT (j : Nat) (b : Expr) := mkApp3 (mkConst ``Eq [lvls[j]!]) types[j]! as[j]! b + let rfl (j : Nat) := mkApp2 (mkConst ``Eq.refl [lvls[j]!]) types[j]! as[j]! + let mut subst : Std.HashMap Expr Expr := + (as.zip zs).foldl (init := {}) fun m (a, z) => m.insert a z + -- `c` cast along `e_j` for each `a_j` its type mentions, in order. + for c in casts do + let ty ← inferType c + let u ← getLevel ty + let mut term := c + let mut cur := ty + let present := constInsts ty + for j in [:as.size] do + unless present.contains as[j]! do continue + let y ← mkFreshFVarId + let next := replaceConsts cur (({} : Std.HashMap Expr Expr).insert as[j]! (mkFVar y)) + let motive := Expr.lam `y types[j]! (.lam `h (eqT j (.bvar 0)) (next.abstract #[mkFVar y] |>.liftLooseBVars 0 1) .default) .default + term := mkAppN (mkConst ``Eq.rec [u, lvls[j]!]) #[types[j]!, as[j]!, motive, term, zs[j]!, es[j]!] + cur := replaceConsts cur (({} : Std.HashMap Expr Expr).insert as[j]! zs[j]!) + subst := subst.insert c term + let body ← if target then do + -- `fun ps => unroll F[zs] (fix α C r hwf F) depth es` + let (bnds, fixBody) := lamBinders value #[] + let (lvl, args, extra) ← fixParts fixBody + let bndsZ := bnds.map fun (n, t, bi) => (n, replaceConsts t subst, bi) + pure (wrapLams bndsZ (unrolled lvl args extra (replaceConsts args[4]! subst))) + else pure (replaceConsts value subst) + -- Binders `z_j : A_j`, `e_j : a_j = z_j`. + let xs := (zs.zip es).foldl (init := #[]) fun acc (z, e) => acc.push z |>.push e + let bTypes := (Array.range as.size).foldl (init := #[]) fun acc j => + acc.push types[j]! |>.push (eqT j zs[j]!) + let lamOver (e : Expr) (mk : Name → Expr → Expr → Expr) : Expr := Id.run do + let mut r := e.abstract xs + for i' in [:xs.size] do + let i := xs.size - 1 - i' + r := mk (Name.mkSimple s!"x{i}") (bTypes[i]!.abstractRange i xs) r + return r + let gen := lamOver body fun n t b => .lam n t b .default + let genType := lamOver type fun n t b => .forallE n t b .default + let genName := name ++ `gen + let genApp (args : Array Expr) := mkAppN (mkConst genName) args + try + let env ← getEnv + let genDefn : DefinitionVal := + { name := genName, levelParams := [], type := genType, value := gen, + hints := .regular (getMaxHeight env gen + 1), safety := .safe } + addDecl (.defnDecl genDefn) + let cloneArgs := (bs.zip hs).foldl (init := #[]) fun acc (b, h) => acc.push b |>.push h + let cloneDefn : DefinitionVal := + { name := name, levelParams := [], type := type, value := genApp cloneArgs, + hints := .regular (getMaxHeight env gen + 2), safety := .safe } + addDecl (.defnDecl cloneDefn) + -- `x = gen a₁ rfl … aₙ rfl`, by unfolding (and, for a fixpoint, `fix_eq_unroll`). + let w ← getLevel type + let pf0 ← if target then unrollProof value type + else pure (mkApp2 (mkConst ``Eq.refl [w]) type x) + let mut pf := pf0 + -- Then rewrite the `j`-th pair from `a_j, rfl` to `b_j, h_j`. + for j in [:as.size] do + let pre := (Array.range j).foldl (init := #[]) fun acc i => acc.push bs[i]! |>.push hs[i]! + let post := (Array.range (as.size - j - 1)).foldl (init := #[]) fun acc i => + acc.push as[j + 1 + i]! |>.push (rfl (j + 1 + i)) + let motive := Expr.lam `y types[j]! (.lam `h (eqT j (.bvar 0)) + (mkApp3 (mkConst ``Eq [w]) type x (genApp (pre ++ #[.bvar 1, .bvar 0] ++ post))) .default) .default + pf := mkAppN (mkConst ``Eq.rec [Level.zero, lvls[j]!]) #[types[j]!, as[j]!, motive, pf, bs[j]!, hs[j]!] + let eqType := mkApp3 (mkConst ``Eq [w]) type x (mkConst name) + let thm : TheoremVal := { name := eqName name, levelParams := [], type := eqType, value := pf } + addDecl (.thmDecl thm) + catch e => + throwError "kernel_clone: copying {x} failed: {e.toMessageData}" + +end + +/-- The copy of the closed definition `c` and its equation, the names of new copies +prefixed by `pre`. -/ +def cloneRoot (c : Name) (pre : Name) : MetaM (Option (Expr × Nat)) := do + let (r, s) ← (cloneInst (mkConst c)).run { pre := pre } + return r.map (·, s.added) + +/-- `kernel_clone c` adds the shared copy `c.kclone` of the closed definition `c`, +with `c.kclone.eq : c = c.kclone`, and the copies it needs. -/ +elab "kernel_clone " id:ident : command => do + let c ← liftCoreM <| realizeGlobalConstNoOverloadWithInfo id + liftTermElabM do + let t0 ← IO.monoMsNow + let r ← cloneRoot c .anonymous + let t1 ← IO.monoMsNow + match r with + | some (_, n) => logInfo m!"kernel_clone {c}: {n} copies in {t1 - t0} ms" + | none => logInfo m!"kernel_clone {c}: nothing to copy" + +/-- `kernel_decide h c` proves `h : c = true` for a closed `c : Bool` in the kernel: +it copies `c` (new copies under the current namespace's `kernel`), and the kernel checks +`c = c'` by the copies' equations and `c' = true` by evaluating the copy `c'`. -/ +elab "kernel_decide " h:ident ppSpace id:ident : command => do + let c ← liftCoreM <| realizeGlobalConstNoOverloadWithInfo id + let ns ← getCurrNamespace + let thmName := ns ++ h.getId + liftTermElabM do + let lhs := mkConst c + let goal := mkApp3 (mkConst ``Eq [1]) (mkConst ``Bool) lhs (mkConst ``Bool.true) + let rfl := mkApp2 (mkConst ``Eq.refl [1]) (mkConst ``Bool) (mkConst ``Bool.true) + let value ← match ← cloneRoot c (ns ++ `kernel) with + | some (k, _) => + let eq := mkConst (eqName k.constName!) + pure (mkAppN (mkConst ``Eq.trans [1]) #[mkConst ``Bool, lhs, k, mkConst ``Bool.true, eq, rfl]) + | none => pure rfl + let t0 ← IO.monoMsNow + let thm : TheoremVal := { name := thmName, levelParams := [], type := goal, value := value } + withOptions (Elab.async.set · false) <| addDecl (.thmDecl thm) + let t1 ← IO.monoMsNow + if debugClone then IO.eprintln s!"kernel_decide {thmName}: kernel check {t1 - t0} ms" + +end SolidCore.Refinement.Kernel diff --git a/SolidCore/Refinement/KernelCopies.lean b/SolidCore/Refinement/KernelCopies.lean new file mode 100644 index 00000000..f612fd48 --- /dev/null +++ b/SolidCore/Refinement/KernelCopies.lean @@ -0,0 +1,28 @@ +import SolidCore.Refinement.Kernel +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Wide.Refines + +/-! +# Shared kernel copies of the type checker and the interpreter + +The copies (`SolidCore.Refinement.Kernel`) of the definitions every corpus contract's +shape checks reach: the type checker and elaborator behind `contract?`, and the +interpreter behind `deployedStorage`, `deployedEmpty` and `Dirty.fnShapeOk`. Each +contract's module copies only what is its own, and anew what reaches the selectors it +reads from its table (`kernel_rfl … using selector_eq`, `SolidCore.Refinement.KernelRfl`). +-/ + +namespace SolidCore.Refinement.KernelCopies + +open SolidCore.Refinement + +set_option maxHeartbeats 0 + +kernel_clone SolidCore.Solidity.TypeCheck.CheckedInput.contract +kernel_clone SolidCore.Solidity.TypeCheck.checkedInputSourceUnit +kernel_clone SolidCore.Refinement.Abi.deployedStorage +kernel_clone SolidCore.Refinement.Wide.deployedEmpty +kernel_clone SolidCore.Refinement.Dirty.fnShapeOk + +end SolidCore.Refinement.KernelCopies diff --git a/SolidCore/Refinement/KernelRfl.lean b/SolidCore/Refinement/KernelRfl.lean new file mode 100644 index 00000000..8ad9a766 --- /dev/null +++ b/SolidCore/Refinement/KernelRfl.lean @@ -0,0 +1,172 @@ +import SolidCore.Refinement.Kernel + +/-! +# Kernel equality of a closed term with a value + +`kernel_rfl h c v` proves `h : c = v` for a closed definition `c` and a closed term `v` +of its type: it copies `c` (`kernel_clone`, new copies under the current namespace's +`kernel`), and the kernel checks `c = c'` by the copies' equations and `c' = v` by +definitional unfolding of the copy `c'`, as `kernel_decide` checks `c' = true`. + +This is how a corpus module learns that SolidCore's checked core of a contract is the +literal it printed, without a decision procedure for equality of cores: the source +syntax (`SolidCore.Solidity.Source.Expr`, `Stmt` and the rest) is nested inductive, so +Lean 4.35 derives no `DecidableEq` for it, and a `match` on the whole literal costs +gigabytes to compile and split. The kernel's own conversion check is the comparison. + +`kernel_rfl h c v using e₁ … eₙ`, with `eᵢ : aᵢ = bᵢ` for constants `aᵢ` and `bᵢ`, makes +the copies call `bᵢ` where the originals call `aᵢ`: every definition `c` reaches that +reaches some `aᵢ` gets a copy of its own, named under `kernel.using_e₁_…` and shared by +the module's checks with the same `eᵢ`, with its equation by congruence along the `eᵢ`; +the rest are the shared copies. This is how the kernel skips a costly subcomputation it +checked once, in a declaration of its own: SolidCore's type checker computes each +external function's selector by Keccak-256, whose kernel evaluation costs about 400 MB +a hash, so a module replaces `ABI.selectorFromSignature` by a table of its contract's +selectors, each proved by `kernel_rfl` alone. +-/ + +namespace SolidCore.Refinement.Kernel + +open Lean Meta Elab Command + +/-- The state of copying under replacements. -/ +structure SubstState where + /-- The prefix of the names of the copies that reach a replaced constant. -/ + pre : Name + /-- The prefix of the current module's own copies (`kernel_decide`'s and + `kernel_rfl`'s), which a copy that reaches no replaced constant may reuse. -/ + modPre : Name + /-- Replaced constants `aᵢ` and their replacements `bᵢ`, with `bᵢ.eq : aᵢ = bᵢ`. -/ + subst : Std.HashMap Name Name + /-- Copies, by shared copy name: the copy and whether it reaches a replaced constant. -/ + done : Std.HashMap Name (Option (Expr × Bool)) := {} + added : Nat := 0 + +/-- The copy of the instance `x` and whether it reaches a replaced constant: `x`'s +replacement, an existing copy (a shared one only when `x` reaches no replaced +constant), else a new copy. -/ +partial def cloneSubst (x : Expr) : StateRefT SubstState MetaM (Option (Expr × Bool)) := do + let c := x.constName! + let ls := x.constLevels! + if let some b := (← get).subst[c]? then return some (mkConst b, true) + let shared := cloneName c ls + if let some r := (← get).done[shared]? then return r + -- Constants are acyclic, so this placeholder is never read for x itself. + modify fun s => { s with done := s.done.insert shared none } + let some (type, value) ← instDefn? c ls | return none + let target := isWFFix value + let mut as := #[] + let mut bs := #[] + let mut others := #[] + let mut tainted := false + for y in constInsts value do + if let some (b, t) ← cloneSubst y then + as := as.push y + bs := bs.push b + tainted := tainted || t + else others := others.push y + let mut casts := #[] + for y in others do + let ty ← inferType y + let mut uses := false + for t in constInsts ty do + if let some (b, tt) ← cloneSubst t then + uses := true + tainted := tainted || tt + unless as.contains t do + as := as.push t + bs := bs.push b + if uses then casts := casts.push y + if !target && as.isEmpty then return none + let s ← get + let mut r : Option Expr := none + let names := if tainted then [s.pre ++ shared] else [shared, s.modPre ++ shared, s.pre ++ shared] + for n in names do + if r.isNone && (← getEnv).contains n then r := some (mkConst n) + let e ← match r with + | some e => pure e + | none => do + let name := s.pre ++ shared + (build x name type value target as bs casts).run' { pre := s.pre } + modify fun s => { s with added := s.added + 1 } + pure (mkConst name) + modify fun s => { s with done := s.done.insert shared (some (e, tainted)) } + return some (e, tainted) + +/-- The copy of the closed definition `c` under the replacements `eqs` (theorems +`aᵢ = bᵢ`), new copies prefixed by `pre`: each `aᵢ` is replaced by `pre ++ bᵢ`, a +definition of `bᵢ` whose equation `(pre ++ bᵢ).eq : aᵢ = pre ++ bᵢ` is `eᵢ`. -/ +def cloneRootSubst (c : Name) (pre modPre : Name) (eqs : Array Name) : + MetaM (Option (Expr × Nat)) := do + let mut subst : Std.HashMap Name Name := {} + for e in eqs do + let some info := (← getEnv).find? e | throwError "kernel_rfl: unknown {e}" + let some (ty, a, b) := info.type.eq? | + throwError "kernel_rfl: {e} is not an equation" + unless a.isConst && b.isConst && a.constLevels!.isEmpty && b.constLevels!.isEmpty do + throwError "kernel_rfl: {e} does not equate two constants" + let rep := pre ++ b.constName! + subst := subst.insert a.constName! rep + let env ← getEnv + if env.contains rep then continue + let defn : DefinitionVal := + { name := rep, levelParams := [], type := ty, value := b, + hints := .regular (getMaxHeight env b + 1), safety := .safe } + addDecl (.defnDecl defn) + let u ← getLevel ty + let thm : TheoremVal := + { name := eqName rep, levelParams := [], + type := mkApp3 (mkConst ``Eq [u]) ty a (mkConst rep), value := mkConst e } + addDecl (.thmDecl thm) + let (r, s) ← (cloneSubst (mkConst c)).run { pre := pre, modPre := modPre, subst := subst } + return r.map fun (e, _) => (e, s.added) + +/-- The identifiers of a piece of syntax, in order. -/ +partial def identsOf (stx : Syntax) : Array Syntax := + if stx.isIdent then #[stx] else stx.getArgs.foldl (fun acc s => acc ++ identsOf s) #[] + +/-- `kernel_rfl h c v` proves `h : c = v` in the kernel for a closed definition `c` and +a closed term `v` of its type; `kernel_rfl h c v using e₁ … eₙ` with its copies calling +`bᵢ` for `aᵢ`, where `eᵢ : aᵢ = bᵢ`. -/ +syntax (name := kernelRflCmd) "kernel_rfl " ident ppSpace ident ppSpace term:max + (" using" (ppSpace ident)+)? : command + +@[command_elab kernelRflCmd, inherit_doc kernelRflCmd] +def elabKernelRfl : CommandElab := fun stx => do + let h : Ident := ⟨stx[1]⟩ + let id : Ident := ⟨stx[2]⟩ + let v : Term := ⟨stx[3]⟩ + let c ← liftCoreM <| realizeGlobalConstNoOverloadWithInfo id + let eqNames ← liftCoreM <| (identsOf stx[4]).mapM fun e => + realizeGlobalConstNoOverloadWithInfo e + let ns ← getCurrNamespace + let thmName := ns ++ h.getId + liftTermElabM do + let lhs := mkConst c + let ty ← inferType lhs + let rhs ← Term.elabTermEnsuringType v ty + Term.synthesizeSyntheticMVarsNoPostponing + let rhs ← instantiateMVars rhs + if rhs.hasMVar || rhs.hasFVar then throwError "kernel_rfl: {rhs} is not closed" + let u ← getLevel ty + let goal := mkApp3 (mkConst ``Eq [u]) ty lhs rhs + let rfl := mkApp2 (mkConst ``Eq.refl [u]) ty rhs + let t0 ← IO.monoMsNow + let copy ← if eqNames.isEmpty then cloneRoot c (ns ++ `kernel) + else + let tag := String.intercalate "_" (eqNames.toList.map fun e => + e.components.getLast!.toString (escape := false)) + cloneRootSubst c (ns ++ `kernel ++ Name.mkSimple ("using_" ++ tag)) (ns ++ `kernel) eqNames + let value := match copy with + | some (k, _) => + let eq := mkConst (eqName k.constName!) + mkAppN (mkConst ``Eq.trans [u]) #[ty, lhs, k, rhs, eq, rfl] + | none => rfl + let t1 ← IO.monoMsNow + let thm : TheoremVal := { name := thmName, levelParams := [], type := goal, value := value } + withOptions (Elab.async.set · false) <| addDecl (.thmDecl thm) + let t2 ← IO.monoMsNow + if debugClone then + IO.eprintln s!"kernel_rfl {thmName}: {copy.map (·.2) |>.getD 0} copies in {t1 - t0} ms, kernel check {t2 - t1} ms" + +end SolidCore.Refinement.Kernel diff --git a/SolidCore/Refinement/KernelThm.lean b/SolidCore/Refinement/KernelThm.lean new file mode 100644 index 00000000..295924ad --- /dev/null +++ b/SolidCore/Refinement/KernelThm.lean @@ -0,0 +1,28 @@ +import Lean + +/-! +# Kernel conversion of an equation under binders + +`kernel_thm h : ∀ xs, l = r` adds the theorem `h` with the proof `fun xs => Eq.refl l`, which +only the kernel checks, by its conversion of `l` and `r`: the elaborator does not unfold either +side, so a symbolic run of a program, whose terms its `whnf` takes too long to unfold, is +checked at the kernel's speed. Free variables (an oracle, a storage) stay symbolic; a mismatch is +the kernel's `declaration type mismatch`. +-/ + +namespace SolidCore.Refinement.Kernel + +open Lean Meta Elab Command in +/-- `kernel_thm h : ∀ xs, l = r` proves the equation by the kernel's conversion alone. -/ +elab "kernel_thm " n:ident " : " t:term : command => do + let name := (← getCurrNamespace) ++ n.getId + liftTermElabM do + let ty ← Term.elabType t + Term.synthesizeSyntheticMVarsNoPostponing + let ty ← instantiateMVars ty + let pf ← forallTelescope ty fun xs body => do + let some (_, l, _) := body.eq? | throwError "kernel_thm: not an equation" + mkLambdaFVars xs (← mkEqRefl l) + addDecl (.thmDecl { name, levelParams := [], type := ty, value := pf }) + +end SolidCore.Refinement.Kernel diff --git a/SolidCore/Refinement/KernelValue.lean b/SolidCore/Refinement/KernelValue.lean new file mode 100644 index 00000000..95366cd4 --- /dev/null +++ b/SolidCore/Refinement/KernelValue.lean @@ -0,0 +1,64 @@ +import SolidCore.Refinement.KernelRfl + +/-! +# The value of a closed computation, printed and checked by the kernel + +`kernel_some v c`, for a closed definition `c : Option α`, evaluates `c` by compiled code, prints the +value inside its `some` by `α`'s `Repr`, elaborates the print as `def v : α`, and proves +`v_eq : c = some v` by `kernel_rfl` (`kernel_some v c using e₁ … eₙ` passes the `eᵢ` on). The +evaluator and the printer are untrusted: the kernel checks the equation, so a mistake in either +is a kernel error, never a wrong literal. + +This is how a check of a large closed computation is split into stages, each a declaration of +its own whose result the next stage reads as a literal, so the kernel's memory for one stage is +freed before the next: the literal is computed afresh by every build, never a checked-in copy. +-/ + +namespace SolidCore.Refinement.Kernel + +open Lean Meta Elab Command + +private unsafe def evalOptStringUnsafe (e : Expr) : MetaM (Option String) := + evalExpr (Option String) (mkApp (mkConst ``Option [.zero]) (mkConst ``String)) e + +@[implemented_by evalOptStringUnsafe] +private opaque evalOptString (e : Expr) : MetaM (Option String) + +/-- Parse and elaborate a command given as text. -/ +private def elabCommandText (s : String) : CommandElabM Unit := do + match Parser.runParserCategory (← getEnv) `command s with + | .ok cmd => elabCommand cmd + | .error err => throwError "kernel_some: generated command does not parse: {err}" + +/-- `kernel_some v c` defines `v` as the printed value of the closed `c : Option α` and proves +`v_eq : c = some v` by `kernel_rfl`; `kernel_some v c using e₁ … eₙ` passes the `eᵢ` on. -/ +syntax (name := kernelSomeCmd) "kernel_some " ident ppSpace ident + (" using" (ppSpace ident)+)? : command + +@[command_elab kernelSomeCmd, inherit_doc kernelSomeCmd] +def elabKernelSome : CommandElab := fun stx => do + let v : Ident := ⟨stx[1]⟩ + let id : Ident := ⟨stx[2]⟩ + let c ← liftCoreM <| realizeGlobalConstNoOverloadWithInfo id + let eqNames ← liftCoreM <| (identsOf stx[3]).mapM fun e => + realizeGlobalConstNoOverloadWithInfo e + let printer := s!"(match _root_.{c} with | some y => some (Std.Format.pretty (repr y) 100) | none => none : Option String)" + let printerStx ← match Parser.runParserCategory (← getEnv) `term printer with + | .ok t => pure t + | .error err => throwError "kernel_some: {err}" + let (s, ty) ← liftTermElabM do + let ty ← whnfR (← inferType (mkConst c)) + let some α := ty.app1? ``Option | throwError "kernel_some: {c} is not of an Option type" + let e ← Term.elabTermEnsuringType printerStx none + Term.synthesizeSyntheticMVarsNoPostponing + let e ← instantiateMVars e + let some s ← evalOptString e | throwError "kernel_some: {c} evaluates to none" + let ty ← withOptions (fun o => (pp.fullNames.set o true)) <| ppExpr α + return (s, toString ty) + elabCommandText s!"def {v.getId} : {ty} :=\n{s}" + let ns ← getCurrNamespace + let usingTxt := if eqNames.isEmpty then "" else + " using" ++ String.join (eqNames.toList.map fun e => s!" _root_.{e}") + elabCommandText s!"kernel_rfl {v.getId.appendAfter "_eq"} _root_.{c} (some _root_.{ns ++ v.getId}){usingTxt}" + +end SolidCore.Refinement.Kernel diff --git a/SolidCore/Refinement/NonVacuity.lean b/SolidCore/Refinement/NonVacuity.lean new file mode 100644 index 00000000..31f42197 --- /dev/null +++ b/SolidCore/Refinement/NonVacuity.lean @@ -0,0 +1,370 @@ +import SolidCore.Refinement.Headline +import SolidCore.Refinement.Behaviours + +/-! +# The headline theorems on concrete calls + +Each headline theorem (`Headline.c1`, `w1`, `w4`, `c4`, `w5`) states that a specification +holds of solar's bytecode on EthLib. This module checks that none of them holds for a trivial +reason, by reading off them, for concrete calls, the exact observable both sides give: + +* each `*_target` theorem is EthLib's run of the bytecode on one call, derived from the headline + alone; each `*_source` theorem is SolidCore's run of the same call, derived from the verified + specification alone, and the two agree (the relation is checked on a call both sides finish); +* the calls include a success that returns data, a success that writes storage, and a revert with + `Panic(0x11)` data, so return data, storage and revert data are each pinned; +* each `*_rejects` theorem shows the bytecode does not give a neighbouring observable (one + more in the returned word, or success where it reverts). + +Were `Satisfies`, `Stage` or `Refines` a relation that related everything, the headline would +carry no information about `Target.run`, and neither the `*_target` nor the `*_rejects` +theorems could be proved. +-/ + +namespace SolidCore.Refinement.NonVacuity + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Verify + +/-- A specification whose postcondition pins one observable gives that observable. -/ +theorem run_of_pinned {S : Sem} {p : S.Prog} {scope pre : Call → Prop} + {post : Call → Observable → Prop} (h : Satisfies S p scope pre post) {call : Call} + (hc : scope call) (hp : pre call) {o : Observable} (pin : ∀ obs, post call obs → obs = o) : + S.run p call = some o := by + obtain ⟨obs, hrun, hpost⟩ := h call hc hp + rw [hrun, pin obs hpost] + +/-- The call of `sel` on `args` with no value from the storage `σ`. -/ +def callAt (sel : Nat) (args : List Nat) (σ : List (Nat × Nat)) : Call := + { calldata := Abi.calldata sel args, callvalue := 0, storage := σ } + +theorem argWords_callAt (sel : Nat) (args : List Nat) (σ : List (Nat × Nat)) + (h : ∀ a ∈ args, a < 2 ^ 256) : argWords args.length (callAt sel args σ) = args := + argWords_calldata sel args h 0 σ + +theorem fullScope_callAt {fn : Fn} {fns : List Fn} (hfn : fn ∈ fns) (args : List Nat) + (hlen : args.length = fn.params.length) (h : ∀ a ∈ args, a < 2 ^ 256) (σ : List (Nat × Nat)) : + fullScope fns σ (callAt fn.sel args σ) := + ⟨fn, hfn, args, hlen, h, rfl⟩ + +theorem obs_eq {o : Observable} {s : Bool} {out : List Nat} {logs : List (List Nat × List Nat)} + {st : Nat → Nat} (h1 : o.success = s) (h2 : o.output = out) (h3 : o.logs = logs) + (h4 : ∀ slot, o.storage slot = st slot) : o = ⟨s, out, logs, st⟩ := by + cases o + simp only at h1 h2 h3 h4 + subst h1 h2 h3 + rw [show _ = st from funext h4] + +/-! ## w5: `f(a, b)` returns `a + b` or reverts with `Panic(0x11)` -/ + +namespace W5 + +open SolidCore.Refinement.Corpus.W5 + +def fn : Fn := ⟨Bytecode.W5.Main.fSelector, [(.uint 256), (.uint 256)]⟩ + +/-- `f(1, 2)`. -/ +def add : Call := callAt fn.sel [1, 2] [] + +/-- `f(2 ^ 256 - 1, 1)`, which overflows. -/ +def overflow : Call := callAt fn.sel [2 ^ 256 - 1, 1] [] + +def addObs : Observable := ⟨true, word 3, [], fun _ => 0⟩ + +def overflowObs : Observable := ⟨false, panic 0x11, [], fun _ => 0⟩ + +theorem add_scope : Verify.W5.scope add := + fullScope_callAt (fn := fn) (List.mem_singleton_self _) [1, 2] rfl (by decide) [] + +theorem overflow_scope : Verify.W5.scope overflow := + fullScope_callAt (fn := fn) (List.mem_singleton_self _) [2 ^ 256 - 1, 1] rfl (by decide) [] + +theorem add_pin (obs : Observable) (h : Verify.W5.post add obs) : obs = addObs := by + have hw : argWords 2 add = [1, 2] := argWords_callAt fn.sel [1, 2] [] (by decide) + simp only [Verify.W5.post, hw] at h + obtain ⟨⟨hs, ho⟩, hl, hst⟩ := (by simpa using h : + (obs.success = true ∧ obs.output = word 3) ∧ obs.logs = [] ∧ ∀ slot, obs.storage slot = 0) + exact obs_eq hs ho hl hst + +theorem overflow_pin (obs : Observable) (h : Verify.W5.post overflow obs) : obs = overflowObs := by + have hw : argWords 2 overflow = [2 ^ 256 - 1, 1] := argWords_callAt fn.sel [2 ^ 256 - 1, 1] [] (by decide) + simp only [Verify.W5.post, hw] at h + obtain ⟨⟨hs, ho⟩, hl, hst⟩ := (by simpa using h : + (obs.success = false ∧ obs.output = panic 0x11) ∧ obs.logs = [] ∧ + ∀ slot, obs.storage slot = 0) + exact obs_eq hs ho hl hst + +/-- solar's bytecode returns `3` on `f(1, 2)`, read off the headline. -/ +theorem add_target : Target.run code add = some addObs := + run_of_pinned Headline.w5 add_scope trivial add_pin + +/-- solar's bytecode reverts with `Panic(0x11)` on `f(2 ^ 256 - 1, 1)`. -/ +theorem overflow_target : Target.run code overflow = some overflowObs := + run_of_pinned Headline.w5 overflow_scope trivial overflow_pin + +/-- SolidCore gives the same observables, read off the verified specification. -/ +theorem source : ∃ c, contract? = .ok c ∧ + Source.run fuel c add = some addObs ∧ Source.run fuel c overflow = some overflowObs := by + obtain ⟨c, hc, h⟩ := Verify.W5.satisfies + exact ⟨c, hc, run_of_pinned h add_scope trivial add_pin, + run_of_pinned h overflow_scope trivial overflow_pin⟩ + +theorem rejects : Target.run code add ≠ some ⟨true, word 4, [], fun _ => 0⟩ ∧ + Target.run code overflow ≠ some ⟨true, [], [], fun _ => 0⟩ := by + rw [add_target, overflow_target] + refine ⟨fun h => ?_, fun h => ?_⟩ + · have := congrArg (Option.map fun o : Observable => o.output) h + simp only [addObs, Option.map_some, Option.some.injEq] at this + exact absurd this (by decide) + · have := congrArg (Option.map fun o : Observable => o.success) h + simp [overflowObs] at this + +end W5 + +/-! ## w1: `f(x)` returns `x + 1` or reverts with `Panic(0x11)` -/ + +namespace W1 + +open SolidCore.Refinement.Corpus.W1 + +def fn : Fn := ⟨Bytecode.W1.Main.fSelector, [(.uint 256)]⟩ + +def inc : Call := callAt fn.sel [41] [] + +def overflow : Call := callAt fn.sel [2 ^ 256 - 1] [] + +def incObs : Observable := ⟨true, word 42, [], fun _ => 0⟩ + +def overflowObs : Observable := ⟨false, panic 0x11, [], fun _ => 0⟩ + +theorem inc_pin (obs : Observable) (h : Verify.W1.post inc obs) : obs = incObs := by + have hw : argWords 1 inc = [41] := argWords_callAt fn.sel [41] [] (by decide) + simp only [Verify.W1.post, hw] at h + obtain ⟨⟨hs, ho⟩, hl, hst⟩ := (by simpa using h : + (obs.success = true ∧ obs.output = word 42) ∧ obs.logs = [] ∧ ∀ slot, obs.storage slot = 0) + exact obs_eq hs ho hl hst + +theorem overflow_pin (obs : Observable) (h : Verify.W1.post overflow obs) : obs = overflowObs := by + have hw : argWords 1 overflow = [2 ^ 256 - 1] := argWords_callAt fn.sel [2 ^ 256 - 1] [] (by decide) + simp only [Verify.W1.post, hw] at h + obtain ⟨⟨hs, ho⟩, hl, hst⟩ := (by simpa using h : + (obs.success = false ∧ obs.output = panic 0x11) ∧ obs.logs = [] ∧ + ∀ slot, obs.storage slot = 0) + exact obs_eq hs ho hl hst + +theorem inc_scope : Verify.W1.scope inc := + fullScope_callAt (fn := fn) (List.mem_singleton_self _) [41] rfl (by decide) [] + +theorem overflow_scope : Verify.W1.scope overflow := + fullScope_callAt (fn := fn) (List.mem_singleton_self _) [2 ^ 256 - 1] rfl (by decide) [] + +theorem inc_target : Target.run code inc = some incObs := + run_of_pinned Headline.w1 inc_scope trivial inc_pin + +theorem overflow_target : Target.run code overflow = some overflowObs := + run_of_pinned Headline.w1 overflow_scope trivial overflow_pin + +theorem source : ∃ c, contract? = .ok c ∧ + Source.run fuel c inc = some incObs ∧ Source.run fuel c overflow = some overflowObs := by + obtain ⟨c, hc, h⟩ := Verify.W1.satisfies + exact ⟨c, hc, run_of_pinned h inc_scope trivial inc_pin, + run_of_pinned h overflow_scope trivial overflow_pin⟩ + +theorem rejects : Target.run code inc ≠ some ⟨true, word 43, [], fun _ => 0⟩ := by + rw [inc_target] + intro h + have := congrArg (Option.map fun o : Observable => o.output) h + simp only [incObs, Option.map_some, Option.some.injEq] at this + exact absurd this (by decide) + +end W1 + +/-! ## w4: `set(v)` stores `v` in slot 0 -/ + +namespace W4 + +open SolidCore.Refinement.Corpus.W4 + +def fn : Fn := ⟨Bytecode.W4.Main.setSelector, [(.uint 256)]⟩ + +def set9 : Call := callAt fn.sel [9] [] + +def set9Obs : Observable := ⟨true, [], [], fun slot => if slot % 2 ^ 256 = 0 then 9 else 0⟩ + +theorem set9_pin (obs : Observable) (h : Verify.W4.post set9 obs) : obs = set9Obs := by + have hw : argWords 1 set9 = [9] := argWords_callAt fn.sel [9] [] (by decide) + simp only [Verify.W4.post, hw] at h + obtain ⟨hs, ho, hl, hst⟩ := (by simpa using h : + obs.success = true ∧ obs.output = [] ∧ obs.logs = [] ∧ + ∀ slot, obs.storage slot = if slot % 2 ^ 256 = 0 then 9 else 0) + exact obs_eq hs ho hl hst + +theorem set9_scope : Verify.W4.scope set9 := + fullScope_callAt (fn := fn) (List.mem_singleton_self _) [9] rfl (by decide) [] + +/-- solar's bytecode leaves `9` in slot 0 on `set(9)`, read off the headline. -/ +theorem set9_target : Target.run code set9 = some set9Obs := + run_of_pinned Headline.w4 set9_scope trivial set9_pin + +theorem source : ∃ c, contract? = .ok c ∧ Source.run fuel c set9 = some set9Obs := by + obtain ⟨c, hc, h⟩ := Verify.W4.satisfies + exact ⟨c, hc, run_of_pinned h set9_scope trivial set9_pin⟩ + +/-- It does not leave slot 0 holding `8`. -/ +theorem rejects : Target.run code set9 ≠ some ⟨true, [], [], fun slot => if slot = 0 then 8 else 0⟩ := by + rw [set9_target] + intro h + have := congrArg (Option.map fun o => o.storage 0) h + simp [set9Obs] at this + +end W4 + +/-! ## c1: `f(x)` on a `uint8` returns `3 * x + 1` or reverts with `Panic(0x11)` -/ + +namespace C1 + +open SolidCore.Refinement.Corpus.C1 + +def two : Call := callAt Bytecode.C1.Main.fSelector [2] [] + +def big : Call := callAt Bytecode.C1.Main.fSelector [85] [] + +def twoObs : Observable := ⟨true, word 7, [], fun _ => 0⟩ + +def bigObs : Observable := ⟨false, panic 0x11, [], fun _ => 0⟩ + +theorem mem_calls {x : Nat} (hx : x < 2 ^ 8) : + callAt Bytecode.C1.Main.fSelector [x] [] ∈ calls fns [[]] := by + unfold calls + refine List.mem_flatMap.mpr ⟨[], List.mem_singleton_self _, ?_⟩ + refine List.mem_flatMap.mpr ⟨⟨Bytecode.C1.Main.fSelector, [.uint 8]⟩, List.mem_singleton_self _, ?_⟩ + refine List.mem_map.mpr ⟨[x], ?_, rfl⟩ + show [x] ∈ (Param.uint 8).values.flatMap fun v => ([[]] : List (List Nat)).map (v :: ·) + exact List.mem_flatMap.mpr ⟨x, List.mem_range.mpr hx, List.mem_singleton_self _⟩ + +theorem two_pin (obs : Observable) (h : Verify.C1.post two obs) : obs = twoObs := by + have hw : argWords 1 two = [2] := argWords_callAt Bytecode.C1.Main.fSelector [2] [] (by decide) + simp only [Verify.C1.post, hw] at h + obtain ⟨⟨hs, ho⟩, -, hl, hst⟩ := (by simpa using h : + (obs.success = true ∧ obs.output = word 7) ∧ True ∧ obs.logs = [] ∧ + ∀ slot, obs.storage slot = 0) + exact obs_eq hs ho hl hst + +theorem big_pin (obs : Observable) (h : Verify.C1.post big obs) : obs = bigObs := by + have hw : argWords 1 big = [85] := argWords_callAt Bytecode.C1.Main.fSelector [85] [] (by decide) + simp only [Verify.C1.post, hw] at h + obtain ⟨-, ⟨hs, ho⟩, hl, hst⟩ := (by simpa using h : + True ∧ (obs.success = false ∧ obs.output = panic 0x11) ∧ obs.logs = [] ∧ + ∀ slot, obs.storage slot = 0) + exact obs_eq hs ho hl hst + +theorem two_target : Target.run code two = some twoObs := + run_of_pinned Headline.c1 (mem_calls (by decide)) trivial two_pin + +theorem big_target : Target.run code big = some bigObs := + run_of_pinned Headline.c1 (mem_calls (by decide)) trivial big_pin + +theorem source : ∃ c, contract? = .ok c ∧ + Source.run fuel c two = some twoObs ∧ Source.run fuel c big = some bigObs := by + obtain ⟨c, hc, -, h⟩ := Verify.C1.satisfies + exact ⟨c, hc, run_of_pinned h (mem_calls (by decide)) trivial two_pin, + run_of_pinned h (mem_calls (by decide)) trivial big_pin⟩ + +theorem rejects : Target.run code big ≠ some ⟨true, word 256, [], fun _ => 0⟩ := by + rw [big_target] + intro h + have := congrArg (Option.map fun o : Observable => o.success) h + simp [bigObs] at this + +end C1 + +/-! ## c4: `add(x)` updates two `uint8` fields packed in slot 0 -/ + +namespace C4 + +open SolidCore.Refinement.Corpus.C4 + +def fn : Fn := ⟨Bytecode.C4.Main.addSelector, [(.uint 8)]⟩ + +def add3 : Call := callAt fn.sel [3] Verify.C4.deployed + +/-- A dirty word for a `uint8` parameter. -/ +def dirty : Call := callAt fn.sel [256] Verify.C4.deployed + +def add3Obs : Observable := + ⟨true, word 3, [], fun slot => if slot % 2 ^ 256 = 0 then 3 + (7 ^^^ 3) * 2 ^ 8 else 0⟩ + +def dirtyObs : Observable := ⟨false, [], [], fun slot => slotValue Verify.C4.deployed slot⟩ + +theorem add3_pin (obs : Observable) (h : Verify.C4.post add3 obs) : obs = add3Obs := by + have hw : argWords 1 add3 = [3] := argWords_callAt fn.sel [3] Verify.C4.deployed (by decide) + simp only [Verify.C4.post, hw] at h + obtain ⟨⟨hs, ho, hst⟩, hl⟩ := (by simpa using h : + (obs.success = true ∧ obs.output = word 3 ∧ + ∀ slot, obs.storage slot = if slot % 2 ^ 256 = 0 then 3 + (7 ^^^ 3) * 2 ^ 8 else 0) ∧ + obs.logs = []) + exact obs_eq hs ho hl hst + +theorem dirty_pin (obs : Observable) (h : Verify.C4.post dirty obs) : obs = dirtyObs := by + have hw : argWords 1 dirty = [256] := argWords_callAt fn.sel [256] Verify.C4.deployed (by decide) + simp only [Verify.C4.post, hw] at h + obtain ⟨⟨hs, ho, hst⟩, hl⟩ := (by simpa using h : + (obs.success = false ∧ obs.output = [] ∧ + ∀ slot, obs.storage slot = slotValue Verify.C4.deployed slot) ∧ obs.logs = []) + exact obs_eq hs ho hl hst + +theorem add3_scope : Verify.C4.scope add3 := + fullScope_callAt (fn := fn) (List.mem_singleton_self _) [3] rfl (by decide) _ + +theorem dirty_scope : Verify.C4.scope dirty := + fullScope_callAt (fn := fn) (List.mem_singleton_self _) [256] rfl (by decide) _ + +/-- solar's bytecode returns `3` and packs `v = 3`, `w = 7 ^ 3` into slot 0 on `add(3)`. -/ +theorem add3_target : Target.run code add3 = some add3Obs := + run_of_pinned Headline.c4 add3_scope trivial add3_pin + +/-- It reverts with empty data and keeps the storage on a dirty word. -/ +theorem dirty_target : Target.run code dirty = some dirtyObs := + run_of_pinned Headline.c4 dirty_scope trivial dirty_pin + +theorem source : ∃ c, contract? = .ok c ∧ + Source.run fuel c add3 = some add3Obs ∧ Source.run fuel c dirty = some dirtyObs := by + obtain ⟨c, hc, -, h⟩ := Verify.C4.satisfies + exact ⟨c, hc, run_of_pinned h add3_scope trivial add3_pin, + run_of_pinned h dirty_scope trivial dirty_pin⟩ + +/-- It does not leave `w` unchanged. -/ +theorem rejects : Target.run code add3 ≠ + some ⟨true, word 3, [], fun slot => if slot % 2 ^ 256 = 0 then 3 + 7 * 2 ^ 8 else 0⟩ := by + rw [add3_target] + intro h + have := congrArg (Option.map fun o => o.storage 0) h + simp [add3Obs] at this + +end C4 + + +/-- +info: 'SolidCore.Refinement.NonVacuity.W5.add_target' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms W5.add_target + +/-- +info: 'SolidCore.Refinement.NonVacuity.W5.rejects' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms W5.rejects + +/-- +info: 'SolidCore.Refinement.NonVacuity.C4.dirty_target' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms C4.dirty_target + +/-- +info: 'SolidCore.Refinement.NonVacuity.C1.source' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms C1.source + +end SolidCore.Refinement.NonVacuity diff --git a/SolidCore/Refinement/Seq/Check.lean b/SolidCore/Refinement/Seq/Check.lean new file mode 100644 index 00000000..bd333389 --- /dev/null +++ b/SolidCore/Refinement/Seq/Check.lean @@ -0,0 +1,277 @@ +import SolidCore.Refinement.Sequence +import SolidCore.Refinement.Dirty.Source + +/-! +# Checking sequence refinement on a certificate of reachable storages + +`Sequence.lean` lifts single calls to sequences over a set of storages closed +under the calls. This module makes that set a finite, checkable certificate for +the corpus's ABI scope. + +* `canon keys base obs` is the `next` of the corpus: the slots of `keys`, in + order, whose final value is nonzero or that the constructor wrote (`base`), + with their values. With `keys` sorted it is a canonical list, so equal + storages give equal lists and a set of storages is a list of lists. +* `exactOn zero f σ` checks `slotValue σ = f` on finitely many slots: those `σ` + names and those `zero` names, off which `f` is zero (`slotValue_eq_of_exactOn`). +* `stepCheck` runs one call: both semantics agree (`agreeAt`, `agree` with + SolidCore's result already computed, so each check runs SolidCore once), the + next storage is exact on SolidCore's final storage when a later call reads it, + and `target` accepts it. +* A certificate is a list of levels of storages. `items` lists every clean call + from every storage of every level, `states` every storage with its level. + `target` accepts what a step from level `d` must reach: for a closed + certificate any storage of any level, otherwise one of the levels up to the + next, and anything from the last level. +* `refinesSeq_of_cert` (closed) and `refinesSeqUpTo_of_cert` (as many messages as + there are levels) turn a passing check into `RefinesSeq` and `RefinesSeqUpTo` + on `fullMsg fns`: every message of a corpus function on any argument words + below `2 ^ 256`, with no value. Dirty argument words reuse `Dirty.run_dirty` + and `Dirty.TargetDirty`, which hold from every storage, so the check of a + dirty message is one cheap `dirtyOk` per storage: it keeps the storage, which + must be exact and reach the target. +-/ + +namespace SolidCore.Refinement.Seq + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.State +open SolidCore.Solidity SolidCore.Refinement.Abi + +/-! ## The next storage and its exactness -/ + +/-- The keys `keys` as words, sorted and without duplicates. -/ +def normKeys (keys : List Nat) : List Nat := + ((keys.map (· % wordSize)).mergeSort (· ≤ ·)).eraseDups + +/-- The slots of `keys` whose final value in `obs` is nonzero or that `base` names, +in the order of `keys`, with their final values. -/ +def canon (keys base : List Nat) (obs : Observable) : List (Nat × Nat) := + keys.filterMap fun k => + let v := obs.storage k + if v != 0 || base.contains k then some (k, v) else none + +/-- Whether `slotValue σ` and `f` agree on every slot `σ` or `zero` names. -/ +def exactOn (zero : List Nat) (f : Nat → Nat) (σ : List (Nat × Nat)) : Bool := + (σ.map (·.1 % wordSize) ++ zero).all fun k => slotValue σ k == f k + +/-- A storage function read modulo `2 ^ 256` and zero off `zero` is the one `σ` +reads as, once `exactOn` accepts them. -/ +theorem slotValue_eq_of_exactOn {zero : List Nat} {f : Nat → Nat} {σ : List (Nat × Nat)} + (fp : ∀ s, f s = f (s % wordSize)) (fz : ∀ s, s % wordSize ∉ zero → f s = 0) + (h : exactOn zero f σ = true) : slotValue σ = f := + storage_ext (σ.map (·.1 % wordSize) ++ zero) (slotValue_mod σ) fp + (fun s hs => slotValue_of_not_mem { calldata := .empty, callvalue := 0, storage := σ } s + fun m => hs (List.mem_append_left _ m)) + (fun s hs => fz s fun m => hs (List.mem_append_right _ m)) + (fun k hk => by simpa using List.all_eq_true.mp h k hk) + +/-! ## One call -/ + +/-- `agree` on `call`, given SolidCore's result `r` of it. -/ +def agreeAt (code : ByteArray) (call : Call) (r : TypeCheck.CoreAbiCallResult) : Bool := + match processMessage (Meter := Nat) .fusaka (Target.message code call) + (Target.preState code call) Substate.empty, Target.run code call with + | .ok ⟨evm, _⟩, some tgt => + let src := Source.observe call r + src.success == tgt.success && src.output == tgt.output && src.logs == tgt.logs && + (sourceKeys r.state ++ targetKeys evm.state (Target.address selfAddress) ++ + callKeys call).all fun k => src.storage k == tgt.storage k + | _, _ => false + +theorem agree_of_agreeAt {fuel : Nat} {c : TypeCheck.CheckedContract} {code : ByteArray} + {call : Call} {r : TypeCheck.CoreAbiCallResult} (hr : Source.result? fuel c call = some r) + (h : agreeAt code call r = true) : agree fuel c code call = true := by + unfold agreeAt at h + unfold agree + rw [hr] + split at h + next evm sub tgt hpm htgt => simp only [hpm, htgt]; exact h + next => exact absurd h (by simp) + +/-- Whether `call` refines, its next storage under `next` is exact when `exact` asks +for it, and `target` accepts that storage. SolidCore runs once. -/ +def stepCheck (fuel : Nat) (c : TypeCheck.CheckedContract) (code : ByteArray) + (next : Observable → List (Nat × Nat)) (exact : Bool) (target : List (Nat × Nat) → Bool) + (call : Call) : Bool := + match Source.result? fuel c call with + | some r => + let obs := Source.observe call r + agreeAt code call r && + (!exact || exactOn (sourceKeys r.state ++ callKeys call) obs.storage (next obs)) && + target (next obs) + | none => false + +theorem stepCheck_sound {fuel : Nat} {c : TypeCheck.CheckedContract} {code : ByteArray} + {next : Observable → List (Nat × Nat)} {exact : Bool} {target : List (Nat × Nat) → Bool} + {call : Call} (h : stepCheck fuel c code next exact target call = true) : + ∃ obs, Source.run fuel c call = some obs ∧ Target.run code call = some obs ∧ + (exact = true → Exact next obs) ∧ target (next obs) = true := by + unfold stepCheck at h + split at h + next r hr => + simp only [Bool.and_eq_true] at h + obtain ⟨⟨ha, hex⟩, ht⟩ := h + obtain ⟨obs, hs, htg⟩ := agree_sound (agree_of_agreeAt hr ha) + have hobs : obs = Source.observe call r := by + simp only [Source.run, hr, Option.map_some, Option.some.injEq] at hs + exact hs.symm + subst hobs + refine ⟨_, hs, htg, fun he => ?_, ht⟩ + simp only [he, Bool.not_true, Bool.false_or] at hex + apply slotValue_eq_of_exactOn _ _ hex + · intro s + simp only [Source.observe] + split + · exact loadSlot_mod _ s + · exact slotValue_mod _ s + · intro s hs' + simp only [Source.observe] + split + · exact loadSlot_of_not_mem _ _ fun m => hs' (List.mem_append_left _ m) + · exact slotValue_of_not_mem _ _ fun m => hs' (List.mem_append_right _ m) + next => exact absurd h (by simp) + +/-! ## Certificates -/ + +/-- What a step from level `d` of `levels` must reach: any storage of any level when +the certificate is closed; otherwise one of a level up to `d + 1`, or anything from the +last level. -/ +def target (levels : List (List (List (Nat × Nat)))) (closed : Bool) (d : Nat) + (σ : List (Nat × Nat)) : Bool := + if closed then levels.any (·.contains σ) + else levels.length ≤ d + 1 || (levels.take (d + 2)).any (·.contains σ) + +/-- Every storage of `levels` with its level. -/ +def states (levels : List (List (List (Nat × Nat)))) : List (Nat × List (Nat × Nat)) := + (List.range levels.length).flatMap fun d => (levels.getD d []).map (d, ·) + +/-- Every clean call of a function of `fns` from every storage of `levels`, with the +storage's level. -/ +def items (fns : List Fn) (levels : List (List (List (Nat × Nat)))) : List (Nat × Call) := + (states levels).flatMap fun ds => (calls fns [ds.2]).map (ds.1, ·) + +/-- Whether a step from level `d` must carry its storage exactly: always in a closed +certificate, otherwise unless it is from the last level, whose next storage no call +of the sequences it covers reads. -/ +def needExact (levels : List (List (List (Nat × Nat)))) (closed : Bool) (d : Nat) : Bool := + closed || d + 1 < levels.length + +/-- The check of one clean call of the certificate. -/ +def itemOk (fuel : Nat) (c : TypeCheck.CheckedContract) (code : ByteArray) + (next : Observable → List (Nat × Nat)) (levels : List (List (List (Nat × Nat)))) + (closed : Bool) (item : Nat × Call) : Bool := + stepCheck fuel c code next (needExact levels closed item.1) (target levels closed item.1) + item.2 + +/-- The check of every dirty call from one storage of the certificate: such a call +keeps the storage, which must be exact when `needExact` asks and reach the target. -/ +def dirtyOk (next : Observable → List (Nat × Nat)) (levels : List (List (List (Nat × Nat)))) + (closed : Bool) (ds : Nat × List (Nat × Nat)) : Bool := + (!needExact levels closed ds.1 || + exactOn (ds.2.map (·.1 % wordSize)) (rejected ds.2).storage (next (rejected ds.2))) && + target levels closed ds.1 (next (rejected ds.2)) + +/-- Every message of a function of `fns` on any argument words below `2 ^ 256`, with +no value. -/ +def fullMsg (fns : List Fn) (m : Msg) : Prop := + ∃ fn ∈ fns, ∃ args : List Nat, args.length = fn.params.length ∧ (∀ a ∈ args, a < 2 ^ 256) ∧ + m = { calldata := calldata fn.sel args, callvalue := 0 } + +theorem mem_states {levels : List (List (List (Nat × Nat)))} {d : Nat} + {σ : List (Nat × Nat)} (hd : d < levels.length) (hσ : σ ∈ levels.getD d []) : + (d, σ) ∈ states levels := by + simp only [states, List.mem_flatMap, List.mem_range, List.mem_map] + exact ⟨d, hd, σ, hσ, rfl⟩ + +/-- A passing certificate check gives every message of `fullMsg fns` from a storage of +level `d`: both sides agree, the next storage is exact, and `target` accepts it. -/ +theorem step_of_cert {fuel : Nat} {c : TypeCheck.CheckedContract} {code : ByteArray} + {s0 : List (Nat × Nat)} {fns : List Fn} {next : Observable → List (Nat × Nat)} + {levels : List (List (List (Nat × Nat)))} {closed : Bool} + (hdep : deployedStorage fuel c = some s0) + (hitems : (items fns levels).all (itemOk fuel c code next levels closed) = true) + (hdirty : (states levels).all (dirtyOk next levels closed) = true) + (hshape : fns.all (Dirty.fnShapeOk c) = true) (htgt : Dirty.TargetDirty code fns) + {d : Nat} {σ : List (Nat × Nat)} (hσ : (d, σ) ∈ states levels) {m : Msg} + (hm : fullMsg fns m) : + ∃ obs, Source.run fuel c (m.call σ) = some obs ∧ Target.run code (m.call σ) = some obs ∧ + (needExact levels closed d = true → Exact next obs) ∧ + target levels closed d (next obs) = true := by + obtain ⟨fn, hfn, args, hlen, hargs, rfl⟩ := hm + have hcall : Msg.call { calldata := calldata fn.sel args, callvalue := 0 } σ = + { calldata := calldata fn.sel args, callvalue := 0, storage := σ } := rfl + rw [hcall] + by_cases hd : Dirty fn.params args + · have hok := List.all_eq_true.mp hdirty _ hσ + simp only [dirtyOk, Bool.and_eq_true] at hok + refine ⟨rejected σ, + Dirty.run_dirty hdep fn (List.all_eq_true.mp hshape fn hfn) σ args hlen hargs hd, + htgt fn hfn σ args hlen hargs hd, fun he => ?_, hok.2⟩ + have h1 := hok.1 + simp only [he, Bool.not_true, Bool.false_or] at h1 + exact slotValue_eq_of_exactOn (slotValue_mod σ) + (fun s hs => slotValue_of_not_mem { calldata := .empty, callvalue := 0, storage := σ } s hs) + h1 + · have hmem := mem_calls (s := σ) hfn hlen hargs fun i hp ha => by + cases h : fn.params[i].clean args[i] + · exact absurd ⟨i, hp, ha, h⟩ hd + · rfl + have hit : (d, { calldata := calldata fn.sel args, callvalue := 0, storage := σ }) ∈ + items fns levels := by + simp only [items, List.mem_flatMap, List.mem_map] + exact ⟨(d, σ), hσ, _, hmem, rfl⟩ + exact stepCheck_sound (List.all_eq_true.mp hitems _ hit) + +/-- A passing check of a closed certificate whose levels hold the deployed storage gives +every finite sequence of messages of `fullMsg fns` from it. -/ +theorem refinesSeq_of_cert {fuel : Nat} {c : TypeCheck.CheckedContract} {code : ByteArray} + {s0 : List (Nat × Nat)} {fns : List Fn} {next : Observable → List (Nat × Nat)} + {levels : List (List (List (Nat × Nat)))} + (hdep : deployedStorage fuel c = some s0) (h0 : ∃ L ∈ levels, s0 ∈ L) + (hitems : (items fns levels).all (itemOk fuel c code next levels true) = true) + (hdirty : (states levels).all (dirtyOk next levels true) = true) + (hshape : fns.all (Dirty.fnShapeOk c) = true) (htgt : Dirty.TargetDirty code fns) : + RefinesSeq fuel c code next s0 (fullMsg fns) := fun _ => + refinesSeqUpTo_of_levels (fun _ σ => ∃ L ∈ levels, σ ∈ L) h0 + fun _ _ σ ⟨L, hL, hσ⟩ m hm => by + obtain ⟨d, hd, rfl⟩ := List.getElem_of_mem hL + have hs : (d, σ) ∈ states levels := + mem_states hd (by simpa [List.getD_eq_getElem?_getD, hd] using hσ) + obtain ⟨obs, h1, h2, h3, h4⟩ := step_of_cert hdep hitems hdirty hshape htgt hs hm + simp only [target, ite_true, List.any_eq_true, List.contains_iff_mem] at h4 + exact ⟨obs, h1, h2, fun _ => h3 (by simp [needExact]), h4⟩ + +/-- A passing check of an open certificate whose first level holds the deployed storage +gives every sequence of at most as many messages of `fullMsg fns` as it has levels. -/ +theorem refinesSeqUpTo_of_cert {fuel : Nat} {c : TypeCheck.CheckedContract} {code : ByteArray} + {s0 : List (Nat × Nat)} {fns : List Fn} {next : Observable → List (Nat × Nat)} + {levels : List (List (List (Nat × Nat)))} + (hdep : deployedStorage fuel c = some s0) (h0 : s0 ∈ levels.getD 0 []) + (hitems : (items fns levels).all (itemOk fuel c code next levels false) = true) + (hdirty : (states levels).all (dirtyOk next levels false) = true) + (hshape : fns.all (Dirty.fnShapeOk c) = true) (htgt : Dirty.TargetDirty code fns) : + RefinesSeqUpTo fuel c code next s0 (fullMsg fns) levels.length := + refinesSeqUpTo_of_levels + (fun d σ => levels.length ≤ d ∨ ∃ j ≤ d, j < levels.length ∧ σ ∈ levels.getD j []) + (.inr ⟨0, Nat.le_refl 0, by + cases levels with + | nil => simp at h0 + | cons _ _ => simp, h0⟩) + fun d hd σ hS m hm => by + obtain ⟨j, hj, hjl, hσ⟩ := hS.resolve_left (by omega) + obtain ⟨obs, h1, h2, h3, h4⟩ := + step_of_cert hdep hitems hdirty hshape htgt (mem_states hjl hσ) hm + have h3' : d + 1 < levels.length → Exact next obs := fun hn => + h3 (by simp only [needExact, Bool.false_or, decide_eq_true_eq]; omega) + refine ⟨obs, h1, h2, h3', ?_⟩ + simp only [target, Bool.false_eq_true, ite_false, Bool.or_eq_true, decide_eq_true_eq, + List.any_eq_true, List.contains_iff_mem] at h4 + rcases h4 with h4 | ⟨L, hL, hn⟩ + · exact .inl (by omega) + · obtain ⟨i, hi, rfl⟩ := List.getElem_of_mem hL + simp only [List.length_take] at hi + refine .inr ⟨i, by omega, by omega, ?_⟩ + rw [List.getElem_take] at hn + simpa [List.getD_eq_getElem?_getD, show i < levels.length by omega] using hn + +end SolidCore.Refinement.Seq diff --git a/SolidCore/Refinement/Seq/Corpus.lean b/SolidCore/Refinement/Seq/Corpus.lean new file mode 100644 index 00000000..806e74ed --- /dev/null +++ b/SolidCore/Refinement/Seq/Corpus.lean @@ -0,0 +1,8 @@ +-- Generated by scripts/refinement/gen_proof.py. Do not edit. + +import SolidCore.Refinement.Sequence +import SolidCore.Refinement.Corpus.C1.Seq +import SolidCore.Refinement.Corpus.C4.Seq + +/-! The sequence refinement proofs of every contract in scripts/refinement/corpus/ +that has one: `Corpus//Seq.lean`. -/ diff --git a/SolidCore/Refinement/Seq/Explore.lean b/SolidCore/Refinement/Seq/Explore.lean new file mode 100644 index 00000000..6e9372f4 --- /dev/null +++ b/SolidCore/Refinement/Seq/Explore.lean @@ -0,0 +1,90 @@ +import SolidCore.Refinement.Seq.Check + +/-! +# Exploring the storages a contract reaches + +`explore` computes, by breadth-first search over SolidCore alone, the storages +reachable from the deployed storage by clean calls of a contract's functions, in +the canonical form `Seq.canon` gives them, deduplicated, level by level. It +also collects every slot any reached storage writes (`Plan.keys`), the keys +`canon` then lists. + +It stops at the first of: no new storages (the closure, a closed plan), or a next +level that would push the storages past `maxStates` or the calls a check of every +level runs past `budget` (an open plan, whose levels bound the length of the +sequences it covers). `scripts/refinement/gen_proof.py` runs it once per +contract through `render` and writes its result into the generated certificate. +Nothing here is trusted: `Seq.refinesSeq_of_cert` and `Seq.refinesSeqUpTo_of_cert` +re-check the certificate against both semantics. +-/ + +namespace SolidCore.Refinement.Seq + +open SolidCore.Solidity SolidCore.Refinement.Abi + +/-- What `explore` found. -/ +structure Plan where + /-- Whether the levels are closed under every clean call. -/ + closed : Bool + /-- The storages by level, the deployed one alone at level 0. -/ + levels : List (List (List (Nat × Nat))) + /-- Every slot a reached storage holds a word for, sorted. -/ + keys : List Nat + /-- The clean calls from one storage. -/ + callsPer : Nat + +/-- The storages one clean call of `fns` from `σ` leaves, and the slots each holds a +word for. A call SolidCore does not finish gives nothing; the check refutes it. -/ +def successors (fuel : Nat) (c : TypeCheck.CheckedContract) (fns : List Fn) + (base : List Nat) (σ : List (Nat × Nat)) : List (List (Nat × Nat) × List Nat) := + (calls fns [σ]).filterMap fun call => + match Source.result? fuel c call with + | some r => + let keys := normKeys (sourceKeys r.state ++ callKeys call ++ base) + some (canon keys base (Source.observe call r), keys) + | none => none + +/-- Breadth-first search from the deployed storage `s0`, at most `rounds` levels deep. -/ +def explore (fuel : Nat) (c : TypeCheck.CheckedContract) (fns : List Fn) + (s0 : List (Nat × Nat)) (maxStates budget rounds : Nat) : Plan := Id.run do + let base := s0.map (·.1) + let per := (calls fns [s0]).length + let cap := min maxStates (budget / max per 1) + let mut seen : Std.HashSet (List (Nat × Nat)) := Std.HashSet.emptyWithCapacity.insert s0 + let mut levels : Array (List (List (Nat × Nat))) := #[[s0]] + let mut keys : List Nat := normKeys base + let mut total := 1 + for _ in [0:rounds] do + let last := levels.back! + let mut fresh : Array (List (Nat × Nat)) := #[] + let mut over := false + let mut newKeys := keys + for σ in last do + if over then break + for (σ', ks) in successors fuel c fns base σ do + newKeys := ks ++ newKeys + if !seen.contains σ' then + seen := seen.insert σ' + fresh := fresh.push σ' + if total + fresh.size > cap then + over := true + break + if over then + return { closed := false, levels := levels.toList, keys, callsPer := per } + keys := normKeys newKeys + if fresh.isEmpty then + return { closed := true, levels := levels.toList, keys, callsPer := per } + total := total + fresh.size + levels := levels.push fresh.toList + return { closed := false, levels := levels.toList, keys, callsPer := per } + +/-- The plan as text for the generator: `closed` or `open`, the calls per storage, the +keys, then one line per level after the first, storages separated by `;` and pairs +by `,` as `slot:value`. -/ +def Plan.render (p : Plan) : String := + let pairs (σ : List (Nat × Nat)) := ",".intercalate (σ.map fun kv => s!"{kv.1}:{kv.2}") + let lines := p.levels.drop 1 |>.map fun level => ";".intercalate (level.map pairs) + "\n".intercalate ([if p.closed then "closed" else "open", toString p.callsPer, + " ".intercalate (p.keys.map toString)] ++ lines.map (s!"L {·}")) + +end SolidCore.Refinement.Seq diff --git a/SolidCore/Refinement/Sequence.lean b/SolidCore/Refinement/Sequence.lean new file mode 100644 index 00000000..60108c1c --- /dev/null +++ b/SolidCore/Refinement/Sequence.lean @@ -0,0 +1,138 @@ +import SolidCore.Refinement.Statement + +/-! +# Refinement of sequences of calls + +`Refines` is about one call from a given initial storage. A deployed contract +sees a sequence of calls, each starting from the storage the previous one left. +This module states that once and lifts single-call refinements to it. + +`Observable.storage` is a function from every slot to a word, while the next +`Call` takes its storage as a finite list of (slot, value) pairs. A sequence is +therefore run with a function `next` that turns an observable into that list, +the same on both sides. `runSeq` runs a list of messages (call data and value) +from an initial storage list, feeding `next obs` to each following call. + +`Exact next obs` says the list `next obs` reads back, slot by slot through +`slotValue`, as exactly the final storage of `obs`: under it, the next call +starts from the previous call's final storage, not an approximation of it. +`RefinesSeqUpTo` asks that every sequence of at most `n` messages of a scope +finishes on both sides with the same list of observables, each of them but the +last exact (no call reads the last one's storage list); `RefinesSeq` asks it +for every length. + +`refinesSeqUpTo_of_levels` is the lifting theorem: storages graded by depth, +the initial one at depth 0, and every step from depth `d < n` refining, landing at +depth `d + 1` and exact unless it is the `n`-th, give `RefinesSeqUpTo n`. `refinesSeq_of_closed` is the +unbounded case in terms of `Refines`: if every single call of the scope refines +from every storage of a set that contains the initial storage and is closed under +the steps, every sequence refines. + +The source side starts each call from the deployed storage overwritten by the +call's list (see `Source.result?`). A `next` that lists every slot the +constructor writes, with its current value even when that is zero, makes that +the previous final storage; the corpus's `Seq.canon` does. +-/ + +namespace SolidCore.Refinement + +/-- One call of a sequence without its initial storage, which the sequence supplies. -/ +structure Msg where + /-- The call data. -/ + calldata : ByteArray + /-- The wei sent with the call. -/ + callvalue : Nat + +/-- The call of `m` from the storage `storage`. -/ +def Msg.call (m : Msg) (storage : List (Nat × Nat)) : Call := + { calldata := m.calldata, callvalue := m.callvalue, storage } + +/-- Run the messages `ms` one after the other with `run`, the first from `σ` and each +later one from `next` of the previous observable. `none` when any run is `none`. -/ +def runSeq (run : Call → Option Observable) (next : Observable → List (Nat × Nat)) : + List (Nat × Nat) → List Msg → Option (List Observable) + | _, [] => some [] + | σ, m :: ms => + match run (m.call σ) with + | some obs => (runSeq run next (next obs) ms).map (obs :: ·) + | none => none + +/-- The storage list `next` gives for `obs` reads as exactly the final storage of `obs`. -/ +def Exact (next : Observable → List (Nat × Nat)) (obs : Observable) : Prop := + slotValue (next obs) = obs.storage + +/-- `code` implements `contract` on every sequence of at most `n` messages of `scope` +from the storage `σ0`: SolidCore with `fuel` and EthLib both finish every call and +show the same observables, and `next` carries each final storage a later call reads +exactly. -/ +def RefinesSeqUpTo (fuel : Nat) (contract : SolidCore.Solidity.TypeCheck.CheckedContract) + (code : ByteArray) (next : Observable → List (Nat × Nat)) (σ0 : List (Nat × Nat)) + (scope : Msg → Prop) (n : Nat) : Prop := + ∀ ms : List Msg, ms.length ≤ n → (∀ m ∈ ms, scope m) → + ∃ obss, runSeq (Source.run fuel contract) next σ0 ms = some obss ∧ + runSeq (Target.run code) next σ0 ms = some obss ∧ ∀ obs ∈ obss.dropLast, Exact next obs + +/-- `code` implements `contract` on every finite sequence of messages of `scope` from +the storage `σ0`. -/ +def RefinesSeq (fuel : Nat) (contract : SolidCore.Solidity.TypeCheck.CheckedContract) + (code : ByteArray) (next : Observable → List (Nat × Nat)) (σ0 : List (Nat × Nat)) + (scope : Msg → Prop) : Prop := + ∀ n, RefinesSeqUpTo fuel contract code next σ0 scope n + +/-- Storages graded by depth, with `σ0` at depth 0, on which every message of `scope` +from depth `d < n` refines, lands at depth `d + 1` and is exact unless `d + 1 = n`, +give every sequence of at most `n` messages. -/ +theorem refinesSeqUpTo_of_levels {fuel : Nat} + {contract : SolidCore.Solidity.TypeCheck.CheckedContract} {code : ByteArray} + {next : Observable → List (Nat × Nat)} {σ0 : List (Nat × Nat)} {scope : Msg → Prop} + {n : Nat} (S : Nat → List (Nat × Nat) → Prop) (h0 : S 0 σ0) + (hstep : ∀ d < n, ∀ σ, S d σ → ∀ m, scope m → + ∃ obs, Source.run fuel contract (m.call σ) = some obs ∧ + Target.run code (m.call σ) = some obs ∧ (d + 1 < n → Exact next obs) ∧ + S (d + 1) (next obs)) : + RefinesSeqUpTo fuel contract code next σ0 scope n := by + intro ms hlen hms + suffices h : ∀ (ms : List Msg) (d : Nat) (σ : List (Nat × Nat)), d + ms.length ≤ n → + S d σ → (∀ m ∈ ms, scope m) → + ∃ obss, runSeq (Source.run fuel contract) next σ ms = some obss ∧ + runSeq (Target.run code) next σ ms = some obss ∧ obss.length = ms.length ∧ + ∀ obs ∈ obss.dropLast, Exact next obs by + obtain ⟨obss, hs, ht, -, hex⟩ := h ms 0 σ0 (by omega) h0 hms + exact ⟨obss, hs, ht, hex⟩ + intro ms + induction ms with + | nil => exact fun _ _ _ _ _ => ⟨[], rfl, rfl, rfl, by simp⟩ + | cons m ms ih => + intro d σ hlen hS hms + simp only [List.length_cons] at hlen + obtain ⟨obs, hs, ht, hex, hS'⟩ := + hstep d (by omega) σ hS m (hms m List.mem_cons_self) + obtain ⟨obss, hs', ht', hl', hex'⟩ := + ih (d + 1) (next obs) (by omega) hS' fun m' hm' => hms m' (List.mem_cons_of_mem _ hm') + refine ⟨obs :: obss, ?_, ?_, by simp [hl'], ?_⟩ + · simp only [runSeq, hs, hs', Option.map_some] + · simp only [runSeq, ht, ht', Option.map_some] + · cases obss with + | nil => simp + | cons o os => + simp only [List.dropLast_cons_of_ne_nil (List.cons_ne_nil o os), List.mem_cons, + forall_eq_or_imp] + simp only [List.length_cons] at hl' + exact ⟨hex (by omega), hex'⟩ + +/-- A set of storages that holds `σ0`, on each of which every single call of `scope` +refines, and that every such call keeps exact and inside, gives every sequence. -/ +theorem refinesSeq_of_closed {fuel : Nat} + {contract : SolidCore.Solidity.TypeCheck.CheckedContract} {code : ByteArray} + {next : Observable → List (Nat × Nat)} {σ0 : List (Nat × Nat)} {scope : Msg → Prop} + (S : List (Nat × Nat) → Prop) (h0 : S σ0) + (href : ∀ σ, S σ → Refines fuel contract code fun call => ∃ m, scope m ∧ call = m.call σ) + (hnext : ∀ σ, S σ → ∀ m, scope m → ∀ obs, Target.run code (m.call σ) = some obs → + Exact next obs ∧ S (next obs)) : + RefinesSeq fuel contract code next σ0 scope := fun _ => + refinesSeqUpTo_of_levels (fun _ σ => S σ) h0 fun _ _ σ hS m hm => by + obtain ⟨obs, hs, ht⟩ := href σ hS _ ⟨m, hm, rfl⟩ + obtain ⟨hex, hS'⟩ := hnext σ hS m hm obs ht + exact ⟨obs, hs, ht, fun _ => hex, hS'⟩ + +end SolidCore.Refinement diff --git a/SolidCore/Refinement/Solar/AbiHash/Lowering.lean b/SolidCore/Refinement/Solar/AbiHash/Lowering.lean new file mode 100644 index 00000000..be3c2587 --- /dev/null +++ b/SolidCore/Refinement/Solar/AbiHash/Lowering.lean @@ -0,0 +1,284 @@ +import SolidCore.Refinement.Generic.Value +import SolidCore.Refinement.KernelCopies +import SolidCore.Refinement.KernelRfl +import SolidCore.Refinement.Source.AbiHash +import abi_hash.gen.AbiHash.Stage0 + +/-! +# abi_hash: Keccak-256 of ABI-encoded memory through the generic source stage + +scripts/refinement/mem/abi_hash.sol, + + contract AbiHash { + function hashPair(uint256 a, uint256 b) external pure returns (uint256) { + return uint256(keccak256(abi.encode(a, b))); } } + +SolidCore evaluates `keccak256(abi.encode(a, b))` on the ABI encoding of the two words, 64 +bytes; solar's first lowered MIR stores the two words at memory 0 and 32 and hashes those 64 +bytes with `keccak256`. The generic erasure reads the source expression as `WExpr.hash a b` +(`Generic.hashPair?`, `Generic.eval_hash_pair`) and the symbolic run reads the module's hash of +the two memory words as the same `WExpr.hash`, so the check compares them structurally. Both +sides are Keccak-256 of the same 64 bytes: the stage holds under every oracle whose Keccak-256 of +two words is SolidCore's (`Generic.HashOk`, part of `Generic.SourceEnvOk`), with no +injectivity or separation premise: equal inputs give equal hashes and nothing more is used. + +* `shape_eq`: `AbiHash` type checks, its core is `coreLit`, its constructor leaves no storage; +* `check_stage0`, `checkValue_stage0`: the generic check with the environment flags accepts + stage0 (`decide +kernel`), at no value and at any value; +* `check_rejects_order`, `check_rejects_size`, `check_rejects_arg`: it rejects stage0 hashing + the words in the other order, hashing only the first word, and returning the first argument; +* `lowering`, `loweringValue`: the stage from SolidCore to stage0 on every call of `hashPair`. + +No sorry, native_decide or bv_decide. +-/ + +namespace SolidCore.Refinement.Solar.AbiHash + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity SolidCore.Solidity.Source + +/-- The interpreter fuel of SolidCore's runs. -/ +def fuel : Nat := 4096 + +/-- The interpreter fuel of the symbolic run of the module: steps along each path. -/ +def mirFuel : Nat := 40 + +/-- SolidCore's checked `AbiHash`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.AbiHash.importedSourceUnit "AbiHash" + +/-- The selector of `hashPair(uint256,uint256)`. -/ +abbrev hashPairSel : Nat := 0x66d82b2b + +/-- `hashPair` and its parameters. -/ +def fnHashPair : Fn := ⟨hashPairSel, [.uint 256, .uint 256]⟩ + +/-- The external function of `AbiHash`. -/ +def fns : List Fn := [fnHashPair] + +/-- SolidCore's core contract of `AbiHash`, as the type checker leaves it. -/ +def coreLit : Contract := + { storageFields := [], + immutableFields := [], + eventDecls := [], + errorDecls := [], + functions := [{ name := "hashPair", + selector? := some 1725442859, + payable := false, + params := [{ name := "a", + ty := SolidCore.Solidity.Source.Ty.uint256, + isStorageRef := false }, + { name := "b", + ty := SolidCore.Solidity.Source.Ty.uint256, + isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256, + SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [{ name := "_ret0", + ty := SolidCore.Solidity.Source.Ty.uint256, + isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "a") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "a")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "b") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "b")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 256 + (SolidCore.Solidity.Source.Expr.keccak256 + (SolidCore.Solidity.Source.Expr.encode + (SolidCore.Solidity.Source.EncodeKind.plain) + none + [] + [SolidCore.Solidity.Source.Ty.uint256, + SolidCore.Solidity.Source.Ty.uint256] + [SolidCore.Solidity.Source.Expr.var "a", + SolidCore.Solidity.Source.Expr.var "b"])))]]], + dispatchId? := none }, + { name := "__internal_hashPair(uint256,uint256)#[SolidCore.Solidity.Ty.uint 256, SolidCore.Solidity.Ty.uint 256]", + selector? := none, + payable := false, + params := [{ name := "a", + ty := SolidCore.Solidity.Source.Ty.uint256, + isStorageRef := false }, + { name := "b", + ty := SolidCore.Solidity.Source.Ty.uint256, + isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256, + SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [{ name := "_ret0", + ty := SolidCore.Solidity.Source.Ty.uint256, + isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "a") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "a")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "b") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "b")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 256 + (SolidCore.Solidity.Source.Expr.keccak256 + (SolidCore.Solidity.Source.Expr.encode + (SolidCore.Solidity.Source.EncodeKind.plain) + none + [] + [SolidCore.Solidity.Source.Ty.uint256, + SolidCore.Solidity.Source.Ty.uint256] + [SolidCore.Solidity.Source.Expr.var "a", + SolidCore.Solidity.Source.Expr.var "b"])))]]], + dispatchId? := none }] } + +/-! ## The selector + +The type checker computes the selector by Keccak-256, which costs the kernel about 400 MB: it is +checked once, alone, and the check of the shape below reads it from a table. -/ + +/-- The selector of `hashPair(uint256,uint256)`, by Keccak-256 of its signature. -/ +def selHashPair : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "hashPair(uint256,uint256)" + +kernel_rfl selHashPair_eq selHashPair hashPairSel + +/-- `ABI.selectorFromSignature`, with `AbiHash`'s signature by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "hashPair(uint256,uint256)" then hashPairSel + else SolidCore.Solidity.Source.ABI.selectorFromSignature s + +theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + split + · next h => subst h; exact selHashPair_eq + · rfl + +/-- SolidCore's checked core of `AbiHash`, and whether its constructor leaves no storage and no +logs, when `AbiHash` type checks. -/ +def shape? : Option (Contract × Bool) := + match contract? with + | .ok c => some (c.core, Wide.deployedAt fuel c []) + | .error _ => none + +kernel_rfl shape_eq shape? (some (coreLit, true)) using selector_eq + +/-! ## The check on solar's module -/ + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for `hashPair`. -/ +theorem check_stage0 : + Generic.check fuel mirFuel coreLit SolarTV.Export.AbiHash.stage0 fns .all = true := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: `hashPair` is not payable, and stage0 reverts with empty output on a +call with a value other than 0. -/ +theorem checkValue_stage0 : + Generic.checkValue mirFuel coreLit SolarTV.Export.AbiHash.stage0 fns .all = true := by + decide +kernel + +/-! ## Mutants the check rejects -/ + +/-- stage0 with each instruction of function `i` changed by `f`. -/ +def mapFn (i : Nat) (f : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst) : + SolarTV.MIR.Lowered.Module := + { SolarTV.Export.AbiHash.stage0 with + functions := SolarTV.Export.AbiHash.stage0.functions.mapIdx fun j fn => + if j = i then { fn with blocks := fn.blocks.map fun b => { b with insts := b.insts.map f } } + else fn } + +/-- `hashPair` storing the two words in each other's place before hashing them. -/ +def swapWords : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect none .mstore [.const o, a] => + .effect none .mstore [.const (if o = 0 then 32 else if o = 32 then 0 else o), a] + | i => i + +/-- `hashPair` hashing only the first word. -/ +def shortHash : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect d .keccak256 [o, .const n] => .effect d .keccak256 [o, .const (if n = 64 then 32 else n)] + | i => i + +/-- `hashPair` returning its first argument rather than the hash. -/ +def noHash : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect (some d) .keccak256 _ => .effect (some d) .calldataload [.const 4] + | i => i + +set_option maxRecDepth 100000 in +theorem check_rejects_order : + Generic.check fuel mirFuel coreLit (mapFn 0 swapWords) fns .all = false := by + decide +kernel + +set_option maxRecDepth 100000 in +theorem check_rejects_size : + Generic.check fuel mirFuel coreLit (mapFn 0 shortHash) fns .all = false := by + decide +kernel + +set_option maxRecDepth 100000 in +theorem check_rejects_arg : + Generic.check fuel mirFuel coreLit (mapFn 0 noHash) fns .all = false := by + decide +kernel + +/-! ## The stage -/ + +/-- The checked contract has the core `coreLit`, and its constructor leaves no storage. -/ +theorem deployed_of {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core = coreLit ∧ ∃ d, Wide.DeployedAt fuel c d [] := by + have h := shape_eq + unfold shape? at h + rw [hc] at h + obtain ⟨hk, hd⟩ := Prod.mk.inj (Option.some.inj h) + exact ⟨hk, Wide.deployedAt_of hd⟩ + +/-- **The source stage of `AbiHash`**: every call of `hashPair` on any argument words, no +value, from any storage, under every oracle whose caller and Keccak-256 of two words are +SolidCore's (`Generic.SourceEnvOk`). -/ +theorem lowering (o : SolarTV.Machine.Oracle) (henv : Generic.SourceEnvOk o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.AbiHash.stage0 (fun call => ∃ σ, fullScope fns σ call) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact Generic.stageEnv o henv hd (by rw [hk]; exact check_stage0) + +/-- **The source stage of `AbiHash` at every value**. -/ +theorem loweringValue (o : SolarTV.Machine.Oracle) (henv : Generic.SourceEnvOk o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.AbiHash.stage0 (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact Generic.stageValueEnv o henv hd (by rw [hk]; exact check_stage0) + (by rw [hk]; exact checkValue_stage0) + +#print axioms shape_eq +#print axioms check_stage0 +#print axioms checkValue_stage0 +#print axioms check_rejects_order +#print axioms check_rejects_size +#print axioms check_rejects_arg +#print axioms lowering +#print axioms loweringValue + +end SolidCore.Refinement.Solar.AbiHash diff --git a/SolidCore/Refinement/Solar/Assemble.lean b/SolidCore/Refinement/Solar/Assemble.lean new file mode 100644 index 00000000..acdcb42d --- /dev/null +++ b/SolidCore/Refinement/Solar/Assemble.lean @@ -0,0 +1,915 @@ +import SolidCore.Refinement.Evm.Wide +import SolarTV.Composition +import SolarTV.Stages.AssemblyCheck +import SolidCore.Refinement.Solar.AssembleStackN + +/-! +# EVM IR to bytecode, once for every program + +solar's last backend stage lays out the final EVM IR program as assembly and assembles it to +bytecode. This file proves that stage once, for every program and every bytecode a decidable +check accepts: `stage_of_check_env` gives `Stage (evmirSem o) ethLib p code scope` on every call, +with any value, from any storage, from `check p code cert = true`, for every oracle when the +certificate says the program reads neither the caller nor a hash (`stage_of_check_all`, +`stage_of_check`), and otherwise for every oracle whose CALLER is the caller of EthLib's calls and +whose hash is EthLib's KECCAK256 (`OracleOk`, `stage_of_check_eth`). + +* `lower` is the lowering of EVM IR to assembly items, as solar's assembler lays it out: + each block is its instructions, with a label (a JUMPDEST) when the code pushes it; a jump is + a push of its label and the jump, except that a final jump to the next block is left out (the + code falls into it), so is the last block's final STOP (the code ends), and a final + `jumpi t; jump e` with `t` the next block that the certificate lists as turned is + `ISZERO; PUSH e; JUMPI`, falling into `t`. A pushed return label is a PUSH of its block's + offset and a dynamic jump is JUMP. +* `check` is the checker: the code's linear decoding is the lowered program at the layout of + the certificate (`SolarTV.Assembly.walk`, as -Zvalidate-assembly decodes it), each label is + a valid jump destination of the code by EthLib's own analysis, stack reads never pass the + entry heights of the certificate, each memory access (MSTORE, KECCAK256, LOGn, RETURN, + REVERT) has a constant offset and size (pushed, or a DUP of a pushed one) below the + certificate's memory bound, and the code is + below 2^32 bytes. Each block has a potential, a bound on the items its runs execute (the + certificate's, or by default the items from it to the end of the layout): each item takes one + unit, and a jump or a fall goes to a block whose potential is at most what is left, so a run + executes at most the first block's potential in items, and gas for 22100 per item (the most + SSTORE costs, and a bound the check puts on each hash and log) plus the memory fits in the + call's 10M. With the default potentials this is every jump going forward. +* Return labels: SolarTV's label of a block is its number where the code has its offset, so the + checker types the stack words (`Ty`): data, the same word on both sides, which every operation + that computes, stores, hashes, logs or branches on must read; a return label, which only + PUSH (from `pushLabel`), DUP, SWAP, POP and a dynamic jump touch; or unknown. The certificate + gives each block's entry types and the blocks a return label can name (`rets`); a dynamic + jump needs a return label on top and checks the jump to each of them, and every jump checks + that its stack has the types its target claims. +* The proof is a simulation of SolarTV's EVM IR semantics by EthLib's interpreter, opcode by + opcode, with EthLib's own rules for each opcode (`EthLib.Execution.Evm.Logic`), relating the two + stacks word by word at their types. SolarTV's storage is the storage of EthLib's account of + the frame throughout: SLOAD reads it and SSTORE writes it, at any price EthLib charges for a + cold or warm slot; SolarTV's logs are EthLib's, topic by topic and byte by byte. + +The fragment: PUSH, POP, DUP, SWAP, ADD, MUL, SUB, DIV, MOD, LT, GT, EQ, ISZERO, AND, OR, XOR, NOT, BYTE, +SHL, SHR, CALLDATASIZE, CALLVALUE, CALLDATALOAD, CALLER, KECCAK256, MSTORE, SLOAD, SSTORE, +LOG0 to LOG4, JUMP (static and to a return label), JUMPI, STOP, RETURN and REVERT. Anything +else (a conditional jump to a label on the stack, a jump table, ...) makes the check false. +-/ + +namespace SolidCore.Refinement.Solar.Assemble + +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts + +abbrev Instr := SolarTV.EVM.Program.Instr +abbrev Program := SolarTV.EVM.Program.Program +abbrev Word := EvmRules.Word + +/-! ## The certificate -/ + +/-- What the checker knows of a stack word: data (`some false`), the same word on both sides; a +return label (`some true`), a block number in SolarTV where the code has the block's offset; or +nothing (`none`), a word the block never reads. -/ +abbrev Ty := Option Bool + +/-- What the checker needs beside the program and the code: each block's offset in the code +(the layout), the stack height each block needs on entry, a bound on memory, the blocks whose +final branch the assembler turned around, a bound on the items each block's runs execute, which +words are return labels on each block's entry, the blocks an internal call returns to, and +whether the program reads the caller or hashes. -/ +structure Cert where + offsets : List Nat + needs : List Nat + top : Nat + /-- The blocks whose final `jumpi t; jump e`, with `t` the next block, solar's assembler lays + out turned around, as `ISZERO; PUSH e; JUMPI` falling into `t` (what it does for a `JumpI` terminator + whose then block is next; the exported program cannot tell it from a `push t; jumpi` that + the assembler keeps). -/ + turned : List Nat := [] + /-- For each block, a bound on the items any run from its entry executes (its potential), or + empty for the items from the block to the end of the layout, which bounds them when every + jump goes forward. -/ + costs : List Nat := [] + /-- For each block, what the words on top of its entry stack are (`Ty`), the rest unknown; + empty for a block that reads nothing it does not push. -/ + types : List (List Ty) := [] + /-- The blocks a pushed label names, where a dynamic jump may go: each `pushLabel` names one. -/ + rets : List Nat := [] + /-- Whether the program reads CALLER and hashes with KECCAK256, which holds only under an oracle + whose caller and hash are EthLib's (`OracleOk`). -/ + env : Bool := false + /-- Whether the program reads the block or the transaction (TIMESTAMP, NUMBER, CHAINID, + COINBASE, GASLIMIT, GASPRICE, ORIGIN), which holds only under an oracle whose reads are those of + EthLib's environment of the call (`EnvOk`). -/ + reads : Bool := false + /-- Whether the program makes STATICCALLs, which the checker cuts at (`AssembleCutSim.blockOkC`) + and only the checker of runs with calls (`AssembleCutCall`) accepts, under a runner of messages + meeting `AssembleCallCut.StaticOk`. -/ + calls : Bool := false + /-- Whether the program makes CALLs, CREATE2s and CODECOPYs, which the checker cuts at + (`AssembleCutSim.blockOkC`, with `calls`) and only the checker of runs with creations + accepts. -/ + creates : Bool := false + deriving Repr + +def Cert.offset (c : Cert) (b : Nat) : Nat := c.offsets.getD b 0 + +def Cert.need (c : Cert) (b : Nat) : Nat := c.needs.getD b 0 + +def Cert.entry (c : Cert) (b : Nat) : List Ty := c.types.getD b [] + +/-! ## Lowering EVM IR to assembly -/ + +/-- The opcode of each stack operation of the fragment. `dup` and `swap` take a `Fin 256` position, +as SolarTV's EVM IR does; only DUP1 to DUP16 and SWAP1 to SWAP16 are one-byte opcodes, so a deeper +position (DUPN and SWAPN, which take an immediate) is outside the fragment. -/ +def opByte : SolarTV.EVM.Op → Option Nat + | .add => some 0x01 | .mul => some 0x02 | .sub => some 0x03 | .div => some 0x04 + | .mod => some 0x06 | .lt => some 0x10 | .gt => some 0x11 | .slt => some 0x12 | .sgt => some 0x13 + | .eq => some 0x14 | .iszero => some 0x15 | .and => some 0x16 | .or => some 0x17 + | .xor => some 0x18 | .not => some 0x19 | .byte => some 0x1a | .shl => some 0x1b + | .shr => some 0x1c + | .calldatasize => some 0x36 | .pop => some 0x50 + | .dup i => if i.val < 16 then some (0x80 + i.val) else none + | .swap i => if i.val < 16 then some (0x90 + i.val) else none + | _ => none + +/-- The environment reads of the fragment, by the name the exporter gives each: its opcode and +the word it reads in EthLib's environment of the call (`Target.blockEnv` and `Target.txEnv`), +the oracle's answer under `EnvOk`. -/ +def envRead : String → Option (Nat × Nat) + | "origin" => some (0x32, 0x2000) + | "gasprice" => some (0x3a, 0) + | "coinbase" => some (0x41, 0) + | "timestamp" => some (0x42, 1) + | "number" => some (0x43, 1) + | "gaslimit" => some (0x45, 30000000) + | "chainid" => some (0x46, 1) + | _ => none + +/-- The assembly items of an instruction. Outside the fragment it is INVALID, which the check +rejects. -/ +def lowerInstr : Instr → List Item + | .op (.stack (.push v)) => [.push v.toNat] + | .op (.stack op) => [.op ((opByte op).getD 0xfe)] + | .op .store => [.op 0x52] + | .op .load => [.op 0x51] + | .op _ => [.op 0xfe] + | .effect .callvalue _ => [.op 0x34] + | .effect .calldataload _ => [.op 0x35] + | .effect .calldatasize _ => [.op 0x36] + | .effect .caller _ => [.op 0x33] + | .effect .address _ => [.op 0x30] + | .effect .gas _ => [.op 0x5a] + | .effect (.env name) _ => [.op (((envRead name).map Prod.fst).getD 0xfe)] + | .effect .keccak256 _ => [.op 0x20] + | .effect (.log n) _ => [.op (if n ≤ 4 then 0xa0 + n else 0xfe)] + | .effect .sload _ => [.op 0x54] + | .effect .sstore _ => [.op 0x55] + | .effect .calldatacopy _ => [.op 0x37] + | .effect .returndatasize _ => [.op 0x3d] + | .effect .returndatacopy _ => [.op 0x3e] + | .effect (.call .staticcall) _ => [.op 0xfa] + | .effect .codecopy _ => [.op 0x39] + | .effect (.call .call) _ => [.op 0xf1] + | .effect .create2 _ => [.op 0xf5] + | .effect _ _ => [.op 0xfe] + | .jump t => [.pushLabel t, .op 0x56] + | .jumpi t => [.pushLabel t, .op 0x57] + | .pushLabel t => [.pushLabel t] + | .jumpDyn => [.op 0x56] + | .jumpiDyn => [.op 0xfe] + | .jumpTable _ => [.op 0xfe] + | .stop => [.op 0x00] + | .ret => [.op 0xf3] + | .revert => [.op 0xfd] + | .invalid => [.op 0xfe] + +/-- The else block of block `b`'s final `jumpi t; jump e` when the certificate lists `b` as turned and `t` +is the next block: the code tests the condition's `ISZERO`, jumps to `e` and falls into `t`. -/ +def turnedElse (c : Cert) (b : Nat) : Instr → List Instr → Option Nat + | .jumpi t, [.jump e] => if c.turned.contains b && t == b + 1 then some e else none + | _, _ => none + +/-- Whether the assembler leaves out an instruction that ends block `b`: a jump to the next +block, which the code falls into, or the last block's STOP, where the code ends. -/ +def dropped (p : Program) (b : Nat) : Instr → List Instr → Bool + | .jump t, [] => t == b + 1 + | .stop, [] => b + 1 == p.blocks.length + | _, _ => false + +/-- The items of block `b`'s instructions, as solar's assembler lays them out: each +instruction's items, except that a final jump to the next block and the last block's final STOP +are left out and a turned final branch is `ISZERO; PUSH e; JUMPI`. -/ +def lowerInstrs (p : Program) (c : Cert) (b : Nat) : List Instr → List Item + | [] => [] + | i :: rest => + match turnedElse c b i rest with + | some e => [.op 0x15, .pushLabel e, .op 0x57] + | none => if dropped p b i rest then [] else lowerInstr i ++ lowerInstrs p c b rest + +/-- The items of the blocks' instructions from block `b`, without labels. -/ +def bodies (p : Program) (c : Cert) : Nat → List (List Instr) → List Item + | _, [] => [] + | b, instrs :: rest => lowerInstrs p c b instrs ++ bodies p c (b + 1) rest + +/-- Whether the code pushes block `b`'s label, to jump to it or to return to it, so that the +block has one. -/ +def isTarget (p : Program) (c : Cert) (b : Nat) : Bool := + (bodies p c 0 p.blocks).contains (.pushLabel b) + +/-- A block's items: its label when a jump targets it, then its instructions. -/ +def lowerBlock (p : Program) (c : Cert) (b : Nat) (instrs : List Instr) : List Item := + (if isTarget p c b then [.label b] else []) ++ lowerInstrs p c b instrs + +/-- The items of the blocks from block `b`, in layout order. -/ +def lowerFrom (p : Program) (c : Cert) : Nat → List (List Instr) → List Item + | _, [] => [] + | b, instrs :: rest => lowerBlock p c b instrs ++ lowerFrom p c (b + 1) rest + +/-- The assembly program of an EVM IR program. -/ +def lower (p : Program) (c : Cert) : List Item := lowerFrom p c 0 p.blocks + +/-! ## Stack types -/ + +/-- What the checker knows of the word at depth `i`: nothing below the words it lists. -/ +def tyAt (ty : List Ty) (i : Nat) : Ty := ty.getD i none + +/-- The top `n` words are data. -/ +def isData (ty : List Ty) (n : Nat) : Bool := (List.range n).all fun i => tyAt ty i == some false + +/-- What `known` types covers what `want` claims: each word `want` types, `known` types the +same. -/ +def tyLe (known want : List Ty) : Bool := + (List.range want.length).all fun i => tyAt want i == none || tyAt want i == tyAt known i + +/-- The types after SWAP of the top word and the word at depth `i + 1`. -/ +def tySwap (ty : List Ty) (i : Nat) : List Ty := + List.ofFn (n := max ty.length (i + 2)) fun j => + if j.val = 0 then tyAt ty (i + 1) else if j.val = i + 1 then tyAt ty 0 else tyAt ty j.val + +/-! ## The checker -/ + +/-- Block `t`'s potential: the certificate's, or the items from it to the end of the layout. -/ +def cost (p : Program) (c : Cert) (t : Nat) : Nat := + if c.costs.isEmpty then (lowerFrom p c t (p.blocks.drop t)).length else c.costs.getD t 0 + +/-- The items a block's label takes. -/ +def labelItems (p : Program) (c : Cert) (t : Nat) : Nat := if isTarget p c t then 1 else 0 + +/-- The bytes of the code. -/ +def bytesOf (code : ByteArray) : List Nat := code.data.toList.map (·.toNat) + +/-- The stack height a stack operation of the fragment needs, and the height after it, from +height `h`. -/ +def stackNeed : SolarTV.EVM.Op → Option (Nat × Int) + | .add | .mul | .sub | .div | .mod | .lt | .gt | .slt | .sgt | .eq | .and | .or | .xor | .byte + | .shl | .shr => some (2, -1) + | .iszero | .not => some (1, 0) + | .calldatasize => some (0, 1) + | .pop => some (1, -1) + | .dup i => if i.val < 16 then some (i.val + 1, 1) else none + | .swap i => if i.val < 16 then some (i.val + 2, 0) else none + | _ => none + +/-- A jump to block `t` with a stack of at least `h` words typed `ty` and potential `k` left: `t` is a +labelled block, finds the height and the types it needs, and its potential is at most `k`. -/ +def jumpOk (p : Program) (c : Cert) (t h : Nat) (ty : List Ty) (k : Nat) : Bool := + decide (t < p.blocks.length) && isTarget p c t && decide (c.need t ≤ h) && tyLe ty (c.entry t) && + decide (cost p c t ≤ k) + +/-- Block `b` falls into the next one with a stack of at least `h` words typed `ty` and potential +`k` left. -/ +def fallOk (p : Program) (c : Cert) (b h : Nat) (ty : List Ty) (k : Nat) : Bool := + (decide (p.blocks.length ≤ b + 1) || decide (c.need (b + 1) ≤ h)) && tyLe ty (c.entry (b + 1)) && + decide (cost p c (b + 1) ≤ k) + +/-- A memory range of constant offset and size within the certificate's bound. -/ +def rangeOk (c : Cert) (o s : Word) : Bool := decide (s.toNat = 0) || decide (o.toNat + s.toNat ≤ c.top) + +/-- The constants on top of the stack after DUP of the word at depth `i`, from the constants +`known` on top before it: that word, when it is one of them, on top of the constant below it. -/ +def dupKnown (known : List Word) (i : Nat) : List Word := + match known[i]? with + | some v => v :: known.take 1 + | none => [] + +/-- The check of one instruction from a stack of at least `h` words whose top words are +`known`, constants just pushed, typed `ty`, with potential `k`, and `ok` for the rest of the block: +each item takes one unit of potential, each instruction finds the words it reads, as data +where it computes with them, each memory access has constant operands within `top`, each +jump goes to a labelled block (`jumpOk`), and a dynamic jump to a return label goes to a +block the certificate lists, each of which it checks. -/ +def blockStep (p : Program) (c : Cert) (ok : Nat → List Word → List Ty → Nat → Bool) : + Nat → List Word → List Ty → Nat → Instr → Bool + | h, known, ty, k, .op (.stack op) => + match op with + | .push v => decide (1 ≤ k) && ok (h + 1) (v :: known.take 1) (some false :: ty) (k - 1) + | .dup i => decide (1 ≤ k) && decide (i.val < 16) && decide (i.val + 1 ≤ h) && + ok (h + 1) (dupKnown known i.val) (tyAt ty i.val :: ty) (k - 1) + | .swap i => decide (1 ≤ k) && decide (i.val < 16) && decide (i.val + 2 ≤ h) && + ok h [] (tySwap ty i.val) (k - 1) + | .pop => decide (1 ≤ k) && decide (1 ≤ h) && ok (h - 1) [] ty.tail (k - 1) + | op => + match stackNeed op with + | some (need, d) => decide (1 ≤ k) && decide (need ≤ h) && isData ty need && + ok (h + d).toNat [] (some false :: ty.drop need) (k - 1) + | none => false + | h, known, ty, k, .op .store => + match known with + | o :: _ => decide (1 ≤ k) && decide (2 ≤ h) && decide (o.toNat + 32 ≤ c.top) && isData ty 2 && + ok (h - 2) [] (ty.drop 2) (k - 1) + | [] => false + | h, _, ty, k, .effect .callvalue 0 => decide (1 ≤ k) && ok (h + 1) [] (some false :: ty) (k - 1) + | h, _, ty, k, .effect .calldatasize 0 => decide (1 ≤ k) && ok (h + 1) [] (some false :: ty) (k - 1) + | h, _, ty, k, .effect .caller 0 => + c.env && decide (1 ≤ k) && ok (h + 1) [] (some false :: ty) (k - 1) + | h, _, ty, k, .effect .calldataload 1 => decide (1 ≤ k) && decide (1 ≤ h) && isData ty 1 && + ok h [] (some false :: ty.drop 1) (k - 1) + | h, _, ty, k, .effect .sload 1 => decide (1 ≤ k) && decide (1 ≤ h) && isData ty 1 && + ok h [] (some false :: ty.drop 1) (k - 1) + | h, _, ty, k, .effect .sstore 2 => decide (1 ≤ k) && decide (2 ≤ h) && isData ty 2 && + ok (h - 2) [] (ty.drop 2) (k - 1) + | h, known, ty, k, .effect .keccak256 2 => + match known with + | o :: s :: _ => c.env && decide (1 ≤ k) && decide (2 ≤ h) && isData ty 2 && rangeOk c o s && + decide (keccak256Cost s ≤ 22100) && ok (h - 1) [] (some false :: ty.drop 2) (k - 1) + | _ => false + | h, known, ty, k, .effect (.log n) a => + match known with + | o :: s :: _ => decide (n ≤ 4) && decide (a = n + 2) && decide (1 ≤ k) && decide (n + 2 ≤ h) && + isData ty (n + 2) && rangeOk c o s && decide (logCost n s ≤ 22100) && + ok (h - (n + 2)) [] (ty.drop (n + 2)) (k - 1) + | _ => false + | h, _, ty, k, .jump t => decide (2 ≤ k) && jumpOk p c t h ty (k - 2) + | h, _, ty, k, .jumpi t => + decide (2 ≤ k) && decide (1 ≤ h) && isData ty 1 && jumpOk p c t (h - 1) ty.tail (k - 2) && + ok (h - 1) [] ty.tail (k - 2) + | h, _, ty, k, .pushLabel t => + decide (1 ≤ k) && c.rets.contains t && decide (t < 2 ^ 32) && ok (h + 1) [] (some true :: ty) (k - 1) + | h, _, ty, k, .jumpDyn => + decide (1 ≤ k) && decide (1 ≤ h) && tyAt ty 0 == some true && + c.rets.all fun t => jumpOk p c t (h - 1) ty.tail (k - 1) + | _, _, _, _, .stop => true + | _, known, ty, _, .ret | _, known, ty, _, .revert => + match known with + | o :: s :: _ => isData ty 2 && rangeOk c o s + | _ => false + | _, _, _, _, _ => false + +/-- The check of block `b`'s instructions as `lowerInstrs` lays them out: each instruction by +`blockStep`, a turned branch jumps to its else block and falls into the next one, a left out +jump falls into the next block, and the end of the block falls through to the next one. -/ +def blockOk (p : Program) (c : Cert) (b : Nat) : Nat → List Word → List Ty → Nat → List Instr → Bool + | h, _, ty, k, [] => fallOk p c b h ty k + | h, known, ty, k, i :: rest => + match turnedElse c b i rest with + | some e => + decide (3 ≤ k) && decide (1 ≤ h) && isData ty 1 && jumpOk p c e (h - 1) ty.tail (k - 3) && + fallOk p c b (h - 1) ty.tail (k - 3) + | none => + if dropped p b i rest then + match i with + | .stop => true + | _ => fallOk p c b h ty k + else blockStep p c (fun h known ty k => blockOk p c b h known ty k rest) h known ty k i + +/-- Every block checks from the height and the types it needs, with its potential less its +label's item. -/ +def blocksOk (p : Program) (c : Cert) : Nat → List (List Instr) → Bool + | _, [] => true + | b, instrs :: rest => + decide (labelItems p c b ≤ cost p c b) && + blockOk p c b (c.need b) [] (c.entry b) (cost p c b - labelItems p c b) instrs && + blocksOk p c (b + 1) rest + +/-- Every labelled block's offset is a valid jump destination of the code. -/ +def labelsValid (p : Program) (c : Cert) (code : ByteArray) : Bool := + (List.range p.blocks.length).all fun b => + !isTarget p c b || isValidJumpDest (validJumpDestinations code) (c.offset b) + +/-- The checker. -/ +def check (p : Program) (code : ByteArray) (c : Cert) : Bool := + (walk (bytesOf code) c.offset 0 (lower p c)).isSome && blocksOk p c 0 p.blocks && + labelsValid p c code && decide (c.need 0 = 0) && decide (c.top % 32 = 0) && + decide (cost p c 0 ≤ 1000) && decide (c.top ≤ 2 ^ 32) && + decide (22100 * cost p c 0 + memoryGasCost c.top ≤ 10000000) && decide (code.size < 2 ^ 32) + +/-! ## Decoding -/ + +theorem length_bytesOf (code : ByteArray) : (bytesOf code).length = code.size := by + unfold bytesOf + rw [List.length_map, Array.length_toList] + rfl + +theorem getElem?_bytesOf {code : ByteArray} {pc byte : Nat} + (h : (bytesOf code)[pc]? = some byte) : + ∃ hlt : pc < code.size, code[pc] = UInt8.ofNat byte := by + unfold bytesOf at h + rw [List.getElem?_map] at h + obtain ⟨u, hu, rfl⟩ := Option.map_eq_some_iff.1 h + rw [Array.getElem?_toList, Array.getElem?_eq_some_iff] at hu + obtain ⟨hlt, hu⟩ := hu + refine ⟨hlt, ?_⟩ + rw [ByteArray.getElem_eq_getElem_data, hu] + simp + +theorem byteAt_toNat (code : ByteArray) (i : Nat) : + (byteAt code i).toNat = (bytesOf code).getD i 0 := by + unfold byteAt + rw [List.getD_eq_getElem?_getD] + split + · rename_i h + have h' : i < (bytesOf code).length := by rw [length_bytesOf]; exact h + rw [List.getElem?_eq_getElem h'] + simp only [bytesOf, List.getElem_map, Array.getElem_toList, Option.getD_some] + rfl + · rename_i h + rw [List.getElem?_eq_none (by rw [length_bytesOf]; omega)] + rfl + +theorem decode_op {code : List Nat} {pc next byte : Nat} + (h : decode code pc = some (.op byte, next)) : code[pc]? = some byte ∧ next = pc + 1 := by + obtain ⟨hb, -, -, -, hn⟩ := decode_op_inv h + exact ⟨hb, hn⟩ + +theorem decode_push {code : List Nat} {pc next v : Nat} + (h : decode code pc = some (.push v, next)) : + ∃ byte, code[pc]? = some byte ∧ + ((byte = PUSH0 ∧ v = 0 ∧ next = pc + 1) ∨ + (PUSH1 ≤ byte ∧ byte ≤ PUSH32 ∧ next = pc + 1 + (byte - PUSH1 + 1) ∧ + next ≤ code.length ∧ v = bigEndian ((code.drop (pc + 1)).take (byte - PUSH1 + 1)))) := by + unfold decode at h + split at h + · cases h + · rename_i b hb + refine ⟨b, hb, ?_⟩ + by_cases h0 : b = PUSH0 + · rw [if_pos h0] at h + simp only [Option.some.injEq, Prod.mk.injEq, Instr.push.injEq] at h + exact .inl ⟨h0, h.1.symm, h.2.symm⟩ + · by_cases h1 : PUSH1 ≤ b ∧ b ≤ PUSH32 + · rw [if_neg h0, if_pos h1] at h + split at h + · simp only [Option.some.injEq, Prod.mk.injEq, Instr.push.injEq] at h + exact .inr ⟨h1.1, h1.2, h.2.symm, by omega, h.1.symm⟩ + · cases h + · rw [if_neg h0, if_neg h1] at h + repeat' split at h + all_goals simp at h + +theorem decode_pushByte : ∀ b : Fin 32, + Op.decode (UInt8.ofNat (0x60 + b.val)) = some (.push ⟨b.val + 1, by omega⟩) := by + decide + +/-- The bytes PUSHn reads are its immediate as the checker decodes it. -/ +theorem pushData_eq {code : ByteArray} {pc n : Nat} (h : pc + 1 + n ≤ code.size) : + pushData code pc n = + BitVec.ofNat 256 (bigEndian (((bytesOf code).drop (pc + 1)).take n)) := by + unfold pushData bytesToNat bigEndian + congr 1 + rw [← List.foldl_map (f := UInt8.toNat) (g := fun acc b => acc * 256 + b)] + congr 1 + apply List.ext_getElem + · simp [bufferRead, length_bytesOf]; omega + · intro i h1 h2 + simp only [bufferRead, List.getElem_map, List.getElem_range, List.getElem_take, + List.getElem_drop] + rw [byteAt_toNat, List.getD_eq_getElem?_getD, List.getElem?_eq_getElem] + · rfl + +/-! ## Memory -/ + +open SolarTV.Machine in +/-- SolarTV's memory and EthLib's agree: EthLib's size is the active words', and every byte is +the same, zero past the size on both sides. -/ +def MemRel (m : Mem) (M : ByteArray) : Prop := + M.size = 32 * m.words.toNat ∧ ∀ i, (byteAt M i).toBitVec = m.bytes i + +open SolarTV.Machine in +theorem memRel_initial : MemRel Mem.initial .empty := by + refine ⟨rfl, fun i => ?_⟩ + simp [byteAt, Mem.initial] + +theorem natToBytes_toNat (len n : Nat) : + (natToBytes len n).map (·.toNat) = (List.range len).map (fun i => (n / 256 ^ (len - 1 - i)) % 256) := by + induction len generalizing n with + | zero => rfl + | succ len ih => + rw [natToBytes_succ, List.map_append, ih, List.range_succ, List.map_append] + congr 1 + · apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [Nat.div_div_eq_div_mul, ← Nat.pow_succ'] + congr 3 + omega + · simp + +theorem byte_toNat (v : Word) (i : Nat) (hi : i < 32) : + (SolarTV.Memory.byte v i).toNat = v.toNat / 256 ^ (31 - i) % 256 := by + unfold SolarTV.Memory.byte + rw [BitVec.toNat_setWidth, BitVec.toNat_ushiftRight, Nat.shiftRight_eq_div_pow, Nat.pow_mul] + +theorem byteAt_wordBytes (v : Word) (j : Nat) (hj : j < 32) : + (byteAt (wordBytes v) j).toBitVec = SolarTV.Memory.byte v j := by + apply BitVec.eq_of_toNat_eq + rw [UInt8.toNat_toBitVec, byte_toNat v j hj, byteAt_toNat] + have h := congrArg (fun l => l.getD j 0) (natToBytes_toNat 32 v.toNat) + have hb : bytesOf (wordBytes v) = (natToBytes 32 v.toNat).map (·.toNat) := by + simp [bytesOf, wordBytes, U256.toBeBytes] + rw [hb, h, List.getD_eq_getElem?_getD, List.getElem?_map, List.getElem?_range hj] + simp only [Option.map_some, Option.getD_some] + +theorem ceil32_eq (n : Nat) : ceil32 n = 32 * ((n + 31) / 32) := by + unfold ceil32 WORD_BYTES + split <;> omega + +/-! The growth of memory for one range, as EthLib's `Logic/Region.lean` states it (that module +is not in this library's imports). -/ + +theorem extendMemory_of_le' {size : Nat} {start length : U256} + (h : start.toNat + length.toNat ≤ size) : extendMemory size [(start, length)] = ⟨0, 0⟩ := + extendMemory_eq_zero size _ fun p hp => by + rw [List.mem_singleton.mp hp] + exact .inr (ceil32_le (ceil32_mod size) (Nat.le_trans h (le_ceil32 size))) + +theorem extendMemory_zero' (size : Nat) (start : U256) : + extendMemory size [(start, 0)] = ⟨0, 0⟩ := + extendMemory_cons_zero size start [] + +theorem extendMemory_of_lt' {size : Nat} {start length : U256} (hmod : size % 32 = 0) + (hz : length ≠ 0) (h : size < start.toNat + length.toNat) : + extendMemory size [(start, length)] = + ⟨memoryGasCost (ceil32 (start.toNat + length.toNat)) - memoryGasCost size, + ceil32 (start.toNat + length.toNat) - size⟩ := by + have hup := le_ceil32 (start.toNat + length.toNat) + have hz' : ¬length = 0#256 := hz + have grows : ¬ceil32 (start.toNat + length.toNat) ≤ size := by omega + simp [extendMemory, hz', ceil32_of_mod hmod, grows] + +theorem size_memoryExtend_extendMemory' {memory : ByteArray} {start length : U256} + (hmod : memory.size % 32 = 0) (hz : length ≠ 0) : + (memoryExtend memory (extendMemory memory.size [(start, length)]).expandBy).size = + max memory.size (ceil32 (start.toNat + length.toNat)) := by + rw [size_memoryExtend] + by_cases h : memory.size < start.toNat + length.toNat + · rw [extendMemory_of_lt' hmod hz h] + have := le_ceil32 (start.toNat + length.toNat) + simp only + omega + · rw [extendMemory_of_le' (by omega)] + have := ceil32_le hmod (Nat.le_of_not_lt h) + simp only + omega + +open SolarTV.Machine in +theorem memRel_store {m : Mem} {M : ByteArray} {o v : Word} (hm : MemRel m M) + (hbound : o.toNat + 32 ≤ 2 ^ 32) : + MemRel (m.store o.toNat v) + (memoryWrite (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy) o.toNat (wordBytes v)) ∧ + (memoryWrite (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy) o.toNat + (wordBytes v)).size = max M.size (ceil32 (o.toNat + 32)) := by + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have hext := size_memoryExtend_extendMemory' (memory := M) (start := o) (length := 32) hmod + (by decide) + have h32 : (32 : U256).toNat = 32 := rfl + rw [h32] at hext + have hfit : o.toNat + (wordBytes v).size ≤ + (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy).size := by + rw [size_wordBytes, hext] + have := le_ceil32 (o.toNat + 32) + omega + have hsize : (memoryWrite (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy) o.toNat + (wordBytes v)).size = max M.size (ceil32 (o.toNat + 32)) := by + rw [size_memoryWrite_of_fit (fun _ => hfit), hext] + refine ⟨⟨?_, fun i => ?_⟩, hsize⟩ + · rw [hsize, hm.1, ceil32_eq] + unfold Mem.store Mem.expand SolarTV.Memory.grow + simp only [show (32 = 0) = False from by decide, ite_false] + have hlt : (o.toNat + 32 + 31) / 32 < 2 ^ 251 := by omega + split + · rename_i h + rw [BitVec.ult_iff_toNat_lt, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hlt] at h + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt hlt] + omega + · rename_i h + rw [BitVec.ult_iff_toNat_lt, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hlt] at h + omega + · rw [byteAt_memoryWrite hfit, byteAt_memoryExtend, size_wordBytes] + have hb : (m.store o.toNat v).bytes i = + if o.toNat ≤ i ∧ i < o.toNat + 32 then SolarTV.Memory.byte v (i - o.toNat) else m.bytes i := by + unfold Mem.store Mem.expand + simp only [show (32 = 0) = False from by decide, ite_false] + rw [hb] + split + · rename_i h + exact byteAt_wordBytes v _ (by omega) + · exact hm.2 i + +/-- A byte array is its bytes. -/ +theorem toList_map_toNat (B : ByteArray) : + B.toList.map (·.toNat) = (List.range B.size).map (fun i => (byteAt B i).toNat) := by + have e : B.toList = B.data.toList := by simp + rw [e] + apply List.ext_getElem + · simp only [List.length_map, Array.length_toList, List.length_range]; rfl + · intro i h1 h2 + simp only [List.getElem_map, List.getElem_range] + rw [byteAt_toNat, List.getD_eq_getElem?_getD] + have hi : i < (bytesOf B).length := by + rw [length_bytesOf]; simpa using h2 + rw [List.getElem?_eq_getElem hi] + simp [bytesOf] + +open SolarTV.Machine in +/-- RETURN and REVERT give the bytes SolarTV's semantics reads. -/ +theorem read_eq {m : Mem} {M : ByteArray} {o sz : Word} (hm : MemRel m M) : + (memoryReadBytes (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) o.toNat + sz.toNat).toList.map (·.toNat) = + ((m.expand o.toNat sz.toNat).read o.toNat sz.toNat).map BitVec.toNat := by + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + by_cases hz : sz = 0 + · subst hz + simp [memoryReadBytes, Mem.read] + · have hext := size_memoryExtend_extendMemory' (memory := M) (start := o) (length := sz) hmod hz + have hfit : o.toNat + sz.toNat ≤ + (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy).size := by + rw [hext]; have := le_ceil32 (o.toNat + sz.toNat); omega + rw [toList_map_toNat, size_memoryReadBytes hfit] + have hb : (m.expand o.toNat sz.toNat).bytes = m.bytes := by + unfold Mem.expand; split <;> rfl + simp only [Mem.read, hb, List.map_map] + apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [byteAt_memoryReadBytes hfit, if_pos hi, byteAt_memoryExtend, Function.comp_apply, + ← hm.2 (o.toNat + i), UInt8.toNat_toBitVec] + +/-- The growth for a range within `top` costs the price of the new size less the old one. -/ +theorem extend_cost {size top : Nat} {o sz : Word} (hmod : size % 32 = 0) (htop : top % 32 = 0) + (hle : size ≤ top) (hin : sz = 0 ∨ o.toNat + sz.toNat ≤ top) : + size + (extendMemory size [(o, sz)]).expandBy ≤ top ∧ + (extendMemory size [(o, sz)]).cost + (memoryGasCost top - + memoryGasCost (size + (extendMemory size [(o, sz)]).expandBy)) = + memoryGasCost top - memoryGasCost size := by + by_cases hz : sz = 0 + · subst hz + rw [extendMemory_zero'] + simp [hle] + · have hin : o.toNat + sz.toNat ≤ top := hin.resolve_left hz + by_cases hlt : size < o.toNat + sz.toNat + · rw [extendMemory_of_lt' hmod hz hlt] + simp only + have hc := ceil32_le htop hin + have hc' := le_ceil32 (o.toNat + sz.toNat) + have m1 := memoryGasCost_mono (show size ≤ ceil32 (o.toNat + sz.toNat) by omega) + have m2 := memoryGasCost_mono hc + refine ⟨by omega, ?_⟩ + rw [show size + (ceil32 (o.toNat + sz.toNat) - size) = ceil32 (o.toNat + sz.toNat) by omega] + omega + · rw [extendMemory_of_le' (by omega)] + simp [hle] + +/-! ## EthLib's rules for the items -/ + +section Rules + +variable {code : ByteArray} {msg : Message .fusaka} {pc gas : Nat} {M : ByteArray} + {st : State.TransactionState} {ss : Substate} + +/-- PUSH of a decoded constant, PUSH0 or PUSHn. -/ +theorem push_item {v next : Nat} {stack : List Word} + (h : decode (bytesOf code) pc = some (.push v, next)) (hgas : 3 ≤ gas) + (hstack : stack.length < 1024) : + ∃ g, gas - 3 ≤ g ∧ Hoare .fusaka (At code msg pc stack M gas st ss .empty) + (At code msg next (BitVec.ofNat 256 v :: stack) M g st ss .empty) := by + obtain ⟨byte, hb, h⟩ := decode_push h + obtain ⟨hlt, hcode⟩ := getElem?_bytesOf hb + rcases h with ⟨rfl, rfl, rfl⟩ | ⟨h1, h2, rfl, hle, rfl⟩ + · exact ⟨gas - 2, by omega, SolidCore.Refinement.Evm.Logic.push0 (by decide) hlt hcode (by omega) hstack⟩ + · have hn : byte - PUSH1 < 32 := by unfold PUSH1 PUSH32 at *; omega + have hdec := decode_pushByte ⟨byte - PUSH1, hn⟩ + have hbyte : 0x60 + (byte - PUSH1) = byte := by unfold PUSH1 at *; omega + simp only [hbyte] at hdec + refine ⟨gas - 3, le_refl _, ?_⟩ + have hle' : pc + 1 + (byte - PUSH1 + 1) ≤ code.size := by rw [← length_bytesOf]; exact hle + have := push_of_decode (fork := .fusaka) (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) hlt hcode hdec (by simp) + (pushData_eq hle') hgas hstack + simpa [Nat.add_assoc] using this + +/-- An opcode item decodes from the byte at the counter. -/ +theorem op_item {byte next : Nat} (h : decode (bytesOf code) pc = some (.op byte, next)) : + ∃ hlt : pc < code.size, code[pc] = UInt8.ofNat byte ∧ next = pc + 1 := by + obtain ⟨hb, rfl⟩ := decode_op h + obtain ⟨hlt, hcode⟩ := getElem?_bytesOf hb + exact ⟨hlt, hcode, rfl⟩ + +theorem add_agree (x y : Word) : add x y = EvmRules.Evm.add x y := rfl +theorem sub_agree (x y : Word) : sub x y = EvmRules.Evm.sub x y := rfl +theorem mul_agree (x y : Word) : mul x y = EvmRules.Evm.mul x y := rfl + +theorem div_agree (x y : Word) : div x y = EvmRules.Evm.div x y := by + unfold div EvmRules.Evm.div + by_cases h : y = 0 + · simp [h] + · rw [if_neg h] + apply BitVec.eq_of_toNat_eq + simp only [BitVec.toNat_ofNat, BitVec.toNat_udiv] + exact Nat.mod_eq_of_lt (Nat.lt_of_le_of_lt (Nat.div_le_self _ _) x.isLt) +theorem and_agree (x y : Word) : bitwiseAnd x y = EvmRules.Evm.and x y := rfl +theorem or_agree (x y : Word) : bitwiseOr x y = EvmRules.Evm.or x y := rfl +theorem xor_agree (x y : Word) : bitwiseXor x y = EvmRules.Evm.xor x y := rfl +theorem not_agree (x : Word) : bitwiseNot x = EvmRules.Evm.not x := rfl + +theorem mod_agree (x y : Word) : mod x y = EvmRules.Evm.mod x y := by + unfold mod EvmRules.Evm.mod + by_cases h : y = 0 + · simp [h] + · have hb : (y == 0) = false := by simpa using h + rw [if_neg h, hb, cond_false] + apply BitVec.eq_of_toNat_eq + simp only [BitVec.toNat_ofNat, BitVec.toNat_umod] + exact Nat.mod_eq_of_lt (Nat.lt_of_le_of_lt (Nat.mod_le _ _) x.isLt) + +theorem lt_agree (x y : Word) : lessThan x y = EvmRules.Evm.lt x y := by + unfold lessThan EvmRules.Evm.lt + by_cases h : x.toNat < y.toNat <;> simp [h, BitVec.ult] + +theorem slt_agree (x y : Word) : signedLessThan x y = EvmRules.Evm.slt x y := by + unfold signedLessThan EvmRules.Evm.slt + rw [U256.toSigned_eq_toInt, U256.toSigned_eq_toInt] + by_cases h : x.toInt < y.toInt <;> simp [h, BitVec.slt_iff_toInt_lt] + +theorem sgt_agree (x y : Word) : signedGreaterThan x y = EvmRules.Evm.sgt x y := by + unfold signedGreaterThan EvmRules.Evm.sgt + rw [U256.toSigned_eq_toInt, U256.toSigned_eq_toInt] + by_cases h : y.toInt < x.toInt <;> simp [h, BitVec.slt_iff_toInt_lt] + +theorem gt_agree (x y : Word) : greaterThan x y = EvmRules.Evm.gt x y := by + unfold greaterThan EvmRules.Evm.gt + by_cases h : y.toNat < x.toNat <;> simp [h, BitVec.ult] + +theorem eq_agree (x y : Word) : equal x y = EvmRules.Evm.eq x y := by + unfold equal EvmRules.Evm.eq + by_cases h : x = y <;> simp [h] + +theorem iszero_agree (x : Word) : isZero x = EvmRules.Evm.iszero x := by + unfold isZero EvmRules.Evm.iszero + by_cases h : x = 0 <;> simp [h] + +theorem ult_256 (x : Word) : x.ult (256 : Word) = decide (x.toNat < 256) := by + simp [BitVec.ult] + +theorem shr_agree (x y : Word) : bitwiseShr x y = EvmRules.Evm.shr x y := by + unfold bitwiseShr EvmRules.Evm.shr + rw [ult_256] + by_cases h : x.toNat < 256 <;> simp [h, BitVec.ushiftRight_eq'] + +theorem shl_agree (x y : Word) : bitwiseShl x y = EvmRules.Evm.shl x y := by + unfold bitwiseShl EvmRules.Evm.shl + rw [ult_256] + by_cases h : x.toNat < 256 <;> simp [h, BitVec.shiftLeft_eq'] + +theorem byte_agree (i v : Word) : getByte i v = EvmRules.Evm.byte i v := by + unfold getByte EvmRules.Evm.byte + by_cases h : i.toNat < 32 + · have hu : i.ult (32 : Word) = true := by simp [BitVec.ult, h] + have hs : ((31 - i) * 8 : Word).toNat = (31 - i.toNat) * 8 := by bv_omega + rw [if_neg (by omega), hu, Bool.cond_true, BitVec.ushiftRight_eq' v ((31 - i) * 8), hs] + · have hu : i.ult (32 : Word) = false := by simp [BitVec.ult]; omega + simp only [show i.toNat ≥ 32 by omega, ↓reduceIte, hu, Bool.cond_false] + +theorem instr_stack (op : Op) (run : Evm .fusaka Nat → Except EvmError (Evm .fusaka Nat)) + (h : stackOnlyStep (Meter := Nat) .fusaka op = some run) : instruction .fusaka op = some run := by + simp [instruction, h, HOrElse.hOrElse, OrElse.orElse, Option.orElse] + +set_option hygiene false in +/-- A two-operand stack operation: EthLib's rule, with its function shown to be SolarTV's. -/ +local macro "bin_rule" agree:term : tactic => `(tactic| ( + rcases stack with _ | ⟨x, _ | ⟨y, rest⟩⟩ <;> simp only [SolarTV.EVM.step, reduceCtorEq, + Option.some.injEq] at hstep + subst hstep + refine ⟨_, le_refl _, ?_⟩ + rw [← $agree x y] + exact binary hlt hcode rfl (instr_stack _ _ rfl) (Nat.le_trans (m := 3) (by decide) hgas))) + +set_option hygiene false in +/-- A one-operand stack operation. -/ +local macro "un_rule" agree:term : tactic => `(tactic| ( + rcases stack with _ | ⟨x, rest⟩ <;> simp only [SolarTV.EVM.step, reduceCtorEq, + Option.some.injEq] at hstep + subst hstep + refine ⟨_, le_refl _, ?_⟩ + rw [← $agree x] + exact unary hlt hcode rfl (instr_stack _ _ rfl) (Nat.le_trans (m := 3) (by decide) hgas))) + +/-- Whether a stack operation of the fragment costs 5 gas (MUL, DIV and MOD) rather than 3. -/ +def low : SolarTV.EVM.Op → Bool + | .mul | .div | .mod => true + | _ => false + +/-- A stack operation of the fragment other than MUL, DIV and MOD, at its opcode, does what +SolarTV's semantics does. -/ +theorem stack_rule_cheap {op : SolarTV.EVM.Op} {byte : Nat} {stack next : List Word} + {r : Word} (hm : low op = false) (hb : opByte op = some byte) (hlt : pc < code.size) + (hcode : code[pc] = UInt8.ofNat byte) + (hstep : SolarTV.EVM.step ⟨BitVec.ofNat 256 msg.data.size, r⟩ op stack = some next) + (hgas : 3 ≤ gas) (hlen : stack.length < 1024) : + ∃ g, gas - 3 ≤ g ∧ Hoare .fusaka (At code msg pc stack M gas st ss .empty) + (At code msg (pc + 1) next M g st ss .empty) := by + cases op <;> simp only [opByte, reduceCtorEq, Option.some.injEq] at hb <;> try subst hb + case mod | mul | div => simp [low] at hm + case add => bin_rule add_agree + case sub => bin_rule sub_agree + case lt => bin_rule lt_agree + case gt => bin_rule gt_agree + case slt => bin_rule slt_agree + case sgt => bin_rule sgt_agree + case eq => bin_rule eq_agree + case and => bin_rule and_agree + case or => bin_rule or_agree + case xor => bin_rule xor_agree + case byte => bin_rule byte_agree + case shl => bin_rule shl_agree + case shr => bin_rule shr_agree + case iszero => un_rule iszero_agree + case not => un_rule not_agree + case pop => + rcases stack with _ | ⟨x, rest⟩ <;> simp only [SolarTV.EVM.step, reduceCtorEq, + Option.some.injEq] at hstep + subst hstep + exact ⟨_, by omega, pop hlt hcode (by omega)⟩ + case calldatasize => + simp only [SolarTV.EVM.step, Option.some.injEq] at hstep + subst hstep + exact ⟨_, by omega, calldatasize hlt hcode (by omega) hlen⟩ + case dup i => + split at hb + · rename_i hi + simp only [Option.some.injEq] at hb + subst hb + simp only [SolarTV.EVM.step, Option.map_eq_some_iff] at hstep + obtain ⟨x, hx, rfl⟩ := hstep + exact ⟨_, le_refl _, dup (⟨i.val, hi⟩ : Fin 16) hlt hcode hx hgas hlen⟩ + · simp at hb + case swap i => + split at hb + · rename_i hi + simp only [Option.some.injEq] at hb + subst hb + rcases stack with _ | ⟨top, rest⟩ + · simp [SolarTV.EVM.step] at hstep + · simp only [SolarTV.EVM.step, Option.map_eq_some_iff] at hstep + obtain ⟨x, hx, rfl⟩ := hstep + exact ⟨_, le_refl _, swap_of_decode hlt hcode (decode_swap ⟨i.val, hi⟩) hx hgas⟩ + · simp at hb + +/-- A stack operation of the fragment, at its opcode, does what SolarTV's semantics does, for at +most 5 gas (the price of MUL, DIV and MOD; the rest cost 3). -/ +theorem stack_rule {op : SolarTV.EVM.Op} {byte : Nat} {stack next : List Word} + {r : Word} (hb : opByte op = some byte) (hlt : pc < code.size) + (hcode : code[pc] = UInt8.ofNat byte) + (hstep : SolarTV.EVM.step ⟨BitVec.ofNat 256 msg.data.size, r⟩ op stack = some next) + (hgas : 5 ≤ gas) (hlen : stack.length < 1024) : + ∃ g, gas - 5 ≤ g ∧ Hoare .fusaka (At code msg pc stack M gas st ss .empty) + (At code msg (pc + 1) next M g st ss .empty) := by + cases hm : low op + · obtain ⟨g, hg, H⟩ := stack_rule_cheap hm hb hlt hcode hstep (Nat.le_trans (by decide) hgas) hlen + exact ⟨g, by omega, H⟩ + · cases op <;> simp [low] at hm <;> simp only [opByte, Option.some.injEq] at hb <;> subst hb <;> + rcases stack with _ | ⟨x, _ | ⟨y, rest⟩⟩ <;> simp only [SolarTV.EVM.step, reduceCtorEq, + Option.some.injEq] at hstep <;> subst hstep <;> refine ⟨_, le_refl _, ?_⟩ + all_goals first + | (rw [← mul_agree x y]; exact binary hlt hcode rfl (instr_stack _ _ rfl) hgas) + | (rw [← div_agree x y]; exact binary hlt hcode rfl (instr_stack _ _ rfl) hgas) + | (rw [← mod_agree x y]; exact binary hlt hcode rfl (instr_stack _ _ rfl) hgas) + +end Rules + +/-! ## DUPN, SWAPN and EXCHANGE are outside the fragment + +The fragment runs at Fusaka, where EIP-8024's DUPN, SWAPN and EXCHANGE are no instruction +(`stackN_fusaka`), so the check refuses every `dup` and `swap` past the sixteenth word and every +`exchange`: the program solar's assembler lowers with them is not the bytecode this stage proves. -/ + +theorem blockStep_dup {p : Program} {c : Cert} {ok : Nat → List Word → List Ty → Nat → Bool} + {h : Nat} {known : List Word} {ty : List Ty} {k : Nat} {i : Fin 256} + (hc : blockStep p c ok h known ty k (.op (.stack (.dup i))) = true) : i.val < 16 := by + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hc + exact hc.1.1.2 + +theorem blockStep_swap {p : Program} {c : Cert} {ok : Nat → List Word → List Ty → Nat → Bool} + {h : Nat} {known : List Word} {ty : List Ty} {k : Nat} {i : Fin 256} + (hc : blockStep p c ok h known ty k (.op (.stack (.swap i))) = true) : i.val < 16 := by + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hc + exact hc.1.1.2 + +theorem blockStep_exchange {p : Program} {c : Cert} {ok : Nat → List Word → List Ty → Nat → Bool} + {h : Nat} {known : List Word} {ty : List Ty} {k : Nat} {n m : Fin 32} : + blockStep p c ok h known ty k (.op (.stack (.exchange n m))) = false := by + simp [blockStep, stackNeed] + +/-- The lowering never spells an instruction with an immediate: `dup` and `swap` past the +sixteenth word and `exchange` are INVALID, which the check refuses. -/ +theorem lowerInstr_no_opImm (i : Instr) (b imm : Nat) : Item.opImm b imm ∉ lowerInstr i := by + cases i <;> simp [lowerInstr] <;> split <;> simp + +end SolidCore.Refinement.Solar.Assemble diff --git a/SolidCore/Refinement/Solar/AssembleCall.lean b/SolidCore/Refinement/Solar/AssembleCall.lean new file mode 100644 index 00000000..fc0fe833 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCall.lean @@ -0,0 +1,589 @@ +import SolidCore.Refinement.Solar.AssembleCut +import EthLib.Execution.Proofs.Evm.Call.StaticMessage +import EthLib.Execution.Proofs.Evm.Logic.CallSteps + +/-! +# EVM IR to bytecode: STATICCALL at the frame's own gas + +What a STATICCALL does in a run of EthLib that succeeds, at the gas the frame has, under the runner +of messages the interpreter uses, so that the answers of a run's oracle to the call (its success, +its output and the storage after it) are what the actual callee frame gave. + +* `StaticKept`: the frame that ends a static message to code keeps the account, the storage and + the transient storage of every address. `meets_static` proves that the interpreter's runner of + messages (`processRunner`) meets it, from EthLib's `processMessage_sameOutside_static`: this is + the connection of the oracle's storage answer to the actual execution, for every callee code and + however deep its own calls go. +* `staticcall_back`: a STATICCALL in a run that succeeds had the gas for its access and the growth + of memory (a frame short of it fails, `callStep_fails_of_routes`), and the run goes on from the + frame after the call: the flag of the callee frame's success, memory with its output written to + the output range, its output as the return data, at most the gas before less the access and the + growth of memory (the callee gets less than the call costs, EIP-150), and the state the callee + left, which `StaticKept` relates to the caller's. + +Nothing is assumed of the callee's code: a STATICCALL step that does not fail has read the code of +the callee, and of its delegate for an EIP-7702 delegation (`staticcall_routes_of_ok`), so the +run's success gives the code and the route, and `staticcall_back` follows EthLib's `callKindRoute` +along it, delegated callees included. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCall + +open SolarTV SolarTV.Machine SolidCore.Refinement +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts + +/-- The frame that ends a static message to code keeps every address's account, storage and +transient storage (up to the records of reads). -/ +def StaticKept (caller : Evm .fusaka Nat) (m : Message .fusaka) (child : Evm .fusaka Nat) : Prop := + StaticMessage caller.state m → State.TransactionState.SameOutside [] caller.state child.state + +/-- **The interpreter's runner of messages keeps the state across static messages.** -/ +theorem meets_static (bound : Nat) : + Meets (bound := bound) StaticKept (processRunner .fusaka (Meter := Nat) bound) := by + refine ⟨fun caller m lt ended h hs => ?_, (meets_process .fusaka bound).aborts⟩ + unfold processRunner at h + split at h + · exact processMessage_sameOutside_static (by decide) hs h + · rename_i hnone + have := hs.2.1 + rw [hnone] at this + cases this + +/-- The price of a STATICCALL with no value: what it passes on and its access, and what it passes +on is at most the gas left after the access and the growth of memory (EIP-150). -/ +theorem staticcall_gas {asked g memc extra : Nat} (h : extra + memc ≤ g) : + (messageCallGas .fusaka 0 asked g memc extra).cost = + (messageCallGas .fusaka 0 asked g memc extra).subCall + extra ∧ + (messageCallGas .fusaka 0 asked g memc extra).subCall + extra + memc ≤ g := by + unfold messageCallGas maxMessageCallGas + simp only [ite_true, Nat.add_zero, show Fork.fusaka ≥ .tangerineWhistle by decide, h, and_self, + ite_true] + constructor + · trivial + · have := Nat.min_le_right asked (g - memc - extra - (g - memc - extra) / 64) + omega + +/-! ## The callee's code, from the run -/ + +/-- The pops of STATICCALL's operands. -/ +theorem pop_static {evm : Evm .fusaka Nat} {g a i isz o osz : U256} {rest : List U256} + (hst : evm.stack.val = g :: a :: i :: isz :: o :: osz :: rest) : + ∃ stack : Stack, stack.val = rest ∧ + popCallOperands .staticcall evm = + .ok (⟨g, toAddressMasked a, 0, i, isz, o, osz⟩, { evm with stack }) := by + rcases evm with ⟨pc, ⟨l, hl⟩, memory, code, valid, gas, running, message, output, returnData, + state, substate, error⟩ + simp only at hst + subst hst + exact ⟨_, rfl, rfl⟩ + +/-- The rest of an instruction that errors makes the step fail. -/ +theorem fails_keepReads {evm : Evm .fusaka Nat} {e : EvmError} : + StepFails (keepReads evm StepResult.next (.error e : Except EvmError (StepResult .fusaka Nat))) := by + unfold keepReads + dsimp only + split + · exact .inl ⟨_, rfl⟩ + · exact .inr ⟨_, rfl, rfl, by simp [exceptionalHalt]⟩ + +/-- The rest of an instruction that starts with an error makes the step fail. -/ +theorem fails_keepReads_bind {α : Type} {E : Evm .fusaka Nat} {x : Except EvmError α} + {f : α → Except EvmError (StepResult .fusaka Nat)} (hx : ∃ e, x = .error e) : + StepFails (keepReads E StepResult.next (x >>= f)) := by + obtain ⟨e, rfl⟩ := hx + exact fails_keepReads + +/-- The access to the callee fails when the state holds no code for it. -/ +theorem accessDelegation_err1 {e : Evm .fusaka Nat} {addr : Address} {known : Nat} + (h : ∀ cc, e.state.getCode (e.state.getAccount addr).codeHash ≠ .ok cc) : + ∃ err, accessDelegation e addr known = .error err := by + unfold accessDelegation accountCode + cases hc : e.state.getCode (e.state.getAccount addr).codeHash with + | error x => exact ⟨.state x, by simp [Except.mapError, bind, Except.bind]⟩ + | ok cc => exact absurd hc (h cc) + +/-- The access to the callee fails when its code delegates to an account whose code the state +does not hold. -/ +theorem accessDelegation_err2 {e : Evm .fusaka Nat} {addr d : Address} {known : Nat} {cc : ByteArray} + (hc : e.state.getCode (e.state.getAccount addr).codeHash = .ok cc) + (hd : delegatedAddress cc = some d) + (h : ∀ c', e.state.getCode (e.state.getAccount d).codeHash ≠ .ok c') : + ∃ err, accessDelegation e addr known = .error err := by + unfold accessDelegation + cases hc2 : e.state.getCode (e.state.getAccount d).codeHash with + | error x => + refine ⟨.state x, ?_⟩ + simp [accountCode, Except.mapError, hc, hc2, hd, bind, Except.bind, accessAddress, checkGas, + recordAccountRead, show Fork.fusaka ≥ Fork.pectra by decide, show Fork.berlin ≤ Fork.fusaka by decide, + show ¬ (Fork.fusaka ≥ Fork.glamsterdam) by decide, pure, Except.pure] + | ok c' => exact absurd hc2 (h c') + +/-- **A STATICCALL step that does not fail reads the callee's code and follows a route**: the +state holds the code of the callee and, for an EIP-7702 delegation, of its delegate. So a run that +succeeds needs no assumption on the state at its calls. -/ +theorem staticcall_routes_of_ok {evm : Evm .fusaka Nat} {g a i isz o osz : U256} {rest : List U256} + (hst : evm.stack.val = g :: a :: i :: isz :: o :: osz :: rest) + (hnf : ¬ StepFails (callStep .staticcall evm)) : + ∃ cc route, evm.state.getCode (evm.state.getAccount (toAddressMasked a)).codeHash = .ok cc ∧ + Routes .fusaka evm.state cc route := by + obtain ⟨stack, -, hpop⟩ := pop_static hst + have key : ∀ (hx : ∀ E : Evm .fusaka Nat, E.state = evm.state.recordAccountRead (toAddressMasked a) → + ∀ known, ∃ err, accessDelegation E (toAddressMasked a) known = .error err), + StepFails (callStep .staticcall evm) := by + intro hx + simp only [callStep, hpop, bind, Except.bind, accessAddress, checkGas, recordAccountRead, + show ¬ (Fork.fusaka ≥ .glamsterdam) by decide, false_and, ite_false, + show Fork.fusaka ≥ Fork.berlin by decide, ite_true, pure, Except.pure] + exact fails_keepReads_bind (hx _ rfl _) + cases hc : evm.state.getCode (evm.state.getAccount (toAddressMasked a)).codeHash with + | error x => + exact absurd (key fun E hE known => accessDelegation_err1 (by + intro cc; rw [hE]; simp [hc])) hnf + | ok cc => + cases hd : delegatedAddress cc with + | none => exact ⟨cc, none, rfl, fun _ => hd⟩ + | some d => + cases hc2 : evm.state.getCode (evm.state.getAccount d).codeHash with + | ok c' => exact ⟨cc, some (d, c'), rfl, by decide, hd, hc2⟩ + | error x => + exact absurd (key fun E hE known => accessDelegation_err2 (cc := cc) (d := d) + (by rw [hE]; simpa using hc) hd (by intro c'; rw [hE]; simp [hc2])) hnf + +/-- **STATICCALL in a run that succeeds**, at the frame's own gas: the state held the callee's code +(and its delegate's, `Routes`), the gas paid for the access, the route and the growth of memory, +and the run goes on from the frame after the callee's frame ended. -/ +theorem staticcall_back {code : ByteArray} {msg : Message .fusaka} {pc g : Nat} {M : ByteArray} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray} + {asked addr inOff inSize outOff outSize : U256} {rest : List U256} + {evm : Evm .fusaka Nat} + (hat : At code msg pc (asked :: addr :: inOff :: inSize :: outOff :: outSize :: rest) M g st ss + rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0xfa) (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} (meets : Meets P runChild) + (within : GasMeter.gasHeld evm.gas ≤ bound) {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + ∃ (calleeCode : ByteArray) (route : Route), + st.getCode (st.getAccount (toAddressMasked addr)).codeHash = .ok calleeCode ∧ + Routes .fusaka st calleeCode route ∧ + (if decide (toAddressMasked addr ∉ ss.accessedAddresses) then 2600 else 100) + + routeCost .fusaka (ss.accessedAddresses.insert (toAddressMasked addr)) route + + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost ≤ g ∧ + ∃ (caller : Evm .fusaka Nat) (m : Message .fusaka) (child after : Evm .fusaka Nat) + (within' : GasMeter.gasHeld after.gas ≤ bound) (g' : Nat), + P caller m child ∧ child.gas ≤ m.gas ∧ + caller.state = (routeState (st.recordAccountRead (toAddressMasked addr)) route).recordAccountRead + msg.currentTarget ∧ + caller.substate = routeSub { ss with + accessedAddresses := ss.accessedAddresses.insert (toAddressMasked addr) } route ∧ + m.isStatic = true ∧ m.value = 0 ∧ m.code = routeCode calleeCode route ∧ + m.currentTarget = toAddressMasked addr ∧ m.target = some (toAddressMasked addr) ∧ + m.data = memoryReadBytes (memoryExtend M + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).expandBy) inOff.toNat + inSize.toNat ∧ + m.codeAddress = some (routeAddr (toAddressMasked addr) route) ∧ + m.disablePrecompiles = route.isSome ∧ + m.gas = (messageCallGas .fusaka 0 asked.toNat g + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost + ((if decide (toAddressMasked addr ∉ ss.accessedAddresses) then 2600 else 100) + + routeCost .fusaka (ss.accessedAddresses.insert (toAddressMasked addr)) route)).subCall ∧ + g' + (if decide (toAddressMasked addr ∉ ss.accessedAddresses) then 2600 else 100) + + routeCost .fusaka (ss.accessedAddresses.insert (toAddressMasked addr)) route + + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost ≤ g ∧ + At code msg (pc + 1) ((if child.error.isNone then 1 else 0) :: rest) + (memoryWrite (memoryExtend M + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).expandBy) + outOff.toNat (child.output.extract 0 (min outSize.toNat child.output.size))) + g' (incorporateChild .fusaka caller child).state + (incorporateChild .fusaka caller child).substate child.output after ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild after within' = .ok fin := by + have hat0 := hat + obtain ⟨hc, hv, hm, hpc, hst, hmem, hgas, hrunning, -, -, hst', hss, -⟩ := hat0 + have hlt' : evm.pc < evm.code.size := by rw [hc, hpc]; exact hlt + have decoded : Op.ofByte .fusaka (evm.code[evm.pc]'hlt') = some .staticcall := by + have he : evm.code[evm.pc]'hlt' = code[pc]'hlt := by subst hc hpc; rfl + rw [he, hbyte] + exact ofByte_of_decode rfl (by decide) + have hstep : step .fusaka evm = callStep .staticcall evm := + step_of_messageInstruction hlt' decoded instruction_staticcall + (messageInstruction_staticcall (by decide)) + have hnf : ¬ StepFails (callStep .staticcall evm) := fun hf => + error_ne_none_of_stepFails hrunning (by rw [hstep]; exact hf) hrun hok + obtain ⟨calleeCode, route, hcode, hroute⟩ := staticcall_routes_of_ok hst hnf + rw [hst'] at hcode hroute + refine ⟨calleeCode, route, hcode, hroute, ?_⟩ + have hcost := callBaseCost_of_berlin (fork := .fusaka) (by decide) (by decide) + (decide (toAddressMasked addr ∉ ss.accessedAddresses)) + generalize hcold : decide (toAddressMasked addr ∉ ss.accessedAddresses) = cold at hcost + generalize hdc : routeCost .fusaka (ss.accessedAddresses.insert (toAddressMasked addr)) route = dc + by_cases hg : (if cold then 2600 else 100) + dc + + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost ≤ g + · refine ⟨hg, ?_⟩ + have H := (callKindRoute (fork := .fusaka) (kind := .staticcall) (callee := P) + (asked := asked) (rest := rest) (returnData := rd) (gas := g) (memory := M) (substate := ss) + (inputStart := inOff) (inputSize := inSize) (outputStart := outOff) (outputSize := outSize) + (by decide) hlt hbyte (ofByte_of_decode rfl (by decide)) instruction_staticcall + (messageInstruction_staticcall (by decide)) hcode hroute hdepth + (by rw [← hcold] at hcost; rw [hcost, hcold, hdc]; exact hg)).toUnder + obtain ⟨after, hr, hq⟩ := H bound runChild meets evm hat within + have within' := Nat.le_trans (hr.gasHeld_le StepBy.gasHeld_le) within + have hrun' := hrun + rw [runFrame_eq_of_reaches StepBy.gasHeld_le StepBy.runFrame_eq hr within] at hrun' + rcases hq with ⟨caller, m, child, ⟨s1, s2, m1, -, -, mt, mtg, mca, mc, mdp, md, mv, -, -, ms, -, -⟩, + hk, hcg, hat'⟩ | aborted + · rw [← hcold] at hcost + rw [hcost, hdc, hcold] at m1 hat' + obtain ⟨hc1, hc2⟩ := staticcall_gas (asked := asked.toNat) + (memc := (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost) + (extra := (if cold then 2600 else 100) + dc) (g := g) (by omega) + refine ⟨caller, m, child, after, within', _, hk, hcg, s1, s2, by simpa using ms, + by simpa using mv, mc, by simpa using mt, by simpa using mtg, md, mca, mdp, m1, ?_, hat', hrun'⟩ + rw [m1] at hcg + rw [hc1] + omega + · obtain ⟨e, he, -⟩ := runFrame_of_abortsBy meets.aborts aborted within' + rw [he] at hrun' + cases hrun' + · exfalso + have fails : StepFails (step .fusaka evm) := by + rw [hstep] + refine callStep_fails_of_routes (route := route) (by decide) (a := addr) (i := inOff) + (isz := inSize) (o := outOff) (osz := outSize) (g := asked) (rest := rest) + (by rw [hst]; rfl) (by rw [hst']; exact hcode) (by rw [hst']; exact hroute) ?_ + rw [callBaseCost_of_berlin (by decide) (by decide), hgas, hmem, hss, hcold, hdc] + omega + exact error_ne_none_of_stepFails hrunning fails hrun hok + +/-- info: 'SolidCore.Refinement.Solar.AssembleCall.meets_static' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms meets_static + +/-- info: 'SolidCore.Refinement.Solar.AssembleCall.staticcall_back' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms staticcall_back + +/-! ## STATICCALL in SolarTV at any ranges -/ + +section Effect + +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.RunOracle +open SolidCore.Refinement.Solar.AssembleEffects SolidCore.Refinement.Solar.AssembleLoop + +/-- `AssembleEffects.memRel_expand2` at any ranges whose words SolarTV counts (`memRel_expandW`). -/ +theorem memRel_expand2W {m : Mem} {M : ByteArray} {o1 s1 o2 s2 : Word} (hm : MemRel m M) + (hb1 : s1 = 0 ∨ (o1.toNat + s1.toNat + 31) / 32 < 2 ^ 251) + (hb2 : s2 = 0 ∨ (o2.toNat + s2.toNat + 31) / 32 < 2 ^ 251) : + MemRel ((m.expand o1.toNat s1.toNat).expand o2.toNat s2.toNat) + (memoryExtend M (extendMemory M.size [(o1, s1), (o2, s2)]).expandBy) := by + have h1 := memRel_expandW hm hb1 + have h2 := memRel_expandW h1 hb2 + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + refine ⟨?_, fun i => ?_⟩ + · rw [← h2.1] + simp only [size_memoryExtend, extendMemory_cons_expandBy hmod (o1, s1) [(o2, s2)]] + omega + · rw [byteAt_memoryExtend] + have := h2.2 i + rw [byteAt_memoryExtend, byteAt_memoryExtend] at this + rw [this] + +/-- **STATICCALL in SolarTV at any ranges** whose words SolarTV counts, under an oracle that answers +the call as the callee's frame `child` ended: `AssembleEffects.staticcall_effect` without its +bound of `2 ^ 32` on the ranges, so at any offset a run that succeeds pays for. -/ +theorem staticcall_effectW {o : Oracle} {call : Call} {s : State} {M : ByteArray} + {gas addr inOff inSize outOff outSize : Word} {child : Evm .fusaka Nat} + (hm : MemRel s.memory M) + (hb1 : inSize = 0 ∨ (inOff.toNat + inSize.toNat + 31) / 32 < 2 ^ 251) + (hb2 : outSize = 0 ∨ (outOff.toNat + outSize.toNat + 31) / 32 < 2 ^ 251) + (hflag : callFlag o (s.world ++ [.call .staticcall [gas, addr] + (((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat outSize.toNat).read + inOff.toNat inSize.toNat) s.storage s.transient]) = if child.error.isNone then 1 else 0) + (hrd : RdRel o (s.world ++ [.call .staticcall [gas, addr] + (((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat outSize.toNat).read + inOff.toNat inSize.toNat) s.storage s.transient]) child.output) : + ∃ s', Effect.apply o call (.call .staticcall) [gas, addr, inOff, inSize, outOff, outSize] s = + some (some (if child.error.isNone then 1 else 0), s') ∧ + s'.storage = s.storage ∧ s'.transient = s.transient ∧ RdRel o s'.world child.output ∧ + s'.world = s.world ++ [.call .staticcall [gas, addr] + (((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat outSize.toNat).read + inOff.toNat inSize.toNat) s.storage s.transient] ∧ + MemRel s'.memory (memoryWrite (memoryExtend M + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).expandBy) + outOff.toNat (child.output.extract 0 (min outSize.toNat child.output.size))) := by + have he := memRel_expand2W hm hb1 hb2 + refine ⟨called o .staticcall s ((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat + outSize.toNat) outOff outSize (s.world ++ [.call .staticcall [gas, addr] + (((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat outSize.toNat).read + inOff.toNat inSize.toNat) s.storage s.transient]), ?_, ?_, ?_, ?_, ?_, ?_⟩ + · simp only [Effect.apply, CallKind.shape, hflag] + · rfl + · rfl + · exact hrd + · rfl + · simp only [called] + rw [hrd.1] + refine memRel_write he (fun hz => ?_) ?_ (fun i hi => ?_) + · have hz' : outSize ≠ 0 := fun h => hz (by simp [h]) + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have := le_ceil32_add_expandBy M.size [(inOff, inSize), (outOff, outSize)] (outOff, outSize) + (by simp) hz' + dsimp only at this + rw [ceil32_of_mod hmod] at this + rw [size_memoryExtend] + have := Nat.min_le_left outSize.toNat child.output.size + omega + · simp [ByteArray.size_extract] + · rw [byteAt_extract, Nat.zero_add, if_pos (by omega)] + exact (hrd.2 i (by omega)).symm + +end Effect + +/-- info: 'SolidCore.Refinement.Solar.AssembleCall.staticcall_effectW' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms staticcall_effectW + +/-! ## Runs whose messages keep the state across static calls -/ + +section Runs + +open SolarTV.Machine SolidCore.Refinement.Final SolidCore.Refinement.Solar.Assemble +open SolidCore.Refinement.Solar.RunOracle SolidCore.Refinement.Solar.AssembleRun +open EthLib.Execution.State + +/-- A runner that keeps the state across static messages meets the assumption that always holds. -/ +theorem Meets.weaken {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + (h : Meets StaticKept runChild) : Meets (fun _ _ _ => True) runChild := + ⟨fun _ _ _ _ _ => trivial, h.aborts⟩ + +section BlocksS + +variable {σ : Type} (blk : Oracle → σ → Option ((Halt × Machine.State) ⊕ σ)) + (O : RunTable → Oracle) + +/-- **One block of the simulation, read back from a run that succeeds**, as AssembleRun.Advances +but under every runner of messages that keeps the state across static messages (StaticKept): when the loop runs the frame `evm` to a frame `fin` with no error, the table grows to `T'` +and every oracle of a table extending `T'` runs the block from `x` to the same `r`: an end `fin` +shows (`Post`), or the next block state, related (`E T'`) to a frame with a lower measure that the +loop runs to `fin` too. -/ +def AdvancesS (E : RunTable → σ → Evm .fusaka Nat → Prop) + (Post : Halt × Machine.State → Evm .fusaka Nat → Prop) (meas : σ → Evm .fusaka Nat → Nat) + (T : RunTable) (x : σ) (evm : Evm .fusaka Nat) : Prop := + ∀ (bound : Nat) (runChild : MessageRunner .fusaka Nat bound), Meets StaticKept runChild → + ∀ (within : GasMeter.gasHeld evm.gas ≤ bound) (fin : Evm .fusaka Nat), + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + fin.error = none → + ∃ T' r, T.Le T' ∧ (∀ T'', T'.Le T'' → blk (O T'') x = some r) ∧ + (∀ res, r = .inl res → Post res fin) ∧ + (∀ y, r = .inr y → ∃ after within', E T' y after ∧ meas y after < meas x evm ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild after within' = .ok fin) + +/-- **A run of EthLib that ends with no error is SolarTV's**, for every table extending the last +one the run grew. -/ +theorem run_of_advancesS {E : RunTable → σ → Evm .fusaka Nat → Prop} + {Post : Halt × Machine.State → Evm .fusaka Nat → Prop} {meas : σ → Evm .fusaka Nat → Nat} + (adv : ∀ T x evm, E T x evm → AdvancesS blk O E Post meas T x evm) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + (meets : Meets StaticKept runChild) : + ∀ (n : Nat) (T : RunTable) (x : σ) (evm : Evm .fusaka Nat) + (within : GasMeter.gasHeld evm.gas ≤ bound) (fin : Evm .fusaka Nat), + E T x evm → meas x evm < n → + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + fin.error = none → + ∃ T' res, T.Le T' ∧ + (∀ T'', T'.Le T'' → ∃ k, iterate (blk (O T'')) k x = some res) ∧ + Post res fin + | 0, _, _, _, _, _, _, h, _, _ => absurd h (Nat.not_lt_zero _) + | n + 1, T, x, evm, within, fin, hE, hm, hrun, hok => by + obtain ⟨T', r, hle, hstep, hinl, hinr⟩ := adv T x evm hE bound runChild meets within fin hrun hok + cases r with + | inl res => + exact ⟨T', res, hle, fun T'' h => ⟨1, by simp [iterate, hstep T'' h]⟩, hinl res rfl⟩ + | inr y => + obtain ⟨after, within', hE', hm', hrun'⟩ := hinr y rfl + obtain ⟨T2, res, hle2, hit, hpost⟩ := + run_of_advancesS adv meets n T' y after within' fin hE' (by omega) hrun' hok + refine ⟨T2, res, hle.trans hle2, fun T'' h => ?_, hpost⟩ + obtain ⟨k, hk⟩ := hit T'' h + exact ⟨k + 1, by simp [iterate, hstep T'' (hle2.trans h), hk]⟩ + +end BlocksS + +/-- A block that advances under every runner advances under every runner keeping static state. -/ +theorem AdvancesS.of_advances {σ : Type} {blk : Oracle → σ → Option ((Halt × Machine.State) ⊕ σ)} + {O : RunTable → Oracle} {E : RunTable → σ → Evm .fusaka Nat → Prop} + {Post : Halt × Machine.State → Evm .fusaka Nat → Prop} {meas : σ → Evm .fusaka Nat → Nat} + {T : RunTable} {x : σ} {evm : Evm .fusaka Nat} (h : AssembleRun.Advances blk O E Post meas T x evm) : + AdvancesS blk O E Post meas T x evm := + fun bound runChild meets => h bound runChild (Meets.weaken meets) + + +open SolarTV.EVM.Program SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Evm.Symex in +/-- **EVM IR to bytecode at the given gas, run by run, from a block simulation**: when every frame +related to a block state (`E`, from the substate the frame started with) advances (`Advances`) to +an end SolarTV's halt shows (`PostL`) or to the next block, and the frame a call starts with is +related to SolarTV's initial state, then the oracle of the run's table makes every result of the +bytecode on the call the EVM IR's or a failure that changes nothing. -/ +theorem within_of_advancesS {p : Assemble.Program} {code : ByteArray} {call : Call} {gas : Nat} + (O : RunTable → Oracle) + (E : Substate → RunTable → Nat × List Word × Machine.State → Evm .fusaka Nat → Prop) + (meas : Nat × List Word × Machine.State → Evm .fusaka Nat → Nat) + (start : ∀ st' ss', Rel (Final.Target.messageWith gas code call) ss' st' ss' + (Machine.State.initial call) → + E ss' {} (0, [], Machine.State.initial call) + (startFrame (Final.Target.messageWith gas code call) st' ss' gas)) + (adv : ∀ ss0 T x evm, E ss0 T x evm → AdvancesS (fun o => block o call p) O (E ss0) + (fun res => PostL call (Final.Target.messageWith gas code call).currentTarget ss0 res.2 res.1) + meas T x evm) : + ∃ T, Within (evmirSem (O T)) (ethLibWith gas) p code (· = call) := by + by_cases hs : ∃ obs, Target.runWith gas code call = some obs ∧ obs.success = true + swap + · refine ⟨{}, fun call' hc obs hrun => Or.inr ?_⟩ + subst hc + have hf : obs.success = false := by + cases h : obs.success + · rfl + · exact absurd ⟨obs, hrun, h⟩ hs + exact ⟨hf, Target.runWith_failure hrun hf⟩ + obtain ⟨obs, hrun, hsucc⟩ := hs + suffices H : ∃ T, (evmirSem (O T)).run p call = some obs by + obtain ⟨T, hT⟩ := H + refine ⟨T, fun call' hc obs' hrun' => Or.inl ?_⟩ + subst hc + change Target.runWith gas code call' = some obs' at hrun' + rw [hrun] at hrun' + cases hrun' + exact hT + unfold Target.runWith Target.runMsg at hrun + split at hrun + · cases hrun + rename_i evm hev hpm + simp only [Option.some.injEq] at hrun + subst hrun + have hok : evm.error = none := by simpa using hsucc + obtain ⟨st', ss', within, hcases, hmove, hrf⟩ := + AssembleRun.processMessage_ok' (message := Final.Target.messageWith gas code call) (evm := ⟨evm, hev⟩) + (precompileAddress_message code call) hpm hok + simp only at hrf + have R := AssembleLoop.rel_start code call gas ss' (fun h => (hcases h).1) (fun h => (hmove h).1) + obtain ⟨T, ⟨halt, sF⟩, -, hit, hpost⟩ := run_of_advancesS (fun o => block o call p) O (adv ss') + (meets_static _) _ {} _ _ within evm (start st' ss' R) (Nat.lt_succ_self _) hrf hok + obtain ⟨k, hk⟩ := hit T (RunTable.Le.refl T) + refine ⟨T, ?_⟩ + have hres : (evmirSem (O T)).run p call = some (observe call sF halt) := by + change (SolarTV.EVM.Program.layer.result (O T) p call).map _ = _ + rw [SolarTV.EVM.Program.layer.result_of_ends ⟨k, hk⟩] + rfl + rw [hres] + set msg := Final.Target.messageWith gas code call with hmsg + obtain ⟨ssF, ⟨herr, hout, hlogsF, hst⟩, L, hL1, hL2⟩ := hpost + have hss' : ss'.logs.toList = [] := by + by_cases htr : msg.shouldTransferValue = true ∧ msg.value ≠ 0 + · rw [(hmove htr).2] + simp [pushTransferLog, show ¬ (Fork.fusaka ≥ Fork.glamsterdam) by decide, Substate.empty] + · rw [(hcases htr).2] + simp [Substate.empty] + have hlogs := logs_of_match hL2 + have hL1' : ssF.logs.toList = L := by rw [hL1, hss', List.nil_append] + have herr' : evm.error = errorOf (observe call sF halt) := herr + have hout' : evm.output.toList.map (·.toNat) = (observe call sF halt).output := hout + have hst' : (observe call sF halt).success = true → + evm.substate.logs = ssF.logs ∧ ∀ slot, + (evm.state.getStorage (Target.address selfAddress) (Target.storageKey slot)).toNat = + (observe call sF halt).storage slot := + fun h => ⟨hlogsF, hst h⟩ + have hfail : (observe call sF halt).success = false → + (observe call sF halt).logs = [] ∧ + (observe call sF halt).storage = slotValue call.storage := by + cases halt <;> simp [observe] + have hok2 : (observe call sF halt).success = true → + (observe call sF halt).logs = logs sF := by + cases halt <;> simp [observe] + clear herr hout hst hres hit hk + generalize observe call sF halt = X at * + have hsucc' : evm.error.isNone = X.success := by + rw [herr']; cases hX : X.success <;> simp [errorOf, hX] + symm + congr 1 + cases X with + | mk success output logs storage => + simp only at hsucc' hout' hfail hok2 hst' ⊢ + rw [SolarTV.Observable.mk.injEq] + refine ⟨hsucc', hout', ?_, ?_⟩ + · rw [hsucc'] + cases hs : success + · simp [hok, hs] at hsucc' + · simp only [ite_true] + rw [(hst' hs).1, hL1', hlogs, hok2 hs] + rfl + · funext slot + rw [hsucc'] + cases hs : success + · simp [hok, hs] at hsucc' + · simp only [ite_true] + exact (hst' hs).2 slot + +/-- info: 'SolidCore.Refinement.Solar.AssembleCall.within_of_advancesS' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms within_of_advancesS + +end Runs + +/-! ## The state after a STATICCALL -/ + +section State + +open EthLib.Execution.State + +/-- **The state after a STATICCALL is the caller's**, at every address (account, storage and +transient storage), under a runner keeping static state: the message is static, has a target, sends +no value, and its code, when it has any, is the callee account's (`getCode` of the empty hash is +empty). -/ +theorem staticcall_state {st : State.TransactionState} {msg : Message .fusaka} {addr : U256} + {calleeCode : ByteArray} {route : Route} {caller child : Evm .fusaka Nat} {m : Message .fusaka} + (hcode : st.getCode (st.getAccount (toAddressMasked addr)).codeHash = .ok calleeCode) + (hroute : Routes .fusaka st calleeCode route) + (hk : StaticKept caller m child) + (hcs : caller.state = (routeState (st.recordAccountRead (toAddressMasked addr)) route).recordAccountRead + msg.currentTarget) + (hms : m.isStatic = true) (hmv : m.value = 0) (hmc : m.code = routeCode calleeCode route) + (hmt : m.currentTarget = toAddressMasked addr) (htg : m.target = some (toAddressMasked addr)) : + TransactionState.SameOutside [] st (incorporateChild .fusaka caller child).state := by + have hsm : StaticMessage caller.state m := by + refine ⟨hms, by rw [htg]; rfl, fun hsz he => ?_, fun _ hv => absurd hmv hv⟩ + rw [hcs, hmt] at he + rcases route with _ | ⟨d, c'⟩ + · simp only [routeState, TransactionState.getAccount_recordAccountRead] at he + rw [he] at hcode + simp only [TransactionState.getCode, ite_true, Except.ok.injEq] at hcode + rw [hmc, routeCode, ← hcode] at hsz + exact hsz rfl + · simp only [routeState, TransactionState.getAccount_recordAccountRead] at he + rw [he] at hcode + simp only [TransactionState.getCode, ite_true, Except.ok.injEq] at hcode + have hdel := hroute.2.1 + rw [← hcode] at hdel + simp only [delegatedAddress, isValidDelegation] at hdel + obtain ⟨⟨h0, -⟩, -⟩ := hdel + have h1 : TransactionState.SameOutside [] st caller.state := by + rw [hcs] + rcases route with _ | ⟨d, c'⟩ + · exact (TransactionState.sameOutside_recordAccountRead st _).trans + (TransactionState.sameOutside_recordAccountRead _ _) + · exact ((TransactionState.sameOutside_recordAccountRead st _).trans + (TransactionState.sameOutside_recordAccountRead _ _)).trans + (TransactionState.sameOutside_recordAccountRead _ _) + have h2 := h1.trans (hk hsm) + have hst : (incorporateChild .fusaka caller child).state = child.state := by + unfold incorporateChild + split <;> rfl + rw [hst] + simpa using h2 + +end State + +/-- info: 'SolidCore.Refinement.Solar.AssembleCall.staticcall_state' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms staticcall_state + +end SolidCore.Refinement.Solar.AssembleCall diff --git a/SolidCore/Refinement/Solar/AssembleCallCut.lean b/SolidCore/Refinement/Solar/AssembleCallCut.lean new file mode 100644 index 00000000..b9ada0e7 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCallCut.lean @@ -0,0 +1,561 @@ +import SolidCore.Refinement.Solar.AssembleCall +import SolidCore.Refinement.Solar.AssembleCallWorld +import SolidCore.Refinement.Solar.AssembleCallPre +import EthLib.Base.Proofs.U256 + +/-! +# A STATICCALL to code as a cut of a run, at the frame's own gas + +`staticcall_cut` is the step the checker's segments (`AssembleCut.seg`) take at a STATICCALL to +code: from a run of the bytecode that succeeds, the STATICCALL had the gas for its access and memory +(`AssembleCall.staticcall_back`, EIP-150 forwarding), and the run goes on from the frame after it, +with the callee frame's flag and output. The run's table grows by that flag and output +(`RunTable.oks`, `RunTable.outs`), and under the oracle of every extension of it +(`AssembleCallWorld.OS`) SolarTV's STATICCALL pushes the same flag, leaves the same return data and +memory, and keeps storage and logs as EthLib's frame does: the relation of a block entry holds again. + +The same cut covers a STATICCALL to ECRECOVER (address 1) under `PreOk`: there the oracle answers +as the source does (SolidCore's precompile semantics, `tabResp` falls back to `failResp`), and +`AssembleCallPre.ecrecover_answer` shows EthLib's callee frame gives that flag and output, under +the named `AssembleCallPre.EcrecoverAgree`. The table still grows by one entry per STATICCALL. + +The runner of messages must meet `StaticOk`: `StaticKept`, proved of EthLib's runner +(`AssembleCall.meets_static`), and two named hypotheses that a final theorem using this cut lists: +`StaticNoLogs` (EIP-214: a static message that succeeds ends with no log; EthLib's LOG fails in a +static frame, but EthLib proves only that a static message keeps the state, +`processMessage_sameOutside_static`, not its logs) and `OutputFits` (a callee's output is shorter +than `2 ^ 256` bytes, which the gas paid for its memory bounds but which is not derived here). +-/ + +namespace SolidCore.Refinement.Solar.AssembleCallCut + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Witness +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.RunOracle +open SolidCore.Refinement.Solar.AssembleCut SolidCore.Refinement.Solar.AssembleEffects +open SolidCore.Refinement.Solar.AssembleLoop SolidCore.Refinement.Solar.AssembleRun +open SolidCore.Refinement.Solar.AssembleCall SolidCore.Refinement.Solar.AssembleCallWorld +open SolidCore.Refinement.Solar.AssembleDyn +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +/-! ## Memory a run pays for, over several ranges -/ + +/-- Growing memory of whole words for a list of ranges costs the price of the grown memory less the +price of the old one, keeps whole words, and covers every nonempty range. -/ +theorem extendMemory_facts : ∀ (l : List (U256 × U256)) (size : Nat), size % 32 = 0 → + (extendMemory size l).cost + memoryGasCost size = + memoryGasCost (size + (extendMemory size l).expandBy) ∧ + (size + (extendMemory size l).expandBy) % 32 = 0 ∧ + ∀ r ∈ l, r.2 ≠ 0 → r.1.toNat + r.2.toNat ≤ size + (extendMemory size l).expandBy + | [], size, hmod => by simp [extendMemory, hmod] + | (o, sz) :: l, size, hmod => by + have ih := extendMemory_facts l + by_cases hz : sz = 0 + · obtain ⟨h1, h2, h3⟩ := ih size hmod + simp only [extendMemory, hz, ite_true] + refine ⟨h1, h2, fun r hr hr0 => ?_⟩ + rcases List.mem_cons.1 hr with rfl | hr + · exact absurd rfl hr0 + · exact h3 r hr hr0 + · have hc := ceil32_of_mod hmod + by_cases hle : ceil32 (o.toNat + sz.toNat) ≤ ceil32 size + · obtain ⟨h1, h2, h3⟩ := ih size hmod + simp only [extendMemory, hz, ite_false, hle, ite_true] + refine ⟨h1, h2, fun r hr hr0 => ?_⟩ + rcases List.mem_cons.1 hr with rfl | hr + · have := le_ceil32 (o.toNat + sz.toNat) + dsimp only + omega + · exact h3 r hr hr0 + · obtain ⟨h1, h2, h3⟩ := ih (ceil32 (o.toNat + sz.toNat)) (ceil32_mod _) + simp only [extendMemory, hz, ite_false, hle] + have hlt : size < ceil32 (o.toNat + sz.toNat) := by omega + have hm := memoryGasCost_mono (Nat.le_of_lt hlt) + rw [hc] + have he : size + (ceil32 (o.toNat + sz.toNat) - size + + (extendMemory (ceil32 (o.toNat + sz.toNat)) l).expandBy) = + ceil32 (o.toNat + sz.toNat) + (extendMemory (ceil32 (o.toNat + sz.toNat)) l).expandBy := by + omega + rw [he] + refine ⟨by omega, h2, fun r hr hr0 => ?_⟩ + rcases List.mem_cons.1 hr with rfl | hr + · have := le_ceil32 (o.toNat + sz.toNat) + dsimp only + omega + · exact h3 r hr hr0 + +/-- **A paid growth of memory for two ranges keeps the budget**: each nonempty range's words are +within SolarTV's count, and the grown memory's price and the gas left are within the budget. -/ +theorem budget_grow2 {size g G pre : Nat} (hmod : size % 32 = 0) {o1 s1 o2 s2 : U256} + (hb : memoryGasCost size + g ≤ G) (hG : G < 2 ^ 300) + (hg : pre + (extendMemory size [(o1, s1), (o2, s2)]).cost ≤ g) : + (s1 = 0 ∨ (o1.toNat + s1.toNat + 31) / 32 < 2 ^ 251) ∧ + (s2 = 0 ∨ (o2.toNat + s2.toNat + 31) / 32 < 2 ^ 251) ∧ + memoryGasCost (size + (extendMemory size [(o1, s1), (o2, s2)]).expandBy) + + (g - (pre + (extendMemory size [(o1, s1), (o2, s2)]).cost)) ≤ G ∧ + (s2 ≠ 0 → o2.toNat + s2.toNat ≤ size + (extendMemory size [(o1, s1), (o2, s2)]).expandBy) := by + obtain ⟨h1, -, h3⟩ := extendMemory_facts [(o1, s1), (o2, s2)] size hmod + have hw : ∀ r ∈ [(o1, s1), (o2, s2)], r.2 = 0 ∨ (r.1.toNat + r.2.toNat + 31) / 32 < 2 ^ 251 := by + intro r hr + by_cases hz : r.2 = 0 + · exact .inl hz + · refine .inr (words_lt_of_cost (B := G) ?_ hG) + have := memoryGasCost_mono (h3 r hr hz) + omega + exact ⟨hw (o1, s1) (by simp), hw (o2, s2) (by simp), by omega, fun hz => h3 (o2, s2) (by simp) hz⟩ + +/-! ## The named hypothesis -/ + +/-- **EIP-214, as a named hypothesis on the runner of messages**: a static message that succeeds +ends with no log. -/ +def StaticNoLogs (_caller : Evm .fusaka Nat) (m : Message .fusaka) (child : Evm .fusaka Nat) : Prop := + m.isStatic = true → child.error = none → child.substate.logs.toList = [] + +/-- **Named hypothesis on the runner of messages**: a callee's output has fewer than `2 ^ 256` bytes, +so RETURNDATASIZE reports it exactly. (A callee pays for the memory it returns from out of gas below +`2 ^ 256`, so this holds of EthLib's runner; it is not yet derived here.) -/ +def OutputFits (_caller : Evm .fusaka Nat) (_m : Message .fusaka) (child : Evm .fusaka Nat) : Prop := + child.output.size < 2 ^ 256 + +/-- What a STATICCALL cut asks of the callee frames of the runner. -/ +def StaticOk (caller : Evm .fusaka Nat) (m : Message .fusaka) (child : Evm .fusaka Nat) : Prop := + StaticKept caller m child ∧ StaticNoLogs caller m child ∧ OutputFits caller m child + +/-! ## Oracles of tables that extend each other -/ + +theorem tabResp_congr {oks oks' : List Bool} {outs outs' : List ByteArray} {n : Nat} + (h1 : oks.getD n false = oks'.getD n false) (h2 : outs.getD n .empty = outs'.getD n .empty) : + tabResp oks outs n = tabResp oks' outs' n := by + funext k c v i + simp only [tabResp, h1, h2] + +/-- The oracles of two tables, one extending the other, agree at every world whose calls and GAS +reads the shorter answers. -/ +theorem OS_le {codes : SolidCore.Solidity.Shared.Account.BytesMap} {T T' : RunTable} (hle : T.Le T') + {w : List Event} (hn : (machineCalls w).length ≤ T.oks.length) + (hn' : (machineCalls w).length ≤ T.outs.length) (h0 : 0 < T.oks.length) (h0' : 0 < T.outs.length) + (hg : gasReads w ≤ T.gases.length) : + (∀ name a, (OS codes T').env name w a = (OS codes T).env name w a) ∧ + (OS codes T').result w = (OS codes T).result w := by + have hr : tabResp T'.oks T'.outs ((machineCalls w).length - 1) = + tabResp T.oks T.outs ((machineCalls w).length - 1) := + tabResp_congr (getD_of_prefix hle.1 (by omega) _) (getD_of_prefix hle.2.1 (by omega) _) + have hgas : gasReads w ≠ 0 → + T'.gases.getD (gasReads w - 1) 0 = T.gases.getD (gasReads w - 1) 0 := fun h => + getD_of_prefix hle.2.2.2.2 (by omega) _ + refine ⟨fun name a => ?_, ?_⟩ + · simp only [OS, gasOracle] + split_ifs with h + · rw [hgas h.2.2] + · simp only [envOracle, ethOracle, tabOracle_envEq, tabEnv, hr] + · show tabResult T'.oks T'.outs w = tabResult T.oks T.outs w + simp only [tabResult, hr] + +/-! ## Segments under the oracles of tables that extend each other -/ + +/-- A frame's calls are among the messages it sent. -/ +theorem machineCalls_length_le_sent : ∀ w : List Event, (machineCalls w).length ≤ sent w + | [] => by simp [machineCalls, sent] + | e :: w => by + have ih := machineCalls_length_le_sent w + unfold sent at ih ⊢ + cases e <;> simp [machineCalls, Event.sends, List.filter_cons] <;> omega + +/-- **The oracles of a table and of any extension agree at the worlds the table answers**: every +world with at most `ng` GAS reads and `ns` messages, when the table holds `ng` gases and `ns` +flags and outputs. So a segment runs alike under both (`AssembleCut.execC_agree`), as +`AssembleCut.table_agree` gives for the failing world's oracle. -/ +theorem OS_agreeT (codes : SolidCore.Solidity.Shared.Account.BytesMap) {T T' : RunTable} + (hle : T.Le T') {ng ns : Nat} (hg : ng ≤ T.gases.length) (hn : ns ≤ T.oks.length) + (hn' : ns ≤ T.outs.length) : Agree (OS codes T) (OS codes T') ng ns := by + refine ⟨rfl, rfl, fun w hw hsw name a => ?_⟩ + have hgas : gasReads w ≠ 0 → + T.gases.getD (gasReads w - 1) 0 = T'.gases.getD (gasReads w - 1) 0 := fun h => + (getD_of_prefix hle.2.2.2.2 (by omega) _).symm + have hm := machineCalls_length_le_sent w + simp only [OS, gasOracle] + split_ifs with h + · rw [hgas h.2.2] + · simp only [envOracle, ethOracle, tabOracle_envEq] + by_cases h0 : (machineCalls w).length = 0 + · have hnil : machineCalls w = [] := List.eq_nil_of_length_eq_zero h0 + simp [tabEnv, hnil] + · have hr : tabResp T.oks T.outs ((machineCalls w).length - 1) = + tabResp T'.oks T'.outs ((machineCalls w).length - 1) := + tabResp_congr (getD_of_prefix hle.1 (by omega) _).symm + (getD_of_prefix hle.2.1 (by omega) _).symm + simp only [tabEnv, hr] + +/-- An effect that stops no segment adds no call to the frame's world. -/ +theorem apply_calls {o : Oracle} {call : Call} {e : Effect} (he : cutEffect e = false) + {args : List Word} {s s' : State} {r : Option Word} + (h : Effect.apply o call e args s = some (r, s')) : + machineCalls s'.world = machineCalls s.world := by + unfold Effect.apply at h + split at h <;> (try split at h) <;> simp_all [cutEffect] + all_goals (obtain ⟨-, rfl⟩ := h; simp) + +/-- **A segment adds no call to the frame's world**: the state it ends in, when it does not halt, +has the calls of the state it started from. With `AssembleCut.execC_agree`'s `Kept` (GAS reads and +messages), this keeps the table of a run's calls in step with the frame's calls between cuts. -/ +theorem execC_calls (o : Oracle) (call : Call) (b : Nat) : + ∀ (is : List Assemble.Instr) (S : List Word) (s s' : State), + endState (execC o call b is S s) = some s' → machineCalls s'.world = machineCalls s.world + | [], _, s, s', h => by simp [execC, endState] at h; subst h; rfl + | .op op :: rest, S, s, s', h => by + by_cases hc : cutOp op = true + · simp only [execC, hc, ite_true, endState, Option.some.injEq] at h + subst h; rfl + · have hc' : cutOp op = false := by simpa using hc + cases hs : SolarTV.EVM.Program.stepOp (SolarTV.EVM.Program.context o call s) op S s.memory with + | error _ => simp [execC, hc', hs, endState] at h + | ok r => + obtain ⟨S', m⟩ := r + simp only [execC, hc', hs, Bool.false_eq_true, ite_false] at h + exact execC_calls o call b rest S' { s with memory := m } s' h + | .effect e a :: rest, S, s, s', h => by + by_cases hc : cutEffect e = true + · simp only [execC, hc, ite_true, endState, Option.some.injEq] at h + subst h; rfl + · have he : cutEffect e = false := by simpa using hc + by_cases hl : S.length < a + · simp [execC, he, hl, endState] at h + · cases happ : Effect.apply o call e (S.take a) s with + | none => simp [execC, he, hl, happ, endState] at h + | some r => + obtain ⟨res, s1⟩ := r + have hw := apply_calls he happ + simp only [execC, he, hl, Bool.false_eq_true, ite_false, happ] at h + split_ifs at h + · simp [endState] at h + · rw [execC_calls o call b rest _ s1 s' h, hw] + | .jump t :: rest, S, s, s', h => by + simp only [execC] at h + split_ifs at h <;> simp [endState] at h + subst h; rfl + | .jumpi t :: rest, S, s, s', h => by + simp only [execC] at h + split_ifs at h + · simp [endState] at h + · cases S with + | nil => simp [endState] at h + | cons x S => + simp only at h + split_ifs at h + · exact execC_calls o call b rest S s s' h + · simp [endState] at h; subst h; rfl + | .pushLabel t :: rest, S, s, s', h => by + simp only [execC] at h + split_ifs at h + · simp [endState] at h + · exact execC_calls o call b rest _ s s' h + | .jumpDyn :: rest, S, s, s', h => by + cases S with + | nil => simp [execC, endState] at h + | cons x S => simp [execC, endState] at h; subst h; rfl + | .jumpiDyn :: rest, S, s, s', h => by + match S with + | [] => simp [execC, endState] at h + | [_] => simp [execC, endState] at h + | x :: y :: S => + simp only [execC] at h + split_ifs at h + · exact execC_calls o call b rest S s s' h + · simp [endState] at h; subst h; rfl + | .jumpTable ts :: rest, S, s, s', h => by + cases S with + | nil => simp [execC, endState] at h + | cons x S => + cases ht : ts[x.toNat]? with + | none => simp [execC, ht, endState] at h + | some t => simp [execC, ht, endState] at h; subst h; rfl + | .stop :: rest, S, s, s', h => by simp [execC, endState] at h + | .ret :: rest, S, s, s', h => by simp [execC, endState] at h; subst h; rfl + | .revert :: rest, S, s, s', h => by simp [execC, endState] at h; subst h; rfl + | .invalid :: rest, S, s, s', h => by simp [execC, endState] at h + +/-! ## The cut -/ + +/-- The word of a masked address is the word modulo `2 ^ 160` (as EthLib's Base.Proofs.Address, +which the build of this library does not include). -/ +theorem toNat_toU256_masked (w : U256) : + (toAddressMasked w).toU256.toNat = w.toNat % 2 ^ 160 := by + have h1 : (toAddressMasked w).toList = natToBytes 20 w.toNat := by + rw [toAddressMasked, Vector.toList_drop, U256.toList_toBeBytes] + rw [show 32 = 12 + 20 from rfl, natToBytes_add] + exact List.drop_left' (natToBytes_length _ _) + have h := bytesToNat_lt (toAddressMasked w).toList + rw [Vector.length_toList] at h + show (BitVec.ofNat 256 (bytesToNat (toAddressMasked w).toList)).toNat = _ + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt (Nat.lt_trans h (by decide)), h1, bytesToNat_natToBytes] + rfl + +/-- What a STATICCALL to ECRECOVER (address 1) asks: the named EcrecoverAgree, a runner whose +frames for priced ECRECOVER messages are EthLib's (AssembleCallPre.meets_ecrecover), an account at +address 1 that is no EIP-7702 delegation, and at least ECRECOVER's price, 3000, passed on. -/ +def PreOk (P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop) + (st : State.TransactionState) (ss : Substate) (M : ByteArray) (g : Nat) + (asked addr inOff inSize outOff outSize : U256) : Prop := + addr.toNat % 2 ^ 160 = 1 ∧ AssembleCallPre.EcrecoverAgree ∧ + (∀ c m ch, P c m ch → AssembleCallPre.EcrecoverRuns c m ch) ∧ + (∀ cc, st.getCode (st.getAccount (toAddressMasked addr)).codeHash = .ok cc → + delegatedAddress cc = none) ∧ + 3000 ≤ (messageCallGas .fusaka 0 asked.toNat g + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost + (if decide (toAddressMasked addr ∉ ss.accessedAddresses) then 2600 else 100)).subCall + +open SolarTV.Machine in +/-- The input range of a STATICCALL, read from both memories once both ranges grew. -/ +theorem read_eq2 {m : Mem} {M : ByteArray} {i isz o osz : Word} (hm : MemRel m M) : + (memoryReadBytes (memoryExtend M (extendMemory M.size [(i, isz), (o, osz)]).expandBy) i.toNat + isz.toNat).toList.map (·.toNat) = + (((m.expand i.toNat isz.toNat).expand o.toNat osz.toNat).read i.toNat isz.toNat).map + BitVec.toNat := by + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + by_cases hz : isz = 0 + · subst hz + simp [memoryReadBytes, Mem.read] + · have hfit : i.toNat + isz.toNat ≤ + (memoryExtend M (extendMemory M.size [(i, isz), (o, osz)]).expandBy).size := by + have := le_ceil32_add_expandBy M.size [(i, isz), (o, osz)] (i, isz) (by simp) hz + dsimp only at this + rw [ceil32_of_mod hmod] at this + rw [size_memoryExtend] + have := le_ceil32 (i.toNat + isz.toNat) + omega + rw [toList_map_toNat, size_memoryReadBytes hfit] + have hb : ((m.expand i.toNat isz.toNat).expand o.toNat osz.toNat).bytes = m.bytes := by + unfold Mem.expand; split <;> split <;> rfl + simp only [Mem.read, hb, List.map_map] + apply List.map_congr_left + intro k hk + simp only [List.mem_range] at hk + rw [byteAt_memoryReadBytes hfit, if_pos hk, byteAt_memoryExtend, Function.comp_apply, + ← hm.2 (i.toNat + k), UInt8.toNat_toBitVec] + +/-- A STATICCALL under the oracle of a run answers as the table's world does at that call +(`tabResp`): its flag, and its output as the return data until the next call. -/ +theorem OS_ans (codes : SolidCore.Solidity.Shared.Account.BytesMap) (T : RunTable) + (w : List SolarTV.Machine.Event) (gas addr : (BitVec 256)) (input : List SolarTV.Memory.Byte) (st tr : (BitVec 256) → (BitVec 256)) + (ok : Bool) (out : ByteArray) + (hr : tabResp T.oks T.outs (machineCalls w).length .staticcall (addr.toNat % 2 ^ 160) 0 + (input.map BitVec.toNat) = (ok, out)) + (hsz : out.size < 2 ^ 256) : + callFlag (OS codes T) (w ++ [.call .staticcall [gas, addr] input st tr]) = + (if ok then 1 else 0) ∧ + ∀ rest, machineCalls rest = [] → + RdRel (OS codes T) (w ++ [.call .staticcall [gas, addr] input st tr] ++ rest) + out := by + have hm := machineCalls_static w gas addr input st tr + refine ⟨?_, fun rest hrest => ?_⟩ + · show (if tabResult T.oks T.outs _ = 0 then _ else _) = _ + simp only [tabResult, hm, List.getLast?_append, List.getLast?_singleton, Option.some_or, + List.length_append, List.length_singleton, Nat.add_sub_cancel, hr] + cases ok <;> simp + · have hmr : machineCalls (w ++ [.call .staticcall [gas, addr] input st tr] ++ rest) = + machineCalls w ++ [(.staticcall, addr.toNat % 2 ^ 160, 0, input.map BitVec.toNat)] := by + rw [machineCalls_append, hm, hrest, List.append_nil] + refine ⟨?_, fun i hi => ?_⟩ + · show ((OS codes T).env "returndatasize" _ []).toNat = _ + rw [OS_env codes T _ _ _ (by decide) rfl] + simp only [tabEnv, show ("returndatasize" = "extcodesize") = False by simp, ite_false, hmr, + List.getLast?_append, List.getLast?_singleton, Option.some_or, List.length_append, + List.length_singleton, Nat.add_sub_cancel, hr, BitVec.toNat_ofNat] + exact Nat.mod_eq_of_lt hsz + · show ((OS codes T).env "returndata" _ [BitVec.ofNat 256 i]).setWidth 8 = _ + rw [OS_env codes T _ _ _ (by decide) rfl] + simp only [tabEnv, show ("returndata" = "extcodesize") = False by simp, ite_false, hmr, + List.getLast?_append, List.getLast?_singleton, Option.some_or, List.length_append, + List.length_singleton, Nat.add_sub_cancel, hr] + apply BitVec.eq_of_toNat_eq + have hi' : i < 2 ^ 256 := by omega + simp only [BitVec.toNat_setWidth, BitVec.toNat_ofNat, UInt8.toNat_toBitVec, + Nat.mod_eq_of_lt hi', EthLib.Base.byteAt, hi, dite_true] + have := (out.get! i).toNat_lt + rw [Nat.mod_eq_of_lt (by omega), Nat.mod_eq_of_lt (by omega)] + simp only [ByteArray.get!] + clear this + exact congrArg UInt8.toNat (data_getElem! _ i hi) + +/-- **A STATICCALL to code, read back from a run that succeeds**, at the frame's own gas: the run's +table grows by the callee frame's flag and output, and under the oracle of every extension of it, +SolarTV's STATICCALL pushes that flag and leaves that return data, and the frame after it relates to +SolarTV's state as a block entry does (memory, storage, logs, the budget of memory and gas). -/ +theorem staticcall_cut {code : ByteArray} {msg : Message .fusaka} {call : Call} {pc g G : Nat} + {M : ByteArray} {st : State.TransactionState} {ss ss0 : Substate} {rd : ByteArray} + {asked addr inOff inSize outOff outSize : U256} {Tr : List U256} + {s : State} {evm : Evm .fusaka Nat} + (codes : SolidCore.Solidity.Shared.Account.BytesMap) (T : RunTable) + (hm : MemRel s.memory M) (R : Rel msg ss0 st ss s) (hb : MemBudget G M g) (hG : G < 2 ^ 300) + (hat : At code msg pc (asked :: addr :: inOff :: inSize :: outOff :: outSize :: Tr) M g st ss + rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0xfa) + (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} (meets : Meets P runChild) + (hPok : ∀ c m ch, P c m ch → StaticOk c m ch) + (within : GasMeter.gasHeld evm.gas ≤ bound) {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) + (hto : toCode .staticcall (addr.toNat % 2 ^ 160) 0 = true ∨ + PreOk P st ss M g asked addr inOff inSize outOff outSize) + (hoks : T.oks.length = (machineCalls s.world).length) + (houts : T.outs.length = (machineCalls s.world).length) + (hgr : gasReads s.world ≤ T.gases.length) : + ∃ (ok : Bool) (out : ByteArray) (s' : State) (M' : ByteArray) (g' : Nat) + (st' : State.TransactionState) (ss' : Substate) (m : Evm .fusaka Nat) + (within' : GasMeter.gasHeld m.gas ≤ bound), + (∀ T'', ({ T with oks := T.oks ++ [ok], outs := T.outs ++ [out] } : RunTable).Le T'' → + Effect.apply (OS codes T'') call (.call .staticcall) + [asked, addr, inOff, inSize, outOff, outSize] s = + some (some (if ok then 1 else 0), s') ∧ RdRel (OS codes T'') s'.world out) ∧ + (∃ ev, s'.world = s.world ++ [ev] ∧ sent [ev] = 1 ∧ gasReads [ev] = 0 ∧ + (machineCalls [ev]).length = 1) ∧ + MemRel s'.memory M' ∧ Rel msg ss0 st' ss' s' ∧ MemBudget G M' g' ∧ g' ≤ g ∧ + At code msg (pc + 1) ((if ok then 1 else 0) :: Tr) M' g' st' ss' out m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + obtain ⟨calleeCode, route, hcode, hroute, hg, caller, mm, child, after, within', g', hPP, -, hcs, + hcsub, hms, hmv, hmc, hmt, htg, hmd, hmca, hmdp, hmgas, hg', hat', hrun'⟩ := + staticcall_back hat hlt hbyte hdepth meets within hrun hok + have hP := hPok _ _ _ hPP + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + obtain ⟨hb1, hb2, hbud, hfit⟩ := budget_grow2 (pre := (if decide (toAddressMasked addr ∉ + ss.accessedAddresses) then 2600 else 100) + + routeCost .fusaka (ss.accessedAddresses.insert (toAddressMasked addr)) route) hmod hb hG + (by omega) + -- The table with the call's flag and output. + let T1 : RunTable := { T with oks := T.oks ++ [child.error.isNone], outs := T.outs ++ [child.output] } + have hle1 : T.Le T1 := ⟨List.prefix_append _ _, List.prefix_append _ _, List.prefix_refl _, + List.prefix_refl _, List.prefix_refl _⟩ + let ev : Event := .call .staticcall [asked, addr] + (((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat outSize.toNat).read + inOff.toNat inSize.toNat) s.storage s.transient + have hev : ∀ T'', T1.Le T'' → + callFlag (OS codes T'') (s.world ++ [ev]) = (if child.error.isNone then 1 else 0) ∧ + RdRel (OS codes T'') (s.world ++ [ev]) child.output := by + intro T'' hle + have hok' : T''.oks.getD (machineCalls s.world).length false = child.error.isNone := by + rw [getD_of_prefix hle.1 (by simp [T1, hoks])] + simp [T1, hoks] + have hout' : T''.outs.getD (machineCalls s.world).length .empty = child.output := by + rw [getD_of_prefix hle.2.1 (by simp [T1, houts])] + simp [T1, houts] + have hresp : tabResp T''.oks T''.outs (machineCalls s.world).length .staticcall + (addr.toNat % 2 ^ 160) 0 + ((((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat outSize.toNat).read + inOff.toNat inSize.toNat).map BitVec.toNat) = (child.error.isNone, child.output) := by + rcases hto with hto | ⟨h1, hag, hER, hnd, hg3⟩ + · simp only [tabResp, hto, ite_true] + rw [hok', hout'] + · -- ECRECOVER: the source's answer, which the callee frame matches. + have htc : toCode .staticcall (addr.toNat % 2 ^ 160) 0 = false := by rw [h1]; decide + simp only [tabResp, htc, Bool.false_eq_true, ite_false] + have hrn : route = none := by + rcases route with _ | ⟨d, c'⟩ + · rfl + · have := hroute.2.1 + rw [hnd _ hcode] at this + cases this + subst hrn + have hmsg : AssembleCallPre.EcrecoverMsg mm := by + refine ⟨by rw [htg]; rfl, ?_, by simpa using hmdp, hmv, ?_⟩ + · have h1' : (toAddressMasked addr).toU256.toNat = 1 := by + rw [toNat_toU256_masked]; exact h1 + simp only [precompileAddress, hmca, routeAddr, h1'] + decide + · rw [hmgas] + simpa [routeCost] using hg3 + have hin : (((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat + outSize.toNat).read inOff.toNat inSize.toNat).map BitVec.toNat = + SolidCore.Solidity.Source.byteArrayToBytes mm.data := by + rw [hmd, ← read_eq2 hm] + rfl + rw [h1, hin] + exact AssembleCallPre.ecrecover_answer hag (hER _ _ _ hPP) hmsg + obtain ⟨hf, hr⟩ := OS_ans codes T'' s.world asked addr + (((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat outSize.toNat).read + inOff.toNat inSize.toNat) s.storage s.transient _ _ hresp hP.2.2 + refine ⟨hf, ?_⟩ + have := hr [] rfl + rw [List.append_nil] at this + exact this + -- SolarTV's STATICCALL under the table's oracle. + obtain ⟨s', happ, hsto, htr, hrd, hw, hmem'⟩ := staticcall_effectW (o := OS codes T1) (call := call) + (gas := asked) (addr := addr) (child := child) hm hb1 hb2 (hev T1 (RunTable.Le.refl _)).1 + (hev T1 (RunTable.Le.refl _)).2 + -- Under every extension it runs the same. + have hsame : ∀ T'', T1.Le T'' → + Effect.apply (OS codes T'') call (.call .staticcall) + [asked, addr, inOff, inSize, outOff, outSize] s = + Effect.apply (OS codes T1) call (.call .staticcall) + [asked, addr, inOff, inSize, outOff, outSize] s := by + intro T'' hle + have hmc1 : (machineCalls (s.world ++ [ev])).length = (machineCalls s.world).length + 1 := by + rw [machineCalls_static] + simp + obtain ⟨henv, hres⟩ := OS_le (codes := codes) hle (w := s.world ++ [ev]) + (by simp [T1, hmc1, hoks]) (by simp [T1, hmc1, houts]) (by simp [T1]) (by simp [T1]) + (by simp [T1, ev]; omega) + have hflag : callFlag (OS codes T'') (s.world ++ [ev]) = callFlag (OS codes T1) (s.world ++ [ev]) := by + simp only [callFlag, hres] + have hbyte : returndataByte (OS codes T'') (s.world ++ [ev]) = + returndataByte (OS codes T1) (s.world ++ [ev]) := by + funext i + simp only [returndataByte] + rw [henv] + simp only [ev] at henv hflag hbyte + simp only [Effect.apply, CallKind.shape, called, returndataSize, hflag, henv, hbyte] + refine ⟨child.error.isNone, child.output, s', _, g', (incorporateChild .fusaka caller child).state, + (incorporateChild .fusaka caller child).substate, after, within', fun T'' hle => ?_, + ⟨ev, hw, by simp [ev], by simp [ev], by simp [ev, machineCalls]⟩, hmem', ?_, ?_, + by omega, ?_, hrun'⟩ + · rw [hsame T'' hle, happ] + refine ⟨by cases child.error.isNone <;> rfl, ?_⟩ + rw [hw] + exact (hev T'' hle).2 + · -- Storage and the account are the caller's; the logs are the frame's, with no log of the callee. + have hso := staticcall_state hcode hroute hP.1 hcs hms hmv hmc hmt htg + refine ⟨fun k => ?_, ?_, ?_⟩ + · rw [(hso msg.currentTarget (List.not_mem_nil)).2.1, hsto] + exact R.storage k + · rw [(hso msg.currentTarget (List.not_mem_nil)).1] + exact R.account + · obtain ⟨L, hL1, hL2⟩ := R.logs + refine ⟨L, ?_, ?_⟩ + · have hlogs : (incorporateChild .fusaka caller child).substate.logs.toList = ss.logs.toList := by + unfold incorporateChild + split + · rename_i hn + have h0 := hP.2.1 hms (by simpa using hn) + rcases route with _ | ⟨d, c'⟩ <;> simp [Array.toList_append, h0, hcsub, routeSub] + · rcases route with _ | ⟨d, c'⟩ <;> simp [hcsub, routeSub] + rw [hlogs, hL1] + · rw [hw, List.filter_append] + simpa [ev, isLogE] using hL2 + · unfold MemBudget + rw [size_memoryWrite_of_fit, size_memoryExtend] + · omega + · intro h + simp only [ByteArray.size_extract] at h ⊢ + have hz : outSize ≠ 0 := by + intro hz + simp [hz] at h + have := hfit hz + rw [size_memoryExtend] + have := Nat.min_le_left outSize.toNat child.output.size + omega + · simpa using hat' + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallCut.staticcall_cut' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms staticcall_cut + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallCut.OS_agreeT' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms OS_agreeT + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallCut.execC_calls' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms execC_calls + +end SolidCore.Refinement.Solar.AssembleCallCut diff --git a/SolidCore/Refinement/Solar/AssembleCallExample.lean b/SolidCore/Refinement/Solar/AssembleCallExample.lean new file mode 100644 index 00000000..07c42d3b --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCallExample.lean @@ -0,0 +1,191 @@ +import SolidCore.Refinement.Solar.AssembleCallSeg + +/-! +# A STATICCALL to an address the call names: an example and mutants + +A program that makes a STATICCALL with all its gas to the address in the call data's word at +offset 4, with no input and 32 bytes of output at offset 0, then stores the call's flag at offset 0 +and returns that word. The checker without the no-call gate (`AssembleCut.checkCB`) accepts the +bytecode under a certificate that says the program makes calls; at every gas below `2 ^ 256`, every +run that meets the named hypotheses (`AssembleCallSeg.StaticRunner`, `AssembleCallSeg.CalleesRun`) +gives the program's result under the oracle of the run's table, which agrees with an open world. + +Rejected by evaluation: the bytecode reading the address at offset 5, the bytecode with +DELEGATECALL in place of STATICCALL, the certificate that says the program makes no call, and the +gated checker `AssembleCut.checkC` (programs without calls only). +-/ + +namespace SolidCore.Refinement.Solar.AssembleCallExample + +open SolidCore.Refinement.Solar SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCut SolidCore.Refinement.Solar.AssembleCallSeg +open SolidCore.Refinement.Final + +/-- PUSH1 32, PUSH0 x3, PUSH1 4 CALLDATALOAD, GAS, STATICCALL, then the flag stored at offset 0 +and returned. -/ +def prog : Assemble.Program := + { blocks := [[.op (.stack (.push 32)), .op (.stack (.push 0)), .op (.stack (.push 0)), + .op (.stack (.push 0)), .op (.stack (.push 4)), .effect .calldataload 1, .effect .gas 0, + .effect (.call .staticcall) 6, .op (.stack (.push 0)), .op .store, .op (.stack (.push 32)), + .op (.stack (.push 0)), .ret]] } + +def code : ByteArray := + ⟨#[0x60, 0x20, 0x5f, 0x5f, 0x5f, 0x60, 0x04, 0x35, 0x5a, 0xfa, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3]⟩ + +/-- The address read from the call data at offset 5. -/ +def mutantAddr : ByteArray := + ⟨#[0x60, 0x20, 0x5f, 0x5f, 0x5f, 0x60, 0x05, 0x35, 0x5a, 0xfa, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3]⟩ + +/-- DELEGATECALL (0xf4) in place of STATICCALL. -/ +def mutantKind : ByteArray := + ⟨#[0x60, 0x20, 0x5f, 0x5f, 0x5f, 0x60, 0x04, 0x35, 0x5a, 0xf4, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3]⟩ + +def cert : Assemble.Cert := + { offsets := [0], needs := [0], top := 2 ^ 140, costs := [13], types := [[]], calls := true } + +def maxs : List Nat := [0] + +theorem check_ok : checkCB prog code cert maxs = true := by decide +kernel + +theorem mutantAddr_fails : checkCB prog mutantAddr cert maxs = false := by decide +kernel + +theorem mutantKind_fails : checkCB prog mutantKind cert maxs = false := by decide +kernel + +/-- A certificate that says the program makes no call does not cover the STATICCALL. -/ +theorem nocalls_fails : checkCB prog code { cert with calls := false } maxs = false := by + decide +kernel + +/-- The gated checker takes programs without calls only. -/ +theorem gated_fails : checkC prog code cert maxs = false := by decide +kernel + +/-- **At every gas below `2 ^ 256`, every result of the bytecode is the program's**, under an oracle +that agrees with an open world, for every run meeting the named hypotheses. -/ +theorem bytecode (codes : SolidCore.Solidity.Shared.Account.BytesMap) (scope : SolarTV.Call → Prop) + (hP : ∀ gas, StaticRunner gas) (hQ : ∀ gas call, scope call → CalleesRun gas code call) : + ∀ gas, gas < 2 ^ 256 → ∀ call, scope call → ∃ (o : SolarTV.Machine.Oracle) (W : World), + W.Open ∧ SolidCore.Refinement.CallsAgree o W ∧ RunOracle.CertOk cert o ∧ + SolidCore.Refinement.Final.Within (SolarTV.evmirSem o) (ethLibWith gas) prog code (· = call) := + assembly_of_checkCB check_ok codes scope hP hQ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallExample.bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecode + +/-- The flag and RETURNDATASIZE, after the call, stored at offsets 0 and 32 and returned. -/ +def progRds : Assemble.Program := + { blocks := [[.op (.stack (.push 32)), .op (.stack (.push 0)), .op (.stack (.push 0)), + .op (.stack (.push 0)), .op (.stack (.push 4)), .effect .calldataload 1, .effect .gas 0, + .effect (.call .staticcall) 6, .op (.stack (.push 0)), .op .store, .effect .returndatasize 0, + .op (.stack (.push 32)), .op .store, .op (.stack (.push 64)), .op (.stack (.push 0)), .ret]] } + +def codeRds : ByteArray := + ⟨#[0x60, 0x20, 0x5f, 0x5f, 0x5f, 0x60, 0x04, 0x35, 0x5a, 0xfa, 0x5f, 0x52, 0x3d, 0x60, 0x20, 0x52, + 0x60, 0x40, 0x5f, 0xf3]⟩ + +/-- CALLDATASIZE (0x36) in place of RETURNDATASIZE. -/ +def mutantRds : ByteArray := + ⟨#[0x60, 0x20, 0x5f, 0x5f, 0x5f, 0x60, 0x04, 0x35, 0x5a, 0xfa, 0x5f, 0x52, 0x36, 0x60, 0x20, 0x52, + 0x60, 0x40, 0x5f, 0xf3]⟩ + +def certRds : Assemble.Cert := { cert with costs := [16] } + +theorem checkRds_ok : checkCB progRds codeRds certRds maxs = true := by decide +kernel + +theorem mutantRds_fails : checkCB progRds mutantRds certRds maxs = false := by decide +kernel + +/-- **The callee's return data size, read back**: at every gas below `2 ^ 256`, every result of the +bytecode is the program's, whose RETURNDATASIZE reads the table's output of the call. -/ +theorem bytecodeRds (codes : SolidCore.Solidity.Shared.Account.BytesMap) (scope : SolarTV.Call → Prop) + (hP : ∀ gas, StaticRunner gas) (hQ : ∀ gas call, scope call → CalleesRun gas codeRds call) : + ∀ gas, gas < 2 ^ 256 → ∀ call, scope call → ∃ (o : SolarTV.Machine.Oracle) (W : World), + W.Open ∧ SolidCore.Refinement.CallsAgree o W ∧ RunOracle.CertOk certRds o ∧ + SolidCore.Refinement.Final.Within (SolarTV.evmirSem o) (ethLibWith gas) progRds codeRds + (· = call) := + assembly_of_checkCB checkRds_ok codes scope hP hQ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallExample.bytecodeRds' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecodeRds + +/-- After the call, the whole return data copied to offset 0 and returned: RETURNDATASIZE PUSH0 +PUSH0 RETURNDATACOPY RETURNDATASIZE PUSH0 RETURN. -/ +def progRdc : Assemble.Program := + { blocks := [[.op (.stack (.push 32)), .op (.stack (.push 0)), .op (.stack (.push 0)), + .op (.stack (.push 0)), .op (.stack (.push 4)), .effect .calldataload 1, .effect .gas 0, + .effect (.call .staticcall) 6, .op (.stack (.push 0)), .op .store, .effect .returndatasize 0, + .op (.stack (.push 0)), .op (.stack (.push 0)), .effect .returndatacopy 3, + .effect .returndatasize 0, .op (.stack (.push 0)), .ret]] } + +def codeRdc : ByteArray := + ⟨#[0x60, 0x20, 0x5f, 0x5f, 0x5f, 0x60, 0x04, 0x35, 0x5a, 0xfa, 0x5f, 0x52, 0x3d, 0x5f, 0x5f, 0x3e, + 0x3d, 0x5f, 0xf3]⟩ + +/-- CODECOPY (0x39) in place of RETURNDATACOPY. -/ +def mutantRdc : ByteArray := + ⟨#[0x60, 0x20, 0x5f, 0x5f, 0x5f, 0x60, 0x04, 0x35, 0x5a, 0xfa, 0x5f, 0x52, 0x3d, 0x5f, 0x5f, 0x39, + 0x3d, 0x5f, 0xf3]⟩ + +def certRdc : Assemble.Cert := { cert with costs := [17] } + +theorem checkRdc_ok : checkCB progRdc codeRdc certRdc maxs = true := by decide +kernel + +theorem mutantRdc_fails : checkCB progRdc mutantRdc certRdc maxs = false := by decide +kernel + +/-- **The callee's return data, copied and returned**: return data bubbling. At every gas below +`2 ^ 256`, every result of the bytecode is the program's. -/ +theorem bytecodeRdc (codes : SolidCore.Solidity.Shared.Account.BytesMap) (scope : SolarTV.Call → Prop) + (hP : ∀ gas, StaticRunner gas) (hQ : ∀ gas call, scope call → CalleesRun gas codeRdc call) : + ∀ gas, gas < 2 ^ 256 → ∀ call, scope call → ∃ (o : SolarTV.Machine.Oracle) (W : World), + W.Open ∧ SolidCore.Refinement.CallsAgree o W ∧ RunOracle.CertOk certRdc o ∧ + SolidCore.Refinement.Final.Within (SolarTV.evmirSem o) (ethLibWith gas) progRdc codeRdc + (· = call) := + assembly_of_checkCB checkRdc_ok codes scope hP hQ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallExample.bytecodeRdc' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecodeRdc + + +/-! ## A STATICCALL to ECRECOVER -/ + +/-- PUSH1 32, PUSH0, PUSH1 128, PUSH0, PUSH1 1, GAS, STATICCALL: ECRECOVER on the 128 bytes of +memory at 0, its 32-byte output written at 0; the flag stored at 64, and the output returned. -/ +def progEc : Assemble.Program := + { blocks := [[.op (.stack (.push 32)), .op (.stack (.push 0)), .op (.stack (.push 128)), + .op (.stack (.push 0)), .op (.stack (.push 1)), .effect .gas 0, + .effect (.call .staticcall) 6, .op (.stack (.push 64)), .op .store, .op (.stack (.push 32)), + .op (.stack (.push 0)), .ret]] } + +def codeEc : ByteArray := + ⟨#[0x60, 0x20, 0x5f, 0x60, 0x80, 0x5f, 0x60, 0x01, 0x5a, 0xfa, 0x60, 0x40, 0x52, 0x60, 0x20, 0x5f, + 0xf3]⟩ + +/-- The STATICCALL to address 2 (SHA-256) in place of ECRECOVER. -/ +def mutantEcAddr : ByteArray := + ⟨#[0x60, 0x20, 0x5f, 0x60, 0x80, 0x5f, 0x60, 0x02, 0x5a, 0xfa, 0x60, 0x40, 0x52, 0x60, 0x20, 0x5f, + 0xf3]⟩ + +def certEc : Assemble.Cert := + { offsets := [0], needs := [0], top := 2 ^ 140, costs := [12], types := [[]], calls := true } + +theorem checkEc_ok : checkCB progEc codeEc certEc maxs = true := by decide +kernel + +theorem mutantEcAddr_fails : checkCB progEc mutantEcAddr certEc maxs = false := by decide +kernel + +/-- **The ECRECOVER bytecode, at every gas below `2 ^ 256`**: every result is the program's +under an oracle that agrees with an open world, in which the call to address 1 is answered by the +source's ECRECOVER; `CalleesRun` admits the call through `AssembleCallCut.PreOk`, which names +`AssembleCallPre.EcrecoverAgree`. -/ +theorem bytecodeEc (codes : SolidCore.Solidity.Shared.Account.BytesMap) + (scope : SolarTV.Call → Prop) (hP : ∀ gas, StaticRunner gas) + (hQ : ∀ gas call, scope call → CalleesRun gas codeEc call) : + ∀ gas, gas < 2 ^ 256 → ∀ call, scope call → ∃ (o : SolarTV.Machine.Oracle) (W : World), + W.Open ∧ SolidCore.Refinement.CallsAgree o W ∧ RunOracle.CertOk certEc o ∧ + SolidCore.Refinement.Final.Within (SolarTV.evmirSem o) (ethLibWith gas) progEc codeEc (· = call) := + assembly_of_checkCB checkEc_ok codes scope hP hQ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallExample.bytecodeEc' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecodeEc + +end SolidCore.Refinement.Solar.AssembleCallExample diff --git a/SolidCore/Refinement/Solar/AssembleCallPre.lean b/SolidCore/Refinement/Solar/AssembleCallPre.lean new file mode 100644 index 00000000..9bbbeae6 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCallPre.lean @@ -0,0 +1,184 @@ +import SolidCore.Refinement.Solar.AssembleCall +import SolidCore.Refinement.Solar.AssembleCallWorld + +/-! +# STATICCALL to ECRECOVER: EthLib's precompile and SolidCore's answer + +The source semantics answers a static call with no value to a precompile address itself +(SourceOracleSat's failResp, by Precompile.execute?), while EthLib runs its own +precompile. This file connects the two for ECRECOVER (address 1): + +* processMessage_ecrecover, meets_ecrecover: EthLib's runner of messages, on a message to + ECRECOVER with at least 3000 gas (its price), ends with no error, with + Precompiles.Ecrecover.compute of the call data as output, and with the substate it was sent + with (so no log). Proved from EthLib's processMessage. +* EcrecoverAgree, the **named hypothesis**: SolidCore's Crypto.ecrecoverBytes and EthLib's + Ecrecover.compute give the same bytes on every input. They are two independent implementations of + secp256k1 recovery (with two Keccak implementations), checked against each other only by the test + vectors of PrecompileParity, not proved equal here. +* ecrecover_answer: under EcrecoverAgree, SolidCore's answer to the call is the callee frame's flag + and output, the premise a STATICCALL cut to ECRECOVER needs in place of the run's table. + +AssembleCallCut.staticcall_cut uses these for a STATICCALL to address 1: there the source's answer, not +the run's table, gives the flag and return data, and the callee frame matches it. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCallPre + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Witness +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open EthLib.Execution.State + +/-- ECRECOVER at a frame with the gas for it: the frame ends with no new error, the precompile's +output, and the substate and state it had. -/ +theorem runPrecompile_ecrecover {evm after : Evm .fusaka Nat} (hg : 3000 ≤ evm.gas) + (h : runPrecompile .fusaka 1 evm = some after) : + after.error = evm.error ∧ after.output = Precompiles.Ecrecover.compute evm.message.data ∧ + after.substate = evm.substate ∧ after.state = evm.state := by + unfold runPrecompile at h + have hrun : Precompiles.run .fusaka 1 evm.message.data (GasMeter.gasLeft evm.gas) = + some (.ok (Precompiles.Ecrecover.compute evm.message.data)) := by + simp only [Precompiles.run, show Precompiles.isPrecompile Fork.fusaka 1 = true by decide, + Bool.not_true, Bool.false_eq_true, ite_false, Precompiles.Ecrecover.ecrecover] + have : ¬ GasMeter.gasLeft evm.gas < Precompiles.Ecrecover.GAS_ECRECOVER := by + show ¬ evm.gas < 3000 + omega + rw [ite_cond_eq_false _ _ (eq_false this)] + rfl + rw [hrun] at h + simp only at h + have hp : Precompiles.price .fusaka 1 evm.message.data = some 3000 := by + simp [Precompiles.price, show Precompiles.isPrecompile Fork.fusaka 1 = true by decide, + Precompiles.Ecrecover.GAS_ECRECOVER] + rw [hp] at h + simp only [Option.getD_some] at h + split at h + · rename_i heq + have : ¬ evm.gas < 3000 := by omega + simp only [GasMeter.charge, this, ite_false] at heq + cases heq + · rename_i hc + simp only [Option.some.injEq] at h + subst h + refine ⟨rfl, ?_, rfl, rfl⟩ + dsimp only + +/-- ECRECOVER at a frame with the gas for it runs. -/ +theorem runPrecompile_ecrecover_isSome {evm : Evm .fusaka Nat} (hg : 3000 ≤ evm.gas) : + (runPrecompile .fusaka 1 evm).isSome = true := by + unfold runPrecompile + have hrun : Precompiles.run .fusaka 1 evm.message.data (GasMeter.gasLeft evm.gas) = + some (.ok (Precompiles.Ecrecover.compute evm.message.data)) := by + simp only [Precompiles.run, show Precompiles.isPrecompile Fork.fusaka 1 = true by decide, + Bool.not_true, Bool.false_eq_true, ite_false, Precompiles.Ecrecover.ecrecover] + have : ¬ GasMeter.gasLeft evm.gas < Precompiles.Ecrecover.GAS_ECRECOVER := by + show ¬ evm.gas < 3000 + omega + rw [ite_cond_eq_false _ _ (eq_false this)] + rfl + rw [hrun] + simp only + split <;> rfl + +/-- **A message to ECRECOVER with the gas for it succeeds with EthLib's output**, keeping the +substate it was sent with. -/ +theorem processMessage_ecrecover {m : Message .fusaka} {state : TransactionState} {substate : Substate} + {ended : { evm : Evm .fusaka Nat // GasMeter.gasHeld evm.gas ≤ m.gas }} + (hpa : precompileAddress .fusaka m = some 1) (hdis : m.disablePrecompiles = false) + (hval : m.value = 0) (hg : 3000 ≤ m.gas) + (h : processMessage .fusaka m state substate = .ok ended) : + ended.val.error = none ∧ ended.val.output = Precompiles.Ecrecover.compute m.data ∧ + ended.val.substate = substate := by + rw [processMessage] at h + obtain ⟨ended0, hdo, rolled⟩ := EthLib.Base.map_ok_iff.mp h + have ht : ¬ (m.shouldTransferValue = true ∧ m.value ≠ 0) := by simp [hval] + simp only [ht, ite_false, hpa, hdis, Bool.false_eq_true, pure, Except.pure, bind, Except.bind] + at hdo + split at hdo + · rename_i after heq + rw [if_neg ht] at heq + cases hdo + subst rolled + obtain ⟨e1, e2, e3, -⟩ := runPrecompile_ecrecover (by simp only [startFrame]; exact hg) heq + simp only [startFrame] at e1 e2 e3 + have herr : after.error = none := e1 + refine ⟨?_, ?_, ?_⟩ + · unfold rollbackOnError + split + · rename_i hx; rw [herr] at hx; cases hx + · exact herr + · unfold rollbackOnError + split + · rename_i hx; rw [herr] at hx; cases hx + · exact e2 + · unfold rollbackOnError + split + · rename_i hx; rw [herr] at hx; cases hx + · exact e3 + · rename_i heq + rw [if_neg ht] at heq + have := runPrecompile_ecrecover_isSome (evm := startFrame m (startState .fusaka m state) substate + (GasMeter.start m.gas m.reservoir)) (by simp only [startFrame]; exact hg) + rw [heq] at this + cases this + +/-- A message the runner sends to ECRECOVER with its price in gas: a call (it has a target) whose +code address is ECRECOVER's, with precompiles enabled, no value and at least 3000 gas. -/ +def EcrecoverMsg (m : Message .fusaka) : Prop := + m.target.isSome = true ∧ precompileAddress .fusaka m = some 1 ∧ m.disablePrecompiles = false ∧ + m.value = 0 ∧ 3000 ≤ m.gas + +/-- What ECRECOVER's frame ends with: no error, EthLib's output, the substate it was sent with. -/ +def EcrecoverRuns (caller : Evm .fusaka Nat) (m : Message .fusaka) (child : Evm .fusaka Nat) : Prop := + EcrecoverMsg m → child.error = none ∧ child.output = Precompiles.Ecrecover.compute m.data ∧ + child.substate = caller.substate.child + +/-- **The interpreter's runner of messages runs ECRECOVER** on every message with its price. -/ +theorem meets_ecrecover (bound : Nat) : + Meets (bound := bound) EcrecoverRuns (processRunner .fusaka (Meter := Nat) bound) := by + refine ⟨fun caller m lt ended h hm => ?_, (meets_process .fusaka bound).aborts⟩ + obtain ⟨htg, hpa, hdis, hval, hg⟩ := hm + unfold processRunner at h + split at h + · exact processMessage_ecrecover hpa hdis hval hg h + · rename_i hnone + rw [hnone] at htg + cases htg + +/-- **Named hypothesis**: SolidCore's ECRECOVER (Crypto.ecrecoverBytes on the normalized input) +and EthLib's (Precompiles.Ecrecover.compute) give the same bytes on every call data. -/ +def EcrecoverAgree : Prop := + ∀ d : ByteArray, SolidCore.Solidity.Source.bytesToByteArray + (SolidCore.Solidity.Shared.Crypto.ecrecoverBytes + (SolidCore.Solidity.Shared.Precompile.normalizeBytes (SolidCore.Solidity.Source.byteArrayToBytes d))) = + Precompiles.Ecrecover.compute d + +/-- SolidCore answers a static call with no value to address 1 as ECRECOVER, with success. -/ +theorem failResp_ecrecover (input : List Nat) : + failResp .staticcall 1 0 input = (true, SolidCore.Solidity.Source.bytesToByteArray + (SolidCore.Solidity.Shared.Crypto.ecrecoverBytes + (SolidCore.Solidity.Shared.Precompile.normalizeBytes input))) := by + have hk : SolidCore.Solidity.Shared.Precompile.kindOfAddress? 1 = + some SolidCore.Solidity.Shared.Precompile.Kind.ecrecover := by decide + simp [failResp, hk, SolidCore.Solidity.Shared.Precompile.execute?] + +/-- **SolidCore's answer to a STATICCALL to ECRECOVER is the callee frame's flag and output**, under +the named hypothesis EcrecoverAgree, for every frame the runner ends a priced ECRECOVER message +with. -/ +theorem ecrecover_answer (hagree : EcrecoverAgree) {caller child : Evm .fusaka Nat} + {m : Message .fusaka} (hruns : EcrecoverRuns caller m child) (hm : EcrecoverMsg m) : + failResp .staticcall 1 0 (SolidCore.Solidity.Source.byteArrayToBytes m.data) = + (child.error.isNone, child.output) := by + obtain ⟨he, ho, -⟩ := hruns hm + rw [failResp_ecrecover, hagree, he, ho] + rfl + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallPre.meets_ecrecover' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms meets_ecrecover + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallPre.ecrecover_answer' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms ecrecover_answer + +end SolidCore.Refinement.Solar.AssembleCallPre diff --git a/SolidCore/Refinement/Solar/AssembleCallSeg.lean b/SolidCore/Refinement/Solar/AssembleCallSeg.lean new file mode 100644 index 00000000..e216176a --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCallSeg.lean @@ -0,0 +1,1437 @@ +import SolidCore.Refinement.Solar.AssembleCallCut + +/-! +# Code with STATICCALLs, block by block, at the frame's own gas + +The checker without the certificate's no-call gate (`AssembleCut.checkCB`) cuts a block at each +STATICCALL (`AssembleCutSim.blockOkC`), and `segS` reads each segment back from a run that +succeeds as `AssembleCut.seg` does, with the run's table grown at each STATICCALL by the callee +frame's flag and output (`AssembleCallCut.staticcall_cut`). The oracle of a run's table is +`AssembleCallWorld.OS`: it answers the `n`-th STATICCALL to code from the table, and agrees with an +open world (`AssembleCallWorld.OS_agree`), so the composition with the source's specification +applies to it. + +RETURNDATASIZE and RETURNDATACOPY are cuts too: `segS` keeps the return data of the frame related to +the oracle of every extension of the table (`AssembleEffects.RdRel`), so they read the last call's +output from the table, and a RETURNDATACOPY past the return data, which EthLib fails, is no run +that succeeds (`rdc_back`). + +The final theorems name what they assume of the run, beside `AssembleCallCut.StaticOk`'s +`StaticNoLogs` and `OutputFits`: + +* `CalleesOk`: at every STATICCALL of the run, the callee address is not a precompile's, or it is + ECRECOVER's and `AssembleCallCut.PreOk` holds (the named `AssembleCallPre.EcrecoverAgree`, at + least 3000 gas passed on, no delegation at address 1); then the source's answer gives the flag + and return data and EthLib's ECRECOVER frame matches it. For calls to code it is a condition on + the addresses the run calls only, not on any state: the callee's code (and, for an + EIP-7702 delegation, its delegate's) is derived from the run succeeding + (`AssembleCall.staticcall_routes_of_ok`), and delegated callees are covered + (`AssembleCall.staticcall_back` follows EthLib's `callKindRoute` along any route). +-/ + +namespace SolidCore.Refinement.Solar.AssembleCallSeg + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Witness SolidCore.Refinement.Final +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.RunOracle +open SolidCore.Refinement.Solar.AssembleCut SolidCore.Refinement.Solar.AssembleEffects +open SolidCore.Refinement.Solar.AssembleLoop SolidCore.Refinement.Solar.AssembleRun +open SolidCore.Refinement.Solar.AssembleRunLoop +open SolidCore.Refinement.Solar.AssembleCall SolidCore.Refinement.Solar.AssembleCallWorld +open SolidCore.Refinement.Solar.AssembleCallCut SolidCore.Refinement.Solar.AssembleDyn +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +/-! ## The named hypothesis on the run's callees -/ + +/-- A STATICCALL to `addr` is answered by the run's table: `addr` is no precompile's address. +Nothing about the state: the callee's code and route come from the run (`staticcall_back`). -/ +def CalleeOk (addr : U256) : Prop := + toCode .staticcall (addr.toNat % 2 ^ 160) 0 = true + +/-- **Named hypothesis on a run**: every frame of the code that the run goes on from to `fin` and +that is at a STATICCALL calls an address that is no precompile's (`CalleeOk`), or calls ECRECOVER +(address 1) as `AssembleCallCut.PreOk` asks: under the named `AssembleCallPre.EcrecoverAgree`, with +an account at address 1 that is no delegation and at least 3000 gas passed on. -/ +def CalleesOk (code : ByteArray) (msg : Message .fusaka) + (P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop) (bound : Nat) + (runChild : MessageRunner .fusaka Nat bound) (fin : Evm .fusaka Nat) : Prop := + ∀ {e : Evm .fusaka Nat} {within : GasMeter.gasHeld e.gas ≤ bound} {pc : Nat} + {asked addr inOff inSize outOff outSize : U256} + {S : List U256} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {rd : ByteArray}, + At code msg pc (asked :: addr :: inOff :: inSize :: outOff :: outSize :: S) M g st ss rd e → + (hlt : pc < code.size) → code[pc] = 0xfa → + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild e within = .ok fin → + CalleeOk addr ∨ PreOk P st ss M g asked addr inOff inSize outOff outSize + +/-- What the final theorems ask of the runner's callee frames: `StaticOk`, and EthLib's ECRECOVER +on priced messages to address 1 (proved, `AssembleCallPre.meets_ecrecover`). -/ +def StaticOkE (caller : Evm .fusaka Nat) (m : Message .fusaka) (child : Evm .fusaka Nat) : Prop := + StaticOk caller m child ∧ AssembleCallPre.EcrecoverRuns caller m child + +/-! ## The table and the frame's world -/ + +theorem sent_append (w v : List Event) : sent (w ++ v) = sent w + sent v := by + simp [sent, List.filter_append] + +theorem gasReads_append (w v : List Event) : gasReads (w ++ v) = gasReads w + gasReads v := by + simp [gasReads, List.filter_append] + +theorem machineCalls_append : ∀ w v : List Event, machineCalls (w ++ v) = machineCalls w ++ machineCalls v + | [], v => rfl + | e :: w, v => by + cases e <;> simp [machineCalls, machineCalls_append w v] + +/-- The table holds one flag and one output for each message the frame sent, and the frame's +messages are its calls. -/ +def TabInv (T : RunTable) (w : List Event) : Prop := + sent w = T.oks.length ∧ (machineCalls w).length = T.oks.length ∧ T.outs.length = T.oks.length + +theorem TabInv.of_seg {T : RunTable} {w w' : List Event} (hs : sent w' = sent w) + (hm : machineCalls w' = machineCalls w) (h : TabInv T w) : TabInv T w' := + ⟨hs.trans h.1, by rw [hm]; exact h.2.1, h.2.2⟩ + +theorem TabInv.read {T : RunTable} {w : List Event} {n : String} (h : TabInv T w) : + TabInv T (w ++ [.read n]) := + ⟨by rw [sent_append]; simpa using h.1, by rw [machineCalls_append]; simpa [machineCalls] using h.2.1, + h.2.2⟩ + +theorem TabInv.log {T : RunTable} {w : List Event} {t : List Word} {d : List SolarTV.Memory.Byte} + (h : TabInv T w) : TabInv T (w ++ [.log t d]) := + ⟨by rw [sent_append]; simpa using h.1, by rw [machineCalls_append]; simpa [machineCalls] using h.2.1, + h.2.2⟩ + +/-- Under every extension of the table, a block runs as its segment under the table does, then +from the instruction the segment stopped at. -/ +theorem exec_OS (codes : SolidCore.Solidity.Shared.Account.BytesMap) {T T'' : RunTable} + (hle : T.Le T'') {call : Call} {b : Nat} {is : List Assemble.Instr} {S : List Word} {s : State} + (hg : gasReads s.world ≤ T.gases.length) (hs : TabInv T s.world) : + SolarTV.EVM.Program.exec (OS codes T'') call b is S s = match execC (OS codes T) call b is S s with + | .done r => r + | .cut i rest S' s' => SolarTV.EVM.Program.exec (OS codes T'') call b (i :: rest) S' s' := by + rw [exec_eq_execC, ← (execC_agree (OS_agreeT codes hle (ng := T.gases.length) + (ns := sent s.world) le_rfl (by rw [hs.1]) (by rw [hs.1, hs.2.2])) call b is S s hg le_rfl).1] + rfl + +theorem lowerInstrs_sc (p : Assemble.Program) (c : Cert) (b : Nat) (rest : List Assemble.Instr) : + lowerInstrs p c b (.effect (.call .staticcall) 6 :: rest) = .op 0xfa :: lowerInstrs p c b rest := by + simp [lowerInstrs, turnedElse, dropped, lowerInstr] + +theorem exec_scC {o : Oracle} {call : Call} {b : Nat} {rest : List Assemble.Instr} + {a1 a2 a3 a4 a5 a6 w : Word} {S : List Word} {s s2 : State} + (happ : Effect.apply o call (.call .staticcall) [a1, a2, a3, a4, a5, a6] s = some (some w, s2)) + (h : S.length < 1024) : + SolarTV.EVM.Program.exec o call b (.effect (.call .staticcall) 6 :: rest) + (a1 :: a2 :: a3 :: a4 :: a5 :: a6 :: S) s = + SolarTV.EVM.Program.exec o call b rest (w :: S) s2 := by + simp [SolarTV.EVM.Program.exec, happ, show ¬ 1024 < S.length + 1 by omega] + + +/-- GAS under the oracle of a table whose next gas is `v`. -/ +theorem exec_gasS (codes : SolidCore.Solidity.Shared.Account.BytesMap) {T : RunTable} {call : Call} + {b : Nat} {rest : List Assemble.Instr} {S : List Word} {s : State} {v : Nat} + (hT : T.gases.getD (gasReads s.world) 0 = v) (hS : S.length < 1024) : + SolarTV.EVM.Program.exec (OS codes T) call b (.effect .gas 0 :: rest) S s = + SolarTV.EVM.Program.exec (OS codes T) call b rest (BitVec.ofNat 256 v :: S) + { s with world := s.world ++ [.read "gas"] } := by + have happ : Effect.apply (OS codes T) call .gas [] s = + some (some (BitVec.ofNat 256 v), { s with world := s.world ++ [.read "gas"] }) := by + simp only [Effect.apply] + rw [gasOracle_gas, hT] + simp [SolarTV.EVM.Program.exec, happ, show ¬ 1024 < S.length + 1 by omega] + + +theorem machineCalls_read (w : List Event) (n : String) : + machineCalls (w ++ [.read n]) = machineCalls w := by + rw [machineCalls_append]; simp [machineCalls] + +theorem machineCalls_log (w : List Event) (t : List Word) (d : List SolarTV.Memory.Byte) : + machineCalls (w ++ [.log t d]) = machineCalls w := by + rw [machineCalls_append]; simp [machineCalls] + +/-- The table's oracle reads a world, but GAS, only through the frame's calls. -/ +theorem OS_env_world (codes : SolidCore.Solidity.Shared.Account.BytesMap) (T : RunTable) + {w w' : List Event} (h : machineCalls w' = machineCalls w) {n : String} (hn : n ≠ "gas") + (a : List Word) : (OS codes T).env n w' a = (OS codes T).env n w a := by + simp only [OS, gasOracle, hn, false_and, ite_false] + simp only [envOracle, ethOracle, tabOracle_envEq, tabEnv, h] + +/-- The return data the table's oracle answers stays while the frame makes no call. -/ +theorem rdRel_world (codes : SolidCore.Solidity.Shared.Account.BytesMap) {T : RunTable} + {w w' : List Event} {rd : ByteArray} (h : machineCalls w' = machineCalls w) + (hr : RdRel (OS codes T) w rd) : RdRel (OS codes T) w' rd := by + obtain ⟨h1, h2⟩ := hr + refine ⟨?_, fun i hi => ?_⟩ + · have := OS_env_world codes T h (n := "returndatasize") (by decide) [] + simp only [returndataSize] at h1 ⊢ + rw [this]; exact h1 + · have := OS_env_world codes T h (n := "returndata") (by decide) [BitVec.ofNat 256 i] + have h3 := h2 i hi + simp only [returndataByte] at h3 ⊢ + rw [this]; exact h3 + +/-- Before any call, the table's oracle answers no return data. -/ +theorem rdRel_nil (codes : SolidCore.Solidity.Shared.Account.BytesMap) (T : RunTable) : + RdRel (OS codes T) [] ByteArray.empty := + ⟨by simp [returndataSize, OS, gasOracle, envOracle, ethOracle, tabOracle_envEq, tabEnv, machineCalls, + envRead], fun i hi => by simp at hi⟩ + +theorem lowerInstrs_rds (p : Assemble.Program) (c : Cert) (b : Nat) (rest : List Assemble.Instr) : + lowerInstrs p c b (.effect .returndatasize 0 :: rest) = .op 0x3d :: lowerInstrs p c b rest := by + simp [lowerInstrs, turnedElse, dropped, lowerInstr] + +theorem exec_rdsC {o : Oracle} {call : Call} {b : Nat} {rest : List Assemble.Instr} + {S : List Word} {s : State} {v : Word} (hv : o.env "returndatasize" s.world [] = v) + (h : S.length < 1024) : + SolarTV.EVM.Program.exec o call b (.effect .returndatasize 0 :: rest) S s = + SolarTV.EVM.Program.exec o call b rest (v :: S) s := by + simp [SolarTV.EVM.Program.exec, SolarTV.Machine.Effect.apply, hv, show ¬ 1024 < S.length + 1 by omega] + +/-- RETURNDATASIZE (EIP-211) pushes the size of the frame's return data, for 2 gas. -/ +theorem returndatasize_rule {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {stack : List U256} + {memory : ByteArray} {gas : Nat} {st : State.TransactionState} {ss : Substate} {rd : ByteArray} + (hlt : pc < code.size) (hbyte : code[pc] = 0x3d) (hgas : 2 ≤ gas) + (hstack : stack.length < STACK_LIMIT) : + Hoare .fusaka (At code msg pc stack memory gas st ss rd) + (At code msg (pc + 1) (BitVec.ofNat 256 rd.size :: stack) memory (gas - 2) st ss rd) := by + apply At.rule hlt hbyte (ofByte_of_decode (op := .returndatasize) rfl (by decide)) rfl + rintro evm ⟨hcode, hj, hm, hpc, hst, hmem, hg, hrun, herr, hout, hs, hss, hrd⟩ + rw [readFrame_of_length_lt (by rw [hst]; exact hstack), + charge_nat (by rw [hg, show OPCODE_RETURNDATASIZE = 2 from rfl]; exact hgas)] + refine ⟨_, rfl, hcode, hj, hm, by simp [hpc], ?_, hmem, by simp [hg, OPCODE_RETURNDATASIZE, BASE], + hrun, herr, hout, hs, hss, hrd⟩ + simp [hst, hg, hrd, OPCODE_RETURNDATASIZE, BASE, GasMeter.gasLeft] + +/-- **RETURNDATASIZE in a run that succeeds**: the frame had the gas for it, and the run goes on +from the frame after it, with the size of its return data pushed. -/ +theorem rds_back {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {T : List Word} + {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} {rd : ByteArray} + {evm : Evm .fusaka Nat} (hat : At code msg pc T M g st ss rd evm) (hlt : pc < code.size) + (hbyte : code[pc] = 0x3d) (hstack : T.length < STACK_LIMIT) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + 2 ≤ g ∧ ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) (BitVec.ofNat 256 rd.size :: T) M (g - 2) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + by_cases hg : 2 ≤ g + · obtain ⟨m, hr, hm⟩ := returndatasize_rule hlt hbyte hg hstack evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc T M g st ss rd) (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, -, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .returndatasize := by + rw [hbyte] + exact ofByte_of_decode rfl (by decide) + rw [step_of_instruction hlt decoded rfl] + simp [readFrame, chargeGas, GasMeter.charge, hgas, OPCODE_RETURNDATASIZE, BASE, + show g < 2 by omega, bind, Except.bind] + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rw [hf.2.1] at hok + cases hok + + +/-- The table's oracle and that of any extension answer alike, but GAS, at a world whose calls the +table answers. -/ +theorem OS_env_ext (codes : SolidCore.Solidity.Shared.Account.BytesMap) {T T3 : RunTable} + (hle : T.Le T3) {w : List Event} (hm : (machineCalls w).length ≤ T.oks.length) + (hm' : (machineCalls w).length ≤ T.outs.length) (hg : gasReads w ≤ T.gases.length) + {n : String} (hn : n ≠ "gas") (a : List Word) : + (OS codes T3).env n w a = (OS codes T).env n w a := by + by_cases h0 : (machineCalls w).length = 0 + · have hnil : machineCalls w = [] := List.eq_nil_of_length_eq_zero h0 + simp only [OS, gasOracle, hn, false_and, ite_false] + simp only [envOracle, ethOracle, tabOracle_envEq, tabEnv, hnil] + split <;> simp_all + · exact (OS_le (codes := codes) hle hm hm' (by omega) (by omega) hg).1 n a + +theorem instruction_returndatacopy : + instruction (Meter := Nat) .fusaka .returndatacopy = some returndatacopyStep := by + simp [instruction, stackOnlyStep, controlFlowStep, memoryDataStep, HOrElse.hOrElse, + OrElse.orElse, Option.orElse] + +/-- RETURNDATACOPY (EIP-211) of a range within the return data: 3, 3 gas a word and the growth of +memory, then the bytes of the return data written. -/ +theorem returndatacopy_rule {code : ByteArray} {msg : Message .fusaka} {pc : Nat} + {start offset size : U256} {rest : List U256} {memory : ByteArray} {gas : Nat} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray} + (hlt : pc < code.size) (hbyte : code[pc] = 0x3e) (hfit : offset.toNat + size.toNat ≤ rd.size) + (hgas : 3 + 3 * wordCount size.toNat + (extendMemory memory.size [(start, size)]).cost ≤ gas) : + Hoare .fusaka (At code msg pc (start :: offset :: size :: rest) memory gas st ss rd) + (At code msg (pc + 1) rest + (memoryWrite (memoryExtend memory (extendMemory memory.size [(start, size)]).expandBy) + start.toNat (memoryReadBytes rd offset.toNat size.toNat)) + (gas - (3 + 3 * wordCount size.toNat + (extendMemory memory.size [(start, size)]).cost)) + st ss rd) := by + apply At.rule hlt hbyte (ofByte_of_decode (op := .returndatacopy) rfl (by decide)) + instruction_returndatacopy + rintro evm ⟨hcode, hj, hm, hpc, hst, hmem, hg, hrun', herr, hout, hs, hss, hrd⟩ + rw [returndatacopyStep_cons hst (by rw [hrd]; exact hfit)] + dsimp only + rw [show OPCODE_RETURNDATACOPY_BASE = 3 from rfl, show OPCODE_RETURNDATACOPY_PER_WORD = 3 from rfl, + hmem, hg, hrd, charge_nat hgas] + exact ⟨_, rfl, hcode, hj, hm, by simp [hpc], rfl, rfl, rfl, hrun', herr, hout, hs, hss, rfl⟩ + +/-- RETURNDATACOPY that cannot pay fails out of gas. -/ +theorem returndatacopyStep_oog {e : Evm .fusaka Nat} {d off sz : U256} {T : List U256} + (h : e.stack.val = d :: off :: sz :: T) + (hc : GasMeter.charge e.gas (OPCODE_RETURNDATACOPY_BASE + OPCODE_RETURNDATACOPY_PER_WORD * + wordCount sz.toNat + (extendMemory e.memory.size [(d, sz)]).cost) = .error .outOfGas) : + returndatacopyStep e = .error .outOfGas := by + have hstack : e.stack = ⟨d :: off :: sz :: T, h ▸ e.stack.property⟩ := Subtype.ext h + simp only [returndatacopyStep, popWord, chargeGas, hstack, Stack.pop] + simp [hc, bind, Except.bind, pure, Except.pure, throw, throwThe, MonadExceptOf.throw] + +/-- **RETURNDATACOPY in a run that succeeds**: the range was within the return data, the frame had +the gas for the copy and the growth of memory, and the run goes on from the frame after it. -/ +theorem rdc_back {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {d off sz : Word} + {T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {rd : ByteArray} {evm : Evm .fusaka Nat} (hat : At code msg pc (d :: off :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x3e) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + off.toNat + sz.toNat ≤ rd.size ∧ + 3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost ≤ g ∧ + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) T + (memoryWrite (memoryExtend M (extendMemory M.size [(d, sz)]).expandBy) + d.toNat (memoryReadBytes rd off.toNat sz.toNat)) + (g - (3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost)) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + have decoded : Op.ofByte .fusaka (0x3e : UInt8) = some .returndatacopy := + ofByte_of_decode rfl (by decide) + by_cases hg : 3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost ≤ g + · by_cases hfit : off.toNat + sz.toNat ≤ rd.size + · obtain ⟨m, hr, hm⟩ := returndatacopy_rule hlt hbyte hfit hg evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hfit, hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc (d :: off :: sz :: T) M g st ss rd) + (Faulted .outOfBoundsRead st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -, -, -, -, -, hrd⟩ := hat' + subst hcode hpc + rw [step_of_instruction hlt (by rw [hbyte]; exact decoded) instruction_returndatacopy] + have hpaid : GasMeter.charge e.gas (OPCODE_RETURNDATACOPY_BASE + + OPCODE_RETURNDATACOPY_PER_WORD * wordCount sz.toNat + + (extendMemory e.memory.size [(d, sz)]).cost) = .ok (g - (3 + 3 * wordCount sz.toNat + + (extendMemory M.size [(d, sz)]).cost)) := by + rw [hmem, hgas, show OPCODE_RETURNDATACOPY_BASE = 3 from rfl, + show OPCODE_RETURNDATACOPY_PER_WORD = 3 from rfl] + exact charge_nat hg + rw [(returndatacopyStep_eq_error_iff hst hpaid).2 (by rw [hrd]; omega)] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rw [hf.2.1] at hok + cases hok + · exfalso + have hspec : Spec .fusaka (At code msg pc (d :: off :: sz :: T) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + rw [step_of_instruction hlt (by rw [hbyte]; exact decoded) instruction_returndatacopy] + have hlt' : g < 3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost := + Nat.lt_of_not_le hg + have hc : GasMeter.charge e.gas (OPCODE_RETURNDATACOPY_BASE + OPCODE_RETURNDATACOPY_PER_WORD * + wordCount sz.toNat + (extendMemory e.memory.size [(d, sz)]).cost) = .error .outOfGas := by + rw [hgas, hmem, show OPCODE_RETURNDATACOPY_BASE = 3 from rfl, + show OPCODE_RETURNDATACOPY_PER_WORD = 3 from rfl] + simp only [GasMeter.charge] + rw [ite_eq_left_of_eq_true _ _ (eq_true hlt')] + rw [returndatacopyStep_oog hst hc] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rw [hf.2.1] at hok + cases hok + +/-- **RETURNDATACOPY of any range, in a run that succeeds**: with the budget below `2 ^ 300` and an +oracle that answers the frame's return data, SolarTV's copy agrees with EthLib's memory after it, +the budget holds at the gas left, and the run goes on. -/ +theorem rdc_dyn {code : ByteArray} {msg : Message .fusaka} {o : Oracle} {w : List Event} + {pc : Nat} {d off sz : Word} {T : List Word} {M : ByteArray} {g G : Nat} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray} {m0 : SolarTV.Machine.Mem} + (hm : MemRel m0 M) (hb : MemBudget G M g) (hG : G < 2 ^ 300) (hrdr : RdRel o w rd) + {evm : Evm .fusaka Nat} (hat : At code msg pc (d :: off :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x3e) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + off.toNat + sz.toNat ≤ rd.size ∧ + ∃ (M' : ByteArray) (g' : Nat) (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + MemRel (m0.write d.toNat sz.toNat (fun i => returndataByte o w (off.toNat + i))) M' ∧ + MemBudget G M' g' ∧ g' ≤ g ∧ At code msg (pc + 1) T M' g' st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + obtain ⟨hfit0, hg, m, within', hat', hrun'⟩ := rdc_back hat hlt hbyte within hrun hok + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have hbound : sz = 0 ∨ (d.toNat + sz.toNat + 31) / 32 < 2 ^ 251 := by + by_cases hz : sz = 0 + · exact .inl hz + · exact .inr (words_lt_of_cost (budget_grow hmod hz hb hg).1 hG) + have hfit : sz.toNat ≠ 0 → + d.toNat + sz.toNat ≤ (memoryExtend M (extendMemory M.size [(d, sz)]).expandBy).size := by + intro hz + have hz' : sz ≠ 0 := fun h => hz (by simp [h]) + rw [size_memoryExtend_extendMemory' hmod hz'] + have := le_ceil32 (d.toNat + sz.toNat) + omega + refine ⟨hfit0, _, _, m, within', ?_, ?_, by omega, hat', hrun'⟩ + · have he := memRel_expandW hm hbound + rw [← write_expand] + refine memRel_write he hfit (size_memoryReadBytes hfit0) (fun i hi => ?_) + rw [byteAt_memoryReadBytes hfit0, if_pos hi] + exact (hrdr.2 (off.toNat + i) (by omega)).symm + · refine MemBudget.grow hmod hb hg ?_ + rw [size_memoryWrite_of_fit, size_memoryExtend] + intro h + rw [size_memoryReadBytes hfit0] at h ⊢ + exact hfit h + +theorem lowerInstrs_rdc (p : Assemble.Program) (c : Cert) (b : Nat) (rest : List Assemble.Instr) : + lowerInstrs p c b (.effect .returndatacopy 3 :: rest) = .op 0x3e :: lowerInstrs p c b rest := by + simp [lowerInstrs, turnedElse, dropped, lowerInstr] + +theorem exec_rdcC {o : Oracle} {call : Call} {b : Nat} {rest : List Assemble.Instr} + {d off sz : Word} {S : List Word} {s : State} + (hfit : off.toNat + sz.toNat ≤ (o.env "returndatasize" s.world []).toNat) (h : S.length ≤ 1024) : + SolarTV.EVM.Program.exec o call b (.effect .returndatacopy 3 :: rest) (d :: off :: sz :: S) s = + SolarTV.EVM.Program.exec o call b rest S { s with + memory := s.memory.write d.toNat sz.toNat (fun i => returndataByte o s.world (off.toNat + i)) } := by + have hn : ¬ (o.env "returndatasize" s.world []).toNat < off.toNat + sz.toNat := by omega + simp [SolarTV.EVM.Program.exec, SolarTV.Machine.Effect.apply, hn, show ¬ 1024 < S.length by omega] + +/-! ## A block, segment by segment, with STATICCALLs -/ + +set_option maxRecDepth 8000 in +/-- **`AssembleCut.seg` with STATICCALLs**: the rest of a block from an instruction, read back from +a run that succeeds, under the oracle of the run's table of GAS reads and static calls. -/ +theorem segS {p : Assemble.Program} {c : Cert} {mx : List Nat} {code : ByteArray} + (G : GlobT p c code) (codes : SolidCore.Solidity.Shared.Account.BytesMap) (hcr : c.creates = false) {call : Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : msg.txEnv = Target.txEnv) + {b : Nat} (hb : b < p.blocks.length) {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {fin : Evm .fusaka Nat} (hok : fin.error = none) {G0 : Nat} (hG0 : G0 < 2 ^ 256) + (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} (meets : Meets P runChild) + (hPok : ∀ c m ch, P c m ch → StaticOk c m ch) + (hcal : CalleesOk code msg P bound runChild fin) : + ∀ (n : Nat) (is : List Assemble.Instr) (h : Nat) (known : Known) (ty : List Ty) (k : Nat) + (S Tw : List Word) (s : State) (pc : Nat) (M : ByteArray) (g : Nat) + (st : State.TransactionState) (ss : Substate) (rd : ByteArray) (T : RunTable) (evm : Evm .fusaka Nat) + (within : GasMeter.gasHeld evm.gas ≤ bound), + is.length < n → blockOkC p c mx b h known ty k is = true → h ≤ S.length → + S.length + c.need b ≤ h + maxH mx b → KR known S → SR c ty S Tw → + Seg (bytesOf code) c.offset pc + (lowerInstrs p c b is ++ lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) code.size → + S.length + k ≤ 1000 → M.size ≤ c.top → MemRel s.memory M → Rel msg ss0 st ss s → + At code msg pc Tw M g st ss rd evm → T.gases.length = gasReads s.world → + TabInv T s.world → (∀ T'', T.Le T'' → RdRel (OS codes T'') s.world rd) → + MemBudget G0 M g → + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + ∃ T' r, T.Le T' ∧ + (∀ T'', T'.Le T'' → SolarTV.EVM.Program.exec (OS codes T'') call b is S s = r) ∧ + (∀ res, r = .inl res → PostL call msg.currentTarget ss0 res.2 res.1 fin) ∧ + (∀ y, r = .inr y → (y.1 ≤ p.blocks.length ∧ + (y.1 < p.blocks.length → c.need y.1 ≤ y.2.1.length ∧ y.2.1.length ≤ maxH mx y.1) ∧ + (y.1 = b + 1 ∨ isTarget p c y.1 = true)) ∧ + ∃ (after : Evm .fusaka Nat) (within' : GasMeter.gasHeld after.gas ≤ bound), + EntC p c mx code msg ss0 y after ∧ T'.gases.length = gasReads y.2.2.world ∧ + TabInv T' y.2.2.world ∧ + (∀ T'', T'.Le T'' → RdRel (OS codes T'') y.2.2.world after.returnData) ∧ after.gas ≤ g ∧ + memoryGasCost after.memory.size + after.gas ≤ G0 ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild after within' = .ok fin) + | 0, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, hn, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ => absurd hn (Nat.not_lt_zero _) + | n + 1, is, h, known, ty, k, S, Tw, s, pc, M, g, st, ss, rd, T, evm, within, hn, hokC, hh, hu, hk, + hR, hseg, hstk, htop, hmem, R, hat, hTg, hs0, hrdr, hB, hrun => by + have hge : evm.gas = g := hat.2.2.2.2.2.2.1 + -- The segment with gas to spare for it alone: `K` more than the frame holds. + generalize hK : 22100 * k + memoryGasCost c.top = K + have hp := hat.addGas K + have I : InvL c code call (lowerInstrs p c b is ++ lowerFrom p c (b + 1) + (p.blocks.drop (b + 1))) k 0 pc S s M (g + K) := + ⟨hseg, hstk, by simp only [Nat.add_zero]; omega, htop, hmem⟩ + have hsim := exec_simC (mx := mx) G (o := OS codes T) hdata hvalue hstatic hself hcaller + (OS_ok codes c T).1 hbenv htx (OS_ok codes c T).2 b hb 0 (G0 + K) rd is h known ty S Tw k s pc M + (g + K) st ss hokC hh hu hk hR I R (by unfold MemBudget at *; omega) + have hcnt := (execC_agree (Agree.refl (OS codes T) (gasReads s.world) (sent s.world)) call b is S s + le_rfl le_rfl).2 + have hex : ∀ T'', T.Le T'' → SolarTV.EVM.Program.exec (OS codes T'') call b is S s = + match execC (OS codes T) call b is S s with + | .done r => r + | .cut i rest S' s' => SolarTV.EVM.Program.exec (OS codes T'') call b (i :: rest) S' s' := + fun T'' hle => exec_OS codes hle (by omega) hs0 + generalize hr : execC (OS codes T) call b is S s = r at hsim hcnt hex + cases r with + | done r => + refine ⟨T, r, RunTable.Le.refl T, fun T'' hle => hex T'' hle, fun res hres => ?_, + fun y hy => ?_⟩ + · subst hres + exact SpecG.low hsim hp within hrun hok + · subst hy + obtain ⟨t, S', s'⟩ := y + obtain ⟨⟨htle, hneedt, hj⟩, pc', T', M', g', st', ss', hh', hR', E', R', hB'⟩ := hsim + obtain ⟨e1, r1, he1⟩ := hh' _ hp + obtain ⟨m, within', hz, hrm⟩ := reaches_low r1 K evm rfl within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hmK⟩ := at_of_addGasR he1 + have hgm := reaches_gas_le r1 + rw [hz] at hgm + simp only [gas_addGas] at hgm + have hc1 := hcnt.1 s' rfl + refine ⟨⟨htle, hneedt, hj⟩, m, within', ⟨T', pc', M', st', ss', rd, htle, hneedt, hR', E'.seg, + E'.le_top, E'.mem, R', hatm⟩, ?_, ?_, ?_, by omega, + by rw [hatm.2.2.2.2.2.1]; unfold MemBudget at hB'; omega, hrm⟩ + · dsimp only; omega + · exact TabInv.of_seg hc1.2 (execC_calls _ _ _ is S s s' (by rw [hr]; rfl)) hs0 + · intro T'' hle + rw [hatm.2.2.2.2.2.2.2.2.2.2.2.2] + exact rdRel_world codes (execC_calls _ _ _ is S s s' (by rw [hr]; rfl)) (hrdr T'' hle) + | cut i rest S' s' => + obtain ⟨hci, h', known', ty', k', pc', T', M', g', st', ss', hh', hok2, hh2, hu2, hk2, hR', + I', R', hB'⟩ := hsim + -- The segment, moved back to the frame's gas. + obtain ⟨e1, r1, he1⟩ := hh' _ hp + obtain ⟨m, within1, hz, hrm⟩ := reaches_low r1 K evm rfl within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hmK⟩ := at_of_addGasR he1 + have hgm := reaches_gas_le r1 + rw [hz] at hgm + simp only [gas_addGas] at hgm + have hL := hR'.length + have hst := I'.stack + have hc1 := hcnt.1 s' rfl + have hmc := execC_calls (OS codes T) call b is S s s' (by rw [hr]; rfl) + have hlen := hcnt.2 _ rest S' s' rfl + have hmB : MemBudget G0 M' m.gas := by unfold MemBudget at *; omega + have hci' : isGasI i = true ∨ isLoadI i = true ∨ isStoreI i = true ∨ isRetI i = true ∨ + isRevI i = true ∨ isKecI i = true ∨ isLogI i = true ∨ isCdcI i = true ∨ isScI i = true ∨ + isRdsI i = true ∨ isRdcI i = true ∨ isCallI i = true ∨ isC2I i = true ∨ isCcI i = true := by + simpa [isCutI, isMemCutI, or_assoc] using hci + rcases hci' with hgi | hli | hsi | hri | hvi | hki | hlgi | hcdi | hsci | hrdi | hrdci | hcalli | + hc2i | hcci + · obtain rfl := isGasI_eq hgi + obtain ⟨hk1, hok3⟩ := blockOkC_gas hok2 + have hs := I'.seg + rw [lowerInstrs_gas, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + -- GAS at the frame's gas. + obtain ⟨h2, m2, within2, hat2, hrun2⟩ := + gas_back hatm hlt hcode (by unfold STACK_LIMIT; omega) within1 hrm hok + let T1 : RunTable := { T with gases := T.gases ++ [m.gas - 2] } + have hle1 : T.Le T1 := ⟨List.prefix_refl _, List.prefix_refl _, List.prefix_refl _, + List.prefix_refl _, List.prefix_append _ _⟩ + have hv : ∀ T'', T1.Le T'' → T''.gases.getD (gasReads s'.world) 0 = m.gas - 2 := by + intro T'' hle + rw [getD_of_prefix hle.2.2.2.2 (by simp [T1]; omega)] + simp [T1, List.getD_eq_getElem?_getD, hc1.1, ← hTg] + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segS (G0 := G0) G codes (hcr := hcr) hdata hvalue hstatic hself hcaller hbenv + htx hb hok hG0 hdepth meets hPok hcal n rest (h' + 1) [] (some false :: ty') (k' - 1) + (BitVec.ofNat 256 (m.gas - 2) :: S') (BitVec.ofNat 256 (m.gas - 2) :: T') + { s' with world := s'.world ++ [.read "gas"] } (pc' + 1) M' (m.gas - 2) st' ss' rd T1 m2 + within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl hR') hseg' (by simp; omega) I'.le_top + I'.mem ⟨R'.storage, R'.account, logsRel_read _ R'.logs⟩ hat2 + (by simp [T1]; omega) (TabInv.read (TabInv.of_seg hc1.2 hmc hs0)) + (fun T3 hle => rdRel_world codes (by rw [machineCalls_read, hmc]) (hrdr T3 (hle1.trans hle))) + (by unfold MemBudget at *; omega) hrun2 + refine ⟨T2, r, hle1.trans hle2, fun T'' hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T'' (hle1.trans (hle2.trans hle))] + show SolarTV.EVM.Program.exec (OS codes T'') call b (.effect .gas 0 :: rest) S' s' = r + rw [exec_gasS codes (hv T'' (hle2.trans hle)) (by omega)] + exact hex2 T'' hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + + · -- MLOAD at the frame's gas, at any offset. + obtain rfl := isLoadI_eq hli + obtain ⟨hk1, hh1, hdat, htop', hok3⟩ := blockOkC_load hok2 + have hs := I'.seg + rw [lowerInstrs_load, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, S''⟩ + · simp at hh2; omega + rcases T' with _ | ⟨x', Tr⟩ + · simp at hL + obtain rfl := (SR.head hR' hdat).symm + have hR'' := (SR.uncons.1 hR').2 + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + AssembleDyn.mload_dyn I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segS (G0 := G0) G codes (hcr := hcr) hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 hdepth meets hPok hcal n rest h' [] (some false :: ty'.drop 1) (k' - 1) + (s'.memory.load x.toNat :: S'') (s'.memory.load x.toNat :: Tr) + { s' with memory := s'.memory.expand x.toNat 32 } (pc' + 1) M2 g2 st' ss' rd T m2 + within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl (by simpa using hR'')) hseg' + (by simp; omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by show T.gases.length = gasReads s'.world; rw [hc1.1]; exact hTg) + (TabInv.of_seg hc1.2 hmc hs0) (fun T3 hle => rdRel_world codes hmc (hrdr T3 hle)) hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (OS codes T3) call b (.op .load :: rest) _ s' = r + rw [exec_loadC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + · -- MSTORE at the frame's gas, at any offset. + obtain rfl := isStoreI_eq hsi + obtain ⟨hk1, hh1, hdat, htop', hok3⟩ := blockOkC_store hok2 + have hs := I'.seg + rw [lowerInstrs_store, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 2) S'' Tr := by simpa using SR.drop 2 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + AssembleDyn.mstore_dyn I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segS (G0 := G0) G codes (hcr := hcr) hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 hdepth meets hPok hcal n rest (h' - 2) [] (ty'.drop 2) (k' - 1) S'' Tr + { s' with memory := s'.memory.store x.toNat y } (pc' + 1) M2 g2 st' ss' rd T m2 + within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by show T.gases.length = gasReads s'.world; rw [hc1.1]; exact hTg) + (TabInv.of_seg hc1.2 hmc hs0) (fun T3 hle => rdRel_world codes hmc (hrdr T3 hle)) hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (OS codes T3) call b (.op .store :: rest) _ s' = r + rw [exec_storeC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + + · -- RETURN at the frame's gas, from any range. + obtain rfl := isRetI_eq hri + obtain ⟨hh1, hdat⟩ := blockOkC_ret hok2 + have hs := I'.seg + rw [lowerInstrs_ret, List.cons_append] at hs + obtain ⟨next, hd, -⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hg := AssembleDyn.return_back hatm hlt hcode within1 hrm hok + refine ⟨T, .inl (SolarTV.EVM.Program.output s' (x :: y :: S'') false), RunTable.Le.refl T, + fun T3 hle => ?_, fun res hres => ?_, fun y hy => ?_⟩ + · rw [hex T3 hle] + rfl + · obtain rfl := Sum.inl.inj hres + simp only [SolarTV.EVM.Program.output, Bool.false_eq_true, ↓reduceIte] + exact SpecG.low (SpecG.consequence (return_postSG (ss := ss') hlt hcode (by omega) rfl + (by rw [read_eq I'.mem]; rfl) rfl (R'.slot hself)) (fun _ h => h) + (fun _ h => ⟨ss', h, R'.logs⟩)) (hatm.addGas 0) within1 hrm hok + · cases hy + · -- REVERT: no run that succeeds reaches it. + obtain rfl := isRevI_eq hvi + obtain ⟨hh1, hdat⟩ := blockOkC_revert hok2 + have hs := I'.seg + rw [lowerInstrs_revert, List.cons_append] at hs + obtain ⟨next, hd, -⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + exact (AssembleDyn.revert_false hatm hlt hcode within1 hrm hok).elim + + · -- KECCAK256 at the frame's gas, of any range. + obtain rfl := isKecI_eq hki + obtain ⟨henv, hk1, hh1, hdat, htop', hok3⟩ := blockOkC_kec hok2 + have hs := I'.seg + rw [lowerInstrs_kec, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 2) S'' Tr := by simpa using SR.drop 2 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨m2, within2, hmem2, hb2, hat2, hrun2⟩ := + AssembleDyn.keccak_dyn I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + obtain ⟨-, hkec⟩ := (OS_ok codes c T).1 henv + rw [byteArray_eq_of_map (read_eq I'.mem), ← hkec] at hat2 + have hsz : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size ≤ c.top := by + have hmod : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size % 32 = 0 := by + rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segS (G0 := G0) G codes (hcr := hcr) hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 hdepth meets hPok hcal n rest (h' - 1) [] (some false :: ty'.drop 2) (k' - 1) + ((OS codes T).keccak ((s'.memory.expand x.toNat y.toNat).read x.toNat y.toNat) :: S'') + ((OS codes T).keccak ((s'.memory.expand x.toNat y.toNat).read x.toNat y.toNat) :: Tr) + { s' with memory := s'.memory.expand x.toNat y.toNat } (pc' + 1) _ _ st' ss' rd T m2 + within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl (by simpa using hR'')) hseg' + (by simp; omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by show T.gases.length = gasReads s'.world; rw [hc1.1]; exact hTg) + (TabInv.of_seg hc1.2 hmc hs0) (fun T3 hle => rdRel_world codes hmc (hrdr T3 hle)) hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (OS codes T3) call b (.effect .keccak256 2 :: rest) _ s' = r + rw [exec_keccakC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + + · -- LOGn at the frame's gas, of any range. + obtain ⟨nl, hn4, rfl⟩ := isLogI_eq hlgi + obtain ⟨hk1, hnh, hdat, htop', hok3⟩ := blockOkC_log hn4 hok2 + have hs := I'.seg + rw [lowerInstrs_log p c b hn4, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S1⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', T1⟩⟩ + · simp at hL + · simp at hL + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨tops, S2, rfl, hlen⟩ : ∃ tops S2, S1 = tops ++ S2 ∧ tops.length = nl := + ⟨S1.take nl, S1.drop nl, (List.take_append_drop nl S1).symm, by simp; omega⟩ + obtain ⟨tops', T2, rfl, hlen'⟩ : ∃ tops' T2, T1 = tops' ++ T2 ∧ tops'.length = nl := + ⟨T1.take nl, T1.drop nl, (List.take_append_drop nl T1).symm, by simp; omega⟩ + subst hlen + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.cons.injEq, List.take_left' hlen', + List.take_left' rfl] at htake + obtain ⟨rfl, rfl, rfl⟩ := htake + have hR'' : SR c (ty'.drop (tops.length + 2)) S2 T2 := by + simpa using SR.drop (tops.length + 2) hR' + simp only [List.length_append] at hL hst hh2 hu2 + obtain ⟨m2, within2, hmem2, hb2, hat2, hrun2⟩ := + AssembleDyn.log_dyn (n := ⟨tops.length, by omega⟩) I'.mem hmB (by omega) hatm rfl hlt hcode + (decode_log ⟨tops.length, by omega⟩) hstatic within1 hrm hok + have hsz : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size ≤ c.top := by + have hmod : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size % 32 = 0 := by + rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨L, hL1, hL2⟩ := R'.logs + obtain ⟨T2', r, hle2, hex2, hpost, hnext⟩ := segS (G0 := G0) (ss0 := ss0) G codes (hcr := hcr) hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 hdepth meets hPok hcal n rest (h' - (tops.length + 2)) [] (ty'.drop (tops.length + 2)) + (k' - 1) S2 T2 + ⟨s'.memory.expand x.toNat y.toNat, s'.storage, s'.transient, + s'.world ++ [.log tops ((s'.memory.expand x.toNat y.toNat).read x.toNat y.toNat)]⟩ + (pc' + 1) _ _ st' { ss' with logs := ss'.logs.push ⟨msg.currentTarget, + tops.map U256.toBeBytes, memoryReadBytes (memoryExtend M' (extendMemory M'.size + [(x, y)]).expandBy) x.toNat y.toNat⟩ } rd T m2 within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 + ⟨R'.storage, R'.account, ⟨L ++ [⟨msg.currentTarget, tops.map U256.toBeBytes, + memoryReadBytes (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy) + x.toNat y.toNat⟩], by simp [Array.toList_push, hL1], + filter_snoc_log ▸ forall₂_snoc hL2 ⟨rfl, rfl, read_eq I'.mem⟩⟩⟩ hat2 + (by show T.gases.length = gasReads (s'.world ++ [_]); rw [AssembleCut.gasReads_log, hc1.1]; exact hTg) + (TabInv.log (TabInv.of_seg hc1.2 hmc hs0)) + (fun T3 hle => rdRel_world codes (by rw [machineCalls_log, hmc]) (hrdr T3 hle)) hb2 hrun2 + refine ⟨T2', r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (OS codes T3) call b + (.effect (.log tops.length) (tops.length + 2) :: rest) _ s' = r + rw [exec_logC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + + · -- CALLDATACOPY at the frame's gas, of any range. + obtain rfl := isCdcI_eq hcdi + obtain ⟨hk1, hh1, hdat, htop', hok3⟩ := blockOkC_cdc hok2 + have hs := I'.seg + rw [lowerInstrs_cdc, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, _ | ⟨z, S''⟩⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', _ | ⟨z', Tr⟩⟩⟩ + · simp at hL + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 3) S'' Tr := by simpa using SR.drop 3 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + AssembleDynCopy.cdc_dyn hdata I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segS (G0 := G0) (ss0 := ss0) G codes (hcr := hcr) hdata hvalue + hstatic hself hcaller hbenv htx hb hok hG0 hdepth meets hPok hcal n rest (h' - 3) [] (ty'.drop 3) (k' - 1) S'' Tr + { s' with + memory := s'.memory.write x.toNat z.toNat + (fun i => SolarTV.Machine.calldataByte call (y.toNat + i)) } (pc' + 1) M2 g2 st' ss' rd T m2 + within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by show T.gases.length = gasReads s'.world; rw [hc1.1]; exact hTg) + (TabInv.of_seg hc1.2 hmc hs0) (fun T3 hle => rdRel_world codes hmc (hrdr T3 hle)) hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (OS codes T3) call b (.effect .calldatacopy 3 :: rest) _ s' = r + rw [exec_cdcC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + · -- STATICCALL to code at the frame's gas: the callee frame's flag and output join the table. + obtain rfl := isScI_eq hsci + obtain ⟨-, hk1, hh1, hdat, htop', hok3⟩ := blockOkC_sc hok2 + have hs := I'.seg + rw [lowerInstrs_sc, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x1, _ | ⟨x2, _ | ⟨x3, _ | ⟨x4, _ | ⟨x5, _ | ⟨x6, S''⟩⟩⟩⟩⟩⟩ + all_goals (first | (simp at hh2; omega) | skip) + rcases T' with _ | ⟨y1, _ | ⟨y2, _ | ⟨y3, _ | ⟨y4, _ | ⟨y5, _ | ⟨y6, Tr⟩⟩⟩⟩⟩⟩ + all_goals (first | (simp at hL; done) | skip) + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, rfl, rfl, rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 6) S'' Tr := by simpa using SR.drop 6 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + have hco := hcal hatm hlt hcode hrm + obtain ⟨hi1, hi2, hi3⟩ := hs0 + obtain ⟨ok, out, s2, M2, g2, st2, ss2, m2, within2, happ, ⟨ev, hw, hev1, hev2, hev3⟩, hmem2, + R2, hb2, hg2, hat2, hrun2⟩ := staticcall_cut codes T I'.mem R' hmB (by omega) hatm hlt hcode + hdepth meets hPok within1 hrm hok hco (by rw [hmc, hi2]) (by rw [hmc, hi2, hi3]) + (by rw [hc1.1]; omega) + let T1 : RunTable := { T with oks := T.oks ++ [ok], outs := T.outs ++ [out] } + have hle1 : T.Le T1 := ⟨List.prefix_append _ _, List.prefix_append _ _, List.prefix_refl _, + List.prefix_refl _, List.prefix_refl _⟩ + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + have hinv : TabInv T1 s2.world := by + refine ⟨?_, ?_, ?_⟩ + · rw [hw, sent_append, hev1, hc1.2, hi1] + simp [T1] + · rw [hw, machineCalls_append, List.length_append, hev3, hmc, hi2] + simp [T1] + · simp [T1, hi3] + have hTg1 : T1.gases.length = gasReads s2.world := by + rw [hw, gasReads_append, hev2, hc1.1] + simpa [T1] using hTg + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segS (G0 := G0) G codes (hcr := hcr) hdata hvalue hstatic + hself hcaller hbenv htx hb hok hG0 hdepth meets hPok hcal n rest (h' - 5) [] + (some false :: ty'.drop 6) (k' - 1) ((if ok then 1 else 0) :: S'') + ((if ok then 1 else 0) :: Tr) s2 (pc' + 1) M2 g2 st2 ss2 out T1 m2 within2 (by omega) hok3 + (by simp; omega) (by simp; omega) (KR.nil _) (SR.cons (τ := some false) rfl hR'') + hseg' (by simp; omega) hsz hmem2 R2 hat2 hTg1 hinv (fun T3 hle => (happ T3 hle).2) hb2 hrun2 + refine ⟨T2, r, hle1.trans hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle1.trans (hle2.trans hle))] + show SolarTV.EVM.Program.exec (OS codes T3) call b + (.effect (.call .staticcall) 6 :: rest) _ s' = r + rw [exec_scC (happ T3 (hle2.trans hle)).1 (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + · -- RETURNDATASIZE at the frame's gas: the size of the frame's return data, the table's. + obtain rfl := isRdsI_eq hrdi + obtain ⟨-, hk1, hok3⟩ := blockOkC_rds hok2 + have hs := I'.seg + rw [lowerInstrs_rds, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + obtain ⟨h2, m2, within2, hat2, hrun2⟩ := + rds_back hatm hlt hcode (by unfold STACK_LIMIT; omega) within1 hrm hok + have hrd' : ∀ T3, T.Le T3 → RdRel (OS codes T3) s'.world rd := + fun T3 hle => rdRel_world codes hmc (hrdr T3 hle) + have hv : ∀ T3, T.Le T3 → + (OS codes T3).env "returndatasize" s'.world [] = BitVec.ofNat 256 rd.size := by + intro T3 hle + have h1 := (hrd' T3 hle).1 + simp only [returndataSize] at h1 + have hlt' : rd.size < 2 ^ 256 := by rw [← h1]; exact BitVec.isLt _ + apply BitVec.eq_of_toNat_eq + rw [BitVec.toNat_ofNat, h1, Nat.mod_eq_of_lt hlt'] + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segS (G0 := G0) G codes (hcr := hcr) hdata hvalue hstatic + hself hcaller hbenv htx hb hok hG0 hdepth meets hPok hcal n rest (h' + 1) [] (some false :: ty') + (k' - 1) (BitVec.ofNat 256 rd.size :: S') (BitVec.ofNat 256 rd.size :: T') s' (pc' + 1) M' + (m.gas - 2) st' ss' rd T m2 within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl hR') hseg' (by simp; omega) I'.le_top + I'.mem R' hat2 (by rw [hc1.1]; exact hTg) (TabInv.of_seg hc1.2 hmc hs0) hrd' + (by unfold MemBudget at *; omega) hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (OS codes T3) call b (.effect .returndatasize 0 :: rest) S' s' = r + rw [exec_rdsC (hv T3 (hle2.trans hle)) (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + · -- RETURNDATACOPY at the frame's gas, of any range within the return data. + obtain rfl := isRdcI_eq hrdci + obtain ⟨-, hk1, hh1, hdat, htop', hok3⟩ := blockOkC_rdc hok2 + have hs := I'.seg + rw [lowerInstrs_rdc, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, _ | ⟨z, S''⟩⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', _ | ⟨z', Tr⟩⟩⟩ + · simp at hL + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 3) S'' Tr := by simpa using SR.drop 3 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + have hrd' : ∀ T3, T.Le T3 → RdRel (OS codes T3) s'.world rd := + fun T3 hle => rdRel_world codes hmc (hrdr T3 hle) + obtain ⟨hfit, M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + rdc_dyn I'.mem hmB (by omega) (hrd' T (RunTable.Le.refl T)) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + have hext : ∀ T3, T.Le T3 → returndataByte (OS codes T3) s'.world = + returndataByte (OS codes T) s'.world := by + intro T3 hle + funext i + simp only [returndataByte] + rw [OS_env_ext codes hle (by rw [hmc, hs0.2.1]) (by rw [hmc, hs0.2.1, hs0.2.2]) + (by rw [hc1.1]; omega) (by decide)] + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segS (G0 := G0) G codes (hcr := hcr) hdata hvalue + hstatic hself hcaller hbenv htx hb hok hG0 hdepth meets hPok hcal n rest (h' - 3) [] (ty'.drop 3) + (k' - 1) S'' Tr + { s' with + memory := s'.memory.write x.toNat z.toNat + (fun i => returndataByte (OS codes T) s'.world (y.toNat + i)) } (pc' + 1) M2 g2 st' ss' rd + T m2 within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by rw [hc1.1]; exact hTg) (TabInv.of_seg hc1.2 hmc hs0) hrd' hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (OS codes T3) call b (.effect .returndatacopy 3 :: rest) _ s' = r + rw [exec_rdcC (by rw [(hrd' T3 (hle2.trans hle)).1]; exact hfit) (by omega), + hext T3 (hle2.trans hle)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + · -- CALL, CREATE2 and CODECOPY: only a certificate that says the program creates lets the + -- checker cut there. + obtain rfl := isCallI_eq hcalli + exact absurd (blockOkC_call hok2).2.1 (by simp [hcr]) + · obtain rfl := isC2I_eq hc2i + exact absurd (blockOkC_c2 hok2).2.1 (by simp [hcr]) + · obtain rfl := isCcI_eq hcci + exact absurd (blockOkC_cc hok2).2.1 (by simp [hcr]) + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallSeg.segS' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms segS + + +/-! ## Runs under a runner meeting an assumption, with a hypothesis on the run -/ + +section BlocksQ + +variable {σ : Type} (blk : Oracle → σ → Option ((Halt × Machine.State) ⊕ σ)) + (O : RunTable → Oracle) + +/-- **One block of the simulation, read back from a run that succeeds**, as +`AssembleCall.AdvancesS` under every runner of messages meeting `P`, for the runs to a frame `fin` +that meet the hypothesis `Q`. -/ +def AdvancesQ (P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop) + (Q : (bound : Nat) → MessageRunner .fusaka Nat bound → Evm .fusaka Nat → Prop) + (E : RunTable → σ → Evm .fusaka Nat → Prop) + (Post : Halt × Machine.State → Evm .fusaka Nat → Prop) (meas : σ → Evm .fusaka Nat → Nat) + (T : RunTable) (x : σ) (evm : Evm .fusaka Nat) : Prop := + ∀ (bound : Nat) (runChild : MessageRunner .fusaka Nat bound), Meets P runChild → + ∀ (within : GasMeter.gasHeld evm.gas ≤ bound) (fin : Evm .fusaka Nat), + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + fin.error = none → Q bound runChild fin → + ∃ T' r, T.Le T' ∧ (∀ T'', T'.Le T'' → blk (O T'') x = some r) ∧ + (∀ res, r = .inl res → Post res fin) ∧ + (∀ y, r = .inr y → ∃ after within', E T' y after ∧ meas y after < meas x evm ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild after within' = .ok fin) + +/-- A run of EthLib that ends with no error and meets the hypothesis is SolarTV's, for every table +extending the last one the run grew. -/ +theorem run_of_advancesQ {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} + {Q : (bound : Nat) → MessageRunner .fusaka Nat bound → Evm .fusaka Nat → Prop} + {E : RunTable → σ → Evm .fusaka Nat → Prop} + {Post : Halt × Machine.State → Evm .fusaka Nat → Prop} {meas : σ → Evm .fusaka Nat → Nat} + (adv : ∀ T x evm, E T x evm → AdvancesQ blk O P Q E Post meas T x evm) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + (meets : Meets P runChild) : + ∀ (n : Nat) (T : RunTable) (x : σ) (evm : Evm .fusaka Nat) + (within : GasMeter.gasHeld evm.gas ≤ bound) (fin : Evm .fusaka Nat), + E T x evm → meas x evm < n → + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + fin.error = none → Q bound runChild fin → + ∃ T' res, T.Le T' ∧ + (∀ T'', T'.Le T'' → ∃ k, SolarTV.Machine.iterate (blk (O T'')) k x = some res) ∧ + Post res fin + | 0, _, _, _, _, _, _, h, _, _, _ => absurd h (Nat.not_lt_zero _) + | n + 1, T, x, evm, within, fin, hE, hm, hrun, hok, hq => by + obtain ⟨T', r, hle, hstep, hinl, hinr⟩ := + adv T x evm hE bound runChild meets within fin hrun hok hq + cases r with + | inl res => + exact ⟨T', res, hle, fun T'' h => ⟨1, by simp [SolarTV.Machine.iterate, hstep T'' h]⟩, + hinl res rfl⟩ + | inr y => + obtain ⟨after, within', hE', hm', hrun'⟩ := hinr y rfl + obtain ⟨T2, res, hle2, hit, hpost⟩ := + run_of_advancesQ adv meets n T' y after within' fin hE' (by omega) hrun' hok hq + refine ⟨T2, res, hle.trans hle2, fun T'' h => ?_, hpost⟩ + obtain ⟨k, hk⟩ := hit T'' h + exact ⟨k + 1, by simp [SolarTV.Machine.iterate, hstep T'' (hle2.trans h), hk]⟩ + +end BlocksQ + +section Runs + +open EthLib.Execution.State + +open SolarTV.EVM.Program SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Evm.Symex in +/-- **EVM IR to bytecode at the given gas, run by run, from a block simulation**: when every frame +related to a block state (`E`, from the substate the frame started with) advances (`Advances`) to +an end SolarTV's halt shows (`PostL`) or to the next block, and the frame a call starts with is +related to SolarTV's initial state, then the oracle of the run's table makes every result of the +bytecode on the call the EVM IR's or a failure that changes nothing. -/ +theorem within_of_advancesQ {p : Assemble.Program} {code : ByteArray} {call : Call} {gas : Nat} + (O : RunTable → Oracle) (P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop) + (Q : (bound : Nat) → MessageRunner .fusaka Nat bound → Evm .fusaka Nat → Prop) + (E : Substate → RunTable → Nat × List Word × Machine.State → Evm .fusaka Nat → Prop) + (meas : Nat × List Word × Machine.State → Evm .fusaka Nat → Nat) + (hP : Meets P (processRunner .fusaka (Meter := Nat) (Final.Target.messageWith gas code call).gas)) + (hQ : ∀ r, processMessage (Meter := Nat) .fusaka (Final.Target.messageWith gas code call) + (SolidCore.Refinement.Target.preState code call) Substate.empty = .ok r → r.1.error = none → + Q _ (processRunner .fusaka (Meter := Nat) (Final.Target.messageWith gas code call).gas) r.1) + (start : ∀ st' ss', Rel (Final.Target.messageWith gas code call) ss' st' ss' + (Machine.State.initial call) → + E ss' {} (0, [], Machine.State.initial call) + (startFrame (Final.Target.messageWith gas code call) st' ss' gas)) + (adv : ∀ ss0 T x evm, E ss0 T x evm → AdvancesQ (fun o => block o call p) O P Q (E ss0) + (fun res => PostL call (Final.Target.messageWith gas code call).currentTarget ss0 res.2 res.1) + meas T x evm) : + ∃ T, Within (evmirSem (O T)) (ethLibWith gas) p code (· = call) := by + by_cases hs : ∃ obs, Target.runWith gas code call = some obs ∧ obs.success = true + swap + · refine ⟨{}, fun call' hc obs hrun => Or.inr ?_⟩ + subst hc + have hf : obs.success = false := by + cases h : obs.success + · rfl + · exact absurd ⟨obs, hrun, h⟩ hs + exact ⟨hf, Target.runWith_failure hrun hf⟩ + obtain ⟨obs, hrun, hsucc⟩ := hs + suffices H : ∃ T, (evmirSem (O T)).run p call = some obs by + obtain ⟨T, hT⟩ := H + refine ⟨T, fun call' hc obs' hrun' => Or.inl ?_⟩ + subst hc + change Target.runWith gas code call' = some obs' at hrun' + rw [hrun] at hrun' + cases hrun' + exact hT + unfold Target.runWith Target.runMsg at hrun + split at hrun + · cases hrun + rename_i evm hev hpm + simp only [Option.some.injEq] at hrun + subst hrun + have hok : evm.error = none := by simpa using hsucc + obtain ⟨st', ss', within, hcases, hmove, hrf⟩ := + AssembleRun.processMessage_ok' (message := Final.Target.messageWith gas code call) (evm := ⟨evm, hev⟩) + (precompileAddress_message code call) hpm hok + simp only at hrf + have R := AssembleLoop.rel_start code call gas ss' (fun h => (hcases h).1) (fun h => (hmove h).1) + obtain ⟨T, ⟨halt, sF⟩, -, hit, hpost⟩ := run_of_advancesQ (fun o => block o call p) O (adv ss') + hP _ {} _ _ within evm (start st' ss' R) (Nat.lt_succ_self _) hrf hok (hQ _ hpm hok) + obtain ⟨k, hk⟩ := hit T (RunTable.Le.refl T) + refine ⟨T, ?_⟩ + have hres : (evmirSem (O T)).run p call = some (observe call sF halt) := by + change (SolarTV.EVM.Program.layer.result (O T) p call).map _ = _ + rw [SolarTV.EVM.Program.layer.result_of_ends ⟨k, hk⟩] + rfl + rw [hres] + set msg := Final.Target.messageWith gas code call with hmsg + obtain ⟨ssF, ⟨herr, hout, hlogsF, hst⟩, L, hL1, hL2⟩ := hpost + have hss' : ss'.logs.toList = [] := by + by_cases htr : msg.shouldTransferValue = true ∧ msg.value ≠ 0 + · rw [(hmove htr).2] + simp [pushTransferLog, show ¬ (Fork.fusaka ≥ Fork.glamsterdam) by decide, Substate.empty] + · rw [(hcases htr).2] + simp [Substate.empty] + have hlogs := logs_of_match hL2 + have hL1' : ssF.logs.toList = L := by rw [hL1, hss', List.nil_append] + have herr' : evm.error = errorOf (observe call sF halt) := herr + have hout' : evm.output.toList.map (·.toNat) = (observe call sF halt).output := hout + have hst' : (observe call sF halt).success = true → + evm.substate.logs = ssF.logs ∧ ∀ slot, + (evm.state.getStorage (Target.address selfAddress) (Target.storageKey slot)).toNat = + (observe call sF halt).storage slot := + fun h => ⟨hlogsF, hst h⟩ + have hfail : (observe call sF halt).success = false → + (observe call sF halt).logs = [] ∧ + (observe call sF halt).storage = slotValue call.storage := by + cases halt <;> simp [observe] + have hok2 : (observe call sF halt).success = true → + (observe call sF halt).logs = logs sF := by + cases halt <;> simp [observe] + clear herr hout hst hres hit hk + generalize observe call sF halt = X at * + have hsucc' : evm.error.isNone = X.success := by + rw [herr']; cases hX : X.success <;> simp [errorOf, hX] + symm + congr 1 + cases X with + | mk success output logs storage => + simp only at hsucc' hout' hfail hok2 hst' ⊢ + rw [SolarTV.Observable.mk.injEq] + refine ⟨hsucc', hout', ?_, ?_⟩ + · rw [hsucc'] + cases hs : success + · simp [hok, hs] at hsucc' + · simp only [ite_true] + rw [(hst' hs).1, hL1', hlogs, hok2 hs] + rfl + · funext slot + rw [hsucc'] + cases hs : success + · simp [hok, hs] at hsucc' + · simp only [ite_true] + exact (hst' hs).2 slot + + +end Runs + +/-! ## The checker with STATICCALLs -/ + +/-- The relation at a block entry, with the table's GAS reads and one flag and output per message +sent. -/ +def EntS (codes : SolidCore.Solidity.Shared.Account.BytesMap) (p : Assemble.Program) (c : Cert) (mx : List Nat) (code : ByteArray) + (msg : Message .fusaka) (ss0 : Substate) (T : RunTable) (x : Nat × List Word × State) + (evm : Evm .fusaka Nat) : Prop := + EntC p c mx code msg ss0 x evm ∧ T.gases.length = gasReads x.2.2.world ∧ TabInv T x.2.2.world ∧ + (∀ T'', T.Le T'' → RdRel (OS codes T'') x.2.2.world evm.returnData) ∧ + memoryGasCost evm.memory.size + evm.gas ≤ msg.gas + +/-- **A block of code with loops, GAS and STATICCALLs, read back from a run that succeeds.** -/ +theorem advances_checkCS {p : Assemble.Program} {c : Cert} {mx : List Nat} {code : ByteArray} + (G : GlobC p c mx code) (codes : SolidCore.Solidity.Shared.Account.BytesMap) (hcr : c.creates = false) {call : Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : msg.txEnv = Target.txEnv) + (hgas : msg.gas < 2 ^ 256) (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + (T0 : RunTable) (x : Nat × List Word × State) (evm : Evm .fusaka Nat) + (hE : EntS codes p c mx code msg ss0 T0 x evm) : + AdvancesQ (fun o => SolarTV.EVM.Program.block o call p) (OS codes) StaticOkE + (CalleesOk code msg StaticOkE) + (EntS codes p c mx code msg ss0) + (fun res => PostL call msg.currentTarget ss0 res.2 res.1) + (fun y e => AssembleLoop.meas p c e.gas y.1) T0 x evm := by + intro bound runChild meets within fin hrun hok hcal + obtain ⟨b, S, s⟩ := x + obtain ⟨⟨Tw, pc, M, st, ss, rd, hle, hneed, hR, hseg, htop, hmem, R, hat⟩, hTg, hs0, hrdr, hbud⟩ := hE + simp only at hle hneed hR hseg hmem R hTg hs0 hrdr + by_cases hb : b < p.blocks.length + · obtain ⟨hL, hnm, hstk, hblock⟩ := G.block b hb + obtain ⟨hn, hm⟩ := hneed hb + have hblk : p.blocks[b]? = some p.blocks[b] := List.getElem?_eq_getElem hb + rw [lowerFrom_drop p c hb, lowerBlock, List.append_assoc] at hseg + -- The label, at the frame's gas. + obtain ⟨pc1, m1, within1, hat1, hseg1, hg1, hrun1⟩ : ∃ (pc1 : Nat) (m1 : Evm .fusaka Nat) + (within1 : GasMeter.gasHeld m1.gas ≤ bound), + At code msg pc1 Tw M m1.gas st ss rd m1 ∧ + Seg (bytesOf code) c.offset pc1 (lowerInstrs p c b p.blocks[b] ++ + lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) code.size ∧ + m1.gas + (if isTarget p c b then 1 else 0) ≤ evm.gas ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m1 within1 = .ok fin := by + by_cases ht : isTarget p c b = true + · simp only [ht, ite_true, List.singleton_append, List.cons_append] at hseg + obtain ⟨next, hd, hseg'⟩ := hseg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hp := hat.addGas 1 + obtain ⟨e1, r1, he1⟩ := Logic.jumpdestG hlt hcode (show 1 ≤ evm.gas + 1 by omega) _ hp + obtain ⟨m, within', hz, hrm⟩ := reaches_low r1 1 evm rfl within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hgm⟩ := at_of_addGasR he1 + exact ⟨pc + 1, m, within', hatm, hseg', by simp only [ht, ite_true]; omega, hrm⟩ + · simp only [ht, Bool.false_eq_true, ite_false, List.nil_append] at hseg + exact ⟨pc, evm, within, hat, hseg, by simp only [ht, Bool.false_eq_true, ite_false]; omega, + hrun⟩ + obtain ⟨T', r, hle', hex, hpost, hnext⟩ := segS (G0 := msg.gas) G.toGlobT codes (hcr := hcr) hdata hvalue hstatic hself hcaller + hbenv htx hb hok hgas hdepth meets (fun _ _ _ h => h.1) hcal (p.blocks[b].length + 1) p.blocks[b] (c.need b) [] (c.entry b) + (budget c b - labelItems p c b) S Tw s pc1 M m1.gas st ss rd T0 m1 within1 (Nat.lt_succ_self _) + hblock hn (by omega) (KR.nil _) hR hseg1 (by omega) htop hmem R hat1 hTg hs0 + (by rw [← hat.2.2.2.2.2.2.2.2.2.2.2.2]; exact hrdr) + (by unfold MemBudget; rw [← hat.2.2.2.2.2.1]; omega) hrun1 + refine ⟨T', r, hle', fun T'' h => ?_, fun res hres => hpost res hres, fun y hy => ?_⟩ + · simp only [SolarTV.EVM.Program.block, hblk] + rw [hex T'' h] + · obtain ⟨t, S', s'⟩ := y + obtain ⟨⟨htle, -, hj⟩, after, within', hE', hT', hs', hrdy', hga, hbud', hra⟩ := hnext _ hy + refine ⟨after, within', ⟨hE', hT', hs', hrdy', hbud'⟩, ?_, hra⟩ + have := meas_step (c := c) (g := evm.gas) (g' := after.gas) hb htle (by omega) hj + dsimp only at this ⊢ + omega + · obtain rfl : b = p.blocks.length := by omega + have hblk : p.blocks[p.blocks.length]? = none := List.getElem?_eq_none (by omega) + have hbl : ∀ o, SolarTV.EVM.Program.block o call p (p.blocks.length, S, s) = + some (.inl (.stop, s)) := by + intro o + simp only [SolarTV.EVM.Program.block, hblk, ite_true] + refine ⟨T0, _, RunTable.Le.refl T0, fun _ _ => hbl _, ?_, ?_⟩ + · intro res hres + cases hres + have hseg' := hseg + rw [lowerFrom_nil p c (by omega)] at hseg' + have hpc := hseg'.nil_end + exact SpecG.low (SpecG.consequence (stop_of_size_leG (by omega)) + (fun _ h => h) fun evm h => postL_stop R hself evm h) (hat.addGas 0) within hrun hok + · intro y hy + cases hy + +/-- **Named hypothesis on a run of the bytecode**: the run of the call, when it succeeds, calls code +at each STATICCALL (`CalleesOk`). -/ +def CalleesRun (gas : Nat) (code : ByteArray) (call : Call) : Prop := + ∀ r, processMessage (Meter := Nat) .fusaka (Final.Target.messageWith gas code call) + (SolidCore.Refinement.Target.preState code call) Substate.empty = .ok r → r.1.error = none → + CalleesOk code (Final.Target.messageWith gas code call) StaticOkE gas (processRunner .fusaka (Meter := Nat) gas) r.1 + +/-- **Named hypotheses on the runner of messages**: a static message that succeeds ends with no log +(EIP-214), and a callee's output has fewer than `2 ^ 256` bytes. -/ +def StaticRunner (gas : Nat) : Prop := + Meets (bound := gas) (fun caller m child => StaticNoLogs caller m child ∧ OutputFits caller m child) + (processRunner .fusaka (Meter := Nat) gas) + +theorem staticOk_of (gas : Nat) (h : StaticRunner gas) : + Meets (bound := gas) StaticOk (processRunner .fusaka (Meter := Nat) gas) := + ⟨fun a b c d e => ⟨(meets_static gas).ok a b c d e, h.ok a b c d e⟩, h.aborts⟩ + +theorem staticOkE_of (gas : Nat) (h : StaticRunner gas) : + Meets (bound := gas) StaticOkE (processRunner .fusaka (Meter := Nat) gas) := + ⟨fun a b c d e => ⟨(staticOk_of gas h).ok a b c d e, (AssembleCallPre.meets_ecrecover gas).ok a b c d e⟩, + h.aborts⟩ + +/-- **EVM IR to bytecode, run by run, for code with loops, GAS, memory at any offset and +STATICCALLs to code**: for every program the checker without the no-call gate accepts, at every +gas below `2 ^ 256` and every call whose run meets the named hypotheses, the oracle of the run's +table (`OS`: the static calls' flags and outputs, the GAS reads) makes every result of the bytecode +the EVM IR's or a failure that changes nothing. -/ +theorem runs_of_checkCB {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (hc : checkCB p code c mx = true) (codes : SolidCore.Solidity.Shared.Account.BytesMap) + (gas : Nat) (hgas : gas < 2 ^ 256) (call : Call) (hP : StaticRunner gas) + (hQ : CalleesRun gas code call) : + ∃ T, Within (evmirSem (OS codes T)) (ethLibWith gas) p code (· = call) := by + obtain ⟨G, hseg, hneed0⟩ := globC_of_checkC hc + refine within_of_advancesQ (OS codes) StaticOkE + (CalleesOk code (Final.Target.messageWith gas code call) StaticOkE) + (fun ss0 => EntS codes p c mx code (Final.Target.messageWith gas code call) ss0) + (fun y e => AssembleLoop.meas p c e.gas y.1) (staticOkE_of gas hP) hQ (fun st' ss' R => ?_) + (fun ss0 T x evm hE => advances_checkCS G codes (hcr := checkCB_creates hc) rfl + (by simp [Final.Target.messageWith, SolidCore.Refinement.Target.message]) rfl rfl rfl rfl rfl + hgas (by show 0 + 1 ≤ 1024; decide) T x evm hE) + refine ⟨⟨[], 0, .empty, st', ss', .empty, Nat.zero_le _, fun _ => ⟨by simp [hneed0], by simp⟩, + SR.nil c _, by rw [List.drop_zero]; exact hseg, by simp, memRel_initial, R, ?_⟩, rfl, + ⟨rfl, rfl, rfl⟩, fun T'' _ => rdRel_nil codes T'', ?_⟩ + have hcode : (Final.Target.messageWith gas code call).code = code := rfl + · exact ⟨by simp [startFrame, hcode], by simp [startFrame, hcode], rfl, rfl, rfl, rfl, rfl, rfl, rfl, + rfl, rfl, rfl, rfl⟩ + · have h0 : memoryGasCost 0 = 0 := by rw [memoryGasCost_eq]; simp [wordCount, ceil32, WORD_BYTES] + simp only [startFrame, ByteArray.size_empty, h0, Nat.zero_add] + exact le_refl _ + +/-- **The assembly premise of `holds_of_runs` for code with STATICCALLs**: below `2 ^ 256` gas, for +every call in scope whose run meets the named hypotheses, an oracle and an open world that agree +(`AssembleCallWorld.tabWorld` answers the static calls from the run's table), under which the EVM IR +gives the bytecode's result or a failure that changes nothing. -/ +theorem assembly_of_checkCB {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (hc : checkCB p code c mx = true) (codes : SolidCore.Solidity.Shared.Account.BytesMap) + (scope : Call → Prop) (hP : ∀ gas, StaticRunner gas) + (hQ : ∀ gas call, scope call → CalleesRun gas code call) : + ∀ gas, gas < 2 ^ 256 → ∀ call, scope call → ∃ (o : Oracle) (W : World), W.Open ∧ + CallsAgree o W ∧ CertOk c o ∧ Within (evmirSem o) (ethLibWith gas) p code (· = call) := by + intro gas hgas call hs + obtain ⟨T, hT⟩ := runs_of_checkCB hc codes gas hgas call (hP gas) (hQ gas call hs) + exact ⟨OS codes T, tabWorld T.oks T.outs codes, (OS_agree codes T).1, (OS_agree codes T).2, + OS_ok codes c T, hT⟩ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallSeg.assembly_of_checkCB' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms assembly_of_checkCB + + +/-- **The specification of SolidCore to the exact bytecode, for code with STATICCALLs**: the +source's specification at every open world, its totality on the calls in scope, the stages to EVM +IR and the checker without the no-call gate give the specification of the bytecode at every gas +below `2 ^ 256`, for the runs meeting the named hypotheses `StaticRunner` and `CalleesRun`. -/ +theorem holds_of_checkCB {St : Type} {fuel : Nat} + {mirSem : SolarTV.Machine.Oracle → Sem} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {mir : ∀ o, (mirSem o).Prog} {p : Assemble.Program} {code : ByteArray} {cert : Cert} + {mx : List Nat} {spec : Final.ContractSpec St} + (source : ∀ W : World, W.Open → Final.Holds (solidCoreIn W fuel) c spec) + (fin : ∀ W : World, W.Open → ∀ call, spec.Calls call → (Source.runIn W fuel c call).isSome) + (lowering : ∀ o W, CallsAgree o W → Stage (solidCoreIn W fuel) (mirSem o) c (mir o) spec.Calls) + (backend : ∀ o, Stage (mirSem o) (evmirSem o) (mir o) p spec.Calls) + (hc : checkCB p code cert mx = true) (codes : SolidCore.Solidity.Shared.Account.BytesMap) + (hP : ∀ gas, StaticRunner gas) (hQ : ∀ gas call, spec.Calls call → CalleesRun gas code call) + (gas : Nat) (hgas : gas < 2 ^ 256) : Final.Holds (Final.ethLibWith gas) code spec := + holds_of_runs_lt (evmirSem := evmirSem) (evmir := fun _ => p) source fin lowering backend + (fun gas hg call hcall => by + obtain ⟨o, W, h1, h2, -, h4⟩ := assembly_of_checkCB hc codes spec.Calls hP hQ gas hg call hcall + exact ⟨o, W, h1, h2, h4⟩) gas hgas + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallSeg.holds_of_checkCB' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holds_of_checkCB + +/-- **The assembly premise in the shape of `Shapes.equiv_of_runs`** for code with STATICCALLs: at every gas +below `2 ^ 256` and every valid call whose run meets the named hypotheses, an oracle meeting the +certificate's constraints and agreeing with an open world, under which every result of the +bytecode is the EVM IR's or a failure that changes nothing. -/ +theorem runs_shape_of_checkCB {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (hc : checkCB p code c mx = true) (codes : SolidCore.Solidity.Shared.Account.BytesMap) + (Valid : Call → Prop) (hP : ∀ gas, StaticRunner gas) + (hQ : ∀ gas call, Valid call → CalleesRun gas code call) : + ∀ gas, gas < 2 ^ 256 → ∀ call, Valid call → ∃ o : Oracle, + (CertOk c o ∧ ∃ W : World, W.Open ∧ CallsAgree o W) ∧ + Within (evmirSem o) (ethLibWith gas) p code (· = call) := by + intro gas hgas call hv + obtain ⟨o, W, h1, h2, h3, h4⟩ := assembly_of_checkCB hc codes Valid hP hQ gas hgas call hv + exact ⟨o, ⟨h3, W, h1, h2⟩, h4⟩ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallSeg.runs_shape_of_checkCB' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms runs_shape_of_checkCB + + +/-! ## The ECRECOVER agreement as a hypothesis of its own -/ + +/-- `AssembleCallCut.PreOk` without the named agreement of the two ECRECOVER implementations: what a +run must give a STATICCALL to address 1 (no delegation there, at least 3000 gas passed on), the +runner's ECRECOVER frames being proved (`AssembleCallPre.meets_ecrecover`). -/ +def PreRun (P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop) + (st : State.TransactionState) (ss : Substate) (M : ByteArray) (g : Nat) + (asked addr inOff inSize outOff outSize : U256) : Prop := + addr.toNat % 2 ^ 160 = 1 ∧ (∀ c m ch, P c m ch → AssembleCallPre.EcrecoverRuns c m ch) ∧ + (∀ cc, st.getCode (st.getAccount (toAddressMasked addr)).codeHash = .ok cc → + delegatedAddress cc = none) ∧ + 3000 ≤ (messageCallGas .fusaka 0 asked.toNat g + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost + (if decide (toAddressMasked addr ∉ ss.accessedAddresses) then 2600 else 100)).subCall + +/-- `CalleesOk` with `PreRun` for the calls to ECRECOVER. -/ +def CalleesOkR (code : ByteArray) (msg : Message .fusaka) + (P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop) (bound : Nat) + (runChild : MessageRunner .fusaka Nat bound) (fin : Evm .fusaka Nat) : Prop := + ∀ {e : Evm .fusaka Nat} {within : GasMeter.gasHeld e.gas ≤ bound} {pc : Nat} + {asked addr inOff inSize outOff outSize : U256} + {S : List U256} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {rd : ByteArray}, + At code msg pc (asked :: addr :: inOff :: inSize :: outOff :: outSize :: S) M g st ss rd e → + (hlt : pc < code.size) → code[pc] = 0xfa → + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild e within = .ok fin → + CalleeOk addr ∨ PreRun P st ss M g asked addr inOff inSize outOff outSize + +/-- **Named hypothesis on a run**, without the ECRECOVER agreement: its STATICCALLs call code, or +ECRECOVER as `PreRun` asks. -/ +def CalleesRunR (gas : Nat) (code : ByteArray) (call : Call) : Prop := + ∀ r, processMessage (Meter := Nat) .fusaka (Final.Target.messageWith gas code call) + (SolidCore.Refinement.Target.preState code call) Substate.empty = .ok r → r.1.error = none → + CalleesOkR code (Final.Target.messageWith gas code call) StaticOkE gas + (processRunner .fusaka (Meter := Nat) gas) r.1 + +theorem calleesRun_of_R (hagree : AssembleCallPre.EcrecoverAgree) {gas : Nat} {code : ByteArray} + {call : Call} (h : CalleesRunR gas code call) : CalleesRun gas code call := +by + intro r hr he e within pc asked addr inOff inSize outOff outSize S M g st ss rd hat hlt hb hrun + exact (h r hr he hat hlt hb hrun).imp id fun ⟨a, b, c, d⟩ => ⟨a, hagree, b, c, d⟩ + +/-- **`holds_of_checkCB` with every assumption named in its statement**: the source's +specification at every open world, its totality, the stages and the checker give the +specification of the exact bytecode at every gas below `2 ^ 256`, under the named hypotheses +`StaticRunner` (EIP-214 logs, output sizes), `AssembleCallPre.EcrecoverAgree` (SolidCore's and +EthLib's ECRECOVER agree) and `CalleesRunR` (each STATICCALL of the run calls code, or ECRECOVER +with its price passed on and no delegation at address 1). -/ +theorem holds_of_checkCB_named {St : Type} {fuel : Nat} + {mirSem : SolarTV.Machine.Oracle → Sem} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {mir : ∀ o, (mirSem o).Prog} {p : Assemble.Program} {code : ByteArray} {cert : Cert} + {mx : List Nat} {spec : Final.ContractSpec St} + (source : ∀ W : World, W.Open → Final.Holds (solidCoreIn W fuel) c spec) + (fin : ∀ W : World, W.Open → ∀ call, spec.Calls call → (Source.runIn W fuel c call).isSome) + (lowering : ∀ o W, CallsAgree o W → Stage (solidCoreIn W fuel) (mirSem o) c (mir o) spec.Calls) + (backend : ∀ o, Stage (mirSem o) (evmirSem o) (mir o) p spec.Calls) + (hc : checkCB p code cert mx = true) (codes : SolidCore.Solidity.Shared.Account.BytesMap) + (hP : ∀ gas, StaticRunner gas) (hagree : AssembleCallPre.EcrecoverAgree) + (hQ : ∀ gas call, spec.Calls call → CalleesRunR gas code call) + (gas : Nat) (hgas : gas < 2 ^ 256) : Final.Holds (Final.ethLibWith gas) code spec := + holds_of_checkCB source fin lowering backend hc codes hP + (fun gas call hcall => calleesRun_of_R hagree (hQ gas call hcall)) gas hgas + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallSeg.holds_of_checkCB_named' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holds_of_checkCB_named + +end SolidCore.Refinement.Solar.AssembleCallSeg diff --git a/SolidCore/Refinement/Solar/AssembleCallStatic.lean b/SolidCore/Refinement/Solar/AssembleCallStatic.lean new file mode 100644 index 00000000..a06be1ca --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCallStatic.lean @@ -0,0 +1,708 @@ +import EthLib.Execution.Proofs.Evm.Call.StepRules +import EthLib.Execution.Proofs.Evm.Logic.Message + +/-! +# EIP-214 from EthLib: a static message that succeeds ends with no log + +EthLib proves that a static message keeps the state (processMessage_sameOutside_static), but its +static steps (EthLib.Execution.Evm.StaticStep) say nothing of the logs of the substate. This file +proves the logs half, by the same classification of instructions and the same induction on the +gas of messages (EthLib.Execution.Evm.processMessage_rel): + +* LStep: a step that keeps the message and the logs. Every instruction of a static frame that + gives the next frame is one (lStep_instruction_of_isStatic): LOG fails there, SSTORE, TSTORE + and SELFDESTRUCT halt or fail, every other instruction keeps the substate's logs. +* A call from a static frame sends a static message, and the caller resumes with its own logs + when the child ends with no log (lResult_step). +* processMessage_logs_static: before Glamsterdam (no transfer logs, EIP-7708), a static message + that ends with no error ends with the logs it started with, however deep its calls. A message + starts from Substate.child, which has no log, so the frame ends with no log. +* meets_staticNoLogs: the interpreter's runner of messages meets that, the hypothesis that + AssembleCallCut.StaticNoLogs names. +-/ + +namespace EthLib.Execution.Evm.StaticLogs + +open EthLib +open EthLib.Base (Address Bytes32 Fork U256 toAddressMasked) +open EthLib.Execution.Evm +open EthLib.Execution.State (TransactionState) + +variable {fork : Fork} {Meter : Type} + +/-- A step that keeps the message and the logs of the substate. -/ +structure LStep (before after : Evm fork Meter) : Prop where + message : after.message = before.message + logs : after.substate.logs = before.substate.logs + +namespace LStep + +theorem refl (evm : Evm fork Meter) : LStep evm evm := ⟨rfl, rfl⟩ + +theorem trans {a b c : Evm fork Meter} (hab : LStep a b) (hbc : LStep b c) : LStep a c := + ⟨hbc.message.trans hab.message, hbc.logs.trans hab.logs⟩ + +theorem of_sameContext {a b : Evm fork Meter} (h : SameContext a b) : LStep a b := + ⟨h.message, by rw [h.substate]⟩ + +theorem withMemory (evm : Evm fork Meter) (memory : ByteArray) : LStep evm { evm with memory } := + ⟨rfl, rfl⟩ + +theorem advance {a b : Evm fork Meter} (h : LStep a b) (n : Nat := 1) : + LStep a (Evm.advance b n) := + ⟨h.message, h.logs⟩ + +end LStep + +theorem lStep_recordAccountRead (evm : Evm fork Meter) (address : Address) : + LStep evm (recordAccountRead evm address) := ⟨rfl, rfl⟩ + +theorem lStep_recordStorageRead (evm : Evm fork Meter) (address : Address) (key : Bytes32) : + LStep evm (recordStorageRead evm address key) := ⟨rfl, rfl⟩ + +variable [GasMeter Meter] + +omit [GasMeter Meter] in +theorem lStep_accessAddress (evm : Evm fork Meter) (address : Address) : + LStep evm (accessAddress evm address).2 := by + obtain ⟨_, h⟩ := accessAddress_snd evm address + exact ⟨by rw [h], by rw [h]⟩ + +omit [GasMeter Meter] in +theorem lStep_accessStorageKey (evm : Evm fork Meter) (address : Address) (key : Bytes32) : + LStep evm (accessStorageKey evm address key).2 := by + obtain ⟨_, h⟩ := accessStorageKey_snd evm address key + exact ⟨by rw [h], by rw [h]⟩ + +theorem lStep_exceptionalHalt (evm : Evm fork Meter) (e : EvmError) : + LStep evm (exceptionalHalt evm e) := ⟨rfl, rfl⟩ + +/-! ## The instructions that give the next frame (after EthLib's Instructions/Static.lean) -/ + +/-- BALANCE is a static step. -/ +theorem lStep_balanceStep {evm after : Evm fork Meter} (h : balanceStep evm = .ok after) : + LStep evm after := by + obtain ⟨⟨w, e1⟩, h1, h⟩ := Base.bind_ok_iff.mp h + rcases hacc : accessAddress e1 (toAddressMasked w) with ⟨cold, e2⟩ + simp only [hacc] at h + obtain ⟨e3, h3, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨e4, h4, h⟩ := Base.bind_ok_iff.mp h + cases h + have ha : LStep e1 e2 := by + have := lStep_accessAddress e1 (toAddressMasked w) + rwa [hacc] at this + exact ((((LStep.of_sameContext (popWord_sameContext h1)).trans ha).trans + (LStep.of_sameContext (chargeGas_sameContext h3))).trans + (lStep_recordAccountRead _ _)).trans + (LStep.of_sameContext (pushWord_sameContext h4)) |>.advance + +/-- EXTCODESIZE is a static step. -/ +theorem lStep_extcodesizeStep {evm after : Evm fork Meter} + (h : extcodesizeStep evm = .ok after) : LStep evm after := by + obtain ⟨⟨w, e1⟩, h1, h⟩ := Base.bind_ok_iff.mp h + rcases hacc : accessAddress e1 (toAddressMasked w) with ⟨cold, e2⟩ + simp only [hacc] at h + obtain ⟨e3, h3, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨code, h4, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨e5, h5, h⟩ := Base.bind_ok_iff.mp h + cases h + have ha : LStep e1 e2 := by + have := lStep_accessAddress e1 (toAddressMasked w) + rwa [hacc] at this + exact ((((LStep.of_sameContext (popWord_sameContext h1)).trans ha).trans + (LStep.of_sameContext (chargeGas_sameContext h3))).trans + (lStep_recordAccountRead _ _)).trans + (LStep.of_sameContext (pushWord_sameContext h5)) |>.advance + +/-- EXTCODEHASH is a static step. -/ +theorem lStep_extcodehashStep {evm after : Evm fork Meter} + (h : extcodehashStep evm = .ok after) : LStep evm after := by + obtain ⟨⟨w, e1⟩, h1, h⟩ := Base.bind_ok_iff.mp h + rcases hacc : accessAddress e1 (toAddressMasked w) with ⟨cold, e2⟩ + simp only [hacc] at h + obtain ⟨e3, h3, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨e4, h4, h⟩ := Base.bind_ok_iff.mp h + cases h + have ha : LStep e1 e2 := by + have := lStep_accessAddress e1 (toAddressMasked w) + rwa [hacc] at this + exact ((((LStep.of_sameContext (popWord_sameContext h1)).trans ha).trans + (LStep.of_sameContext (chargeGas_sameContext h3))).trans + (lStep_recordAccountRead _ _)).trans + (LStep.of_sameContext (pushWord_sameContext h4)) |>.advance + +/-- EXTCODECOPY is a static step. -/ +theorem lStep_extcodecopyStep {evm after : Evm fork Meter} + (h : extcodecopyStep evm = .ok after) : LStep evm after := by + obtain ⟨⟨w, e1⟩, h1, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨⟨st, e2⟩, h2, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨⟨off, e3⟩, h3, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨⟨sz, e4⟩, h4, h⟩ := Base.bind_ok_iff.mp h + rcases hacc : accessAddress e4 (toAddressMasked w) with ⟨cold, e5⟩ + simp only [hacc] at h + obtain ⟨e6, h6, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨code, h7, h⟩ := Base.bind_ok_iff.mp h + cases h + have ha : LStep e4 e5 := by + have := lStep_accessAddress e4 (toAddressMasked w) + rwa [hacc] at this + exact (((((((LStep.of_sameContext (popWord_sameContext h1)).trans + (LStep.of_sameContext (popWord_sameContext h2))).trans + (LStep.of_sameContext (popWord_sameContext h3))).trans + (LStep.of_sameContext (popWord_sameContext h4))).trans ha).trans + (LStep.of_sameContext (chargeGasAndMemory_sameContext h6))).trans + (lStep_recordAccountRead _ _)).trans (LStep.withMemory _ _) |>.advance + +/-- Each instruction that reads another account is a static step. -/ +theorem lStep_accountStep {op : Op} + {step : Evm fork Meter → Except EvmError (Evm fork Meter)} + (hstep : accountStep fork op = some step) {evm after : Evm fork Meter} + (h : step evm = .ok after) : LStep evm after := by + cases op <;> simp only [accountStep, Option.some.injEq, reduceCtorEq] at hstep + case balance => subst hstep; exact lStep_balanceStep h + case extcodesize => subst hstep; exact lStep_extcodesizeStep h + case extcodecopy => subst hstep; exact lStep_extcodecopyStep h + case selfbalance => + split at hstep + · cases hstep + exact (lStep_recordAccountRead _ _).trans + (LStep.of_sameContext (readFrame_sameContext h)) + · cases hstep + case extcodehash => + split at hstep + · cases hstep; exact lStep_extcodehashStep h + · cases hstep + +/-- SLOAD is a static step. -/ +theorem lStep_sloadStep {evm after : Evm fork Meter} (h : sloadStep evm = .ok after) : + LStep evm after := by + obtain ⟨⟨w, e1⟩, h1, h⟩ := Base.bind_ok_iff.mp h + dsimp only at h + rcases hacc : accessStorageKey e1 e1.message.currentTarget (U256.toBeBytes w) with ⟨cold, e2⟩ + simp only [hacc] at h + obtain ⟨e3, h3, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨e4, h4, h⟩ := Base.bind_ok_iff.mp h + cases h + have ha : LStep e1 e2 := by + have := lStep_accessStorageKey e1 e1.message.currentTarget (U256.toBeBytes w) + rwa [hacc] at this + exact ((((LStep.of_sameContext (popWord_sameContext h1)).trans ha).trans + (LStep.of_sameContext (chargeGas_sameContext h3))).trans + (lStep_recordStorageRead _ _ _)).trans + (LStep.of_sameContext (pushWord_sameContext h4)) |>.advance + +/-- SSTORE in a static frame is a static step. + +Before Glamsterdam it halts the frame with its reads. + +From Glamsterdam it fails before any read. -/ +theorem lStep_sstoreStep_of_isStatic {evm after : Evm fork Meter} + (static : evm.message.isStatic = true) (h : sstoreStep evm = .ok after) : + LStep evm after := by + unfold sstoreStep at h + split at h + · simp [bind, Except.bind, throw, throwThe, MonadExceptOf.throw] at h + obtain ⟨⟨k, e1⟩, h1, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨⟨n, e2⟩, h2, h⟩ := Base.bind_ok_iff.mp h + have c2 := (LStep.of_sameContext (popWord_sameContext h1)).trans + (LStep.of_sameContext (popWord_sameContext h2)) + have m2 : e2.message = evm.message := + (popWord_sameContext h2).message.trans (popWord_sameContext h1).message + simp only [] at h + split at h + · simp [throw, throwThe, MonadExceptOf.throw] at h + · rcases keepReads_eq_ok h with h | ⟨e, rfl⟩ + · obtain ⟨keys, hacc⟩ := accessStorageKey_snd e2 e2.message.currentTarget (U256.toBeBytes k) + rcases hpair : accessStorageKey e2 e2.message.currentTarget (U256.toBeBytes k) with + ⟨cold, e3⟩ + rw [hpair] at hacc + simp only [hpair] at h + obtain ⟨e4, h4, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨e5, h5, h⟩ := Base.bind_ok_iff.mp h + have m5 : e5.message = evm.message := by + obtain ⟨_, -, h5⟩ := Base.bind_ok_iff.mp h5 + cases h5 + rw [(chargeGas_sameContext h4).message] + cases hacc + exact m2 + simp [m5, static, throw, throwThe, MonadExceptOf.throw] at h + · rcases hpair : accessStorageKey e2 e2.message.currentTarget (U256.toBeBytes k) with + ⟨cold, e3⟩ + have ha : LStep e2 e3 := by + have := lStep_accessStorageKey e2 e2.message.currentTarget (U256.toBeBytes k) + rwa [hpair] at this + exact ((c2.trans ha).trans (lStep_recordStorageRead _ _ _)).trans + (lStep_exceptionalHalt _ _) + +/-- Each instruction that uses storage is a static step in a static frame. -/ +theorem lStep_storageStep_of_isStatic {op : Op} + {step : Evm fork Meter → Except EvmError (Evm fork Meter)} + (hstep : storageStep op = some step) {evm after : Evm fork Meter} + (static : evm.message.isStatic = true) (h : step evm = .ok after) : LStep evm after := by + cases op <;> simp only [storageStep, Option.some.injEq, reduceCtorEq] at hstep + case sload => subst hstep; exact lStep_sloadStep h + case sstore => subst hstep; exact lStep_sstoreStep_of_isStatic static h + +/-- SELFDESTRUCT in a static frame is a static step. + +Before Glamsterdam it halts the frame with its reads. + +From Glamsterdam it fails before any read. -/ +theorem lStep_selfdestructStep_of_isStatic {evm after : Evm fork Meter} + (static : evm.message.isStatic = true) (h : selfdestructStep fork evm = .ok after) : + LStep evm after := by + unfold selfdestructStep at h + by_cases hs : fork ≥ .glamsterdam ∧ evm.message.isStatic = true + · simp only [hs, and_self, ↓reduceIte] at h + cases h + simp only [hs, ↓reduceIte] at h + obtain ⟨⟨w, e1⟩, h1, h⟩ := Base.bind_ok_iff.mp h + dsimp only at h + rcases hacc : accessAddress e1 (toAddressMasked w) with ⟨cold, e2⟩ + simp only [hacc] at h + have ha : LStep e1 e2 := by + have := lStep_accessAddress e1 (toAddressMasked w) + rwa [hacc] at this + obtain ⟨_, -, h⟩ := Base.bind_ok_iff.mp h + have c := ((LStep.of_sameContext (popWord_sameContext h1)).trans ha).trans + (lStep_recordAccountRead e2 (toAddressMasked w)) + rcases keepReads_eq_ok h with h | ⟨e, rfl⟩ + · obtain ⟨e3, h3, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨e4, h4, h⟩ := Base.bind_ok_iff.mp h + have m4 : e4.message = evm.message := by + rw [(chargeStateGas_sameContext h4).message, (chargeGas_sameContext h3).message] + exact c.message + unfold finishSelfdestruct at h + simp [m4, static] at h + · exact c.trans (lStep_exceptionalHalt _ _) + +/-- Each instruction of transient storage is a static step in a static frame. -/ +theorem lStep_transientStorageStep_of_isStatic {op : Op} + {step : Evm fork Meter → Except EvmError (Evm fork Meter)} + (hstep : transientStorageStep fork op = some step) {evm after : Evm fork Meter} + (static : evm.message.isStatic = true) (h : step evm = .ok after) : LStep evm after := by + cases op <;> simp only [transientStorageStep, reduceCtorEq] at hstep <;> split at hstep <;> + simp only [Option.some.injEq, reduceCtorEq] at hstep <;> subst hstep + case tload => exact LStep.of_sameContext (tloadStep_sameContext h) + case tstore => exact absurd h (tstoreStep_ne_ok_of_isStatic static) + +/-- RETURN and REVERT are static steps. -/ +theorem lStep_returnOpStep {op : Op} + {step : Evm fork Meter → Except EvmError (Evm fork Meter)} + (hstep : returnOpStep fork op = some step) {evm after : Evm fork Meter} + (h : step evm = .ok after) : LStep evm after := by + cases op <;> simp only [returnOpStep, Option.some.injEq, reduceCtorEq] at hstep + case «return» => subst hstep; exact LStep.of_sameContext (returnStep_sameContext h) + case revert => + split at hstep + · cases hstep; exact LStep.of_sameContext (revertStep_sameContext h) + · cases hstep + +/-- The instruction of SELFDESTRUCT is a static step in a static frame. -/ +theorem lStep_selfdestructOpStep_of_isStatic {op : Op} + {step : Evm fork Meter → Except EvmError (Evm fork Meter)} + (hstep : selfdestructOpStep fork op = some step) {evm after : Evm fork Meter} + (static : evm.message.isStatic = true) (h : step evm = .ok after) : LStep evm after := by + cases op <;> simp only [selfdestructOpStep, Option.some.injEq, reduceCtorEq] at hstep + subst hstep + exact lStep_selfdestructStep_of_isStatic static h + +/-- The instructions of LOG are static steps in a static frame, as none completes. -/ +theorem lStep_logOpStep_of_isStatic {op : Op} + {step : Evm fork Meter → Except EvmError (Evm fork Meter)} + (hstep : logOpStep op = some step) {evm after : Evm fork Meter} + (static : evm.message.isStatic = true) (h : step evm = .ok after) : LStep evm after := by + cases op <;> simp only [logOpStep, Option.some.injEq, reduceCtorEq] at hstep + subst hstep + exact absurd h (logStep_ne_ok_of_isStatic static) + +/-- Each instruction that gives the next frame is a static step in a static frame. -/ +theorem lStep_instruction_of_isStatic {op : Op} + {run : Evm fork Meter → Except EvmError (Evm fork Meter)} {evm after : Evm fork Meter} + (hrun : instruction fork op = some run) (static : evm.message.isStatic = true) + (h : run evm = .ok after) : LStep evm after := by + unfold instruction at hrun + rcases orElse_eq_some hrun with hf | hrun + · exact LStep.of_sameContext (stackOnlyStep_sameContext hf h) + rcases orElse_eq_some hrun with hf | hrun + · exact LStep.of_sameContext (controlFlowStep_sameContext hf h) + rcases orElse_eq_some hrun with hf | hrun + · exact LStep.of_sameContext (memoryDataStep_sameContext hf h) + rcases orElse_eq_some hrun with hf | hrun + · exact lStep_returnOpStep hf h + rcases orElse_eq_some hrun with hf | hrun + · exact LStep.of_sameContext (environmentStep_sameContext hf h) + rcases orElse_eq_some hrun with hf | hrun + · exact lStep_accountStep hf h + rcases orElse_eq_some hrun with hf | hrun + · exact lStep_storageStep_of_isStatic hf static h + rcases orElse_eq_some hrun with hf | hrun + · exact lStep_transientStorageStep_of_isStatic hf static h + rcases orElse_eq_some hrun with hf | hf + · exact lStep_logOpStep_of_isStatic hf static h + · exact lStep_selfdestructOpStep_of_isStatic hf static h + +omit [GasMeter Meter] in +/-- The pops of the operands of a call are a static step. + +A call that sends no value pops none. -/ +theorem lStep_popCallOperands {kind : CallKind} {evm after : Evm fork Meter} + {call : CallOperands} (h : popCallOperands kind evm = .ok (call, after)) : + LStep evm after ∧ (kind.sendsValue = false → call.value = 0) := by + obtain ⟨⟨_, e1⟩, h1, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨⟨_, e2⟩, h2, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨⟨v, e3⟩, h3, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨⟨_, e4⟩, h4, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨⟨_, e5⟩, h5, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨⟨_, e6⟩, h6, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨⟨_, e7⟩, h7, h⟩ := Base.bind_ok_iff.mp h + cases h + have p3 : LStep e2 e3 ∧ (kind.sendsValue = false → v = 0) := by + unfold popCallValue at h3 + split at h3 + · exact ⟨LStep.of_sameContext (popWord_sameContext h3), fun h => by simp_all⟩ + · cases h3 + exact ⟨LStep.refl _, fun _ => rfl⟩ + refine ⟨?_, p3.2⟩ + exact (((((((LStep.of_sameContext (popWord_sameContext h1)).trans + (LStep.of_sameContext (popWord_sameContext h2))).trans p3.1).trans + (LStep.of_sameContext (popWord_sameContext h4))).trans + (LStep.of_sameContext (popWord_sameContext h5))).trans + (LStep.of_sameContext (popWord_sameContext h6))).trans + (LStep.of_sameContext (popWord_sameContext h7))) + +/-- The access to a delegate is a static step. -/ +theorem lStep_accessDelegation {evm after : Evm fork Meter} {address : Address} + {known : Nat} {callee : Callee} (h : accessDelegation evm address known = .ok (callee, after)) : + LStep evm after := by + obtain ⟨code, -, h⟩ := Base.bind_ok_iff.mp h + dsimp only at h + split at h + · obtain ⟨_, -, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨_, -, h⟩ := Base.bind_ok_iff.mp h + cases h + exact (lStep_accessAddress _ _).trans (lStep_recordAccountRead _ _) + · cases h + exact LStep.refl _ + +/-- The payment of a call is a static step. -/ +theorem lStep_payCall {kind : CallKind} {call : CallOperands} + {memoryCost extraGas newAccount subCall : Nat} {evm after : Evm fork Meter} + (h : payCall kind call memoryCost extraGas newAccount evm = .ok (subCall, after)) : + LStep evm after := by + unfold payCall at h + split at h + · obtain ⟨e1, h1, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨e2, h2, h⟩ := Base.bind_ok_iff.mp h + obtain ⟨e3, h3, h⟩ := Base.bind_ok_iff.mp h + cases h + exact ((LStep.of_sameContext (chargeGas_sameContext h1)).trans + (LStep.of_sameContext (chargeStateGas_sameContext h2))).trans + (LStep.of_sameContext (chargeGas_sameContext h3)) + · obtain ⟨e1, h1, h⟩ := Base.bind_ok_iff.mp h + cases h + exact LStep.of_sameContext (chargeGas_sameContext h1) + +/-- A call that runs no message is a static step. -/ +theorem lStep_skipCall {evm after : Evm fork Meter} {gas reservoir : Nat} + (h : skipCall evm gas reservoir = .ok after) : LStep evm after := by + obtain ⟨stack, -, rfl⟩ := skipCall_eq_ok h + exact ⟨rfl, rfl⟩ + + +/-! ## The steps that send a message -/ + +/-- What a step of a static frame gives: a step that keeps the message and the logs, or a static +message from such a step, after which the caller keeps its logs when the child ends with none. -/ +def LChild (evm caller : Evm fork Meter) (message : Message fork) + (resume : Evm fork Meter → Except EvmError (Evm fork Meter)) : Prop := + LStep evm caller ∧ message.isStatic = true ∧ + ∀ child after, resume child = .ok after → (child.error = none → child.substate.logs = #[]) → + LStep evm after + +def LResult (evm : Evm fork Meter) : StepResult fork Meter → Prop + | .next after => LStep evm after + | .child caller message resume => LChild evm caller message resume + +omit [GasMeter Meter] in +theorem LResult.lift {evm evm' : Evm fork Meter} {result : StepResult fork Meter} + (h : LStep evm evm') (r : LResult evm' result) : LResult evm result := by + cases result with + | next after => exact h.trans r + | child caller message resume => + obtain ⟨c, m, k⟩ := r + exact ⟨h.trans c, m, fun child after hres hl => h.trans (k child after hres hl)⟩ + +/-- A caller that resumes after a child that ends with no log keeps its message and logs. -/ +theorem lStep_resumeCall {caller child after : Evm fork Meter} {newAccount : Nat} + {outputStart outputSize : U256} + (h : resumeCall fork caller newAccount outputStart outputSize child = .ok after) + (hl : child.error = none → child.substate.logs = #[]) : LStep caller after := by + obtain ⟨e, h1, h⟩ := Base.bind_ok_iff.mp h + cases h + have hp := pushWord_sameContext h1 + refine ⟨?_, ?_⟩ + · show e.message = caller.message + rw [hp.message]; split <;> simp [message_incorporateChild, refillStateGas] + · show e.substate.logs = caller.substate.logs + rw [hp.substate] + by_cases he : child.error = none + · simp [incorporateChild, he, hl he] + · have hn : child.error.isNone = false := by + cases hc : child.error with + | none => exact absurd hc he + | some _ => rfl + simp [incorporateChild, hn, refillStateGas] + +theorem lResult_genericCall {evm : Evm fork Meter} {message : Message fork} + {newAccount : Nat} {outputStart outputSize : U256} {result : StepResult fork Meter} + (hmsg : message.isStatic = true) + (h : genericCall evm message newAccount outputStart outputSize = .ok result) : + LResult evm result := by + unfold genericCall at h + dsimp only at h + split at h + · cases hs : skipCall (refillStateGas { evm with returnData := .empty } newAccount) + message.gas message.reservoir with + | error e => simp [hs, Functor.map, Except.map] at h + | ok after => + simp only [hs, Functor.map, Except.map, Except.ok.injEq] at h + subst h + exact (⟨rfl, rfl⟩ : LStep evm + (refillStateGas { evm with returnData := .empty } newAccount)).trans + (lStep_skipCall hs) + · cases h + refine ⟨⟨rfl, rfl⟩, hmsg, ?_⟩ + intro child after hres hl + have pre : LStep evm { evm with returnData := .empty } := ⟨rfl, rfl⟩ + exact pre.trans (lStep_resumeCall hres hl) + +theorem lResult_finishCall {kind : CallKind} {call : CallOperands} {callee : Callee} + {subCall newAccount expandBy : Nat} {evm : Evm fork Meter} {result : StepResult fork Meter} + (static : evm.message.isStatic = true) + (h : finishCall kind call callee subCall newAccount expandBy evm = .ok result) : + LResult evm result := by + unfold finishCall at h + split at h + · cases h + dsimp only at h + have pre : LStep evm (recordAccountRead { evm with + memory := memoryExtend evm.memory expandBy, gas := GasMeter.drain evm.gas } + evm.message.currentTarget) := ⟨rfl, rfl⟩ + split at h + · cases hs : skipCall (refillStateGas (recordAccountRead { evm with + memory := memoryExtend evm.memory expandBy, gas := GasMeter.drain evm.gas } + evm.message.currentTarget) newAccount) subCall (GasMeter.reservoir evm.gas) with + | error e => simp [hs, Functor.map, Except.map] at h + | ok after => + simp only [hs, Functor.map, Except.map, Except.ok.injEq] at h + subst h + have refill : LStep (recordAccountRead { evm with + memory := memoryExtend evm.memory expandBy, gas := GasMeter.drain evm.gas } + evm.message.currentTarget) + (refillStateGas (recordAccountRead { evm with + memory := memoryExtend evm.memory expandBy, gas := GasMeter.drain evm.gas } + evm.message.currentTarget) newAccount) := ⟨rfl, rfl⟩ + exact (pre.trans refill).trans (lStep_skipCall hs) + · refine LResult.lift pre (lResult_genericCall ?_ h) + simp only [Bool.or_eq_true, beq_iff_eq] + exact Or.inr static + +theorem lResult_callStep {kind : CallKind} {evm : Evm fork Meter} + {result : StepResult fork Meter} (static : evm.message.isStatic = true) + (h : callStep kind evm = .ok result) : LResult evm result := by + unfold callStep at h + obtain ⟨⟨call, e1⟩, h1, h⟩ := Base.bind_ok_iff.mp h + have c1 := (lStep_popCallOperands h1).1 + dsimp only at h + split at h + · simp only [throw, throwThe, MonadExceptOf.throw, bind, Except.bind] at h + cases h + rcases hacc : accessAddress e1 call.address with ⟨cold, e2⟩ + simp only [hacc] at h + have ha : LStep e1 e2 := by + have := lStep_accessAddress e1 call.address + rwa [hacc] at this + have s3 : LStep evm (recordAccountRead e2 call.address) := + (c1.trans ha).trans (lStep_recordAccountRead e2 call.address) + obtain ⟨_, -, h⟩ := Base.bind_ok_iff.mp h + rcases keepReads_eq_ok h with h | ⟨e, rfl⟩ + · obtain ⟨⟨callee, e4⟩, h4, h⟩ := Base.bind_ok_iff.mp h + have s4 : LStep evm e4 := s3.trans (lStep_accessDelegation h4) + dsimp only at h + rcases keepReads_eq_ok h with h | ⟨e, rfl⟩ + · obtain ⟨⟨subCall, e5⟩, h5, h⟩ := Base.bind_ok_iff.mp h + have s5 : LStep evm e5 := s4.trans (lStep_payCall h5) + exact LResult.lift s5 (lResult_finishCall (by rw [s5.message]; exact static) h) + · exact s4.trans (lStep_exceptionalHalt _ _) + · exact s3.trans (lStep_exceptionalHalt _ _) + +theorem lResult_messageInstruction {op : Op} + {run : Evm fork Meter → Except EvmError (StepResult fork Meter)} {evm : Evm fork Meter} + {result : StepResult fork Meter} (hrun : messageInstruction fork op = some run) + (static : evm.message.isStatic = true) (h : run evm = .ok result) : LResult evm result := by + unfold messageInstruction at hrun + cases hc : callInstruction (Meter := Meter) fork op with + | some call => + simp only [hc, HOrElse.hOrElse, OrElse.orElse, Option.orElse, Option.some.injEq] at hrun + subst hrun + cases op <;> simp only [callInstruction, Option.some.injEq, reduceCtorEq] at hc + all_goals first + | (subst hc; exact lResult_callStep static h) + | (split at hc + · simp only [Option.some.injEq] at hc + subst hc + exact lResult_callStep static h + · cases hc) + | none => + simp only [hc, HOrElse.hOrElse, OrElse.orElse, Option.orElse] at hrun + cases op <;> simp only [createInstruction, Option.some.injEq, reduceCtorEq] at hrun + all_goals first + | (subst hrun; exact absurd h (createStep_ne_ok_of_isStatic static)) + | (split at hrun + · simp only [Option.some.injEq] at hrun + subst hrun + exact absurd h (createStep_ne_ok_of_isStatic static) + · cases hrun) + +/-- **A step of a static frame keeps the message and the logs**, or sends a static message +after which the caller keeps its logs when the child ends with none. -/ +theorem lResult_step {evm : Evm fork Meter} {result : StepResult fork Meter} + (static : evm.message.isStatic = true) (h : step fork evm = .ok result) : + LResult evm result := by + unfold step at h + split at h + · dsimp only at h + split at h + · cases h + · split at h + · rename_i hop + cases hr : ‹Evm fork Meter → Except EvmError (Evm fork Meter)› evm with + | error => simp [hr, Functor.map, Except.map] at h + | ok after => + simp only [hr, Functor.map, Except.map, Except.ok.injEq] at h + subst h + exact lStep_instruction_of_isStatic hop static hr + · split at h + · rename_i hcall + exact lResult_messageInstruction hcall static h + · cases h + · simp only [stopStep, Functor.map, Except.map, Except.ok.injEq] at h + subst h + exact LStep.of_sameContext (controlFlowStep_sameContext (op := .stop) rfl rfl) + +/-! ## Messages -/ + +theorem lStep_runPrecompile {address : Nat} {evm after : Evm fork Meter} + (h : runPrecompile fork address evm = some after) : LStep evm after := by + unfold runPrecompile at h + split at h + · cases h + · cases h + exact lStep_exceptionalHalt _ _ + · split at h + · cases h + exact lStep_exceptionalHalt _ _ + · cases h + exact ⟨rfl, rfl⟩ + +/-- The deposit of code keeps the substate, and leaves no error only after a frame with none. -/ +theorem depositCode_facts {snapshot : TransactionState} {evm after : Evm fork Meter} + (h : depositCode fork snapshot evm = .ok after) : + after.substate = evm.substate ∧ (after.error = none → evm.error = none) := by + unfold depositCode at h + split at h + · cases h + exact ⟨rfl, id⟩ + · dsimp only at h + split at h + · cases h + exact ⟨rfl, fun h' => by simp at h'⟩ + · split at h + · cases h + exact ⟨rfl, fun h' => by simp at h'⟩ + · split at h + · split at h <;> cases h <;> first | exact ⟨rfl, id⟩ | exact ⟨rfl, fun h' => by simp at h'⟩ + · split at h + · cases h + exact ⟨rfl, fun h' => by simp at h'⟩ + · obtain ⟨st, -, h⟩ := Base.bind_ok_iff.mp h + cases h + exact ⟨rfl, id⟩ + +/-- What a static message that ends with no error keeps: its starting logs. -/ +def LogsKept (message : Message fork) (_state : TransactionState) (substate : Substate) + (_meter : Meter) (ended : Evm fork Meter) : Prop := + message.isStatic = true → ended.error = none → ended.substate.logs = substate.logs + +/-- **Before Glamsterdam, every static call and creation that ends with no error ends with the +logs it started from**, however deep its calls: the induction on the gas of messages. -/ +theorem logsKept_process [LawfulGasMeter Meter] (hfork : fork < .glamsterdam) (n : Nat) : + (∀ (message : Message fork) (state : TransactionState) (substate : Substate) (meter : Meter) + (held : GasMeter.gasHeld meter ≤ message.gas), message.gas = n → + ∀ ended, processMessage fork message state substate meter held = .ok ended → + LogsKept message state substate meter ended.val) ∧ + (∀ (message : Message fork) (state : TransactionState) (substate : Substate) (meter : Meter) + (held : GasMeter.gasHeld meter ≤ message.gas), message.gas = n → + ∀ ended, processCreateMessage fork message state substate meter held = .ok ended → + LogsKept message state substate meter ended.val) := by + refine processMessage_rel (R := fun a b => a.message.isStatic = true → LStep a b) + (Inv := fun evm => evm.message.isStatic = true) (M := LogsKept) + (fun evm _ => LStep.refl evm) + (fun {a b c} hab hbc ha => (hab ha).trans (hbc (by rw [(hab ha).message]; exact ha))) + (fun {a b} ha r => by rw [(r ha).message]; exact ha) + (fun evm e _ _ => lStep_exceptionalHalt evm e) + ?steps (fun evm _ _ => ⟨rfl, rfl⟩) + (fun {address evm after} h _ _ => lStep_runPrecompile h) + ?call ?create n + case steps => + intro evm result hinv hstep + have r := lResult_step hinv hstep + cases result with + | next after => exact fun _ => r + | child caller message resume => + obtain ⟨c, hm, k⟩ := r + refine ⟨fun _ => c, fun child after hres hc _ => k child after hres ?_⟩ + intro he + have := hc hm he + rw [this] + rfl + case call => + intro message state entry substate entrySubstate meter ended hE hR hs he + have hst : (startFrame message entry entrySubstate meter).message.isStatic = true := hs + have l := hR hst hst + have hsub : (rollbackOnError state ended).substate = ended.substate := by + unfold rollbackOnError; split <;> rfl + rw [hsub, l.logs] + show entrySubstate.logs = substate.logs + rcases hE with ⟨-, -, rfl⟩ | ⟨-, -, rfl⟩ + · rfl + · have : ¬fork ≥ .glamsterdam := Nat.not_le_of_lt hfork + simp only [pushTransferLog, this, false_and, ↓reduceIte] + case create => + intro message state prepared substate meter evm after _ hM hd hs he + obtain ⟨hsub, herr⟩ := depositCode_facts hd + rw [hsub] + exact hM hs (herr he) + +/-- **EIP-214 for EthLib's runner of messages**: before Glamsterdam, a static message that the +runner ends with no error ends with no log. -/ +theorem meets_staticNoLogs [LawfulGasMeter Meter] (hfork : fork < .glamsterdam) (bound : Nat) : + Logic.Meets (bound := bound) + (fun _ m child => m.isStatic = true → child.error = none → child.substate.logs.toList = []) + (Logic.processRunner fork (Meter := Meter) bound) := by + refine ⟨fun caller m lt ended h hs he => ?_, (Logic.meets_process fork bound).aborts⟩ + unfold Logic.processRunner at h + split at h + · have := (logsKept_process hfork m.gas).1 m _ _ _ _ rfl ended h hs he + rw [this] + rfl + · have := (logsKept_process hfork m.gas).2 m _ _ _ _ rfl ended h hs he + rw [this] + rfl + +/-- info: 'EthLib.Execution.Evm.StaticLogs.meets_staticNoLogs' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms meets_staticNoLogs + +end EthLib.Execution.Evm.StaticLogs diff --git a/SolidCore/Refinement/Solar/AssembleCallStaticRunner.lean b/SolidCore/Refinement/Solar/AssembleCallStaticRunner.lean new file mode 100644 index 00000000..6d2d4033 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCallStaticRunner.lean @@ -0,0 +1,67 @@ +import SolidCore.Refinement.Solar.AssembleCallSeg +import SolidCore.Refinement.Solar.AssembleCallStatic + +/-! +# EIP-214 discharged: StaticNoLogs is a theorem of EthLib's runner + +AssembleCallCut.StaticNoLogs (a static message that succeeds ends with no log) was a named +hypothesis of AssembleCallSeg.StaticRunner. EthLib.Execution.Evm.StaticLogs.meets_staticNoLogs +proves it of the interpreter's runner of messages before Glamsterdam, so at Fusaka: + +* meets_staticNoLogs: the runner meets StaticNoLogs at every bound (proved, no hypothesis). +* OutputRunner: what is left of StaticRunner, the named hypothesis that each callee's output + has fewer than 2 ^ 256 bytes (AssembleCallCut.OutputFits; not derived here). +* holds_of_checkCB_out: holds_of_checkCB_named with StaticRunner replaced by OutputRunner, so the + final theorem names OutputRunner, EcrecoverAgree and CalleesRunR and nothing about logs. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCallStaticRunner + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Witness SolidCore.Refinement.Final +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleCallCut +open SolidCore.Refinement.Solar.AssembleCallSeg SolidCore.Refinement.Solar.AssembleCut +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic + +/-- **EIP-214, proved**: at Fusaka, the interpreter's runner of messages ends every static +message that succeeds with no log, at every bound on the gas of messages. -/ +theorem meets_staticNoLogs (gas : Nat) : + Meets (bound := gas) StaticNoLogs (processRunner .fusaka (Meter := Nat) gas) := + EthLib.Execution.Evm.StaticLogs.meets_staticNoLogs (by decide) gas + +/-- **Named hypothesis on the runner of messages**: each callee's output has fewer than +2 ^ 256 bytes (OutputFits), the part of StaticRunner not derived. -/ +def OutputRunner (gas : Nat) : Prop := + Meets (bound := gas) OutputFits (processRunner .fusaka (Meter := Nat) gas) + +/-- StaticRunner from OutputRunner alone: its StaticNoLogs half is meets_staticNoLogs. -/ +theorem staticRunner_of_output {gas : Nat} (h : OutputRunner gas) : StaticRunner gas := + ⟨fun a b c d e => ⟨(meets_staticNoLogs gas).ok a b c d e, h.ok a b c d e⟩, h.aborts⟩ + +/-- **holds_of_checkCB_named without the EIP-214 hypothesis**: the source's specification at +every open world, its totality, the stages and the checker give the specification of the exact +bytecode at every gas below 2 ^ 256, under the named hypotheses OutputRunner (callee outputs +below 2 ^ 256 bytes), AssembleCallPre.EcrecoverAgree and CalleesRunR. -/ +theorem holds_of_checkCB_out {St : Type} {fuel : Nat} + {mirSem : SolarTV.Machine.Oracle → Sem} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {mir : ∀ o, (mirSem o).Prog} {p : Assemble.Program} {code : ByteArray} {cert : Cert} + {mx : List Nat} {spec : Final.ContractSpec St} + (source : ∀ W : World, W.Open → Final.Holds (solidCoreIn W fuel) c spec) + (fin : ∀ W : World, W.Open → ∀ call, spec.Calls call → (Source.runIn W fuel c call).isSome) + (lowering : ∀ o W, CallsAgree o W → Stage (solidCoreIn W fuel) (mirSem o) c (mir o) spec.Calls) + (backend : ∀ o, Stage (mirSem o) (evmirSem o) (mir o) p spec.Calls) + (hc : checkCB p code cert mx = true) (codes : SolidCore.Solidity.Shared.Account.BytesMap) + (hO : ∀ gas, OutputRunner gas) (hagree : AssembleCallPre.EcrecoverAgree) + (hQ : ∀ gas call, spec.Calls call → CalleesRunR gas code call) + (gas : Nat) (hgas : gas < 2 ^ 256) : Final.Holds (Final.ethLibWith gas) code spec := + holds_of_checkCB_named source fin lowering backend hc codes + (fun gas => staticRunner_of_output (hO gas)) hagree hQ gas hgas + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallStaticRunner.meets_staticNoLogs' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms meets_staticNoLogs + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallStaticRunner.holds_of_checkCB_out' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holds_of_checkCB_out + +end SolidCore.Refinement.Solar.AssembleCallStaticRunner diff --git a/SolidCore/Refinement/Solar/AssembleCallValue.lean b/SolidCore/Refinement/Solar/AssembleCallValue.lean new file mode 100644 index 00000000..476b08ef --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCallValue.lean @@ -0,0 +1,176 @@ +import EthLib.Execution.Proofs.Evm.Logic.Call +import EthLib.Execution.Proofs.Evm.Logic.LessGas + +/-! +# CALL with value at the frame's own gas, from a run that succeeds + +`callValue_back`: a CALL that sends a nonzero value, in a run of EthLib's interpreter (Fusaka) that ends +with no error, had the gas for its price (the access of EIP-2929, 9000 for the value, 25000 for a +dead callee and the growth of memory; `callValue_oog` shows the step fails short of it), and the run goes on +in one of two ways: + +* the current account lacks the value: no message, 0 pushed, the gas it would pass on (with the + stipend of 2300) given back, empty return data (EthLib's `Logic.callValueLow`); +* otherwise the callee runs with the value, its input and the gas EIP-150 passes on (with the + stipend), under any runner of messages meeting `P`; the caller pushes 1 when the callee's frame + ends with no error and 0 otherwise, writes its output to the output range, takes it as the return + data, and its state and substate are the ones the callee left (EthLib's `Logic.callValue`). + Nothing is assumed of the callee: it may reenter the caller, so the rule says nothing of the + state after the call beyond the callee's frame, which a run's table records. + +Named hypotheses: the callee's code is in the state and is no EIP-7702 delegation, and the frame +is below the greatest depth (a frame of a call at depth below 1024 is, `hdepth`). +-/ + +namespace SolidCore.Refinement.Solar.AssembleCallValue + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts + +/-- The price of CALL with value before the gas it passes on: the access, the value, a new +account, and the growth of memory. -/ +def priceV (st : State.TransactionState) (ss : Substate) (msize : Nat) (to v i isz o osz : U256) : + Nat := + (callBaseCost .fusaka (decide (toAddressMasked to ∉ ss.accessedAddresses)) + + callNewAccountCost .fusaka st (toAddressMasked to) v + callValueCost .fusaka v) + + (extendMemory msize [(i, isz), (o, osz)]).cost + +/-- **CALL with value short of its price fails or halts the frame.** -/ +theorem callValue_oog {evm : Evm .fusaka Nat} {g a v i isz o osz : U256} {rest : List U256} + {calleeCode : ByteArray} + (hst : evm.stack.val = g :: a :: v :: i :: isz :: o :: osz :: rest) (hv : v ≠ 0) + (hcode : evm.state.getCode (evm.state.getAccount (toAddressMasked a)).codeHash = .ok calleeCode) + (hdel : delegatedAddress calleeCode = none) + (hgas : evm.gas < priceV evm.state evm.substate evm.memory.size a v i isz o osz) : + StepFails (callStep .call evm) := by + rcases evm with ⟨pc, ⟨l, hl⟩, memory, code, valid, gas, running, message, output, returnData, + state, substate, error⟩ + simp only at hst + subst hst + simp only [priceV] at hcode hgas + have hv' : ¬v = 0#256 := hv + generalize hE : callBaseCost .fusaka (!decide (toAddressMasked a ∈ substate.accessedAddresses)) + + (if state.isAccountAlive (toAddressMasked a) = true then 0 else NEW_ACCOUNT) + CALL_VALUE = E + have hgas' : gas < E + (extendMemory memory.size [(i, isz), (o, osz)]).cost := by + rw [← hE] + simpa [callNewAccountCost, callValueCost, hv', show ¬ Fork.fusaka ≥ .glamsterdam by decide, + show Fork.spuriousDragon ≤ Fork.fusaka by decide] using hgas + have hle : E ≤ (messageCallGas .fusaka v g.toNat gas + (extendMemory memory.size [(i, isz), (o, osz)]).cost E).cost := by + simp [messageCallGas] + have hlt : gas < (messageCallGas .fusaka v g.toNat gas + (extendMemory memory.size [(i, isz), (o, osz)]).cost E).cost + + (extendMemory memory.size [(i, isz), (o, osz)]).cost := by omega + unfold StepFails + simp [callStep, popCallOperands, popCallValue, CallKind.sendsValue, popWord, Stack.pop, bind, + Except.bind, pure, Except.pure, accessAddress, show Fork.berlin ≤ Fork.fusaka by decide, + checkGas, show ¬ Fork.fusaka ≥ .glamsterdam by decide, accessDelegation, accountCode, + recordAccountRead, hcode, hdel, show Fork.pectra ≤ Fork.fusaka by decide, + show Fork.tangerineWhistle ≤ Fork.fusaka by decide, + show Fork.spuriousDragon ≤ Fork.fusaka by decide, Except.mapError, callExtraGas, + callNewAccountCost, callValueCost, hv', payCall, chargeGas, GasMeter.charge, keepReads, hE, hlt, + GasMeter.gasLeft, + exceptionalHalt, EvmError.aborts] + + +/-- The gas CALL with value passes on and its full price, EIP-150 at the frame's gas `g`. -/ +abbrev mcgV (g : Nat) (st : State.TransactionState) (ss : Substate) (msize : Nat) + (asked to v i isz o osz : U256) : MessageCallGas := + messageCallGas .fusaka v asked.toNat g (extendMemory msize [(i, isz), (o, osz)]).cost + (callBaseCost .fusaka (decide (toAddressMasked to ∉ ss.accessedAddresses)) + + callNewAccountCost .fusaka st (toAddressMasked to) v + callValueCost .fusaka v) + +/-- **CALL with value in a run that succeeds**: the frame had its price, and the run goes on with +no message when the current account lacks the value, or from the frame after the callee's message +otherwise, under any runner of messages meeting `P`. -/ +theorem callValue_back {code : ByteArray} {msg : Message .fusaka} {pc g : Nat} {M : ByteArray} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray} + {asked to v i isz o osz : U256} {rest : List U256} {evm : Evm .fusaka Nat} + {calleeCode : ByteArray} + (hat : At code msg pc (asked :: to :: v :: i :: isz :: o :: osz :: rest) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0xf1) (hv : v ≠ 0) + (hstatic : msg.isStatic = false) + (hcode : st.getCode (st.getAccount (toAddressMasked to)).codeHash = .ok calleeCode) + (hdel : delegatedAddress calleeCode = none) (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} (meets : Meets P runChild) + (within : GasMeter.gasHeld evm.gas ≤ bound) {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + priceV st ss M.size to v i isz o osz ≤ g ∧ + (((st.getAccount msg.currentTarget).balance < v ∧ + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) (0 :: rest) + (memoryExtend M (extendMemory M.size [(i, isz), (o, osz)]).expandBy) + (g - ((mcgV g st ss M.size asked to v i isz o osz).cost + + (extendMemory M.size [(i, isz), (o, osz)]).cost) + + (mcgV g st ss M.size asked to v i isz o osz).subCall) + ((st.recordAccountRead (toAddressMasked to)).recordAccountRead msg.currentTarget) + { ss with accessedAddresses := ss.accessedAddresses.insert (toAddressMasked to) } + .empty m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin) ∨ + (v ≤ (st.getAccount msg.currentTarget).balance ∧ + ∃ (caller : Evm .fusaka Nat) (m : Message .fusaka) (child after : Evm .fusaka Nat) + (within' : GasMeter.gasHeld after.gas ≤ bound), + P caller m child ∧ child.gas ≤ m.gas ∧ + caller.state = (st.recordAccountRead (toAddressMasked to)).recordAccountRead + msg.currentTarget ∧ + caller.substate = { ss with + accessedAddresses := ss.accessedAddresses.insert (toAddressMasked to) } ∧ + m.gas = (mcgV g st ss M.size asked to v i isz o osz).subCall ∧ + m.caller = msg.currentTarget ∧ m.currentTarget = toAddressMasked to ∧ + m.code = calleeCode ∧ + m.data = memoryReadBytes (memoryExtend M + (extendMemory M.size [(i, isz), (o, osz)]).expandBy) i.toNat isz.toNat ∧ + m.value = v ∧ m.isStatic = false ∧ + At code msg (pc + 1) ((if child.error.isNone then 1 else 0) :: rest) + (memoryWrite (memoryExtend M (extendMemory M.size [(i, isz), (o, osz)]).expandBy) + o.toNat (child.output.extract 0 (min osz.toNat child.output.size))) + (g - ((mcgV g st ss M.size asked to v i isz o osz).cost + + (extendMemory M.size [(i, isz), (o, osz)]).cost) + child.gas) + (incorporateChild .fusaka caller child).state + (incorporateChild .fusaka caller child).substate child.output after ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild after within' = .ok fin)) := by + have hat0 := hat + obtain ⟨hc, hj, hm, hpc, hst, hmem, hgas, hrunning, herr, hout, hs, hss, hrd⟩ := hat0 + have hlt' : evm.pc < evm.code.size := by rw [hc, hpc]; exact hlt + have decoded : Op.ofByte .fusaka (evm.code[evm.pc]'hlt') = some .call := by + have he : evm.code[evm.pc]'hlt' = code[pc]'hlt := by subst hc hpc; rfl + rw [he, hbyte] + exact ofByte_of_decode rfl (Fork.frontier_le _) + have hstep : step .fusaka evm = callStep .call evm := + step_of_messageInstruction hlt' decoded instruction_call messageInstruction_call + have hg : priceV st ss M.size to v i isz o osz ≤ g := by + refine Nat.le_of_not_lt fun hlow => ?_ + have fails := callValue_oog (evm := evm) hst hv (by rw [hs]; exact hcode) hdel + (by rw [hs, hss, hmem, hgas]; exact hlow) + exact error_ne_none_of_stepFails hrunning (by rw [hstep]; exact fails) hrun hok + refine ⟨hg, ?_⟩ + rcases Nat.lt_or_ge (st.getAccount msg.currentTarget).balance.toNat v.toNat with hb | hb + · -- The current account lacks the value: no message. + have hbal : (st.getAccount msg.currentTarget).balance < v := BitVec.lt_def.mpr hb + obtain ⟨m, hr, hq⟩ := callValueLow (fork := .fusaka) (cold := _) (by decide) (by decide) hlt + hbyte hv hstatic hbal hcode (fun _ => hdel) rfl hg evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact .inl ⟨hbal, m, _, hq, hrun⟩ + · have hbal : v ≤ (st.getAccount msg.currentTarget).balance := BitVec.le_def.mpr hb + have H := callValue (fork := .fusaka) (callee := P) (asked := asked) (rest := rest) + (returnData := rd) + (cold := _) (by decide) (by decide) hlt hbyte hv hstatic hbal hcode (fun _ => hdel) hdepth rfl hg + obtain ⟨after, hr, hq⟩ := H bound runChild meets evm hat within + have within' := Nat.le_trans (hr.gasHeld_le StepBy.gasHeld_le) within + have hrun' := hrun + rw [runFrame_eq_of_reaches StepBy.gasHeld_le StepBy.runFrame_eq hr within] at hrun' + rcases hq with ⟨caller, m, child, hk, hcg, c1, c2, m1, m2, m3, -, -, m6, m7, m8, -, -, m11, + hat'⟩ | aborted + · exact .inr ⟨hbal, caller, m, child, after, within', hk, hcg, c1, c2, m1, m2, m3, m6, m7, m8, + m11, hat', hrun'⟩ + · obtain ⟨e, he, -⟩ := runFrame_of_abortsBy meets.aborts aborted within' + rw [he] at hrun' + cases hrun' + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallValue.callValue_back' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms callValue_back + +end SolidCore.Refinement.Solar.AssembleCallValue diff --git a/SolidCore/Refinement/Solar/AssembleCallValueEffect.lean b/SolidCore/Refinement/Solar/AssembleCallValueEffect.lean new file mode 100644 index 00000000..06ab46d9 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCallValueEffect.lean @@ -0,0 +1,122 @@ +import SolidCore.Refinement.Solar.AssembleCall +import SolidCore.Refinement.Solar.AssembleCreate + +/-! +# CALL with value and CREATE2 in SolarTV, beside EthLib + +What SolarTV's effects do for a CALL with value and a CREATE2, under an oracle that answers each as +the callee's frame ended, and that this is what EthLib leaves (`AssembleCallValue.callValue_back`, +`AssembleCreateBack.create2_back`): + +* `call_effectW`: CALL with operands `gas, addr, value, ranges` pushes the flag EthLib pushes, writes + the callee's output to the output range as EthLib does, takes it as the return data, and leaves + the storage and transient storage the oracle answers after the call (`storageAfter` of the world + with the call): a reentrant callee may change them, so they are the oracle's, which a run's table + takes from the frame after the callee. +* `create2_effectW`: CREATE2 pushes the word the oracle answers for the creation, which is EthLib's + (the EIP-1014 address on success, below `2 ^ 160`, `toU256_lt`; 0 on failure), grows memory as + EthLib does, and records as init code the bytes EthLib sends as the message's code. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCallValueEffect + +open SolarTV SolarTV.Machine +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.RunOracle +open SolidCore.Refinement.Solar.AssembleEffects SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCall +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts + +/-- The world after a CALL with value, as SolarTV records it. -/ +abbrev callWorld (s : State) (gas addr value inOff inSize outOff outSize : Word) : List Event := + s.world ++ [.call .call [gas, addr, value] + (((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat outSize.toNat).read + inOff.toNat inSize.toNat) s.storage s.transient] + +/-- **CALL with value in SolarTV at any ranges** whose words SolarTV counts, under an oracle that +answers the call as the callee's frame `child` ended. -/ +theorem call_effectW {o : Oracle} {call : Call} {s : State} {M : ByteArray} + {gas addr value inOff inSize outOff outSize : Word} {child : Evm .fusaka Nat} + (hm : MemRel s.memory M) + (hb1 : inSize = 0 ∨ (inOff.toNat + inSize.toNat + 31) / 32 < 2 ^ 251) + (hb2 : outSize = 0 ∨ (outOff.toNat + outSize.toNat + 31) / 32 < 2 ^ 251) + (hflag : callFlag o (callWorld s gas addr value inOff inSize outOff outSize) = + if child.error.isNone then 1 else 0) + (hrd : RdRel o (callWorld s gas addr value inOff inSize outOff outSize) child.output) : + ∃ s', Effect.apply o call (.call .call) [gas, addr, value, inOff, inSize, outOff, outSize] s = + some (some (if child.error.isNone then 1 else 0), s') ∧ + s'.storage = o.storageAfter (callWorld s gas addr value inOff inSize outOff outSize) ∧ + s'.transient = o.transientAfter (callWorld s gas addr value inOff inSize outOff outSize) ∧ + RdRel o s'.world child.output ∧ + s'.world = callWorld s gas addr value inOff inSize outOff outSize ∧ + MemRel s'.memory (memoryWrite (memoryExtend M + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).expandBy) + outOff.toNat (child.output.extract 0 (min outSize.toNat child.output.size))) := by + have he := memRel_expand2W hm hb1 hb2 + refine ⟨called o .call s ((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat + outSize.toNat) outOff outSize (callWorld s gas addr value inOff inSize outOff outSize), + ?_, rfl, rfl, hrd, rfl, ?_⟩ + · simp only [Effect.apply, CallKind.shape, hflag] + · simp only [called] + rw [hrd.1] + refine memRel_write he (fun hz => ?_) ?_ (fun i hi => ?_) + · have hz' : outSize ≠ 0 := fun h => hz (by simp [h]) + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have := le_ceil32_add_expandBy M.size [(inOff, inSize), (outOff, outSize)] (outOff, outSize) + (by simp) hz' + dsimp only at this + rw [ceil32_of_mod hmod] at this + rw [size_memoryExtend] + have := Nat.min_le_left outSize.toNat child.output.size + omega + · simp [ByteArray.size_extract] + · rw [byteAt_extract, Nat.zero_add, if_pos (by omega)] + exact (hrd.2 i (by omega)).symm + +/-- An address, as a word, is below `2 ^ 160`. -/ +theorem toU256_lt (a : Address) : a.toU256.toNat < 2 ^ 160 := by + unfold Address.toU256 + rw [BitVec.toNat_ofNat] + have h := bytesToNat_lt a.toList + simp only [Vector.length_toList] at h + rw [show (256 : Nat) ^ 20 = 2 ^ 160 from rfl] at h + exact Nat.lt_of_le_of_lt (Nat.mod_le _ _) h + +/-- The world after a CREATE2, as SolarTV records it. -/ +abbrev createWorld (s : State) (value offset size salt : Word) : List Event := + s.world ++ [.create [value, salt] ((s.memory.expand offset.toNat size.toNat).read offset.toNat + size.toNat) s.storage s.transient] + +/-- **CREATE2 in SolarTV** at any range whose words SolarTV counts, under an oracle that answers the +creation with the word `r` below `2 ^ 160` (the address EthLib pushes on success, 0 on failure): it +pushes `r`, grows memory as EthLib does, records as init code the bytes EthLib reads, and leaves +the storage the oracle answers after the creation. -/ +theorem create2_effectW {o : Oracle} {call : Call} {s : State} {M : ByteArray} + {value offset size salt r : Word} (hm : MemRel s.memory M) + (hb : size = 0 ∨ (offset.toNat + size.toNat + 31) / 32 < 2 ^ 251) + (hr : r.toNat < 2 ^ 160) + (hres : (o.result (createWorld s value offset size salt)).toNat % 2 ^ 160 = r.toNat) : + ∃ s', Effect.apply o call .create2 [value, offset, size, salt] s = some (some r, s') ∧ + s'.storage = o.storageAfter (createWorld s value offset size salt) ∧ + s'.transient = o.transientAfter (createWorld s value offset size salt) ∧ + s'.world = createWorld s value offset size salt ∧ + MemRel s'.memory (memoryExtend M (extendMemory M.size [(offset, size)]).expandBy) ∧ + ((s.memory.expand offset.toNat size.toNat).read offset.toNat size.toNat).map BitVec.toNat = + (memoryReadBytes (memoryExtend M (extendMemory M.size [(offset, size)]).expandBy) + offset.toNat size.toNat).toList.map (·.toNat) := by + refine ⟨⟨s.memory.expand offset.toNat size.toNat, o.storageAfter (createWorld s value offset size salt), + o.transientAfter (createWorld s value offset size salt), createWorld s value offset size salt⟩, + ?_, rfl, rfl, rfl, memRel_expandW hm hb, (read_eq hm).symm⟩ + simp only [Effect.apply, created, hres] + congr + apply BitVec.eq_of_toNat_eq + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt (by omega)] + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallValueEffect.call_effectW' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms call_effectW + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallValueEffect.create2_effectW' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms create2_effectW + +end SolidCore.Refinement.Solar.AssembleCallValueEffect diff --git a/SolidCore/Refinement/Solar/AssembleCallValueSeg.lean b/SolidCore/Refinement/Solar/AssembleCallValueSeg.lean new file mode 100644 index 00000000..1719f886 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCallValueSeg.lean @@ -0,0 +1,317 @@ +import SolidCore.Refinement.Solar.AssembleCallValue +import SolidCore.Refinement.Solar.AssembleCallCut +import SolidCore.Refinement.Solar.AssembleCreateSeg + +/-! +# CALL with value as a cut of a run, at the frame's own gas + +`callValue_cut` is the step the checker's segments take at a CALL that sends a nonzero value: from a +run of the bytecode that succeeds, the CALL had its price (`AssembleCallValue.callValue_back`: EIP-2929 +access, 9000 for the value, 25000 for a dead callee, the growth of memory, EIP-150 forwarding with the +stipend) and the run goes on from the frame after it. The run's table (`RunOracle.RunTable`) grows by +the call's success flag, its return data and the storage of the frame's account after it (a callee +may reenter the frame and change it), and under the oracle of every extension of it +(`RunOracle.tableOracle`) SolarTV's CALL pushes the same flag, writes the same output, takes the same +return data and leaves that storage: every relation of a block entry holds again. + +When the frame lacks the value there is no message: 0 pushed, no return data, the stipend given back. + +Named, as for STATICCALL (`AssembleCallSeg.CalleesOk`): the callee's code is in the state and is no +EIP-7702 delegation (`callValue_back`'s premises), and `CallOk` of the frame that ends this call's message +(asked only of the message this step sends, with its input, value and gas, from the caller state the +step leaves): the frame's account still exists after it, a call that succeeds adds no log (SolarTV's +world records only the frame's own logs), and its output has fewer than `2 ^ 256` bytes. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCallValueSeg + +open SolarTV SolarTV.Machine +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.RunOracle +open SolidCore.Refinement.Solar.AssembleEffects SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCallValue SolidCore.Refinement.Solar.AssembleCallValueEffect +open SolidCore.Refinement.Solar.AssembleCreateSeg SolidCore.Refinement.Solar.AssembleCall +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts + +/-- **CALL with value in SolarTV**, for any flag and return data the oracle answers. -/ +theorem call_effectO {o : Oracle} {call : Call} {s : State} {M : ByteArray} + {gas addr value inOff inSize outOff outSize : Word} {ok : Bool} {out : ByteArray} + (hm : MemRel s.memory M) + (hb1 : inSize = 0 ∨ (inOff.toNat + inSize.toNat + 31) / 32 < 2 ^ 251) + (hb2 : outSize = 0 ∨ (outOff.toNat + outSize.toNat + 31) / 32 < 2 ^ 251) + (hflag : callFlag o (callWorld s gas addr value inOff inSize outOff outSize) = if ok then 1 else 0) + (hrd : RdRel o (callWorld s gas addr value inOff inSize outOff outSize) out) : + ∃ s', Effect.apply o call (.call .call) [gas, addr, value, inOff, inSize, outOff, outSize] s = + some (some (if ok then 1 else 0), s') ∧ + s'.storage = o.storageAfter (callWorld s gas addr value inOff inSize outOff outSize) ∧ + s'.world = callWorld s gas addr value inOff inSize outOff outSize ∧ + MemRel s'.memory (memoryWrite (memoryExtend M + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).expandBy) + outOff.toNat (out.extract 0 (min outSize.toNat out.size))) := by + have he := memRel_expand2W hm hb1 hb2 + refine ⟨called o .call s ((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat + outSize.toNat) outOff outSize (callWorld s gas addr value inOff inSize outOff outSize), + ?_, rfl, rfl, ?_⟩ + · simp only [Effect.apply, CallKind.shape, hflag] + · simp only [called] + rw [hrd.1] + refine memRel_write he (fun hz => ?_) ?_ (fun i hi => ?_) + · have hz' : outSize ≠ 0 := fun h => hz (by simp [h]) + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have := le_ceil32_add_expandBy M.size [(inOff, inSize), (outOff, outSize)] (outOff, outSize) + (by simp) hz' + dsimp only at this + rw [ceil32_of_mod hmod] at this + rw [size_memoryExtend] + have := Nat.min_le_left outSize.toNat out.size + omega + · simp [ByteArray.size_extract] + · rw [byteAt_extract, Nat.zero_add, if_pos (by omega)] + exact (hrd.2 i (by omega)).symm + +/-- The table with one more message: its flag, return data and the storage after it. -/ +def pushCall (T : RunTable) (ok : Bool) (out : ByteArray) (sto : Word → Word) : RunTable := + { T with + oks := T.oks ++ [ok] + outs := T.outs ++ [out] + stores := T.stores ++ [sto] + transients := T.transients ++ [fun _ => 0] } + +theorem le_pushCall (T : RunTable) (ok : Bool) (out : ByteArray) (sto : Word → Word) : + T.Le (pushCall T ok out sto) := + ⟨List.prefix_append _ _, List.prefix_append _ _, List.prefix_append _ _, List.prefix_append _ _, + List.prefix_refl _⟩ + +/-- **What every extension of the table answers at the world with the call**: the flag, the return +data, the storage and transient storage of the call's entry. -/ +theorem table_call {base : Oracle} {T T'' : RunTable} {w : List Event} {ok : Bool} {out : ByteArray} + {sto : Word → Word} (hsent : sent w = T.oks.length + 1) (houts : T.outs.length = T.oks.length) + (hst : T.stores.length = T.oks.length) (htr : T.transients.length = T.oks.length) + (hle : (pushCall T ok out sto).Le T'') : + (tableOracle base T'').result w = (if ok then 1 else 0) ∧ T''.out w = out ∧ + (tableOracle base T'').storageAfter w = sto ∧ + (tableOracle base T'').transientAfter w = fun _ => 0 := by + have h1 : T''.oks.getD T.oks.length false = ok := by + rw [AssembleRun.getD_of_prefix hle.1 (by simp [pushCall])] + simp [pushCall] + have h2 : T''.outs.getD T.oks.length .empty = out := by + rw [AssembleRun.getD_of_prefix hle.2.1 (by simp [pushCall, houts])] + simp [pushCall, houts] + have h3 : ∀ d, T''.stores.getD T.oks.length d = sto := by + intro d + rw [AssembleRun.getD_of_prefix hle.2.2.1 (by simp [pushCall, hst])] + simp [pushCall, hst] + have h4 : ∀ d, T''.transients.getD T.oks.length d = fun _ => 0 := by + intro d + rw [AssembleRun.getD_of_prefix hle.2.2.2.1 (by simp [pushCall, htr])] + simp [pushCall, htr] + refine ⟨?_, ?_, ?_, ?_⟩ + · simp only [tableOracle, hsent, Nat.add_sub_cancel, h1, ne_eq, Nat.add_one_ne_zero, + not_false_eq_true, true_and] + all_goals (cases ok <;> simp) + · simp only [RunTable.out, hsent, Nat.add_one_ne_zero, ite_false, Nat.add_sub_cancel, h2] + · simp only [tableOracle, hsent, Nat.add_one_ne_zero, ite_false, Nat.add_sub_cancel, h3] + · simp only [tableOracle, hsent, Nat.add_one_ne_zero, ite_false, Nat.add_sub_cancel, h4] + +/-- The price paid for the access, the value, a new account and the gas passed on covers the gas the +callee gets back, with its stipend: the frame ends the call with at most its gas less the growth of +memory. -/ +theorem gas_after_le {g : Nat} {st : State.TransactionState} {ss : Substate} {msize : Nat} + {asked dst v i isz o osz : U256} (hv : v ≠ 0) (hp : priceV st ss msize dst v i isz o osz ≤ g) + {c : Nat} (hc : c ≤ (mcgV g st ss msize asked dst v i isz o osz).subCall) : + g - ((mcgV g st ss msize asked dst v i isz o osz).cost + + (extendMemory msize [(i, isz), (o, osz)]).cost) + c ≤ + g - (extendMemory msize [(i, isz), (o, osz)]).cost := by + have hs := stipend_lt_callValueCost (fork := .fusaka) hv + have hm : ∀ x, maxMessageCallGas x ≤ x := fun x => by unfold maxMessageCallGas; omega + unfold priceV at hp + unfold mcgV messageCallGas at hc ⊢ + simp only [hv, ite_false] at hc ⊢ + simp only [CALL_STIPEND] at hs hc + split_ifs at hc ⊢ with hif + · have := hm (g - (extendMemory msize [(i, isz), (o, osz)]).cost - + (callBaseCost .fusaka (decide (toAddressMasked dst ∉ ss.accessedAddresses)) + + callNewAccountCost .fusaka st (toAddressMasked dst) v + callValueCost .fusaka v)) + have := Nat.min_le_right asked.toNat (maxMessageCallGas (g - (extendMemory msize + [(i, isz), (o, osz)]).cost - (callBaseCost .fusaka (decide (toAddressMasked dst ∉ + ss.accessedAddresses)) + callNewAccountCost .fusaka st (toAddressMasked dst) v + + callValueCost .fusaka v))) + omega + · exfalso + apply hif + exact ⟨by decide, by omega⟩ + +/-- **Named hypothesis on the frame that ends a call's message**: the caller's account still exists +after it, a call that succeeds adds no log, and its output has fewer than `2 ^ 256` bytes. -/ +def CallOk (msg : Message .fusaka) (child : Evm .fusaka Nat) : Prop := + (child.state.getAccountOptional msg.currentTarget).isSome = true ∧ + (child.error.isNone = true → child.substate.logs.toList = []) ∧ child.output.size < 2 ^ 256 + +/-- A call event writes no log. -/ +theorem logsRel_call {a : Address} {ss0 ss : Substate} {w : List Event} (k : SolarTV.Machine.CallKind) + (ops : List Word) (c : List Memory.Byte) (sto tr : Word → Word) (h : LogsRel a ss0 ss w) : + LogsRel a ss0 ss (w ++ [.call k ops c sto tr]) := by + obtain ⟨L, h1, h2⟩ := h + refine ⟨L, h1, ?_⟩ + rw [List.filter_append] + simpa [isLogE] using h2 + +/-- **CALL with value as a cut of a run that succeeds.** -/ +theorem callValue_cut {code : ByteArray} {msg : Message .fusaka} {call : Call} {pc g G : Nat} + {M : ByteArray} {st : State.TransactionState} {ss ss0 : Substate} {rd : ByteArray} + {asked dst v i isz o osz : U256} {Tr : List U256} {s : State} {evm : Evm .fusaka Nat} + (base : Oracle) (T : RunTable) + (hm : MemRel s.memory M) (R : Rel msg ss0 st ss s) (hb : MemBudget G M g) (hG : G < 2 ^ 300) + (hat : At code msg pc (asked :: dst :: v :: i :: isz :: o :: osz :: Tr) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0xf1) (hv : v ≠ 0) + (hstatic : msg.isStatic = false) {calleeCode : ByteArray} + (hcode : st.getCode (st.getAccount (toAddressMasked dst)).codeHash = .ok calleeCode) + (hdel : delegatedAddress calleeCode = none) (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} (meets : Meets P runChild) + (hq : ∀ caller m child, P caller m child → + caller.state = (st.recordAccountRead (toAddressMasked dst)).recordAccountRead msg.currentTarget → + m.gas = (mcgV g st ss M.size asked dst v i isz o osz).subCall → + m.caller = msg.currentTarget → m.currentTarget = toAddressMasked dst → + m.data = memoryReadBytes (memoryExtend M (extendMemory M.size [(i, isz), (o, osz)]).expandBy) + i.toNat isz.toNat → m.value = v → CallOk msg child) + (within : GasMeter.gasHeld evm.gas ≤ bound) {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) + (hoks : T.oks.length = sent s.world) (houts : T.outs.length = sent s.world) + (hsts : T.stores.length = sent s.world) (htrs : T.transients.length = sent s.world) : + ∃ (ok : Bool) (out : ByteArray) (s' : State) (st' : State.TransactionState) (ss' : Substate) + (M' : ByteArray) (g' : Nat) (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + (∀ T'', (pushCall T ok out (storeOf st' msg.currentTarget)).Le T'' → + Effect.apply (tableOracle base T'') call (.call .call) [asked, dst, v, i, isz, o, osz] s = + some (some (if ok then 1 else 0), s') ∧ RdRel (tableOracle base T'') s'.world out) ∧ + s'.world = callWorld s asked dst v i isz o osz ∧ + MemRel s'.memory M' ∧ Rel msg ss0 st' ss' s' ∧ MemBudget G M' g' ∧ g' ≤ g ∧ + At code msg (pc + 1) ((if ok then 1 else 0) :: Tr) M' g' st' ss' out m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + obtain ⟨hp, hcase⟩ := callValue_back hat hlt hbyte hv hstatic hcode hdel hdepth meets within hrun hok + have hp' : (callBaseCost .fusaka (decide (toAddressMasked dst ∉ ss.accessedAddresses)) + + callNewAccountCost .fusaka st (toAddressMasked dst) v + callValueCost .fusaka v) + + (extendMemory M.size [(i, isz), (o, osz)]).cost ≤ g := hp + obtain ⟨hb1, hb2, hbud, hfit⟩ := AssembleCallCut.budget_grow2 hmod hb hG hp' + have hbud0 : MemBudget G (memoryExtend M (extendMemory M.size [(i, isz), (o, osz)]).expandBy) + (g - (extendMemory M.size [(i, isz), (o, osz)]).cost) := by + have hc := extendMemory_cost M.size [(i, isz), (o, osz)] + rw [ceil32_of_mod hmod] at hc + have hmono := memoryGasCost_mono + (Nat.le_add_right M.size (extendMemory M.size [(i, isz), (o, osz)]).expandBy) + unfold MemBudget at hb ⊢ + rw [size_memoryExtend] + omega + -- The world with the call, and what every extension of a table with it answers there. + have hsent : sent (callWorld s asked dst v i isz o osz) = T.oks.length + 1 := by + simp [callWorld, hoks] + have hsame : ∀ (ok : Bool) (out : ByteArray) (sto : Word → Word) T'', + (pushCall T ok out sto).Le T'' → + Effect.apply (tableOracle base T'') call (.call .call) [asked, dst, v, i, isz, o, osz] s = + Effect.apply (tableOracle base (pushCall T ok out sto)) call (.call .call) + [asked, dst, v, i, isz, o, osz] s := by + intro ok out sto T'' hle + obtain ⟨r1, o1, s1, t1⟩ := table_call (base := base) hsent (by omega) (by omega) (by omega) hle + obtain ⟨r2, o2, s2, t2⟩ := table_call (base := base) hsent (by omega) (by omega) (by omega) + (RunTable.Le.refl (pushCall T ok out sto)) + have hrds : returndataSize (tableOracle base T'') (callWorld s asked dst v i isz o osz) = + returndataSize (tableOracle base (pushCall T ok out sto)) (callWorld s asked dst v i isz o osz) := by + rw [returndataSize_table, returndataSize_table, o1, o2] + have hrdb : returndataByte (tableOracle base T'') (callWorld s asked dst v i isz o osz) = + returndataByte (tableOracle base (pushCall T ok out sto)) (callWorld s asked dst v i isz o osz) := by + funext j + simp only [returndataByte, tableOracle, o1, o2] + simp + have hflag : callFlag (tableOracle base T'') (callWorld s asked dst v i isz o osz) = + callFlag (tableOracle base (pushCall T ok out sto)) (callWorld s asked dst v i isz o osz) := by + simp only [callFlag, r1, r2] + simp only [callWorld] at hrds hrdb hflag s1 s2 t1 t2 + simp only [Effect.apply, CallKind.shape, called, hflag, hrds, hrdb, s1, s2, t1, t2] + -- SolarTV's CALL under the table with the call's answers. + have heff : ∀ (ok : Bool) (out : ByteArray) (sto : Word → Word), out.size < 2 ^ 256 → + ∃ s', (∀ T'', (pushCall T ok out sto).Le T'' → + Effect.apply (tableOracle base T'') call (.call .call) [asked, dst, v, i, isz, o, osz] s = + some (some (if ok then 1 else 0), s') ∧ RdRel (tableOracle base T'') s'.world out) ∧ + s'.storage = sto ∧ s'.world = callWorld s asked dst v i isz o osz ∧ + MemRel s'.memory (memoryWrite (memoryExtend M + (extendMemory M.size [(i, isz), (o, osz)]).expandBy) + o.toNat (out.extract 0 (min osz.toNat out.size))) := by + intro ok out sto hsz + obtain ⟨r2, o2, s2, -⟩ := table_call (base := base) (ok := ok) (out := out) (sto := sto) hsent + (by omega) (by omega) (by omega) (RunTable.Le.refl _) + have hrd2 : RdRel (tableOracle base (pushCall T ok out sto)) (callWorld s asked dst v i isz o osz) out := by + have := rdRel_table base (pushCall T ok out sto) (callWorld s asked dst v i isz o osz) (by rw [o2]; exact hsz) + rwa [o2] at this + obtain ⟨s', happ, hsto, hw, hmem⟩ := call_effectO (o := tableOracle base (pushCall T ok out sto)) + (call := call) (ok := ok) hm hb1 hb2 (by simp only [callFlag, r2]; cases ok <;> simp) hrd2 + refine ⟨s', fun T'' hle => ⟨by rw [hsame ok out sto T'' hle, happ], ?_⟩, by rw [hsto, s2], hw, hmem⟩ + obtain ⟨-, o1, -, -⟩ := table_call (base := base) hsent (by omega) (by omega) (by omega) hle + have := rdRel_table base T'' (callWorld s asked dst v i isz o osz) (by rw [o1]; exact hsz) + rw [o1] at this + rw [hw] + exact this + rcases hcase with ⟨-, m, within', hat', hrun'⟩ | + ⟨-, caller, mm, child, after, within', hP, hcg, hcs, hcsub, hmg, hmc, hmt, -, hmd, hmv, -, + hat', hrun'⟩ + · -- The frame lacks the value: no message. + obtain ⟨s', hall, hsto, hw, hmem⟩ := heff false .empty + (storeOf ((st.recordAccountRead (toAddressMasked dst)).recordAccountRead msg.currentTarget) + msg.currentTarget) (by simp) + have hw0 : memoryWrite (memoryExtend M (extendMemory M.size [(i, isz), (o, osz)]).expandBy) + o.toNat (ByteArray.empty.extract 0 (min osz.toNat ByteArray.empty.size)) = + memoryExtend M (extendMemory M.size [(i, isz), (o, osz)]).expandBy := by + simp [memoryWrite, ByteArray.size_extract] + rw [hw0] at hmem + refine ⟨false, .empty, s', _, { ss with + accessedAddresses := ss.accessedAddresses.insert (toAddressMasked dst) }, _, + g - ((mcgV g st ss M.size asked dst v i isz o osz).cost + + (extendMemory M.size [(i, isz), (o, osz)]).cost) + + (mcgV g st ss M.size asked dst v i isz o osz).subCall, m, within', + hall, hw, hmem, ⟨fun k => by rw [hsto]; rfl, by simpa using R.account, ?_⟩, + MemBudget.spend hbud0 (gas_after_le (asked := asked) hv hp le_rfl), + le_trans (gas_after_le (asked := asked) hv hp le_rfl) (Nat.sub_le _ _), + by simpa using hat', hrun'⟩ + rw [hw] + exact logsRel_call _ _ _ _ _ R.logs + · -- The callee ran. + obtain ⟨hacc, hlogs, hout⟩ := hq caller mm child hP hcs hmg hmc hmt hmd hmv + obtain ⟨s', hall, hsto, hw, hmem⟩ := heff child.error.isNone child.output + (storeOf (incorporateChild .fusaka caller child).state msg.currentTarget) hout + have hg2 := gas_after_le (asked := asked) hv hp (c := child.gas) (by rw [← hmg]; exact hcg) + refine ⟨child.error.isNone, child.output, s', _, _, _, + g - ((mcgV g st ss M.size asked dst v i isz o osz).cost + + (extendMemory M.size [(i, isz), (o, osz)]).cost) + child.gas, after, within', + hall, hw, hmem, ⟨fun k => by rw [hsto]; rfl, ?_, ?_⟩, ?_, by omega, hat', hrun'⟩ + · rw [incorporateChild_state] + exact hacc + · have hl : (incorporateChild .fusaka caller child).substate.logs.toList = ss.logs.toList := by + unfold incorporateChild + split + · rename_i hn + simp [Array.toList_append, hcsub, hlogs (by simpa using hn)] + · simp [hcsub] + obtain ⟨L, h1, h2⟩ := R.logs + refine ⟨L, by rw [hl, h1], ?_⟩ + rw [hw, callWorld, List.filter_append] + simpa [isLogE] using h2 + · unfold MemBudget + rw [size_memoryWrite_of_fit, size_memoryExtend] + · unfold MemBudget at hbud0 + rw [size_memoryExtend] at hbud0 + omega + · intro h + simp only [ByteArray.size_extract] at h ⊢ + have hz : osz ≠ 0 := by + intro hz + simp [hz] at h + have := hfit hz + rw [size_memoryExtend] + have := Nat.min_le_left osz.toNat child.output.size + omega + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallValueSeg.callValue_cut' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms callValue_cut + +end SolidCore.Refinement.Solar.AssembleCallValueSeg diff --git a/SolidCore/Refinement/Solar/AssembleCallValueZero.lean b/SolidCore/Refinement/Solar/AssembleCallValueZero.lean new file mode 100644 index 00000000..d1b8cc33 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCallValueZero.lean @@ -0,0 +1,178 @@ +import SolidCore.Refinement.Solar.AssembleCall + +/-! +# CALL with no value at the frame's own gas, from a run that succeeds + +`call0_back`: `AssembleCall.staticcall_back` for CALL with value 0 in a frame that may change the +state, as UniswapV2Factory's call to the new pair's `initialize` is: a CALL step in a run that ends +with no error read the callee's code (and its delegate's for an EIP-7702 delegation, +`call0_routes_of_ok`), had the gas for its access, the route and the growth of memory, and the run +goes on from the frame after the callee's frame ended (EthLib's `Logic.callKindRoute` for +`.call`), under any runner of messages meeting `P`. The message is not static and sends no value; +nothing is assumed of the callee, which may reenter the caller, so the state after the call is +the callee frame's. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCallValueZero + +open SolarTV SolarTV.Machine SolidCore.Refinement +open SolidCore.Refinement.Solar.AssembleCall +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts + +/-- The pops of CALL's (with value 0) operands. -/ +theorem pop_call0 {evm : Evm .fusaka Nat} {g a i isz o osz : U256} {rest : List U256} + (hst : evm.stack.val = g :: a :: 0 :: i :: isz :: o :: osz :: rest) : + ∃ stack : Stack, stack.val = rest ∧ + popCallOperands .call evm = + .ok (⟨g, toAddressMasked a, 0, i, isz, o, osz⟩, { evm with stack }) := by + rcases evm with ⟨pc, ⟨l, hl⟩, memory, code, valid, gas, running, message, output, returnData, + state, substate, error⟩ + simp only at hst + subst hst + exact ⟨_, rfl, rfl⟩ + + +/-- **A CALL step with value 0 that does not fail reads the callee's code and follows a route**: the +state holds the code of the callee and, for an EIP-7702 delegation, of its delegate. So a run that +succeeds needs no assumption on the state at its calls. -/ +theorem call0_routes_of_ok {evm : Evm .fusaka Nat} {g a i isz o osz : U256} {rest : List U256} + (hst : evm.stack.val = g :: a :: 0 :: i :: isz :: o :: osz :: rest) + (hnf : ¬ StepFails (callStep .call evm)) : + ∃ cc route, evm.state.getCode (evm.state.getAccount (toAddressMasked a)).codeHash = .ok cc ∧ + Routes .fusaka evm.state cc route := by + obtain ⟨stack, -, hpop⟩ := pop_call0 hst + have key : ∀ (hx : ∀ E : Evm .fusaka Nat, E.state = evm.state.recordAccountRead (toAddressMasked a) → + ∀ known, ∃ err, accessDelegation E (toAddressMasked a) known = .error err), + StepFails (callStep .call evm) := by + intro hx + simp only [callStep, hpop, bind, Except.bind, accessAddress, checkGas, recordAccountRead, + show ¬ (Fork.fusaka ≥ .glamsterdam) by decide, false_and, ite_false, + show Fork.fusaka ≥ Fork.berlin by decide, ite_true, pure, Except.pure] + exact fails_keepReads_bind (hx _ rfl _) + cases hc : evm.state.getCode (evm.state.getAccount (toAddressMasked a)).codeHash with + | error x => + exact absurd (key fun E hE known => accessDelegation_err1 (by + intro cc; rw [hE]; simp [hc])) hnf + | ok cc => + cases hd : delegatedAddress cc with + | none => exact ⟨cc, none, rfl, fun _ => hd⟩ + | some d => + cases hc2 : evm.state.getCode (evm.state.getAccount d).codeHash with + | ok c' => exact ⟨cc, some (d, c'), rfl, by decide, hd, hc2⟩ + | error x => + exact absurd (key fun E hE known => accessDelegation_err2 (cc := cc) (d := d) + (by rw [hE]; simpa using hc) hd (by intro c'; rw [hE]; simp [hc2])) hnf + + +/-- **CALL with value 0 in a run that succeeds**, at the frame's own gas: the state held the callee's +code (and its delegate's, `Routes`), the gas paid for the access, the route and the growth of memory, +and the run goes on from the frame after the callee's frame ended. -/ +theorem call0_back {code : ByteArray} {msg : Message .fusaka} {pc g : Nat} {M : ByteArray} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray} + {asked addr inOff inSize outOff outSize : U256} {rest : List U256} + {evm : Evm .fusaka Nat} + (hat : At code msg pc (asked :: addr :: 0 :: inOff :: inSize :: outOff :: outSize :: rest) M g st ss + rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0xf1) (hstatic : msg.isStatic = false) + (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} (meets : Meets P runChild) + (within : GasMeter.gasHeld evm.gas ≤ bound) {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + ∃ (calleeCode : ByteArray) (route : Route), + st.getCode (st.getAccount (toAddressMasked addr)).codeHash = .ok calleeCode ∧ + Routes .fusaka st calleeCode route ∧ + (if decide (toAddressMasked addr ∉ ss.accessedAddresses) then 2600 else 100) + + routeCost .fusaka (ss.accessedAddresses.insert (toAddressMasked addr)) route + + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost ≤ g ∧ + ∃ (caller : Evm .fusaka Nat) (m : Message .fusaka) (child after : Evm .fusaka Nat) + (within' : GasMeter.gasHeld after.gas ≤ bound) (g' : Nat), + P caller m child ∧ child.gas ≤ m.gas ∧ + caller.state = (routeState (st.recordAccountRead (toAddressMasked addr)) route).recordAccountRead + msg.currentTarget ∧ + caller.substate = routeSub { ss with + accessedAddresses := ss.accessedAddresses.insert (toAddressMasked addr) } route ∧ + m.isStatic = false ∧ m.value = 0 ∧ m.code = routeCode calleeCode route ∧ + m.currentTarget = toAddressMasked addr ∧ m.target = some (toAddressMasked addr) ∧ + m.data = memoryReadBytes (memoryExtend M + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).expandBy) inOff.toNat + inSize.toNat ∧ + m.codeAddress = some (routeAddr (toAddressMasked addr) route) ∧ + m.disablePrecompiles = route.isSome ∧ + m.gas = (messageCallGas .fusaka 0 asked.toNat g + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost + ((if decide (toAddressMasked addr ∉ ss.accessedAddresses) then 2600 else 100) + + routeCost .fusaka (ss.accessedAddresses.insert (toAddressMasked addr)) route)).subCall ∧ + g' + (if decide (toAddressMasked addr ∉ ss.accessedAddresses) then 2600 else 100) + + routeCost .fusaka (ss.accessedAddresses.insert (toAddressMasked addr)) route + + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost ≤ g ∧ + At code msg (pc + 1) ((if child.error.isNone then 1 else 0) :: rest) + (memoryWrite (memoryExtend M + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).expandBy) + outOff.toNat (child.output.extract 0 (min outSize.toNat child.output.size))) + g' (incorporateChild .fusaka caller child).state + (incorporateChild .fusaka caller child).substate child.output after ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild after within' = .ok fin := by + have hat0 := hat + obtain ⟨hc, hv, hm, hpc, hst, hmem, hgas, hrunning, -, -, hst', hss, -⟩ := hat0 + have hlt' : evm.pc < evm.code.size := by rw [hc, hpc]; exact hlt + have decoded : Op.ofByte .fusaka (evm.code[evm.pc]'hlt') = some .call := by + have he : evm.code[evm.pc]'hlt' = code[pc]'hlt := by subst hc hpc; rfl + rw [he, hbyte] + exact ofByte_of_decode rfl (by decide) + have hstep : step .fusaka evm = callStep .call evm := + step_of_messageInstruction hlt' decoded instruction_call + messageInstruction_call + have hnf : ¬ StepFails (callStep .call evm) := fun hf => + error_ne_none_of_stepFails hrunning (by rw [hstep]; exact hf) hrun hok + obtain ⟨calleeCode, route, hcode, hroute⟩ := call0_routes_of_ok hst hnf + rw [hst'] at hcode hroute + refine ⟨calleeCode, route, hcode, hroute, ?_⟩ + have hcost := callBaseCost_of_berlin (fork := .fusaka) (by decide) (by decide) + (decide (toAddressMasked addr ∉ ss.accessedAddresses)) + generalize hcold : decide (toAddressMasked addr ∉ ss.accessedAddresses) = cold at hcost + generalize hdc : routeCost .fusaka (ss.accessedAddresses.insert (toAddressMasked addr)) route = dc + by_cases hg : (if cold then 2600 else 100) + dc + + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost ≤ g + · refine ⟨hg, ?_⟩ + have H := (callKindRoute (fork := .fusaka) (kind := .call) (callee := P) + (asked := asked) (rest := rest) (returnData := rd) (gas := g) (memory := M) (substate := ss) + (inputStart := inOff) (inputSize := inSize) (outputStart := outOff) (outputSize := outSize) + (by decide) hlt hbyte (ofByte_of_decode rfl (by decide)) instruction_call + messageInstruction_call hcode hroute hdepth + (by rw [← hcold] at hcost; rw [hcost, hcold, hdc]; exact hg)).toUnder + obtain ⟨after, hr, hq⟩ := H bound runChild meets evm hat within + have within' := Nat.le_trans (hr.gasHeld_le StepBy.gasHeld_le) within + have hrun' := hrun + rw [runFrame_eq_of_reaches StepBy.gasHeld_le StepBy.runFrame_eq hr within] at hrun' + rcases hq with ⟨caller, m, child, ⟨s1, s2, m1, -, -, mt, mtg, mca, mc, mdp, md, mv, -, -, ms, -, -⟩, + hk, hcg, hat'⟩ | aborted + · rw [← hcold] at hcost + rw [hcost, hdc, hcold] at m1 hat' + obtain ⟨hc1, hc2⟩ := staticcall_gas (asked := asked.toNat) + (memc := (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost) + (extra := (if cold then 2600 else 100) + dc) (g := g) (by omega) + refine ⟨caller, m, child, after, within', _, hk, hcg, s1, s2, by rw [ms, hstatic]; decide, + by simpa using mv, mc, by simpa using mt, by simpa using mtg, md, mca, mdp, m1, ?_, hat', hrun'⟩ + rw [m1] at hcg + rw [hc1] + omega + · obtain ⟨e, he, -⟩ := runFrame_of_abortsBy meets.aborts aborted within' + rw [he] at hrun' + cases hrun' + · exfalso + have fails : StepFails (step .fusaka evm) := by + rw [hstep] + refine callStep_fails_of_routes (route := route) (by decide) (a := addr) (i := inOff) + (isz := inSize) (o := outOff) (osz := outSize) (g := asked) (rest := rest) + (by rw [hst]; rfl) (by rw [hst']; exact hcode) (by rw [hst']; exact hroute) ?_ + rw [callBaseCost_of_berlin (by decide) (by decide), hgas, hmem, hss, hcold, hdc] + omega + exact error_ne_none_of_stepFails hrunning fails hrun hok + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallValueZero.call0_back' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms call0_back + +end SolidCore.Refinement.Solar.AssembleCallValueZero diff --git a/SolidCore/Refinement/Solar/AssembleCallValueZeroSeg.lean b/SolidCore/Refinement/Solar/AssembleCallValueZeroSeg.lean new file mode 100644 index 00000000..f7940fa8 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCallValueZeroSeg.lean @@ -0,0 +1,164 @@ +import SolidCore.Refinement.Solar.AssembleCallValueSeg +import SolidCore.Refinement.Solar.AssembleCallValueZero + +/-! +# CALL with no value as a cut of a run, at the frame's own gas + +`call0_cut` is `AssembleCallValueSeg.callValue_cut` for a CALL that sends no value, as UniswapV2Factory's +call to the new pair's `initialize` is: from a run that succeeds, the CALL read the callee's code (and its +delegate's, `AssembleCallValueZero.call0_back`, so nothing is assumed of the callee's code or route), had +the gas for its access, the route and the growth of memory, and the run goes on from the frame after +the callee's frame ended. The run's table grows by the flag, the return data and the storage of the +frame's account after the call (a reentrant callee may have changed it), and under the oracle of every +extension of it SolarTV's CALL does the same (`call_answers`, for any call with its value word). + +Named: `AssembleCallValueSeg.CallOk` of the frame that ends the call's message, asked only of messages to +this callee with this input, no value and not static. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCallValueZeroSeg + +open SolarTV SolarTV.Machine +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.RunOracle +open SolidCore.Refinement.Solar.AssembleEffects SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCallValueEffect SolidCore.Refinement.Solar.AssembleCallValueSeg +open SolidCore.Refinement.Solar.AssembleCreateSeg SolidCore.Refinement.Solar.AssembleCall +open SolidCore.Refinement.Solar.AssembleCallValueZero +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts + +/-- **SolarTV's CALL under every extension of a table with the call's answers**: it pushes the flag, +writes the output to the output range, takes it as the return data and leaves the table's storage. -/ +theorem call_answers {base : Oracle} {T : RunTable} {call : Call} {s : State} {M : ByteArray} + {gas addr value inOff inSize outOff outSize : Word} (hm : MemRel s.memory M) + (hb1 : inSize = 0 ∨ (inOff.toNat + inSize.toNat + 31) / 32 < 2 ^ 251) + (hb2 : outSize = 0 ∨ (outOff.toNat + outSize.toNat + 31) / 32 < 2 ^ 251) + (hsent : sent (callWorld s gas addr value inOff inSize outOff outSize) = T.oks.length + 1) + (houts : T.outs.length = T.oks.length) (hst : T.stores.length = T.oks.length) + (htr : T.transients.length = T.oks.length) + (ok : Bool) (out : ByteArray) (sto : Word → Word) (hsz : out.size < 2 ^ 256) : + ∃ s', (∀ T'', (pushCall T ok out sto).Le T'' → + Effect.apply (tableOracle base T'') call (.call .call) + [gas, addr, value, inOff, inSize, outOff, outSize] s = + some (some (if ok then 1 else 0), s') ∧ RdRel (tableOracle base T'') s'.world out) ∧ + s'.storage = sto ∧ s'.world = callWorld s gas addr value inOff inSize outOff outSize ∧ + MemRel s'.memory (memoryWrite (memoryExtend M + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).expandBy) + outOff.toNat (out.extract 0 (min outSize.toNat out.size))) := by + have hsame : ∀ T'', (pushCall T ok out sto).Le T'' → + Effect.apply (tableOracle base T'') call (.call .call) + [gas, addr, value, inOff, inSize, outOff, outSize] s = + Effect.apply (tableOracle base (pushCall T ok out sto)) call (.call .call) + [gas, addr, value, inOff, inSize, outOff, outSize] s := by + intro T'' hle + obtain ⟨r1, o1, s1, t1⟩ := table_call (base := base) hsent houts hst htr hle + obtain ⟨r2, o2, s2, t2⟩ := table_call (base := base) hsent houts hst htr + (RunTable.Le.refl (pushCall T ok out sto)) + have hrds : returndataSize (tableOracle base T'') (callWorld s gas addr value inOff inSize outOff outSize) = + returndataSize (tableOracle base (pushCall T ok out sto)) + (callWorld s gas addr value inOff inSize outOff outSize) := by + rw [returndataSize_table, returndataSize_table, o1, o2] + have hrdb : returndataByte (tableOracle base T'') (callWorld s gas addr value inOff inSize outOff outSize) = + returndataByte (tableOracle base (pushCall T ok out sto)) + (callWorld s gas addr value inOff inSize outOff outSize) := by + funext j + simp only [returndataByte, tableOracle, o1, o2] + simp + have hflag : callFlag (tableOracle base T'') (callWorld s gas addr value inOff inSize outOff outSize) = + callFlag (tableOracle base (pushCall T ok out sto)) + (callWorld s gas addr value inOff inSize outOff outSize) := by + simp only [callFlag, r1, r2] + simp only [callWorld] at hrds hrdb hflag s1 s2 t1 t2 + simp only [Effect.apply, CallKind.shape, called, hflag, hrds, hrdb, s1, s2, t1, t2] + obtain ⟨r2, o2, s2, -⟩ := table_call (base := base) (ok := ok) (out := out) (sto := sto) hsent + houts hst htr (RunTable.Le.refl _) + have hrd2 : RdRel (tableOracle base (pushCall T ok out sto)) + (callWorld s gas addr value inOff inSize outOff outSize) out := by + have := rdRel_table base (pushCall T ok out sto) + (callWorld s gas addr value inOff inSize outOff outSize) (by rw [o2]; exact hsz) + rwa [o2] at this + obtain ⟨s', happ, hsto, hw, hmem⟩ := call_effectO (o := tableOracle base (pushCall T ok out sto)) + (call := call) (ok := ok) hm hb1 hb2 (by simp only [callFlag, r2]; cases ok <;> simp) hrd2 + refine ⟨s', fun T'' hle => ⟨by rw [hsame T'' hle, happ], ?_⟩, by rw [hsto, s2], hw, hmem⟩ + obtain ⟨-, o1, -, -⟩ := table_call (base := base) hsent houts hst htr hle + have := rdRel_table base T'' (callWorld s gas addr value inOff inSize outOff outSize) + (by rw [o1]; exact hsz) + rw [o1] at this + rw [hw] + exact this + +/-- **CALL with no value as a cut of a run that succeeds.** -/ +theorem call0_cut {code : ByteArray} {msg : Message .fusaka} {call : Call} {pc g G : Nat} + {M : ByteArray} {st : State.TransactionState} {ss ss0 : Substate} {rd : ByteArray} + {asked addr inOff inSize outOff outSize : U256} {Tr : List U256} {s : State} + {evm : Evm .fusaka Nat} (base : Oracle) (T : RunTable) + (hm : MemRel s.memory M) (R : Rel msg ss0 st ss s) (hb : MemBudget G M g) (hG : G < 2 ^ 300) + (hat : At code msg pc (asked :: addr :: 0 :: inOff :: inSize :: outOff :: outSize :: Tr) M g st + ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0xf1) (hstatic : msg.isStatic = false) + (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} (meets : Meets P runChild) + (hq : ∀ caller m child, P caller m child → m.currentTarget = toAddressMasked addr → + m.value = 0 → m.isStatic = false → + m.data = memoryReadBytes (memoryExtend M + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).expandBy) inOff.toNat inSize.toNat → + CallOk msg child) + (within : GasMeter.gasHeld evm.gas ≤ bound) {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) + (hoks : T.oks.length = sent s.world) (houts : T.outs.length = sent s.world) + (hsts : T.stores.length = sent s.world) (htrs : T.transients.length = sent s.world) : + ∃ (ok : Bool) (out : ByteArray) (s' : State) (st' : State.TransactionState) (ss' : Substate) + (M' : ByteArray) (g' : Nat) (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + (∀ T'', (pushCall T ok out (storeOf st' msg.currentTarget)).Le T'' → + Effect.apply (tableOracle base T'') call (.call .call) + [asked, addr, 0, inOff, inSize, outOff, outSize] s = + some (some (if ok then 1 else 0), s') ∧ RdRel (tableOracle base T'') s'.world out) ∧ + s'.world = callWorld s asked addr 0 inOff inSize outOff outSize ∧ + MemRel s'.memory M' ∧ Rel msg ss0 st' ss' s' ∧ MemBudget G M' g' ∧ g' ≤ g ∧ + At code msg (pc + 1) ((if ok then 1 else 0) :: Tr) M' g' st' ss' out m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + obtain ⟨calleeCode, route, -, -, hgp, caller, mm, child, after, within', g', hP, -, -, hcsub, hms, + hmv, -, hmt, -, hmd, -, -, -, hg', hat', hrun'⟩ := + call0_back hat hlt hbyte hstatic hdepth meets within hrun hok + obtain ⟨hb1, hb2, hbud, hfit⟩ := AssembleCallCut.budget_grow2 hmod hb hG hgp + obtain ⟨hacc, hlogs, hout⟩ := hq caller mm child hP hmt hmv hms hmd + have hsent : sent (callWorld s asked addr 0 inOff inSize outOff outSize) = T.oks.length + 1 := by + simp [callWorld, hoks] + obtain ⟨s', hall, hsto, hw, hmem⟩ := call_answers (base := base) (call := call) hm hb1 hb2 hsent + (by omega) (by omega) (by omega) child.error.isNone child.output + (storeOf (incorporateChild .fusaka caller child).state msg.currentTarget) hout + refine ⟨child.error.isNone, child.output, s', _, _, _, g', after, within', hall, hw, hmem, + ⟨fun k => by rw [hsto]; rfl, ?_, ?_⟩, ?_, by omega, hat', hrun'⟩ + · rw [incorporateChild_state] + exact hacc + · have hl : (incorporateChild .fusaka caller child).substate.logs.toList = ss.logs.toList := by + unfold incorporateChild + split + · rename_i hn + have h0 := hlogs (by simpa using hn) + rcases route with _ | ⟨d, c'⟩ <;> simp [Array.toList_append, h0, hcsub, routeSub] + · rcases route with _ | ⟨d, c'⟩ <;> simp [hcsub, routeSub] + obtain ⟨L, h1, h2⟩ := R.logs + refine ⟨L, by rw [hl, h1], ?_⟩ + rw [hw, callWorld, List.filter_append] + simpa [isLogE] using h2 + · unfold MemBudget + rw [size_memoryWrite_of_fit, size_memoryExtend] + · omega + · intro h + simp only [ByteArray.size_extract] at h ⊢ + have hz : outSize ≠ 0 := by + intro hz + simp [hz] at h + have := hfit hz + rw [size_memoryExtend] + have := Nat.min_le_left outSize.toNat child.output.size + omega + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallValueZeroSeg.call0_cut' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms call0_cut + +end SolidCore.Refinement.Solar.AssembleCallValueZeroSeg diff --git a/SolidCore/Refinement/Solar/AssembleCallWorld.lean b/SolidCore/Refinement/Solar/AssembleCallWorld.lean new file mode 100644 index 00000000..7c625d5e --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCallWorld.lean @@ -0,0 +1,392 @@ +import SolidCore.Refinement.Solar.AssembleCut +import SolidCore.Refinement.SourceOracleSat + +/-! +# An open world whose static calls succeed, from a run's table + +`AssembleCut.O_agree` meets the oracle hypothesis (`CallsAgree`) with `Witness.failWorld`, in which +every call to code fails. Here the open world `tabWorld oks outs codes` answers the `n`-th call of a +source history, when it is a `STATICCALL` to code (not to a precompile address), with the table's +`n`-th success flag and return data, leaving the world it was sent (a static frame keeps every +account, as `AssembleCall.meets_static` proves of EthLib's runner); a precompile call is answered by +SolidCore's precompile semantics, as every open world answers it; every other call fails, leaving the +sent world. The other accounts' code is `codes`, read before and after calls. + +`tabOracle` computes the same answers from what the MIR frame sees of its calls (kind, callee, value, +input, and their number), and `tabAgree` proves the two agree. `OS codes T` is the oracle of a run's +table `T` (its GAS reads and the flags and return data of its static calls) over EthLib's caller, +hash and environment: `OS_agree` gives the open world for it and `OS_ok` the certificate's +constraints, the two premises `SourceOracle.holds_of_runs` asks of the oracle of a run once the +checker cuts at STATICCALL. +-/ + +namespace SolidCore.Refinement + +open SolidCore.Solidity SolidCore.Solidity.Source EvmCompiler.Simulation + +namespace Witness + +/-- A `STATICCALL`, on the MIR side. -/ +def isStaticM : SolarTV.Machine.CallKind → Bool + | .staticcall => true + | _ => false + +/-- A `STATICCALL`, on the source side. -/ +def isStaticS : CallKind → Bool + | .staticcall => true + | _ => false + +theorem isStaticM_machineKind (k : CallKind) : isStaticM (machineKind k) = isStaticS k := by + cases k <;> rfl + +/-- A `STATICCALL` with no value to a precompile address, which SolidCore answers itself. -/ +def prePath (k : SolarTV.Machine.CallKind) (callee value : Nat) : Bool := + isStaticM k && value == 0 && (SolidCore.Solidity.Shared.Precompile.kindOfAddress? callee).isSome + +/-- A static call to code: answered by the table. -/ +def toCode (k : SolarTV.Machine.CallKind) (callee value : Nat) : Bool := + isStaticM k && !prePath k callee value + +/-- The success flag and return data of the `n`-th call in the table's world, from what both sides +see of it. -/ +def tabResp (oks : List Bool) (outs : List ByteArray) (n : Nat) (k : SolarTV.Machine.CallKind) + (callee value : Nat) (input : List Nat) : Bool × ByteArray := + if toCode k callee value then (oks.getD n false, outs.getD n ByteArray.empty) + else failResp k callee value input + +/-- The table's answer to its `n`-th call, a static call to code: the table's flag and return data, +and the world it was sent. -/ +def tabHit (oks : List Bool) (outs : List ByteArray) (n : Nat) + (world : SolidCore.Solidity.Shared.OpenWorld) : CallResponse := + { success := oks.getD n false, returnData := outs.getD n ByteArray.empty, postWorld := world, + returnedGas := EvmYul.UInt256.ofNat 0 } + +/-- The table's world's answer to its `n`-th call. -/ +def tabCall (oks : List Bool) (outs : List ByteArray) (n : Nat) + (world : SolidCore.Solidity.Shared.OpenWorld) (request : CallRequest) : CallResponse := + if toCode (machineKind request.kind) (addressToWord request.codeAddress) + (u256ToWord request.transferValue) then tabHit oks outs n world + else failCall world request + +/-- The table's world's answerer: the `n`-th external call of a history is answered by `tabCall` +with `n` the number of calls before it. -/ +def tabAns (oks : List Bool) (outs : List ByteArray) : Ans := fun h q => + match q with + | .resource r => some (Query.defaultAnswer (.resource r)) + | .external world (.call request) => some (tabCall oks outs (sourceCalls h).length world request) + | .external world (.create request) => some (Query.defaultAnswer (.external world (.create request))) + +/-- The table's world, with `codes` the other accounts' code. -/ +def tabWorld (oks : List Bool) (outs : List ByteArray) (codes : Shared.Account.BytesMap) : World := + { ans := tabAns oks outs, codes := some codes } + +/-- A precompile answer comes only from a static call with no value to a precompile address. -/ +theorem prePath_of_answer {world : SolidCore.Solidity.Shared.OpenWorld} {request : CallRequest} + {a : CallResponse} (h : precompileAnswerCall? world request = some a) : + prePath (machineKind request.kind) (addressToWord request.codeAddress) + (u256ToWord request.transferValue) = true := by + unfold precompileAnswerCall? at h + cases hk : request.kind <;> simp only [hk] at h <;> try cases h + by_cases hv : u256ToWord request.transferValue = 0 + · cases ho : SolidCore.Solidity.Shared.Precompile.kindOfAddress? (addressToWord request.codeAddress) with + | none => simp [hv, ho] at h + | some kind => simp [prePath, machineKind, isStaticM, hv, ho] + · simp [hv] at h + +theorem tabCall_postWorld (oks : List Bool) (outs : List ByteArray) (n : Nat) + (world : SolidCore.Solidity.Shared.OpenWorld) (request : CallRequest) : + (tabCall oks outs n world request).postWorld = world := by + unfold tabCall + split + · rfl + · exact failCall_postWorld world request + +theorem tabCall_resp (oks : List Bool) (outs : List ByteArray) (n : Nat) + (world : SolidCore.Solidity.Shared.OpenWorld) (request : CallRequest) : + ((tabCall oks outs n world request).success, (tabCall oks outs n world request).returnData) = + tabResp oks outs n (machineKind request.kind) (addressToWord request.codeAddress) + (u256ToWord request.transferValue) (byteArrayToBytes request.calldata) := by + unfold tabCall tabResp + split + · rfl + · exact failCall_resp world request + +/-- **The table's world is a world of the open world.** -/ +theorem tabWorld_open (oks : List Bool) (outs : List ByteArray) (codes : Shared.Account.BytesMap) : + (tabWorld oks outs codes).Open where + calls := by intros; rfl + creates := by intros; rfl + precompiles := by + intro h world request a ha + show some (tabCall oks outs (sourceCalls h).length world request) = some a + have hp := prePath_of_answer ha + simp [tabCall, toCode, hp, failCall, ha] + resources := by intros; rfl + codes := rfl + +/-- The reads of the table's oracle: the return data of the frame's last call, the table's +world's, and `codes`' code test at every address. -/ +def tabEnv (oks : List Bool) (outs : List ByteArray) (codes : Shared.Account.BytesMap) + (name : String) (w : List SolarTV.Machine.Event) (args : List (BitVec 256)) : BitVec 256 := + if name = "extcodesize" then + match args with + | [a] => if (Shared.Account.codeAt codes a.toNat).isEmpty then 0 else 1 + | _ => 0 + else + match name, args, (machineCalls w).getLast? with + | "returndatasize", [], some (k, c, v, i) => + BitVec.ofNat 256 (tabResp oks outs ((machineCalls w).length - 1) k c v i).2.size + | "returndata", [j], some (k, c, v, i) => + BitVec.ofNat 256 ((tabResp oks outs ((machineCalls w).length - 1) k c v i).2.get! j.toNat).toNat + | _, _, _ => 0 + +/-- The success flag of the frame's last call, the table's world's. -/ +def tabResult (oks : List Bool) (outs : List ByteArray) (w : List SolarTV.Machine.Event) : BitVec 256 := + match (machineCalls w).getLast? with + | some (k, c, v, i) => if (tabResp oks outs ((machineCalls w).length - 1) k c v i).1 then 1 else 0 + | none => 0 + +/-- The table's oracle: the table's world's answers from the frame's last call and the number of +its calls, the storage it had at the call, and `codes`' code test at every address. -/ +def tabOracle (oks : List Bool) (outs : List ByteArray) (codes : Shared.Account.BytesMap) : + SolarTV.Machine.Oracle where + env := tabEnv oks outs codes + result := tabResult oks outs + storageAfter := failOracle.storageAfter + transientAfter := failOracle.transientAfter + keccak := fun _ => 0 + caller := 0 + +theorem tabOracle_envEq (oks : List Bool) (outs : List ByteArray) (codes : Shared.Account.BytesMap) : + (tabOracle oks outs codes).env = tabEnv oks outs codes := rfl + +theorem tabOracle_codes (oks : List Bool) (outs : List ByteArray) (codes : Shared.Account.BytesMap) + (w : List SolarTV.Machine.Event) (a : Nat) : + (tabOracle oks outs codes).env "extcodesize" w [BitVec.ofNat 256 a] = + if (Shared.Account.codeAt codes (a % 2 ^ 256)).isEmpty then 0 else 1 := by + rw [tabOracle_envEq] + simp [tabEnv] + +/-- The table oracle's code test does not depend on the world. -/ +theorem tabOracle_codesAgree {oks : List Bool} {outs : List ByteArray} + {codes : Shared.Account.BytesMap} {w w' : List SolarTV.Machine.Event} + {code : Nat → List SolidCore.Solidity.Byte} (h : CodesAgree (tabOracle oks outs codes) w code) : + CodesAgree (tabOracle oks outs codes) w' code := by + intro a ha + rw [tabOracle_codes] + have := h a ha + rwa [tabOracle_codes] at this + +/-- **The table's world and the table's oracle agree.** -/ +theorem tabAgree (oks : List Bool) (outs : List ByteArray) (codes : Shared.Account.BytesMap) : + CallsAgree (tabOracle oks outs codes) (tabWorld oks outs codes) where + codes := by + intro w _ a ha + rw [tabOracle_codes, Nat.mod_eq_of_lt (by omega)] + simp only [tabWorld, Option.getD_some] + split <;> simp_all + calls := by + intro h world request a ha w k s i st tr hlast hm hst hcodes + have ha' : a = tabCall oks outs (sourceCalls h).length world request := by + simp only [tabWorld, tabAns] at ha + exact (Option.some.inj ha).symm + subst ha' + have hresp := tabCall_resp oks outs (sourceCalls h).length world request + have hpost := tabCall_postWorld oks outs (sourceCalls h).length world request + have hm' : machineCalls w = sourceCalls h ++ [(machineKind request.kind, + addressToWord request.codeAddress, u256ToWord request.transferValue, + byteArrayToBytes request.calldata)] := by + rw [hm, sourceCalls_append] + simp [sourceCalls] + have hl : (machineCalls w).getLast? = some (machineKind request.kind, + addressToWord request.codeAddress, u256ToWord request.transferValue, + byteArrayToBytes request.calldata) := by + rw [hm'] + simp + have hn : (machineCalls w).length - 1 = (sourceCalls h).length := by + rw [hm'] + simp + refine ⟨?_, ?_, ?_⟩ + · simp only [SolarTV.Machine.callFlag] + show (if tabResult oks outs w = 0 then _ else _) = _ ↔ _ + simp only [tabResult, hl, hn] + rw [Prod.ext_iff] at hresp + rw [← hresp.1] + cases (tabCall oks outs (sourceCalls h).length world request).success <;> simp + · intro _ slot hslot + have := hst slot hslot + show ((failOracle.storageAfter w) _).toNat = _ ∧ ((failOracle.transientAfter w) _).toNat = _ + simp only [failOracle, hlast, hpost] + exact this + · intro rest hrest + have hmr : machineCalls (w ++ rest) = machineCalls w := by + rw [machineCalls_append, hrest, List.append_nil] + rw [Prod.ext_iff] at hresp + refine ⟨?_, ?_, ?_⟩ + · simp only [SolarTV.Machine.returndataSize] + rw [tabOracle_envEq] + simp only [tabEnv, show ("returndatasize" = "extcodesize") = False by simp, ite_false, hmr, hl, hn, BitVec.toNat_ofNat] + rw [← hresp.2] + · intro j _ hj + simp only [SolarTV.Machine.returndataByte] + rw [tabOracle_envEq] + simp only [tabEnv, show ("returndata" = "extcodesize") = False by simp, ite_false, hmr, hl, hn, ← hresp.2, + BitVec.toNat_ofNat, Nat.mod_eq_of_lt hj, BitVec.toNat_setWidth] + have := ((tabCall oks outs (sourceCalls h).length world request).returnData.get! j).toNat_lt + omega + · have hc := tabOracle_codesAgree (w' := w ++ rest) hcodes + have hca : codeAfter (tabWorld oks outs codes) + (h ++ [⟨.external world (.call request), tabCall oks outs (sourceCalls h).length world request⟩]) + = codeIn world := by + funext x + simp [codeAfter, hpost] + rw [hca] + exact hc + static := by + intro h world request a ha _ slot + have ha' : a = tabCall oks outs (sourceCalls h).length world request := by + simp only [tabWorld, tabAns] at ha + exact (Option.some.inj ha).symm + subst ha' + rw [tabCall_postWorld] + exact ⟨rfl, rfl⟩ + +/-- In the table's world a static call to code succeeds exactly as the table says, with the table's +return data. -/ +theorem tabWorld_static (oks : List Bool) (outs : List ByteArray) (codes : Shared.Account.BytesMap) + (h : List Interaction.Exchange) (world : SolidCore.Solidity.Shared.OpenWorld) + (request : CallRequest) + (hc : toCode (machineKind request.kind) (addressToWord request.codeAddress) + (u256ToWord request.transferValue) = true) : + (tabWorld oks outs codes).ans h (.external world (.call request)) = + some (tabHit oks outs (sourceCalls h).length world) := by + simp only [tabWorld, tabAns, tabCall, hc, ite_true] + rfl + +end Witness + +end SolidCore.Refinement + +namespace SolidCore.Refinement.Solar.AssembleCallWorld + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Witness +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.RunOracle +open SolidCore.Refinement.Solar.AssembleCut SolidCore.Refinement.Solar.AssembleEffects +open SolidCore.Solidity SolidCore.Solidity.Source EvmCompiler.Simulation + +/-- **The oracle of a run that makes static calls**: GAS reads from the table's `gases`, EthLib's +caller, hash and environment, and the success flags and return data of its static calls to code from +the table's `oks` and `outs`, in order; `codes` is the other accounts' code. -/ +abbrev OS (codes : SolidCore.Solidity.Shared.Account.BytesMap) (T : RunTable) : Oracle := + gasOracle (envOracle (ethOracle (tabOracle T.oks T.outs codes))) T + +theorem OS_ok (codes : SolidCore.Solidity.Shared.Account.BytesMap) (c : Cert) (T : RunTable) : + CertOk c (OS codes T) := by + refine ⟨fun _ => ethOracle_ok (tabOracle T.oks T.outs codes), fun _ => ?_⟩ + intro name byte w he world + have hn : name ≠ "gas" := by + unfold envRead at he + rintro rfl + simp at he + simp only [OS, gasOracle, hn, false_and, ite_false] + exact envOracle_ok _ name byte w he world + +/-- **The open world of a run that makes static calls**: the oracle of every table agrees with the +table's world, in which the table's static calls to code succeed or fail as the table says, with its +return data. This replaces `AssembleCut.O_agree`'s world, in which every call to code fails. -/ +theorem OS_agree (codes : SolidCore.Solidity.Shared.Account.BytesMap) (T : RunTable) : + (tabWorld T.oks T.outs codes).Open ∧ CallsAgree (OS codes T) (tabWorld T.oks T.outs codes) := + ⟨tabWorld_open _ _ _, callsAgree_gas T (callsAgree_envEth (tabAgree _ _ _))⟩ + +/-! ## A static call to code under the oracle of a run -/ + +theorem OS_env (codes : SolidCore.Solidity.Shared.Account.BytesMap) (T : RunTable) (n : String) + (w : List SolarTV.Machine.Event) (a : List (BitVec 256)) (hn : n ≠ "gas") (h : envRead n = none) : + (OS codes T).env n w a = tabEnv T.oks T.outs codes n w a := by + simp only [OS, gasOracle, hn, false_and, ite_false] + rw [env_envEth _ n w a h] + rfl + +theorem data_getElem! (b : ByteArray) (i : Nat) (h : i < b.size) : b.data[i]! = b[i] := by + rw [getElem!_pos b.data i (by simpa using h)] + rfl + +theorem machineCalls_static (w : List SolarTV.Machine.Event) (gas addr : (BitVec 256)) (input : List SolarTV.Memory.Byte) + (st tr : (BitVec 256) → (BitVec 256)) : + machineCalls (w ++ [.call .staticcall [gas, addr] input st tr]) = + machineCalls w ++ [(.staticcall, addr.toNat % 2 ^ 160, 0, input.map BitVec.toNat)] := by + rw [machineCalls_append] + simp [machineCalls] + +/-- **A static call to code under the oracle of a run answers the table's next entry**: the +`n`-th call of the frame (`n` the calls before it) succeeds as the table's `n`-th flag says, and +until the next call the return data is the table's `n`-th output. With +`AssembleCall.staticcall_back`, which reads the callee frame's flag and output from the run, these +are `AssembleCall.staticcall_effectW`'s premises. -/ +theorem OS_static (codes : SolidCore.Solidity.Shared.Account.BytesMap) (T : RunTable) + (w : List SolarTV.Machine.Event) (gas addr : (BitVec 256)) (input : List SolarTV.Memory.Byte) (st tr : (BitVec 256) → (BitVec 256)) + (hc : toCode .staticcall (addr.toNat % 2 ^ 160) 0 = true) + (hsz : (T.outs.getD (machineCalls w).length ByteArray.empty).size < 2 ^ 256) : + callFlag (OS codes T) (w ++ [.call .staticcall [gas, addr] input st tr]) = + (if T.oks.getD (machineCalls w).length false then 1 else 0) ∧ + ∀ rest, machineCalls rest = [] → + RdRel (OS codes T) (w ++ [.call .staticcall [gas, addr] input st tr] ++ rest) + (T.outs.getD (machineCalls w).length ByteArray.empty) := by + have hm := machineCalls_static w gas addr input st tr + refine ⟨?_, fun rest hrest => ?_⟩ + · show (if tabResult T.oks T.outs _ = 0 then _ else _) = _ + simp only [tabResult, hm, List.getLast?_append, List.getLast?_singleton, Option.some_or, + List.length_append, List.length_singleton, Nat.add_sub_cancel, tabResp, hc, ite_true] + cases T.oks.getD (machineCalls w).length false <;> simp + · have hmr : machineCalls (w ++ [.call .staticcall [gas, addr] input st tr] ++ rest) = + machineCalls w ++ [(.staticcall, addr.toNat % 2 ^ 160, 0, input.map BitVec.toNat)] := by + rw [machineCalls_append, hm, hrest, List.append_nil] + refine ⟨?_, fun i hi => ?_⟩ + · show ((OS codes T).env "returndatasize" _ []).toNat = _ + rw [OS_env codes T _ _ _ (by decide) rfl] + simp only [tabEnv, show ("returndatasize" = "extcodesize") = False by simp, ite_false, hmr, + List.getLast?_append, List.getLast?_singleton, Option.some_or, List.length_append, + List.length_singleton, Nat.add_sub_cancel, tabResp, hc, ite_true, BitVec.toNat_ofNat] + exact Nat.mod_eq_of_lt hsz + · show ((OS codes T).env "returndata" _ [BitVec.ofNat 256 i]).setWidth 8 = _ + rw [OS_env codes T _ _ _ (by decide) rfl] + simp only [tabEnv, show ("returndata" = "extcodesize") = False by simp, ite_false, hmr, + List.getLast?_append, List.getLast?_singleton, Option.some_or, List.length_append, + List.length_singleton, Nat.add_sub_cancel, tabResp, hc, ite_true] + apply BitVec.eq_of_toNat_eq + have hi' : i < 2 ^ 256 := by omega + simp only [BitVec.toNat_setWidth, BitVec.toNat_ofNat, UInt8.toNat_toBitVec, + Nat.mod_eq_of_lt hi', EthLib.Base.byteAt, hi, dite_true] + have := ((T.outs.getD (machineCalls w).length ByteArray.empty).get! i).toNat_lt + rw [Nat.mod_eq_of_lt (by omega), Nat.mod_eq_of_lt (by omega)] + simp only [ByteArray.get!] + clear this + revert hi + simp only [List.getD_eq_getElem?_getD] + intro hi + exact congrArg UInt8.toNat (data_getElem! _ i hi) + +/-- The world of a table whose one static call succeeded with data `d` answers that call with +success and `d`: the open world of `OS_agree` admits successful calls. -/ +example (d : ByteArray) (world : SolidCore.Solidity.Shared.OpenWorld) + (request : EvmCompiler.Simulation.CallRequest) + (hc : toCode (machineKind request.kind) (addressToWord request.codeAddress) + (u256ToWord request.transferValue) = true) : + ((tabWorld [true] [d] []).ans [] (.external world (.call request))).map + (fun a => (a.success, a.returnData)) = some (true, d) := by + rw [tabWorld_static _ _ _ _ _ _ hc] + rfl + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallWorld.OS_agree' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms OS_agree + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallWorld.OS_ok' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms OS_ok + +/-- info: 'SolidCore.Refinement.Solar.AssembleCallWorld.OS_static' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms OS_static + +end SolidCore.Refinement.Solar.AssembleCallWorld diff --git a/SolidCore/Refinement/Solar/AssembleCodeCopy.lean b/SolidCore/Refinement/Solar/AssembleCodeCopy.lean new file mode 100644 index 00000000..1ab9283f --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCodeCopy.lean @@ -0,0 +1,196 @@ +import SolidCore.Refinement.Solar.AssembleDynCopy + +/-! +# CODECOPY of the frame's code at the frame's own gas + +CODECOPY copies a range of the code that runs to memory, with zeros past its end. In SolarTV the +bytes come from the oracle's read `code` (`SolarTV.Machine.codeByte`), so the bytecode's CODECOPY +is SolarTV's under an oracle whose reads are the bytes of that code (`CodeOk`); every oracle has a +form that meets it (`codeOracle_ok`). + +* `codecopy_back`: a CODECOPY in a run that succeeds had the gas for the copy and the growth of + memory, and the run goes on from the frame after it (EthLib's `Logic.codecopy`). +* `codecopy_dyn`: with the budget of a frame below `2 ^ 256` gas and a code offset below `2 ^ 32` + (a constant the checker reads), SolarTV's copy agrees with EthLib's memory after it at any + destination and size. SolarTV's read takes its index as a word, so an offset near `2 ^ 256` + would wrap where EthLib reads zeros: the bound on the offset excludes that, and the budget bounds + the size by `2 ^ 140` (`size_le_of_cost`). +-/ + +namespace SolidCore.Refinement.Solar.AssembleCodeCopy + +open SolarTV SolarTV.Machine SolidCore.Refinement +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleDyn SolidCore.Refinement.Solar.AssembleEffects +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +variable {rd : ByteArray} + +/-! ## The oracle's reads of the code -/ + +/-- The oracle reads the frame's code: byte `w` of `code` at every word `w`, zero past its end. -/ +def CodeOk (o : Oracle) (code : ByteArray) : Prop := + ∀ w : Word, (o.env "code" [] [w]).setWidth 8 = (byteAt code w.toNat).toBitVec + +/-- Any oracle, with the reads of `code`. -/ +def codeOracle (code : ByteArray) (o : Oracle) : Oracle := + { o with env := fun name w args => + if name = "code" ∧ w = [] then + match args with + | [a] => BitVec.ofNat 256 (byteAt code a.toNat).toNat + | _ => o.env name w args + else o.env name w args } + +theorem setWidth_ofNat_byte (x : UInt8) : (BitVec.ofNat 256 x.toNat).setWidth 8 = x.toBitVec := by + apply BitVec.eq_of_toNat_eq + have hx := UInt8.toNat_lt x + simp only [BitVec.toNat_setWidth, BitVec.toNat_ofNat, UInt8.toNat_toBitVec] + rw [Nat.mod_eq_of_lt (by omega : x.toNat < 2 ^ 256), Nat.mod_eq_of_lt (by omega : x.toNat < 2 ^ 8)] + +/-- `CodeOk` is no vacuous hypothesis: every oracle has a form that meets it. -/ +theorem codeOracle_ok (code : ByteArray) (o : Oracle) : CodeOk (codeOracle code o) code := by + intro w + simp only [codeOracle, and_self, ite_true] + exact setWidth_ofNat_byte _ + +/-- The other reads of `codeOracle` are the oracle's. -/ +theorem codeOracle_env (code : ByteArray) (o : Oracle) {name : String} (h : name ≠ "code") + (w : List Event) (args : List Word) : (codeOracle code o).env name w args = o.env name w args := by + simp [codeOracle, h] + +/-- SolarTV's byte of the code at an index below `2 ^ 256` is EthLib's. -/ +theorem codeByte_eq {o : Oracle} {code : ByteArray} (hc : CodeOk o code) {i : Nat} (hi : i < 2 ^ 256) : + codeByte o i = (byteAt code i).toBitVec := by + unfold codeByte + rw [hc] + simp only [BitVec.toNat_ofNat, Nat.mod_eq_of_lt hi] + +/-! ## CODECOPY in a run that succeeds -/ + +/-- **CODECOPY in a run that succeeds**: the frame had the gas for the copy and the growth of +memory, and the run goes on from the frame after it. -/ +theorem codecopy_back {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {d off sz : Word} + {T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {evm : Evm .fusaka Nat} (hat : At code msg pc (d :: off :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x39) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + 3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost ≤ g ∧ + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) T + (memoryWrite (memoryExtend M (extendMemory M.size [(d, sz)]).expandBy) + d.toNat ⟨(bufferRead code off.toNat sz.toNat).toArray⟩) + (g - (3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost)) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + by_cases hg : 3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost ≤ g + · obtain ⟨m, hr, hm⟩ := Logic.codecopy (fork := .fusaka) hlt hbyte hg evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc (d :: off :: sz :: T) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .codecopy := by + rw [hbyte] + exact ofByte_of_decode rfl (Fork.frontier_le _) + rw [step_of_instruction hlt decoded instruction_codecopy] + rw [copyToMemory_cons hst] + have hlt' : g < 3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost := + Nat.lt_of_not_le hg + have hc : GasMeter.charge e.gas (OPCODE_CODECOPY_BASE + OPCODE_COPY_PER_WORD * + wordCount sz.toNat + (extendMemory e.memory.size [(d, sz)]).cost) = .error .outOfGas := by + rw [hgas, hmem, show OPCODE_CODECOPY_BASE = 3 from rfl, + show OPCODE_COPY_PER_WORD = 3 from rfl] + simp only [GasMeter.charge] + rw [ite_eq_left_of_eq_true _ _ (eq_true hlt')] + simp only [hc] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rw [hf.2.1] at hok + cases hok + +/-- A copy the budget of a frame below `2 ^ 256` gas pays for has at most `2 ^ 140` bytes. -/ +theorem size_le_of_budget {M : ByteArray} {g G pre : Nat} (hmod : M.size % 32 = 0) {d sz : Word} + (hz : sz ≠ 0) (hb : MemBudget G M g) (hG : G < 2 ^ 256) + (hg : pre + (extendMemory M.size [(d, sz)]).cost ≤ g) : d.toNat + sz.toNat ≤ 2 ^ 140 := by + have h1 := (budget_grow hmod hz hb hg).1 + rw [← memoryGasCost_ceil32] at h1 + have h2 := size_le_of_cost h1 hG (by rw [ceil32_eq]; omega) + have := le_ceil32 (d.toNat + sz.toNat) + omega + +/-- **CODECOPY of any range, in a run that succeeds**: with the budget of a frame below `2 ^ 256` +gas and the code offset below `2 ^ 32`, under an oracle that reads the frame's code, SolarTV's copy +agrees with EthLib's memory after it, the budget holds at the gas left, and the run goes on. -/ +theorem codecopy_dyn {code : ByteArray} {msg : Message .fusaka} {o : Oracle} (hc : CodeOk o code) + {pc : Nat} {d off sz : Word} (hoff : off.toNat < 2 ^ 32) {T : List Word} {M : ByteArray} + {g G : Nat} {st : State.TransactionState} {ss : Substate} {m0 : SolarTV.Machine.Mem} + (hm : MemRel m0 M) (hb : MemBudget G M g) (hG : G < 2 ^ 256) {evm : Evm .fusaka Nat} + (hat : At code msg pc (d :: off :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x39) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + ∃ (M' : ByteArray) (g' : Nat) (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + MemRel (m0.write d.toNat sz.toNat (fun i => codeByte o (off.toNat + i))) M' ∧ + MemBudget G M' g' ∧ g' ≤ g ∧ At code msg (pc + 1) T M' g' st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + obtain ⟨hg, m, within', hat', hrun'⟩ := codecopy_back hat hlt hbyte within hrun hok + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have hsmall : sz = 0 ∨ d.toNat + sz.toNat ≤ 2 ^ 140 := by + by_cases hz : sz = 0 + · exact .inl hz + · exact .inr (size_le_of_budget hmod hz hb hG hg) + have hbound : sz = 0 ∨ (d.toNat + sz.toNat + 31) / 32 < 2 ^ 251 := by + rcases hsmall with h | h + · exact .inl h + · exact .inr (by omega) + have hfit : sz.toNat ≠ 0 → + d.toNat + sz.toNat ≤ (memoryExtend M (extendMemory M.size [(d, sz)]).expandBy).size := by + intro hz + have hz' : sz ≠ 0 := fun h => hz (by simp [h]) + rw [size_memoryExtend_extendMemory' hmod hz'] + have := le_ceil32 (d.toNat + sz.toNat) + omega + refine ⟨_, _, m, within', ?_, ?_, by omega, hat', hrun'⟩ + · have he := memRel_expandW hm hbound + rw [← write_expand] + refine memRel_write he hfit (size_bufferRead _ _ _) (fun i hi => ?_) + rw [byteAt_bufferRead, ite_eq_left_of_eq_true _ _ (eq_true hi)] + have hz : sz ≠ 0 := by + intro h + subst h + simp at hi + have hle := hsmall.resolve_left hz + rw [codeByte_eq hc (by omega)] + · refine MemBudget.grow hmod hb hg ?_ + rw [size_memoryWrite_of_fit, size_memoryExtend] + intro h + rw [size_bufferRead] at h ⊢ + exact hfit h + +/-- **CODECOPY in SolarTV**: the effect writes the oracle's bytes of the code and grows nothing else. -/ +theorem codecopy_effect (o : Oracle) (call : Call) (d off sz : Word) (s : SolarTV.Machine.State) : + Effect.apply o call .codecopy [d, off, sz] s = + some (none, { s with + memory := s.memory.write d.toNat sz.toNat (fun i => codeByte o (off.toNat + i)) }) := rfl + +/-- info: 'SolidCore.Refinement.Solar.AssembleCodeCopy.codecopy_dyn' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms codecopy_dyn + +/-- info: 'SolidCore.Refinement.Solar.AssembleCodeCopy.codeOracle_ok' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms codeOracle_ok + +end SolidCore.Refinement.Solar.AssembleCodeCopy diff --git a/SolidCore/Refinement/Solar/AssembleCreate.lean b/SolidCore/Refinement/Solar/AssembleCreate.lean new file mode 100644 index 00000000..2816c347 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCreate.lean @@ -0,0 +1,255 @@ +import EthLib.Execution.Proofs.Evm.Logic.Call +import EthLib.Execution.Proofs.Evm.Call.Create + +/-! +# CREATE2 in EthLib: the address and the steps that send no message + +What CREATE2 does in EthLib's interpreter (Fusaka) beside the step that sends the init code as a +message (EthLib's `Logic.create2With`): + +* `create2Address_toU256`: the new address, as the word the creator pushes, is the low 160 bits + of Keccak-256 of `0xff`, the creator's address, the salt and Keccak-256 of the init code (EIP-1014). +* `createStep2_oog`: short of the price of the creation and the growth of memory, the step fails. +* `createStep2_skip`: a creator that lacks the value, holds the greatest nonce, or is at the + greatest depth runs no message: it pays the price, grows memory, pushes 0 and goes on, with empty + return data and only the read of its own account recorded. +* `createStep2_collision`: an address that holds code or a nonce gets no message: the creator pays + the gas it would pass on as well, its nonce grows, and it pushes 0 (EIP-684). +-/ + +namespace SolidCore.Refinement.Solar.AssembleCreate + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open EthLib.Cryptography.Hash.Keccak (keccak256) + +/-! ## The address -/ + +/-- The address in a hash, as a word, is the hash's word modulo `2 ^ 160`: its last 20 bytes. -/ +theorem addressOfHash_toU256 (h : Vector UInt8 32) : + (addressOfHash h).toU256 = BitVec.ofNat 256 ((U256.fromBeBytes h).toNat % 2 ^ 160) := by + have hsplit : h.toList = h.toList.take 12 ++ h.toList.drop 12 := (List.take_append_drop 12 _).symm + have hlen : (h.toList.drop 12).length = 20 := by simp + have hlt := bytesToNat_lt (h.toList.drop 12) + rw [hlen, show (256 : Nat) ^ 20 = 2 ^ 160 from rfl] at hlt + have hall := bytesToNat_lt h.toList + simp only [Vector.length_toList] at hall + unfold Address.toU256 addressOfHash U256.fromBeBytes + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt (by omega : bytesToNat h.toList < 2 ^ 256)] + congr 1 + have hd : (h.drop 12).toList = h.toList.drop 12 := by + simp only [Vector.drop] + simp + have h20 : (List.drop 12 h.toArray.toList).length ≤ 20 := Nat.le_of_eq hlen + rw [List.take_of_length_le h20] + rfl + rw [hd] + conv => rhs; rw [hsplit, bytesToNat_append, hlen] + rw [show (256 : Nat) ^ 20 = 2 ^ 160 from rfl, Nat.mul_comm (bytesToNat _) (2 ^ 160), + Nat.mul_add_mod, Nat.mod_eq_of_lt hlt] + +/-- **The CREATE2 address** (EIP-1014), as the word the creator pushes: the low 160 bits of the +Keccak-256 word of its preimage, `0xff`, the sender's 20 bytes, the salt's 32 bytes and the 32 bytes of the +Keccak-256 word of the init code (`create2Preimage`). -/ +theorem create2Address_toU256 (sender : Address) (salt : U256) (initCode : ByteArray) : + (create2Address sender salt initCode).toU256 = BitVec.ofNat 256 ((keccak + (create2Preimage sender salt (U256.toBeBytes (keccak initCode)))).toNat % 2 ^ 160) := by + have e : U256.toBeBytes (keccak initCode) = keccak256 initCode := U256.toBeBytes_fromBeBytes _ + rw [e] + exact addressOfHash_toU256 _ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreate.create2Address_toU256' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms create2Address_toU256 + + +/-! ## The steps of CREATE2 that send no message -/ + +/-- The price CREATE2 pays at Fusaka before the gas it passes on: 32000, 6 gas a word to hash the +init code, 2 gas a word of init code (EIP-3860) and the growth of memory. -/ +def cost2 (msize : Nat) (start size : U256) : Nat := + createBaseCost .fusaka + OPCODE_KECCAK256_PER_WORD * wordCount size.toNat + + initCodeCost size.toNat + (extendMemory msize [(start, size)]).cost + +theorem cost2_eq (msize : Nat) (start size : U256) : + cost2 msize start size = createBaseCost .fusaka + + (if true then OPCODE_KECCAK256_PER_WORD * wordCount size.toNat else 0) + + (if Fork.fusaka ≥ .shapella then initCodeCost size.toNat else 0) + + (extendMemory msize [(start, size)]).cost := by + simp [cost2, show Fork.fusaka ≥ .shapella by decide] + +/-- **CREATE2 short of its price fails**: the step is an error. -/ +theorem createStep2_oog {evm : Evm .fusaka Nat} {value start size salt : U256} {rest : List U256} + (hst : evm.stack.val = value :: start :: size :: salt :: rest) + (hgas : evm.gas < cost2 evm.memory.size start size) : + ∃ e, createStep (fork := .fusaka) (Meter := Nat) true evm = .error e := by + rcases evm with ⟨pc, ⟨l, hl⟩, memory, code, valid, gas, running, message, output, returnData, + state, substate, error⟩ + simp only at hst hgas ⊢ + subst hst + unfold cost2 at hgas + refine ⟨.outOfGas, ?_⟩ + simp [createStep, show ¬ Fork.fusaka ≥ .glamsterdam by decide, popWord, Stack.pop, popSalt, bind, + Except.bind, pure, Except.pure, chargeGasAndMemory, chargeGas, GasMeter.charge, + show Fork.fusaka ≥ .shapella by decide, hgas] + +/-- The init code CREATE2 reads from memory grown for its range has the range's size. -/ +theorem size_read {memory : ByteArray} (hmod : memory.size % 32 = 0) (start size : U256) : + (memoryReadBytes (memoryExtend memory (extendMemory memory.size [(start, size)]).expandBy) + start.toNat size.toNat).size = size.toNat := by + unfold memoryReadBytes + split + · rename_i h; simp [h] + · rename_i h + have hz : size ≠ 0 := fun e => h (by simp [e]) + have hle := le_ceil32_add_expandBy memory.size [(start, size)] (start, size) (by simp) hz + rw [ceil32_of_mod hmod] at hle + simp only at hle + simp only [ByteArray.size_extract, size_memoryExtend] + omega + +/-- **CREATE2 of init code past the limit of EIP-3860 fails.** -/ +theorem createStep2_big {evm : Evm .fusaka Nat} {value start size salt : U256} {rest : List U256} + (hst : evm.stack.val = value :: start :: size :: salt :: rest) (hmod : evm.memory.size % 32 = 0) + (hgas : cost2 evm.memory.size start size ≤ evm.gas) + (hbig : maxInitCodeSize .fusaka < size.toNat) : + ∃ e, createStep (fork := .fusaka) (Meter := Nat) true evm = .error e := by + rcases evm with ⟨pc, ⟨l, hl⟩, memory, code, valid, gas, running, message, output, returnData, + state, substate, error⟩ + simp only at hst hgas hmod ⊢ + subst hst + unfold cost2 at hgas + have hread := size_read hmod start size + refine ⟨.outOfGas, ?_⟩ + simp [createStep, show ¬ Fork.fusaka ≥ .glamsterdam by decide, popWord, Stack.pop, popSalt, bind, + Except.bind, pure, Except.pure, chargeGasAndMemory, chargeGas, GasMeter.charge, + show Fork.fusaka ≥ .shapella by decide, Nat.not_lt.mpr hgas, genericCreate, hread, hbig] + +/-- **A creator that lacks the value, holds the greatest nonce or is at the greatest depth runs no +message**: CREATE2 pays its price, grows memory, pushes 0 and goes on, with empty return data and +the read of its own account recorded. -/ +theorem createStep2_skip {evm : Evm .fusaka Nat} {value start size salt : U256} {rest : List U256} + (hst : evm.stack.val = value :: start :: size :: salt :: rest) + (hstatic : evm.message.isStatic = false) + (hinit : size.toNat ≤ maxInitCodeSize .fusaka) + (hgas : cost2 evm.memory.size start size ≤ evm.gas) + (hskip : (evm.state.getAccount evm.message.currentTarget).balance < value ∨ + (evm.state.getAccount evm.message.currentTarget).nonce = MAX_NONCE ∨ + STACK_DEPTH_LIMIT < evm.message.depth + 1) : + ∃ after, createStep (fork := .fusaka) (Meter := Nat) true evm = .ok (.next after) ∧ + after.code = evm.code ∧ after.validJumpDestinations = evm.validJumpDestinations ∧ + after.message = evm.message ∧ after.pc = evm.pc + 1 ∧ after.stack.val = 0 :: rest ∧ + after.memory = memoryExtend evm.memory (extendMemory evm.memory.size [(start, size)]).expandBy ∧ + after.gas = evm.gas - cost2 evm.memory.size start size ∧ + after.running = evm.running ∧ after.error = evm.error ∧ after.output = evm.output ∧ + after.returnData = .empty ∧ + after.state = evm.state.recordAccountRead evm.message.currentTarget ∧ + after.substate = evm.substate := by + rcases evm with ⟨pc, ⟨l, hl⟩, memory, code, valid, gas, running, message, output, returnData, + state, substate, error⟩ + simp only at hst hstatic hgas hskip ⊢ + subst hst + unfold cost2 at hgas ⊢ + have hread : (memoryReadBytes (memoryExtend memory + (extendMemory memory.size [(start, size)]).expandBy) start.toNat size.toNat).size ≤ + size.toNat := by + unfold memoryReadBytes + split + · simp + · simp only [ByteArray.size_extract] + omega + have hlim : ¬(Fork.shapella ≤ Fork.fusaka ∧ maxInitCodeSize .fusaka < (memoryReadBytes + (memoryExtend memory (extendMemory memory.size [(start, size)]).expandBy) start.toNat + size.toNat).size) := by + rintro ⟨-, hlt⟩ + omega + have hlen : rest.length < STACK_LIMIT := by simp at hl; unfold STACK_LIMIT at *; omega + have hne : rest.length ≠ STACK_LIMIT := by omega + have hlim' : ¬ maxInitCodeSize .fusaka < (memoryReadBytes (memoryExtend memory + (extendMemory memory.size [(start, size)]).expandBy) start.toNat size.toNat).size := by + omega + have hgd : ∀ (tx : State.TransactionState) (x : Address), + (tx.recordAccountRead x).getAccount = tx.getAccount := fun _ _ => rfl + simp [createStep, show ¬ Fork.fusaka ≥ .glamsterdam by decide, popWord, Stack.pop, popSalt, bind, + Except.bind, pure, Except.pure, chargeGasAndMemory, chargeGas, GasMeter.charge, + show Fork.fusaka ≥ .shapella by decide, Nat.not_lt.mpr hgas, genericCreate, hlim, hstatic, + launchCreate, recordAccountRead, hgd, hskip, skipCall, pushWord, Stack.push, hne, hlim', + GasMeter.credit, advance] + all_goals first + | done + | exact ⟨_, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩ + + +/-- **An address that holds code or a nonce gets no message** (EIP-684): CREATE2 pays its price and +the gas it would pass on, grows memory, the creator's nonce grows, and it pushes 0 and goes on with +empty return data. -/ +theorem createStep2_collision {evm : Evm .fusaka Nat} {value start size salt : U256} + {rest : List U256} + (hst : evm.stack.val = value :: start :: size :: salt :: rest) + (hstatic : evm.message.isStatic = false) + (hinit : size.toNat ≤ maxInitCodeSize .fusaka) + (hgas : cost2 evm.memory.size start size ≤ evm.gas) + (hbal : value ≤ (evm.state.getAccount evm.message.currentTarget).balance) + (hnonce : (evm.state.getAccount evm.message.currentTarget).nonce ≠ MAX_NONCE) + (hdepth : evm.message.depth + 1 ≤ STACK_DEPTH_LIMIT) + (hdeploy : evm.state.accountDeployable (create2Address evm.message.currentTarget salt + (memoryReadBytes (memoryExtend evm.memory + (extendMemory evm.memory.size [(start, size)]).expandBy) start.toNat size.toNat)) = false) : + ∃ after st', createStep (fork := .fusaka) (Meter := Nat) true evm = .ok (.next after) ∧ + ((evm.state.recordAccountRead evm.message.currentTarget).recordAccountRead + (create2Address evm.message.currentTarget salt (memoryReadBytes (memoryExtend evm.memory + (extendMemory evm.memory.size [(start, size)]).expandBy) start.toNat size.toNat))).incrementNonce + .fusaka evm.message.currentTarget = .ok st' ∧ + after.code = evm.code ∧ after.validJumpDestinations = evm.validJumpDestinations ∧ + after.message = evm.message ∧ after.pc = evm.pc + 1 ∧ after.stack.val = 0 :: rest ∧ + after.memory = memoryExtend evm.memory (extendMemory evm.memory.size [(start, size)]).expandBy ∧ + after.gas = evm.gas - cost2 evm.memory.size start size - + createMessageGas .fusaka (evm.gas - cost2 evm.memory.size start size) ∧ + after.running = evm.running ∧ after.error = evm.error ∧ after.output = evm.output ∧ + after.returnData = .empty ∧ after.state = st' ∧ + after.substate = { evm.substate with + accessedAddresses := evm.substate.accessedAddresses.insert (create2Address + evm.message.currentTarget salt (memoryReadBytes (memoryExtend evm.memory + (extendMemory evm.memory.size [(start, size)]).expandBy) start.toNat size.toNat)) } := by + rcases evm with ⟨pc, ⟨l, hl⟩, memory, code, valid, gas, running, message, output, returnData, + state, substate, error⟩ + simp only at hst hstatic hgas hbal hnonce hdepth hdeploy ⊢ + subst hst + unfold cost2 at hgas ⊢ + have hread : (memoryReadBytes (memoryExtend memory + (extendMemory memory.size [(start, size)]).expandBy) start.toNat size.toNat).size ≤ + size.toNat := by + unfold memoryReadBytes + split + · simp + · simp only [ByteArray.size_extract] + omega + have hlim : ¬(Fork.shapella ≤ Fork.fusaka ∧ maxInitCodeSize .fusaka < (memoryReadBytes + (memoryExtend memory (extendMemory memory.size [(start, size)]).expandBy) start.toNat + size.toNat).size) := by + rintro ⟨-, hlt⟩ + omega + have hlen : rest.length < STACK_LIMIT := by simp at hl; unfold STACK_LIMIT at *; omega + have hmg : ∀ g, ¬g < createMessageGas .fusaka g := by + intro g + simp only [createMessageGas, show Fork.fusaka ≥ .tangerineWhistle by decide, ite_true, + maxMessageCallGas] + omega + have hgd : ∀ (tx : State.TransactionState) (x y : Address), + (tx.recordAccountRead x).accountDeployable y = tx.accountDeployable y := fun _ _ _ => rfl + generalize hA : create2Address message.currentTarget salt (memoryReadBytes (memoryExtend memory + (extendMemory memory.size [(start, size)]).expandBy) start.toNat size.toNat) = A at hdeploy ⊢ + obtain ⟨state', hinc⟩ := State.TransactionState.incrementNonce_isOk .fusaka + ((state.recordAccountRead message.currentTarget).recordAccountRead A) message.currentTarget + have hne : rest.length ≠ STACK_LIMIT := by omega + have hlim' : ¬ maxInitCodeSize .fusaka < (memoryReadBytes (memoryExtend memory + (extendMemory memory.size [(start, size)]).expandBy) start.toNat size.toNat).size := by + omega + simp [createStep, show ¬ Fork.fusaka ≥ .glamsterdam by decide, popWord, Stack.pop, popSalt, bind, + Except.bind, pure, Except.pure, chargeGasAndMemory, chargeGas, GasMeter.charge, + show Fork.fusaka ≥ .shapella by decide, Nat.not_lt.mpr hgas, genericCreate, hlim, hstatic, + launchCreate, recordAccountRead, hgd, BitVec.not_lt.mpr hbal, hnonce, Nat.not_lt.mpr hdepth, + creationAddress, hA, accessAddress, keepReads, show Fork.berlin ≤ Fork.fusaka by decide, createNewAccountStateGas, chargeStateGas, + GasMeter.chargeState, hmg, hdeploy, hinc, Except.mapError, GasMeter.gasLeft, pushWord, + Stack.push, hne, hlim', advance] + +end SolidCore.Refinement.Solar.AssembleCreate diff --git a/SolidCore/Refinement/Solar/AssembleCreateBack.lean b/SolidCore/Refinement/Solar/AssembleCreateBack.lean new file mode 100644 index 00000000..bf09d06f --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCreateBack.lean @@ -0,0 +1,185 @@ +import SolidCore.Refinement.Solar.AssembleCreate +import EthLib.Execution.Proofs.Evm.Logic.Create +import EthLib.Execution.Proofs.Evm.Logic.LessGas + +/-! +# CREATE2 at the frame's own gas, from a run that succeeds + +`create2_back`: a CREATE2 step in a run of EthLib's interpreter (Fusaka) that ends with no error had +the gas for its price and the growth of memory, its init code is within the limit of EIP-3860, and +the run goes on from the frame after it, in one of three ways, each with every fact the frame gives: + +* the creator lacks the value, holds the greatest nonce or is at the greatest depth: no message, 0 + pushed, empty return data; +* the address of EIP-1014 (`AssembleCreate.create2Address_toU256`) holds code or a nonce: no + message, the creator pays the gas it would pass on and its nonce grows, 0 pushed (EIP-684); +* otherwise the init code runs as a callee at that address, under any runner of messages meeting + `P`: the frame that ends it meets `P` and the creator pushes the address when it ends with no + error and 0 otherwise (EthLib's `Logic.create2With`). + +Nothing is assumed of the init code: what it does is the callee's frame, which a run's table +records as it records a call's. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCreateBack + +open SolidCore.Refinement.Solar.AssembleCreate +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts + +/-- **CREATE2 in a run that succeeds.** -/ +theorem create2_back {code : ByteArray} {msg : Message .fusaka} {pc g : Nat} {M : ByteArray} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray} + {value start size salt : U256} {rest : List U256} {evm : Evm .fusaka Nat} + (hat : At code msg pc (value :: start :: size :: salt :: rest) M g st ss rd evm) + (hmod : M.size % 32 = 0) (hlt : pc < code.size) (hbyte : code[pc] = 0xf5) + (hstatic : msg.isStatic = false) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} (meets : Meets P runChild) + (within : GasMeter.gasHeld evm.gas ≤ bound) {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + cost2 M.size start size ≤ g ∧ size.toNat ≤ maxInitCodeSize .fusaka ∧ + ((((st.getAccount msg.currentTarget).balance < value ∨ + (st.getAccount msg.currentTarget).nonce = MAX_NONCE ∨ STACK_DEPTH_LIMIT < msg.depth + 1) ∧ + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) (0 :: rest) + (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) + (g - cost2 M.size start size) (st.recordAccountRead msg.currentTarget) ss .empty m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin) ∨ + (value ≤ (st.getAccount msg.currentTarget).balance ∧ + (st.getAccount msg.currentTarget).nonce ≠ MAX_NONCE ∧ msg.depth + 1 ≤ STACK_DEPTH_LIMIT ∧ + st.accountDeployable (create2Address msg.currentTarget salt (memoryReadBytes + (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) start.toNat size.toNat)) = + false ∧ + ∃ (st' : State.TransactionState) (m : Evm .fusaka Nat) + (within' : GasMeter.gasHeld m.gas ≤ bound), + ((st.recordAccountRead msg.currentTarget).recordAccountRead (create2Address + msg.currentTarget salt (memoryReadBytes (memoryExtend M + (extendMemory M.size [(start, size)]).expandBy) start.toNat size.toNat))).incrementNonce + .fusaka msg.currentTarget = .ok st' ∧ + At code msg (pc + 1) (0 :: rest) + (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) + (g - cost2 M.size start size - createMessageGas .fusaka (g - cost2 M.size start size)) + st' { ss with accessedAddresses := ss.accessedAddresses.insert (create2Address + msg.currentTarget salt (memoryReadBytes (memoryExtend M + (extendMemory M.size [(start, size)]).expandBy) start.toNat size.toNat)) } + .empty m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin) ∨ + (value ≤ (st.getAccount msg.currentTarget).balance ∧ + (st.getAccount msg.currentTarget).nonce ≠ MAX_NONCE ∧ msg.depth + 1 ≤ STACK_DEPTH_LIMIT ∧ + st.accountDeployable (create2Address msg.currentTarget salt (memoryReadBytes + (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) start.toNat size.toNat)) = + true ∧ + ∃ (caller : Evm .fusaka Nat) (m : Message .fusaka) (child after : Evm .fusaka Nat) + (within' : GasMeter.gasHeld after.gas ≤ bound), + P caller m child ∧ child.gas ≤ m.gas ∧ + ((st.recordAccountRead msg.currentTarget).recordAccountRead (create2Address + msg.currentTarget salt (memoryReadBytes (memoryExtend M + (extendMemory M.size [(start, size)]).expandBy) start.toNat size.toNat))).incrementNonce + .fusaka msg.currentTarget = .ok caller.state ∧ + caller.substate = { ss with accessedAddresses := ss.accessedAddresses.insert (create2Address + msg.currentTarget salt (memoryReadBytes (memoryExtend M + (extendMemory M.size [(start, size)]).expandBy) start.toNat size.toNat)) } ∧ + m.gas = createMessageGas .fusaka (g - cost2 M.size start size) ∧ + m.caller = msg.currentTarget ∧ + m.currentTarget = create2Address msg.currentTarget salt (memoryReadBytes (memoryExtend M + (extendMemory M.size [(start, size)]).expandBy) start.toNat size.toNat) ∧ + m.code = memoryReadBytes (memoryExtend M + (extendMemory M.size [(start, size)]).expandBy) start.toNat size.toNat ∧ + m.value = value ∧ m.isStatic = false ∧ + At code msg (pc + 1) ((if child.error.isNone then (create2Address msg.currentTarget salt + (memoryReadBytes (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) + start.toNat size.toNat)).toU256 else 0) :: rest) + (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) + (g - cost2 M.size start size - createMessageGas .fusaka (g - cost2 M.size start size) + + child.gas) + (incorporateChild .fusaka caller child).state + (incorporateChild .fusaka caller child).substate + (if child.error.isNone then .empty else child.output) after ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild after within' = .ok fin)) := by + have hat0 := hat + obtain ⟨hc, hj, hm, hpc, hst, hmem, hgas, hrunning, herr, hout, hs, hss, hrd⟩ := hat0 + have hlt' : evm.pc < evm.code.size := by rw [hc, hpc]; exact hlt + have decoded : Op.ofByte .fusaka (evm.code[evm.pc]'hlt') = some .create2 := by + have he : evm.code[evm.pc]'hlt' = code[pc]'hlt := by subst hc hpc; rfl + rw [he, hbyte] + exact ofByte_of_decode rfl (by decide) + have hstep : step .fusaka evm = createStep true evm := + step_of_messageInstruction hlt' decoded instruction_create2 + (messageInstruction_create2 (by decide)) + have hmod' : evm.memory.size % 32 = 0 := by rw [hmem]; exact hmod + have hst2 : evm.message.isStatic = false := by rw [hm]; exact hstatic + -- The price, from the run's success. + have hg : cost2 M.size start size ≤ g := by + refine Nat.le_of_not_lt fun hlow => ?_ + obtain ⟨e, he⟩ := createStep2_oog (evm := evm) hst (by rw [hmem, hgas]; exact hlow) + exact error_ne_none_of_stepFails hrunning (by rw [hstep]; exact .inl ⟨e, he⟩) hrun hok + have hgE : cost2 evm.memory.size start size ≤ evm.gas := by rw [hmem, hgas]; exact hg + have hinit : size.toNat ≤ maxInitCodeSize .fusaka := by + refine Nat.le_of_not_lt fun hbig => ?_ + obtain ⟨e, he⟩ := createStep2_big (evm := evm) hst hmod' hgE hbig + exact error_ne_none_of_stepFails hrunning (by rw [hstep]; exact .inl ⟨e, he⟩) hrun hok + refine ⟨hg, hinit, ?_⟩ + by_cases hsk : (st.getAccount msg.currentTarget).balance < value ∨ + (st.getAccount msg.currentTarget).nonce = MAX_NONCE ∨ STACK_DEPTH_LIMIT < msg.depth + 1 + · -- No message. + obtain ⟨after, h1, a1, a2, a3, a4, a5, a6, a7, a8, a9, ao, ar, as, ass⟩ := + createStep2_skip (evm := evm) hst hst2 hinit hgE (by rw [hs, hm]; exact hsk) + have hS : Step .fusaka evm after := .next hrunning (by rw [hstep]; exact h1) + have hrun' := hrun + rw [runFrame_eq_of_reaches Step.gasHeld_le Step.runFrame_eq (.single hS) within] at hrun' + refine .inl ⟨hsk, after, _, ⟨by rw [a1, hc], by rw [a2, hj], by rw [a3, hm], + by rw [a4, hpc], a5, by rw [a6, hmem], by rw [a7, hmem, hgas], by rw [a8, hrunning], + by rw [a9, herr], by rw [ao, hout], by rw [as, hs, hm], by rw [ass, hss], ar⟩, hrun'⟩ + have hbal : value ≤ (st.getAccount msg.currentTarget).balance := by + rcases Nat.lt_or_ge (st.getAccount msg.currentTarget).balance.toNat value.toNat with h | h + · exact absurd (.inl (BitVec.lt_def.mpr h)) hsk + · exact BitVec.le_def.mpr h + have hnonce : (st.getAccount msg.currentTarget).nonce ≠ MAX_NONCE := fun h => + hsk (.inr (.inl h)) + have hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT := Nat.le_of_not_lt fun h => hsk (.inr (.inr h)) + by_cases hdep : st.accountDeployable (create2Address msg.currentTarget salt (memoryReadBytes + (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) start.toNat size.toNat)) = true + · -- The init code runs as a callee. + have H := (create2With (fork := .fusaka) (callee := P) (rest := rest) (returnData := rd) + (substate := ss) (state := st) (memory := M) (gas := g) (by decide) (by decide) hlt hbyte hstatic + (fun _ => hinit) hbal hnonce hdepth rfl hdep (by + have := hg + unfold cost2 at this + simpa [show Fork.fusaka ≥ .shapella by decide] using this)) + obtain ⟨after, hr, hq⟩ := H bound runChild meets evm hat within + have within' := Nat.le_trans (hr.gasHeld_le StepBy.gasHeld_le) within + have hrun' := hrun + rw [runFrame_eq_of_reaches StepBy.gasHeld_le StepBy.runFrame_eq hr within] at hrun' + rcases hq with ⟨caller, m, child, hk, hcg, c1, c2, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, + hat'⟩ | aborted + · refine .inr (.inr ⟨hbal, hnonce, hdepth, hdep, caller, m, child, after, within', hk, hcg, c1, + c2, ?_, m2, m4, m6, m8, m10, ?_, hrun'⟩) + · rw [m1]; unfold cost2; simp [show Fork.fusaka ≥ .shapella by decide] + · unfold cost2 + simpa [show Fork.fusaka ≥ .shapella by decide] using hat' + · obtain ⟨e, he, -⟩ := runFrame_of_abortsBy meets.aborts aborted within' + rw [he] at hrun' + cases hrun' + · -- A collision: no message. + have hdep' : st.accountDeployable (create2Address msg.currentTarget salt (memoryReadBytes + (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) start.toNat size.toNat)) = + false := by simpa using hdep + obtain ⟨after, st', h1, hinc, a1, a2, a3, a4, a5, a6, a7, a8, a9, ao, ar, as, ass⟩ := + createStep2_collision (evm := evm) hst hst2 hinit hgE (by rw [hs, hm]; exact hbal) + (by rw [hs, hm]; exact hnonce) (by rw [hm]; exact hdepth) + (by rw [hs, hm, hmem]; exact hdep') + have hS : Step .fusaka evm after := .next hrunning (by rw [hstep]; exact h1) + have hrun' := hrun + rw [runFrame_eq_of_reaches Step.gasHeld_le Step.runFrame_eq (.single hS) within] at hrun' + rw [hs, hm, hmem] at hinc + refine .inr (.inl ⟨hbal, hnonce, hdepth, hdep', st', after, _, hinc, + ⟨by rw [a1, hc], by rw [a2, hj], by rw [a3, hm], by rw [a4, hpc], a5, by rw [a6, hmem], + by rw [a7, hmem, hgas], by rw [a8, hrunning], by rw [a9, herr], by rw [ao, hout], as, + by rw [ass, hss, hm, hmem], ar⟩, hrun'⟩) + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateBack.create2_back' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms create2_back + +end SolidCore.Refinement.Solar.AssembleCreateBack diff --git a/SolidCore/Refinement/Solar/AssembleCreateCut.lean b/SolidCore/Refinement/Solar/AssembleCreateCut.lean new file mode 100644 index 00000000..c818e6c6 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCreateCut.lean @@ -0,0 +1,74 @@ +import SolidCore.Refinement.Solar.AssembleCut +import SolidCore.Refinement.Solar.AssembleCreateSegOracle + +/-! +# CALL, CREATE2 and CODECOPY at a cut of the checker + +The checker cuts a block at CALL, CREATE2 and CODECOPY (`AssembleCutSim.blockOkC`, under a +certificate that says the program creates). These are the facts a segment proof takes at such a cut: +the code the lowering lays out there (one opcode each), and SolarTV's run of the rest of the block from +the effect's result, which the cut lemmas (`AssembleCallValueSeg.callValue_cut`, +`AssembleCallValueZeroSeg.call0_cut`, `AssembleCreateSeg.create2_cut`, +`AssembleCreateSeg.codecopy_cut`) give under the oracle of the run's tables. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCreateCut + +open SolarTV SolarTV.Machine +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCut +open SolarTV.EVM.Program + +theorem lowerInstrs_call (p : Assemble.Program) (c : Cert) (b : Nat) (rest : List Assemble.Instr) : + lowerInstrs p c b (.effect (.call .call) 7 :: rest) = .op 0xf1 :: lowerInstrs p c b rest := by + simp [lowerInstrs, turnedElse, dropped, lowerInstr] + +theorem lowerInstrs_c2 (p : Assemble.Program) (c : Cert) (b : Nat) (rest : List Assemble.Instr) : + lowerInstrs p c b (.effect .create2 4 :: rest) = .op 0xf5 :: lowerInstrs p c b rest := by + simp [lowerInstrs, turnedElse, dropped, lowerInstr] + +theorem lowerInstrs_cc (p : Assemble.Program) (c : Cert) (b : Nat) (rest : List Assemble.Instr) : + lowerInstrs p c b (.effect .codecopy 3 :: rest) = .op 0x39 :: lowerInstrs p c b rest := by + simp [lowerInstrs, turnedElse, dropped, lowerInstr] + +/-- SolarTV's run of a block from a CALL: the rest of the block from the call's flag. -/ +theorem exec_callC {o : Oracle} {call : Call} {b : Nat} {rest : List Assemble.Instr} + {a1 a2 a3 a4 a5 a6 a7 w : Word} {S : List Word} {s s2 : State} + (happ : Effect.apply o call (.call .call) [a1, a2, a3, a4, a5, a6, a7] s = some (some w, s2)) + (h : S.length < 1024) : + exec o call b (.effect (.call .call) 7 :: rest) (a1 :: a2 :: a3 :: a4 :: a5 :: a6 :: a7 :: S) s = + exec o call b rest (w :: S) s2 := by + simp [exec, happ, show ¬ 1024 < S.length + 1 by omega] + +/-- SolarTV's run of a block from a CREATE2: the rest of the block from the word it pushes. -/ +theorem exec_c2C {o : Oracle} {call : Call} {b : Nat} {rest : List Assemble.Instr} + {a1 a2 a3 a4 w : Word} {S : List Word} {s s2 : State} + (happ : Effect.apply o call .create2 [a1, a2, a3, a4] s = some (some w, s2)) + (h : S.length < 1024) : + exec o call b (.effect .create2 4 :: rest) (a1 :: a2 :: a3 :: a4 :: S) s = + exec o call b rest (w :: S) s2 := by + simp [exec, happ, show ¬ 1024 < S.length + 1 by omega] + +/-- SolarTV's run of a block from a CODECOPY: the rest of the block from the copy. -/ +theorem exec_ccC {o : Oracle} {call : Call} {b : Nat} {rest : List Assemble.Instr} + {d off sz : Word} {S : List Word} {s s2 : State} + (happ : Effect.apply o call .codecopy [d, off, sz] s = some (none, s2)) (h : S.length ≤ 1024) : + exec o call b (.effect .codecopy 3 :: rest) (d :: off :: sz :: S) s = exec o call b rest S s2 := by + simp [exec, happ, show ¬ 1024 < S.length by omega] + +/-- **A CODECOPY cut, read back**: SolarTV's run of the block from the CODECOPY is the run of the rest +from SolarTV's copy, which `AssembleCreateSeg.codecopy_cut` relates to EthLib's under an oracle that +reads the frame's code, at a code offset the checker knows below 2 ^ 32 +(`AssembleCut.blockOkC_cc`). -/ +theorem exec_codecopy {o : Oracle} {call : Call} {b : Nat} {rest : List Assemble.Instr} + {d off sz : Word} {S : List Word} {s : State} + (h : S.length ≤ 1024) : + exec o call b (.effect .codecopy 3 :: rest) (d :: off :: sz :: S) s = + exec o call b rest S (AssembleCreateSeg.codeCopied o s d off sz) := + exec_ccC (AssembleCodeCopy.codecopy_effect o call d off sz s) h + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateCut.exec_codecopy' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms exec_codecopy + +end SolidCore.Refinement.Solar.AssembleCreateCut diff --git a/SolidCore/Refinement/Solar/AssembleCreateCutQ.lean b/SolidCore/Refinement/Solar/AssembleCreateCutQ.lean new file mode 100644 index 00000000..5ecf8c2d --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCreateCutQ.lean @@ -0,0 +1,399 @@ +import SolidCore.Refinement.Solar.AssembleCreateSegOracle + +/-! +# CALL and CREATE2 cuts from what the run gives the callee's frame + +`AssembleCallValueZeroSeg.call0_cut`, `AssembleCallValueSeg.callValue_cut` and `AssembleCreateSeg.create2_cut` +ask of every frame the runner of messages may return (`P caller m child`, with a few fields of the +message) that it keep the frame's account, add no log when it succeeds and have an output below +`2 ^ 256` bytes, over every caller state: too much, since some state gives the callee code that logs. +The versions here ask it only of the frames the runner returns from the caller state the instruction +makes out of the frame's own state, for the code the callee runs there (`Call0Q`, `CallVQ`, +`Create2Q`), which a run that calls and creates only contracts that do not log meets. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCreateCutQ + +open SolarTV SolarTV.Machine +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.RunOracle +open SolidCore.Refinement.Solar.AssembleEffects SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCreateSeg SolidCore.Refinement.Solar.AssembleCall +open SolidCore.Refinement.Solar.AssembleCallValue SolidCore.Refinement.Solar.AssembleCallValueEffect +open SolidCore.Refinement.Solar.AssembleCallValueZero SolidCore.Refinement.Solar.AssembleCallValueSeg +open SolidCore.Refinement.Solar.AssembleCallValueZeroSeg SolidCore.Refinement.Solar.AssembleCreate +open SolidCore.Refinement.Solar.AssembleCreateBack +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts + +/-- **What a run gives a CALL with no value**: every frame the runner returns for its message (to the +callee, with its data), from the caller state the CALL makes out of the frame's state `st` and for +the code the callee runs, keeps the frame's account, adds no log when it succeeds and has an output +below `2 ^ 256` bytes (`CallOk`). -/ +def Call0Q (msg : Message .fusaka) (P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop) + (st : State.TransactionState) (M : ByteArray) (addr inOff inSize outOff outSize : U256) : Prop := + ∀ caller m child, P caller m child → m.currentTarget = toAddressMasked addr → m.value = 0 → + m.isStatic = false → + m.data = memoryReadBytes (memoryExtend M + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).expandBy) inOff.toNat inSize.toNat → + (∃ calleeCode route, st.getCode (st.getAccount (toAddressMasked addr)).codeHash = .ok calleeCode ∧ + caller.state = (routeState (st.recordAccountRead (toAddressMasked addr)) route).recordAccountRead + msg.currentTarget ∧ m.code = routeCode calleeCode route) → + CallOk msg child + +/-- **What a run gives a CALL with value** to a callee whose code is `calleeCode`, as `Call0Q`. -/ +def CallVQ (msg : Message .fusaka) (P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop) + (g : Nat) (st : State.TransactionState) (ss : Substate) (M : ByteArray) + (asked dst v i isz o osz : U256) (calleeCode : ByteArray) : Prop := + ∀ caller m child, P caller m child → + caller.state = (st.recordAccountRead (toAddressMasked dst)).recordAccountRead msg.currentTarget → + m.gas = (mcgV g st ss M.size asked dst v i isz o osz).subCall → + m.caller = msg.currentTarget → m.currentTarget = toAddressMasked dst → m.code = calleeCode → + m.data = memoryReadBytes (memoryExtend M (extendMemory M.size [(i, isz), (o, osz)]).expandBy) + i.toNat isz.toNat → m.value = v → CallOk msg child + +/-- **What a run gives a CREATE2**: every frame the runner returns for the creation's message (its +init code, at its address), from the caller state the creation makes out of `st`, keeps the frame's +account, adds no log when it succeeds and has revert data below `2 ^ 256` bytes (`CreateOk`). -/ +def Create2Q (msg : Message .fusaka) (P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop) + (g : Nat) (st : State.TransactionState) (M : ByteArray) (value start size salt : U256) : Prop := + ∀ caller m child, P caller m child → + ((st.recordAccountRead msg.currentTarget).recordAccountRead (create2Address msg.currentTarget salt + (memoryReadBytes (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) start.toNat + size.toNat))).incrementNonce .fusaka msg.currentTarget = .ok caller.state → + m.caller = msg.currentTarget → + m.currentTarget = create2Address msg.currentTarget salt (memoryReadBytes (memoryExtend M + (extendMemory M.size [(start, size)]).expandBy) start.toNat size.toNat) → + m.code = memoryReadBytes (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) + start.toNat size.toNat → m.value = value → + m.gas = createMessageGas .fusaka (g - cost2 M.size start size) → CreateOk msg child + +/-- **CREATE2 as a cut of a run that succeeds**: the creation had the gas for its price, and the run +goes on from the frame after it, pushing the word `r` (the EIP-1014 address on success, 0 otherwise), +with return data `out` and the storage of the frame's account after it. Under the oracle of every +extension of the table with these answers, SolarTV's CREATE2 pushes `r`, leaves `out` and that storage, +and every relation of a block entry holds again, at no more gas than the frame had. -/ +theorem create2_cutQ {code : ByteArray} {msg : Message .fusaka} {call : Call} {pc g G : Nat} + {M : ByteArray} {st : State.TransactionState} {ss ss0 : Substate} {rd : ByteArray} + {value start size salt : U256} {Tr : List U256} {s : State} {evm : Evm .fusaka Nat} + (o : Oracle) (A : CreateTable) + (hm : MemRel s.memory M) (R : Rel msg ss0 st ss s) (hb : MemBudget G M g) (hG : G < 2 ^ 256) + (hat : At code msg pc (value :: start :: size :: salt :: Tr) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0xf5) (hstatic : msg.isStatic = false) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} (meets : Meets P runChild) + (hq : Create2Q msg P g st M value start size salt) + (within : GasMeter.gasHeld evm.gas ≤ bound) {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) + (hA : A.addrs.length = creates s.world) (hAo : A.outs.length = creates s.world) + (hAs : A.stores.length = creates s.world) : + ∃ (r : Word) (out : ByteArray) (st' : State.TransactionState) (ss' : Substate) (M' : ByteArray) + (g' : Nat) (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + (∀ A'', (A.push r out (storeOf st' msg.currentTarget)).Le A'' → + Effect.apply (createOracle o A'') call .create2 [value, start, size, salt] s = + some (some r, postCreate o s (storeOf st' msg.currentTarget) value start size salt) ∧ + RdRel (createOracle o A'') (createWorld s value start size salt) out) ∧ + MemRel (postCreate o s (storeOf st' msg.currentTarget) value start size salt).memory M' ∧ + Rel msg ss0 st' ss' (postCreate o s (storeOf st' msg.currentTarget) value start size salt) ∧ + MemBudget G M' g' ∧ g' ≤ g ∧ + At code msg (pc + 1) (r :: Tr) M' g' st' ss' out m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + obtain ⟨hg, -, hcase⟩ := create2_back hat hmod hlt hbyte hstatic meets within hrun hok + have hg' : createBaseCost .fusaka + OPCODE_KECCAK256_PER_WORD * wordCount size.toNat + + initCodeCost size.toNat + (extendMemory M.size [(start, size)]).cost ≤ g := hg + have hbnd : size = 0 ∨ (start.toNat + size.toNat + 31) / 32 < 2 ^ 251 := by + by_cases hz : size = 0 + · exact .inl hz + · have := AssembleCodeCopy.size_le_of_budget hmod hz hb hG hg' + exact .inr (by omega) + have hm1 := memRel_expandW hm hbnd + have hb1 : MemBudget G (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) + (g - cost2 M.size start size) := + MemBudget.grow hmod hb hg' (size_memoryExtend _ _) + rcases hcase with ⟨-, m, within', hat', hrun'⟩ | + ⟨-, -, -, -, st', m, within', hinc, hat', hrun'⟩ | + ⟨-, -, -, -, caller, mm, child, after, within', hP, hcg, hinc2, hcsub, hmg, hmc, hmt, hmcode, hmv, -, + hat', hrun'⟩ + · -- No message: 0 pushed, no return data. + refine ⟨0, .empty, _, ss, memoryExtend M (extendMemory M.size [(start, size)]).expandBy, + g - cost2 M.size start size, m, within', fun A'' hle => + create2_apply hA hAo hAs hle (by simp) (by simp), hm1, ⟨fun k => rfl, ?_, ?_⟩, hb1, + by omega, hat', hrun'⟩ + · simpa using R.account + · exact logsRel_create _ _ _ _ R.logs + · -- A collision: 0 pushed, the creator's nonce grows. + refine ⟨0, .empty, st', { ss with + accessedAddresses := ss.accessedAddresses.insert (create2Address msg.currentTarget salt + (memoryReadBytes (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) + start.toNat size.toNat)) }, + memoryExtend M (extendMemory M.size [(start, size)]).expandBy, + g - cost2 M.size start size - createMessageGas .fusaka (g - cost2 M.size start size), m, + within', fun A'' hle => + create2_apply hA hAo hAs hle (by simp) (by simp), hm1, + ⟨fun k => rfl, account_incrementNonce hinc, logsRel_create _ _ _ _ R.logs⟩, + MemBudget.spend hb1 (by omega), by omega, hat', hrun'⟩ + · -- The init code ran as a callee. + obtain ⟨hacc, hlogs, hfit⟩ := hq caller mm child hP hinc2 hmc hmt hmcode hmv hmg + have hle1 := createMessageGas_le (g - cost2 M.size start size) + have hgas : g - cost2 M.size start size - createMessageGas .fusaka (g - cost2 M.size start size) + + child.gas ≤ g - cost2 M.size start size := by omega + refine ⟨if child.error.isNone then (create2Address msg.currentTarget salt (memoryReadBytes + (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) start.toNat size.toNat)).toU256 + else 0, if child.error.isNone then .empty else child.output, _, _, + memoryExtend M (extendMemory M.size [(start, size)]).expandBy, + g - cost2 M.size start size - createMessageGas .fusaka (g - cost2 M.size start size) + + child.gas, after, within', + fun A'' hle => create2_apply hA hAo hAs hle ?_ ?_, hm1, ⟨fun k => rfl, ?_, ?_⟩, + MemBudget.spend hb1 hgas, by omega, hat', hrun'⟩ + · split + · exact toU256_lt _ + · simp + · split + · simp + · exact hfit + · rw [incorporateChild_state] + exact hacc + · have hl : (incorporateChild .fusaka caller child).substate.logs.toList = ss.logs.toList := by + unfold incorporateChild + split + · rename_i hn + simp [Array.toList_append, hcsub, hlogs (by simpa using hn)] + · simp [hcsub] + obtain ⟨L, h1, h2⟩ := R.logs + refine ⟨L, by rw [hl, h1], ?_⟩ + simp only [postCreate, createWorld, List.filter_append] + simpa [isLogE] using h2 + +/-- **CALL with value as a cut of a run that succeeds**, from what the run gives the frame its +message ends with (`CallVQ`, at the caller state and callee code the CALL makes). -/ +theorem callValue_cutQ {code : ByteArray} {msg : Message .fusaka} {call : Call} {pc g G : Nat} + {M : ByteArray} {st : State.TransactionState} {ss ss0 : Substate} {rd : ByteArray} + {asked dst v i isz o osz : U256} {Tr : List U256} {s : State} {evm : Evm .fusaka Nat} + (base : Oracle) (T : RunTable) + (hm : MemRel s.memory M) (R : Rel msg ss0 st ss s) (hb : MemBudget G M g) (hG : G < 2 ^ 300) + (hat : At code msg pc (asked :: dst :: v :: i :: isz :: o :: osz :: Tr) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0xf1) (hv : v ≠ 0) + (hstatic : msg.isStatic = false) {calleeCode : ByteArray} + (hcode : st.getCode (st.getAccount (toAddressMasked dst)).codeHash = .ok calleeCode) + (hdel : delegatedAddress calleeCode = none) (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} (meets : Meets P runChild) + (hq : CallVQ msg P g st ss M asked dst v i isz o osz calleeCode) + (within : GasMeter.gasHeld evm.gas ≤ bound) {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) + (hoks : T.oks.length = sent s.world) (houts : T.outs.length = sent s.world) + (hsts : T.stores.length = sent s.world) (htrs : T.transients.length = sent s.world) : + ∃ (ok : Bool) (out : ByteArray) (s' : State) (st' : State.TransactionState) (ss' : Substate) + (M' : ByteArray) (g' : Nat) (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + (∀ T'', (pushCall T ok out (storeOf st' msg.currentTarget)).Le T'' → + Effect.apply (tableOracle base T'') call (.call .call) [asked, dst, v, i, isz, o, osz] s = + some (some (if ok then 1 else 0), s') ∧ RdRel (tableOracle base T'') s'.world out) ∧ + s'.world = callWorld s asked dst v i isz o osz ∧ + MemRel s'.memory M' ∧ Rel msg ss0 st' ss' s' ∧ MemBudget G M' g' ∧ g' ≤ g ∧ + At code msg (pc + 1) ((if ok then 1 else 0) :: Tr) M' g' st' ss' out m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + obtain ⟨hp, hcase⟩ := callValue_back hat hlt hbyte hv hstatic hcode hdel hdepth meets within hrun hok + have hp' : (callBaseCost .fusaka (decide (toAddressMasked dst ∉ ss.accessedAddresses)) + + callNewAccountCost .fusaka st (toAddressMasked dst) v + callValueCost .fusaka v) + + (extendMemory M.size [(i, isz), (o, osz)]).cost ≤ g := hp + obtain ⟨hb1, hb2, hbud, hfit⟩ := AssembleCallCut.budget_grow2 hmod hb hG hp' + have hbud0 : MemBudget G (memoryExtend M (extendMemory M.size [(i, isz), (o, osz)]).expandBy) + (g - (extendMemory M.size [(i, isz), (o, osz)]).cost) := by + have hc := extendMemory_cost M.size [(i, isz), (o, osz)] + rw [ceil32_of_mod hmod] at hc + have hmono := memoryGasCost_mono + (Nat.le_add_right M.size (extendMemory M.size [(i, isz), (o, osz)]).expandBy) + unfold MemBudget at hb ⊢ + rw [size_memoryExtend] + omega + -- The world with the call, and what every extension of a table with it answers there. + have hsent : sent (callWorld s asked dst v i isz o osz) = T.oks.length + 1 := by + simp [callWorld, hoks] + have hsame : ∀ (ok : Bool) (out : ByteArray) (sto : Word → Word) T'', + (pushCall T ok out sto).Le T'' → + Effect.apply (tableOracle base T'') call (.call .call) [asked, dst, v, i, isz, o, osz] s = + Effect.apply (tableOracle base (pushCall T ok out sto)) call (.call .call) + [asked, dst, v, i, isz, o, osz] s := by + intro ok out sto T'' hle + obtain ⟨r1, o1, s1, t1⟩ := table_call (base := base) hsent (by omega) (by omega) (by omega) hle + obtain ⟨r2, o2, s2, t2⟩ := table_call (base := base) hsent (by omega) (by omega) (by omega) + (RunTable.Le.refl (pushCall T ok out sto)) + have hrds : returndataSize (tableOracle base T'') (callWorld s asked dst v i isz o osz) = + returndataSize (tableOracle base (pushCall T ok out sto)) (callWorld s asked dst v i isz o osz) := by + rw [returndataSize_table, returndataSize_table, o1, o2] + have hrdb : returndataByte (tableOracle base T'') (callWorld s asked dst v i isz o osz) = + returndataByte (tableOracle base (pushCall T ok out sto)) (callWorld s asked dst v i isz o osz) := by + funext j + simp only [returndataByte, tableOracle, o1, o2] + simp + have hflag : callFlag (tableOracle base T'') (callWorld s asked dst v i isz o osz) = + callFlag (tableOracle base (pushCall T ok out sto)) (callWorld s asked dst v i isz o osz) := by + simp only [callFlag, r1, r2] + simp only [callWorld] at hrds hrdb hflag s1 s2 t1 t2 + simp only [Effect.apply, CallKind.shape, called, hflag, hrds, hrdb, s1, s2, t1, t2] + -- SolarTV's CALL under the table with the call's answers. + have heff : ∀ (ok : Bool) (out : ByteArray) (sto : Word → Word), out.size < 2 ^ 256 → + ∃ s', (∀ T'', (pushCall T ok out sto).Le T'' → + Effect.apply (tableOracle base T'') call (.call .call) [asked, dst, v, i, isz, o, osz] s = + some (some (if ok then 1 else 0), s') ∧ RdRel (tableOracle base T'') s'.world out) ∧ + s'.storage = sto ∧ s'.world = callWorld s asked dst v i isz o osz ∧ + MemRel s'.memory (memoryWrite (memoryExtend M + (extendMemory M.size [(i, isz), (o, osz)]).expandBy) + o.toNat (out.extract 0 (min osz.toNat out.size))) := by + intro ok out sto hsz + obtain ⟨r2, o2, s2, -⟩ := table_call (base := base) (ok := ok) (out := out) (sto := sto) hsent + (by omega) (by omega) (by omega) (RunTable.Le.refl _) + have hrd2 : RdRel (tableOracle base (pushCall T ok out sto)) (callWorld s asked dst v i isz o osz) out := by + have := rdRel_table base (pushCall T ok out sto) (callWorld s asked dst v i isz o osz) (by rw [o2]; exact hsz) + rwa [o2] at this + obtain ⟨s', happ, hsto, hw, hmem⟩ := call_effectO (o := tableOracle base (pushCall T ok out sto)) + (call := call) (ok := ok) hm hb1 hb2 (by simp only [callFlag, r2]; cases ok <;> simp) hrd2 + refine ⟨s', fun T'' hle => ⟨by rw [hsame ok out sto T'' hle, happ], ?_⟩, by rw [hsto, s2], hw, hmem⟩ + obtain ⟨-, o1, -, -⟩ := table_call (base := base) hsent (by omega) (by omega) (by omega) hle + have := rdRel_table base T'' (callWorld s asked dst v i isz o osz) (by rw [o1]; exact hsz) + rw [o1] at this + rw [hw] + exact this + rcases hcase with ⟨-, m, within', hat', hrun'⟩ | + ⟨-, caller, mm, child, after, within', hP, hcg, hcs, hcsub, hmg, hmc, hmt, hmcode, hmd, hmv, -, + hat', hrun'⟩ + · -- The frame lacks the value: no message. + obtain ⟨s', hall, hsto, hw, hmem⟩ := heff false .empty + (storeOf ((st.recordAccountRead (toAddressMasked dst)).recordAccountRead msg.currentTarget) + msg.currentTarget) (by simp) + have hw0 : memoryWrite (memoryExtend M (extendMemory M.size [(i, isz), (o, osz)]).expandBy) + o.toNat (ByteArray.empty.extract 0 (min osz.toNat ByteArray.empty.size)) = + memoryExtend M (extendMemory M.size [(i, isz), (o, osz)]).expandBy := by + simp [memoryWrite, ByteArray.size_extract] + rw [hw0] at hmem + refine ⟨false, .empty, s', _, { ss with + accessedAddresses := ss.accessedAddresses.insert (toAddressMasked dst) }, _, + g - ((mcgV g st ss M.size asked dst v i isz o osz).cost + + (extendMemory M.size [(i, isz), (o, osz)]).cost) + + (mcgV g st ss M.size asked dst v i isz o osz).subCall, m, within', + hall, hw, hmem, ⟨fun k => by rw [hsto]; rfl, by simpa using R.account, ?_⟩, + MemBudget.spend hbud0 (gas_after_le (asked := asked) hv hp le_rfl), + le_trans (gas_after_le (asked := asked) hv hp le_rfl) (Nat.sub_le _ _), + by simpa using hat', hrun'⟩ + rw [hw] + exact logsRel_call _ _ _ _ _ R.logs + · -- The callee ran. + obtain ⟨hacc, hlogs, hout⟩ := hq caller mm child hP hcs hmg hmc hmt hmcode hmd hmv + obtain ⟨s', hall, hsto, hw, hmem⟩ := heff child.error.isNone child.output + (storeOf (incorporateChild .fusaka caller child).state msg.currentTarget) hout + have hg2 := gas_after_le (asked := asked) hv hp (c := child.gas) (by rw [← hmg]; exact hcg) + refine ⟨child.error.isNone, child.output, s', _, _, _, + g - ((mcgV g st ss M.size asked dst v i isz o osz).cost + + (extendMemory M.size [(i, isz), (o, osz)]).cost) + child.gas, after, within', + hall, hw, hmem, ⟨fun k => by rw [hsto]; rfl, ?_, ?_⟩, ?_, by omega, hat', hrun'⟩ + · rw [incorporateChild_state] + exact hacc + · have hl : (incorporateChild .fusaka caller child).substate.logs.toList = ss.logs.toList := by + unfold incorporateChild + split + · rename_i hn + simp [Array.toList_append, hcsub, hlogs (by simpa using hn)] + · simp [hcsub] + obtain ⟨L, h1, h2⟩ := R.logs + refine ⟨L, by rw [hl, h1], ?_⟩ + rw [hw, callWorld, List.filter_append] + simpa [isLogE] using h2 + · unfold MemBudget + rw [size_memoryWrite_of_fit, size_memoryExtend] + · unfold MemBudget at hbud0 + rw [size_memoryExtend] at hbud0 + omega + · intro h + simp only [ByteArray.size_extract] at h ⊢ + have hz : osz ≠ 0 := by + intro hz + simp [hz] at h + have := hfit hz + rw [size_memoryExtend] + have := Nat.min_le_left osz.toNat child.output.size + omega + +/-- **CALL with no value as a cut of a run that succeeds**, from what the run gives the frame its +message ends with (`Call0Q`, at the caller state and code the CALL makes). -/ +theorem call0_cutQ {code : ByteArray} {msg : Message .fusaka} {call : Call} {pc g G : Nat} + {M : ByteArray} {st : State.TransactionState} {ss ss0 : Substate} {rd : ByteArray} + {asked addr inOff inSize outOff outSize : U256} {Tr : List U256} {s : State} + {evm : Evm .fusaka Nat} (base : Oracle) (T : RunTable) + (hm : MemRel s.memory M) (R : Rel msg ss0 st ss s) (hb : MemBudget G M g) (hG : G < 2 ^ 300) + (hat : At code msg pc (asked :: addr :: 0 :: inOff :: inSize :: outOff :: outSize :: Tr) M g st + ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0xf1) (hstatic : msg.isStatic = false) + (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} (meets : Meets P runChild) + (hq : Call0Q msg P st M addr inOff inSize outOff outSize) + (within : GasMeter.gasHeld evm.gas ≤ bound) {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) + (hoks : T.oks.length = sent s.world) (houts : T.outs.length = sent s.world) + (hsts : T.stores.length = sent s.world) (htrs : T.transients.length = sent s.world) : + ∃ (ok : Bool) (out : ByteArray) (s' : State) (st' : State.TransactionState) (ss' : Substate) + (M' : ByteArray) (g' : Nat) (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + (∀ T'', (pushCall T ok out (storeOf st' msg.currentTarget)).Le T'' → + Effect.apply (tableOracle base T'') call (.call .call) + [asked, addr, 0, inOff, inSize, outOff, outSize] s = + some (some (if ok then 1 else 0), s') ∧ RdRel (tableOracle base T'') s'.world out) ∧ + s'.world = callWorld s asked addr 0 inOff inSize outOff outSize ∧ + MemRel s'.memory M' ∧ Rel msg ss0 st' ss' s' ∧ MemBudget G M' g' ∧ g' ≤ g ∧ + At code msg (pc + 1) ((if ok then 1 else 0) :: Tr) M' g' st' ss' out m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + obtain ⟨calleeCode, route, hgc, -, hgp, caller, mm, child, after, within', g', hP, -, hcst, hcsub, hms, + hmv, hmc, hmt, -, hmd, -, -, -, hg', hat', hrun'⟩ := + call0_back hat hlt hbyte hstatic hdepth meets within hrun hok + obtain ⟨hb1, hb2, hbud, hfit⟩ := AssembleCallCut.budget_grow2 hmod hb hG hgp + obtain ⟨hacc, hlogs, hout⟩ := hq caller mm child hP hmt hmv hms hmd ⟨calleeCode, route, hgc, hcst, hmc⟩ + have hsent : sent (callWorld s asked addr 0 inOff inSize outOff outSize) = T.oks.length + 1 := by + simp [callWorld, hoks] + obtain ⟨s', hall, hsto, hw, hmem⟩ := call_answers (base := base) (call := call) hm hb1 hb2 hsent + (by omega) (by omega) (by omega) child.error.isNone child.output + (storeOf (incorporateChild .fusaka caller child).state msg.currentTarget) hout + refine ⟨child.error.isNone, child.output, s', _, _, _, g', after, within', hall, hw, hmem, + ⟨fun k => by rw [hsto]; rfl, ?_, ?_⟩, ?_, by omega, hat', hrun'⟩ + · rw [incorporateChild_state] + exact hacc + · have hl : (incorporateChild .fusaka caller child).substate.logs.toList = ss.logs.toList := by + unfold incorporateChild + split + · rename_i hn + have h0 := hlogs (by simpa using hn) + rcases route with _ | ⟨d, c'⟩ <;> simp [Array.toList_append, h0, hcsub, routeSub] + · rcases route with _ | ⟨d, c'⟩ <;> simp [hcsub, routeSub] + obtain ⟨L, h1, h2⟩ := R.logs + refine ⟨L, by rw [hl, h1], ?_⟩ + rw [hw, callWorld, List.filter_append] + simpa [isLogE] using h2 + · unfold MemBudget + rw [size_memoryWrite_of_fit, size_memoryExtend] + · omega + · intro h + simp only [ByteArray.size_extract] at h ⊢ + have hz : outSize ≠ 0 := by + intro hz + simp [hz] at h + have := hfit hz + rw [size_memoryExtend] + have := Nat.min_le_left outSize.toNat child.output.size + omega + + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateCutQ.call0_cutQ' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms call0_cutQ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateCutQ.callValue_cutQ' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms callValue_cutQ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateCutQ.create2_cutQ' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms create2_cutQ + +end SolidCore.Refinement.Solar.AssembleCreateCutQ diff --git a/SolidCore/Refinement/Solar/AssembleCreateExample.lean b/SolidCore/Refinement/Solar/AssembleCreateExample.lean new file mode 100644 index 00000000..57a5f919 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCreateExample.lean @@ -0,0 +1,126 @@ +import SolidCore.Refinement.Solar.AssembleCut + +/-! +# CALL with value, CODECOPY and CREATE2: the checker on an example and its mutants + +A program in one block that copies 8 bytes of its own code from offset 2 to memory at 0x80 +(CODECOPY, its destination a DUP of the free memory word over the known code offset), creates a +contract from them with CREATE2 and salt 0x2a, calls the new address with value 1 (CALL), and +returns the call's flag. The checker of code with calls and creations (`AssembleCut.checkCF`) +accepts its bytecode under a certificate that says the program makes calls and creates. + +Rejected by evaluation: the bytecode with salt 0x2b, the bytecode sending value 2, the bytecode +copying from code offset 3, the certificates that say the program does not create or makes no call, +the gated checker `AssembleCut.checkCB`, a program whose code offset is a call data word (not known +to the checker), and a program whose known code offset is 2 ^ 32. + +Scope: this is the checker only. The theorem over runs of programs `checkCF` accepts (the segment +proof with the run's tables of calls and creations, `createOracle (tableOracle base T) A`) is not +proved yet, so nothing here says the bytecode refines the program. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCreateExample + +open SolidCore.Refinement.Solar SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCut + +/-- The program, from its code offset, salt and call value. -/ +def progOf (off salt value : Assemble.Word) : Assemble.Program := + { blocks := [[.op (.stack (.push 0x80)), .op (.stack (.push 8)), .op (.stack (.push off)), + .op (.stack (.dup 2)), .effect .codecopy 3, + .op (.stack (.push salt)), .op (.stack (.push 8)), .op (.stack (.dup 2)), + .op (.stack (.push 0)), .effect .create2 4, + .op (.stack (.push 0)), .op (.stack (.push 0)), .op (.stack (.push 0)), .op (.stack (.push 0)), + .op (.stack (.push value)), .op (.stack (.dup 5)), .effect .gas 0, .effect (.call .call) 7, + .op (.stack (.push 0)), .op .store, .op (.stack (.push 32)), .op (.stack (.push 0)), .ret]] } + +def prog : Assemble.Program := progOf 2 0x2a 1 + +/-- The bytecode, from the bytes of its code offset, salt and call value. -/ +def codeOf (off salt value : UInt8) : ByteArray := + ⟨#[0x60, 0x80, 0x60, 0x08, 0x60, off, 0x82, 0x39, + 0x60, salt, 0x60, 0x08, 0x82, 0x5f, 0xf5, + 0x5f, 0x5f, 0x5f, 0x5f, 0x60, value, 0x85, 0x5a, 0xf1, + 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3]⟩ + +def code : ByteArray := codeOf 2 0x2a 1 + +def cert : Assemble.Cert := + { offsets := [0], needs := [0], top := 2 ^ 140, costs := [23], types := [[]], calls := true, + creates := true } + +def maxs : List Nat := [0] + +theorem check_ok : checkCF prog code cert maxs = true := by decide +kernel + +/-- The salt mutant: CREATE2 with salt 0x2b. -/ +theorem mutantSalt_fails : checkCF prog (codeOf 2 0x2b 1) cert maxs = false := by decide +kernel + +/-- The value mutant: the CALL sends 2. -/ +theorem mutantValue_fails : checkCF prog (codeOf 2 0x2a 2) cert maxs = false := by decide +kernel + +/-- The code offset mutant: CODECOPY from offset 3. -/ +theorem mutantOffset_fails : checkCF prog (codeOf 3 0x2a 1) cert maxs = false := by decide +kernel + +/-- A certificate that says the program does not create covers no CALL, CREATE2 or CODECOPY. -/ +theorem nocreates_fails : checkCF prog code { cert with creates := false } maxs = false := by + decide +kernel + +/-- Nor one that says it makes no call. -/ +theorem nocalls_fails : checkCF prog code { cert with calls := false } maxs = false := by + decide +kernel + +/-- The gated checker of code with STATICCALLs takes no program that creates. -/ +theorem gated_fails : checkCB prog code cert maxs = false := by decide +kernel + +/-- The code offset read from the call data: the checker does not know it, so it refuses the +CODECOPY (SolarTV's code read takes its index as a word and would wrap where EthLib reads zeros). -/ +def progDyn : Assemble.Program := + { blocks := [[.op (.stack (.push 0x80)), .op (.stack (.push 8)), .op (.stack (.push 4)), + .effect .calldataload 1, .op (.stack (.dup 2)), .effect .codecopy 3, .op (.stack (.push 0)), + .op (.stack (.push 0)), .ret]] } + +def codeDyn : ByteArray := + ⟨#[0x60, 0x80, 0x60, 0x08, 0x60, 0x04, 0x35, 0x82, 0x39, 0x5f, 0x5f, 0xf3]⟩ + +theorem dyn_fails : checkCF progDyn codeDyn { cert with costs := [9] } maxs = false := by + decide +kernel + +/-- With a pushed offset in place of the call data word the same shape passes, so `dyn_fails` fails at +the offset. -/ +def progDynK : Assemble.Program := + { blocks := [[.op (.stack (.push 0x80)), .op (.stack (.push 8)), .op (.stack (.push 4)), + .op (.stack (.dup 2)), .effect .codecopy 3, .op (.stack (.push 0)), + .op (.stack (.push 0)), .ret]] } + +def codeDynK : ByteArray := + ⟨#[0x60, 0x80, 0x60, 0x08, 0x60, 0x04, 0x82, 0x39, 0x5f, 0x5f, 0xf3]⟩ + +theorem dynK_ok : checkCF progDynK codeDynK { cert with costs := [8] } maxs = true := by + decide +kernel + +/-- A known code offset of 2 ^ 32 is refused. -/ +def progBig : Assemble.Program := + { blocks := [[.op (.stack (.push 0x80)), .op (.stack (.push 8)), + .op (.stack (.push (2 ^ 32))), .op (.stack (.dup 2)), .effect .codecopy 3, + .op (.stack (.push 0)), .op (.stack (.push 0)), .ret]] } + +def codeBig : ByteArray := + ⟨#[0x60, 0x80, 0x60, 0x08, 0x64, 0x01, 0x00, 0x00, 0x00, 0x00, 0x82, 0x39, 0x5f, 0x5f, 0xf3]⟩ + +theorem big_fails : checkCF progBig codeBig { cert with costs := [8] } maxs = false := by + decide +kernel + +/-- One below it passes, so `big_fails` fails at the offset. -/ +def progSmall : Assemble.Program := + { blocks := [[.op (.stack (.push 0x80)), .op (.stack (.push 8)), + .op (.stack (.push (2 ^ 32 - 1))), .op (.stack (.dup 2)), .effect .codecopy 3, + .op (.stack (.push 0)), .op (.stack (.push 0)), .ret]] } + +def codeSmall : ByteArray := + ⟨#[0x60, 0x80, 0x60, 0x08, 0x63, 0xff, 0xff, 0xff, 0xff, 0x82, 0x39, 0x5f, 0x5f, 0xf3]⟩ + +theorem small_ok : checkCF progSmall codeSmall { cert with costs := [8] } maxs = true := by + decide +kernel + +end SolidCore.Refinement.Solar.AssembleCreateExample diff --git a/SolidCore/Refinement/Solar/AssembleCreateRun.lean b/SolidCore/Refinement/Solar/AssembleCreateRun.lean new file mode 100644 index 00000000..08a8c511 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCreateRun.lean @@ -0,0 +1,306 @@ +import SolidCore.Refinement.Solar.AssembleCreateCut + +/-! +# Segments of a run with calls and creations read the same under every longer table + +A run that makes CALLs and CREATE2s is read back segment by segment under the oracle of its two +tables, `createOracle (tableOracle base T) A`: the run's table `T` of GAS reads and message answers +(indexed by the messages a world sent) and the table `A` of its creations (indexed by the creations +a world made). `AssembleCut.Agree` bounds the worlds it compares by GAS reads and messages only, which +does not bound the creations; but between two cuts a segment never changes its world (every effect that +adds an event is a cut, `apply_world_eq`), so it reads only the world it starts in and the empty one +(`execC_agreeW`). Every extension of both tables answers there as they do (`createTable_agree`), so +every extension runs the segment to the same end (`exec_F`), which a segment proof of runs with +creations needs, as `AssembleCut.exec_O` is for `AssembleCut.seg`. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCreateRun + +open SolarTV SolarTV.Machine +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCut SolidCore.Refinement.Solar.RunOracle +open SolidCore.Refinement.Solar.AssembleCreateSeg + +/-- An effect that stops no segment leaves the world as it was. -/ +theorem apply_world_eq {o : Oracle} {call : Call} {e : Effect} (he : cutEffect e = false) + {args : List Word} {s s' : State} {r : Option Word} + (h : Effect.apply o call e args s = some (r, s')) : s'.world = s.world := by + unfold Effect.apply at h + split at h <;> (try split at h) <;> simp_all [cutEffect] + all_goals (obtain ⟨-, rfl⟩ := h; simp) + +/-- An effect that stops no segment answers the same under oracles that agree at its world and the +empty one. -/ +theorem apply_congrW {o1 o2 : Oracle} (hk : o1.keccak = o2.keccak) (hc : o1.caller = o2.caller) + (h0 : ∀ name a, o1.env name [] a = o2.env name [] a) {call : Call} {e : Effect} + (he : cutEffect e = false) {args : List Word} {s : State} + (hw : ∀ name a, o1.env name s.world a = o2.env name s.world a) : + Effect.apply o1 call e args s = Effect.apply o2 call e args s := by + unfold Effect.apply + split <;> simp_all [cutEffect, returndataSize, returndataByte, codeByte, immutableWord, + immutableValue] + +/-- **A segment runs the same under oracles that agree at its world** (and the empty one). -/ +theorem execC_agreeW {o1 o2 : Oracle} (hk : o1.keccak = o2.keccak) (hc : o1.caller = o2.caller) + (h0 : ∀ name a, o1.env name [] a = o2.env name [] a) (call : Call) (b : Nat) : + ∀ (is : List Assemble.Instr) (S : List Word) (s : State), + (∀ name a, o1.env name s.world a = o2.env name s.world a) → + execC o1 call b is S s = execC o2 call b is S s + | [], _, _, _ => rfl + | .op op :: rest, S, s, hw => by + by_cases hcut : cutOp op = true + · simp only [execC, hcut, ite_true] + have hcut' : cutOp op = false := by simpa using hcut + have hctx : SolarTV.EVM.Program.context o1 call s = SolarTV.EVM.Program.context o2 call s := by + simp [SolarTV.EVM.Program.context, hw] + cases h : SolarTV.EVM.Program.stepOp (SolarTV.EVM.Program.context o2 call s) op S s.memory with + | error _ => simp only [execC, hctx, h, hcut', Bool.false_eq_true, ite_false] + | ok r => + obtain ⟨S', m⟩ := r + simp only [execC, hctx, h, hcut', Bool.false_eq_true, ite_false] + exact execC_agreeW hk hc h0 call b rest S' { s with memory := m } hw + | .effect e a :: rest, S, s, hw => by + by_cases hcut : cutEffect e = true + · simp only [execC, hcut, ite_true] + have he : cutEffect e = false := by simpa using hcut + by_cases hl : S.length < a + · simp only [execC, hcut, hl, Bool.false_eq_true, ite_false, ite_true] + cases happ : Effect.apply o2 call e (S.take a) s with + | none => + simp only [execC, hcut, hl, Bool.false_eq_true, ite_false, apply_congrW hk hc h0 he hw, happ] + | some r => + obtain ⟨res, s1⟩ := r + have hw1 : ∀ name a, o1.env name s1.world a = o2.env name s1.world a := by + rw [apply_world_eq he happ] + exact hw + simp only [execC, hcut, hl, Bool.false_eq_true, ite_false, apply_congrW hk hc h0 he hw, happ] + split_ifs + · rfl + · exact execC_agreeW hk hc h0 call b rest _ s1 hw1 + | .jump t :: rest, S, s, _ => by simp only [execC] + | .jumpi t :: rest, S, s, hw => by + cases S with + | nil => simp only [execC] + | cons x S => + simp only [execC] + split_ifs + · rfl + · exact execC_agreeW hk hc h0 call b rest S s hw + · rfl + | .pushLabel t :: rest, S, s, hw => by + simp only [execC] + split_ifs + · rfl + · exact execC_agreeW hk hc h0 call b rest _ s hw + | .jumpDyn :: rest, S, s, _ => rfl + | .jumpiDyn :: rest, S, s, hw => by + match S with + | [] => rfl + | [_] => rfl + | x :: y :: S => + simp only [execC] + split_ifs + · exact execC_agreeW hk hc h0 call b rest S s hw + · rfl + | .jumpTable ts :: rest, S, s, _ => rfl + | .stop :: rest, S, s, _ => rfl + | .ret :: rest, S, s, _ => rfl + | .revert :: rest, S, s, _ => rfl + | .invalid :: rest, S, s, _ => rfl + +/-- A world whose last message is a creation made one. -/ +theorem creates_pos_of_lastCreate {w : List Event} (h : lastCreate w = true) : 0 < creates w := by + cases hl : (w.filter Event.sends).getLast? with + | none => simp [lastCreate, hl] at h + | some e => + have hm : e ∈ w.filter Event.sends := by + first + | exact List.mem_of_getLast? hl + | exact List.mem_of_getLast?_eq_some hl + | exact List.getLast?_mem hl + have hc : isCreateE e = true := by + cases e <;> simp_all [lastCreate, isCreateE] + unfold creates + exact List.length_pos_of_mem (List.mem_filter.2 ⟨(List.mem_filter.1 hm).1, hc⟩) + +/-- **The oracle of two tables and of any extensions of both agree** at every world with no more GAS +reads, messages and creations than the tables answer. -/ +theorem createTable_agree (base : Oracle) {T T'' : RunTable} {A A'' : CreateTable} (hT : T.Le T'') + (hA : A.Le A'') {w : List Event} (hg : gasReads w ≤ T.gases.length) (hs : sent w ≤ T.outs.length) + (hc : creates w ≤ A.outs.length) (name : String) (a : List Word) : + (createOracle (tableOracle base T) A).env name w a = + (createOracle (tableOracle base T'') A'').env name w a := by + have ht : ∀ name a, (tableOracle base T).env name w a = (tableOracle base T'').env name w a := + (table_agree base hT (ng := T.gases.length) (ns := T.outs.length) le_rfl le_rfl).2.2 w hg hs + by_cases hl : lastCreate w = true + · have hout : A.out w = A''.out w := by + have := creates_pos_of_lastCreate hl + unfold CreateTable.out + exact (AssembleRun.getD_of_prefix hA.2.1 (by omega) _).symm + simp only [createOracle, hl, ite_true, ↓reduceIte, hout, ht] + · simp only [createOracle, hl, Bool.false_eq_true, ite_false, ↓reduceIte, ht] + +/-- **Every extension of both tables runs a segment to the same end** as the tables do. -/ +theorem exec_F {base : Oracle} {T T'' : RunTable} {A A'' : CreateTable} (hT : T.Le T'') + (hA : A.Le A'') {call : Call} {b : Nat} {is : List Assemble.Instr} {S : List Word} {s : State} + (hg : gasReads s.world ≤ T.gases.length) (hs : sent s.world ≤ T.outs.length) + (hc : creates s.world ≤ A.outs.length) : + SolarTV.EVM.Program.exec (createOracle (tableOracle base T'') A'') call b is S s = + match execC (createOracle (tableOracle base T) A) call b is S s with + | .done r => r + | .cut i rest S' s' => + SolarTV.EVM.Program.exec (createOracle (tableOracle base T'') A'') call b (i :: rest) S' s' := by + rw [exec_eq_execC, execC_agreeW (o1 := createOracle (tableOracle base T'') A'') + (o2 := createOracle (tableOracle base T) A) rfl rfl + (fun name a => (createTable_agree base hT hA (w := []) (by simp [gasReads]) (by simp [sent]) + (by simp [creates]) name a).symm) call b is S s + (fun name a => (createTable_agree base hT hA hg hs hc name a).symm)] + rfl + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateRun.exec_F' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms exec_F + +/-! ## The oracle of a run with creations -/ + +/-- What the oracle of a run with creations answers that the run does not decide: the frame's code +(`AssembleCodeCopy.codeOracle`), EthLib's caller, hash and environment, and every other call fails. -/ +def baseF (code : ByteArray) : Oracle := AssembleCodeCopy.codeOracle code base0 + +/-- **The oracle of a run with creations**: GAS reads and message answers from the run's table, +creations from the creation table, the frame's code and EthLib's caller, hash and environment. -/ +abbrev FO (code : ByteArray) (T : RunTable) (A : CreateTable) : Oracle := + createOracle (tableOracle (baseF code) T) A + +/-- It reads the frame's code, which `AssembleCreateSeg.codecopy_cut` needs. -/ +theorem FO_codeOk (code : ByteArray) (T : RunTable) (A : CreateTable) : + AssembleCodeCopy.CodeOk (FO code T A) code := + codeOk_createOracle A (codeOk_tableOracle T (AssembleCodeCopy.codeOracle_ok code base0)) + +/-- It meets what every certificate asks of an oracle. -/ +theorem FO_ok (c : Cert) (code : ByteArray) (T : RunTable) (A : CreateTable) : + CertOk c (FO code T A) := by + refine ⟨fun _ => ethOracle_ok Witness.failOracle, fun _ => ?_⟩ + intro name byte w he world + have hn : name ≠ "returndatasize" ∧ name ≠ "returndata" ∧ name ≠ "gas" ∧ name ≠ "code" := by + unfold envRead at he + refine ⟨?_, ?_, ?_, ?_⟩ <;> (rintro rfl; simp at he) + simp only [FO, baseF, createOracle, tableOracle, AssembleCodeCopy.codeOracle, hn.1, hn.2.1, + hn.2.2.1, hn.2.2.2, false_and, ite_false, ite_self] + exact envOracle_ok _ name byte w he world + +/-- The `k`-th GAS read pushes the table's `k`-th gas. -/ +theorem FO_gas (code : ByteArray) (T : RunTable) (A : CreateTable) (w : List Event) : + (FO code T A).env "gas" (w ++ [.read "gas"]) [] = BitVec.ofNat 256 (T.gases.getD (gasReads w) 0) := by + rw [← gas_table (baseF code) T w] + simp [FO, createOracle] + +/-- GAS under the oracle of tables whose next gas is `v`. -/ +theorem exec_gasF {code : ByteArray} {T : RunTable} {A : CreateTable} {call : Call} {b : Nat} + {rest : List Assemble.Instr} {S : List Word} {s : State} {v : Nat} + (hT : T.gases.getD (gasReads s.world) 0 = v) (hS : S.length < 1024) : + SolarTV.EVM.Program.exec (FO code T A) call b (.effect .gas 0 :: rest) S s = + SolarTV.EVM.Program.exec (FO code T A) call b rest (BitVec.ofNat 256 v :: S) + { s with world := s.world ++ [.read "gas"] } := by + have happ : Effect.apply (FO code T A) call .gas [] s = + some (some (BitVec.ofNat 256 v), { s with world := s.world ++ [.read "gas"] }) := by + simp only [Effect.apply] + rw [FO_gas, hT] + simp [SolarTV.EVM.Program.exec, happ, show ¬ 1024 < S.length + 1 by omega] + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateRun.FO_ok' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms FO_ok + +/-! ## The tables of a run with creations, along its world -/ + +theorem sends_call (k : CallKind) (ops : List Word) (i : List Memory.Byte) (sto tr : Word → Word) : + (List.filter Event.sends [Event.call k ops i sto tr]).length = 1 := rfl + +theorem sends_create (ops : List Word) (c : List Memory.Byte) (sto tr : Word → Word) : + (List.filter Event.sends [Event.create ops c sto tr]).length = 1 := rfl + +/-- **The run's tables match its world**: one gas per GAS read, one entry of the run table per +message (calls and creations alike), one entry of the creation table per creation. -/ +def TabF (T : RunTable) (A : CreateTable) (w : List Event) : Prop := + T.gases.length = gasReads w ∧ T.oks.length = sent w ∧ T.outs.length = sent w ∧ + T.stores.length = sent w ∧ T.transients.length = sent w ∧ A.addrs.length = creates w ∧ + A.outs.length = creates w ∧ A.stores.length = creates w + +theorem TabF.log {T : RunTable} {A : CreateTable} {w : List Event} (h : TabF T A w) + (t : List Word) (d : List Memory.Byte) : TabF T A (w ++ [.log t d]) := by + simpa [TabF, gasReads, sent, Event.sends, Event.readsGas, List.filter_append] using h + +/-- A GAS read adds the gas it pushed to the run table. -/ +theorem TabF.gas {T : RunTable} {A : CreateTable} {w : List Event} (h : TabF T A w) (v : Nat) : + TabF { T with gases := T.gases ++ [v] } A (w ++ [.read "gas"]) := by + obtain ⟨h1, h2⟩ := h + refine ⟨?_, by simpa [sent, Event.sends, List.filter_append] using h2⟩ + simp [gasReads, Event.readsGas, List.filter_append] at h1 ⊢ + omega + +/-- A CALL adds its entry to the run table. -/ +theorem TabF.call {T : RunTable} {A : CreateTable} {w : List Event} (h : TabF T A w) (ok : Bool) + (out : ByteArray) (sto : Word → Word) (k : CallKind) (ops : List Word) (i : List Memory.Byte) + (sto' tr : Word → Word) : + TabF (AssembleCallValueSeg.pushCall T ok out sto) A (w ++ [.call k ops i sto' tr]) := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8⟩ := h + have hs : sent (w ++ [.call k ops i sto' tr]) = sent w + 1 := by + simp only [sent, List.filter_append, List.length_append, sends_call] + have hg : gasReads (w ++ [.call k ops i sto' tr]) = gasReads w := by + simp [gasReads, Event.readsGas, List.filter_append] + have hc : creates (w ++ [.call k ops i sto' tr]) = creates w := by + simp [creates, isCreateE, List.filter_append] + simp only [TabF, AssembleCallValueSeg.pushCall, List.length_append, List.length_singleton, hs, hg, + hc] + omega + +/-- A CREATE2 adds its entry to the creation table, and one to the run table at its message, whose +transient storage after it is the only answer the oracle reads from there. -/ +theorem TabF.create {T : RunTable} {A : CreateTable} {w : List Event} (h : TabF T A w) (r : Word) + (out : ByteArray) (sto : Word → Word) (ops : List Word) (c : List Memory.Byte) + (sto' tr : Word → Word) : + TabF (AssembleCallValueSeg.pushCall T false .empty (fun _ => 0)) (A.push r out sto) + (w ++ [.create ops c sto' tr]) := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8⟩ := h + have hs : sent (w ++ [.create ops c sto' tr]) = sent w + 1 := by + simp only [sent, List.filter_append, List.length_append, sends_create] + have hg : gasReads (w ++ [.create ops c sto' tr]) = gasReads w := by + simp [gasReads, Event.readsGas, List.filter_append] + simp only [TabF, AssembleCallValueSeg.pushCall, CreateTable.push, List.length_append, + List.length_singleton, hs, hg, creates_create] + omega + +/-- Every extension of a run table answers the transient storage after a message the table holds +as the table does. -/ +theorem table_transient {base : Oracle} {T1 T'' : RunTable} (hle : T1.Le T'') {w : List Event} + (hw : sent w ≤ T1.transients.length) : + (tableOracle base T'').transientAfter w = (tableOracle base T1).transientAfter w := by + simp only [tableOracle] + split_ifs with h + · rfl + · exact AssembleRun.getD_of_prefix hle.2.2.2.1 (by omega) _ + +/-- **SolarTV's CREATE2 reads the run table only for the transient storage after it**, so every +extension of a run table holding the creation's message answers it as that table does. -/ +theorem create2_table {base : Oracle} {T1 T'' : RunTable} (hle : T1.Le T'') {A : CreateTable} + {call : Call} {s : State} {value start size salt : Word} + (hsent : sent s.world < T1.transients.length) (hA : creates s.world < A.stores.length) : + Effect.apply (createOracle (tableOracle base T'') A) call .create2 [value, start, size, salt] s = + Effect.apply (createOracle (tableOracle base T1) A) call .create2 [value, start, size, salt] s := by + have key := table_transient (base := base) hle (w := s.world ++ [.create [value, salt] + ((s.memory.expand start.toNat size.toNat).read start.toNat size.toNat) s.storage s.transient]) + (by simp only [sent, List.filter_append, List.length_append, sends_create] at hsent ⊢; omega) + have key2 : ∀ d1 d2 : Word → Word, A.stores.getD (creates s.world) d1 = + A.stores.getD (creates s.world) d2 := fun d1 d2 => by + simp [List.getD_eq_getElem?_getD, List.getElem?_eq_getElem hA] + simp only [Effect.apply, created, createOracle, lastCreate_create, ite_true, ↓reduceIte, key, + creates_create, Nat.add_sub_cancel, Option.some.injEq, Prod.mk.injEq, State.mk.injEq, true_and, + and_true] + exact key2 _ _ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateRun.create2_table' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms create2_table + +end SolidCore.Refinement.Solar.AssembleCreateRun diff --git a/SolidCore/Refinement/Solar/AssembleCreateRunF.lean b/SolidCore/Refinement/Solar/AssembleCreateRunF.lean new file mode 100644 index 00000000..01b4c2e1 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCreateRunF.lean @@ -0,0 +1,482 @@ +import SolidCore.Refinement.Solar.AssembleCreateSegF +import SolidCore.Refinement.Solar.AssembleCreateExample + +/-! +# EVM IR to bytecode, run by run, for code with CALLs, CREATE2s and CODECOPYs + +`AssembleCreateSegF.segF` reads a block back from a run that succeeds under the oracle of the run's two +tables (`AssembleCreateRun.FO`): the run table of GAS reads and messages, and the creation table. +`within_of_advancesF` is `AssembleCallSeg.within_of_advancesQ` over the pair of tables (`Tabs`), with an +assumption on the runner of messages that may name the runner (`RunOut`: the frames it returns), and +`runs_of_checkCF` is the per-run theorem for every program the checker with calls and creations +(`AssembleCut.checkCF`) accepts, under the named hypothesis `SitesRun` on the run. + +Scope: the runtime code of one frame, as the other assembly theorems; the source side of CALL and +CREATE2 (a world answering them, `RunOracle.CallsAgree`) is not covered, so the composition with the +source's specification is stated at EVM IR (`holds_of_checkCF`), not at SolidCore. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCreateRunF + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Witness SolidCore.Refinement.Final +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.RunOracle +open SolidCore.Refinement.Solar.AssembleCut SolidCore.Refinement.Solar.AssembleEffects +open SolidCore.Refinement.Solar.AssembleLoop SolidCore.Refinement.Solar.AssembleRun +open SolidCore.Refinement.Solar.AssembleRunLoop +open SolidCore.Refinement.Solar.AssembleCall SolidCore.Refinement.Solar.AssembleCallSeg +open SolidCore.Refinement.Solar.AssembleCreateSeg SolidCore.Refinement.Solar.AssembleCreateRun +open SolidCore.Refinement.Solar.AssembleCreateSegF +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +/-! ## The tables of a run with creations -/ + +/-- The two tables of a run with creations. -/ +structure Tabs where + run : RunTable := {} + cre : CreateTable := {} + +/-- Tables that answer everything the shorter ones do, the same. -/ +def Tabs.Le (a b : Tabs) : Prop := a.run.Le b.run ∧ a.cre.Le b.cre + +theorem Tabs.Le.refl (a : Tabs) : a.Le a := ⟨RunTable.Le.refl _, CreateTable.Le.refl _⟩ + +theorem Tabs.Le.trans {a b c : Tabs} (h1 : a.Le b) (h2 : b.Le c) : a.Le c := + ⟨h1.1.trans h2.1, h1.2.trans h2.2⟩ + +/-- The frames a runner of messages returns. -/ +def RunOut {bound : Nat} (runChild : MessageRunner .fusaka Nat bound) (caller : Evm .fusaka Nat) + (m : Message .fusaka) (child : Evm .fusaka Nat) : Prop := + ∃ lt ended, runChild caller m lt = .ok ended ∧ ended.val = child + +/-- EthLib's runner of messages meets the assumption that names its frames. -/ +theorem meets_runOut (bound : Nat) : + Meets (bound := bound) (RunOut (processRunner .fusaka (Meter := Nat) bound)) + (processRunner .fusaka (Meter := Nat) bound) := + ⟨fun _ _ lt e h => ⟨lt, e, h, rfl⟩, (meets_static bound).aborts⟩ + +/-! ## Runs under a runner meeting an assumption that names it, over two tables -/ + +section BlocksF + +variable {σ : Type} (blk : Oracle → σ → Option ((Halt × Machine.State) ⊕ σ)) + (O : Tabs → Oracle) + +/-- **One block of the simulation, read back from a run that succeeds**, as +`AssembleCall.AdvancesS` under every runner of messages meeting `P`, for the runs to a frame `fin` +that meet the hypothesis `Q`. -/ +def AdvancesF (P : (bound : Nat) → MessageRunner .fusaka Nat bound → Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop) + (Q : (bound : Nat) → MessageRunner .fusaka Nat bound → Evm .fusaka Nat → Prop) + (E : Tabs → σ → Evm .fusaka Nat → Prop) + (Post : Halt × Machine.State → Evm .fusaka Nat → Prop) (meas : σ → Evm .fusaka Nat → Nat) + (T : Tabs) (x : σ) (evm : Evm .fusaka Nat) : Prop := + ∀ (bound : Nat) (runChild : MessageRunner .fusaka Nat bound), Meets (P bound runChild) runChild → + ∀ (within : GasMeter.gasHeld evm.gas ≤ bound) (fin : Evm .fusaka Nat), + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + fin.error = none → Q bound runChild fin → + ∃ T' r, Tabs.Le T T' ∧ (∀ T'', T'.Le T'' → blk (O T'') x = some r) ∧ + (∀ res, r = .inl res → Post res fin) ∧ + (∀ y, r = .inr y → ∃ after within', E T' y after ∧ meas y after < meas x evm ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild after within' = .ok fin) + +/-- A run of EthLib that ends with no error and meets the hypothesis is SolarTV's, for every table +extending the last one the run grew. -/ +theorem run_of_advancesF {P : (bound : Nat) → MessageRunner .fusaka Nat bound → Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} + {Q : (bound : Nat) → MessageRunner .fusaka Nat bound → Evm .fusaka Nat → Prop} + {E : Tabs → σ → Evm .fusaka Nat → Prop} + {Post : Halt × Machine.State → Evm .fusaka Nat → Prop} {meas : σ → Evm .fusaka Nat → Nat} + (adv : ∀ T x evm, E T x evm → AdvancesF blk O P Q E Post meas T x evm) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + (meets : Meets (P bound runChild) runChild) : + ∀ (n : Nat) (T : Tabs) (x : σ) (evm : Evm .fusaka Nat) + (within : GasMeter.gasHeld evm.gas ≤ bound) (fin : Evm .fusaka Nat), + E T x evm → meas x evm < n → + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + fin.error = none → Q bound runChild fin → + ∃ T' res, Tabs.Le T T' ∧ + (∀ T'', T'.Le T'' → ∃ k, SolarTV.Machine.iterate (blk (O T'')) k x = some res) ∧ + Post res fin + | 0, _, _, _, _, _, _, h, _, _, _ => absurd h (Nat.not_lt_zero _) + | n + 1, T, x, evm, within, fin, hE, hm, hrun, hok, hq => by + obtain ⟨T', r, hle, hstep, hinl, hinr⟩ := + adv T x evm hE bound runChild meets within fin hrun hok hq + cases r with + | inl res => + exact ⟨T', res, hle, fun T'' h => ⟨1, by simp [SolarTV.Machine.iterate, hstep T'' h]⟩, + hinl res rfl⟩ + | inr y => + obtain ⟨after, within', hE', hm', hrun'⟩ := hinr y rfl + obtain ⟨T2, res, hle2, hit, hpost⟩ := + run_of_advancesF adv meets n T' y after within' fin hE' (by omega) hrun' hok hq + refine ⟨T2, res, hle.trans hle2, fun T'' h => ?_, hpost⟩ + obtain ⟨k, hk⟩ := hit T'' h + exact ⟨k + 1, by simp [SolarTV.Machine.iterate, hstep T'' (hle2.trans h), hk]⟩ + +end BlocksF + +section Runs + +open EthLib.Execution.State + +open SolarTV.EVM.Program SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Evm.Symex in +/-- **EVM IR to bytecode at the given gas, run by run, from a block simulation**: when every frame +related to a block state (`E`, from the substate the frame started with) advances (`Advances`) to +an end SolarTV's halt shows (`PostL`) or to the next block, and the frame a call starts with is +related to SolarTV's initial state, then the oracle of the run's table makes every result of the +bytecode on the call the EVM IR's or a failure that changes nothing. -/ +theorem within_of_advancesF {p : Assemble.Program} {code : ByteArray} {call : Call} {gas : Nat} + (O : Tabs → Oracle) (P : (bound : Nat) → MessageRunner .fusaka Nat bound → Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop) + (Q : (bound : Nat) → MessageRunner .fusaka Nat bound → Evm .fusaka Nat → Prop) + (E : Substate → Tabs → Nat × List Word × Machine.State → Evm .fusaka Nat → Prop) + (meas : Nat × List Word × Machine.State → Evm .fusaka Nat → Nat) + (hP : Meets (P _ (processRunner .fusaka (Meter := Nat) (Final.Target.messageWith gas code call).gas)) (processRunner .fusaka (Meter := Nat) (Final.Target.messageWith gas code call).gas)) + (hQ : ∀ r, processMessage (Meter := Nat) .fusaka (Final.Target.messageWith gas code call) + (SolidCore.Refinement.Target.preState code call) Substate.empty = .ok r → r.1.error = none → + Q _ (processRunner .fusaka (Meter := Nat) (Final.Target.messageWith gas code call).gas) r.1) + (start : ∀ st' ss', Rel (Final.Target.messageWith gas code call) ss' st' ss' + (Machine.State.initial call) → + E ss' {} (0, [], Machine.State.initial call) + (startFrame (Final.Target.messageWith gas code call) st' ss' gas)) + (adv : ∀ ss0 T x evm, E ss0 T x evm → AdvancesF (fun o => block o call p) O P Q (E ss0) + (fun res => PostL call (Final.Target.messageWith gas code call).currentTarget ss0 res.2 res.1) + meas T x evm) : + ∃ T, Within (evmirSem (O T)) (ethLibWith gas) p code (· = call) := by + by_cases hs : ∃ obs, Target.runWith gas code call = some obs ∧ obs.success = true + swap + · refine ⟨{}, fun call' hc obs hrun => Or.inr ?_⟩ + subst hc + have hf : obs.success = false := by + cases h : obs.success + · rfl + · exact absurd ⟨obs, hrun, h⟩ hs + exact ⟨hf, Target.runWith_failure hrun hf⟩ + obtain ⟨obs, hrun, hsucc⟩ := hs + suffices H : ∃ T, (evmirSem (O T)).run p call = some obs by + obtain ⟨T, hT⟩ := H + refine ⟨T, fun call' hc obs' hrun' => Or.inl ?_⟩ + subst hc + change Target.runWith gas code call' = some obs' at hrun' + rw [hrun] at hrun' + cases hrun' + exact hT + unfold Target.runWith Target.runMsg at hrun + split at hrun + · cases hrun + rename_i evm hev hpm + simp only [Option.some.injEq] at hrun + subst hrun + have hok : evm.error = none := by simpa using hsucc + obtain ⟨st', ss', within, hcases, hmove, hrf⟩ := + AssembleRun.processMessage_ok' (message := Final.Target.messageWith gas code call) (evm := ⟨evm, hev⟩) + (precompileAddress_message code call) hpm hok + simp only at hrf + have R := AssembleLoop.rel_start code call gas ss' (fun h => (hcases h).1) (fun h => (hmove h).1) + obtain ⟨T, ⟨halt, sF⟩, -, hit, hpost⟩ := run_of_advancesF (fun o => block o call p) O (adv ss') + hP _ {} _ _ within evm (start st' ss' R) (Nat.lt_succ_self _) hrf hok (hQ _ hpm hok) + obtain ⟨k, hk⟩ := hit T (Tabs.Le.refl T) + refine ⟨T, ?_⟩ + have hres : (evmirSem (O T)).run p call = some (observe call sF halt) := by + change (SolarTV.EVM.Program.layer.result (O T) p call).map _ = _ + rw [SolarTV.EVM.Program.layer.result_of_ends ⟨k, hk⟩] + rfl + rw [hres] + set msg := Final.Target.messageWith gas code call with hmsg + obtain ⟨ssF, ⟨herr, hout, hlogsF, hst⟩, L, hL1, hL2⟩ := hpost + have hss' : ss'.logs.toList = [] := by + by_cases htr : msg.shouldTransferValue = true ∧ msg.value ≠ 0 + · rw [(hmove htr).2] + simp [pushTransferLog, show ¬ (Fork.fusaka ≥ Fork.glamsterdam) by decide, Substate.empty] + · rw [(hcases htr).2] + simp [Substate.empty] + have hlogs := logs_of_match hL2 + have hL1' : ssF.logs.toList = L := by rw [hL1, hss', List.nil_append] + have herr' : evm.error = errorOf (observe call sF halt) := herr + have hout' : evm.output.toList.map (·.toNat) = (observe call sF halt).output := hout + have hst' : (observe call sF halt).success = true → + evm.substate.logs = ssF.logs ∧ ∀ slot, + (evm.state.getStorage (Target.address selfAddress) (Target.storageKey slot)).toNat = + (observe call sF halt).storage slot := + fun h => ⟨hlogsF, hst h⟩ + have hfail : (observe call sF halt).success = false → + (observe call sF halt).logs = [] ∧ + (observe call sF halt).storage = slotValue call.storage := by + cases halt <;> simp [observe] + have hok2 : (observe call sF halt).success = true → + (observe call sF halt).logs = logs sF := by + cases halt <;> simp [observe] + clear herr hout hst hres hit hk + generalize observe call sF halt = X at * + have hsucc' : evm.error.isNone = X.success := by + rw [herr']; cases hX : X.success <;> simp [errorOf, hX] + symm + congr 1 + cases X with + | mk success output logs storage => + simp only at hsucc' hout' hfail hok2 hst' ⊢ + rw [SolarTV.Observable.mk.injEq] + refine ⟨hsucc', hout', ?_, ?_⟩ + · rw [hsucc'] + cases hs : success + · simp [hok, hs] at hsucc' + · simp only [ite_true] + rw [(hst' hs).1, hL1', hlogs, hok2 hs] + rfl + · funext slot + rw [hsucc'] + cases hs : success + · simp [hok, hs] at hsucc' + · simp only [ite_true] + exact (hst' hs).2 slot + + +end Runs + +/-! ## The checker with calls and creations -/ + +theorem globC_of_checkCF {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (h : checkCF p code c mx = true) : + GlobC p c mx code ∧ Seg (bytesOf code) c.offset 0 (lower p c) code.size ∧ c.need 0 = 0 := by + simp only [checkCF, Bool.and_eq_true, decide_eq_true_eq] at h + obtain ⟨⟨⟨⟨⟨⟨hw, hblocks⟩, hlabels⟩, hneed⟩, hmod⟩, htop⟩, hsize⟩ := h + obtain ⟨stream, hw⟩ := Option.isSome_iff_exists.1 hw + have hseg : Seg (bytesOf code) c.offset 0 (lower p c) code.size := by + have := seg_of_walk (walk_sound hw) + rwa [length_bytesOf] at this + refine ⟨⟨⟨hmod, htop, hsize, fun t ht htgt => ?_⟩, fun t ht => ?_⟩, hseg, hneed⟩ + · have hv : isValidJumpDest (validJumpDestinations code) (c.offset t) = true := by + simp only [labelsValid, List.all_eq_true, List.mem_range] at hlabels + have := hlabels t ht + simpa [htgt] using this + obtain ⟨pc', hs, hpc⟩ := seg_lowerFrom p c t p.blocks 0 0 hseg ht + simp only [Nat.zero_add] at hs hpc + rw [← hpc htgt] at hs + refine ⟨hv, ?_, hs⟩ + have hs' := hs + rw [lowerFrom_drop p c ht] at hs' + simp only [lowerBlock, htgt, ite_true, List.cons_append] at hs' + cases hs' with + | cons d _ _ => + have := decode_lt d + rwa [length_bytesOf] at this + · have := blocksOkC_get p.blocks 0 hblocks t ht + simpa using this + +/-- The relation at a block entry, with the run's tables in step with its world. -/ +def EntF (p : Assemble.Program) (c : Cert) (mx : List Nat) (code : ByteArray) + (msg : Message .fusaka) (ss0 : Substate) (T : Tabs) (x : Nat × List Word × State) + (evm : Evm .fusaka Nat) : Prop := + EntC p c mx code msg ss0 x evm ∧ TabF T.run T.cre x.2.2.world ∧ + RdF code T.run T.cre x.2.2.world evm.returnData ∧ + memoryGasCost evm.memory.size + evm.gas ≤ msg.gas + +/-- **A block of code with loops, GAS, CALLs, CREATE2s and CODECOPYs, read back from a run that +succeeds**, under every runner meeting `P` for the runs meeting `SitesOk`. -/ +theorem advances_checkCF {p : Assemble.Program} {c : Cert} {mx : List Nat} {code : ByteArray} + (G : GlobC p c mx code) (hcr : c.creates = true) {call : Call} {msg : Message .fusaka} + {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : msg.txEnv = Target.txEnv) + (hgas : msg.gas < 2 ^ 256) (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + (P : (bound : Nat) → MessageRunner .fusaka Nat bound → Evm .fusaka Nat → Message .fusaka → + Evm .fusaka Nat → Prop) + (T0 : Tabs) (x : Nat × List Word × State) (evm : Evm .fusaka Nat) + (hE : EntF p c mx code msg ss0 T0 x evm) : + AdvancesF (fun o => SolarTV.EVM.Program.block o call p) (fun T => FO code T.run T.cre) P + (fun bound runChild fin => SitesOk code msg (P bound runChild) bound runChild fin) + (EntF p c mx code msg ss0) + (fun res => PostL call msg.currentTarget ss0 res.2 res.1) + (fun y e => AssembleLoop.meas p c e.gas y.1) T0 x evm := by + intro bound runChild meets within fin hrun hok hsites + obtain ⟨b, S, s⟩ := x + obtain ⟨⟨Tw, pc, M, st, ss, rd, hle, hneed, hR, hseg, htop, hmem, R, hat⟩, hTab, hRd, hbud⟩ := hE + simp only at hle hneed hR hseg hmem R hTab hRd + have hRd' : RdF code T0.run T0.cre s.world rd := by + rw [hat.2.2.2.2.2.2.2.2.2.2.2.2] at hRd + exact hRd + by_cases hb : b < p.blocks.length + · obtain ⟨hL, hnm, hstk, hblock⟩ := G.block b hb + obtain ⟨hn, hm⟩ := hneed hb + have hblk : p.blocks[b]? = some p.blocks[b] := List.getElem?_eq_getElem hb + rw [lowerFrom_drop p c hb, lowerBlock, List.append_assoc] at hseg + obtain ⟨pc1, m1, within1, hat1, hseg1, hg1, hrun1⟩ : ∃ (pc1 : Nat) (m1 : Evm .fusaka Nat) + (within1 : GasMeter.gasHeld m1.gas ≤ bound), + At code msg pc1 Tw M m1.gas st ss rd m1 ∧ + Seg (bytesOf code) c.offset pc1 (lowerInstrs p c b p.blocks[b] ++ + lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) code.size ∧ + m1.gas + (if isTarget p c b then 1 else 0) ≤ evm.gas ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m1 within1 = .ok fin := by + by_cases ht : isTarget p c b = true + · simp only [ht, ite_true, List.singleton_append, List.cons_append] at hseg + obtain ⟨next, hd, hseg'⟩ := hseg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hp := hat.addGas 1 + obtain ⟨e1, r1, he1⟩ := Logic.jumpdestG hlt hcode (show 1 ≤ evm.gas + 1 by omega) _ hp + obtain ⟨m, within', hz, hrm⟩ := reaches_low r1 1 evm rfl within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hgm⟩ := at_of_addGasR he1 + exact ⟨pc + 1, m, within', hatm, hseg', by simp only [ht, ite_true]; omega, hrm⟩ + · simp only [ht, Bool.false_eq_true, ite_false, List.nil_append] at hseg + exact ⟨pc, evm, within, hat, hseg, by simp only [ht, Bool.false_eq_true, ite_false]; omega, + hrun⟩ + obtain ⟨T', A', r, hle', hA', hex, hpost, hnext⟩ := segF (G0 := msg.gas) G.toGlobT hcr hdata + hvalue hstatic hself hcaller hbenv htx hb hok hgas hdepth meets hsites + (p.blocks[b].length + 1) p.blocks[b] (c.need b) [] (c.entry b) + (budget c b - labelItems p c b) S Tw s pc1 M m1.gas st ss rd T0.run T0.cre m1 within1 + (Nat.lt_succ_self _) hblock hn (by omega) (KR.nil _) hR hseg1 (by omega) htop hmem R hat1 + hTab hRd' (by unfold MemBudget; rw [← hat.2.2.2.2.2.1]; omega) hrun1 + refine ⟨⟨T', A'⟩, r, ⟨hle', hA'⟩, fun T'' h => ?_, fun res hres => hpost res hres, fun y hy => ?_⟩ + · simp only [SolarTV.EVM.Program.block, hblk] + rw [hex T''.run T''.cre h.1 h.2] + · obtain ⟨t, S', s'⟩ := y + obtain ⟨⟨htle, -, hj⟩, after, within', hE', hT', hrdy, hga, hbud', hra⟩ := hnext _ hy + refine ⟨after, within', ⟨hE', hT', hrdy, hbud'⟩, ?_, hra⟩ + have := meas_step (c := c) (g := evm.gas) (g' := after.gas) hb htle (by omega) hj + dsimp only at this ⊢ + omega + · obtain rfl : b = p.blocks.length := by omega + have hblk : p.blocks[p.blocks.length]? = none := List.getElem?_eq_none (by omega) + have hbl : ∀ o, SolarTV.EVM.Program.block o call p (p.blocks.length, S, s) = + some (.inl (.stop, s)) := by + intro o + simp only [SolarTV.EVM.Program.block, hblk, ite_true] + refine ⟨T0, _, Tabs.Le.refl T0, fun _ _ => hbl _, ?_, ?_⟩ + · intro res hres + cases hres + have hseg' := hseg + rw [lowerFrom_nil p c (by omega)] at hseg' + have hpc := hseg'.nil_end + exact SpecG.low (SpecG.consequence (stop_of_size_leG (by omega)) + (fun _ h => h) fun evm h => postL_stop R hself evm h) (hat.addGas 0) within hrun hok + · intro y hy + cases hy + +/-- **Named hypothesis on a run of the bytecode with calls and creations**: the run of the call, when +it succeeds, meets `SitesOk` for the frames EthLib's runner returns (`RunOut`): at each CALL and +CREATE2, the frames the runner returns for its message from the caller state it makes keep the +frame's account, add no log when they succeed and have outputs below `2 ^ 256` bytes, and a CALL +with value calls code that is no EIP-7702 delegation. -/ +def SitesRun (gas : Nat) (code : ByteArray) (call : Call) : Prop := + ∀ r, processMessage (Meter := Nat) .fusaka (Final.Target.messageWith gas code call) + (SolidCore.Refinement.Target.preState code call) Substate.empty = .ok r → r.1.error = none → + SitesOk code (Final.Target.messageWith gas code call) + (RunOut (processRunner .fusaka (Meter := Nat) gas)) gas (processRunner .fusaka (Meter := Nat) gas) + r.1 + +/-- **EVM IR to bytecode, run by run, for code with loops, GAS, memory at any offset, CALLs, +CREATE2s and CODECOPYs**: for every program the checker with calls and creations accepts, at every +gas below `2 ^ 256` and every call whose run meets `SitesRun`, the oracle of the run's two tables makes +every result of the bytecode the EVM IR's or a failure that changes nothing. -/ +theorem runs_of_checkCF {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (hc : checkCF p code c mx = true) (hcr : c.creates = true) (gas : Nat) (hgas : gas < 2 ^ 256) + (call : Call) (hQ : SitesRun gas code call) : + ∃ T : Tabs, Within (evmirSem (FO code T.run T.cre)) (ethLibWith gas) p code (· = call) := by + obtain ⟨G, hseg, hneed0⟩ := globC_of_checkCF hc + refine within_of_advancesF (fun T => FO code T.run T.cre) (fun _ runChild => RunOut runChild) + (fun bound runChild fin => SitesOk code (Final.Target.messageWith gas code call) (RunOut runChild) + bound runChild fin) + (fun ss0 => EntF p c mx code (Final.Target.messageWith gas code call) ss0) + (fun y e => AssembleLoop.meas p c e.gas y.1) (meets_runOut _) hQ (fun st' ss' R => ?_) + (fun ss0 T x evm hE => advances_checkCF G hcr rfl + (by simp [Final.Target.messageWith, SolidCore.Refinement.Target.message]) rfl rfl rfl rfl rfl + hgas (by show 0 + 1 ≤ 1024; decide) (fun _ runChild => RunOut runChild) T x evm hE) + refine ⟨⟨[], 0, .empty, st', ss', .empty, Nat.zero_le _, fun _ => ⟨by simp [hneed0], by simp⟩, + SR.nil c _, by rw [List.drop_zero]; exact hseg, by simp, memRel_initial, R, ?_⟩, + ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩, RdF.nil code _ _, ?_⟩ + have hcode : (Final.Target.messageWith gas code call).code = code := rfl + · exact ⟨by simp [startFrame, hcode], by simp [startFrame, hcode], rfl, rfl, rfl, rfl, rfl, rfl, rfl, + rfl, rfl, rfl, rfl⟩ + · have h0 : memoryGasCost 0 = 0 := by rw [memoryGasCost_eq]; simp [wordCount, ceil32, WORD_BYTES] + simp only [startFrame, ByteArray.size_empty, h0, Nat.zero_add] + exact le_refl _ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateRunF.runs_of_checkCF' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms runs_of_checkCF + +/-- The per-run theorem below `2 ^ 256` gas for every program the checker with calls and creations +accepts, on the calls in scope whose runs meet `SitesRun`: the oracle meets the certificate. -/ +theorem withinRun_of_checkCF {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (hc : checkCF p code c mx = true) (hcr : c.creates = true) (scope : Call → Prop) + (hQ : ∀ gas call, scope call → SitesRun gas code call) : + WithinRunLt evmirSem (fun _ => p) code scope (CertOk c) := by + intro gas hgas call hs + obtain ⟨T, hT⟩ := runs_of_checkCF hc hcr gas hgas call (hQ gas call hs) + exact ⟨FO code T.run T.cre, FO_ok c code T.run T.cre, hT⟩ + +/-- **The assembly premise for code with calls and creations**: below `2 ^ 256` gas, for every call +in scope whose run meets `SitesRun`, an oracle meeting the certificate under which the EVM IR gives +the bytecode's result or a failure that changes nothing. (No world answering its calls at the +source is given: the source side of CALL and CREATE2 is out of scope.) -/ +theorem assembly_of_checkCF {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (hc : checkCF p code c mx = true) (hcr : c.creates = true) (scope : Call → Prop) + (hQ : ∀ gas call, scope call → SitesRun gas code call) : + ∀ gas, gas < 2 ^ 256 → ∀ call, scope call → ∃ o : Oracle, CertOk c o ∧ + Within (evmirSem o) (ethLibWith gas) p code (· = call) := + withinRun_of_checkCF hc hcr scope hQ + +/-- **The first lowered MIR to the exact bytecode, run by run, for code with calls and creations**: +the backend stages read backwards and the checker with calls and creations. -/ +theorem withinRun_mir_of_checkCF {stage0 : SolarTV.MIR.Lowered.moduleLayer.Prog} + {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} {S scope : Call → Prop} + (back : ∀ o, Certified SolarTV.EVM.Program.layer SolarTV.MIR.Lowered.moduleLayer o p stage0 S) + (hS : ∀ call, scope call → S call) (hc : checkCF p code c mx = true) (hcr : c.creates = true) + (hQ : ∀ gas call, scope call → SitesRun gas code call) : + WithinRunLt mirSem (fun _ => stage0) code scope (CertOk c) := + WithinRunLt.of_back (fun o _ => fun call hcall obs h => + stage_of_certified (back o) call (hS call hcall) obs h) + (withinRun_of_checkCF hc hcr scope hQ) + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateRunF.withinRun_mir_of_checkCF' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms withinRun_mir_of_checkCF + +/-- **A specification at EVM IR to the exact bytecode, for code with calls and creations**: a +specification of the EVM IR under every oracle meeting the certificate, the checker and `SitesRun` +on the calls in scope give the specification of the bytecode at every gas below `2 ^ 256`. -/ +theorem holds_of_checkCF {St : Type} {p : Assemble.Program} {code : ByteArray} {c : Cert} + {mx : List Nat} {spec : Final.ContractSpec St} + (evmir : ∀ o, CertOk c o → Final.Holds (evmirSem o) p spec) + (hc : checkCF p code c mx = true) (hcr : c.creates = true) + (hQ : ∀ gas call, spec.Calls call → SitesRun gas code call) + (gas : Nat) (hgas : gas < 2 ^ 256) : Final.Holds (Final.ethLibWith gas) code spec := by + intro f hf args ht v hv σ hinv hreq obs hrun + have hcall : spec.Calls (f.call args v σ) := ⟨f, hf, args, ht, v, hv, σ, rfl⟩ + obtain ⟨o, ho, hwithin⟩ := assembly_of_checkCF hc hcr spec.Calls hQ gas hgas _ hcall + rcases hwithin _ rfl obs hrun with h | ⟨hs, hst, hl⟩ + · exact evmir o ho f hf args ht v hv σ hinv hreq obs h + · exact ⟨fun h'' => absurd (hs.symm.trans h'') (by decide), fun _ => ⟨hst, hl⟩⟩ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateRunF.holds_of_checkCF' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holds_of_checkCF + +/-! ## The example: CODECOPY, CREATE2 and CALL with value, run by run -/ + +/-- **The example's bytecode, run by run**: at every gas below `2 ^ 256` and every call whose run meets +`SitesRun`, every result of `AssembleCreateExample.code` (CODECOPY of its init code, CREATE2 with salt +`0x2a`, CALL with value 1 to the created address) is the EVM IR program's under the oracle of the +run's tables, or a failure that changes nothing. -/ +theorem example_runs (gas : Nat) (hgas : gas < 2 ^ 256) (call : Call) + (hQ : SitesRun gas AssembleCreateExample.code call) : + ∃ T : Tabs, Within (evmirSem (FO AssembleCreateExample.code T.run T.cre)) (ethLibWith gas) + AssembleCreateExample.prog AssembleCreateExample.code (· = call) := + runs_of_checkCF AssembleCreateExample.check_ok rfl gas hgas call hQ + +/-- The same checker refuses the example's bytecode with another salt or value: the premise of +`runs_of_checkCF` fails for them. -/ +theorem example_mutants : + checkCF AssembleCreateExample.prog (AssembleCreateExample.codeOf 2 0x2b 1) + AssembleCreateExample.cert AssembleCreateExample.maxs = false ∧ + checkCF AssembleCreateExample.prog (AssembleCreateExample.codeOf 2 0x2a 2) + AssembleCreateExample.cert AssembleCreateExample.maxs = false := + ⟨AssembleCreateExample.mutantSalt_fails, AssembleCreateExample.mutantValue_fails⟩ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateRunF.example_runs' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms example_runs + +end SolidCore.Refinement.Solar.AssembleCreateRunF diff --git a/SolidCore/Refinement/Solar/AssembleCreateSeg.lean b/SolidCore/Refinement/Solar/AssembleCreateSeg.lean new file mode 100644 index 00000000..18c8f95a --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCreateSeg.lean @@ -0,0 +1,398 @@ +import SolidCore.Refinement.Solar.AssembleCreateBack +import SolidCore.Refinement.Solar.AssembleCallValueEffect +import SolidCore.Refinement.Solar.AssembleCodeCopy + +/-! +# CREATE2 as a cut of a run, at the frame's own gas + +The checker cuts a block at each CREATE2 (as it does at a STATICCALL, `AssembleCallCut.staticcall_cut`): +from a run of the bytecode that succeeds, `create2_cut` reads the creation back at the frame's own gas +(`AssembleCreateBack.create2_back`) and gives the run's answers to it: the word the frame pushes (the +EIP-1014 address when the init code ends with no error, 0 when the creation fails or sends no message), +the return data the frame is left with, and the storage of the frame's account after it, which a +reentrant init code may have changed. A run's table of creations (`CreateTable`) records them in order, +and the oracle of every extension of it (`createOracle`) makes SolarTV's CREATE2 push that word, leave that +return data and storage, and record the init code EthLib runs; memory, the storage relation, the +account and the logs of the frame are related again (`Assemble.Rel`). + +`createOracle o A` answers a world whose last message is a creation from the table, by the number of +creations in it, and every other world as `o` does, so it extends the oracle of calls and GAS reads of a run +(`AssembleCallWorld.OS`, `RunOracle.tableOracle`) without changing their answers (`createOracle_other`). + +The init code is the callee's frame and nothing is assumed of its code. What SolarTV's frame cannot see +is named (`CreateOk`, a hypothesis on the frame that ends the creation's message, asked only of messages +from this frame with this init code): the creator's account still exists after it, a creation that +succeeds adds no log (SolarTV's world records only the frame's own logs, so a logging init code would +make the observables differ), and the revert data of a failed creation has fewer than `2 ^ 256` bytes +(as `AssembleCallCut.OutputFits` for calls). +-/ + +namespace SolidCore.Refinement.Solar.AssembleCreateSeg + +open SolarTV SolarTV.Machine +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.RunOracle +open SolidCore.Refinement.Solar.AssembleEffects SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCreate SolidCore.Refinement.Solar.AssembleCreateBack +open SolidCore.Refinement.Solar.AssembleCallValueEffect +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts + +/-! ## A run's answers to its creations -/ + +/-- A creation event. -/ +def isCreateE : Event → Bool + | .create .. => true + | _ => false + +/-- The creations of a world. -/ +def creates (w : List Event) : Nat := (w.filter isCreateE).length + +/-- Whether the last message a world sent is a creation. -/ +def lastCreate (w : List Event) : Bool := + match (w.filter Event.sends).getLast? with + | some (.create ..) => true + | _ => false + +@[simp] theorem lastCreate_create (w : List Event) (ops : List Word) (c : List Memory.Byte) + (sto tr : Word → Word) : lastCreate (w ++ [.create ops c sto tr]) = true := by + simp [lastCreate, List.filter_append, Event.sends] + +@[simp] theorem creates_create (w : List Event) (ops : List Word) (c : List Memory.Byte) + (sto tr : Word → Word) : creates (w ++ [.create ops c sto tr]) = creates w + 1 := by + simp [creates, List.filter_append, List.filter_cons, isCreateE] + +@[simp] theorem lastCreate_read (w : List Event) (n : String) : + lastCreate (w ++ [.read n]) = lastCreate w := by + simp [lastCreate, List.filter_append, Event.sends] + +@[simp] theorem lastCreate_log (w : List Event) (t : List Word) (d : List Memory.Byte) : + lastCreate (w ++ [.log t d]) = lastCreate w := by + simp [lastCreate, List.filter_append, Event.sends] + +@[simp] theorem lastCreate_call (w : List Event) (k : SolarTV.Machine.CallKind) (ops : List Word) + (i : List Memory.Byte) (sto tr : Word → Word) : + lastCreate (w ++ [.call k ops i sto tr]) = false := by + simp [lastCreate, List.filter_append, Event.sends] + +@[simp] theorem creates_read (w : List Event) (n : String) : creates (w ++ [.read n]) = creates w := by + simp [creates, List.filter_append, isCreateE] + +@[simp] theorem creates_log (w : List Event) (t : List Word) (d : List Memory.Byte) : + creates (w ++ [.log t d]) = creates w := by + simp [creates, List.filter_append, isCreateE] + +/-- What a run answers to its creations, in order: the word each pushed, the return data it left, and +the storage of the frame's account after it. -/ +structure CreateTable where + addrs : List Word := [] + outs : List ByteArray := [] + stores : List (Word → Word) := [] + +/-- A table that answers every creation the shorter one does, the same. -/ +def CreateTable.Le (A B : CreateTable) : Prop := + A.addrs <+: B.addrs ∧ A.outs <+: B.outs ∧ A.stores <+: B.stores + +theorem CreateTable.Le.refl (A : CreateTable) : A.Le A := + ⟨List.prefix_refl _, List.prefix_refl _, List.prefix_refl _⟩ + +theorem CreateTable.Le.trans {A B C : CreateTable} (h1 : A.Le B) (h2 : B.Le C) : A.Le C := + ⟨h1.1.trans h2.1, h1.2.1.trans h2.2.1, h1.2.2.trans h2.2.2⟩ + +/-- The table with one more creation. -/ +def CreateTable.push (A : CreateTable) (r : Word) (out : ByteArray) (sto : Word → Word) : + CreateTable := + { addrs := A.addrs ++ [r], outs := A.outs ++ [out], stores := A.stores ++ [sto] } + +theorem CreateTable.le_push (A : CreateTable) (r : Word) (out : ByteArray) (sto : Word → Word) : + A.Le (A.push r out sto) := + ⟨List.prefix_append _ _, List.prefix_append _ _, List.prefix_append _ _⟩ + +/-- The return data the last creation of a world left. -/ +def CreateTable.out (A : CreateTable) (w : List Event) : ByteArray := A.outs.getD (creates w - 1) .empty + +/-- **The oracle of a run's creations**: a world whose last message is a creation is answered from +the table (the word pushed, the return data, the storage after), every other world as by `o`. -/ +def createOracle (o : Oracle) (A : CreateTable) : Oracle := + { o with + env := fun name w args => + if lastCreate w = true then + if name = "returndatasize" ∧ args = [] then BitVec.ofNat 256 (A.out w).size + else if name = "returndata" then + match args with + | [i] => BitVec.ofNat 256 (byteAt (A.out w) i.toNat).toNat + | _ => o.env name w args + else o.env name w args + else o.env name w args + result := fun w => if lastCreate w = true then A.addrs.getD (creates w - 1) 0 else o.result w + storageAfter := fun w => + if lastCreate w = true then A.stores.getD (creates w - 1) (o.storageAfter w) + else o.storageAfter w } + +/-- Every world whose last message is no creation is answered as by `o`. -/ +theorem createOracle_other {o : Oracle} {A : CreateTable} {w : List Event} (h : lastCreate w = false) : + (createOracle o A).result w = o.result w ∧ (createOracle o A).storageAfter w = o.storageAfter w ∧ + (createOracle o A).transientAfter w = o.transientAfter w ∧ + ∀ name args, (createOracle o A).env name w args = o.env name w args := by + simp [createOracle, h] + +/-- The hash, the caller and the reads of the frame's code are `o`'s. -/ +theorem createOracle_keccak (o : Oracle) (A : CreateTable) : (createOracle o A).keccak = o.keccak := rfl + +theorem createOracle_caller (o : Oracle) (A : CreateTable) : (createOracle o A).caller = o.caller := rfl + +theorem createOracle_code (o : Oracle) (A : CreateTable) (args : List Word) : + (createOracle o A).env "code" [] args = o.env "code" [] args := by + simp [createOracle, lastCreate] + +/-- The storage of an account of EthLib's state, as SolarTV's words. -/ +def storeOf (st : State.TransactionState) (a : Address) : Word → Word := + fun k => st.getStorage a (U256.toBeBytes k) + +/-- SolarTV's state after a CREATE2 whose storage after is `sto`. -/ +def postCreate (o : Oracle) (s : State) (sto : Word → Word) (value start size salt : Word) : State := + ⟨s.memory.expand start.toNat size.toNat, sto, o.transientAfter (createWorld s value start size salt), + createWorld s value start size salt⟩ + +/-- **SolarTV's CREATE2 under the oracle of every extension of a table with the creation**: it +pushes the table's word, leaves the table's return data and storage. -/ +theorem create2_apply {o : Oracle} {A A'' : CreateTable} {call : Call} {s : State} + {value start size salt r : Word} {out : ByteArray} {sto : Word → Word} + (hA : A.addrs.length = creates s.world) (hAo : A.outs.length = creates s.world) + (hAs : A.stores.length = creates s.world) (hle : (A.push r out sto).Le A'') + (hr : r.toNat < 2 ^ 160) (hsz : out.size < 2 ^ 256) : + Effect.apply (createOracle o A'') call .create2 [value, start, size, salt] s = + some (some r, postCreate o s sto value start size salt) ∧ + RdRel (createOracle o A'') (createWorld s value start size salt) out := by + have haddr : A''.addrs.getD (creates s.world) 0 = r := by + rw [AssembleRun.getD_of_prefix hle.1 (by simp [CreateTable.push, hA])] + simp [CreateTable.push, hA] + have hout : A''.outs.getD (creates s.world) .empty = out := by + rw [AssembleRun.getD_of_prefix hle.2.1 (by simp [CreateTable.push, hAo])] + simp [CreateTable.push, hAo] + have hsto : ∀ d, A''.stores.getD (creates s.world) d = sto := by + intro d + rw [AssembleRun.getD_of_prefix hle.2.2 (by simp [CreateTable.push, hAs])] + simp [CreateTable.push, hAs] + have hr' : BitVec.ofNat 256 (r.toNat % 2 ^ 160) = r := by + apply BitVec.eq_of_toNat_eq + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt hr, Nat.mod_eq_of_lt (by omega)] + refine ⟨?_, ?_, fun i hi => ?_⟩ + · simp only [Effect.apply, created, createOracle, postCreate, createWorld, lastCreate_create, + creates_create, Nat.add_sub_cancel, ite_true, haddr, hsto, hr'] + · simp only [returndataSize, createOracle, createWorld, lastCreate_create, and_self, ite_true, + CreateTable.out, creates_create, Nat.add_sub_cancel, hout, BitVec.toNat_ofNat] + exact Nat.mod_eq_of_lt hsz + · have hi' : i < 2 ^ 256 := by omega + simp only [returndataByte, createOracle, createWorld, lastCreate_create, ite_true, + show ¬("returndata" = "returndatasize" ∧ [BitVec.ofNat 256 i] = []) by simp, ite_false, + CreateTable.out, creates_create, Nat.add_sub_cancel, hout, BitVec.toNat_ofNat, + Nat.mod_eq_of_lt hi'] + exact AssembleCodeCopy.setWidth_ofNat_byte _ + +/-! ## The frame after a creation -/ + +/-- **Named hypothesis on the frame that ends a creation's message**: the creator's account still +exists after it, a creation that succeeds adds no log, and the revert data has fewer than `2 ^ 256` +bytes. -/ +def CreateOk (msg : Message .fusaka) (child : Evm .fusaka Nat) : Prop := + (child.state.getAccountOptional msg.currentTarget).isSome = true ∧ + (child.error.isNone = true → child.substate.logs.toList = []) ∧ child.output.size < 2 ^ 256 + +/-- A creation event writes no log. -/ +theorem logsRel_create {a : Address} {ss0 ss : Substate} {w : List Event} (ops : List Word) + (c : List Memory.Byte) (sto tr : Word → Word) (h : LogsRel a ss0 ss w) : + LogsRel a ss0 ss (w ++ [.create ops c sto tr]) := by + obtain ⟨L, h1, h2⟩ := h + refine ⟨L, h1, ?_⟩ + rw [List.filter_append] + simpa [isLogE] using h2 + +/-- Adding one to the nonce of an account keeps it. -/ +theorem account_incrementNonce {tx tx' : State.TransactionState} {a : Address} + (h : tx.incrementNonce .fusaka a = .ok tx') : (tx'.getAccountOptional a).isSome = true := by + have h' : tx.modifyState .fusaka a (fun account => .ok { account with nonce := account.nonce + 1 }) = + .ok tx' := h + obtain ⟨account, hf, rfl⟩ := EthLib.Execution.State.TransactionState.modifyState_eq_ok_iff.mp h' + simp only [Except.ok.injEq] at hf + subst hf + have hne : ((tx.recordAccountRead a).setAccount a (some { tx.getAccount a with + nonce := (tx.getAccount a).nonce + 1 })).accountExistsAndIsEmpty a = false := by + simp [State.TransactionState.accountExistsAndIsEmpty, + EthLib.Execution.State.TransactionState.getAccountOptional_setAccount_self] + rw [hne, Bool.and_false] + simp [EthLib.Execution.State.TransactionState.getAccountOptional_setAccount_self] + +/-- A creation passes on at most the gas left. -/ +theorem createMessageGas_le (x : Nat) : createMessageGas .fusaka x ≤ x := by + unfold createMessageGas maxMessageCallGas + split <;> omega + +/-- The caller's state after the callee is the callee's. -/ +theorem incorporateChild_state (caller child : Evm .fusaka Nat) : + (incorporateChild .fusaka caller child).state = child.state := by + unfold incorporateChild + split <;> rfl + +/-! ## CREATE2 at the frame's own gas -/ + +/-- **CREATE2 as a cut of a run that succeeds**: the creation had the gas for its price, and the run +goes on from the frame after it, pushing the word `r` (the EIP-1014 address on success, 0 otherwise), +with return data `out` and the storage of the frame's account after it. Under the oracle of every +extension of the table with these answers, SolarTV's CREATE2 pushes `r`, leaves `out` and that storage, +and every relation of a block entry holds again, at no more gas than the frame had. -/ +theorem create2_cut {code : ByteArray} {msg : Message .fusaka} {call : Call} {pc g G : Nat} + {M : ByteArray} {st : State.TransactionState} {ss ss0 : Substate} {rd : ByteArray} + {value start size salt : U256} {Tr : List U256} {s : State} {evm : Evm .fusaka Nat} + (o : Oracle) (A : CreateTable) + (hm : MemRel s.memory M) (R : Rel msg ss0 st ss s) (hb : MemBudget G M g) (hG : G < 2 ^ 256) + (hat : At code msg pc (value :: start :: size :: salt :: Tr) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0xf5) (hstatic : msg.isStatic = false) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} (meets : Meets P runChild) + (hq : ∀ caller m child, P caller m child → m.caller = msg.currentTarget → + m.currentTarget = create2Address msg.currentTarget salt (memoryReadBytes (memoryExtend M + (extendMemory M.size [(start, size)]).expandBy) start.toNat size.toNat) → + m.code = memoryReadBytes (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) + start.toNat size.toNat → m.value = value → + m.gas = createMessageGas .fusaka (g - cost2 M.size start size) → CreateOk msg child) + (within : GasMeter.gasHeld evm.gas ≤ bound) {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) + (hA : A.addrs.length = creates s.world) (hAo : A.outs.length = creates s.world) + (hAs : A.stores.length = creates s.world) : + ∃ (r : Word) (out : ByteArray) (st' : State.TransactionState) (ss' : Substate) (M' : ByteArray) + (g' : Nat) (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + (∀ A'', (A.push r out (storeOf st' msg.currentTarget)).Le A'' → + Effect.apply (createOracle o A'') call .create2 [value, start, size, salt] s = + some (some r, postCreate o s (storeOf st' msg.currentTarget) value start size salt) ∧ + RdRel (createOracle o A'') (createWorld s value start size salt) out) ∧ + MemRel (postCreate o s (storeOf st' msg.currentTarget) value start size salt).memory M' ∧ + Rel msg ss0 st' ss' (postCreate o s (storeOf st' msg.currentTarget) value start size salt) ∧ + MemBudget G M' g' ∧ g' ≤ g ∧ + At code msg (pc + 1) (r :: Tr) M' g' st' ss' out m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + obtain ⟨hg, -, hcase⟩ := create2_back hat hmod hlt hbyte hstatic meets within hrun hok + have hg' : createBaseCost .fusaka + OPCODE_KECCAK256_PER_WORD * wordCount size.toNat + + initCodeCost size.toNat + (extendMemory M.size [(start, size)]).cost ≤ g := hg + have hbnd : size = 0 ∨ (start.toNat + size.toNat + 31) / 32 < 2 ^ 251 := by + by_cases hz : size = 0 + · exact .inl hz + · have := AssembleCodeCopy.size_le_of_budget hmod hz hb hG hg' + exact .inr (by omega) + have hm1 := memRel_expandW hm hbnd + have hb1 : MemBudget G (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) + (g - cost2 M.size start size) := + MemBudget.grow hmod hb hg' (size_memoryExtend _ _) + rcases hcase with ⟨-, m, within', hat', hrun'⟩ | + ⟨-, -, -, -, st', m, within', hinc, hat', hrun'⟩ | + ⟨-, -, -, -, caller, mm, child, after, within', hP, hcg, -, hcsub, hmg, hmc, hmt, hmcode, hmv, -, + hat', hrun'⟩ + · -- No message: 0 pushed, no return data. + refine ⟨0, .empty, _, ss, memoryExtend M (extendMemory M.size [(start, size)]).expandBy, + g - cost2 M.size start size, m, within', fun A'' hle => + create2_apply hA hAo hAs hle (by simp) (by simp), hm1, ⟨fun k => rfl, ?_, ?_⟩, hb1, + by omega, hat', hrun'⟩ + · simpa using R.account + · exact logsRel_create _ _ _ _ R.logs + · -- A collision: 0 pushed, the creator's nonce grows. + refine ⟨0, .empty, st', { ss with + accessedAddresses := ss.accessedAddresses.insert (create2Address msg.currentTarget salt + (memoryReadBytes (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) + start.toNat size.toNat)) }, + memoryExtend M (extendMemory M.size [(start, size)]).expandBy, + g - cost2 M.size start size - createMessageGas .fusaka (g - cost2 M.size start size), m, + within', fun A'' hle => + create2_apply hA hAo hAs hle (by simp) (by simp), hm1, + ⟨fun k => rfl, account_incrementNonce hinc, logsRel_create _ _ _ _ R.logs⟩, + MemBudget.spend hb1 (by omega), by omega, hat', hrun'⟩ + · -- The init code ran as a callee. + obtain ⟨hacc, hlogs, hfit⟩ := hq caller mm child hP hmc hmt hmcode hmv hmg + have hle1 := createMessageGas_le (g - cost2 M.size start size) + have hgas : g - cost2 M.size start size - createMessageGas .fusaka (g - cost2 M.size start size) + + child.gas ≤ g - cost2 M.size start size := by omega + refine ⟨if child.error.isNone then (create2Address msg.currentTarget salt (memoryReadBytes + (memoryExtend M (extendMemory M.size [(start, size)]).expandBy) start.toNat size.toNat)).toU256 + else 0, if child.error.isNone then .empty else child.output, _, _, + memoryExtend M (extendMemory M.size [(start, size)]).expandBy, + g - cost2 M.size start size - createMessageGas .fusaka (g - cost2 M.size start size) + + child.gas, after, within', + fun A'' hle => create2_apply hA hAo hAs hle ?_ ?_, hm1, ⟨fun k => rfl, ?_, ?_⟩, + MemBudget.spend hb1 hgas, by omega, hat', hrun'⟩ + · split + · exact toU256_lt _ + · simp + · split + · simp + · exact hfit + · rw [incorporateChild_state] + exact hacc + · have hl : (incorporateChild .fusaka caller child).substate.logs.toList = ss.logs.toList := by + unfold incorporateChild + split + · rename_i hn + simp [Array.toList_append, hcsub, hlogs (by simpa using hn)] + · simp [hcsub] + obtain ⟨L, h1, h2⟩ := R.logs + refine ⟨L, by rw [hl, h1], ?_⟩ + simp only [postCreate, createWorld, List.filter_append] + simpa [isLogE] using h2 + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateSeg.create2_cut' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms create2_cut + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateSeg.create2_apply' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms create2_apply + +/-! ## CODECOPY at the frame's own gas -/ + +/-- The oracle of a run's creations reads the frame's code as `o` does. -/ +theorem codeOk_createOracle {o : Oracle} {code : ByteArray} (A : CreateTable) + (hc : AssembleCodeCopy.CodeOk o code) : AssembleCodeCopy.CodeOk (createOracle o A) code := by + intro w + rw [createOracle_code] + exact hc w + +/-- The oracle of a run's table reads the frame's code as its base does. -/ +theorem codeOk_tableOracle {o : Oracle} {code : ByteArray} (T : RunTable) + (hc : AssembleCodeCopy.CodeOk o code) : AssembleCodeCopy.CodeOk (tableOracle o T) code := by + intro w + have : (tableOracle o T).env "code" [] [w] = o.env "code" [] [w] := by + simp [tableOracle] + rw [this] + exact hc w + +/-- SolarTV's state after CODECOPY. -/ +def codeCopied (o : Oracle) (s : State) (d off sz : Word) : State := + { s with memory := s.memory.write d.toNat sz.toNat (fun i => codeByte o (off.toNat + i)) } + +/-- **CODECOPY as a cut of a run that succeeds**: with a code offset below `2 ^ 32` and an oracle that +reads the frame's code, the copy had its price, SolarTV's copy writes the bytes EthLib's does, and +every relation of a block entry holds again (memory is all it changes). -/ +theorem codecopy_cut {code : ByteArray} {msg : Message .fusaka} {call : Call} {o : Oracle} + (hc : AssembleCodeCopy.CodeOk o code) {pc g G : Nat} {M : ByteArray} + {st : State.TransactionState} {ss ss0 : Substate} {rd : ByteArray} {d off sz : U256} + {Tr : List U256} {s : State} {evm : Evm .fusaka Nat} (hoff : off.toNat < 2 ^ 32) + (hm : MemRel s.memory M) (R : Rel msg ss0 st ss s) (hb : MemBudget G M g) (hG : G < 2 ^ 256) + (hat : At code msg pc (d :: off :: sz :: Tr) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x39) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + ∃ (M' : ByteArray) (g' : Nat) (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + Effect.apply o call .codecopy [d, off, sz] s = some (none, codeCopied o s d off sz) ∧ + MemRel (codeCopied o s d off sz).memory M' ∧ Rel msg ss0 st ss (codeCopied o s d off sz) ∧ + MemBudget G M' g' ∧ g' ≤ g ∧ At code msg (pc + 1) Tr M' g' st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + obtain ⟨M', g', m, within', hmem, hb', hg', hat', hrun'⟩ := + AssembleCodeCopy.codecopy_dyn hc hoff hm hb hG hat hlt hbyte within hrun hok + exact ⟨M', g', m, within', AssembleCodeCopy.codecopy_effect o call d off sz s, hmem, + ⟨R.storage, R.account, R.logs⟩, hb', hg', hat', hrun'⟩ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateSeg.codecopy_cut' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms codecopy_cut + +end SolidCore.Refinement.Solar.AssembleCreateSeg diff --git a/SolidCore/Refinement/Solar/AssembleCreateSegF.lean b/SolidCore/Refinement/Solar/AssembleCreateSegF.lean new file mode 100644 index 00000000..2afa70d5 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCreateSegF.lean @@ -0,0 +1,934 @@ +import SolidCore.Refinement.Solar.AssembleCreateRun +import SolidCore.Refinement.Solar.AssembleCreateCutQ +import SolidCore.Refinement.Solar.AssembleCallSeg + +/-! +# Code with CALLs, CREATE2s and CODECOPYs, block by block, at the frame's own gas + +The checker without the creation gate (`AssembleCut.checkCF`) cuts a block at each CALL, CREATE2 and +CODECOPY (`AssembleCut.blockOkC`, under a certificate that says the program creates), and refuses +STATICCALL there (`AssembleCut.blockOkC_noSc_creates`). `segF` reads each +segment back from a run that succeeds as `AssembleCut.seg` does, under the oracle of the run's two tables +(`AssembleCreateRun.FO`): GAS adds its gas to the run table, CALL its flag, return data and storage +after (`AssembleCallValueZeroSeg.call0_cut`, `AssembleCallValueSeg.callValue_cut`), CREATE2 its word, +return data and storage after to the creation table and an entry at its message to the run table +(`AssembleCreateSeg.create2_cut`, `AssembleCreateRun.create2_table`), and CODECOPY reads the frame's code +(`AssembleCreateSeg.codecopy_cut`). RETURNDATASIZE and RETURNDATACOPY read the frame's return data, +which is the tables' answer at the frame's world (`RdF`): the run table's output of the last CALL, +the creation table's of the last CREATE2, empty before any message; each cut re-establishes it from +the frame EthLib's runner returned (`call0_cutQ`, `callValue_cutQ`, `create2_cutQ`). + +Every extension of both tables runs each segment to the same end (`AssembleCreateRun.exec_F`), and +`TabF` keeps the tables in step with the frame's world from cut to cut. + +`segF` names what it assumes of the run: + +* `SitesOk`: at every CALL and CREATE2 of the run, the frames the runner returns for its message from + the caller state it makes keep the frame's account, add no log when they succeed and have outputs + below `2 ^ 256` bytes (`AssembleCreateCutQ`), and a CALL with value calls code that is no + EIP-7702 delegation. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCreateSegF + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Final +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.RunOracle SolidCore.Refinement.Solar.AssembleRun +open SolidCore.Refinement.Solar.AssembleRunLoop SolidCore.Refinement.Solar.AssembleCut +open SolidCore.Refinement.Solar.AssembleEffects +open SolidCore.Refinement.Solar.AssembleCreateSeg SolidCore.Refinement.Solar.AssembleCreateRun +open SolidCore.Refinement.Solar.AssembleCallValueSeg SolidCore.Refinement.Solar.AssembleCallValueZeroSeg +open SolidCore.Refinement.Solar.AssembleCreateSegOracle SolidCore.Refinement.Solar.AssembleCreateCut +open SolidCore.Refinement.Solar.AssembleCreateCutQ +open SolidCore.Refinement.Solar.AssembleCallValueEffect +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +/-- **A segment keeps the frame's world**: every effect that adds an event is a cut. -/ +theorem execC_world (o : Oracle) (call : Call) (b : Nat) : + ∀ (is : List Assemble.Instr) (S : List Word) (s s' : State), + endState (execC o call b is S s) = some s' → s'.world = s.world + | [], _, s, s', h => by simp [execC, endState] at h; subst h; rfl + | .op op :: rest, S, s, s', h => by + by_cases hc : cutOp op = true + · simp only [execC, hc, ite_true, endState, Option.some.injEq] at h + subst h; rfl + · have hc' : cutOp op = false := by simpa using hc + cases hs : SolarTV.EVM.Program.stepOp (SolarTV.EVM.Program.context o call s) op S s.memory with + | error _ => simp [execC, hc', hs, endState] at h + | ok r => + obtain ⟨S', m⟩ := r + simp only [execC, hc', hs, Bool.false_eq_true, ite_false] at h + exact execC_world o call b rest S' { s with memory := m } s' h + | .effect e a :: rest, S, s, s', h => by + by_cases hc : cutEffect e = true + · simp only [execC, hc, ite_true, endState, Option.some.injEq] at h + subst h; rfl + · have he : cutEffect e = false := by simpa using hc + by_cases hl : S.length < a + · simp [execC, he, hl, endState] at h + · cases happ : Effect.apply o call e (S.take a) s with + | none => simp [execC, he, hl, happ, endState] at h + | some r => + obtain ⟨res, s1⟩ := r + have hw := apply_world_eq he happ + simp only [execC, he, hl, Bool.false_eq_true, ite_false, happ] at h + split_ifs at h + · simp [endState] at h + · rw [execC_world o call b rest _ s1 s' h, hw] + | .jump t :: rest, S, s, s', h => by + simp only [execC] at h + split_ifs at h <;> simp [endState] at h + subst h; rfl + | .jumpi t :: rest, S, s, s', h => by + simp only [execC] at h + split_ifs at h + · simp [endState] at h + · cases S with + | nil => simp [endState] at h + | cons x S => + simp only at h + split_ifs at h + · exact execC_world o call b rest S s s' h + · simp [endState] at h; subst h; rfl + | .pushLabel t :: rest, S, s, s', h => by + simp only [execC] at h + split_ifs at h + · simp [endState] at h + · exact execC_world o call b rest _ s s' h + | .jumpDyn :: rest, S, s, s', h => by + cases S with + | nil => simp [execC, endState] at h + | cons x S => simp [execC, endState] at h; subst h; rfl + | .jumpiDyn :: rest, S, s, s', h => by + match S with + | [] => simp [execC, endState] at h + | [_] => simp [execC, endState] at h + | x :: y :: S => + simp only [execC] at h + split_ifs at h + · exact execC_world o call b rest S s s' h + · simp [endState] at h; subst h; rfl + | .jumpTable ts :: rest, S, s, s', h => by + cases S with + | nil => simp [execC, endState] at h + | cons x S => + cases ht : ts[x.toNat]? with + | none => simp [execC, ht, endState] at h + | some t => simp [execC, ht, endState] at h; subst h; rfl + | .stop :: rest, S, s, s', h => by simp [execC, endState] at h + | .ret :: rest, S, s, s', h => by simp [execC, endState] at h; subst h; rfl + | .revert :: rest, S, s, s', h => by simp [execC, endState] at h; subst h; rfl + | .invalid :: rest, S, s, s', h => by simp [execC, endState] at h + +/-- The oracle of a run with creations reads the frame's code as its base does, whatever its +tables. -/ +theorem codeByte_FO (code : ByteArray) (T : RunTable) (A : CreateTable) (j : Nat) : + codeByte (FO code T A) j = codeByte (baseF code) j := by + have h1 : (FO code T A).env "code" [] [BitVec.ofNat 256 j] = + (tableOracle (baseF code) T).env "code" [] [BitVec.ofNat 256 j] := + (createOracle_other (o := tableOracle (baseF code) T) (A := A) (w := []) (by simp [lastCreate])).2.2.2 _ _ + have h2 : (tableOracle (baseF code) T).env "code" [] [BitVec.ofNat 256 j] = + (baseF code).env "code" [] [BitVec.ofNat 256 j] := by + simp [tableOracle] + unfold codeByte + rw [h1, h2] + +theorem codeCopied_FO (code : ByteArray) (T T' : RunTable) (A A' : CreateTable) (s : State) + (d off sz : Word) : codeCopied (FO code T' A') s d off sz = codeCopied (FO code T A) s d off sz := by + simp only [codeCopied, codeByte_FO] + +/-! ## The named hypotheses on a run with calls and creations -/ + +/-- **Named hypothesis on a run with calls and creations**: at every CALL and CREATE2 of the frame +that the run goes on from to `fin`, what the run gives the callee's frame (`AssembleCreateCutQ.Call0Q`, +`CallVQ`, `Create2Q`: it keeps the frame's account, adds no log when it succeeds and has an output +below `2 ^ 256` bytes), and at a CALL with value, a callee whose code is found and is no EIP-7702 +delegation. -/ +structure SitesOk (code : ByteArray) (msg : Message .fusaka) + (P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop) (bound : Nat) + (runChild : MessageRunner .fusaka Nat bound) (fin : Evm .fusaka Nat) : Prop where + call0 : ∀ {e : Evm .fusaka Nat} {within : GasMeter.gasHeld e.gas ≤ bound} {pc : Nat} + {asked addr inOff inSize outOff outSize : U256} {Tr : List U256} {M : ByteArray} {g : Nat} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray}, + At code msg pc (asked :: addr :: 0 :: inOff :: inSize :: outOff :: outSize :: Tr) M g st ss rd e → + (hlt : pc < code.size) → code[pc] = 0xf1 → + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild e within = .ok fin → + Call0Q msg P st M addr inOff inSize outOff outSize + callV : ∀ {e : Evm .fusaka Nat} {within : GasMeter.gasHeld e.gas ≤ bound} {pc : Nat} + {asked dst v i isz o osz : U256} {Tr : List U256} {M : ByteArray} {g : Nat} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray}, + At code msg pc (asked :: dst :: v :: i :: isz :: o :: osz :: Tr) M g st ss rd e → + (hlt : pc < code.size) → code[pc] = 0xf1 → v ≠ 0 → + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild e within = .ok fin → + ∃ calleeCode, st.getCode (st.getAccount (toAddressMasked dst)).codeHash = .ok calleeCode ∧ + delegatedAddress calleeCode = none ∧ CallVQ msg P g st ss M asked dst v i isz o osz calleeCode + create2 : ∀ {e : Evm .fusaka Nat} {within : GasMeter.gasHeld e.gas ≤ bound} {pc : Nat} + {value start size salt : U256} {Tr : List U256} {M : ByteArray} {g : Nat} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray}, + At code msg pc (value :: start :: size :: salt :: Tr) M g st ss rd e → + (hlt : pc < code.size) → code[pc] = 0xf5 → + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild e within = .ok fin → + Create2Q msg P g st M value start size salt + +/-! ## A block, segment by segment, with calls and creations -/ + +/-! ## The return data of a run with calls and creations -/ + +/-- **The frame's return data is the tables' answer** at the world, under every extension of both +tables: after a CALL the run table's output of its message, after a CREATE2 the creation table's, and +empty before any message. -/ +def RdF (code : ByteArray) (T : RunTable) (A : CreateTable) (w : List Event) (rd : ByteArray) : Prop := + ∀ T'' A'', T.Le T'' → A.Le A'' → RdRel (FO code T'' A'') w rd + +theorem RdF.mono {code : ByteArray} {T T1 : RunTable} {A A1 : CreateTable} {w : List Event} + {rd : ByteArray} (hT : T.Le T1) (hA : A.Le A1) (h : RdF code T A w rd) : RdF code T1 A1 w rd := + fun T'' A'' h1 h2 => h T'' A'' (hT.trans h1) (hA.trans h2) + +/-- An event that sends no message keeps what the tables answer for the return data. -/ +theorem FO_rd_append {code : ByteArray} {T : RunTable} {A : CreateTable} {w : List Event} {e : Event} + (he : Event.sends e = false) (hc : isCreateE e = false) (name : String) (a : List Word) + (hn : (name = "returndatasize" ∧ a = []) ∨ ∃ i, name = "returndata" ∧ a = [i]) : + (FO code T A).env name (w ++ [e]) a = (FO code T A).env name w a := by + have hl : lastCreate (w ++ [e]) = lastCreate w := by + simp [lastCreate, List.filter_append, he] + have hcr : creates (w ++ [e]) = creates w := by + simp [creates, List.filter_append, hc] + have hs : sent (w ++ [e]) = sent w := by + simp [sent, List.filter_append, he] + have hout : T.out (w ++ [e]) = T.out w := by simp [RunTable.out, hs] + have hAo : A.out (w ++ [e]) = A.out w := by simp [CreateTable.out, hcr] + rcases hn with ⟨rfl, rfl⟩ | ⟨i, rfl, rfl⟩ + · simp [FO, createOracle, tableOracle, hl, hAo, hout] + · simp [FO, createOracle, tableOracle, hl, hAo, hout] + +theorem RdF.append {code : ByteArray} {T : RunTable} {A : CreateTable} {w : List Event} {e : Event} + {rd : ByteArray} (he : Event.sends e = false) (hc : isCreateE e = false) (h : RdF code T A w rd) : + RdF code T A (w ++ [e]) rd := by + intro T'' A'' h1 h2 + obtain ⟨h3, h4⟩ := h T'' A'' h1 h2 + refine ⟨?_, fun i hi => ?_⟩ + · simp only [returndataSize] at h3 ⊢ + rw [FO_rd_append he hc _ _ (.inl ⟨rfl, rfl⟩)] + exact h3 + · simp only [returndataByte] at h4 ⊢ + rw [FO_rd_append he hc _ _ (.inr ⟨_, rfl, rfl⟩)] + exact h4 i hi + +/-- A world whose last message is no creation reads the return data of the run table. -/ +theorem rdRel_FO_of_table {code : ByteArray} {T : RunTable} {A : CreateTable} {w : List Event} + {rd : ByteArray} (hl : lastCreate w = false) (h : RdRel (tableOracle (baseF code) T) w rd) : + RdRel (FO code T A) w rd := by + obtain ⟨_, _, _, henv⟩ := createOracle_other (o := tableOracle (baseF code) T) (A := A) hl + refine ⟨?_, fun i hi => ?_⟩ + · simp only [returndataSize, henv] + exact h.1 + · simp only [returndataByte, henv] + exact h.2 i hi + +/-- A world whose last message is a creation reads the return data of the creation table, whatever +the oracle under it. -/ +theorem rdRel_FO_of_create {code : ByteArray} {o : Oracle} {T : RunTable} {A : CreateTable} + {w : List Event} {rd : ByteArray} (hl : lastCreate w = true) (h : RdRel (createOracle o A) w rd) : + RdRel (FO code T A) w rd := by + refine ⟨?_, fun i hi => ?_⟩ + · have := h.1 + simp only [returndataSize, createOracle, hl, ite_true, and_self] at this ⊢ + exact this + · have := h.2 i hi + simp only [returndataByte, createOracle, hl, ite_true] at this ⊢ + simpa using this + +/-- Before any message the frame's return data is empty, which every table answers. -/ +theorem RdF.nil (code : ByteArray) (T : RunTable) (A : CreateTable) : RdF code T A [] .empty := by + intro T'' A'' _ _ + have hl : lastCreate ([] : List Event) = false := by simp [lastCreate] + refine rdRel_FO_of_table hl ?_ + refine ⟨?_, fun i hi => by simp at hi⟩ + simp [returndataSize, tableOracle, RunTable.out, sent] + +set_option maxRecDepth 8000 in +/-- **`AssembleCut.seg` with CALLs, CREATE2s and CODECOPYs**: the rest of a block from an instruction, +read back from a run that succeeds, under the oracle of the run's two tables. Every extension of the +tables it ends with runs the rest of the block to the same end. -/ +theorem segF {p : Assemble.Program} {c : Cert} {mx : List Nat} {code : ByteArray} + (G : GlobT p c code) (hcr : c.creates = true) {call : Call} {msg : Message .fusaka} + {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : msg.txEnv = Target.txEnv) + {b : Nat} (hb : b < p.blocks.length) {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {fin : Evm .fusaka Nat} (hok : fin.error = none) {G0 : Nat} (hG0 : G0 < 2 ^ 256) + (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} (meets : Meets P runChild) + (hsites : SitesOk code msg P bound runChild fin) : + ∀ (n : Nat) (is : List Assemble.Instr) (h : Nat) (known : Known) (ty : List Ty) (k : Nat) + (S Tw : List Word) (s : State) (pc : Nat) (M : ByteArray) (g : Nat) + (st : State.TransactionState) (ss : Substate) (rd : ByteArray) (T : RunTable) + (A : CreateTable) (evm : Evm .fusaka Nat) (within : GasMeter.gasHeld evm.gas ≤ bound), + is.length < n → blockOkC p c mx b h known ty k is = true → h ≤ S.length → + S.length + c.need b ≤ h + maxH mx b → KR known S → SR c ty S Tw → + Seg (bytesOf code) c.offset pc + (lowerInstrs p c b is ++ lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) code.size → + S.length + k ≤ 1000 → M.size ≤ c.top → MemRel s.memory M → Rel msg ss0 st ss s → + At code msg pc Tw M g st ss rd evm → TabF T A s.world → RdF code T A s.world rd → + MemBudget G0 M g → + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + ∃ T' A' r, T.Le T' ∧ A.Le A' ∧ + (∀ T'' A'', T'.Le T'' → A'.Le A'' → + SolarTV.EVM.Program.exec (FO code T'' A'') call b is S s = r) ∧ + (∀ res, r = .inl res → PostL call msg.currentTarget ss0 res.2 res.1 fin) ∧ + (∀ y, r = .inr y → (y.1 ≤ p.blocks.length ∧ + (y.1 < p.blocks.length → c.need y.1 ≤ y.2.1.length ∧ y.2.1.length ≤ maxH mx y.1) ∧ + (y.1 = b + 1 ∨ isTarget p c y.1 = true)) ∧ + ∃ (after : Evm .fusaka Nat) (within' : GasMeter.gasHeld after.gas ≤ bound), + EntC p c mx code msg ss0 y after ∧ TabF T' A' y.2.2.world ∧ + RdF code T' A' y.2.2.world after.returnData ∧ after.gas ≤ g ∧ + memoryGasCost after.memory.size + after.gas ≤ G0 ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild after within' = .ok fin) + | 0, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, hn, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ => absurd hn (Nat.not_lt_zero _) + | n + 1, is, h, known, ty, k, S, Tw, s, pc, M, g, st, ss, rd, T, A, evm, within, hn, hokC, hh, hu, + hk, hR, hseg, hstk, htop, hmem, R, hat, hs0, hrd0, hB, hrun => by + have hTg : T.gases.length = gasReads s.world := hs0.1 + have hge : evm.gas = g := hat.2.2.2.2.2.2.1 + -- The segment with gas to spare for it alone: `K` more than the frame holds. + generalize hK : 22100 * k + memoryGasCost c.top = K + have hp := hat.addGas K + have I : InvL c code call (lowerInstrs p c b is ++ lowerFrom p c (b + 1) + (p.blocks.drop (b + 1))) k 0 pc S s M (g + K) := + ⟨hseg, hstk, by simp only [Nat.add_zero]; omega, htop, hmem⟩ + have hsim := exec_simC (mx := mx) G (o := FO code T A) hdata hvalue hstatic hself hcaller + (FO_ok c code T A).1 hbenv htx (FO_ok c code T A).2 b hb 0 (G0 + K) rd is h known ty S Tw k s pc M + (g + K) st ss hokC hh hu hk hR I R (by unfold MemBudget at *; omega) + have hcnt := (execC_agree (Agree.refl (FO code T A) (gasReads s.world) (sent s.world)) call b is S s + le_rfl le_rfl).2 + have hex : ∀ T'' A'', T.Le T'' → A.Le A'' → SolarTV.EVM.Program.exec (FO code T'' A'') call b is S s = + match execC (FO code T A) call b is S s with + | .done r => r + | .cut i rest S' s' => SolarTV.EVM.Program.exec (FO code T'' A'') call b (i :: rest) S' s' := + fun T'' A'' hle hleA => exec_F hle hleA (by omega) (le_of_eq hs0.2.2.1.symm) (le_of_eq hs0.2.2.2.2.2.2.1.symm) + generalize hr : execC (FO code T A) call b is S s = r at hsim hcnt hex + cases r with + | done r => + refine ⟨T, A, r, RunTable.Le.refl T, CreateTable.Le.refl A, fun T'' A'' hle hleA => hex T'' A'' hle hleA, + fun res hres => ?_, fun y hy => ?_⟩ + · subst hres + exact SpecG.low hsim hp within hrun hok + · subst hy + obtain ⟨t, S', s'⟩ := y + obtain ⟨⟨htle, hneedt, hj⟩, pc', T', M', g', st', ss', hh', hR', E', R', hB'⟩ := hsim + obtain ⟨e1, r1, he1⟩ := hh' _ hp + obtain ⟨m, within', hz, hrm⟩ := reaches_low r1 K evm rfl within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hmK⟩ := at_of_addGasR he1 + have hgm := reaches_gas_le r1 + rw [hz] at hgm + simp only [gas_addGas] at hgm + have hw1 := execC_world _ _ _ is S s s' (by rw [hr]; rfl) + refine ⟨⟨htle, hneedt, hj⟩, m, within', ⟨T', pc', M', st', ss', rd, htle, hneedt, hR', E'.seg, + E'.le_top, E'.mem, R', hatm⟩, ?_, ?_, by omega, + by rw [hatm.2.2.2.2.2.1]; unfold MemBudget at hB'; omega, hrm⟩ + · dsimp only + rw [hw1] + exact hs0 + · dsimp only + rw [hw1, show m.returnData = rd from hatm.2.2.2.2.2.2.2.2.2.2.2.2] + exact hrd0 + | cut i rest S' s' => + obtain ⟨hci, h', known', ty', k', pc', T', M', g', st', ss', hh', hok2, hh2, hu2, hk2, hR', + I', R', hB'⟩ := hsim + -- The segment, moved back to the frame's gas. + obtain ⟨e1, r1, he1⟩ := hh' _ hp + obtain ⟨m, within1, hz, hrm⟩ := reaches_low r1 K evm rfl within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hmK⟩ := at_of_addGasR he1 + have hgm := reaches_gas_le r1 + rw [hz] at hgm + simp only [gas_addGas] at hgm + have hL := hR'.length + have hst := I'.stack + have hc1 := hcnt.1 s' rfl + have hw1 := execC_world _ _ _ is S s s' (by rw [hr]; rfl) + have hs1 : TabF T A s'.world := by rw [hw1]; exact hs0 + have hrd1 : RdF code T A s'.world rd := by rw [hw1]; exact hrd0 + have hlen := hcnt.2 _ rest S' s' rfl + have hmB : MemBudget G0 M' m.gas := by unfold MemBudget at *; omega + have hci' : isGasI i = true ∨ isLoadI i = true ∨ isStoreI i = true ∨ isRetI i = true ∨ + isRevI i = true ∨ isKecI i = true ∨ isLogI i = true ∨ isCdcI i = true ∨ isScI i = true ∨ + isRdsI i = true ∨ isRdcI i = true ∨ isCallI i = true ∨ isC2I i = true ∨ isCcI i = true := by + simpa [isCutI, isMemCutI, or_assoc] using hci + rcases hci' with hgi | hli | hsi | hri | hvi | hki | hlgi | hcdi | hsci | hrdi | hrdci | hcalli | + hc2i | hcci + · obtain rfl := isGasI_eq hgi + obtain ⟨hk1, hok3⟩ := blockOkC_gas hok2 + have hs := I'.seg + rw [lowerInstrs_gas, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + -- GAS at the frame's gas. + obtain ⟨h2, m2, within2, hat2, hrun2⟩ := + gas_back hatm hlt hcode (by unfold STACK_LIMIT; omega) within1 hrm hok + let T1 : RunTable := { T with gases := T.gases ++ [m.gas - 2] } + have hle1 : T.Le T1 := ⟨List.prefix_refl _, List.prefix_refl _, List.prefix_refl _, + List.prefix_refl _, List.prefix_append _ _⟩ + have hv : ∀ T'', T1.Le T'' → T''.gases.getD (gasReads s'.world) 0 = m.gas - 2 := by + intro T'' hle + rw [getD_of_prefix hle.2.2.2.2 (by simp [T1]; omega)] + simp [T1, List.getD_eq_getElem?_getD, hc1.1, ← hTg] + obtain ⟨T2, A2, r, hle2, hA2, hex2, hpost, hnext⟩ := segF (G0 := G0) G hcr hdata hvalue hstatic hself hcaller hbenv + htx hb hok hG0 hdepth meets hsites n rest (h' + 1) [] (some false :: ty') (k' - 1) + (BitVec.ofNat 256 (m.gas - 2) :: S') (BitVec.ofNat 256 (m.gas - 2) :: T') + { s' with world := s'.world ++ [.read "gas"] } (pc' + 1) M' (m.gas - 2) st' ss' rd T1 A m2 + within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl hR') hseg' (by simp; omega) I'.le_top + I'.mem ⟨R'.storage, R'.account, logsRel_read _ R'.logs⟩ hat2 + (TabF.gas hs1 (m.gas - 2)) (RdF.append rfl rfl (RdF.mono hle1 (CreateTable.Le.refl A) hrd1)) + (by unfold MemBudget at *; omega) hrun2 + refine ⟨T2, A2, r, hle1.trans hle2, hA2, fun T'' A'' hle hleA => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T'' A'' (hle1.trans (hle2.trans hle)) (hA2.trans hleA)] + show SolarTV.EVM.Program.exec (FO code T'' A'') call b (.effect .gas 0 :: rest) S' s' = r + rw [exec_gasF (hv T'' (hle2.trans hle)) (by omega)] + exact hex2 T'' A'' hle hleA + · obtain ⟨hy1, after, within', hE, hT, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hrdy, by omega, hbud, hra⟩ + + · -- MLOAD at the frame's gas, at any offset. + obtain rfl := isLoadI_eq hli + obtain ⟨hk1, hh1, hdat, htop', hok3⟩ := blockOkC_load hok2 + have hs := I'.seg + rw [lowerInstrs_load, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, S''⟩ + · simp at hh2; omega + rcases T' with _ | ⟨x', Tr⟩ + · simp at hL + obtain rfl := (SR.head hR' hdat).symm + have hR'' := (SR.uncons.1 hR').2 + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + AssembleDyn.mload_dyn I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, A2, r, hle2, hA2, hex2, hpost, hnext⟩ := segF (G0 := G0) G hcr hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 hdepth meets hsites n rest h' [] (some false :: ty'.drop 1) (k' - 1) + (s'.memory.load x.toNat :: S'') (s'.memory.load x.toNat :: Tr) + { s' with memory := s'.memory.expand x.toNat 32 } (pc' + 1) M2 g2 st' ss' rd T A m2 + within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl (by simpa using hR'')) hseg' + (by simp; omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + hs1 hrd1 hb2 hrun2 + refine ⟨T2, A2, r, hle2, hA2, fun T3 A3 hle hleA => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 A3 (hle2.trans hle) (hA2.trans hleA)] + show SolarTV.EVM.Program.exec (FO code T3 A3) call b (.op .load :: rest) _ s' = r + rw [exec_loadC (by omega)] + exact hex2 T3 A3 hle hleA + · obtain ⟨hy1, after, within', hE, hT, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hrdy, by omega, hbud, hra⟩ + · -- MSTORE at the frame's gas, at any offset. + obtain rfl := isStoreI_eq hsi + obtain ⟨hk1, hh1, hdat, htop', hok3⟩ := blockOkC_store hok2 + have hs := I'.seg + rw [lowerInstrs_store, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 2) S'' Tr := by simpa using SR.drop 2 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + AssembleDyn.mstore_dyn I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, A2, r, hle2, hA2, hex2, hpost, hnext⟩ := segF (G0 := G0) G hcr hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 hdepth meets hsites n rest (h' - 2) [] (ty'.drop 2) (k' - 1) S'' Tr + { s' with memory := s'.memory.store x.toNat y } (pc' + 1) M2 g2 st' ss' rd T A m2 + within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + hs1 hrd1 hb2 hrun2 + refine ⟨T2, A2, r, hle2, hA2, fun T3 A3 hle hleA => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 A3 (hle2.trans hle) (hA2.trans hleA)] + show SolarTV.EVM.Program.exec (FO code T3 A3) call b (.op .store :: rest) _ s' = r + rw [exec_storeC (by omega)] + exact hex2 T3 A3 hle hleA + · obtain ⟨hy1, after, within', hE, hT, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hrdy, by omega, hbud, hra⟩ + + · -- RETURN at the frame's gas, from any range. + obtain rfl := isRetI_eq hri + obtain ⟨hh1, hdat⟩ := blockOkC_ret hok2 + have hs := I'.seg + rw [lowerInstrs_ret, List.cons_append] at hs + obtain ⟨next, hd, -⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hg := AssembleDyn.return_back hatm hlt hcode within1 hrm hok + refine ⟨T, A, .inl (SolarTV.EVM.Program.output s' (x :: y :: S'') false), RunTable.Le.refl T, + CreateTable.Le.refl A, fun T3 A3 hle hleA => ?_, fun res hres => ?_, fun y hy => ?_⟩ + · rw [hex T3 A3 hle hleA] + rfl + · obtain rfl := Sum.inl.inj hres + simp only [SolarTV.EVM.Program.output, Bool.false_eq_true, ↓reduceIte] + exact SpecG.low (SpecG.consequence (return_postSG (ss := ss') hlt hcode (by omega) rfl + (by rw [read_eq I'.mem]; rfl) rfl (R'.slot hself)) (fun _ h => h) + (fun _ h => ⟨ss', h, R'.logs⟩)) (hatm.addGas 0) within1 hrm hok + · cases hy + · -- REVERT: no run that succeeds reaches it. + obtain rfl := isRevI_eq hvi + obtain ⟨hh1, hdat⟩ := blockOkC_revert hok2 + have hs := I'.seg + rw [lowerInstrs_revert, List.cons_append] at hs + obtain ⟨next, hd, -⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + exact (AssembleDyn.revert_false hatm hlt hcode within1 hrm hok).elim + + · -- KECCAK256 at the frame's gas, of any range. + obtain rfl := isKecI_eq hki + obtain ⟨henv, hk1, hh1, hdat, htop', hok3⟩ := blockOkC_kec hok2 + have hs := I'.seg + rw [lowerInstrs_kec, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 2) S'' Tr := by simpa using SR.drop 2 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨m2, within2, hmem2, hb2, hat2, hrun2⟩ := + AssembleDyn.keccak_dyn I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + obtain ⟨-, hkec⟩ := (FO_ok c code T A).1 henv + rw [byteArray_eq_of_map (read_eq I'.mem), ← hkec] at hat2 + have hsz : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size ≤ c.top := by + have hmod : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size % 32 = 0 := by + rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, A2, r, hle2, hA2, hex2, hpost, hnext⟩ := segF (G0 := G0) G hcr hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 hdepth meets hsites n rest (h' - 1) [] (some false :: ty'.drop 2) (k' - 1) + ((FO code T A).keccak ((s'.memory.expand x.toNat y.toNat).read x.toNat y.toNat) :: S'') + ((FO code T A).keccak ((s'.memory.expand x.toNat y.toNat).read x.toNat y.toNat) :: Tr) + { s' with memory := s'.memory.expand x.toNat y.toNat } (pc' + 1) _ _ st' ss' rd T A m2 + within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl (by simpa using hR'')) hseg' + (by simp; omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + hs1 hrd1 hb2 hrun2 + refine ⟨T2, A2, r, hle2, hA2, fun T3 A3 hle hleA => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 A3 (hle2.trans hle) (hA2.trans hleA)] + show SolarTV.EVM.Program.exec (FO code T3 A3) call b (.effect .keccak256 2 :: rest) _ s' = r + rw [exec_keccakC (by omega)] + exact hex2 T3 A3 hle hleA + · obtain ⟨hy1, after, within', hE, hT, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hrdy, by omega, hbud, hra⟩ + + · -- LOGn at the frame's gas, of any range. + obtain ⟨nl, hn4, rfl⟩ := isLogI_eq hlgi + obtain ⟨hk1, hnh, hdat, htop', hok3⟩ := blockOkC_log hn4 hok2 + have hs := I'.seg + rw [lowerInstrs_log p c b hn4, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S1⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', T1⟩⟩ + · simp at hL + · simp at hL + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨tops, S2, rfl, hlen⟩ : ∃ tops S2, S1 = tops ++ S2 ∧ tops.length = nl := + ⟨S1.take nl, S1.drop nl, (List.take_append_drop nl S1).symm, by simp; omega⟩ + obtain ⟨tops', T2, rfl, hlen'⟩ : ∃ tops' T2, T1 = tops' ++ T2 ∧ tops'.length = nl := + ⟨T1.take nl, T1.drop nl, (List.take_append_drop nl T1).symm, by simp; omega⟩ + subst hlen + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.cons.injEq, List.take_left' hlen', + List.take_left' rfl] at htake + obtain ⟨rfl, rfl, rfl⟩ := htake + have hR'' : SR c (ty'.drop (tops.length + 2)) S2 T2 := by + simpa using SR.drop (tops.length + 2) hR' + simp only [List.length_append] at hL hst hh2 hu2 + obtain ⟨m2, within2, hmem2, hb2, hat2, hrun2⟩ := + AssembleDyn.log_dyn (n := ⟨tops.length, by omega⟩) I'.mem hmB (by omega) hatm rfl hlt hcode + (decode_log ⟨tops.length, by omega⟩) hstatic within1 hrm hok + have hsz : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size ≤ c.top := by + have hmod : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size % 32 = 0 := by + rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨L, hL1, hL2⟩ := R'.logs + obtain ⟨T2', A2, r, hle2, hA2, hex2, hpost, hnext⟩ := segF (G0 := G0) (ss0 := ss0) G hcr hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 hdepth meets hsites n rest (h' - (tops.length + 2)) [] (ty'.drop (tops.length + 2)) + (k' - 1) S2 T2 + ⟨s'.memory.expand x.toNat y.toNat, s'.storage, s'.transient, + s'.world ++ [.log tops ((s'.memory.expand x.toNat y.toNat).read x.toNat y.toNat)]⟩ + (pc' + 1) _ _ st' { ss' with logs := ss'.logs.push ⟨msg.currentTarget, + tops.map U256.toBeBytes, memoryReadBytes (memoryExtend M' (extendMemory M'.size + [(x, y)]).expandBy) x.toNat y.toNat⟩ } rd T A m2 within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 + ⟨R'.storage, R'.account, ⟨L ++ [⟨msg.currentTarget, tops.map U256.toBeBytes, + memoryReadBytes (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy) + x.toNat y.toNat⟩], by simp [Array.toList_push, hL1], + filter_snoc_log ▸ forall₂_snoc hL2 ⟨rfl, rfl, read_eq I'.mem⟩⟩⟩ hat2 + (TabF.log hs1 _ _) (RdF.append rfl rfl hrd1) hb2 hrun2 + refine ⟨T2', A2, r, hle2, hA2, fun T3 A3 hle hleA => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 A3 (hle2.trans hle) (hA2.trans hleA)] + show SolarTV.EVM.Program.exec (FO code T3 A3) call b + (.effect (.log tops.length) (tops.length + 2) :: rest) _ s' = r + rw [exec_logC (by omega)] + exact hex2 T3 A3 hle hleA + · obtain ⟨hy1, after, within', hE, hT, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hrdy, by omega, hbud, hra⟩ + + · -- CALLDATACOPY at the frame's gas, of any range. + obtain rfl := isCdcI_eq hcdi + obtain ⟨hk1, hh1, hdat, htop', hok3⟩ := blockOkC_cdc hok2 + have hs := I'.seg + rw [lowerInstrs_cdc, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, _ | ⟨z, S''⟩⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', _ | ⟨z', Tr⟩⟩⟩ + · simp at hL + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 3) S'' Tr := by simpa using SR.drop 3 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + AssembleDynCopy.cdc_dyn hdata I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, A2, r, hle2, hA2, hex2, hpost, hnext⟩ := segF (G0 := G0) (ss0 := ss0) G hcr hdata hvalue + hstatic hself hcaller hbenv htx hb hok hG0 hdepth meets hsites n rest (h' - 3) [] (ty'.drop 3) (k' - 1) S'' Tr + { s' with + memory := s'.memory.write x.toNat z.toNat + (fun i => SolarTV.Machine.calldataByte call (y.toNat + i)) } (pc' + 1) M2 g2 st' ss' rd T A m2 + within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + hs1 hrd1 hb2 hrun2 + refine ⟨T2, A2, r, hle2, hA2, fun T3 A3 hle hleA => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 A3 (hle2.trans hle) (hA2.trans hleA)] + show SolarTV.EVM.Program.exec (FO code T3 A3) call b (.effect .calldatacopy 3 :: rest) _ s' = r + rw [exec_cdcC (by omega)] + exact hex2 T3 A3 hle hleA + · obtain ⟨hy1, after, within', hE, hT, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hrdy, by omega, hbud, hra⟩ + · -- STATICCALL: the checker refuses it in a program that creates. + exact absurd (blockOkC_noSc_creates hsci hok2) (by simp [hcr]) + · -- RETURNDATASIZE at the frame's gas: the size of the frame's return data, the tables'. + obtain rfl := isRdsI_eq hrdi + obtain ⟨-, hk1, hok3⟩ := blockOkC_rds hok2 + have hs := I'.seg + rw [AssembleCallSeg.lowerInstrs_rds, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + obtain ⟨h2, m2, within2, hat2, hrun2⟩ := + AssembleCallSeg.rds_back hatm hlt hcode (by unfold STACK_LIMIT; omega) within1 hrm hok + have hv : ∀ T3 A3, T.Le T3 → A.Le A3 → + (FO code T3 A3).env "returndatasize" s'.world [] = BitVec.ofNat 256 rd.size := by + intro T3 A3 hle hleA + have h1 := (hrd1 T3 A3 hle hleA).1 + simp only [returndataSize] at h1 + have hlt' : rd.size < 2 ^ 256 := by rw [← h1]; exact BitVec.isLt _ + apply BitVec.eq_of_toNat_eq + rw [BitVec.toNat_ofNat, h1, Nat.mod_eq_of_lt hlt'] + obtain ⟨T2, A2, r, hle2, hA2, hex2, hpost, hnext⟩ := segF (G0 := G0) G hcr hdata hvalue + hstatic hself hcaller hbenv htx hb hok hG0 hdepth meets hsites n rest (h' + 1) [] + (some false :: ty') (k' - 1) (BitVec.ofNat 256 rd.size :: S') + (BitVec.ofNat 256 rd.size :: T') s' (pc' + 1) M' (m.gas - 2) st' ss' rd T A m2 within2 + (by omega) hok3 (by simp; omega) (by simp; omega) (KR.nil _) + (SR.cons (τ := some false) rfl hR') hseg' (by simp; omega) I'.le_top I'.mem R' hat2 hs1 + hrd1 (by unfold MemBudget at *; omega) hrun2 + refine ⟨T2, A2, r, hle2, hA2, fun T3 A3 hle hleA => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 A3 (hle2.trans hle) (hA2.trans hleA)] + show SolarTV.EVM.Program.exec (FO code T3 A3) call b (.effect .returndatasize 0 :: rest) S' s' = r + rw [AssembleCallSeg.exec_rdsC (hv T3 A3 (hle2.trans hle) (hA2.trans hleA)) (by omega)] + exact hex2 T3 A3 hle hleA + · obtain ⟨hy1, after, within', hE, hT, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hrdy, by omega, hbud, hra⟩ + · -- RETURNDATACOPY at the frame's gas, of any range within the return data. + obtain rfl := isRdcI_eq hrdci + obtain ⟨-, hk1, hh1, hdat, htop', hok3⟩ := blockOkC_rdc hok2 + have hs := I'.seg + rw [AssembleCallSeg.lowerInstrs_rdc, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, _ | ⟨z, S''⟩⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', _ | ⟨z', Tr⟩⟩⟩ + · simp at hL + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 3) S'' Tr := by simpa using SR.drop 3 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨hfit, M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + AssembleCallSeg.rdc_dyn I'.mem hmB (by omega) (hrd1 T A (RunTable.Le.refl T) + (CreateTable.Le.refl A)) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + have hext : ∀ T3 A3, T.Le T3 → A.Le A3 → returndataByte (FO code T3 A3) s'.world = + returndataByte (FO code T A) s'.world := by + intro T3 A3 hle hleA + funext i + simp only [returndataByte] + rw [createTable_agree (baseF code) hle hleA (le_of_eq hs1.1.symm) (le_of_eq hs1.2.2.1.symm) + (le_of_eq hs1.2.2.2.2.2.2.1.symm)] + obtain ⟨T2, A2, r, hle2, hA2, hex2, hpost, hnext⟩ := segF (G0 := G0) G hcr hdata hvalue + hstatic hself hcaller hbenv htx hb hok hG0 hdepth meets hsites n rest (h' - 3) [] (ty'.drop 3) + (k' - 1) S'' Tr + { s' with + memory := s'.memory.write x.toNat z.toNat + (fun i => returndataByte (FO code T A) s'.world (y.toNat + i)) } (pc' + 1) M2 g2 st' ss' rd + T A m2 within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + hs1 hrd1 hb2 hrun2 + refine ⟨T2, A2, r, hle2, hA2, fun T3 A3 hle hleA => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 A3 (hle2.trans hle) (hA2.trans hleA)] + show SolarTV.EVM.Program.exec (FO code T3 A3) call b (.effect .returndatacopy 3 :: rest) _ s' = r + rw [AssembleCallSeg.exec_rdcC (by rw [(hrd1 T3 A3 (hle2.trans hle) (hA2.trans hleA)).1]; exact hfit) + (by omega), hext T3 A3 (hle2.trans hle) (hA2.trans hleA)] + exact hex2 T3 A3 hle hleA + · obtain ⟨hy1, after, within', hE, hT, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hrdy, by omega, hbud, hra⟩ + · -- CALL at the frame's gas: the callee's flag, output and the storage after join the table. + obtain rfl := isCallI_eq hcalli + obtain ⟨-, -, hk1, hh1, hdat, htop', hok3⟩ := blockOkC_call hok2 + have hs := I'.seg + rw [lowerInstrs_call, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x1, _ | ⟨x2, _ | ⟨x3, _ | ⟨x4, _ | ⟨x5, _ | ⟨x6, _ | ⟨x7, S''⟩⟩⟩⟩⟩⟩⟩ + all_goals (first | (simp at hh2; omega) | skip) + rcases T' with _ | ⟨y1, _ | ⟨y2, _ | ⟨y3, _ | ⟨y4, _ | ⟨y5, _ | ⟨y6, _ | ⟨y7, Tr⟩⟩⟩⟩⟩⟩⟩ + all_goals (first | (simp at hL; done) | skip) + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 7) S'' Tr := by simpa using SR.drop 7 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨ok, out, s2, st2, ss2, M2, g2, m2, within2, hall, hw, hmem2, R2, hb2, hg2, hat2, + hrun2⟩ : ∃ (ok : Bool) (out : ByteArray) (s2 : State) (st2 : State.TransactionState) + (ss2 : Substate) (M2 : ByteArray) (g2 : Nat) (m2 : Evm .fusaka Nat) + (within2 : GasMeter.gasHeld m2.gas ≤ bound), + (∀ T'', (pushCall T ok out (storeOf st2 msg.currentTarget)).Le T'' → + Effect.apply (tableOracle (baseF code) T'') call (.call .call) + [x1, x2, x3, x4, x5, x6, x7] s' = some (some (if ok then 1 else 0), s2) ∧ + RdRel (tableOracle (baseF code) T'') s2.world out) ∧ + s2.world = callWorld s' x1 x2 x3 x4 x5 x6 x7 ∧ MemRel s2.memory M2 ∧ + Rel msg ss0 st2 ss2 s2 ∧ MemBudget G0 M2 g2 ∧ g2 ≤ m.gas ∧ + At code msg (pc' + 1) ((if ok then 1 else 0) :: Tr) M2 g2 st2 ss2 out m2 ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m2 within2 = .ok fin := by + by_cases hv : x3 = 0 + · subst hv + obtain ⟨ok, out, s2, st2, ss2, M2, g2, m2, within2, hall, hw, hmem2, R2, hb2, hg2, hat2, + hrun2⟩ := call0_cutQ (baseF code) T I'.mem R' hmB (by omega) hatm hlt hcode hstatic + hdepth meets (hsites.call0 hatm hlt hcode hrm) within1 hrm hok + hs1.2.1 hs1.2.2.1 hs1.2.2.2.1 hs1.2.2.2.2.1 + exact ⟨ok, out, s2, st2, ss2, M2, g2, m2, within2, fun T'' hle => hall T'' hle, hw, + hmem2, R2, hb2, hg2, hat2, hrun2⟩ + · obtain ⟨cc, hcc, hdel, hq⟩ := hsites.callV hatm hlt hcode hv hrm + obtain ⟨ok, out, s2, st2, ss2, M2, g2, m2, within2, hall, hw, hmem2, R2, hb2, hg2, hat2, + hrun2⟩ := callValue_cutQ (baseF code) T I'.mem R' hmB (by omega) hatm hlt hcode hv + hstatic hcc hdel hdepth meets hq + within1 hrm hok hs1.2.1 hs1.2.2.1 hs1.2.2.2.1 hs1.2.2.2.2.1 + exact ⟨ok, out, s2, st2, ss2, M2, g2, m2, within2, fun T'' hle => hall T'' hle, hw, + hmem2, R2, hb2, hg2, hat2, hrun2⟩ + have hle1 := le_pushCall T ok out (storeOf st2 msg.currentTarget) + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + have hT1 : TabF (pushCall T ok out (storeOf st2 msg.currentTarget)) A s2.world := by + rw [hw] + exact TabF.call hs1 ok out _ .call [x1, x2, x3] _ _ _ + have hRd1 : RdF code (pushCall T ok out (storeOf st2 msg.currentTarget)) A s2.world out := by + intro T'' A'' h1 _ + have hl : lastCreate s2.world = false := by + rw [hw] + simp [callWorld, lastCreate, List.filter_append, Event.sends] + exact rdRel_FO_of_table hl (hall T'' h1).2 + obtain ⟨T2, A2, r, hle2, hA2, hex2, hpost, hnext⟩ := segF (G0 := G0) G hcr hdata hvalue + hstatic hself hcaller hbenv htx hb hok hG0 hdepth meets hsites n rest (h' - 6) [] + (some false :: ty'.drop 7) (k' - 1) ((if ok then 1 else 0) :: S'') + ((if ok then 1 else 0) :: Tr) s2 (pc' + 1) M2 g2 st2 ss2 out _ A m2 within2 (by omega) + hok3 (by simp; omega) (by simp; omega) (KR.nil _) (SR.cons (τ := some false) rfl hR'') + hseg' (by simp; omega) hsz hmem2 R2 hat2 hT1 hRd1 hb2 hrun2 + refine ⟨T2, A2, r, hle1.trans hle2, hA2, fun T3 A3 hle hleA => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 A3 (hle1.trans (hle2.trans hle)) (hA2.trans hleA)] + show SolarTV.EVM.Program.exec (FO code T3 A3) call b + (.effect (.call .call) 7 :: rest) _ s' = r + have happ3 : Effect.apply (FO code T3 A3) call (.call .call) [x1, x2, x3, x4, x5, x6, x7] s' = + some (some (if ok then 1 else 0), s2) := by + rw [apply_call_createOracle] + exact (hall T3 (hle2.trans hle)).1 + rw [exec_callC happ3 (by omega)] + exact hex2 T3 A3 hle hleA + · obtain ⟨hy1, after, within', hE, hT, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hrdy, by omega, hbud, hra⟩ + · -- CREATE2 at the frame's gas: its word, return data and the storage after join the + -- creation table, and an entry at its message the run table. + obtain rfl := isC2I_eq hc2i + obtain ⟨-, -, hk1, hh1, hdat, htop', hok3⟩ := blockOkC_c2 hok2 + have hs := I'.seg + rw [lowerInstrs_c2, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x1, _ | ⟨x2, _ | ⟨x3, _ | ⟨x4, S''⟩⟩⟩⟩ + all_goals (first | (simp at hh2; omega) | skip) + rcases T' with _ | ⟨y1, _ | ⟨y2, _ | ⟨y3, _ | ⟨y4, Tr⟩⟩⟩⟩ + all_goals (first | (simp at hL; done) | skip) + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 4) S'' Tr := by simpa using SR.drop 4 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + have hle1 := le_pushCall T false .empty (fun _ => 0) + obtain ⟨r0, out, st2, ss2, M2, g2, m2, within2, hall, hmem2, R2, hb2, hg2, hat2, hrun2⟩ := + create2_cutQ (tableOracle (baseF code) (pushCall T false .empty (fun _ => 0))) A I'.mem R' + hmB hG0 hatm hlt hcode hstatic meets (hsites.create2 hatm hlt hcode hrm) + within1 hrm hok hs1.2.2.2.2.2.1 hs1.2.2.2.2.2.2.1 hs1.2.2.2.2.2.2.2 + have hleA1 := CreateTable.le_push A r0 out (storeOf st2 msg.currentTarget) + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + have hT1 : TabF (pushCall T false .empty (fun _ => 0)) + (A.push r0 out (storeOf st2 msg.currentTarget)) + (postCreate (tableOracle (baseF code) (pushCall T false .empty (fun _ => 0))) s' + (storeOf st2 msg.currentTarget) x1 x2 x3 x4).world := + TabF.create hs1 r0 out _ [x1, x4] _ _ _ + have hRd1 : RdF code (pushCall T false .empty (fun _ => 0)) + (A.push r0 out (storeOf st2 msg.currentTarget)) + (postCreate (tableOracle (baseF code) (pushCall T false .empty (fun _ => 0))) s' + (storeOf st2 msg.currentTarget) x1 x2 x3 x4).world out := by + intro T'' A'' _ h2 + have hl : lastCreate (createWorld s' x1 x2 x3 x4) = true := by + simp [createWorld] + exact rdRel_FO_of_create hl (hall A'' h2).2 + obtain ⟨T2, A2, r, hle2, hA2, hex2, hpost, hnext⟩ := segF (G0 := G0) G hcr hdata hvalue + hstatic hself hcaller hbenv htx hb hok hG0 hdepth meets hsites n rest (h' - 3) [] + (some false :: ty'.drop 4) (k' - 1) (r0 :: S'') (r0 :: Tr) _ (pc' + 1) M2 g2 st2 ss2 out _ + _ m2 within2 (by omega) hok3 (by simp; omega) (by simp; omega) (KR.nil _) + (SR.cons (τ := some false) rfl hR'') hseg' (by simp; omega) hsz hmem2 R2 hat2 hT1 hRd1 hb2 hrun2 + refine ⟨T2, A2, r, hle1.trans hle2, hleA1.trans hA2, fun T3 A3 hle hleA => ?_, hpost, + fun y hy => ?_⟩ + · rw [hex T3 A3 (hle1.trans (hle2.trans hle)) (hleA1.trans (hA2.trans hleA))] + show SolarTV.EVM.Program.exec (FO code T3 A3) call b (.effect .create2 4 :: rest) _ s' = r + have hlA := (hA2.trans hleA).2.2.length_le + simp only [CreateTable.push, List.length_append, List.length_singleton] at hlA + have htr := hs1.2.2.2.2.1 + have hAst := hs1.2.2.2.2.2.2.2 + have hsent : sent s'.world < (pushCall T false .empty (fun _ => 0)).transients.length := by + simp only [pushCall, List.length_append, List.length_singleton] + omega + have happ3 : Effect.apply (FO code T3 A3) call .create2 [x1, x2, x3, x4] s' = + some (some r0, postCreate (tableOracle (baseF code) (pushCall T false .empty (fun _ => 0))) + s' (storeOf st2 msg.currentTarget) x1 x2 x3 x4) := by + rw [create2_table (hle2.trans hle) hsent (by omega)] + exact (hall A3 (hA2.trans hleA)).1 + rw [exec_c2C happ3 (by omega)] + exact hex2 T3 A3 hle hleA + · obtain ⟨hy1, after, within', hE, hT, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hrdy, by omega, hbud, hra⟩ + · -- CODECOPY at the frame's gas, at the code offset the checker knows. + obtain rfl := isCcI_eq hcci + obtain ⟨-, -, ⟨x0, off0, t0, rfl, hoff⟩, hk1, hh1, hdat, htop', hok3⟩ := blockOkC_cc hok2 + have hs := I'.seg + rw [lowerInstrs_cc, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, _ | ⟨z, S''⟩⟩⟩ + all_goals (first | (simp at hh2; omega) | skip) + rcases T' with _ | ⟨x', _ | ⟨y', _ | ⟨z', Tr⟩⟩⟩ + all_goals (first | (simp at hL; done) | skip) + have hu : off0 = y := by simpa [kAt] using (hk2 1 off0 (by simp [kAt])).symm + obtain rfl := hu + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 3) S'' Tr := by simpa using SR.drop 3 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨M2, g2, m2, within2, -, hmem2, R2, hb2, hg2, hat2, hrun2⟩ := + codecopy_cut (call := call) (FO_codeOk code T A) hoff I'.mem R' hmB hG0 hatm hlt hcode + within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, A2, r, hle2, hA2, hex2, hpost, hnext⟩ := segF (G0 := G0) G hcr hdata hvalue + hstatic hself hcaller hbenv htx hb hok hG0 hdepth meets hsites n rest (h' - 3) [] + (ty'.drop 3) (k' - 1) S'' Tr _ (pc' + 1) M2 g2 st' + ss' rd T A m2 within2 (by omega) hok3 (by omega) (by omega) (KR.nil _) hR'' hseg' + (by omega) hsz hmem2 R2 hat2 hs1 hrd1 hb2 hrun2 + refine ⟨T2, A2, r, hle2, hA2, fun T3 A3 hle hleA => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 A3 (hle2.trans hle) (hA2.trans hleA)] + show SolarTV.EVM.Program.exec (FO code T3 A3) call b (.effect .codecopy 3 :: rest) _ s' = r + rw [exec_codecopy (by omega), codeCopied_FO code T T3 A A3] + exact hex2 T3 A3 hle hleA + · obtain ⟨hy1, after, within', hE, hT, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hrdy, by omega, hbud, hra⟩ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateSegF.segF' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms segF + +end SolidCore.Refinement.Solar.AssembleCreateSegF diff --git a/SolidCore/Refinement/Solar/AssembleCreateSegOracle.lean b/SolidCore/Refinement/Solar/AssembleCreateSegOracle.lean new file mode 100644 index 00000000..710e5b7b --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCreateSegOracle.lean @@ -0,0 +1,98 @@ +import SolidCore.Refinement.Solar.AssembleCallValueZeroSeg + +/-! +# The oracle of a run with calls, creations and GAS reads + +A segment that cuts at CALL, CREATE2 and GAS reads its answers from two tables: the run's table +(`RunOracle.RunTable`, indexed by the messages a world sent, calls and creations alike, and by its GAS reads) +and the table of its creations (`AssembleCreateSeg.CreateTable`). The oracle of both is +`createOracle (tableOracle base T) A`. These facts say each cut lemma holds under it: + +* `apply_call_createOracle`: a call is answered as by `tableOracle base T` (the world with a call has a + call as its last message), so `AssembleCallValueSeg.callValue_cut` and + `AssembleCallValueZeroSeg.call0_cut` hold under the combined oracle as stated; +* `AssembleCreateSeg.create2_cut` holds for any base, so for `tableOracle base T` (whose table then needs an + entry at the creation's message index, which only its transient storage after the creation reads); +* the return data of the last message is kept by GAS reads and logs (`rdRel_read`, `rdRel_log`) after a + creation, as `RunOracle` keeps it after a call. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCreateSegOracle + +open SolarTV SolarTV.Machine +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.RunOracle +open SolidCore.Refinement.Solar.AssembleEffects SolidCore.Refinement.Solar.AssembleCreateSeg + +/-- The return data of a world whose last message is no creation is the base oracle's. -/ +theorem returndataByte_other {o : Oracle} {A : CreateTable} {w : List Event} + (h : lastCreate w = false) : returndataByte (createOracle o A) w = returndataByte o w := by + funext i + simp [returndataByte, createOracle, h] + +/-- **A call is answered as by the base oracle.** -/ +theorem apply_call_createOracle (o : Oracle) (A : CreateTable) (call : Call) + (k : SolarTV.Machine.CallKind) (ops : List Word) (s : State) : + Effect.apply (createOracle o A) call (.call k) ops s = Effect.apply o call (.call k) ops s := by + simp only [Effect.apply] + split + · rfl + · cases k <;> + (simp only [called] + rw [returndataByte_other (lastCreate_call _ _ _ _ _ _)] + simp only [callFlag, returndataSize, createOracle, lastCreate_call, Bool.false_eq_true, + ite_false]) + +/-- The return data a world whose last message is a creation leaves, after a GAS read. -/ +theorem env_read {o : Oracle} {A : CreateTable} {w : List Event} (hl : lastCreate w = true) + (n name : String) (args : List Word) (hname : name = "returndatasize" ∨ name = "returndata") + (hargs : name = "returndatasize" → args = []) (hone : name = "returndata" → args.length = 1) : + (createOracle o A).env name (w ++ [.read n]) args = (createOracle o A).env name w args := by + rcases hname with rfl | rfl + · simp [createOracle, hl, hargs rfl, CreateTable.out] + · match args, hone rfl with + | [i], _ => simp [createOracle, hl, CreateTable.out] + +/-- **A GAS read keeps the return data of a creation.** -/ +theorem rdRel_read {o : Oracle} {A : CreateTable} {w : List Event} {out : ByteArray} + (hl : lastCreate w = true) (n : String) (h : RdRel (createOracle o A) w out) : + RdRel (createOracle o A) (w ++ [.read n]) out := by + refine ⟨?_, fun i hi => ?_⟩ + · simp only [returndataSize] + rw [env_read hl n _ [] (.inl rfl) (fun _ => rfl) (by simp)] + exact h.1 + · simp only [returndataByte] + rw [env_read hl n _ _ (.inr rfl) (by simp) (fun _ => rfl)] + exact h.2 i hi + +/-- The same after a log. -/ +theorem env_log {o : Oracle} {A : CreateTable} {w : List Event} (hl : lastCreate w = true) + (t : List Word) (d : List Memory.Byte) (name : String) (args : List Word) + (hname : name = "returndatasize" ∨ name = "returndata") + (hargs : name = "returndatasize" → args = []) (hone : name = "returndata" → args.length = 1) : + (createOracle o A).env name (w ++ [.log t d]) args = (createOracle o A).env name w args := by + rcases hname with rfl | rfl + · simp [createOracle, hl, hargs rfl, CreateTable.out] + · match args, hone rfl with + | [i], _ => simp [createOracle, hl, CreateTable.out] + +/-- **A log keeps the return data of a creation.** -/ +theorem rdRel_log {o : Oracle} {A : CreateTable} {w : List Event} {out : ByteArray} + (hl : lastCreate w = true) (t : List Word) (d : List Memory.Byte) + (h : RdRel (createOracle o A) w out) : RdRel (createOracle o A) (w ++ [.log t d]) out := by + refine ⟨?_, fun i hi => ?_⟩ + · simp only [returndataSize] + rw [env_log hl t d _ [] (.inl rfl) (fun _ => rfl) (by simp)] + exact h.1 + · simp only [returndataByte] + rw [env_log hl t d _ _ (.inr rfl) (by simp) (fun _ => rfl)] + exact h.2 i hi + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateSegOracle.apply_call_createOracle' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms apply_call_createOracle + +/-- info: 'SolidCore.Refinement.Solar.AssembleCreateSegOracle.rdRel_read' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms rdRel_read + +end SolidCore.Refinement.Solar.AssembleCreateSegOracle diff --git a/SolidCore/Refinement/Solar/AssembleCtx.lean b/SolidCore/Refinement/Solar/AssembleCtx.lean new file mode 100644 index 00000000..5d6f5a3e --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCtx.lean @@ -0,0 +1,561 @@ +import SolidCore.Refinement.Solar.AssembleCut +import SolidCore.Refinement.Solar.AssembleCtxTrack + +/-! +# EVM IR to bytecode, block by block in each of a block's contexts + +\`AssembleCut.checkC\` gives each block one entry height and one stack type, and checks a dynamic +jump against every block a return label names. An internal function called from two stack +heights, or with different words under its frame, has no such type: after its return each caller +needs the words it left under the frame typed as it left them, which the callee's one type cannot +say for both. This checker, \`checkX\`, checks each block once in each of its *contexts* (\`Ctx\`): +an entry height range and types for the whole stack the context knows, what the words are as +labels (\`AssembleCtxTrack.Lab\`), and the context each successor enters in. A return label is +then known as the label it is (\`exits\`), so a dynamic jump enters the one context its caller +named, at the caller's height and types. + +Soundness reuses the checker with GAS: in context \`j\`, block \`b\` is checked by +\`AssembleCut.blockOkC\` under a certificate (\`certAt\`) that has \`b\`'s entry from the context +and each successor's from the context it enters in (every other block's entry asks for nothing). +\`AssembleCut.seg\` runs the block against the bytecode under that certificate, and +\`AssembleCtxTrack.exits_sound\` says which block, and so which context, SolarTV's run of it +enters, with the words there known as the context needs them. The invariant at a block entry +(\`EntX\`) is \`AssembleCut.EntT\` under some certificate of the same layout, with the entry of a +context of that block. \`withinRun_of_checkX\` is \`AssembleCut.withinRun_of_checkC\`'s statement, +unchanged in shape, for every program the context checker accepts. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCtx + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Final +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.RunOracle SolidCore.Refinement.Solar.AssembleRun +open SolidCore.Refinement.Solar.AssembleRunLoop SolidCore.Refinement.Solar.AssembleCut +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +/-! ## Certificates with contexts -/ + +/-- One context of a block: the least and the greatest height it is entered at, the types of the +words on top of its stack, what they are as labels, and the context (by its index among the +successor's) each block it leaves to enters in, and the blocks its labels may name. A jump to its +own block stays in it. -/ +structure Ctx where + need : Nat + max : Nat + types : List Ty := [] + labs : List Lab := [] + succ : List (Nat × Nat) := [] + /-- The blocks a label on its stack, or one the block pushes, may name. -/ + rets : List Nat := [] + deriving Repr + +/-- The context that asks for nothing. -/ +def trivialCtx : Ctx := { need := 0, max := 4096 } + +/-- A certificate with contexts: the layout and the flags of \`base\` (its \`needs\` and \`types\` +are unused), and each block's contexts. -/ +structure CtxCert where + base : Cert + ctxs : List (List Ctx) + deriving Repr + +def CtxCert.at (cx : CtxCert) (t j : Nat) : Ctx := (cx.ctxs.getD t []).getD j trivialCtx + +def CtxCert.count (cx : CtxCert) (t : Nat) : Nat := (cx.ctxs.getD t []).length + +/-- The context block \`t\` is entered in from block \`b\` in context \`j\`. -/ +def exitCtx (cx : CtxCert) (b j t : Nat) : Option Nat := + if t = b then some j else (cx.at b j).succ.lookup t + +/-- What block \`b\` in context \`j\` asks of block \`t\`'s entry. -/ +def pick (cx : CtxCert) (b j t : Nat) : Ctx := + match exitCtx cx b j t with + | some j' => cx.at t j' + | none => trivialCtx + +/-- The certificate block \`b\` is checked under in context \`j\`, over blocks below \`n\`. -/ +def certAt (cx : CtxCert) (n b j : Nat) : Cert := + { cx.base with + needs := (List.range n).map fun t => (pick cx b j t).need + types := (List.range n).map fun t => (pick cx b j t).types + rets := (cx.at b j).rets } + +def maxsAt (cx : CtxCert) (n b j : Nat) : List Nat := (List.range n).map fun t => (pick cx b j t).max + +/-- Every word \`W\` knows as a label, \`L\` knows as one of fewer blocks. -/ +def labLe (L W : List Lab) : Bool := + (List.range W.length).all fun i => + match labAt W i with + | none => true + | some ws => + match labAt L i with + | some ts => ts.all fun t => ws.contains t + | none => false + +/-- Every word the types call a label is one the context knows as a label of the blocks `R`. -/ +def labsCover (ty : List Ty) (L : List Lab) (R : List Nat) : Bool := + (List.range ty.length).all fun i => tyAt ty i != some true || + match labAt L i with + | some ts => ts.all fun t => R.contains t + | none => false + +/-- The block's check under a certificate, as \`AssembleCut.blocksOkC\` checks each block. -/ +def blockCtxOk (p : Assemble.Program) (c : Cert) (mx : List Nat) (b : Nat) + (instrs : List Assemble.Instr) : Bool := + decide (labelItems p c b ≤ budget c b) && decide (c.need b ≤ maxH mx b) && + decide (maxH mx b + budget c b ≤ 1000) && + blockOkC p c mx b (c.need b) [] (c.entry b) (budget c b - labelItems p c b) instrs + +/-- Each block the run of block \`b\` in context \`j\` may leave to below \`n\` enters a context of it +that the words there meet. -/ +def exitsOk (n : Nat) (cx : CtxCert) (b j : Nat) : Option (List (Nat × List Lab)) → Bool + | none => false + | some E => E.all fun e => decide (n ≤ e.1) || + match exitCtx cx b j e.1 with + | some j' => decide (j' < cx.count e.1) && labLe e.2 (cx.at e.1 j').labs + | none => false + +/-- Block \`b\` in context \`j\`. -/ +def ctxOk (p : Assemble.Program) (cx : CtxCert) (b j : Nat) (instrs : List Assemble.Instr) : Bool := + blockCtxOk p (certAt cx (p.blocks.length + 1) b j) (maxsAt cx (p.blocks.length + 1) b j) b instrs && + exitsOk p.blocks.length cx b j (exits b (cx.at b j).labs instrs) && + labsCover (cx.at b j).types (cx.at b j).labs (cx.at b j).rets + +/-- Every block in every one of its contexts. -/ +def blocksX (p : Assemble.Program) (cx : CtxCert) : Nat → List (List Assemble.Instr) → Bool + | _, [] => true + | b, instrs :: rest => + (List.range (cx.count b)).all (fun j => ctxOk p cx b j instrs) && blocksX p cx (b + 1) rest + +/-- **The checker with contexts**, for programs that make no call: the layout of \`checkC\`, the +first block's first context at height zero, and every block in each of its contexts. -/ +def checkX (p : Assemble.Program) (code : ByteArray) (cx : CtxCert) : Bool := + (walk (bytesOf code) cx.base.offset 0 (lower p cx.base)).isSome && labelsValid p cx.base code && + decide (cx.base.top % 32 = 0) && decide (cx.base.top ≤ 2 ^ 200) && decide (code.size < 2 ^ 32) && + !cx.base.calls && decide (0 < cx.count 0) && decide ((cx.at 0 0).need = 0) && + blocksX p cx 0 p.blocks + +/-! ## Certificates of one layout -/ + +/-- Two certificates of one layout and memory bound. -/ +def Same (c1 c2 : Cert) : Prop := + c1.offsets = c2.offsets ∧ c1.turned = c2.turned ∧ c1.top = c2.top + +theorem Same.offset {c1 c2 : Cert} (h : Same c1 c2) : c1.offset = c2.offset := by + funext t; simp [Cert.offset, h.1] + +theorem turnedElse_congr {c1 c2 : Cert} (h : c1.turned = c2.turned) (b : Nat) (i : Assemble.Instr) + (rest : List Assemble.Instr) : turnedElse c1 b i rest = turnedElse c2 b i rest := by + unfold turnedElse; rw [h] + +theorem lowerInstrs_congr {c1 c2 : Cert} (h : c1.turned = c2.turned) (p : Assemble.Program) (b : Nat) : + ∀ l, lowerInstrs p c1 b l = lowerInstrs p c2 b l + | [] => rfl + | i :: rest => by + simp only [lowerInstrs, turnedElse_congr h b i rest, lowerInstrs_congr h p b rest] + +theorem bodies_congr {c1 c2 : Cert} (h : c1.turned = c2.turned) (p : Assemble.Program) : + ∀ b l, bodies p c1 b l = bodies p c2 b l + | _, [] => rfl + | b, x :: l => by simp only [bodies, lowerInstrs_congr h p b x, bodies_congr h p (b + 1) l] + +theorem isTarget_congr {c1 c2 : Cert} (h : c1.turned = c2.turned) (p : Assemble.Program) (t : Nat) : + isTarget p c1 t = isTarget p c2 t := by + simp only [isTarget, bodies_congr h p 0 p.blocks] + +theorem lowerFrom_congr {c1 c2 : Cert} (h : c1.turned = c2.turned) (p : Assemble.Program) : + ∀ b l, lowerFrom p c1 b l = lowerFrom p c2 b l + | _, [] => rfl + | b, x :: l => by + simp only [lowerFrom, lowerBlock, isTarget_congr h p b, lowerInstrs_congr h p b x, + lowerFrom_congr h p (b + 1) l] + +theorem meas_congr {c1 c2 : Cert} (h : c1.turned = c2.turned) (p : Assemble.Program) (g b : Nat) : + AssembleLoop.meas p c1 g b = AssembleLoop.meas p c2 g b := by + simp only [AssembleLoop.meas, isTarget_congr h p b] + +theorem SR_congr {c1 c2 : Cert} (h : Same c1 c2) {ty : List Ty} {S T : List Word} + (hR : SR c1 ty S T) + (hl : ∀ i (hi : i < S.length), tyAt ty i = some true → S[i].toNat ∈ c2.rets) : SR c2 ty S T := by + refine ⟨hR.1, fun i h1 h2 => ?_⟩ + have hw := hR.2 i h1 h2 + have hl' := hl i h1 + generalize tyAt ty i = τ at hw hl' ⊢ + cases τ with + | none => trivial + | some bb => + cases bb with + | false => exact hw + | true => + obtain ⟨-, hy⟩ := hw + exact ⟨hl' rfl, by rw [← h.offset]; exact hy⟩ + +theorem labsCover_mem {ty : List Ty} {L : List Lab} {R : List Nat} {S : List Word} + (h : labsCover ty L R = true) (hL : LabOk L S) : + ∀ i (hi : i < S.length), tyAt ty i = some true → S[i].toNat ∈ R := by + intro i hi ht + have hit : i < ty.length := by + by_contra hc + simp [tyAt, List.getD_eq_getElem?_getD, List.getElem?_eq_none (Nat.le_of_not_lt hc)] at ht + simp only [labsCover, List.all_eq_true, List.mem_range] at h + have := h i hit + simp only [ht, bne_self_eq_false, Bool.false_or] at this + cases hl : labAt L i with + | none => simp [hl] at this + | some ts => + simp only [hl, List.all_eq_true] at this + have h2 := this _ (hL i ts hl S[i] (List.getElem?_eq_getElem hi)) + simpa using h2 + +theorem globT_congr {p : Assemble.Program} {code : ByteArray} {c1 c2 : Cert} (h : Same c1 c2) + (G : GlobT p c1 code) : GlobT p c2 code where + top_mod := h.2.2 ▸ G.top_mod + top_le := h.2.2 ▸ G.top_le + size_lt := G.size_lt + target := fun t ht htg => by + rw [← isTarget_congr h.2.1] at htg + rw [← h.offset, ← lowerFrom_congr h.2.1] + exact G.target t ht htg + +theorem entC_congr {p : Assemble.Program} {code : ByteArray} {msg : Message .fusaka} {ss0 : Substate} + {c1 c2 : Cert} {mx1 mx2 : List Nat} (h : Same c1 c2) {x : Nat × List Word × State} + {evm : Evm .fusaka Nat} + (hn : x.1 < p.blocks.length → c1.need x.1 = c2.need x.1 ∧ maxH mx1 x.1 = maxH mx2 x.1) + (he : c1.entry x.1 = c2.entry x.1) + (hl : ∀ i (hi : i < x.2.1.length), tyAt (c1.entry x.1) i = some true → x.2.1[i].toNat ∈ c2.rets) + (hE : EntC p c1 mx1 code msg ss0 x evm) : + EntC p c2 mx2 code msg ss0 x evm := by + obtain ⟨Tw, pc, M, st, ss, rd, hle, hneed, hR, hseg, htop, hmem, R, hat⟩ := hE + refine ⟨Tw, pc, M, st, ss, rd, hle, fun hb => ?_, ?_, ?_, h.2.2 ▸ htop, hmem, R, hat⟩ + · obtain ⟨h1, h2⟩ := hn hb + rw [← h1, ← h2]; exact hneed hb + · rw [← he]; exact SR_congr h hR hl + · rw [← h.offset, ← lowerFrom_congr h.2.1]; exact hseg + +theorem entT_congr {p : Assemble.Program} {code : ByteArray} {msg : Message .fusaka} {ss0 : Substate} + {T : RunTable} {c1 c2 : Cert} {mx1 mx2 : List Nat} (h : Same c1 c2) {x : Nat × List Word × State} + {evm : Evm .fusaka Nat} + (hn : x.1 < p.blocks.length → c1.need x.1 = c2.need x.1 ∧ maxH mx1 x.1 = maxH mx2 x.1) + (he : c1.entry x.1 = c2.entry x.1) + (hl : ∀ i (hi : i < x.2.1.length), tyAt (c1.entry x.1) i = some true → x.2.1[i].toNat ∈ c2.rets) + (hE : EntT p c1 mx1 code msg ss0 T x evm) : + EntT p c2 mx2 code msg ss0 T x evm := + ⟨entC_congr h hn he hl hE.1, hE.2⟩ + +/-! ## The certificate of a block in a context -/ + +theorem getD_map_range {α : Type} {f : Nat → α} {n t : Nat} (ht : t < n) (d : α) : + ((List.range n).map f).getD t d = f t := by + simp [List.getD_eq_getElem?_getD, List.getElem?_map, List.getElem?_range ht] + +theorem certAt_same (cx : CtxCert) (n b j : Nat) : Same (certAt cx n b j) cx.base := + ⟨rfl, rfl, rfl⟩ + +theorem certAt_need {cx : CtxCert} {n b j t : Nat} (ht : t < n) : + (certAt cx n b j).need t = (pick cx b j t).need := getD_map_range ht 0 + +theorem certAt_entry {cx : CtxCert} {n b j t : Nat} (ht : t < n) : + (certAt cx n b j).entry t = (pick cx b j t).types := getD_map_range ht [] + +theorem maxsAt_max {cx : CtxCert} {n b j t : Nat} (ht : t < n) : + maxH (maxsAt cx n b j) t = (pick cx b j t).max := getD_map_range ht 0 + +theorem pick_of_exit {cx : CtxCert} {b j t j' : Nat} (h : exitCtx cx b j t = some j') : + pick cx b j t = cx.at t j' := by + simp [pick, h] + +theorem exitCtx_self (cx : CtxCert) (b j : Nat) : exitCtx cx b j b = some j := by + simp [exitCtx] + +theorem LabOk.le {L W : List Lab} {S : List Word} (hle : labLe L W = true) (h : LabOk L S) : + LabOk W S := by + intro i ws hw w hS + have hi : i < W.length := by + by_contra hc + simp [labAt, List.getD_eq_getElem?_getD, List.getElem?_eq_none (Nat.le_of_not_lt hc)] at hw + simp only [labLe, List.all_eq_true, List.mem_range] at hle + have := hle i hi + rw [hw] at this + cases hl : labAt L i with + | none => simp [hl] at this + | some ts => + simp only [hl, List.all_eq_true] at this + have h2 := this _ (h i ts hl w hS) + simpa using h2 + +theorem LabOk.empty (L : List Lab) : LabOk L [] := by + intro i ts _ w hw + simp at hw + +theorem exitsOk_mem {n : Nat} {cx : CtxCert} {b j : Nat} {E : List (Nat × List Lab)} + (h : exitsOk n cx b j (some E) = true) {t : Nat} {L : List Lab} (hm : (t, L) ∈ E) (ht : t < n) : + ∃ j', exitCtx cx b j t = some j' ∧ j' < cx.count t ∧ labLe L (cx.at t j').labs = true := by + simp only [exitsOk, List.all_eq_true] at h + have := h _ hm + simp only [Bool.or_eq_true, decide_eq_true_eq] at this + rcases this with h1 | h1 + · omega + · cases he : exitCtx cx b j t with + | none => simp [he] at h1 + | some j' => + simp only [he, Bool.and_eq_true, decide_eq_true_eq] at h1 + exact ⟨j', rfl, h1.1, h1.2⟩ + +theorem blocksX_get {p : Assemble.Program} {cx : CtxCert} : + ∀ (l : List (List Assemble.Instr)) (b : Nat), blocksX p cx b l = true → + ∀ k (hk : k < l.length) j, j < cx.count (b + k) → ctxOk p cx (b + k) j l[k] = true + | [], _, _, _, hk, _, _ => absurd hk (by simp) + | x :: l, b, h, 0, _, j, hj => by + simp only [blocksX, Bool.and_eq_true, List.all_eq_true, List.mem_range] at h + simpa using h.1 j (by simpa using hj) + | x :: l, b, h, k + 1, hk, j, hj => by + simp only [blocksX, Bool.and_eq_true] at h + have := blocksX_get l (b + 1) h.2 k (by simp at hk; omega) j (by rw [show b + 1 + k = b + (k + 1) by omega]; exact hj) + rw [show b + (k + 1) = b + 1 + k by omega] + simpa using this + +/-- The facts of the checker with contexts. -/ +structure GlobX (p : Assemble.Program) (cx : CtxCert) (code : ByteArray) : Prop where + glob : GlobT p cx.base code + calls : cx.base.calls = false + block : ∀ b (hb : b < p.blocks.length) j, j < cx.count b → ctxOk p cx b j p.blocks[b] = true + +theorem globX_of_checkX {p : Assemble.Program} {code : ByteArray} {cx : CtxCert} + (h : checkX p code cx = true) : + GlobX p cx code ∧ Seg (bytesOf code) cx.base.offset 0 (lower p cx.base) code.size ∧ + 0 < cx.count 0 ∧ (cx.at 0 0).need = 0 := by + simp only [checkX, Bool.and_eq_true, decide_eq_true_eq, Bool.not_eq_true'] at h + obtain ⟨⟨⟨⟨⟨⟨⟨⟨hw, hlabels⟩, hmod⟩, htop⟩, hsize⟩, hnc⟩, hcount⟩, hneed⟩, hblocks⟩ := h + obtain ⟨stream, hw⟩ := Option.isSome_iff_exists.1 hw + have hseg : Seg (bytesOf code) cx.base.offset 0 (lower p cx.base) code.size := by + have := seg_of_walk (walk_sound hw) + rwa [length_bytesOf] at this + refine ⟨⟨⟨hmod, htop, hsize, fun t ht htgt => ?_⟩, hnc, fun b hb j hj => ?_⟩, hseg, hcount, hneed⟩ + · have hv : isValidJumpDest (validJumpDestinations code) (cx.base.offset t) = true := by + simp only [labelsValid, List.all_eq_true, List.mem_range] at hlabels + have := hlabels t ht + simpa [htgt] using this + obtain ⟨pc', hs, hpc⟩ := seg_lowerFrom p cx.base t p.blocks 0 0 hseg ht + simp only [Nat.zero_add] at hs hpc + rw [← hpc htgt] at hs + refine ⟨hv, ?_, hs⟩ + have hs' := hs + rw [lowerFrom_drop p cx.base ht] at hs' + simp only [lowerBlock, htgt, ite_true, List.cons_append] at hs' + cases hs' with + | cons d _ _ => + have := decode_lt d + rwa [length_bytesOf] at this + · have := blocksX_get p.blocks 0 hblocks b hb j (by simpa using hj) + simpa using this + +/-! ## A block in a context, read back from a run that succeeds -/ + +/-- The relation at a block entry: \`AssembleCut.EntT\` under a certificate of the layout, at the +height range and the types of one of the block's contexts, its words what the context knows them +as. -/ +def EntX (p : Assemble.Program) (cx : CtxCert) (code : ByteArray) (msg : Message .fusaka) + (ss0 : Substate) (T : RunTable) (x : Nat × List Word × State) (evm : Evm .fusaka Nat) : Prop := + ∃ (c : Cert) (mx : List Nat), Same c cx.base ∧ EntT p c mx code msg ss0 T x evm ∧ + (x.1 < p.blocks.length → ∃ j, j < cx.count x.1 ∧ c.need x.1 = (cx.at x.1 j).need ∧ + maxH mx x.1 = (cx.at x.1 j).max ∧ c.entry x.1 = (cx.at x.1 j).types ∧ + LabOk (cx.at x.1 j).labs x.2.1) + +/-- **A block of code with loops and GAS, in one of its contexts, read back from a run that +succeeds.** -/ +theorem advances_checkX {p : Assemble.Program} {cx : CtxCert} {code : ByteArray} + (G : GlobX p cx code) {call : Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : msg.txEnv = Target.txEnv) + (hgas : msg.gas < 2 ^ 256) + (T0 : RunTable) (x : Nat × List Word × State) (evm : Evm .fusaka Nat) + (hE : EntX p cx code msg ss0 T0 x evm) : + Advances (fun o => SolarTV.EVM.Program.block o call p) O (EntX p cx code msg ss0) + (fun res => PostL call msg.currentTarget ss0 res.2 res.1) + (fun y e => AssembleLoop.meas p cx.base e.gas y.1) T0 x evm := by + intro bound runChild _ within fin hrun hok + obtain ⟨b, S, s⟩ := x + obtain ⟨c0, mx0, hsame0, hE0, hctx⟩ := hE + by_cases hb : b < p.blocks.length + · obtain ⟨j, hj, hn0, hm0, he0, hlab⟩ := hctx hb + have hbn : b < p.blocks.length + 1 := by omega + obtain ⟨c, hc⟩ : ∃ c, c = certAt cx (p.blocks.length + 1) b j := ⟨_, rfl⟩ + obtain ⟨mx, hmx⟩ : ∃ mx, mx = maxsAt cx (p.blocks.length + 1) b j := ⟨_, rfl⟩ + have hsame : Same c cx.base := hc ▸ certAt_same cx _ b j + have hcb : c.need b = (cx.at b j).need := by + rw [hc, certAt_need hbn, pick_of_exit (exitCtx_self cx b j)] + have hmb : maxH mx b = (cx.at b j).max := by + rw [hmx, maxsAt_max hbn, pick_of_exit (exitCtx_self cx b j)] + have heb : c.entry b = (cx.at b j).types := by + rw [hc, certAt_entry hbn, pick_of_exit (exitCtx_self cx b j)] + have hck := G.block b hb j hj + simp only [ctxOk, Bool.and_eq_true] at hck + obtain ⟨⟨hblk0, hexOk⟩, hcov⟩ := hck + have hcr : c.rets = (cx.at b j).rets := by rw [hc]; rfl + have hE' : EntT p c mx code msg ss0 T0 (b, S, s) evm := + entT_congr (c1 := c0) (mx1 := mx0) ⟨hsame0.1.trans hsame.1.symm, hsame0.2.1.trans hsame.2.1.symm, + hsame0.2.2.trans hsame.2.2.symm⟩ + (fun _ => ⟨hn0.trans hcb.symm, hm0.trans hmb.symm⟩) (he0.trans heb.symm) + (by rw [he0, hcr]; exact labsCover_mem hcov hlab) hE0 + have hGc : GlobT p c code := globT_congr ⟨hsame.1.symm, hsame.2.1.symm, hsame.2.2.symm⟩ G.glob + have hnc : c.calls = false := by rw [hc]; exact G.calls + rw [← hc, ← hmx] at hblk0 + simp only [blockCtxOk, Bool.and_eq_true, decide_eq_true_eq] at hblk0 + obtain ⟨⟨⟨hL, hnm⟩, hstk⟩, hblock⟩ := hblk0 + cases hexE : exits b (cx.at b j).labs p.blocks[b] with + | none => rw [hexE] at hexOk; simp [exitsOk] at hexOk + | some Ex => + rw [hexE] at hexOk + obtain ⟨⟨Tw, pc, M, st, ss, rd, hle, hneed, hR, hseg, htop, hmem, R, hat⟩, hTg, hs0, hbud⟩ := hE' + simp only at hle hneed hR hseg hmem R hTg hs0 + obtain ⟨hn, hm⟩ := hneed hb + have hblk : p.blocks[b]? = some p.blocks[b] := List.getElem?_eq_getElem hb + rw [lowerFrom_drop p c hb, lowerBlock, List.append_assoc] at hseg + -- The label, at the frame's gas. + obtain ⟨pc1, m1, within1, hat1, hseg1, hg1, hrun1⟩ : ∃ (pc1 : Nat) (m1 : Evm .fusaka Nat) + (within1 : GasMeter.gasHeld m1.gas ≤ bound), + At code msg pc1 Tw M m1.gas st ss rd m1 ∧ + Seg (bytesOf code) c.offset pc1 (lowerInstrs p c b p.blocks[b] ++ + lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) code.size ∧ + m1.gas + (if isTarget p c b then 1 else 0) ≤ evm.gas ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m1 within1 = .ok fin := by + by_cases ht : isTarget p c b = true + · simp only [ht, ite_true, List.cons_append] at hseg + obtain ⟨next, hd, hseg'⟩ := hseg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hp := hat.addGas 1 + obtain ⟨e1, r1, he1⟩ := Logic.jumpdestG hlt hcode (show 1 ≤ evm.gas + 1 by omega) _ hp + obtain ⟨m, within', hz, hrm⟩ := reaches_low r1 1 evm rfl within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hgm⟩ := at_of_addGasR he1 + exact ⟨pc + 1, m, within', hatm, hseg', by simp only [ht, ite_true]; omega, hrm⟩ + · simp only [ht, Bool.false_eq_true, ite_false, List.nil_append] at hseg + exact ⟨pc, evm, within, hat, hseg, by simp only [ht, Bool.false_eq_true, ite_false]; omega, + hrun⟩ + obtain ⟨T', r, hle', hex, hpost, hnext⟩ := seg (G0 := msg.gas) hGc hnc hdata hvalue hstatic hself + hcaller hbenv htx hb hok hgas (p.blocks[b].length + 1) p.blocks[b] (c.need b) [] (c.entry b) + (budget c b - labelItems p c b) S Tw s pc1 M m1.gas st ss T0 m1 within1 (Nat.lt_succ_self _) + hblock hn (by omega) (KR.nil _) hR hseg1 (by omega) htop hmem R hat1 hTg hs0 + (by unfold MemBudget; rw [← hat.2.2.2.2.2.1]; omega) hrun1 + refine ⟨T', r, hle', fun T'' h => ?_, fun res hres => hpost res hres, fun y hy => ?_⟩ + · simp only [SolarTV.EVM.Program.block, hblk] + rw [hex T'' h] + · obtain ⟨t, S', s'⟩ := y + obtain ⟨⟨htle, -, hj'⟩, after, within', hE', hT', hs', hga, hbud', hra⟩ := hnext _ hy + have hr := hex T' (RunTable.Le.refl T') + rw [hy] at hr + obtain ⟨L', hmemE, hL'⟩ := exits_sound (O T') call b p.blocks[b] _ S s Ex _ hlab hexE hr + refine ⟨after, within', ⟨c, mx, hsame, ⟨hE', hT', hs', hbud'⟩, fun ht => ?_⟩, ?_, hra⟩ + · obtain ⟨j', hx, hj'c, hlabs⟩ := exitsOk_mem hexOk hmemE ht + have htn : t < p.blocks.length + 1 := by omega + have hpk := pick_of_exit hx + refine ⟨j', hj'c, ?_, ?_, ?_, hL'.le hlabs⟩ + · rw [hc, certAt_need htn, hpk] + · rw [hmx, maxsAt_max htn, hpk] + · rw [hc, certAt_entry htn, hpk] + · have := meas_step (c := c) (g := evm.gas) (g' := after.gas) hb htle (by omega) hj' + rw [meas_congr hsame.2.1, meas_congr hsame.2.1] at this + dsimp only at this ⊢ + omega + · obtain ⟨⟨Tw, pc, M, st, ss, rd, hle, hneed, hR, hseg, htop, hmem, R, hat⟩, hTg, hs0, hbud⟩ := hE0 + simp only at hle hseg R + obtain rfl : b = p.blocks.length := by omega + have hblk : p.blocks[p.blocks.length]? = none := List.getElem?_eq_none (by omega) + have hbl : ∀ o, SolarTV.EVM.Program.block o call p (p.blocks.length, S, s) = + some (.inl (.stop, s)) := by + intro o + simp only [SolarTV.EVM.Program.block, hblk, ite_true] + refine ⟨T0, _, RunTable.Le.refl T0, fun _ _ => hbl _, ?_, ?_⟩ + · intro res hres + cases hres + have hseg' := hseg + rw [lowerFrom_nil p c0 (by omega)] at hseg' + have hpc := hseg'.nil_end + exact SpecG.low (SpecG.consequence (stop_of_size_leG (by omega)) + (fun _ h => h) fun evm h => postL_stop R hself evm h) (hat.addGas 0) within hrun hok + · intro y hy + cases hy + +/-! ## The theorems -/ + +/-- **EVM IR to bytecode, run by run, at the run's own gas, for code with loops, GAS, memory at +any offset and internal functions called in several contexts**: \`AssembleCut.runs_of_checkC\` for +every program the checker with contexts accepts. -/ +theorem runs_of_checkX {p : Assemble.Program} {code : ByteArray} {cx : CtxCert} + (hc : checkX p code cx = true) (gas : Nat) (hgas : gas < 2 ^ 256) (call : Call) : + ∃ T, Within (evmirSem (O T)) (ethLibWith gas) p code (· = call) := by + obtain ⟨G, hseg, hcount, hneed0⟩ := globX_of_checkX hc + refine within_of_advances O (fun ss0 => EntX p cx code (Final.Target.messageWith gas code call) ss0) + (fun y e => AssembleLoop.meas p cx.base e.gas y.1) (fun st' ss' R => ?_) + (fun ss0 T x evm hE => advances_checkX G rfl + (by simp [Final.Target.messageWith, Target.message]) rfl rfl rfl rfl rfl hgas T x evm hE) + have h0n : 0 < p.blocks.length + 1 := by omega + have hsame := certAt_same cx (p.blocks.length + 1) 0 0 + have hn0 : (certAt cx (p.blocks.length + 1) 0 0).need 0 = (cx.at 0 0).need := by + rw [certAt_need h0n, pick_of_exit (exitCtx_self cx 0 0)] + have hseg0 : Seg (bytesOf code) (certAt cx (p.blocks.length + 1) 0 0).offset 0 + (lowerFrom p (certAt cx (p.blocks.length + 1) 0 0) 0 (p.blocks.drop 0)) code.size := by + rw [hsame.offset, lowerFrom_congr hsame.2.1, List.drop_zero] + exact hseg + refine ⟨certAt cx (p.blocks.length + 1) 0 0, maxsAt cx (p.blocks.length + 1) 0 0, hsame, + ⟨⟨[], 0, .empty, st', ss', .empty, Nat.zero_le _, fun _ => ⟨by simp [hn0, hneed0], by simp⟩, + SR.nil _ _, hseg0, by simp, memRel_initial, R, ?_⟩, rfl, rfl, ?_⟩, fun _ => ⟨0, hcount, + hn0, by rw [maxsAt_max h0n, pick_of_exit (exitCtx_self cx 0 0)], + by rw [certAt_entry h0n, pick_of_exit (exitCtx_self cx 0 0)], LabOk.empty _⟩⟩ + have hcode : (Final.Target.messageWith gas code call).code = code := rfl + · exact ⟨by simp [startFrame, hcode], by simp [startFrame, hcode], rfl, rfl, rfl, rfl, rfl, rfl, rfl, + rfl, rfl, rfl, rfl⟩ + · have h0 : memoryGasCost 0 = 0 := by rw [memoryGasCost_eq]; simp [wordCount, ceil32, WORD_BYTES] + simp only [startFrame, ByteArray.size_empty, h0, Nat.zero_add] + exact le_refl _ + +/-- **The per-run theorem below \`2 ^ 256\` gas for every program the checker with contexts +accepts**: \`AssembleCut.withinRun_of_checkC\`'s statement, under the oracles that meet the base +certificate's flags. -/ +theorem withinRun_of_checkX {p : Assemble.Program} {code : ByteArray} {cx : CtxCert} + (hc : checkX p code cx = true) (scope : Call → Prop) : + WithinRunLt evmirSem (fun _ => p) code scope (CertOk cx.base) := by + intro gas hgas call _ + obtain ⟨T, hT⟩ := runs_of_checkX hc gas hgas call + exact ⟨O T, O_ok cx.base T, hT⟩ + +/-- **The assembly premise of \`AssembleCut.holds_of_runs_lt\`** for every program the checker with +contexts accepts. -/ +theorem assembly_of_checkX {p : Assemble.Program} {code : ByteArray} {cx : CtxCert} + (hc : checkX p code cx = true) (scope : Call → Prop) : + ∀ gas, gas < 2 ^ 256 → ∀ call, scope call → ∃ (o : Oracle) (W : World), W.Open ∧ + CallsAgree o W ∧ Within (evmirSem o) (ethLibWith gas) p code (· = call) := by + intro gas hgas call _ + obtain ⟨T, hT⟩ := runs_of_checkX hc gas hgas call + obtain ⟨W, hW, hA⟩ := O_agree T + exact ⟨O T, W, hW, hA, hT⟩ + +/-- The first lowered MIR to the exact bytecode, run by run, for every program the checker with +contexts accepts: \`AssembleCut.withinRun_mir_of_checkC\` with \`checkX\`. -/ +theorem withinRun_mir_of_checkX {stage0 : SolarTV.MIR.Lowered.moduleLayer.Prog} + {p : Assemble.Program} {code : ByteArray} {cx : CtxCert} {S scope : Call → Prop} + (back : ∀ o, Certified SolarTV.EVM.Program.layer SolarTV.MIR.Lowered.moduleLayer o p stage0 S) + (hS : ∀ call, scope call → S call) (hc : checkX p code cx = true) : + WithinRunLt mirSem (fun _ => stage0) code scope (CertOk cx.base) := + WithinRunLt.of_back (fun o _ => fun call hcall obs h => + stage_of_certified (back o) call (hS call hcall) obs h) + (withinRun_of_checkX hc scope) + +/-- info: 'SolidCore.Refinement.Solar.AssembleCtx.withinRun_of_checkX' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms withinRun_of_checkX + +/-- info: 'SolidCore.Refinement.Solar.AssembleCtx.assembly_of_checkX' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms assembly_of_checkX + +/-- info: 'SolidCore.Refinement.Solar.AssembleCtx.withinRun_mir_of_checkX' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms withinRun_mir_of_checkX + +end SolidCore.Refinement.Solar.AssembleCtx diff --git a/SolidCore/Refinement/Solar/AssembleCtxCall.lean b/SolidCore/Refinement/Solar/AssembleCtxCall.lean new file mode 100644 index 00000000..c7495614 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCtxCall.lean @@ -0,0 +1,397 @@ +import SolidCore.Refinement.Solar.AssembleCtx +import SolidCore.Refinement.Solar.AssembleCallSeg +import SolidCore.Refinement.Solar.AssembleFast + +/-! +# The checker with contexts, for code with STATICCALLs + +\`AssembleCtx.checkX\` without its no-call gate (\`checkXB\`): each block checked once per context by +\`AssembleCut.blockOkC\` under the context's certificate, which may make STATICCALLs, and run against +the bytecode by \`AssembleCallSeg.segS\` (the runner of messages under \`StaticOkE\`, the calls' flags +and outputs in the run's table). \`assembly_of_checkXB\` is \`AssembleCallSeg.assembly_of_checkCB\`'s +statement, with the same named hypotheses (\`StaticRunner\`, \`CalleesRun\`), for every program the +checker with contexts accepts. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCtx + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Witness SolidCore.Refinement.Final +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.RunOracle +open SolidCore.Refinement.Solar.AssembleCut SolidCore.Refinement.Solar.AssembleEffects +open SolidCore.Refinement.Solar.AssembleLoop SolidCore.Refinement.Solar.AssembleRun +open SolidCore.Refinement.Solar.AssembleRunLoop +open SolidCore.Refinement.Solar.AssembleCall SolidCore.Refinement.Solar.AssembleCallWorld +open SolidCore.Refinement.Solar.AssembleCallCut SolidCore.Refinement.Solar.AssembleDyn +open SolidCore.Refinement.Solar.AssembleCallSeg +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +/-- **The checker with contexts**, for programs that may make STATICCALLs: \`checkX\` without its +no-call gate. -/ +def checkXB (p : Assemble.Program) (code : ByteArray) (cx : CtxCert) : Bool := + (walk (bytesOf code) cx.base.offset 0 (lower p cx.base)).isSome && labelsValid p cx.base code && + decide (cx.base.top % 32 = 0) && decide (cx.base.top ≤ 2 ^ 200) && decide (code.size < 2 ^ 32) && + decide (0 < cx.count 0) && decide ((cx.at 0 0).need = 0) && !cx.base.creates && blocksX p cx 0 p.blocks + +/-- The facts of the checker with contexts and calls. -/ +structure GlobXB (p : Assemble.Program) (cx : CtxCert) (code : ByteArray) : Prop where + glob : GlobT p cx.base code + block : ∀ b (hb : b < p.blocks.length) j, j < cx.count b → ctxOk p cx b j p.blocks[b] = true + creates : cx.base.creates = false + +theorem globXB_of_checkXB {p : Assemble.Program} {code : ByteArray} {cx : CtxCert} + (h : checkXB p code cx = true) : + GlobXB p cx code ∧ Seg (bytesOf code) cx.base.offset 0 (lower p cx.base) code.size ∧ + 0 < cx.count 0 ∧ (cx.at 0 0).need = 0 := by + simp only [checkXB, Bool.and_eq_true, decide_eq_true_eq] at h + obtain ⟨⟨⟨⟨⟨⟨⟨⟨hw, hlabels⟩, hmod⟩, htop⟩, hsize⟩, hcount⟩, hneed⟩, hcre⟩, hblocks⟩ := h + obtain ⟨stream, hw⟩ := Option.isSome_iff_exists.1 hw + have hseg : Seg (bytesOf code) cx.base.offset 0 (lower p cx.base) code.size := by + have := seg_of_walk (walk_sound hw) + rwa [length_bytesOf] at this + refine ⟨⟨⟨hmod, htop, hsize, fun t ht htgt => ?_⟩, fun b hb j hj => ?_, by simpa using hcre⟩, hseg, hcount, hneed⟩ + · have hv : isValidJumpDest (validJumpDestinations code) (cx.base.offset t) = true := by + simp only [labelsValid, List.all_eq_true, List.mem_range] at hlabels + have := hlabels t ht + simpa [htgt] using this + obtain ⟨pc', hs, hpc⟩ := seg_lowerFrom p cx.base t p.blocks 0 0 hseg ht + simp only [Nat.zero_add] at hs hpc + rw [← hpc htgt] at hs + refine ⟨hv, ?_, hs⟩ + have hs' := hs + rw [lowerFrom_drop p cx.base ht] at hs' + simp only [lowerBlock, htgt, ite_true, List.cons_append] at hs' + cases hs' with + | cons d _ _ => + have := decode_lt d + rwa [length_bytesOf] at this + · have := blocksX_get p.blocks 0 hblocks b hb j (by simpa using hj) + simpa using this + +/-- The relation at a block entry of code with calls: \`AssembleCallSeg.EntS\` under a certificate of +the layout, at one of the block's contexts. -/ +def EntXS (codes : SolidCore.Solidity.Shared.Account.BytesMap) (p : Assemble.Program) (cx : CtxCert) + (code : ByteArray) (msg : Message .fusaka) (ss0 : Substate) (T : RunTable) + (x : Nat × List Word × State) (evm : Evm .fusaka Nat) : Prop := + ∃ (c : Cert) (mx : List Nat), Same c cx.base ∧ EntS codes p c mx code msg ss0 T x evm ∧ + (x.1 < p.blocks.length → ∃ j, j < cx.count x.1 ∧ c.need x.1 = (cx.at x.1 j).need ∧ + maxH mx x.1 = (cx.at x.1 j).max ∧ c.entry x.1 = (cx.at x.1 j).types ∧ + LabOk (cx.at x.1 j).labs x.2.1) + +theorem entS_congr {codes : SolidCore.Solidity.Shared.Account.BytesMap} {p : Assemble.Program} + {code : ByteArray} {msg : Message .fusaka} {ss0 : Substate} + {T : RunTable} {c1 c2 : Cert} {mx1 mx2 : List Nat} (h : Same c1 c2) {x : Nat × List Word × State} + {evm : Evm .fusaka Nat} + (hn : x.1 < p.blocks.length → c1.need x.1 = c2.need x.1 ∧ maxH mx1 x.1 = maxH mx2 x.1) + (he : c1.entry x.1 = c2.entry x.1) + (hl : ∀ i (hi : i < x.2.1.length), tyAt (c1.entry x.1) i = some true → x.2.1[i].toNat ∈ c2.rets) + (hE : EntS codes p c1 mx1 code msg ss0 T x evm) : + EntS codes p c2 mx2 code msg ss0 T x evm := + ⟨entC_congr h hn he hl hE.1, hE.2⟩ + +/-- **A block of code with loops, GAS and STATICCALLs, in one of its contexts, read back from a run +that succeeds.** -/ +theorem advances_checkXS {p : Assemble.Program} {cx : CtxCert} {code : ByteArray} + (G : GlobXB p cx code) (codes : SolidCore.Solidity.Shared.Account.BytesMap) {call : Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : msg.txEnv = Target.txEnv) + (hgas : msg.gas < 2 ^ 256) (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + (T0 : RunTable) (x : Nat × List Word × State) (evm : Evm .fusaka Nat) + (hE : EntXS codes p cx code msg ss0 T0 x evm) : + AdvancesQ (fun o => SolarTV.EVM.Program.block o call p) (OS codes) StaticOkE + (CalleesOk code msg StaticOkE) (EntXS codes p cx code msg ss0) + (fun res => PostL call msg.currentTarget ss0 res.2 res.1) + (fun y e => AssembleLoop.meas p cx.base e.gas y.1) T0 x evm := by + intro bound runChild meets within fin hrun hok hcal + obtain ⟨b, S, s⟩ := x + obtain ⟨c0, mx0, hsame0, hE0, hctx⟩ := hE + by_cases hb : b < p.blocks.length + · obtain ⟨j, hj, hn0, hm0, he0, hlab⟩ := hctx hb + have hbn : b < p.blocks.length + 1 := by omega + obtain ⟨c, hc⟩ : ∃ c, c = certAt cx (p.blocks.length + 1) b j := ⟨_, rfl⟩ + obtain ⟨mx, hmx⟩ : ∃ mx, mx = maxsAt cx (p.blocks.length + 1) b j := ⟨_, rfl⟩ + have hsame : Same c cx.base := hc ▸ certAt_same cx _ b j + have hcb : c.need b = (cx.at b j).need := by + rw [hc, certAt_need hbn, pick_of_exit (exitCtx_self cx b j)] + have hmb : maxH mx b = (cx.at b j).max := by + rw [hmx, maxsAt_max hbn, pick_of_exit (exitCtx_self cx b j)] + have heb : c.entry b = (cx.at b j).types := by + rw [hc, certAt_entry hbn, pick_of_exit (exitCtx_self cx b j)] + have hck := G.block b hb j hj + simp only [ctxOk, Bool.and_eq_true] at hck + obtain ⟨⟨hblk0, hexOk⟩, hcov⟩ := hck + have hcr : c.rets = (cx.at b j).rets := by rw [hc]; rfl + have hE' : EntS codes p c mx code msg ss0 T0 (b, S, s) evm := + entS_congr (c1 := c0) (mx1 := mx0) ⟨hsame0.1.trans hsame.1.symm, hsame0.2.1.trans hsame.2.1.symm, + hsame0.2.2.trans hsame.2.2.symm⟩ + (fun _ => ⟨hn0.trans hcb.symm, hm0.trans hmb.symm⟩) (he0.trans heb.symm) + (by rw [he0, hcr]; exact labsCover_mem hcov hlab) hE0 + have hGc : GlobT p c code := globT_congr ⟨hsame.1.symm, hsame.2.1.symm, hsame.2.2.symm⟩ G.glob + rw [← hc, ← hmx] at hblk0 + simp only [blockCtxOk, Bool.and_eq_true, decide_eq_true_eq] at hblk0 + obtain ⟨⟨⟨hL, hnm⟩, hstk⟩, hblock⟩ := hblk0 + cases hexE : exits b (cx.at b j).labs p.blocks[b] with + | none => rw [hexE] at hexOk; simp [exitsOk] at hexOk + | some Ex => + rw [hexE] at hexOk + obtain ⟨⟨Tw, pc, M, st, ss, rd, hle, hneed, hR, hseg, htop, hmem, R, hat⟩, hTg, hs0, hrdr, hbud⟩ := hE' + simp only at hle hneed hR hseg hmem R hTg hs0 hrdr + obtain ⟨hn, hm⟩ := hneed hb + have hblk : p.blocks[b]? = some p.blocks[b] := List.getElem?_eq_getElem hb + rw [lowerFrom_drop p c hb, lowerBlock, List.append_assoc] at hseg + -- The label, at the frame's gas. + obtain ⟨pc1, m1, within1, hat1, hseg1, hg1, hrun1⟩ : ∃ (pc1 : Nat) (m1 : Evm .fusaka Nat) + (within1 : GasMeter.gasHeld m1.gas ≤ bound), + At code msg pc1 Tw M m1.gas st ss rd m1 ∧ + Seg (bytesOf code) c.offset pc1 (lowerInstrs p c b p.blocks[b] ++ + lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) code.size ∧ + m1.gas + (if isTarget p c b then 1 else 0) ≤ evm.gas ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m1 within1 = .ok fin := by + by_cases ht : isTarget p c b = true + · simp only [ht, ite_true, List.cons_append] at hseg + obtain ⟨next, hd, hseg'⟩ := hseg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hp := hat.addGas 1 + obtain ⟨e1, r1, he1⟩ := Logic.jumpdestG hlt hcode (show 1 ≤ evm.gas + 1 by omega) _ hp + obtain ⟨m, within', hz, hrm⟩ := reaches_low r1 1 evm rfl within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hgm⟩ := at_of_addGasR he1 + exact ⟨pc + 1, m, within', hatm, hseg', by simp only [ht, ite_true]; omega, hrm⟩ + · simp only [ht, Bool.false_eq_true, ite_false, List.nil_append] at hseg + exact ⟨pc, evm, within, hat, hseg, by simp only [ht, Bool.false_eq_true, ite_false]; omega, + hrun⟩ + obtain ⟨T', r, hle', hex, hpost, hnext⟩ := segS (G0 := msg.gas) hGc codes (hc ▸ G.creates) hdata hvalue hstatic + hself hcaller hbenv htx hb hok hgas hdepth meets (fun _ _ _ h => h.1) hcal (p.blocks[b].length + 1) p.blocks[b] (c.need b) [] (c.entry b) + (budget c b - labelItems p c b) S Tw s pc1 M m1.gas st ss rd T0 m1 within1 (Nat.lt_succ_self _) + hblock hn (by omega) (KR.nil _) hR hseg1 (by omega) htop hmem R hat1 hTg hs0 + (by rw [← hat.2.2.2.2.2.2.2.2.2.2.2.2]; exact hrdr) + (by unfold MemBudget; rw [← hat.2.2.2.2.2.1]; omega) hrun1 + refine ⟨T', r, hle', fun T'' h => ?_, fun res hres => hpost res hres, fun y hy => ?_⟩ + · simp only [SolarTV.EVM.Program.block, hblk] + rw [hex T'' h] + · obtain ⟨t, S', s'⟩ := y + obtain ⟨⟨htle, -, hj'⟩, after, within', hE', hT', hs', hrdy', hga, hbud', hra⟩ := hnext _ hy + have hr := hex T' (RunTable.Le.refl T') + rw [hy] at hr + obtain ⟨L', hmemE, hL'⟩ := exits_sound (OS codes T') call b p.blocks[b] _ S s Ex _ hlab hexE hr + refine ⟨after, within', ⟨c, mx, hsame, ⟨hE', hT', hs', hrdy', hbud'⟩, fun ht => ?_⟩, ?_, hra⟩ + · obtain ⟨j', hx, hj'c, hlabs⟩ := exitsOk_mem hexOk hmemE ht + have htn : t < p.blocks.length + 1 := by omega + have hpk := pick_of_exit hx + refine ⟨j', hj'c, ?_, ?_, ?_, hL'.le hlabs⟩ + · rw [hc, certAt_need htn, hpk] + · rw [hmx, maxsAt_max htn, hpk] + · rw [hc, certAt_entry htn, hpk] + · have := meas_step (c := c) (g := evm.gas) (g' := after.gas) hb htle (by omega) hj' + rw [meas_congr hsame.2.1, meas_congr hsame.2.1] at this + dsimp only at this ⊢ + omega + · obtain ⟨⟨Tw, pc, M, st, ss, rd, hle, hneed, hR, hseg, htop, hmem, R, hat⟩, hTg, hs0, hrdr, hbud⟩ := hE0 + simp only at hle hseg R + obtain rfl : b = p.blocks.length := by omega + have hblk : p.blocks[p.blocks.length]? = none := List.getElem?_eq_none (by omega) + have hbl : ∀ o, SolarTV.EVM.Program.block o call p (p.blocks.length, S, s) = + some (.inl (.stop, s)) := by + intro o + simp only [SolarTV.EVM.Program.block, hblk, ite_true] + refine ⟨T0, _, RunTable.Le.refl T0, fun _ _ => hbl _, ?_, ?_⟩ + · intro res hres + cases hres + have hseg' := hseg + rw [lowerFrom_nil p c0 (by omega)] at hseg' + have hpc := hseg'.nil_end + exact SpecG.low (SpecG.consequence (stop_of_size_leG (by omega)) + (fun _ h => h) fun evm h => postL_stop R hself evm h) (hat.addGas 0) within hrun hok + · intro y hy + cases hy + +/-- **EVM IR to bytecode, run by run, for code with loops, GAS, memory at any offset, STATICCALLs to +code and internal functions called in several contexts**: \`AssembleCallSeg.runs_of_checkCB\` for +every program the checker with contexts accepts. -/ +theorem runs_of_checkXB {p : Assemble.Program} {code : ByteArray} {cx : CtxCert} + (hc : checkXB p code cx = true) (codes : SolidCore.Solidity.Shared.Account.BytesMap) + (gas : Nat) (hgas : gas < 2 ^ 256) (call : Call) (hP : StaticRunner gas) + (hQ : CalleesRun gas code call) : + ∃ T, Within (evmirSem (OS codes T)) (ethLibWith gas) p code (· = call) := by + obtain ⟨G, hseg, hcount, hneed0⟩ := globXB_of_checkXB hc + refine within_of_advancesQ (OS codes) StaticOkE + (CalleesOk code (Final.Target.messageWith gas code call) StaticOkE) + (fun ss0 => EntXS codes p cx code (Final.Target.messageWith gas code call) ss0) + (fun y e => AssembleLoop.meas p cx.base e.gas y.1) (staticOkE_of gas hP) hQ (fun st' ss' R => ?_) + (fun ss0 T x evm hE => advances_checkXS G codes rfl + (by simp [Final.Target.messageWith, SolidCore.Refinement.Target.message]) rfl rfl rfl rfl rfl + hgas (by show 0 + 1 ≤ 1024; decide) T x evm hE) + have h0n : 0 < p.blocks.length + 1 := by omega + have hsame := certAt_same cx (p.blocks.length + 1) 0 0 + have hn0 : (certAt cx (p.blocks.length + 1) 0 0).need 0 = (cx.at 0 0).need := by + rw [certAt_need h0n, pick_of_exit (exitCtx_self cx 0 0)] + have hseg0 : Seg (bytesOf code) (certAt cx (p.blocks.length + 1) 0 0).offset 0 + (lowerFrom p (certAt cx (p.blocks.length + 1) 0 0) 0 (p.blocks.drop 0)) code.size := by + rw [hsame.offset, lowerFrom_congr hsame.2.1, List.drop_zero] + exact hseg + refine ⟨certAt cx (p.blocks.length + 1) 0 0, maxsAt cx (p.blocks.length + 1) 0 0, hsame, + ⟨⟨[], 0, .empty, st', ss', .empty, Nat.zero_le _, fun _ => ⟨by simp [hn0, hneed0], by simp⟩, + SR.nil _ _, hseg0, by simp, memRel_initial, R, ?_⟩, rfl, ⟨rfl, rfl, rfl⟩, + fun T'' _ => rdRel_nil codes T'', ?_⟩, fun _ => ⟨0, hcount, + hn0, by rw [maxsAt_max h0n, pick_of_exit (exitCtx_self cx 0 0)], + by rw [certAt_entry h0n, pick_of_exit (exitCtx_self cx 0 0)], LabOk.empty _⟩⟩ + have hcode : (Final.Target.messageWith gas code call).code = code := rfl + · exact ⟨by simp [startFrame, hcode], by simp [startFrame, hcode], rfl, rfl, rfl, rfl, rfl, rfl, rfl, + rfl, rfl, rfl, rfl⟩ + · have h0 : memoryGasCost 0 = 0 := by rw [memoryGasCost_eq]; simp [wordCount, ceil32, WORD_BYTES] + simp only [startFrame, ByteArray.size_empty, h0, Nat.zero_add] + exact le_refl _ + +/-- **The assembly premise of \`holds_of_runs\` for code with STATICCALLs and internal functions +called in several contexts**: \`AssembleCallSeg.assembly_of_checkCB\`'s statement, with its named +hypotheses, for every program the checker with contexts accepts. -/ +theorem assembly_of_checkXB {p : Assemble.Program} {code : ByteArray} {cx : CtxCert} + (hc : checkXB p code cx = true) (codes : SolidCore.Solidity.Shared.Account.BytesMap) + (scope : Call → Prop) (hP : ∀ gas, StaticRunner gas) + (hQ : ∀ gas call, scope call → CalleesRun gas code call) : + ∀ gas, gas < 2 ^ 256 → ∀ call, scope call → ∃ (o : Oracle) (W : World), W.Open ∧ + CallsAgree o W ∧ CertOk cx.base o ∧ Within (evmirSem o) (ethLibWith gas) p code (· = call) := by + intro gas hgas call hs + obtain ⟨T, hT⟩ := runs_of_checkXB hc codes gas hgas call (hP gas) (hQ gas call hs) + exact ⟨OS codes T, tabWorld T.oks T.outs codes, (OS_agree codes T).1, (OS_agree codes T).2, + OS_ok codes cx.base T, hT⟩ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCtx.assembly_of_checkXB' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms assembly_of_checkXB + +/-! ## RETURNDATASIZE as a stack operation + +solar's export writes RETURNDATASIZE as the stack operation \`.op (.stack .returndatasize)\`, which +SolarTV runs as the effect \`.effect .returndatasize 0\` does (both push the oracle's return data +size and fail on the same stacks), and which the checkers lower only in its effect form. \`norm\` +writes the program with every such operation as the effect; it runs as the program does +(\`sem_norm\`), so the checker's theorem for \`norm p\` is one for \`p\`. -/ + +/-- An instruction with RETURNDATASIZE in its effect form. -/ +def normI : SolarTV.EVM.Program.Instr → SolarTV.EVM.Program.Instr + | .op (.stack .returndatasize) => .effect .returndatasize 0 + | i => i + +/-- The program with RETURNDATASIZE in its effect form. -/ +def norm (p : Assemble.Program) : Assemble.Program := ⟨p.blocks.map (·.map normI)⟩ + +theorem normI_of_ne {i : SolarTV.EVM.Program.Instr} (h : i ≠ .op (.stack .returndatasize)) : + normI i = i := by + unfold normI; split + · exact absurd rfl h + · rfl + +open SolarTV.EVM.Program in +theorem exec_norm (o : Oracle) (call : Call) (b : Nat) : + ∀ (is : List SolarTV.EVM.Program.Instr) (S : List Word) (s : State), + exec o call b (is.map normI) S s = exec o call b is S s + | [], _, _ => rfl + | i :: rest, S, s => by + have ih := exec_norm o call b rest + by_cases hi : i = .op (.stack .returndatasize) + · subst hi + simp only [List.map_cons, normI] + by_cases h1 : S.length + 1 > 1024 + · have h2 : ¬ S.length < 0 := by omega + simp [exec, stepOp, SolarTV.EVM.stepChecked, SolarTV.EVM.step, Effect.apply, h1, Except.map] + · simp [exec, stepOp, SolarTV.EVM.stepChecked, SolarTV.EVM.step, Effect.apply, Except.map, + show ¬ 1024 < S.length by omega, show ¬ 1024 < S.length + 1 by omega, ih, context] + · rw [List.map_cons, normI_of_ne hi] + cases i <;> simp only [exec, ih] + +theorem run_norm (o : Oracle) (p : Assemble.Program) : + SolarTV.EVM.Program.run o (norm p) = SolarTV.EVM.Program.run o p := by + have hb : ∀ call, SolarTV.EVM.Program.block o call (norm p) = SolarTV.EVM.Program.block o call p := by + intro call + funext x + obtain ⟨b, S, s⟩ := x + simp only [SolarTV.EVM.Program.block, norm, List.getElem?_map, List.length_map] + cases p.blocks[b]? with + | none => rfl + | some instrs => simp only [Option.map_some, exec_norm] + funext call fuel + simp only [SolarTV.EVM.Program.run] + rw [hb call] + +theorem sem_norm (o : Oracle) (p : Assemble.Program) (call : Call) : + (evmirSem o).run (norm p) call = (evmirSem o).run p call := by + have h : SolarTV.EVM.Program.layer.run o (norm p) = SolarTV.EVM.Program.layer.run o p := + run_norm o p + have hE : ∀ r, SolarTV.EVM.Program.layer.Ends o (norm p) call r ↔ + SolarTV.EVM.Program.layer.Ends o p call r := by + intro r; simp only [Layer.Ends, h] + have hres : SolarTV.EVM.Program.layer.result o (norm p) call = + SolarTV.EVM.Program.layer.result o p call := by + by_cases hq : ∃ r, SolarTV.EVM.Program.layer.Ends o p call r + · obtain ⟨r, hr⟩ := hq + rw [SolarTV.EVM.Program.layer.result_of_ends hr, + SolarTV.EVM.Program.layer.result_of_ends ((hE r).2 hr)] + · have hq' : ¬ ∃ r, SolarTV.EVM.Program.layer.Ends o (norm p) call r := + fun ⟨r, hr⟩ => hq ⟨r, (hE r).1 hr⟩ + simp only [Layer.result, hq, hq', dite_false] + simp only [evmirSem, SolarTV.EVM.Program.sem, Layer.sem, hres] + +theorem within_norm {o : Oracle} {T : Sem} {p : Assemble.Program} {code : T.Prog} + {scope : Call → Prop} (h : Within (evmirSem o) T (norm p) code scope) : + Within (evmirSem o) T p code scope := by + intro call hc obs hrun + rw [← sem_norm o p call] + exact h call hc obs hrun + +/-! ## The check, block by block -/ + +theorem all_range_of {n : Nat} {f : Nat → Bool} (h : ∀ j, j < n → f j = true) : + (List.range n).all f = true := by + simp only [List.all_eq_true, List.mem_range] + exact h + +theorem blocksX_of_forall {p : Assemble.Program} {cx : CtxCert} : + ∀ (l : List (List Assemble.Instr)) (b : Nat), + (∀ k (_ : k < l.length), (List.range (cx.count (b + k))).all + (fun j => ctxOk p cx (b + k) j (l.getD k [])) = true) → blocksX p cx b l = true + | [], _, _ => rfl + | x :: l, b, h => by + simp only [blocksX, Bool.and_eq_true] + refine ⟨by simpa using h 0 (by simp), blocksX_of_forall l (b + 1) fun k hk => ?_⟩ + have := h (k + 1) (by simp; omega) + rw [show b + (k + 1) = b + 1 + k by omega] at this + simpa using this + +/-- \`checkXB\` from its parts, each its own evaluation: the walk of the code, the layout's bounds +and each block in each of its contexts. -/ +theorem checkXB_of_parts {p : Assemble.Program} {code : ByteArray} {cx : CtxCert} + (hw : (walk (bytesOf code) cx.base.offset 0 (lower p cx.base)).isSome = true) + (hrest : (decide (cx.base.top % 32 = 0) && decide (cx.base.top ≤ 2 ^ 200) && + decide (code.size < 2 ^ 32) && decide (0 < cx.count 0) && decide ((cx.at 0 0).need = 0)) = true) + (hb : ∀ k (_ : k < p.blocks.length), (List.range (cx.count k)).all + (fun j => ctxOk p cx k j (p.blocks.getD k [])) = true) + (hcre : cx.base.creates = false := by decide) : + checkXB p code cx = true := by + have hl := SolidCore.Refinement.Solar.Assemble.labelsValid_of_walk hw + have hbx := blocksX_of_forall (cx := cx) p.blocks 0 (fun k hk => by simpa using hb k hk) + simp only [Bool.and_eq_true] at hrest + obtain ⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩ := hrest + simp only [checkXB, hw, hl, h1, h2, h3, h4, h5, hcre, hbx, Bool.and_self, Bool.not_false] + +/-- **The assembly premise for an exported program with RETURNDATASIZE as a stack operation**: +\`assembly_of_checkXB\` for the program the checker accepts in its effect form. -/ +theorem assembly_of_checkXB_norm {p : Assemble.Program} {code : ByteArray} {cx : CtxCert} + (hc : checkXB (norm p) code cx = true) (codes : SolidCore.Solidity.Shared.Account.BytesMap) + (scope : Call → Prop) (hP : ∀ gas, StaticRunner gas) + (hQ : ∀ gas call, scope call → CalleesRun gas code call) : + ∀ gas, gas < 2 ^ 256 → ∀ call, scope call → ∃ (o : Oracle) (W : World), W.Open ∧ + CallsAgree o W ∧ CertOk cx.base o ∧ Within (evmirSem o) (ethLibWith gas) p code (· = call) := by + intro gas hgas call hs + obtain ⟨o, W, hW, hA, hok, hwi⟩ := assembly_of_checkXB hc codes scope hP hQ gas hgas call hs + exact ⟨o, W, hW, hA, hok, within_norm hwi⟩ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCtx.assembly_of_checkXB_norm' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms assembly_of_checkXB_norm + +end SolidCore.Refinement.Solar.AssembleCtx diff --git a/SolidCore/Refinement/Solar/AssembleCtxExample.lean b/SolidCore/Refinement/Solar/AssembleCtxExample.lean new file mode 100644 index 00000000..7ac1e2b5 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCtxExample.lean @@ -0,0 +1,107 @@ +import SolidCore.Refinement.Solar.AssembleCtx + +/-! +# An internal function called at two stack heights: an example and mutants + +\`prog\` calls the internal function at block 3 (\`x ↦ x + 1\`, returning with a dynamic jump to the +label under its argument) twice: from block 0 with one word under the call (the callee entered at +height 3) and from block 1 with two (height 4), then adds the three words and returns their sum. +\`AssembleCut.checkC\` takes one entry height and type per block and checks the callee's return +against both return labels, so no certificate of it covers the second return, which needs three +words where the first leaves two (\`single_fails\`; solar's \`asm_cert.infer\` finds no fixed point +of heights either). The checker with contexts (\`AssembleCtx.checkX\`) checks the callee once per +call site: each context knows the return label under the argument as the one its caller pushed +(\`labs\`), so the return enters the caller's own context. The certificate is +\`tools/certify/asm_cert.py\`'s \`infer_ctx\` output for this program and bytecode. + +Rejected by evaluation: the bytecode whose second call returns to block 1's offset (a mutant +return label), a certificate that says the second call's return label is the first call's, and a +certificate whose second context enters the callee one word low. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCtxExample + +open SolidCore.Refinement.Solar SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCut SolidCore.Refinement.Solar.AssembleCtx +open SolidCore.Refinement.Final + +def prog : Assemble.Program := + { blocks := [ + [.op (.stack (.push 5)), .pushLabel 1, .op (.stack (.push 7)), .jump 3], + [.pushLabel 2, .op (.stack (.push 8)), .jump 3], + [.op (.stack .add), .op (.stack .add), .op (.stack (.push 0)), .op .store, + .op (.stack (.push 32)), .op (.stack (.push 0)), .ret], + [.op (.stack (.push 1)), .op (.stack .add), .op (.stack (.swap 0)), .jumpDyn]] } + +/-- PUSH1 5 PUSH1 9 PUSH1 7 PUSH1 26 JUMP; JUMPDEST PUSH1 17 PUSH1 8 PUSH1 26 JUMP; JUMPDEST ADD +ADD PUSH0 MSTORE PUSH1 32 PUSH0 RETURN; JUMPDEST PUSH1 1 ADD SWAP1 JUMP. -/ +def code : ByteArray := + ⟨#[0x60, 0x05, 0x60, 0x09, 0x60, 0x07, 0x60, 0x1a, 0x56, 0x5b, 0x60, 0x11, 0x60, 0x08, 0x60, + 0x1a, 0x56, 0x5b, 0x01, 0x01, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x01, 0x01, 0x90, + 0x56]⟩ + +/-- The second call's return label pushes block 1's offset (9) in place of block 2's (17). -/ +def mutantRet : ByteArray := + ⟨#[0x60, 0x05, 0x60, 0x09, 0x60, 0x07, 0x60, 0x1a, 0x56, 0x5b, 0x60, 0x09, 0x60, 0x08, 0x60, + 0x1a, 0x56, 0x5b, 0x01, 0x01, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x60, 0x01, 0x01, 0x90, + 0x56]⟩ + +def base : Assemble.Cert := + { offsets := [0x0, 0x9, 0x11, 0x1a], needs := [], top := 2 ^ 140, turned := [], + costs := [5, 5, 7, 5], rets := [1, 2] } + +/-- The callee's context from the second call. -/ +def calleeTwo : Ctx := + { need := 4, max := 4, types := [some false, some true, some false, some false], + labs := [none, some [2]], succ := [(2, 0)], rets := [2] } + +def cxWith (two : Ctx) : CtxCert := + { base := base, + ctxs := [[{ need := 0, max := 0, types := [], labs := [], succ := [(3, 0)], rets := [1] }], + [{ need := 2, max := 2, types := [some false, some false], labs := [], succ := [(3, 1)], + rets := [2] }], + [{ need := 3, max := 3, types := [some false, some false, some false], labs := [], succ := [], + rets := [] }], + [{ need := 3, max := 3, types := [some false, some true, some false], labs := [none, some [1]], + succ := [(1, 0)], rets := [1] }, two]] } + +/-- \`asm_cert.infer_ctx\`'s certificate. -/ +def cx : CtxCert := cxWith calleeTwo + +theorem check_ok : checkX prog code cx = true := by decide +kernel + +/-- A mutant return label: the bytecode's second call returns to block 1. -/ +theorem mutantRet_fails : checkX prog mutantRet cx = false := by decide +kernel + +/-- The second call's return label claimed to be the first call's. -/ +theorem wrongLabel_fails : + checkX prog code (cxWith { calleeTwo with labs := [none, some [1]], rets := [1] }) = false := by + decide +kernel + +/-- The second call's context entered one word low. -/ +theorem lowHeight_fails : + checkX prog code (cxWith { calleeTwo with need := 3, max := 3, types := [some false, some true, some false] }) = + false := by + decide +kernel + +/-- One entry per block, as \`AssembleCut.checkC\` takes it: the callee entered at three words or +more, typed as the first call leaves them; its return checks block 2's three words against the +two it knows. -/ +theorem single_fails : + checkC prog code { base with + needs := [0, 2, 3, 3], + types := [[], [some false, some false], [some false, some false, some false], + [some false, some true, some false]] } [0, 3, 3, 4] = false := by + decide +kernel + +/-- **The bytecode runs as the program, at every gas below \`2 ^ 256\`**: +\`AssembleCut.withinRun_of_checkC\`'s statement, from the checker with contexts. -/ +theorem bytecode (scope : SolarTV.Call → Prop) : + WithinRunLt SolarTV.evmirSem (fun _ => prog) code scope (RunOracle.CertOk cx.base) := + withinRun_of_checkX check_ok scope + +/-- info: 'SolidCore.Refinement.Solar.AssembleCtxExample.bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecode + +end SolidCore.Refinement.Solar.AssembleCtxExample diff --git a/SolidCore/Refinement/Solar/AssembleCtxGas.lean b/SolidCore/Refinement/Solar/AssembleCtxGas.lean new file mode 100644 index 00000000..40353410 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCtxGas.lean @@ -0,0 +1,453 @@ +import SolidCore.Refinement.Solar.AssembleCtx +import SolidCore.Refinement.Solar.AssembleGasLoop +import SolidCore.Refinement.Solar.AssembleLoopWithin + +/-! +# EVM IR to bytecode from a gas bound on, for internal functions called in several contexts + +The checker with contexts (`AssembleCtx.checkX`, `checkXB`) reads each run back from a frame that +succeeds, at the run's own gas: it proves no gas bound. Here is the forward direction with gas, for +the loop checker's fragment (memory at known offsets, no GAS, no call): `checkXL` checks each block +once per context with `AssembleLoop.blockOkL` under the context's certificate, except the blocks of +a set `F` that it leaves unchecked (a contract's functions outside a statement: the permit path's +STATICCALL and GAS, say). `guard F p` is the program with each block of `F` replaced by a jump to +itself, so a run of it that ends never enters `F`. `forward_of_checkXL`: when SolarTV's run of +`guard F p` ends within `n` blocks, then at every gas from `gasBoundL cx.base n` on, EthLib runs +the exact bytecode to exactly that result, reverts and their data included. That a valid call's +run of `guard F p` ends is a stage like any other (the run of `p` ends and never enters `F`), +which the stage generator proves by symbolic execution; nothing here assumes it. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCtxGas + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Final +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCtx +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +/-! ## The guarded program -/ + +/-- `p` with each block of `F` a jump to itself. -/ +def guard (F : List Nat) (p : Assemble.Program) : Assemble.Program := + ⟨p.blocks.mapIdx fun b instrs => if F.contains b then [.jump b] else instrs⟩ + +theorem guard_length (F : List Nat) (p : Assemble.Program) : + (guard F p).blocks.length = p.blocks.length := by + simp [guard] + +theorem guard_get? (F : List Nat) (p : Assemble.Program) (b : Nat) : + (guard F p).blocks[b]? = p.blocks[b]?.map fun instrs => if F.contains b then [.jump b] else instrs := by + simp [guard, List.getElem?_mapIdx] + +theorem block_guard_out {F : List Nat} {p : Assemble.Program} {o : Oracle} {call : Call} {b : Nat} + (hb : b < p.blocks.length) (hF : F.contains b = false) (S : List Word) (s : State) : + SolarTV.EVM.Program.block o call (guard F p) (b, S, s) = + some (SolarTV.EVM.Program.exec o call b p.blocks[b] S s) := by + simp only [SolarTV.EVM.Program.block, guard_get?, List.getElem?_eq_getElem hb, Option.map_some, + hF, Bool.false_eq_true, ite_false] + +theorem block_guard_end {F : List Nat} {p : Assemble.Program} {o : Oracle} {call : Call} + (S : List Word) (s : State) : + SolarTV.EVM.Program.block o call (guard F p) (p.blocks.length, S, s) = some (.inl (.stop, s)) := by + have h : (guard F p).blocks[p.blocks.length]? = none := by + rw [guard_get?, List.getElem?_eq_none (by omega)]; rfl + simp only [SolarTV.EVM.Program.block, h, guard_length, ite_true] + +/-- A run of `guard F p` that enters a block of `F` with fewer than 1024 words never ends. -/ +theorem iterate_guard_in {F : List Nat} {p : Assemble.Program} {o : Oracle} {call : Call} {b : Nat} + (hb : b < p.blocks.length) (hF : F.contains b = true) (S : List Word) (hS : S.length < 1024) + (s : State) : ∀ n, iterate (SolarTV.EVM.Program.block o call (guard F p)) n (b, S, s) = none + | 0 => rfl + | n + 1 => by + have hblk : SolarTV.EVM.Program.block o call (guard F p) (b, S, s) = some (.inr (b, S, s)) := by + simp only [SolarTV.EVM.Program.block, guard_get?, List.getElem?_eq_getElem hb, Option.map_some, + hF, ite_true, SolarTV.EVM.Program.exec] + rw [if_neg (by omega)] + simp only [iterate, hblk] + exact iterate_guard_in hb hF S hS s n + +/-! ## The checker -/ + +/-- Block `b` under a certificate, as `AssembleLoop.blocksOkL` checks it. -/ +def blockCtxOkL (p : Assemble.Program) (c : Cert) (mx : List Nat) (b : Nat) + (instrs : List Assemble.Instr) : Bool := + decide (labelItems p c b ≤ budget c b) && decide (c.need b ≤ maxH mx b) && + decide (maxH mx b + budget c b ≤ 1000) && + blockOkL p c mx b (c.need b) [] (c.entry b) (budget c b - labelItems p c b) instrs + +/-- Block `b` in context `j`, on the loop checker's fragment. -/ +def ctxOkL (p : Assemble.Program) (cx : CtxCert) (b j : Nat) (instrs : List Assemble.Instr) : Bool := + blockCtxOkL p (certAt cx (p.blocks.length + 1) b j) (maxsAt cx (p.blocks.length + 1) b j) b instrs && + exitsOk p.blocks.length cx b j (exits b (cx.at b j).labs instrs) && + labsCover (cx.at b j).types (cx.at b j).labs (cx.at b j).rets + +/-- Every block outside `F` in each of its contexts; a block of `F` is entered with at most 1000 +words in every context. -/ +def blocksXL (F : List Nat) (p : Assemble.Program) (cx : CtxCert) : + Nat → List (List Assemble.Instr) → Bool + | _, [] => true + | b, instrs :: rest => + (List.range (cx.count b)).all (fun j => + if F.contains b then decide ((cx.at b j).max ≤ 1000) else ctxOkL p cx b j instrs) && + blocksXL F p cx (b + 1) rest + +/-- **The checker with contexts and gas**: the layout of `AssembleLoop.checkL`, the first +block's first context at height zero, and every block outside `F` in each of its contexts. -/ +def checkXL (F : List Nat) (p : Assemble.Program) (code : ByteArray) (cx : CtxCert) : Bool := + (walk (bytesOf code) cx.base.offset 0 (lower p cx.base)).isSome && labelsValid p cx.base code && + decide (cx.base.top % 32 = 0) && decide (cx.base.top ≤ 2 ^ 32) && decide (code.size < 2 ^ 32) && + decide (0 < cx.count 0) && decide ((cx.at 0 0).need = 0) && !F.contains 0 && + blocksXL F p cx 0 p.blocks + +theorem blocksXL_get {F : List Nat} {p : Assemble.Program} {cx : CtxCert} : + ∀ (l : List (List Assemble.Instr)) (b : Nat), blocksXL F p cx b l = true → + ∀ k (hk : k < l.length) j, j < cx.count (b + k) → + (if F.contains (b + k) then decide ((cx.at (b + k) j).max ≤ 1000) + else ctxOkL p cx (b + k) j l[k]) = true + | [], _, _, _, hk, _, _ => absurd hk (by simp) + | x :: l, b, h, 0, _, j, hj => by + simp only [blocksXL, Bool.and_eq_true, List.all_eq_true, List.mem_range] at h + simpa using h.1 j (by simpa using hj) + | x :: l, b, h, k + 1, hk, j, hj => by + simp only [blocksXL, Bool.and_eq_true] at h + have := blocksXL_get l (b + 1) h.2 k (by simp at hk; omega) j + (by rw [show b + 1 + k = b + (k + 1) by omega]; exact hj) + rw [show b + (k + 1) = b + 1 + k by omega] + simpa using this + +/-- The facts of the checker. -/ +structure GlobXL (F : List Nat) (p : Assemble.Program) (cx : CtxCert) (code : ByteArray) : Prop where + glob : GlobLT p cx.base code + block : ∀ b (hb : b < p.blocks.length), F.contains b = false → ∀ j, j < cx.count b → + ctxOkL p cx b j p.blocks[b] = true + guarded : ∀ b, b < p.blocks.length → F.contains b = true → ∀ j, j < cx.count b → (cx.at b j).max ≤ 1000 + +theorem globXL_of_checkXL {F : List Nat} {p : Assemble.Program} {code : ByteArray} {cx : CtxCert} + (h : checkXL F p code cx = true) : + GlobXL F p cx code ∧ Seg (bytesOf code) cx.base.offset 0 (lower p cx.base) code.size ∧ + 0 < cx.count 0 ∧ (cx.at 0 0).need = 0 ∧ F.contains 0 = false := by + simp only [checkXL, Bool.and_eq_true, decide_eq_true_eq, Bool.not_eq_true'] at h + obtain ⟨⟨⟨⟨⟨⟨⟨⟨hw, hlabels⟩, hmod⟩, htop⟩, hsize⟩, hcount⟩, hneed⟩, hF0⟩, hblocks⟩ := h + obtain ⟨stream, hw⟩ := Option.isSome_iff_exists.1 hw + have hseg : Seg (bytesOf code) cx.base.offset 0 (lower p cx.base) code.size := by + have := seg_of_walk (walk_sound hw) + rwa [length_bytesOf] at this + refine ⟨⟨⟨hmod, htop, hsize, fun t ht htgt => ?_⟩, fun b hb hF j hj => ?_, fun b hb hF j hj => ?_⟩, + hseg, hcount, hneed, hF0⟩ + · have hv : isValidJumpDest (validJumpDestinations code) (cx.base.offset t) = true := by + simp only [labelsValid, List.all_eq_true, List.mem_range] at hlabels + have := hlabels t ht + simpa [htgt] using this + obtain ⟨pc', hs, hpc⟩ := seg_lowerFrom p cx.base t p.blocks 0 0 hseg ht + simp only [Nat.zero_add] at hs hpc + rw [← hpc htgt] at hs + refine ⟨hv, ?_, hs⟩ + have hs' := hs + rw [lowerFrom_drop p cx.base ht] at hs' + simp only [lowerBlock, htgt, ite_true, List.cons_append] at hs' + cases hs' with + | cons d _ _ => + have := decode_lt d + rwa [length_bytesOf] at this + · have := blocksXL_get p.blocks 0 hblocks b hb j (by simpa using hj) + simp only [Nat.zero_add, hF] at this + simpa using this + · have := blocksXL_get p.blocks 0 hblocks b hb j (by simpa using hj) + simp only [Nat.zero_add, hF] at this + simpa using this + +theorem globLT_congr {p : Assemble.Program} {code : ByteArray} {c1 c2 : Cert} (h : Same c1 c2) + (G : GlobLT p c1 code) : GlobLT p c2 code where + top_mod := h.2.2 ▸ G.top_mod + top_le := h.2.2 ▸ G.top_le + size_lt := G.size_lt + target := fun t ht htg => by + rw [← isTarget_congr h.2.1] at htg + rw [← h.offset, ← lowerFrom_congr h.2.1] + exact G.target t ht htg + +theorem entryL_congr {c1 c2 : Cert} (h : Same c1 c2) {p : Assemble.Program} {code : ByteArray} + {call : Call} {b R pc : Nat} {s : State} {M : ByteArray} {g : Nat} + (E : EntryL c1 code call (lowerFrom p c1 b (p.blocks.drop b)) R pc s M g) : + EntryL c2 code call (lowerFrom p c2 b (p.blocks.drop b)) R pc s M g := by + obtain ⟨hseg, hg, htop, hmem⟩ := E + refine ⟨?_, h.2.2 ▸ hg, h.2.2 ▸ htop, hmem⟩ + rw [← h.offset, ← lowerFrom_congr h.2.1] + exact hseg + +/-! ## The forward simulation -/ + +/-- The relation at a block entry, with gas for `R` more items: `AssembleLoop.run_simL`'s, under a +certificate of the layout, at the height range and types of one of the block's contexts when the +block is outside `F`. -/ +def EntL (F : List Nat) (p : Assemble.Program) (cx : CtxCert) (code : ByteArray) (call : Call) + (R : Nat) (x : Nat × List Word × State) (pc : Nat) (T : List Word) (M : ByteArray) (g : Nat) : + Prop := + ∃ (c : Cert) (mx : List Nat), Same c cx.base ∧ x.1 ≤ p.blocks.length ∧ + (x.1 < p.blocks.length → c.need x.1 ≤ x.2.1.length ∧ x.2.1.length ≤ maxH mx x.1) ∧ + SR c (c.entry x.1) x.2.1 T ∧ EntryL c code call (lowerFrom p c x.1 (p.blocks.drop x.1)) R pc x.2.2 M g ∧ + (x.1 < p.blocks.length → ∃ j, j < cx.count x.1 ∧ c.need x.1 = (cx.at x.1 j).need ∧ + maxH mx x.1 = (cx.at x.1 j).max ∧ c.entry x.1 = (cx.at x.1 j).types ∧ + LabOk (cx.at x.1 j).labs x.2.1) + +theorem bmax_certAt (cx : CtxCert) (n b j : Nat) : bmax (certAt cx n b j) = bmax cx.base := rfl + +open SolarTV.EVM.Program in +/-- **EthLib runs the bytecode as SolarTV runs `guard F p`**, from a block whose relation holds, +with gas for `fuel` blocks: to SolarTV's result when its run ends within them. -/ +theorem run_simXL {F : List Nat} {p : Assemble.Program} {cx : CtxCert} {code : ByteArray} + (G : GlobXL F p cx code) + {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + {a : Nat} (hcaller : msg.caller = Target.address a) (ho : cx.base.env = true → OracleOkAt a o) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : cx.base.reads = true → msg.txEnv = Target.txEnv) + (he : cx.base.reads = true → EnvOk o) : + ∀ (fuel b : Nat) (S T : List Word) (s : SolarTV.Machine.State) (pc : Nat) (M : ByteArray) + (g : Nat) (st : State.TransactionState) (ss : Substate), + EntL F p cx code call (fuel * bmax cx.base) (b, S, s) pc T M g → Rel msg ss0 st ss s → + ∀ r, SolarTV.Machine.iterate (block o call (guard F p)) fuel (b, S, s) = some r → + SpecG .fusaka (At code msg pc T M g st ss .empty) (PostL call msg.currentTarget ss0 r.2 r.1) + | 0, b, S, T, s, pc, M, g, st, ss, _, _, r, hr => by simp [SolarTV.Machine.iterate] at hr + | fuel + 1, b, S, T, s, pc, M, g, st, ss, hE, R, r, hr => by + obtain ⟨c0, mx0, hsame0, hle, hneed0, hR0, E0, hctx⟩ := hE + dsimp only at hle hneed0 hR0 E0 hctx + by_cases hb : b < p.blocks.length + · obtain ⟨j, hj, hn0, hm0, he0, hlab⟩ := hctx hb + cases hF : F.contains b with + | true => + have hS : S.length < 1024 := by + have := G.guarded b hb hF j hj + have := (hneed0 hb).2 + omega + rw [iterate_guard_in hb hF S hS s] at hr + cases hr + | false => + have hbn : b < p.blocks.length + 1 := by omega + obtain ⟨c, hc⟩ : ∃ c, c = certAt cx (p.blocks.length + 1) b j := ⟨_, rfl⟩ + obtain ⟨mx, hmx⟩ : ∃ mx, mx = maxsAt cx (p.blocks.length + 1) b j := ⟨_, rfl⟩ + have hsame : Same c cx.base := hc ▸ certAt_same cx _ b j + have hsame' : Same c0 c := ⟨hsame0.1.trans hsame.1.symm, hsame0.2.1.trans hsame.2.1.symm, + hsame0.2.2.trans hsame.2.2.symm⟩ + have hcb : c.need b = (cx.at b j).need := by + rw [hc, certAt_need hbn, pick_of_exit (exitCtx_self cx b j)] + have hmb : maxH mx b = (cx.at b j).max := by + rw [hmx, maxsAt_max hbn, pick_of_exit (exitCtx_self cx b j)] + have heb : c.entry b = (cx.at b j).types := by + rw [hc, certAt_entry hbn, pick_of_exit (exitCtx_self cx b j)] + have hcr : c.rets = (cx.at b j).rets := by rw [hc]; rfl + have hbc : bmax c = bmax cx.base := by rw [hc]; rfl + have hck := G.block b hb hF j hj + simp only [ctxOkL, Bool.and_eq_true] at hck + obtain ⟨⟨hblk0, hexOk⟩, hcov⟩ := hck + have hR : SR c (c.entry b) S T := by + rw [heb, ← he0] + exact SR_congr hsame' hR0 (by rw [he0, hcr]; exact labsCover_mem hcov hlab) + have E : EntryL c code call (lowerFrom p c b (p.blocks.drop b)) ((fuel + 1) * bmax c) pc s M g := by + rw [hbc]; exact entryL_congr hsame' E0 + have hn : c.need b ≤ S.length := by rw [hcb, ← hn0]; exact (hneed0 hb).1 + have hm : S.length ≤ maxH mx b := by rw [hmb, ← hm0]; exact (hneed0 hb).2 + have hGc : GlobLT p c code := globLT_congr ⟨hsame.1.symm, hsame.2.1.symm, hsame.2.2.symm⟩ G.glob + rw [← hc, ← hmx] at hblk0 + simp only [blockCtxOkL, Bool.and_eq_true, decide_eq_true_eq] at hblk0 + obtain ⟨⟨⟨hL, hnm⟩, hstk⟩, hblock⟩ := hblk0 + have hbm := budget_le_bmax c b + have hfm : (fuel + 1) * bmax c = fuel * bmax c + bmax c := Nat.succ_mul _ _ + obtain ⟨pc1, g1, hlabel, hg1, I1⟩ : ∃ pc1 g1, HoareG .fusaka (At code msg pc T M g st ss .empty) + (At code msg pc1 T M g1 st ss .empty) ∧ g1 + (if isTarget p c b then 1 else 0) ≤ g ∧ + InvL c code call (lowerInstrs p c b p.blocks[b] ++ + lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) (budget c b - labelItems p c b) + (fuel * bmax c) pc1 S s M g1 := by + have E' := E + rw [lowerFrom_drop p c hb, lowerBlock, List.append_assoc] at E' + have hG := E'.gas + rw [hfm] at hG + by_cases ht : isTarget p c b = true + · have hl : labelItems p c b = 1 := by simp [labelItems, ht] + rw [hl] at hL ⊢ + simp only [ht, ite_true, List.singleton_append] at E' + obtain ⟨next, hd, hseg⟩ := E'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + exact ⟨pc + 1, g - 1, Logic.jumpdestG hlt hcode (by omega), by simp only [ht, ite_true]; omega, + ⟨hseg, by omega, by omega, E'.le_top, E'.mem⟩⟩ + · have hl : labelItems p c b = 0 := by simp [labelItems, ht] + rw [hl, Nat.sub_zero] + simp only [ht, Bool.false_eq_true, ite_false, List.nil_append] at E' + exact ⟨pc, g, Triple.of_imp fun _ h => h, by simp only [ht, Bool.false_eq_true, ite_false]; omega, + ⟨E'.seg, by omega, by omega, E'.le_top, E'.mem⟩⟩ + have hsim := exec_simL (o := o) hGc hdata hvalue hstatic hself hcaller (by rw [hc]; exact ho) + hbenv (by rw [hc]; exact htx) (by rw [hc]; exact he) b hb (fuel * bmax c) + p.blocks[b] (c.need b) [] (c.entry b) S T _ s pc1 M g1 st ss hblock hn (by omega) + (KR.nil _) hR I1 R + cases hexE : exits b (cx.at b j).labs p.blocks[b] with + | none => rw [hexE] at hexOk; simp [exitsOk] at hexOk + | some Ex => + rw [hexE] at hexOk + simp only [SolarTV.Machine.iterate, block_guard_out hb hF] at hr + generalize hx : exec o call b p.blocks[b] S s = x at hsim hr + rcases x with ⟨halt, s'⟩ | ⟨t, S', s'⟩ + · simp only [Option.some.injEq] at hr + subst hr + exact SpecG.seq hlabel hsim + · obtain ⟨⟨htle, hneedt, hj⟩, pc', T', M', g', st', ss', hh, hR', E', R'⟩ := hsim + obtain ⟨L', hmemE, hL'⟩ := exits_sound o call b p.blocks[b] _ S s Ex _ hlab hexE hx + have IH := run_simXL G hdata hvalue hstatic hself hcaller ho hbenv htx he fuel t S' T' s' pc' + M' g' st' ss' ⟨c, mx, hsame, htle, hneedt, hR', by rw [← hbc]; exact E', fun ht => ?_⟩ R' r hr + · exact SpecG.seq (Triple.seq hlabel hh) IH + · obtain ⟨j', hx', hj'c, hlabs⟩ := exitsOk_mem hexOk hmemE ht + have htn : t < p.blocks.length + 1 := by omega + have hpk := pick_of_exit hx' + refine ⟨j', hj'c, ?_, ?_, ?_, hL'.le hlabs⟩ + · rw [hc, certAt_need htn, hpk] + · rw [hmx, maxsAt_max htn, hpk] + · rw [hc, certAt_entry htn, hpk] + · obtain rfl : b = p.blocks.length := by omega + simp only [SolarTV.Machine.iterate, block_guard_end, Option.some.injEq] at hr + subst hr + have hseg := E0.seg + rw [lowerFrom_nil p c0 (by omega)] at hseg + have hpc := hseg.nil_end + exact SpecG.consequence (stop_of_size_leG (by omega)) + (fun _ h => h) fun evm h => postL_stop R hself evm h + +/-- **The forward assembly theorem for code with contexts.** When SolarTV's run of `guard F p` +ends within `n` blocks, from `gasBoundL cx.base n` gas on EthLib runs the exact bytecode to +exactly its result. -/ +theorem forward_of_checkXL {F : List Nat} {p : Assemble.Program} {code : ByteArray} {cx : CtxCert} + (hc : checkXL F p code cx = true) (o : SolarTV.Machine.Oracle) (ho : cx.base.env = true → OracleOk o) + (he : cx.base.reads = true → EnvOk o) (call : SolarTV.Call) (n : Nat) + (r : SolarTV.Machine.Halt × SolarTV.Machine.State) + (hit : SolarTV.Machine.iterate (SolarTV.EVM.Program.block o call (guard F p)) n + (0, [], SolarTV.Machine.State.initial call) = some r) + {gas : Nat} (hg : gasBoundL cx.base n ≤ gas) : + Final.Target.runWith gas code call = some (SolarTV.Machine.observe call r.2 r.1) := by + obtain ⟨G, hseg, hcount, hneed0, hF0⟩ := globXL_of_checkXL hc + have hm0 : memoryGasCost (ByteArray.empty).size = 0 := by decide + refine Assemble.run_of_rel_with code call r.2 r.1 gas fun st R => ?_ + have h0n : 0 < p.blocks.length + 1 := by omega + have hsame := certAt_same cx (p.blocks.length + 1) 0 0 + have hn0 : (certAt cx (p.blocks.length + 1) 0 0).need 0 = (cx.at 0 0).need := by + rw [certAt_need h0n, pick_of_exit (exitCtx_self cx 0 0)] + refine SpecG.toSpec (run_simXL G rfl (by simp [Final.Target.messageWith, Target.message]) rfl rfl rfl ho rfl (fun _ => rfl) he + n 0 [] [] _ 0 .empty gas st Substate.empty + ⟨certAt cx (p.blocks.length + 1) 0 0, maxsAt cx (p.blocks.length + 1) 0 0, hsame, Nat.zero_le _, + fun _ => ⟨by simp [hn0, hneed0], by simp⟩, SR.nil _ _, ⟨?_, ?_, by simp, memRel_initial⟩, + fun _ => ⟨0, hcount, hn0, by rw [maxsAt_max h0n, pick_of_exit (exitCtx_self cx 0 0)], + by rw [certAt_entry h0n, pick_of_exit (exitCtx_self cx 0 0)], LabOk.empty _⟩⟩ R r hit) + · rw [hsame.offset, lowerFrom_congr hsame.2.1, List.drop_zero] + exact hseg + · rw [hm0, hsame.2.2] + unfold gasBoundL at hg + exact Nat.le_trans (Nat.add_le_add_left (Nat.sub_le _ _) _) hg + +/-- info: 'SolidCore.Refinement.Solar.AssembleCtxGas.forward_of_checkXL' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms forward_of_checkXL + +open SolidCore.Refinement.Evm.Symex in +/-- **EVM IR to bytecode at every gas, without hypotheses on the runner of messages.** When +SolarTV's run of `guard F p` ends within `n` blocks, every result EthLib gives for the exact +bytecode at any gas is that run's result, or a failure that changes nothing: a run that succeeds at +gas `g` is the run with `gasBoundL cx.base n` more gas, which `run_simXL` follows to the end. No +block of `F` (the only ones with STATICCALL or GAS) is reached, so the runner of messages is never +consulted. -/ +theorem within_of_checkXL {F : List Nat} {p : Assemble.Program} {code : ByteArray} {cx : CtxCert} + (hc : checkXL F p code cx = true) (o : SolarTV.Machine.Oracle) (ho : cx.base.env = true → OracleOk o) + (he : cx.base.reads = true → EnvOk o) (call : SolarTV.Call) (n : Nat) + (r : SolarTV.Machine.Halt × SolarTV.Machine.State) + (hit : SolarTV.Machine.iterate (SolarTV.EVM.Program.block o call (guard F p)) n + (0, [], SolarTV.Machine.State.initial call) = some r) (gas : Nat) (obs : Observable) + (hrun : Final.Target.runWith gas code call = some obs) : + obs = SolarTV.Machine.observe call r.2 r.1 ∨ + (obs.success = false ∧ obs.storage = slotValue call.storage ∧ obs.logs = []) := by + obtain ⟨G, hseg, hcount, hneed0, hF0⟩ := globXL_of_checkXL hc + cases hs : obs.success + · exact Or.inr ⟨rfl, Target.runWith_failure hrun hs⟩ + left + unfold Target.runWith Target.runMsg at hrun + split at hrun + · cases hrun + rename_i evm hev hpm + simp only [Option.some.injEq] at hrun + subst hrun + have hok : evm.error = none := by simpa using hs + obtain ⟨st', ss', runChild, within, hcases, hmove, hrf⟩ := + processMessage_ok (message := Final.Target.messageWith gas code call) (evm := ⟨evm, hev⟩) + (precompileAddress_message code call) hpm hok + simp only at hrf + set msg := Final.Target.messageWith gas code call with hmsg + have hcode : msg.code = code := rfl + have R := rel_start code call gas ss' (fun h => (hcases h).1) (fun h => (hmove h).1) + have hm0 : memoryGasCost (ByteArray.empty).size = 0 := by decide + have h0n : 0 < p.blocks.length + 1 := by omega + have hsame := certAt_same cx (p.blocks.length + 1) 0 0 + have hn0 : (certAt cx (p.blocks.length + 1) 0 0).need 0 = (cx.at 0 0).need := by + rw [certAt_need h0n, pick_of_exit (exitCtx_self cx 0 0)] + have hsim := run_simXL (msg := msg) (ss0 := ss') G rfl (by simp [msg, Final.Target.messageWith, + Target.message]) rfl rfl rfl ho rfl (fun _ => rfl) he n 0 [] [] _ 0 .empty (gas + gasBoundL cx.base n) st' ss' + ⟨certAt cx (p.blocks.length + 1) 0 0, maxsAt cx (p.blocks.length + 1) 0 0, hsame, Nat.zero_le _, + fun _ => ⟨by simp [hn0, hneed0], by simp⟩, SR.nil _ _, + ⟨by rw [hsame.offset, lowerFrom_congr hsame.2.1, List.drop_zero]; exact hseg, + by + rw [hm0] + show 22100 * (n * bmax cx.base) + (memoryGasCost (certAt cx (p.blocks.length + 1) 0 0).top - 0) ≤ _ + have : memoryGasCost (certAt cx (p.blocks.length + 1) 0 0).top - 0 ≤ memoryGasCost cx.base.top := by + rw [hsame.2.2]; exact Nat.sub_le _ _ + unfold gasBoundL; omega, + by simp, memRel_initial⟩, + fun _ => ⟨0, hcount, hn0, by rw [maxsAt_max h0n, pick_of_exit (exitCtx_self cx 0 0)], + by rw [certAt_entry h0n, pick_of_exit (exitCtx_self cx 0 0)], LabOk.empty _⟩⟩ R r hit + have hl : At code msg 0 [] .empty gas st' ss' .empty (startFrame msg st' ss' msg.gas) := + ⟨by simp [startFrame, hcode], by simp [startFrame, hcode], rfl, rfl, rfl, rfl, rfl, rfl, rfl, + rfl, rfl, rfl, rfl⟩ + have hp := hl.addGas (gasBoundL cx.base n) + rcases r with ⟨halt, sF⟩ + obtain ⟨ssF, ⟨herr, hout, hlogsF, hst⟩, L, hL1, hL2⟩ := SpecG.low hsim hp within hrf hok + have hss' : ss'.logs.toList = [] := by + by_cases htr : msg.shouldTransferValue = true ∧ msg.value ≠ 0 + · rw [(hmove htr).2] + simp [pushTransferLog, show ¬ (Fork.fusaka ≥ Fork.glamsterdam) by decide, Substate.empty] + · rw [(hcases htr).2] + simp [Substate.empty] + have hlogs := logs_of_match hL2 + have hL1' : ssF.logs.toList = L := by rw [hL1, hss', List.nil_append] + have herr' : evm.error = errorOf (SolarTV.Machine.observe call sF halt) := herr + have hout' : evm.output.toList.map (·.toNat) = (SolarTV.Machine.observe call sF halt).output := hout + have hst' : (SolarTV.Machine.observe call sF halt).success = true → + evm.substate.logs = ssF.logs ∧ ∀ slot, + (evm.state.getStorage (Target.address selfAddress) (Target.storageKey slot)).toNat = + (SolarTV.Machine.observe call sF halt).storage slot := + fun h => ⟨hlogsF, hst h⟩ + have hok2 : (SolarTV.Machine.observe call sF halt).success = true → + (SolarTV.Machine.observe call sF halt).logs = SolarTV.Machine.logs sF := by + cases halt <;> simp [SolarTV.Machine.observe] + clear herr hout hst hsim hit + generalize SolarTV.Machine.observe call sF halt = X at * + have hsucc : evm.error.isNone = X.success := by + rw [herr']; cases hX : X.success <;> simp [errorOf, hX] + cases X with + | mk success output logs storage => + simp only at hsucc hout' hok2 hst' ⊢ + rw [SolarTV.Observable.mk.injEq] + refine ⟨hsucc, hout', ?_, ?_⟩ + · rw [hsucc] + cases hs : success + · simp [hok, hs] at hsucc + · simp only [ite_true] + rw [(hst' hs).1, hL1', hlogs, hok2 hs] + rfl + · funext slot + rw [hsucc] + cases hs : success + · simp [hok, hs] at hsucc + · simp only [ite_true] + exact (hst' hs).2 slot + +/-- info: 'SolidCore.Refinement.Solar.AssembleCtxGas.within_of_checkXL' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms within_of_checkXL + +end SolidCore.Refinement.Solar.AssembleCtxGas diff --git a/SolidCore/Refinement/Solar/AssembleCtxGasFrom.lean b/SolidCore/Refinement/Solar/AssembleCtxGasFrom.lean new file mode 100644 index 00000000..c625af7a --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCtxGasFrom.lean @@ -0,0 +1,333 @@ +import SolidCore.Refinement.Solar.AssembleCtxGas + +/-! +# The forward assembly theorem with gas, from any caller + +`Final.Target.runWith gas` runs one message from the fixed account `callerAddress`. Here +`Final.Target.runWithFrom a gas` runs the same message from the account `a` (its sender and the +transaction's origin, holding exactly the call's value), any account below `2 ^ 160` but the +contract's own, at `gas` gas; at `callerAddress` it is `runWith` (`runWithFrom_callerAddress`). + +`forward_of_checkXLFrom` is `AssembleCtxGas.forward_of_checkXL` for it: when SolarTV's run of +`guard F p`, under an oracle whose CALLER is `a` and whose Keccak-256 is EthLib's, ends within +`n` blocks, then at every gas from `gasBoundL cx.base n` on EthLib runs the exact bytecode from +`a` to exactly that result. The bound is the same for every caller: it charges every item of the +lowered program 22100 gas, at least the price of any instruction of the loop checker's fragment +under EIP-2929 (an SSTORE to a cold slot that sets a zero slot: 20000 + 2100; a cold SLOAD: 2100), +whatever slots and accounts the call finds warm or cold; EthLib's interpreter meters the actual +accesses, so the theorem holds of the access sets the run builds, not of a model of them. + +The lemmas on `preStateFrom` follow `AssembleSim`'s on `preState`. +-/ + +namespace SolidCore.Refinement.Target + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.State + +/-- The transaction of a call from the account `caller`, its origin. -/ +def txEnvFrom (caller : Nat) : TransactionEnvironment .fusaka := + { origin := address caller, gasPrice := 0, blobVersionedHashes := fun _ => [] } + +/-- The state before a call from the account `caller`: `code` at `selfAddress` with the call's +storage, and `caller` holding exactly the call value. -/ +def preStateFrom (caller : Nat) (code : ByteArray) (call : Call) : TransactionState := + let hash := EthLib.Cryptography.Hash.Keccak.keccak256 code + let storage : Std.ExtTreeMap Bytes32 U256 := + call.storage.foldl (fun m kv => m.insert (storageKey kv.1) (BitVec.ofNat 256 kv.2)) ∅ + let pre : State := + { accounts := ((∅ : Std.ExtTreeMap Address Account).insert (address selfAddress) + { nonce := 1, balance := 0, codeHash := hash }).insert (address caller) + { nonce := 0, balance := BitVec.ofNat 256 call.callvalue, + codeHash := EthLib.Cryptography.Hash.Keccak.keccak256 .empty }, + storage := (∅ : Std.ExtTreeMap Address (Std.ExtTreeMap Bytes32 U256)).insert + (address selfAddress) storage, + code := (∅ : Std.ExtTreeMap Hash32 ByteArray).insert hash code } + TransactionState.ofBlock + { preState := pre, accountWrites := ∅, storageWrites := ∅, codeWrites := ∅, + storageClears := ∅ } + +/-- The message of a call from the account `caller` with `gas` gas to `selfAddress`. -/ +def messageFromWith (caller gas : Nat) (code : ByteArray) (call : Call) : Message .fusaka := + { blockEnv, txEnv := txEnvFrom caller, caller := address caller, + target := some (address selfAddress), + currentTarget := address selfAddress, gas, value := call.callvalue, + data := call.calldata, codeAddress := some (address selfAddress), + code, depth := 0, shouldTransferValue := true, isStatic := false, + disablePrecompiles := false } + +theorem txEnvFrom_callerAddress : txEnvFrom callerAddress = txEnv := rfl + +theorem preStateFrom_callerAddress : preStateFrom callerAddress = preState := rfl + +end SolidCore.Refinement.Target + +namespace SolidCore.Refinement.Final.Target + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm + +/-- **EthLib's run of `call` from the account `caller` with `gas` gas.** -/ +def runWithFrom (caller gas : Nat) (code : ByteArray) (call : Call) : Option Observable := + match processMessage (Meter := Nat) .fusaka (Refinement.Target.messageFromWith caller gas code call) + (Refinement.Target.preStateFrom caller code call) Substate.empty with + | .error _ => none + | .ok ⟨evm, _⟩ => + let success := evm.error.isNone + some + { success + output := evm.output.toList.map (·.toNat) + logs := + if success then + evm.substate.logs.toList.map fun log => + (log.topics.map fun topic => bytesToNat topic.toList, + log.data.toList.map (·.toNat)) + else [] + storage := fun slot => + if success then + (evm.state.getStorage (Refinement.Target.address selfAddress) + (Refinement.Target.storageKey slot)).toNat + else slotValue call.storage slot } + +/-- From `callerAddress` it is `runWith`. -/ +theorem messageFromWith_callerAddress (gas : Nat) (code : ByteArray) (call : Call) : + Refinement.Target.messageFromWith callerAddress gas code call = messageWith gas code call := rfl + +theorem runWithFrom_callerAddress : runWithFrom callerAddress = runWith := by + funext gas code call + simp only [runWithFrom, runWith, runMsg, messageFromWith_callerAddress, + Refinement.Target.preStateFrom_callerAddress] + split <;> rename_i h <;> rw [h] + +end SolidCore.Refinement.Final.Target + +namespace SolidCore.Refinement.Solar.Assemble + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open EthLib.Execution.State +open SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Evm.Symex + +/-- The word of the address of a number below `2 ^ 160` is the number. -/ +theorem address_toNat {n : Nat} (h : n < 2 ^ 160) : (Target.address n).toU256.toNat = n := by + have h20 : n < 256 ^ 20 := by simpa using h + simp only [Address.toU256, Target.address, BitVec.toNat_ofNat] + rw [show (⟨(natToBytes 20 n).toArray, _⟩ : Address).toList = natToBytes 20 n from rfl, + bytesToNat_natToBytes_of_lt h20] + exact Nat.mod_eq_of_lt (Nat.lt_trans h (by decide)) + +/-- The address of an account below `2 ^ 160` other than `selfAddress` is not the contract's. -/ +theorem address_ne_self {a : Nat} (ha : a < 2 ^ 160) (hne : a ≠ selfAddress) : + Target.address selfAddress ≠ Target.address a := fun h => by + apply hne + have : (Target.address selfAddress).toU256.toNat = (Target.address a).toU256.toNat := + congrArg (fun x : Address => x.toU256.toNat) h + rw [address_toNat ha, address_toNat (show selfAddress < 2 ^ 160 by decide)] at this + exact this.symm + +theorem precompileAddress_messageFromWith (a gas : Nat) (code : ByteArray) (call : SolarTV.Call) : + precompileAddress .fusaka (Target.messageFromWith a gas code call) = none := by + have h := precompileAddress_message code call + unfold precompileAddress at h ⊢ + exact h + +theorem getStorage_preStateFrom (a : Nat) (code : ByteArray) (call : SolarTV.Call) (k : Nat) : + ((Target.preStateFrom a code call).getStorage (Target.address selfAddress) + (Target.storageKey k)).toNat = slotValue call.storage k := by + simp only [Target.preStateFrom, TransactionState.getStorage, TransactionState.ofBlock, + StorageMap.slot, State.getStorage] + simp + exact getD_foldl_insert _ _ _ _ (by simp) + +theorem getAccount_preStateFrom_self (a : Nat) (hAB : Target.address selfAddress ≠ Target.address a) + (code : ByteArray) (call : SolarTV.Call) : + (Target.preStateFrom a code call).getAccount (Target.address selfAddress) = + { nonce := 1, balance := 0, codeHash := EthLib.Cryptography.Hash.Keccak.keccak256 code } := by + simp only [Target.preStateFrom, TransactionState.getAccount, TransactionState.getAccountOptional, + TransactionState.ofBlock, State.getAccountOptional] + rw [Std.ExtTreeMap.getElem?_insert, ite_eq_right (fun h => absurd (Std.LawfulEqCmp.eq_of_compare h).symm hAB), + Std.ExtTreeMap.getElem?_insert, ite_eq_left (Std.ReflCmp.compare_self)] + simp + +theorem account_preStateFrom (a : Nat) (hAB : Target.address selfAddress ≠ Target.address a) + (code : ByteArray) (call : SolarTV.Call) : + (Target.preStateFrom a code call).getAccountOptional (Target.address selfAddress) ≠ none := by + simp only [Target.preStateFrom, TransactionState.getAccountOptional, TransactionState.ofBlock, + State.getAccountOptional] + rw [Std.ExtTreeMap.getElem?_insert, ite_eq_right (fun h => absurd (Std.LawfulEqCmp.eq_of_compare h).symm hAB), + Std.ExtTreeMap.getElem?_insert, ite_eq_left (Std.ReflCmp.compare_self)] + simp + +theorem getAccount_preStateFrom_caller (a : Nat) (code : ByteArray) (call : SolarTV.Call) : + ((Target.preStateFrom a code call).getAccount (Target.address a)).balance = + BitVec.ofNat 256 call.callvalue := by + simp only [Target.preStateFrom, TransactionState.getAccount, TransactionState.getAccountOptional, + TransactionState.ofBlock, State.getAccountOptional] + simp + +/-- `rel_initial` from the account `a`, at any gas. -/ +theorem rel_initialFrom (a gas : Nat) (hAB : Target.address selfAddress ≠ Target.address a) + (code : ByteArray) (call : SolarTV.Call) : + Rel (Target.messageFromWith a gas code call) Substate.empty (Target.preStateFrom a code call) + Substate.empty (SolarTV.Machine.State.initial call) := by + have htgt : (Target.messageFromWith a gas code call).currentTarget = Target.address selfAddress := rfl + refine ⟨fun k => ?_, ?_, ⟨[], by simp, .nil⟩⟩ + · apply BitVec.eq_of_toNat_eq + have hkey : U256.toBeBytes k = Target.storageKey k.toNat := + ((storageKey_eq_toBeBytes k.toNat k).2 (Nat.mod_eq_of_lt k.isLt)).symm + rw [htgt, hkey, getStorage_preStateFrom a code call k.toNat] + simp only [SolarTV.Machine.State.initial, BitVec.toNat_ofNat] + exact (Nat.mod_eq_of_lt (slotValue_lt _ _)).symm + · rw [htgt] + exact Option.isSome_iff_ne_none.2 (account_preStateFrom a hAB code call) + +/-- `moveEther_preState_any` from the account `a`. -/ +theorem moveEther_preStateFrom_any (a : Nat) (hAB : Target.address selfAddress ≠ Target.address a) + (code : ByteArray) (call : SolarTV.Call) : + ∃ st', (Target.preStateFrom a code call).moveEther .fusaka (Target.address a) + (Target.address selfAddress) (BitVec.ofNat 256 call.callvalue) = .ok st' := by + have hd : Account.debit (Target.address a) (BitVec.ofNat 256 call.callvalue) + ((Target.preStateFrom a code call).getAccount (Target.address a)) = + .ok { (Target.preStateFrom a code call).getAccount (Target.address a) with + balance := 0 } := by + simp [Account.debit, getAccount_preStateFrom_caller] + obtain ⟨t1, h1⟩ := modifyState_exists (fork := .fusaka) hd + have ha1 := (modifyState_ne h1 hAB (Target.storageKey 0)).2 + have hc : Account.credit (Target.address selfAddress) (BitVec.ofNat 256 call.callvalue) + (t1.getAccount (Target.address selfAddress)) = + .ok { t1.getAccount (Target.address selfAddress) with + balance := 0 + BitVec.ofNat 256 call.callvalue } := by + have : t1.getAccount (Target.address selfAddress) = + (Target.preStateFrom a code call).getAccount (Target.address selfAddress) := by + simp only [TransactionState.getAccount, ha1] + rw [this, getAccount_preStateFrom_self a hAB] + unfold Account.credit + rw [ite_eq_left_iff.mpr (fun h => absurd ?_ h)] + dsimp only + have h1 := (BitVec.ofNat 256 call.callvalue).isLt + have h0 : (0 : U256).toNat = 0 := rfl + omega + obtain ⟨t2, h2⟩ := modifyState_exists (fork := .fusaka) hc + exact ⟨t2, by simp [TransactionState.moveEther, bind, Except.bind, h1, h2]⟩ + +/-- `run_of_rel_with` from the account `a`: `runWithFrom a gas` of any call, with or without value. -/ +theorem run_of_rel_withFrom (a gas : Nat) (hAB : Target.address selfAddress ≠ Target.address a) + (code : ByteArray) (call : SolarTV.Call) (s : SolarTV.Machine.State) + (halt : SolarTV.Machine.Halt) + (h : ∀ st, Rel (Target.messageFromWith a gas code call) Substate.empty st Substate.empty + (SolarTV.Machine.State.initial call) → + Spec .fusaka (At code (Target.messageFromWith a gas code call) 0 [] .empty gas st Substate.empty + .empty) (PostL call (Target.address selfAddress) Substate.empty s halt)) : + Final.Target.runWithFrom a gas code call = some (SolarTV.Machine.observe call s halt) := by + have key : ∃ evm, processMessage (Meter := Nat) .fusaka (Target.messageFromWith a gas code call) + (Target.preStateFrom a code call) Substate.empty = .ok evm ∧ + MsgOut (SolarTV.Machine.observe call s halt) (Target.address selfAddress) Substate.empty + s.world evm.1 := by + by_cases hv : (Target.messageFromWith a gas code call).value = 0 + · exact processMessage_postL _ rfl hv (precompileAddress_messageFromWith a gas code call) _ _ _ _ _ + (h _ (rel_initialFrom a gas hAB code call)) + · obtain ⟨st', hmove⟩ := moveEther_preStateFrom_any a hAB code call + have hn : ((Target.preStateFrom a code call).getAccount + (Target.address selfAddress)).nonce ≠ 0 := by + rw [getAccount_preStateFrom_self a hAB]; simp + have R0 := rel_initialFrom a gas hAB code call + have R : Rel (Target.messageFromWith a gas code call) Substate.empty st' Substate.empty + (SolarTV.Machine.State.initial call) := + ⟨fun k => ((moveEther_recipient hmove hAB hn _).1).trans (R0.storage k), + (moveEther_recipient hmove hAB hn (Target.storageKey 0)).2, R0.logs⟩ + exact processMessage_postL_move _ rfl rfl hv (precompileAddress_messageFromWith a gas code call) + _ _ _ _ st' _ hmove (h st' R) + obtain ⟨evm, hr, ssF, ⟨L, hL1, hL2⟩, herr, hout, hst⟩ := key + have hlogs := logs_of_match hL2 + have hL1' : ssF.logs.toList = L := by simpa [Substate.empty] using hL1 + have hfail : (SolarTV.Machine.observe call s halt).success = false → + (SolarTV.Machine.observe call s halt).logs = [] ∧ + (SolarTV.Machine.observe call s halt).storage = slotValue call.storage := by + cases halt <;> simp [SolarTV.Machine.observe] + have hok : (SolarTV.Machine.observe call s halt).success = true → + (SolarTV.Machine.observe call s halt).logs = SolarTV.Machine.logs s := by + cases halt <;> simp [SolarTV.Machine.observe] + simp only [Final.Target.runWithFrom, hr] + generalize SolarTV.Machine.observe call s halt = X at * + have hsucc : evm.1.error.isNone = X.success := by + rw [herr]; cases hX : X.success <;> simp [errorOf, hX] + congr 1 + cases X with + | mk success output logs storage => + simp only at hsucc hout hfail hok hst ⊢ + rw [SolarTV.Observable.mk.injEq] + refine ⟨hsucc, hout, ?_, ?_⟩ + · rw [hsucc] + cases hs : success + · simp [(hfail hs).1] + · simp only [ite_true] + rw [(hst hs).1, hL1', hlogs, hok hs] + rfl + · funext slot + rw [hsucc] + cases hs : success + · simp [(hfail hs).2] + · simp only [ite_true] + exact (hst hs).2 slot + +end SolidCore.Refinement.Solar.Assemble + +namespace SolidCore.Refinement.Solar.AssembleCtxGas + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Final +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCtx +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +/-- **The forward assembly theorem with gas, from any caller.** For every account `a` but the +contract's: when SolarTV's run of `guard F p` under an oracle whose CALLER is `a` ends within +`n` blocks, then at every gas from `gasBoundL cx.base n` on, EthLib runs the exact bytecode from +`a` to exactly that result, a revert with its data included. A program that reads the +transaction's environment (`cx.base.reads`) is covered only where that environment is +`Target.txEnv`'s. -/ +theorem forward_of_checkXLFrom {F : List Nat} {p : Assemble.Program} {code : ByteArray} + {cx : CtxCert} (hc : checkXL F p code cx = true) (a : Nat) + (hAB : Target.address selfAddress ≠ Target.address a) (o : SolarTV.Machine.Oracle) + (ho : cx.base.env = true → OracleOkAt a o) + (he : cx.base.reads = true → EnvOk o ∧ Target.txEnvFrom a = Target.txEnv) + (call : SolarTV.Call) (n : Nat) (r : SolarTV.Machine.Halt × SolarTV.Machine.State) + (hit : SolarTV.Machine.iterate (SolarTV.EVM.Program.block o call (guard F p)) n + (0, [], SolarTV.Machine.State.initial call) = some r) + {gas : Nat} (hg : gasBoundL cx.base n ≤ gas) : + Final.Target.runWithFrom a gas code call = some (SolarTV.Machine.observe call r.2 r.1) := by + obtain ⟨G, hseg, hcount, hneed0, hF0⟩ := globXL_of_checkXL hc + have hm0 : memoryGasCost (ByteArray.empty).size = 0 := by decide + refine Assemble.run_of_rel_withFrom a gas hAB code call r.2 r.1 fun st R => ?_ + have h0n : 0 < p.blocks.length + 1 := by omega + have hsame := certAt_same cx (p.blocks.length + 1) 0 0 + have hn0 : (certAt cx (p.blocks.length + 1) 0 0).need 0 = (cx.at 0 0).need := by + rw [certAt_need h0n, pick_of_exit (exitCtx_self cx 0 0)] + refine SpecG.toSpec (run_simXL (a := a) G rfl (by simp [Target.messageFromWith]) rfl rfl rfl ho rfl + (fun h => (he h).2) (fun h => (he h).1) + n 0 [] [] _ 0 .empty gas st Substate.empty + ⟨certAt cx (p.blocks.length + 1) 0 0, maxsAt cx (p.blocks.length + 1) 0 0, hsame, Nat.zero_le _, + fun _ => ⟨by simp [hn0, hneed0], by simp⟩, SR.nil _ _, ⟨?_, ?_, by simp, memRel_initial⟩, + fun _ => ⟨0, hcount, hn0, by rw [maxsAt_max h0n, pick_of_exit (exitCtx_self cx 0 0)], + by rw [certAt_entry h0n, pick_of_exit (exitCtx_self cx 0 0)], LabOk.empty _⟩⟩ R r hit) + · rw [hsame.offset, lowerFrom_congr hsame.2.1, List.drop_zero] + exact hseg + · rw [hm0, hsame.2.2] + unfold gasBoundL at hg + exact Nat.le_trans (Nat.add_le_add_left (Nat.sub_le _ _) _) hg + +/-- info: 'SolidCore.Refinement.Solar.AssembleCtxGas.forward_of_checkXLFrom' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms forward_of_checkXLFrom + +/-- At `callerAddress` it is `forward_of_checkXL`'s statement. -/ +theorem forward_of_checkXL' {F : List Nat} {p : Assemble.Program} {code : ByteArray} {cx : CtxCert} + (hc : checkXL F p code cx = true) (o : SolarTV.Machine.Oracle) + (ho : cx.base.env = true → OracleOk o) (he : cx.base.reads = true → EnvOk o) + (call : SolarTV.Call) (n : Nat) (r : SolarTV.Machine.Halt × SolarTV.Machine.State) + (hit : SolarTV.Machine.iterate (SolarTV.EVM.Program.block o call (guard F p)) n + (0, [], SolarTV.Machine.State.initial call) = some r) + {gas : Nat} (hg : gasBoundL cx.base n ≤ gas) : + Final.Target.runWith gas code call = some (SolarTV.Machine.observe call r.2 r.1) := by + rw [← Final.Target.runWithFrom_callerAddress] + exact forward_of_checkXLFrom hc callerAddress (by decide) o ho (fun h => ⟨he h, rfl⟩) call n r hit hg + +end SolidCore.Refinement.Solar.AssembleCtxGas diff --git a/SolidCore/Refinement/Solar/AssembleCtxTrack.lean b/SolidCore/Refinement/Solar/AssembleCtxTrack.lean new file mode 100644 index 00000000..0587ce28 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCtxTrack.lean @@ -0,0 +1,394 @@ +import SolidCore.Refinement.Solar.AssembleSim + +/-! +# Which block a block of EVM IR leaves to, from the labels on its stack + +The checker of \`AssembleCtx\` checks a block once in each of its contexts, and a context names +the context each successor enters in. A dynamic jump goes to the label on top of the stack, so +which block it reaches, and so which context, is what the words on the stack are: this file reads +it from SolarTV alone. A \`Lab\` is what a word is known to be: \`some ts\` says it is a label of +one of the blocks \`ts\`; \`none\`, nothing. \`exits\` runs a block's instructions over such words +(a pushed label is its block, DUP and SWAP move what they move, every other result is unknown), +and \`exits_sound\`: every next block SolarTV's run of the block reaches is one \`exits\` lists, +with the words it lists at it. The EVM side is \`AssembleCut.seg\`'s; nothing here reads the +bytecode. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCtx + +open SolarTV SolarTV.Machine +open SolarTV.EVM.Program (exec stepOp context) +open SolidCore.Refinement.Solar.Assemble + +/-- What a word is known to be: a label of one of the blocks listed, or unknown. -/ +abbrev Lab := Option (List Nat) + +/-- What the word at depth \`i\` is known to be. -/ +def labAt (L : List Lab) (i : Nat) : Lab := L.getD i none + +/-- The words after SWAP of the top word and the word at depth \`i + 1\`. -/ +def labSwap (L : List Lab) (i : Nat) : List Lab := + List.ofFn (n := max L.length (i + 2)) fun j => + if j.val = 0 then labAt L (i + 1) else if j.val = i + 1 then labAt L 0 else labAt L j.val + +/-- Whether an effect leaves a result on the stack. -/ +def pushesE : Effect → Bool + | .mstore | .mstore8 | .sstore | .tstore | .log _ | .calldatacopy | .mcopy | .codecopy + | .returndatacopy => false + | _ => true + +/-- The next blocks a block's instructions reach from words known as \`L\`, each with what the +words are known to be there; \`none\` for a dynamic jump to an unknown word, or an instruction +the reading leaves out. -/ +def exits (b : Nat) : List Lab → List SolarTV.EVM.Program.Instr → Option (List (Nat × List Lab)) + | L, [] => some [(b + 1, L)] + | L, .op o :: rest => + match o with + | .stack op => + match op with + | .push _ => exits b (none :: L) rest + | .dup i => exits b (labAt L i.val :: L) rest + | .swap i => exits b (labSwap L i.val) rest + | .pop => exits b L.tail rest + | op => + match stackNeed op with + | some (n, _) => exits b (none :: L.drop n) rest + | none => none + | .load => exits b (none :: L.drop 1) rest + | .store => exits b (L.drop 2) rest + | _ => none + | L, .effect e a :: rest => + if pushesE e then exits b (none :: L.drop a) rest else exits b (L.drop a) rest + | L, .jump t :: _ => some [(t, L)] + | L, .jumpi t :: rest => (exits b L.tail rest).map ((t, L.tail) :: ·) + | L, .pushLabel t :: rest => exits b (some [t % 2 ^ 256] :: L) rest + | L, .jumpDyn :: _ => + match labAt L 0 with + | some ts => some (ts.map fun t => (t, L.tail)) + | none => none + | _, .jumpiDyn :: _ => none + | _, .jumpTable _ :: _ => none + | _, .stop :: _ => some [] + | _, .ret :: _ => some [] + | _, .revert :: _ => some [] + | _, .invalid :: _ => some [] + +/-- The words of \`S\` are what \`L\` says they are. -/ +def LabOk (L : List Lab) (S : List Word) : Prop := + ∀ i ts, labAt L i = some ts → ∀ w, S[i]? = some w → w.toNat ∈ ts + +theorem labAt_drop (L : List Lab) (n i : Nat) : labAt (L.drop n) i = labAt L (n + i) := by + simp [labAt, List.getD_eq_getElem?_getD, List.getElem?_drop] + +theorem labAt_cons_zero (x : Lab) (L : List Lab) : labAt (x :: L) 0 = x := rfl + +theorem labAt_cons_succ (x : Lab) (L : List Lab) (i : Nat) : labAt (x :: L) (i + 1) = labAt L i := by + simp [labAt] + +theorem labAt_nil (i : Nat) : labAt [] i = none := by simp [labAt] + +theorem LabOk.nil (S : List Word) : LabOk [] S := fun i ts h => by simp [labAt_nil] at h + +theorem LabOk.drop {L : List Lab} {S : List Word} (h : LabOk L S) (n : Nat) : + LabOk (L.drop n) (S.drop n) := by + intro i ts hl w hw + rw [labAt_drop] at hl + rw [List.getElem?_drop] at hw + exact h _ ts hl w hw + +theorem LabOk.tail {L : List Lab} {S : List Word} (h : LabOk L S) : LabOk L.tail S.tail := by + have := h.drop 1 + simpa using this + +theorem LabOk.cons {L : List Lab} {S : List Word} (h : LabOk L S) {x : Lab} {v : Word} + (hx : ∀ ts, x = some ts → v.toNat ∈ ts) : LabOk (x :: L) (v :: S) := by + intro i ts hl w hw + cases i with + | zero => + simp only [labAt_cons_zero] at hl + simp only [List.getElem?_cons_zero, Option.some.injEq] at hw + subst hw + exact hx ts hl + | succ i => + rw [labAt_cons_succ] at hl + simp only [List.getElem?_cons_succ] at hw + exact h i ts hl w hw + +theorem LabOk.cons_none {L : List Lab} {S : List Word} (h : LabOk L S) (v : Word) : + LabOk (none :: L) (v :: S) := h.cons (by simp) + +theorem LabOk.dup {L : List Lab} {S : List Word} (h : LabOk L S) {i : Nat} {v : Word} + (hv : S[i]? = some v) : LabOk (labAt L i :: L) (v :: S) := + h.cons fun ts hl => h i ts hl v hv + +theorem LabOk.swap {L : List Lab} {a : Word} {rest : List Word} (h : LabOk L (a :: rest)) {i : Nat} + {v : Word} (hv : rest[i]? = some v) : LabOk (labSwap L i) (v :: rest.set i a) := by + intro j ts hl w hw + have hlen : j < max L.length (i + 2) := by + by_contra hc + simp [labSwap, labAt, List.getD_eq_getElem?_getD, hc] at hl + have hl' : labAt (labSwap L i) j = + (if j = 0 then labAt L (i + 1) else if j = i + 1 then labAt L 0 else labAt L j) := by + simp [labSwap, labAt, List.getD_eq_getElem?_getD, hlen] + rw [hl'] at hl + by_cases h0 : j = 0 + · subst h0 + simp only [ite_true] at hl + simp only [List.getElem?_cons_zero, Option.some.injEq] at hw + subst hw + exact h (i + 1) ts hl v (by simpa using hv) + · simp only [h0, ite_false] at hl + obtain ⟨j, rfl⟩ : ∃ k, j = k + 1 := ⟨j - 1, by omega⟩ + simp only [List.getElem?_cons_succ] at hw + by_cases hi : j + 1 = i + 1 + · simp only [hi, ite_true] at hl + obtain rfl : i = j := by omega + have hil : i < rest.length := by + rcases Nat.lt_or_ge i rest.length with h' | h' + · exact h' + · simp [List.getElem?_eq_none h'] at hv + rw [List.getElem?_set_self hil] at hw + cases hw + exact h 0 ts hl a rfl + · simp only [hi, ite_false] at hl + rw [List.getElem?_set_ne (by omega)] at hw + exact h (j + 1) ts hl w (by simpa using hw) + +theorem LabOk.label {L : List Lab} {S : List Word} (h : LabOk L S) (t : Nat) : + LabOk (some [t % 2 ^ 256] :: L) (BitVec.ofNat 256 t :: S) := + h.cons fun ts hl => by cases hl; simp + +/-! ## SolarTV's steps, read backwards -/ + +theorem pushesE_apply {o : Oracle} {call : Call} {e : Effect} {args : List Word} {s s' : State} + {r : Option Word} (h : e.apply o call args s = some (r, s')) : r.isSome = pushesE e := by + unfold Effect.apply at h + split at h <;> (try split at h) <;> simp_all [pushesE, created] + all_goals (obtain ⟨rfl, -⟩ := h; rfl) + +variable {o : Oracle} {call : Call} {b : Nat} + +theorem exec_stack_inv {op : SolarTV.EVM.Op} {rest : List SolarTV.EVM.Program.Instr} {S : List Word} {s : State} + {y : Nat × List Word × State} (h : exec o call b (.op (.stack op) :: rest) S s = .inr y) : + ∃ next, SolarTV.EVM.step (context o call s) op S = some next ∧ exec o call b rest next s = .inr y := by + simp only [exec, stepOp] at h + by_cases h1 : S.length > 1024 + · simp [h1] at h + · simp only [h1, ite_false, SolarTV.EVM.stepChecked] at h + cases hs : SolarTV.EVM.step (context o call s) op S with + | none => simp [hs, Except.map] at h + | some next => + by_cases h2 : next.length > 1024 + · simp [hs, h2, Except.map] at h + · simp [hs, h2, Except.map] at h + exact ⟨next, rfl, h⟩ + +theorem exec_load_inv {rest : List SolarTV.EVM.Program.Instr} {S : List Word} {s : State} + {y : Nat × List Word × State} (h : exec o call b (.op .load :: rest) S s = .inr y) : + ∃ v s1, exec o call b rest (v :: S.drop 1) s1 = .inr y := by + simp only [exec, stepOp] at h + by_cases h1 : S.length > 1024 + · simp [h1] at h + · rcases S with _ | ⟨x, S⟩ + · simp at h + · by_cases h2 : 1024 < S.length + 1 + · simp [h2] at h + · simp [h2] at h + exact ⟨_, _, h⟩ + +theorem exec_store_inv {rest : List SolarTV.EVM.Program.Instr} {S : List Word} {s : State} + {y : Nat × List Word × State} (h : exec o call b (.op .store :: rest) S s = .inr y) : + ∃ s1, exec o call b rest (S.drop 2) s1 = .inr y := by + simp only [exec, stepOp] at h + by_cases h1 : S.length > 1024 + · simp [h1] at h + · rcases S with _ | ⟨x, _ | ⟨z, S⟩⟩ + · simp at h + · simp at h + · by_cases h2 : 1024 < S.length + 1 + 1 + · simp [h2] at h + · simp [h2] at h + exact ⟨_, h⟩ + +theorem exec_effect_inv {e : Effect} {a : Nat} {rest : List SolarTV.EVM.Program.Instr} {S : List Word} {s : State} + {y : Nat × List Word × State} (h : exec o call b (.effect e a :: rest) S s = .inr y) : + ∃ r s1, r.isSome = pushesE e ∧ + exec o call b rest (match r with | some v => v :: S.drop a | none => S.drop a) s1 = .inr y := by + simp only [exec] at h + by_cases h1 : S.length < a + · simp [h1] at h + · simp only [h1, ite_false] at h + cases ha : e.apply o call (S.take a) s with + | none => simp [ha] at h + | some rs => + obtain ⟨r, s1⟩ := rs + refine ⟨r, s1, pushesE_apply ha, ?_⟩ + simp only [ha] at h + cases r with + | none => + try simp only at h ⊢ + split at h + · cases h + · exact h + | some v => + try simp only at h ⊢ + split at h + · cases h + · exact h + +theorem exits_other {b : Nat} {L : List Lab} {rest : List SolarTV.EVM.Program.Instr} {op : SolarTV.EVM.Op} + (h0 : ∀ v, op ≠ .push v) (h1 : ∀ i, op ≠ .dup i) (h2 : ∀ i, op ≠ .swap i) (h3 : op ≠ .pop) : + exits b L (.op (.stack op) :: rest) = + match stackNeed op with + | some (n, _) => exits b (none :: L.drop n) rest + | none => none := by + cases op <;> first | rfl | exact absurd rfl (h0 _) | exact absurd rfl (h1 _) | + exact absurd rfl (h2 _) | exact absurd rfl h3 + +/-! ## The reading is sound -/ + +/-- **Every next block SolarTV's run of a block reaches is one \`exits\` lists**, with the words +there what it lists them as. -/ +theorem exits_sound (o : Oracle) (call : Call) (b : Nat) : + ∀ (is : List SolarTV.EVM.Program.Instr) (L : List Lab) (S : List Word) (s : State) (E : List (Nat × List Lab)) + (y : Nat × List Word × State), + LabOk L S → exits b L is = some E → exec o call b is S s = .inr y → + ∃ L', (y.1, L') ∈ E ∧ LabOk L' y.2.1 + | [], L, S, s, E, y, hL, hE, hx => by + simp only [exits, Option.some.injEq] at hE + simp only [exec, Sum.inr.injEq] at hx + subst hE hx + exact ⟨L, by simp, hL⟩ + | .op o' :: rest, L, S, s, E, y, hL, hE, hx => by + cases o' with + | stack op => + obtain ⟨next, hstep, hx'⟩ := exec_stack_inv hx + by_cases hpu : ∃ v, op = .push v + · obtain ⟨v, rfl⟩ := hpu + simp only [exits] at hE + simp only [SolarTV.EVM.step, Option.some.injEq] at hstep + subst hstep + exact exits_sound o call b rest _ _ s E y (hL.cons_none v) hE hx' + by_cases hdu : ∃ i, op = .dup i + · obtain ⟨i, rfl⟩ := hdu + simp only [exits] at hE + simp only [SolarTV.EVM.step] at hstep + cases hv : S[i.val]? with + | none => simp [hv] at hstep + | some v => + simp only [hv, Option.map_some, Option.some.injEq] at hstep + subst hstep + exact exits_sound o call b rest _ _ s E y (hL.dup hv) hE hx' + by_cases hsw : ∃ i, op = .swap i + · obtain ⟨i, rfl⟩ := hsw + simp only [exits] at hE + rcases S with _ | ⟨a, S⟩ + · simp [SolarTV.EVM.step] at hstep + simp only [SolarTV.EVM.step] at hstep + cases hv : S[i.val]? with + | none => simp [hv] at hstep + | some v => + simp only [hv, Option.map_some, Option.some.injEq] at hstep + subst hstep + exact exits_sound o call b rest _ _ s E y (hL.swap hv) hE hx' + by_cases hpo : op = .pop + · subst hpo + simp only [exits] at hE + rcases S with _ | ⟨a, S⟩ + · simp [SolarTV.EVM.step] at hstep + simp only [SolarTV.EVM.step, Option.some.injEq] at hstep + subst hstep + exact exits_sound o call b rest _ _ s E y hL.tail hE hx' + have h0 : ∀ v, op ≠ .push v := fun v e => hpu ⟨v, e⟩ + have h1 : ∀ i, op ≠ .dup i := fun i e => hdu ⟨i, e⟩ + have h2 : ∀ i, op ≠ .swap i := fun i e => hsw ⟨i, e⟩ + rw [exits_other h0 h1 h2 hpo] at hE + cases hn : stackNeed op with + | none => simp [hn] at hE + | some nd => + obtain ⟨n, d⟩ := nd + simp only [hn] at hE + obtain ⟨v, rfl, -⟩ := step_data hn h1 h2 hpo hstep rfl rfl + exact exits_sound o call b rest _ _ s E y ((hL.drop n).cons_none v) hE hx' + | load => + simp only [exits] at hE + obtain ⟨v, s1, hx'⟩ := exec_load_inv hx + exact exits_sound o call b rest _ _ s1 E y ((hL.drop 1).cons_none v) hE hx' + | store => + simp only [exits] at hE + obtain ⟨s1, hx'⟩ := exec_store_inv hx + exact exits_sound o call b rest _ _ s1 E y (hL.drop 2) hE hx' + | storeByte => simp [exits] at hE + | size => simp [exits] at hE + | copy => simp [exits] at hE + | hash => simp [exits] at hE + | .effect e a :: rest, L, S, s, E, y, hL, hE, hx => by + obtain ⟨r, s1, hr, hx'⟩ := exec_effect_inv hx + simp only [exits] at hE + cases r with + | none => + simp only [Option.isSome_none] at hr + rw [← hr] at hE + simp only [Bool.false_eq_true, ite_false] at hE + exact exits_sound o call b rest _ _ s1 E y (hL.drop a) hE hx' + | some v => + simp only [Option.isSome_some] at hr + rw [← hr] at hE + simp only [ite_true] at hE + exact exits_sound o call b rest _ _ s1 E y ((hL.drop a).cons_none v) hE hx' + | .jump t :: rest, L, S, s, E, y, hL, hE, hx => by + simp only [exits, Option.some.injEq] at hE + simp only [exec] at hx + split at hx + · cases hx + · simp only [Sum.inr.injEq] at hx + subst hE hx + exact ⟨L, by simp, hL⟩ + | .jumpi t :: rest, L, S, s, E, y, hL, hE, hx => by + simp only [exits] at hE + cases hE' : exits b L.tail rest with + | none => simp [hE'] at hE + | some E' => + simp only [hE', Option.map_some, Option.some.injEq] at hE + subst hE + simp only [exec] at hx + split at hx + · cases hx + · rcases S with _ | ⟨cnd, S⟩ + · cases hx + · simp only at hx + split at hx + · obtain ⟨L', h1, h2⟩ := exits_sound o call b rest L.tail S s E' y hL.tail hE' hx + exact ⟨L', List.mem_cons_of_mem _ h1, h2⟩ + · simp only [Sum.inr.injEq] at hx + subst hx + exact ⟨L.tail, by simp, hL.tail⟩ + | .pushLabel t :: rest, L, S, s, E, y, hL, hE, hx => by + simp only [exits] at hE + simp only [exec] at hx + split at hx + · cases hx + · exact exits_sound o call b rest _ _ s E y (hL.label t) hE hx + | .jumpDyn :: rest, L, S, s, E, y, hL, hE, hx => by + simp only [exits] at hE + cases hl : labAt L 0 with + | none => simp [hl] at hE + | some ts => + simp only [hl, Option.some.injEq] at hE + subst hE + rcases S with _ | ⟨x, S⟩ + · simp [exec] at hx + · simp only [exec, Sum.inr.injEq] at hx + subst hx + refine ⟨L.tail, ?_, by simpa using hL.tail⟩ + have := hL 0 ts hl x rfl + simp only [List.mem_map] + exact ⟨x.toNat, this, rfl⟩ + | .jumpiDyn :: rest, L, S, s, E, y, hL, hE, hx => by simp [exits] at hE + | .jumpTable _ :: rest, L, S, s, E, y, hL, hE, hx => by simp [exits] at hE + | .stop :: rest, L, S, s, E, y, hL, hE, hx => by simp [exec] at hx + | .ret :: rest, L, S, s, E, y, hL, hE, hx => by simp [exec] at hx + | .revert :: rest, L, S, s, E, y, hL, hE, hx => by simp [exec] at hx + | .invalid :: rest, L, S, s, E, y, hL, hE, hx => by simp [exec] at hx + +end SolidCore.Refinement.Solar.AssembleCtx diff --git a/SolidCore/Refinement/Solar/AssembleCut.lean b/SolidCore/Refinement/Solar/AssembleCut.lean new file mode 100644 index 00000000..92ce5bd1 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCut.lean @@ -0,0 +1,1349 @@ +import SolidCore.Refinement.Solar.AssembleCutSim +import SolidCore.Refinement.Solar.AssembleDyn +import SolidCore.Refinement.Solar.AssembleDynCopy +import SolidCore.Refinement.Solar.AssembleRunLoop +import SolidCore.Refinement.Solar.RunOracleSource + +/-! +# EVM IR to bytecode with GAS, at the run's own gas + +`AssembleRunLoop.withinRun_of_checkL_atGas` runs each block with gas to spare and moves it back to the +frame's own gas (`Logic.reaches_low`). GAS pushes the gas left, which no run with more gas shows, so a +block with GAS runs in segments (`AssembleLoop.exec_simC`): each segment up to a GAS with gas to spare +for it alone, moved back to the frame's gas, then GAS at the frame's own gas (`gas_back`: a run that +succeeds had the gas for it), with the gas it pushes added to the run's table (`RunTable.gases`). The +oracle of a table answers what a segment reads as every oracle of a longer table does +(`execC_agree`), so every extension of the table runs the block to the same end, which +`AssembleRun.within_of_advances` needs. + +`withinRun_of_checkC` is the per-run theorem (`RunOracle.WithinRun`) for every program the checker with +GAS (`checkC`) accepts. +-/ + +namespace SolidCore.Refinement.Solar.AssembleCut + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Final +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.RunOracle SolidCore.Refinement.Solar.AssembleRun +open SolidCore.Refinement.Solar.AssembleRunLoop +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +/-! ## Oracles that agree before a GAS read or a message -/ + +/-- Two oracles answer the same at every world with at most `ng` GAS reads and `ns` messages. -/ +def Agree (o1 o2 : Oracle) (ng ns : Nat) : Prop := + o1.keccak = o2.keccak ∧ o1.caller = o2.caller ∧ + ∀ w, gasReads w ≤ ng → sent w ≤ ns → ∀ name a, o1.env name w a = o2.env name w a + +theorem Agree.refl (o : Oracle) (ng ns : Nat) : Agree o o ng ns := + ⟨rfl, rfl, fun _ _ _ _ _ => rfl⟩ + +/-- The oracle of a table and of any extension agree at the worlds the table answers. -/ +theorem table_agree (base : Oracle) {T T2 : RunTable} (hle : T.Le T2) {ng ns : Nat} + (hg : ng ≤ T.gases.length) (hs : ns ≤ T.outs.length) : + Agree (tableOracle base T) (tableOracle base T2) ng ns := by + refine ⟨rfl, rfl, fun w hw hsw name a => ?_⟩ + have hout : T.out w = T2.out w := by + unfold RunTable.out + split + · rfl + · exact (getD_of_prefix hle.2.1 (by omega) _).symm + have hgas : gasReads w ≠ 0 → + T.gases.getD (gasReads w - 1) 0 = T2.gases.getD (gasReads w - 1) 0 := fun h => + (getD_of_prefix hle.2.2.2.2 (by omega) _).symm + simp only [tableOracle, hout] + split_ifs <;> simp_all + +/-- An effect that stops no segment answers the same under oracles that agree. -/ +theorem apply_congr {o1 o2 : Oracle} {ng ns : Nat} (hA : Agree o1 o2 ng ns) {call : Call} + {e : Effect} (he : cutEffect e = false) {args : List Word} {s : State} + (hg : gasReads s.world ≤ ng) (hs : sent s.world ≤ ns) : + Effect.apply o1 call e args s = Effect.apply o2 call e args s := by + have hw := hA.2.2 s.world hg hs + have h0 := hA.2.2 [] (by simp [gasReads]) (by simp [sent]) + obtain ⟨hk, hc, -⟩ := hA + unfold Effect.apply + split <;> simp_all [cutEffect, returndataSize, returndataByte, codeByte, immutableWord, + immutableValue] + +/-- An effect that stops no segment adds no GAS read and sends no message. -/ +theorem apply_world {o : Oracle} {call : Call} {e : Effect} (he : cutEffect e = false) + {args : List Word} {s s' : State} {r : Option Word} + (h : Effect.apply o call e args s = some (r, s')) : + gasReads s'.world = gasReads s.world ∧ sent s'.world = sent s.world := by + unfold Effect.apply at h + split at h <;> (try split at h) <;> simp_all [cutEffect] + all_goals (obtain ⟨-, rfl⟩ := h; simp) + +/-- The state a segment ends in, when it does not halt. -/ +def endState : CRes → Option State + | .cut _ _ _ s' => some s' + | .done (.inr (_, _, s')) => some s' + | .done (.inl _) => none + +/-- A segment adds no GAS read and sends no message, and stops, if at all, inside its instructions. -/ +def Kept (r : CRes) (n : Nat) (s : State) : Prop := + (∀ s', endState r = some s' → + gasReads s'.world = gasReads s.world ∧ sent s'.world = sent s.world) ∧ + ∀ i rest S' s', r = .cut i rest S' s' → rest.length < n + +theorem Kept.trans {r : CRes} {n n' : Nat} {s s1 : State} (h : Kept r n s1) + (h1 : gasReads s1.world = gasReads s.world ∧ sent s1.world = sent s.world) (hn : n ≤ n') : + Kept r n' s := + ⟨fun s' hs => ⟨(h.1 s' hs).1.trans h1.1, (h.1 s' hs).2.trans h1.2⟩, + fun i rest S' s' hr => Nat.lt_of_lt_of_le (h.2 i rest S' s' hr) hn⟩ + +theorem Kept.halt {r : (Halt × State)} {n : Nat} {s : State} : Kept (.done (.inl r)) n s := + ⟨fun s' h => by simp [endState] at h, fun _ _ _ _ h => by cases h⟩ + +theorem Kept.next {t : Nat} {S : List Word} {n : Nat} {s : State} : Kept (.done (.inr (t, S, s))) n s := + ⟨fun s' h => by simp [endState] at h; subst h; exact ⟨by trivial, rfl⟩, fun _ _ _ _ h => by cases h⟩ + +/-- **A segment runs the same under oracles that agree**, and adds no GAS read or message. -/ +theorem execC_agree {o1 o2 : Oracle} {ng ns : Nat} (hA : Agree o1 o2 ng ns) (call : Call) (b : Nat) : + ∀ (is : List Assemble.Instr) (S : List Word) (s : State), gasReads s.world ≤ ng → + sent s.world ≤ ns → + execC o1 call b is S s = execC o2 call b is S s ∧ Kept (execC o1 call b is S s) is.length s + | [], _, s, _, _ => ⟨rfl, Kept.next⟩ + | .op op :: rest, S, s, hg, hs => by + by_cases hcut : cutOp op = true + · simp only [execC, hcut, ite_true] + exact ⟨by trivial, fun s' h => by simp [endState] at h; subst h; exact ⟨rfl, rfl⟩, + fun _ _ _ _ h => by cases h; simp⟩ + have hcut' : cutOp op = false := by simpa using hcut + have hc : SolarTV.EVM.Program.context o1 call s = SolarTV.EVM.Program.context o2 call s := by + simp [SolarTV.EVM.Program.context, hA.2.2 s.world hg hs] + cases h : SolarTV.EVM.Program.stepOp (SolarTV.EVM.Program.context o2 call s) op S s.memory with + | error _ => + simp only [execC, hc, h, hcut', Bool.false_eq_true, ite_false] + exact ⟨by trivial, Kept.halt⟩ + | ok r => + obtain ⟨S', m⟩ := r + simp only [execC, hc, h, hcut', Bool.false_eq_true, ite_false] + obtain ⟨h1, h2⟩ := execC_agree hA call b rest S' { s with memory := m } hg hs + exact ⟨h1, h2.trans ⟨rfl, rfl⟩ (by simp)⟩ + | .effect e a :: rest, S, s, hg, hs => by + by_cases hc : cutEffect e = true + · simp only [execC, hc, ite_true] + exact ⟨by trivial, fun s' h => by simp [endState] at h; subst h; exact ⟨rfl, rfl⟩, + fun _ _ _ _ h => by cases h; simp⟩ + · have he : cutEffect e = false := by simpa using hc + by_cases hl : S.length < a + · simp only [execC, hc, hl, Bool.false_eq_true, ite_false, ite_true] + exact ⟨by trivial, Kept.halt⟩ + · cases happ : Effect.apply o2 call e (S.take a) s with + | none => + simp only [execC, hc, hl, Bool.false_eq_true, ite_false, apply_congr hA he hg hs, happ] + exact ⟨by trivial, Kept.halt⟩ + | some r => + obtain ⟨res, s1⟩ := r + have hw := apply_world he happ + simp only [execC, hc, hl, Bool.false_eq_true, ite_false, apply_congr hA he hg hs, happ] + split_ifs + · exact ⟨by trivial, Kept.halt⟩ + · obtain ⟨h1, h2⟩ := execC_agree hA call b rest _ s1 (by omega) (by omega) + exact ⟨h1, h2.trans hw (by simp)⟩ + | .jump t :: rest, S, s, hg, hs => by + simp only [execC] + split_ifs + · exact ⟨by trivial, Kept.halt⟩ + · exact ⟨by trivial, Kept.next⟩ + | .jumpi t :: rest, S, s, hg, hs => by + cases S with + | nil => + simp only [execC] + split_ifs <;> exact ⟨by trivial, Kept.halt⟩ + | cons x S => + simp only [execC] + split_ifs + · exact ⟨by trivial, Kept.halt⟩ + · obtain ⟨h1, h2⟩ := execC_agree hA call b rest S s hg hs + exact ⟨h1, h2.trans ⟨rfl, rfl⟩ (by simp)⟩ + · exact ⟨by trivial, Kept.next⟩ + | .pushLabel t :: rest, S, s, hg, hs => by + simp only [execC] + split_ifs + · exact ⟨by trivial, Kept.halt⟩ + · obtain ⟨h1, h2⟩ := execC_agree hA call b rest _ s hg hs + exact ⟨h1, h2.trans ⟨rfl, rfl⟩ (by simp)⟩ + | .jumpDyn :: rest, S, s, hg, hs => by + cases S with + | nil => exact ⟨by trivial, Kept.halt⟩ + | cons x S => exact ⟨by trivial, Kept.next⟩ + | .jumpiDyn :: rest, S, s, hg, hs => by + match S with + | [] => exact ⟨by trivial, Kept.halt⟩ + | [_] => exact ⟨by trivial, Kept.halt⟩ + | x :: y :: S => + simp only [execC] + split_ifs + · obtain ⟨h1, h2⟩ := execC_agree hA call b rest S s hg hs + exact ⟨h1, h2.trans ⟨rfl, rfl⟩ (by simp)⟩ + · exact ⟨by trivial, Kept.next⟩ + | .jumpTable ts :: rest, S, s, hg, hs => by + cases S with + | nil => exact ⟨by trivial, Kept.halt⟩ + | cons x S => + cases h : ts[x.toNat]? with + | none => simp only [execC, h]; exact ⟨by trivial, Kept.halt⟩ + | some t => simp only [execC, h]; exact ⟨by trivial, Kept.next⟩ + | .stop :: rest, S, s, _, _ => ⟨rfl, Kept.halt⟩ + | .ret :: rest, S, s, _, _ => ⟨rfl, fun s' h => by simp [endState, execC] at h; subst h; exact ⟨rfl, rfl⟩, + fun _ _ _ _ h => by simp only [execC, CRes.cut.injEq] at h; obtain ⟨-, rfl, -, -⟩ := h; simp⟩ + | .revert :: rest, S, s, _, _ => ⟨rfl, fun s' h => by simp [endState, execC] at h; subst h; exact ⟨rfl, rfl⟩, + fun _ _ _ _ h => by simp only [execC, CRes.cut.injEq] at h; obtain ⟨-, rfl, -, -⟩ := h; simp⟩ + | .invalid :: rest, S, s, _, _ => ⟨rfl, Kept.halt⟩ + +/-! ## GAS at the frame's own gas -/ + +/-- **GAS in a run that succeeds**: the frame had the gas for it, and the run goes on from the frame +after it, with the gas left after its price pushed. -/ +theorem gas_back {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {T : List Word} + {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} {rd : ByteArray} + {evm : Evm .fusaka Nat} (hat : At code msg pc T M g st ss rd evm) (hlt : pc < code.size) + (hbyte : code[pc] = 0x5a) (hstack : T.length < STACK_LIMIT) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + 2 ≤ g ∧ ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) (BitVec.ofNat 256 (g - 2) :: T) M (g - 2) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + by_cases hg : 2 ≤ g + · obtain ⟨m, hr, hm⟩ := Logic.gas_rule (fork := .fusaka) hlt hbyte hg hstack evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc T M g st ss rd) (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, -, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .gas := by + rw [hbyte] + exact ofByte_of_decode rfl (Fork.frontier_le _) + rw [step_of_instruction hlt decoded rfl] + simp [readFrame, chargeGas, GasMeter.charge, hgas, OPCODE_GAS, BASE, show g < 2 by omega, bind, Except.bind] + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rw [hf.2.1] at hok + cases hok + +/-! ## The oracle of a run -/ + +/-- The oracle of a run of code that sends no message: `base` with the gas each GAS read pushed, in +order (the table's `gases`); every other read is `base`'s. -/ +def gasOracle (base : Oracle) (T : RunTable) : Oracle := + { base with + env := fun name w args => + if name = "gas" ∧ args = [] ∧ gasReads w ≠ 0 then + BitVec.ofNat 256 (T.gases.getD (gasReads w - 1) 0) + else base.env name w args } + +/-- The `k`-th GAS read pushes the table's `k`-th gas. -/ +theorem gasOracle_gas (base : Oracle) (T : RunTable) (w : List Event) : + (gasOracle base T).env "gas" (w ++ [.read "gas"]) [] = + BitVec.ofNat 256 (T.gases.getD (gasReads w) 0) := by + simp [gasOracle] + +/-- The gas oracle of a table and of any extension agree at the worlds the table answers. -/ +theorem gas_agree (base : Oracle) {T T2 : RunTable} (hle : T.Le T2) {ng ns : Nat} + (hg : ng ≤ T.gases.length) : Agree (gasOracle base T) (gasOracle base T2) ng ns := by + refine ⟨rfl, rfl, fun w hw _ name a => ?_⟩ + have hgas : gasReads w ≠ 0 → + T.gases.getD (gasReads w - 1) 0 = T2.gases.getD (gasReads w - 1) 0 := fun h => + (getD_of_prefix hle.2.2.2.2 (by omega) _).symm + simp only [gasOracle] + split_ifs with h + · rw [hgas h.2.2] + · rfl + +/-- The gas oracle keeps every read but GAS: the code sizes, the return data and the results and +storage of calls stay the open world's. -/ +theorem callsAgree_gas {o : Oracle} {W : World} (T : RunTable) (h : CallsAgree o W) : + CallsAgree (gasOracle o T) W := by + have henv : ∀ n w a, n ≠ "gas" → (gasOracle o T).env n w a = o.env n w a := by + intro n w a hn + simp [gasOracle, hn] + have hcodes : ∀ w code, CodesAgree (gasOracle o T) w code ↔ CodesAgree o w code := by + intro w code + unfold CodesAgree + simp only [henv "extcodesize" _ _ (by decide)] + have hsize : ∀ w, returndataSize (gasOracle o T) w = returndataSize o w := fun w => + henv "returndatasize" w [] (by decide) + have hbyte : ∀ w j, returndataByte (gasOracle o T) w j = returndataByte o w j := by + intro w j + unfold returndataByte + rw [henv "returndata" w _ (by decide)] + refine ⟨fun w hw => (hcodes _ _).2 (h.codes w hw), ?_, h.static⟩ + intro hh world req a ha w k s i st tr hl hm hst hcod + obtain ⟨h1, h2, h3⟩ := h.calls hh world req a ha w k s i st tr hl hm hst ((hcodes _ _).1 hcod) + refine ⟨h1, h2, fun rest hr => ?_⟩ + obtain ⟨r1, r2, r3⟩ := h3 rest hr + exact ⟨by rw [hsize]; exact r1, fun j hj hj' => by rw [hbyte]; exact r2 j hj hj', + (hcodes _ _).2 r3⟩ + +/-- What the oracle of a run answers that the run does not decide: every call fails, as the +open world `Witness.failWorld` answers, with EthLib's caller, hash and environment. -/ +def base0 : Oracle := envOracle (ethOracle Witness.failOracle) + +/-- The oracle of a run's table. -/ +abbrev O (T : RunTable) : Oracle := gasOracle base0 T + +theorem O_ok (c : Cert) (T : RunTable) : CertOk c (O T) := by + refine ⟨fun _ => ethOracle_ok Witness.failOracle, fun _ => ?_⟩ + intro name byte w he world + have hn : name ≠ "gas" := by + unfold envRead at he + rintro rfl + simp at he + simp only [O, gasOracle, hn, false_and, ite_false] + exact envOracle_ok _ name byte w he world + +/-- The oracle of every table agrees with an open world, so the composition with the source's +specification (`SourceOracle.holds_of_runs`) applies to it. -/ +theorem O_agree (T : RunTable) : ∃ W : World, W.Open ∧ CallsAgree (O T) W := + ⟨Witness.failWorld, Witness.failWorld_open, callsAgree_gas T (callsAgree_envEth Witness.failAgree)⟩ + +/-- Under every extension of the table, a block runs as its segment under the table does, then +from the instruction the segment stopped at. -/ +theorem exec_O {T T'' : RunTable} (hle : T.Le T'') {call : Call} {b : Nat} + {is : List Assemble.Instr} {S : List Word} {s : State} + (hg : gasReads s.world ≤ T.gases.length) (hs : sent s.world = 0) : + SolarTV.EVM.Program.exec (O T'') call b is S s = match execC (O T) call b is S s with + | .done r => r + | .cut i rest S' s' => SolarTV.EVM.Program.exec (O T'') call b (i :: rest) S' s' := by + rw [exec_eq_execC, ← (execC_agree (gas_agree base0 hle (ng := T.gases.length) (ns := 0) le_rfl) + call b is S s hg (by omega)).1] + rfl + +/-- GAS under the oracle of a table whose next gas is `v`. -/ +theorem exec_gas {T : RunTable} {call : Call} {b : Nat} {rest : List Assemble.Instr} + {S : List Word} {s : State} {v : Nat} (hT : T.gases.getD (gasReads s.world) 0 = v) + (hS : S.length < 1024) : + SolarTV.EVM.Program.exec (O T) call b (.effect .gas 0 :: rest) S s = + SolarTV.EVM.Program.exec (O T) call b rest (BitVec.ofNat 256 v :: S) + { s with world := s.world ++ [.read "gas"] } := by + have happ : Effect.apply (O T) call .gas [] s = + some (some (BitVec.ofNat 256 v), { s with world := s.world ++ [.read "gas"] }) := by + simp only [Effect.apply] + rw [gasOracle_gas, hT] + simp [SolarTV.EVM.Program.exec, happ, show ¬ 1024 < S.length + 1 by omega] + +theorem lowerInstrs_gas (p : Assemble.Program) (c : Cert) (b : Nat) (rest : List Assemble.Instr) : + lowerInstrs p c b (.effect .gas 0 :: rest) = .op 0x5a :: lowerInstrs p c b rest := by + simp [lowerInstrs, turnedElse, dropped, lowerInstr] + +theorem blockOkC_gas {p : Assemble.Program} {c : Cert} {mx : List Nat} {b h : Nat} + {known : Known} {ty : List Ty} {k : Nat} {rest : List Assemble.Instr} + (hok : blockOkC p c mx b h known ty k (.effect .gas 0 :: rest) = true) : + 1 ≤ k ∧ blockOkC p c mx b (h + 1) [] (some false :: ty) (k - 1) rest = true := by + simpa [blockOkC, turnedElse, dropped, isGasI] using hok + +theorem isLoadI_eq {i : Assemble.Instr} (h : isLoadI i = true) : i = .op .load := by + unfold isLoadI at h + split at h + · rfl + · cases h + +theorem isStoreI_eq {i : Assemble.Instr} (h : isStoreI i = true) : i = .op .store := by + unfold isStoreI at h + split at h + · rfl + · cases h + +theorem lowerInstrs_load (p : Assemble.Program) (c : Cert) (b : Nat) (rest : List Assemble.Instr) : + lowerInstrs p c b (.op .load :: rest) = .op 0x51 :: lowerInstrs p c b rest := by + simp [lowerInstrs, turnedElse, dropped, lowerInstr] + +theorem lowerInstrs_store (p : Assemble.Program) (c : Cert) (b : Nat) (rest : List Assemble.Instr) : + lowerInstrs p c b (.op .store :: rest) = .op 0x52 :: lowerInstrs p c b rest := by + simp [lowerInstrs, turnedElse, dropped, lowerInstr] + +theorem blockOkC_load {p : Assemble.Program} {c : Cert} {mx : List Nat} {b h : Nat} + {known : Known} {ty : List Ty} {k : Nat} {rest : List Assemble.Instr} + (hok : blockOkC p c mx b h known ty k (.op .load :: rest) = true) : + 1 ≤ k ∧ 1 ≤ h ∧ isData ty 1 = true ∧ 2 ^ 140 ≤ c.top ∧ + blockOkC p c mx b h [] (some false :: ty.drop 1) (k - 1) rest = true := by + simp only [blockOkC, turnedElse, dropped, isGasI, isLoadI, Bool.and_eq_true, decide_eq_true_eq, + Bool.false_eq_true, ite_false, ite_true] at hok + exact ⟨hok.1.1.1.1, hok.1.1.1.2, hok.1.1.2, hok.1.2, hok.2⟩ + +theorem blockOkC_store {p : Assemble.Program} {c : Cert} {mx : List Nat} {b h : Nat} + {known : Known} {ty : List Ty} {k : Nat} {rest : List Assemble.Instr} + (hok : blockOkC p c mx b h known ty k (.op .store :: rest) = true) : + 1 ≤ k ∧ 2 ≤ h ∧ isData ty 2 = true ∧ 2 ^ 140 ≤ c.top ∧ + blockOkC p c mx b (h - 2) [] (ty.drop 2) (k - 1) rest = true := by + simp only [blockOkC, turnedElse, dropped, isGasI, isLoadI, isStoreI, Bool.and_eq_true, + decide_eq_true_eq, Bool.false_eq_true, ite_false, ite_true] at hok + exact ⟨hok.1.1.1.1, hok.1.1.1.2, hok.1.1.2, hok.1.2, hok.2⟩ + +theorem isRetI_eq {i : Assemble.Instr} (h : isRetI i = true) : i = .ret := by + unfold isRetI at h + split at h + · rfl + · cases h + +theorem isRevI_eq {i : Assemble.Instr} (h : isRevI i = true) : i = .revert := by + unfold isRevI at h + split at h + · rfl + · cases h + +theorem lowerInstrs_ret (p : Assemble.Program) (c : Cert) (b : Nat) (rest : List Assemble.Instr) : + lowerInstrs p c b (.ret :: rest) = .op 0xf3 :: lowerInstrs p c b rest := by + simp [lowerInstrs, turnedElse, dropped, lowerInstr] + +theorem lowerInstrs_revert (p : Assemble.Program) (c : Cert) (b : Nat) (rest : List Assemble.Instr) : + lowerInstrs p c b (.revert :: rest) = .op 0xfd :: lowerInstrs p c b rest := by + simp [lowerInstrs, turnedElse, dropped, lowerInstr] + +theorem blockOkC_ret {p : Assemble.Program} {c : Cert} {mx : List Nat} {b h : Nat} + {known : Known} {ty : List Ty} {k : Nat} {rest : List Assemble.Instr} + (hok : blockOkC p c mx b h known ty k (.ret :: rest) = true) : 2 ≤ h ∧ isData ty 2 = true := by + simpa [blockOkC, turnedElse, dropped, isGasI, isLoadI, isStoreI, isRetI] using hok + +theorem blockOkC_revert {p : Assemble.Program} {c : Cert} {mx : List Nat} {b h : Nat} + {known : Known} {ty : List Ty} {k : Nat} {rest : List Assemble.Instr} + (hok : blockOkC p c mx b h known ty k (.revert :: rest) = true) : + 2 ≤ h ∧ isData ty 2 = true := by + simpa [blockOkC, turnedElse, dropped, isGasI, isLoadI, isStoreI, isRetI, isRevI] using hok + +theorem isKecI_eq {i : Assemble.Instr} (h : isKecI i = true) : i = .effect .keccak256 2 := by + unfold isKecI at h + split at h + · rfl + · cases h + +theorem lowerInstrs_kec (p : Assemble.Program) (c : Cert) (b : Nat) (rest : List Assemble.Instr) : + lowerInstrs p c b (.effect .keccak256 2 :: rest) = .op 0x20 :: lowerInstrs p c b rest := by + simp [lowerInstrs, turnedElse, dropped, lowerInstr] + +theorem blockOkC_kec {p : Assemble.Program} {c : Cert} {mx : List Nat} {b h : Nat} + {known : Known} {ty : List Ty} {k : Nat} {rest : List Assemble.Instr} + (hok : blockOkC p c mx b h known ty k (.effect .keccak256 2 :: rest) = true) : + c.env = true ∧ 1 ≤ k ∧ 2 ≤ h ∧ isData ty 2 = true ∧ 2 ^ 140 ≤ c.top ∧ + blockOkC p c mx b (h - 1) [] (some false :: ty.drop 2) (k - 1) rest = true := by + simp only [blockOkC, turnedElse, dropped, isGasI, isLoadI, isStoreI, isRetI, isRevI, isKecI, + Bool.or_false, Bool.and_eq_true, decide_eq_true_eq, Bool.false_eq_true, ite_false, + ite_true] at hok + exact ⟨hok.1.1.1.1.1, hok.1.1.1.1.2, hok.1.1.1.2, hok.1.1.2, hok.1.2, hok.2⟩ + +theorem isLogI_eq {i : Assemble.Instr} (h : isLogI i = true) : + ∃ n, n ≤ 4 ∧ i = .effect (.log n) (n + 2) := by + unfold isLogI at h + split at h + · simp only [Bool.and_eq_true, decide_eq_true_eq] at h + obtain ⟨h1, rfl⟩ := h + exact ⟨_, h1, rfl⟩ + · cases h + +theorem lowerInstrs_log (p : Assemble.Program) (c : Cert) (b : Nat) {n : Nat} (hn : n ≤ 4) + (rest : List Assemble.Instr) : + lowerInstrs p c b (.effect (.log n) (n + 2) :: rest) = + .op (0xa0 + n) :: lowerInstrs p c b rest := by + simp [lowerInstrs, turnedElse, dropped, lowerInstr, hn] + +theorem blockOkC_log {p : Assemble.Program} {c : Cert} {mx : List Nat} {b h n : Nat} (hn : n ≤ 4) + {known : Known} {ty : List Ty} {k : Nat} {rest : List Assemble.Instr} + (hok : blockOkC p c mx b h known ty k (.effect (.log n) (n + 2) :: rest) = true) : + 1 ≤ k ∧ n + 2 ≤ h ∧ isData ty (n + 2) = true ∧ 2 ^ 140 ≤ c.top ∧ + blockOkC p c mx b (h - (n + 2)) [] (ty.drop (n + 2)) (k - 1) rest = true := by + simp only [blockOkC, turnedElse, dropped, isGasI, isLoadI, isStoreI, isRetI, isRevI, isKecI, + isLogI, hn, decide_true, Bool.true_and, Bool.or_false, Bool.and_eq_true, decide_eq_true_eq, + Bool.false_eq_true, ite_false, ite_true] at hok + exact ⟨hok.1.1.1.1, hok.1.1.1.2, hok.1.1.2, hok.1.2, hok.2⟩ + +theorem gasReads_log (w : List Event) (t : List Word) (d : List SolarTV.Memory.Byte) : + gasReads (w ++ [.log t d]) = gasReads w := by + simp [gasReads, Event.readsGas] + +theorem sent_log (w : List Event) (t : List Word) (d : List SolarTV.Memory.Byte) : + sent (w ++ [.log t d]) = sent w := by + simp [sent, Event.sends] + +theorem isCdcI_eq {i : Assemble.Instr} (h : isCdcI i = true) : i = .effect .calldatacopy 3 := by + unfold isCdcI at h + split at h + · rfl + · cases h + +theorem lowerInstrs_cdc (p : Assemble.Program) (c : Cert) (b : Nat) (rest : List Assemble.Instr) : + lowerInstrs p c b (.effect .calldatacopy 3 :: rest) = .op 0x37 :: lowerInstrs p c b rest := by + simp [lowerInstrs, turnedElse, dropped, lowerInstr] + +theorem blockOkC_cdc {p : Assemble.Program} {c : Cert} {mx : List Nat} {b h : Nat} + {known : Known} {ty : List Ty} {k : Nat} {rest : List Assemble.Instr} + (hok : blockOkC p c mx b h known ty k (.effect .calldatacopy 3 :: rest) = true) : + 1 ≤ k ∧ 3 ≤ h ∧ isData ty 3 = true ∧ 2 ^ 140 ≤ c.top ∧ + blockOkC p c mx b (h - 3) [] (ty.drop 3) (k - 1) rest = true := by + simp only [blockOkC, turnedElse, dropped, isGasI, isLoadI, isStoreI, isRetI, isRevI, isKecI, + isLogI, isCdcI, Bool.or_false, Bool.and_eq_true, decide_eq_true_eq, Bool.false_eq_true, + ite_false, ite_true] at hok + exact ⟨hok.1.1.1.1, hok.1.1.1.2, hok.1.1.2, hok.1.2, hok.2⟩ + +theorem isScI_eq {i : Assemble.Instr} (h : isScI i = true) : i = .effect (.call .staticcall) 6 := by + unfold isScI at h + split at h + · rfl + · cases h + +/-- The checker cuts at a STATICCALL only in a program whose certificate says it makes calls. -/ +theorem blockOkC_sc {p : Assemble.Program} {c : Cert} {mx : List Nat} {b h : Nat} + {known : Known} {ty : List Ty} {k : Nat} {rest : List Assemble.Instr} + (hok : blockOkC p c mx b h known ty k (.effect (.call .staticcall) 6 :: rest) = true) : + c.calls = true ∧ 1 ≤ k ∧ 6 ≤ h ∧ isData ty 6 = true ∧ 2 ^ 140 ≤ c.top ∧ + blockOkC p c mx b (h - 5) [] (some false :: ty.drop 6) (k - 1) rest = true := by + simp only [blockOkC, turnedElse, dropped, isGasI, isLoadI, isStoreI, isRetI, isRevI, isKecI, + isLogI, isCdcI, isScI, Bool.or_false, Bool.and_eq_true, decide_eq_true_eq, Bool.false_eq_true, + ite_false, ite_true] at hok + exact ⟨hok.1.1.1.1.1.1, hok.1.1.1.1.2, hok.1.1.1.2, hok.1.1.2, hok.1.2, hok.2⟩ + +theorem isRdsI_eq {i : Assemble.Instr} (h : isRdsI i = true) : i = .effect .returndatasize 0 := by + unfold isRdsI at h + split at h + · rfl + · cases h + +/-- The checker cuts at a RETURNDATASIZE only in a program whose certificate says it makes calls. -/ +theorem blockOkC_rds {p : Assemble.Program} {c : Cert} {mx : List Nat} {b h : Nat} + {known : Known} {ty : List Ty} {k : Nat} {rest : List Assemble.Instr} + (hok : blockOkC p c mx b h known ty k (.effect .returndatasize 0 :: rest) = true) : + c.calls = true ∧ 1 ≤ k ∧ blockOkC p c mx b (h + 1) [] (some false :: ty) (k - 1) rest = true := by + simp only [blockOkC, turnedElse, dropped, isGasI, isLoadI, isStoreI, isRetI, isRevI, isKecI, + isLogI, isCdcI, isScI, isRdsI, Bool.or_false, Bool.and_eq_true, decide_eq_true_eq, + Bool.false_eq_true, ite_false, ite_true] at hok + exact ⟨hok.1.1, hok.1.2, hok.2⟩ + +theorem isRdcI_eq {i : Assemble.Instr} (h : isRdcI i = true) : i = .effect .returndatacopy 3 := by + unfold isRdcI at h + split at h + · rfl + · cases h + +/-- The checker cuts at a RETURNDATACOPY only in a program whose certificate says it makes calls. -/ +theorem blockOkC_rdc {p : Assemble.Program} {c : Cert} {mx : List Nat} {b h : Nat} + {known : Known} {ty : List Ty} {k : Nat} {rest : List Assemble.Instr} + (hok : blockOkC p c mx b h known ty k (.effect .returndatacopy 3 :: rest) = true) : + c.calls = true ∧ 1 ≤ k ∧ 3 ≤ h ∧ isData ty 3 = true ∧ 2 ^ 140 ≤ c.top ∧ + blockOkC p c mx b (h - 3) [] (ty.drop 3) (k - 1) rest = true := by + simp only [blockOkC, turnedElse, dropped, isGasI, isLoadI, isStoreI, isRetI, isRevI, isKecI, + isLogI, isCdcI, isScI, isRdsI, isRdcI, Bool.or_false, Bool.and_eq_true, decide_eq_true_eq, + Bool.false_eq_true, ite_false, ite_true] at hok + exact ⟨hok.1.1.1.1.1, hok.1.1.1.1.2, hok.1.1.1.2, hok.1.1.2, hok.1.2, hok.2⟩ + +/-- A program that creates makes no STATICCALL the checker accepts. (It may read the return data of +its CALLs and CREATE2s: RETURNDATASIZE and RETURNDATACOPY, which `AssembleCreateSegF.segF` reads +back from the run's tables.) -/ +theorem blockOkC_noSc_creates {p : Assemble.Program} {c : Cert} {mx : List Nat} {b h : Nat} + {known : Known} {ty : List Ty} {k : Nat} {i : Assemble.Instr} {rest : List Assemble.Instr} + (hi : isScI i = true) + (hok : blockOkC p c mx b h known ty k (i :: rest) = true) : c.creates = false := by + obtain rfl := isScI_eq hi + simp only [blockOkC, turnedElse, dropped, isGasI, isLoadI, isStoreI, isRetI, isRevI, isKecI, + isLogI, isCdcI, isScI, Bool.or_false, Bool.and_eq_true, decide_eq_true_eq, Bool.false_eq_true, + ite_false, ite_true] at hok + simpa using hok.1.1.1.1.1.2 + +theorem isCallI_eq {i : Assemble.Instr} (h : isCallI i = true) : i = .effect (.call .call) 7 := by + unfold isCallI at h + split at h + · rfl + · cases h + +theorem isC2I_eq {i : Assemble.Instr} (h : isC2I i = true) : i = .effect .create2 4 := by + unfold isC2I at h + split at h + · rfl + · cases h + +theorem isCcI_eq {i : Assemble.Instr} (h : isCcI i = true) : i = .effect .codecopy 3 := by + unfold isCcI at h + split at h + · rfl + · cases h + +/-- The checker cuts at a CALL only in a program whose certificate says it makes calls and +creates. -/ +theorem blockOkC_call {p : Assemble.Program} {c : Cert} {mx : List Nat} {b h : Nat} + {known : Known} {ty : List Ty} {k : Nat} {rest : List Assemble.Instr} + (hok : blockOkC p c mx b h known ty k (.effect (.call .call) 7 :: rest) = true) : + c.calls = true ∧ c.creates = true ∧ 1 ≤ k ∧ 7 ≤ h ∧ isData ty 7 = true ∧ 2 ^ 140 ≤ c.top ∧ + blockOkC p c mx b (h - 6) [] (some false :: ty.drop 7) (k - 1) rest = true := by + simp only [blockOkC, turnedElse, dropped, isGasI, isLoadI, isStoreI, isRetI, isRevI, isKecI, + isLogI, isCdcI, isScI, isRdsI, isRdcI, isCallI, Bool.or_false, Bool.and_eq_true, + decide_eq_true_eq, Bool.false_eq_true, ite_false, ite_true] at hok + exact ⟨hok.1.1.1.1.1.1, hok.1.1.1.1.1.2, hok.1.1.1.1.2, hok.1.1.1.2, hok.1.1.2, hok.1.2, hok.2⟩ + +/-- The checker cuts at a CREATE2 only in a program whose certificate says it makes calls and +creates. -/ +theorem blockOkC_c2 {p : Assemble.Program} {c : Cert} {mx : List Nat} {b h : Nat} + {known : Known} {ty : List Ty} {k : Nat} {rest : List Assemble.Instr} + (hok : blockOkC p c mx b h known ty k (.effect .create2 4 :: rest) = true) : + c.calls = true ∧ c.creates = true ∧ 1 ≤ k ∧ 4 ≤ h ∧ isData ty 4 = true ∧ 2 ^ 140 ≤ c.top ∧ + blockOkC p c mx b (h - 3) [] (some false :: ty.drop 4) (k - 1) rest = true := by + simp only [blockOkC, turnedElse, dropped, isGasI, isLoadI, isStoreI, isRetI, isRevI, isKecI, + isLogI, isCdcI, isScI, isRdsI, isRdcI, isCallI, isC2I, Bool.or_false, Bool.and_eq_true, + decide_eq_true_eq, Bool.false_eq_true, ite_false, ite_true] at hok + exact ⟨hok.1.1.1.1.1.1, hok.1.1.1.1.1.2, hok.1.1.1.1.2, hok.1.1.1.2, hok.1.1.2, hok.1.2, hok.2⟩ + +/-- The checker cuts at a CODECOPY only in a program whose certificate says it makes calls and +creates, and only with its code offset known, below 2 ^ 32. -/ +theorem blockOkC_cc {p : Assemble.Program} {c : Cert} {mx : List Nat} {b h : Nat} + {known : Known} {ty : List Ty} {k : Nat} {rest : List Assemble.Instr} + (hok : blockOkC p c mx b h known ty k (.effect .codecopy 3 :: rest) = true) : + c.calls = true ∧ c.creates = true ∧ (∃ x off t, known = x :: some off :: t ∧ off.toNat < 2 ^ 32) ∧ + 1 ≤ k ∧ 3 ≤ h ∧ isData ty 3 = true ∧ 2 ^ 140 ≤ c.top ∧ + blockOkC p c mx b (h - 3) [] (ty.drop 3) (k - 1) rest = true := by + rcases known with _ | ⟨x, _ | ⟨_ | off, t⟩⟩ <;> + simp only [blockOkC, turnedElse, dropped, isGasI, isLoadI, isStoreI, isRetI, isRevI, isKecI, + isLogI, isCdcI, isScI, isRdsI, isRdcI, isCallI, isC2I, isCcI, Bool.or_false, Bool.and_eq_true, + decide_eq_true_eq, Bool.false_eq_true, ite_false, ite_true] at hok + exact ⟨hok.1.1.1.1.1.1.1, hok.1.1.1.1.1.1.2, ⟨x, off, t, rfl, hok.1.1.1.1.1.2⟩, hok.1.1.1.1.2, + hok.1.1.1.2, hok.1.1.2, hok.1.2, hok.2⟩ + +/-! ## A block, segment by segment -/ + +/-- `AssembleRunLoop.Ent` with any return data in the frame: the relation at a block entry once +the frame may hold the output of a message it sent. -/ +def EntC (p : Assemble.Program) (c : Cert) (mx : List Nat) (code : ByteArray) (msg : Message .fusaka) + (ss0 : Substate) (x : Nat × List Word × Machine.State) (evm : Evm .fusaka Nat) : Prop := + ∃ (Tw : List Word) (pc : Nat) (M : ByteArray) (st : State.TransactionState) (ss : Substate) + (rd : ByteArray), + x.1 ≤ p.blocks.length ∧ + (x.1 < p.blocks.length → c.need x.1 ≤ x.2.1.length ∧ x.2.1.length ≤ maxH mx x.1) ∧ + SR c (c.entry x.1) x.2.1 Tw ∧ + Seg (bytesOf code) c.offset pc (lowerFrom p c x.1 (p.blocks.drop x.1)) code.size ∧ + M.size ≤ c.top ∧ MemRel x.2.2.memory M ∧ Rel msg ss0 st ss x.2.2 ∧ + At code msg pc Tw M evm.gas st ss rd evm + +/-- `AssembleRunLoop.at_of_addGas` with any return data. -/ +theorem at_of_addGasR {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {T : List Word} + {M : ByteArray} {G : Nat} {st : State.TransactionState} {ss : Substate} {rd : ByteArray} {K : Nat} + {m : Evm .fusaka Nat} (h : At code msg pc T M G st ss rd (addGas K m)) : + At code msg pc T M m.gas st ss rd m ∧ m.gas + K = G := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11, h12, h13⟩ := h + exact ⟨⟨h1, h2, h3, h4, h5, h6, rfl, h8, h9, h10, h11, h12, h13⟩, by simpa using h7⟩ + +/-- **The rest of a block from an instruction, read back from a run that succeeds**: the segments +up to each GAS with gas to spare, moved back to the frame's gas, and each GAS at the frame's gas, +its gas added to the table. Every extension of the table it ends with runs the rest of the block to +the same end: a halt the frame shows, or the next block, related to a frame the run goes on from. -/ +theorem seg {p : Assemble.Program} {c : Cert} {mx : List Nat} {code : ByteArray} + (G : GlobT p c code) (hnc : c.calls = false) {call : Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : msg.txEnv = Target.txEnv) + {b : Nat} (hb : b < p.blocks.length) {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {fin : Evm .fusaka Nat} (hok : fin.error = none) {G0 : Nat} (hG0 : G0 < 2 ^ 256) + {rd : ByteArray} : + ∀ (n : Nat) (is : List Assemble.Instr) (h : Nat) (known : Known) (ty : List Ty) (k : Nat) + (S Tw : List Word) (s : State) (pc : Nat) (M : ByteArray) (g : Nat) + (st : State.TransactionState) (ss : Substate) (T : RunTable) (evm : Evm .fusaka Nat) + (within : GasMeter.gasHeld evm.gas ≤ bound), + is.length < n → blockOkC p c mx b h known ty k is = true → h ≤ S.length → + S.length + c.need b ≤ h + maxH mx b → KR known S → SR c ty S Tw → + Seg (bytesOf code) c.offset pc + (lowerInstrs p c b is ++ lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) code.size → + S.length + k ≤ 1000 → M.size ≤ c.top → MemRel s.memory M → Rel msg ss0 st ss s → + At code msg pc Tw M g st ss rd evm → T.gases.length = gasReads s.world → + sent s.world = 0 → MemBudget G0 M g → + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + ∃ T' r, T.Le T' ∧ + (∀ T'', T'.Le T'' → SolarTV.EVM.Program.exec (O T'') call b is S s = r) ∧ + (∀ res, r = .inl res → PostL call msg.currentTarget ss0 res.2 res.1 fin) ∧ + (∀ y, r = .inr y → (y.1 ≤ p.blocks.length ∧ + (y.1 < p.blocks.length → c.need y.1 ≤ y.2.1.length ∧ y.2.1.length ≤ maxH mx y.1) ∧ + (y.1 = b + 1 ∨ isTarget p c y.1 = true)) ∧ + ∃ (after : Evm .fusaka Nat) (within' : GasMeter.gasHeld after.gas ≤ bound), + EntC p c mx code msg ss0 y after ∧ T'.gases.length = gasReads y.2.2.world ∧ + sent y.2.2.world = 0 ∧ after.gas ≤ g ∧ + memoryGasCost after.memory.size + after.gas ≤ G0 ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild after within' = .ok fin) + | 0, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, hn, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ => absurd hn (Nat.not_lt_zero _) + | n + 1, is, h, known, ty, k, S, Tw, s, pc, M, g, st, ss, T, evm, within, hn, hokC, hh, hu, hk, + hR, hseg, hstk, htop, hmem, R, hat, hTg, hs0, hB, hrun => by + have hge : evm.gas = g := hat.2.2.2.2.2.2.1 + -- The segment with gas to spare for it alone: `K` more than the frame holds. + generalize hK : 22100 * k + memoryGasCost c.top = K + have hp := hat.addGas K + have I : InvL c code call (lowerInstrs p c b is ++ lowerFrom p c (b + 1) + (p.blocks.drop (b + 1))) k 0 pc S s M (g + K) := + ⟨hseg, hstk, by simp only [Nat.add_zero]; omega, htop, hmem⟩ + have hsim := exec_simC (mx := mx) G (o := O T) hdata hvalue hstatic hself hcaller + (O_ok c T).1 hbenv htx (O_ok c T).2 b hb 0 (G0 + K) rd is h known ty S Tw k s pc M + (g + K) st ss hokC hh hu hk hR I R (by unfold MemBudget at *; omega) + have hcnt := (execC_agree (Agree.refl (O T) (gasReads s.world) (sent s.world)) call b is S s + le_rfl le_rfl).2 + have hex : ∀ T'', T.Le T'' → SolarTV.EVM.Program.exec (O T'') call b is S s = + match execC (O T) call b is S s with + | .done r => r + | .cut i rest S' s' => SolarTV.EVM.Program.exec (O T'') call b (i :: rest) S' s' := + fun T'' hle => exec_O hle (by omega) hs0 + generalize hr : execC (O T) call b is S s = r at hsim hcnt hex + cases r with + | done r => + refine ⟨T, r, RunTable.Le.refl T, fun T'' hle => hex T'' hle, fun res hres => ?_, + fun y hy => ?_⟩ + · subst hres + exact SpecG.low hsim hp within hrun hok + · subst hy + obtain ⟨t, S', s'⟩ := y + obtain ⟨⟨htle, hneedt, hj⟩, pc', T', M', g', st', ss', hh', hR', E', R', hB'⟩ := hsim + obtain ⟨e1, r1, he1⟩ := hh' _ hp + obtain ⟨m, within', hz, hrm⟩ := reaches_low r1 K evm rfl within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hmK⟩ := at_of_addGasR he1 + have hgm := reaches_gas_le r1 + rw [hz] at hgm + simp only [gas_addGas] at hgm + have hc1 := hcnt.1 s' rfl + refine ⟨⟨htle, hneedt, hj⟩, m, within', ⟨T', pc', M', st', ss', rd, htle, hneedt, hR', E'.seg, + E'.le_top, E'.mem, R', hatm⟩, ?_, ?_, by omega, + by rw [hatm.2.2.2.2.2.1]; unfold MemBudget at hB'; omega, hrm⟩ + · dsimp only; omega + · dsimp only; omega + | cut i rest S' s' => + obtain ⟨hci, h', known', ty', k', pc', T', M', g', st', ss', hh', hok2, hh2, hu2, hk2, hR', + I', R', hB'⟩ := hsim + -- The segment, moved back to the frame's gas. + obtain ⟨e1, r1, he1⟩ := hh' _ hp + obtain ⟨m, within1, hz, hrm⟩ := reaches_low r1 K evm rfl within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hmK⟩ := at_of_addGasR he1 + have hgm := reaches_gas_le r1 + rw [hz] at hgm + simp only [gas_addGas] at hgm + have hL := hR'.length + have hst := I'.stack + have hc1 := hcnt.1 s' rfl + have hlen := hcnt.2 _ rest S' s' rfl + have hmB : MemBudget G0 M' m.gas := by unfold MemBudget at *; omega + have hci' : isGasI i = true ∨ isLoadI i = true ∨ isStoreI i = true ∨ isRetI i = true ∨ + isRevI i = true ∨ isKecI i = true ∨ isLogI i = true ∨ isCdcI i = true ∨ isScI i = true ∨ + isRdsI i = true ∨ isRdcI i = true ∨ isCallI i = true ∨ isC2I i = true ∨ isCcI i = true := by + simpa [isCutI, isMemCutI, or_assoc] using hci + rcases hci' with hgi | hli | hsi | hri | hvi | hki | hlgi | hcdi | hsci | hrdi | hrdci | hcalli | + hc2i | hcci + · obtain rfl := isGasI_eq hgi + obtain ⟨hk1, hok3⟩ := blockOkC_gas hok2 + have hs := I'.seg + rw [lowerInstrs_gas, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + -- GAS at the frame's gas. + obtain ⟨h2, m2, within2, hat2, hrun2⟩ := + gas_back hatm hlt hcode (by unfold STACK_LIMIT; omega) within1 hrm hok + let T1 : RunTable := { T with gases := T.gases ++ [m.gas - 2] } + have hle1 : T.Le T1 := ⟨List.prefix_refl _, List.prefix_refl _, List.prefix_refl _, + List.prefix_refl _, List.prefix_append _ _⟩ + have hv : ∀ T'', T1.Le T'' → T''.gases.getD (gasReads s'.world) 0 = m.gas - 2 := by + intro T'' hle + rw [getD_of_prefix hle.2.2.2.2 (by simp [T1]; omega)] + simp [T1, List.getD_eq_getElem?_getD, hc1.1, ← hTg] + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := seg (G0 := G0) G hnc hdata hvalue hstatic hself hcaller hbenv + htx hb hok hG0 n rest (h' + 1) [] (some false :: ty') (k' - 1) + (BitVec.ofNat 256 (m.gas - 2) :: S') (BitVec.ofNat 256 (m.gas - 2) :: T') + { s' with world := s'.world ++ [.read "gas"] } (pc' + 1) M' (m.gas - 2) st' ss' T1 m2 + within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl hR') hseg' (by simp; omega) I'.le_top + I'.mem ⟨R'.storage, R'.account, logsRel_read _ R'.logs⟩ hat2 + (by simp [T1]; omega) (by simp [hc1.2, hs0]) + (by unfold MemBudget at *; omega) hrun2 + refine ⟨T2, r, hle1.trans hle2, fun T'' hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T'' (hle1.trans (hle2.trans hle))] + show SolarTV.EVM.Program.exec (O T'') call b (.effect .gas 0 :: rest) S' s' = r + rw [exec_gas (hv T'' (hle2.trans hle)) (by omega)] + exact hex2 T'' hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, by omega, hbud, hra⟩ + + · -- MLOAD at the frame's gas, at any offset. + obtain rfl := isLoadI_eq hli + obtain ⟨hk1, hh1, hdat, htop', hok3⟩ := blockOkC_load hok2 + have hs := I'.seg + rw [lowerInstrs_load, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, S''⟩ + · simp at hh2; omega + rcases T' with _ | ⟨x', Tr⟩ + · simp at hL + obtain rfl := (SR.head hR' hdat).symm + have hR'' := (SR.uncons.1 hR').2 + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + AssembleDyn.mload_dyn I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := seg (G0 := G0) G hnc hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 n rest h' [] (some false :: ty'.drop 1) (k' - 1) + (s'.memory.load x.toNat :: S'') (s'.memory.load x.toNat :: Tr) + { s' with memory := s'.memory.expand x.toNat 32 } (pc' + 1) M2 g2 st' ss' T m2 + within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl (by simpa using hR'')) hseg' + (by simp; omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by show T.gases.length = gasReads s'.world; rw [hc1.1]; exact hTg) + (by show sent s'.world = 0; rw [hc1.2]; exact hs0) hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (O T3) call b (.op .load :: rest) _ s' = r + rw [exec_loadC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, by omega, hbud, hra⟩ + · -- MSTORE at the frame's gas, at any offset. + obtain rfl := isStoreI_eq hsi + obtain ⟨hk1, hh1, hdat, htop', hok3⟩ := blockOkC_store hok2 + have hs := I'.seg + rw [lowerInstrs_store, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 2) S'' Tr := by simpa using SR.drop 2 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + AssembleDyn.mstore_dyn I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := seg (G0 := G0) G hnc hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 n rest (h' - 2) [] (ty'.drop 2) (k' - 1) S'' Tr + { s' with memory := s'.memory.store x.toNat y } (pc' + 1) M2 g2 st' ss' T m2 + within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by show T.gases.length = gasReads s'.world; rw [hc1.1]; exact hTg) + (by show sent s'.world = 0; rw [hc1.2]; exact hs0) hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (O T3) call b (.op .store :: rest) _ s' = r + rw [exec_storeC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, by omega, hbud, hra⟩ + + · -- RETURN at the frame's gas, from any range. + obtain rfl := isRetI_eq hri + obtain ⟨hh1, hdat⟩ := blockOkC_ret hok2 + have hs := I'.seg + rw [lowerInstrs_ret, List.cons_append] at hs + obtain ⟨next, hd, -⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hg := AssembleDyn.return_back hatm hlt hcode within1 hrm hok + refine ⟨T, .inl (SolarTV.EVM.Program.output s' (x :: y :: S'') false), RunTable.Le.refl T, + fun T3 hle => ?_, fun res hres => ?_, fun y hy => ?_⟩ + · rw [hex T3 hle] + rfl + · obtain rfl := Sum.inl.inj hres + simp only [SolarTV.EVM.Program.output, Bool.false_eq_true, ↓reduceIte] + exact SpecG.low (SpecG.consequence (return_postSG (ss := ss') hlt hcode (by omega) rfl + (by rw [read_eq I'.mem]; rfl) rfl (R'.slot hself)) (fun _ h => h) + (fun _ h => ⟨ss', h, R'.logs⟩)) (hatm.addGas 0) within1 hrm hok + · cases hy + · -- REVERT: no run that succeeds reaches it. + obtain rfl := isRevI_eq hvi + obtain ⟨hh1, hdat⟩ := blockOkC_revert hok2 + have hs := I'.seg + rw [lowerInstrs_revert, List.cons_append] at hs + obtain ⟨next, hd, -⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + exact (AssembleDyn.revert_false hatm hlt hcode within1 hrm hok).elim + + · -- KECCAK256 at the frame's gas, of any range. + obtain rfl := isKecI_eq hki + obtain ⟨henv, hk1, hh1, hdat, htop', hok3⟩ := blockOkC_kec hok2 + have hs := I'.seg + rw [lowerInstrs_kec, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 2) S'' Tr := by simpa using SR.drop 2 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨m2, within2, hmem2, hb2, hat2, hrun2⟩ := + AssembleDyn.keccak_dyn I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + obtain ⟨-, hkec⟩ := (O_ok c T).1 henv + rw [byteArray_eq_of_map (read_eq I'.mem), ← hkec] at hat2 + have hsz : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size ≤ c.top := by + have hmod : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size % 32 = 0 := by + rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := seg (G0 := G0) G hnc hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 n rest (h' - 1) [] (some false :: ty'.drop 2) (k' - 1) + ((O T).keccak ((s'.memory.expand x.toNat y.toNat).read x.toNat y.toNat) :: S'') + ((O T).keccak ((s'.memory.expand x.toNat y.toNat).read x.toNat y.toNat) :: Tr) + { s' with memory := s'.memory.expand x.toNat y.toNat } (pc' + 1) _ _ st' ss' T m2 + within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl (by simpa using hR'')) hseg' + (by simp; omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by show T.gases.length = gasReads s'.world; rw [hc1.1]; exact hTg) + (by show sent s'.world = 0; rw [hc1.2]; exact hs0) hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (O T3) call b (.effect .keccak256 2 :: rest) _ s' = r + rw [exec_keccakC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, by omega, hbud, hra⟩ + + · -- LOGn at the frame's gas, of any range. + obtain ⟨nl, hn4, rfl⟩ := isLogI_eq hlgi + obtain ⟨hk1, hnh, hdat, htop', hok3⟩ := blockOkC_log hn4 hok2 + have hs := I'.seg + rw [lowerInstrs_log p c b hn4, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S1⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', T1⟩⟩ + · simp at hL + · simp at hL + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨tops, S2, rfl, hlen⟩ : ∃ tops S2, S1 = tops ++ S2 ∧ tops.length = nl := + ⟨S1.take nl, S1.drop nl, (List.take_append_drop nl S1).symm, by simp; omega⟩ + obtain ⟨tops', T2, rfl, hlen'⟩ : ∃ tops' T2, T1 = tops' ++ T2 ∧ tops'.length = nl := + ⟨T1.take nl, T1.drop nl, (List.take_append_drop nl T1).symm, by simp; omega⟩ + subst hlen + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.cons.injEq, List.take_left' hlen', + List.take_left' rfl] at htake + obtain ⟨rfl, rfl, rfl⟩ := htake + have hR'' : SR c (ty'.drop (tops.length + 2)) S2 T2 := by + simpa using SR.drop (tops.length + 2) hR' + simp only [List.length_append] at hL hst hh2 hu2 + obtain ⟨m2, within2, hmem2, hb2, hat2, hrun2⟩ := + AssembleDyn.log_dyn (n := ⟨tops.length, by omega⟩) I'.mem hmB (by omega) hatm rfl hlt hcode + (decode_log ⟨tops.length, by omega⟩) hstatic within1 hrm hok + have hsz : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size ≤ c.top := by + have hmod : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size % 32 = 0 := by + rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨L, hL1, hL2⟩ := R'.logs + obtain ⟨T2', r, hle2, hex2, hpost, hnext⟩ := seg (G0 := G0) (ss0 := ss0) G hnc hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 n rest (h' - (tops.length + 2)) [] (ty'.drop (tops.length + 2)) + (k' - 1) S2 T2 + ⟨s'.memory.expand x.toNat y.toNat, s'.storage, s'.transient, + s'.world ++ [.log tops ((s'.memory.expand x.toNat y.toNat).read x.toNat y.toNat)]⟩ + (pc' + 1) _ _ st' { ss' with logs := ss'.logs.push ⟨msg.currentTarget, + tops.map U256.toBeBytes, memoryReadBytes (memoryExtend M' (extendMemory M'.size + [(x, y)]).expandBy) x.toNat y.toNat⟩ } T m2 within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 + ⟨R'.storage, R'.account, ⟨L ++ [⟨msg.currentTarget, tops.map U256.toBeBytes, + memoryReadBytes (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy) + x.toNat y.toNat⟩], by simp [Array.toList_push, hL1], + filter_snoc_log ▸ forall₂_snoc hL2 ⟨rfl, rfl, read_eq I'.mem⟩⟩⟩ hat2 + (by show T.gases.length = gasReads (s'.world ++ [_]); rw [gasReads_log, hc1.1]; exact hTg) + (by show sent (s'.world ++ [_]) = 0; rw [sent_log, hc1.2]; exact hs0) hb2 hrun2 + refine ⟨T2', r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (O T3) call b + (.effect (.log tops.length) (tops.length + 2) :: rest) _ s' = r + rw [exec_logC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, by omega, hbud, hra⟩ + + · -- CALLDATACOPY at the frame's gas, of any range. + obtain rfl := isCdcI_eq hcdi + obtain ⟨hk1, hh1, hdat, htop', hok3⟩ := blockOkC_cdc hok2 + have hs := I'.seg + rw [lowerInstrs_cdc, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, _ | ⟨z, S''⟩⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', _ | ⟨z', Tr⟩⟩⟩ + · simp at hL + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 3) S'' Tr := by simpa using SR.drop 3 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + AssembleDynCopy.cdc_dyn hdata I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := seg (G0 := G0) (ss0 := ss0) G hnc hdata hvalue + hstatic hself hcaller hbenv htx hb hok hG0 n rest (h' - 3) [] (ty'.drop 3) (k' - 1) S'' Tr + { s' with + memory := s'.memory.write x.toNat z.toNat + (fun i => SolarTV.Machine.calldataByte call (y.toNat + i)) } (pc' + 1) M2 g2 st' ss' T m2 + within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by show T.gases.length = gasReads s'.world; rw [hc1.1]; exact hTg) + (by show sent s'.world = 0; rw [hc1.2]; exact hs0) hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (O T3) call b (.effect .calldatacopy 3 :: rest) _ s' = r + rw [exec_cdcC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, by omega, hbud, hra⟩ + · -- STATICCALL: only a certificate that says the program makes calls lets the checker cut there. + obtain rfl := isScI_eq hsci + exact absurd (blockOkC_sc hok2).1 (by simp [hnc]) + · obtain rfl := isRdsI_eq hrdi + exact absurd (blockOkC_rds hok2).1 (by simp [hnc]) + · obtain rfl := isRdcI_eq hrdci + exact absurd (blockOkC_rdc hok2).1 (by simp [hnc]) + · -- CALL, CREATE2 and CODECOPY: only a certificate that says the program creates lets the + -- checker cut there. + obtain rfl := isCallI_eq hcalli + exact absurd (blockOkC_call hok2).1 (by simp [hnc]) + · obtain rfl := isC2I_eq hc2i + exact absurd (blockOkC_c2 hok2).1 (by simp [hnc]) + · obtain rfl := isCcI_eq hcci + exact absurd (blockOkC_cc hok2).1 (by simp [hnc]) + +/-! ## The checker with GAS -/ + +/-- `AssembleLoop.blocksOkL` with GAS. -/ +def blocksOkC (p : Assemble.Program) (c : Cert) (mx : List Nat) : + Nat → List (List Assemble.Instr) → Bool + | _, [] => true + | b, instrs :: rest => + decide (labelItems p c b ≤ budget c b) && decide (c.need b ≤ maxH mx b) && + decide (maxH mx b + budget c b ≤ 1000) && + blockOkC p c mx b (c.need b) [] (c.entry b) (budget c b - labelItems p c b) instrs && + blocksOkC p c mx (b + 1) rest + +/-- **The checker of code with loops and GAS**: `AssembleLoop.checkL` with `blockOkC`. -/ +def checkCB (p : Assemble.Program) (code : ByteArray) (c : Cert) (mx : List Nat) : Bool := + (walk (bytesOf code) c.offset 0 (lower p c)).isSome && blocksOkC p c mx 0 p.blocks && + labelsValid p c code && decide (c.need 0 = 0) && decide (c.top % 32 = 0) && + decide (c.top ≤ 2 ^ 200) && decide (code.size < 2 ^ 32) && !c.creates + +/-- **The checker of code with calls and creations**: `checkCB` without its gate on creations, +for a certificate that says the program makes CALLs, CREATE2s and CODECOPYs (`Cert.creates`, with +`Cert.calls`). No theorem over runs covers it yet: programs it accepts are checked, not proved. -/ +def checkCF (p : Assemble.Program) (code : ByteArray) (c : Cert) (mx : List Nat) : Bool := + (walk (bytesOf code) c.offset 0 (lower p c)).isSome && blocksOkC p c mx 0 p.blocks && + labelsValid p c code && decide (c.need 0 = 0) && decide (c.top % 32 = 0) && + decide (c.top ≤ 2 ^ 200) && decide (code.size < 2 ^ 32) + +/-- **The checker of code with loops and GAS** for a program that makes no call: `checkCB` and a +certificate that says so. (`AssembleCutCall` checks programs with STATICCALLs.) -/ +def checkC (p : Assemble.Program) (code : ByteArray) (c : Cert) (mx : List Nat) : Bool := + (walk (bytesOf code) c.offset 0 (lower p c)).isSome && blocksOkC p c mx 0 p.blocks && + labelsValid p c code && decide (c.need 0 = 0) && decide (c.top % 32 = 0) && + decide (c.top ≤ 2 ^ 200) && decide (code.size < 2 ^ 32) && !c.calls && !c.creates + +theorem checkC_base {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (h : checkC p code c mx = true) : checkCB p code c mx = true ∧ c.calls = false := by + simp only [checkC, checkCB, Bool.and_eq_true, Bool.not_eq_true'] at h ⊢ + exact ⟨⟨h.1.1, h.2⟩, h.1.2⟩ + +/-- The checker of code with GAS and STATICCALLs refuses a certificate that says the program creates. -/ +theorem checkCB_creates {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (h : checkCB p code c mx = true) : c.creates = false := by + simp only [checkCB, Bool.and_eq_true, Bool.not_eq_true'] at h + exact h.2 + +theorem blocksOkC_get {p : Assemble.Program} {c : Cert} {mx : List Nat} : + ∀ (l : List (List Assemble.Instr)) (b : Nat), + blocksOkC p c mx b l = true → ∀ k (hk : k < l.length), + labelItems p c (b + k) ≤ budget c (b + k) ∧ c.need (b + k) ≤ maxH mx (b + k) ∧ + maxH mx (b + k) + budget c (b + k) ≤ 1000 ∧ + blockOkC p c mx (b + k) (c.need (b + k)) [] (c.entry (b + k)) + (budget c (b + k) - labelItems p c (b + k)) l[k] = true + | [], _, _, _, hk => absurd hk (by simp) + | x :: l, b, h, 0, _ => by + simp only [blocksOkC, Bool.and_eq_true, decide_eq_true_eq] at h + simpa [and_assoc] using h.1 + | x :: l, b, h, k + 1, hk => by + simp only [blocksOkC, Bool.and_eq_true] at h + have := blocksOkC_get l (b + 1) h.2 k (by simp at hk; omega) + rw [show b + (k + 1) = b + 1 + k by omega] + simpa using this + +/-- The facts of the checker with GAS. -/ +structure GlobC (p : Assemble.Program) (c : Cert) (mx : List Nat) (code : ByteArray) : Prop + extends GlobT p c code where + block : ∀ t (ht : t < p.blocks.length), labelItems p c t ≤ budget c t ∧ + c.need t ≤ maxH mx t ∧ maxH mx t + budget c t ≤ 1000 ∧ + blockOkC p c mx t (c.need t) [] (c.entry t) (budget c t - labelItems p c t) p.blocks[t] = true + +theorem globC_of_checkC {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (h : checkCB p code c mx = true) : + GlobC p c mx code ∧ Seg (bytesOf code) c.offset 0 (lower p c) code.size ∧ c.need 0 = 0 := by + simp only [checkCB, Bool.and_eq_true, decide_eq_true_eq] at h + obtain ⟨⟨⟨⟨⟨⟨⟨hw, hblocks⟩, hlabels⟩, hneed⟩, hmod⟩, htop⟩, hsize⟩, -⟩ := h + obtain ⟨stream, hw⟩ := Option.isSome_iff_exists.1 hw + have hseg : Seg (bytesOf code) c.offset 0 (lower p c) code.size := by + have := seg_of_walk (walk_sound hw) + rwa [length_bytesOf] at this + refine ⟨⟨⟨hmod, htop, hsize, fun t ht htgt => ?_⟩, fun t ht => ?_⟩, hseg, hneed⟩ + · have hv : isValidJumpDest (validJumpDestinations code) (c.offset t) = true := by + simp only [labelsValid, List.all_eq_true, List.mem_range] at hlabels + have := hlabels t ht + simpa [htgt] using this + obtain ⟨pc', hs, hpc⟩ := seg_lowerFrom p c t p.blocks 0 0 hseg ht + simp only [Nat.zero_add] at hs hpc + rw [← hpc htgt] at hs + refine ⟨hv, ?_, hs⟩ + have hs' := hs + rw [lowerFrom_drop p c ht] at hs' + simp only [lowerBlock, htgt, ite_true, List.cons_append] at hs' + cases hs' with + | cons d _ _ => + have := decode_lt d + rwa [length_bytesOf] at this + · have := blocksOkC_get p.blocks 0 hblocks t ht + simpa using this + +/-! ## A block, read back from a run that succeeds -/ + +/-- The relation at a block entry, with the table's GAS reads and no message sent. -/ +def EntT (p : Assemble.Program) (c : Cert) (mx : List Nat) (code : ByteArray) + (msg : Message .fusaka) (ss0 : Substate) (T : RunTable) (x : Nat × List Word × State) + (evm : Evm .fusaka Nat) : Prop := + EntC p c mx code msg ss0 x evm ∧ T.gases.length = gasReads x.2.2.world ∧ sent x.2.2.world = 0 ∧ + memoryGasCost evm.memory.size + evm.gas ≤ msg.gas + +/-- **A block of code with loops and GAS, read back from a run that succeeds.** -/ +theorem advances_checkC {p : Assemble.Program} {c : Cert} {mx : List Nat} {code : ByteArray} + (G : GlobC p c mx code) (hnc : c.calls = false) {call : Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : msg.txEnv = Target.txEnv) + (hgas : msg.gas < 2 ^ 256) + (T0 : RunTable) (x : Nat × List Word × State) (evm : Evm .fusaka Nat) + (hE : EntT p c mx code msg ss0 T0 x evm) : + Advances (fun o => SolarTV.EVM.Program.block o call p) O (EntT p c mx code msg ss0) + (fun res => PostL call msg.currentTarget ss0 res.2 res.1) + (fun y e => AssembleLoop.meas p c e.gas y.1) T0 x evm := by + intro bound runChild _ within fin hrun hok + obtain ⟨b, S, s⟩ := x + obtain ⟨⟨Tw, pc, M, st, ss, rd, hle, hneed, hR, hseg, htop, hmem, R, hat⟩, hTg, hs0, hbud⟩ := hE + simp only at hle hneed hR hseg hmem R hTg hs0 + by_cases hb : b < p.blocks.length + · obtain ⟨hL, hnm, hstk, hblock⟩ := G.block b hb + obtain ⟨hn, hm⟩ := hneed hb + have hblk : p.blocks[b]? = some p.blocks[b] := List.getElem?_eq_getElem hb + rw [lowerFrom_drop p c hb, lowerBlock, List.append_assoc] at hseg + -- The label, at the frame's gas. + obtain ⟨pc1, m1, within1, hat1, hseg1, hg1, hrun1⟩ : ∃ (pc1 : Nat) (m1 : Evm .fusaka Nat) + (within1 : GasMeter.gasHeld m1.gas ≤ bound), + At code msg pc1 Tw M m1.gas st ss rd m1 ∧ + Seg (bytesOf code) c.offset pc1 (lowerInstrs p c b p.blocks[b] ++ + lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) code.size ∧ + m1.gas + (if isTarget p c b then 1 else 0) ≤ evm.gas ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m1 within1 = .ok fin := by + by_cases ht : isTarget p c b = true + · simp only [ht, ite_true, List.singleton_append, List.cons_append] at hseg + obtain ⟨next, hd, hseg'⟩ := hseg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hp := hat.addGas 1 + obtain ⟨e1, r1, he1⟩ := Logic.jumpdestG hlt hcode (show 1 ≤ evm.gas + 1 by omega) _ hp + obtain ⟨m, within', hz, hrm⟩ := reaches_low r1 1 evm rfl within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hgm⟩ := at_of_addGasR he1 + exact ⟨pc + 1, m, within', hatm, hseg', by simp only [ht, ite_true]; omega, hrm⟩ + · simp only [ht, Bool.false_eq_true, ite_false, List.nil_append] at hseg + exact ⟨pc, evm, within, hat, hseg, by simp only [ht, Bool.false_eq_true, ite_false]; omega, + hrun⟩ + obtain ⟨T', r, hle', hex, hpost, hnext⟩ := seg (G0 := msg.gas) G.toGlobT hnc hdata hvalue hstatic hself hcaller + hbenv htx hb hok hgas (p.blocks[b].length + 1) p.blocks[b] (c.need b) [] (c.entry b) + (budget c b - labelItems p c b) S Tw s pc1 M m1.gas st ss T0 m1 within1 (Nat.lt_succ_self _) + hblock hn (by omega) (KR.nil _) hR hseg1 (by omega) htop hmem R hat1 hTg hs0 + (by unfold MemBudget; rw [← hat.2.2.2.2.2.1]; omega) hrun1 + refine ⟨T', r, hle', fun T'' h => ?_, fun res hres => hpost res hres, fun y hy => ?_⟩ + · simp only [SolarTV.EVM.Program.block, hblk] + rw [hex T'' h] + · obtain ⟨t, S', s'⟩ := y + obtain ⟨⟨htle, -, hj⟩, after, within', hE', hT', hs', hga, hbud', hra⟩ := hnext _ hy + refine ⟨after, within', ⟨hE', hT', hs', hbud'⟩, ?_, hra⟩ + have := meas_step (c := c) (g := evm.gas) (g' := after.gas) hb htle (by omega) hj + dsimp only at this ⊢ + omega + · obtain rfl : b = p.blocks.length := by omega + have hblk : p.blocks[p.blocks.length]? = none := List.getElem?_eq_none (by omega) + have hbl : ∀ o, SolarTV.EVM.Program.block o call p (p.blocks.length, S, s) = + some (.inl (.stop, s)) := by + intro o + simp only [SolarTV.EVM.Program.block, hblk, ite_true] + refine ⟨T0, _, RunTable.Le.refl T0, fun _ _ => hbl _, ?_, ?_⟩ + · intro res hres + cases hres + have hseg' := hseg + rw [lowerFrom_nil p c (by omega)] at hseg' + have hpc := hseg'.nil_end + exact SpecG.low (SpecG.consequence (stop_of_size_leG (by omega)) + (fun _ h => h) fun evm h => postL_stop R hself evm h) (hat.addGas 0) within hrun hok + · intro y hy + cases hy + +/-- **EVM IR to bytecode, run by run, at the run's own gas, for code with loops, GAS and memory at +any offset**: for every program the checker with GAS accepts, at every gas below `2 ^ 256` and +every call, the oracle of the run's table makes every result of the bytecode the EVM IR's or a +failure that changes nothing. The bound on the gas is what keeps memory a run pays for within +SolarTV's count of words (`AssembleLoop.size_le_of_cost`). -/ +theorem runs_of_checkC {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (hc : checkC p code c mx = true) (gas : Nat) (hgas : gas < 2 ^ 256) (call : Call) : + ∃ T, Within (evmirSem (O T)) (ethLibWith gas) p code (· = call) := by + obtain ⟨hcb, hnc⟩ := checkC_base hc + obtain ⟨G, hseg, hneed0⟩ := globC_of_checkC hcb + refine within_of_advances O (fun ss0 => EntT p c mx code (Final.Target.messageWith gas code call) ss0) + (fun y e => AssembleLoop.meas p c e.gas y.1) (fun st' ss' R => ?_) + (fun ss0 T x evm hE => advances_checkC G hnc rfl + (by simp [Final.Target.messageWith, Target.message]) rfl rfl rfl rfl rfl hgas T x evm hE) + refine ⟨⟨[], 0, .empty, st', ss', .empty, Nat.zero_le _, fun _ => ⟨by simp [hneed0], by simp⟩, + SR.nil c _, by rw [List.drop_zero]; exact hseg, by simp, memRel_initial, R, ?_⟩, rfl, rfl, ?_⟩ + have hcode : (Final.Target.messageWith gas code call).code = code := rfl + · exact ⟨by simp [startFrame, hcode], by simp [startFrame, hcode], rfl, rfl, rfl, rfl, rfl, rfl, rfl, + rfl, rfl, rfl, rfl⟩ + · have h0 : memoryGasCost 0 = 0 := by rw [memoryGasCost_eq]; simp [wordCount, ceil32, WORD_BYTES] + simp only [startFrame, ByteArray.size_empty, h0, Nat.zero_add] + exact le_refl _ + +/-- `RunOracle.WithinRun` at every gas below `2 ^ 256` (a transaction's gas is at most +`2 ^ 64`). -/ +def WithinRunLt (sem : Oracle → Sem) (p : ∀ o, (sem o).Prog) (code : ByteArray) + (scope : Call → Prop) (Ok : Oracle → Prop) : Prop := + ∀ gas, gas < 2 ^ 256 → ∀ call, scope call → ∃ o, Ok o ∧ + Within (sem o) (ethLibWith gas) (p o) code (· = call) + +/-- `RunOracle.WithinRun.of_back` below `2 ^ 256` gas. -/ +theorem WithinRunLt.of_back {A sem : Oracle → Sem} {q : ∀ o, (A o).Prog} {p : ∀ o, (sem o).Prog} + {code : ByteArray} {scope : Call → Prop} {Ok : Oracle → Prop} + (back : ∀ o, Ok o → Stage (sem o) (A o) (p o) (q o) scope) + (h : WithinRunLt sem p code scope Ok) : WithinRunLt A q code scope Ok := by + intro gas hgas call hc + obtain ⟨o, ho, hw⟩ := h gas hgas call hc + refine ⟨o, ho, fun call' h' obs hrun => ?_⟩ + subst h' + rcases hw call' rfl obs hrun with e | e + · exact Or.inl (back o ho call' hc obs e) + · exact Or.inr e + +/-- The per-run theorem below `2 ^ 256` gas for every program the checker with GAS accepts. -/ +theorem withinRun_of_checkC {p : Assemble.Program} {code : ByteArray} {c : Cert} + {mx : List Nat} (hc : checkC p code c mx = true) (scope : Call → Prop) : + WithinRunLt evmirSem (fun _ => p) code scope (CertOk c) := by + intro gas hgas call _ + obtain ⟨T, hT⟩ := runs_of_checkC hc gas hgas call + exact ⟨O T, O_ok c T, hT⟩ + +/-- **The assembly premise of `holds_of_runs`** below `2 ^ 256` gas for every program the +checker with GAS accepts: an oracle and an open world that agree, under which the EVM IR gives the +bytecode's result or a failure that changes nothing. -/ +theorem assembly_of_checkC {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (hc : checkC p code c mx = true) (scope : Call → Prop) : + ∀ gas, gas < 2 ^ 256 → ∀ call, scope call → ∃ (o : Oracle) (W : World), W.Open ∧ + CallsAgree o W ∧ Within (evmirSem o) (ethLibWith gas) p code (· = call) := by + intro gas hgas call _ + obtain ⟨T, hT⟩ := runs_of_checkC hc gas hgas call + obtain ⟨W, hW, hA⟩ := O_agree T + exact ⟨O T, W, hW, hA, hT⟩ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCut.withinRun_of_checkC' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms withinRun_of_checkC + +/-- info: 'SolidCore.Refinement.Solar.AssembleCut.assembly_of_checkC' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms assembly_of_checkC + +/-- **The first lowered MIR to the exact bytecode, run by run, for code with loops, GAS and memory +at any offset**: the backend stages read backwards and the checker with GAS give, for every gas below +`2 ^ 256` and every call, an oracle meeting the certificate's constraints under which every result +of the bytecode is the first lowered MIR's or a failure that changes nothing. -/ +theorem withinRun_mir_of_checkC {stage0 : SolarTV.MIR.Lowered.moduleLayer.Prog} + {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} {S scope : Call → Prop} + (back : ∀ o, Certified SolarTV.EVM.Program.layer SolarTV.MIR.Lowered.moduleLayer o p stage0 S) + (hS : ∀ call, scope call → S call) (hc : checkC p code c mx = true) : + WithinRunLt mirSem (fun _ => stage0) code scope (CertOk c) := + WithinRunLt.of_back (fun o _ => fun call hcall obs h => + stage_of_certified (back o) call (hS call hcall) obs h) + (withinRun_of_checkC hc scope) + +/-- info: 'SolidCore.Refinement.Solar.AssembleCut.withinRun_mir_of_checkC' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms withinRun_mir_of_checkC + +/-- **`holds_of_runs` below `2 ^ 256` gas**: the specification of SolidCore, the stages to EVM IR +and the assembly premise at every gas below `2 ^ 256` (`assembly_of_checkC`) give the +specification of the bytecode at each such gas. -/ +theorem holds_of_runs_lt {St : Type} {fuel : Nat} + {mirSem evmirSem : SolarTV.Machine.Oracle → Sem} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {mir : ∀ o, (mirSem o).Prog} {evmir : ∀ o, (evmirSem o).Prog} {code : ByteArray} + {spec : Final.ContractSpec St} + (source : ∀ W : World, W.Open → Final.Holds (solidCoreIn W fuel) c spec) + (fin : ∀ W : World, W.Open → ∀ call, spec.Calls call → (Source.runIn W fuel c call).isSome) + (lowering : ∀ o W, CallsAgree o W → Stage (solidCoreIn W fuel) (mirSem o) c (mir o) spec.Calls) + (backend : ∀ o, Stage (mirSem o) (evmirSem o) (mir o) (evmir o) spec.Calls) + (assembly : ∀ gas, gas < 2 ^ 256 → ∀ call, spec.Calls call → ∃ o W, W.Open ∧ CallsAgree o W ∧ + Final.Within (evmirSem o) (Final.ethLibWith gas) (evmir o) code (· = call)) + (gas : Nat) (hgas : gas < 2 ^ 256) : Final.Holds (Final.ethLibWith gas) code spec := by + intro f hf args ht v hv σ hinv hreq obs hrun + have hc : spec.Calls (f.call args v σ) := ⟨f, hf, args, ht, v, hv, σ, rfl⟩ + obtain ⟨o, W, hopen, hagree, hwithin⟩ := assembly gas hgas _ hc + have agree := Final.agree_of_stage ((lowering o W hagree).trans (backend o)) (fin W hopen) + rcases hwithin _ rfl obs hrun with h | ⟨hs, hst, hl⟩ + · obtain ⟨obs', hs', hm⟩ := agree _ hc + rw [h] at hm + cases hm + exact source W hopen f hf args ht v hv σ hinv hreq obs hs' + · exact ⟨fun h'' => absurd (hs.symm.trans h'') (by decide), fun _ => ⟨hst, hl⟩⟩ + +/-- info: 'SolidCore.Refinement.Solar.AssembleCut.holds_of_runs_lt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holds_of_runs_lt + +end SolidCore.Refinement.Solar.AssembleCut diff --git a/SolidCore/Refinement/Solar/AssembleCutSim.lean b/SolidCore/Refinement/Solar/AssembleCutSim.lean new file mode 100644 index 00000000..40b2a489 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleCutSim.lean @@ -0,0 +1,1119 @@ +import SolidCore.Refinement.Solar.AssembleLoopSim +import SolidCore.Refinement.Solar.AssembleMem + +/-! +# The simulation of a block, cut at GAS + +GAS pushes the gas left, so no run with gas to spare shows what it pushes at the run's own gas: +`AssembleLoop.exec_simL` cannot pass it. `execC` runs a block as `exec` does up to the first +GAS, call or creation, and stops there (`CRes.cut`), before it. `exec_simC` is `exec_simL` for +`execC` and a checker that also takes GAS (`blockOkC`): a block's instructions give SolarTV's halt +or next block, as there, or a stop at GAS with EthLib's frame at GAS's offset related to SolarTV's +state, the check of the rest of the block and its invariant. `AssembleCut` runs GAS at the run's +own gas and resumes from there. +-/ + +namespace SolidCore.Refinement.Solar.AssembleLoop + +open SolidCore.Refinement.Solar.Assemble +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide +open SolarTV.EVM.Program + +/-! ## A block up to its first GAS, call or creation -/ + +/-- What a block's instructions give up to the first GAS, call or creation: SolarTV's result, or +that instruction with the rest of the block, the stack and the state before it. -/ +inductive CRes where + | done (r : (SolarTV.Machine.Halt × SolarTV.Machine.State) ⊕ + (Nat × List Word × SolarTV.Machine.State)) + | cut (i : Assemble.Instr) (rest : List Assemble.Instr) (S : List Word) (s : SolarTV.Machine.State) + +/-- The effects whose result is not monotone in gas or is the oracle's answer to a message. -/ +def cutEffect : SolarTV.Machine.Effect → Bool + | .gas | .call _ | .create | .create2 | .keccak256 | .log _ | .calldatacopy | .returndatasize + | .returndatacopy | .codecopy => + true + | _ => false + +/-- The memory operations that run at the frame's own gas: MLOAD and MSTORE, whose growth of +memory only the gas of the run bounds. -/ +def cutOp : SolarTV.EVM.Memory.Op → Bool + | .load | .store => true + | _ => false + +/-- `exec` up to the first GAS, call or creation. -/ +def execC (o : SolarTV.Machine.Oracle) (call : SolarTV.Call) (b : Nat) : + List Assemble.Instr → List Word → SolarTV.Machine.State → CRes + | [], stack, s => .done (.inr (b + 1, stack, s)) + | .op op :: rest, stack, s => + if cutOp op then .cut (.op op) rest stack s + else match stepOp (context o call s) op stack s.memory with + | .error _ => .done (.inl (.invalid, s)) + | .ok (stack, memory) => execC o call b rest stack { s with memory } + | .effect effect arity :: rest, stack, s => + if cutEffect effect then .cut (.effect effect arity) rest stack s + else if stack.length < arity then .done (.inl (.invalid, s)) + else match effect.apply o call (stack.take arity) s with + | none => .done (.inl (.invalid, s)) + | some (result, s) => + let stack := match result with + | some value => value :: stack.drop arity + | none => stack.drop arity + if stack.length > 1024 then .done (.inl (.invalid, s)) else execC o call b rest stack s + | .jump target :: _, stack, s => + if stack.length + 1 > 1024 then .done (.inl (.invalid, s)) else .done (.inr (target, stack, s)) + | .jumpi target :: rest, stack, s => + if stack.length + 1 > 1024 then .done (.inl (.invalid, s)) + else match stack with + | condition :: stack => + if condition = 0 then execC o call b rest stack s else .done (.inr (target, stack, s)) + | [] => .done (.inl (.invalid, s)) + | .pushLabel target :: rest, stack, s => + if stack.length + 1 > 1024 then .done (.inl (.invalid, s)) + else execC o call b rest (BitVec.ofNat 256 target :: stack) s + | .jumpDyn :: _, stack, s => + match stack with + | target :: stack => .done (.inr (target.toNat, stack, s)) + | [] => .done (.inl (.invalid, s)) + | .jumpiDyn :: rest, stack, s => + match stack with + | target :: condition :: stack => + if condition = 0 then execC o call b rest stack s else .done (.inr (target.toNat, stack, s)) + | _ => .done (.inl (.invalid, s)) + | .jumpTable targets :: _, stack, s => + match stack with + | index :: stack => + match targets[index.toNat]? with + | some target => .done (.inr (target, stack, s)) + | none => .done (.inl (.invalid, s)) + | [] => .done (.inl (.invalid, s)) + | .stop :: _, _, s => .done (.inl (.stop, s)) + | .ret :: rest, stack, s => .cut .ret rest stack s + | .revert :: rest, stack, s => .cut .revert rest stack s + | .invalid :: _, _, s => .done (.inl (.invalid, s)) + +/-- `exec` is `execC` and, at a stop, `exec` from the instruction it stopped at. -/ +theorem exec_eq_execC (o : SolarTV.Machine.Oracle) (call : SolarTV.Call) (b : Nat) : + ∀ (is : List Assemble.Instr) (S : List Word) (s : SolarTV.Machine.State), + exec o call b is S s = match execC o call b is S s with + | .done r => r + | .cut i rest S' s' => exec o call b (i :: rest) S' s' + | [], _, _ => rfl + | .op op :: rest, S, s => by + by_cases hc : cutOp op = true + · simp only [execC, hc, ite_true] + · have hc' : cutOp op = false := by simpa using hc + cases h : stepOp (context o call s) op S s.memory with + | error _ => simp [exec, execC, h, hc'] + | ok r => + obtain ⟨S', m⟩ := r + simp only [exec, execC, h, hc', Bool.false_eq_true, ite_false] + exact exec_eq_execC o call b rest _ _ + | .effect e a :: rest, S, s => by + by_cases hc : cutEffect e = true + · simp only [execC, hc, ite_true] + · by_cases hl : S.length < a + · simp [exec, execC, hc, hl] + · cases happ : SolarTV.Machine.Effect.apply o call e (S.take a) s with + | none => simp [exec, execC, hc, hl, happ] + | some r => + obtain ⟨res, s'⟩ := r + cases res <;> + · simp only [exec, execC, hc, hl, happ, Bool.false_eq_true, ite_false] + split_ifs <;> first | rfl | exact exec_eq_execC o call b rest _ _ + | .jump t :: rest, S, s => by + simp only [exec, execC] + split_ifs <;> rfl + | .jumpi t :: rest, S, s => by + cases S with + | nil => simp only [exec, execC]; split_ifs <;> rfl + | cons x S => + simp only [exec, execC] + split_ifs <;> first | rfl | exact exec_eq_execC o call b rest _ _ + | .pushLabel t :: rest, S, s => by + simp only [exec, execC] + split_ifs <;> first | rfl | exact exec_eq_execC o call b rest _ _ + | .jumpDyn :: rest, S, s => by cases S <;> simp [exec, execC] + | .jumpiDyn :: rest, S, s => by + match S with + | [] => simp [exec, execC] + | [_] => simp [exec, execC] + | x :: y :: S => + simp only [exec, execC] + split_ifs <;> first | rfl | exact exec_eq_execC o call b rest _ _ + | .jumpTable ts :: rest, S, s => by + cases S with + | nil => simp [exec, execC] + | cons x S => cases h : ts[x.toNat]? <;> simp [exec, execC, h] + | .stop :: rest, S, s => rfl + | .ret :: rest, S, s => rfl + | .revert :: rest, S, s => rfl + | .invalid :: rest, S, s => rfl + +/-! ## SolarTV's steps, up to a stop -/ + +theorem execC_stack {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {op : SolarTV.EVM.Op} {rest : List Assemble.Instr} {S next : List Word} {s : SolarTV.Machine.State} + (hstep : SolarTV.EVM.step (context o call s) op S = some next) (h1 : S.length ≤ 1024) + (h2 : next.length ≤ 1024) : + execC o call b (.op (.stack op) :: rest) S s = execC o call b rest next s := by + simp [execC, cutOp, stepOp, SolarTV.EVM.stepChecked, hstep, Except.map, + show ¬ 1024 < S.length by omega, show ¬ 1024 < next.length by omega] + +theorem exec_storeC {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {rest : List Assemble.Instr} {x y : Word} {S : List Word} {s : SolarTV.Machine.State} + (h : S.length < 1023) : + exec o call b (.op .store :: rest) (x :: y :: S) s = + exec o call b rest S { s with memory := s.memory.store x.toNat y } := by + have h1 : ¬ 1024 < S.length + 1 + 1 := by omega + simp [exec, stepOp, h1] + +theorem exec_loadC {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {rest : List Assemble.Instr} {x : Word} {S : List Word} {s : SolarTV.Machine.State} + (h : S.length < 1024) : + exec o call b (.op .load :: rest) (x :: S) s = + exec o call b rest (s.memory.load x.toNat :: S) { s with memory := s.memory.expand x.toNat 32 } := by + have h1 : ¬ 1024 < S.length + 1 := by omega + simp [exec, stepOp, h1] + +theorem execC_effect0 {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {rest : List Assemble.Instr} {e : SolarTV.Machine.Effect} {w : Word} {S : List Word} + {s : SolarTV.Machine.State} (he : cutEffect e = false) + (happ : SolarTV.Machine.Effect.apply o call e [] s = some (some w, s)) + (h : S.length < 1024) : + execC o call b (.effect e 0 :: rest) S s = execC o call b rest (w :: S) s := by + simp [execC, he, happ, show ¬ 1024 < S.length + 1 by omega] + +theorem execC_effect1 {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {rest : List Assemble.Instr} {e : SolarTV.Machine.Effect} {x w : Word} {S : List Word} + {s : SolarTV.Machine.State} (he : cutEffect e = false) + (happ : SolarTV.Machine.Effect.apply o call e [x] s = some (some w, s)) (h : S.length < 1024) : + execC o call b (.effect e 1 :: rest) (x :: S) s = execC o call b rest (w :: S) s := by + simp [execC, he, happ, show ¬ 1024 < S.length + 1 by omega] + +theorem execC_effect2 {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {rest : List Assemble.Instr} {e : SolarTV.Machine.Effect} {x y : Word} {S : List Word} + {s s' : SolarTV.Machine.State} (he : cutEffect e = false) + (happ : SolarTV.Machine.Effect.apply o call e [x, y] s = some (none, s')) (h : S.length ≤ 1024) : + execC o call b (.effect e 2 :: rest) (x :: y :: S) s = execC o call b rest S s' := by + simp [execC, he, happ, show ¬ 1024 < S.length by omega] + +theorem exec_keccakC {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {rest : List Assemble.Instr} {x y : Word} {S : List Word} {s : SolarTV.Machine.State} + (h : S.length < 1024) : + exec o call b (.effect .keccak256 2 :: rest) (x :: y :: S) s = + exec o call b rest (o.keccak ((s.memory.expand x.toNat y.toNat).read x.toNat y.toNat) :: S) + { s with memory := s.memory.expand x.toNat y.toNat } := by + simp [exec, SolarTV.Machine.Effect.apply, show ¬ 1024 < S.length + 1 by omega] + +theorem exec_cdcC {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {rest : List Assemble.Instr} {d off sz : Word} {S : List Word} {s : SolarTV.Machine.State} + (h : S.length ≤ 1024) : + exec o call b (.effect .calldatacopy 3 :: rest) (d :: off :: sz :: S) s = + exec o call b rest S { s with + memory := s.memory.write d.toNat sz.toNat + (fun i => SolarTV.Machine.calldataByte call (off.toNat + i)) } := by + simp [exec, SolarTV.Machine.Effect.apply, show ¬ 1024 < S.length by omega] + +theorem exec_logC {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {rest : List Assemble.Instr} {x y : Word} {tops S : List Word} {s : SolarTV.Machine.State} + (h : S.length ≤ 1024) : + exec o call b (.effect (.log tops.length) (tops.length + 2) :: rest) (x :: y :: (tops ++ S)) s = + exec o call b rest S ⟨s.memory.expand x.toNat y.toNat, s.storage, s.transient, + s.world ++ [.log tops ((s.memory.expand x.toNat y.toNat).read x.toNat y.toNat)]⟩ := by + have ht : (x :: y :: (tops ++ S)).take (tops.length + 2) = x :: y :: tops := by simp + have hd : (x :: y :: (tops ++ S)).drop (tops.length + 2) = S := by simp + simp only [exec, List.length_cons, List.length_append, ht, hd] + simp [SolarTV.Machine.Effect.apply, show ¬ 1024 < S.length by omega, + show ¬ tops.length + S.length + 1 + 1 < tops.length + 2 by omega] + try rw [show (0 : BitVec 256) = BitVec.ofNat 256 0 from rfl, foldl_bytes] + +/-! ## What the simulation uses of the check -/ + +/-- The facts of the check the simulation of a block uses: those of `GlobL` but the blocks' checks. -/ +structure GlobT (p : Assemble.Program) (c : Cert) (code : ByteArray) : Prop where + top_mod : c.top % 32 = 0 + top_le : c.top ≤ 2 ^ 200 + size_lt : code.size < 2 ^ 32 + target : ∀ t, t < p.blocks.length → isTarget p c t = true → + isValidJumpDest (validJumpDestinations code) (c.offset t) = true ∧ c.offset t < code.size ∧ + Seg (bytesOf code) c.offset (c.offset t) (lowerFrom p c t (p.blocks.drop t)) code.size + +/-- `InvL.target` from `GlobT`. -/ +theorem InvL.targetT {p : Assemble.Program} {c : Cert} {code : ByteArray} + (G : GlobT p c code) {call : SolarTV.Call} {t m : Nat} {items : List Item} {k R pc : Nat} + {S : List Word} {s : SolarTV.Machine.State} {M : ByteArray} {g g' : Nat} + (I : InvL c code call items k R pc S s M g) (htn : t < p.blocks.length) + (htgt : isTarget p c t = true) (hm : m ≤ k) (hg : g ≤ g' + 22100 * m) : + EntryL c code call (lowerFrom p c t (p.blocks.drop t)) R (c.offset t) s M g' where + seg := (G.target t htn htgt).2.2 + gas := by + have := I.gas + have hm' : 22100 * m ≤ 22100 * k := Nat.mul_le_mul_left _ hm + rw [Nat.mul_add] at this + omega + le_top := I.le_top + mem := I.mem + +/-! ## The checker with GAS -/ + +/-- GAS, with no operands. -/ +def isGasI : Assemble.Instr → Bool + | .effect .gas 0 => true + | _ => false + +theorem isGasI_eq {i : Assemble.Instr} (h : isGasI i = true) : i = .effect .gas 0 := by + unfold isGasI at h + split at h + · rfl + · cases h + +/-- MLOAD and MSTORE, which run at the frame's own gas. -/ +def isLoadI : Assemble.Instr → Bool + | .op .load => true + | _ => false + +def isStoreI : Assemble.Instr → Bool + | .op .store => true + | _ => false + +def isRetI : Assemble.Instr → Bool + | .ret => true + | _ => false + +def isRevI : Assemble.Instr → Bool + | .revert => true + | _ => false + +def isKecI : Assemble.Instr → Bool + | .effect .keccak256 2 => true + | _ => false + +def isLogI : Assemble.Instr → Bool + | .effect (.log n) a => decide (n ≤ 4) && decide (a = n + 2) + | _ => false + +def isCdcI : Assemble.Instr → Bool + | .effect .calldatacopy 3 => true + | _ => false + +/-- STATICCALL, with its six operands. -/ +def isScI : Assemble.Instr → Bool + | .effect (.call .staticcall) 6 => true + | _ => false + +/-- RETURNDATASIZE, which reads the return data of the frame's last call. -/ +def isRdsI : Assemble.Instr → Bool + | .effect .returndatasize 0 => true + | _ => false + +/-- RETURNDATACOPY, which copies a range of the return data of the frame's last call. -/ +def isRdcI : Assemble.Instr → Bool + | .effect .returndatacopy 3 => true + | _ => false + +/-- CALL, with its seven operands. -/ +def isCallI : Assemble.Instr → Bool + | .effect (.call .call) 7 => true + | _ => false + +/-- CREATE2, with its four operands. -/ +def isC2I : Assemble.Instr → Bool + | .effect .create2 4 => true + | _ => false + +/-- CODECOPY, with its three operands. -/ +def isCcI : Assemble.Instr → Bool + | .effect .codecopy 3 => true + | _ => false + +/-- A DUP right before a CODECOPY: the DUP of the copy's destination, over its code offset. -/ +def isCcDup : Assemble.Instr → List Assemble.Instr → Bool + | .op (.stack (.dup _)), .effect .codecopy 3 :: _ => true + | _, _ => false + +/-- MLOAD, MSTORE, RETURN, REVERT, KECCAK256, LOGn, CALLDATACOPY, STATICCALL, RETURNDATASIZE, +RETURNDATACOPY, CALL, CREATE2 and CODECOPY: memory at ranges only the gas of the run bounds. -/ +def isMemCutI (i : Assemble.Instr) : Bool := + isLoadI i || isStoreI i || isRetI i || isRevI i || isKecI i || isLogI i || isCdcI i || isScI i || + isRdsI i || isRdcI i || isCallI i || isC2I i || isCcI i + +theorem execC_cut {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {i : Assemble.Instr} {rest : List Assemble.Instr} {S : List Word} {s : SolarTV.Machine.State} + (h : isMemCutI i = true) : execC o call b (i :: rest) S s = .cut i rest S s := by + cases i with + | op op => cases op <;> simp_all [isMemCutI, isLoadI, isStoreI, isRetI, isRevI, isKecI, isLogI, isCdcI, isScI, isRdsI, isRdcI, isCallI, isC2I, isCcI, execC, cutOp] + | ret => rfl + | revert => rfl + | effect e a => + cases e <;> simp_all [isMemCutI, isLoadI, isStoreI, isRetI, isRevI, isKecI, isLogI, isCdcI, isScI, isRdsI, isRdcI, isCallI, isC2I, isCcI] <;> + simp [execC, cutEffect] + | _ => simp_all [isMemCutI, isLoadI, isStoreI, isRetI, isRevI, isKecI, isLogI, isCdcI, isScI, isRdsI, isRdcI, isCallI, isC2I, isCcI] + +/-- The instructions a block's segment stops at. -/ +def isCutI (i : Assemble.Instr) : Bool := isGasI i || isMemCutI i + +/-- `blockOkL` with GAS: it pushes a data word, for one item of the budget. -/ +def blockOkC (p : Assemble.Program) (c : Cert) (mx : List Nat) (b : Nat) : + Nat → Known → List Ty → Nat → List Assemble.Instr → Bool + | h, _, ty, _, [] => fallOkL p c mx b h ty + | h, known, ty, k, i :: rest => + match turnedElse c b i rest with + | some e => + decide (3 ≤ k) && decide (1 ≤ h) && isData ty 1 && jumpOkL p c mx b e (h - 1) ty.tail && + fallOkL p c mx b (h - 1) ty.tail + | none => + if dropped p b i rest then + match i with + | .stop => true + | _ => fallOkL p c mx b h ty + else if isGasI i then + decide (1 ≤ k) && blockOkC p c mx b (h + 1) [] (some false :: ty) (k - 1) rest + else if isLoadI i then + decide (1 ≤ k) && decide (1 ≤ h) && isData ty 1 && decide (2 ^ 140 ≤ c.top) && + blockOkC p c mx b h [] (some false :: ty.drop 1) (k - 1) rest + else if isStoreI i then + decide (1 ≤ k) && decide (2 ≤ h) && isData ty 2 && decide (2 ^ 140 ≤ c.top) && + blockOkC p c mx b (h - 2) [] (ty.drop 2) (k - 1) rest + else if isRetI i || isRevI i then decide (2 ≤ h) && isData ty 2 + else if isKecI i then + c.env && decide (1 ≤ k) && decide (2 ≤ h) && isData ty 2 && decide (2 ^ 140 ≤ c.top) && + blockOkC p c mx b (h - 1) [] (some false :: ty.drop 2) (k - 1) rest + else if isLogI i then + match i with + | .effect (.log n) _ => + decide (1 ≤ k) && decide (n + 2 ≤ h) && isData ty (n + 2) && decide (2 ^ 140 ≤ c.top) && + blockOkC p c mx b (h - (n + 2)) [] (ty.drop (n + 2)) (k - 1) rest + | _ => false + else if isCdcI i then + decide (1 ≤ k) && decide (3 ≤ h) && isData ty 3 && decide (2 ^ 140 ≤ c.top) && + blockOkC p c mx b (h - 3) [] (ty.drop 3) (k - 1) rest + else if isScI i then + c.calls && !c.creates && decide (1 ≤ k) && decide (6 ≤ h) && isData ty 6 && decide (2 ^ 140 ≤ c.top) && + blockOkC p c mx b (h - 5) [] (some false :: ty.drop 6) (k - 1) rest + else if isRdsI i then + c.calls && decide (1 ≤ k) && blockOkC p c mx b (h + 1) [] (some false :: ty) (k - 1) rest + else if isRdcI i then + c.calls && decide (1 ≤ k) && decide (3 ≤ h) && isData ty 3 && decide (2 ^ 140 ≤ c.top) && + blockOkC p c mx b (h - 3) [] (ty.drop 3) (k - 1) rest + else if isCallI i then + c.calls && c.creates && decide (1 ≤ k) && decide (7 ≤ h) && isData ty 7 && + decide (2 ^ 140 ≤ c.top) && blockOkC p c mx b (h - 6) [] (some false :: ty.drop 7) (k - 1) rest + else if isC2I i then + c.calls && c.creates && decide (1 ≤ k) && decide (4 ≤ h) && isData ty 4 && + decide (2 ^ 140 ≤ c.top) && blockOkC p c mx b (h - 3) [] (some false :: ty.drop 4) (k - 1) rest + else if isCcI i then + match known with + | _ :: some off :: _ => + c.calls && c.creates && decide (off.toNat < 2 ^ 32) && decide (1 ≤ k) && decide (3 ≤ h) && + isData ty 3 && decide (2 ^ 140 ≤ c.top) && blockOkC p c mx b (h - 3) [] (ty.drop 3) (k - 1) rest + | _ => false + else if isCcDup i rest then + match known with + | some off :: _ => c.calls && c.creates && + blockStepL p c mx b (fun h _ ty k => blockOkC p c mx b h [some 0, some off] ty k rest) h known ty k i + | _ => false + else blockStepL p c mx b (fun h known ty k => blockOkC p c mx b h known ty k rest) h known ty k i + +/-! ## The budget of memory and gas -/ + +/-- The price of memory `M` and the gas `g` are at most `G`: what a frame keeps along a run that +pays for each growth of its memory. -/ +def MemBudget (G : Nat) (M : ByteArray) (g : Nat) : Prop := memoryGasCost M.size + g ≤ G + +/-- Spending gas with memory as it was keeps the budget. -/ +theorem MemBudget.spend {G g g' : Nat} {M : ByteArray} (h : MemBudget G M g) (hg : g' ≤ g) : + MemBudget G M g' := by + unfold MemBudget at * + omega + +/-- **Paying for a growth of memory keeps the budget**: the grown memory's price exceeds the old one +by the growth's cost, which the frame pays. -/ +theorem MemBudget.grow {G g X : Nat} {M M' : ByteArray} (hmod : M.size % 32 = 0) {o sz : Word} + (hb : MemBudget G M g) (hg : X + (extendMemory M.size [(o, sz)]).cost ≤ g) + (hM' : M'.size = M.size + (extendMemory M.size [(o, sz)]).expandBy) : + MemBudget G M' (g - (X + (extendMemory M.size [(o, sz)]).cost)) := by + have hc := extendMemory_cost M.size [(o, sz)] + rw [ceil32_of_mod hmod] at hc + have hm := memoryGasCost_mono (Nat.le_add_right M.size (extendMemory M.size [(o, sz)]).expandBy) + unfold MemBudget at * + rw [hM'] + omega + +/-- A triple between frames at known gas ends with at most the gas it starts with. -/ +theorem gas_le_of_hoareG {code : ByteArray} {msg : Message .fusaka} {pc pc' : Nat} + {T T' : List Word} {M M' : ByteArray} {gas g : Nat} {st st' : State.TransactionState} + {ss ss' : Substate} {rd rd' : ByteArray} + (h : HoareG .fusaka (At code msg pc T M gas st ss rd) (At code msg pc' T' M' g st' ss' rd')) + (hT : T.length ≤ 1024) : g ≤ gas := by + let e : Evm .fusaka Nat := + Evm.mk pc ⟨T, hT⟩ M code (validJumpDestinations code) gas true msg .empty rd st ss none + obtain ⟨e', hr, hq⟩ := h e ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩ + have hle : e'.gas ≤ e.gas := Reaches.gasHeld_le (fun hs => Step.gasHeld_le hs.1) hr + rw [hq.2.2.2.2.2.2.1] at hle + exact hle + +/-- `SimOutL` with the budget `Gs` at the next block's entry. -/ +def SimOutB (p : Assemble.Program) (c : Cert) (mx : List Nat) (code : ByteArray) (call : SolarTV.Call) + (msg : Message .fusaka) (ss0 : Substate) (rd : ByteArray) (st : State.TransactionState) + (ss : Substate) (b R pc : Nat) (T : List Word) (M : ByteArray) (g Gs : Nat) : + (SolarTV.Machine.Halt × SolarTV.Machine.State) ⊕ (Nat × List Word × SolarTV.Machine.State) → + Prop + | .inl (halt, s') => + SpecG .fusaka (At code msg pc T M g st ss rd) (PostL call msg.currentTarget ss0 s' halt) + | .inr (t, S', s') => (t ≤ p.blocks.length ∧ + (t < p.blocks.length → c.need t ≤ S'.length ∧ S'.length ≤ maxH mx t) ∧ + (t = b + 1 ∨ isTarget p c t = true)) ∧ + ∃ pc' T' M' g' st' ss', HoareG .fusaka (At code msg pc T M g st ss rd) + (At code msg pc' T' M' g' st' ss' rd) ∧ SR c (c.entry t) S' T' ∧ + EntryL c code call (lowerFrom p c t (p.blocks.drop t)) R pc' s' M' g' ∧ + Rel msg ss0 st' ss' s' ∧ MemBudget Gs M' g' + +theorem SimOutB.pre {p : Assemble.Program} {c : Cert} {mx : List Nat} {code : ByteArray} + {call : SolarTV.Call} {msg : Message .fusaka} {ss0 : Substate} {st st1 : State.TransactionState} + {ss ss1 : Substate} {rd : ByteArray} {b R pc pc1 : Nat} {T T1 : List Word} {M M1 : ByteArray} + {g g1 Gs : Nat} {r : (SolarTV.Machine.Halt × SolarTV.Machine.State) ⊕ (Nat × List Word × SolarTV.Machine.State)} + (h : HoareG .fusaka (At code msg pc T M g st ss rd) (At code msg pc1 T1 M1 g1 st1 ss1 rd)) + (h1 : SimOutB p c mx code call msg ss0 rd st1 ss1 b R pc1 T1 M1 g1 Gs r) : + SimOutB p c mx code call msg ss0 rd st ss b R pc T M g Gs r := by + match r, h1 with + | .inl (_, _), hspec => exact SpecG.seq h hspec + | .inr (_, _, _), ⟨hneed, pc', T', M', g', st', ss', hh, hR, hinv, hrel, hb⟩ => + exact ⟨hneed, pc', T', M', g', st', ss', Triple.seq h hh, hR, hinv, hrel, hb⟩ + +/-- What a block's instructions give: `SimOutL` for SolarTV's halt or next block, and at a stop, GAS, +with EthLib's frame at its offset, its stack related, the check of the rest and the invariant. -/ +def SimOutC (p : Assemble.Program) (c : Cert) (mx : List Nat) (code : ByteArray) (call : SolarTV.Call) + (msg : Message .fusaka) (ss0 : Substate) (rd : ByteArray) + (st : State.TransactionState) (ss : Substate) (b R pc : Nat) (T : List Word) (M : ByteArray) + (g Gs : Nat) : CRes → Prop + | .done r => SimOutB p c mx code call msg ss0 rd st ss b R pc T M g Gs r + | .cut i rest S' s' => isCutI i = true ∧ + ∃ (h : Nat) (known : Known) (ty : List Ty) (k pc' : Nat) (T' : List Word) (M' : ByteArray) + (g' : Nat) (st' : State.TransactionState) (ss' : Substate), + HoareG .fusaka (At code msg pc T M g st ss rd) (At code msg pc' T' M' g' st' ss' rd) ∧ + blockOkC p c mx b h known ty k (i :: rest) = true ∧ h ≤ S'.length ∧ + S'.length + c.need b ≤ h + maxH mx b ∧ KR known S' ∧ SR c ty S' T' ∧ + InvL c code call (lowerInstrs p c b (i :: rest) ++ + lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) k R pc' S' s' M' g' ∧ + Rel msg ss0 st' ss' s' ∧ MemBudget Gs M' g' + +theorem SimOutC.pre {p : Assemble.Program} {c : Cert} {mx : List Nat} {code : ByteArray} + {call : SolarTV.Call} + {msg : Message .fusaka} {ss0 : Substate} {st st1 : State.TransactionState} {ss ss1 : Substate} + {rd : ByteArray} {b R pc pc1 : Nat} {T T1 : List Word} {M M1 : ByteArray} {g g1 Gs : Nat} + {r : CRes} + (h : HoareG .fusaka (At code msg pc T M g st ss rd) (At code msg pc1 T1 M1 g1 st1 ss1 rd)) + (h1 : SimOutC p c mx code call msg ss0 rd st1 ss1 b R pc1 T1 M1 g1 Gs r) : + SimOutC p c mx code call msg ss0 rd st ss b R pc T M g Gs r := by + match r, h1 with + | .done _, h1 => exact SimOutB.pre h h1 + | .cut _ _ _ _, ⟨hi, hc, known, ty, k, pc', T', M', g', st', ss', hh, rest'⟩ => + exact ⟨hi, hc, known, ty, k, pc', T', M', g', st', ss', Triple.seq h hh, rest'⟩ + +/-- The check of a CODECOPY reads only the code offset of what it knows of the stack. -/ +theorem blockOkC_cc_known {p : Assemble.Program} {c : Cert} {mx : List Nat} {b h : Nat} {ty : List Ty} + {k : Nat} {rest : List Assemble.Instr} (x y off : Word) : + blockOkC p c mx b h [some x, some off] ty k (.effect .codecopy 3 :: rest) = + blockOkC p c mx b h [some y, some off] ty k (.effect .codecopy 3 :: rest) := by + simp only [blockOkC, turnedElse, dropped, isGasI, isLoadI, isStoreI, isRetI, isRevI, isKecI, + isLogI, isCdcI, isScI, isRdsI, isRdcI, isCallI, isC2I, isCcI, Bool.false_eq_true, ite_false, + ite_true] + +/-- After a DUP over a known word, that word is second on the stack. -/ +theorem ccDup_prefix {ctx : SolarTV.EVM.Context} {j : Fin 256} {S S' : List Word} {off : Word} + {known0 : Known} (hk : KR (some off :: known0) S) + (h : SolarTV.EVM.step ctx (.dup j) S = some S') : ∃ x, KR [some x, some off] S' := by + simp only [SolarTV.EVM.step, Option.map_eq_some_iff] at h + obtain ⟨v, -, rfl⟩ := h + refine ⟨v, fun i w hw => ?_⟩ + match i, hw with + | 0, hw => simp [kAt] at hw; simp [hw] + | 1, hw => + simp [kAt] at hw; subst hw + simpa using hk 0 off (by simp [kAt]) + | i + 2, hw => simp [kAt] at hw + +set_option hygiene false in +/-- The budget after an instruction that leaves memory as it was. -/ +local macro "bud_tac" : tactic => `(tactic| first | exact Hb | exact MemBudget.spend Hb (by omega)) + +set_option hygiene false in +/-- The budget after an instruction that grows memory and pays for it. -/ +local macro "bud_mem" : tactic => `(tactic| exact MemBudget.grow hmod Hb (by omega) hM') + +set_option hygiene false in +/-- The bound of the stack in lockstep with the height of the check. -/ +local macro "hu_tac" : tactic => `(tactic| first | omega | (simp at hu ⊢; omega) | (simp; omega)) + +open SolarTV.EVM.Program in +/-- EthLib runs the code of a block's instructions from the offset of the next one as SolarTV +runs them, over steps monotone in gas, with gas for the reserve `R` beyond the block. -/ +theorem exec_simC {p : Assemble.Program} {c : Cert} {mx : List Nat} {code : ByteArray} (G : GlobT p c code) + {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) (ho : c.env = true → OracleOk o) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : msg.txEnv = Target.txEnv) + (he : c.reads = true → EnvOk o) + (b : Nat) (hb : b < p.blocks.length) (Rv Gs : Nat) (rd : ByteArray) : + ∀ (is : List Assemble.Instr) (h : Nat) (known : Known) (ty : List Ty) (S T : List Word) (k : Nat) + (s : SolarTV.Machine.State) (pc : Nat) (M : ByteArray) (g : Nat) + (st : State.TransactionState) (ss : Substate), + blockOkC p c mx b h known ty k is = true → h ≤ S.length → + S.length + c.need b ≤ h + maxH mx b → KR known S → SR c ty S T → + InvL c code call (lowerInstrs p c b is ++ lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) k Rv + pc S s M g → Rel msg ss0 st ss s → MemBudget Gs M g → + SimOutC p c mx code call msg ss0 rd st ss b Rv pc T M g Gs (execC o call b is S s) + | [], h, known, ty, S, T, k, s, pc, M, g, st, ss, hok, hh, hu, _, hR, I, R, Hb => by + simp only [blockOkC, fallOkL, Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at hok + have I2 := I.entry + simp only [lowerInstrs, List.nil_append] at I2 + simp only [execC, SimOutC, SimOutB] + exact ⟨⟨by omega, fun ht => ⟨by omega, by omega⟩, by simp⟩, pc, T, M, g, st, ss, + Triple.of_imp fun _ h => h, SR.le hok.1.2 hR, I2, R, Hb⟩ + | i :: rest, h, known, ty, S, T, k, s, pc, M, g, st, ss, hok, hh, hu, hk, hR, I, R, Hb => by + have hL := hR.length + have hctx : (⟨BitVec.ofNat 256 msg.data.size, o.env "returndatasize" s.world []⟩ : + SolarTV.EVM.Context) = context o call s := by rw [hdata]; rfl + cases hT : turnedElse c b i rest with + | some e => + -- A turned branch: ISZERO; PUSH e; JUMPI, falling into the next block. + obtain ⟨rfl, rfl⟩ := turnedElse_some hT + simp only [blockOkC, hT, jumpOkL, fallOkL, Bool.and_eq_true, Bool.or_eq_true, + decide_eq_true_eq] at hok + obtain ⟨⟨⟨⟨hk3, h1⟩, hdat⟩, ⟨⟨⟨hen, hetgt⟩, hneed⟩, hety⟩, hcost⟩, ⟨hfall, hfty⟩, hcost'⟩ := hok + simp only [lowerInstrs, hT, List.cons_append, List.nil_append] at I + rcases S with _ | ⟨cond, S'⟩ + · simp at hh; omega + rcases T with _ | ⟨cond', T'⟩ + · simp at hL + obtain rfl := (SR.head hR hdat).symm + have hR' := (SR.uncons.1 hR).2 + simp only [List.length_cons] at hL + obtain ⟨n0, hd0, hs0⟩ := I.seg.head + obtain ⟨n1, hd1, hs1⟩ := hs0.head + obtain ⟨n2, hd2, hseg⟩ := hs1.head + simp only [Item.expected] at hd0 hd1 hd2 + obtain ⟨hlt0, hcode0, rfl⟩ := op_item hd0 + obtain ⟨hlt2, hcode2, rfl⟩ := op_item hd2 + have hS := I.stack; have hG := I.gas + simp only [List.length_cons] at hS hh hu + obtain ⟨g0, hg0, hisz⟩ := stack_ruleG (msg := msg) (M := M) (st := st) (ss := ss) (rd := rd) (gas := g) + (op := .iszero) (stack := cond :: T') (next := EvmRules.Evm.iszero cond :: T') + (r := o.env "returndatasize" s.world []) rfl hlt0 hcode0 rfl (by omega) + (by simp only [List.length_cons]; omega) + have hg0u := gas_le_of_hoareG hisz (by first | omega | (simp only [List.length_cons] at *; omega) | simp_all) + obtain ⟨g1, hg1, hpush⟩ := push_itemG (msg := msg) (M := M) (st := st) (ss := ss) (rd := rd) + (gas := g0) (stack := EvmRules.Evm.iszero cond :: T') hd1 (by omega) + (by simp only [List.length_cons]; omega) + have hg1u := gas_le_of_hoareG hpush (by first | omega | (simp only [List.length_cons] at *; omega) | simp_all) + by_cases hc : cond = 0 + · -- The condition is zero: ISZERO gives one and the code jumps to the else block. + subst hc + have hoff := toNat_offset (G.target e hen hetgt).2.1 G.size_lt + have hj := Logic.jumpi_takenG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := rd) (destination := BitVec.ofNat 256 (c.offset e)) + (rest := T') hlt2 hcode2 (show 10 ≤ g1 by omega) iszero_zero + (by rw [hoff]; exact (G.target e hen hetgt).1) + rw [hoff] at hj + simp only [execC, List.length_cons, show ¬ S'.length + 1 + 1 > 1024 by omega, + show ¬ S'.length + 1 > 1024 by omega, ite_false, ite_true, SimOutC, SimOutB] + exact ⟨⟨by omega, fun _ => ⟨by omega, by omega⟩, Or.inr hetgt⟩, c.offset e, T', M, g1 - 10, st, + ss, Triple.seq hisz (Triple.seq hpush hj), SR.le hety hR', + I.targetT G hen hetgt (m := 3) (by omega) (by omega), R, by bud_tac⟩ + · -- The condition is not zero: ISZERO gives zero and the code falls into the next block. + have hj := Logic.jumpi_of_eq_zeroG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := rd) (destination := BitVec.ofNat 256 (c.offset e)) + (rest := T') hlt2 hcode2 (show 10 ≤ g1 by omega) (iszero_nonzero hc) + simp only [execC, List.length_cons, show ¬ S'.length + 1 + 1 > 1024 by omega, ite_false, + hc, SimOutC, SimOutB] + refine ⟨⟨by omega, fun _ => ⟨by omega, by omega⟩, by simp⟩, _, T', M, g1 - 10, st, ss, + Triple.seq hisz (Triple.seq hpush hj), SR.le hfty hR', + ⟨hseg, ?_, I.le_top, I.mem⟩, R, by bud_tac⟩ + have := I.gas + omega + | none => + by_cases hD : dropped p b i rest = true + · rcases dropped_true hD with ⟨rfl, rfl⟩ | ⟨rfl, rfl, hn⟩ + · -- A jump to the next block, left out: the code falls into it. + simp only [blockOkC, hT, hD, ite_true, fallOkL, Bool.and_eq_true, Bool.or_eq_true, + decide_eq_true_eq] at hok + simp only [lowerInstrs, hT, hD, ite_true, List.nil_append] at I + have hS := I.stack + simp only [execC, show ¬ S.length + 1 > 1024 by omega, ite_false, SimOutC, SimOutB] + exact ⟨⟨by omega, fun _ => ⟨by omega, by omega⟩, by simp⟩, pc, T, M, g, st, ss, + Triple.of_imp fun _ h => h, SR.le hok.1.2 hR, I.entry, R, by bud_tac⟩ + · -- The last block's STOP, left out: the code ends. + simp only [lowerInstrs, hT, hD, ite_true, List.nil_append] at I + have hseg := I.seg + rw [lowerFrom_nil p c (by omega)] at hseg + have hpc := hseg.nil_end + simp only [execC, SimOutC, SimOutB] + exact SpecG.consequence (stop_of_size_leG (by omega)) + (fun _ h => h) fun evm h => postL_stop R hself evm h + have hD' : dropped p b i rest = false := by simpa using hD + by_cases hG : isGasI i = true + · obtain rfl := isGasI_eq hG + simp only [execC, cutEffect, ite_true, SimOutC] + exact ⟨rfl, h, known, ty, k, pc, T, M, g, st, ss, Triple.of_imp fun _ h => h, + hok, hh, hu, hk, hR, I, R, by bud_tac⟩ + have hG' : isGasI i = false := by simpa using hG + by_cases hMc : isMemCutI i = true + · rw [execC_cut hMc] + simp only [SimOutC] + exact ⟨by simp [isCutI, hMc], h, known, ty, k, pc, T, M, g, st, ss, Triple.of_imp fun _ h => h, + hok, hh, hu, hk, hR, I, R, Hb⟩ + have hMc' : isMemCutI i = false := by simpa using hMc + simp only [isMemCutI, Bool.or_eq_false_iff] at hMc' + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨hnl, hns⟩, hnr⟩, hnv⟩, hnk⟩, hnlog⟩, hncd⟩, hnsc⟩, hnrds⟩, hnrdc⟩, hncall⟩, hnc2⟩, + hncc⟩ := hMc' + by_cases hDup : isCcDup i rest = true + · -- The DUP of a CODECOPY's destination over the code offset the check knows: the block stops at + -- the CODECOPY, with that offset second on the stack. + obtain ⟨j, rest', rfl, rfl⟩ : ∃ j rest', i = .op (.stack (.dup j)) ∧ + rest = .effect .codecopy 3 :: rest' := by + unfold isCcDup at hDup + split at hDup + · exact ⟨_, _, rfl, rfl⟩ + · cases hDup + obtain _ | ⟨o, known0⟩ := known + · simp [blockOkC, hT, hD', hG', hnl, hns, hnr, hnv, hnk, hnlog, hncd, hnsc, hnrds, hnrdc, hncall, + hnc2, hncc, isCcDup] at hok + obtain _ | off := o + · simp [blockOkC, hT, hD', hG', hnl, hns, hnr, hnv, hnk, hnlog, hncd, hnsc, hnrds, hnrdc, hncall, + hnc2, hncc, isCcDup] at hok + have e : blockOkC p c mx b h (some off :: known0) ty k + (.op (.stack (.dup j)) :: .effect .codecopy 3 :: rest') = (c.calls && c.creates && + blockStepL p c mx b (fun h _ ty k => blockOkC p c mx b h [some 0, some off] ty k + (.effect .codecopy 3 :: rest')) h (some off :: known0) ty k (.op (.stack (.dup j)))) := by + simp only [blockOkC, hT, hD', hG', hnl, hns, hnr, hnv, hnk, hnlog, hncd, hnsc, hnrds, hnrdc, + hncall, hnc2, hncc, isCcDup, Bool.or_false, Bool.false_eq_true, ite_false, ite_true] + rw [e] at hok + have hokd := ((Bool.and_eq_true _ _).mp hok).2 + have I' : InvL c code call (lowerInstr (.op (.stack (.dup j))) ++ + (lowerInstrs p c b (.effect .codecopy 3 :: rest') ++ + lowerFrom p c (b + 1) (p.blocks.drop (b + 1)))) k Rv pc S s M g := by + simpa only [lowerInstrs, hT, hD', Bool.false_eq_true, ite_false, List.append_assoc] using I + have hne : ∀ v, SolarTV.EVM.Op.dup j ≠ .push v := fun v h => by cases h + obtain ⟨hk1, byte, hbyte, h', ty', S', T', hstep, hstepT, hR', hh', hlen', hlock, known', hkn, + hokn⟩ := stack_simL (ctx := context o call s) hne hokd hh hk hR + rw [lowerInstr_stack hne, hbyte] at I' + simp only [Option.getD_some, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rw [← hctx] at hstepT + have hS := I'.stack; have hG := I'.gas + obtain ⟨g1, hg1, hrule⟩ := stack_ruleG (M := M) (st := st) (ss := ss) (rd := rd) (gas := g) + (stack := T) hbyte hlt hcode hstepT (by omega) (by omega) + have hg1u := gas_le_of_hoareG hrule + (by first | omega | (simp only [List.length_cons] at *; omega) | simp_all) + rw [execC_stack hstep (by omega) (by omega), execC_cut (show isMemCutI (.effect .codecopy 3) = true by rfl)] + refine SimOutC.pre hrule ?_ + obtain ⟨x, hx⟩ := ccDup_prefix hk hstep + exact ⟨rfl, h', [some x, some off], ty', k - 1, _, T', M, g1, st, ss, Triple.of_imp fun _ h => h, + by rw [blockOkC_cc_known x 0 off]; exact hokn, hh', by omega, hx, hR', + I'.next hk1 hseg (by omega) (by omega), R, by bud_tac⟩ + have hDup' : isCcDup i rest = false := by simpa using hDup + have hok' : blockStepL p c mx b (fun h known ty k => blockOkC p c mx b h known ty k rest) h known ty k i = + true := by + simpa only [blockOkC, hT, hD', hG', hnl, hns, hnr, hnv, hnk, hnlog, hncd, hnsc, hnrds, hnrdc, + hncall, hnc2, hncc, hDup', Bool.and_false, Bool.or_false, Bool.false_eq_true, ite_false] using hok + have I' : InvL c code call (lowerInstr i ++ (lowerInstrs p c b rest ++ + lowerFrom p c (b + 1) (p.blocks.drop (b + 1)))) k Rv pc S s M g := by + simpa only [lowerInstrs, hT, hD', Bool.false_eq_true, ite_false, List.append_assoc] using I + clear hok hD hD' hT + have IH := exec_simC (mx := mx) (o := o) (ss0 := ss0) G hdata hvalue hstatic hself hcaller ho hbenv htx he b hb Rv Gs rd rest + rcases i with mop | ⟨e, ar⟩ | t | t | t | _ | _ | _ | _ | _ | _ | _ + · rcases mop with sop | _ | _ | _ | _ | _ | _ + · by_cases hpush : ∃ v, sop = .push v + · obtain ⟨v, rfl⟩ := hpush + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + have hS := I'.stack; have hG := I'.gas + obtain ⟨g1, hg1, hpush⟩ := push_itemG (msg := msg) (M := M) (st := st) (ss := ss) (rd := rd) (gas := g) + (stack := T) hd (by omega) (by omega) + have hg1u := gas_le_of_hoareG hpush (by first | omega | (simp only [List.length_cons] at *; omega) | simp_all) + have hv : BitVec.ofNat 256 v.toNat = v := by simp + rw [hv] at hpush + rw [execC_stack (next := v :: S) rfl (by omega) (by simp; omega)] + exact SimOutC.pre hpush (IH (h + 1) (some v :: known) _ (v :: S) (v :: T) (k - 1) s next M g1 + st ss hok'.2 (by simp; omega) (by hu_tac) + (hk.cons_some v) + (SR.cons (τ := some false) rfl hR) (I'.next hok'.1 hseg (by simp) (by omega)) R (by bud_tac)) + · have hne : ∀ v, sop ≠ .push v := fun v he => hpush ⟨v, he⟩ + obtain ⟨hk1, byte, hbyte, h', ty', S', T', hstep, hstepT, hR', hh', hlen', hlock, known', hkn, + hok⟩ := stack_simL (ctx := context o call s) hne hok' hh hk hR + rw [lowerInstr_stack hne, hbyte] at I' + simp only [Option.getD_some, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rw [← hctx] at hstepT + have hS := I'.stack; have hG := I'.gas + obtain ⟨g1, hg1, hrule⟩ := stack_ruleG (M := M) (st := st) (ss := ss) (rd := rd) (gas := g) + (stack := T) hbyte hlt hcode hstepT (by omega) (by omega) + have hg1u := gas_le_of_hoareG hrule (by first | omega | (simp only [List.length_cons] at *; omega) | simp_all) + rw [execC_stack hstep (by omega) (by omega)] + exact SimOutC.pre hrule (IH h' known' ty' S' T' (k - 1) s (pc + 1) M g1 st ss hok (by omega) (by hu_tac) + hkn hR' (I'.next hk1 hseg (by omega) (by omega)) R (by bud_tac)) + · -- MLOAD, at the frame's own gas. + simp [isLoadI] at hnl + · -- MSTORE, at the frame's own gas. + simp [isStoreI] at hns + · simp [blockStepL] at hok' + · simp [blockStepL] at hok' + · simp [blockStepL] at hok' + · simp [blockStepL] at hok' + · rcases e with _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | n | _ | name | _ + all_goals try (simp [blockStepL] at hok'; done) + · -- SLOAD. + rcases ar with _ | _ | ar + · simp [blockStepL] at hok' + rotate_left + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨hk1, h1⟩, hdat⟩, hok⟩ := hok' + rcases S with _ | ⟨x, S'⟩ + · simp at hh; omega + rcases T with _ | ⟨x', T'⟩ + · simp at hL + obtain rfl := (SR.head hR hdat).symm + have hR' := (SR.uncons.1 hR).2 + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hG hh hL hu + rw [execC_effect1 rfl (w := s.storage x) rfl (by omega)] + have hrule := Logic.sloadG (message := msg) (memory := M) (state := st) (substate := ss) + (returnData := rd) (key := x) (rest := T') (gas := g) (by decide) hlt hcode rfl + (by split <;> omega) + rw [R.storage x] at hrule + refine SimOutC.pre hrule ?_ + have hreads := fun k : Word => State.TransactionState.recordStorageRead_reads st + msg.currentTarget msg.currentTarget (U256.toBeBytes x) (U256.toBeBytes k) default + refine IH h [] _ _ _ (k - 1) s (pc + 1) M _ _ _ hok (by simp; omega) (by hu_tac) ((KR.nil _)) + (SR.cons (τ := some false) rfl (by simpa using hR')) (I'.next hk1 hseg (by simp) (by split <;> omega)) + ⟨fun k => ?_, ?_, R.logs⟩ (by bud_tac) + · rw [(hreads k).2.1] + exact R.storage k + · rw [(hreads x).1] + exact R.account + · -- SSTORE. + rcases ar with _ | _ | _ | ar + · simp [blockStepL] at hok' + · simp [blockStepL] at hok' + rotate_left + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨hk1, h2⟩, hdat⟩, hok⟩ := hok' + rcases S with _ | ⟨x, _ | ⟨v, S'⟩⟩ + · simp at hh; omega + · simp at hh; omega + rcases T with _ | ⟨x', _ | ⟨v', T'⟩⟩ + · simp at hL + · simp at hL + have htake := hR.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR' : SR c (ty.drop 2) S' T' := by simpa using SR.drop 2 hR + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hG hh hL hu + rw [execC_effect2 rfl (s' := { s with storage := SolarTV.Machine.update s.storage x v }) rfl + (by omega)] + have hcost := sstoreCost_le (st.getStorageOriginal msg.currentTarget (U256.toBeBytes x)) + (st.getStorage msg.currentTarget (U256.toBeBytes x)) v + (decide (U256.toBeBytes x ∉ ss.accessedStorageKeys.getD msg.currentTarget ∅)) + obtain ⟨st', hnew, hothers, -, hacc, -, -, hrule⟩ := sstore_of_accountG + (message := msg) (memory := M) (state := st) (substate := ss) (returnData := rd) + (key := x) (new := v) (rest := T') (gas := g) (by decide) (by decide) hlt hcode hstatic + rfl (by simp only [CALL_STIPEND]; omega) (by omega) R.account + refine SimOutC.pre hrule ?_ + refine IH (h - 2) [] _ S' T' (k - 1) _ (pc + 1) M _ _ _ hok (by omega) (by hu_tac) ((KR.nil _)) + hR' ?_ ⟨fun k => ?_, by rw [hacc]; exact R.account, R.logs⟩ (by bud_tac) + · exact ⟨hseg, by omega, by omega, I'.le_top, I'.mem⟩ + by_cases hk : k = x + · subst hk + rw [hnew] + simp [SolarTV.Machine.update] + · rw [hothers _ _ (Or.inr fun he => hk (U256.toBeBytes_inj he)), R.storage k] + simp [SolarTV.Machine.update, hk] + · -- CALLDATALOAD. + rcases ar with _ | _ | ar + · simp [blockStepL] at hok' + rotate_left + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨hk1, h1⟩, hdat⟩, hok⟩ := hok' + rcases S with _ | ⟨x, S'⟩ + · simp at hh; omega + rcases T with _ | ⟨x', T'⟩ + · simp at hL + obtain rfl := (SR.head hR hdat).symm + have hR' := (SR.uncons.1 hR).2 + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hG hh hL hu + rw [execC_effect1 rfl (w := SolarTV.Machine.calldataWord call x) rfl (by omega)] + have hrule := Logic.calldataloadG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := rd) (start := x) (rest := T') (gas := g) hlt hcode + (by omega) + rw [hdata, ← calldataWord_eq] at hrule + exact SimOutC.pre hrule (IH h _ _ _ _ (k - 1) s (pc + 1) M (g - 3) st ss hok (by simp; omega) (by hu_tac) + ((hk.drop 1).cons_none _) (SR.cons (τ := some false) rfl (by simpa using hR')) (I'.next hk1 hseg (by simp) (by omega)) R (by bud_tac)) + · -- CALLDATASIZE. + rcases ar with _ | ar + rotate_left + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨hk1, hok⟩ := hok' + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + rw [execC_effect0 rfl (w := BitVec.ofNat 256 call.calldata.size) rfl (by omega)] + have hrule := Logic.calldatasizeG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := rd) (stack := T) (gas := g) hlt hcode (by omega) + (by unfold STACK_LIMIT; omega) + rw [hdata] at hrule + exact SimOutC.pre hrule (IH (h + 1) [] _ _ _ (k - 1) s (pc + 1) M (g - 2) st ss hok + (by simp; omega) (by hu_tac) ((KR.nil _)) (SR.cons (τ := some false) rfl hR) (I'.next hk1 hseg (by simp) (by omega)) R (by bud_tac)) + · -- CALLVALUE. + rcases ar with _ | ar + rotate_left + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨hk1, hok⟩ := hok' + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + rw [execC_effect0 rfl (w := BitVec.ofNat 256 call.callvalue) rfl (by omega)] + have hrule := Logic.callvalueG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := rd) (stack := T) (gas := g) hlt hcode (by omega) + (by unfold STACK_LIMIT; omega) + rw [hvalue] at hrule + exact SimOutC.pre hrule (IH (h + 1) [] _ _ _ (k - 1) s (pc + 1) M (g - 2) st ss hok + (by simp; omega) (by hu_tac) ((KR.nil _)) (SR.cons (τ := some false) rfl hR) (I'.next hk1 hseg (by simp) (by omega)) R (by bud_tac)) + · -- CALLER. + rcases ar with _ | ar + rotate_left + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨henv, hk1⟩, hok⟩ := hok' + obtain ⟨hoc, -⟩ := ho henv + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + rw [execC_effect0 rfl (w := o.caller.setWidth 256) rfl (by omega)] + have hrule := Logic.callerG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := rd) (stack := T) (gas := g) hlt hcode (by omega) + (by unfold STACK_LIMIT; omega) + rw [hcaller, ← hoc] at hrule + exact SimOutC.pre hrule (IH (h + 1) _ _ _ _ (k - 1) s (pc + 1) M (g - 2) st ss hok + (by simp; omega) (by hu_tac) (hk.cons_none _) (SR.cons (τ := some false) rfl hR) (I'.next hk1 hseg (by simp) (by omega)) R (by bud_tac)) + · -- ADDRESS. + rcases ar with _ | ar + rotate_left + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨hk1, hok⟩ := hok' + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + rw [execC_effect0 rfl (w := BitVec.ofNat 256 SolarTV.environment.callee) rfl (by omega)] + have hrule := Logic.addressG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := rd) (stack := T) (gas := g) hlt hcode (by omega) + (by unfold STACK_LIMIT; omega) + rw [hself, address_word] at hrule + exact SimOutC.pre hrule (IH (h + 1) [] _ _ _ (k - 1) s (pc + 1) M (g - 2) st ss hok + (by simp; omega) (by hu_tac) ((KR.nil _)) (SR.cons (τ := some false) rfl hR) (I'.next hk1 hseg (by simp) (by omega)) R (by bud_tac)) + · -- LOGn. + obtain _ | ⟨o, known'⟩ := known + · simp [blockStepL] at hok' + obtain _ | ow := o + · simp [blockStepL] at hok' + obtain _ | ⟨o2, known'⟩ := known' + · simp [blockStepL] at hok' + obtain _ | sw := o2 + · simp [blockStepL] at hok' + simp only [blockStepL, rangeOk, Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨⟨⟨⟨⟨hn4, rfl⟩, hk1⟩, hnh⟩, hdat⟩, hin⟩, hlc⟩, hok⟩ := hok' + simp [isLogI, hn4] at hnlog + · -- KECCAK256. + rcases ar with _ | _ | _ | ar + · simp [blockStepL] at hok' + · simp [blockStepL] at hok' + rotate_left + · simp [blockStepL] at hok' + simp [isKecI] at hnk + · -- An environment read of the block or the transaction. + rcases ar with _ | ar + rotate_left + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨hreads, hsome⟩, hk1⟩, hok⟩ := hok' + obtain ⟨⟨byte, w⟩, hread⟩ := Option.isSome_iff_exists.1 hsome + simp only [lowerInstr, hread, Option.map_some, Option.getD_some, + List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + rw [execC_effect0 rfl (w := BitVec.ofNat 256 w) + (by simp [SolarTV.Machine.Effect.apply, he hreads name byte w hread]) (by omega)] + have hrule := env_readG (msg := msg) (M := M) (st := st) (ss := ss) (rd := rd) (gas := g) + (stack := T) hread hlt hcode hbenv htx (by omega) (by unfold STACK_LIMIT; omega) + exact SimOutC.pre hrule (IH (h + 1) [] _ _ _ (k - 1) s (pc + 1) M (g - 2) st ss hok + (by simp; omega) (by hu_tac) ((KR.nil _)) (SR.cons (τ := some false) rfl hR) (I'.next hk1 hseg (by simp) (by omega)) R (by bud_tac)) + · -- JUMP. + simp only [blockStepL, jumpOkL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨hk2, ⟨⟨⟨⟨htn, htgt⟩, hneed⟩, hty⟩, hcost⟩⟩ := hok' + simp only [lowerInstr, List.cons_append, List.nil_append] at I' + obtain ⟨n1, hd1, hs1⟩ := I'.seg.head + obtain ⟨n2, hd2, -⟩ := hs1.head + simp only [Item.expected] at hd1 hd2 + obtain ⟨hlt2, hcode2, rfl⟩ := op_item hd2 + have hS := I'.stack; have hG := I'.gas + have hoff := toNat_offset (G.target t htn htgt).2.1 G.size_lt + obtain ⟨g1, hg1, hpush⟩ := push_itemG (msg := msg) (M := M) (st := st) (ss := ss) (rd := rd) (gas := g) + (stack := T) hd1 (by omega) (by omega) + have hg1u := gas_le_of_hoareG hpush (by first | omega | (simp only [List.length_cons] at *; omega) | simp_all) + have hj := Logic.jumpG (message := msg) (memory := M) (state := st) (substate := ss) + (returnData := rd) (rest := T) hlt2 hcode2 (show 8 ≤ g1 by omega) + (by rw [hoff]; exact (G.target t htn htgt).1) + rw [hoff] at hj + simp only [execC, show ¬ S.length + 1 > 1024 by omega, ite_false, SimOutC, SimOutB] + exact ⟨⟨by omega, fun _ => ⟨by omega, by omega⟩, Or.inr htgt⟩, c.offset t, T, M, g1 - 8, st, ss, + Triple.seq hpush hj, SR.le hty hR, + I'.targetT G htn htgt (m := 2) (by omega) (by omega), R, by bud_tac⟩ + · -- JUMPI. + simp only [blockStepL, jumpOkL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨⟨hk2, h1⟩, hdat⟩, ⟨⟨⟨⟨htn, htgt⟩, hneed⟩, hty⟩, hcost⟩⟩, hok'⟩ := hok' + rcases S with _ | ⟨cond, S'⟩ + · simp at hh; omega + rcases T with _ | ⟨cond', T'⟩ + · simp at hL + obtain rfl := (SR.head hR hdat).symm + have hR' := (SR.uncons.1 hR).2 + simp only [lowerInstr, List.cons_append, List.nil_append] at I' + obtain ⟨n1, hd1, hs1⟩ := I'.seg.head + obtain ⟨n2, hd2, hseg⟩ := hs1.head + simp only [Item.expected] at hd1 hd2 + obtain ⟨hlt2, hcode2, rfl⟩ := op_item hd2 + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hh hL hu + have hoff := toNat_offset (G.target t htn htgt).2.1 G.size_lt + obtain ⟨g1, hg1, hpush⟩ := push_itemG (msg := msg) (M := M) (st := st) (ss := ss) (rd := rd) (gas := g) + (stack := cond :: T') hd1 (by omega) (by simp; omega) + have hg1u := gas_le_of_hoareG hpush (by first | omega | (simp only [List.length_cons] at *; omega) | simp_all) + by_cases hc : cond = 0 + · subst hc + have hj := Logic.jumpi_of_eq_zeroG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := rd) (destination := BitVec.ofNat 256 (c.offset t)) + (rest := T') hlt2 hcode2 (show 10 ≤ g1 by omega) rfl + simp only [execC, List.length_cons, show ¬ S'.length + 1 + 1 > 1024 by omega, ite_false, + ite_true] + exact SimOutC.pre (Triple.seq hpush hj) (IH (h - 1) [] _ S' T' (k - 2) s (n1 + 1) M + (g1 - 10) st ss hok' (by omega) (by hu_tac) ((KR.nil _)) hR' + (I'.next2 hk2 hseg (by simp only [List.length_cons]; omega) (by omega)) R (by bud_tac)) + · have hj := Logic.jumpi_takenG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := rd) (destination := BitVec.ofNat 256 (c.offset t)) + (rest := T') hlt2 hcode2 (show 10 ≤ g1 by omega) hc + (by rw [hoff]; exact (G.target t htn htgt).1) + rw [hoff] at hj + simp only [execC, List.length_cons, show ¬ S'.length + 1 + 1 > 1024 by omega, ite_false, + hc, SimOutC, SimOutB] + exact ⟨⟨by omega, fun _ => ⟨by omega, by omega⟩, Or.inr htgt⟩, c.offset t, T', M, g1 - 10, st, + ss, Triple.seq hpush hj, SR.le hty hR', + I'.targetT G htn htgt (m := 2) (by omega) (by omega), R, by bud_tac⟩ + · -- A pushed return label: a PUSH of the block's offset. + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨hk1, hmem⟩, ht32⟩, hok⟩ := hok' + have hmem' : t ∈ c.rets := by simpa using hmem + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + have hS := I'.stack; have hG := I'.gas + obtain ⟨g1, hg1, hpush⟩ := push_itemG (msg := msg) (M := M) (st := st) (ss := ss) (rd := rd) (gas := g) + (stack := T) hd (by omega) (by omega) + have hg1u := gas_le_of_hoareG hpush (by first | omega | (simp only [List.length_cons] at *; omega) | simp_all) + have htn : (BitVec.ofNat 256 t).toNat = t := by + rw [BitVec.toNat_ofNat]; exact Nat.mod_eq_of_lt (by omega) + simp only [execC, show ¬ S.length + 1 > 1024 by omega, ite_false] + exact SimOutC.pre hpush (IH (h + 1) [] _ _ _ (k - 1) s next M g1 st ss hok (by simp; omega) (by hu_tac) + ((KR.nil _)) (SR.cons ⟨by rw [htn]; exact hmem', by rw [htn]⟩ hR) + (I'.next hk1 hseg (by simp) (by omega)) R (by bud_tac)) + · -- A dynamic jump to a return label: a JUMP to the label's offset. + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq, beq_iff_eq, + List.all_eq_true] at hok' + obtain ⟨⟨⟨hk1, h1⟩, hlab⟩, hall⟩ := hok' + rcases S with _ | ⟨x, S'⟩ + · simp at hh; omega + rcases T with _ | ⟨y, T'⟩ + · simp at hL + obtain ⟨hw, hR'⟩ := SR.uncons.1 hR + rw [hlab] at hw + obtain ⟨hmem, rfl⟩ := hw + have hj' := hall _ hmem + simp only [jumpOkL, Bool.and_eq_true, decide_eq_true_eq] at hj' + obtain ⟨⟨⟨⟨htn, htgt⟩, hneed⟩, hty⟩, hcost⟩ := hj' + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, -⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hh hL hu + have hoff := toNat_offset (G.target _ htn htgt).2.1 G.size_lt + have hj := Logic.jumpG (message := msg) (memory := M) (state := st) (substate := ss) + (returnData := rd) (destination := BitVec.ofNat 256 (c.offset x.toNat)) (rest := T') + hlt hcode (show 8 ≤ g by omega) (by rw [hoff]; exact (G.target _ htn htgt).1) + rw [hoff] at hj + simp only [execC, SimOutC, SimOutB] + exact ⟨⟨by omega, fun _ => ⟨by omega, by omega⟩, Or.inr htgt⟩, c.offset x.toNat, T', M, g - 8, st, + ss, hj, SR.le hty hR', I'.targetT G htn htgt (m := 1) (by omega) (by omega), R, by bud_tac⟩ + · -- A conditional dynamic jump and a jump table: outside the fragment. + simp [blockStepL] at hok' + · simp [blockStepL] at hok' + · -- STOP. + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, -⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + simp only [execC, SimOutC, SimOutB] + exact SpecG.consequence (Logic.stopG hlt hcode) (fun _ h => h) + fun evm h => postL_stop R hself evm h + · -- RETURN, at the frame's own gas. + simp [isRetI] at hnr + · -- REVERT, at the frame's own gas. + simp [isRevI] at hnv + · simp [blockStepL] at hok' + + + + +/-- info: 'SolidCore.Refinement.Solar.AssembleLoop.exec_simC' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms exec_simC + +end SolidCore.Refinement.Solar.AssembleLoop diff --git a/SolidCore/Refinement/Solar/AssembleDyn.lean b/SolidCore/Refinement/Solar/AssembleDyn.lean new file mode 100644 index 00000000..190eb86f --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleDyn.lean @@ -0,0 +1,476 @@ +import SolidCore.Refinement.Solar.AssembleCutSim + +/-! +# Memory at offsets the checker does not know + +SolarTV counts the active words of memory in `BitVec 251`, so growth to an offset `o` with +`o + size + 31 ≥ 2 ^ 256` wraps there and not in EthLib. A run that succeeds never grows memory that +far: every growth is paid for, and the price of memory and the gas left never exceed what the frame +holds at the start of a block plus a fixed reserve (`MemBudget`). With that reserve below `2 ^ 300`, the +price `3 w + w² / 512` of `w` words keeps `w` below `2 ^ 155` (`words_lt_of_cost`), far from the +wrap. + +* `budget_grow`: one paid growth of memory keeps the budget and bounds the range it grows to. +* `memRel_expandW`, `memRel_storeW`: `Assemble.memRel_expand` and `memRel_store` for any range whose + words SolarTV holds, without the `2 ^ 32` bound of the constant-offset checker. +* `mstore_back`, `mload_back`: MSTORE and MLOAD at the frame's own gas in a run that succeeds (the + frame had the gas for the growth), and `mstore_dyn`, `mload_dyn`: at any offset, SolarTV's + memory after them agrees with EthLib's and the budget holds, with no bound on the offset. +-/ + +namespace SolidCore.Refinement.Solar.AssembleDyn + +open SolarTV SolarTV.Machine SolidCore.Refinement +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleLoop +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +variable {rd : ByteArray} + +/-! ## Gas bounds memory -/ + +/-- **A paid growth of memory keeps the budget**: when the frame pays `pre` and the growth for a +nonempty range, the range's price is within the budget, and so are the grown memory's price and the +gas left. -/ +theorem budget_grow {size g G pre : Nat} (hmod : size % 32 = 0) {o sz : Word} (hz : sz ≠ 0) + (hb : memoryGasCost size + g ≤ G) (hg : pre + (extendMemory size [(o, sz)]).cost ≤ g) : + memoryGasCost (o.toNat + sz.toNat) ≤ G ∧ + memoryGasCost (size + (extendMemory size [(o, sz)]).expandBy) + + (g - (pre + (extendMemory size [(o, sz)]).cost)) ≤ G := by + by_cases h : size < o.toNat + sz.toNat + · rw [extendMemory_of_lt' hmod hz h] at hg ⊢ + simp only at hg ⊢ + have hup := le_ceil32 (o.toNat + sz.toNat) + have hc := memoryGasCost_ceil32 (o.toNat + sz.toNat) + have hm := memoryGasCost_mono (show size ≤ ceil32 (o.toNat + sz.toNat) by omega) + refine ⟨by omega, ?_⟩ + rw [show size + (ceil32 (o.toNat + sz.toNat) - size) = ceil32 (o.toNat + sz.toNat) by omega] + omega + · rw [extendMemory_of_le' (by omega)] at hg ⊢ + simp only at hg ⊢ + have := memoryGasCost_mono (show o.toNat + sz.toNat ≤ size by omega) + refine ⟨by omega, ?_⟩ + rw [Nat.add_zero] + omega + +/-! ## MSTORE and MLOAD at the frame's own gas -/ + +/-- **MSTORE in a run that succeeds**: the frame had the gas for it and its growth of memory, and +the run goes on from the frame after it. -/ +theorem mstore_back {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {o v : Word} + {T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {evm : Evm .fusaka Nat} (hat : At code msg pc (o :: v :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x52) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + 3 + (extendMemory M.size [(o, 32)]).cost ≤ g ∧ + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) T + (memoryWrite (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy) o.toNat + (wordBytes v)) + (g - (3 + (extendMemory M.size [(o, 32)]).cost)) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + by_cases hg : 3 + (extendMemory M.size [(o, 32)]).cost ≤ g + · obtain ⟨m, hr, hm⟩ := Logic.mstore (fork := .fusaka) hlt hbyte hg evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc (o :: v :: T) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .mstore := by + rw [hbyte] + exact ofByte_of_decode rfl (Fork.frontier_le _) + rw [step_of_instruction hlt decoded instruction_mstore, mstoreStep_cons hst] + have hc : GasMeter.charge e.gas (OPCODE_MSTORE_BASE + (extendMemory e.memory.size [(o, 32)]).cost) + = .error .outOfGas := by + rw [hgas, hmem, show OPCODE_MSTORE_BASE = 3 from rfl] + have hlt' : g < 3 + (extendMemory M.size [(o, 32)]).cost := Nat.lt_of_not_le hg + simp only [GasMeter.charge] + rw [ite_eq_left_of_eq_true _ _ (eq_true hlt')] + simp only [hc] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rw [hf.2.1] at hok + cases hok + +/-- **MLOAD in a run that succeeds**: the frame had the gas for it and its growth of memory, and +the run goes on from the frame after it. -/ +theorem mload_back {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {o : Word} + {T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {evm : Evm .fusaka Nat} (hat : At code msg pc (o :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x51) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + 3 + (extendMemory M.size [(o, 32)]).cost ≤ g ∧ + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) + (loadWord (memoryReadBytes + (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy) o.toNat 32) 0 32 :: T) + (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy) + (g - (3 + (extendMemory M.size [(o, 32)]).cost)) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + by_cases hg : 3 + (extendMemory M.size [(o, 32)]).cost ≤ g + · obtain ⟨m, hr, hm⟩ := Logic.mload (fork := .fusaka) hlt hbyte hg evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc (o :: T) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .mload := by + rw [hbyte] + exact ofByte_of_decode rfl (Fork.frontier_le _) + rw [step_of_instruction hlt decoded instruction_mload, mloadStep_cons hst] + have hc : GasMeter.charge e.gas (OPCODE_MLOAD_BASE + (extendMemory e.memory.size [(o, 32)]).cost) + = .error .outOfGas := by + rw [hgas, hmem, show OPCODE_MLOAD_BASE = 3 from rfl] + have hlt' : g < 3 + (extendMemory M.size [(o, 32)]).cost := Nat.lt_of_not_le hg + simp only [GasMeter.charge] + rw [ite_eq_left_of_eq_true _ _ (eq_true hlt')] + simp only [hc] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rw [hf.2.1] at hok + cases hok + +/-! ## RETURN and REVERT at the frame's own gas -/ + +/-- **RETURN in a run that succeeds**: the frame had the gas for the growth of memory to its +range. -/ +theorem return_back {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {o sz : Word} + {T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {rd : ByteArray} {evm : Evm .fusaka Nat} (hat : At code msg pc (o :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0xf3) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + (extendMemory M.size [(o, sz)]).cost ≤ g := by + refine Nat.le_of_not_lt fun hlt' => ?_ + have hspec : Spec .fusaka (At code msg pc (o :: sz :: T) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .«return» := by + rw [hbyte] + exact ofByte_of_decode rfl (Fork.frontier_le _) + rw [step_of_instruction hlt decoded instruction_return, returnStep_cons hst] + have hc : GasMeter.charge e.gas (extendMemory e.memory.size [(o, sz)]).cost = + .error .outOfGas := by + rw [hgas, hmem] + simp only [GasMeter.charge] + rw [ite_eq_left_of_eq_true _ _ (eq_true hlt')] + simp only [hc] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rw [hf.2.1] at hok + cases hok + +/-- **No run that succeeds reaches REVERT**: REVERT stops the frame with the revert error, or with +too little gas for its range, out of gas. -/ +theorem revert_false {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {o sz : Word} + {T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {rd : ByteArray} {evm : Evm .fusaka Nat} (hat : At code msg pc (o :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0xfd) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : False := by + by_cases hg : (extendMemory M.size [(o, sz)]).cost ≤ g + · have hspec := Logic.revertG (fork := .fusaka) (by decide) (message := msg) (state := st) + (substate := ss) (returnData := rd) (rest := T) hlt hbyte (show _ ≤ g + 0 by omega) + have hf := SpecG.low hspec (hat.addGas 0) within hrun hok + have h2 : fin.error = some .revert := by simpa [addGas] using hf.2.1 + rw [h2] at hok + cases hok + · have hspec : Spec .fusaka (At code msg pc (o :: sz :: T) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .revert := by + rw [hbyte] + exact ofByte_of_decode rfl (by decide) + rw [step_of_instruction hlt decoded (instruction_revert (by decide)), revertStep_eq, + returnStep_cons hst] + have hlt' : g < (extendMemory M.size [(o, sz)]).cost := Nat.lt_of_not_le hg + have hc : GasMeter.charge e.gas (extendMemory e.memory.size [(o, sz)]).cost = + .error .outOfGas := by + rw [hgas, hmem] + simp only [GasMeter.charge] + rw [ite_eq_left_of_eq_true _ _ (eq_true hlt')] + simp only [hc] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rw [hf.2.1] at hok + cases hok + +/-! ## KECCAK256 at the frame's own gas -/ + +/-- **KECCAK256 in a run that succeeds**: the frame had the gas for the hash and the growth of +memory to its range, and the run goes on from the frame after it. -/ +theorem keccak_back {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {o sz : Word} + {T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {evm : Evm .fusaka Nat} (hat : At code msg pc (o :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x20) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + keccak256Cost sz + (extendMemory M.size [(o, sz)]).cost ≤ g ∧ + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) + (keccak (memoryReadBytes (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + o.toNat sz.toNat) :: T) + (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + (g - (keccak256Cost sz + (extendMemory M.size [(o, sz)]).cost)) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + by_cases hg : keccak256Cost sz + (extendMemory M.size [(o, sz)]).cost ≤ g + · obtain ⟨m, hr, hm⟩ := Logic.keccak256 (fork := .fusaka) hlt hbyte hg evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc (o :: sz :: T) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .keccak256 := by + rw [hbyte] + exact ofByte_of_decode rfl (Fork.frontier_le _) + rw [step_of_instruction hlt decoded instruction_keccak256, keccak256Step_cons hst] + have hlt' : g < keccak256Cost sz + (extendMemory M.size [(o, sz)]).cost := Nat.lt_of_not_le hg + have hc : GasMeter.charge e.gas (keccak256Cost sz + + (extendMemory e.memory.size [(o, sz)]).cost) = .error .outOfGas := by + rw [hgas, hmem] + simp only [GasMeter.charge] + rw [ite_eq_left_of_eq_true _ _ (eq_true hlt')] + simp only [hc] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rw [hf.2.1] at hok + cases hok + +/-- **KECCAK256 of any range, in a run that succeeds**: with the budget below `2 ^ 300`, +SolarTV's growth agrees with EthLib's memory after it, the budget holds at the gas left, and the run +goes on. -/ +theorem keccak_dyn {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {o sz : Word} + {T : List Word} {M : ByteArray} {g G : Nat} {st : State.TransactionState} {ss : Substate} + {m0 : SolarTV.Machine.Mem} (hm : MemRel m0 M) (hb : MemBudget G M g) (hG : G < 2 ^ 300) + {evm : Evm .fusaka Nat} (hat : At code msg pc (o :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x20) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + MemRel (m0.expand o.toNat sz.toNat) (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) ∧ + MemBudget G (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + (g - (keccak256Cost sz + (extendMemory M.size [(o, sz)]).cost)) ∧ + At code msg (pc + 1) + (keccak (memoryReadBytes (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + o.toNat sz.toNat) :: T) + (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + (g - (keccak256Cost sz + (extendMemory M.size [(o, sz)]).cost)) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + obtain ⟨hg, m, within', hat', hrun'⟩ := keccak_back hat hlt hbyte within hrun hok + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have hbound : sz = 0 ∨ (o.toNat + sz.toNat + 31) / 32 < 2 ^ 251 := by + by_cases hz : sz = 0 + · exact .inl hz + · exact .inr (words_lt_of_cost (budget_grow hmod hz hb hg).1 hG) + refine ⟨m, within', memRel_expandW hm hbound, ?_, hat', hrun'⟩ + exact MemBudget.grow hmod hb hg (size_memoryExtend M _) + +/-! ## LOGn at the frame's own gas -/ + +/-- **LOGn in a run that succeeds**: the frame had the gas for the log and the growth of memory +to its range, and the run goes on from the frame after it, with the log appended. -/ +theorem log_back {n : Fin 5} {byte : UInt8} {code : ByteArray} {msg : Message .fusaka} {pc : Nat} + {o sz : Word} {words T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} + {ss : Substate} {evm : Evm .fusaka Nat} + (hat : At code msg pc (o :: sz :: (words ++ T)) M g st ss rd evm) + (hlen : words.length = n.val) (hlt : pc < code.size) (hbyte : code[pc] = byte) + (decoded : Op.decode byte = some (.log n)) (hstatic : msg.isStatic = false) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + logCost n.val sz + (extendMemory M.size [(o, sz)]).cost ≤ g ∧ + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) T (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + (g - (logCost n.val sz + (extendMemory M.size [(o, sz)]).cost)) st + { ss with + logs := ss.logs.push + { address := msg.currentTarget + topics := words.map U256.toBeBytes + data := memoryReadBytes (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + o.toNat sz.toNat } } rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + by_cases hg : logCost n.val sz + (extendMemory M.size [(o, sz)]).cost ≤ g + · obtain ⟨m, hr, hm⟩ := Logic.log (fork := .fusaka) hlen hlt hbyte decoded hstatic hg evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc (o :: sz :: (words ++ T)) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + have dec' : Op.ofByte .fusaka e.code[e.pc] = some (.log n) := by + rw [hbyte] + exact ofByte_of_decode decoded (Fork.frontier_le _) + rw [step_of_instruction hlt dec' (instruction_log n)] + have hl := e.stack.property + rw [hst] at hl + have hlr : (words ++ T).length ≤ STACK_LIMIT := by simp at hl ⊢; omega + have hs : e.stack = ⟨o :: sz :: (words ++ T), hst ▸ e.stack.property⟩ := Subtype.ext hst + have htop := popTopics_append (evm := { e with stack := ⟨words ++ T, hlr⟩ }) + (words := words) (rest := T) rfl + rw [hlen] at htop + have hlt' : e.gas < logCost n.val sz + (extendMemory e.memory.size [(o, sz)]).cost := by + rw [hgas, hmem] + omega + simp only [logStep, popWord, Stack.pop, hs, bind, Except.bind, pure, Except.pure] + rw [htop] + simp only [chargeGasAndMemory, chargeGas, GasMeter.charge, logCost] at hlt' ⊢ + simp [hlt'] + try rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rw [hf.2.1] at hok + cases hok + +/-- **LOGn of any range, in a run that succeeds**: with the budget below `2 ^ 300`, SolarTV's +growth agrees with EthLib's memory after it, the budget holds at the gas left, and the run goes on +with the log appended. -/ +theorem log_dyn {n : Fin 5} {byte : UInt8} {code : ByteArray} {msg : Message .fusaka} {pc : Nat} + {o sz : Word} {words T : List Word} {M : ByteArray} {g G : Nat} {st : State.TransactionState} + {ss : Substate} {m0 : SolarTV.Machine.Mem} (hm : MemRel m0 M) (hb : MemBudget G M g) + (hG : G < 2 ^ 300) {evm : Evm .fusaka Nat} + (hat : At code msg pc (o :: sz :: (words ++ T)) M g st ss rd evm) + (hlen : words.length = n.val) (hlt : pc < code.size) (hbyte : code[pc] = byte) + (decoded : Op.decode byte = some (.log n)) (hstatic : msg.isStatic = false) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + MemRel (m0.expand o.toNat sz.toNat) (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) ∧ + MemBudget G (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + (g - (logCost n.val sz + (extendMemory M.size [(o, sz)]).cost)) ∧ + At code msg (pc + 1) T (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + (g - (logCost n.val sz + (extendMemory M.size [(o, sz)]).cost)) st + { ss with + logs := ss.logs.push + { address := msg.currentTarget + topics := words.map U256.toBeBytes + data := memoryReadBytes (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + o.toNat sz.toNat } } rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + obtain ⟨hg, m, within', hat', hrun'⟩ := log_back hat hlen hlt hbyte decoded hstatic within hrun hok + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have hbound : sz = 0 ∨ (o.toNat + sz.toNat + 31) / 32 < 2 ^ 251 := by + by_cases hz : sz = 0 + · exact .inl hz + · exact .inr (words_lt_of_cost (budget_grow hmod hz hb hg).1 hG) + exact ⟨m, within', memRel_expandW hm hbound, MemBudget.grow hmod hb hg (size_memoryExtend M _), + hat', hrun'⟩ + +/-! ## At any offset -/ + +/-- **MSTORE at any offset, in a run that succeeds**: with the budget below `2 ^ 300`, SolarTV's +store agrees with EthLib's memory after it, the budget holds at the gas left, and the run goes on. -/ +theorem mstore_dyn {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {o v : Word} + {T : List Word} {M : ByteArray} {g G : Nat} {st : State.TransactionState} {ss : Substate} + {m0 : SolarTV.Machine.Mem} (hm : MemRel m0 M) (hb : MemBudget G M g) (hG : G < 2 ^ 300) + {evm : Evm .fusaka Nat} (hat : At code msg pc (o :: v :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x52) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + ∃ (M' : ByteArray) (g' : Nat) (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + MemRel (m0.store o.toNat v) M' ∧ MemBudget G M' g' ∧ g' ≤ g ∧ + At code msg (pc + 1) T M' g' st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + obtain ⟨hg, m, within', hat', hrun'⟩ := mstore_back hat hlt hbyte within hrun hok + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + obtain ⟨hc, hb'⟩ := budget_grow (pre := 3) hmod (o := o) (sz := 32) (by decide) hb hg + have h32 : (32 : Word).toNat = 32 := rfl + rw [h32] at hc + have hw := words_lt_of_cost hc hG + obtain ⟨hmem', -⟩ := memRel_storeW (v := v) hm hw + refine ⟨_, _, m, within', hmem', ?_, by omega, hat', hrun'⟩ + unfold MemBudget + rw [size_memoryWrite_of_fit, size_memoryExtend] + · exact hb' + · intro _ + rw [size_wordBytes, size_memoryExtend_extendMemory' hmod (by decide), h32] + have := le_ceil32 (o.toNat + 32) + omega + +/-- **MLOAD at any offset, in a run that succeeds**: EthLib pushes SolarTV's load, SolarTV's growth +agrees with EthLib's memory after it, the budget holds at the gas left, and the run goes on. -/ +theorem mload_dyn {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {o : Word} + {T : List Word} {M : ByteArray} {g G : Nat} {st : State.TransactionState} {ss : Substate} + {m0 : SolarTV.Machine.Mem} (hm : MemRel m0 M) (hb : MemBudget G M g) (hG : G < 2 ^ 300) + {evm : Evm .fusaka Nat} (hat : At code msg pc (o :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x51) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + ∃ (M' : ByteArray) (g' : Nat) (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + MemRel (m0.expand o.toNat 32) M' ∧ MemBudget G M' g' ∧ g' ≤ g ∧ + At code msg (pc + 1) (m0.load o.toNat :: T) M' g' st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + obtain ⟨hg, m, within', hat', hrun'⟩ := mload_back hat hlt hbyte within hrun hok + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + obtain ⟨hc, hb'⟩ := budget_grow (pre := 3) hmod (o := o) (sz := 32) (by decide) hb hg + have h32 : (32 : Word).toNat = 32 := rfl + rw [h32] at hc + have hw := words_lt_of_cost hc hG + have hmem' := memRel_expandW (o := o) (sz := 32) hm (.inr (by rw [h32]; exact hw)) + rw [h32] at hmem' + rw [load_eq hm] at hat' + refine ⟨_, _, m, within', hmem', ?_, by omega, hat', hrun'⟩ + unfold MemBudget + rw [size_memoryExtend] + exact hb' + +/-- info: 'SolidCore.Refinement.Solar.AssembleDyn.mstore_dyn' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms mstore_dyn + +/-- info: 'SolidCore.Refinement.Solar.AssembleDyn.mload_dyn' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms mload_dyn + +end SolidCore.Refinement.Solar.AssembleDyn diff --git a/SolidCore/Refinement/Solar/AssembleDynCopy.lean b/SolidCore/Refinement/Solar/AssembleDynCopy.lean new file mode 100644 index 00000000..aa3e11c4 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleDynCopy.lean @@ -0,0 +1,117 @@ +import SolidCore.Refinement.Solar.AssembleDyn +import SolidCore.Refinement.Solar.AssembleEffects + +/-! +# CALLDATACOPY of any range at the frame's own gas + +A run that succeeds paid for CALLDATACOPY's growth of memory (`cdc_back`), so with the budget of +`AssembleDyn` SolarTV's copy agrees with EthLib's at any destination and size (`cdc_dyn`): the +calldata-sized copies of ABI decoding. +-/ + +namespace SolidCore.Refinement.Solar.AssembleDynCopy + +open SolarTV SolarTV.Machine SolidCore.Refinement +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleDyn SolidCore.Refinement.Solar.AssembleEffects +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +variable {rd : ByteArray} + +/-- **CALLDATACOPY in a run that succeeds**: the frame had the gas for the copy and the growth of +memory, and the run goes on from the frame after it. -/ +theorem cdc_back {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {d off sz : Word} + {T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {evm : Evm .fusaka Nat} (hat : At code msg pc (d :: off :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x37) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + 3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost ≤ g ∧ + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) T + (memoryWrite (memoryExtend M (extendMemory M.size [(d, sz)]).expandBy) + d.toNat ⟨(bufferRead msg.data off.toNat sz.toNat).toArray⟩) + (g - (3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost)) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + by_cases hg : 3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost ≤ g + · obtain ⟨m, hr, hm⟩ := Logic.calldatacopy (fork := .fusaka) hlt hbyte hg evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc (d :: off :: sz :: T) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .calldatacopy := by + rw [hbyte] + exact ofByte_of_decode rfl (Fork.frontier_le _) + rw [step_of_instruction hlt decoded instruction_calldatacopy] + rw [copyToMemory_cons hst] + have hlt' : g < 3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost := + Nat.lt_of_not_le hg + have hc : GasMeter.charge e.gas (OPCODE_CALLDATACOPY_BASE + OPCODE_COPY_PER_WORD * + wordCount sz.toNat + (extendMemory e.memory.size [(d, sz)]).cost) = .error .outOfGas := by + rw [hgas, hmem, show OPCODE_CALLDATACOPY_BASE = 3 from rfl, + show OPCODE_COPY_PER_WORD = 3 from rfl] + simp only [GasMeter.charge] + rw [ite_eq_left_of_eq_true _ _ (eq_true hlt')] + simp only [hc] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rw [hf.2.1] at hok + cases hok + +/-- **CALLDATACOPY of any range, in a run that succeeds**: with the budget below `2 ^ 300`, +SolarTV's copy agrees with EthLib's memory after it, the budget holds at the gas left, and the run +goes on. -/ +theorem cdc_dyn {code : ByteArray} {msg : Message .fusaka} {call : Call} (hdata : msg.data = call.calldata) + {pc : Nat} {d off sz : Word} {T : List Word} {M : ByteArray} {g G : Nat} + {st : State.TransactionState} {ss : Substate} {m0 : SolarTV.Machine.Mem} (hm : MemRel m0 M) + (hb : MemBudget G M g) (hG : G < 2 ^ 300) {evm : Evm .fusaka Nat} + (hat : At code msg pc (d :: off :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x37) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : fin.error = none) : + ∃ (M' : ByteArray) (g' : Nat) (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + MemRel (m0.write d.toNat sz.toNat (fun i => calldataByte call (off.toNat + i))) M' ∧ + MemBudget G M' g' ∧ g' ≤ g ∧ At code msg (pc + 1) T M' g' st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + obtain ⟨hg, m, within', hat', hrun'⟩ := cdc_back hat hlt hbyte within hrun hok + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have hbound : sz = 0 ∨ (d.toNat + sz.toNat + 31) / 32 < 2 ^ 251 := by + by_cases hz : sz = 0 + · exact .inl hz + · exact .inr (words_lt_of_cost (budget_grow hmod hz hb hg).1 hG) + have hfit : sz.toNat ≠ 0 → + d.toNat + sz.toNat ≤ (memoryExtend M (extendMemory M.size [(d, sz)]).expandBy).size := by + intro hz + have hz' : sz ≠ 0 := fun h => hz (by simp [h]) + rw [size_memoryExtend_extendMemory' hmod hz'] + have := le_ceil32 (d.toNat + sz.toNat) + omega + refine ⟨_, _, m, within', ?_, ?_, by omega, hat', hrun'⟩ + · have he := memRel_expandW hm hbound + rw [← write_expand] + refine memRel_write he hfit (size_bufferRead _ _ _) (fun i hi => ?_) + rw [byteAt_bufferRead, ite_cond_eq_true _ _ (eq_true hi), hdata, calldataByte_eq] + · refine MemBudget.grow hmod hb hg ?_ + rw [size_memoryWrite_of_fit, size_memoryExtend] + intro h + rw [size_bufferRead] at h ⊢ + exact hfit h + +/-- info: 'SolidCore.Refinement.Solar.AssembleDynCopy.cdc_dyn' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms cdc_dyn + +end SolidCore.Refinement.Solar.AssembleDynCopy diff --git a/SolidCore/Refinement/Solar/AssembleDynExample.lean b/SolidCore/Refinement/Solar/AssembleDynExample.lean new file mode 100644 index 00000000..13d3b776 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleDynExample.lean @@ -0,0 +1,175 @@ +import SolidCore.Refinement.Solar.AssembleCut + +/-! +# Memory at an offset the call chooses: an example and a mutant + +A program that loads the word at the memory offset the first word of the call data names, stores +it at offset 0 and returns it. The offset is anything the caller sends, so no bound on it is known +when checking; the checker with GAS accepts the bytecode with a certificate whose memory bound is +`2 ^ 140` bytes, and at every gas below `2 ^ 256` every result of the bytecode is the program's: +a run that succeeds paid for the growth of memory, which keeps it within SolarTV's count of words. +The bytecode with SLOAD in place of MLOAD is rejected by evaluation, and so is the program under a +certificate whose memory bound is too small. +-/ + +namespace SolidCore.Refinement.Solar.AssembleDynExample + +open SolidCore.Refinement.Solar SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCut SolidCore.Refinement.Final + +/-- PUSH0, CALLDATALOAD, MLOAD, then the word stored at offset 0 and returned. -/ +def prog : Assemble.Program := + { blocks := [[.op (.stack (.push 0)), .effect .calldataload 1, .op .load, .op (.stack (.push 0)), + .op .store, .op (.stack (.push 32)), .op (.stack (.push 0)), .ret]] } + +/-- PUSH0 CALLDATALOAD MLOAD PUSH0 MSTORE PUSH1 32 PUSH0 RETURN. -/ +def code : ByteArray := ⟨#[0x5f, 0x35, 0x51, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3]⟩ + +/-- The same code with SLOAD (0x54) in place of MLOAD. -/ +def mutant : ByteArray := ⟨#[0x5f, 0x35, 0x54, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3]⟩ + +def cert : Assemble.Cert := + { offsets := [0], needs := [0], top := 2 ^ 140, costs := [8], types := [[]] } + +def maxs : List Nat := [0] + +theorem check_ok : checkC prog code cert maxs = true := by decide +kernel + +/-- The mutant fails the check by evaluation. -/ +theorem mutant_fails : checkC prog mutant cert maxs = false := by decide +kernel + +/-- A memory bound below `2 ^ 140` does not cover loads at offsets the checker does not know. -/ +theorem small_top_fails : checkC prog code { cert with top := 2 ^ 32 } maxs = false := by + decide +kernel + +/-- **At every gas below `2 ^ 256`, every result of the bytecode is the program's**, under the +oracle of the run's table. -/ +theorem bytecode (scope : SolarTV.Call → Prop) : + WithinRunLt SolarTV.evmirSem (fun _ => prog) code scope (RunOracle.CertOk cert) := + withinRun_of_checkC check_ok scope + +/-- info: 'SolidCore.Refinement.Solar.AssembleDynExample.bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecode + +/-- The range the call names, returned: PUSH0 CALLDATALOAD (the size) PUSH1 32 CALLDATALOAD (the +offset) RETURN. -/ +def progRet : Assemble.Program := + { blocks := [[.op (.stack (.push 0)), .effect .calldataload 1, .op (.stack (.push 32)), + .effect .calldataload 1, .ret]] } + +def codeRet : ByteArray := ⟨#[0x5f, 0x35, 0x60, 0x20, 0x35, 0xf3]⟩ + +/-- The same code with REVERT (0xfd) in place of RETURN. -/ +def mutantRet : ByteArray := ⟨#[0x5f, 0x35, 0x60, 0x20, 0x35, 0xfd]⟩ + +def certRet : Assemble.Cert := + { offsets := [0], needs := [0], top := 2 ^ 140, costs := [5], types := [[]] } + +theorem checkRet_ok : checkC progRet codeRet certRet maxs = true := by decide +kernel + +theorem mutantRet_fails : checkC progRet mutantRet certRet maxs = false := by decide +kernel + +/-- **RETURN of any range the call names**: at every gas below `2 ^ 256`, every result of the +bytecode is the program's. -/ +theorem bytecodeRet (scope : SolarTV.Call → Prop) : + WithinRunLt SolarTV.evmirSem (fun _ => progRet) codeRet scope (RunOracle.CertOk certRet) := + withinRun_of_checkC checkRet_ok scope + +/-- info: 'SolidCore.Refinement.Solar.AssembleDynExample.bytecodeRet' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecodeRet + +/-- The hash of the range the call names, returned: PUSH0 CALLDATALOAD (the size) PUSH1 32 +CALLDATALOAD (the offset) KECCAK256, then the word stored at offset 0 and returned. -/ +def progKec : Assemble.Program := + { blocks := [[.op (.stack (.push 0)), .effect .calldataload 1, .op (.stack (.push 32)), + .effect .calldataload 1, .effect .keccak256 2, .op (.stack (.push 0)), .op .store, + .op (.stack (.push 32)), .op (.stack (.push 0)), .ret]] } + +def codeKec : ByteArray := + ⟨#[0x5f, 0x35, 0x60, 0x20, 0x35, 0x20, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3]⟩ + +/-- The same code with SWAP1 before KECCAK256, which hashes another range. -/ +def mutantKec : ByteArray := + ⟨#[0x5f, 0x35, 0x60, 0x20, 0x35, 0x90, 0x20, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3]⟩ + +def certKec : Assemble.Cert := + { offsets := [0], needs := [0], top := 2 ^ 140, costs := [10], types := [[]], env := true } + +theorem checkKec_ok : checkC progKec codeKec certKec maxs = true := by decide +kernel + +theorem mutantKec_fails : checkC progKec mutantKec certKec maxs = false := by decide +kernel + +/-- Without the flag that states EthLib's hash, the checker rejects KECCAK256. -/ +theorem unflaggedKec_fails : checkC progKec codeKec { certKec with env := false } maxs = false := by + decide +kernel + +/-- **KECCAK256 of any range the call names**: at every gas below `2 ^ 256`, every result of +the bytecode is the program's under the oracle of the run's table, whose hash is EthLib's. -/ +theorem bytecodeKec (scope : SolarTV.Call → Prop) : + WithinRunLt SolarTV.evmirSem (fun _ => progKec) codeKec scope (RunOracle.CertOk certKec) := + withinRun_of_checkC checkKec_ok scope + +/-- info: 'SolidCore.Refinement.Solar.AssembleDynExample.bytecodeKec' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecodeKec + +/-- An event whose data is the range the call names: PUSH0 CALLDATALOAD (the size) PUSH1 32 +CALLDATALOAD (the offset) LOG0, then an empty RETURN. -/ +def progLog : Assemble.Program := + { blocks := [[.op (.stack (.push 0)), .effect .calldataload 1, .op (.stack (.push 32)), + .effect .calldataload 1, .effect (.log 0) 2, .op (.stack (.push 0)), .op (.stack (.push 0)), + .ret]] } + +def codeLog : ByteArray := ⟨#[0x5f, 0x35, 0x60, 0x20, 0x35, 0xa0, 0x5f, 0x5f, 0xf3]⟩ + +/-- The same code with LOG1 (0xa1) in place of LOG0. -/ +def mutantLog : ByteArray := ⟨#[0x5f, 0x35, 0x60, 0x20, 0x35, 0xa1, 0x5f, 0x5f, 0xf3]⟩ + +def certLog : Assemble.Cert := + { offsets := [0], needs := [0], top := 2 ^ 140, costs := [8], types := [[]] } + +theorem checkLog_ok : checkC progLog codeLog certLog maxs = true := by decide +kernel + +theorem mutantLog_fails : checkC progLog mutantLog certLog maxs = false := by decide +kernel + +/-- **An event with data of any range the call names**: at every gas below `2 ^ 256`, every +result of the bytecode, its logs included, is the program's. -/ +theorem bytecodeLog (scope : SolarTV.Call → Prop) : + WithinRunLt SolarTV.evmirSem (fun _ => progLog) codeLog scope (RunOracle.CertOk certLog) := + withinRun_of_checkC checkLog_ok scope + +/-- info: 'SolidCore.Refinement.Solar.AssembleDynExample.bytecodeLog' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecodeLog + +/-- The call data echoed: CALLDATASIZE PUSH0 PUSH0 CALLDATACOPY copies all of it to offset 0, +then CALLDATASIZE PUSH0 RETURN returns it. -/ +def progCdc : Assemble.Program := + { blocks := [[.effect .calldatasize 0, .op (.stack (.push 0)), .op (.stack (.push 0)), + .effect .calldatacopy 3, .effect .calldatasize 0, .op (.stack (.push 0)), .ret]] } + +def codeCdc : ByteArray := ⟨#[0x36, 0x5f, 0x5f, 0x37, 0x36, 0x5f, 0xf3]⟩ + +/-- The same code with CODECOPY (0x39) in place of CALLDATACOPY. -/ +def mutantCdc : ByteArray := ⟨#[0x36, 0x5f, 0x5f, 0x39, 0x36, 0x5f, 0xf3]⟩ + +def certCdc : Assemble.Cert := + { offsets := [0], needs := [0], top := 2 ^ 140, costs := [7], types := [[]] } + +theorem checkCdc_ok : checkC progCdc codeCdc certCdc maxs = true := by decide +kernel + +theorem mutantCdc_fails : checkC progCdc mutantCdc certCdc maxs = false := by decide +kernel + +/-- **A copy of the call data of any size**: at every gas below `2 ^ 256`, every result of the +bytecode is the program's. -/ +theorem bytecodeCdc (scope : SolarTV.Call → Prop) : + WithinRunLt SolarTV.evmirSem (fun _ => progCdc) codeCdc scope (RunOracle.CertOk certCdc) := + withinRun_of_checkC checkCdc_ok scope + +/-- info: 'SolidCore.Refinement.Solar.AssembleDynExample.bytecodeCdc' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecodeCdc + +end SolidCore.Refinement.Solar.AssembleDynExample diff --git a/SolidCore/Refinement/Solar/AssembleEffects.lean b/SolidCore/Refinement/Solar/AssembleEffects.lean new file mode 100644 index 00000000..437d3256 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleEffects.lean @@ -0,0 +1,407 @@ +import SolidCore.Refinement.Solar.RunOracle +import EthLib.Execution.Proofs.Evm.Logic.Copy +import EthLib.Execution.Proofs.Evm.Logic.Call +import EthLib.Execution.Proofs.Evm.Logic.Known + +/-! +# EVM IR to bytecode: the instructions of a run's oracle + +What each instruction that reads what the oracle of a run answers (GAS, RETURNDATASIZE, +RETURNDATACOPY) or that copies a range of dynamic size (CALLDATACOPY, RETURNDATACOPY) does in +SolarTV and in EthLib, one instruction at a time: EthLib's rule, SolarTV's effect, and that the +relations of the simulation hold after both. + +* `MemRel` after a write of a range (`memRel_write`) and after the growth of memory for two ranges + at once, as a call grows it (`memRel_expand2`). +* `RdRel o w rd`: EthLib's return data `rd` is the oracle's for SolarTV's world `w`. The oracle of a + run meets it for the table's return data (`rdRel_table`); a log or a GAS read keeps it. +* GAS (`gas_step`) pushes EthLib's gas left when the oracle answers it, which the oracle of a run + does for the `k`-th read with the table's `k`-th gas (`gas_step_table`). GAS is not monotone in gas, so + its rule is a plain `Hoare` triple, not `HoareG`. +* RETURNDATASIZE (`returndatasize_step`), RETURNDATACOPY within the return data + (`returndatacopy_step`; past its end SolarTV's effect is undefined, `returndatacopy_past`), + CALLDATACOPY of any size (`calldatacopy_step`). +* STATICCALL (`staticcall_step`), from EthLib's `Logic.staticcallWith` under every frame that ends the + message: the flag, the stack, memory with the callee's output written and the return data are + SolarTV's under an oracle that answers the call's success and output as the callee ended, which + the oracle of a run does with the callee's frame as the table's next entry (`staticcall_table`). +-/ + +namespace SolidCore.Refinement.Solar.AssembleEffects + +open SolarTV SolarTV.Machine +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.RunOracle +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts + +/-! ## Memory -/ + +/-- A write of a range that memory already holds keeps the relation of the memories. -/ +theorem memRel_write {m : Mem} {M B : ByteArray} {o n : Nat} {src : Nat → Memory.Byte} + (hm : MemRel m M) (hfit : n ≠ 0 → o + n ≤ M.size) (hB : B.size = n) + (hsrc : ∀ i, i < n → (byteAt B i).toBitVec = src i) : + MemRel (m.write o n src) (memoryWrite M o B) := by + by_cases hz : n = 0 + · subst hz + have hw : memoryWrite M o B = M := by simp [memoryWrite, hB] + rw [hw] + have hwords : (m.write o 0 src).words = m.words := by + unfold Mem.write Mem.expand + rw [if_pos rfl] + have hbytes : ∀ i, (m.write o 0 src).bytes i = m.bytes i := by + intro i + unfold Mem.write Mem.expand + rw [if_pos rfl] + dsimp only + exact if_neg (by omega) + exact ⟨by rw [hwords]; exact hm.1, fun i => by rw [hbytes]; exact hm.2 i⟩ + have hfit' : o + B.size ≤ M.size := by rw [hB]; exact hfit hz + refine ⟨?_, fun i => ?_⟩ + · rw [size_memoryWrite_of_fit (fun _ => hfit'), hm.1] + unfold Mem.write Mem.expand + simp only [hz, ite_false] + unfold SolarTV.Memory.grow + have hle : (m.words.ult (BitVec.ofNat 251 ((o + n + 31) / 32))) = false := by + have h1 := hfit hz + rw [hm.1] at h1 + have h2 : (o + n + 31) / 32 ≤ m.words.toNat := by omega + have h3 := Nat.mod_le ((o + n + 31) / 32) (2 ^ 251) + simp only [BitVec.ult, BitVec.toNat_ofNat, decide_eq_false_iff_not] + omega + simp only [hle] + rfl + · rw [byteAt_memoryWrite hfit'] + have hb : (m.write o n src).bytes i = if o ≤ i ∧ i < o + n then src (i - o) else m.bytes i := by + unfold Mem.write Mem.expand + split <;> rfl + rw [hb, hB] + split + · rename_i h + exact hsrc _ (by omega) + · exact hm.2 i + +/-- A write after growth for its range is the write. -/ +theorem write_expand (m : Mem) (o n : Nat) (src : Nat → Memory.Byte) : + (m.expand o n).write o n src = m.write o n src := by + unfold Mem.write Mem.expand + by_cases hz : n = 0 + · simp [hz] + · simp only [hz, ite_false, SolarTV.Memory.grow_idempotent] + +/-- The growth for a list of ranges is the growth for its first range and then for the rest, +from the size after the first. -/ +theorem extendMemory_cons_expandBy {sz : Nat} (hmod : sz % 32 = 0) (r : U256 × U256) + (rest : List (U256 × U256)) : + (extendMemory sz (r :: rest)).expandBy = (extendMemory sz [r]).expandBy + + (extendMemory (sz + (extendMemory sz [r]).expandBy) rest).expandBy := by + obtain ⟨a, b⟩ := r + simp only [extendMemory] + by_cases hb : b = 0 + · simp [hb] + · simp only [hb, ite_false, ceil32_of_mod hmod] + by_cases hg : ceil32 (a.toNat + b.toNat) ≤ sz + · simp [hg] + · simp only [hg, ite_false, Nat.add_zero] + rw [show sz + (ceil32 (a.toNat + b.toNat) - sz) = ceil32 (a.toNat + b.toNat) by omega] + +/-- The growth of memory for two ranges at once, as a call grows it, is the growth for the first +and then for the second. -/ +theorem memRel_expand2 {m : Mem} {M : ByteArray} {o1 s1 o2 s2 : Word} (hm : MemRel m M) + (hb1 : s1 = 0 ∨ o1.toNat + s1.toNat ≤ 2 ^ 32) (hb2 : s2 = 0 ∨ o2.toNat + s2.toNat ≤ 2 ^ 32) : + MemRel ((m.expand o1.toNat s1.toNat).expand o2.toNat s2.toNat) + (memoryExtend M (extendMemory M.size [(o1, s1), (o2, s2)]).expandBy) := by + have h1 := memRel_expand hm hb1 + have h2 := memRel_expand h1 hb2 + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + refine ⟨?_, fun i => ?_⟩ + · rw [← h2.1] + simp only [size_memoryExtend, extendMemory_cons_expandBy hmod (o1, s1) [(o2, s2)]] + omega + · rw [byteAt_memoryExtend] + have := h2.2 i + rw [byteAt_memoryExtend, byteAt_memoryExtend] at this + rw [this] + +/-! ## Return data -/ + +/-- EthLib's return data is the oracle's for SolarTV's world. -/ +def RdRel (o : Oracle) (w : List Event) (rd : ByteArray) : Prop := + (returndataSize o w).toNat = rd.size ∧ ∀ i, i < rd.size → returndataByte o w i = (byteAt rd i).toBitVec + +/-- The oracle of a run answers the table's return data. -/ +theorem rdRel_table (base : Oracle) (T : RunTable) (w : List Event) (hsz : (T.out w).size < 2 ^ 256) : + RdRel (tableOracle base T) w (T.out w) := + ⟨by rw [returndataSize_table, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hsz], + fun i hi => returndataByte_table base T w i (by omega)⟩ + +/-- A frame starts with no return data, as the oracle of a run answers before any message. -/ +theorem rdRel_initial (base : Oracle) (T : RunTable) : RdRel (tableOracle base T) [] .empty := + rdRel_table base T [] (by simp [out_nil]) + +/-! ## GAS -/ + +/-- **GAS** pushes EthLib's gas left after its price when the oracle answers it so. -/ +theorem gas_step {o : Oracle} {call : Call} {s : State} {code : ByteArray} {msg : Message .fusaka} + {pc g : Nat} {stack : List Word} {M : ByteArray} {st : State.TransactionState} {ss : Substate} + {rd : ByteArray} (hlt : pc < code.size) (hbyte : code[pc] = 0x5a) (hgas : 2 ≤ g) + (hstack : stack.length < STACK_LIMIT) + (ho : o.env "gas" (s.world ++ [.read "gas"]) [] = BitVec.ofNat 256 (g - 2)) : + Effect.apply o call .gas [] s = + some (some (BitVec.ofNat 256 (g - 2)), { s with world := s.world ++ [.read "gas"] }) ∧ + Hoare .fusaka (At code msg pc stack M g st ss rd) + (At code msg (pc + 1) (BitVec.ofNat 256 (g - 2) :: stack) M (g - 2) st ss rd) := + ⟨by simp [Effect.apply, ho], gas_rule hlt hbyte hgas hstack⟩ + +/-- GAS under the oracle of a run whose next gas is EthLib's. -/ +theorem gas_step_table {base : Oracle} {T : RunTable} {call : Call} {s : State} {code : ByteArray} + {msg : Message .fusaka} {pc g : Nat} {stack : List Word} {M : ByteArray} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray} (hlt : pc < code.size) + (hbyte : code[pc] = 0x5a) (hgas : 2 ≤ g) (hstack : stack.length < STACK_LIMIT) + (hT : T.gases.getD (gasReads s.world) 0 = g - 2) : + Effect.apply (tableOracle base T) call .gas [] s = + some (some (BitVec.ofNat 256 (g - 2)), { s with world := s.world ++ [.read "gas"] }) ∧ + Hoare .fusaka (At code msg pc stack M g st ss rd) + (At code msg (pc + 1) (BitVec.ofNat 256 (g - 2) :: stack) M (g - 2) st ss rd) := + gas_step hlt hbyte hgas hstack (by rw [gas_table, hT]) + +/-- A GAS read keeps the return data of the oracle of a run. -/ +theorem rdRel_read {base : Oracle} {T : RunTable} {w : List Event} {rd : ByteArray} (n : String) + (h : RdRel (tableOracle base T) w rd) : RdRel (tableOracle base T) (w ++ [.read n]) rd := by + obtain ⟨h1, h2⟩ := h + refine ⟨?_, fun i hi => ?_⟩ + · rw [returndataSize_table, rd_read, ← returndataSize_table]; exact h1 + · have hi' : i < 2 ^ 256 := by + have := (returndataSize (tableOracle base T) w).isLt + omega + rw [returndataByte_table _ _ _ _ hi', rd_read, ← returndataByte_table _ _ _ _ hi'] + exact h2 i hi + +/-- A log keeps the return data of the oracle of a run. -/ +theorem rdRel_log {base : Oracle} {T : RunTable} {w : List Event} {rd : ByteArray} + (t : List Word) (d : List Memory.Byte) + (h : RdRel (tableOracle base T) w rd) : RdRel (tableOracle base T) (w ++ [.log t d]) rd := by + obtain ⟨h1, h2⟩ := h + refine ⟨?_, fun i hi => ?_⟩ + · rw [returndataSize_table, rd_log, ← returndataSize_table]; exact h1 + · have hi' : i < 2 ^ 256 := by + have := (returndataSize (tableOracle base T) w).isLt + omega + rw [returndataByte_table _ _ _ _ hi', rd_log, ← returndataByte_table _ _ _ _ hi'] + exact h2 i hi + +/-! ## RETURNDATASIZE and RETURNDATACOPY -/ + +/-- **RETURNDATASIZE** pushes the size of EthLib's return data. -/ +theorem returndatasize_step {o : Oracle} {call : Call} {s : State} {code : ByteArray} + {msg : Message .fusaka} {pc g : Nat} {stack : List Word} {M : ByteArray} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray} (hr : RdRel o s.world rd) + (hlt : pc < code.size) (hbyte : code[pc] = 0x3d) (hgas : 2 ≤ g) + (hstack : stack.length < STACK_LIMIT) : + Effect.apply o call .returndatasize [] s = some (some (BitVec.ofNat 256 rd.size), s) ∧ + Hoare .fusaka (At code msg pc stack M g st ss rd) + (At code msg (pc + 1) (BitVec.ofNat 256 rd.size :: stack) M (g - 2) st ss rd) := by + refine ⟨?_, Logic.returndatasize (by decide) hlt hbyte hgas hstack⟩ + have h1 := hr.1 + simp only [returndataSize] at h1 + simp only [Effect.apply, ← h1, BitVec.ofNat_toNat, BitVec.setWidth_eq] + +/-- RETURNDATACOPY past the end of the return data has no SolarTV result. -/ +theorem returndatacopy_past {o : Oracle} {call : Call} {s : State} {rd : ByteArray} + {dest off size : Word} (hr : RdRel o s.world rd) (h : rd.size < off.toNat + size.toNat) : + Effect.apply o call .returndatacopy [dest, off, size] s = none := by + simp only [Effect.apply, hr.1, h, ite_true] + +/-- **RETURNDATACOPY** within the return data writes EthLib's bytes. -/ +theorem returndatacopy_step {o : Oracle} {call : Call} {s : State} {code : ByteArray} + {msg : Message .fusaka} {pc g : Nat} {rest : List Word} {M : ByteArray} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray} {dest off size : Word} + (hr : RdRel o s.world rd) (hm : MemRel s.memory M) + (hbound : size = 0 ∨ dest.toNat + size.toNat ≤ 2 ^ 32) + (fit : off.toNat + size.toNat ≤ rd.size) (hlt : pc < code.size) (hbyte : code[pc] = 0x3e) + (hgas : 3 + 3 * wordCount size.toNat + (extendMemory M.size [(dest, size)]).cost ≤ g) : + ∃ m', Effect.apply o call .returndatacopy [dest, off, size] s = some (none, { s with memory := m' }) ∧ + MemRel m' (memoryWrite (memoryExtend M (extendMemory M.size [(dest, size)]).expandBy) + dest.toNat (memoryReadBytes rd off.toNat size.toNat)) ∧ + Hoare .fusaka (At code msg pc (dest :: off :: size :: rest) M g st ss rd) + (At code msg (pc + 1) rest + (memoryWrite (memoryExtend M (extendMemory M.size [(dest, size)]).expandBy) + dest.toNat (memoryReadBytes rd off.toNat size.toNat)) + (g - (3 + 3 * wordCount size.toNat + (extendMemory M.size [(dest, size)]).cost)) + st ss rd) := by + refine ⟨s.memory.write dest.toNat size.toNat (fun i => returndataByte o s.world (off.toNat + i)), + ?_, ?_, Logic.returndatacopy (by decide) hlt hbyte fit hgas⟩ + · have hn : ¬((returndataSize o s.world).toNat < off.toNat + size.toNat) := by rw [hr.1]; omega + show (if (returndataSize o s.world).toNat < off.toNat + size.toNat then none else _) = _ + rw [if_neg hn] + · have he := memRel_expand hm hbound + rw [← write_expand] + refine memRel_write he (fun hz => ?_) (size_memoryReadBytes fit) (fun i hi => ?_) + · have hz' : size ≠ 0 := fun h => hz (by simp [h]) + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + rw [size_memoryExtend_extendMemory' hmod hz'] + have := le_ceil32 (dest.toNat + size.toNat) + omega + · rw [byteAt_memoryReadBytes fit, if_pos hi] + exact (hr.2 _ (by omega)).symm + +/-! ## CALLDATACOPY -/ + +/-- A byte of the call data, as SolarTV reads it, is EthLib's. -/ +theorem calldataByte_eq (call : Call) (i : Nat) : + calldataByte call i = (byteAt call.calldata i).toBitVec := by + apply BitVec.eq_of_toNat_eq + simp only [calldataByte, BitVec.toNat_ofNat, UInt8.toNat_toBitVec] + rw [Nat.mod_eq_of_lt (UInt8.toNat_lt _)] + unfold byteAt + split + · rename_i h + rw [Array.getD_eq_getD_getElem?, Array.getElem?_eq_getElem h] + rfl + · rename_i h + rw [Array.getD_eq_getD_getElem?, Array.getElem?_eq_none (Nat.le_of_not_lt h)] + rfl + +/-- **CALLDATACOPY** of any size writes EthLib's bytes, zero past the end of the call data. -/ +theorem calldatacopy_step {o : Oracle} {call : Call} {s : State} {code : ByteArray} + {msg : Message .fusaka} {pc g : Nat} {rest : List Word} {M : ByteArray} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray} {dest off size : Word} + (hdata : msg.data = call.calldata) (hm : MemRel s.memory M) + (hbound : size = 0 ∨ dest.toNat + size.toNat ≤ 2 ^ 32) (hlt : pc < code.size) + (hbyte : code[pc] = 0x37) + (hgas : 3 + 3 * wordCount size.toNat + (extendMemory M.size [(dest, size)]).cost ≤ g) : + ∃ m', Effect.apply o call .calldatacopy [dest, off, size] s = some (none, { s with memory := m' }) ∧ + MemRel m' (memoryWrite (memoryExtend M (extendMemory M.size [(dest, size)]).expandBy) + dest.toNat ⟨(bufferRead msg.data off.toNat size.toNat).toArray⟩) ∧ + Hoare .fusaka (At code msg pc (dest :: off :: size :: rest) M g st ss rd) + (At code msg (pc + 1) rest + (memoryWrite (memoryExtend M (extendMemory M.size [(dest, size)]).expandBy) + dest.toNat ⟨(bufferRead msg.data off.toNat size.toNat).toArray⟩) + (g - (3 + 3 * wordCount size.toNat + (extendMemory M.size [(dest, size)]).cost)) + st ss rd) := by + refine ⟨s.memory.write dest.toNat size.toNat (fun i => calldataByte call (off.toNat + i)), + rfl, ?_, Logic.calldatacopy hlt hbyte hgas⟩ + have he := memRel_expand hm hbound + rw [← write_expand] + refine memRel_write he (fun hz => ?_) (size_bufferRead _ _ _) (fun i hi => ?_) + · have hz' : size ≠ 0 := fun h => hz (by simp [h]) + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + rw [size_memoryExtend_extendMemory' hmod hz'] + have := le_ceil32 (dest.toNat + size.toNat) + omega + · rw [byteAt_bufferRead, if_pos hi, hdata, calldataByte_eq] + +/-! ## STATICCALL -/ + +/-- **STATICCALL in SolarTV** under an oracle that answers the call as the callee's frame `child` +ended (its success and output): the flag EthLib pushes, memory as EthLib leaves it with the +callee's output written to the output range, the return data the callee's output, and the storage +kept. -/ +theorem staticcall_effect {o : Oracle} {call : Call} {s : State} {M : ByteArray} + {gas addr inOff inSize outOff outSize : Word} {child : Evm .fusaka Nat} + (hm : MemRel s.memory M) + (hb1 : inSize = 0 ∨ inOff.toNat + inSize.toNat ≤ 2 ^ 32) + (hb2 : outSize = 0 ∨ outOff.toNat + outSize.toNat ≤ 2 ^ 32) + (hflag : callFlag o (s.world ++ [.call .staticcall [gas, addr] + (((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat outSize.toNat).read + inOff.toNat inSize.toNat) s.storage s.transient]) = if child.error.isNone then 1 else 0) + (hrd : RdRel o (s.world ++ [.call .staticcall [gas, addr] + (((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat outSize.toNat).read + inOff.toNat inSize.toNat) s.storage s.transient]) child.output) : + ∃ s', Effect.apply o call (.call .staticcall) [gas, addr, inOff, inSize, outOff, outSize] s = + some (some (if child.error.isNone then 1 else 0), s') ∧ + s'.storage = s.storage ∧ s'.transient = s.transient ∧ RdRel o s'.world child.output ∧ + MemRel s'.memory (memoryWrite (memoryExtend M + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).expandBy) + outOff.toNat (child.output.extract 0 (min outSize.toNat child.output.size))) := by + have he := memRel_expand2 hm hb1 hb2 + refine ⟨called o .staticcall s ((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat + outSize.toNat) outOff outSize (s.world ++ [.call .staticcall [gas, addr] + (((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat outSize.toNat).read + inOff.toNat inSize.toNat) s.storage s.transient]), ?_, ?_, ?_, ?_, ?_⟩ + · simp only [Effect.apply, CallKind.shape, hflag] + · rfl + · rfl + · exact hrd + · simp only [called] + rw [hrd.1] + refine memRel_write he (fun hz => ?_) ?_ (fun i hi => ?_) + · have hz' : outSize ≠ 0 := fun h => hz (by simp [h]) + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have := le_ceil32_add_expandBy M.size [(inOff, inSize), (outOff, outSize)] (outOff, outSize) + (by simp) hz' + dsimp only at this + rw [ceil32_of_mod hmod] at this + rw [size_memoryExtend] + have := Nat.min_le_left outSize.toNat child.output.size + omega + · simp [ByteArray.size_extract] + · rw [byteAt_extract, Nat.zero_add, if_pos (by omega)] + exact (hrd.2 i (by omega)).symm + +/-- **STATICCALL in EthLib**, at Fusaka, from EthLib's rule: under every frame that ends the +message, the caller pushes the callee's success, writes its output to the output range and keeps +its output as the return data. -/ +theorem staticcall_rule {callee : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} + {code : ByteArray} {msg : Message .fusaka} {pc g : Nat} {M : ByteArray} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray} + {asked addr inOff inSize outOff outSize : Word} {rest : List Word} {cold : Bool} + {calleeCode : ByteArray} (hlt : pc < code.size) (hbyte : code[pc] = 0xfa) + (hcode : st.getCode (st.getAccount (toAddressMasked addr)).codeHash = .ok calleeCode) + (hdel : delegatedAddress calleeCode = none) + (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + (hcold : decide (toAddressMasked addr ∉ ss.accessedAddresses) = cold) + (hgas : (if cold then 2600 else 100) + + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost ≤ g) : + HoareUnder .fusaka callee + (At code msg pc (asked :: addr :: inOff :: inSize :: outOff :: outSize :: rest) M g st ss rd) + fun after => ∃ caller m child, callee caller m child ∧ child.gas ≤ m.gas ∧ + m.isStatic = true ∧ m.value = 0 ∧ + m.data = memoryReadBytes (memoryExtend M + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).expandBy) + inOff.toNat inSize.toNat ∧ + ∃ g' st' ss', At code msg (pc + 1) ((if child.error.isNone then 1 else 0) :: rest) + (memoryWrite (memoryExtend M + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).expandBy) + outOff.toNat (child.output.extract 0 (min outSize.toNat child.output.size))) + g' st' ss' child.output after := by + have H := staticcallWith (fork := .fusaka) (by decide) (by decide) (callee := callee) + (asked := asked) (rest := rest) (returnData := rd) hlt hbyte hcode (fun _ => hdel) hdepth hcold hgas + intro bound runChild meets evm hp within + obtain ⟨after, hr, hq⟩ := H bound runChild meets evm hp within + refine ⟨after, hr, hq.imp_left fun ⟨caller, m, child, hc, hg, _, _, _, _, _, _, _, _, hd, hv, _, + hs, hat⟩ => ⟨caller, m, child, hc, hg, hs, hv, hd, _, _, _, hat⟩⟩ + +/-- The oracle of a run answers a STATICCALL as the callee's frame ended when the table's next +entry is that frame's success and output. -/ +theorem staticcall_table {base : Oracle} {T : RunTable} {w : List Event} {ops : List Word} + {input : List Memory.Byte} {stor tr : Word → Word} {child : Evm .fusaka Nat} + (hok : T.oks.getD (sent w) false = child.error.isNone) + (hout : T.outs.getD (sent w) .empty = child.output) (hsz : child.output.size < 2 ^ 256) : + callFlag (tableOracle base T) (w ++ [.call .staticcall ops input stor tr]) = + (if child.error.isNone then 1 else 0) ∧ + RdRel (tableOracle base T) (w ++ [.call .staticcall ops input stor tr]) child.output := by + refine ⟨by rw [callFlag_table, hok], ?_⟩ + have h := rdRel_table base T (w ++ [.call .staticcall ops input stor tr]) + (by rw [out_call, hout]; exact hsz) + rwa [out_call, hout] at h + +/-- info: 'SolidCore.Refinement.Solar.AssembleEffects.staticcall_effect' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms staticcall_effect + +/-- info: 'SolidCore.Refinement.Solar.AssembleEffects.staticcall_rule' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms staticcall_rule + +/-- info: 'SolidCore.Refinement.Solar.AssembleEffects.returndatacopy_step' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms returndatacopy_step + +/-- info: 'SolidCore.Refinement.Solar.AssembleEffects.calldatacopy_step' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms calldatacopy_step + +/-- info: 'SolidCore.Refinement.Solar.AssembleEffects.gas_step_table' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms gas_step_table + +end SolidCore.Refinement.Solar.AssembleEffects diff --git a/SolidCore/Refinement/Solar/AssembleFast.lean b/SolidCore/Refinement/Solar/AssembleFast.lean new file mode 100644 index 00000000..e670d2ee --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleFast.lean @@ -0,0 +1,354 @@ +import SolidCore.Refinement.Solar.Assemble +import EthLib.Execution.Proofs.Evm.Machine.JumpDest + +/-! +# The assembler check, in one pass over the code + +The kernel evaluates `Assemble.check` on a contract's bytecode to prove its assembly stage. Two of +its parts read the code at random offsets of a list: the walk (`SolarTV.Assembly.walk`) decodes +each instruction at its offset with `code[pc]?`, and the labels' check (`labelsValid`) runs +EthLib's scan of the valid jump destinations, which reads each byte with `byteAt`. Each of those +reads walks the list from its head, and the kernel keeps every step it took: for bank's 454 bytes +the walk costs 0.7 GB and the scan 1.1 GB. + +`checkFast` is the same check in one pass: its walk (`walkS`) carries the rest of the code from +the offset it reached, so each instruction decodes from the list's head, and it has no labels' +check, which the walk implies. `check_eq_checkFast` proves the two equal on every program, code and +certificate, so a kernel evaluation of `checkFast` proves `check` true or false. + +* `decodeS`, `walkS`: `decode` and `walk` on the rest of the code (`decodeS_drop`, `walkS_drop`). +* `labelsValid_of_walk`: each label the walk reaches is a valid jump destination by EthLib's own + analysis: the walk steps from opcode to opcode as EthLib's scan does (`next_eq_nextOpcode`, by + `opLen`, the bytes the scan steps over at each of the 256 bytes), from offset 0, and finds + JUMPDEST at each label. +-/ + +namespace SolidCore.Refinement.Solar.Assemble + +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm GasCosts + +/-! ## Decoding from the rest of the code -/ + +/-- `decode` at offset `pc` of the code whose rest from `pc` is the list: the instruction, the +offset after it and the rest of the code from there. -/ +def decodeS : List Nat → Nat → Option (SolarTV.Assembly.Instr × Nat × List Nat) + | [], _ => none + | byte :: tl, pc => + if byte = PUSH0 then some (.push 0, pc + 1, tl) + else if PUSH1 ≤ byte ∧ byte ≤ PUSH32 then + if (tl.take (byte - PUSH1 + 1)).length = byte - PUSH1 + 1 then + some (.push (bigEndian (tl.take (byte - PUSH1 + 1))), pc + 1 + (byte - PUSH1 + 1), + tl.drop (byte - PUSH1 + 1)) + else none + else if hasImmediate byte then + match tl with + | imm :: tl => if immediateOk byte imm then some (.opImm byte imm, pc + 2, tl) else none + | [] => none + else some (.op byte, pc + 1, tl) + +/-- `Item.placed` at offset `pc` of the code whose rest from `pc` is the list. -/ +def placedS (rest : List Nat) (offset : Nat → Nat) (pc : Nat) : Item → Bool + | .immutable _ bytes => + decide (1 ≤ bytes) && decide (bytes ≤ 32) && rest.head? == some (PUSH1 + bytes - 1) + | item => item.placed [] offset pc + +theorem placedS_drop (code : List Nat) (offset : Nat → Nat) (pc : Nat) (item : Item) : + placedS (code.drop pc) offset pc item = item.placed code offset pc := by + cases item <;> first | rfl | simp only [placedS, Item.placed, List.head?_drop] + +/-- `walk` from offset `pc` of the code whose rest from `pc` is the list: whether the walk +succeeds. -/ +def walkS (offset : Nat → Nat) : List Nat → Nat → List Item → Bool + | rest, _, [] => rest.isEmpty + | rest, pc, item :: items => + match decodeS rest pc with + | none => false + | some (instr, next, rest') => + instr == item.expected offset && placedS rest offset pc item && walkS offset rest' next items + +/-- The checker `check`, with the walk on the rest of the code and without the labels' check, +which the walk implies. -/ +def checkFast (p : Program) (code : ByteArray) (c : Cert) : Bool := + walkS c.offset (bytesOf code) 0 (lower p c) && blocksOk p c 0 p.blocks && + decide (c.need 0 = 0) && decide (c.top % 32 = 0) && + decide (cost p c 0 ≤ 1000) && decide (c.top ≤ 2 ^ 32) && + decide (22100 * cost p c 0 + memoryGasCost c.top ≤ 10000000) && decide (code.size < 2 ^ 32) + +theorem decodeS_drop (code : List Nat) (pc : Nat) : + decodeS (code.drop pc) pc = (decode code pc).map fun x => (x.1, x.2, code.drop x.2) := by + unfold decode + rcases h : code.drop pc with _ | ⟨byte, tl⟩ + · have hle : code.length ≤ pc := List.drop_eq_nil_iff.1 h + rw [List.getElem?_eq_none hle] + rfl + · have hget : code[pc]? = some byte := by + rw [← List.head?_drop, h] + rfl + have htl : code.drop (pc + 1) = tl := by + rw [← List.drop_drop, h] + rfl + have hlen : code.length = pc + 1 + tl.length := by + have := congrArg List.length h + simp only [List.length_drop, List.length_cons] at this + omega + rw [hget] + simp only [decodeS] + by_cases h0 : byte = PUSH0 + · simp [h0, htl] + · by_cases h1 : PUSH1 ≤ byte ∧ byte ≤ PUSH32 + · have hd : ∀ n, code.drop (pc + 1 + n) = tl.drop n := fun n => by + rw [← htl, List.drop_drop] + by_cases h2 : pc + 1 + (byte - PUSH1 + 1) ≤ code.length + · have h2' : (tl.take (byte - PUSH1 + 1)).length = byte - PUSH1 + 1 := by + rw [List.length_take] + omega + simp [h0, h1, h2, h2', htl, hd] + · have h2' : ¬(tl.take (byte - PUSH1 + 1)).length = byte - PUSH1 + 1 := by + rw [List.length_take] + omega + have h3 : ¬byte - PUSH1 + 1 ≤ tl.length := by omega + simp [h0, h1, h3] + omega + · by_cases h2 : hasImmediate byte = true + · rcases tl with _ | ⟨imm, tl⟩ + · have h3 : code[pc + 1]? = none := List.getElem?_eq_none (by simp at hlen; omega) + simp [h0, h1, h2, h3] + · have h3 : code[pc + 1]? = some imm := by + rw [← List.head?_drop, htl] + rfl + have h4 : code.drop (pc + 2) = tl := by + rw [← List.drop_drop, h] + rfl + by_cases h5 : immediateOk byte imm = true <;> simp [h0, h1, h2, h3, h4, h5] + · simp [h0, h1, h2, htl] + +/-- A successful decode ends within the code. -/ +theorem decode_lt' {code : List Nat} {pc next : Nat} {i : SolarTV.Assembly.Instr} + (h : decode code pc = some (i, next)) : pc < code.length := by + unfold decode at h + split at h + · cases h + · rename_i byte hb + exact (List.getElem?_eq_some_iff.1 hb).1 + +theorem decode_next_le {code : List Nat} {pc next : Nat} {i : SolarTV.Assembly.Instr} + (h : decode code pc = some (i, next)) : next ≤ code.length := by + cases i with + | op b => + obtain ⟨hb, -, -, -, rfl⟩ := decode_op_inv h + have := (List.getElem?_eq_some_iff.1 hb).1 + omega + | opImm b imm => + obtain ⟨-, -, hi, -, rfl⟩ := decode_opImm_inv h + have := (List.getElem?_eq_some_iff.1 hi).1 + omega + | push v => + obtain ⟨b, hb, ⟨-, -, rfl⟩ | ⟨-, -, -, hle, -⟩⟩ := decode_push h + · have := (List.getElem?_eq_some_iff.1 hb).1 + omega + · exact hle + +theorem walkS_drop (code : List Nat) (offset : Nat → Nat) : + ∀ (items : List Item) (pc : Nat), pc ≤ code.length → + walkS offset (code.drop pc) pc items = (walk code offset pc items).isSome + | [], pc, hpc => by + simp only [walkS, walk] + by_cases h : pc = code.length + · subst h + simp + · simp only [h, ↓reduceIte] + cases e : code.drop pc with + | nil => have := List.drop_eq_nil_iff.1 e; omega + | cons x l => rfl + | item :: items, pc, hpc => by + simp only [walkS, walk, decodeS_drop, placedS_drop] + cases hd : decode code pc with + | none => rfl + | some x => + obtain ⟨instr, next⟩ := x + simp only [Option.map_some] + rw [walkS_drop code offset items next (decode_next_le hd)] + cases h1 : instr == item.expected offset <;> cases h2 : item.placed code offset pc <;> + cases walk code offset next items <;> + simp only [beq_iff_eq, beq_eq_false_iff_ne] at h1 <;> + simp only [h1, Bool.and_false, Bool.and_true, and_true, and_false, ↓reduceIte, + Option.isSome_none, Option.isSome_some, Bool.and_self, reduceCtorEq, and_self] + +/-! ## The walk implies the labels' check -/ + +/-- The bytes EthLib's scan steps over at an opcode: PUSHn's opcode and its `n` bytes of data, one +byte for every other opcode. -/ +def opLen (b : UInt8) : Nat := + match Op.decode b with + | some (.push n) => n.val + 1 + | _ => 1 + +theorem nextOpcode_eq_opLen (code : ByteArray) (pc : Nat) : + nextOpcode code pc = pc + opLen (byteAt code pc) := by + unfold nextOpcode opLen + rcases Op.decode (byteAt code pc) with _ | op + · rfl + · cases op <;> rfl + +theorem opLen_ofNat : ∀ n, n < 256 → opLen (UInt8.ofNat n) = + 1 + if 0x60 ≤ n ∧ n ≤ 0x7f then n - 0x5f else 0 := by + decide +kernel + +/-- The bytes EthLib's scan steps over by the byte alone, as the walk decodes it. -/ +theorem opLen_eq (b : UInt8) : + opLen b = 1 + if 0x60 ≤ b.toNat ∧ b.toNat ≤ 0x7f then b.toNat - 0x5f else 0 := by + have h := opLen_ofNat b.toNat b.toNat_lt + rwa [UInt8.ofNat_toNat] at h + +theorem boundary_next {code : ByteArray} {s p : Nat} (h : BoundaryFrom code s p) + (hn : nextOpcode code p < code.size) : BoundaryFrom code s (nextOpcode code p) := by + induction h with + | here hs => exact .step hs (.here hn) + | step hs _ ih => exact .step hs (ih hn) + +/-- The walk steps from an instruction to the next opcode, as EthLib's scan does: over a push +and its data, over one byte, or over an opcode and its immediate, which the scan steps over as +an opcode of its own, since no immediate that decodes is a push (`immediateOk_not_push`). -/ +theorem decode_boundary {code : ByteArray} {pc next : Nat} {i : SolarTV.Assembly.Instr} + (h : decode (bytesOf code) pc = some (i, next)) : + pc < code.size ∧ (BoundaryFrom code 0 pc → next < code.size → BoundaryFrom code 0 next) := by + have hpc : pc < code.size := by + have := decode_lt' h + rwa [length_bytesOf] at this + refine ⟨hpc, fun hb hn => ?_⟩ + have hbyteOf : ∀ q byte, (bytesOf code)[q]? = some byte → (byteAt code q).toNat = byte := + fun q byte hq => by + rw [byteAt_toNat, List.getD_eq_getElem?_getD, hq] + rfl + have step : ∀ q, BoundaryFrom code 0 q → (byteAt code q).toNat < 0x60 ∨ 0x7f < (byteAt code q).toNat → + q + 1 < code.size → BoundaryFrom code 0 (q + 1) := fun q hq hnp hlt => by + have e : nextOpcode code q = q + 1 := by + rw [nextOpcode_eq_opLen, opLen_eq] + have : ¬(0x60 ≤ (byteAt code q).toNat ∧ (byteAt code q).toNat ≤ 0x7f) := by omega + simp only [this, ↓reduceIte] + have := boundary_next hq (by rw [e]; exact hlt) + rwa [e] at this + cases i with + | op b => + obtain ⟨hb', -, h1, -, rfl⟩ := decode_op_inv h + have := hbyteOf pc b hb' + unfold PUSH1 PUSH32 at h1 + have hx : (byteAt code pc).toNat < 0x60 ∨ 0x7f < (byteAt code pc).toNat := by + rw [this] + cases Nat.decLt b 0x60 with + | isTrue hlt => exact .inl hlt + | isFalse hge => exact .inr (Nat.lt_of_not_le (fun hle => h1 ⟨by omega, hle⟩)) + exact step pc hb hx hn + | opImm b imm => + obtain ⟨hb', him, hi, hok, rfl⟩ := decode_opImm_inv h + have e1 := hbyteOf pc b hb' + have e2 := hbyteOf (pc + 1) imm hi + have hnp := immediateOk_not_push hok + have hb1 : b = 0xe6 ∨ b = 0xe7 ∨ b = 0xe8 := by + simp only [hasImmediate, DUPN, SWAPN, EXCHANGE, Bool.or_eq_true, beq_iff_eq] at him + rcases him with (e | e) | e + · exact .inl e + · exact .inr (.inl e) + · exact .inr (.inr e) + have hx : (byteAt code pc).toNat < 0x60 ∨ 0x7f < (byteAt code pc).toNat := + .inr (by rcases hb1 with e | e | e <;> omega) + have h1 := step pc hb hx (by omega) + have hy : (byteAt code (pc + 1)).toNat < 0x60 ∨ 0x7f < (byteAt code (pc + 1)).toNat := by + rw [e2] + cases Nat.decLt imm 0x60 with + | isTrue hlt => exact .inl hlt + | isFalse hge => exact .inr (Nat.lt_of_not_le (fun hle => hnp ⟨by omega, hle⟩)) + exact step (pc + 1) h1 hy hn + | push v => + obtain ⟨b, hb', ⟨h0, -, rfl⟩ | ⟨h1, h2, rfl, -, -⟩⟩ := decode_push h + · have := hbyteOf pc b hb' + unfold PUSH0 at h0 + exact step pc hb (by omega) hn + · have e := hbyteOf pc b hb' + have e' : nextOpcode code pc = pc + 1 + (b - PUSH1 + 1) := by + rw [nextOpcode_eq_opLen, opLen_eq, e] + unfold PUSH1 at h1 ⊢ + unfold PUSH32 at h2 + simp only [h1, h2, and_self, ↓reduceIte] + omega + have := boundary_next hb (by rw [e']; exact hn) + rwa [e'] at this + +/-- Each label a successful walk from an opcode boundary reaches is a valid jump destination. -/ +theorem walk_labels {code : ByteArray} {offset : Nat → Nat} : + ∀ (items : List Item) (pc : Nat), (walk (bytesOf code) offset pc items).isSome = true → + (pc < code.size → BoundaryFrom code 0 pc) → + ∀ l, Item.label l ∈ items → isValidJumpDest (validJumpDestinations code) (offset l) = true + | [], _, _, _, l, hl => absurd hl (by simp) + | item :: items, pc, hw, hb, l, hl => by + simp only [walk] at hw + cases hd : decode (bytesOf code) pc with + | none => rw [hd] at hw; simp at hw + | some x => + obtain ⟨instr, next⟩ := x + rw [hd] at hw + simp only at hw + by_cases ok : instr = item.expected offset ∧ item.placed (bytesOf code) offset pc = true + · simp only [ok, and_self, ↓reduceIte] at hw + have hw' : (walk (bytesOf code) offset next items).isSome = true := by + cases h' : walk (bytesOf code) offset next items <;> simp [h'] at hw ⊢ + obtain ⟨hpc, hnext⟩ := decode_boundary hd + have hbpc := hb hpc + rcases List.mem_cons.1 hl with rfl | hl + · have hoff : offset l = pc := by simpa [Item.placed] using ok.2 + have hi : instr = .op SolarTV.Assembly.JUMPDEST := by simpa [Item.expected] using ok.1 + rw [hi] at hd + obtain ⟨hbyte, -⟩ := decode_op hd + rw [hoff, isValidJumpDest_iff_boundaryFrom] + refine ⟨hbpc, ?_⟩ + apply UInt8.toNat_inj.mp + rw [byteAt_toNat, List.getD_eq_getElem?_getD, hbyte] + rfl + · exact walk_labels items next hw' (hnext hbpc) l hl + · simp only [ok, ↓reduceIte] at hw + simp at hw + +theorem label_mem_lowerFrom (p : Program) (c : Cert) {t : Nat} (ht : isTarget p c t = true) : + ∀ (l : List (List Instr)) (b : Nat), b ≤ t → t < b + l.length → + Item.label t ∈ lowerFrom p c b l + | [], b, h1, h2 => by simp at h2; omega + | x :: l, b, h1, h2 => by + simp only [lowerFrom, List.mem_append] + by_cases e : t = b + · subst e + left + simp [lowerBlock, ht] + · right + exact label_mem_lowerFrom p c ht l (b + 1) (by omega) (by simp at h2; omega) + +/-- The walk of the lowered program implies the labels' check. -/ +theorem labelsValid_of_walk {p : Program} {c : Cert} {code : ByteArray} + (hw : (walk (bytesOf code) c.offset 0 (lower p c)).isSome = true) : + labelsValid p c code = true := by + simp only [labelsValid, List.all_eq_true, List.mem_range] + intro b hb + cases ht : isTarget p c b + · rfl + · simp only [Bool.not_true, Bool.false_or] + exact walk_labels _ 0 hw (fun h => .here h) b + (label_mem_lowerFrom p c ht p.blocks 0 (by omega) (by omega)) + +/-- The two checkers agree on every program, code and certificate. -/ +theorem check_eq_checkFast (p : Program) (code : ByteArray) (c : Cert) : + check p code c = checkFast p code c := by + have hw : walkS c.offset (bytesOf code) 0 (lower p c) = + (walk (bytesOf code) c.offset 0 (lower p c)).isSome := by + simpa using walkS_drop (bytesOf code) c.offset (lower p c) 0 (Nat.zero_le _) + unfold check checkFast + rw [hw] + cases h : (walk (bytesOf code) c.offset 0 (lower p c)).isSome + · simp + · rw [labelsValid_of_walk h] + simp + +/-- info: 'SolidCore.Refinement.Solar.Assemble.check_eq_checkFast' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms check_eq_checkFast + +end SolidCore.Refinement.Solar.Assemble diff --git a/SolidCore/Refinement/Solar/AssembleGas.lean b/SolidCore/Refinement/Solar/AssembleGas.lean new file mode 100644 index 00000000..03d7e3e6 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleGas.lean @@ -0,0 +1,124 @@ +import SolidCore.Refinement.Solar.AssembleSim +import Verify.Final + +/-! +# EVM IR to bytecode from a gas bound on + +`stage_of_check_env` is the forward stage of the assembly checker at the gas of +`Target.message`: every observable SolarTV's EVM IR gives, EthLib gives for the bytecode. Its +proof needs only that the message holds the gas the checker's invariant asks for, 22100 per item +of the lowered program plus the memory up to the certificate's top (`gasBound`, at most +10,000,000 by the check). So the same proof gives the stage at every gas from `gasBound` on +(`stage_of_check_gas`): from that gas the bytecode does not run out of gas, it shows exactly the +EVM IR's result, a revert with its data included. This is the resources half of a certificate: +a proved gas bound, a constant of the checked program, not a premise of success. + +The bound is coarse (22100 gas, an SSTORE's worst case, for every item) and covers only code the +straight-line checker accepts: no loops, GAS or calls. +-/ + +namespace SolidCore.Refinement.Solar.Assemble + +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Evm.Symex + +/-- The gas a run of a checked program needs at most. -/ +def gasBound (p : Program) (c : Cert) : Nat := 22100 * cost p c 0 + memoryGasCost c.top + +/-- `run_of_rel` with the message of `gas` gas. -/ +theorem run_of_rel_with (code : ByteArray) (call : SolarTV.Call) (s : SolarTV.Machine.State) + (halt : SolarTV.Machine.Halt) (gas : Nat) + (h : ∀ st, Rel (Final.Target.messageWith gas code call) Substate.empty st Substate.empty + (SolarTV.Machine.State.initial call) → + Spec .fusaka (At code (Final.Target.messageWith gas code call) 0 [] .empty gas st + Substate.empty .empty) (PostL call (Target.address selfAddress) Substate.empty s halt)) : + Final.Target.runWith gas code call = some (SolarTV.Machine.observe call s halt) := by + have key : ∃ evm, processMessage (Meter := Nat) .fusaka (Final.Target.messageWith gas code call) + (Target.preState code call) Substate.empty = .ok evm ∧ + MsgOut (SolarTV.Machine.observe call s halt) (Target.address selfAddress) Substate.empty + s.world evm.1 := by + by_cases hv : (Final.Target.messageWith gas code call).value = 0 + · exact processMessage_postL _ rfl hv (precompileAddress_message code call) _ _ _ _ _ + (h _ ⟨(rel_initial code call).storage, (rel_initial code call).account, + (rel_initial code call).logs⟩) + · obtain ⟨st', hmove⟩ := moveEther_preState_any code call + have hn : ((Target.preState code call).getAccount (Target.address selfAddress)).nonce ≠ 0 := by + rw [getAccount_preState_self]; simp + have hAB : Target.address selfAddress ≠ Target.address callerAddress := by decide + have R0 := rel_initial code call + have R : Rel (Final.Target.messageWith gas code call) Substate.empty st' Substate.empty + (SolarTV.Machine.State.initial call) := + ⟨fun k => ((moveEther_recipient hmove hAB hn _).1).trans (R0.storage k), + (moveEther_recipient hmove hAB hn (Target.storageKey 0)).2, R0.logs⟩ + exact processMessage_postL_move _ rfl rfl hv (precompileAddress_message code call) _ _ _ _ + st' _ hmove (h st' R) + obtain ⟨evm, hr, ssF, ⟨L, hL1, hL2⟩, herr, hout, hst⟩ := key + have hlogs := logs_of_match hL2 + have hL1' : ssF.logs.toList = L := by simpa [Substate.empty] using hL1 + have hfail : (SolarTV.Machine.observe call s halt).success = false → + (SolarTV.Machine.observe call s halt).logs = [] ∧ + (SolarTV.Machine.observe call s halt).storage = slotValue call.storage := by + cases halt <;> simp [SolarTV.Machine.observe] + have hok : (SolarTV.Machine.observe call s halt).success = true → + (SolarTV.Machine.observe call s halt).logs = SolarTV.Machine.logs s := by + cases halt <;> simp [SolarTV.Machine.observe] + simp only [Final.Target.runWith, Final.Target.runMsg, hr] + generalize SolarTV.Machine.observe call s halt = X at * + have hsucc : evm.1.error.isNone = X.success := by + rw [herr]; cases hX : X.success <;> simp [errorOf, hX] + congr 1 + cases X with + | mk success output logs storage => + simp only at hsucc hout hfail hok hst ⊢ + rw [SolarTV.Observable.mk.injEq] + refine ⟨hsucc, hout, ?_, ?_⟩ + · rw [hsucc] + cases hs : success + · simp [(hfail hs).1] + · simp only [ite_true] + rw [(hst hs).1, hL1', hlogs, hok hs] + rfl + · funext slot + rw [hsucc] + cases hs : success + · simp [(hfail hs).2] + · simp only [ite_true] + exact (hst hs).2 slot + +/-- **EVM IR to bytecode from the gas bound on.** For every program and code the checker accepts, +under every oracle whose caller and hash are EthLib's when the program reads them, at every gas +from `gasBound` on: every observable SolarTV's EVM IR gives, EthLib gives for the bytecode with +that gas. -/ +theorem stage_of_check_gas {p : Program} {code : ByteArray} {c : Cert} (hc : check p code c = true) + (o : SolarTV.Machine.Oracle) (ho : c.env = true → OracleOk o) (scope : SolarTV.Call → Prop) + {gas : Nat} (hg : gasBound p c ≤ gas) : + SolarTV.Stage (SolarTV.evmirSem o) (Final.ethLibWith gas) p + (show (Final.ethLibWith gas).Prog from code) scope := by + obtain ⟨G, hseg, hneed0, hlen, -⟩ := glob_of_check hc + intro call _ obs hrun + change (SolarTV.EVM.Program.layer.result o p call).map _ = _ at hrun + obtain ⟨r, hr, rfl⟩ := Option.map_eq_some_iff.1 hrun + obtain ⟨n, hn⟩ := SolarTV.EVM.Program.layer.ends_of_result hr + have hm0 : memoryGasCost (ByteArray.empty).size = 0 := by decide + have I0 : Inv c code call (lowerFrom p c 0 (p.blocks.drop 0)) (cost p c 0) 0 [] + (SolarTV.Machine.State.initial call) .empty gas := + ⟨by rw [List.drop_zero]; exact hseg, by simpa using hlen, + by rw [hm0]; unfold gasBound at hg; omega, by simp, memRel_initial⟩ + exact run_of_rel_with code call r.2 r.1 gas fun st R => + run_sim (msg := Final.Target.messageWith gas code call) (ss0 := Substate.empty) G rfl + (by simp [Final.Target.messageWith, Target.message]) rfl rfl rfl ho n 0 [] [] _ 0 .empty + gas st Substate.empty r (Nat.zero_le _) (by simp [hneed0]) (SR.nil c _) I0 R hn + +/-- The bound is at most 10,000,000, the gas of `Target.message`, for every checked program. -/ +theorem gasBound_le {p : Program} {code : ByteArray} {c : Cert} (hc : check p code c = true) : + gasBound p c ≤ 10000000 := + (glob_of_check hc).2.2.2.2 + +/-- +info: 'SolidCore.Refinement.Solar.Assemble.stage_of_check_gas' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms stage_of_check_gas + +end SolidCore.Refinement.Solar.Assemble diff --git a/SolidCore/Refinement/Solar/AssembleGasLoop.lean b/SolidCore/Refinement/Solar/AssembleGasLoop.lean new file mode 100644 index 00000000..24353cd9 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleGasLoop.lean @@ -0,0 +1,69 @@ +import SolidCore.Refinement.Solar.AssembleLoopRun +import SolidCore.Refinement.Solar.AssembleGas + +/-! +# EVM IR to bytecode from a gas bound on, for code with loops + +`within_of_checkL` is the backward direction at every gas. Here is the forward one: when SolarTV's +EVM IR ends within `n` blocks, then at every gas from `22100 * (n * bmax c) + memoryGasCost c.top` +on, the bytecode shows exactly its result, reverts included (`forward_of_checkL`). The block count +`n` is the run's; a ranking of the program's loops bounds it by a function of the call, which +turns this into a gas bound `G call` (`Shapes.Resources`). +-/ + +namespace SolidCore.Refinement.Solar.AssembleLoop + +open SolidCore.Refinement.Solar.Assemble SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +/-- The gas a run of a program the loop checker accepts needs when it ends within `n` blocks. -/ +def gasBoundL (c : Cert) (n : Nat) : Nat := 22100 * (n * bmax c) + memoryGasCost c.top + +/-- **The forward assembly theorem for code with loops.** -/ +theorem forward_of_checkL {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (hc : checkL p code c mx = true) (o : SolarTV.Machine.Oracle) (ho : c.env = true → OracleOk o) + (he : c.reads = true → EnvOk o) (call : SolarTV.Call) (n : Nat) + (r : SolarTV.Machine.Halt × SolarTV.Machine.State) + (hit : SolarTV.Machine.iterate (SolarTV.EVM.Program.block o call p) n + (0, [], SolarTV.Machine.State.initial call) = some r) + {gas : Nat} (hg : gasBoundL c n ≤ gas) : + Final.Target.runWith gas code call = some (SolarTV.Machine.observe call r.2 r.1) := by + obtain ⟨G, hseg, hneed0⟩ := globL_of_checkL hc + have hm0 : memoryGasCost (ByteArray.empty).size = 0 := by decide + refine run_of_rel_with code call r.2 r.1 gas fun st R => ?_ + have E0 : EntryL c code call (lowerFrom p c 0 (p.blocks.drop 0)) (n * bmax c) 0 + (SolarTV.Machine.State.initial call) .empty gas := + ⟨by rw [List.drop_zero]; exact hseg, by rw [hm0]; unfold gasBoundL at hg; omega, by simp, + memRel_initial⟩ + have hsim := run_simL (msg := Final.Target.messageWith gas code call) (ss0 := Substate.empty) G + rfl (by simp [Final.Target.messageWith, Target.message]) rfl rfl rfl ho rfl rfl he n 0 [] [] _ 0 + .empty gas st Substate.empty (Nat.zero_le _) (fun _ => ⟨by simp [hneed0], by simp⟩) (SR.nil c _) + E0 R + exact SpecG.toSpec (hsim.1 r hit) + +/-- The forward stage at one gas, for the calls whose run ends within `n call` blocks. -/ +theorem stage_of_checkL_gas {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (hc : checkL p code c mx = true) (o : SolarTV.Machine.Oracle) (ho : c.env = true → OracleOk o) + (he : c.reads = true → EnvOk o) (call : SolarTV.Call) (n : Nat) + (ends : ∃ r, SolarTV.Machine.iterate (SolarTV.EVM.Program.block o call p) n + (0, [], SolarTV.Machine.State.initial call) = some r) + {gas : Nat} (hg : gasBoundL c n ≤ gas) (obs : SolarTV.Observable) + (hrun : (SolarTV.evmirSem o).run p call = some obs) : + Final.Target.runWith gas code call = some obs := by + obtain ⟨r, hit⟩ := ends + have hres : (SolarTV.evmirSem o).run p call = some (SolarTV.Machine.observe call r.2 r.1) := by + change (SolarTV.EVM.Program.layer.result o p call).map _ = _ + rw [SolarTV.EVM.Program.layer.result_of_ends ⟨n, hit⟩] + rfl + rw [hres] at hrun + cases hrun + exact forward_of_checkL hc o ho he call n r hit hg + +/-- +info: 'SolidCore.Refinement.Solar.AssembleLoop.stage_of_checkL_gas' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms stage_of_checkL_gas + +end SolidCore.Refinement.Solar.AssembleLoop diff --git a/SolidCore/Refinement/Solar/AssembleLoop.lean b/SolidCore/Refinement/Solar/AssembleLoop.lean new file mode 100644 index 00000000..a69ae589 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleLoop.lean @@ -0,0 +1,528 @@ +import SolidCore.Refinement.Solar.AssembleSim +import SolidCore.Refinement.Evm.Lemmas +import EthLib.Execution.Proofs.Evm.Logic.LessGas + +/-! +# EVM IR to bytecode, for code with loops: the checker + +`Assemble.check` bounds every run by a static potential, the items from a block to the end of the +layout, so it accepts only code whose jumps go forward. This file's checker, `checkL`, accepts +code with loops: each block has a budget, a bound on the items one run of it executes (the +certificate's `costs`), and a jump or a fall may go to any labelled block, backward too. The +budget's item count is spent within a block; across blocks a run executes at most `bmax c` items +per block it enters, so a run of SolarTV that enters `n` blocks runs in EthLib with gas for +`22100 * bmax c` per block (`AssembleLoopRun.lean`), and the other gases follow from EthLib's +facts on runs with less gas (`Logic.LessGas`). + +Stack heights: the certificate's `needs` bound each block's entry height from below, as in +`Assemble.check`, and `maxs` from above: a jump from a block entered at most `maxH b` high +with `h` words over the `need b` it was entered with lands at most `h + maxH b - need b` +high, which the checker bounds by the target's `maxH`. So the stack stays below 1024 on every +run however many blocks it enters (`maxH t + budget t ≤ 1000`). + +The rest is `Assemble.check`'s: the code's linear decoding is the lowered program at the +layout, labels are valid jump destinations, the stack types, memory accesses at constant +offsets below the certificate's bound, and the same fragment of instructions, with SLT, SGT, +ADDRESS and the reads of the block and the transaction `envRead` names (TIMESTAMP, NUMBER, +CHAINID, COINBASE, GASLIMIT, GASPRICE, ORIGIN) besides. ADDRESS needs no hypothesis: it reads +the callee both semantics fix. The reads need the certificate's `reads` flag, and the theorems +then hold under every oracle whose reads are those of EthLib's environment of the call +(`EnvOk`, met by `envOracle` of any oracle). External calls, GAS, RETURNDATASIZE, +RETURNDATACOPY, CALLDATACOPY, CODECOPY, creations and immutables stay outside. +-/ + +namespace SolidCore.Refinement.Solar.AssembleLoop + +open SolidCore.Refinement.Solar.Assemble +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +/-! ## The checker -/ + +/-- Block `t`'s budget: a bound on the items one run of it executes, its label included. -/ +def budget (c : Cert) (t : Nat) : Nat := c.costs.getD t 0 + +/-- The largest budget: a bound on the items of one run of any block. -/ +def bmax (c : Cert) : Nat := c.costs.foldr max 0 + +/-- The highest stack block `t` is entered with. -/ +def maxH (mx : List Nat) (t : Nat) : Nat := mx.getD t 0 + +/-- A jump from block `b` to block `t` with a stack of at least `h` words typed `ty`: `t` is a +labelled block, finds the height and the types it needs, and the stack, at most `h` words over +the `need b` block `b` was entered with, fits `t`'s highest entry. -/ +def jumpOkL (p : Program) (c : Cert) (mx : List Nat) (b t h : Nat) (ty : List Ty) : Bool := + decide (t < p.blocks.length) && isTarget p c t && decide (c.need t ≤ h) && tyLe ty (c.entry t) && + decide (h + maxH mx b ≤ maxH mx t + c.need b) + +/-- Block `b` falls into the next one with a stack of at least `h` words typed `ty`. -/ +def fallOkL (p : Program) (c : Cert) (mx : List Nat) (b h : Nat) (ty : List Ty) : Bool := + (decide (p.blocks.length ≤ b + 1) || decide (c.need (b + 1) ≤ h)) && tyLe ty (c.entry (b + 1)) && + decide (h + maxH mx b ≤ maxH mx (b + 1) + c.need b) + +/-- The constants the check knows on the stack: `some v` at depth `i` when the word there is +`v`, `none` when it is unknown; the words past the list are unknown. -/ +abbrev Known := List (Option Word) + +/-- The constant the check knows at depth `i`. -/ +def kAt (known : Known) (i : Nat) : Option Word := (known[i]?).join + +/-- What the known constants claim of a stack: each known word is the stack's word there. -/ +def KR (known : Known) (S : List Word) : Prop := ∀ i v, kAt known i = some v → S[i]? = some v + +theorem KR.nil (S : List Word) : KR [] S := fun i v h => by simp [kAt] at h + +theorem KR.cons_none {known : Known} {S : List Word} (h : KR known S) (a : Word) : + KR (none :: known) (a :: S) := by + intro i v hv + cases i with + | zero => simp [kAt] at hv + | succ i => exact h i v (by simpa [kAt] using hv) + +theorem KR.cons_some {known : Known} {S : List Word} (h : KR known S) (a : Word) : + KR (some a :: known) (a :: S) := by + intro i v hv + cases i with + | zero => simp [kAt] at hv; simp [hv] + | succ i => exact h i v (by simpa [kAt] using hv) + +theorem KR.tail {j : Option Word} {known : Known} {a : Word} {S : List Word} + (h : KR (j :: known) (a :: S)) : KR known S := fun i v hv => by + simpa using h (i + 1) v (by simpa [kAt] using hv) + +theorem KR.head {o : Word} {known : Known} {a : Word} {S : List Word} + (h : KR (some o :: known) (a :: S)) : o = a ∧ KR known S := + ⟨by simpa [kAt, eq_comm] using h 0 o (by simp [kAt]), h.tail⟩ + +theorem KR.drop {known : Known} {S : List Word} (h : KR known S) (n : Nat) : + KR (known.drop n) (S.drop n) := fun i v hv => by + rw [List.getElem?_drop] + exact h (n + i) v (by simpa [kAt, List.getElem?_drop] using hv) + +theorem KR.not_nil {o : Word} {known : Known} (h : KR (some o :: known) []) : False := by + simpa using h 0 o (by simp [kAt]) + +theorem KR.not_one {j : Option Word} {o x : Word} {known : Known} (h : KR (j :: some o :: known) [x]) : + False := by + simpa using h 1 o (by simp [kAt]) + +/-- DUP of the word at depth `i` pushes what the check knows of it. -/ +theorem KR.dup {known : Known} {S : List Word} (h : KR known S) {i : Nat} (hi : i < S.length) : + KR (kAt known i :: known) (S[i] :: S) := by + intro j v hv + cases j with + | zero => + have := h i v (by simpa [kAt] using hv) + simp only [List.getElem?_cons_zero] + rw [List.getElem?_eq_getElem hi] at this + exact this + | succ j => exact h j v (by simpa [kAt] using hv) + +/-- `Assemble.blockStep` for block `b` of code with loops: the same check of each instruction, +with `jumpOkL` for its jumps, which put no bound on the target's budget, and MLOAD at a constant +offset below the certificate's bound. -/ +def blockStepL (p : Program) (c : Cert) (mx : List Nat) (b : Nat) + (ok : Nat → Known → List Ty → Nat → Bool) : + Nat → Known → List Ty → Nat → Assemble.Instr → Bool + | h, known, ty, k, .op (.stack op) => + match op with + | .push v => decide (1 ≤ k) && ok (h + 1) (some v :: known) (some false :: ty) (k - 1) + | .dup i => decide (1 ≤ k) && decide (i.val < 16) && decide (i.val + 1 ≤ h) && + ok (h + 1) (kAt known i.val :: known) (tyAt ty i.val :: ty) (k - 1) + | .swap i => decide (1 ≤ k) && decide (i.val < 16) && decide (i.val + 2 ≤ h) && + ok h [] (tySwap ty i.val) (k - 1) + | .pop => decide (1 ≤ k) && decide (1 ≤ h) && ok (h - 1) [] ty.tail (k - 1) + | op => + match stackNeed op with + | some (need, d) => decide (1 ≤ k) && decide (need ≤ h) && isData ty need && + ok (h + d).toNat (none :: known.drop need) (some false :: ty.drop need) (k - 1) + | none => false + | h, known, ty, k, .op .store => + match known with + | some o :: _ => decide (1 ≤ k) && decide (2 ≤ h) && decide (o.toNat + 32 ≤ c.top) && isData ty 2 && + ok (h - 2) (known.drop 2) (ty.drop 2) (k - 1) + | _ => false + | h, known, ty, k, .op .load => + match known with + | some o :: _ => decide (1 ≤ k) && decide (1 ≤ h) && decide (o.toNat + 32 ≤ c.top) && isData ty 1 && + ok h [] (some false :: ty.drop 1) (k - 1) + | _ => false + | h, _, ty, k, .effect .callvalue 0 => decide (1 ≤ k) && ok (h + 1) [] (some false :: ty) (k - 1) + | h, _, ty, k, .effect .calldatasize 0 => decide (1 ≤ k) && ok (h + 1) [] (some false :: ty) (k - 1) + | h, known, ty, k, .effect .caller 0 => + c.env && decide (1 ≤ k) && ok (h + 1) (none :: known) (some false :: ty) (k - 1) + | h, _, ty, k, .effect .address 0 => decide (1 ≤ k) && ok (h + 1) [] (some false :: ty) (k - 1) + | h, _, ty, k, .effect (.env name) 0 => + c.reads && (envRead name).isSome && decide (1 ≤ k) && ok (h + 1) [] (some false :: ty) (k - 1) + | h, known, ty, k, .effect .calldataload 1 => decide (1 ≤ k) && decide (1 ≤ h) && isData ty 1 && + ok h (none :: known.drop 1) (some false :: ty.drop 1) (k - 1) + | h, _, ty, k, .effect .sload 1 => decide (1 ≤ k) && decide (1 ≤ h) && isData ty 1 && + ok h [] (some false :: ty.drop 1) (k - 1) + | h, _, ty, k, .effect .sstore 2 => decide (1 ≤ k) && decide (2 ≤ h) && isData ty 2 && + ok (h - 2) [] (ty.drop 2) (k - 1) + | h, known, ty, k, .effect .keccak256 2 => + match known with + | some o :: some s :: _ => c.env && decide (1 ≤ k) && decide (2 ≤ h) && isData ty 2 && rangeOk c o s && + decide (keccak256Cost s ≤ 22100) && ok (h - 1) [] (some false :: ty.drop 2) (k - 1) + | _ => false + | h, known, ty, k, .effect (.log n) a => + match known with + | some o :: some s :: _ => decide (n ≤ 4) && decide (a = n + 2) && decide (1 ≤ k) && decide (n + 2 ≤ h) && + isData ty (n + 2) && rangeOk c o s && decide (logCost n s ≤ 22100) && + ok (h - (n + 2)) [] (ty.drop (n + 2)) (k - 1) + | _ => false + | h, _, ty, k, .jump t => decide (2 ≤ k) && jumpOkL p c mx b t h ty + | h, _, ty, k, .jumpi t => + decide (2 ≤ k) && decide (1 ≤ h) && isData ty 1 && jumpOkL p c mx b t (h - 1) ty.tail && + ok (h - 1) [] ty.tail (k - 2) + | h, _, ty, k, .pushLabel t => + decide (1 ≤ k) && c.rets.contains t && decide (t < 2 ^ 32) && ok (h + 1) [] (some true :: ty) (k - 1) + | h, _, ty, k, .jumpDyn => + decide (1 ≤ k) && decide (1 ≤ h) && tyAt ty 0 == some true && + c.rets.all fun t => jumpOkL p c mx b t (h - 1) ty.tail + | _, _, _, _, .stop => true + | _, known, ty, _, .ret | _, known, ty, _, .revert => + match known with + | some o :: some s :: _ => isData ty 2 && rangeOk c o s + | _ => false + | _, _, _, _, _ => false + +/-- `Assemble.blockOk` for code with loops. -/ +def blockOkL (p : Program) (c : Cert) (mx : List Nat) (b : Nat) : + Nat → Known → List Ty → Nat → List Assemble.Instr → Bool + | h, _, ty, _, [] => fallOkL p c mx b h ty + | h, known, ty, k, i :: rest => + match turnedElse c b i rest with + | some e => + decide (3 ≤ k) && decide (1 ≤ h) && isData ty 1 && jumpOkL p c mx b e (h - 1) ty.tail && + fallOkL p c mx b (h - 1) ty.tail + | none => + if dropped p b i rest then + match i with + | .stop => true + | _ => fallOkL p c mx b h ty + else blockStepL p c mx b (fun h known ty k => blockOkL p c mx b h known ty k rest) h known ty k i + +/-- Every block checks from the height and the types it needs, within its budget less its +label's item, with its highest entry stack and budget below 1000 words. -/ +def blocksOkL (p : Program) (c : Cert) (mx : List Nat) : Nat → List (List Assemble.Instr) → Bool + | _, [] => true + | b, instrs :: rest => + decide (labelItems p c b ≤ budget c b) && decide (c.need b ≤ maxH mx b) && + decide (maxH mx b + budget c b ≤ 1000) && + blockOkL p c mx b (c.need b) [] (c.entry b) (budget c b - labelItems p c b) instrs && + blocksOkL p c mx (b + 1) rest + +/-- The checker for code with loops. -/ +def checkL (p : Program) (code : ByteArray) (c : Cert) (mx : List Nat) : Bool := + (walk (bytesOf code) c.offset 0 (lower p c)).isSome && blocksOkL p c mx 0 p.blocks && + labelsValid p c code && decide (c.need 0 = 0) && decide (c.top % 32 = 0) && + decide (c.top ≤ 2 ^ 32) && decide (code.size < 2 ^ 32) + +/-! ## What the check gives -/ + +theorem getD_le_foldr_max : ∀ (l : List Nat) (t : Nat), l.getD t 0 ≤ l.foldr max 0 + | [], _ => by simp + | x :: l, 0 => by simp + | x :: l, t + 1 => by + simp only [List.getD_cons_succ, List.foldr_cons] + exact Nat.le_trans (getD_le_foldr_max l t) (Nat.le_max_right _ _) + +theorem budget_le_bmax (c : Cert) (t : Nat) : budget c t ≤ bmax c := getD_le_foldr_max _ _ + +theorem blocksOkL_get {p : Program} {c : Cert} {mx : List Nat} : ∀ (l : List (List Assemble.Instr)) (b : Nat), + blocksOkL p c mx b l = true → ∀ k (hk : k < l.length), + labelItems p c (b + k) ≤ budget c (b + k) ∧ c.need (b + k) ≤ maxH mx (b + k) ∧ + maxH mx (b + k) + budget c (b + k) ≤ 1000 ∧ + blockOkL p c mx (b + k) (c.need (b + k)) [] (c.entry (b + k)) + (budget c (b + k) - labelItems p c (b + k)) l[k] = true + | [], _, _, _, hk => absurd hk (by simp) + | x :: l, b, h, 0, _ => by + simp only [blocksOkL, Bool.and_eq_true, decide_eq_true_eq] at h + simpa [and_assoc] using h.1 + | x :: l, b, h, k + 1, hk => by + simp only [blocksOkL, Bool.and_eq_true] at h + have := blocksOkL_get l (b + 1) h.2 k (by simp at hk; omega) + rw [show b + (k + 1) = b + 1 + k by omega] + simpa using this + +/-- The facts of the check the simulation uses at every block. -/ +structure GlobL (p : Program) (c : Cert) (mx : List Nat) (code : ByteArray) : Prop where + top_mod : c.top % 32 = 0 + top_le : c.top ≤ 2 ^ 32 + size_lt : code.size < 2 ^ 32 + target : ∀ t, t < p.blocks.length → isTarget p c t = true → + isValidJumpDest (validJumpDestinations code) (c.offset t) = true ∧ c.offset t < code.size ∧ + Seg (bytesOf code) c.offset (c.offset t) (lowerFrom p c t (p.blocks.drop t)) code.size + block : ∀ t (ht : t < p.blocks.length), labelItems p c t ≤ budget c t ∧ + c.need t ≤ maxH mx t ∧ maxH mx t + budget c t ≤ 1000 ∧ + blockOkL p c mx t (c.need t) [] (c.entry t) (budget c t - labelItems p c t) p.blocks[t] = true + +/-- The facts of the check the simulation of one block uses: `GlobL`'s but the blocks' checks, +so that one block may be simulated under a certificate of its own (one of its contexts). -/ +structure GlobLT (p : Program) (c : Cert) (code : ByteArray) : Prop where + top_mod : c.top % 32 = 0 + top_le : c.top ≤ 2 ^ 32 + size_lt : code.size < 2 ^ 32 + target : ∀ t, t < p.blocks.length → isTarget p c t = true → + isValidJumpDest (validJumpDestinations code) (c.offset t) = true ∧ c.offset t < code.size ∧ + Seg (bytesOf code) c.offset (c.offset t) (lowerFrom p c t (p.blocks.drop t)) code.size + +theorem GlobL.toT {p : Program} {c : Cert} {mx : List Nat} {code : ByteArray} (G : GlobL p c mx code) : + GlobLT p c code := + ⟨G.top_mod, G.top_le, G.size_lt, G.target⟩ + +theorem globL_of_checkL {p : Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (h : checkL p code c mx = true) : + GlobL p c mx code ∧ Seg (bytesOf code) c.offset 0 (lower p c) code.size ∧ c.need 0 = 0 := by + simp only [checkL, Bool.and_eq_true, decide_eq_true_eq] at h + obtain ⟨⟨⟨⟨⟨⟨hw, hblocks⟩, hlabels⟩, hneed⟩, hmod⟩, htop⟩, hsize⟩ := h + obtain ⟨stream, hw⟩ := Option.isSome_iff_exists.1 hw + have hseg : Seg (bytesOf code) c.offset 0 (lower p c) code.size := by + have := seg_of_walk (walk_sound hw) + rwa [length_bytesOf] at this + refine ⟨⟨hmod, htop, hsize, fun t ht htgt => ?_, fun t ht => ?_⟩, hseg, hneed⟩ + · have hv : isValidJumpDest (validJumpDestinations code) (c.offset t) = true := by + simp only [labelsValid, List.all_eq_true, List.mem_range] at hlabels + have := hlabels t ht + simpa [htgt] using this + obtain ⟨pc', hs, hpc⟩ := seg_lowerFrom p c t p.blocks 0 0 hseg ht + simp only [Nat.zero_add] at hs hpc + rw [← hpc htgt] at hs + refine ⟨hv, ?_, hs⟩ + have hs' := hs + rw [lowerFrom_drop p c ht] at hs' + simp only [lowerBlock, htgt, ite_true, List.cons_append] at hs' + cases hs' with + | cons d _ _ => + have := decode_lt d + rwa [length_bytesOf] at this + · have := blocksOkL_get p.blocks 0 hblocks t ht + simpa using this + +/-! ## The invariants -/ + +/-- `Assemble.Inv` with a reserve: inside a block, with `k` items of its budget left and gas for +`R` more items of the blocks the run enters after it. -/ +structure InvL (c : Cert) (code : ByteArray) (call : SolarTV.Call) (items : List Item) + (k R pc : Nat) (S : List Word) (s : SolarTV.Machine.State) (M : ByteArray) (g : Nat) : Prop where + seg : Seg (bytesOf code) c.offset pc items code.size + stack : S.length + k ≤ 1000 + gas : 22100 * (k + R) + (memoryGasCost c.top - memoryGasCost M.size) ≤ g + le_top : M.size ≤ c.top + mem : MemRel s.memory M + +/-- At a block's entry, with gas for `R` more items. -/ +structure EntryL (c : Cert) (code : ByteArray) (call : SolarTV.Call) (items : List Item) + (R pc : Nat) (s : SolarTV.Machine.State) (M : ByteArray) (g : Nat) : Prop where + seg : Seg (bytesOf code) c.offset pc items code.size + gas : 22100 * R + (memoryGasCost c.top - memoryGasCost M.size) ≤ g + le_top : M.size ≤ c.top + mem : MemRel s.memory M + +theorem InvL.next {c : Cert} {code : ByteArray} {call : SolarTV.Call} {item : Item} + {items : List Item} {k R pc next : Nat} {S S' : List Word} {s : SolarTV.Machine.State} + {M : ByteArray} {g g' : Nat} (I : InvL c code call (item :: items) k R pc S s M g) (hk : 1 ≤ k) + (hseg : Seg (bytesOf code) c.offset next items code.size) (hS : S'.length ≤ S.length + 1) + (hg : g ≤ g' + 22100) : InvL c code call items (k - 1) R next S' s M g' where + seg := hseg + stack := by have := I.stack; omega + gas := by have := I.gas; omega + le_top := I.le_top + mem := I.mem + +theorem InvL.next2 {c : Cert} {code : ByteArray} {call : SolarTV.Call} {i1 i2 : Item} + {items : List Item} {k R pc next : Nat} {S S' : List Word} {s : SolarTV.Machine.State} + {M : ByteArray} {g g' : Nat} (I : InvL c code call (i1 :: i2 :: items) k R pc S s M g) + (hk : 2 ≤ k) (hseg : Seg (bytesOf code) c.offset next items code.size) + (hS : S'.length ≤ S.length + 1) (hg : g ≤ g' + 44200) : + InvL c code call items (k - 2) R next S' s M g' where + seg := hseg + stack := by have := I.stack; omega + gas := by have := I.gas; omega + le_top := I.le_top + mem := I.mem + +/-- A block's end, falling into the next one: the entry invariant with the reserve. -/ +theorem InvL.entry {c : Cert} {code : ByteArray} {call : SolarTV.Call} {items : List Item} + {k R pc : Nat} {S : List Word} {s : SolarTV.Machine.State} {M : ByteArray} {g : Nat} + (I : InvL c code call items k R pc S s M g) : EntryL c code call items R pc s M g where + seg := I.seg + gas := by have := I.gas; omega + le_top := I.le_top + mem := I.mem + +/-- A jump's target block, at its offset, from the invariant before the `m` items of the jump. -/ +theorem InvL.target {p : Program} {c : Cert} {code : ByteArray} + (G : GlobLT p c code) {call : SolarTV.Call} {t m : Nat} {items : List Item} {k R pc : Nat} + {S : List Word} {s : SolarTV.Machine.State} {M : ByteArray} {g g' : Nat} + (I : InvL c code call items k R pc S s M g) (htn : t < p.blocks.length) + (htgt : isTarget p c t = true) (hm : m ≤ k) (hg : g ≤ g' + 22100 * m) : + EntryL c code call (lowerFrom p c t (p.blocks.drop t)) R (c.offset t) s M g' where + seg := (G.target t htn htgt).2.2 + gas := by + have := I.gas + have hm' : 22100 * m ≤ 22100 * k := Nat.mul_le_mul_left _ hm + rw [Nat.mul_add] at this + omega + le_top := I.le_top + mem := I.mem + +/-! ## EthLib's rules over steps monotone in gas -/ + +section Rules + +variable {code : ByteArray} {msg : Message .fusaka} {pc gas : Nat} {M : ByteArray} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray} + +/-- PUSH of a decoded constant, PUSH0 or PUSHn. -/ +theorem push_itemG {v next : Nat} {stack : List Word} + (h : decode (bytesOf code) pc = some (.push v, next)) (hgas : 3 ≤ gas) + (hstack : stack.length < 1024) : + ∃ g, gas - 3 ≤ g ∧ HoareG .fusaka (At code msg pc stack M gas st ss rd) + (At code msg next (BitVec.ofNat 256 v :: stack) M g st ss rd) := by + obtain ⟨byte, hb, h⟩ := decode_push h + obtain ⟨hlt, hcode⟩ := getElem?_bytesOf hb + rcases h with ⟨rfl, rfl, rfl⟩ | ⟨h1, h2, rfl, hle, rfl⟩ + · exact ⟨gas - 2, by omega, + (SolidCore.Refinement.Evm.Logic.push0GA (by decide) hlt hcode (by omega) hstack).toG⟩ + · have hn : byte - PUSH1 < 32 := by unfold PUSH1 PUSH32 at *; omega + have hdec := decode_pushByte ⟨byte - PUSH1, hn⟩ + have hbyte : 0x60 + (byte - PUSH1) = byte := by unfold PUSH1 at *; omega + simp only [hbyte] at hdec + refine ⟨gas - 3, le_refl _, ?_⟩ + have hle' : pc + 1 + (byte - PUSH1 + 1) ≤ code.size := by rw [← length_bytesOf]; exact hle + have := push_of_decodeG (fork := .fusaka) (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := rd) hlt hcode hdec (by simp) + (pushData_eq hle') hgas hstack + simpa [Nat.add_assoc] using this + +set_option hygiene false in +/-- A two-operand stack operation. -/ +local macro "bin_ruleG" agree:term : tactic => `(tactic| ( + rcases stack with _ | ⟨x, _ | ⟨y, rest⟩⟩ <;> simp only [SolarTV.EVM.step, reduceCtorEq, + Option.some.injEq] at hstep + subst hstep + refine ⟨_, le_refl _, ?_⟩ + rw [← $agree x y] + exact binaryG hlt hcode rfl (instr_stack _ _ rfl) (Nat.le_trans (m := 3) (by decide) hgas))) + +set_option hygiene false in +/-- A one-operand stack operation. -/ +local macro "un_ruleG" agree:term : tactic => `(tactic| ( + rcases stack with _ | ⟨x, rest⟩ <;> simp only [SolarTV.EVM.step, reduceCtorEq, + Option.some.injEq] at hstep + subst hstep + refine ⟨_, le_refl _, ?_⟩ + rw [← $agree x] + exact unaryG hlt hcode rfl (instr_stack _ _ rfl) (Nat.le_trans (m := 3) (by decide) hgas))) + +/-- ADDRESS pushes the word of the callee, `SolarTV.environment.callee`. -/ +theorem address_word : (Target.address selfAddress).toU256 = + BitVec.ofNat 256 SolarTV.environment.callee := by + decide +kernel + +/-- An environment read of the fragment pushes the word `envRead` gives, for 2 gas, from +EthLib's environment of `Target`'s calls. -/ +theorem env_readG {name : String} {byte w : Nat} {stack : List Word} + (he : envRead name = some (byte, w)) (hlt : pc < code.size) + (hcode : code[pc] = UInt8.ofNat byte) (hblock : msg.blockEnv = Target.blockEnv) + (htx : msg.txEnv = Target.txEnv) (hgas : 2 ≤ gas) (hstack : stack.length < STACK_LIMIT) : + HoareG .fusaka (At code msg pc stack M gas st ss rd) + (At code msg (pc + 1) (BitVec.ofNat 256 w :: stack) M (gas - 2) st ss rd) := by + unfold envRead at he + split at he <;> simp only [Option.some.injEq, Prod.mk.injEq, reduceCtorEq] at he <;> + obtain ⟨rfl, rfl⟩ := he + · exact (push_of_readFrameGA (op := .origin) hlt hcode (ofByte_of_decode rfl (by decide)) rfl + (fun _ _ hm _ _ => by rw [hm, htx]; decide +kernel) hgas hstack).toG + · exact (push_of_readFrameGA (op := .gasprice) hlt hcode (ofByte_of_decode rfl (by decide)) rfl + (fun _ _ hm _ _ => by rw [hm, htx]; decide +kernel) hgas hstack).toG + · exact (push_of_readFrameGA (op := .coinbase) hlt hcode (ofByte_of_decode rfl (by decide)) rfl + (fun _ _ hm _ _ => by rw [hm, hblock]; decide +kernel) hgas hstack).toG + · exact (push_of_readFrameGA (op := .timestamp) hlt hcode (ofByte_of_decode rfl (by decide)) rfl + (fun _ _ hm _ _ => by rw [hm, hblock]; decide +kernel) hgas hstack).toG + · exact (push_of_readFrameGA (op := .number) hlt hcode (ofByte_of_decode rfl (by decide)) rfl + (fun _ _ hm _ _ => by rw [hm, hblock]; decide +kernel) hgas hstack).toG + · exact (push_of_readFrameGA (op := .gaslimit) hlt hcode (ofByte_of_decode rfl (by decide)) rfl + (fun _ _ hm _ _ => by rw [hm, hblock]; decide +kernel) hgas hstack).toG + · exact (push_of_readFrameGA (op := .chainid) hlt hcode (ofByte_of_decode rfl (by decide)) rfl + (fun _ _ hm _ _ => by rw [hm, hblock]; decide +kernel) hgas hstack).toG + +/-- `Assemble.stack_rule_cheap` over steps monotone in gas. -/ +theorem stack_rule_cheapG {op : SolarTV.EVM.Op} {byte : Nat} {stack next : List Word} + {r : Word} (hm : low op = false) (hb : opByte op = some byte) (hlt : pc < code.size) + (hcode : code[pc] = UInt8.ofNat byte) + (hstep : SolarTV.EVM.step ⟨BitVec.ofNat 256 msg.data.size, r⟩ op stack = some next) + (hgas : 3 ≤ gas) (hlen : stack.length < 1024) : + ∃ g, gas - 3 ≤ g ∧ HoareG .fusaka (At code msg pc stack M gas st ss rd) + (At code msg (pc + 1) next M g st ss rd) := by + cases op <;> simp only [opByte, reduceCtorEq, Option.some.injEq] at hb <;> try subst hb + case mod | mul | div => simp [low] at hm + case add => bin_ruleG add_agree + case sub => bin_ruleG sub_agree + case lt => bin_ruleG lt_agree + case gt => bin_ruleG gt_agree + case slt => bin_ruleG slt_agree + case sgt => bin_ruleG sgt_agree + case eq => bin_ruleG eq_agree + case and => bin_ruleG and_agree + case or => bin_ruleG or_agree + case xor => bin_ruleG xor_agree + case byte => bin_ruleG byte_agree + case shl => bin_ruleG shl_agree + case shr => bin_ruleG shr_agree + case iszero => un_ruleG iszero_agree + case not => un_ruleG not_agree + case pop => + rcases stack with _ | ⟨x, rest⟩ <;> simp only [SolarTV.EVM.step, reduceCtorEq, + Option.some.injEq] at hstep + subst hstep + exact ⟨_, by omega, popG hlt hcode (by omega)⟩ + case calldatasize => + simp only [SolarTV.EVM.step, Option.some.injEq] at hstep + subst hstep + exact ⟨_, by omega, calldatasizeG hlt hcode (by omega) hlen⟩ + case dup i => + split at hb + · rename_i hi + simp only [Option.some.injEq] at hb + subst hb + simp only [SolarTV.EVM.step, Option.map_eq_some_iff] at hstep + obtain ⟨x, hx, rfl⟩ := hstep + exact ⟨_, le_refl _, dupG (⟨i.val, hi⟩ : Fin 16) hlt hcode hx hgas hlen⟩ + · simp at hb + case swap i => + split at hb + · rename_i hi + simp only [Option.some.injEq] at hb + subst hb + rcases stack with _ | ⟨top, rest⟩ + · simp [SolarTV.EVM.step] at hstep + · simp only [SolarTV.EVM.step, Option.map_eq_some_iff] at hstep + obtain ⟨x, hx, rfl⟩ := hstep + exact ⟨_, le_refl _, swap_of_decodeG hlt hcode (decode_swap ⟨i.val, hi⟩) hx hgas⟩ + · simp at hb + +/-- `Assemble.stack_rule` over steps monotone in gas. -/ +theorem stack_ruleG {op : SolarTV.EVM.Op} {byte : Nat} {stack next : List Word} + {r : Word} (hb : opByte op = some byte) (hlt : pc < code.size) + (hcode : code[pc] = UInt8.ofNat byte) + (hstep : SolarTV.EVM.step ⟨BitVec.ofNat 256 msg.data.size, r⟩ op stack = some next) + (hgas : 5 ≤ gas) (hlen : stack.length < 1024) : + ∃ g, gas - 5 ≤ g ∧ HoareG .fusaka (At code msg pc stack M gas st ss rd) + (At code msg (pc + 1) next M g st ss rd) := by + cases hm : low op + · obtain ⟨g, hg, H⟩ := stack_rule_cheapG hm hb hlt hcode hstep (Nat.le_trans (by decide) hgas) hlen + exact ⟨g, by omega, H⟩ + · cases op <;> simp [low] at hm <;> simp only [opByte, Option.some.injEq] at hb <;> subst hb <;> + rcases stack with _ | ⟨x, _ | ⟨y, rest⟩⟩ <;> simp only [SolarTV.EVM.step, reduceCtorEq, + Option.some.injEq] at hstep <;> subst hstep <;> refine ⟨_, le_refl _, ?_⟩ + all_goals first + | (rw [← mul_agree x y]; exact binaryG hlt hcode rfl (instr_stack _ _ rfl) hgas) + | (rw [← div_agree x y]; exact binaryG hlt hcode rfl (instr_stack _ _ rfl) hgas) + | (rw [← mod_agree x y]; exact binaryG hlt hcode rfl (instr_stack _ _ rfl) hgas) + +end Rules + +end SolidCore.Refinement.Solar.AssembleLoop diff --git a/SolidCore/Refinement/Solar/AssembleLoopEnv.lean b/SolidCore/Refinement/Solar/AssembleLoopEnv.lean new file mode 100644 index 00000000..014a061f --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleLoopEnv.lean @@ -0,0 +1,58 @@ +import SolidCore.Refinement.Solar.AssembleLoopWithin + +/-! +# The checker of code with loops on environment reads: an example and a mutant + +A program that reads the block's timestamp and the contract's address, compares them as signed +integers (SLT) and returns the result: the checker accepts its bytecode, so at every gas every +result of the bytecode is the program's under every oracle whose reads of the block and the +transaction are EthLib's (`Assemble.EnvOk`), which `Assemble.envOracle` gives every oracle. The +bytecode with NUMBER in place of TIMESTAMP is rejected: the checker's decoding of the code +differs from the program's lowering, by evaluation, not by a timeout. +-/ + +namespace SolidCore.Refinement.Solar.AssembleLoopEnv + +open SolidCore.Refinement.Solar SolidCore.Refinement.Solar.AssembleLoop SolidCore.Refinement.Final + +/-- TIMESTAMP, ADDRESS, SLT, then the word at offset 0 returned. -/ +def prog : Assemble.Program := + { blocks := [[.effect (.env "timestamp") 0, .effect .address 0, .op (.stack .slt), + .op (.stack (.push 0)), .op .store, .op (.stack (.push 32)), .op (.stack (.push 0)), .ret]] } + +/-- TIMESTAMP ADDRESS SLT PUSH0 MSTORE PUSH1 32 PUSH0 RETURN. -/ +def code : ByteArray := ⟨#[0x42, 0x30, 0x12, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3]⟩ + +/-- The same code with NUMBER (0x43) in place of TIMESTAMP. -/ +def mutant : ByteArray := ⟨#[0x43, 0x30, 0x12, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3]⟩ + +def cert : Assemble.Cert := + { offsets := [0], needs := [0], top := 32, costs := [8], types := [[]], reads := true } + +def maxs : List Nat := [0] + +theorem check_ok : checkL prog code cert maxs = true := by decide +kernel + +/-- The mutant fails the check by evaluation. -/ +theorem mutant_fails : checkL prog mutant cert maxs = false := by decide +kernel + +/-- Without the flag that states the environment hypothesis, the checker rejects the reads. -/ +theorem unflagged_fails : checkL prog code { cert with reads := false } maxs = false := by + decide +kernel + +/-- **At every gas, every result of the bytecode is the program's**, under every oracle whose +reads of the block and the transaction are EthLib's. -/ +theorem bytecode (o : SolarTV.Machine.Oracle) (he : Assemble.EnvOk o) (scope : SolarTV.Call → Prop) + (gas : Nat) : Within (SolarTV.evmirSem o) (ethLibWith gas) prog code scope := + within_of_checkL check_ok o (fun h => absurd h (by decide)) scope gas (fun _ => he) + +/-- The hypothesis is met: every oracle's form with EthLib's environment satisfies it. -/ +theorem bytecode_env (o : SolarTV.Machine.Oracle) (scope : SolarTV.Call → Prop) (gas : Nat) : + Within (SolarTV.evmirSem (Assemble.envOracle o)) (ethLibWith gas) prog code scope := + bytecode _ (Assemble.envOracle_ok o) scope gas + +/-- info: 'SolidCore.Refinement.Solar.AssembleLoopEnv.bytecode_env' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecode_env + +end SolidCore.Refinement.Solar.AssembleLoopEnv diff --git a/SolidCore/Refinement/Solar/AssembleLoopRun.lean b/SolidCore/Refinement/Solar/AssembleLoopRun.lean new file mode 100644 index 00000000..1054b876 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleLoopRun.lean @@ -0,0 +1,148 @@ +import SolidCore.Refinement.Solar.AssembleLoopSim +import Verify.Final + +/-! +# EVM IR to bytecode, for code with loops: every gas + +`run_simL` runs EthLib's interpreter as SolarTV runs the program from a block, over steps +monotone in gas, with gas for `22100 * bmax c` per block the run enters: a run of SolarTV that ends +within `fuel` blocks is EthLib's run (its first part), and a run that is still going after `fuel` +blocks has EthLib spend gas with it (its second part, through the measure `meas`: a jump lands on a +labelled block, whose JUMPDEST costs gas, and a fall goes to the next block). + +`within_of_checkL`: at every gas, every result of the bytecode is SolarTV's result or a failure +that changes nothing. A run that succeeds at gas `g` is the run from the same frame with `K` more +gas, with exactly `K` more gas left at every step (`Logic.LessGas`); with `K` large, SolarTV ends +within as many blocks as the measure allows, and then EthLib's run with `K` more gas is SolarTV's. +-/ + +namespace SolidCore.Refinement.Solar.AssembleLoop + +open SolidCore.Refinement.Solar.Assemble +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +/-- The measure of a run at block `b` with `g` gas, in units of the layout's length plus two: +twice the gas, and one more at a block with no label; then the blocks to the end of the layout. -/ +def meas (p : Assemble.Program) (c : Cert) (g b : Nat) : Nat := + 2 * ((p.blocks.length + 2) * g) + (if isTarget p c b then 0 else p.blocks.length + 2) + + (p.blocks.length - b) + +/-- Each block a run enters lowers the measure. -/ +theorem meas_step {p : Assemble.Program} {c : Cert} {g g' b t : Nat} (hb : b < p.blocks.length) + (ht : t ≤ p.blocks.length) (hg : g' + (if isTarget p c b then 1 else 0) ≤ g) + (hj : t = b + 1 ∨ isTarget p c t = true) : meas p c g' t + 1 ≤ meas p c g b := by + unfold meas + generalize hW : p.blocks.length + 2 = W at * + have hL : p.blocks.length + 2 = W := hW + by_cases htb : isTarget p c b = true + · simp only [htb, ite_true] at hg ⊢ + have h1 : W * (g' + 1) ≤ W * g := Nat.mul_le_mul_left _ hg + rw [Nat.mul_succ] at h1 + split <;> omega + · simp only [htb, Bool.false_eq_true, ite_false, Nat.add_zero] at hg ⊢ + have h1 : W * g' ≤ W * g := Nat.mul_le_mul_left _ hg + rcases hj with rfl | htt + · split <;> omega + · simp only [htt, ite_true] + omega + +/-- A triple over steps monotone in gas does not raise the gas. -/ +theorem reaches_gas_le {a b : Evm .fusaka Nat} (h : Reaches (StepG .fusaka) a b) : b.gas ≤ a.gas := + Reaches.gasHeld_le (fun hs => Step.gasHeld_le hs.1) h + +open SolarTV.EVM.Program in +/-- EthLib runs the code from a block's offset as SolarTV runs the program from that block, over +steps monotone in gas, with gas for `fuel` blocks of the run: to SolarTV's result when it ends within +them, and with the measure lowered by `fuel` when it does not. -/ +theorem run_simL {p : Assemble.Program} {c : Cert} {mx : List Nat} {code : ByteArray} + (G : GlobL p c mx code) + {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) (ho : c.env = true → OracleOk o) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : msg.txEnv = Target.txEnv) + (he : c.reads = true → EnvOk o) : + ∀ (fuel b : Nat) (S T : List Word) (s : SolarTV.Machine.State) (pc : Nat) (M : ByteArray) + (g : Nat) (st : State.TransactionState) (ss : Substate), + b ≤ p.blocks.length → (b < p.blocks.length → c.need b ≤ S.length ∧ S.length ≤ maxH mx b) → + SR c (c.entry b) S T → + EntryL c code call (lowerFrom p c b (p.blocks.drop b)) (fuel * bmax c) pc s M g → + Rel msg ss0 st ss s → + (∀ r, SolarTV.Machine.iterate (block o call p) fuel (b, S, s) = some r → + SpecG .fusaka (At code msg pc T M g st ss .empty) (PostL call msg.currentTarget ss0 r.2 r.1)) ∧ + (SolarTV.Machine.iterate (block o call p) fuel (b, S, s) = none → + Triple (StepG .fusaka) (At code msg pc T M g st ss .empty) + (fun z => 2 * ((p.blocks.length + 2) * z.gas) + fuel ≤ meas p c g b)) + | 0, b, S, T, s, pc, M, g, st, ss, _, _, _, _, _ => by + refine ⟨fun r hr => by simp [SolarTV.Machine.iterate] at hr, fun _ evm hp => ⟨evm, Reaches.refl _, ?_⟩⟩ + obtain ⟨-, -, -, -, -, -, hg, -⟩ := hp + rw [hg] + unfold meas + omega + | fuel + 1, b, S, T, s, pc, M, g, st, ss, hle, hneed, hR, E, R => by + by_cases hb : b < p.blocks.length + · have hblk : p.blocks[b]? = some p.blocks[b] := List.getElem?_eq_getElem hb + obtain ⟨hL, hnm, hstk, hblock⟩ := G.block b hb + obtain ⟨hn, hm⟩ := hneed hb + have hbm := budget_le_bmax c b + have hfm : (fuel + 1) * bmax c = fuel * bmax c + bmax c := Nat.succ_mul _ _ + obtain ⟨pc1, g1, hlabel, hg1, I1⟩ : ∃ pc1 g1, HoareG .fusaka (At code msg pc T M g st ss .empty) + (At code msg pc1 T M g1 st ss .empty) ∧ g1 + (if isTarget p c b then 1 else 0) ≤ g ∧ + InvL c code call (lowerInstrs p c b p.blocks[b] ++ + lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) (budget c b - labelItems p c b) + (fuel * bmax c) pc1 S s M g1 := by + have E' := E + rw [lowerFrom_drop p c hb, lowerBlock, List.append_assoc] at E' + have hG := E'.gas + rw [hfm] at hG + by_cases ht : isTarget p c b = true + · have hl : labelItems p c b = 1 := by simp [labelItems, ht] + rw [hl] at hL ⊢ + simp only [ht, ite_true, List.singleton_append] at E' + obtain ⟨next, hd, hseg⟩ := E'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + exact ⟨pc + 1, g - 1, Logic.jumpdestG hlt hcode (by omega), by simp only [ht, ite_true]; omega, + ⟨hseg, by omega, by omega, E'.le_top, E'.mem⟩⟩ + · have hl : labelItems p c b = 0 := by simp [labelItems, ht] + rw [hl, Nat.sub_zero] + simp only [ht, Bool.false_eq_true, ite_false, List.nil_append] at E' + exact ⟨pc, g, Triple.of_imp fun _ h => h, by simp only [ht, Bool.false_eq_true, ite_false]; omega, + ⟨E'.seg, by omega, by omega, E'.le_top, E'.mem⟩⟩ + have hsim := exec_simL (o := o) G.toT hdata hvalue hstatic hself hcaller ho hbenv (fun _ => htx) he b hb (fuel * bmax c) + p.blocks[b] (c.need b) [] (c.entry b) S T _ s pc1 M g1 st ss hblock hn (by omega) + (KR.nil _) hR I1 R + simp only [SolarTV.Machine.iterate, block, hblk] + generalize exec o call b p.blocks[b] S s = x at hsim + rcases x with ⟨halt, s'⟩ | ⟨t, S', s'⟩ + · refine ⟨fun r hr => ?_, fun hr => by simp at hr⟩ + simp only [Option.some.injEq] at hr + subst hr + exact SpecG.seq hlabel hsim + · obtain ⟨⟨htle, hneedt, hj⟩, pc', T', M', g', st', ss', hh, hR', E', R'⟩ := hsim + have IH := run_simL G hdata hvalue hstatic hself hcaller ho hbenv htx he fuel t S' T' s' pc' M' g' st' ss' + htle hneedt hR' E' R' + refine ⟨fun r hr => SpecG.seq (Triple.seq hlabel hh) (IH.1 r hr), fun hr evm hp => ?_⟩ + obtain ⟨e1, r1, he1⟩ := hlabel evm hp + obtain ⟨mid, r2, hmid⟩ := hh e1 he1 + obtain ⟨z, r3, hz⟩ := IH.2 hr mid hmid + refine ⟨z, (r1.trans r2).trans r3, ?_⟩ + have hgm := reaches_gas_le r2 + rw [hmid.2.2.2.2.2.2.1, he1.2.2.2.2.2.2.1] at hgm + have := meas_step (c := c) (g := g) (g' := g') hb htle (by omega) hj + omega + · obtain rfl : b = p.blocks.length := by omega + have hblk : p.blocks[p.blocks.length]? = none := List.getElem?_eq_none (by omega) + simp only [SolarTV.Machine.iterate, block, hblk, ite_true] + refine ⟨fun r hr => ?_, fun hr => by simp at hr⟩ + simp only [Option.some.injEq] at hr + subst hr + have hseg := E.seg + rw [lowerFrom_nil p c (by omega)] at hseg + have hpc := hseg.nil_end + exact SpecG.consequence (stop_of_size_leG (by omega)) + (fun _ h => h) fun evm h => postL_stop R hself evm h + +end SolidCore.Refinement.Solar.AssembleLoop diff --git a/SolidCore/Refinement/Solar/AssembleLoopSim.lean b/SolidCore/Refinement/Solar/AssembleLoopSim.lean new file mode 100644 index 00000000..fa3cbab7 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleLoopSim.lean @@ -0,0 +1,1041 @@ +import SolidCore.Refinement.Solar.AssembleLoop + +/-! +# EVM IR to bytecode, for code with loops: the simulation of a block + +`Assemble.exec_sim` over the steps from frames monotone in gas (`HoareG`, `SpecG`), for the +checker of code with loops: from a block's instructions, EthLib's interpreter runs as SolarTV +does, to a halt or to the next block, reached with the gas for the reserve `R` (the items of the +blocks the run enters after it) and at most its highest entry stack. A jump goes to a labelled +block and a fall to the next one, which the run's measure of gas needs (`AssembleLoopRun`). +-/ + +namespace SolidCore.Refinement.Solar.AssembleLoop + +open SolidCore.Refinement.Solar.Assemble +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +/-! ## Rules over steps monotone in gas -/ + +section G + +variable {fork : Fork} {code : ByteArray} {message : Message fork} {pc : Nat} {stack : List U256} + {memory : ByteArray} {gas : Nat} {state : State.TransactionState} {substate : Substate} + {returnData : ByteArray} + +/-- A frame at or past the end of its code stops as STOP does, at no price. -/ +theorem stop_of_size_leG (hle : code.size ≤ pc) : + SpecG fork (At code message pc stack memory gas state substate returnData) + (Halted false .empty gas state substate) := by + apply Triple.of_step + rintro evm ⟨hcode, -, -, hpc, -, -, hg, hrun, herr, hout, hs, hss, -⟩ + refine ⟨_, ⟨.next hrun (step_of_size_le (by rw [hcode, hpc]; exact hle)), ?_⟩, rfl, rfl, herr, + hout, hg, hs, hss⟩ + rintro k low rfl + have hl : low.code.size ≤ low.pc := by + have h1 : (addGas k low).code = low.code := rfl + have h2 : (addGas k low).pc = low.pc := rfl + rw [← h1, ← h2, hcode, hpc]; exact hle + rw [step_of_size_le hl, step_of_size_le (show (addGas k low).code.size ≤ (addGas k low).pc from hl)] + exact .inr ⟨_, rfl, rfl⟩ + +/-- `Logic.sstore_of_account` over steps monotone in gas. -/ +theorem sstore_of_accountG (hfork : .berlin ≤ fork) (hglam : fork < .glamsterdam) + {key new : U256} {rest : List U256} {cold : Bool} + (hlt : pc < code.size) (hbyte : code[pc] = 0x55) (hstatic : message.isStatic = false) + (hcold : decide (U256.toBeBytes key ∉ + substate.accessedStorageKeys.getD message.currentTarget ∅) = cold) + (hstipend : CALL_STIPEND < gas) + (hgas : sstoreCost fork (state.getStorageOriginal message.currentTarget (U256.toBeBytes key)) + (state.getStorage message.currentTarget (U256.toBeBytes key)) new cold ≤ gas) + (hacc : (state.getAccountOptional message.currentTarget).isSome = true) : + ∃ state' : State.TransactionState, + state'.getStorage message.currentTarget (U256.toBeBytes key) = new ∧ + (∀ other slot, other ≠ message.currentTarget ∨ slot ≠ U256.toBeBytes key → + state'.getStorage other slot = state.getStorage other slot) ∧ + state'.getStorageOriginal = state.getStorageOriginal ∧ + (∀ other, state'.getAccountOptional other = state.getAccountOptional other) ∧ + (∀ codeHash, state'.getCode codeHash = state.getCode codeHash) ∧ + state'.parent = state.parent ∧ + HoareG fork (At code message pc (key :: new :: rest) memory gas state substate returnData) + (At code message (pc + 1) rest memory + (gas - sstoreCost fork + (state.getStorageOriginal message.currentTarget (U256.toBeBytes key)) + (state.getStorage message.currentTarget (U256.toBeBytes key)) new cold) + state' + { substate with + accessedStorageKeys := substate.accessedStorageKeys.insert message.currentTarget + ((substate.accessedStorageKeys.getD message.currentTarget ∅).insert + (U256.toBeBytes key)) + refundCounter := substate.refundCounter + sstoreRefund fork + (state.getStorageOriginal message.currentTarget (U256.toBeBytes key)) + (state.getStorage message.currentTarget (U256.toBeBytes key)) new } returnData) := by + -- Recording the read keeps the account, so the write succeeds. + obtain ⟨state', hset⟩ := State.TransactionState.exists_setStorage (U256.toBeBytes key) new + (tx := state.recordStorageRead message.currentTarget (U256.toBeBytes key)) + (by rw [(State.TransactionState.recordStorageRead_reads state _ message.currentTarget _ + (U256.toBeBytes key) default).1]; exact hacc) + refine ⟨state', State.TransactionState.getStorage_setStorage_self hset, fun other slot hne => ?_, + ?_, fun other => ?_, fun codeHash => ?_, + by rw [State.TransactionState.parent_setStorage hset]; rfl, + sstoreG hfork hglam hlt hbyte hstatic hcold hstipend hgas hset⟩ + · rw [State.TransactionState.getStorage_setStorage_of_ne hset hne] + exact (State.TransactionState.recordStorageRead_reads state _ other _ slot default).2.1 + · rw [State.TransactionState.getStorageOriginal_setStorage hset] + funext other slot + exact (State.TransactionState.recordStorageRead_reads state _ other _ slot default).2.2.1 + · rw [State.TransactionState.getAccountOptional_setStorage hset] + exact (State.TransactionState.recordStorageRead_reads state _ other _ + (U256.toBeBytes key) default).1 + · rw [State.TransactionState.getCode_setStorage hset] + exact (State.TransactionState.recordStorageRead_reads state _ message.currentTarget _ + (U256.toBeBytes key) codeHash).2.2.2.1 + +/-- RETURN shows §X§ when §X§ succeeds with the bytes it reads, the logs are §ss§'s and the +storage is §X§'s. -/ +theorem return_postSG {X : Observable} {ss : Substate} {code : ByteArray} {message : Message fork} + {pc : Nat} {start size : U256} {rest : List U256} {memory : ByteArray} {gas : Nat} + {state : State.TransactionState} {substate : Substate} {returnData : ByteArray} + (hlt : pc < code.size) (hbyte : code[pc] = 0xf3) + (hgas : (extendMemory memory.size [(start, size)]).cost ≤ gas) (hs : X.success = true) + (hout : (memoryReadBytes (memoryExtend memory (extendMemory memory.size [(start, size)]).expandBy) + start.toNat size.toNat).toList.map (·.toNat) = X.output) + (hlogs : substate.logs = ss.logs) + (hstore : ∀ slot, (state.getStorage (Target.address selfAddress) + (Target.storageKey slot)).toNat = X.storage slot) : + SpecG fork (At code message pc (start :: size :: rest) memory gas state substate returnData) + (PostS X ss) := + SpecG.consequence (Logic.returnG hlt hbyte hgas) (fun _ h => h) + (fun _ ⟨_, herr, hout', _, hst, hss⟩ => + ⟨by rw [herr]; simp [errorOf, hs], by rw [hout']; exact hout, by rw [hss, hlogs], + fun _ slot => by rw [hst]; exact hstore slot⟩) + +/-- REVERT shows §X§ when §X§ fails with the bytes it reads and the logs are §ss§'s. -/ +theorem revert_postSG {X : Observable} {ss : Substate} {code : ByteArray} {message : Message fork} + {pc : Nat} {start size : U256} {rest : List U256} {memory : ByteArray} {gas : Nat} + {state : State.TransactionState} {substate : Substate} {returnData : ByteArray} + (hfork : .byzantium ≤ fork) (hlt : pc < code.size) (hbyte : code[pc] = 0xfd) + (hgas : (extendMemory memory.size [(start, size)]).cost ≤ gas) (hs : X.success = false) + (hout : (memoryReadBytes (memoryExtend memory (extendMemory memory.size [(start, size)]).expandBy) + start.toNat size.toNat).toList.map (·.toNat) = X.output) + (hlogs : substate.logs = ss.logs) : + SpecG fork (At code message pc (start :: size :: rest) memory gas state substate returnData) + (PostS X ss) := + SpecG.consequence (Logic.revertG hfork hlt hbyte hgas) (fun _ h => h) + (fun _ ⟨_, herr, hout', _, _, hss⟩ => + ⟨by rw [herr]; simp [errorOf, hs], by rw [hout']; exact hout, by rw [hss, hlogs], + fun h => by rw [hs] at h; cases h⟩) + +end G + +/-! ## MLOAD -/ + +/-- A fold of bytes into a word, as SolarTV's load does it, is EthLib's number of the bytes. -/ +theorem foldl_bytes : ∀ (l : List UInt8) (a : Nat), + l.foldl (fun (acc : BitVec 256) (b : UInt8) => (acc <<< 8) ||| b.toBitVec.setWidth 256) + (BitVec.ofNat 256 a) = + BitVec.ofNat 256 (l.foldl (fun acc b => acc * 256 + b.toNat) a) + | [], _ => rfl + | u :: l, a => by + simp only [List.foldl_cons] + have hu : u.toBitVec.setWidth 256 = BitVec.ofNat 256 u.toNat := by + apply BitVec.eq_of_toNat_eq + simp only [BitVec.toNat_setWidth, BitVec.toNat_ofNat, UInt8.toNat_toBitVec] + rw [hu, shl_or_ofNat _ _ u.toNat_lt, foldl_bytes l] + +open SolarTV.Machine in +/-- MLOAD in SolarTV is EthLib's. -/ +theorem load_eq {m : Mem} {M : ByteArray} {o : Word} (hm : MemRel m M) : + loadWord (memoryReadBytes (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy) o.toNat 32) + 0 32 = m.load o.toNat := by + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have hext := size_memoryExtend_extendMemory' (memory := M) (start := o) (length := 32) hmod + (by decide) + have hfit : o.toNat + 32 ≤ + (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy).size := by + rw [hext, show (32 : Word).toNat = 32 from rfl] + exact Nat.le_trans (le_ceil32 _) (Nat.le_max_right _ _) + have h1 : (List.range 32).map (fun i => byteAt (memoryReadBytes + (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy) o.toNat 32) (0 + i)) = + (List.range 32).map (fun i => byteAt M (o.toNat + i)) := by + apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [byteAt_memoryReadBytes hfit, ite_eq_left (by omega), byteAt_memoryExtend, Nat.zero_add] + have h2 : (List.range 32).map (fun i => m.bytes (o.toNat + i)) = + ((List.range 32).map (fun i => byteAt M (o.toNat + i))).map UInt8.toBitVec := by + rw [List.map_map] + apply List.map_congr_left + intro i _ + exact (hm.2 _).symm + unfold loadWord bufferRead bytesToNat Mem.load Mem.read + rw [h1, h2] + conv_rhs => rw [List.foldl_map] + rw [show (0 : BitVec 256) = BitVec.ofNat 256 0 from rfl, foldl_bytes] + + +open SolarTV.EVM.Program in +theorem exec_load {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {rest : List Assemble.Instr} {x : Word} {S : List Word} {s : SolarTV.Machine.State} + (h : S.length < 1024) : + exec o call b (.op .load :: rest) (x :: S) s = + exec o call b rest (s.memory.load x.toNat :: S) { s with memory := s.memory.expand x.toNat 32 } := by + have h1 : ¬ 1024 < S.length + 1 := by omega + simp [exec, stepOp, h1] + +/-! ## The simulation of a block -/ + +set_option hygiene false in +/-- The bound of the stack in lockstep with the height of the check. -/ +local macro "hu_tac" : tactic => `(tactic| first | omega | (simp at hu ⊢; omega) | (simp; omega)) + +/-- What a block's instructions from `pc` give: a halt EthLib's frame shows, or the next block, +reached by EthLib with its stack related at the block's types, at most its highest entry stack, +with gas for the reserve `R`, and by a jump to a labelled block or a fall into the next one. -/ +def SimOutL (p : Program) (c : Cert) (mx : List Nat) (code : ByteArray) (call : SolarTV.Call) + (msg : Message .fusaka) (ss0 : Substate) (st : State.TransactionState) (ss : Substate) + (b R pc : Nat) (T : List Word) (M : ByteArray) (g : Nat) : + (SolarTV.Machine.Halt × SolarTV.Machine.State) ⊕ (Nat × List Word × SolarTV.Machine.State) → + Prop + | .inl (halt, s') => + SpecG .fusaka (At code msg pc T M g st ss .empty) (PostL call msg.currentTarget ss0 s' halt) + | .inr (t, S', s') => (t ≤ p.blocks.length ∧ + (t < p.blocks.length → c.need t ≤ S'.length ∧ S'.length ≤ maxH mx t) ∧ + (t = b + 1 ∨ isTarget p c t = true)) ∧ + ∃ pc' T' M' g' st' ss', HoareG .fusaka (At code msg pc T M g st ss .empty) + (At code msg pc' T' M' g' st' ss' .empty) ∧ SR c (c.entry t) S' T' ∧ + EntryL c code call (lowerFrom p c t (p.blocks.drop t)) R pc' s' M' g' ∧ + Rel msg ss0 st' ss' s' + +theorem SimOutL.pre {p : Program} {c : Cert} {mx : List Nat} {code : ByteArray} {call : SolarTV.Call} + {msg : Message .fusaka} {ss0 : Substate} {st st1 : State.TransactionState} {ss ss1 : Substate} + {b R pc pc1 : Nat} {T T1 : List Word} {M M1 : ByteArray} {g g1 : Nat} + {r : (SolarTV.Machine.Halt × SolarTV.Machine.State) ⊕ (Nat × List Word × SolarTV.Machine.State)} + (h : HoareG .fusaka (At code msg pc T M g st ss .empty) (At code msg pc1 T1 M1 g1 st1 ss1 .empty)) + (h1 : SimOutL p c mx code call msg ss0 st1 ss1 b R pc1 T1 M1 g1 r) : + SimOutL p c mx code call msg ss0 st ss b R pc T M g r := by + match r, h1 with + | .inl (_, _), hspec => exact SpecG.seq h hspec + | .inr (_, _, _), ⟨hneed, pc', T', M', g', st', ss', hh, hR, hinv, hrel⟩ => + exact ⟨hneed, pc', T', M', g', st', ss', Triple.seq h hh, hR, hinv, hrel⟩ + +theorem blockStepL_stack {p : Program} {c : Cert} {mx : List Nat} {bb : Nat} {ok : Nat → Known → List Ty → Nat → Bool} + {h k : Nat} {known : Known} {ty : List Ty} {op : SolarTV.EVM.Op} (hne : ∀ v, op ≠ .push v) + (hd : ∀ i, op ≠ .dup i) (hs : ∀ i, op ≠ .swap i) (hp : op ≠ .pop) : + blockStepL p c mx bb ok h known ty k (.op (.stack op)) = + match stackNeed op with + | some (need, d) => decide (1 ≤ k) && decide (need ≤ h) && isData ty need && + ok (h + d).toNat (none :: known.drop need) (some false :: ty.drop need) (k - 1) + | none => false := by + cases op <;> first | rfl | exact absurd rfl (hne _) | exact absurd rfl (hd _) | + exact absurd rfl (hs _) | exact absurd rfl hp + + +/-- `stack_sim` for `blockStepL`, with the heights of the check and the stack in lockstep. -/ +theorem stack_simL {p : Program} {c : Cert} {mx : List Nat} {bb : Nat} {ok : Nat → Known → List Ty → Nat → Bool} + {h k : Nat} {known : Known} {ty : List Ty} {op : SolarTV.EVM.Op} (hne : ∀ v, op ≠ .push v) + {ctx : SolarTV.EVM.Context} {S T : List Word} + (hok : blockStepL p c mx bb ok h known ty k (.op (.stack op)) = true) (hh : h ≤ S.length) + (hk : KR known S) (hR : SR c ty S T) : + 1 ≤ k ∧ ∃ byte, opByte op = some byte ∧ ∃ h' ty' S' T', + SolarTV.EVM.step ctx op S = some S' ∧ SolarTV.EVM.step ctx op T = some T' ∧ + SR c ty' S' T' ∧ h' ≤ S'.length ∧ S'.length ≤ S.length + 1 ∧ S'.length + h = h' + S.length ∧ + ∃ known', KR known' S' ∧ ok h' known' ty' (k - 1) = true := by + have hL := hR.length + by_cases hd : ∃ i, op = .dup i + · obtain ⟨i, rfl⟩ := hd + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok + obtain ⟨⟨⟨hk1, h16⟩, hi⟩, hok⟩ := hok + have hiS : i.val < S.length := by omega + have hiT : i.val < T.length := by omega + refine ⟨hk1, 0x80 + i.val, by simp [opByte, h16], h + 1, _, _, _, ?_, ?_, SR.dup hR hiS hiT, by simp; omega, by simp, by simp; omega, _, + hk.dup hiS, hok⟩ + · simp [SolarTV.EVM.step, List.getElem?_eq_getElem hiS] + · simp [SolarTV.EVM.step, List.getElem?_eq_getElem hiT] + by_cases hs : ∃ i, op = .swap i + · obtain ⟨i, rfl⟩ := hs + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok + obtain ⟨⟨⟨hk1, h16⟩, hi⟩, hok⟩ := hok + rcases S with _ | ⟨a, S⟩ + · simp at hh; omega + rcases T with _ | ⟨b, T⟩ + · simp at hL + simp only [List.length_cons] at hh hL + have hiS : i.val < S.length := by omega + have hiT : i.val < T.length := by omega + refine ⟨hk1, 0x90 + i.val, by simp [opByte, h16], h, _, _, _, ?_, ?_, SR.swap hR hiS hiT, by simp; omega, by simp, by simp; omega, [], + KR.nil _, hok⟩ + · simp [SolarTV.EVM.step, List.getElem?_eq_getElem hiS] + · simp [SolarTV.EVM.step, List.getElem?_eq_getElem hiT] + by_cases hp : op = .pop + · subst hp + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok + obtain ⟨⟨hk1, h1⟩, hok⟩ := hok + rcases S with _ | ⟨a, S⟩ + · simp at hh; omega + rcases T with _ | ⟨b, T⟩ + · simp at hL + refine ⟨hk1, _, rfl, h - 1, _, _, _, rfl, rfl, (SR.uncons.1 hR).2, by simp at hh; omega, + by simp only [List.length_cons]; omega, by simp at hh ⊢; omega, [], KR.nil _, hok⟩ + have hd' : ∀ i, op ≠ .dup i := fun i e => hd ⟨i, e⟩ + have hs' : ∀ i, op ≠ .swap i := fun i e => hs ⟨i, e⟩ + rw [blockStepL_stack hne hd' hs' hp] at hok + split at hok + · rename_i need d hn + simp only [Bool.and_eq_true, decide_eq_true_eq] at hok + obtain ⟨⟨⟨hk1, hneed⟩, hdata⟩, hok⟩ := hok + obtain ⟨byte, hbyte⟩ := opByte_of_stackNeed hn + have hS' : ∃ S', SolarTV.EVM.step ctx op S = some S' := by + cases op <;> simp only [stackNeed, reduceCtorEq, Option.some.injEq, Prod.mk.injEq] at hn + all_goals try first + | exact absurd rfl (hd' _) + | exact absurd rfl (hs' _) + | exact absurd rfl hp + all_goals obtain ⟨rfl, -⟩ := hn + all_goals rcases S with _ | ⟨a, _ | ⟨b, S⟩⟩ <;> simp_all [SolarTV.EVM.step] <;> omega + obtain ⟨S', hstep⟩ := hS' + obtain ⟨v, rfl, hstepT⟩ := step_data hn hd' hs' hp hstep (hR.data hdata) hL + have hd1 : (need : Int) + d = 1 := by + cases op <;> simp [stackNeed] at hn <;> + first | omega | exact absurd rfl (hd' _) | exact absurd rfl (hs' _) | exact absurd rfl hp + refine ⟨hk1, byte, hbyte, (h + d).toNat, _, _, _, hstep, hstepT, + SR.cons (τ := some false) rfl (SR.drop need hR), ?_, ?_, ?_, _, (hk.drop need).cons_none _, hok⟩ + · simp only [List.length_cons, List.length_drop]; omega + · simp only [List.length_cons, List.length_drop]; omega + · simp only [List.length_cons, List.length_drop]; omega + · cases hok + + +/-- An oracle whose CALLER is the account `a` and whose hash is EthLib's: the oracle of a call from +`a`. `OracleOk` is the case of `callerAddress` (`OracleOk.at`). -/ +def OracleOkAt (a : Nat) (o : SolarTV.Machine.Oracle) : Prop := + o.caller.setWidth 256 = (Target.address a).toU256 ∧ + ∀ bytes, o.keccak bytes = keccak ⟨(bytes.map UInt8.ofBitVec).toArray⟩ + +theorem OracleOk.at {o : SolarTV.Machine.Oracle} (h : OracleOk o) : OracleOkAt callerAddress o := h + +open SolarTV.EVM.Program in +/-- EthLib runs the code of a block's instructions from the offset of the next one as SolarTV +runs them, over steps monotone in gas, with gas for the reserve `R` beyond the block, for a +message from any account `a` (CALLER is `a`; the transaction's environment is `Target.txEnv`'s +only when the block reads it). -/ +theorem exec_simL {p : Assemble.Program} {c : Cert} {mx : List Nat} {code : ByteArray} (G : GlobLT p c code) + {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + {a : Nat} (hcaller : msg.caller = Target.address a) (ho : c.env = true → OracleOkAt a o) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : c.reads = true → msg.txEnv = Target.txEnv) + (he : c.reads = true → EnvOk o) + (b : Nat) (hb : b < p.blocks.length) (Rv : Nat) : + ∀ (is : List Assemble.Instr) (h : Nat) (known : Known) (ty : List Ty) (S T : List Word) (k : Nat) + (s : SolarTV.Machine.State) (pc : Nat) (M : ByteArray) (g : Nat) + (st : State.TransactionState) (ss : Substate), + blockOkL p c mx b h known ty k is = true → h ≤ S.length → + S.length + c.need b ≤ h + maxH mx b → KR known S → SR c ty S T → + InvL c code call (lowerInstrs p c b is ++ lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) k Rv + pc S s M g → Rel msg ss0 st ss s → + SimOutL p c mx code call msg ss0 st ss b Rv pc T M g (exec o call b is S s) + | [], h, known, ty, S, T, k, s, pc, M, g, st, ss, hok, hh, hu, _, hR, I, R => by + simp only [blockOkL, fallOkL, Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at hok + have I2 := I.entry + simp only [lowerInstrs, List.nil_append] at I2 + simp only [exec, SimOutL] + exact ⟨⟨by omega, fun ht => ⟨by omega, by omega⟩, by simp⟩, pc, T, M, g, st, ss, + Triple.of_imp fun _ h => h, SR.le hok.1.2 hR, I2, R⟩ + | i :: rest, h, known, ty, S, T, k, s, pc, M, g, st, ss, hok, hh, hu, hk, hR, I, R => by + have hL := hR.length + have hctx : (⟨BitVec.ofNat 256 msg.data.size, o.env "returndatasize" s.world []⟩ : + SolarTV.EVM.Context) = context o call s := by rw [hdata]; rfl + cases hT : turnedElse c b i rest with + | some e => + -- A turned branch: ISZERO; PUSH e; JUMPI, falling into the next block. + obtain ⟨rfl, rfl⟩ := turnedElse_some hT + simp only [blockOkL, hT, jumpOkL, fallOkL, Bool.and_eq_true, Bool.or_eq_true, + decide_eq_true_eq] at hok + obtain ⟨⟨⟨⟨hk3, h1⟩, hdat⟩, ⟨⟨⟨hen, hetgt⟩, hneed⟩, hety⟩, hcost⟩, ⟨hfall, hfty⟩, hcost'⟩ := hok + simp only [lowerInstrs, hT, List.cons_append, List.nil_append] at I + rcases S with _ | ⟨cond, S'⟩ + · simp at hh; omega + rcases T with _ | ⟨cond', T'⟩ + · simp at hL + obtain rfl := (SR.head hR hdat).symm + have hR' := (SR.uncons.1 hR).2 + simp only [List.length_cons] at hL + obtain ⟨n0, hd0, hs0⟩ := I.seg.head + obtain ⟨n1, hd1, hs1⟩ := hs0.head + obtain ⟨n2, hd2, hseg⟩ := hs1.head + simp only [Item.expected] at hd0 hd1 hd2 + obtain ⟨hlt0, hcode0, rfl⟩ := op_item hd0 + obtain ⟨hlt2, hcode2, rfl⟩ := op_item hd2 + have hS := I.stack; have hG := I.gas + simp only [List.length_cons] at hS hh hu + obtain ⟨g0, hg0, hisz⟩ := stack_ruleG (msg := msg) (M := M) (st := st) (ss := ss) (gas := g) + (op := .iszero) (stack := cond :: T') (next := EvmRules.Evm.iszero cond :: T') + (r := o.env "returndatasize" s.world []) rfl hlt0 hcode0 rfl (by omega) + (by simp only [List.length_cons]; omega) + obtain ⟨g1, hg1, hpush⟩ := push_itemG (msg := msg) (M := M) (st := st) (ss := ss) + (gas := g0) (stack := EvmRules.Evm.iszero cond :: T') hd1 (by omega) + (by simp only [List.length_cons]; omega) + by_cases hc : cond = 0 + · -- The condition is zero: ISZERO gives one and the code jumps to the else block. + subst hc + have hoff := toNat_offset (G.target e hen hetgt).2.1 G.size_lt + have hj := Logic.jumpi_takenG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (destination := BitVec.ofNat 256 (c.offset e)) + (rest := T') hlt2 hcode2 (show 10 ≤ g1 by omega) iszero_zero + (by rw [hoff]; exact (G.target e hen hetgt).1) + rw [hoff] at hj + simp only [exec, List.length_cons, show ¬ S'.length + 1 + 1 > 1024 by omega, + show ¬ S'.length + 1 > 1024 by omega, ite_false, ite_true, SimOutL] + exact ⟨⟨by omega, fun _ => ⟨by omega, by omega⟩, Or.inr hetgt⟩, c.offset e, T', M, g1 - 10, st, + ss, Triple.seq hisz (Triple.seq hpush hj), SR.le hety hR', + I.target G hen hetgt (m := 3) (by omega) (by omega), R⟩ + · -- The condition is not zero: ISZERO gives zero and the code falls into the next block. + have hj := Logic.jumpi_of_eq_zeroG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (destination := BitVec.ofNat 256 (c.offset e)) + (rest := T') hlt2 hcode2 (show 10 ≤ g1 by omega) (iszero_nonzero hc) + simp only [exec, List.length_cons, show ¬ S'.length + 1 + 1 > 1024 by omega, ite_false, + hc, SimOutL] + refine ⟨⟨by omega, fun _ => ⟨by omega, by omega⟩, by simp⟩, _, T', M, g1 - 10, st, ss, + Triple.seq hisz (Triple.seq hpush hj), SR.le hfty hR', + ⟨hseg, ?_, I.le_top, I.mem⟩, R⟩ + have := I.gas + omega + | none => + by_cases hD : dropped p b i rest = true + · rcases dropped_true hD with ⟨rfl, rfl⟩ | ⟨rfl, rfl, hn⟩ + · -- A jump to the next block, left out: the code falls into it. + simp only [blockOkL, hT, hD, ite_true, fallOkL, Bool.and_eq_true, Bool.or_eq_true, + decide_eq_true_eq] at hok + simp only [lowerInstrs, hT, hD, ite_true, List.nil_append] at I + have hS := I.stack + simp only [exec, show ¬ S.length + 1 > 1024 by omega, ite_false, SimOutL] + exact ⟨⟨by omega, fun _ => ⟨by omega, by omega⟩, by simp⟩, pc, T, M, g, st, ss, + Triple.of_imp fun _ h => h, SR.le hok.1.2 hR, I.entry, R⟩ + · -- The last block's STOP, left out: the code ends. + simp only [lowerInstrs, hT, hD, ite_true, List.nil_append] at I + have hseg := I.seg + rw [lowerFrom_nil p c (by omega)] at hseg + have hpc := hseg.nil_end + simp only [exec, SimOutL] + exact SpecG.consequence (stop_of_size_leG (by omega)) + (fun _ h => h) fun evm h => postL_stop R hself evm h + have hD' : dropped p b i rest = false := by simpa using hD + have hok' : blockStepL p c mx b (fun h known ty k => blockOkL p c mx b h known ty k rest) h known ty k i = + true := by + simpa only [blockOkL, hT, hD', Bool.false_eq_true, ite_false] using hok + have I' : InvL c code call (lowerInstr i ++ (lowerInstrs p c b rest ++ + lowerFrom p c (b + 1) (p.blocks.drop (b + 1)))) k Rv pc S s M g := by + simpa only [lowerInstrs, hT, hD', Bool.false_eq_true, ite_false, List.append_assoc] using I + clear hok hD hD' hT + have IH := exec_simL (mx := mx) (o := o) (ss0 := ss0) G hdata hvalue hstatic hself hcaller ho hbenv htx he b hb Rv rest + rcases i with mop | ⟨e, ar⟩ | t | t | t | _ | _ | _ | _ | _ | _ | _ + · rcases mop with sop | _ | _ | _ | _ | _ | _ + · by_cases hpush : ∃ v, sop = .push v + · obtain ⟨v, rfl⟩ := hpush + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + have hS := I'.stack; have hG := I'.gas + obtain ⟨g1, hg1, hpush⟩ := push_itemG (msg := msg) (M := M) (st := st) (ss := ss) (gas := g) + (stack := T) hd (by omega) (by omega) + have hv : BitVec.ofNat 256 v.toNat = v := by simp + rw [hv] at hpush + rw [exec_stack (next := v :: S) rfl (by omega) (by simp; omega)] + exact SimOutL.pre hpush (IH (h + 1) (some v :: known) _ (v :: S) (v :: T) (k - 1) s next M g1 + st ss hok'.2 (by simp; omega) (by hu_tac) + (hk.cons_some v) + (SR.cons (τ := some false) rfl hR) (I'.next hok'.1 hseg (by simp) (by omega)) R) + · have hne : ∀ v, sop ≠ .push v := fun v he => hpush ⟨v, he⟩ + obtain ⟨hk1, byte, hbyte, h', ty', S', T', hstep, hstepT, hR', hh', hlen', hlock, known', hkn, + hok⟩ := stack_simL (ctx := context o call s) hne hok' hh hk hR + rw [lowerInstr_stack hne, hbyte] at I' + simp only [Option.getD_some, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rw [← hctx] at hstepT + have hS := I'.stack; have hG := I'.gas + obtain ⟨g1, hg1, hrule⟩ := stack_ruleG (M := M) (st := st) (ss := ss) (gas := g) + (stack := T) hbyte hlt hcode hstepT (by omega) (by omega) + rw [exec_stack hstep (by omega) (by omega)] + exact SimOutL.pre hrule (IH h' known' ty' S' T' (k - 1) s (pc + 1) M g1 st ss hok (by omega) (by hu_tac) + hkn hR' (I'.next hk1 hseg (by omega) (by omega)) R) + · -- MLOAD. + obtain _ | ⟨o, known'⟩ := known + · simp [blockStepL] at hok' + obtain _ | ow := o + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨⟨hk1, h1⟩, hin⟩, hdat⟩, hok'⟩ := hok' + rcases S with _ | ⟨x, S'⟩ + · simp at hh; omega + rcases T with _ | ⟨x', T'⟩ + · simp at hL + obtain rfl := (SR.head hR hdat).symm + have hR' := (SR.uncons.1 hR).2 + obtain ⟨rfl, -⟩ := KR.head hk + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hG hh hL hu + have hmod : M.size % 32 = 0 := by rw [I'.mem.1]; omega + obtain ⟨hle, hcost⟩ := extend_cost (o := ow) (sz := 32) hmod G.top_mod I'.le_top + (Or.inr hin) + have hbound : (32 : Word) = 0 ∨ ow.toNat + (32 : Word).toNat ≤ 2 ^ 32 := + Or.inr (by have := G.top_le; exact Nat.le_trans hin this) + have hrule := Logic.mloadG (message := msg) (memory := M) (state := st) (substate := ss) + (returnData := .empty) (start := ow) (rest := T') (gas := g) hlt hcode (by omega) + rw [load_eq I'.mem] at hrule + rw [exec_load (by omega)] + have hM' := size_memoryExtend M (extendMemory M.size [(ow, 32)]).expandBy + refine SimOutL.pre hrule (IH h [] _ _ _ (k - 1) _ (pc + 1) _ _ st ss hok' (by simp; omega) + (by hu_tac) (KR.nil _) (SR.cons (τ := some false) rfl (by simpa using hR')) + ⟨hseg, by simp; omega, ?_, by rw [hM']; omega, memRel_expand I'.mem hbound⟩ + ⟨R.storage, R.account, R.logs⟩) + rw [hM']; omega + · -- MSTORE. + obtain _ | ⟨o, known'⟩ := known + · simp [blockStepL] at hok' + obtain _ | ow := o + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨⟨hk1, h2⟩, hin⟩, hdat⟩, hok'⟩ := hok' + rcases S with _ | ⟨x, _ | ⟨v, S'⟩⟩ + · simp at hh; omega + · simp at hh; omega + rcases T with _ | ⟨x', _ | ⟨v', T'⟩⟩ + · simp at hL + · simp at hL + have htake := hR.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR' : SR c (ty.drop 2) S' T' := by simpa using SR.drop 2 hR + obtain ⟨rfl, -⟩ := KR.head hk + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hG hh hL hu + have hmod : M.size % 32 = 0 := by rw [I'.mem.1]; omega + obtain ⟨hle, hcost⟩ := extend_cost (o := ow) (sz := 32) hmod G.top_mod I'.le_top + (Or.inr hin) + obtain ⟨hmem', hsize⟩ := memRel_store (o := ow) (v := v) I'.mem (by have := G.top_le; omega) + have hext := size_memoryExtend_extendMemory' (memory := M) (start := ow) (length := 32) + hmod (by decide) + rw [size_memoryExtend] at hext + have h32 : (32 : U256).toNat = 32 := rfl + rw [h32] at hext + have hM' : (memoryWrite (memoryExtend M (extendMemory M.size [(ow, 32)]).expandBy) + ow.toNat (wordBytes v)).size = M.size + (extendMemory M.size [(ow, 32)]).expandBy := by + rw [hsize, hext] + rw [exec_store (by omega)] + refine SimOutL.pre (Logic.mstoreG (start := ow) (value := v) (rest := T') (memory := M) + (gas := g) hlt hcode (by omega)) (IH (h - 2) _ _ S' T' (k - 1) _ (pc + 1) _ _ st ss hok' + (by omega) (by hu_tac) (hk.drop 2) hR' ⟨hseg, by omega, ?_, by rw [hM']; omega, hmem'⟩ + ⟨R.storage, R.account, R.logs⟩) + rw [hM']; omega + · simp [blockStepL] at hok' + · simp [blockStepL] at hok' + · simp [blockStepL] at hok' + · simp [blockStepL] at hok' + · rcases e with _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | n | _ | name | _ + all_goals try (simp [blockStepL] at hok'; done) + · -- SLOAD. + rcases ar with _ | _ | ar + · simp [blockStepL] at hok' + rotate_left + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨hk1, h1⟩, hdat⟩, hok⟩ := hok' + rcases S with _ | ⟨x, S'⟩ + · simp at hh; omega + rcases T with _ | ⟨x', T'⟩ + · simp at hL + obtain rfl := (SR.head hR hdat).symm + have hR' := (SR.uncons.1 hR).2 + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hG hh hL hu + rw [exec_effect1 (w := s.storage x) rfl (by omega)] + have hrule := Logic.sloadG (message := msg) (memory := M) (state := st) (substate := ss) + (returnData := .empty) (key := x) (rest := T') (gas := g) (by decide) hlt hcode rfl + (by split <;> omega) + rw [R.storage x] at hrule + refine SimOutL.pre hrule ?_ + have hreads := fun k : Word => State.TransactionState.recordStorageRead_reads st + msg.currentTarget msg.currentTarget (U256.toBeBytes x) (U256.toBeBytes k) default + refine IH h [] _ _ _ (k - 1) s (pc + 1) M _ _ _ hok (by simp; omega) (by hu_tac) (KR.nil _) + (SR.cons (τ := some false) rfl (by simpa using hR')) (I'.next hk1 hseg (by simp) (by split <;> omega)) + ⟨fun k => ?_, ?_, R.logs⟩ + · rw [(hreads k).2.1] + exact R.storage k + · rw [(hreads x).1] + exact R.account + · -- SSTORE. + rcases ar with _ | _ | _ | ar + · simp [blockStepL] at hok' + · simp [blockStepL] at hok' + rotate_left + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨hk1, h2⟩, hdat⟩, hok⟩ := hok' + rcases S with _ | ⟨x, _ | ⟨v, S'⟩⟩ + · simp at hh; omega + · simp at hh; omega + rcases T with _ | ⟨x', _ | ⟨v', T'⟩⟩ + · simp at hL + · simp at hL + have htake := hR.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR' : SR c (ty.drop 2) S' T' := by simpa using SR.drop 2 hR + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hG hh hL hu + rw [exec_effect2 (s' := { s with storage := SolarTV.Machine.update s.storage x v }) rfl + (by omega)] + have hcost := sstoreCost_le (st.getStorageOriginal msg.currentTarget (U256.toBeBytes x)) + (st.getStorage msg.currentTarget (U256.toBeBytes x)) v + (decide (U256.toBeBytes x ∉ ss.accessedStorageKeys.getD msg.currentTarget ∅)) + obtain ⟨st', hnew, hothers, -, hacc, -, -, hrule⟩ := sstore_of_accountG + (message := msg) (memory := M) (state := st) (substate := ss) (returnData := .empty) + (key := x) (new := v) (rest := T') (gas := g) (by decide) (by decide) hlt hcode hstatic + rfl (by simp only [CALL_STIPEND]; omega) (by omega) R.account + refine SimOutL.pre hrule ?_ + refine IH (h - 2) [] _ S' T' (k - 1) _ (pc + 1) M _ _ _ hok (by omega) (by hu_tac) (KR.nil _) + hR' ?_ ⟨fun k => ?_, by rw [hacc]; exact R.account, R.logs⟩ + · exact ⟨hseg, by omega, by omega, I'.le_top, I'.mem⟩ + by_cases hk : k = x + · subst hk + rw [hnew] + simp [SolarTV.Machine.update] + · rw [hothers _ _ (Or.inr fun he => hk (U256.toBeBytes_inj he)), R.storage k] + simp [SolarTV.Machine.update, hk] + · -- CALLDATALOAD. + rcases ar with _ | _ | ar + · simp [blockStepL] at hok' + rotate_left + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨hk1, h1⟩, hdat⟩, hok⟩ := hok' + rcases S with _ | ⟨x, S'⟩ + · simp at hh; omega + rcases T with _ | ⟨x', T'⟩ + · simp at hL + obtain rfl := (SR.head hR hdat).symm + have hR' := (SR.uncons.1 hR).2 + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hG hh hL hu + rw [exec_effect1 (w := SolarTV.Machine.calldataWord call x) rfl (by omega)] + have hrule := Logic.calldataloadG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (start := x) (rest := T') (gas := g) hlt hcode + (by omega) + rw [hdata, ← calldataWord_eq] at hrule + exact SimOutL.pre hrule (IH h _ _ _ _ (k - 1) s (pc + 1) M (g - 3) st ss hok (by simp; omega) (by hu_tac) + ((hk.drop 1).cons_none _) (SR.cons (τ := some false) rfl (by simpa using hR')) (I'.next hk1 hseg (by simp) (by omega)) R) + · -- CALLDATASIZE. + rcases ar with _ | ar + rotate_left + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨hk1, hok⟩ := hok' + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + rw [exec_effect0 (w := BitVec.ofNat 256 call.calldata.size) rfl (by omega)] + have hrule := Logic.calldatasizeG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (stack := T) (gas := g) hlt hcode (by omega) + (by unfold STACK_LIMIT; omega) + rw [hdata] at hrule + exact SimOutL.pre hrule (IH (h + 1) [] _ _ _ (k - 1) s (pc + 1) M (g - 2) st ss hok + (by simp; omega) (by hu_tac) (KR.nil _) (SR.cons (τ := some false) rfl hR) (I'.next hk1 hseg (by simp) (by omega)) R) + · -- CALLVALUE. + rcases ar with _ | ar + rotate_left + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨hk1, hok⟩ := hok' + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + rw [exec_effect0 (w := BitVec.ofNat 256 call.callvalue) rfl (by omega)] + have hrule := Logic.callvalueG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (stack := T) (gas := g) hlt hcode (by omega) + (by unfold STACK_LIMIT; omega) + rw [hvalue] at hrule + exact SimOutL.pre hrule (IH (h + 1) [] _ _ _ (k - 1) s (pc + 1) M (g - 2) st ss hok + (by simp; omega) (by hu_tac) (KR.nil _) (SR.cons (τ := some false) rfl hR) (I'.next hk1 hseg (by simp) (by omega)) R) + · -- CALLER. + rcases ar with _ | ar + rotate_left + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨henv, hk1⟩, hok⟩ := hok' + obtain ⟨hoc, -⟩ := ho henv + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + rw [exec_effect0 (w := o.caller.setWidth 256) rfl (by omega)] + have hrule := Logic.callerG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (stack := T) (gas := g) hlt hcode (by omega) + (by unfold STACK_LIMIT; omega) + rw [hcaller, ← hoc] at hrule + exact SimOutL.pre hrule (IH (h + 1) _ _ _ _ (k - 1) s (pc + 1) M (g - 2) st ss hok + (by simp; omega) (by hu_tac) (hk.cons_none _) (SR.cons (τ := some false) rfl hR) (I'.next hk1 hseg (by simp) (by omega)) R) + · -- ADDRESS. + rcases ar with _ | ar + rotate_left + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨hk1, hok⟩ := hok' + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + rw [exec_effect0 (w := BitVec.ofNat 256 SolarTV.environment.callee) rfl (by omega)] + have hrule := Logic.addressG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (stack := T) (gas := g) hlt hcode (by omega) + (by unfold STACK_LIMIT; omega) + rw [hself, address_word] at hrule + exact SimOutL.pre hrule (IH (h + 1) [] _ _ _ (k - 1) s (pc + 1) M (g - 2) st ss hok + (by simp; omega) (by hu_tac) (KR.nil _) (SR.cons (τ := some false) rfl hR) (I'.next hk1 hseg (by simp) (by omega)) R) + · -- LOGn. + obtain _ | ⟨o, known'⟩ := known + · simp [blockStepL] at hok' + obtain _ | ow := o + · simp [blockStepL] at hok' + obtain _ | ⟨o2, known'⟩ := known' + · simp [blockStepL] at hok' + obtain _ | sw := o2 + · simp [blockStepL] at hok' + simp only [blockStepL, rangeOk, Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨⟨⟨⟨⟨hn4, rfl⟩, hk1⟩, hnh⟩, hdat⟩, hin⟩, hlc⟩, hok⟩ := hok' + rcases S with _ | ⟨x, _ | ⟨y, S1⟩⟩ + · exact hk.not_nil.elim + · exact hk.not_one.elim + obtain ⟨rfl, hk'⟩ := KR.head hk + obtain ⟨rfl, -⟩ := KR.head hk' + rcases T with _ | ⟨x', _ | ⟨y', T1⟩⟩ + · simp at hL + · simp at hL + simp only [List.length_cons] at hh hL hu + obtain ⟨tops, S2, rfl, hlen⟩ : ∃ tops S2, S1 = tops ++ S2 ∧ tops.length = n := + ⟨S1.take n, S1.drop n, (List.take_append_drop n S1).symm, by simp; omega⟩ + obtain ⟨tops', T2, rfl, hlen'⟩ : ∃ tops' T2, T1 = tops' ++ T2 ∧ tops'.length = n := + ⟨T1.take n, T1.drop n, (List.take_append_drop n T1).symm, by simp; omega⟩ + subst hlen + have htake := hR.data hdat + simp only [List.take_succ_cons, List.cons.injEq, List.take_left' hlen', + List.take_left' rfl] at htake + obtain ⟨rfl, rfl, rfl⟩ := htake + have hR' : SR c (ty.drop (tops.length + 2)) S2 T2 := by + simpa using SR.drop (tops.length + 2) hR + simp only [lowerInstr, hn4, ite_true, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons, List.length_append] at hS hG hh hL hu + have hmod : M.size % 32 = 0 := by rw [I'.mem.1]; omega + obtain ⟨hle, hcost⟩ := extend_cost (o := ow) (sz := sw) hmod G.top_mod I'.le_top + (hin.imp_left fun h0 => BitVec.eq_of_toNat_eq (by simpa using h0)) + have hbound : sw = 0 ∨ ow.toNat + sw.toNat ≤ 2 ^ 32 := + hin.imp (fun h0 => BitVec.eq_of_toNat_eq (by simpa using h0)) + (fun h0 => by have := G.top_le; omega) + have hrule := Logic.logG (n := ⟨tops.length, by omega⟩) (message := msg) (memory := M) + (state := st) (substate := ss) (returnData := .empty) (start := ow) (size := sw) + (words := tops) (rest := T2) (gas := g) rfl hlt hcode (decode_log ⟨tops.length, by omega⟩) hstatic + (show logCost tops.length sw + (extendMemory M.size [(ow, sw)]).cost ≤ g by omega) + dsimp only at hrule + rw [exec_log (by omega)] + have hM' := size_memoryExtend M (extendMemory M.size [(ow, sw)]).expandBy + obtain ⟨L, hL1, hL2⟩ := R.logs + refine SimOutL.pre hrule (IH (h - (tops.length + 2)) [] _ S2 T2 (k - 1) _ (pc + 1) _ _ st _ + hok (by omega) (by hu_tac) (KR.nil _) hR' ⟨hseg, by omega, ?_, by rw [hM']; omega, + memRel_expand I'.mem hbound⟩ ⟨R.storage, R.account, ?_⟩) + · rw [hM']; omega + · refine ⟨L ++ [⟨msg.currentTarget, tops.map U256.toBeBytes, + memoryReadBytes (memoryExtend M (extendMemory M.size [(ow, sw)]).expandBy) + ow.toNat sw.toNat⟩], by simp [Array.toList_push, hL1], + filter_snoc_log ▸ forall₂_snoc hL2 ⟨rfl, rfl, ?_⟩⟩ + exact read_eq I'.mem + · -- KECCAK256. + rcases ar with _ | _ | _ | ar + · simp [blockStepL] at hok' + · simp [blockStepL] at hok' + rotate_left + · simp [blockStepL] at hok' + obtain _ | ⟨o, known'⟩ := known + · simp [blockStepL] at hok' + obtain _ | ow := o + · simp [blockStepL] at hok' + obtain _ | ⟨o2, known'⟩ := known' + · simp [blockStepL] at hok' + obtain _ | sw := o2 + · simp [blockStepL] at hok' + simp only [blockStepL, rangeOk, Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨⟨⟨⟨henv, hk1⟩, h2⟩, hdat⟩, hin⟩, hkc⟩, hok⟩ := hok' + rcases S with _ | ⟨x, _ | ⟨y, S'⟩⟩ + · exact hk.not_nil.elim + · exact hk.not_one.elim + obtain ⟨rfl, hk'⟩ := KR.head hk + obtain ⟨rfl, -⟩ := KR.head hk' + rcases T with _ | ⟨x', _ | ⟨y', T'⟩⟩ + · simp at hL + · simp at hL + have htake := hR.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR' : SR c (ty.drop 2) S' T' := by simpa using SR.drop 2 hR + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hG hh hL hu + have hmod : M.size % 32 = 0 := by rw [I'.mem.1]; omega + obtain ⟨hle, hcost⟩ := extend_cost (o := ow) (sz := sw) hmod G.top_mod I'.le_top + (hin.imp_left fun h0 => BitVec.eq_of_toNat_eq (by simpa using h0)) + have hbound : sw = 0 ∨ ow.toNat + sw.toNat ≤ 2 ^ 32 := + hin.imp (fun h0 => BitVec.eq_of_toNat_eq (by simpa using h0)) + (fun h0 => by have := G.top_le; omega) + obtain ⟨-, hkec⟩ := ho henv + have hrule := Logic.keccak256G (message := msg) (memory := M) (state := st) (substate := ss) + (returnData := .empty) (start := ow) (size := sw) (rest := T') (gas := g) hlt hcode + (by omega) + rw [byteArray_eq_of_map (read_eq I'.mem), ← hkec] at hrule + rw [exec_keccak (by omega)] + have hM' := size_memoryExtend M (extendMemory M.size [(ow, sw)]).expandBy + refine SimOutL.pre hrule (IH (h - 1) [] _ _ _ (k - 1) _ (pc + 1) _ _ st ss hok + (by simp; omega) (by hu_tac) (KR.nil _) (SR.cons (τ := some false) rfl hR') ⟨hseg, by simp; omega, ?_, + by rw [hM']; omega, memRel_expand I'.mem hbound⟩ ⟨R.storage, R.account, R.logs⟩) + rw [hM']; omega + · -- An environment read of the block or the transaction. + rcases ar with _ | ar + rotate_left + · simp [blockStepL] at hok' + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨hreads, hsome⟩, hk1⟩, hok⟩ := hok' + obtain ⟨⟨byte, w⟩, hread⟩ := Option.isSome_iff_exists.1 hsome + simp only [lowerInstr, hread, Option.map_some, Option.getD_some, + List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + rw [exec_effect0 (w := BitVec.ofNat 256 w) + (by simp [SolarTV.Machine.Effect.apply, he hreads name byte w hread]) (by omega)] + have hrule := env_readG (msg := msg) (M := M) (st := st) (ss := ss) (rd := .empty) (gas := g) + (stack := T) hread hlt hcode hbenv (htx hreads) (by omega) (by unfold STACK_LIMIT; omega) + exact SimOutL.pre hrule (IH (h + 1) [] _ _ _ (k - 1) s (pc + 1) M (g - 2) st ss hok + (by simp; omega) (by hu_tac) (KR.nil _) (SR.cons (τ := some false) rfl hR) (I'.next hk1 hseg (by simp) (by omega)) R) + · -- JUMP. + simp only [blockStepL, jumpOkL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨hk2, ⟨⟨⟨⟨htn, htgt⟩, hneed⟩, hty⟩, hcost⟩⟩ := hok' + simp only [lowerInstr, List.cons_append, List.nil_append] at I' + obtain ⟨n1, hd1, hs1⟩ := I'.seg.head + obtain ⟨n2, hd2, -⟩ := hs1.head + simp only [Item.expected] at hd1 hd2 + obtain ⟨hlt2, hcode2, rfl⟩ := op_item hd2 + have hS := I'.stack; have hG := I'.gas + have hoff := toNat_offset (G.target t htn htgt).2.1 G.size_lt + obtain ⟨g1, hg1, hpush⟩ := push_itemG (msg := msg) (M := M) (st := st) (ss := ss) (gas := g) + (stack := T) hd1 (by omega) (by omega) + have hj := Logic.jumpG (message := msg) (memory := M) (state := st) (substate := ss) + (returnData := .empty) (rest := T) hlt2 hcode2 (show 8 ≤ g1 by omega) + (by rw [hoff]; exact (G.target t htn htgt).1) + rw [hoff] at hj + simp only [exec, show ¬ S.length + 1 > 1024 by omega, ite_false, SimOutL] + exact ⟨⟨by omega, fun _ => ⟨by omega, by omega⟩, Or.inr htgt⟩, c.offset t, T, M, g1 - 8, st, ss, + Triple.seq hpush hj, SR.le hty hR, + I'.target G htn htgt (m := 2) (by omega) (by omega), R⟩ + · -- JUMPI. + simp only [blockStepL, jumpOkL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨⟨hk2, h1⟩, hdat⟩, ⟨⟨⟨⟨htn, htgt⟩, hneed⟩, hty⟩, hcost⟩⟩, hok'⟩ := hok' + rcases S with _ | ⟨cond, S'⟩ + · simp at hh; omega + rcases T with _ | ⟨cond', T'⟩ + · simp at hL + obtain rfl := (SR.head hR hdat).symm + have hR' := (SR.uncons.1 hR).2 + simp only [lowerInstr, List.cons_append, List.nil_append] at I' + obtain ⟨n1, hd1, hs1⟩ := I'.seg.head + obtain ⟨n2, hd2, hseg⟩ := hs1.head + simp only [Item.expected] at hd1 hd2 + obtain ⟨hlt2, hcode2, rfl⟩ := op_item hd2 + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hh hL hu + have hoff := toNat_offset (G.target t htn htgt).2.1 G.size_lt + obtain ⟨g1, hg1, hpush⟩ := push_itemG (msg := msg) (M := M) (st := st) (ss := ss) (gas := g) + (stack := cond :: T') hd1 (by omega) (by simp; omega) + by_cases hc : cond = 0 + · subst hc + have hj := Logic.jumpi_of_eq_zeroG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (destination := BitVec.ofNat 256 (c.offset t)) + (rest := T') hlt2 hcode2 (show 10 ≤ g1 by omega) rfl + simp only [exec, List.length_cons, show ¬ S'.length + 1 + 1 > 1024 by omega, ite_false, + ite_true] + exact SimOutL.pre (Triple.seq hpush hj) (IH (h - 1) [] _ S' T' (k - 2) s (n1 + 1) M + (g1 - 10) st ss hok' (by omega) (by hu_tac) (KR.nil _) hR' + (I'.next2 hk2 hseg (by simp only [List.length_cons]; omega) (by omega)) R) + · have hj := Logic.jumpi_takenG (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (destination := BitVec.ofNat 256 (c.offset t)) + (rest := T') hlt2 hcode2 (show 10 ≤ g1 by omega) hc + (by rw [hoff]; exact (G.target t htn htgt).1) + rw [hoff] at hj + simp only [exec, List.length_cons, show ¬ S'.length + 1 + 1 > 1024 by omega, ite_false, + hc, SimOutL] + exact ⟨⟨by omega, fun _ => ⟨by omega, by omega⟩, Or.inr htgt⟩, c.offset t, T', M, g1 - 10, st, + ss, Triple.seq hpush hj, SR.le hty hR', + I'.target G htn htgt (m := 2) (by omega) (by omega), R⟩ + · -- A pushed return label: a PUSH of the block's offset. + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨hk1, hmem⟩, ht32⟩, hok⟩ := hok' + have hmem' : t ∈ c.rets := by simpa using hmem + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + have hS := I'.stack; have hG := I'.gas + obtain ⟨g1, hg1, hpush⟩ := push_itemG (msg := msg) (M := M) (st := st) (ss := ss) (gas := g) + (stack := T) hd (by omega) (by omega) + have htn : (BitVec.ofNat 256 t).toNat = t := by + rw [BitVec.toNat_ofNat]; exact Nat.mod_eq_of_lt (by omega) + simp only [exec, show ¬ S.length + 1 > 1024 by omega, ite_false] + exact SimOutL.pre hpush (IH (h + 1) [] _ _ _ (k - 1) s next M g1 st ss hok (by simp; omega) (by hu_tac) + (KR.nil _) (SR.cons ⟨by rw [htn]; exact hmem', by rw [htn]⟩ hR) + (I'.next hk1 hseg (by simp) (by omega)) R) + · -- A dynamic jump to a return label: a JUMP to the label's offset. + simp only [blockStepL, Bool.and_eq_true, decide_eq_true_eq, beq_iff_eq, + List.all_eq_true] at hok' + obtain ⟨⟨⟨hk1, h1⟩, hlab⟩, hall⟩ := hok' + rcases S with _ | ⟨x, S'⟩ + · simp at hh; omega + rcases T with _ | ⟨y, T'⟩ + · simp at hL + obtain ⟨hw, hR'⟩ := SR.uncons.1 hR + rw [hlab] at hw + obtain ⟨hmem, rfl⟩ := hw + have hj' := hall _ hmem + simp only [jumpOkL, Bool.and_eq_true, decide_eq_true_eq] at hj' + obtain ⟨⟨⟨⟨htn, htgt⟩, hneed⟩, hty⟩, hcost⟩ := hj' + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, -⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hh hL hu + have hoff := toNat_offset (G.target _ htn htgt).2.1 G.size_lt + have hj := Logic.jumpG (message := msg) (memory := M) (state := st) (substate := ss) + (returnData := .empty) (destination := BitVec.ofNat 256 (c.offset x.toNat)) (rest := T') + hlt hcode (show 8 ≤ g by omega) (by rw [hoff]; exact (G.target _ htn htgt).1) + rw [hoff] at hj + simp only [exec, SimOutL] + exact ⟨⟨by omega, fun _ => ⟨by omega, by omega⟩, Or.inr htgt⟩, c.offset x.toNat, T', M, g - 8, st, + ss, hj, SR.le hty hR', I'.target G htn htgt (m := 1) (by omega) (by omega), R⟩ + · -- A conditional dynamic jump and a jump table: outside the fragment. + simp [blockStepL] at hok' + · simp [blockStepL] at hok' + · -- STOP. + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, -⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + simp only [exec, SimOutL] + exact SpecG.consequence (Logic.stopG hlt hcode) (fun _ h => h) + fun evm h => postL_stop R hself evm h + · -- RETURN. + obtain _ | ⟨o, known'⟩ := known + · simp [blockStepL] at hok' + obtain _ | ow := o + · simp [blockStepL] at hok' + obtain _ | ⟨o2, known'⟩ := known' + · simp [blockStepL] at hok' + obtain _ | sw := o2 + · simp [blockStepL] at hok' + simp only [blockStepL, rangeOk, Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at hok' + obtain ⟨hdat, hin⟩ := hok' + rcases S with _ | ⟨x, _ | ⟨y, S'⟩⟩ + · exact hk.not_nil.elim + · exact hk.not_one.elim + obtain ⟨rfl, hk'⟩ := KR.head hk + obtain ⟨rfl, -⟩ := KR.head hk' + rcases T with _ | ⟨x', _ | ⟨y', T'⟩⟩ + · simp at hL + · simp at hL + have htake := hR.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, -⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + have hG := I'.gas + have hmod : M.size % 32 = 0 := by rw [I'.mem.1]; omega + obtain ⟨-, hcost⟩ := extend_cost (o := ow) (sz := sw) hmod G.top_mod I'.le_top + (hin.imp_left fun h0 => BitVec.eq_of_toNat_eq (by simpa using h0)) + simp only [exec, SolarTV.EVM.Program.output, SimOutL, Bool.false_eq_true, ↓reduceIte] + exact SpecG.consequence (return_postSG (ss := ss) hlt hcode (by omega) rfl + (by rw [read_eq I'.mem]; rfl) rfl (R.slot hself)) (fun _ h => h) + (fun _ h => ⟨ss, h, R.logs⟩) + · -- REVERT. + obtain _ | ⟨o, known'⟩ := known + · simp [blockStepL] at hok' + obtain _ | ow := o + · simp [blockStepL] at hok' + obtain _ | ⟨o2, known'⟩ := known' + · simp [blockStepL] at hok' + obtain _ | sw := o2 + · simp [blockStepL] at hok' + simp only [blockStepL, rangeOk, Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at hok' + obtain ⟨hdat, hin⟩ := hok' + rcases S with _ | ⟨x, _ | ⟨y, S'⟩⟩ + · exact hk.not_nil.elim + · exact hk.not_one.elim + obtain ⟨rfl, hk'⟩ := KR.head hk + obtain ⟨rfl, -⟩ := KR.head hk' + rcases T with _ | ⟨x', _ | ⟨y', T'⟩⟩ + · simp at hL + · simp at hL + have htake := hR.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, -⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + have hG := I'.gas + have hmod : M.size % 32 = 0 := by rw [I'.mem.1]; omega + obtain ⟨-, hcost⟩ := extend_cost (o := ow) (sz := sw) hmod G.top_mod I'.le_top + (hin.imp_left fun h0 => BitVec.eq_of_toNat_eq (by simpa using h0)) + simp only [exec, SolarTV.EVM.Program.output, SimOutL, ↓reduceIte] + exact SpecG.consequence (revert_postSG (ss := ss) (by decide) hlt hcode (by omega) rfl + (by rw [read_eq I'.mem]; rfl) rfl) (fun _ h => h) (fun _ h => ⟨ss, h, R.logs⟩) + · simp [blockStepL] at hok' + + + +end SolidCore.Refinement.Solar.AssembleLoop diff --git a/SolidCore/Refinement/Solar/AssembleLoopWithin.lean b/SolidCore/Refinement/Solar/AssembleLoopWithin.lean new file mode 100644 index 00000000..6ababac8 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleLoopWithin.lean @@ -0,0 +1,205 @@ +import SolidCore.Refinement.Solar.AssembleLoopRun + +namespace SolidCore.Refinement.Solar.AssembleLoop + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open EthLib.Execution.State + +theorem rollbackOnError_ok {snap : TransactionState} {e : Evm .fusaka Nat} + (h : (rollbackOnError snap e).error = none) : rollbackOnError snap e = e := by + unfold rollbackOnError at h ⊢ + split at h + · rename_i hs; simp only at h; simp [h] at hs + · rename_i hs; simp [hs] + +/-- A message to code that is no precompile that ends with no error ran its frame to that end: +from the state, or from the state after the move of the value. -/ +theorem processMessage_ok {message : Message .fusaka} (hpre : precompileAddress .fusaka message = none) + {st : TransactionState} {ss : Substate} {evm} + (hr : processMessage (Meter := Nat) .fusaka message st ss = .ok evm) (hok : evm.1.error = none) : + ∃ (st' : TransactionState) (ss' : Substate) (runChild : MessageRunner .fusaka Nat message.gas) + (within : GasMeter.gasHeld (startFrame message st' ss' message.gas).gas ≤ message.gas), + (¬ (message.shouldTransferValue = true ∧ message.value ≠ 0) → st' = st ∧ ss' = ss) ∧ + ((message.shouldTransferValue = true ∧ message.value ≠ 0) → + st.moveEther .fusaka message.caller message.currentTarget message.value = .ok st' ∧ + ss' = { ss with logs := (pushTransferLog .fusaka ss.logs message.caller message.currentTarget + message.value) }) ∧ + runFrame (step .fusaka) (step_decreases .fusaka) message.gas runChild + (startFrame message st' ss' message.gas) within = .ok evm.1 := by + rw [processMessage] at hr + have hss : startState .fusaka message st = st := by + simp [startState, show ¬ (Fork.fusaka < Fork.paris) by decide] + simp only [hss, hpre] at hr + by_cases htr : message.shouldTransferValue = true ∧ message.value ≠ 0 + · simp only [htr, ne_eq, not_false_eq_true, and_self, ↓reduceIte] at hr + cases hm : st.moveEther .fusaka message.caller message.currentTarget message.value with + | error e => simp [hm, Except.mapError, bind, Except.bind, Except.map] at hr + | ok st' => + simp only [hm, Except.mapError, bind, Except.bind, pure, Except.pure] at hr + split at hr + · simp [throw, throwThe, MonadExceptOf.throw, Except.map] at hr + · rename_i after hrf + simp only [Except.map, Except.ok.injEq] at hr + subst hr + have := rollbackOnError_ok hok + simp only [htr.1, htr.2, not_false_eq_true, and_self, ↓reduceIte] at hrf + rw [← this] at hrf + exact ⟨st', _, _, _, fun h => absurd htr h, fun _ => ⟨rfl, rfl⟩, hrf⟩ + · simp only [htr, ↓reduceIte, bind, Except.bind, pure, Except.pure] at hr + split at hr + · simp [throw, throwThe, MonadExceptOf.throw, Except.map] at hr + · rename_i after hrf + simp only [Except.map, Except.ok.injEq] at hr + subst hr + have := rollbackOnError_ok hok + simp only [htr, ↓reduceIte] at hrf + rw [← this] at hrf + exact ⟨st, ss, _, _, fun _ => ⟨rfl, rfl⟩, fun h => absurd h htr, hrf⟩ + +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Evm.Wide in +/-- The frame of a call with `gas` gas, from a state related to the call's storage. -/ +theorem rel_start (code : ByteArray) (call : SolarTV.Call) (gas : Nat) {st' : TransactionState} + (ss' : Substate) + (h : ¬ ((Final.Target.messageWith gas code call).shouldTransferValue = true ∧ + (Final.Target.messageWith gas code call).value ≠ 0) → st' = Target.preState code call) + (hm : ((Final.Target.messageWith gas code call).shouldTransferValue = true ∧ + (Final.Target.messageWith gas code call).value ≠ 0) → + (Target.preState code call).moveEther .fusaka (Final.Target.messageWith gas code call).caller + (Final.Target.messageWith gas code call).currentTarget + (Final.Target.messageWith gas code call).value = .ok st') : + Rel (Final.Target.messageWith gas code call) ss' st' ss' (SolarTV.Machine.State.initial call) := by + have R0 := rel_initial code call + by_cases htr : (Final.Target.messageWith gas code call).shouldTransferValue = true ∧ + (Final.Target.messageWith gas code call).value ≠ 0 + · have hmove := hm htr + have hn : ((Target.preState code call).getAccount (Target.address selfAddress)).nonce ≠ 0 := by + rw [getAccount_preState_self]; simp + have hAB : Target.address selfAddress ≠ Target.address callerAddress := by decide + exact ⟨fun k => ((moveEther_recipient hmove hAB hn _).1).trans (R0.storage k), + (moveEther_recipient hmove hAB hn (Target.storageKey 0)).2, ⟨[], by simp, .nil⟩⟩ + · obtain rfl := h htr + exact ⟨R0.storage, R0.account, ⟨[], by simp, .nil⟩⟩ + +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Final + SolidCore.Refinement.Evm.Symex in +/-- **EVM IR to bytecode at every gas, for code with loops.** For every program and code the checker +of code with loops accepts, under every oracle whose caller and hash are EthLib's when the program +reads them and whose reads of the block and the transaction are EthLib's when the program reads +them (`EnvOk`, which the certificate's `reads` states), at every gas: every result the bytecode +gives on a call is the result SolarTV's EVM IR semantics gives, or a failure that leaves the +storage and logs nothing. -/ +theorem within_of_checkL {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (hc : checkL p code c mx = true) (o : SolarTV.Machine.Oracle) (ho : c.env = true → OracleOk o) + (scope : SolarTV.Call → Prop) (gas : Nat) + (he : c.reads = true → EnvOk o := by intro h; exact absurd h (by decide)) : + Within (SolarTV.evmirSem o) (ethLibWith gas) p code scope := by + obtain ⟨G, hseg, hneed0⟩ := globL_of_checkL hc + intro call _ obs hrun + change Target.runWith gas code call = some obs at hrun + cases hs : obs.success + · exact Or.inr ⟨rfl, Target.runWith_failure hrun hs⟩ + left + unfold Target.runWith Target.runMsg at hrun + split at hrun + · cases hrun + rename_i evm hev hpm + simp only [Option.some.injEq] at hrun + subst hrun + have hok : evm.error = none := by simpa using hs + obtain ⟨st', ss', runChild, within, hcases, hmove, hrf⟩ := + processMessage_ok (message := Final.Target.messageWith gas code call) (evm := ⟨evm, hev⟩) + (precompileAddress_message code call) hpm hok + simp only at hrf + -- The run, the reserve and the fuel. + set msg := Final.Target.messageWith gas code call with hmsg + have hcode : msg.code = code := rfl + have hgas : msg.gas = gas := rfl + have R := rel_start code call gas ss' (fun h => (hcases h).1) (fun h => (hmove h).1) + generalize hW : p.blocks.length + 2 = W + generalize hn : 2 * (W * gas) + W + p.blocks.length + 1 = n + generalize hK : 22100 * (n * bmax c) + memoryGasCost c.top = K + have hm0 : memoryGasCost (ByteArray.empty).size = 0 := by decide + have E0 : EntryL c code call (lowerFrom p c 0 (p.blocks.drop 0)) (n * bmax c) 0 + (SolarTV.Machine.State.initial call) .empty (gas + K) := + ⟨by rw [List.drop_zero]; exact hseg, by rw [hm0]; omega, by simp, memRel_initial⟩ + have hsim := run_simL (msg := msg) (ss0 := ss') G rfl (by simp [msg, Final.Target.messageWith, + Target.message]) rfl rfl rfl ho rfl rfl he n 0 [] [] _ 0 .empty (gas + K) st' ss' (Nat.zero_le _) + (fun _ => ⟨by simp [hneed0], by simp⟩) (SR.nil c _) E0 R + have hl : At code msg 0 [] .empty gas st' ss' .empty (startFrame msg st' ss' msg.gas) := + ⟨by simp [startFrame, hcode], by simp [startFrame, hcode], rfl, rfl, rfl, rfl, rfl, rfl, rfl, + rfl, rfl, rfl, rfl⟩ + have hp := hl.addGas K + cases hit : SolarTV.Machine.iterate (SolarTV.EVM.Program.block o call p) n + (0, [], SolarTV.Machine.State.initial call) with + | none => + exfalso + obtain ⟨z, hz, hmeas⟩ := hsim.2 hit _ hp + obtain ⟨m, -, rfl, -⟩ := reaches_low hz K _ rfl within hrf hok + have h1 : W * K ≤ W * (m.gas + K) := Nat.mul_le_mul_left _ (by simp) + simp only [gas_addGas] at hmeas h1 + unfold meas at hmeas + rw [hW] at hmeas + have h2 : W * (gas + K) = W * gas + W * K := Nat.mul_add _ _ _ + split at hmeas <;> omega + | some r => + rcases r with ⟨halt, sF⟩ + have hres : (SolarTV.evmirSem o).run p call = some (SolarTV.Machine.observe call sF halt) := by + change (SolarTV.EVM.Program.layer.result o p call).map _ = _ + rw [SolarTV.EVM.Program.layer.result_of_ends ⟨n, hit⟩] + rfl + rw [hres] + obtain ⟨ssF, ⟨herr, hout, hlogsF, hst⟩, L, hL1, hL2⟩ := + SpecG.low (hsim.1 _ hit) hp within hrf hok + have hss' : ss'.logs.toList = [] := by + by_cases htr : msg.shouldTransferValue = true ∧ msg.value ≠ 0 + · rw [(hmove htr).2] + simp [pushTransferLog, show ¬ (Fork.fusaka ≥ Fork.glamsterdam) by decide, Substate.empty] + · rw [(hcases htr).2] + simp [Substate.empty] + have hlogs := logs_of_match hL2 + have hL1' : ssF.logs.toList = L := by rw [hL1, hss', List.nil_append] + have herr' : evm.error = errorOf (SolarTV.Machine.observe call sF halt) := herr + have hout' : evm.output.toList.map (·.toNat) = (SolarTV.Machine.observe call sF halt).output := hout + have hst' : (SolarTV.Machine.observe call sF halt).success = true → + evm.substate.logs = ssF.logs ∧ ∀ slot, + (evm.state.getStorage (Target.address selfAddress) (Target.storageKey slot)).toNat = + (SolarTV.Machine.observe call sF halt).storage slot := + fun h => ⟨hlogsF, hst h⟩ + have hfail : (SolarTV.Machine.observe call sF halt).success = false → + (SolarTV.Machine.observe call sF halt).logs = [] ∧ + (SolarTV.Machine.observe call sF halt).storage = slotValue call.storage := by + cases halt <;> simp [SolarTV.Machine.observe] + have hok2 : (SolarTV.Machine.observe call sF halt).success = true → + (SolarTV.Machine.observe call sF halt).logs = SolarTV.Machine.logs sF := by + cases halt <;> simp [SolarTV.Machine.observe] + clear herr hout hst hres hsim hit + generalize SolarTV.Machine.observe call sF halt = X at * + have hsucc : evm.error.isNone = X.success := by + rw [herr']; cases hX : X.success <;> simp [errorOf, hX] + symm + congr 1 + cases X with + | mk success output logs storage => + simp only at hsucc hout' hfail hok2 hst' ⊢ + rw [SolarTV.Observable.mk.injEq] + refine ⟨hsucc, hout', ?_, ?_⟩ + · rw [hsucc] + cases hs : success + · simp [hok, hs] at hsucc + · simp only [ite_true] + rw [(hst' hs).1, hL1', hlogs, hok2 hs] + rfl + · funext slot + rw [hsucc] + cases hs : success + · simp [hok, hs] at hsucc + · simp only [ite_true] + exact (hst' hs).2 slot + +/-- +info: 'SolidCore.Refinement.Solar.AssembleLoop.within_of_checkL' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms within_of_checkL + +end SolidCore.Refinement.Solar.AssembleLoop diff --git a/SolidCore/Refinement/Solar/AssembleMem.lean b/SolidCore/Refinement/Solar/AssembleMem.lean new file mode 100644 index 00000000..3d01ff46 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleMem.lean @@ -0,0 +1,131 @@ +import SolidCore.Refinement.Solar.AssembleLoopSim + +/-! +# Memory that a budget of gas pays for + +SolarTV counts the active words of memory in `BitVec 251`, EthLib in a `Nat`. Memory whose price +`3 w + w ^ 2 / 512` is within a budget below `2 ^ 300` has fewer than `2 ^ 155` words +(`words_lt_of_cost`), so growth that a run pays for never wraps in SolarTV, and SolarTV's memory +agrees with EthLib's after it at any offset (`memRel_expandW`, `memRel_storeW`: the lemmas of +`Assemble` without the `2 ^ 32` bound of constant offsets). +-/ + +namespace SolidCore.Refinement.Solar.AssembleLoop + +open SolarTV SolarTV.Machine +open SolidCore.Refinement.Solar.Assemble +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts + +set_option exponentiation.threshold 600 in +/-- A square below \`2 ^ 502\` has its root below \`2 ^ 251\`. -/ +theorem lt_of_mul_self_lt {w : Nat} (h : w * w < 2 ^ 502) : w < 2 ^ 251 := by + refine Nat.lt_of_not_le fun hw => ?_ + have hsq := Nat.mul_le_mul hw hw + have e : (2 : Nat) ^ 251 * 2 ^ 251 = 2 ^ 502 := by rw [← Nat.pow_add] + omega + +/-- **Memory a budget below \`2 ^ 300\` pays for has fewer than \`2 ^ 251\` words**, so SolarTV's count +of words does not wrap. -/ +theorem words_lt_of_cost {n B : Nat} (h : memoryGasCost n ≤ B) (hB : B < 2 ^ 300) : + (n + 31) / 32 < 2 ^ 251 := by + have hw := wordCount_mul_self_le h + have e : wordCount n = (n + 31) / 32 := by + unfold wordCount WORD_BYTES + rw [ceil32_eq] + omega + rw [e] at hw + apply lt_of_mul_self_lt + generalize (n + 31) / 32 * ((n + 31) / 32) = sq at hw ⊢ + omega + +/-- Memory a budget below `2 ^ 256` pays for is at most `2 ^ 140` bytes. -/ +theorem size_le_of_cost {n B : Nat} (h : memoryGasCost n ≤ B) (hB : B < 2 ^ 256) (hmod : n % 32 = 0) : + n ≤ 2 ^ 140 := by + have hw := wordCount_mul_self_le h + have e : wordCount n = (n + 31) / 32 := by + unfold wordCount WORD_BYTES + rw [ceil32_eq] + omega + rw [e] at hw + have hlt : (n + 31) / 32 < 2 ^ 135 := by + refine Nat.lt_of_not_le fun hw' => ?_ + have hsq := Nat.mul_le_mul hw' hw' + have e2 : (2 : Nat) ^ 135 * 2 ^ 135 = 2 ^ 270 := by rw [← Nat.pow_add] + generalize (n + 31) / 32 * ((n + 31) / 32) = sq at hw hsq + omega + omega + +/-! ## SolarTV's memory and EthLib's at any range SolarTV holds -/ + +open SolarTV.Machine in +/-- \`Assemble.memRel_expand\` for every range whose words SolarTV holds. -/ +theorem memRel_expandW {m : Mem} {M : ByteArray} {o sz : Word} (hm : MemRel m M) + (hbound : sz = 0 ∨ (o.toNat + sz.toNat + 31) / 32 < 2 ^ 251) : + MemRel (m.expand o.toNat sz.toNat) (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) := by + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have hb : (m.expand o.toNat sz.toNat).bytes = m.bytes := by unfold Mem.expand; split <;> rfl + refine ⟨?_, fun i => by rw [byteAt_memoryExtend, hb]; exact hm.2 i⟩ + by_cases hz : sz = 0 + · subst hz + rw [extendMemory_zero', memoryExtend_zero] + simpa [Mem.expand] using hm.1 + · have hlt := hbound.resolve_left hz + rw [size_memoryExtend_extendMemory' hmod hz, hm.1, ceil32_eq] + have hz' : sz.toNat ≠ 0 := fun h => hz (BitVec.eq_of_toNat_eq (by simpa using h)) + unfold Mem.expand SolarTV.Memory.grow + simp only [hz', ite_false] + split + · rename_i h + rw [BitVec.ult_iff_toNat_lt, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hlt] at h + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt hlt] + omega + · rename_i h + rw [BitVec.ult_iff_toNat_lt, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hlt] at h + omega + +open SolarTV.Machine in +/-- \`Assemble.memRel_store\` for every offset whose word SolarTV holds. -/ +theorem memRel_storeW {m : Mem} {M : ByteArray} {o v : Word} (hm : MemRel m M) + (hlt : (o.toNat + 32 + 31) / 32 < 2 ^ 251) : + MemRel (m.store o.toNat v) + (memoryWrite (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy) o.toNat (wordBytes v)) ∧ + (memoryWrite (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy) o.toNat + (wordBytes v)).size = max M.size (ceil32 (o.toNat + 32)) := by + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have hext := size_memoryExtend_extendMemory' (memory := M) (start := o) (length := 32) hmod + (by decide) + have h32 : (32 : U256).toNat = 32 := rfl + rw [h32] at hext + have hfit : o.toNat + (wordBytes v).size ≤ + (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy).size := by + rw [size_wordBytes, hext] + have := le_ceil32 (o.toNat + 32) + omega + have hsize : (memoryWrite (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy) o.toNat + (wordBytes v)).size = max M.size (ceil32 (o.toNat + 32)) := by + rw [size_memoryWrite_of_fit (fun _ => hfit), hext] + refine ⟨⟨?_, fun i => ?_⟩, hsize⟩ + · rw [hsize, hm.1, ceil32_eq] + unfold Mem.store Mem.expand SolarTV.Memory.grow + simp only [show (32 = 0) = False from by decide, ite_false] + split + · rename_i h + rw [BitVec.ult_iff_toNat_lt, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hlt] at h + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt hlt] + omega + · rename_i h + rw [BitVec.ult_iff_toNat_lt, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hlt] at h + omega + · rw [byteAt_memoryWrite hfit, byteAt_memoryExtend, size_wordBytes] + have hb : (m.store o.toNat v).bytes i = + if o.toNat ≤ i ∧ i < o.toNat + 32 then SolarTV.Memory.byte v (i - o.toNat) else m.bytes i := by + unfold Mem.store Mem.expand + simp only [show (32 = 0) = False from by decide, ite_false] + rw [hb] + split + · rename_i h + exact byteAt_wordBytes v _ (by omega) + · exact hm.2 i + +end SolidCore.Refinement.Solar.AssembleLoop diff --git a/SolidCore/Refinement/Solar/AssembleNoCall.lean b/SolidCore/Refinement/Solar/AssembleNoCall.lean new file mode 100644 index 00000000..cceab4cb --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleNoCall.lean @@ -0,0 +1,526 @@ +import SolidCore.Refinement.Solar.AssembleCallStaticRunner +import SolidCore.Refinement.Solar.AssembleCtxCall + +/-! +# The runner premises for code that makes no call (slice-runners) + +The checker with STATICCALLs (`AssembleCut.checkCB`, `AssembleCtx.checkXB`) gives its per-run theorem +under two named hypotheses (`AssembleCallSeg.StaticRunner`, `AssembleCallSeg.CalleesRun`). This file +settles both for code whose exact bytes make no call: + +* **`StaticRunner` is refuted**, not discharged: EthLib's IDENTITY precompile returns its call data, + so a message to address 4 with `2 ^ 256` bytes of data and the gas to pay for them ends with an + output of `2 ^ 256` bytes, against `AssembleCallCut.OutputFits` (`not_outputRunner`, + `not_staticRunner`, at a gas of `2 ^ 255`, below the `2 ^ 256` the final theorems use). So + `∀ gas, StaticRunner gas` and `∀ gas, AssembleCallStaticRunner.OutputRunner gas` are false + (`not_forall_staticRunner`, `not_forall_outputRunner`), and every theorem that assumes either + holds vacuously. +* **For call-free code neither hypothesis is needed** (`holds_of_checkCB_callFree`, + `runs_shape_of_checkCB_callFree`, `assembly_of_checkXB_callFree`): `callFree` is a syntactic + check over the exact bytes, decoded linearly from 0 as the walk reads them (PUSH immediates + skipped), that no instruction is CREATE, CALL, CALLCODE, DELEGATECALL, CREATE2, STATICCALL, + RETURNDATASIZE or RETURNDATACOPY. A program the checker with STATICCALLs accepts on such bytes has + no STATICCALL, RETURNDATASIZE or RETURNDATACOPY instruction (`noCallI_of_callFree`), so the same + certificate with its call flag cleared passes the no-call checker (`checkC_of_checkCB_callFree`, + `checkX_of_checkXB_callFree`), whose theorem (`AssembleCut.assembly_of_checkC`, + `AssembleCtx.assembly_of_checkX`) has no hypothesis on the runner. +* **`CalleesRun` is discharged outright** for bytes with no `0xfa` byte at all + (`calleesRun_of_noFaByte`). It quantifies over every frame at any counter whose byte is `0xfa`, + not only over the instructions a run reaches, so a scan that skips PUSH immediates cannot + discharge it as stated; `callFree` code does not need it (above). +-/ + +namespace SolidCore.Refinement.Solar.AssembleNoCall + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Witness SolidCore.Refinement.Final +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.RunOracle +open SolidCore.Refinement.Solar.AssembleCut SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCallCut SolidCore.Refinement.Solar.AssembleCallSeg +open SolidCore.Refinement.Solar.AssembleCallStaticRunner +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic + +/-! ## 1. `StaticRunner` is false: IDENTITY returns its call data -/ + +/-- A message that IDENTITY (address 4) runs: no value moved, precompiles enabled. -/ +theorem identity_output (state : State.TransactionState) (substate : Substate) (m : Message .fusaka) + (htv : m.shouldTransferValue = false) (hpa : precompileAddress .fusaka m = some 4) + (hdis : m.disablePrecompiles = false) + (hgas : Precompiles.Identity.gasCost m.data.size ≤ m.gas) : + ∃ ended, processMessage (Meter := Nat) .fusaka m state substate = .ok ended ∧ + ended.val.output = m.data := by + have hrun : Precompiles.run .fusaka 4 m.data m.gas = some (.ok m.data) := by + simp only [Precompiles.run, Precompiles.Identity.identity, Except.mapError] + simp [Precompiles.isPrecompile, Precompiles.addedAt, Nat.not_lt.2 hgas] + decide + have hpr : Precompiles.price .fusaka 4 m.data = some (Precompiles.Identity.gasCost m.data.size) := by + simp [Precompiles.price, Precompiles.isPrecompile, Precompiles.addedAt] + decide + have hrp : ∀ st ss, runPrecompile .fusaka 4 (startFrame m st ss (GasMeter.start (Meter := Nat) m.gas m.reservoir)) = + some { startFrame m st ss (GasMeter.start (Meter := Nat) m.gas m.reservoir) with + gas := m.gas - Precompiles.Identity.gasCost m.data.size, output := m.data, running := false } := by + intro st ss + simp only [runPrecompile, startFrame, GasMeter.gasLeft, GasMeter.start, hrun, hpr, + Option.getD_some, GasMeter.charge, Nat.not_lt.2 hgas, ite_false] + rw [processMessage] + simp only [htv, hpa, hdis, Bool.false_eq_true, false_and, ite_false, pure_bind] + split + · rename_i after h + rw [hrp] at h + cases h + exact ⟨_, rfl, by simp [rollbackOnError, startFrame]⟩ + · rename_i h + rw [hrp] at h + cases h + +/-- `2 ^ 256` zero bytes. -/ +def bigData : ByteArray := ⟨Array.replicate (2 ^ 256) 0⟩ + +theorem bigData_size : bigData.size = 2 ^ 256 := by + simp [bigData, ByteArray.size] + +/-- The gas IDENTITY charges for `bigData`. -/ +abbrev bigGas : Nat := Precompiles.Identity.gasCost (2 ^ 256) + +theorem bigGas_lt : bigGas < 2 ^ 255 := by + simp only [bigGas, Precompiles.Identity.gasCost, Precompiles.Identity.GAS_BASE, + Precompiles.Identity.GAS_PER_WORD, wordCount] + decide + +/-- A static message to IDENTITY with `bigData` and the gas to pay for it. -/ +def idMessage (blockEnv : BlockEnvironment .fusaka) (txEnv : TransactionEnvironment .fusaka) : + Message .fusaka where + blockEnv := blockEnv + txEnv := txEnv + caller := Target.address 0 + target := some (Target.address 4) + currentTarget := Target.address 4 + gas := bigGas + value := 0 + data := bigData + codeAddress := some (Target.address 4) + code := .empty + depth := 0 + shouldTransferValue := false + isStatic := true + disablePrecompiles := false + +/-- **`OutputRunner` fails at every gas above IDENTITY's price for `2 ^ 256` bytes**: the runner of +messages ends `idMessage` with an output of `2 ^ 256` bytes, from any caller. -/ +theorem not_outputRunner_of_lt {gas : Nat} (hg : bigGas < gas) (caller : Evm .fusaka Nat) : + ¬ OutputRunner gas := by + intro h + let m := idMessage caller.message.blockEnv caller.message.txEnv + have hpa : precompileAddress .fusaka m = some 4 := by + simp only [precompileAddress, m, idMessage] + decide + obtain ⟨ended, hrun, hout⟩ := identity_output caller.state caller.substate.child m rfl hpa rfl + (by rw [show m.data = bigData from rfl, bigData_size]; exact le_refl _) + have hfit := h.ok caller m hg ended (by simpa [processRunner, m, idMessage] using hrun) + simp only [OutputFits, hout, m, idMessage, bigData_size] at hfit + exact Nat.lt_irrefl _ hfit + +/-- The caller frame of the counterexample: any frame will do. -/ +def someCaller : Evm .fusaka Nat := + startFrame (idMessage Target.blockEnv Target.txEnv) (Target.preState .empty default) Substate.empty 0 + +theorem not_outputRunner : ¬ OutputRunner (2 ^ 255) := + not_outputRunner_of_lt bigGas_lt someCaller + +/-- **`StaticRunner` fails at gas `2 ^ 255`**: its `OutputFits` half is `not_outputRunner`. -/ +theorem not_staticRunner : ¬ StaticRunner (2 ^ 255) := fun h => + not_outputRunner ⟨fun a b c d e => (h.ok a b c d e).2, h.aborts⟩ + +theorem not_forall_staticRunner : ¬ ∀ gas, StaticRunner gas := fun h => not_staticRunner (h _) + +theorem not_forall_outputRunner : ¬ ∀ gas, OutputRunner gas := fun h => not_outputRunner (h _) + +/-- Even below `2 ^ 256` gas, where the final theorems use it. -/ +theorem not_forall_lt_staticRunner : ¬ ∀ gas, gas < 2 ^ 256 → StaticRunner gas := fun h => + not_staticRunner (h _ (by decide)) + +/-! ## 2. The syntactic check over the exact bytes -/ + +/-- The opcodes that send a message or read the return data of one: CREATE, CALL, CALLCODE, +DELEGATECALL, CREATE2, STATICCALL, RETURNDATASIZE, RETURNDATACOPY. -/ +def callOps : List Nat := [0xf0, 0xf1, 0xf2, 0xf4, 0xf5, 0xfa, 0x3d, 0x3e] + +/-- An instruction that is none of `callOps`. -/ +def instrFree : SolarTV.Assembly.Instr → Bool + | .op b => !callOps.contains b + | _ => true + +/-- **The syntactic no-call check over the exact bytes**: the instructions of `code`, decoded +linearly from 0 (`SolarTV.Assembly.decodeFrom`, PUSH immediates skipped), are none of `callOps`. -/ +def callFree (code : ByteArray) : Bool := + (decodeFrom (bytesOf code) code.size 0).all fun x => instrFree x.2 + +theorem decode_next_gt {code : List Nat} {pc next : Nat} {i : SolarTV.Assembly.Instr} + (h : decode code pc = some (i, next)) : pc < next := by + unfold decode at h + split at h + · cases h + · split at h + · cases h; omega + · split at h + · split at h + · cases h; omega + · cases h + · split at h + · split at h + · split at h + · cases h; omega + · cases h + · cases h + · cases h; omega + +theorem seg_length_le {code : List Nat} {off : Nat → Nat} {pc pc' : Nat} {items : List Item} + (h : Seg code off pc items pc') : pc + items.length ≤ pc' := by + induction h with + | nil => simp + | cons d _ _ ih => + have := decode_next_gt d + simp only [List.length_cons] + omega + +theorem seg_mem_decodeFrom {code : List Nat} {off : Nat → Nat} {pc pc' : Nat} {items : List Item} + (h : Seg code off pc items pc') : + ∀ fuel, items.length ≤ fuel → ∀ item ∈ items, ∃ q, (q, item.expected off) ∈ decodeFrom code fuel pc := by + induction h with + | nil => intro _ _ item hm; cases hm + | @cons pc next pc' item items d _ _ ih => + intro fuel hf it hm + obtain ⟨f, rfl⟩ : ∃ f, fuel = f + 1 := ⟨fuel - 1, by simp only [List.length_cons] at hf; omega⟩ + simp only [decodeFrom, d] + rcases List.mem_cons.1 hm with rfl | hm + · exact ⟨pc, List.mem_cons_self⟩ + · obtain ⟨q, hq⟩ := ih f (by simp only [List.length_cons] at hf; omega) it hm + exact ⟨q, List.mem_cons_of_mem _ hq⟩ + +/-- An EVM IR instruction the checker gates on the certificate's call flag. -/ +def NoCallI (i : Assemble.Instr) : Prop := isScI i = false ∧ isRdsI i = false ∧ isRdcI i = false + +theorem lowerInstr_of_callI {i : Assemble.Instr} (h : ¬ NoCallI i) : + ∃ byte ∈ callOps, lowerInstr i = [.op byte] ∧ (∀ t, i ≠ .jumpi t) ∧ (∀ t, i ≠ .jump t) ∧ + i ≠ .stop := by + simp only [NoCallI, not_and_or, Bool.not_eq_false] at h + rcases h with h | h | h + · unfold isScI at h; split at h <;> simp_all [lowerInstr, callOps] + · unfold isRdsI at h; split at h <;> simp_all [lowerInstr, callOps] + · unfold isRdcI at h; split at h <;> simp_all [lowerInstr, callOps] + +theorem turnedElse_rest {c : Cert} {b e : Nat} {j : Assemble.Instr} {rest : List Assemble.Instr} + (h : turnedElse c b j rest = some e) : ∃ e', rest = [.jump e'] := by + unfold turnedElse at h + split at h + · exact ⟨_, rfl⟩ + · cases h + +theorem dropped_rest {p : Assemble.Program} {b : Nat} {j : Assemble.Instr} {rest : List Assemble.Instr} + (h : dropped p b j rest = true) : rest = [] := by + unfold dropped at h + split at h <;> first | rfl | cases h + +theorem mem_lowerInstrs {p : Assemble.Program} {c : Cert} {b : Nat} {i : Assemble.Instr} + (hi : ¬ NoCallI i) : ∀ {instrs : List Assemble.Instr}, i ∈ instrs → + ∃ byte ∈ callOps, Item.op byte ∈ lowerInstrs p c b instrs + | [], h => absurd h List.not_mem_nil + | j :: rest, h => by + obtain ⟨byte, hb, hlow, hji, hjj, hjs⟩ := lowerInstr_of_callI hi + unfold lowerInstrs + rcases List.mem_cons.1 h with rfl | h + · have ht : turnedElse c b i rest = none := by + unfold turnedElse; split + · exact absurd rfl (hji _) + · rfl + have hd : dropped p b i rest = false := by + unfold dropped; split + · exact absurd rfl (hjj _) + · exact absurd rfl hjs + · rfl + rw [ht] + simp only [hd, Bool.false_eq_true, ite_false, hlow, List.singleton_append] + exact ⟨byte, hb, List.mem_cons_self⟩ + · cases hte : turnedElse c b j rest with + | some e => + exfalso + obtain ⟨e', rfl⟩ := turnedElse_rest hte + simp only [List.mem_singleton] at h + exact hjj e' h + | none => + simp only + by_cases hd : dropped p b j rest = true + · exfalso + rw [dropped_rest hd] at h + exact List.not_mem_nil h + · simp only [hd, Bool.false_eq_true, ite_false, List.mem_append] + obtain ⟨byte', hb', hm⟩ := mem_lowerInstrs hi h + exact ⟨byte', hb', Or.inr hm⟩ + +theorem mem_lowerFrom {p : Assemble.Program} {c : Cert} {item : Item} : + ∀ (blocks : List (List Assemble.Instr)) (b0 k : Nat) (hk : k < blocks.length), + item ∈ lowerInstrs p c (b0 + k) blocks[k] → item ∈ lowerFrom p c b0 blocks + | [], _, _, hk, _ => absurd hk (by simp) + | x :: l, b0, 0, _, h => by + simp only [lowerFrom, lowerBlock, List.mem_append] + exact Or.inl (Or.inr (by simpa using h)) + | x :: l, b0, k + 1, hk, h => by + simp only [lowerFrom, List.mem_append] + refine Or.inr (mem_lowerFrom l (b0 + 1) k (by simp at hk; omega) ?_) + rw [show b0 + 1 + k = b0 + (k + 1) by omega] + simpa using h + +/-- **The bytes' check reaches the program**: when the walk reads the lowered program off bytes +that pass `callFree`, no instruction of the program is a STATICCALL, RETURNDATASIZE or +RETURNDATACOPY. -/ +theorem noCallI_of_callFree {p : Assemble.Program} {code : ByteArray} {c : Cert} + (hseg : Seg (bytesOf code) c.offset 0 (lower p c) code.size) (hfree : callFree code = true) : + ∀ b (hb : b < p.blocks.length), ∀ i ∈ p.blocks[b], NoCallI i := by + intro b hb i hi + by_contra hn + obtain ⟨byte, hbyte, hm⟩ := mem_lowerInstrs (p := p) (c := c) (b := 0 + b) hn hi + have hl : Item.op byte ∈ lower p c := mem_lowerFrom p.blocks 0 b hb hm + have hlen := seg_length_le hseg + obtain ⟨q, hq⟩ := seg_mem_decodeFrom hseg code.size (by omega) _ hl + have := List.all_eq_true.1 hfree _ hq + simp only [Item.expected, instrFree, Bool.not_eq_true', List.contains_eq_mem, + decide_eq_false_iff_not] at this + exact this hbyte + +/-! ## 3. The certificate with its call flag cleared -/ + +/-- The certificate that says the program makes no call. -/ +def noCallCert (c : Cert) : Cert := { c with calls := false } + +theorem isTarget_flip (p : Assemble.Program) (c : Cert) (t : Nat) : + isTarget p (noCallCert c) t = isTarget p c t := + @SolidCore.Refinement.Solar.AssembleCtx.isTarget_congr (noCallCert c) c rfl p t + +theorem fallOkL_flip (p : Assemble.Program) (c : Cert) (mx : List Nat) (b h : Nat) (ty : List Ty) : + fallOkL p (noCallCert c) mx b h ty = fallOkL p c mx b h ty := rfl + +theorem jumpOkL_flip (p : Assemble.Program) (c : Cert) (mx : List Nat) (b t h : Nat) (ty : List Ty) : + jumpOkL p (noCallCert c) mx b t h ty = jumpOkL p c mx b t h ty := by + simp only [jumpOkL, isTarget_flip]; rfl + +theorem blockStepL_flip (p : Assemble.Program) (c : Cert) (mx : List Nat) (b : Nat) + (ok : Nat → Known → List Ty → Nat → Bool) : + blockStepL p (noCallCert c) mx b ok = blockStepL p c mx b ok := by + funext h known ty k i + cases i <;> (try simp only [blockStepL, jumpOkL_flip]) <;> rfl + +theorem turnedElse_flip (c : Cert) : turnedElse (noCallCert c) = turnedElse c := by + funext b i rest + exact @SolidCore.Refinement.Solar.AssembleCtx.turnedElse_congr (noCallCert c) c rfl b i rest + +theorem blockOkC_flip {p : Assemble.Program} {c : Cert} {mx : List Nat} {b : Nat} + (hcr : c.creates = false) : ∀ (instrs : List Assemble.Instr), (∀ i ∈ instrs, NoCallI i) → + ∀ h known ty k, blockOkC p (noCallCert c) mx b h known ty k instrs = + blockOkC p c mx b h known ty k instrs := by + intro instrs + induction instrs with + | nil => intro _ h known ty k; simp only [blockOkC, fallOkL_flip] + | cons i rest ih => + intro hno h known ty k + have ih' := ih (fun j hj => hno j (List.mem_cons_of_mem _ hj)) + obtain ⟨hsc, hrds, hrdc⟩ := hno i List.mem_cons_self + have hc' : (noCallCert c).calls = false := rfl + have hcr' : (noCallCert c).creates = false := hcr + have he : (noCallCert c).env = c.env := rfl + have ht : (noCallCert c).top = c.top := rfl + simp only [blockOkC, turnedElse_flip, fallOkL_flip, jumpOkL_flip, blockStepL_flip, ih', hsc, + hrds, hrdc, hc', hcr', hcr, he, ht, Bool.false_and, Bool.and_false, Bool.false_eq_true, + ite_false] + +theorem blocksOkC_flip {p : Assemble.Program} {c : Cert} {mx : List Nat} (hcr : c.creates = false) : + ∀ (blocks : List (List Assemble.Instr)) (b : Nat), (∀ k (hk : k < blocks.length), ∀ i ∈ blocks[k], NoCallI i) → + blocksOkC p (noCallCert c) mx b blocks = blocksOkC p c mx b blocks + | [], _, _ => rfl + | x :: l, b, h => by + have h0 := h 0 (by simp) + have hl : ∀ k (hk : k < l.length), ∀ i ∈ l[k], NoCallI i := fun k hk => h (k + 1) (by simp; omega) + simp only [blocksOkC, labelItems, isTarget_flip, blockOkC_flip hcr x (by simpa using h0), + blocksOkC_flip hcr l (b + 1) hl] + rfl + +theorem lower_flip (p : Assemble.Program) (c : Cert) : lower p (noCallCert c) = lower p c := + @SolidCore.Refinement.Solar.AssembleCtx.lowerFrom_congr (noCallCert c) c rfl p 0 p.blocks + +theorem labelsValid_flip (p : Assemble.Program) (c : Cert) (code : ByteArray) : + labelsValid p (noCallCert c) code = labelsValid p c code := by + simp only [labelsValid, isTarget_flip]; rfl + +/-- **The checker with STATICCALLs on call-free bytes is the no-call checker**: the same program, +bytes and certificate, with the call flag cleared. -/ +theorem checkC_of_checkCB_callFree {p : Assemble.Program} {code : ByteArray} {c : Cert} + {mx : List Nat} (hc : checkCB p code c mx = true) (hfree : callFree code = true) : + checkC p code (noCallCert c) mx = true := by + obtain ⟨-, hseg, -⟩ := globC_of_checkC hc + have hno := noCallI_of_callFree hseg hfree + have hcr := checkCB_creates hc + have hb := blocksOkC_flip (p := p) (mx := mx) hcr p.blocks 0 hno + simp only [checkCB, Bool.and_eq_true] at hc + simp only [checkC, Bool.and_eq_true, lower_flip, labelsValid_flip, hb] + obtain ⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, h8⟩ := hc + exact ⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, rfl⟩, h8⟩ + +/-! ## 4. The final theorems with no runner hypothesis -/ + +/-- **EVM IR to the exact bytecode for call-free code, with no hypothesis on the runner**: every +program the checker with STATICCALLs accepts on bytes that pass `callFree`. -/ +theorem assembly_of_checkCB_callFree {p : Assemble.Program} {code : ByteArray} {c : Cert} + {mx : List Nat} (hc : checkCB p code c mx = true) (hfree : callFree code = true) + (scope : Call → Prop) : + ∀ gas, gas < 2 ^ 256 → ∀ call, scope call → ∃ (o : Oracle) (W : World), W.Open ∧ + CallsAgree o W ∧ Within (evmirSem o) (ethLibWith gas) p code (· = call) := + assembly_of_checkC (checkC_of_checkCB_callFree hc hfree) scope + +/-- `AssembleCallSeg.runs_shape_of_checkCB` without `StaticRunner` and `CalleesRun`, for call-free +bytes. -/ +theorem runs_shape_of_checkCB_callFree {p : Assemble.Program} {code : ByteArray} {c : Cert} + {mx : List Nat} (hc : checkCB p code c mx = true) (hfree : callFree code = true) + (Valid : Call → Prop) : + ∀ gas, gas < 2 ^ 256 → ∀ call, Valid call → ∃ o : Oracle, + (CertOk c o ∧ ∃ W : World, W.Open ∧ CallsAgree o W) ∧ + Within (evmirSem o) (ethLibWith gas) p code (· = call) := by + intro gas hgas call _ + obtain ⟨T, hT⟩ := runs_of_checkC (checkC_of_checkCB_callFree hc hfree) gas hgas call + obtain ⟨W, hW, hA⟩ := O_agree T + exact ⟨O T, ⟨O_ok c T, W, hW, hA⟩, hT⟩ + +/-- **`AssembleCallSeg.holds_of_checkCB` for call-free bytes, with no runner hypothesis**: the +source's specification at every open world, its totality, the stages to EVM IR and the checker +with STATICCALLs on bytes that pass `callFree` give the specification of the exact bytecode at +every gas below `2 ^ 256`. -/ +theorem holds_of_checkCB_callFree {St : Type} {fuel : Nat} + {mirSem : SolarTV.Machine.Oracle → Sem} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {mir : ∀ o, (mirSem o).Prog} {p : Assemble.Program} {code : ByteArray} {cert : Cert} + {mx : List Nat} {spec : Final.ContractSpec St} + (source : ∀ W : World, W.Open → Final.Holds (solidCoreIn W fuel) c spec) + (fin : ∀ W : World, W.Open → ∀ call, spec.Calls call → (Source.runIn W fuel c call).isSome) + (lowering : ∀ o W, CallsAgree o W → Stage (solidCoreIn W fuel) (mirSem o) c (mir o) spec.Calls) + (backend : ∀ o, Stage (mirSem o) (evmirSem o) (mir o) p spec.Calls) + (hc : checkCB p code cert mx = true) (hfree : callFree code = true) + (gas : Nat) (hgas : gas < 2 ^ 256) : Final.Holds (Final.ethLibWith gas) code spec := + holds_of_runs_lt (evmirSem := evmirSem) (evmir := fun _ => p) source fin lowering backend + (assembly_of_checkCB_callFree hc hfree spec.Calls) gas hgas + +/-! ## 5. `CalleesRun` for bytes with no 0xfa byte -/ + +/-- No byte of `code` is `0xfa` (STATICCALL), PUSH immediates included. -/ +def noFaByte (code : ByteArray) : Bool := code.data.all (· != 0xfa) + +theorem ne_fa_of_noFaByte {code : ByteArray} (h : noFaByte code = true) : + ∀ i (hi : i < code.size), code[i] ≠ 0xfa := by + intro i hi heq + have := (Array.all_eq_true.1 h) i hi + simp only [bne_iff_ne, ne_eq] at this + exact this heq + +/-- **`CalleesRun` discharged for bytes with no `0xfa` byte**, at every gas and call: no frame of +the code is at a STATICCALL. -/ +theorem calleesRun_of_noFaByte {code : ByteArray} (h : noFaByte code = true) (gas : Nat) + (call : Call) : CalleesRun gas code call := by + intro r _ _ e within pc asked addr inOff inSize outOff outSize S M g st ss rd _ hlt hb _ + exact absurd hb (ne_fa_of_noFaByte h pc hlt) + +theorem calleesRunR_of_noFaByte {code : ByteArray} (h : noFaByte code = true) (gas : Nat) + (call : Call) : CalleesRunR gas code call := by + intro r _ _ e within pc asked addr inOff inSize outOff outSize S M g st ss rd _ hlt hb _ + exact absurd hb (ne_fa_of_noFaByte h pc hlt) + +/-! ## Axioms -/ + +/-- info: 'SolidCore.Refinement.Solar.AssembleNoCall.not_forall_staticRunner' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms not_forall_staticRunner + +/-- info: 'SolidCore.Refinement.Solar.AssembleNoCall.not_forall_lt_staticRunner' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms not_forall_lt_staticRunner + +/-- info: 'SolidCore.Refinement.Solar.AssembleNoCall.not_forall_outputRunner' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms not_forall_outputRunner + +/-- info: 'SolidCore.Refinement.Solar.AssembleNoCall.holds_of_checkCB_callFree' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holds_of_checkCB_callFree + +/-- info: 'SolidCore.Refinement.Solar.AssembleNoCall.runs_shape_of_checkCB_callFree' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms runs_shape_of_checkCB_callFree + +/-- info: 'SolidCore.Refinement.Solar.AssembleNoCall.calleesRun_of_noFaByte' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms calleesRun_of_noFaByte + + +/-! ## 6. The checker with contexts -/ + +open SolidCore.Refinement.Solar.AssembleCtx in +/-- The context certificate whose base says the program makes no call. -/ +def noCallCtx (cx : SolidCore.Refinement.Solar.AssembleCtx.CtxCert) : + SolidCore.Refinement.Solar.AssembleCtx.CtxCert := { cx with base := noCallCert cx.base } + +open SolidCore.Refinement.Solar.AssembleCtx in +theorem ctxOk_flip {p : Assemble.Program} {cx : CtxCert} {b j : Nat} {instrs : List Assemble.Instr} + (hcr : cx.base.creates = false) (hno : ∀ i ∈ instrs, NoCallI i) : + ctxOk p (noCallCtx cx) b j instrs = ctxOk p cx b j instrs := by + have hc : certAt (noCallCtx cx) (p.blocks.length + 1) b j = + noCallCert (certAt cx (p.blocks.length + 1) b j) := rfl + have hm : maxsAt (noCallCtx cx) (p.blocks.length + 1) b j = maxsAt cx (p.blocks.length + 1) b j := rfl + have hb := blockOkC_flip (p := p) (c := certAt cx (p.blocks.length + 1) b j) + (mx := maxsAt cx (p.blocks.length + 1) b j) (b := b) hcr instrs hno + simp only [ctxOk, hc, hm, blockCtxOk, labelItems, isTarget_flip, hb] + rfl + +open SolidCore.Refinement.Solar.AssembleCtx in +theorem blocksX_flip {p : Assemble.Program} {cx : CtxCert} (hcr : cx.base.creates = false) : + ∀ (blocks : List (List Assemble.Instr)) (b : Nat), + (∀ k (hk : k < blocks.length), ∀ i ∈ blocks[k], NoCallI i) → + blocksX p (noCallCtx cx) b blocks = blocksX p cx b blocks + | [], _, _ => rfl + | x :: l, b, h => by + have h0 := h 0 (by simp) + have hl : ∀ k (hk : k < l.length), ∀ i ∈ l[k], NoCallI i := fun k hk => h (k + 1) (by simp; omega) + have hx : ∀ j, ctxOk p (noCallCtx cx) b j x = ctxOk p cx b j x := + fun j => ctxOk_flip hcr (by simpa using h0) + simp only [blocksX, hx, blocksX_flip hcr l (b + 1) hl] + rfl + +open SolidCore.Refinement.Solar.AssembleCtx in +/-- **The checker with contexts and STATICCALLs on call-free bytes is the no-call checker with +contexts**, with the base certificate's call flag cleared. -/ +theorem checkX_of_checkXB_callFree {p : Assemble.Program} {code : ByteArray} {cx : CtxCert} + (hc : checkXB p code cx = true) (hfree : callFree code = true) : + checkX p code (noCallCtx cx) = true := by + obtain ⟨G, hseg, -, -⟩ := globXB_of_checkXB hc + have hno := noCallI_of_callFree hseg hfree + have hb := blocksX_flip (p := p) G.creates p.blocks 0 hno + have hl : lower p (noCallCtx cx).base = lower p cx.base := lower_flip p cx.base + have hv : labelsValid p (noCallCtx cx).base code = labelsValid p cx.base code := + labelsValid_flip p cx.base code + simp only [checkXB, Bool.and_eq_true] at hc + obtain ⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, h8⟩, h9⟩ := hc + simp only [checkX, Bool.and_eq_true, hl, hv, hb] + exact ⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, rfl⟩, h6⟩, h7⟩, h9⟩ + +open SolidCore.Refinement.Solar.AssembleCtx in +/-- **`AssembleCtx.assembly_of_checkXB_norm` for call-free bytes, with no runner hypothesis**: the +shape an exported contract's `Ctx.bytecode` theorem has, without `StaticRunner` and +`CalleesRun`. -/ +theorem assembly_of_checkXB_norm_callFree {p : Assemble.Program} {code : ByteArray} {cx : CtxCert} + (hc : checkXB (norm p) code cx = true) (hfree : callFree code = true) (scope : Call → Prop) : + ∀ gas, gas < 2 ^ 256 → ∀ call, scope call → ∃ (o : Oracle) (W : World), W.Open ∧ + CallsAgree o W ∧ CertOk cx.base o ∧ Within (evmirSem o) (ethLibWith gas) p code (· = call) := by + intro gas hgas call _ + obtain ⟨T, hT⟩ := runs_of_checkX (checkX_of_checkXB_callFree hc hfree) gas hgas call + obtain ⟨W, hW, hA⟩ := O_agree T + exact ⟨O T, W, hW, hA, O_ok cx.base T, within_norm hT⟩ + +/-- info: 'SolidCore.Refinement.Solar.AssembleNoCall.assembly_of_checkXB_norm_callFree' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms assembly_of_checkXB_norm_callFree + +end SolidCore.Refinement.Solar.AssembleNoCall diff --git a/SolidCore/Refinement/Solar/AssembleNoCallExample.lean b/SolidCore/Refinement/Solar/AssembleNoCallExample.lean new file mode 100644 index 00000000..fa5e3ad9 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleNoCallExample.lean @@ -0,0 +1,62 @@ +import SolidCore.Refinement.Solar.AssembleNoCall +import SolidCore.Refinement.Solar.AssembleDynExample +import SolidCore.Refinement.Solar.AssembleCallExample + +/-! +# The call-free check on examples, by evaluation + +* Positive: `AssembleDynExample`'s bytecode (MLOAD at an offset the call data names) passes + `callFree` and has no `0xfa` byte; the checker with STATICCALLs accepts its program under a + certificate that allows calls, and `runs_shape_of_checkCB_callFree` gives its per-run theorem with + no hypothesis on the runner; `CalleesRun` holds at every gas and call. +* Negative: `AssembleCallExample`'s bytecode (a STATICCALL to code) fails `callFree` and + `noFaByte`, and so does `AssembleDynExample`'s with its MLOAD byte replaced by STATICCALL. +-/ + +namespace SolidCore.Refinement.Solar.AssembleNoCallExample + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Final +open SolidCore.Refinement.Solar SolidCore.Refinement.Solar.AssembleCut +open SolidCore.Refinement.Solar.AssembleNoCall SolidCore.Refinement.Solar.RunOracle SolidCore.Refinement.Witness + +theorem dyn_callFree : callFree AssembleDynExample.code = true := by decide +kernel + +theorem dyn_noFaByte : noFaByte AssembleDynExample.code = true := by decide +kernel + +/-- The checker with STATICCALLs accepts the call-free program under a certificate that allows +calls. -/ +theorem dyn_checkCB : checkCB AssembleDynExample.prog AssembleDynExample.code + { AssembleDynExample.cert with calls := true } AssembleDynExample.maxs = true := by + decide +kernel + +/-- Its per-run theorem with no runner hypothesis. -/ +theorem dyn_runs : ∀ gas, gas < 2 ^ 256 → ∀ call, True → ∃ o : Oracle, + (CertOk { AssembleDynExample.cert with calls := true } o ∧ ∃ W : World, W.Open ∧ CallsAgree o W) ∧ + Within (evmirSem o) (ethLibWith gas) AssembleDynExample.prog AssembleDynExample.code (· = call) := + runs_shape_of_checkCB_callFree dyn_checkCB dyn_callFree (fun _ => True) + +theorem dyn_calleesRun (gas : Nat) (call : Call) : + AssembleCallSeg.CalleesRun gas AssembleDynExample.code call := + calleesRun_of_noFaByte dyn_noFaByte gas call + +/-- STATICCALL (0xfa) in place of MLOAD. -/ +def dynStatic : ByteArray := ⟨#[0x5f, 0x35, 0xfa, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3]⟩ + +theorem dynStatic_not_callFree : callFree dynStatic = false := by decide +kernel + +/-- 0xfa only as a PUSH1 immediate: call-free, though not free of the byte. -/ +def dynPushFa : ByteArray := ⟨#[0x60, 0xfa, 0x50, 0x5f, 0x35, 0x51, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3]⟩ + +theorem dynPushFa_callFree : callFree dynPushFa = true := by decide +kernel + +theorem dynPushFa_not_noFaByte : noFaByte dynPushFa = false := by decide +kernel + +theorem call_not_callFree : callFree AssembleCallExample.code = false := by decide +kernel + +theorem call_not_noFaByte : noFaByte AssembleCallExample.code = false := by decide +kernel + +/-- info: 'SolidCore.Refinement.Solar.AssembleNoCallExample.dyn_runs' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms dyn_runs + +end SolidCore.Refinement.Solar.AssembleNoCallExample diff --git a/SolidCore/Refinement/Solar/AssembleRevert.lean b/SolidCore/Refinement/Solar/AssembleRevert.lean new file mode 100644 index 00000000..ae083374 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleRevert.lean @@ -0,0 +1,222 @@ +import SolidCore.Refinement.Solar.EthLibErrLow +import SolidCore.Refinement.Solar.AssembleLoopWithin + +/-! +# EVM IR to bytecode with the revert data related + +`Final.Within` lets every failure of the bytecode stand for itself: a run that fails rolls back and +logs nothing, and nothing relates its output to the EVM IR's. That admits a bytecode that reverts +with other data than the program, or reverts where the program does not. `WithinR` keeps the +weaker disjunct only for an exceptional halt (`HaltsExceptionally`: the run ends with an error that +is no REVERT, such as out of gas): every other result of the bytecode, a run that reverts among +them, is the EVM IR's result, so its revert data are the program's, byte for byte, and its storage +is the call's. + +* `processMessage_frame`: a message to code that is no precompile ran its frame, and the message + ends with that frame's error and output (`rollbackOnError` keeps them). +* `withinR_of_checkL`: for every program and code the checker of code with loops accepts, at every + gas, `WithinR`. A run that reverts is transferred to the run with the checker's reserve of gas by + `RevertErr.SpecG.lowR`, which rests on `RevertErr.step_good` (no step throws a revert, and only + REVERT ends a frame with it). +* `WithinR.within`: `WithinR` gives `Final.Within`. +-/ + +namespace SolidCore.Refinement.Solar.AssembleLoop + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open EthLib.Execution.State +open SolarTV + +theorem error_rollbackOnError (snap : TransactionState) (e : Evm .fusaka Nat) : + (rollbackOnError snap e).error = e.error := by + unfold rollbackOnError; split <;> rfl + +theorem output_rollbackOnError (snap : TransactionState) (e : Evm .fusaka Nat) : + (rollbackOnError snap e).output = e.output := by + unfold rollbackOnError; split <;> rfl + +/-- A message to code that is no precompile ran its frame, from the state or from the state after +the move of the value, and ends with the error and the output of that frame. -/ +theorem processMessage_frame {message : Message .fusaka} + (hpre : precompileAddress .fusaka message = none) {st : TransactionState} {ss : Substate} {evm} + (hr : processMessage (Meter := Nat) .fusaka message st ss = .ok evm) : + ∃ (st' : TransactionState) (ss' : Substate) (runChild : MessageRunner .fusaka Nat message.gas) + (within : GasMeter.gasHeld (startFrame message st' ss' message.gas).gas ≤ message.gas) + (fr : Evm .fusaka Nat), + (¬ (message.shouldTransferValue = true ∧ message.value ≠ 0) → st' = st ∧ ss' = ss) ∧ + ((message.shouldTransferValue = true ∧ message.value ≠ 0) → + st.moveEther .fusaka message.caller message.currentTarget message.value = .ok st' ∧ + ss' = { ss with logs := (pushTransferLog .fusaka ss.logs message.caller message.currentTarget + message.value) }) ∧ + runFrame (step .fusaka) (step_decreases .fusaka) message.gas runChild + (startFrame message st' ss' message.gas) within = .ok fr ∧ + evm.1.error = fr.error ∧ evm.1.output = fr.output := by + rw [processMessage] at hr + have hss : startState .fusaka message st = st := by + simp [startState, show ¬ (Fork.fusaka < Fork.paris) by decide] + simp only [hss, hpre] at hr + by_cases htr : message.shouldTransferValue = true ∧ message.value ≠ 0 + · simp only [htr, ne_eq, not_false_eq_true, and_self, ↓reduceIte] at hr + cases hm : st.moveEther .fusaka message.caller message.currentTarget message.value with + | error e => simp [hm, Except.mapError, bind, Except.bind, Except.map] at hr + | ok st' => + simp only [hm, Except.mapError, bind, Except.bind, pure, Except.pure] at hr + split at hr + · simp [throw, throwThe, MonadExceptOf.throw, Except.map] at hr + · rename_i after hrf + simp only [Except.map, Except.ok.injEq] at hr + subst hr + simp only [htr.1, htr.2, not_false_eq_true, and_self, ↓reduceIte] at hrf + exact ⟨st', _, _, _, _, fun h => absurd htr h, fun _ => ⟨rfl, rfl⟩, hrf, + error_rollbackOnError _ _, output_rollbackOnError _ _⟩ + · simp only [htr, ↓reduceIte, bind, Except.bind, pure, Except.pure] at hr + split at hr + · simp [throw, throwThe, MonadExceptOf.throw, Except.map] at hr + · rename_i after hrf + simp only [Except.map, Except.ok.injEq] at hr + subst hr + simp only [htr, ↓reduceIte] at hrf + exact ⟨st, ss, _, _, _, fun _ => ⟨rfl, rfl⟩, fun h => absurd h htr, hrf, + error_rollbackOnError _ _, output_rollbackOnError _ _⟩ + +open SolidCore.Refinement.Final + +/-- The run of `code` on `call` with `gas` gas halts exceptionally: it ends with an error that is +no REVERT (out of gas, a stack error, an invalid jump, ...). -/ +def HaltsExceptionally (gas : Nat) (code : ByteArray) (call : SolarTV.Call) : Prop := + ∃ evm, processMessage (Meter := Nat) .fusaka (Final.Target.messageWith gas code call) + (Refinement.Target.preState code call) Substate.empty = .ok evm ∧ + ∃ e, e ≠ .revert ∧ evm.1.error = some e + +/-- **Refinement that relates reverts**: every result of `code` with `gas` gas on the scope is +the result of `p`, or the run halted exceptionally (`HaltsExceptionally`) and failed, leaving the +storage and logging nothing. A run that succeeds or reverts gives `p`'s result: the same output +(the revert data of a revert), the same logs and the same storage. -/ +def WithinR (A : Sem) (gas : Nat) (p : A.Prog) (code : ByteArray) (scope : SolarTV.Call → Prop) : + Prop := + ∀ call, scope call → ∀ obs, Final.Target.runWith gas code call = some obs → + A.run p call = some obs ∨ + (HaltsExceptionally gas code call ∧ obs.success = false ∧ + obs.storage = slotValue call.storage ∧ obs.logs = []) + +/-- `WithinR` is `Within` with the failures that may stand for themselves narrowed to exceptional +halts. -/ +theorem WithinR.within {A : Sem} {gas : Nat} {p : A.Prog} {code : ByteArray} + {scope : SolarTV.Call → Prop} (h : WithinR A gas p code scope) : + Within A (ethLibWith gas) p code scope := by + intro call hc obs hrun + rcases h call hc obs hrun with h | ⟨-, hs, hst, hl⟩ + · exact Or.inl h + · exact Or.inr ⟨hs, hst, hl⟩ + +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Evm.Wide + SolidCore.Refinement.Evm.Symex in +/-- **EVM IR to bytecode at every gas, for code with loops, with the revert data related.** For +every program and code the checker of code with loops accepts, under every oracle that +`within_of_checkL` admits, at every gas: every result the bytecode gives on a call is the result +of SolarTV's EVM IR semantics (a run that reverts too, with its revert data), or the run halted +exceptionally and failed with the storage kept and no log. -/ +theorem withinR_of_checkL {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (hc : checkL p code c mx = true) (o : SolarTV.Machine.Oracle) (ho : c.env = true → OracleOk o) + (scope : SolarTV.Call → Prop) (gas : Nat) + (he : c.reads = true → EnvOk o := by intro h; exact absurd h (by decide)) : + WithinR (SolarTV.evmirSem o) gas p code scope := by + intro call hcall obs hrun + have hrun0 := hrun + unfold Target.runWith Target.runMsg at hrun + split at hrun + · cases hrun + rename_i evm hev hpm + simp only [Option.some.injEq] at hrun + by_cases hex : ∃ e, e ≠ EvmError.revert ∧ evm.error = some e + · obtain ⟨e, hne, he'⟩ := hex + have hs : obs.success = false := by rw [← hrun]; simp [he'] + exact Or.inr ⟨⟨⟨evm, hev⟩, hpm, e, hne, he'⟩, hs, Target.runWith_failure hrun0 hs⟩ + left + rcases herrc : evm.error with _ | e + · rcases within_of_checkL hc o ho scope gas he call hcall obs hrun0 with h | ⟨hs, -⟩ + · exact h + · rw [← hrun] at hs; simp [herrc] at hs + have hrev : e = .revert := by + by_contra hne + exact hex ⟨e, hne, herrc⟩ + subst hrev + subst hrun + obtain ⟨G, hseg, hneed0⟩ := globL_of_checkL hc + obtain ⟨st', ss', runChild, within, fr, hcases, hmove, hrf, herrfr, houtfr⟩ := + processMessage_frame (message := Final.Target.messageWith gas code call) (evm := ⟨evm, hev⟩) + (precompileAddress_message code call) hpm + simp only at herrfr houtfr + have hfrrev : fr.error = some .revert := by rw [← herrfr, herrc] + set msg := Final.Target.messageWith gas code call with hmsg + have hcode : msg.code = code := rfl + have R := rel_start code call gas ss' (fun h => (hcases h).1) (fun h => (hmove h).1) + generalize hW : p.blocks.length + 2 = W + generalize hn : 2 * (W * gas) + W + p.blocks.length + 1 = n + generalize hK : 22100 * (n * bmax c) + memoryGasCost c.top = K + have hm0 : memoryGasCost (ByteArray.empty).size = 0 := by decide + have E0 : EntryL c code call (lowerFrom p c 0 (p.blocks.drop 0)) (n * bmax c) 0 + (SolarTV.Machine.State.initial call) .empty (gas + K) := + ⟨by rw [List.drop_zero]; exact hseg, by rw [hm0]; omega, by simp, memRel_initial⟩ + have hsim := run_simL (msg := msg) (ss0 := ss') G rfl (by simp [msg, Final.Target.messageWith, + Target.message]) rfl rfl rfl ho rfl rfl he n 0 [] [] _ 0 .empty (gas + K) st' ss' (Nat.zero_le _) + (fun _ => ⟨by simp [hneed0], by simp⟩) (SR.nil c _) E0 R + have hl : At code msg 0 [] .empty gas st' ss' .empty (startFrame msg st' ss' msg.gas) := + ⟨by simp [startFrame, hcode], by simp [startFrame, hcode], rfl, rfl, rfl, rfl, rfl, rfl, rfl, + rfl, rfl, rfl, rfl⟩ + have hp := hl.addGas K + have hstart : (startFrame msg st' ss' msg.gas).error ≠ some .revert := by + rw [hl.2.2.2.2.2.2.2.2.1]; simp + have hfork : Fork.byzantium ≤ Fork.fusaka := by decide + cases hit : SolarTV.Machine.iterate (SolarTV.EVM.Program.block o call p) n + (0, [], SolarTV.Machine.State.initial call) with + | none => + exfalso + obtain ⟨z, hz, hmeas⟩ := hsim.2 hit _ hp + obtain ⟨m, -, rfl, -⟩ := RevertErr.reaches_lowR hfork hz K _ rfl hstart within hrf hfrrev + have h1 : W * K ≤ W * (m.gas + K) := Nat.mul_le_mul_left _ (by simp) + simp only [gas_addGas] at hmeas h1 + unfold meas at hmeas + rw [hW] at hmeas + have h2 : W * (gas + K) = W * gas + W * K := Nat.mul_add _ _ _ + split at hmeas <;> omega + | some r => + rcases r with ⟨halt, sF⟩ + have hres : (SolarTV.evmirSem o).run p call = some (SolarTV.Machine.observe call sF halt) := by + change (SolarTV.EVM.Program.layer.result o p call).map _ = _ + rw [SolarTV.EVM.Program.layer.result_of_ends ⟨n, hit⟩] + rfl + rw [hres] + obtain ⟨ssF, ⟨herr, hout, -, -⟩, -⟩ := + RevertErr.SpecG.lowR hfork (hsim.1 _ hit) hp hstart within hrf hfrrev + have herr' : fr.error = errorOf (SolarTV.Machine.observe call sF halt) := herr + have hout' : fr.output.toList.map (·.toNat) = (SolarTV.Machine.observe call sF halt).output := + hout + have hfail : (SolarTV.Machine.observe call sF halt).success = false → + (SolarTV.Machine.observe call sF halt).logs = [] ∧ + (SolarTV.Machine.observe call sF halt).storage = slotValue call.storage := by + cases halt <;> simp [SolarTV.Machine.observe] + clear herr hout hres hsim hit + generalize SolarTV.Machine.observe call sF halt = X at * + have hsucc : fr.error.isNone = X.success := by + rw [herr']; cases hX : X.success <;> simp [errorOf, hX] + rw [hfrrev] at hsucc + simp only [Option.isNone_some] at hsucc + obtain ⟨hlogs, hst⟩ := hfail hsucc.symm + congr 1 + cases X with + | mk success output logs storage => + simp only at hsucc hout' hlogs hst ⊢ + subst hsucc hlogs hst + rw [SolarTV.Observable.mk.injEq] + refine ⟨by simp [herrc], ?_, by simp [herrc], by funext slot; simp [herrc]⟩ + rw [houtfr] + exact hout'.symm + +/-- +info: 'SolidCore.Refinement.Solar.AssembleLoop.withinR_of_checkL' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms withinR_of_checkL + +end SolidCore.Refinement.Solar.AssembleLoop diff --git a/SolidCore/Refinement/Solar/AssembleRevertCall.lean b/SolidCore/Refinement/Solar/AssembleRevertCall.lean new file mode 100644 index 00000000..37f1a1ff --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleRevertCall.lean @@ -0,0 +1,1366 @@ +import SolidCore.Refinement.Solar.AssembleRevertCut +import SolidCore.Refinement.Solar.AssembleCallSeg + +/-! +# Code with STATICCALLs, with the revert data related + +`AssembleCallSeg.segS` reads each segment of code with STATICCALLs back from a run that succeeds and +rules REVERT out (`AssembleDyn.revert_false`). As `AssembleRevertCut` does for the checker with GAS, +this file reads them back from a run that ends with no error or reverts (`AssembleRevertCut.OkR`): +the STATICCALL at the frame's gas (`staticcall_backR`, `staticcall_cutR`) rules out a failing call +step by `error_ne_none_of_stepFailsR` (a step that fails at an opcode that is no REVERT ends no run +with the revert error, `RevertErr.step_good`), and REVERT shows the program's revert with its data. + +* `segSR`, `advances_checkCSR`, `within_of_advancesQR`, `runs_of_checkCBR`: the per-run theorem + for every program `AssembleCut.checkCB` accepts, with `AssembleLoop.WithinR`, under the named + hypotheses `AssembleCallSeg.StaticRunner` and `CalleesRunE`: `AssembleCallSeg.CalleesRun` for + the runs that end with no error or revert, stated of the frame the message runs. +-/ + +namespace SolidCore.Refinement.Solar.AssembleRevertCall + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Witness SolidCore.Refinement.Final +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.RunOracle +open SolidCore.Refinement.Solar.AssembleCut SolidCore.Refinement.Solar.AssembleEffects +open SolidCore.Refinement.Solar.AssembleLoop SolidCore.Refinement.Solar.AssembleRun +open SolidCore.Refinement.Solar.AssembleRunLoop +open SolidCore.Refinement.Solar.AssembleCall SolidCore.Refinement.Solar.AssembleCallWorld +open SolidCore.Refinement.Solar.AssembleCallCut SolidCore.Refinement.Solar.AssembleDyn +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide +open SolidCore.Refinement.Solar.AssembleCallSeg SolidCore.Refinement.Solar.AssembleRevertCut + +/-- **A step that fails at an opcode that is no REVERT ends no run that succeeds or reverts.** -/ +theorem error_ne_none_of_stepFailsR {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {low s : Evm .fusaka Nat} (running : low.running = true) (fails : StepFails (step .fusaka low)) + {within : GasMeter.gasHeld low.gas ≤ bound} + (hs : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild low within = .ok s) + (hok : OkR s) (herr : low.error = none) {op : Op} + (hop : ∃ h : low.pc < low.code.size, Op.ofByte .fusaka low.code[low.pc] = some op) + (hne : op ≠ .revert) : False := by + have good := RevertErr.step_good (fork := .fusaka) low + rcases fails with ⟨e, he⟩ | ⟨b, hb, hbr, hbe⟩ + · have hne' := good.1 e he + cases ab : e.aborts + · rw [runFrame_of_step_eq_error running he ab] at hs + cases hs + rcases hok with h | h + · simp [exceptionalHalt] at h + · simp only [exceptionalHalt, Option.some.injEq] at h + exact hne' h + · rw [runFrame_of_step_eq_abort running he ab] at hs + cases hs + · rw [runFrame_of_step_eq_next running hb, runFrame_of_running_eq_false hbr] at hs + cases hs + rcases hok with h | h + · exact hbe h + · rcases good.2 _ hb h with h' | ⟨hlt, hop'⟩ + · rw [herr] at h'; cases h' + · obtain ⟨hlt2, hop2⟩ := hop + rw [hop2] at hop' + exact hne (Option.some.inj hop') + +section Dyn + +variable {rd : ByteArray} + +/-- **STATICCALL in a run that succeeds**, at the frame's own gas: the state held the callee's code +(and its delegate's, `Routes`), the gas paid for the access, the route and the growth of memory, +and the run goes on from the frame after the callee's frame ended. -/ +theorem staticcall_backR {code : ByteArray} {msg : Message .fusaka} {pc g : Nat} {M : ByteArray} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray} + {asked addr inOff inSize outOff outSize : U256} {rest : List U256} + {evm : Evm .fusaka Nat} + (hat : At code msg pc (asked :: addr :: inOff :: inSize :: outOff :: outSize :: rest) M g st ss + rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0xfa) (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} (meets : Meets P runChild) + (within : GasMeter.gasHeld evm.gas ≤ bound) {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + ∃ (calleeCode : ByteArray) (route : Route), + st.getCode (st.getAccount (toAddressMasked addr)).codeHash = .ok calleeCode ∧ + Routes .fusaka st calleeCode route ∧ + (if decide (toAddressMasked addr ∉ ss.accessedAddresses) then 2600 else 100) + + routeCost .fusaka (ss.accessedAddresses.insert (toAddressMasked addr)) route + + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost ≤ g ∧ + ∃ (caller : Evm .fusaka Nat) (m : Message .fusaka) (child after : Evm .fusaka Nat) + (within' : GasMeter.gasHeld after.gas ≤ bound) (g' : Nat), + P caller m child ∧ child.gas ≤ m.gas ∧ + caller.state = (routeState (st.recordAccountRead (toAddressMasked addr)) route).recordAccountRead + msg.currentTarget ∧ + caller.substate = routeSub { ss with + accessedAddresses := ss.accessedAddresses.insert (toAddressMasked addr) } route ∧ + m.isStatic = true ∧ m.value = 0 ∧ m.code = routeCode calleeCode route ∧ + m.currentTarget = toAddressMasked addr ∧ m.target = some (toAddressMasked addr) ∧ + m.data = memoryReadBytes (memoryExtend M + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).expandBy) inOff.toNat + inSize.toNat ∧ + m.codeAddress = some (routeAddr (toAddressMasked addr) route) ∧ + m.disablePrecompiles = route.isSome ∧ + m.gas = (messageCallGas .fusaka 0 asked.toNat g + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost + ((if decide (toAddressMasked addr ∉ ss.accessedAddresses) then 2600 else 100) + + routeCost .fusaka (ss.accessedAddresses.insert (toAddressMasked addr)) route)).subCall ∧ + g' + (if decide (toAddressMasked addr ∉ ss.accessedAddresses) then 2600 else 100) + + routeCost .fusaka (ss.accessedAddresses.insert (toAddressMasked addr)) route + + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost ≤ g ∧ + At code msg (pc + 1) ((if child.error.isNone then 1 else 0) :: rest) + (memoryWrite (memoryExtend M + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).expandBy) + outOff.toNat (child.output.extract 0 (min outSize.toNat child.output.size))) + g' (incorporateChild .fusaka caller child).state + (incorporateChild .fusaka caller child).substate child.output after ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild after within' = .ok fin := by + have hat0 := hat + have herr0 : evm.error = none := hat.2.2.2.2.2.2.2.2.1 + obtain ⟨hc, hv, hm, hpc, hst, hmem, hgas, hrunning, -, -, hst', hss, -⟩ := hat0 + have hlt' : evm.pc < evm.code.size := by rw [hc, hpc]; exact hlt + have decoded : Op.ofByte .fusaka (evm.code[evm.pc]'hlt') = some .staticcall := by + have he : evm.code[evm.pc]'hlt' = code[pc]'hlt := by subst hc hpc; rfl + rw [he, hbyte] + exact ofByte_of_decode rfl (by decide) + have hstep : step .fusaka evm = callStep .staticcall evm := + step_of_messageInstruction hlt' decoded instruction_staticcall + (messageInstruction_staticcall (by decide)) + have hnf : ¬ StepFails (callStep .staticcall evm) := fun hf => + error_ne_none_of_stepFailsR hrunning (by rw [hstep]; exact hf) hrun hok herr0 ⟨hlt', decoded⟩ (by decide) + obtain ⟨calleeCode, route, hcode, hroute⟩ := staticcall_routes_of_ok hst hnf + rw [hst'] at hcode hroute + refine ⟨calleeCode, route, hcode, hroute, ?_⟩ + have hcost := callBaseCost_of_berlin (fork := .fusaka) (by decide) (by decide) + (decide (toAddressMasked addr ∉ ss.accessedAddresses)) + generalize hcold : decide (toAddressMasked addr ∉ ss.accessedAddresses) = cold at hcost + generalize hdc : routeCost .fusaka (ss.accessedAddresses.insert (toAddressMasked addr)) route = dc + by_cases hg : (if cold then 2600 else 100) + dc + + (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost ≤ g + · refine ⟨hg, ?_⟩ + have H := (callKindRoute (fork := .fusaka) (kind := .staticcall) (callee := P) + (asked := asked) (rest := rest) (returnData := rd) (gas := g) (memory := M) (substate := ss) + (inputStart := inOff) (inputSize := inSize) (outputStart := outOff) (outputSize := outSize) + (by decide) hlt hbyte (ofByte_of_decode rfl (by decide)) instruction_staticcall + (messageInstruction_staticcall (by decide)) hcode hroute hdepth + (by rw [← hcold] at hcost; rw [hcost, hcold, hdc]; exact hg)).toUnder + obtain ⟨after, hr, hq⟩ := H bound runChild meets evm hat within + have within' := Nat.le_trans (hr.gasHeld_le StepBy.gasHeld_le) within + have hrun' := hrun + rw [runFrame_eq_of_reaches StepBy.gasHeld_le StepBy.runFrame_eq hr within] at hrun' + rcases hq with ⟨caller, m, child, ⟨s1, s2, m1, -, -, mt, mtg, mca, mc, mdp, md, mv, -, -, ms, -, -⟩, + hk, hcg, hat'⟩ | aborted + · rw [← hcold] at hcost + rw [hcost, hdc, hcold] at m1 hat' + obtain ⟨hc1, hc2⟩ := staticcall_gas (asked := asked.toNat) + (memc := (extendMemory M.size [(inOff, inSize), (outOff, outSize)]).cost) + (extra := (if cold then 2600 else 100) + dc) (g := g) (by omega) + refine ⟨caller, m, child, after, within', _, hk, hcg, s1, s2, by simpa using ms, + by simpa using mv, mc, by simpa using mt, by simpa using mtg, md, mca, mdp, m1, ?_, hat', hrun'⟩ + rw [m1] at hcg + rw [hc1] + omega + · obtain ⟨e, he, -⟩ := runFrame_of_abortsBy meets.aborts aborted within' + rw [he] at hrun' + cases hrun' + · exfalso + have fails : StepFails (step .fusaka evm) := by + rw [hstep] + refine callStep_fails_of_routes (route := route) (by decide) (a := addr) (i := inOff) + (isz := inSize) (o := outOff) (osz := outSize) (g := asked) (rest := rest) + (by rw [hst]; rfl) (by rw [hst']; exact hcode) (by rw [hst']; exact hroute) ?_ + rw [callBaseCost_of_berlin (by decide) (by decide), hgas, hmem, hss, hcold, hdc] + omega + exact error_ne_none_of_stepFailsR hrunning fails hrun hok herr0 ⟨hlt', decoded⟩ (by decide) + +/-- **A STATICCALL to code, read back from a run that succeeds**, at the frame's own gas: the run's +table grows by the callee frame's flag and output, and under the oracle of every extension of it, +SolarTV's STATICCALL pushes that flag and leaves that return data, and the frame after it relates to +SolarTV's state as a block entry does (memory, storage, logs, the budget of memory and gas). -/ +theorem staticcall_cutR {code : ByteArray} {msg : Message .fusaka} {call : Call} {pc g G : Nat} + {M : ByteArray} {st : State.TransactionState} {ss ss0 : Substate} {rd : ByteArray} + {asked addr inOff inSize outOff outSize : U256} {Tr : List U256} + {s : State} {evm : Evm .fusaka Nat} + (codes : SolidCore.Solidity.Shared.Account.BytesMap) (T : RunTable) + (hm : MemRel s.memory M) (R : Rel msg ss0 st ss s) (hb : MemBudget G M g) (hG : G < 2 ^ 300) + (hat : At code msg pc (asked :: addr :: inOff :: inSize :: outOff :: outSize :: Tr) M g st ss + rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0xfa) + (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} (meets : Meets P runChild) + (hPok : ∀ c m ch, P c m ch → StaticOk c m ch) + (within : GasMeter.gasHeld evm.gas ≤ bound) {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) + (hto : toCode .staticcall (addr.toNat % 2 ^ 160) 0 = true ∨ + PreOk P st ss M g asked addr inOff inSize outOff outSize) + (hoks : T.oks.length = (machineCalls s.world).length) + (houts : T.outs.length = (machineCalls s.world).length) + (hgr : gasReads s.world ≤ T.gases.length) : + ∃ (ok : Bool) (out : ByteArray) (s' : State) (M' : ByteArray) (g' : Nat) + (st' : State.TransactionState) (ss' : Substate) (m : Evm .fusaka Nat) + (within' : GasMeter.gasHeld m.gas ≤ bound), + (∀ T'', ({ T with oks := T.oks ++ [ok], outs := T.outs ++ [out] } : RunTable).Le T'' → + Effect.apply (OS codes T'') call (.call .staticcall) + [asked, addr, inOff, inSize, outOff, outSize] s = + some (some (if ok then 1 else 0), s') ∧ RdRel (OS codes T'') s'.world out) ∧ + (∃ ev, s'.world = s.world ++ [ev] ∧ sent [ev] = 1 ∧ gasReads [ev] = 0 ∧ + (machineCalls [ev]).length = 1) ∧ + MemRel s'.memory M' ∧ Rel msg ss0 st' ss' s' ∧ MemBudget G M' g' ∧ g' ≤ g ∧ + At code msg (pc + 1) ((if ok then 1 else 0) :: Tr) M' g' st' ss' out m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + obtain ⟨calleeCode, route, hcode, hroute, hg, caller, mm, child, after, within', g', hPP, -, hcs, + hcsub, hms, hmv, hmc, hmt, htg, hmd, hmca, hmdp, hmgas, hg', hat', hrun'⟩ := + staticcall_backR hat hlt hbyte hdepth meets within hrun hok + have hP := hPok _ _ _ hPP + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + obtain ⟨hb1, hb2, hbud, hfit⟩ := budget_grow2 (pre := (if decide (toAddressMasked addr ∉ + ss.accessedAddresses) then 2600 else 100) + + routeCost .fusaka (ss.accessedAddresses.insert (toAddressMasked addr)) route) hmod hb hG + (by omega) + -- The table with the call's flag and output. + let T1 : RunTable := { T with oks := T.oks ++ [child.error.isNone], outs := T.outs ++ [child.output] } + have hle1 : T.Le T1 := ⟨List.prefix_append _ _, List.prefix_append _ _, List.prefix_refl _, + List.prefix_refl _, List.prefix_refl _⟩ + let ev : Event := .call .staticcall [asked, addr] + (((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat outSize.toNat).read + inOff.toNat inSize.toNat) s.storage s.transient + have hev : ∀ T'', T1.Le T'' → + callFlag (OS codes T'') (s.world ++ [ev]) = (if child.error.isNone then 1 else 0) ∧ + RdRel (OS codes T'') (s.world ++ [ev]) child.output := by + intro T'' hle + have hok' : T''.oks.getD (machineCalls s.world).length false = child.error.isNone := by + rw [getD_of_prefix hle.1 (by simp [T1, hoks])] + simp [T1, hoks] + have hout' : T''.outs.getD (machineCalls s.world).length .empty = child.output := by + rw [getD_of_prefix hle.2.1 (by simp [T1, houts])] + simp [T1, houts] + have hresp : tabResp T''.oks T''.outs (machineCalls s.world).length .staticcall + (addr.toNat % 2 ^ 160) 0 + ((((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat outSize.toNat).read + inOff.toNat inSize.toNat).map BitVec.toNat) = (child.error.isNone, child.output) := by + rcases hto with hto | ⟨h1, hag, hER, hnd, hg3⟩ + · simp only [tabResp, hto, ite_true] + rw [hok', hout'] + · -- ECRECOVER: the source's answer, which the callee frame matches. + have htc : toCode .staticcall (addr.toNat % 2 ^ 160) 0 = false := by rw [h1]; decide + simp only [tabResp, htc, Bool.false_eq_true, ite_false] + have hrn : route = none := by + rcases route with _ | ⟨d, c'⟩ + · rfl + · have := hroute.2.1 + rw [hnd _ hcode] at this + cases this + subst hrn + have hmsg : AssembleCallPre.EcrecoverMsg mm := by + refine ⟨by rw [htg]; rfl, ?_, by simpa using hmdp, hmv, ?_⟩ + · have h1' : (toAddressMasked addr).toU256.toNat = 1 := by + rw [toNat_toU256_masked]; exact h1 + simp only [precompileAddress, hmca, routeAddr, h1'] + decide + · rw [hmgas] + simpa [routeCost] using hg3 + have hin : (((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat + outSize.toNat).read inOff.toNat inSize.toNat).map BitVec.toNat = + SolidCore.Solidity.Source.byteArrayToBytes mm.data := by + rw [hmd, ← read_eq2 hm] + rfl + rw [h1, hin] + exact AssembleCallPre.ecrecover_answer hag (hER _ _ _ hPP) hmsg + obtain ⟨hf, hr⟩ := OS_ans codes T'' s.world asked addr + (((s.memory.expand inOff.toNat inSize.toNat).expand outOff.toNat outSize.toNat).read + inOff.toNat inSize.toNat) s.storage s.transient _ _ hresp hP.2.2 + refine ⟨hf, ?_⟩ + have := hr [] rfl + rw [List.append_nil] at this + exact this + -- SolarTV's STATICCALL under the table's oracle. + obtain ⟨s', happ, hsto, htr, hrd, hw, hmem'⟩ := staticcall_effectW (o := OS codes T1) (call := call) + (gas := asked) (addr := addr) (child := child) hm hb1 hb2 (hev T1 (RunTable.Le.refl _)).1 + (hev T1 (RunTable.Le.refl _)).2 + -- Under every extension it runs the same. + have hsame : ∀ T'', T1.Le T'' → + Effect.apply (OS codes T'') call (.call .staticcall) + [asked, addr, inOff, inSize, outOff, outSize] s = + Effect.apply (OS codes T1) call (.call .staticcall) + [asked, addr, inOff, inSize, outOff, outSize] s := by + intro T'' hle + have hmc1 : (machineCalls (s.world ++ [ev])).length = (machineCalls s.world).length + 1 := by + rw [machineCalls_static] + simp + obtain ⟨henv, hres⟩ := OS_le (codes := codes) hle (w := s.world ++ [ev]) + (by simp [T1, hmc1, hoks]) (by simp [T1, hmc1, houts]) (by simp [T1]) (by simp [T1]) + (by simp [T1, ev]; omega) + have hflag : callFlag (OS codes T'') (s.world ++ [ev]) = callFlag (OS codes T1) (s.world ++ [ev]) := by + simp only [callFlag, hres] + have hbyte : returndataByte (OS codes T'') (s.world ++ [ev]) = + returndataByte (OS codes T1) (s.world ++ [ev]) := by + funext i + simp only [returndataByte] + rw [henv] + simp only [ev] at henv hflag hbyte + simp only [Effect.apply, CallKind.shape, called, returndataSize, hflag, henv, hbyte] + refine ⟨child.error.isNone, child.output, s', _, g', (incorporateChild .fusaka caller child).state, + (incorporateChild .fusaka caller child).substate, after, within', fun T'' hle => ?_, + ⟨ev, hw, by simp [ev], by simp [ev], by simp [ev, machineCalls]⟩, hmem', ?_, ?_, + by omega, ?_, hrun'⟩ + · rw [hsame T'' hle, happ] + refine ⟨by cases child.error.isNone <;> rfl, ?_⟩ + rw [hw] + exact (hev T'' hle).2 + · -- Storage and the account are the caller's; the logs are the frame's, with no log of the callee. + have hso := staticcall_state hcode hroute hP.1 hcs hms hmv hmc hmt htg + refine ⟨fun k => ?_, ?_, ?_⟩ + · rw [(hso msg.currentTarget (List.not_mem_nil)).2.1, hsto] + exact R.storage k + · rw [(hso msg.currentTarget (List.not_mem_nil)).1] + exact R.account + · obtain ⟨L, hL1, hL2⟩ := R.logs + refine ⟨L, ?_, ?_⟩ + · have hlogs : (incorporateChild .fusaka caller child).substate.logs.toList = ss.logs.toList := by + unfold incorporateChild + split + · rename_i hn + have h0 := hP.2.1 hms (by simpa using hn) + rcases route with _ | ⟨d, c'⟩ <;> simp [Array.toList_append, h0, hcsub, routeSub] + · rcases route with _ | ⟨d, c'⟩ <;> simp [hcsub, routeSub] + rw [hlogs, hL1] + · rw [hw, List.filter_append] + simpa [ev, isLogE] using hL2 + · unfold MemBudget + rw [size_memoryWrite_of_fit, size_memoryExtend] + · omega + · intro h + simp only [ByteArray.size_extract] at h ⊢ + have hz : outSize ≠ 0 := by + intro hz + simp [hz] at h + have := hfit hz + rw [size_memoryExtend] + have := Nat.min_le_left outSize.toNat child.output.size + omega + · simpa using hat' + +/-- **RETURNDATASIZE in a run that succeeds**: the frame had the gas for it, and the run goes on +from the frame after it, with the size of its return data pushed. -/ +theorem rds_backR {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {T : List Word} + {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} {rd : ByteArray} + {evm : Evm .fusaka Nat} (hat : At code msg pc T M g st ss rd evm) (hlt : pc < code.size) + (hbyte : code[pc] = 0x3d) (hstack : T.length < STACK_LIMIT) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + 2 ≤ g ∧ ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) (BitVec.ofNat 256 rd.size :: T) M (g - 2) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + by_cases hg : 2 ≤ g + · obtain ⟨m, hr, hm⟩ := returndatasize_rule hlt hbyte hg hstack evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc T M g st ss rd) (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, -, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .returndatasize := by + rw [hbyte] + exact ofByte_of_decode rfl (by decide) + rw [step_of_instruction hlt decoded rfl] + simp [readFrame, chargeGas, GasMeter.charge, hgas, OPCODE_RETURNDATASIZE, BASE, + show g < 2 by omega, bind, Except.bind] + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rcases hok with hok | hok <;> rw [hf.2.1] at hok <;> cases hok + +/-- **RETURNDATACOPY in a run that succeeds**: the range was within the return data, the frame had +the gas for the copy and the growth of memory, and the run goes on from the frame after it. -/ +theorem rdc_backR {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {d off sz : Word} + {T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {rd : ByteArray} {evm : Evm .fusaka Nat} (hat : At code msg pc (d :: off :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x3e) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + off.toNat + sz.toNat ≤ rd.size ∧ + 3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost ≤ g ∧ + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) T + (memoryWrite (memoryExtend M (extendMemory M.size [(d, sz)]).expandBy) + d.toNat (memoryReadBytes rd off.toNat sz.toNat)) + (g - (3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost)) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + have decoded : Op.ofByte .fusaka (0x3e : UInt8) = some .returndatacopy := + ofByte_of_decode rfl (by decide) + by_cases hg : 3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost ≤ g + · by_cases hfit : off.toNat + sz.toNat ≤ rd.size + · obtain ⟨m, hr, hm⟩ := returndatacopy_rule hlt hbyte hfit hg evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hfit, hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc (d :: off :: sz :: T) M g st ss rd) + (Faulted .outOfBoundsRead st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -, -, -, -, -, hrd⟩ := hat' + subst hcode hpc + rw [step_of_instruction hlt (by rw [hbyte]; exact decoded) AssembleCallSeg.instruction_returndatacopy] + have hpaid : GasMeter.charge e.gas (OPCODE_RETURNDATACOPY_BASE + + OPCODE_RETURNDATACOPY_PER_WORD * wordCount sz.toNat + + (extendMemory e.memory.size [(d, sz)]).cost) = .ok (g - (3 + 3 * wordCount sz.toNat + + (extendMemory M.size [(d, sz)]).cost)) := by + rw [hmem, hgas, show OPCODE_RETURNDATACOPY_BASE = 3 from rfl, + show OPCODE_RETURNDATACOPY_PER_WORD = 3 from rfl] + exact charge_nat hg + rw [(returndatacopyStep_eq_error_iff hst hpaid).2 (by rw [hrd]; omega)] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rcases hok with hok | hok <;> rw [hf.2.1] at hok <;> cases hok + · exfalso + have hspec : Spec .fusaka (At code msg pc (d :: off :: sz :: T) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + rw [step_of_instruction hlt (by rw [hbyte]; exact decoded) AssembleCallSeg.instruction_returndatacopy] + have hlt' : g < 3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost := + Nat.lt_of_not_le hg + have hc : GasMeter.charge e.gas (OPCODE_RETURNDATACOPY_BASE + OPCODE_RETURNDATACOPY_PER_WORD * + wordCount sz.toNat + (extendMemory e.memory.size [(d, sz)]).cost) = .error .outOfGas := by + rw [hgas, hmem, show OPCODE_RETURNDATACOPY_BASE = 3 from rfl, + show OPCODE_RETURNDATACOPY_PER_WORD = 3 from rfl] + simp only [GasMeter.charge] + rw [ite_eq_left_of_eq_true _ _ (eq_true hlt')] + rw [returndatacopyStep_oog hst hc] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rcases hok with hok | hok <;> rw [hf.2.1] at hok <;> cases hok + +/-- **RETURNDATACOPY of any range, in a run that succeeds**: with the budget below `2 ^ 300` and an +oracle that answers the frame's return data, SolarTV's copy agrees with EthLib's memory after it, +the budget holds at the gas left, and the run goes on. -/ +theorem rdc_dynR {code : ByteArray} {msg : Message .fusaka} {o : Oracle} {w : List Event} + {pc : Nat} {d off sz : Word} {T : List Word} {M : ByteArray} {g G : Nat} + {st : State.TransactionState} {ss : Substate} {rd : ByteArray} {m0 : SolarTV.Machine.Mem} + (hm : MemRel m0 M) (hb : MemBudget G M g) (hG : G < 2 ^ 300) (hrdr : RdRel o w rd) + {evm : Evm .fusaka Nat} (hat : At code msg pc (d :: off :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x3e) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + off.toNat + sz.toNat ≤ rd.size ∧ + ∃ (M' : ByteArray) (g' : Nat) (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + MemRel (m0.write d.toNat sz.toNat (fun i => returndataByte o w (off.toNat + i))) M' ∧ + MemBudget G M' g' ∧ g' ≤ g ∧ At code msg (pc + 1) T M' g' st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + obtain ⟨hfit0, hg, m, within', hat', hrun'⟩ := rdc_backR hat hlt hbyte within hrun hok + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have hbound : sz = 0 ∨ (d.toNat + sz.toNat + 31) / 32 < 2 ^ 251 := by + by_cases hz : sz = 0 + · exact .inl hz + · exact .inr (words_lt_of_cost (budget_grow hmod hz hb hg).1 hG) + have hfit : sz.toNat ≠ 0 → + d.toNat + sz.toNat ≤ (memoryExtend M (extendMemory M.size [(d, sz)]).expandBy).size := by + intro hz + have hz' : sz ≠ 0 := fun h => hz (by simp [h]) + rw [size_memoryExtend_extendMemory' hmod hz'] + have := le_ceil32 (d.toNat + sz.toNat) + omega + refine ⟨hfit0, _, _, m, within', ?_, ?_, by omega, hat', hrun'⟩ + · have he := memRel_expandW hm hbound + rw [← write_expand] + refine memRel_write he hfit (size_memoryReadBytes hfit0) (fun i hi => ?_) + rw [byteAt_memoryReadBytes hfit0, if_pos hi] + exact (hrdr.2 (off.toNat + i) (by omega)).symm + · refine MemBudget.grow hmod hb hg ?_ + rw [size_memoryWrite_of_fit, size_memoryExtend] + intro h + rw [size_memoryReadBytes hfit0] at h ⊢ + exact hfit h + +end Dyn + +set_option maxRecDepth 8000 in +/-- **`AssembleCut.seg` with STATICCALLs**: the rest of a block from an instruction, read back from +a run that succeeds, under the oracle of the run's table of GAS reads and static calls. -/ +theorem segSR {p : Assemble.Program} {c : Cert} {mx : List Nat} {code : ByteArray} + (G : GlobT p c code) (codes : SolidCore.Solidity.Shared.Account.BytesMap) (hcr : c.creates = false) {call : Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : msg.txEnv = Target.txEnv) + {b : Nat} (hb : b < p.blocks.length) {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {fin : Evm .fusaka Nat} (hok : OkR fin) {G0 : Nat} (hG0 : G0 < 2 ^ 256) + (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} (meets : Meets P runChild) + (hPok : ∀ c m ch, P c m ch → StaticOk c m ch) + (hcal : CalleesOk code msg P bound runChild fin) : + ∀ (n : Nat) (is : List Assemble.Instr) (h : Nat) (known : Known) (ty : List Ty) (k : Nat) + (S Tw : List Word) (s : State) (pc : Nat) (M : ByteArray) (g : Nat) + (st : State.TransactionState) (ss : Substate) (rd : ByteArray) (T : RunTable) (evm : Evm .fusaka Nat) + (within : GasMeter.gasHeld evm.gas ≤ bound), + is.length < n → blockOkC p c mx b h known ty k is = true → h ≤ S.length → + S.length + c.need b ≤ h + maxH mx b → KR known S → SR c ty S Tw → + Seg (bytesOf code) c.offset pc + (lowerInstrs p c b is ++ lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) code.size → + S.length + k ≤ 1000 → M.size ≤ c.top → MemRel s.memory M → Rel msg ss0 st ss s → + At code msg pc Tw M g st ss rd evm → T.gases.length = gasReads s.world → + TabInv T s.world → (∀ T'', T.Le T'' → RdRel (OS codes T'') s.world rd) → + MemBudget G0 M g → + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + ∃ T' r, T.Le T' ∧ + (∀ T'', T'.Le T'' → SolarTV.EVM.Program.exec (OS codes T'') call b is S s = r) ∧ + (∀ res, r = .inl res → PostL call msg.currentTarget ss0 res.2 res.1 fin) ∧ + (∀ y, r = .inr y → (y.1 ≤ p.blocks.length ∧ + (y.1 < p.blocks.length → c.need y.1 ≤ y.2.1.length ∧ y.2.1.length ≤ maxH mx y.1) ∧ + (y.1 = b + 1 ∨ isTarget p c y.1 = true)) ∧ + ∃ (after : Evm .fusaka Nat) (within' : GasMeter.gasHeld after.gas ≤ bound), + EntC p c mx code msg ss0 y after ∧ T'.gases.length = gasReads y.2.2.world ∧ + TabInv T' y.2.2.world ∧ + (∀ T'', T'.Le T'' → RdRel (OS codes T'') y.2.2.world after.returnData) ∧ after.gas ≤ g ∧ + memoryGasCost after.memory.size + after.gas ≤ G0 ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild after within' = .ok fin) + | 0, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, hn, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ => absurd hn (Nat.not_lt_zero _) + | n + 1, is, h, known, ty, k, S, Tw, s, pc, M, g, st, ss, rd, T, evm, within, hn, hokC, hh, hu, hk, + hR, hseg, hstk, htop, hmem, R, hat, hTg, hs0, hrdr, hB, hrun => by + have hge : evm.gas = g := hat.2.2.2.2.2.2.1 + -- The segment with gas to spare for it alone: `K` more than the frame holds. + generalize hK : 22100 * k + memoryGasCost c.top = K + have hp := hat.addGas K + have I : InvL c code call (lowerInstrs p c b is ++ lowerFrom p c (b + 1) + (p.blocks.drop (b + 1))) k 0 pc S s M (g + K) := + ⟨hseg, hstk, by simp only [Nat.add_zero]; omega, htop, hmem⟩ + have hsim := exec_simC (mx := mx) G (o := OS codes T) hdata hvalue hstatic hself hcaller + (OS_ok codes c T).1 hbenv htx (OS_ok codes c T).2 b hb 0 (G0 + K) rd is h known ty S Tw k s pc M + (g + K) st ss hokC hh hu hk hR I R (by unfold MemBudget at *; omega) + have hcnt := (execC_agree (Agree.refl (OS codes T) (gasReads s.world) (sent s.world)) call b is S s + le_rfl le_rfl).2 + have hex : ∀ T'', T.Le T'' → SolarTV.EVM.Program.exec (OS codes T'') call b is S s = + match execC (OS codes T) call b is S s with + | .done r => r + | .cut i rest S' s' => SolarTV.EVM.Program.exec (OS codes T'') call b (i :: rest) S' s' := + fun T'' hle => exec_OS codes hle (by omega) hs0 + generalize hr : execC (OS codes T) call b is S s = r at hsim hcnt hex + cases r with + | done r => + refine ⟨T, r, RunTable.Le.refl T, fun T'' hle => hex T'' hle, fun res hres => ?_, + fun y hy => ?_⟩ + · subst hres + exact lowAt hsim hp within hrun hok + · subst hy + obtain ⟨t, S', s'⟩ := y + obtain ⟨⟨htle, hneedt, hj⟩, pc', T', M', g', st', ss', hh', hR', E', R', hB'⟩ := hsim + obtain ⟨e1, r1, he1⟩ := hh' _ hp + obtain ⟨m, within', hz, hrm⟩ := reaches_lowAt r1 K evm rfl hat within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hmK⟩ := at_of_addGasR he1 + have hgm := reaches_gas_le r1 + rw [hz] at hgm + simp only [gas_addGas] at hgm + have hc1 := hcnt.1 s' rfl + refine ⟨⟨htle, hneedt, hj⟩, m, within', ⟨T', pc', M', st', ss', rd, htle, hneedt, hR', E'.seg, + E'.le_top, E'.mem, R', hatm⟩, ?_, ?_, ?_, by omega, + by rw [hatm.2.2.2.2.2.1]; unfold MemBudget at hB'; omega, hrm⟩ + · dsimp only; omega + · exact TabInv.of_seg hc1.2 (execC_calls _ _ _ is S s s' (by rw [hr]; rfl)) hs0 + · intro T'' hle + rw [hatm.2.2.2.2.2.2.2.2.2.2.2.2] + exact rdRel_world codes (execC_calls _ _ _ is S s s' (by rw [hr]; rfl)) (hrdr T'' hle) + | cut i rest S' s' => + obtain ⟨hci, h', known', ty', k', pc', T', M', g', st', ss', hh', hok2, hh2, hu2, hk2, hR', + I', R', hB'⟩ := hsim + -- The segment, moved back to the frame's gas. + obtain ⟨e1, r1, he1⟩ := hh' _ hp + obtain ⟨m, within1, hz, hrm⟩ := reaches_lowAt r1 K evm rfl hat within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hmK⟩ := at_of_addGasR he1 + have hgm := reaches_gas_le r1 + rw [hz] at hgm + simp only [gas_addGas] at hgm + have hL := hR'.length + have hst := I'.stack + have hc1 := hcnt.1 s' rfl + have hmc := execC_calls (OS codes T) call b is S s s' (by rw [hr]; rfl) + have hlen := hcnt.2 _ rest S' s' rfl + have hmB : MemBudget G0 M' m.gas := by unfold MemBudget at *; omega + have hci' : isGasI i = true ∨ isLoadI i = true ∨ isStoreI i = true ∨ isRetI i = true ∨ + isRevI i = true ∨ isKecI i = true ∨ isLogI i = true ∨ isCdcI i = true ∨ isScI i = true ∨ + isRdsI i = true ∨ isRdcI i = true ∨ isCallI i = true ∨ isC2I i = true ∨ isCcI i = true := by + simpa [isCutI, isMemCutI, or_assoc] using hci + rcases hci' with hgi | hli | hsi | hri | hvi | hki | hlgi | hcdi | hsci | hrdi | hrdci | hcalli | + hc2i | hcci + · obtain rfl := isGasI_eq hgi + obtain ⟨hk1, hok3⟩ := blockOkC_gas hok2 + have hs := I'.seg + rw [lowerInstrs_gas, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + -- GAS at the frame's gas. + obtain ⟨h2, m2, within2, hat2, hrun2⟩ := + gas_backR hatm hlt hcode (by unfold STACK_LIMIT; omega) within1 hrm hok + let T1 : RunTable := { T with gases := T.gases ++ [m.gas - 2] } + have hle1 : T.Le T1 := ⟨List.prefix_refl _, List.prefix_refl _, List.prefix_refl _, + List.prefix_refl _, List.prefix_append _ _⟩ + have hv : ∀ T'', T1.Le T'' → T''.gases.getD (gasReads s'.world) 0 = m.gas - 2 := by + intro T'' hle + rw [getD_of_prefix hle.2.2.2.2 (by simp [T1]; omega)] + simp [T1, List.getD_eq_getElem?_getD, hc1.1, ← hTg] + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segSR (G0 := G0) G codes (hcr := hcr) hdata hvalue hstatic hself hcaller hbenv + htx hb hok hG0 hdepth meets hPok hcal n rest (h' + 1) [] (some false :: ty') (k' - 1) + (BitVec.ofNat 256 (m.gas - 2) :: S') (BitVec.ofNat 256 (m.gas - 2) :: T') + { s' with world := s'.world ++ [.read "gas"] } (pc' + 1) M' (m.gas - 2) st' ss' rd T1 m2 + within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl hR') hseg' (by simp; omega) I'.le_top + I'.mem ⟨R'.storage, R'.account, logsRel_read _ R'.logs⟩ hat2 + (by simp [T1]; omega) (TabInv.read (TabInv.of_seg hc1.2 hmc hs0)) + (fun T3 hle => rdRel_world codes (by rw [machineCalls_read, hmc]) (hrdr T3 (hle1.trans hle))) + (by unfold MemBudget at *; omega) hrun2 + refine ⟨T2, r, hle1.trans hle2, fun T'' hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T'' (hle1.trans (hle2.trans hle))] + show SolarTV.EVM.Program.exec (OS codes T'') call b (.effect .gas 0 :: rest) S' s' = r + rw [exec_gasS codes (hv T'' (hle2.trans hle)) (by omega)] + exact hex2 T'' hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + + · -- MLOAD at the frame's gas, at any offset. + obtain rfl := isLoadI_eq hli + obtain ⟨hk1, hh1, hdat, htop', hok3⟩ := blockOkC_load hok2 + have hs := I'.seg + rw [lowerInstrs_load, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, S''⟩ + · simp at hh2; omega + rcases T' with _ | ⟨x', Tr⟩ + · simp at hL + obtain rfl := (SR.head hR' hdat).symm + have hR'' := (SR.uncons.1 hR').2 + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + mload_dynR I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segSR (G0 := G0) G codes (hcr := hcr) hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 hdepth meets hPok hcal n rest h' [] (some false :: ty'.drop 1) (k' - 1) + (s'.memory.load x.toNat :: S'') (s'.memory.load x.toNat :: Tr) + { s' with memory := s'.memory.expand x.toNat 32 } (pc' + 1) M2 g2 st' ss' rd T m2 + within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl (by simpa using hR'')) hseg' + (by simp; omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by show T.gases.length = gasReads s'.world; rw [hc1.1]; exact hTg) + (TabInv.of_seg hc1.2 hmc hs0) (fun T3 hle => rdRel_world codes hmc (hrdr T3 hle)) hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (OS codes T3) call b (.op .load :: rest) _ s' = r + rw [exec_loadC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + · -- MSTORE at the frame's gas, at any offset. + obtain rfl := isStoreI_eq hsi + obtain ⟨hk1, hh1, hdat, htop', hok3⟩ := blockOkC_store hok2 + have hs := I'.seg + rw [lowerInstrs_store, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 2) S'' Tr := by simpa using SR.drop 2 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + mstore_dynR I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segSR (G0 := G0) G codes (hcr := hcr) hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 hdepth meets hPok hcal n rest (h' - 2) [] (ty'.drop 2) (k' - 1) S'' Tr + { s' with memory := s'.memory.store x.toNat y } (pc' + 1) M2 g2 st' ss' rd T m2 + within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by show T.gases.length = gasReads s'.world; rw [hc1.1]; exact hTg) + (TabInv.of_seg hc1.2 hmc hs0) (fun T3 hle => rdRel_world codes hmc (hrdr T3 hle)) hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (OS codes T3) call b (.op .store :: rest) _ s' = r + rw [exec_storeC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + + · -- RETURN at the frame's gas, from any range. + obtain rfl := isRetI_eq hri + obtain ⟨hh1, hdat⟩ := blockOkC_ret hok2 + have hs := I'.seg + rw [lowerInstrs_ret, List.cons_append] at hs + obtain ⟨next, hd, -⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hg := return_backR hatm hlt hcode within1 hrm hok + refine ⟨T, .inl (SolarTV.EVM.Program.output s' (x :: y :: S'') false), RunTable.Le.refl T, + fun T3 hle => ?_, fun res hres => ?_, fun y hy => ?_⟩ + · rw [hex T3 hle] + rfl + · obtain rfl := Sum.inl.inj hres + simp only [SolarTV.EVM.Program.output, Bool.false_eq_true, ↓reduceIte] + exact lowAt (SpecG.consequence (return_postSG (ss := ss') hlt hcode (by omega) rfl + (by rw [read_eq I'.mem]; rfl) rfl (R'.slot hself)) (fun _ h => h) + (fun _ h => ⟨ss', h, R'.logs⟩)) (hatm.addGas 0) within1 hrm hok + · cases hy + · -- REVERT at the frame's gas, from any range: the program's revert, with its data. + obtain rfl := isRevI_eq hvi + obtain ⟨hh1, hdat⟩ := blockOkC_revert hok2 + have hs := I'.seg + rw [lowerInstrs_revert, List.cons_append] at hs + obtain ⟨next, hd, -⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hg := revert_backR hatm hlt hcode within1 hrm hok + refine ⟨T, .inl (SolarTV.EVM.Program.output s' (x :: y :: S'') true), RunTable.Le.refl T, + fun T3 hle => ?_, fun res hres => ?_, fun y hy => ?_⟩ + · rw [hex T3 hle] + rfl + · obtain rfl := Sum.inl.inj hres + simp only [SolarTV.EVM.Program.output, ↓reduceIte] + exact lowAt (SpecG.consequence (revert_postSG (ss := ss') (by decide) hlt hcode (by omega) + rfl (by rw [read_eq I'.mem]; rfl) rfl) (fun _ h => h) + (fun _ h => ⟨ss', h, R'.logs⟩)) (hatm.addGas 0) within1 hrm hok + · cases hy + + · -- KECCAK256 at the frame's gas, of any range. + obtain rfl := isKecI_eq hki + obtain ⟨henv, hk1, hh1, hdat, htop', hok3⟩ := blockOkC_kec hok2 + have hs := I'.seg + rw [lowerInstrs_kec, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 2) S'' Tr := by simpa using SR.drop 2 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨m2, within2, hmem2, hb2, hat2, hrun2⟩ := + keccak_dynR I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + obtain ⟨-, hkec⟩ := (OS_ok codes c T).1 henv + rw [byteArray_eq_of_map (read_eq I'.mem), ← hkec] at hat2 + have hsz : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size ≤ c.top := by + have hmod : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size % 32 = 0 := by + rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segSR (G0 := G0) G codes (hcr := hcr) hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 hdepth meets hPok hcal n rest (h' - 1) [] (some false :: ty'.drop 2) (k' - 1) + ((OS codes T).keccak ((s'.memory.expand x.toNat y.toNat).read x.toNat y.toNat) :: S'') + ((OS codes T).keccak ((s'.memory.expand x.toNat y.toNat).read x.toNat y.toNat) :: Tr) + { s' with memory := s'.memory.expand x.toNat y.toNat } (pc' + 1) _ _ st' ss' rd T m2 + within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl (by simpa using hR'')) hseg' + (by simp; omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by show T.gases.length = gasReads s'.world; rw [hc1.1]; exact hTg) + (TabInv.of_seg hc1.2 hmc hs0) (fun T3 hle => rdRel_world codes hmc (hrdr T3 hle)) hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (OS codes T3) call b (.effect .keccak256 2 :: rest) _ s' = r + rw [exec_keccakC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + + · -- LOGn at the frame's gas, of any range. + obtain ⟨nl, hn4, rfl⟩ := isLogI_eq hlgi + obtain ⟨hk1, hnh, hdat, htop', hok3⟩ := blockOkC_log hn4 hok2 + have hs := I'.seg + rw [lowerInstrs_log p c b hn4, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S1⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', T1⟩⟩ + · simp at hL + · simp at hL + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨tops, S2, rfl, hlen⟩ : ∃ tops S2, S1 = tops ++ S2 ∧ tops.length = nl := + ⟨S1.take nl, S1.drop nl, (List.take_append_drop nl S1).symm, by simp; omega⟩ + obtain ⟨tops', T2, rfl, hlen'⟩ : ∃ tops' T2, T1 = tops' ++ T2 ∧ tops'.length = nl := + ⟨T1.take nl, T1.drop nl, (List.take_append_drop nl T1).symm, by simp; omega⟩ + subst hlen + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.cons.injEq, List.take_left' hlen', + List.take_left' rfl] at htake + obtain ⟨rfl, rfl, rfl⟩ := htake + have hR'' : SR c (ty'.drop (tops.length + 2)) S2 T2 := by + simpa using SR.drop (tops.length + 2) hR' + simp only [List.length_append] at hL hst hh2 hu2 + obtain ⟨m2, within2, hmem2, hb2, hat2, hrun2⟩ := + log_dynR (n := ⟨tops.length, by omega⟩) I'.mem hmB (by omega) hatm rfl hlt hcode + (decode_log ⟨tops.length, by omega⟩) hstatic within1 hrm hok + have hsz : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size ≤ c.top := by + have hmod : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size % 32 = 0 := by + rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨L, hL1, hL2⟩ := R'.logs + obtain ⟨T2', r, hle2, hex2, hpost, hnext⟩ := segSR (G0 := G0) (ss0 := ss0) G codes (hcr := hcr) hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 hdepth meets hPok hcal n rest (h' - (tops.length + 2)) [] (ty'.drop (tops.length + 2)) + (k' - 1) S2 T2 + ⟨s'.memory.expand x.toNat y.toNat, s'.storage, s'.transient, + s'.world ++ [.log tops ((s'.memory.expand x.toNat y.toNat).read x.toNat y.toNat)]⟩ + (pc' + 1) _ _ st' { ss' with logs := ss'.logs.push ⟨msg.currentTarget, + tops.map U256.toBeBytes, memoryReadBytes (memoryExtend M' (extendMemory M'.size + [(x, y)]).expandBy) x.toNat y.toNat⟩ } rd T m2 within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 + ⟨R'.storage, R'.account, ⟨L ++ [⟨msg.currentTarget, tops.map U256.toBeBytes, + memoryReadBytes (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy) + x.toNat y.toNat⟩], by simp [Array.toList_push, hL1], + filter_snoc_log ▸ forall₂_snoc hL2 ⟨rfl, rfl, read_eq I'.mem⟩⟩⟩ hat2 + (by show T.gases.length = gasReads (s'.world ++ [_]); rw [AssembleCut.gasReads_log, hc1.1]; exact hTg) + (TabInv.log (TabInv.of_seg hc1.2 hmc hs0)) + (fun T3 hle => rdRel_world codes (by rw [machineCalls_log, hmc]) (hrdr T3 hle)) hb2 hrun2 + refine ⟨T2', r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (OS codes T3) call b + (.effect (.log tops.length) (tops.length + 2) :: rest) _ s' = r + rw [exec_logC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + + · -- CALLDATACOPY at the frame's gas, of any range. + obtain rfl := isCdcI_eq hcdi + obtain ⟨hk1, hh1, hdat, htop', hok3⟩ := blockOkC_cdc hok2 + have hs := I'.seg + rw [lowerInstrs_cdc, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, _ | ⟨z, S''⟩⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', _ | ⟨z', Tr⟩⟩⟩ + · simp at hL + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 3) S'' Tr := by simpa using SR.drop 3 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + cdc_dynR hdata I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segSR (G0 := G0) (ss0 := ss0) G codes (hcr := hcr) hdata hvalue + hstatic hself hcaller hbenv htx hb hok hG0 hdepth meets hPok hcal n rest (h' - 3) [] (ty'.drop 3) (k' - 1) S'' Tr + { s' with + memory := s'.memory.write x.toNat z.toNat + (fun i => SolarTV.Machine.calldataByte call (y.toNat + i)) } (pc' + 1) M2 g2 st' ss' rd T m2 + within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by show T.gases.length = gasReads s'.world; rw [hc1.1]; exact hTg) + (TabInv.of_seg hc1.2 hmc hs0) (fun T3 hle => rdRel_world codes hmc (hrdr T3 hle)) hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (OS codes T3) call b (.effect .calldatacopy 3 :: rest) _ s' = r + rw [exec_cdcC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + · -- STATICCALL to code at the frame's gas: the callee frame's flag and output join the table. + obtain rfl := isScI_eq hsci + obtain ⟨-, hk1, hh1, hdat, htop', hok3⟩ := blockOkC_sc hok2 + have hs := I'.seg + rw [lowerInstrs_sc, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x1, _ | ⟨x2, _ | ⟨x3, _ | ⟨x4, _ | ⟨x5, _ | ⟨x6, S''⟩⟩⟩⟩⟩⟩ + all_goals (first | (simp at hh2; omega) | skip) + rcases T' with _ | ⟨y1, _ | ⟨y2, _ | ⟨y3, _ | ⟨y4, _ | ⟨y5, _ | ⟨y6, Tr⟩⟩⟩⟩⟩⟩ + all_goals (first | (simp at hL; done) | skip) + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, rfl, rfl, rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 6) S'' Tr := by simpa using SR.drop 6 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + have hco := hcal hatm hlt hcode hrm + obtain ⟨hi1, hi2, hi3⟩ := hs0 + obtain ⟨ok, out, s2, M2, g2, st2, ss2, m2, within2, happ, ⟨ev, hw, hev1, hev2, hev3⟩, hmem2, + R2, hb2, hg2, hat2, hrun2⟩ := staticcall_cutR codes T I'.mem R' hmB (by omega) hatm hlt hcode + hdepth meets hPok within1 hrm hok hco (by rw [hmc, hi2]) (by rw [hmc, hi2, hi3]) + (by rw [hc1.1]; omega) + let T1 : RunTable := { T with oks := T.oks ++ [ok], outs := T.outs ++ [out] } + have hle1 : T.Le T1 := ⟨List.prefix_append _ _, List.prefix_append _ _, List.prefix_refl _, + List.prefix_refl _, List.prefix_refl _⟩ + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + have hinv : TabInv T1 s2.world := by + refine ⟨?_, ?_, ?_⟩ + · rw [hw, AssembleCallSeg.sent_append, hev1, hc1.2, hi1] + simp [T1] + · rw [hw, AssembleCallSeg.machineCalls_append, List.length_append, hev3, hmc, hi2] + simp [T1] + · simp [T1, hi3] + have hTg1 : T1.gases.length = gasReads s2.world := by + rw [hw, AssembleCallSeg.gasReads_append, hev2, hc1.1] + simpa [T1] using hTg + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segSR (G0 := G0) G codes (hcr := hcr) hdata hvalue hstatic + hself hcaller hbenv htx hb hok hG0 hdepth meets hPok hcal n rest (h' - 5) [] + (some false :: ty'.drop 6) (k' - 1) ((if ok then 1 else 0) :: S'') + ((if ok then 1 else 0) :: Tr) s2 (pc' + 1) M2 g2 st2 ss2 out T1 m2 within2 (by omega) hok3 + (by simp; omega) (by simp; omega) (KR.nil _) (SR.cons (τ := some false) rfl hR'') + hseg' (by simp; omega) hsz hmem2 R2 hat2 hTg1 hinv (fun T3 hle => (happ T3 hle).2) hb2 hrun2 + refine ⟨T2, r, hle1.trans hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle1.trans (hle2.trans hle))] + show SolarTV.EVM.Program.exec (OS codes T3) call b + (.effect (.call .staticcall) 6 :: rest) _ s' = r + rw [exec_scC (happ T3 (hle2.trans hle)).1 (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + · -- RETURNDATASIZE at the frame's gas: the size of the frame's return data, the table's. + obtain rfl := isRdsI_eq hrdi + obtain ⟨-, hk1, hok3⟩ := blockOkC_rds hok2 + have hs := I'.seg + rw [lowerInstrs_rds, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + obtain ⟨h2, m2, within2, hat2, hrun2⟩ := + rds_backR hatm hlt hcode (by unfold STACK_LIMIT; omega) within1 hrm hok + have hrd' : ∀ T3, T.Le T3 → RdRel (OS codes T3) s'.world rd := + fun T3 hle => rdRel_world codes hmc (hrdr T3 hle) + have hv : ∀ T3, T.Le T3 → + (OS codes T3).env "returndatasize" s'.world [] = BitVec.ofNat 256 rd.size := by + intro T3 hle + have h1 := (hrd' T3 hle).1 + simp only [returndataSize] at h1 + have hlt' : rd.size < 2 ^ 256 := by rw [← h1]; exact BitVec.isLt _ + apply BitVec.eq_of_toNat_eq + rw [BitVec.toNat_ofNat, h1, Nat.mod_eq_of_lt hlt'] + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segSR (G0 := G0) G codes (hcr := hcr) hdata hvalue hstatic + hself hcaller hbenv htx hb hok hG0 hdepth meets hPok hcal n rest (h' + 1) [] (some false :: ty') + (k' - 1) (BitVec.ofNat 256 rd.size :: S') (BitVec.ofNat 256 rd.size :: T') s' (pc' + 1) M' + (m.gas - 2) st' ss' rd T m2 within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl hR') hseg' (by simp; omega) I'.le_top + I'.mem R' hat2 (by rw [hc1.1]; exact hTg) (TabInv.of_seg hc1.2 hmc hs0) hrd' + (by unfold MemBudget at *; omega) hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (OS codes T3) call b (.effect .returndatasize 0 :: rest) S' s' = r + rw [exec_rdsC (hv T3 (hle2.trans hle)) (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + · -- RETURNDATACOPY at the frame's gas, of any range within the return data. + obtain rfl := isRdcI_eq hrdci + obtain ⟨-, hk1, hh1, hdat, htop', hok3⟩ := blockOkC_rdc hok2 + have hs := I'.seg + rw [lowerInstrs_rdc, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, _ | ⟨z, S''⟩⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', _ | ⟨z', Tr⟩⟩⟩ + · simp at hL + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 3) S'' Tr := by simpa using SR.drop 3 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + have hrd' : ∀ T3, T.Le T3 → RdRel (OS codes T3) s'.world rd := + fun T3 hle => rdRel_world codes hmc (hrdr T3 hle) + obtain ⟨hfit, M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + rdc_dynR I'.mem hmB (by omega) (hrd' T (RunTable.Le.refl T)) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + have hext : ∀ T3, T.Le T3 → returndataByte (OS codes T3) s'.world = + returndataByte (OS codes T) s'.world := by + intro T3 hle + funext i + simp only [returndataByte] + rw [OS_env_ext codes hle (by rw [hmc, hs0.2.1]) (by rw [hmc, hs0.2.1, hs0.2.2]) + (by rw [hc1.1]; omega) (by decide)] + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segSR (G0 := G0) G codes (hcr := hcr) hdata hvalue + hstatic hself hcaller hbenv htx hb hok hG0 hdepth meets hPok hcal n rest (h' - 3) [] (ty'.drop 3) + (k' - 1) S'' Tr + { s' with + memory := s'.memory.write x.toNat z.toNat + (fun i => returndataByte (OS codes T) s'.world (y.toNat + i)) } (pc' + 1) M2 g2 st' ss' rd + T m2 within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by rw [hc1.1]; exact hTg) (TabInv.of_seg hc1.2 hmc hs0) hrd' hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (OS codes T3) call b (.effect .returndatacopy 3 :: rest) _ s' = r + rw [exec_rdcC (by rw [(hrd' T3 (hle2.trans hle)).1]; exact hfit) (by omega), + hext T3 (hle2.trans hle)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hrdy, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, hrdy, by omega, hbud, hra⟩ + · -- CALL, CREATE2 and CODECOPY: only a certificate that says the program creates lets the + -- checker cut there. + obtain rfl := isCallI_eq hcalli + exact absurd (blockOkC_call hok2).2.1 (by simp [hcr]) + · obtain rfl := isC2I_eq hc2i + exact absurd (blockOkC_c2 hok2).2.1 (by simp [hcr]) + · obtain rfl := isCcI_eq hcci + exact absurd (blockOkC_cc hok2).2.1 (by simp [hcr]) + +section BlocksQ + +variable {σ : Type} (blk : Oracle → σ → Option ((Halt × Machine.State) ⊕ σ)) + (O : RunTable → Oracle) + +/-- **One block of the simulation, read back from a run that succeeds**, as +`AssembleCall.AdvancesS` under every runner of messages meeting `P`, for the runs to a frame `fin` +that meet the hypothesis `Q`. -/ +def AdvancesQR (P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop) + (Q : (bound : Nat) → MessageRunner .fusaka Nat bound → Evm .fusaka Nat → Prop) + (E : RunTable → σ → Evm .fusaka Nat → Prop) + (Post : Halt × Machine.State → Evm .fusaka Nat → Prop) (meas : σ → Evm .fusaka Nat → Nat) + (T : RunTable) (x : σ) (evm : Evm .fusaka Nat) : Prop := + ∀ (bound : Nat) (runChild : MessageRunner .fusaka Nat bound), Meets P runChild → + ∀ (within : GasMeter.gasHeld evm.gas ≤ bound) (fin : Evm .fusaka Nat), + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + OkR fin → Q bound runChild fin → + ∃ T' r, T.Le T' ∧ (∀ T'', T'.Le T'' → blk (O T'') x = some r) ∧ + (∀ res, r = .inl res → Post res fin) ∧ + (∀ y, r = .inr y → ∃ after within', E T' y after ∧ meas y after < meas x evm ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild after within' = .ok fin) + +/-- A run of EthLib that ends with no error and meets the hypothesis is SolarTV's, for every table +extending the last one the run grew. -/ +theorem run_of_advancesQR {P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop} + {Q : (bound : Nat) → MessageRunner .fusaka Nat bound → Evm .fusaka Nat → Prop} + {E : RunTable → σ → Evm .fusaka Nat → Prop} + {Post : Halt × Machine.State → Evm .fusaka Nat → Prop} {meas : σ → Evm .fusaka Nat → Nat} + (adv : ∀ T x evm, E T x evm → AdvancesQR blk O P Q E Post meas T x evm) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + (meets : Meets P runChild) : + ∀ (n : Nat) (T : RunTable) (x : σ) (evm : Evm .fusaka Nat) + (within : GasMeter.gasHeld evm.gas ≤ bound) (fin : Evm .fusaka Nat), + E T x evm → meas x evm < n → + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + OkR fin → Q bound runChild fin → + ∃ T' res, T.Le T' ∧ + (∀ T'', T'.Le T'' → ∃ k, SolarTV.Machine.iterate (blk (O T'')) k x = some res) ∧ + Post res fin + | 0, _, _, _, _, _, _, h, _, _, _ => absurd h (Nat.not_lt_zero _) + | n + 1, T, x, evm, within, fin, hE, hm, hrun, hok, hq => by + obtain ⟨T', r, hle, hstep, hinl, hinr⟩ := + adv T x evm hE bound runChild meets within fin hrun hok hq + cases r with + | inl res => + exact ⟨T', res, hle, fun T'' h => ⟨1, by simp [SolarTV.Machine.iterate, hstep T'' h]⟩, + hinl res rfl⟩ + | inr y => + obtain ⟨after, within', hE', hm', hrun'⟩ := hinr y rfl + obtain ⟨T2, res, hle2, hit, hpost⟩ := + run_of_advancesQR adv meets n T' y after within' fin hE' (by omega) hrun' hok hq + refine ⟨T2, res, hle.trans hle2, fun T'' h => ?_, hpost⟩ + obtain ⟨k, hk⟩ := hit T'' h + exact ⟨k + 1, by simp [SolarTV.Machine.iterate, hstep T'' (hle2.trans h), hk]⟩ + +end BlocksQ + +/-- **A block of code with loops, GAS and STATICCALLs, read back from a run that succeeds.** -/ +theorem advances_checkCSR {p : Assemble.Program} {c : Cert} {mx : List Nat} {code : ByteArray} + (G : GlobC p c mx code) (codes : SolidCore.Solidity.Shared.Account.BytesMap) (hcr : c.creates = false) {call : Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : msg.txEnv = Target.txEnv) + (hgas : msg.gas < 2 ^ 256) (hdepth : msg.depth + 1 ≤ STACK_DEPTH_LIMIT) + (T0 : RunTable) (x : Nat × List Word × State) (evm : Evm .fusaka Nat) + (hE : EntS codes p c mx code msg ss0 T0 x evm) : + AdvancesQR (fun o => SolarTV.EVM.Program.block o call p) (OS codes) StaticOkE + (CalleesOk code msg StaticOkE) + (EntS codes p c mx code msg ss0) + (fun res => PostL call msg.currentTarget ss0 res.2 res.1) + (fun y e => AssembleLoop.meas p c e.gas y.1) T0 x evm := by + intro bound runChild meets within fin hrun hok hcal + obtain ⟨b, S, s⟩ := x + obtain ⟨⟨Tw, pc, M, st, ss, rd, hle, hneed, hR, hseg, htop, hmem, R, hat⟩, hTg, hs0, hrdr, hbud⟩ := hE + simp only at hle hneed hR hseg hmem R hTg hs0 hrdr + by_cases hb : b < p.blocks.length + · obtain ⟨hL, hnm, hstk, hblock⟩ := G.block b hb + obtain ⟨hn, hm⟩ := hneed hb + have hblk : p.blocks[b]? = some p.blocks[b] := List.getElem?_eq_getElem hb + rw [lowerFrom_drop p c hb, lowerBlock, List.append_assoc] at hseg + -- The label, at the frame's gas. + obtain ⟨pc1, m1, within1, hat1, hseg1, hg1, hrun1⟩ : ∃ (pc1 : Nat) (m1 : Evm .fusaka Nat) + (within1 : GasMeter.gasHeld m1.gas ≤ bound), + At code msg pc1 Tw M m1.gas st ss rd m1 ∧ + Seg (bytesOf code) c.offset pc1 (lowerInstrs p c b p.blocks[b] ++ + lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) code.size ∧ + m1.gas + (if isTarget p c b then 1 else 0) ≤ evm.gas ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m1 within1 = .ok fin := by + by_cases ht : isTarget p c b = true + · simp only [ht, ite_true, List.singleton_append, List.cons_append] at hseg + obtain ⟨next, hd, hseg'⟩ := hseg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hp := hat.addGas 1 + obtain ⟨e1, r1, he1⟩ := Logic.jumpdestG hlt hcode (show 1 ≤ evm.gas + 1 by omega) _ hp + obtain ⟨m, within', hz, hrm⟩ := reaches_lowAt r1 1 evm rfl hat within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hgm⟩ := at_of_addGasR he1 + exact ⟨pc + 1, m, within', hatm, hseg', by simp only [ht, ite_true]; omega, hrm⟩ + · simp only [ht, Bool.false_eq_true, ite_false, List.nil_append] at hseg + exact ⟨pc, evm, within, hat, hseg, by simp only [ht, Bool.false_eq_true, ite_false]; omega, + hrun⟩ + obtain ⟨T', r, hle', hex, hpost, hnext⟩ := segSR (G0 := msg.gas) G.toGlobT codes (hcr := hcr) hdata hvalue hstatic hself hcaller + hbenv htx hb hok hgas hdepth meets (fun _ _ _ h => h.1) hcal (p.blocks[b].length + 1) p.blocks[b] (c.need b) [] (c.entry b) + (budget c b - labelItems p c b) S Tw s pc1 M m1.gas st ss rd T0 m1 within1 (Nat.lt_succ_self _) + hblock hn (by omega) (KR.nil _) hR hseg1 (by omega) htop hmem R hat1 hTg hs0 + (by rw [← hat.2.2.2.2.2.2.2.2.2.2.2.2]; exact hrdr) + (by unfold MemBudget; rw [← hat.2.2.2.2.2.1]; omega) hrun1 + refine ⟨T', r, hle', fun T'' h => ?_, fun res hres => hpost res hres, fun y hy => ?_⟩ + · simp only [SolarTV.EVM.Program.block, hblk] + rw [hex T'' h] + · obtain ⟨t, S', s'⟩ := y + obtain ⟨⟨htle, -, hj⟩, after, within', hE', hT', hs', hrdy', hga, hbud', hra⟩ := hnext _ hy + refine ⟨after, within', ⟨hE', hT', hs', hrdy', hbud'⟩, ?_, hra⟩ + have := meas_step (c := c) (g := evm.gas) (g' := after.gas) hb htle (by omega) hj + dsimp only at this ⊢ + omega + · obtain rfl : b = p.blocks.length := by omega + have hblk : p.blocks[p.blocks.length]? = none := List.getElem?_eq_none (by omega) + have hbl : ∀ o, SolarTV.EVM.Program.block o call p (p.blocks.length, S, s) = + some (.inl (.stop, s)) := by + intro o + simp only [SolarTV.EVM.Program.block, hblk, ite_true] + refine ⟨T0, _, RunTable.Le.refl T0, fun _ _ => hbl _, ?_, ?_⟩ + · intro res hres + cases hres + have hseg' := hseg + rw [lowerFrom_nil p c (by omega)] at hseg' + have hpc := hseg'.nil_end + exact lowAt (SpecG.consequence (stop_of_size_leG (by omega)) + (fun _ h => h) fun evm h => postL_stop R hself evm h) (hat.addGas 0) within hrun hok + · intro y hy + cases hy + + +open EthLib.Execution.State in +/-- **Named hypothesis on a run**: `AssembleCallSeg.CalleesRun` for every run of the message's frame +that ends with no error or reverts (`CalleesOk` at each of its STATICCALLs). -/ +def CalleesRunE (gas : Nat) (code : ByteArray) (call : Call) : Prop := + ∀ (st' : TransactionState) (ss' : Substate) + (within : GasMeter.gasHeld (startFrame (Final.Target.messageWith gas code call) st' ss' + (Final.Target.messageWith gas code call).gas).gas ≤ (Final.Target.messageWith gas code call).gas) + (fr : Evm .fusaka Nat), + runFrame (step .fusaka) (step_decreases .fusaka) (Final.Target.messageWith gas code call).gas + (processRunner .fusaka (Final.Target.messageWith gas code call).gas) + (startFrame (Final.Target.messageWith gas code call) st' ss' + (Final.Target.messageWith gas code call).gas) within = .ok fr → OkR fr → + CalleesOk code (Final.Target.messageWith gas code call) StaticOkE gas + (processRunner .fusaka (Meter := Nat) gas) fr + +open SolarTV.EVM.Program SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Evm.Symex in +/-- **`AssembleCallSeg.within_of_advancesQ` with the revert data related.** -/ +theorem within_of_advancesQR {p : Assemble.Program} {code : ByteArray} {call : Call} {gas : Nat} + (O : RunTable → Oracle) (P : Evm .fusaka Nat → Message .fusaka → Evm .fusaka Nat → Prop) + (Q : (bound : Nat) → MessageRunner .fusaka Nat bound → Evm .fusaka Nat → Prop) + (E : Substate → RunTable → Nat × List Word × Machine.State → Evm .fusaka Nat → Prop) + (meas : Nat × List Word × Machine.State → Evm .fusaka Nat → Nat) + (hP : Meets P (processRunner .fusaka (Meter := Nat) (Final.Target.messageWith gas code call).gas)) + (hQ : ∀ (st' : EthLib.Execution.State.TransactionState) (ss' : Substate) + (within : GasMeter.gasHeld (startFrame (Final.Target.messageWith gas code call) st' ss' + (Final.Target.messageWith gas code call).gas).gas ≤ + (Final.Target.messageWith gas code call).gas) (fr : Evm .fusaka Nat), + runFrame (step .fusaka) (step_decreases .fusaka) (Final.Target.messageWith gas code call).gas + (processRunner .fusaka (Final.Target.messageWith gas code call).gas) + (startFrame (Final.Target.messageWith gas code call) st' ss' + (Final.Target.messageWith gas code call).gas) within = .ok fr → OkR fr → + Q _ (processRunner .fusaka (Meter := Nat) (Final.Target.messageWith gas code call).gas) fr) + (start : ∀ st' ss', Rel (Final.Target.messageWith gas code call) ss' st' ss' + (Machine.State.initial call) → + E ss' {} (0, [], Machine.State.initial call) + (startFrame (Final.Target.messageWith gas code call) st' ss' gas)) + (adv : ∀ ss0 T x evm, E ss0 T x evm → AdvancesQR (fun o => block o call p) O P Q (E ss0) + (fun res => PostL call (Final.Target.messageWith gas code call).currentTarget ss0 res.2 res.1) + meas T x evm) : + ∃ T, WithinR (evmirSem (O T)) gas p code (· = call) := by + cases hrunE : Target.runWith gas code call with + | none => + refine ⟨{}, fun call' hc obs h => ?_⟩ + subst hc + rw [hrunE] at h + cases h + | some obs => + have hrun0 := hrunE + unfold Target.runWith Target.runMsg at hrunE + split at hrunE + · cases hrunE + rename_i evm hev hpm + simp only [Option.some.injEq] at hrunE + by_cases hex : ∃ e, e ≠ EvmError.revert ∧ evm.error = some e + · obtain ⟨e, hne, he'⟩ := hex + have hs : obs.success = false := by rw [← hrunE]; simp [he'] + have hfail := Target.runWith_failure hrun0 hs + have hh : HaltsExceptionally gas code call := ⟨⟨evm, hev⟩, hpm, e, hne, he'⟩ + refine ⟨{}, fun call' hc obs' h => ?_⟩ + subst hc + rw [hrun0] at h + cases h + exact Or.inr ⟨hh, hs, hfail⟩ + rcases herrc : evm.error with _ | e + · obtain ⟨T, hT⟩ := within_of_advancesQ O P Q E meas hP + (fun r hr he => by + obtain ⟨st', ss', within, -, -, hrf⟩ := AssembleRun.processMessage_ok' + (message := Final.Target.messageWith gas code call) (evm := r) + (precompileAddress_message code call) hr he + exact hQ st' ss' within r.1 hrf (.inl he)) + start (fun ss0 T x evm h b rc m w f hr he hq => adv ss0 T x evm h b rc m w f hr (.inl he) hq) + have hsucc : obs.success = true := by rw [← hrunE]; simp [herrc] + refine ⟨T, fun call' hc obs' h => ?_⟩ + rcases hT call' hc obs' h with h' | ⟨hs, -⟩ + · exact .inl h' + · subst hc + rw [hrun0] at h + cases h + rw [hsucc] at hs + cases hs + have hrev : e = .revert := by + by_contra hne + exact hex ⟨e, hne, herrc⟩ + subst hrev + obtain ⟨st', ss', within, fr, hcases, hmove, hrf, herrfr, houtfr⟩ := + processMessage_frameP (message := Final.Target.messageWith gas code call) (evm := ⟨evm, hev⟩) + (precompileAddress_message code call) hpm + simp only at herrfr houtfr + have hfrrev : fr.error = some .revert := by rw [← herrfr, herrc] + have R := AssembleLoop.rel_start code call gas ss' (fun h => (hcases h).1) (fun h => (hmove h).1) + obtain ⟨T, ⟨halt, sF⟩, -, hit, hpost⟩ := run_of_advancesQR (fun o => block o call p) O (adv ss') + hP _ {} _ _ within fr (start st' ss' R) (Nat.lt_succ_self _) hrf (.inr hfrrev) + (hQ st' ss' within fr hrf (.inr hfrrev)) + obtain ⟨k, hk⟩ := hit T (RunTable.Le.refl T) + have hres : (evmirSem (O T)).run p call = some (observe call sF halt) := by + change (SolarTV.EVM.Program.layer.result (O T) p call).map _ = _ + rw [SolarTV.EVM.Program.layer.result_of_ends ⟨k, hk⟩] + rfl + obtain ⟨ssF, ⟨herr, hout, -, -⟩, -⟩ := hpost + have hfinal : (evmirSem (O T)).run p call = some obs := by + rw [hres, ← hrunE] + have herr' : fr.error = errorOf (observe call sF halt) := herr + have hout' : fr.output.toList.map (·.toNat) = (observe call sF halt).output := hout + have hfail : (observe call sF halt).success = false → + (observe call sF halt).logs = [] ∧ + (observe call sF halt).storage = slotValue call.storage := by + cases halt <;> simp [observe] + clear herr hout hres hit hk + generalize observe call sF halt = X at * + have hsucc : fr.error.isNone = X.success := by + rw [herr']; cases hX : X.success <;> simp [errorOf, hX] + rw [hfrrev] at hsucc + simp only [Option.isNone_some] at hsucc + obtain ⟨hlogs, hst⟩ := hfail hsucc.symm + congr 1 + cases X with + | mk success output logs storage => + simp only at hsucc hout' hlogs hst ⊢ + subst hsucc hlogs hst + rw [SolarTV.Observable.mk.injEq] + refine ⟨by simp [herrc], ?_, by simp [herrc], by funext slot; simp [herrc]⟩ + rw [houtfr] + exact hout'.symm + refine ⟨T, fun call' hc obs' h => ?_⟩ + subst hc + rw [hrun0] at h + cases h + exact .inl hfinal + +/-- **EVM IR to bytecode, run by run, for code with loops, GAS, memory at any offset and +STATICCALLs to code, with the revert data related**: for every program the checker without the +no-call gate accepts, at every gas below `2 ^ 256` and every call whose run meets the named +hypotheses, the oracle of the run's table makes every result of the bytecode the EVM IR's (a +revert with its data among them), unless the run halted exceptionally. -/ +theorem runs_of_checkCBR {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (hc : checkCB p code c mx = true) (codes : SolidCore.Solidity.Shared.Account.BytesMap) + (gas : Nat) (hgas : gas < 2 ^ 256) (call : Call) (hP : StaticRunner gas) + (hQ : CalleesRunE gas code call) : + ∃ T, WithinR (evmirSem (OS codes T)) gas p code (· = call) := by + obtain ⟨G, hseg, hneed0⟩ := globC_of_checkC hc + refine within_of_advancesQR (OS codes) StaticOkE + (CalleesOk code (Final.Target.messageWith gas code call) StaticOkE) + (fun ss0 => EntS codes p c mx code (Final.Target.messageWith gas code call) ss0) + (fun y e => AssembleLoop.meas p c e.gas y.1) (staticOkE_of gas hP) hQ (fun st' ss' R => ?_) + (fun ss0 T x evm hE => advances_checkCSR G codes (hcr := checkCB_creates hc) rfl + (by simp [Final.Target.messageWith, SolidCore.Refinement.Target.message]) rfl rfl rfl rfl rfl + hgas (by show 0 + 1 ≤ 1024; decide) T x evm hE) + refine ⟨⟨[], 0, .empty, st', ss', .empty, Nat.zero_le _, fun _ => ⟨by simp [hneed0], by simp⟩, + SR.nil c _, by rw [List.drop_zero]; exact hseg, by simp, memRel_initial, R, ?_⟩, rfl, + ⟨rfl, rfl, rfl⟩, fun T'' _ => rdRel_nil codes T'', ?_⟩ + have hcode : (Final.Target.messageWith gas code call).code = code := rfl + · exact ⟨by simp [startFrame, hcode], by simp [startFrame, hcode], rfl, rfl, rfl, rfl, rfl, rfl, rfl, + rfl, rfl, rfl, rfl⟩ + · have h0 : memoryGasCost 0 = 0 := by rw [memoryGasCost_eq]; simp [wordCount, ceil32, WORD_BYTES] + simp only [startFrame, ByteArray.size_empty, h0, Nat.zero_add] + exact le_refl _ + +/-- info: 'SolidCore.Refinement.Solar.AssembleRevertCall.runs_of_checkCBR' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms runs_of_checkCBR + +end SolidCore.Refinement.Solar.AssembleRevertCall diff --git a/SolidCore/Refinement/Solar/AssembleRevertCut.lean b/SolidCore/Refinement/Solar/AssembleRevertCut.lean new file mode 100644 index 00000000..e4dcbe53 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleRevertCut.lean @@ -0,0 +1,1385 @@ +import SolidCore.Refinement.Solar.EthLibErrLow +import SolidCore.Refinement.Solar.AssembleRevert +import SolidCore.Refinement.Solar.AssembleCut + +/-! +# EVM IR to bytecode with GAS and memory at any offset, with the revert data related + +`AssembleCut.runs_of_checkC` reads each block back from a run that succeeds: a run that reverts +fails, and `AssembleDyn.revert_false` rules REVERT out, so its revert data stand for themselves. +Here the same reading back holds of a run that ends with no error or reverts (`OkR`): a segment +moved back to the frame's gas by `RevertErr.reaches_lowR` and `RevertErr.SpecG.lowR` +(`reaches_lowAt`, `lowAt`), each instruction at the frame's gas (`gas_backR`, `mstore_dynR`, ...) +ruling out only an exceptional halt, and REVERT at the frame's gas (`revert_backR`) showing the +program's revert, with its data, as RETURN shows its output. + +* `segR`, `advances_checkCR`: `AssembleCut.seg` and `advances_checkC` for such runs, REVERT + included. +* `within_of_advancesR`: `AssembleRun.within_of_advances` with the revert data related + (`AssembleLoop.WithinR`). +* `runs_of_checkCR`, `withinRunR_of_checkC`: for every program the checker with GAS accepts, at + every gas below `2 ^ 256` and every call, the oracle of the run's table makes every result of the + bytecode the EVM IR's, a revert with its data among them, unless the run halted exceptionally. + +The proofs of the instructions are those of `AssembleDyn`, `AssembleDynCopy` and `AssembleCut` +with the run's end allowed to revert: each rules out an exceptional halt the same way. +-/ + +namespace SolidCore.Refinement.Solar.AssembleRevertCut + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Final +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.RunOracle SolidCore.Refinement.Solar.AssembleRun +open SolidCore.Refinement.Solar.AssembleRunLoop +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide +open SolidCore.Refinement.Solar.AssembleCut SolidCore.Refinement.Solar.AssembleDyn + SolidCore.Refinement.Solar.AssembleDynCopy SolidCore.Refinement.Solar.AssembleEffects + +/-- A run that ends with no error, or with the revert error. -/ +def OkR (fin : Evm .fusaka Nat) : Prop := fin.error = none ∨ fin.error = some .revert + +/-- `SpecG.low` from a frame of the code, for a run that ends with no error or reverts. -/ +theorem lowAt {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {T : List Word} + {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} {rd : ByteArray} + {Q : Evm .fusaka Nat → Prop} (h : SpecG .fusaka (At code msg pc T M g st ss rd) Q) {k : Nat} + {l : Evm .fusaka Nat} (hp : At code msg pc T M g st ss rd (addGas k l)) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld l.gas ≤ bound) + {s : Evm .fusaka Nat} + (hs : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild l within = .ok s) + (hok : OkR s) : Q (addGas k s) := by + have he : l.error = none := by + have := hp.2.2.2.2.2.2.2.2.1 + simpa using this + exact RevertErr.SpecG.lowE (by decide) h hp (by rw [he]; simp) within hs hok + +/-- `reaches_low` from a frame of the code, for a run that ends with no error or reverts. -/ +theorem reaches_lowAt {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {T : List Word} + {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} {rd : ByteArray} + {hi z : Evm .fusaka Nat} (hr : Reaches (StepG .fusaka) hi z) (k : Nat) (low : Evm .fusaka Nat) + (e : hi = addGas k low) (hat : At code msg pc T M g st ss rd low) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld low.gas ≤ bound) + {s : Evm .fusaka Nat} + (hs : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild low within = .ok s) + (hok : OkR s) : ∃ m within', z = addGas k m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok s := by + rcases hok with h | h + · exact reaches_low hr k low e within hs h + · exact RevertErr.reaches_lowR (by decide) hr k low e + (by rw [hat.2.2.2.2.2.2.2.2.1]; simp) within hs h + +section Dyn + +variable {rd : ByteArray} + +/-- **MSTORE in a run that succeeds**: the frame had the gas for it and its growth of memory, and +the run goes on from the frame after it. -/ +theorem mstore_backR {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {o v : Word} + {T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {evm : Evm .fusaka Nat} (hat : At code msg pc (o :: v :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x52) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + 3 + (extendMemory M.size [(o, 32)]).cost ≤ g ∧ + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) T + (memoryWrite (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy) o.toNat + (wordBytes v)) + (g - (3 + (extendMemory M.size [(o, 32)]).cost)) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + by_cases hg : 3 + (extendMemory M.size [(o, 32)]).cost ≤ g + · obtain ⟨m, hr, hm⟩ := Logic.mstore (fork := .fusaka) hlt hbyte hg evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc (o :: v :: T) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .mstore := by + rw [hbyte] + exact ofByte_of_decode rfl (Fork.frontier_le _) + rw [step_of_instruction hlt decoded instruction_mstore, mstoreStep_cons hst] + have hc : GasMeter.charge e.gas (OPCODE_MSTORE_BASE + (extendMemory e.memory.size [(o, 32)]).cost) + = .error .outOfGas := by + rw [hgas, hmem, show OPCODE_MSTORE_BASE = 3 from rfl] + have hlt' : g < 3 + (extendMemory M.size [(o, 32)]).cost := Nat.lt_of_not_le hg + simp only [GasMeter.charge] + rw [ite_eq_left_of_eq_true _ _ (eq_true hlt')] + simp only [hc] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rcases hok with hok | hok <;> rw [hf.2.1] at hok <;> cases hok + +/-- **MLOAD in a run that succeeds**: the frame had the gas for it and its growth of memory, and +the run goes on from the frame after it. -/ +theorem mload_backR {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {o : Word} + {T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {evm : Evm .fusaka Nat} (hat : At code msg pc (o :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x51) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + 3 + (extendMemory M.size [(o, 32)]).cost ≤ g ∧ + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) + (loadWord (memoryReadBytes + (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy) o.toNat 32) 0 32 :: T) + (memoryExtend M (extendMemory M.size [(o, 32)]).expandBy) + (g - (3 + (extendMemory M.size [(o, 32)]).cost)) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + by_cases hg : 3 + (extendMemory M.size [(o, 32)]).cost ≤ g + · obtain ⟨m, hr, hm⟩ := Logic.mload (fork := .fusaka) hlt hbyte hg evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc (o :: T) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .mload := by + rw [hbyte] + exact ofByte_of_decode rfl (Fork.frontier_le _) + rw [step_of_instruction hlt decoded instruction_mload, mloadStep_cons hst] + have hc : GasMeter.charge e.gas (OPCODE_MLOAD_BASE + (extendMemory e.memory.size [(o, 32)]).cost) + = .error .outOfGas := by + rw [hgas, hmem, show OPCODE_MLOAD_BASE = 3 from rfl] + have hlt' : g < 3 + (extendMemory M.size [(o, 32)]).cost := Nat.lt_of_not_le hg + simp only [GasMeter.charge] + rw [ite_eq_left_of_eq_true _ _ (eq_true hlt')] + simp only [hc] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rcases hok with hok | hok <;> rw [hf.2.1] at hok <;> cases hok + +/-- **RETURN in a run that succeeds**: the frame had the gas for the growth of memory to its +range. -/ +theorem return_backR {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {o sz : Word} + {T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {rd : ByteArray} {evm : Evm .fusaka Nat} (hat : At code msg pc (o :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0xf3) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + (extendMemory M.size [(o, sz)]).cost ≤ g := by + refine Nat.le_of_not_lt fun hlt' => ?_ + have hspec : Spec .fusaka (At code msg pc (o :: sz :: T) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .«return» := by + rw [hbyte] + exact ofByte_of_decode rfl (Fork.frontier_le _) + rw [step_of_instruction hlt decoded instruction_return, returnStep_cons hst] + have hc : GasMeter.charge e.gas (extendMemory e.memory.size [(o, sz)]).cost = + .error .outOfGas := by + rw [hgas, hmem] + simp only [GasMeter.charge] + rw [ite_eq_left_of_eq_true _ _ (eq_true hlt')] + simp only [hc] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rcases hok with hok | hok <;> rw [hf.2.1] at hok <;> cases hok + +/-- **KECCAK256 in a run that succeeds**: the frame had the gas for the hash and the growth of +memory to its range, and the run goes on from the frame after it. -/ +theorem keccak_backR {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {o sz : Word} + {T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {evm : Evm .fusaka Nat} (hat : At code msg pc (o :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x20) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + keccak256Cost sz + (extendMemory M.size [(o, sz)]).cost ≤ g ∧ + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) + (keccak (memoryReadBytes (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + o.toNat sz.toNat) :: T) + (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + (g - (keccak256Cost sz + (extendMemory M.size [(o, sz)]).cost)) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + by_cases hg : keccak256Cost sz + (extendMemory M.size [(o, sz)]).cost ≤ g + · obtain ⟨m, hr, hm⟩ := Logic.keccak256 (fork := .fusaka) hlt hbyte hg evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc (o :: sz :: T) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .keccak256 := by + rw [hbyte] + exact ofByte_of_decode rfl (Fork.frontier_le _) + rw [step_of_instruction hlt decoded instruction_keccak256, keccak256Step_cons hst] + have hlt' : g < keccak256Cost sz + (extendMemory M.size [(o, sz)]).cost := Nat.lt_of_not_le hg + have hc : GasMeter.charge e.gas (keccak256Cost sz + + (extendMemory e.memory.size [(o, sz)]).cost) = .error .outOfGas := by + rw [hgas, hmem] + simp only [GasMeter.charge] + rw [ite_eq_left_of_eq_true _ _ (eq_true hlt')] + simp only [hc] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rcases hok with hok | hok <;> rw [hf.2.1] at hok <;> cases hok + +/-- **KECCAK256 of any range, in a run that succeeds**: with the budget below `2 ^ 300`, +SolarTV's growth agrees with EthLib's memory after it, the budget holds at the gas left, and the run +goes on. -/ +theorem keccak_dynR {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {o sz : Word} + {T : List Word} {M : ByteArray} {g G : Nat} {st : State.TransactionState} {ss : Substate} + {m0 : SolarTV.Machine.Mem} (hm : MemRel m0 M) (hb : MemBudget G M g) (hG : G < 2 ^ 300) + {evm : Evm .fusaka Nat} (hat : At code msg pc (o :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x20) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + MemRel (m0.expand o.toNat sz.toNat) (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) ∧ + MemBudget G (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + (g - (keccak256Cost sz + (extendMemory M.size [(o, sz)]).cost)) ∧ + At code msg (pc + 1) + (keccak (memoryReadBytes (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + o.toNat sz.toNat) :: T) + (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + (g - (keccak256Cost sz + (extendMemory M.size [(o, sz)]).cost)) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + obtain ⟨hg, m, within', hat', hrun'⟩ := keccak_backR hat hlt hbyte within hrun hok + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have hbound : sz = 0 ∨ (o.toNat + sz.toNat + 31) / 32 < 2 ^ 251 := by + by_cases hz : sz = 0 + · exact .inl hz + · exact .inr (words_lt_of_cost (budget_grow hmod hz hb hg).1 hG) + refine ⟨m, within', memRel_expandW hm hbound, ?_, hat', hrun'⟩ + exact MemBudget.grow hmod hb hg (size_memoryExtend M _) + +/-- **LOGn in a run that succeeds**: the frame had the gas for the log and the growth of memory +to its range, and the run goes on from the frame after it, with the log appended. -/ +theorem log_backR {n : Fin 5} {byte : UInt8} {code : ByteArray} {msg : Message .fusaka} {pc : Nat} + {o sz : Word} {words T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} + {ss : Substate} {evm : Evm .fusaka Nat} + (hat : At code msg pc (o :: sz :: (words ++ T)) M g st ss rd evm) + (hlen : words.length = n.val) (hlt : pc < code.size) (hbyte : code[pc] = byte) + (decoded : Op.decode byte = some (.log n)) (hstatic : msg.isStatic = false) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + logCost n.val sz + (extendMemory M.size [(o, sz)]).cost ≤ g ∧ + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) T (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + (g - (logCost n.val sz + (extendMemory M.size [(o, sz)]).cost)) st + { ss with + logs := ss.logs.push + { address := msg.currentTarget + topics := words.map U256.toBeBytes + data := memoryReadBytes (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + o.toNat sz.toNat } } rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + by_cases hg : logCost n.val sz + (extendMemory M.size [(o, sz)]).cost ≤ g + · obtain ⟨m, hr, hm⟩ := Logic.log (fork := .fusaka) hlen hlt hbyte decoded hstatic hg evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc (o :: sz :: (words ++ T)) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + have dec' : Op.ofByte .fusaka e.code[e.pc] = some (.log n) := by + rw [hbyte] + exact ofByte_of_decode decoded (Fork.frontier_le _) + rw [step_of_instruction hlt dec' (instruction_log n)] + have hl := e.stack.property + rw [hst] at hl + have hlr : (words ++ T).length ≤ STACK_LIMIT := by simp at hl ⊢; omega + have hs : e.stack = ⟨o :: sz :: (words ++ T), hst ▸ e.stack.property⟩ := Subtype.ext hst + have htop := popTopics_append (evm := { e with stack := ⟨words ++ T, hlr⟩ }) + (words := words) (rest := T) rfl + rw [hlen] at htop + have hlt' : e.gas < logCost n.val sz + (extendMemory e.memory.size [(o, sz)]).cost := by + rw [hgas, hmem] + omega + simp only [logStep, popWord, Stack.pop, hs, bind, Except.bind, pure, Except.pure] + rw [htop] + simp only [chargeGasAndMemory, chargeGas, GasMeter.charge, logCost] at hlt' ⊢ + simp [hlt'] + try rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rcases hok with hok | hok <;> rw [hf.2.1] at hok <;> cases hok + +/-- **LOGn of any range, in a run that succeeds**: with the budget below `2 ^ 300`, SolarTV's +growth agrees with EthLib's memory after it, the budget holds at the gas left, and the run goes on +with the log appended. -/ +theorem log_dynR {n : Fin 5} {byte : UInt8} {code : ByteArray} {msg : Message .fusaka} {pc : Nat} + {o sz : Word} {words T : List Word} {M : ByteArray} {g G : Nat} {st : State.TransactionState} + {ss : Substate} {m0 : SolarTV.Machine.Mem} (hm : MemRel m0 M) (hb : MemBudget G M g) + (hG : G < 2 ^ 300) {evm : Evm .fusaka Nat} + (hat : At code msg pc (o :: sz :: (words ++ T)) M g st ss rd evm) + (hlen : words.length = n.val) (hlt : pc < code.size) (hbyte : code[pc] = byte) + (decoded : Op.decode byte = some (.log n)) (hstatic : msg.isStatic = false) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + MemRel (m0.expand o.toNat sz.toNat) (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) ∧ + MemBudget G (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + (g - (logCost n.val sz + (extendMemory M.size [(o, sz)]).cost)) ∧ + At code msg (pc + 1) T (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + (g - (logCost n.val sz + (extendMemory M.size [(o, sz)]).cost)) st + { ss with + logs := ss.logs.push + { address := msg.currentTarget + topics := words.map U256.toBeBytes + data := memoryReadBytes (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) + o.toNat sz.toNat } } rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + obtain ⟨hg, m, within', hat', hrun'⟩ := log_backR hat hlen hlt hbyte decoded hstatic within hrun hok + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have hbound : sz = 0 ∨ (o.toNat + sz.toNat + 31) / 32 < 2 ^ 251 := by + by_cases hz : sz = 0 + · exact .inl hz + · exact .inr (words_lt_of_cost (budget_grow hmod hz hb hg).1 hG) + exact ⟨m, within', memRel_expandW hm hbound, MemBudget.grow hmod hb hg (size_memoryExtend M _), + hat', hrun'⟩ + +/-- **MSTORE at any offset, in a run that succeeds**: with the budget below `2 ^ 300`, SolarTV's +store agrees with EthLib's memory after it, the budget holds at the gas left, and the run goes on. -/ +theorem mstore_dynR {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {o v : Word} + {T : List Word} {M : ByteArray} {g G : Nat} {st : State.TransactionState} {ss : Substate} + {m0 : SolarTV.Machine.Mem} (hm : MemRel m0 M) (hb : MemBudget G M g) (hG : G < 2 ^ 300) + {evm : Evm .fusaka Nat} (hat : At code msg pc (o :: v :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x52) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + ∃ (M' : ByteArray) (g' : Nat) (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + MemRel (m0.store o.toNat v) M' ∧ MemBudget G M' g' ∧ g' ≤ g ∧ + At code msg (pc + 1) T M' g' st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + obtain ⟨hg, m, within', hat', hrun'⟩ := mstore_backR hat hlt hbyte within hrun hok + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + obtain ⟨hc, hb'⟩ := budget_grow (pre := 3) hmod (o := o) (sz := 32) (by decide) hb hg + have h32 : (32 : Word).toNat = 32 := rfl + rw [h32] at hc + have hw := words_lt_of_cost hc hG + obtain ⟨hmem', -⟩ := memRel_storeW (v := v) hm hw + refine ⟨_, _, m, within', hmem', ?_, by omega, hat', hrun'⟩ + unfold MemBudget + rw [size_memoryWrite_of_fit, size_memoryExtend] + · exact hb' + · intro _ + rw [size_wordBytes, size_memoryExtend_extendMemory' hmod (by decide), h32] + have := le_ceil32 (o.toNat + 32) + omega + +/-- **MLOAD at any offset, in a run that succeeds**: EthLib pushes SolarTV's load, SolarTV's growth +agrees with EthLib's memory after it, the budget holds at the gas left, and the run goes on. -/ +theorem mload_dynR {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {o : Word} + {T : List Word} {M : ByteArray} {g G : Nat} {st : State.TransactionState} {ss : Substate} + {m0 : SolarTV.Machine.Mem} (hm : MemRel m0 M) (hb : MemBudget G M g) (hG : G < 2 ^ 300) + {evm : Evm .fusaka Nat} (hat : At code msg pc (o :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x51) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + ∃ (M' : ByteArray) (g' : Nat) (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + MemRel (m0.expand o.toNat 32) M' ∧ MemBudget G M' g' ∧ g' ≤ g ∧ + At code msg (pc + 1) (m0.load o.toNat :: T) M' g' st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + obtain ⟨hg, m, within', hat', hrun'⟩ := mload_backR hat hlt hbyte within hrun hok + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + obtain ⟨hc, hb'⟩ := budget_grow (pre := 3) hmod (o := o) (sz := 32) (by decide) hb hg + have h32 : (32 : Word).toNat = 32 := rfl + rw [h32] at hc + have hw := words_lt_of_cost hc hG + have hmem' := memRel_expandW (o := o) (sz := 32) hm (.inr (by rw [h32]; exact hw)) + rw [h32] at hmem' + rw [load_eq hm] at hat' + refine ⟨_, _, m, within', hmem', ?_, by omega, hat', hrun'⟩ + unfold MemBudget + rw [size_memoryExtend] + exact hb' + +/-- **CALLDATACOPY in a run that succeeds**: the frame had the gas for the copy and the growth of +memory, and the run goes on from the frame after it. -/ +theorem cdc_backR {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {d off sz : Word} + {T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {evm : Evm .fusaka Nat} (hat : At code msg pc (d :: off :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x37) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + 3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost ≤ g ∧ + ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) T + (memoryWrite (memoryExtend M (extendMemory M.size [(d, sz)]).expandBy) + d.toNat ⟨(bufferRead msg.data off.toNat sz.toNat).toArray⟩) + (g - (3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost)) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + by_cases hg : 3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost ≤ g + · obtain ⟨m, hr, hm⟩ := Logic.calldatacopy (fork := .fusaka) hlt hbyte hg evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc (d :: off :: sz :: T) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .calldatacopy := by + rw [hbyte] + exact ofByte_of_decode rfl (Fork.frontier_le _) + rw [step_of_instruction hlt decoded instruction_calldatacopy] + rw [copyToMemory_cons hst] + have hlt' : g < 3 + 3 * wordCount sz.toNat + (extendMemory M.size [(d, sz)]).cost := + Nat.lt_of_not_le hg + have hc : GasMeter.charge e.gas (OPCODE_CALLDATACOPY_BASE + OPCODE_COPY_PER_WORD * + wordCount sz.toNat + (extendMemory e.memory.size [(d, sz)]).cost) = .error .outOfGas := by + rw [hgas, hmem, show OPCODE_CALLDATACOPY_BASE = 3 from rfl, + show OPCODE_COPY_PER_WORD = 3 from rfl] + simp only [GasMeter.charge] + rw [ite_eq_left_of_eq_true _ _ (eq_true hlt')] + simp only [hc] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rcases hok with hok | hok <;> rw [hf.2.1] at hok <;> cases hok + +/-- **CALLDATACOPY of any range, in a run that succeeds**: with the budget below `2 ^ 300`, +SolarTV's copy agrees with EthLib's memory after it, the budget holds at the gas left, and the run +goes on. -/ +theorem cdc_dynR {code : ByteArray} {msg : Message .fusaka} {call : Call} (hdata : msg.data = call.calldata) + {pc : Nat} {d off sz : Word} {T : List Word} {M : ByteArray} {g G : Nat} + {st : State.TransactionState} {ss : Substate} {m0 : SolarTV.Machine.Mem} (hm : MemRel m0 M) + (hb : MemBudget G M g) (hG : G < 2 ^ 300) {evm : Evm .fusaka Nat} + (hat : At code msg pc (d :: off :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0x37) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + ∃ (M' : ByteArray) (g' : Nat) (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + MemRel (m0.write d.toNat sz.toNat (fun i => calldataByte call (off.toNat + i))) M' ∧ + MemBudget G M' g' ∧ g' ≤ g ∧ At code msg (pc + 1) T M' g' st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + obtain ⟨hg, m, within', hat', hrun'⟩ := cdc_backR hat hlt hbyte within hrun hok + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have hbound : sz = 0 ∨ (d.toNat + sz.toNat + 31) / 32 < 2 ^ 251 := by + by_cases hz : sz = 0 + · exact .inl hz + · exact .inr (words_lt_of_cost (budget_grow hmod hz hb hg).1 hG) + have hfit : sz.toNat ≠ 0 → + d.toNat + sz.toNat ≤ (memoryExtend M (extendMemory M.size [(d, sz)]).expandBy).size := by + intro hz + have hz' : sz ≠ 0 := fun h => hz (by simp [h]) + rw [size_memoryExtend_extendMemory' hmod hz'] + have := le_ceil32 (d.toNat + sz.toNat) + omega + refine ⟨_, _, m, within', ?_, ?_, by omega, hat', hrun'⟩ + · have he := memRel_expandW hm hbound + rw [← write_expand] + refine memRel_write he hfit (size_bufferRead _ _ _) (fun i hi => ?_) + rw [byteAt_bufferRead, ite_cond_eq_true _ _ (eq_true hi), hdata, calldataByte_eq] + · refine MemBudget.grow hmod hb hg ?_ + rw [size_memoryWrite_of_fit, size_memoryExtend] + intro h + rw [size_bufferRead] at h ⊢ + exact hfit h + + +/-- **REVERT in a run that ends with no error or reverts**: the frame had the gas for the growth of +memory to its range. -/ +theorem revert_backR {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {o sz : Word} + {T : List Word} {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} + {rd : ByteArray} {evm : Evm .fusaka Nat} (hat : At code msg pc (o :: sz :: T) M g st ss rd evm) + (hlt : pc < code.size) (hbyte : code[pc] = 0xfd) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + (extendMemory M.size [(o, sz)]).cost ≤ g := by + refine Nat.le_of_not_lt fun hlt' => ?_ + have hspec : Spec .fusaka (At code msg pc (o :: sz :: T) M g st ss rd) + (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, hmem, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .revert := by + rw [hbyte] + exact ofByte_of_decode rfl (by decide) + rw [step_of_instruction hlt decoded (instruction_revert (by decide)), revertStep_eq, + returnStep_cons hst] + have hc : GasMeter.charge e.gas (extendMemory e.memory.size [(o, sz)]).cost = + .error .outOfGas := by + rw [hgas, hmem] + simp only [GasMeter.charge] + rw [ite_eq_left_of_eq_true _ _ (eq_true hlt')] + simp only [hc] + rfl + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rcases hok with hok | hok <;> rw [hf.2.1] at hok <;> cases hok + +end Dyn + +/-- **GAS in a run that succeeds**: the frame had the gas for it, and the run goes on from the frame +after it, with the gas left after its price pushed. -/ +theorem gas_backR {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {T : List Word} + {M : ByteArray} {g : Nat} {st : State.TransactionState} {ss : Substate} {rd : ByteArray} + {evm : Evm .fusaka Nat} (hat : At code msg pc T M g st ss rd evm) (hlt : pc < code.size) + (hbyte : code[pc] = 0x5a) (hstack : T.length < STACK_LIMIT) {bound : Nat} + {runChild : MessageRunner .fusaka Nat bound} (within : GasMeter.gasHeld evm.gas ≤ bound) + {fin : Evm .fusaka Nat} + (hrun : runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin) + (hok : OkR fin) : + 2 ≤ g ∧ ∃ (m : Evm .fusaka Nat) (within' : GasMeter.gasHeld m.gas ≤ bound), + At code msg (pc + 1) (BitVec.ofNat 256 (g - 2) :: T) M (g - 2) st ss rd m ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m within' = .ok fin := by + by_cases hg : 2 ≤ g + · obtain ⟨m, hr, hm⟩ := Logic.gas_rule (fork := .fusaka) hlt hbyte hg hstack evm hat + have := runFrame_eq_of_reaches (runChild := runChild) Step.gasHeld_le Step.runFrame_eq hr within + rw [this] at hrun + exact ⟨hg, m, _, hm, hrun⟩ + · exfalso + have hspec : Spec .fusaka (At code msg pc T M g st ss rd) (Faulted .outOfGas st ss) := by + refine At.fault rfl fun e hat' => ?_ + obtain ⟨hcode, -, -, hpc, hst, -, hgas, -⟩ := hat' + subst hcode hpc + have decoded : Op.ofByte .fusaka e.code[e.pc] = some .gas := by + rw [hbyte] + exact ofByte_of_decode rfl (Fork.frontier_le _) + rw [step_of_instruction hlt decoded rfl] + simp [readFrame, chargeGas, GasMeter.charge, hgas, OPCODE_GAS, BASE, show g < 2 by omega, bind, Except.bind] + obtain ⟨z, hr, hstop, hf⟩ := hspec evm hat + rw [runFrame_of_reaches hr hstop within] at hrun + cases hrun + rcases hok with hok | hok <;> rw [hf.2.1] at hok <;> cases hok + +/-- **The rest of a block from an instruction, read back from a run that succeeds**: the segments +up to each GAS with gas to spare, moved back to the frame's gas, and each GAS at the frame's gas, +its gas added to the table. Every extension of the table it ends with runs the rest of the block to +the same end: a halt the frame shows, or the next block, related to a frame the run goes on from. -/ +theorem segR {p : Assemble.Program} {c : Cert} {mx : List Nat} {code : ByteArray} + (G : GlobT p c code) (hnc : c.calls = false) {call : Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : msg.txEnv = Target.txEnv) + {b : Nat} (hb : b < p.blocks.length) {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + {fin : Evm .fusaka Nat} (hok : OkR fin) {G0 : Nat} (hG0 : G0 < 2 ^ 256) + {rd : ByteArray} : + ∀ (n : Nat) (is : List Assemble.Instr) (h : Nat) (known : Known) (ty : List Ty) (k : Nat) + (S Tw : List Word) (s : State) (pc : Nat) (M : ByteArray) (g : Nat) + (st : State.TransactionState) (ss : Substate) (T : RunTable) (evm : Evm .fusaka Nat) + (within : GasMeter.gasHeld evm.gas ≤ bound), + is.length < n → blockOkC p c mx b h known ty k is = true → h ≤ S.length → + S.length + c.need b ≤ h + maxH mx b → KR known S → SR c ty S Tw → + Seg (bytesOf code) c.offset pc + (lowerInstrs p c b is ++ lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) code.size → + S.length + k ≤ 1000 → M.size ≤ c.top → MemRel s.memory M → Rel msg ss0 st ss s → + At code msg pc Tw M g st ss rd evm → T.gases.length = gasReads s.world → + sent s.world = 0 → MemBudget G0 M g → + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + ∃ T' r, T.Le T' ∧ + (∀ T'', T'.Le T'' → SolarTV.EVM.Program.exec (O T'') call b is S s = r) ∧ + (∀ res, r = .inl res → PostL call msg.currentTarget ss0 res.2 res.1 fin) ∧ + (∀ y, r = .inr y → (y.1 ≤ p.blocks.length ∧ + (y.1 < p.blocks.length → c.need y.1 ≤ y.2.1.length ∧ y.2.1.length ≤ maxH mx y.1) ∧ + (y.1 = b + 1 ∨ isTarget p c y.1 = true)) ∧ + ∃ (after : Evm .fusaka Nat) (within' : GasMeter.gasHeld after.gas ≤ bound), + EntC p c mx code msg ss0 y after ∧ T'.gases.length = gasReads y.2.2.world ∧ + sent y.2.2.world = 0 ∧ after.gas ≤ g ∧ + memoryGasCost after.memory.size + after.gas ≤ G0 ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild after within' = .ok fin) + | 0, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, hn, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ => absurd hn (Nat.not_lt_zero _) + | n + 1, is, h, known, ty, k, S, Tw, s, pc, M, g, st, ss, T, evm, within, hn, hokC, hh, hu, hk, + hR, hseg, hstk, htop, hmem, R, hat, hTg, hs0, hB, hrun => by + have hge : evm.gas = g := hat.2.2.2.2.2.2.1 + -- The segment with gas to spare for it alone: `K` more than the frame holds. + generalize hK : 22100 * k + memoryGasCost c.top = K + have hp := hat.addGas K + have I : InvL c code call (lowerInstrs p c b is ++ lowerFrom p c (b + 1) + (p.blocks.drop (b + 1))) k 0 pc S s M (g + K) := + ⟨hseg, hstk, by simp only [Nat.add_zero]; omega, htop, hmem⟩ + have hsim := exec_simC (mx := mx) G (o := O T) hdata hvalue hstatic hself hcaller + (O_ok c T).1 hbenv htx (O_ok c T).2 b hb 0 (G0 + K) rd is h known ty S Tw k s pc M + (g + K) st ss hokC hh hu hk hR I R (by unfold MemBudget at *; omega) + have hcnt := (execC_agree (Agree.refl (O T) (gasReads s.world) (sent s.world)) call b is S s + le_rfl le_rfl).2 + have hex : ∀ T'', T.Le T'' → SolarTV.EVM.Program.exec (O T'') call b is S s = + match execC (O T) call b is S s with + | .done r => r + | .cut i rest S' s' => SolarTV.EVM.Program.exec (O T'') call b (i :: rest) S' s' := + fun T'' hle => exec_O hle (by omega) hs0 + generalize hr : execC (O T) call b is S s = r at hsim hcnt hex + cases r with + | done r => + refine ⟨T, r, RunTable.Le.refl T, fun T'' hle => hex T'' hle, fun res hres => ?_, + fun y hy => ?_⟩ + · subst hres + exact lowAt hsim hp within hrun hok + · subst hy + obtain ⟨t, S', s'⟩ := y + obtain ⟨⟨htle, hneedt, hj⟩, pc', T', M', g', st', ss', hh', hR', E', R', hB'⟩ := hsim + obtain ⟨e1, r1, he1⟩ := hh' _ hp + obtain ⟨m, within', hz, hrm⟩ := reaches_lowAt r1 K evm rfl hat within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hmK⟩ := at_of_addGasR he1 + have hgm := reaches_gas_le r1 + rw [hz] at hgm + simp only [gas_addGas] at hgm + have hc1 := hcnt.1 s' rfl + refine ⟨⟨htle, hneedt, hj⟩, m, within', ⟨T', pc', M', st', ss', rd, htle, hneedt, hR', E'.seg, + E'.le_top, E'.mem, R', hatm⟩, ?_, ?_, by omega, + by rw [hatm.2.2.2.2.2.1]; unfold MemBudget at hB'; omega, hrm⟩ + · dsimp only; omega + · dsimp only; omega + | cut i rest S' s' => + obtain ⟨hci, h', known', ty', k', pc', T', M', g', st', ss', hh', hok2, hh2, hu2, hk2, hR', + I', R', hB'⟩ := hsim + -- The segment, moved back to the frame's gas. + obtain ⟨e1, r1, he1⟩ := hh' _ hp + obtain ⟨m, within1, hz, hrm⟩ := reaches_lowAt r1 K evm rfl hat within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hmK⟩ := at_of_addGasR he1 + have hgm := reaches_gas_le r1 + rw [hz] at hgm + simp only [gas_addGas] at hgm + have hL := hR'.length + have hst := I'.stack + have hc1 := hcnt.1 s' rfl + have hlen := hcnt.2 _ rest S' s' rfl + have hmB : MemBudget G0 M' m.gas := by unfold MemBudget at *; omega + have hci' : isGasI i = true ∨ isLoadI i = true ∨ isStoreI i = true ∨ isRetI i = true ∨ + isRevI i = true ∨ isKecI i = true ∨ isLogI i = true ∨ isCdcI i = true ∨ isScI i = true ∨ + isRdsI i = true ∨ isRdcI i = true ∨ isCallI i = true ∨ isC2I i = true ∨ isCcI i = true := by + simpa [isCutI, isMemCutI, or_assoc] using hci + rcases hci' with hgi | hli | hsi | hri | hvi | hki | hlgi | hcdi | hsci | hrdi | hrdci | hcalli | + hc2i | hcci + · obtain rfl := isGasI_eq hgi + obtain ⟨hk1, hok3⟩ := blockOkC_gas hok2 + have hs := I'.seg + rw [lowerInstrs_gas, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + -- GAS at the frame's gas. + obtain ⟨h2, m2, within2, hat2, hrun2⟩ := + gas_backR hatm hlt hcode (by unfold STACK_LIMIT; omega) within1 hrm hok + let T1 : RunTable := { T with gases := T.gases ++ [m.gas - 2] } + have hle1 : T.Le T1 := ⟨List.prefix_refl _, List.prefix_refl _, List.prefix_refl _, + List.prefix_refl _, List.prefix_append _ _⟩ + have hv : ∀ T'', T1.Le T'' → T''.gases.getD (gasReads s'.world) 0 = m.gas - 2 := by + intro T'' hle + rw [getD_of_prefix hle.2.2.2.2 (by simp [T1]; omega)] + simp [T1, List.getD_eq_getElem?_getD, hc1.1, ← hTg] + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segR (G0 := G0) G hnc hdata hvalue hstatic hself hcaller hbenv + htx hb hok hG0 n rest (h' + 1) [] (some false :: ty') (k' - 1) + (BitVec.ofNat 256 (m.gas - 2) :: S') (BitVec.ofNat 256 (m.gas - 2) :: T') + { s' with world := s'.world ++ [.read "gas"] } (pc' + 1) M' (m.gas - 2) st' ss' T1 m2 + within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl hR') hseg' (by simp; omega) I'.le_top + I'.mem ⟨R'.storage, R'.account, logsRel_read _ R'.logs⟩ hat2 + (by simp [T1]; omega) (by simp [hc1.2, hs0]) + (by unfold MemBudget at *; omega) hrun2 + refine ⟨T2, r, hle1.trans hle2, fun T'' hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T'' (hle1.trans (hle2.trans hle))] + show SolarTV.EVM.Program.exec (O T'') call b (.effect .gas 0 :: rest) S' s' = r + rw [exec_gas (hv T'' (hle2.trans hle)) (by omega)] + exact hex2 T'' hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, by omega, hbud, hra⟩ + + · -- MLOAD at the frame's gas, at any offset. + obtain rfl := isLoadI_eq hli + obtain ⟨hk1, hh1, hdat, htop', hok3⟩ := blockOkC_load hok2 + have hs := I'.seg + rw [lowerInstrs_load, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, S''⟩ + · simp at hh2; omega + rcases T' with _ | ⟨x', Tr⟩ + · simp at hL + obtain rfl := (SR.head hR' hdat).symm + have hR'' := (SR.uncons.1 hR').2 + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + mload_dynR I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segR (G0 := G0) G hnc hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 n rest h' [] (some false :: ty'.drop 1) (k' - 1) + (s'.memory.load x.toNat :: S'') (s'.memory.load x.toNat :: Tr) + { s' with memory := s'.memory.expand x.toNat 32 } (pc' + 1) M2 g2 st' ss' T m2 + within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl (by simpa using hR'')) hseg' + (by simp; omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by show T.gases.length = gasReads s'.world; rw [hc1.1]; exact hTg) + (by show sent s'.world = 0; rw [hc1.2]; exact hs0) hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (O T3) call b (.op .load :: rest) _ s' = r + rw [exec_loadC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, by omega, hbud, hra⟩ + · -- MSTORE at the frame's gas, at any offset. + obtain rfl := isStoreI_eq hsi + obtain ⟨hk1, hh1, hdat, htop', hok3⟩ := blockOkC_store hok2 + have hs := I'.seg + rw [lowerInstrs_store, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 2) S'' Tr := by simpa using SR.drop 2 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + mstore_dynR I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segR (G0 := G0) G hnc hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 n rest (h' - 2) [] (ty'.drop 2) (k' - 1) S'' Tr + { s' with memory := s'.memory.store x.toNat y } (pc' + 1) M2 g2 st' ss' T m2 + within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by show T.gases.length = gasReads s'.world; rw [hc1.1]; exact hTg) + (by show sent s'.world = 0; rw [hc1.2]; exact hs0) hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (O T3) call b (.op .store :: rest) _ s' = r + rw [exec_storeC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, by omega, hbud, hra⟩ + + · -- RETURN at the frame's gas, from any range. + obtain rfl := isRetI_eq hri + obtain ⟨hh1, hdat⟩ := blockOkC_ret hok2 + have hs := I'.seg + rw [lowerInstrs_ret, List.cons_append] at hs + obtain ⟨next, hd, -⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hg := return_backR hatm hlt hcode within1 hrm hok + refine ⟨T, .inl (SolarTV.EVM.Program.output s' (x :: y :: S'') false), RunTable.Le.refl T, + fun T3 hle => ?_, fun res hres => ?_, fun y hy => ?_⟩ + · rw [hex T3 hle] + rfl + · obtain rfl := Sum.inl.inj hres + simp only [SolarTV.EVM.Program.output, Bool.false_eq_true, ↓reduceIte] + exact lowAt (SpecG.consequence (return_postSG (ss := ss') hlt hcode (by omega) rfl + (by rw [read_eq I'.mem]; rfl) rfl (R'.slot hself)) (fun _ h => h) + (fun _ h => ⟨ss', h, R'.logs⟩)) (hatm.addGas 0) within1 hrm hok + · cases hy + · -- REVERT at the frame's gas, from any range: the program's revert, with its data. + obtain rfl := isRevI_eq hvi + obtain ⟨hh1, hdat⟩ := blockOkC_revert hok2 + have hs := I'.seg + rw [lowerInstrs_revert, List.cons_append] at hs + obtain ⟨next, hd, -⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hg := revert_backR hatm hlt hcode within1 hrm hok + refine ⟨T, .inl (SolarTV.EVM.Program.output s' (x :: y :: S'') true), RunTable.Le.refl T, + fun T3 hle => ?_, fun res hres => ?_, fun y hy => ?_⟩ + · rw [hex T3 hle] + rfl + · obtain rfl := Sum.inl.inj hres + simp only [SolarTV.EVM.Program.output, ↓reduceIte] + exact lowAt (SpecG.consequence (revert_postSG (ss := ss') (by decide) hlt hcode (by omega) + rfl (by rw [read_eq I'.mem]; rfl) rfl) (fun _ h => h) + (fun _ h => ⟨ss', h, R'.logs⟩)) (hatm.addGas 0) within1 hrm hok + · cases hy + + · -- KECCAK256 at the frame's gas, of any range. + obtain rfl := isKecI_eq hki + obtain ⟨henv, hk1, hh1, hdat, htop', hok3⟩ := blockOkC_kec hok2 + have hs := I'.seg + rw [lowerInstrs_kec, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S''⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', Tr⟩⟩ + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 2) S'' Tr := by simpa using SR.drop 2 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨m2, within2, hmem2, hb2, hat2, hrun2⟩ := + keccak_dynR I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + obtain ⟨-, hkec⟩ := (O_ok c T).1 henv + rw [byteArray_eq_of_map (read_eq I'.mem), ← hkec] at hat2 + have hsz : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size ≤ c.top := by + have hmod : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size % 32 = 0 := by + rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segR (G0 := G0) G hnc hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 n rest (h' - 1) [] (some false :: ty'.drop 2) (k' - 1) + ((O T).keccak ((s'.memory.expand x.toNat y.toNat).read x.toNat y.toNat) :: S'') + ((O T).keccak ((s'.memory.expand x.toNat y.toNat).read x.toNat y.toNat) :: Tr) + { s' with memory := s'.memory.expand x.toNat y.toNat } (pc' + 1) _ _ st' ss' T m2 + within2 (by omega) hok3 (by simp; omega) (by simp; omega) + (KR.nil _) (SR.cons (τ := some false) rfl (by simpa using hR'')) hseg' + (by simp; omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by show T.gases.length = gasReads s'.world; rw [hc1.1]; exact hTg) + (by show sent s'.world = 0; rw [hc1.2]; exact hs0) hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (O T3) call b (.effect .keccak256 2 :: rest) _ s' = r + rw [exec_keccakC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, by omega, hbud, hra⟩ + + · -- LOGn at the frame's gas, of any range. + obtain ⟨nl, hn4, rfl⟩ := isLogI_eq hlgi + obtain ⟨hk1, hnh, hdat, htop', hok3⟩ := blockOkC_log hn4 hok2 + have hs := I'.seg + rw [lowerInstrs_log p c b hn4, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, S1⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', T1⟩⟩ + · simp at hL + · simp at hL + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨tops, S2, rfl, hlen⟩ : ∃ tops S2, S1 = tops ++ S2 ∧ tops.length = nl := + ⟨S1.take nl, S1.drop nl, (List.take_append_drop nl S1).symm, by simp; omega⟩ + obtain ⟨tops', T2, rfl, hlen'⟩ : ∃ tops' T2, T1 = tops' ++ T2 ∧ tops'.length = nl := + ⟨T1.take nl, T1.drop nl, (List.take_append_drop nl T1).symm, by simp; omega⟩ + subst hlen + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.cons.injEq, List.take_left' hlen', + List.take_left' rfl] at htake + obtain ⟨rfl, rfl, rfl⟩ := htake + have hR'' : SR c (ty'.drop (tops.length + 2)) S2 T2 := by + simpa using SR.drop (tops.length + 2) hR' + simp only [List.length_append] at hL hst hh2 hu2 + obtain ⟨m2, within2, hmem2, hb2, hat2, hrun2⟩ := + log_dynR (n := ⟨tops.length, by omega⟩) I'.mem hmB (by omega) hatm rfl hlt hcode + (decode_log ⟨tops.length, by omega⟩) hstatic within1 hrm hok + have hsz : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size ≤ c.top := by + have hmod : (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy).size % 32 = 0 := by + rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨L, hL1, hL2⟩ := R'.logs + obtain ⟨T2', r, hle2, hex2, hpost, hnext⟩ := segR (G0 := G0) (ss0 := ss0) G hnc hdata hvalue hstatic hself + hcaller hbenv htx hb hok hG0 n rest (h' - (tops.length + 2)) [] (ty'.drop (tops.length + 2)) + (k' - 1) S2 T2 + ⟨s'.memory.expand x.toNat y.toNat, s'.storage, s'.transient, + s'.world ++ [.log tops ((s'.memory.expand x.toNat y.toNat).read x.toNat y.toNat)]⟩ + (pc' + 1) _ _ st' { ss' with logs := ss'.logs.push ⟨msg.currentTarget, + tops.map U256.toBeBytes, memoryReadBytes (memoryExtend M' (extendMemory M'.size + [(x, y)]).expandBy) x.toNat y.toNat⟩ } T m2 within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 + ⟨R'.storage, R'.account, ⟨L ++ [⟨msg.currentTarget, tops.map U256.toBeBytes, + memoryReadBytes (memoryExtend M' (extendMemory M'.size [(x, y)]).expandBy) + x.toNat y.toNat⟩], by simp [Array.toList_push, hL1], + filter_snoc_log ▸ forall₂_snoc hL2 ⟨rfl, rfl, read_eq I'.mem⟩⟩⟩ hat2 + (by show T.gases.length = gasReads (s'.world ++ [_]); rw [AssembleCut.gasReads_log, hc1.1]; exact hTg) + (by show sent (s'.world ++ [_]) = 0; rw [AssembleCut.sent_log, hc1.2]; exact hs0) hb2 hrun2 + refine ⟨T2', r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (O T3) call b + (.effect (.log tops.length) (tops.length + 2) :: rest) _ s' = r + rw [exec_logC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, by omega, hbud, hra⟩ + + · -- CALLDATACOPY at the frame's gas, of any range. + obtain rfl := isCdcI_eq hcdi + obtain ⟨hk1, hh1, hdat, htop', hok3⟩ := blockOkC_cdc hok2 + have hs := I'.seg + rw [lowerInstrs_cdc, List.cons_append] at hs + obtain ⟨next, hd, hseg'⟩ := hs.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rcases S' with _ | ⟨x, _ | ⟨y, _ | ⟨z, S''⟩⟩⟩ + · simp at hh2; omega + · simp at hh2; omega + · simp at hh2; omega + rcases T' with _ | ⟨x', _ | ⟨y', _ | ⟨z', Tr⟩⟩⟩ + · simp at hL + · simp at hL + · simp at hL + have htake := hR'.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, rfl, -⟩ := htake + have hR'' : SR c (ty'.drop 3) S'' Tr := by simpa using SR.drop 3 hR' + simp only [List.length_cons] at hL hst hh2 hu2 + obtain ⟨M2, g2, m2, within2, hmem2, hb2, hg2, hat2, hrun2⟩ := + cdc_dynR hdata I'.mem hmB (by omega) hatm hlt hcode within1 hrm hok + have hsz : M2.size ≤ c.top := by + have hmod : M2.size % 32 = 0 := by rw [hmem2.1]; omega + have := size_le_of_cost (B := G0) (by unfold MemBudget at hb2; omega) hG0 hmod + omega + obtain ⟨T2, r, hle2, hex2, hpost, hnext⟩ := segR (G0 := G0) (ss0 := ss0) G hnc hdata hvalue + hstatic hself hcaller hbenv htx hb hok hG0 n rest (h' - 3) [] (ty'.drop 3) (k' - 1) S'' Tr + { s' with + memory := s'.memory.write x.toNat z.toNat + (fun i => SolarTV.Machine.calldataByte call (y.toNat + i)) } (pc' + 1) M2 g2 st' ss' T m2 + within2 (by omega) hok3 (by omega) (by omega) + (KR.nil _) hR'' hseg' (by omega) hsz hmem2 ⟨R'.storage, R'.account, R'.logs⟩ hat2 + (by show T.gases.length = gasReads s'.world; rw [hc1.1]; exact hTg) + (by show sent s'.world = 0; rw [hc1.2]; exact hs0) hb2 hrun2 + refine ⟨T2, r, hle2, fun T3 hle => ?_, hpost, fun y hy => ?_⟩ + · rw [hex T3 (hle2.trans hle)] + show SolarTV.EVM.Program.exec (O T3) call b (.effect .calldatacopy 3 :: rest) _ s' = r + rw [exec_cdcC (by omega)] + exact hex2 T3 hle + · obtain ⟨hy1, after, within', hE, hT, hsn, hga, hbud, hra⟩ := hnext y hy + exact ⟨hy1, after, within', hE, hT, hsn, by omega, hbud, hra⟩ + · -- STATICCALL: only a certificate that says the program makes calls lets the checker cut there. + obtain rfl := isScI_eq hsci + exact absurd (blockOkC_sc hok2).1 (by simp [hnc]) + · obtain rfl := isRdsI_eq hrdi + exact absurd (blockOkC_rds hok2).1 (by simp [hnc]) + · obtain rfl := isRdcI_eq hrdci + exact absurd (blockOkC_rdc hok2).1 (by simp [hnc]) + · -- CALL, CREATE2 and CODECOPY: only a certificate that says the program creates lets the + -- checker cut there. + obtain rfl := isCallI_eq hcalli + exact absurd (blockOkC_call hok2).1 (by simp [hnc]) + · obtain rfl := isC2I_eq hc2i + exact absurd (blockOkC_c2 hok2).1 (by simp [hnc]) + · obtain rfl := isCcI_eq hcci + exact absurd (blockOkC_cc hok2).1 (by simp [hnc]) + +/-- `AssembleRun.Advances` for a run that ends with no error or reverts. -/ +def AdvancesR {σ : Type} (blk : Oracle → σ → Option ((Halt × Machine.State) ⊕ σ)) + (O : RunTable → Oracle) (E : RunTable → σ → Evm .fusaka Nat → Prop) + (Post : Halt × Machine.State → Evm .fusaka Nat → Prop) (meas : σ → Evm .fusaka Nat → Nat) + (T : RunTable) (x : σ) (evm : Evm .fusaka Nat) : Prop := + ∀ (bound : Nat) (runChild : MessageRunner .fusaka Nat bound), Meets (fun _ _ _ => True) runChild → + ∀ (within : GasMeter.gasHeld evm.gas ≤ bound) (fin : Evm .fusaka Nat), + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + OkR fin → + ∃ T' r, T.Le T' ∧ (∀ T'', T'.Le T'' → blk (O T'') x = some r) ∧ + (∀ res, r = .inl res → Post res fin) ∧ + (∀ y, r = .inr y → ∃ after within', E T' y after ∧ meas y after < meas x evm ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild after within' = .ok fin) + +theorem AdvancesR.advances {σ : Type} {blk : Oracle → σ → Option ((Halt × Machine.State) ⊕ σ)} + {O : RunTable → Oracle} {E : RunTable → σ → Evm .fusaka Nat → Prop} + {Post : Halt × Machine.State → Evm .fusaka Nat → Prop} {meas : σ → Evm .fusaka Nat → Nat} + {T : RunTable} {x : σ} {evm : Evm .fusaka Nat} (h : AdvancesR blk O E Post meas T x evm) : + Advances blk O E Post meas T x evm := + fun bound runChild meets within fin hrun hok => h bound runChild meets within fin hrun (.inl hok) + +/-- `AssembleRun.run_of_advances` for a run that ends with no error or reverts. -/ +theorem run_of_advancesR {σ : Type} (blk : Oracle → σ → Option ((Halt × Machine.State) ⊕ σ)) + (O : RunTable → Oracle) {E : RunTable → σ → Evm .fusaka Nat → Prop} + {Post : Halt × Machine.State → Evm .fusaka Nat → Prop} {meas : σ → Evm .fusaka Nat → Nat} + (adv : ∀ T x evm, E T x evm → AdvancesR blk O E Post meas T x evm) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + (meets : Meets (fun _ _ _ => True) runChild) : + ∀ (n : Nat) (T : RunTable) (x : σ) (evm : Evm .fusaka Nat) + (within : GasMeter.gasHeld evm.gas ≤ bound) (fin : Evm .fusaka Nat), + E T x evm → meas x evm < n → + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + OkR fin → + ∃ T' res, T.Le T' ∧ + (∀ T'', T'.Le T'' → ∃ k, iterate (blk (O T'')) k x = some res) ∧ + Post res fin + | 0, _, _, _, _, _, _, h, _, _ => absurd h (Nat.not_lt_zero _) + | n + 1, T, x, evm, within, fin, hE, hm, hrun, hok => by + obtain ⟨T', r, hle, hstep, hinl, hinr⟩ := adv T x evm hE bound runChild meets within fin hrun hok + cases r with + | inl res => + exact ⟨T', res, hle, fun T'' h => ⟨1, by simp [iterate, hstep T'' h]⟩, hinl res rfl⟩ + | inr y => + obtain ⟨after, within', hE', hm', hrun'⟩ := hinr y rfl + obtain ⟨T2, res, hle2, hit, hpost⟩ := + run_of_advancesR blk O adv meets n T' y after within' fin hE' (by omega) hrun' hok + refine ⟨T2, res, hle.trans hle2, fun T'' h => ?_, hpost⟩ + obtain ⟨k, hk⟩ := hit T'' h + exact ⟨k + 1, by simp [iterate, hstep T'' (hle2.trans h), hk]⟩ + +/-- **A block of code with loops and GAS, read back from a run that succeeds.** -/ +theorem advances_checkCR {p : Assemble.Program} {c : Cert} {mx : List Nat} {code : ByteArray} + (G : GlobC p c mx code) (hnc : c.calls = false) {call : Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : msg.txEnv = Target.txEnv) + (hgas : msg.gas < 2 ^ 256) + (T0 : RunTable) (x : Nat × List Word × State) (evm : Evm .fusaka Nat) + (hE : EntT p c mx code msg ss0 T0 x evm) : + AdvancesR (fun o => SolarTV.EVM.Program.block o call p) O (EntT p c mx code msg ss0) + (fun res => PostL call msg.currentTarget ss0 res.2 res.1) + (fun y e => AssembleLoop.meas p c e.gas y.1) T0 x evm := by + intro bound runChild _ within fin hrun hok + obtain ⟨b, S, s⟩ := x + obtain ⟨⟨Tw, pc, M, st, ss, rd, hle, hneed, hR, hseg, htop, hmem, R, hat⟩, hTg, hs0, hbud⟩ := hE + simp only at hle hneed hR hseg hmem R hTg hs0 + by_cases hb : b < p.blocks.length + · obtain ⟨hL, hnm, hstk, hblock⟩ := G.block b hb + obtain ⟨hn, hm⟩ := hneed hb + have hblk : p.blocks[b]? = some p.blocks[b] := List.getElem?_eq_getElem hb + rw [lowerFrom_drop p c hb, lowerBlock, List.append_assoc] at hseg + -- The label, at the frame's gas. + obtain ⟨pc1, m1, within1, hat1, hseg1, hg1, hrun1⟩ : ∃ (pc1 : Nat) (m1 : Evm .fusaka Nat) + (within1 : GasMeter.gasHeld m1.gas ≤ bound), + At code msg pc1 Tw M m1.gas st ss rd m1 ∧ + Seg (bytesOf code) c.offset pc1 (lowerInstrs p c b p.blocks[b] ++ + lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) code.size ∧ + m1.gas + (if isTarget p c b then 1 else 0) ≤ evm.gas ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild m1 within1 = .ok fin := by + by_cases ht : isTarget p c b = true + · simp only [ht, ite_true, List.singleton_append, List.cons_append] at hseg + obtain ⟨next, hd, hseg'⟩ := hseg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hp := hat.addGas 1 + obtain ⟨e1, r1, he1⟩ := Logic.jumpdestG hlt hcode (show 1 ≤ evm.gas + 1 by omega) _ hp + obtain ⟨m, within', hz, hrm⟩ := reaches_lowAt r1 1 evm rfl hat within hrun hok + rw [hz] at he1 + obtain ⟨hatm, hgm⟩ := at_of_addGasR he1 + exact ⟨pc + 1, m, within', hatm, hseg', by simp only [ht, ite_true]; omega, hrm⟩ + · simp only [ht, Bool.false_eq_true, ite_false, List.nil_append] at hseg + exact ⟨pc, evm, within, hat, hseg, by simp only [ht, Bool.false_eq_true, ite_false]; omega, + hrun⟩ + obtain ⟨T', r, hle', hex, hpost, hnext⟩ := segR (G0 := msg.gas) G.toGlobT hnc hdata hvalue hstatic hself hcaller + hbenv htx hb hok hgas (p.blocks[b].length + 1) p.blocks[b] (c.need b) [] (c.entry b) + (budget c b - labelItems p c b) S Tw s pc1 M m1.gas st ss T0 m1 within1 (Nat.lt_succ_self _) + hblock hn (by omega) (KR.nil _) hR hseg1 (by omega) htop hmem R hat1 hTg hs0 + (by unfold MemBudget; rw [← hat.2.2.2.2.2.1]; omega) hrun1 + refine ⟨T', r, hle', fun T'' h => ?_, fun res hres => hpost res hres, fun y hy => ?_⟩ + · simp only [SolarTV.EVM.Program.block, hblk] + rw [hex T'' h] + · obtain ⟨t, S', s'⟩ := y + obtain ⟨⟨htle, -, hj⟩, after, within', hE', hT', hs', hga, hbud', hra⟩ := hnext _ hy + refine ⟨after, within', ⟨hE', hT', hs', hbud'⟩, ?_, hra⟩ + have := meas_step (c := c) (g := evm.gas) (g' := after.gas) hb htle (by omega) hj + dsimp only at this ⊢ + omega + · obtain rfl : b = p.blocks.length := by omega + have hblk : p.blocks[p.blocks.length]? = none := List.getElem?_eq_none (by omega) + have hbl : ∀ o, SolarTV.EVM.Program.block o call p (p.blocks.length, S, s) = + some (.inl (.stop, s)) := by + intro o + simp only [SolarTV.EVM.Program.block, hblk, ite_true] + refine ⟨T0, _, RunTable.Le.refl T0, fun _ _ => hbl _, ?_, ?_⟩ + · intro res hres + cases hres + have hseg' := hseg + rw [lowerFrom_nil p c (by omega)] at hseg' + have hpc := hseg'.nil_end + exact lowAt (SpecG.consequence (stop_of_size_leG (by omega)) + (fun _ h => h) fun evm h => postL_stop R hself evm h) (hat.addGas 0) within hrun hok + · intro y hy + cases hy + + +/-- `AssembleRun.processMessage_ok'` for a run that ends with any error: the frame the interpreter +runs under its runner of messages, whose error and output the message ends with. -/ +theorem processMessage_frameP {message : Message .fusaka} + (hpre : precompileAddress .fusaka message = none) {st : EthLib.Execution.State.TransactionState} {ss : Substate} {evm} + (hr : processMessage (Meter := Nat) .fusaka message st ss = .ok evm) : + ∃ (st' : EthLib.Execution.State.TransactionState) (ss' : Substate) + (within : GasMeter.gasHeld (startFrame message st' ss' message.gas).gas ≤ message.gas) + (fr : Evm .fusaka Nat), + (¬ (message.shouldTransferValue = true ∧ message.value ≠ 0) → st' = st ∧ ss' = ss) ∧ + ((message.shouldTransferValue = true ∧ message.value ≠ 0) → + st.moveEther .fusaka message.caller message.currentTarget message.value = .ok st' ∧ + ss' = { ss with logs := (pushTransferLog .fusaka ss.logs message.caller message.currentTarget + message.value) }) ∧ + runFrame (step .fusaka) (step_decreases .fusaka) message.gas + (processRunner .fusaka message.gas) (startFrame message st' ss' message.gas) within = + .ok fr ∧ + evm.1.error = fr.error ∧ evm.1.output = fr.output := by + rw [processMessage] at hr + have hss : startState .fusaka message st = st := by + simp [startState, show ¬ (Fork.fusaka < Fork.paris) by decide] + simp only [hss, hpre] at hr + by_cases htr : message.shouldTransferValue = true ∧ message.value ≠ 0 + · simp only [htr, ne_eq, not_false_eq_true, and_self, ↓reduceIte] at hr + cases hm : st.moveEther .fusaka message.caller message.currentTarget message.value with + | error e => simp [hm, Except.mapError, bind, Except.bind, Except.map] at hr + | ok st' => + simp only [hm, Except.mapError, bind, Except.bind, pure, Except.pure] at hr + split at hr + · simp [throw, throwThe, MonadExceptOf.throw, Except.map] at hr + · rename_i after hrf + simp only [Except.map, Except.ok.injEq] at hr + subst hr + simp only [htr.1, htr.2, not_false_eq_true, and_self, ↓reduceIte] at hrf + exact ⟨st', _, _, _, fun h => absurd htr h, fun _ => ⟨rfl, rfl⟩, hrf, + AssembleLoop.error_rollbackOnError _ _, AssembleLoop.output_rollbackOnError _ _⟩ + · simp only [htr, ↓reduceIte, bind, Except.bind, pure, Except.pure] at hr + split at hr + · simp [throw, throwThe, MonadExceptOf.throw, Except.map] at hr + · rename_i after hrf + simp only [Except.map, Except.ok.injEq] at hr + subst hr + simp only [htr, ↓reduceIte] at hrf + exact ⟨st, ss, _, _, fun _ => ⟨rfl, rfl⟩, fun h => absurd h htr, hrf, + AssembleLoop.error_rollbackOnError _ _, AssembleLoop.output_rollbackOnError _ _⟩ + +open SolarTV.EVM.Program SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Evm.Symex in +/-- **`AssembleRun.within_of_advances` with the revert data related**: when every frame related to a +block state advances in a run that ends with no error or reverts, the oracle of the run's table +makes every result of the bytecode on the call the EVM IR's, unless the run halted exceptionally. -/ +theorem within_of_advancesR {p : Assemble.Program} {code : ByteArray} {call : Call} {gas : Nat} + (O : RunTable → Oracle) + (E : Substate → RunTable → Nat × List Word × Machine.State → Evm .fusaka Nat → Prop) + (meas : Nat × List Word × Machine.State → Evm .fusaka Nat → Nat) + (start : ∀ st' ss', Rel (Final.Target.messageWith gas code call) ss' st' ss' + (Machine.State.initial call) → + E ss' {} (0, [], Machine.State.initial call) + (startFrame (Final.Target.messageWith gas code call) st' ss' gas)) + (adv : ∀ ss0 T x evm, E ss0 T x evm → AdvancesR (fun o => block o call p) O (E ss0) + (fun res => PostL call (Final.Target.messageWith gas code call).currentTarget ss0 res.2 res.1) + meas T x evm) : + ∃ T, WithinR (evmirSem (O T)) gas p code (· = call) := by + cases hrunE : Target.runWith gas code call with + | none => + refine ⟨{}, fun call' hc obs h => ?_⟩ + subst hc + rw [hrunE] at h + cases h + | some obs => + have hrun0 := hrunE + unfold Target.runWith Target.runMsg at hrunE + split at hrunE + · cases hrunE + rename_i evm hev hpm + simp only [Option.some.injEq] at hrunE + by_cases hex : ∃ e, e ≠ EvmError.revert ∧ evm.error = some e + · obtain ⟨e, hne, he'⟩ := hex + have hs : obs.success = false := by rw [← hrunE]; simp [he'] + have hfail := Target.runWith_failure hrun0 hs + have hh : HaltsExceptionally gas code call := ⟨⟨evm, hev⟩, hpm, e, hne, he'⟩ + refine ⟨{}, fun call' hc obs' h => ?_⟩ + subst hc + rw [hrun0] at h + cases h + exact Or.inr ⟨hh, hs, hfail⟩ + rcases herrc : evm.error with _ | e + · obtain ⟨T, hT⟩ := within_of_advances O E meas start + (fun ss0 T x evm h => (adv ss0 T x evm h).advances) + have hsucc : obs.success = true := by rw [← hrunE]; simp [herrc] + refine ⟨T, fun call' hc obs' h => ?_⟩ + rcases hT call' hc obs' h with h' | ⟨hs, -⟩ + · exact .inl h' + · subst hc + rw [hrun0] at h + cases h + rw [hsucc] at hs + cases hs + have hrev : e = .revert := by + by_contra hne + exact hex ⟨e, hne, herrc⟩ + subst hrev + obtain ⟨st', ss', within, fr, hcases, hmove, hrf, herrfr, houtfr⟩ := + processMessage_frameP (message := Final.Target.messageWith gas code call) (evm := ⟨evm, hev⟩) + (precompileAddress_message code call) hpm + simp only at herrfr houtfr + have hfrrev : fr.error = some .revert := by rw [← herrfr, herrc] + have R := AssembleLoop.rel_start code call gas ss' (fun h => (hcases h).1) (fun h => (hmove h).1) + obtain ⟨T, ⟨halt, sF⟩, -, hit, hpost⟩ := run_of_advancesR (fun o => block o call p) O (adv ss') + (meets_process .fusaka _) _ {} _ _ within fr (start st' ss' R) (Nat.lt_succ_self _) hrf + (.inr hfrrev) + obtain ⟨k, hk⟩ := hit T (RunTable.Le.refl T) + have hres : (evmirSem (O T)).run p call = some (observe call sF halt) := by + change (SolarTV.EVM.Program.layer.result (O T) p call).map _ = _ + rw [SolarTV.EVM.Program.layer.result_of_ends ⟨k, hk⟩] + rfl + obtain ⟨ssF, ⟨herr, hout, -, -⟩, -⟩ := hpost + have hfinal : (evmirSem (O T)).run p call = some obs := by + rw [hres, ← hrunE] + have herr' : fr.error = errorOf (observe call sF halt) := herr + have hout' : fr.output.toList.map (·.toNat) = (observe call sF halt).output := hout + have hfail : (observe call sF halt).success = false → + (observe call sF halt).logs = [] ∧ + (observe call sF halt).storage = slotValue call.storage := by + cases halt <;> simp [observe] + clear herr hout hres hit hk + generalize observe call sF halt = X at * + have hsucc : fr.error.isNone = X.success := by + rw [herr']; cases hX : X.success <;> simp [errorOf, hX] + rw [hfrrev] at hsucc + simp only [Option.isNone_some] at hsucc + obtain ⟨hlogs, hst⟩ := hfail hsucc.symm + congr 1 + cases X with + | mk success output logs storage => + simp only at hsucc hout' hlogs hst ⊢ + subst hsucc hlogs hst + rw [SolarTV.Observable.mk.injEq] + refine ⟨by simp [herrc], ?_, by simp [herrc], by funext slot; simp [herrc]⟩ + rw [houtfr] + exact hout'.symm + refine ⟨T, fun call' hc obs' h => ?_⟩ + subst hc + rw [hrun0] at h + cases h + exact .inl hfinal + +/-- **EVM IR to bytecode, run by run, for code with loops, GAS and memory at any offset, with the +revert data related**: for every program the checker with GAS accepts, at every gas below +`2 ^ 256` and every call, the oracle of the run's table makes every result of the bytecode the EVM +IR's (a revert with its data among them), unless the run halted exceptionally. -/ +theorem runs_of_checkCR {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (hc : checkC p code c mx = true) (gas : Nat) (hgas : gas < 2 ^ 256) (call : Call) : + ∃ T, WithinR (evmirSem (O T)) gas p code (· = call) := by + obtain ⟨hcb, hnc⟩ := checkC_base hc + obtain ⟨G, hseg, hneed0⟩ := globC_of_checkC hcb + refine within_of_advancesR O + (fun ss0 => EntT p c mx code (Final.Target.messageWith gas code call) ss0) + (fun y e => AssembleLoop.meas p c e.gas y.1) (fun st' ss' R => ?_) + (fun ss0 T x evm hE => advances_checkCR G hnc rfl + (by simp [Final.Target.messageWith, Target.message]) rfl rfl rfl rfl rfl hgas T x evm hE) + refine ⟨⟨[], 0, .empty, st', ss', .empty, Nat.zero_le _, fun _ => ⟨by simp [hneed0], by simp⟩, + SR.nil c _, by rw [List.drop_zero]; exact hseg, by simp, memRel_initial, R, ?_⟩, rfl, rfl, ?_⟩ + have hcode : (Final.Target.messageWith gas code call).code = code := rfl + · exact ⟨by simp [startFrame, hcode], by simp [startFrame, hcode], rfl, rfl, rfl, rfl, rfl, rfl, rfl, + rfl, rfl, rfl, rfl⟩ + · have h0 : memoryGasCost 0 = 0 := by rw [memoryGasCost_eq]; simp [wordCount, ceil32, WORD_BYTES] + simp only [startFrame, ByteArray.size_empty, h0, Nat.zero_add] + exact le_refl _ + +/-- **The per-run theorem with the revert data related**, below `2 ^ 256` gas, for every program +the checker with GAS accepts: an oracle meeting the certificate's constraints for each run. -/ +theorem withinRunR_of_checkC {p : Assemble.Program} {code : ByteArray} {c : Cert} + {mx : List Nat} (hc : checkC p code c mx = true) : + ∀ gas, gas < 2 ^ 256 → ∀ call, ∃ o, CertOk c o ∧ + WithinR (evmirSem o) gas p code (· = call) := by + intro gas hgas call + obtain ⟨T, hT⟩ := runs_of_checkCR hc gas hgas call + exact ⟨O T, O_ok c T, hT⟩ + +/-- info: 'SolidCore.Refinement.Solar.AssembleRevertCut.withinRunR_of_checkC' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms withinRunR_of_checkC + +/-- `AssembleCut.WithinRunLt` with the revert data related (`AssembleLoop.WithinR`). -/ +def WithinRunLtR (sem : Oracle → Sem) (p : ∀ o, (sem o).Prog) (code : ByteArray) + (scope : Call → Prop) (Ok : Oracle → Prop) : Prop := + ∀ gas, gas < 2 ^ 256 → ∀ call, scope call → ∃ o, Ok o ∧ + WithinR (sem o) gas (p o) code (· = call) + +/-- `WithinRunLtR` gives `AssembleCut.WithinRunLt`. -/ +theorem WithinRunLtR.withinRunLt {sem : Oracle → Sem} {p : ∀ o, (sem o).Prog} {code : ByteArray} + {scope : Call → Prop} {Ok : Oracle → Prop} (h : WithinRunLtR sem p code scope Ok) : + WithinRunLt sem p code scope Ok := by + intro gas hgas call hc + obtain ⟨o, ho, hw⟩ := h gas hgas call hc + exact ⟨o, ho, hw.within⟩ + +/-- Stages read backwards before a per-run refinement with the revert data related give one from +the earlier program. -/ +theorem WithinRunLtR.of_back {A sem : Oracle → Sem} {q : ∀ o, (A o).Prog} {p : ∀ o, (sem o).Prog} + {code : ByteArray} {scope : Call → Prop} {Ok : Oracle → Prop} + (back : ∀ o, Ok o → Stage (sem o) (A o) (p o) (q o) scope) + (h : WithinRunLtR sem p code scope Ok) : WithinRunLtR A q code scope Ok := by + intro gas hgas call hc + obtain ⟨o, ho, hw⟩ := h gas hgas call hc + refine ⟨o, ho, fun call' h' obs hrun => ?_⟩ + subst h' + rcases hw call' rfl obs hrun with e | e + · exact Or.inl (back o ho call' hc obs e) + · exact Or.inr e + +/-- **The per-run theorem with the revert data related** on a scope, for every program the checker +with GAS accepts. -/ +theorem withinRunLtR_of_checkC {p : Assemble.Program} {code : ByteArray} {c : Cert} + {mx : List Nat} (hc : checkC p code c mx = true) (scope : Call → Prop) : + WithinRunLtR evmirSem (fun _ => p) code scope (CertOk c) := + fun gas hgas call _ => withinRunR_of_checkC hc gas hgas call + +/-- **The first lowered MIR to the exact bytecode, run by run, with the revert data related**: the +backend stages read backwards and the checker with GAS give, for every gas below `2 ^ 256` and +every call, an oracle meeting the certificate's constraints under which every result of the +bytecode is the first lowered MIR's (a revert with its data among them), unless the run halted +exceptionally. -/ +theorem withinRunR_mir_of_checkC {stage0 : SolarTV.MIR.Lowered.moduleLayer.Prog} + {p : Assemble.Program} {code : ByteArray} {c : Cert} {mx : List Nat} {S scope : Call → Prop} + (back : ∀ o, Certified SolarTV.EVM.Program.layer SolarTV.MIR.Lowered.moduleLayer o p stage0 S) + (hS : ∀ call, scope call → S call) (hc : checkC p code c mx = true) : + WithinRunLtR mirSem (fun _ => stage0) code scope (CertOk c) := + WithinRunLtR.of_back (fun o _ => fun call hcall obs h => + stage_of_certified (back o) call (hS call hcall) obs h) + (withinRunLtR_of_checkC hc scope) + +/-- info: 'SolidCore.Refinement.Solar.AssembleRevertCut.withinRunR_mir_of_checkC' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms withinRunR_mir_of_checkC + +end SolidCore.Refinement.Solar.AssembleRevertCut diff --git a/SolidCore/Refinement/Solar/AssembleRevertCutExample.lean b/SolidCore/Refinement/Solar/AssembleRevertCutExample.lean new file mode 100644 index 00000000..c86723cc --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleRevertCutExample.lean @@ -0,0 +1,58 @@ +import SolidCore.Refinement.Solar.AssembleRevertCut + +/-! +# A revert of the call data, of any size: an example and mutants + +The program copies all of its call data to memory at offset 0 (CALLDATACOPY, a copy of a size the +call chooses, which only the checker with GAS and memory at any offset admits) and reverts with +it. `withinRunR_of_checkC` gives, at every gas below `2 ^ 256` and for every call, an oracle under +which every result of the bytecode is the program's, its revert with the call data as revert data +among them, unless the run halted exceptionally. + +The mutant that copies from offset 1 reverts with other data, and the one that returns instead +reverts nothing: the checker rejects both by evaluation. +-/ + +namespace SolidCore.Refinement.Solar.AssembleRevertCutExample + +open SolidCore.Refinement.Solar SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.AssembleCut SolidCore.Refinement.Solar.AssembleRevertCut + +/-- CALLDATASIZE PUSH0 PUSH0 CALLDATACOPY, then CALLDATASIZE PUSH0 REVERT. -/ +def prog : Assemble.Program := + { blocks := [[.effect .calldatasize 0, .op (.stack (.push 0)), .op (.stack (.push 0)), + .effect .calldatacopy 3, .effect .calldatasize 0, .op (.stack (.push 0)), .revert]] } + +def code : ByteArray := ⟨#[0x36, 0x5f, 0x5f, 0x37, 0x36, 0x5f, 0xfd]⟩ + +/-- The copy from offset 1 of the call data: PUSH1 1 in place of the first PUSH0. -/ +def mutantData : ByteArray := ⟨#[0x36, 0x60, 0x01, 0x5f, 0x37, 0x36, 0x5f, 0xfd]⟩ + +/-- RETURN (0xf3) in place of REVERT. -/ +def mutantReturn : ByteArray := ⟨#[0x36, 0x5f, 0x5f, 0x37, 0x36, 0x5f, 0xf3]⟩ + +def cert : Assemble.Cert := + { offsets := [0], needs := [0], top := 2 ^ 140, costs := [7], types := [[]] } + +def maxs : List Nat := [0] + +theorem check_ok : checkC prog code cert maxs = true := by decide +kernel + +/-- The mutant that reverts with other data fails the check by evaluation. -/ +theorem mutantData_fails : checkC prog mutantData cert maxs = false := by decide +kernel + +/-- The mutant that returns fails the check by evaluation. -/ +theorem mutantReturn_fails : checkC prog mutantReturn cert maxs = false := by decide +kernel + +/-- **At every gas below `2 ^ 256`, every result of the bytecode is the program's**: its revert +with the call data, unless the run halted exceptionally, under an oracle of each run that meets +the certificate's constraints. -/ +theorem bytecode : ∀ gas, gas < 2 ^ 256 → ∀ call, ∃ o, RunOracle.CertOk cert o ∧ + WithinR (SolarTV.evmirSem o) gas prog code (· = call) := + withinRunR_of_checkC check_ok + +/-- info: 'SolidCore.Refinement.Solar.AssembleRevertCutExample.bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecode + +end SolidCore.Refinement.Solar.AssembleRevertCutExample diff --git a/SolidCore/Refinement/Solar/AssembleRevertExample.lean b/SolidCore/Refinement/Solar/AssembleRevertExample.lean new file mode 100644 index 00000000..376473ae --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleRevertExample.lean @@ -0,0 +1,60 @@ +import SolidCore.Refinement.Solar.AssembleRevert + +/-! +# A program that reverts with data the call chooses: an example and a mutant + +The program loads the first word of its calldata, stores it at offset 0 and reverts with that +word: `withinR_of_checkL` gives, at every gas, under every oracle, that every result of its bytecode +is the program's, a revert among them (with the calldata's first word as its revert data), unless +the run halted exceptionally (out of gas). `Final.Within` would let a reverting bytecode stand +for itself; `WithinR` does not. + +The mutant loads the calldata word at offset 4 instead, so it reverts with other data: the checker +rejects it by evaluation, not by a timeout. +-/ + +namespace SolidCore.Refinement.Solar.AssembleRevertExample + +open SolidCore.Refinement.Solar SolidCore.Refinement.Solar.AssembleLoop SolidCore.Refinement.Final + +/-- PUSH 0, CALLDATALOAD, PUSH 0, MSTORE, PUSH 32, PUSH 0, REVERT. -/ +def prog : Assemble.Program := + { blocks := [[.op (.stack (.push 0)), .effect .calldataload 1, .op (.stack (.push 0)), .op .store, + .op (.stack (.push 32)), .op (.stack (.push 0)), .revert]] } + +/-- PUSH0 CALLDATALOAD PUSH0 MSTORE PUSH1 32 PUSH0 REVERT. -/ +def code : ByteArray := ⟨#[0x5f, 0x35, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xfd]⟩ + +/-- The same code loading the calldata word at offset 4: PUSH1 4 in place of the first PUSH0. -/ +def mutant : ByteArray := ⟨#[0x60, 0x04, 0x35, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xfd]⟩ + +def cert : Assemble.Cert := + { offsets := [0], needs := [0], top := 32, costs := [7], types := [[]] } + +def maxs : List Nat := [0] + +theorem check_ok : checkL prog code cert maxs = true := by decide +kernel + +/-- The mutant, which reverts with other data, fails the check by evaluation. -/ +theorem mutant_fails : checkL prog mutant cert maxs = false := by decide +kernel + +/-- **At every gas, every result of the bytecode is the program's**: its revert with the +calldata's first word, unless the run halted exceptionally, under every oracle. -/ +theorem bytecode (o : SolarTV.Machine.Oracle) (scope : SolarTV.Call → Prop) (gas : Nat) : + WithinR (SolarTV.evmirSem o) gas prog code scope := + withinR_of_checkL check_ok o (fun h => absurd h (by decide)) scope gas + +/-- The same below `2 ^ 256` gas, in the form of `Final.Within` too. -/ +theorem bytecode_within (o : SolarTV.Machine.Oracle) (scope : SolarTV.Call → Prop) (gas : Nat) + (_ : gas < 2 ^ 256) : Within (SolarTV.evmirSem o) (ethLibWith gas) prog code scope := + (bytecode o scope gas).within + +/-- info: 'SolidCore.Refinement.Solar.AssembleRevertExample.bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms bytecode + +/-- info: 'SolidCore.Refinement.Solar.AssembleRevertExample.mutant_fails' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms mutant_fails + +end SolidCore.Refinement.Solar.AssembleRevertExample diff --git a/SolidCore/Refinement/Solar/AssembleRun.lean b/SolidCore/Refinement/Solar/AssembleRun.lean new file mode 100644 index 00000000..49c6f842 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleRun.lean @@ -0,0 +1,337 @@ +import SolidCore.Refinement.Solar.RunOracle +import EthLib.Execution.Proofs.Evm.Logic.Message + +/-! +# EVM IR to bytecode at the given gas, run by run + +The assembly theorems so far (`Assemble.stage_of_check`, `AssembleLoop.within_of_checkL`) run +EthLib's interpreter with gas to spare and carry a gas reserve through the simulation; a run with +less gas is then the same run with less gas left (`Logic.LessGas`). That argument holds only for +code whose every step is monotone in gas: GAS pushes the gas left, a call forwards all but a 64th +of it, and a copy of dynamic size has no static bound on its memory, so none of them fits it. + +This file proves the refinement at the gas the run has, from a simulation block by block over +EthLib's steps under the runner of messages (`StepBy`, `HoareUnder`), with the oracle of the run +built as the run goes: + +* `Advances`: from a frame related to a SolarTV block state, EthLib reaches a frame that failed + (out of gas, or any exceptional halt), or the table of the run grows to `T'` (the gas a GAS read + pushed, the success and output of a call) and every oracle of a table extending `T'` runs the + block to the same end, which EthLib's frame shows (`Post`), or to the next block state, related + to EthLib's frame with a lower measure. +* `run_of_advances`: a run of EthLib that ends with no error is, for every table extending the + last one, SolarTV's run to the same end. +* `within_of_advances`: at every gas, for every call, the oracle of that run's table makes every + result of the bytecode the EVM IR's or a failure that changes nothing: the per-run theorem + (`RunOracle.WithinRun`) for code with GAS, calls and dynamic copies, from a block simulation. + +The block simulation of the checker's fragment in this form (each instruction's rule when the +gas suffices, the frame failing when it does not, and the single-instruction effects of +`AssembleEffects` for GAS, the return data, copies and calls) is what remains to instantiate it. +-/ + +namespace SolidCore.Refinement.Solar.AssembleRun + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Final +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.RunOracle +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic +open EthLib.Execution.State + +/-! ## Tables that grow -/ + +/-- `T'` extends `T`: each table of `T` is a prefix of `T'`'s. -/ +def _root_.SolidCore.Refinement.Solar.RunOracle.RunTable.Le (T T' : RunTable) : Prop := + T.oks <+: T'.oks ∧ T.outs <+: T'.outs ∧ T.stores <+: T'.stores ∧ + T.transients <+: T'.transients ∧ T.gases <+: T'.gases + +theorem _root_.SolidCore.Refinement.Solar.RunOracle.RunTable.Le.refl (T : RunTable) : T.Le T := + ⟨List.prefix_refl _, List.prefix_refl _, List.prefix_refl _, List.prefix_refl _, + List.prefix_refl _⟩ + +theorem _root_.SolidCore.Refinement.Solar.RunOracle.RunTable.Le.trans {T1 T2 T3 : RunTable} (a : T1.Le T2) (b : T2.Le T3) : T1.Le T3 := + ⟨a.1.trans b.1, a.2.1.trans b.2.1, a.2.2.1.trans b.2.2.1, a.2.2.2.1.trans b.2.2.2.1, + a.2.2.2.2.trans b.2.2.2.2⟩ + +/-- An entry of a table is the same in every extension. -/ +theorem getD_of_prefix {α : Type} {l l' : List α} (h : l <+: l') {i : Nat} (hi : i < l.length) + (d : α) : l'.getD i d = l.getD i d := by + obtain ⟨t, rfl⟩ := h + simp [List.getD_eq_getElem?_getD, List.getElem?_append_left hi] + +/-! ## A run, block by block -/ + +section Blocks + +variable {σ : Type} (blk : Oracle → σ → Option ((Halt × Machine.State) ⊕ σ)) + (O : RunTable → Oracle) + +/-- **One block of the simulation, read back from a run that succeeds**: under every runner of +messages, when the loop runs the frame `evm` to a frame `fin` with no error, the table grows to `T'` +and every oracle of a table extending `T'` runs the block from `x` to the same `r`: an end `fin` +shows (`Post`), or the next block state, related (`E T'`) to a frame with a lower measure that the +loop runs to `fin` too. -/ +def Advances (E : RunTable → σ → Evm .fusaka Nat → Prop) + (Post : Halt × Machine.State → Evm .fusaka Nat → Prop) (meas : σ → Evm .fusaka Nat → Nat) + (T : RunTable) (x : σ) (evm : Evm .fusaka Nat) : Prop := + ∀ (bound : Nat) (runChild : MessageRunner .fusaka Nat bound), Meets (fun _ _ _ => True) runChild → + ∀ (within : GasMeter.gasHeld evm.gas ≤ bound) (fin : Evm .fusaka Nat), + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + fin.error = none → + ∃ T' r, T.Le T' ∧ (∀ T'', T'.Le T'' → blk (O T'') x = some r) ∧ + (∀ res, r = .inl res → Post res fin) ∧ + (∀ y, r = .inr y → ∃ after within', E T' y after ∧ meas y after < meas x evm ∧ + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild after within' = .ok fin) + +/-- **One block of the simulation, forwards**: from the frame `evm`, under every runner of messages, +EthLib reaches a frame that failed, or the table grows to `T'` and every oracle of a table extending +`T'` runs the block to the same `r`: an end the frame reached shows, or the next block state, +related to the frame reached with a lower measure. -/ +def AdvancesFwd (E : RunTable → σ → Evm .fusaka Nat → Prop) + (Post : Halt × Machine.State → Evm .fusaka Nat → Prop) (meas : σ → Evm .fusaka Nat → Nat) + (T : RunTable) (x : σ) (evm : Evm .fusaka Nat) : Prop := + HoareUnder .fusaka (fun _ _ _ => True) (· = evm) fun after => + (after.running = false ∧ after.error ≠ none) ∨ + ∃ T' r, T.Le T' ∧ (∀ T'', T'.Le T'' → blk (O T'') x = some r) ∧ + (∀ res, r = .inl res → after.running = false ∧ Post res after) ∧ + (∀ y, r = .inr y → E T' y after ∧ meas y after < meas x evm) + +/-- A block that advances forwards advances in a run that succeeds. -/ +theorem advances_of_fwd {E : RunTable → σ → Evm .fusaka Nat → Prop} + {Post : Halt × Machine.State → Evm .fusaka Nat → Prop} {meas : σ → Evm .fusaka Nat → Nat} + {T : RunTable} {x : σ} {evm : Evm .fusaka Nat} (h : AdvancesFwd blk O E Post meas T x evm) : + Advances blk O E Post meas T x evm := by + intro bound runChild meets within fin hrun hok + obtain ⟨after, hreach, hq⟩ := h bound runChild meets evm rfl within + have within' := Nat.le_trans (hreach.gasHeld_le StepBy.gasHeld_le) within + have hrun' := hrun + rw [runFrame_eq_of_reaches StepBy.gasHeld_le StepBy.runFrame_eq hreach within] at hrun' + rcases hq with hq | aborted + · rcases hq with ⟨hstop, herr⟩ | ⟨T', r, hle, hstep, hinl, hinr⟩ + · rw [runFrame_of_running_eq_false hstop] at hrun' + cases hrun' + exact absurd hok herr + · refine ⟨T', r, hle, hstep, fun res hr => ?_, fun y hy => ?_⟩ + · obtain ⟨hstop, hpost⟩ := hinl res hr + rw [runFrame_of_running_eq_false hstop] at hrun' + cases hrun' + exact hpost + · obtain ⟨hE', hm'⟩ := hinr y hy + exact ⟨after, within', hE', hm', hrun'⟩ + · obtain ⟨e, he, -⟩ := runFrame_of_abortsBy meets.aborts aborted within' + rw [he] at hrun' + cases hrun' + +/-- **A run of EthLib that ends with no error is SolarTV's**, for every table extending the last +one the run grew. -/ +theorem run_of_advances {E : RunTable → σ → Evm .fusaka Nat → Prop} + {Post : Halt × Machine.State → Evm .fusaka Nat → Prop} {meas : σ → Evm .fusaka Nat → Nat} + (adv : ∀ T x evm, E T x evm → Advances blk O E Post meas T x evm) + {bound : Nat} {runChild : MessageRunner .fusaka Nat bound} + (meets : Meets (fun _ _ _ => True) runChild) : + ∀ (n : Nat) (T : RunTable) (x : σ) (evm : Evm .fusaka Nat) + (within : GasMeter.gasHeld evm.gas ≤ bound) (fin : Evm .fusaka Nat), + E T x evm → meas x evm < n → + runFrame (step .fusaka) (step_decreases .fusaka) bound runChild evm within = .ok fin → + fin.error = none → + ∃ T' res, T.Le T' ∧ + (∀ T'', T'.Le T'' → ∃ k, iterate (blk (O T'')) k x = some res) ∧ + Post res fin + | 0, _, _, _, _, _, _, h, _, _ => absurd h (Nat.not_lt_zero _) + | n + 1, T, x, evm, within, fin, hE, hm, hrun, hok => by + obtain ⟨T', r, hle, hstep, hinl, hinr⟩ := adv T x evm hE bound runChild meets within fin hrun hok + cases r with + | inl res => + exact ⟨T', res, hle, fun T'' h => ⟨1, by simp [iterate, hstep T'' h]⟩, hinl res rfl⟩ + | inr y => + obtain ⟨after, within', hE', hm', hrun'⟩ := hinr y rfl + obtain ⟨T2, res, hle2, hit, hpost⟩ := + run_of_advances adv meets n T' y after within' fin hE' (by omega) hrun' hok + refine ⟨T2, res, hle.trans hle2, fun T'' h => ?_, hpost⟩ + obtain ⟨k, hk⟩ := hit T'' h + exact ⟨k + 1, by simp [iterate, hstep T'' (hle2.trans h), hk]⟩ + +end Blocks + +/-! ## The message of a call -/ + +/-- `AssembleLoop.processMessage_ok` with the runner of messages named: the one the interpreter +runs the frame's calls and creations with. -/ +theorem processMessage_ok' {message : Message .fusaka} + (hpre : precompileAddress .fusaka message = none) {st : TransactionState} {ss : Substate} {evm} + (hr : processMessage (Meter := Nat) .fusaka message st ss = .ok evm) (hok : evm.1.error = none) : + ∃ (st' : TransactionState) (ss' : Substate) + (within : GasMeter.gasHeld (startFrame message st' ss' message.gas).gas ≤ message.gas), + (¬ (message.shouldTransferValue = true ∧ message.value ≠ 0) → st' = st ∧ ss' = ss) ∧ + ((message.shouldTransferValue = true ∧ message.value ≠ 0) → + st.moveEther .fusaka message.caller message.currentTarget message.value = .ok st' ∧ + ss' = { ss with logs := (pushTransferLog .fusaka ss.logs message.caller message.currentTarget + message.value) }) ∧ + runFrame (step .fusaka) (step_decreases .fusaka) message.gas + (processRunner .fusaka message.gas) (startFrame message st' ss' message.gas) within = + .ok evm.1 := by + rw [processMessage] at hr + have hss : startState .fusaka message st = st := by + simp [startState, show ¬ (Fork.fusaka < Fork.paris) by decide] + simp only [hss, hpre] at hr + by_cases htr : message.shouldTransferValue = true ∧ message.value ≠ 0 + · simp only [htr, ne_eq, not_false_eq_true, and_self, ↓reduceIte] at hr + cases hm : st.moveEther .fusaka message.caller message.currentTarget message.value with + | error e => simp [hm, Except.mapError, bind, Except.bind, Except.map] at hr + | ok st' => + simp only [hm, Except.mapError, bind, Except.bind, pure, Except.pure] at hr + split at hr + · simp [throw, throwThe, MonadExceptOf.throw, Except.map] at hr + · rename_i after hrf + simp only [Except.map, Except.ok.injEq] at hr + subst hr + have := AssembleLoop.rollbackOnError_ok hok + simp only [htr.1, htr.2, not_false_eq_true, and_self, ↓reduceIte] at hrf + rw [← this] at hrf + exact ⟨st', _, _, fun h => absurd htr h, fun _ => ⟨rfl, rfl⟩, hrf⟩ + · simp only [htr, ↓reduceIte, bind, Except.bind, pure, Except.pure] at hr + split at hr + · simp [throw, throwThe, MonadExceptOf.throw, Except.map] at hr + · rename_i after hrf + simp only [Except.map, Except.ok.injEq] at hr + subst hr + have := AssembleLoop.rollbackOnError_ok hok + simp only [htr, ↓reduceIte] at hrf + rw [← this] at hrf + exact ⟨st, ss, _, fun _ => ⟨rfl, rfl⟩, fun h => absurd h htr, hrf⟩ + +/-! ## The refinement at the given gas -/ + +open SolarTV.EVM.Program SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Evm.Symex in +/-- **EVM IR to bytecode at the given gas, run by run, from a block simulation**: when every frame +related to a block state (`E`, from the substate the frame started with) advances (`Advances`) to +an end SolarTV's halt shows (`PostL`) or to the next block, and the frame a call starts with is +related to SolarTV's initial state, then the oracle of the run's table makes every result of the +bytecode on the call the EVM IR's or a failure that changes nothing. -/ +theorem within_of_advances {p : Assemble.Program} {code : ByteArray} {call : Call} {gas : Nat} + (O : RunTable → Oracle) + (E : Substate → RunTable → Nat × List Word × Machine.State → Evm .fusaka Nat → Prop) + (meas : Nat × List Word × Machine.State → Evm .fusaka Nat → Nat) + (start : ∀ st' ss', Rel (Final.Target.messageWith gas code call) ss' st' ss' + (Machine.State.initial call) → + E ss' {} (0, [], Machine.State.initial call) + (startFrame (Final.Target.messageWith gas code call) st' ss' gas)) + (adv : ∀ ss0 T x evm, E ss0 T x evm → Advances (fun o => block o call p) O (E ss0) + (fun res => PostL call (Final.Target.messageWith gas code call).currentTarget ss0 res.2 res.1) + meas T x evm) : + ∃ T, Within (evmirSem (O T)) (ethLibWith gas) p code (· = call) := by + by_cases hs : ∃ obs, Target.runWith gas code call = some obs ∧ obs.success = true + swap + · refine ⟨{}, fun call' hc obs hrun => Or.inr ?_⟩ + subst hc + have hf : obs.success = false := by + cases h : obs.success + · rfl + · exact absurd ⟨obs, hrun, h⟩ hs + exact ⟨hf, Target.runWith_failure hrun hf⟩ + obtain ⟨obs, hrun, hsucc⟩ := hs + suffices H : ∃ T, (evmirSem (O T)).run p call = some obs by + obtain ⟨T, hT⟩ := H + refine ⟨T, fun call' hc obs' hrun' => Or.inl ?_⟩ + subst hc + change Target.runWith gas code call' = some obs' at hrun' + rw [hrun] at hrun' + cases hrun' + exact hT + unfold Target.runWith Target.runMsg at hrun + split at hrun + · cases hrun + rename_i evm hev hpm + simp only [Option.some.injEq] at hrun + subst hrun + have hok : evm.error = none := by simpa using hsucc + obtain ⟨st', ss', within, hcases, hmove, hrf⟩ := + processMessage_ok' (message := Final.Target.messageWith gas code call) (evm := ⟨evm, hev⟩) + (precompileAddress_message code call) hpm hok + simp only at hrf + have R := AssembleLoop.rel_start code call gas ss' (fun h => (hcases h).1) (fun h => (hmove h).1) + obtain ⟨T, ⟨halt, sF⟩, -, hit, hpost⟩ := run_of_advances (fun o => block o call p) O (adv ss') + (meets_process .fusaka _) _ {} _ _ within evm (start st' ss' R) (Nat.lt_succ_self _) hrf hok + obtain ⟨k, hk⟩ := hit T (RunTable.Le.refl T) + refine ⟨T, ?_⟩ + have hres : (evmirSem (O T)).run p call = some (observe call sF halt) := by + change (SolarTV.EVM.Program.layer.result (O T) p call).map _ = _ + rw [SolarTV.EVM.Program.layer.result_of_ends ⟨k, hk⟩] + rfl + rw [hres] + set msg := Final.Target.messageWith gas code call with hmsg + obtain ⟨ssF, ⟨herr, hout, hlogsF, hst⟩, L, hL1, hL2⟩ := hpost + have hss' : ss'.logs.toList = [] := by + by_cases htr : msg.shouldTransferValue = true ∧ msg.value ≠ 0 + · rw [(hmove htr).2] + simp [pushTransferLog, show ¬ (Fork.fusaka ≥ Fork.glamsterdam) by decide, Substate.empty] + · rw [(hcases htr).2] + simp [Substate.empty] + have hlogs := logs_of_match hL2 + have hL1' : ssF.logs.toList = L := by rw [hL1, hss', List.nil_append] + have herr' : evm.error = errorOf (observe call sF halt) := herr + have hout' : evm.output.toList.map (·.toNat) = (observe call sF halt).output := hout + have hst' : (observe call sF halt).success = true → + evm.substate.logs = ssF.logs ∧ ∀ slot, + (evm.state.getStorage (Target.address selfAddress) (Target.storageKey slot)).toNat = + (observe call sF halt).storage slot := + fun h => ⟨hlogsF, hst h⟩ + have hfail : (observe call sF halt).success = false → + (observe call sF halt).logs = [] ∧ + (observe call sF halt).storage = slotValue call.storage := by + cases halt <;> simp [observe] + have hok2 : (observe call sF halt).success = true → + (observe call sF halt).logs = logs sF := by + cases halt <;> simp [observe] + clear herr hout hst hres hit hk + generalize observe call sF halt = X at * + have hsucc' : evm.error.isNone = X.success := by + rw [herr']; cases hX : X.success <;> simp [errorOf, hX] + symm + congr 1 + cases X with + | mk success output logs storage => + simp only at hsucc' hout' hfail hok2 hst' ⊢ + rw [SolarTV.Observable.mk.injEq] + refine ⟨hsucc', hout', ?_, ?_⟩ + · rw [hsucc'] + cases hs : success + · simp [hok, hs] at hsucc' + · simp only [ite_true] + rw [(hst' hs).1, hL1', hlogs, hok2 hs] + rfl + · funext slot + rw [hsucc'] + cases hs : success + · simp [hok, hs] at hsucc' + · simp only [ite_true] + exact (hst' hs).2 slot + +/-- **Per run, from a block simulation**: under a base oracle meeting the certificate's constraints, +a block simulation at every gas and call gives the per-run refinement. -/ +theorem withinRun_of_advances {p : Assemble.Program} {code : ByteArray} {scope : Call → Prop} + {Ok : Oracle → Prop} (O : RunTable → Oracle) (hok : ∀ T, Ok (O T)) + (sim : ∀ gas call, scope call → ∃ (E : Substate → RunTable → Nat × List Word × Machine.State → + Evm .fusaka Nat → Prop) (meas : Nat × List Word × Machine.State → Evm .fusaka Nat → Nat), + (∀ st' ss', Rel (Final.Target.messageWith gas code call) ss' st' ss' + (Machine.State.initial call) → + E ss' {} (0, [], Machine.State.initial call) + (startFrame (Final.Target.messageWith gas code call) st' ss' gas)) ∧ + (∀ ss0 T x evm, E ss0 T x evm → Advances (fun o => SolarTV.EVM.Program.block o call p) O + (E ss0) + (fun res => PostL call (Final.Target.messageWith gas code call).currentTarget ss0 res.2 res.1) + meas T x evm)) : + WithinRun evmirSem (fun _ => p) code scope Ok := by + intro gas call hc + obtain ⟨E, meas, start, adv⟩ := sim gas call hc + obtain ⟨T, hT⟩ := within_of_advances O E meas start adv + exact ⟨O T, hok T, hT⟩ + +/-- info: 'SolidCore.Refinement.Solar.AssembleRun.within_of_advances' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms within_of_advances + +/-- info: 'SolidCore.Refinement.Solar.AssembleRun.withinRun_of_advances' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms withinRun_of_advances + +end SolidCore.Refinement.Solar.AssembleRun diff --git a/SolidCore/Refinement/Solar/AssembleRunLoop.lean b/SolidCore/Refinement/Solar/AssembleRunLoop.lean new file mode 100644 index 00000000..8846eaf6 --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleRunLoop.lean @@ -0,0 +1,171 @@ +import SolidCore.Refinement.Solar.AssembleRun +import SolidCore.Refinement.Solar.AssembleLoopWithin + +/-! +# The loop assembly theorem at the run's gas + +`AssembleRun.within_of_advances` instantiated for the checker of code with loops: each block is read +back from a run that succeeds (`advances_checkL`) by the block simulation of `AssembleLoopSim`, run +with gas to spare for that block alone (`K` more than the frame holds) and moved back to the frame's +own gas by `Logic.reaches_low`, block by block rather than for the whole run. The relation at a block +entry (`Ent`) holds at any gas, so no gas reserve crosses blocks. + +`withinRun_of_checkL_atGas` is `RunOracle.withinRun_of_checkL` proved this way: the per-run theorem +through the block framework that GAS, calls and copies of dynamic size need, here with the oracle +the fragment needs (any oracle meeting `CertOk`), so the framework's hypotheses are met by every +program the checker accepts. +-/ + +namespace SolidCore.Refinement.Solar.AssembleRunLoop + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Final +open SolidCore.Refinement.Solar.Assemble SolidCore.Refinement.Solar.AssembleLoop +open SolidCore.Refinement.Solar.RunOracle SolidCore.Refinement.Solar.AssembleRun +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +/-- The relation at a block entry, at any gas: the block is within the layout with a stack between +its bounds, typed as its entry says, the code from EthLib's pc is the rest of the layout, memory is +below the certificate's bound and agrees, and the storage and logs agree. -/ +def Ent (p : Assemble.Program) (c : Cert) (mx : List Nat) (code : ByteArray) (msg : Message .fusaka) + (ss0 : Substate) (x : Nat × List Word × Machine.State) (evm : Evm .fusaka Nat) : Prop := + ∃ (Tw : List Word) (pc : Nat) (M : ByteArray) (st : State.TransactionState) (ss : Substate), + x.1 ≤ p.blocks.length ∧ + (x.1 < p.blocks.length → c.need x.1 ≤ x.2.1.length ∧ x.2.1.length ≤ maxH mx x.1) ∧ + SR c (c.entry x.1) x.2.1 Tw ∧ + Seg (bytesOf code) c.offset pc (lowerFrom p c x.1 (p.blocks.drop x.1)) code.size ∧ + M.size ≤ c.top ∧ MemRel x.2.2.memory M ∧ Rel msg ss0 st ss x.2.2 ∧ + At code msg pc Tw M evm.gas st ss .empty evm + +/-- A frame with `K` more gas that meets `At` is a frame that meets it with its own gas. -/ +theorem at_of_addGas {code : ByteArray} {msg : Message .fusaka} {pc : Nat} {T : List Word} + {M : ByteArray} {G : Nat} {st : State.TransactionState} {ss : Substate} {K : Nat} + {m : Evm .fusaka Nat} (h : At code msg pc T M G st ss .empty (addGas K m)) : + At code msg pc T M m.gas st ss .empty m ∧ m.gas + K = G := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11, h12, h13⟩ := h + exact ⟨⟨h1, h2, h3, h4, h5, h6, rfl, h8, h9, h10, h11, h12, h13⟩, by simpa using h7⟩ + +open SolarTV.EVM.Program in +/-- **A block of code with loops, read back from a run that succeeds.** -/ +theorem advances_checkL {p : Assemble.Program} {c : Cert} {mx : List Nat} {code : ByteArray} + (G : GlobL p c mx code) {o : Oracle} {call : Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) (ho : c.env = true → OracleOk o) + (hbenv : msg.blockEnv = Target.blockEnv) (htx : msg.txEnv = Target.txEnv) + (he : c.reads = true → EnvOk o) (T0 : RunTable) (x : Nat × List Word × Machine.State) + (evm : Evm .fusaka Nat) (hE : Ent p c mx code msg ss0 x evm) : + Advances (fun o => block o call p) (fun _ => o) (fun _ => Ent p c mx code msg ss0) + (fun res => PostL call msg.currentTarget ss0 res.2 res.1) + (fun y e => AssembleLoop.meas p c e.gas y.1) T0 x evm := by + intro bound runChild _ within fin hrun hok + obtain ⟨b, S, s⟩ := x + obtain ⟨Tw, pc, M, st, ss, hle, hneed, hR, hseg, htop, hmem, R, hat⟩ := hE + simp only at hle hneed hR hseg hmem R + -- The block with gas to spare: `K` more than the frame holds. + generalize hK : 22100 * bmax c + memoryGasCost c.top = K + generalize hg : evm.gas = g at hat + have hp : At code msg pc Tw M (g + K) st ss .empty (addGas K evm) := hat.addGas K + have E : EntryL c code call (lowerFrom p c b (p.blocks.drop b)) (bmax c) pc s M (g + K) := + ⟨hseg, by omega, htop, hmem⟩ + by_cases hb : b < p.blocks.length + · have hblk : p.blocks[b]? = some p.blocks[b] := List.getElem?_eq_getElem hb + obtain ⟨hL, hnm, hstk, hblock⟩ := G.block b hb + obtain ⟨hn, hm⟩ := hneed hb + have hbm := budget_le_bmax c b + obtain ⟨pc1, g1, hlabel, hg1, I1⟩ : ∃ pc1 g1, HoareG .fusaka (At code msg pc Tw M (g + K) st ss .empty) + (At code msg pc1 Tw M g1 st ss .empty) ∧ g1 + (if isTarget p c b then 1 else 0) ≤ g + K ∧ + InvL c code call (lowerInstrs p c b p.blocks[b] ++ + lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) (budget c b - labelItems p c b) + 0 pc1 S s M g1 := by + have E' := E + rw [lowerFrom_drop p c hb, lowerBlock, List.append_assoc] at E' + have hG := E'.gas + by_cases ht : isTarget p c b = true + · have hl : labelItems p c b = 1 := by simp [labelItems, ht] + rw [hl] at hL ⊢ + simp only [ht, ite_true, List.singleton_append] at E' + obtain ⟨next, hd, hseg'⟩ := E'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + exact ⟨pc + 1, g + K - 1, Logic.jumpdestG hlt hcode (by omega), by simp only [ht, ite_true]; omega, + ⟨hseg', by omega, by omega, E'.le_top, E'.mem⟩⟩ + · have hl : labelItems p c b = 0 := by simp [labelItems, ht] + rw [hl, Nat.sub_zero] + simp only [ht, Bool.false_eq_true, ite_false, List.nil_append] at E' + exact ⟨pc, g + K, Triple.of_imp fun _ h => h, by simp only [ht, Bool.false_eq_true, ite_false]; omega, + ⟨E'.seg, by omega, by omega, E'.le_top, E'.mem⟩⟩ + have hsim := exec_simL (o := o) G.toT hdata hvalue hstatic hself hcaller ho hbenv (fun _ => htx) he b hb 0 + p.blocks[b] (c.need b) [] (c.entry b) S Tw _ s pc1 M g1 st ss hblock hn (by omega) + (KR.nil _) hR I1 R + have hbl : block o call p (b, S, s) = some (exec o call b p.blocks[b] S s) := by + simp only [block, hblk] + refine ⟨T0, exec o call b p.blocks[b] S s, RunTable.Le.refl T0, fun _ _ => hbl, ?_, ?_⟩ + · intro res hres + rw [hres] at hsim + exact SpecG.low (SpecG.seq hlabel hsim) hp within hrun hok + · intro y hy + rw [hy] at hsim + obtain ⟨t, S', s'⟩ := y + obtain ⟨⟨htle, hneedt, hj⟩, pc', T', M', g', st', ss', hh, hR', E', R'⟩ := hsim + obtain ⟨e1, r1, he1⟩ := hlabel _ hp + obtain ⟨mid, r2, hmid⟩ := hh e1 he1 + obtain ⟨m, within', hz, hrm⟩ := reaches_low (r1.trans r2) K evm rfl within hrun hok + rw [hz] at hmid + obtain ⟨hatm, hgm'⟩ := at_of_addGas hmid + have hgm := reaches_gas_le r2 + rw [hz, he1.2.2.2.2.2.2.1] at hgm + simp only [gas_addGas] at hgm + have hms := meas_step (c := c) (g := g) (g' := m.gas) hb htle (by omega) hj + refine ⟨m, within', ⟨T', pc', M', st', ss', htle, hneedt, hR', E'.seg, E'.le_top, E'.mem, R', + hatm⟩, ?_, hrm⟩ + show meas p c m.gas t < meas p c evm.gas b + rw [hg] + omega + · obtain rfl : b = p.blocks.length := by omega + have hblk : p.blocks[p.blocks.length]? = none := List.getElem?_eq_none (by omega) + have hbl : block o call p (p.blocks.length, S, s) = some (.inl (.stop, s)) := by + simp only [block, hblk, ite_true] + refine ⟨T0, _, RunTable.Le.refl T0, fun _ _ => hbl, ?_, ?_⟩ + · intro res hres + cases hres + have hseg' := hseg + rw [lowerFrom_nil p c (by omega)] at hseg' + have hpc := hseg'.nil_end + exact SpecG.low (SpecG.consequence (stop_of_size_leG (by omega)) + (fun _ h => h) fun evm h => postL_stop R hself evm h) hp within hrun hok + · intro y hy + cases hy + +/-- The oracle the fragment of the checker runs under: any one meeting `CertOk`. -/ +def fragOracle : Oracle := tableOracle (envOracle (ethOracle anyOracle)) {} + +/-- **The loop assembly theorem, run by run, at the run's own gas**: `RunOracle.withinRun_of_checkL` +through the block framework of `AssembleRun`, with no gas reserve across blocks. -/ +theorem withinRun_of_checkL_atGas {p : Assemble.Program} {code : ByteArray} {c : Cert} + {mx : List Nat} (hc : checkL p code c mx = true) (scope : Call → Prop) : + WithinRun evmirSem (fun _ => p) code scope (CertOk c) := by + obtain ⟨G, hseg, hneed0⟩ := globL_of_checkL hc + have hok := table_ok anyOracle {} + refine withinRun_of_advances (fun _ => fragOracle) (fun _ => ⟨fun _ => hok.1, fun _ => hok.2⟩) + fun gas call _ => ⟨fun ss0 _ => Ent p c mx code (Final.Target.messageWith gas code call) ss0, + fun y e => AssembleLoop.meas p c e.gas y.1, fun st' ss' R => ?_, + fun ss0 T x evm hE => advances_checkL G rfl + (by simp [Final.Target.messageWith, Target.message]) rfl rfl rfl (fun _ => hok.1) rfl rfl + (fun _ => hok.2) T x evm hE⟩ + refine ⟨[], 0, .empty, st', ss', Nat.zero_le _, fun _ => ⟨by simp [hneed0], by simp⟩, SR.nil c _, + by rw [List.drop_zero]; exact hseg, by simp, memRel_initial, R, ?_⟩ + have hcode : (Final.Target.messageWith gas code call).code = code := rfl + exact ⟨by simp [startFrame, hcode], by simp [startFrame, hcode], rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, + rfl, rfl⟩ + +/-- info: 'SolidCore.Refinement.Solar.AssembleRunLoop.advances_checkL' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms advances_checkL + +/-- info: 'SolidCore.Refinement.Solar.AssembleRunLoop.withinRun_of_checkL_atGas' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms withinRun_of_checkL_atGas + +end SolidCore.Refinement.Solar.AssembleRunLoop diff --git a/SolidCore/Refinement/Solar/AssembleSim.lean b/SolidCore/Refinement/Solar/AssembleSim.lean new file mode 100644 index 00000000..d7af5d1b --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleSim.lean @@ -0,0 +1,1907 @@ +import EthLib.Execution.Proofs.Evm.Logic.Log +import SolidCore.Refinement.Solar.Assemble +import SolidCore.Refinement.Compose +import SolidCore.Refinement.Evm.WideStorage + +/-! +# EVM IR to bytecode, the simulation + +The proof of `stage_of_check_env` (and of `stage_of_check_all`, `stage_of_check_eth` and +`stage_of_check`, its forms for programs that read neither the caller nor a hash, for EthLib's +caller and hash, and on calls with no value): EthLib's interpreter simulates SolarTV's EVM IR +semantics on every program and code the checker of `Assemble.lean` accepts. A walk segment +(`Seg`) is the checker's lockstep decoding between two offsets; the stack relation (`SR`) +relates SolarTV's stack to EthLib's word by word at the checker's types (a return label is its +block's number in SolarTV and its offset in EthLib); the invariant (`Inv`) relates SolarTV's +memory to EthLib's frame at the offset of the next item, with 22100 gas (SSTORE's highest price) +for each item left and the price of memory up to the certificate's bound; and `Rel` relates +SolarTV's storage to the storage of EthLib's account of the frame, from any initial storage, and +EthLib's logs to SolarTV's world (`LogsRel`). Each item takes one unit of potential, and a jump +or a fall into the next block lands where the potential left bounds the target's, so a run +executes at most the first block's potential in items, and the gas and the stack bound follow +from that count. +-/ + +namespace SolidCore.Refinement.Solar.Assemble + +open SolarTV.Assembly +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Wide + +/-! ## Walk segments -/ + +/-- The checker's walk from `pc` over `items`, ending at `pc'`. -/ +inductive Seg (code : List Nat) (offset : Nat → Nat) : Nat → List Item → Nat → Prop + | nil {pc : Nat} : Seg code offset pc [] pc + | cons {pc next pc' : Nat} {item : Item} {items : List Item} : + decode code pc = some (item.expected offset, next) → + (∀ label, item = .label label → offset label = pc) → + Seg code offset next items pc' → Seg code offset pc (item :: items) pc' + +theorem seg_of_walk {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × SolarTV.Assembly.Instr)} (w : Walk code offset pc items stream) : + Seg code offset pc items code.length := by + induction w with + | nil => exact .nil + | cons d l _ ih => exact .cons d (fun label he => by subst he; simpa [Item.placed] using l) ih + +theorem Seg.split {code : List Nat} {offset : Nat → Nat} : + ∀ {pc pc'' : Nat} {A B : List Item}, Seg code offset pc (A ++ B) pc'' → + ∃ pc', Seg code offset pc A pc' ∧ Seg code offset pc' B pc'' + | pc, _, [], _, h => ⟨pc, .nil, h⟩ + | _, _, a :: A, B, h => by + rw [List.cons_append] at h + cases h with + | cons d l rest => + obtain ⟨pc', h1, h2⟩ := Seg.split rest + exact ⟨pc', .cons d l h1, h2⟩ + +theorem Seg.nil_end {code : List Nat} {offset : Nat → Nat} {pc pc' : Nat} + (h : Seg code offset pc [] pc') : pc = pc' := by + cases h; rfl + +theorem decode_lt {code : List Nat} {pc : Nat} {x : SolarTV.Assembly.Instr × Nat} + (h : decode code pc = some x) : pc < code.length := by + unfold decode at h + split at h + · cases h + · rename_i byte hb + exact (List.getElem?_eq_some_iff.1 hb).1 + +/-! ## The lowered program -/ + +theorem lowerFrom_drop (p : Program) (c : Cert) {b : Nat} (hb : b < p.blocks.length) : + lowerFrom p c b (p.blocks.drop b) = + lowerBlock p c b p.blocks[b] ++ lowerFrom p c (b + 1) (p.blocks.drop (b + 1)) := by + rw [List.drop_eq_getElem_cons hb] + rfl + +theorem lowerFrom_nil (p : Program) (c : Cert) {b : Nat} (hb : p.blocks.length ≤ b) : + lowerFrom p c b (p.blocks.drop b) = [] := by + rw [List.drop_eq_nil_of_le hb] + rfl + +theorem seg_lowerFrom {code : List Nat} {offset : Nat → Nat} {e : Nat} (p : Program) (c : Cert) : + ∀ (k : Nat) (l : List (List Instr)) (b pc : Nat), + Seg code offset pc (lowerFrom p c b l) e → k < l.length → + ∃ pc', Seg code offset pc' (lowerFrom p c (b + k) (l.drop k)) e ∧ + (isTarget p c (b + k) = true → offset (b + k) = pc') + | _, [], _, _, _, hk => absurd hk (by simp) + | 0, x :: l, b, pc, h, _ => by + refine ⟨pc, by simpa using h, fun ht => ?_⟩ + simp only [Nat.add_zero] at ht ⊢ + simp only [lowerFrom, lowerBlock, ht, ite_true, List.cons_append] at h + cases h with + | cons _ l _ => exact l b rfl + | k + 1, x :: l, b, pc, h, hk => by + simp only [lowerFrom] at h + obtain ⟨pc', -, h2⟩ := Seg.split h + obtain ⟨pc'', h3, h4⟩ := seg_lowerFrom p c k l (b + 1) pc' h2 (by simp at hk; omega) + rw [show b + (k + 1) = b + 1 + k by omega, List.drop_succ_cons] + exact ⟨pc'', h3, h4⟩ + +/-! ## Stack types -/ + +/-- What a word of SolarTV's stack is to EthLib's at its type: the same word for data, the +offset of a block the certificate lists for a return label, anything where the type is +unknown. -/ +def WR (c : Cert) : Ty → Word → Word → Prop + | some false, x, y => y = x + | some true, x, y => x.toNat ∈ c.rets ∧ y = BitVec.ofNat 256 (c.offset x.toNat) + | none, _, _ => True + +/-- SolarTV's stack and EthLib's have one height and agree word by word at their types. -/ +def SR (c : Cert) (ty : List Ty) (S T : List Word) : Prop := + S.length = T.length ∧ ∀ i (h1 : i < S.length) (h2 : i < T.length), WR c (tyAt ty i) S[i] T[i] + +theorem tyAt_tail (ty : List Ty) (i : Nat) : tyAt ty.tail i = tyAt ty (i + 1) := by + cases ty <;> simp [tyAt] + +theorem tyAt_cons_zero (τ : Ty) (ty : List Ty) : tyAt (τ :: ty) 0 = τ := by simp [tyAt] + +theorem tyAt_cons_succ (τ : Ty) (ty : List Ty) (i : Nat) : tyAt (τ :: ty) (i + 1) = tyAt ty i := by + simp [tyAt] + +theorem SR.nil (c : Cert) (ty : List Ty) : SR c ty [] [] := + ⟨rfl, fun _ h => absurd h (by simp)⟩ + +theorem SR.uncons {c : Cert} {ty : List Ty} {x y : Word} {S T : List Word} : + SR c ty (x :: S) (y :: T) ↔ WR c (tyAt ty 0) x y ∧ SR c ty.tail S T := by + constructor + · rintro ⟨hl, h⟩ + refine ⟨h 0 (by simp) (by simp), by simpa using hl, fun i h1 h2 => ?_⟩ + have := h (i + 1) (by simp; omega) (by simp; omega) + simpa [tyAt_tail] using this + · rintro ⟨hw, hl, h⟩ + refine ⟨by simp [hl], fun i h1 h2 => ?_⟩ + cases i with + | zero => simpa using hw + | succ i => + have := h i (by simpa using h1) (by simpa using h2) + simpa [tyAt_tail] using this + +theorem SR.cons {c : Cert} {τ : Ty} {ty : List Ty} {x y : Word} {S T : List Word} + (hw : WR c τ x y) (h : SR c ty S T) : SR c (τ :: ty) (x :: S) (y :: T) := + SR.uncons.2 ⟨by simpa [tyAt_cons_zero] using hw, by simpa using h⟩ + +theorem SR.length {c : Cert} {ty : List Ty} {S T : List Word} (h : SR c ty S T) : + S.length = T.length := h.1 + +theorem SR.get {c : Cert} {ty : List Ty} {S T : List Word} (h : SR c ty S T) {i : Nat} + (hi : i < S.length) : WR c (tyAt ty i) S[i] (T[i]'(h.1 ▸ hi)) := h.2 i hi _ + +theorem SR.tail {c : Cert} {ty : List Ty} {S T : List Word} (h : SR c ty S T) : + SR c ty.tail S.tail T.tail := by + rcases S with _ | ⟨x, S⟩ <;> rcases T with _ | ⟨y, T⟩ + · exact SR.nil c _ + · exact absurd h.1 (by simp) + · exact absurd h.1 (by simp) + · exact (SR.uncons.1 h).2 + +theorem SR.drop {c : Cert} : ∀ (n : Nat) {ty : List Ty} {S T : List Word}, SR c ty S T → + SR c (ty.drop n) (S.drop n) (T.drop n) + | 0, _, _, _, h => by simpa using h + | n + 1, _, _, _, h => by + rw [← List.drop_tail, ← List.drop_tail, ← List.drop_tail] + exact SR.drop n h.tail + +theorem isData_lt {ty : List Ty} {n i : Nat} (h : isData ty n = true) (hi : i < n) : + tyAt ty i = some false := by + simp only [isData, List.all_eq_true, List.mem_range, beq_iff_eq] at h + exact h i hi + +/-- Data words are the same on both sides. -/ +theorem SR.data {c : Cert} {ty : List Ty} {S T : List Word} (h : SR c ty S T) {n : Nat} + (hd : isData ty n = true) : S.take n = T.take n := by + apply List.ext_getElem + · simp [h.1] + · intro i h1 h2 + simp only [List.length_take] at h1 h2 + have hw := h.2 i (by omega) (by omega) + rw [isData_lt hd (by omega)] at hw + simp only [List.getElem_take] + exact hw.symm + +theorem SR.head {c : Cert} {ty : List Ty} {x y : Word} {S T : List Word} + (h : SR c (ty) (x :: S) (y :: T)) (hd : isData ty 1 = true) : y = x := by + have := (SR.uncons.1 h).1 + rw [isData_lt hd (by decide)] at this + exact this + +theorem SR.le {c : Cert} {ty σ : List Ty} {S T : List Word} (hle : tyLe ty σ = true) + (h : SR c ty S T) : SR c σ S T := by + refine ⟨h.1, fun i h1 h2 => ?_⟩ + have hw := h.2 i h1 h2 + simp only [tyLe, List.all_eq_true, List.mem_range, Bool.or_eq_true, beq_iff_eq] at hle + by_cases hi : i < σ.length + · rcases hle i hi with he | he + · rw [he]; trivial + · rw [he]; exact hw + · have : tyAt σ i = none := by simp [tyAt, List.getD_eq_getElem?_getD, hi] + rw [this]; trivial + +theorem SR.dup {c : Cert} {ty : List Ty} {S T : List Word} (h : SR c ty S T) {i : Nat} + (hi : i < S.length) (hi' : i < T.length) : + SR c (tyAt ty i :: ty) (S[i] :: S) (T[i] :: T) := + SR.cons (h.2 i hi hi') h + +/-- DUP of a word keeps the known constants a prefix of the stack. -/ +theorem dupKnown_prefix {known S : List Word} (hk : known <+: S) {i : Nat} (hi : i < S.length) : + dupKnown known i <+: S[i] :: S := by + unfold dupKnown + split + · rename_i v hv + have hS : S[i]? = some v := by + obtain ⟨t, rfl⟩ := hk + rw [List.getElem?_append_left (List.getElem?_eq_some_iff.1 hv).1, hv] + rw [List.getElem?_eq_getElem hi, Option.some.injEq] at hS + rw [hS] + exact (List.prefix_cons_inj v).2 ((List.take_prefix 1 known).trans hk) + · exact List.nil_prefix + +theorem tyAt_tySwap (ty : List Ty) (i j : Nat) : + tyAt (tySwap ty i) j = + if j = 0 then tyAt ty (i + 1) else if j = i + 1 then tyAt ty 0 else tyAt ty j := by + unfold tySwap + by_cases hj : j < max ty.length (i + 2) + · simp only [tyAt, List.getD_eq_getElem?_getD, List.getElem?_ofFn, hj] + simp + · have h1 : ¬ j = 0 := by omega + have h2 : ¬ j = i + 1 := by omega + simp only [h1, h2, ite_false] + simp [tyAt, List.getD_eq_getElem?_getD, List.getElem?_eq_none (show ty.length ≤ j by omega), + List.getElem?_eq_none (show (List.ofFn (n := max ty.length (i + 2)) _).length ≤ j by simp; omega)] + +theorem SR.swap {c : Cert} {ty : List Ty} {a b : Word} {S T : List Word} + (h : SR c ty (a :: S) (b :: T)) {i : Nat} (hi : i < S.length) (hi' : i < T.length) : + SR c (tySwap ty i) (S[i] :: S.set i a) (T[i] :: T.set i b) := by + refine ⟨by simpa using h.1, fun j h1 h2 => ?_⟩ + rw [tyAt_tySwap] + rcases j with _ | j + · simp only [ite_true, List.getElem_cons_zero] + have := h.2 (i + 1) (by simp; omega) (by simp; omega) + simpa using this + · simp only [Nat.add_one_ne_zero, ite_false, List.getElem_cons_succ, Nat.add_right_cancel_iff] + rw [List.getElem_set, List.getElem_set] + by_cases hj : i = j + · subst hj + simp only [ite_true] + have := h.2 0 (by simp) (by simp) + simpa using this + · simp only [hj, ite_false, show ¬ j = i from fun e => hj e.symm] + have := h.2 (j + 1) (by simp at h1 ⊢; omega) (by simp at h2 ⊢; omega) + simpa using this + +/-! ## What the check gives -/ + +theorem blocksOk_get {p : Program} {c : Cert} : ∀ (l : List (List Instr)) (b : Nat), + blocksOk p c b l = true → ∀ k (hk : k < l.length), + labelItems p c (b + k) ≤ cost p c (b + k) ∧ + blockOk p c (b + k) (c.need (b + k)) [] (c.entry (b + k)) + (cost p c (b + k) - labelItems p c (b + k)) l[k] = true + | [], _, _, _, hk => absurd hk (by simp) + | x :: l, b, h, 0, _ => by + simp only [blocksOk, Bool.and_eq_true, decide_eq_true_eq] at h + simpa using h.1 + | x :: l, b, h, k + 1, hk => by + simp only [blocksOk, Bool.and_eq_true] at h + have := blocksOk_get l (b + 1) h.2 k (by simp at hk; omega) + rw [show b + (k + 1) = b + 1 + k by omega] + simpa using this + +/-- The facts of the check the simulation uses at every block. -/ +structure Glob (p : Program) (c : Cert) (code : ByteArray) : Prop where + top_mod : c.top % 32 = 0 + top_le : c.top ≤ 2 ^ 32 + size_lt : code.size < 2 ^ 32 + target : ∀ t, t < p.blocks.length → isTarget p c t = true → + isValidJumpDest (validJumpDestinations code) (c.offset t) = true ∧ c.offset t < code.size ∧ + Seg (bytesOf code) c.offset (c.offset t) (lowerFrom p c t (p.blocks.drop t)) code.size + block : ∀ t (ht : t < p.blocks.length), labelItems p c t ≤ cost p c t ∧ + blockOk p c t (c.need t) [] (c.entry t) (cost p c t - labelItems p c t) p.blocks[t] = true + +theorem glob_of_check {p : Program} {code : ByteArray} {c : Cert} (h : check p code c = true) : + Glob p c code ∧ Seg (bytesOf code) c.offset 0 (lower p c) code.size ∧ c.need 0 = 0 ∧ + cost p c 0 ≤ 1000 ∧ 22100 * cost p c 0 + memoryGasCost c.top ≤ 10000000 := by + simp only [check, Bool.and_eq_true, decide_eq_true_eq] at h + obtain ⟨⟨⟨⟨⟨⟨⟨⟨hw, hblocks⟩, hlabels⟩, hneed⟩, hmod⟩, hlen⟩, htop⟩, hgas⟩, hsize⟩ := h + obtain ⟨stream, hw⟩ := Option.isSome_iff_exists.1 hw + have hseg : Seg (bytesOf code) c.offset 0 (lower p c) code.size := by + have := seg_of_walk (walk_sound hw) + rwa [length_bytesOf] at this + refine ⟨⟨hmod, htop, hsize, fun t ht htgt => ?_, fun t ht => ?_⟩, hseg, hneed, hlen, hgas⟩ + · have hv : isValidJumpDest (validJumpDestinations code) (c.offset t) = true := by + simp only [labelsValid, List.all_eq_true, List.mem_range] at hlabels + have := hlabels t ht + simpa [htgt] using this + obtain ⟨pc', hs, hpc⟩ := seg_lowerFrom p c t p.blocks 0 0 hseg ht + simp only [Nat.zero_add] at hs hpc + rw [← hpc htgt] at hs + refine ⟨hv, ?_, hs⟩ + have hs' := hs + rw [lowerFrom_drop p c ht] at hs' + simp only [lowerBlock, htgt, ite_true, List.cons_append] at hs' + cases hs' with + | cons d _ _ => + have := decode_lt d + rwa [length_bytesOf] at this + · have := blocksOk_get p.blocks 0 hblocks t ht + simpa using this + +/-! ## The invariant -/ + +/-- SolarTV's stack, state and memory at EthLib's offset `pc` with `items` left and potential `k`: +the walk goes on from `pc` to the end, the stack and the potential fit in 1000 words, the gas +pays 22100 for each unit of potential and memory up to the bound, and SolarTV's memory is +EthLib's. Each item run takes a unit of potential; the check bounds the potential of each +block by those of the blocks it jumps or falls to. -/ +structure Inv (c : Cert) (code : ByteArray) (call : SolarTV.Call) (items : List Item) (k pc : Nat) + (S : List Word) (s : SolarTV.Machine.State) (M : ByteArray) (g : Nat) : Prop where + seg : Seg (bytesOf code) c.offset pc items code.size + stack : S.length + k ≤ 1000 + gas : 22100 * k + (memoryGasCost c.top - memoryGasCost M.size) ≤ g + le_top : M.size ≤ c.top + mem : MemRel s.memory M + +theorem Inv.next {c : Cert} {code : ByteArray} {call : SolarTV.Call} {item : Item} + {items : List Item} {k pc next : Nat} {S S' : List Word} {s : SolarTV.Machine.State} + {M : ByteArray} {g g' : Nat} (I : Inv c code call (item :: items) k pc S s M g) (hk : 1 ≤ k) + (hseg : Seg (bytesOf code) c.offset next items code.size) (hS : S'.length ≤ S.length + 1) + (hg : g ≤ g' + 22100) : Inv c code call items (k - 1) next S' s M g' where + seg := hseg + stack := by have := I.stack; omega + gas := by have := I.gas; omega + le_top := I.le_top + mem := I.mem + +theorem Inv.weaken {c : Cert} {code : ByteArray} {call : SolarTV.Call} {items : List Item} + {k k' pc : Nat} {S : List Word} {s : SolarTV.Machine.State} {M : ByteArray} {g : Nat} + (I : Inv c code call items k pc S s M g) (hk : k' ≤ k) : Inv c code call items k' pc S s M g where + seg := I.seg + stack := by have := I.stack; omega + gas := by have := I.gas; omega + le_top := I.le_top + mem := I.mem + +/-- An event of SolarTV's world is a log EthLib's frame wrote at `a`: the same topics and data. -/ +def LogMatch (a : Address) : SolarTV.Machine.Event → EthLib.Execution.Blocks.Log → Prop + | .log topics data, l => + l.address = a ∧ l.topics = topics.map U256.toBeBytes ∧ l.data.toList.map (·.toNat) = data.map BitVec.toNat + | .call .., _ | .read _, _ | .create .., _ => False + +/-- An event of SolarTV's world that is a log. -/ +def isLogE : SolarTV.Machine.Event → Bool + | .log .. => true + | _ => false + +/-- EthLib's logs are those of \`ss0\` and then one for each log of SolarTV's world; its reads, +calls and creations write none. -/ +def LogsRel (a : Address) (ss0 ss : Substate) (w : List SolarTV.Machine.Event) : Prop := + ∃ L, ss.logs.toList = ss0.logs.toList ++ L ∧ List.Forall₂ (LogMatch a) (w.filter isLogE) L + +/-- SolarTV's storage is the storage of EthLib's account of the frame, which exists, and the +substate's logs are those of `ss0`, the substate the frame started from, and then SolarTV's. -/ +structure Rel (msg : Message .fusaka) (ss0 : Substate) (st : State.TransactionState) + (ss : Substate) (s : SolarTV.Machine.State) : Prop where + storage : ∀ k : Word, st.getStorage msg.currentTarget (U256.toBeBytes k) = s.storage k + account : (st.getAccountOptional msg.currentTarget).isSome = true + logs : LogsRel msg.currentTarget ss0 ss s.world + +/-- A slot of EthLib's storage at the callee is SolarTV's. -/ +theorem Rel.slot {msg : Message .fusaka} {ss0 : Substate} {st : State.TransactionState} + {ss : Substate} {s : SolarTV.Machine.State} (R : Rel msg ss0 st ss s) + (htgt : msg.currentTarget = Target.address selfAddress) (slot : Nat) : + (st.getStorage (Target.address selfAddress) (Target.storageKey slot)).toNat = + SolarTV.Machine.storageOf s slot := by + have hkey : Target.storageKey slot = U256.toBeBytes (BitVec.ofNat 256 slot) := + (storageKey_eq_toBeBytes slot _).2 (by simp) + rw [hkey, ← htgt, R.storage] + rfl + +/-- How the frame ends for SolarTV's `halt` in state `s`: as `PostS` shows its observable, with logs +that are those of `ss0` and then SolarTV's. -/ +def PostL (call : SolarTV.Call) (a : Address) (ss0 : Substate) (s : SolarTV.Machine.State) + (halt : SolarTV.Machine.Halt) (evm : Evm .fusaka Nat) : Prop := + ∃ ssF, PostS (SolarTV.Machine.observe call s halt) ssF evm ∧ LogsRel a ss0 ssF s.world + +/-- A frame stopped with no error and no output from `st` and `ss` shows SolarTV's STOP. -/ +theorem postL_stop {msg : Message .fusaka} {ss0 : Substate} {st : State.TransactionState} + {ss : Substate} {s : SolarTV.Machine.State} (R : Rel msg ss0 st ss s) + (htgt : msg.currentTarget = Target.address selfAddress) {call : SolarTV.Call} {g : Nat} + (evm : Evm .fusaka Nat) (h : Halted false .empty g st ss evm) : + PostL call msg.currentTarget ss0 s .stop evm := by + obtain ⟨-, herr, hout, -, hst, hss⟩ := h + refine ⟨ss, ⟨by rw [herr]; rfl, by rw [hout]; simp [SolarTV.Machine.observe], by rw [hss], + fun _ slot => ?_⟩, R.logs⟩ + rw [hst] + exact R.slot htgt slot + +/-- What a block's instructions from `pc` give, from EthLib's stack `T`, state `st` and substate +`ss`: a halt EthLib's frame shows, or the next block, reached by EthLib with its stack related +at the block's types, the invariant at its potential and the relation of the storage. -/ +def SimOut (p : Program) (c : Cert) (code : ByteArray) (call : SolarTV.Call) + (msg : Message .fusaka) (ss0 : Substate) (st : State.TransactionState) (ss : Substate) + (pc : Nat) (T : List Word) (M : ByteArray) (g : Nat) : + (SolarTV.Machine.Halt × SolarTV.Machine.State) ⊕ (Nat × List Word × SolarTV.Machine.State) → + Prop + | .inl (halt, s') => + Spec .fusaka (At code msg pc T M g st ss .empty) (PostL call msg.currentTarget ss0 s' halt) + | .inr (t, S', s') => (t ≤ p.blocks.length ∧ (t < p.blocks.length → c.need t ≤ S'.length)) ∧ + ∃ pc' T' M' g' st' ss', Hoare .fusaka (At code msg pc T M g st ss .empty) + (At code msg pc' T' M' g' st' ss' .empty) ∧ SR c (c.entry t) S' T' ∧ + Inv c code call (lowerFrom p c t (p.blocks.drop t)) (cost p c t) pc' S' s' M' g' ∧ + Rel msg ss0 st' ss' s' + +theorem SimOut.pre {p : Program} {c : Cert} {code : ByteArray} {call : SolarTV.Call} + {msg : Message .fusaka} {ss0 : Substate} {st st1 : State.TransactionState} {ss ss1 : Substate} + {pc pc1 : Nat} {T T1 : List Word} {M M1 : ByteArray} {g g1 : Nat} + {r : (SolarTV.Machine.Halt × SolarTV.Machine.State) ⊕ (Nat × List Word × SolarTV.Machine.State)} + (h : Hoare .fusaka (At code msg pc T M g st ss .empty) (At code msg pc1 T1 M1 g1 st1 ss1 .empty)) + (h1 : SimOut p c code call msg ss0 st1 ss1 pc1 T1 M1 g1 r) : + SimOut p c code call msg ss0 st ss pc T M g r := by + match r, h1 with + | .inl (_, _), hspec => exact Spec.seq h hspec + | .inr (_, _, _), ⟨hneed, pc', T', M', g', st', ss', hh, hR, hinv, hrel⟩ => + exact ⟨hneed, pc', T', M', g', st', ss', Triple.seq h hh, hR, hinv, hrel⟩ + +/-! ## SolarTV's steps -/ + +open SolarTV.EVM.Program in +theorem exec_stack {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {op : SolarTV.EVM.Op} {rest : List Instr} {S next : List Word} {s : SolarTV.Machine.State} + (hstep : SolarTV.EVM.step (context o call s) op S = some next) (h1 : S.length ≤ 1024) + (h2 : next.length ≤ 1024) : + exec o call b (.op (.stack op) :: rest) S s = exec o call b rest next s := by + simp [exec, stepOp, SolarTV.EVM.stepChecked, hstep, Except.map, + show ¬ 1024 < S.length by omega, show ¬ 1024 < next.length by omega] + +theorem opByte_of_stackNeed {op : SolarTV.EVM.Op} {x : Nat × Int} (h : stackNeed op = some x) : + ∃ byte, opByte op = some byte := by + cases op <;> simp [stackNeed, opByte] at h ⊢ <;> exact h.1 + +theorem lowerInstr_stack {op : SolarTV.EVM.Op} (hne : ∀ v, op ≠ .push v) : + lowerInstr (.op (.stack op)) = [.op ((opByte op).getD 0xfe)] := by + cases op <;> first | rfl | exact absurd rfl (hne _) + +/-- The check of a stack operation other than PUSH, DUP, SWAP and POP. -/ +theorem blockStep_stack {p : Program} {c : Cert} {ok : Nat → List Word → List Ty → Nat → Bool} + {h k : Nat} {known : List Word} {ty : List Ty} {op : SolarTV.EVM.Op} (hne : ∀ v, op ≠ .push v) + (hd : ∀ i, op ≠ .dup i) (hs : ∀ i, op ≠ .swap i) (hp : op ≠ .pop) : + blockStep p c ok h known ty k (.op (.stack op)) = + match stackNeed op with + | some (need, d) => decide (1 ≤ k) && decide (need ≤ h) && isData ty need && + ok (h + d).toNat [] (some false :: ty.drop need) (k - 1) + | none => false := by + cases op <;> first | rfl | exact absurd rfl (hne _) | exact absurd rfl (hd _) | + exact absurd rfl (hs _) | exact absurd rfl hp + +/-- A stack operation of the fragment other than DUP, SWAP and POP reads its top words and +puts one word in their place. -/ +theorem step_data {op : SolarTV.EVM.Op} {need : Nat} {d : Int} (hn : stackNeed op = some (need, d)) + (h1 : ∀ i, op ≠ .dup i) (h2 : ∀ i, op ≠ .swap i) (h3 : op ≠ .pop) {ctx : SolarTV.EVM.Context} + {S S' T : List Word} (hs : SolarTV.EVM.step ctx op S = some S') (ht : S.take need = T.take need) + (hl : S.length = T.length) : + ∃ v, S' = v :: S.drop need ∧ SolarTV.EVM.step ctx op T = some (v :: T.drop need) := by + cases op <;> simp only [stackNeed, reduceCtorEq, Option.some.injEq, Prod.mk.injEq] at hn + all_goals try first + | exact absurd rfl (h1 _) + | exact absurd rfl (h2 _) + | exact absurd rfl h3 + all_goals obtain ⟨rfl, -⟩ := hn + all_goals + rcases S with _ | ⟨a, _ | ⟨b, S⟩⟩ <;> rcases T with _ | ⟨a', _ | ⟨b', T⟩⟩ <;> + simp_all [SolarTV.EVM.step] + all_goals (try subst_vars) + all_goals (try simp) + +/-- A checked stack operation other than PUSH runs on both stacks, to stacks related at the +types the check goes on with. -/ +theorem stack_sim {p : Program} {c : Cert} {ok : Nat → List Word → List Ty → Nat → Bool} + {h k : Nat} {known : List Word} {ty : List Ty} {op : SolarTV.EVM.Op} (hne : ∀ v, op ≠ .push v) + {ctx : SolarTV.EVM.Context} {S T : List Word} + (hok : blockStep p c ok h known ty k (.op (.stack op)) = true) (hh : h ≤ S.length) + (hk : known <+: S) (hR : SR c ty S T) : + 1 ≤ k ∧ ∃ byte, opByte op = some byte ∧ ∃ h' ty' S' T', + SolarTV.EVM.step ctx op S = some S' ∧ SolarTV.EVM.step ctx op T = some T' ∧ + SR c ty' S' T' ∧ h' ≤ S'.length ∧ S'.length ≤ S.length + 1 ∧ + ∃ known', known' <+: S' ∧ ok h' known' ty' (k - 1) = true := by + have hL := hR.length + by_cases hd : ∃ i, op = .dup i + · obtain ⟨i, rfl⟩ := hd + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok + obtain ⟨⟨⟨hk1, h16⟩, hi⟩, hok⟩ := hok + have hiS : i.val < S.length := by omega + have hiT : i.val < T.length := by omega + refine ⟨hk1, 0x80 + i.val, by simp [opByte, h16], h + 1, _, _, _, ?_, ?_, SR.dup hR hiS hiT, by simp; omega, by simp, _, + dupKnown_prefix hk hiS, hok⟩ + · simp [SolarTV.EVM.step, List.getElem?_eq_getElem hiS] + · simp [SolarTV.EVM.step, List.getElem?_eq_getElem hiT] + by_cases hs : ∃ i, op = .swap i + · obtain ⟨i, rfl⟩ := hs + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok + obtain ⟨⟨⟨hk1, h16⟩, hi⟩, hok⟩ := hok + rcases S with _ | ⟨a, S⟩ + · simp at hh; omega + rcases T with _ | ⟨b, T⟩ + · simp at hL + simp only [List.length_cons] at hh hL + have hiS : i.val < S.length := by omega + have hiT : i.val < T.length := by omega + refine ⟨hk1, 0x90 + i.val, by simp [opByte, h16], h, _, _, _, ?_, ?_, SR.swap hR hiS hiT, by simp; omega, by simp, [], + List.nil_prefix, hok⟩ + · simp [SolarTV.EVM.step, List.getElem?_eq_getElem hiS] + · simp [SolarTV.EVM.step, List.getElem?_eq_getElem hiT] + by_cases hp : op = .pop + · subst hp + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok + obtain ⟨⟨hk1, h1⟩, hok⟩ := hok + rcases S with _ | ⟨a, S⟩ + · simp at hh; omega + rcases T with _ | ⟨b, T⟩ + · simp at hL + refine ⟨hk1, _, rfl, h - 1, _, _, _, rfl, rfl, (SR.uncons.1 hR).2, by simp at hh; omega, + by simp only [List.length_cons]; omega, [], List.nil_prefix, hok⟩ + have hd' : ∀ i, op ≠ .dup i := fun i e => hd ⟨i, e⟩ + have hs' : ∀ i, op ≠ .swap i := fun i e => hs ⟨i, e⟩ + rw [blockStep_stack hne hd' hs' hp] at hok + split at hok + · rename_i need d hn + simp only [Bool.and_eq_true, decide_eq_true_eq] at hok + obtain ⟨⟨⟨hk1, hneed⟩, hdata⟩, hok⟩ := hok + obtain ⟨byte, hbyte⟩ := opByte_of_stackNeed hn + have hS' : ∃ S', SolarTV.EVM.step ctx op S = some S' := by + cases op <;> simp only [stackNeed, reduceCtorEq, Option.some.injEq, Prod.mk.injEq] at hn + all_goals try first + | exact absurd rfl (hd' _) + | exact absurd rfl (hs' _) + | exact absurd rfl hp + all_goals obtain ⟨rfl, -⟩ := hn + all_goals rcases S with _ | ⟨a, _ | ⟨b, S⟩⟩ <;> simp_all [SolarTV.EVM.step] <;> omega + obtain ⟨S', hstep⟩ := hS' + obtain ⟨v, rfl, hstepT⟩ := step_data hn hd' hs' hp hstep (hR.data hdata) hL + have hd1 : (need : Int) + d = 1 := by + cases op <;> simp [stackNeed] at hn <;> + first | omega | exact absurd rfl (hd' _) | exact absurd rfl (hs' _) | exact absurd rfl hp + refine ⟨hk1, byte, hbyte, (h + d).toNat, _, _, _, hstep, hstepT, + SR.cons (τ := some false) rfl (SR.drop need hR), ?_, ?_, [], List.nil_prefix, hok⟩ + · simp only [List.length_cons, List.length_drop]; omega + · simp only [List.length_cons, List.length_drop]; omega + · cases hok + +theorem turnedElse_some {c : Cert} {b e : Nat} {i : Instr} {rest : List Instr} + (h : turnedElse c b i rest = some e) : i = .jumpi (b + 1) ∧ rest = [.jump e] := by + unfold turnedElse at h + split at h + · split at h + · rename_i hc + simp only [Option.some.injEq] at h + simp only [Bool.and_eq_true, beq_iff_eq] at hc + subst h + rw [hc.2] + exact ⟨rfl, rfl⟩ + · cases h + · cases h + +/-- What the assembler leaves out: a final jump to the next block, or the last block's STOP. -/ +theorem dropped_true {p : Program} {b : Nat} {i : Instr} {rest : List Instr} + (h : dropped p b i rest = true) : + (i = .jump (b + 1) ∧ rest = []) ∨ (i = .stop ∧ rest = [] ∧ b + 1 = p.blocks.length) := by + unfold dropped at h + split at h + · simp only [beq_iff_eq] at h + subst h + exact .inl ⟨rfl, rfl⟩ + · simp only [beq_iff_eq] at h + exact .inr ⟨rfl, rfl, h⟩ + · cases h + +theorem iszero_zero : EvmRules.Evm.iszero (0 : Word) ≠ 0 := by + unfold EvmRules.Evm.iszero + decide + +theorem iszero_nonzero {x : Word} (h : x ≠ 0) : EvmRules.Evm.iszero x = 0 := by + unfold EvmRules.Evm.iszero + have : (x == 0) = false := by simpa using h + rw [this] + rfl + +/-- CALLDATALOAD in SolarTV is EthLib's. -/ +theorem shl_or_ofNat (acc b : Nat) (hb : b < 256) : + (BitVec.ofNat 256 acc <<< 8) ||| BitVec.ofNat 256 b = BitVec.ofNat 256 (acc * 256 + b) := by + have hand : (BitVec.ofNat 256 acc <<< 8) &&& BitVec.ofNat 256 b = 0 := by + ext i hi + rw [BitVec.getElem_and, BitVec.getElem_shiftLeft, ← BitVec.getLsbD_eq_getElem, + ← BitVec.getLsbD_eq_getElem, BitVec.getLsbD_ofNat] + by_cases h8 : i < 8 + · simp [h8] + · have : b.testBit i = false := + Nat.testBit_lt_two_pow (Nat.lt_of_lt_of_le hb + (by simpa using Nat.pow_le_pow_right (by decide : 0 < 2) (Nat.le_of_not_lt h8))) + simp [BitVec.getLsbD_ofNat, this] + rw [← BitVec.add_eq_or_of_and_eq_zero _ _ hand] + apply BitVec.eq_of_toNat_eq + simp only [BitVec.toNat_add, BitVec.toNat_shiftLeft, BitVec.toNat_ofNat, Nat.shiftLeft_eq] + omega + +theorem foldl_word (data : ByteArray) (off : Nat) : ∀ (l : List Nat) (acc : Nat), + l.foldl (fun (acc : BitVec 256) i => + (acc <<< 8) ||| BitVec.ofNat 256 (data.data.getD (off + i) 0).toNat) + (BitVec.ofNat 256 acc) = + BitVec.ofNat 256 (l.foldl (fun acc i => acc * 256 + (byteAt data (off + i)).toNat) acc) + | [], _ => rfl + | i :: l, acc => by + simp only [List.foldl_cons] + have hget : (data.data.getD (off + i) 0) = byteAt data (off + i) := rfl + rw [hget, shl_or_ofNat _ _ (byteAt data (off + i)).toNat_lt, foldl_word data off l] + +theorem calldataWord_eq (call : SolarTV.Call) (off : BitVec 256) : + SolarTV.Machine.calldataWord call off = loadWord call.calldata off.toNat 32 := by + unfold SolarTV.Machine.calldataWord loadWord bufferRead bytesToNat + rw [show (0 : BitVec 256) = BitVec.ofNat 256 0 from rfl, foldl_word, List.foldl_map] + + +/-! ## SolarTV's steps, continued -/ + +open SolarTV.EVM.Program in +theorem exec_store {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {rest : List Instr} {x y : Word} {S : List Word} {s : SolarTV.Machine.State} + (h : S.length < 1023) : + exec o call b (.op .store :: rest) (x :: y :: S) s = + exec o call b rest S { s with memory := s.memory.store x.toNat y } := by + have h1 : ¬ 1024 < S.length + 1 + 1 := by omega + simp [exec, stepOp, h1] + +open SolarTV.EVM.Program in +theorem exec_effect0 {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {rest : List Instr} {e : SolarTV.Machine.Effect} {w : Word} {S : List Word} + {s : SolarTV.Machine.State} (happ : SolarTV.Machine.Effect.apply o call e [] s = some (some w, s)) + (h : S.length < 1024) : + exec o call b (.effect e 0 :: rest) S s = exec o call b rest (w :: S) s := by + simp [exec, happ, show ¬ 1024 < S.length + 1 by omega] + +open SolarTV.EVM.Program in +theorem exec_effect1 {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {rest : List Instr} {e : SolarTV.Machine.Effect} {x w : Word} {S : List Word} + {s : SolarTV.Machine.State} + (happ : SolarTV.Machine.Effect.apply o call e [x] s = some (some w, s)) (h : S.length < 1024) : + exec o call b (.effect e 1 :: rest) (x :: S) s = exec o call b rest (w :: S) s := by + simp [exec, happ, show ¬ 1024 < S.length + 1 by omega] + +open SolarTV.EVM.Program in +theorem exec_effect2 {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {rest : List Instr} {e : SolarTV.Machine.Effect} {x y : Word} {S : List Word} + {s s' : SolarTV.Machine.State} + (happ : SolarTV.Machine.Effect.apply o call e [x, y] s = some (none, s')) (h : S.length ≤ 1024) : + exec o call b (.effect e 2 :: rest) (x :: y :: S) s = exec o call b rest S s' := by + simp [exec, happ, show ¬ 1024 < S.length by omega] + +open SolarTV.EVM.Program in +theorem exec_keccak {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {rest : List Instr} {x y : Word} {S : List Word} {s : SolarTV.Machine.State} + (h : S.length < 1024) : + exec o call b (.effect .keccak256 2 :: rest) (x :: y :: S) s = + exec o call b rest (o.keccak ((s.memory.expand x.toNat y.toNat).read x.toNat y.toNat) :: S) + { s with memory := s.memory.expand x.toNat y.toNat } := by + simp [exec, SolarTV.Machine.Effect.apply, show ¬ 1024 < S.length + 1 by omega] + +open SolarTV.EVM.Program in +theorem exec_log {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {b : Nat} + {rest : List Instr} {x y : Word} {tops S : List Word} {s : SolarTV.Machine.State} + (h : S.length ≤ 1024) : + exec o call b (.effect (.log tops.length) (tops.length + 2) :: rest) (x :: y :: (tops ++ S)) s = + exec o call b rest S ⟨s.memory.expand x.toNat y.toNat, s.storage, s.transient, + s.world ++ [.log tops ((s.memory.expand x.toNat y.toNat).read x.toNat y.toNat)]⟩ := by + have ht : (x :: y :: (tops ++ S)).take (tops.length + 2) = x :: y :: tops := by simp + have hd : (x :: y :: (tops ++ S)).drop (tops.length + 2) = S := by simp + simp only [exec, List.length_cons, List.length_append, ht, hd] + simp [SolarTV.Machine.Effect.apply, show ¬ 1024 < S.length by omega, + show ¬ tops.length + S.length + 1 + 1 < tops.length + 2 by omega] + +theorem Inv.next2 {c : Cert} {code : ByteArray} {call : SolarTV.Call} {i1 i2 : Item} + {items : List Item} {k pc next : Nat} {S S' : List Word} {s : SolarTV.Machine.State} + {M : ByteArray} {g g' : Nat} (I : Inv c code call (i1 :: i2 :: items) k pc S s M g) + (hk : 2 ≤ k) (hseg : Seg (bytesOf code) c.offset next items code.size) + (hS : S'.length ≤ S.length + 1) (hg : g ≤ g' + 44200) : + Inv c code call items (k - 2) next S' s M g' where + seg := hseg + stack := by have := I.stack; omega + gas := by have := I.gas; omega + le_top := I.le_top + mem := I.mem + +theorem toNat_offset {code : ByteArray} {n : Nat} (h : n < code.size) (hs : code.size < 2 ^ 32) : + (BitVec.ofNat 256 n).toNat = n := by + rw [BitVec.toNat_ofNat] + exact Nat.mod_eq_of_lt (Nat.lt_trans (Nat.lt_trans h hs) (by decide)) + +/-- A jump's target block, with the invariant at its offset and potential, from the invariant +before the `m` items of the jump. -/ +theorem Inv.target {p : Program} {c : Cert} {code : ByteArray} (G : Glob p c code) + {call : SolarTV.Call} {t m : Nat} {items : List Item} {k pc : Nat} + {S S' : List Word} {s : SolarTV.Machine.State} {M : ByteArray} {g g' : Nat} + (I : Inv c code call items k pc S s M g) (htn : t < p.blocks.length) + (htgt : isTarget p c t = true) (hcost : cost p c t + m ≤ k) (hS : S'.length ≤ S.length) + (hg : g ≤ g' + 22100 * m) : + Inv c code call (lowerFrom p c t (p.blocks.drop t)) (cost p c t) (c.offset t) S' s M g' where + seg := (G.target t htn htgt).2.2 + stack := by have := I.stack; omega + gas := by + have := I.gas + have hm : 22100 * (cost p c t + m) ≤ 22100 * k := Nat.mul_le_mul_left _ hcost + rw [Nat.mul_add] at hm + omega + le_top := I.le_top + mem := I.mem + +open SolarTV.Machine in +/-- Growth of memory for a range keeps the relation of the memories. -/ +theorem memRel_expand {m : Mem} {M : ByteArray} {o sz : Word} (hm : MemRel m M) + (hbound : sz = 0 ∨ o.toNat + sz.toNat ≤ 2 ^ 32) : + MemRel (m.expand o.toNat sz.toNat) (memoryExtend M (extendMemory M.size [(o, sz)]).expandBy) := by + have hmod : M.size % 32 = 0 := by rw [hm.1]; omega + have hb : (m.expand o.toNat sz.toNat).bytes = m.bytes := by unfold Mem.expand; split <;> rfl + refine ⟨?_, fun i => by rw [byteAt_memoryExtend, hb]; exact hm.2 i⟩ + by_cases hz : sz = 0 + · subst hz + rw [extendMemory_zero', memoryExtend_zero] + simpa [Mem.expand] using hm.1 + · have hbound := hbound.resolve_left hz + rw [size_memoryExtend_extendMemory' hmod hz, hm.1, ceil32_eq] + have hz' : sz.toNat ≠ 0 := fun h => hz (BitVec.eq_of_toNat_eq (by simpa using h)) + unfold Mem.expand SolarTV.Memory.grow + simp only [hz', ite_false] + have hlt : (o.toNat + sz.toNat + 31) / 32 < 2 ^ 251 := by omega + split + · rename_i h + rw [BitVec.ult_iff_toNat_lt, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hlt] at h + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt hlt] + omega + · rename_i h + rw [BitVec.ult_iff_toNat_lt, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hlt] at h + omega + +/-- Bytes with the values of SolarTV's bytes are those bytes. -/ +theorem byteArray_eq_of_map {B : ByteArray} {d : List (BitVec 8)} + (h : B.toList.map (·.toNat) = d.map BitVec.toNat) : B = ⟨(d.map UInt8.ofBitVec).toArray⟩ := by + have e : B.toList = B.data.toList := by simp + have h1 : B.data.toList = d.map UInt8.ofBitVec := by + apply List.map_injective_iff.2 (fun a b hab => UInt8.toNat_inj.1 hab) + rw [← e, h, List.map_map] + apply List.map_congr_left + intro x _ + simp + cases B with + | mk data => + simp only at h1 + congr 1 + apply Array.toList_inj.1 + simpa using h1 + +theorem decode_log : ∀ n : Fin 5, Op.decode (UInt8.ofNat (0xa0 + n.val)) = some (.log n) := by + decide + +/-- An oracle whose CALLER is the caller of `Target`'s calls and whose hash is EthLib's. -/ +def OracleOk (o : SolarTV.Machine.Oracle) : Prop := + o.caller.setWidth 256 = (Target.address callerAddress).toU256 ∧ + ∀ bytes, o.keccak bytes = keccak ⟨(bytes.map UInt8.ofBitVec).toArray⟩ + +/-- An oracle whose environment reads of the fragment (`envRead`), in every world, are the words of +EthLib's environment of `Target`'s calls (`Target.blockEnv` and `Target.txEnv`). -/ +def EnvOk (o : SolarTV.Machine.Oracle) : Prop := + ∀ name byte w, envRead name = some (byte, w) → ∀ world, o.env name world [] = BitVec.ofNat 256 w + +/-- Any oracle with the reads of EthLib's environment. -/ +def envOracle (o : SolarTV.Machine.Oracle) : SolarTV.Machine.Oracle := + { o with env := fun name world args => + match envRead name, args with + | some (_, w), [] => BitVec.ofNat 256 w + | _, _ => o.env name world args } + +/-- `EnvOk` is no vacuous hypothesis: every oracle has a form that meets it. -/ +theorem envOracle_ok (o : SolarTV.Machine.Oracle) : EnvOk (envOracle o) := by + intro name byte w h world + simp [envOracle, h] + +/-- Any oracle with EthLib's caller and hash. -/ +def ethOracle (o : SolarTV.Machine.Oracle) : SolarTV.Machine.Oracle := + { o with caller := BitVec.ofNat 160 callerAddress, + keccak := fun bytes => keccak ⟨(bytes.map UInt8.ofBitVec).toArray⟩ } + +theorem ethOracle_ok (o : SolarTV.Machine.Oracle) : OracleOk (ethOracle o) := + ⟨show (BitVec.ofNat 160 callerAddress).setWidth 256 = (Target.address callerAddress).toU256 by + decide +kernel, fun _ => rfl⟩ + +theorem forall₂_snoc {α β : Type} {R : α → β → Prop} {a : α} {b : β} : + ∀ {l1 : List α} {l2 : List β}, List.Forall₂ R l1 l2 → R a b → + List.Forall₂ R (l1 ++ [a]) (l2 ++ [b]) + | [], [], .nil, h => .cons h .nil + | _ :: _, _ :: _, .cons h1 t, h => .cons h1 (forall₂_snoc t h) + +/-- A log is the last log of the world it ends. -/ +theorem filter_snoc_log {w : List SolarTV.Machine.Event} {t d} : + (w ++ [SolarTV.Machine.Event.log t d]).filter isLogE = w.filter isLogE ++ [.log t d] := by + rw [List.filter_append] + rfl + +/-- A read of the world writes no log. -/ +theorem logsRel_read {a : Address} {ss0 ss : Substate} {w : List SolarTV.Machine.Event} (n : String) + (h : LogsRel a ss0 ss w) : LogsRel a ss0 ss (w ++ [.read n]) := by + obtain ⟨L, h1, h2⟩ := h + refine ⟨L, h1, ?_⟩ + rw [List.filter_append] + simpa [isLogE] using h2 + +/-! ## The simulation of a block -/ + +/-- The first instruction of a walk segment and the segment after it. -/ +theorem Seg.head {code : List Nat} {offset : Nat → Nat} {pc e : Nat} {item : Item} + {items : List Item} (h : Seg code offset pc (item :: items) e) : + ∃ next, decode code pc = some (item.expected offset, next) ∧ Seg code offset next items e := by + cases h with | cons d _ r => exact ⟨_, d, r⟩ + +open SolarTV.EVM.Program in +/-- EthLib runs the code of a block's instructions from the offset of the next one as SolarTV +runs them. -/ +theorem exec_sim {p : Program} {c : Cert} {code : ByteArray} (G : Glob p c code) + {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) (ho : c.env = true → OracleOk o) + (b : Nat) (hb : b < p.blocks.length) : + ∀ (is : List Instr) (h : Nat) (known : List Word) (ty : List Ty) (S T : List Word) (k : Nat) + (s : SolarTV.Machine.State) (pc : Nat) (M : ByteArray) (g : Nat) + (st : State.TransactionState) (ss : Substate), + blockOk p c b h known ty k is = true → h ≤ S.length → known <+: S → SR c ty S T → + Inv c code call (lowerInstrs p c b is ++ lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) k + pc S s M g → Rel msg ss0 st ss s → + SimOut p c code call msg ss0 st ss pc T M g (exec o call b is S s) + | [], h, known, ty, S, T, k, s, pc, M, g, st, ss, hok, hh, _, hR, I, R => by + simp only [blockOk, fallOk, Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at hok + have I2 := I.weaken hok.2 + simp only [lowerInstrs, List.nil_append] at I2 + simp only [exec, SimOut] + exact ⟨⟨by omega, fun ht => by omega⟩, pc, T, M, g, st, ss, Triple.of_imp fun _ h => h, + SR.le hok.1.2 hR, I2, R⟩ + | i :: rest, h, known, ty, S, T, k, s, pc, M, g, st, ss, hok, hh, hk, hR, I, R => by + have hL := hR.length + have hctx : (⟨BitVec.ofNat 256 msg.data.size, o.env "returndatasize" s.world []⟩ : + SolarTV.EVM.Context) = context o call s := by rw [hdata]; rfl + cases hT : turnedElse c b i rest with + | some e => + -- A turned branch: ISZERO; PUSH e; JUMPI, falling into the next block. + obtain ⟨rfl, rfl⟩ := turnedElse_some hT + simp only [blockOk, hT, jumpOk, fallOk, Bool.and_eq_true, Bool.or_eq_true, + decide_eq_true_eq] at hok + obtain ⟨⟨⟨⟨hk3, h1⟩, hdat⟩, ⟨⟨⟨hen, hetgt⟩, hneed⟩, hety⟩, hcost⟩, ⟨hfall, hfty⟩, hcost'⟩ := hok + simp only [lowerInstrs, hT, List.cons_append, List.nil_append] at I + rcases S with _ | ⟨cond, S'⟩ + · simp at hh; omega + rcases T with _ | ⟨cond', T'⟩ + · simp at hL + obtain rfl := (SR.head hR hdat).symm + have hR' := (SR.uncons.1 hR).2 + simp only [List.length_cons] at hL + obtain ⟨n0, hd0, hs0⟩ := I.seg.head + obtain ⟨n1, hd1, hs1⟩ := hs0.head + obtain ⟨n2, hd2, hseg⟩ := hs1.head + simp only [Item.expected] at hd0 hd1 hd2 + obtain ⟨hlt0, hcode0, rfl⟩ := op_item hd0 + obtain ⟨hlt2, hcode2, rfl⟩ := op_item hd2 + have hS := I.stack; have hG := I.gas + simp only [List.length_cons] at hS hh + obtain ⟨g0, hg0, hisz⟩ := stack_rule (msg := msg) (M := M) (st := st) (ss := ss) (gas := g) + (op := .iszero) (stack := cond :: T') (next := EvmRules.Evm.iszero cond :: T') + (r := o.env "returndatasize" s.world []) rfl hlt0 hcode0 rfl (by omega) + (by simp only [List.length_cons]; omega) + obtain ⟨g1, hg1, hpush⟩ := push_item (msg := msg) (M := M) (st := st) (ss := ss) + (gas := g0) (stack := EvmRules.Evm.iszero cond :: T') hd1 (by omega) + (by simp only [List.length_cons]; omega) + by_cases hc : cond = 0 + · -- The condition is zero: ISZERO gives one and the code jumps to the else block. + subst hc + have hoff := toNat_offset (G.target e hen hetgt).2.1 G.size_lt + have hj := Logic.jumpi_taken (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (destination := BitVec.ofNat 256 (c.offset e)) + (rest := T') hlt2 hcode2 (show 10 ≤ g1 by omega) iszero_zero + (by rw [hoff]; exact (G.target e hen hetgt).1) + rw [hoff] at hj + simp only [exec, List.length_cons, show ¬ S'.length + 1 + 1 > 1024 by omega, + show ¬ S'.length + 1 > 1024 by omega, ite_false, ite_true, SimOut] + exact ⟨⟨by omega, fun _ => by omega⟩, c.offset e, T', M, g1 - 10, st, ss, + Triple.seq hisz (Triple.seq hpush hj), SR.le hety hR', + I.target G hen hetgt (m := 3) (by omega) (by simp) (by omega), R⟩ + · -- The condition is not zero: ISZERO gives zero and the code falls into the next block. + have hj := Logic.jumpi_of_eq_zero (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (destination := BitVec.ofNat 256 (c.offset e)) + (rest := T') hlt2 hcode2 (show 10 ≤ g1 by omega) (iszero_nonzero hc) + simp only [exec, List.length_cons, show ¬ S'.length + 1 + 1 > 1024 by omega, ite_false, + hc, SimOut] + refine ⟨⟨by omega, fun _ => by omega⟩, _, T', M, g1 - 10, st, ss, + Triple.seq hisz (Triple.seq hpush hj), SR.le hfty hR', + ⟨hseg, by omega, ?_, I.le_top, I.mem⟩, R⟩ + have hm : 22100 * (cost p c (b + 1) + 3) ≤ 22100 * k := Nat.mul_le_mul_left _ (by omega) + rw [Nat.mul_add] at hm + omega + | none => + by_cases hD : dropped p b i rest = true + · rcases dropped_true hD with ⟨rfl, rfl⟩ | ⟨rfl, rfl, hn⟩ + · -- A jump to the next block, left out: the code falls into it. + simp only [blockOk, hT, hD, ite_true, fallOk, Bool.and_eq_true, Bool.or_eq_true, + decide_eq_true_eq] at hok + simp only [lowerInstrs, hT, hD, ite_true, List.nil_append] at I + have hS := I.stack + simp only [exec, show ¬ S.length + 1 > 1024 by omega, ite_false, SimOut] + exact ⟨⟨by omega, fun _ => by omega⟩, pc, T, M, g, st, ss, Triple.of_imp fun _ h => h, + SR.le hok.1.2 hR, I.weaken hok.2, R⟩ + · -- The last block's STOP, left out: the code ends. + simp only [lowerInstrs, hT, hD, ite_true, List.nil_append] at I + have hseg := I.seg + rw [lowerFrom_nil p c (by omega)] at hseg + have hpc := hseg.nil_end + simp only [exec, SimOut] + exact Spec.consequence (Logic.stop_of_size_le (by omega)) + (fun _ h => h) fun evm h => postL_stop R hself evm h + have hD' : dropped p b i rest = false := by simpa using hD + have hok' : blockStep p c (fun h known ty k => blockOk p c b h known ty k rest) h known ty k i = + true := by + simpa only [blockOk, hT, hD', Bool.false_eq_true, ite_false] using hok + have I' : Inv c code call (lowerInstr i ++ (lowerInstrs p c b rest ++ + lowerFrom p c (b + 1) (p.blocks.drop (b + 1)))) k pc S s M g := by + simpa only [lowerInstrs, hT, hD', Bool.false_eq_true, ite_false, List.append_assoc] using I + clear hok hD hD' hT + have IH := exec_sim (o := o) (ss0 := ss0) G hdata hvalue hstatic hself hcaller ho b hb rest + rcases i with mop | ⟨e, ar⟩ | t | t | t | _ | _ | _ | _ | _ | _ | _ + · rcases mop with sop | _ | _ | _ | _ | _ | _ + · by_cases hpush : ∃ v, sop = .push v + · obtain ⟨v, rfl⟩ := hpush + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok' + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + have hS := I'.stack; have hG := I'.gas + obtain ⟨g1, hg1, hpush⟩ := push_item (msg := msg) (M := M) (st := st) (ss := ss) (gas := g) + (stack := T) hd (by omega) (by omega) + have hv : BitVec.ofNat 256 v.toNat = v := by simp + rw [hv] at hpush + rw [exec_stack (next := v :: S) rfl (by omega) (by simp; omega)] + exact SimOut.pre hpush (IH (h + 1) (v :: known.take 1) _ (v :: S) (v :: T) (k - 1) s next M g1 + st ss hok'.2 (by simp; omega) + ((List.prefix_cons_inj v).2 ((List.take_prefix 1 known).trans hk)) + (SR.cons (τ := some false) rfl hR) (I'.next hok'.1 hseg (by simp) (by omega)) R) + · have hne : ∀ v, sop ≠ .push v := fun v he => hpush ⟨v, he⟩ + obtain ⟨hk1, byte, hbyte, h', ty', S', T', hstep, hstepT, hR', hh', hlen', known', hkn, + hok⟩ := stack_sim (ctx := context o call s) hne hok' hh hk hR + rw [lowerInstr_stack hne, hbyte] at I' + simp only [Option.getD_some, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + rw [← hctx] at hstepT + have hS := I'.stack; have hG := I'.gas + obtain ⟨g1, hg1, hrule⟩ := stack_rule (M := M) (st := st) (ss := ss) (gas := g) + (stack := T) hbyte hlt hcode hstepT (by omega) (by omega) + rw [exec_stack hstep (by omega) (by omega)] + exact SimOut.pre hrule (IH h' known' ty' S' T' (k - 1) s (pc + 1) M g1 st ss hok (by omega) + hkn hR' (I'.next hk1 hseg (by omega) (by omega)) R) + · simp [blockStep] at hok' + · -- MSTORE. + rcases known with _ | ⟨ow, known'⟩ + · simp [blockStep] at hok' + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨⟨hk1, h2⟩, hin⟩, hdat⟩, hok'⟩ := hok' + rcases S with _ | ⟨x, _ | ⟨v, S'⟩⟩ + · simp at hh; omega + · simp at hh; omega + rcases T with _ | ⟨x', _ | ⟨v', T'⟩⟩ + · simp at hL + · simp at hL + have htake := hR.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR' : SR c (ty.drop 2) S' T' := by simpa using SR.drop 2 hR + obtain ⟨rfl, -⟩ := List.cons_prefix_cons.1 hk + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hG hh hL + have hmod : M.size % 32 = 0 := by rw [I'.mem.1]; omega + obtain ⟨hle, hcost⟩ := extend_cost (o := ow) (sz := 32) hmod G.top_mod I'.le_top + (Or.inr hin) + obtain ⟨hmem', hsize⟩ := memRel_store (o := ow) (v := v) I'.mem (by have := G.top_le; omega) + have hext := size_memoryExtend_extendMemory' (memory := M) (start := ow) (length := 32) + hmod (by decide) + rw [size_memoryExtend] at hext + have h32 : (32 : U256).toNat = 32 := rfl + rw [h32] at hext + have hM' : (memoryWrite (memoryExtend M (extendMemory M.size [(ow, 32)]).expandBy) + ow.toNat (wordBytes v)).size = M.size + (extendMemory M.size [(ow, 32)]).expandBy := by + rw [hsize, hext] + rw [exec_store (by omega)] + refine SimOut.pre (Logic.mstore (start := ow) (value := v) (rest := T') (memory := M) + (gas := g) hlt hcode (by omega)) (IH (h - 2) [] _ S' T' (k - 1) _ (pc + 1) _ _ st ss hok' + (by omega) (List.nil_prefix) hR' ⟨hseg, by omega, ?_, by rw [hM']; omega, hmem'⟩ + ⟨R.storage, R.account, R.logs⟩) + rw [hM']; omega + · simp [blockStep] at hok' + · simp [blockStep] at hok' + · simp [blockStep] at hok' + · simp [blockStep] at hok' + · rcases e with _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | n | _ | _ | _ + all_goals try (simp [blockStep] at hok'; done) + · -- SLOAD. + rcases ar with _ | _ | ar + · simp [blockStep] at hok' + rotate_left + · simp [blockStep] at hok' + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨hk1, h1⟩, hdat⟩, hok⟩ := hok' + rcases S with _ | ⟨x, S'⟩ + · simp at hh; omega + rcases T with _ | ⟨x', T'⟩ + · simp at hL + obtain rfl := (SR.head hR hdat).symm + have hR' := (SR.uncons.1 hR).2 + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hG hh hL + rw [exec_effect1 (w := s.storage x) rfl (by omega)] + have hrule := Logic.sload (message := msg) (memory := M) (state := st) (substate := ss) + (returnData := .empty) (key := x) (rest := T') (gas := g) (by decide) hlt hcode rfl + (by split <;> omega) + rw [R.storage x] at hrule + refine SimOut.pre hrule ?_ + have hreads := fun k : Word => State.TransactionState.recordStorageRead_reads st + msg.currentTarget msg.currentTarget (U256.toBeBytes x) (U256.toBeBytes k) default + refine IH h [] _ _ _ (k - 1) s (pc + 1) M _ _ _ hok (by simp; omega) (List.nil_prefix) + (SR.cons (τ := some false) rfl (by simpa using hR')) (I'.next hk1 hseg (by simp) (by split <;> omega)) + ⟨fun k => ?_, ?_, R.logs⟩ + · rw [(hreads k).2.1] + exact R.storage k + · rw [(hreads x).1] + exact R.account + · -- SSTORE. + rcases ar with _ | _ | _ | ar + · simp [blockStep] at hok' + · simp [blockStep] at hok' + rotate_left + · simp [blockStep] at hok' + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨hk1, h2⟩, hdat⟩, hok⟩ := hok' + rcases S with _ | ⟨x, _ | ⟨v, S'⟩⟩ + · simp at hh; omega + · simp at hh; omega + rcases T with _ | ⟨x', _ | ⟨v', T'⟩⟩ + · simp at hL + · simp at hL + have htake := hR.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR' : SR c (ty.drop 2) S' T' := by simpa using SR.drop 2 hR + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hG hh hL + rw [exec_effect2 (s' := { s with storage := SolarTV.Machine.update s.storage x v }) rfl + (by omega)] + have hcost := sstoreCost_le (st.getStorageOriginal msg.currentTarget (U256.toBeBytes x)) + (st.getStorage msg.currentTarget (U256.toBeBytes x)) v + (decide (U256.toBeBytes x ∉ ss.accessedStorageKeys.getD msg.currentTarget ∅)) + obtain ⟨st', hnew, hothers, -, hacc, -, -, hrule⟩ := Logic.sstore_of_account + (message := msg) (memory := M) (state := st) (substate := ss) (returnData := .empty) + (key := x) (new := v) (rest := T') (gas := g) (by decide) (by decide) hlt hcode hstatic + rfl (by simp only [CALL_STIPEND]; omega) (by omega) R.account + refine SimOut.pre hrule ?_ + refine IH (h - 2) [] _ S' T' (k - 1) _ (pc + 1) M _ _ _ hok (by omega) (List.nil_prefix) + hR' ?_ ⟨fun k => ?_, by rw [hacc]; exact R.account, R.logs⟩ + · exact ⟨hseg, by omega, by omega, I'.le_top, I'.mem⟩ + by_cases hk : k = x + · subst hk + rw [hnew] + simp [SolarTV.Machine.update] + · rw [hothers _ _ (Or.inr fun he => hk (U256.toBeBytes_inj he)), R.storage k] + simp [SolarTV.Machine.update, hk] + · -- CALLDATALOAD. + rcases ar with _ | _ | ar + · simp [blockStep] at hok' + rotate_left + · simp [blockStep] at hok' + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨hk1, h1⟩, hdat⟩, hok⟩ := hok' + rcases S with _ | ⟨x, S'⟩ + · simp at hh; omega + rcases T with _ | ⟨x', T'⟩ + · simp at hL + obtain rfl := (SR.head hR hdat).symm + have hR' := (SR.uncons.1 hR).2 + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hG hh hL + rw [exec_effect1 (w := SolarTV.Machine.calldataWord call x) rfl (by omega)] + have hrule := Logic.calldataload (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (start := x) (rest := T') (gas := g) hlt hcode + (by omega) + rw [hdata, ← calldataWord_eq] at hrule + exact SimOut.pre hrule (IH h [] _ _ _ (k - 1) s (pc + 1) M (g - 3) st ss hok (by simp; omega) + (List.nil_prefix) (SR.cons (τ := some false) rfl (by simpa using hR')) (I'.next hk1 hseg (by simp) (by omega)) R) + · -- CALLDATASIZE. + rcases ar with _ | ar + rotate_left + · simp [blockStep] at hok' + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨hk1, hok⟩ := hok' + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + rw [exec_effect0 (w := BitVec.ofNat 256 call.calldata.size) rfl (by omega)] + have hrule := Logic.calldatasize (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (stack := T) (gas := g) hlt hcode (by omega) + (by unfold STACK_LIMIT; omega) + rw [hdata] at hrule + exact SimOut.pre hrule (IH (h + 1) [] _ _ _ (k - 1) s (pc + 1) M (g - 2) st ss hok + (by simp; omega) (List.nil_prefix) (SR.cons (τ := some false) rfl hR) (I'.next hk1 hseg (by simp) (by omega)) R) + · -- CALLVALUE. + rcases ar with _ | ar + rotate_left + · simp [blockStep] at hok' + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨hk1, hok⟩ := hok' + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + rw [exec_effect0 (w := BitVec.ofNat 256 call.callvalue) rfl (by omega)] + have hrule := Logic.callvalue (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (stack := T) (gas := g) hlt hcode (by omega) + (by unfold STACK_LIMIT; omega) + rw [hvalue] at hrule + exact SimOut.pre hrule (IH (h + 1) [] _ _ _ (k - 1) s (pc + 1) M (g - 2) st ss hok + (by simp; omega) (List.nil_prefix) (SR.cons (τ := some false) rfl hR) (I'.next hk1 hseg (by simp) (by omega)) R) + · -- CALLER. + rcases ar with _ | ar + rotate_left + · simp [blockStep] at hok' + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨henv, hk1⟩, hok⟩ := hok' + obtain ⟨hoc, -⟩ := ho henv + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + rw [exec_effect0 (w := o.caller.setWidth 256) rfl (by omega)] + have hrule := Logic.caller (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (stack := T) (gas := g) hlt hcode (by omega) + (by unfold STACK_LIMIT; omega) + rw [hcaller, ← hoc] at hrule + exact SimOut.pre hrule (IH (h + 1) [] _ _ _ (k - 1) s (pc + 1) M (g - 2) st ss hok + (by simp; omega) (List.nil_prefix) (SR.cons (τ := some false) rfl hR) (I'.next hk1 hseg (by simp) (by omega)) R) + · -- LOGn. + rcases known with _ | ⟨ow, _ | ⟨sw, known'⟩⟩ + · simp [blockStep] at hok' + · simp [blockStep] at hok' + simp only [blockStep, rangeOk, Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨⟨⟨⟨⟨hn4, rfl⟩, hk1⟩, hnh⟩, hdat⟩, hin⟩, hlc⟩, hok⟩ := hok' + rcases S with _ | ⟨x, _ | ⟨y, S1⟩⟩ + · simp at hk + · simp at hk + obtain ⟨rfl, hk'⟩ := List.cons_prefix_cons.1 hk + obtain ⟨rfl, -⟩ := List.cons_prefix_cons.1 hk' + rcases T with _ | ⟨x', _ | ⟨y', T1⟩⟩ + · simp at hL + · simp at hL + simp only [List.length_cons] at hh hL + obtain ⟨tops, S2, rfl, hlen⟩ : ∃ tops S2, S1 = tops ++ S2 ∧ tops.length = n := + ⟨S1.take n, S1.drop n, (List.take_append_drop n S1).symm, by simp; omega⟩ + obtain ⟨tops', T2, rfl, hlen'⟩ : ∃ tops' T2, T1 = tops' ++ T2 ∧ tops'.length = n := + ⟨T1.take n, T1.drop n, (List.take_append_drop n T1).symm, by simp; omega⟩ + subst hlen + have htake := hR.data hdat + simp only [List.take_succ_cons, List.cons.injEq, List.take_left' hlen', + List.take_left' rfl] at htake + obtain ⟨rfl, rfl, rfl⟩ := htake + have hR' : SR c (ty.drop (tops.length + 2)) S2 T2 := by + simpa using SR.drop (tops.length + 2) hR + simp only [lowerInstr, hn4, ite_true, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons, List.length_append] at hS hG hh hL + have hmod : M.size % 32 = 0 := by rw [I'.mem.1]; omega + obtain ⟨hle, hcost⟩ := extend_cost (o := ow) (sz := sw) hmod G.top_mod I'.le_top + (hin.imp_left fun h0 => BitVec.eq_of_toNat_eq (by simpa using h0)) + have hbound : sw = 0 ∨ ow.toNat + sw.toNat ≤ 2 ^ 32 := + hin.imp (fun h0 => BitVec.eq_of_toNat_eq (by simpa using h0)) + (fun h0 => by have := G.top_le; omega) + have hrule := Logic.log (n := ⟨tops.length, by omega⟩) (message := msg) (memory := M) + (state := st) (substate := ss) (returnData := .empty) (start := ow) (size := sw) + (words := tops) (rest := T2) (gas := g) rfl hlt hcode (decode_log ⟨tops.length, by omega⟩) hstatic + (show logCost tops.length sw + (extendMemory M.size [(ow, sw)]).cost ≤ g by omega) + dsimp only at hrule + rw [exec_log (by omega)] + have hM' := size_memoryExtend M (extendMemory M.size [(ow, sw)]).expandBy + obtain ⟨L, hL1, hL2⟩ := R.logs + refine SimOut.pre hrule (IH (h - (tops.length + 2)) [] _ S2 T2 (k - 1) _ (pc + 1) _ _ st _ + hok (by omega) (List.nil_prefix) hR' ⟨hseg, by omega, ?_, by rw [hM']; omega, + memRel_expand I'.mem hbound⟩ ⟨R.storage, R.account, ?_⟩) + · rw [hM']; omega + · refine ⟨L ++ [⟨msg.currentTarget, tops.map U256.toBeBytes, + memoryReadBytes (memoryExtend M (extendMemory M.size [(ow, sw)]).expandBy) + ow.toNat sw.toNat⟩], by simp [Array.toList_push, hL1], + filter_snoc_log ▸ forall₂_snoc hL2 ⟨rfl, rfl, ?_⟩⟩ + exact read_eq I'.mem + · -- KECCAK256. + rcases ar with _ | _ | _ | ar + · simp [blockStep] at hok' + · simp [blockStep] at hok' + rotate_left + · simp [blockStep] at hok' + rcases known with _ | ⟨ow, _ | ⟨sw, known'⟩⟩ + · simp [blockStep] at hok' + · simp [blockStep] at hok' + simp only [blockStep, rangeOk, Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨⟨⟨⟨henv, hk1⟩, h2⟩, hdat⟩, hin⟩, hkc⟩, hok⟩ := hok' + rcases S with _ | ⟨x, _ | ⟨y, S'⟩⟩ + · simp at hk + · simp at hk + obtain ⟨rfl, hk'⟩ := List.cons_prefix_cons.1 hk + obtain ⟨rfl, -⟩ := List.cons_prefix_cons.1 hk' + rcases T with _ | ⟨x', _ | ⟨y', T'⟩⟩ + · simp at hL + · simp at hL + have htake := hR.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + have hR' : SR c (ty.drop 2) S' T' := by simpa using SR.drop 2 hR + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hG hh hL + have hmod : M.size % 32 = 0 := by rw [I'.mem.1]; omega + obtain ⟨hle, hcost⟩ := extend_cost (o := ow) (sz := sw) hmod G.top_mod I'.le_top + (hin.imp_left fun h0 => BitVec.eq_of_toNat_eq (by simpa using h0)) + have hbound : sw = 0 ∨ ow.toNat + sw.toNat ≤ 2 ^ 32 := + hin.imp (fun h0 => BitVec.eq_of_toNat_eq (by simpa using h0)) + (fun h0 => by have := G.top_le; omega) + obtain ⟨-, hkec⟩ := ho henv + have hrule := Logic.keccak256 (message := msg) (memory := M) (state := st) (substate := ss) + (returnData := .empty) (start := ow) (size := sw) (rest := T') (gas := g) hlt hcode + (by omega) + rw [byteArray_eq_of_map (read_eq I'.mem), ← hkec] at hrule + rw [exec_keccak (by omega)] + have hM' := size_memoryExtend M (extendMemory M.size [(ow, sw)]).expandBy + refine SimOut.pre hrule (IH (h - 1) [] _ _ _ (k - 1) _ (pc + 1) _ _ st ss hok + (by simp; omega) (List.nil_prefix) (SR.cons (τ := some false) rfl hR') ⟨hseg, by simp; omega, ?_, + by rw [hM']; omega, memRel_expand I'.mem hbound⟩ ⟨R.storage, R.account, R.logs⟩) + rw [hM']; omega + · -- JUMP. + simp only [blockStep, jumpOk, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨hk2, ⟨⟨⟨⟨htn, htgt⟩, hneed⟩, hty⟩, hcost⟩⟩ := hok' + simp only [lowerInstr, List.cons_append, List.nil_append] at I' + obtain ⟨n1, hd1, hs1⟩ := I'.seg.head + obtain ⟨n2, hd2, -⟩ := hs1.head + simp only [Item.expected] at hd1 hd2 + obtain ⟨hlt2, hcode2, rfl⟩ := op_item hd2 + have hS := I'.stack; have hG := I'.gas + have hoff := toNat_offset (G.target t htn htgt).2.1 G.size_lt + obtain ⟨g1, hg1, hpush⟩ := push_item (msg := msg) (M := M) (st := st) (ss := ss) (gas := g) + (stack := T) hd1 (by omega) (by omega) + have hj := Logic.jump (message := msg) (memory := M) (state := st) (substate := ss) + (returnData := .empty) (rest := T) hlt2 hcode2 (show 8 ≤ g1 by omega) + (by rw [hoff]; exact (G.target t htn htgt).1) + rw [hoff] at hj + simp only [exec, show ¬ S.length + 1 > 1024 by omega, ite_false, SimOut] + exact ⟨⟨by omega, fun _ => le_trans hneed hh⟩, c.offset t, T, M, g1 - 8, st, ss, + Triple.seq hpush hj, SR.le hty hR, + I'.target G htn htgt (m := 2) (by omega) (le_refl _) (by omega), R⟩ + · -- JUMPI. + simp only [blockStep, jumpOk, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨⟨hk2, h1⟩, hdat⟩, ⟨⟨⟨⟨htn, htgt⟩, hneed⟩, hty⟩, hcost⟩⟩, hok'⟩ := hok' + rcases S with _ | ⟨cond, S'⟩ + · simp at hh; omega + rcases T with _ | ⟨cond', T'⟩ + · simp at hL + obtain rfl := (SR.head hR hdat).symm + have hR' := (SR.uncons.1 hR).2 + simp only [lowerInstr, List.cons_append, List.nil_append] at I' + obtain ⟨n1, hd1, hs1⟩ := I'.seg.head + obtain ⟨n2, hd2, hseg⟩ := hs1.head + simp only [Item.expected] at hd1 hd2 + obtain ⟨hlt2, hcode2, rfl⟩ := op_item hd2 + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hh hL + have hoff := toNat_offset (G.target t htn htgt).2.1 G.size_lt + obtain ⟨g1, hg1, hpush⟩ := push_item (msg := msg) (M := M) (st := st) (ss := ss) (gas := g) + (stack := cond :: T') hd1 (by omega) (by simp; omega) + by_cases hc : cond = 0 + · subst hc + have hj := Logic.jumpi_of_eq_zero (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (destination := BitVec.ofNat 256 (c.offset t)) + (rest := T') hlt2 hcode2 (show 10 ≤ g1 by omega) rfl + simp only [exec, List.length_cons, show ¬ S'.length + 1 + 1 > 1024 by omega, ite_false, + ite_true] + exact SimOut.pre (Triple.seq hpush hj) (IH (h - 1) [] _ S' T' (k - 2) s (n1 + 1) M + (g1 - 10) st ss hok' (by omega) (List.nil_prefix) hR' + (I'.next2 hk2 hseg (by simp only [List.length_cons]; omega) (by omega)) R) + · have hj := Logic.jumpi_taken (message := msg) (memory := M) (state := st) + (substate := ss) (returnData := .empty) (destination := BitVec.ofNat 256 (c.offset t)) + (rest := T') hlt2 hcode2 (show 10 ≤ g1 by omega) hc + (by rw [hoff]; exact (G.target t htn htgt).1) + rw [hoff] at hj + simp only [exec, List.length_cons, show ¬ S'.length + 1 + 1 > 1024 by omega, ite_false, + hc, SimOut] + exact ⟨⟨by omega, fun _ => by omega⟩, c.offset t, T', M, g1 - 10, st, ss, + Triple.seq hpush hj, SR.le hty hR', + I'.target G htn htgt (m := 2) (by omega) (by simp) (by omega), R⟩ + · -- A pushed return label: a PUSH of the block's offset. + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq] at hok' + obtain ⟨⟨⟨hk1, hmem⟩, ht32⟩, hok⟩ := hok' + have hmem' : t ∈ c.rets := by simpa using hmem + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + have hS := I'.stack; have hG := I'.gas + obtain ⟨g1, hg1, hpush⟩ := push_item (msg := msg) (M := M) (st := st) (ss := ss) (gas := g) + (stack := T) hd (by omega) (by omega) + have htn : (BitVec.ofNat 256 t).toNat = t := by + rw [BitVec.toNat_ofNat]; exact Nat.mod_eq_of_lt (by omega) + simp only [exec, show ¬ S.length + 1 > 1024 by omega, ite_false] + exact SimOut.pre hpush (IH (h + 1) [] _ _ _ (k - 1) s next M g1 st ss hok (by simp; omega) + (List.nil_prefix) (SR.cons ⟨by rw [htn]; exact hmem', by rw [htn]⟩ hR) + (I'.next hk1 hseg (by simp) (by omega)) R) + · -- A dynamic jump to a return label: a JUMP to the label's offset. + simp only [blockStep, Bool.and_eq_true, decide_eq_true_eq, beq_iff_eq, + List.all_eq_true] at hok' + obtain ⟨⟨⟨hk1, h1⟩, hlab⟩, hall⟩ := hok' + rcases S with _ | ⟨x, S'⟩ + · simp at hh; omega + rcases T with _ | ⟨y, T'⟩ + · simp at hL + obtain ⟨hw, hR'⟩ := SR.uncons.1 hR + rw [hlab] at hw + obtain ⟨hmem, rfl⟩ := hw + have hj' := hall _ hmem + simp only [jumpOk, Bool.and_eq_true, decide_eq_true_eq] at hj' + obtain ⟨⟨⟨⟨htn, htgt⟩, hneed⟩, hty⟩, hcost⟩ := hj' + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, -⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hS := I'.stack; have hG := I'.gas + simp only [List.length_cons] at hS hh hL + have hoff := toNat_offset (G.target _ htn htgt).2.1 G.size_lt + have hj := Logic.jump (message := msg) (memory := M) (state := st) (substate := ss) + (returnData := .empty) (destination := BitVec.ofNat 256 (c.offset x.toNat)) (rest := T') + hlt hcode (show 8 ≤ g by omega) (by rw [hoff]; exact (G.target _ htn htgt).1) + rw [hoff] at hj + simp only [exec, SimOut] + exact ⟨⟨by omega, fun _ => by omega⟩, c.offset x.toNat, T', M, g - 8, st, ss, hj, + SR.le hty hR', I'.target G htn htgt (m := 1) (by omega) (by simp) (by omega), R⟩ + · -- A conditional dynamic jump and a jump table: outside the fragment. + simp [blockStep] at hok' + · simp [blockStep] at hok' + · -- STOP. + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, -⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + simp only [exec, SimOut] + exact Spec.consequence (Logic.stop hlt hcode) (fun _ h => h) + fun evm h => postL_stop R hself evm h + · -- RETURN. + rcases known with _ | ⟨ow, _ | ⟨sw, known'⟩⟩ + · simp [blockStep] at hok' + · simp [blockStep] at hok' + simp only [blockStep, rangeOk, Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at hok' + obtain ⟨hdat, hin⟩ := hok' + rcases S with _ | ⟨x, _ | ⟨y, S'⟩⟩ + · simp at hk + · simp at hk + obtain ⟨rfl, hk'⟩ := List.cons_prefix_cons.1 hk + obtain ⟨rfl, -⟩ := List.cons_prefix_cons.1 hk' + rcases T with _ | ⟨x', _ | ⟨y', T'⟩⟩ + · simp at hL + · simp at hL + have htake := hR.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, -⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + have hG := I'.gas + have hmod : M.size % 32 = 0 := by rw [I'.mem.1]; omega + obtain ⟨-, hcost⟩ := extend_cost (o := ow) (sz := sw) hmod G.top_mod I'.le_top + (hin.imp_left fun h0 => BitVec.eq_of_toNat_eq (by simpa using h0)) + simp only [exec, SolarTV.EVM.Program.output, SimOut, Bool.false_eq_true, ↓reduceIte] + exact Spec.consequence (return_postS (ss := ss) hlt hcode (by omega) rfl + (by rw [read_eq I'.mem]; rfl) rfl (R.slot hself)) (fun _ h => h) + (fun _ h => ⟨ss, h, R.logs⟩) + · -- REVERT. + rcases known with _ | ⟨ow, _ | ⟨sw, known'⟩⟩ + · simp [blockStep] at hok' + · simp [blockStep] at hok' + simp only [blockStep, rangeOk, Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at hok' + obtain ⟨hdat, hin⟩ := hok' + rcases S with _ | ⟨x, _ | ⟨y, S'⟩⟩ + · simp at hk + · simp at hk + obtain ⟨rfl, hk'⟩ := List.cons_prefix_cons.1 hk + obtain ⟨rfl, -⟩ := List.cons_prefix_cons.1 hk' + rcases T with _ | ⟨x', _ | ⟨y', T'⟩⟩ + · simp at hL + · simp at hL + have htake := hR.data hdat + simp only [List.take_succ_cons, List.take_zero, List.cons.injEq] at htake + obtain ⟨rfl, rfl, -⟩ := htake + simp only [lowerInstr, List.singleton_append] at I' + obtain ⟨next, hd, -⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, -⟩ := op_item hd + have hG := I'.gas + have hmod : M.size % 32 = 0 := by rw [I'.mem.1]; omega + obtain ⟨-, hcost⟩ := extend_cost (o := ow) (sz := sw) hmod G.top_mod I'.le_top + (hin.imp_left fun h0 => BitVec.eq_of_toNat_eq (by simpa using h0)) + simp only [exec, SolarTV.EVM.Program.output, SimOut, ↓reduceIte] + exact Spec.consequence (revert_postS (ss := ss) (by decide) hlt hcode (by omega) rfl + (by rw [read_eq I'.mem]; rfl) rfl) (fun _ h => h) (fun _ h => ⟨ss, h, R.logs⟩) + · simp [blockStep] at hok' + +open SolarTV.EVM.Program in +/-- EthLib runs the code from a block's offset as SolarTV runs the program from that block, +to the observable SolarTV's run ends with. -/ +theorem run_sim {p : Program} {c : Cert} {code : ByteArray} (G : Glob p c code) + {o : SolarTV.Machine.Oracle} {call : SolarTV.Call} {msg : Message .fusaka} {ss0 : Substate} + (hdata : msg.data = call.calldata) (hvalue : msg.value = BitVec.ofNat 256 call.callvalue) + (hstatic : msg.isStatic = false) (hself : msg.currentTarget = Target.address selfAddress) + (hcaller : msg.caller = Target.address callerAddress) (ho : c.env = true → OracleOk o) : + ∀ (fuel b : Nat) (S T : List Word) (s : SolarTV.Machine.State) (pc : Nat) (M : ByteArray) + (g : Nat) (st : State.TransactionState) (ss : Substate) + (r : SolarTV.Machine.Halt × SolarTV.Machine.State), + b ≤ p.blocks.length → (b < p.blocks.length → c.need b ≤ S.length) → SR c (c.entry b) S T → + Inv c code call (lowerFrom p c b (p.blocks.drop b)) (cost p c b) pc S s M g → + Rel msg ss0 st ss s → + SolarTV.Machine.iterate (block o call p) fuel (b, S, s) = some r → + Spec .fusaka (At code msg pc T M g st ss .empty) (PostL call msg.currentTarget ss0 r.2 r.1) + | 0, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, hr => by simp [SolarTV.Machine.iterate] at hr + | fuel + 1, b, S, T, s, pc, M, g, st, ss, r, hle, hneed, hR, I, R, hr => by + by_cases hb : b < p.blocks.length + · have hblk : p.blocks[b]? = some p.blocks[b] := List.getElem?_eq_getElem hb + simp only [SolarTV.Machine.iterate, block, hblk] at hr + obtain ⟨hL, hblock⟩ := G.block b hb + obtain ⟨pc1, g1, hlabel, I1⟩ : ∃ pc1 g1, Hoare .fusaka (At code msg pc T M g st ss .empty) + (At code msg pc1 T M g1 st ss .empty) ∧ + Inv c code call (lowerInstrs p c b p.blocks[b] ++ + lowerFrom p c (b + 1) (p.blocks.drop (b + 1))) (cost p c b - labelItems p c b) + pc1 S s M g1 := by + have I' := I + rw [lowerFrom_drop p c hb, lowerBlock, List.append_assoc] at I' + by_cases ht : isTarget p c b = true + · have hl : labelItems p c b = 1 := by simp [labelItems, ht] + rw [hl] at hL ⊢ + simp only [ht, ite_true, List.singleton_append] at I' + obtain ⟨next, hd, hseg⟩ := I'.seg.head + simp only [Item.expected] at hd + obtain ⟨hlt, hcode, rfl⟩ := op_item hd + have hG := I'.gas + exact ⟨pc + 1, g - 1, Logic.jumpdest hlt hcode (by omega), + I'.next hL hseg (Nat.le_succ _) (by omega)⟩ + · have hl : labelItems p c b = 0 := by simp [labelItems, ht] + rw [hl, Nat.sub_zero] + simp only [ht, Bool.false_eq_true, ite_false, List.nil_append] at I' + exact ⟨pc, g, Triple.of_imp fun _ h => h, I'⟩ + have hsim := exec_sim (o := o) G hdata hvalue hstatic hself hcaller ho b hb p.blocks[b] + (c.need b) [] (c.entry b) S T _ s pc1 M g1 st ss hblock (hneed hb) (List.nil_prefix) hR I1 R + generalize exec o call b p.blocks[b] S s = x at hr hsim + rcases x with ⟨halt, s'⟩ | ⟨t, S', s'⟩ + · simp only [Option.some.injEq] at hr + subst hr + exact Spec.seq hlabel hsim + · simp only at hr + obtain ⟨hneed', pc', T', M', g', st', ss', hh, hR', I', R'⟩ := hsim + have := run_sim G hdata hvalue hstatic hself hcaller ho fuel t S' T' s' pc' M' g' st' ss' r + hneed'.1 hneed'.2 hR' I' R' hr + exact Spec.seq (Triple.seq hlabel hh) this + · obtain rfl : b = p.blocks.length := by omega + have hblk : p.blocks[p.blocks.length]? = none := List.getElem?_eq_none (by omega) + simp only [SolarTV.Machine.iterate, block, hblk, ite_true, Option.some.injEq] at hr + subst hr + have hseg := I.seg + rw [lowerFrom_nil p c (by omega)] at hseg + have hpc := hseg.nil_end + exact Spec.consequence (Logic.stop_of_size_le (by omega)) + (fun _ h => h) fun evm h => postL_stop R hself evm h + +theorem logs_of_match' {a : Address} : ∀ {w : List SolarTV.Machine.Event} + {L : List EthLib.Execution.Blocks.Log}, List.Forall₂ (LogMatch a) w L → + L.map (fun log => (log.topics.map fun topic => bytesToNat topic.toList, + log.data.toList.map (·.toNat))) = + w.filterMap fun + | .log topics data => some (topics.map BitVec.toNat, data.map BitVec.toNat) + | .call .. | .read _ | .create .. => none + | [], [], .nil => rfl + | .log topics data :: w, l :: L, .cons ⟨_, ht, hd⟩ rest => by + simp only [List.map_cons, List.filterMap_cons, logs_of_match' rest, ht, hd, List.map_map] + congr 2 + apply List.map_congr_left + intro x _ + simp only [Function.comp_apply, U256.toList_toBeBytes] + rw [bytesToNat_natToBytes_of_lt (by have := x.isLt; simpa using this)] + | .call .. :: _, _ :: _, .cons h _ => h.elim + | .read _ :: _, _ :: _, .cons h _ => h.elim + | .create .. :: _, _ :: _, .cons h _ => h.elim + +theorem filterMap_logs : ∀ (w : List SolarTV.Machine.Event), + (w.filter isLogE).filterMap (fun + | .log topics data => some (topics.map BitVec.toNat, data.map BitVec.toNat) + | .call .. | .read _ | .create .. => none) = + w.filterMap fun + | .log topics data => some (topics.map BitVec.toNat, data.map BitVec.toNat) + | .call .. | .read _ | .create .. => none + | [] => rfl + | e :: w => by cases e <;> simp [isLogE, List.filter_cons, filterMap_logs w] + +/-- The values of EthLib's logs that match SolarTV's world are SolarTV's logs. -/ +theorem logs_of_match {a : Address} {w : List SolarTV.Machine.Event} + {L : List EthLib.Execution.Blocks.Log} (h : List.Forall₂ (LogMatch a) (w.filter isLogE) L) : + L.map (fun log => (log.topics.map fun topic => bytesToNat topic.toList, + log.data.toList.map (·.toNat))) = + w.filterMap fun + | .log topics data => some (topics.map BitVec.toNat, data.map BitVec.toNat) + | .call .. | .read _ | .create .. => none := by + rw [logs_of_match' h, filterMap_logs] + +/-- The callee's storage before the call, at its account, which exists, is the call's: the +relation at the start of the frame. -/ +theorem rel_initial (code : ByteArray) (call : SolarTV.Call) : + Rel (Target.message code call) Substate.empty (Target.preState code call) Substate.empty + (SolarTV.Machine.State.initial call) := by + have htgt : (Target.message code call).currentTarget = Target.address selfAddress := rfl + refine ⟨fun k => ?_, ?_, ⟨[], by simp, .nil⟩⟩ + · apply BitVec.eq_of_toNat_eq + have hkey : U256.toBeBytes k = Target.storageKey k.toNat := + ((storageKey_eq_toBeBytes k.toNat k).2 (Nat.mod_eq_of_lt k.isLt)).symm + rw [htgt, hkey, getStorage_preState code call k.toNat] + simp only [SolarTV.Machine.State.initial, BitVec.toNat_ofNat] + exact (Nat.mod_eq_of_lt (slotValue_lt _ _)).symm + · rw [htgt] + exact Option.isSome_iff_ne_none.2 (account_preState code call) + +/-! ## Calls with value + +A call with value moves it from the caller, who holds exactly it, to the contract before the +frame starts (`moveEther_preState_any`, for every value). The move changes balances only: the +contract keeps its storage and its account (`moveEther_recipient`), so the frame starts in a +state related to the call's storage as with no value, and `run_sim` holds from it. -/ + +section Move + +open EthLib.Execution.State + +theorem getAccount_recordAccountRead (tx : TransactionState) (a b : Address) : + (tx.recordAccountRead a).getAccount b = tx.getAccount b := rfl + +/-- After `modifyState` at `a`, the storage and the account of every other address are as before. -/ +theorem modifyState_ne {fork : Fork} {tx tx' : TransactionState} {a : Address} + {f : Account → Except StateError Account} (h : tx.modifyState fork a f = .ok tx') {b : Address} + (hb : b ≠ a) (k : Bytes32) : + tx'.getStorage b k = tx.getStorage b k ∧ tx'.getAccountOptional b = tx.getAccountOptional b := by + unfold TransactionState.modifyState at h + simp only [bind, Except.bind, pure, Except.pure] at h + split at h + · cases h + · split at h <;> cases h <;> + simp [TransactionState.destroyAccount, TransactionState.destroyStorage, + TransactionState.setAccount, TransactionState.recordAccountRead, + TransactionState.getStorage, TransactionState.getAccountOptional, StorageMap.slot, + Std.ExtTreeMap.getElem?_erase, Std.ExtTreeMap.getElem?_insert, Std.ExtTreeSet.mem_insert, + Ne.symm hb] <;> rfl + +/-- After `modifyState` at `a` with a step that keeps the nonce, from an account with a nonzero +nonce, the storage of `a` is as before and `a` has an account. -/ +theorem modifyState_self {fork : Fork} {tx tx' : TransactionState} {a : Address} + {f : Account → Except StateError Account} (h : tx.modifyState fork a f = .ok tx') + (hf : ∀ acc acc', f acc = .ok acc' → acc'.nonce = acc.nonce) (hn : (tx.getAccount a).nonce ≠ 0) + (k : Bytes32) : + tx'.getStorage a k = tx.getStorage a k ∧ (tx'.getAccountOptional a).isSome = true := by + unfold TransactionState.modifyState at h + simp only [bind, Except.bind, pure, Except.pure] at h + split at h + · cases h + · rename_i acc' hacc + have hnon := hf _ _ hacc + rw [getAccount_recordAccountRead] at hnon + split at h + · rename_i hc + exfalso + simp [TransactionState.accountExistsAndIsEmpty, TransactionState.setAccount, + TransactionState.getAccountOptional, hnon, hn] at hc + · cases h + exact ⟨rfl, by simp [TransactionState.setAccount, TransactionState.recordAccountRead, + TransactionState.getAccountOptional]⟩ + +theorem credit_nonce (r : Address) (amt : U256) : + ∀ acc acc', Account.credit r amt acc = .ok acc' → acc'.nonce = acc.nonce := by + intro acc acc' h + unfold Account.credit at h + split at h <;> cases h + rfl + +/-- A move of ether from `s` to another address `r` with an account of nonzero nonce keeps the +storage of `r`, and `r` keeps an account. -/ +theorem moveEther_recipient {fork : Fork} {tx tx' : TransactionState} {s r : Address} {amt : U256} + (h : tx.moveEther fork s r amt = .ok tx') (hrs : r ≠ s) (hn : (tx.getAccount r).nonce ≠ 0) + (k : Bytes32) : + tx'.getStorage r k = tx.getStorage r k ∧ (tx'.getAccountOptional r).isSome = true := by + unfold TransactionState.moveEther at h + simp only [bind, Except.bind] at h + split at h + · cases h + · rename_i t1 h1 + obtain ⟨hs1, ha1⟩ := modifyState_ne h1 hrs k + have hn1 : (t1.getAccount r).nonce ≠ 0 := by + simpa only [TransactionState.getAccount, ha1] using hn + obtain ⟨hs2, ha2⟩ := modifyState_self h (credit_nonce r amt) hn1 k + exact ⟨hs2.trans hs1, ha2⟩ + +theorem getAccount_preState_self (code : ByteArray) (call : SolarTV.Call) : + (Target.preState code call).getAccount (Target.address selfAddress) = + { nonce := 1, balance := 0, codeHash := EthLib.Cryptography.Hash.Keccak.keccak256 code } := by + simp only [Target.preState, TransactionState.getAccount, TransactionState.getAccountOptional, + TransactionState.ofBlock, State.getAccountOptional] + rw [Std.ExtTreeMap.getElem?_insert, ite_eq_right (by decide +kernel), Std.ExtTreeMap.getElem?_insert, + ite_eq_left (by decide +kernel)] + simp + +theorem getAccount_preState_caller (code : ByteArray) (call : SolarTV.Call) : + ((Target.preState code call).getAccount (Target.address callerAddress)).balance = + BitVec.ofNat 256 call.callvalue := by + simp only [Target.preState, TransactionState.getAccount, TransactionState.getAccountOptional, + TransactionState.ofBlock, State.getAccountOptional] + simp + +theorem modifyState_exists {fork : Fork} {tx : TransactionState} {a : Address} + {f : Account → Except StateError Account} {acc : Account} (h : f (tx.getAccount a) = .ok acc) : + ∃ tx', tx.modifyState fork a f = .ok tx' := by + unfold TransactionState.modifyState + simp only [bind, Except.bind, pure, Except.pure, getAccount_recordAccountRead, h] + split <;> exact ⟨_, rfl⟩ + +/-- The move of the call's value from the caller, who holds exactly it, to the contract, which +holds none, succeeds, for every value. -/ +theorem moveEther_preState_any (code : ByteArray) (call : SolarTV.Call) : + ∃ st', (Target.preState code call).moveEther .fusaka (Target.address callerAddress) + (Target.address selfAddress) (BitVec.ofNat 256 call.callvalue) = .ok st' := by + have hAB : Target.address selfAddress ≠ Target.address callerAddress := by decide + have hd : Account.debit (Target.address callerAddress) (BitVec.ofNat 256 call.callvalue) + ((Target.preState code call).getAccount (Target.address callerAddress)) = + .ok { (Target.preState code call).getAccount (Target.address callerAddress) with + balance := 0 } := by + simp [Account.debit, getAccount_preState_caller] + obtain ⟨t1, h1⟩ := modifyState_exists (fork := .fusaka) hd + have ha1 := (modifyState_ne h1 hAB (Target.storageKey 0)).2 + have hc : Account.credit (Target.address selfAddress) (BitVec.ofNat 256 call.callvalue) + (t1.getAccount (Target.address selfAddress)) = + .ok { t1.getAccount (Target.address selfAddress) with + balance := 0 + BitVec.ofNat 256 call.callvalue } := by + have : t1.getAccount (Target.address selfAddress) = + (Target.preState code call).getAccount (Target.address selfAddress) := by + simp only [TransactionState.getAccount, ha1] + rw [this, getAccount_preState_self] + unfold Account.credit + rw [ite_eq_left_iff.mpr (fun h => absurd ?_ h)] + dsimp only + have h1 := (BitVec.ofNat 256 call.callvalue).isLt + have h0 : (0 : U256).toNat = 0 := rfl + omega + obtain ⟨t2, h2⟩ := modifyState_exists (fork := .fusaka) hc + exact ⟨t2, by simp [TransactionState.moveEther, bind, Except.bind, h1, h2]⟩ + +end Move + +section RunAny + +open SolidCore.Refinement.Evm.Symex + +/-- What `processMessage` gives from a frame that ends as `PostS X` shows for a substate whose logs +are those of `ss` and then SolarTV's world `w`. -/ +def MsgOut (X : SolarTV.Observable) (a : Address) (ss : Substate) (w : List SolarTV.Machine.Event) + (evm : Evm .fusaka Nat) : Prop := + ∃ ssF, LogsRel a ss ssF w ∧ evm.error = errorOf X ∧ evm.output.toList.map (·.toNat) = X.output ∧ + (X.success = true → evm.substate.logs = ssF.logs ∧ ∀ slot, + (evm.state.getStorage (Target.address selfAddress) (Target.storageKey slot)).toNat = + X.storage slot) + +/-- processMessage at Fusaka of a message with no value, to code that is no precompile. -/ +theorem processMessage_postL {c : ByteArray} (message : Message .fusaka) + (hcode : message.code = c) (hv : message.value = 0) + (hpre : precompileAddress .fusaka message = none) (X : SolarTV.Observable) (a : Address) + (w : List SolarTV.Machine.Event) (st : EthLib.Execution.State.TransactionState) (ss : Substate) + (h : Spec .fusaka (At c message 0 [] .empty message.gas st ss .empty) + (fun evm => ∃ ssF, PostS X ssF evm ∧ LogsRel a ss ssF w)) : + ∃ evm, processMessage (Meter := Nat) .fusaka message st ss = .ok evm ∧ MsgOut X a ss w evm.1 := by + rw [processMessage] + have hss : startState .fusaka message st = st := by + simp [startState, show ¬ (Fork.fusaka < Fork.paris) by decide] + simp only [hss, hpre] + split + · rename_i htr; exact absurd htr.2 (by simp [hv]) + simp only [pure, Except.pure, bind, Except.bind] + split + · rename_i e hr + simp only [hv, ne_eq, not_true_eq_false, and_false, ite_false] at hr + obtain ⟨after, h', -⟩ := runFrame_of_spec hcode h hr + cases h' + · rename_i after hr + simp only [hv, ne_eq, not_true_eq_false, and_false, ite_false] at hr + obtain ⟨after', h', -, ssF, ⟨herr, hout, hlogs, hst⟩, hL⟩ := runFrame_of_spec hcode h hr + cases h' + refine ⟨_, rfl, ssF, hL, ?_, ?_, ?_⟩ + · simp only [rollbackOnError]; split <;> simp [herr] + · simp only [rollbackOnError]; split <;> exact hout + · intro hX + have hE : errorOf X = none := by simp [errorOf, hX] + simp only [rollbackOnError, herr, hE, Option.isSome_none, Bool.false_eq_true, ↓reduceIte] + exact ⟨hlogs, hst hX⟩ + +/-- processMessage at Fusaka of a message with nonzero value, whose move of the value succeeds +into st', to code that is no precompile. -/ +theorem processMessage_postL_move {c : ByteArray} (message : Message .fusaka) + (hcode : message.code = c) (htr : message.shouldTransferValue = true) (hv : message.value ≠ 0) + (hpre : precompileAddress .fusaka message = none) (X : SolarTV.Observable) (a : Address) + (w : List SolarTV.Machine.Event) (st st' : EthLib.Execution.State.TransactionState) + (ss : Substate) + (hmove : st.moveEther .fusaka message.caller message.currentTarget message.value = .ok st') + (h : Spec .fusaka (At c message 0 [] .empty message.gas st' ss .empty) + (fun evm => ∃ ssF, PostS X ssF evm ∧ LogsRel a ss ssF w)) : + ∃ evm, processMessage (Meter := Nat) .fusaka message st ss = .ok evm ∧ MsgOut X a ss w evm.1 := by + rw [processMessage] + have hss : startState .fusaka message st = st := by + simp [startState, show ¬ (Fork.fusaka < Fork.paris) by decide] + simp only [hss, hpre, htr, ne_eq, hv, not_false_eq_true, and_self, ↓reduceIte, hmove] + simp only [pure, Except.pure, bind, Except.bind, Except.mapError] + -- At Fusaka a move of value pushes no transfer log. + have hsub : ∀ x : Substate, + { x with logs := (pushTransferLog .fusaka x.logs message.caller message.currentTarget + message.value) } = x := fun x => by + simp [pushTransferLog, show ¬ (Fork.fusaka ≥ Fork.glamsterdam) by decide] + split + · rename_i e hr + simp only [htr, hv, not_false_eq_true, and_self, ↓reduceIte, hsub] at hr + obtain ⟨after, h', -⟩ := runFrame_of_spec hcode h hr + cases h' + · rename_i after hr + simp only [htr, hv, not_false_eq_true, and_self, ↓reduceIte, hsub] at hr + obtain ⟨after', h', -, ssF, ⟨herr, hout, hlogs, hst⟩, hL⟩ := runFrame_of_spec hcode h hr + cases h' + refine ⟨_, rfl, ssF, hL, ?_, ?_, ?_⟩ + · simp only [rollbackOnError]; split <;> simp [herr] + · simp only [rollbackOnError]; split <;> exact hout + · intro hX + have hE : errorOf X = none := by simp [errorOf, hX] + simp only [rollbackOnError, herr, hE, Option.isSome_none, Bool.false_eq_true, ↓reduceIte] + exact ⟨hlogs, hst hX⟩ + +/-- Target.run of any call, with or without value, is SolarTV's observable of `halt` in `s` when the +frame from every state related to the call's storage ends as `PostL` shows: with value, the frame +starts after the move of the value, which keeps the contract's storage. -/ +theorem run_of_rel (code : ByteArray) (call : SolarTV.Call) (s : SolarTV.Machine.State) + (halt : SolarTV.Machine.Halt) + (h : ∀ st, Rel (Target.message code call) Substate.empty st Substate.empty + (SolarTV.Machine.State.initial call) → + Spec .fusaka (At code (Target.message code call) 0 [] .empty 10000000 st Substate.empty + .empty) (PostL call (Target.address selfAddress) Substate.empty s halt)) : + Target.run code call = some (SolarTV.Machine.observe call s halt) := by + have key : ∃ evm, processMessage (Meter := Nat) .fusaka (Target.message code call) + (Target.preState code call) Substate.empty = .ok evm ∧ + MsgOut (SolarTV.Machine.observe call s halt) (Target.address selfAddress) Substate.empty + s.world evm.1 := by + by_cases hv : (Target.message code call).value = 0 + · exact processMessage_postL _ rfl hv (precompileAddress_message code call) _ _ _ _ _ + (h _ (rel_initial code call)) + · obtain ⟨st', hmove⟩ := moveEther_preState_any code call + have hn : ((Target.preState code call).getAccount (Target.address selfAddress)).nonce ≠ 0 := by + rw [getAccount_preState_self]; simp + have hAB : Target.address selfAddress ≠ Target.address callerAddress := by decide + have R0 := rel_initial code call + have R : Rel (Target.message code call) Substate.empty st' Substate.empty + (SolarTV.Machine.State.initial call) := + ⟨fun k => ((moveEther_recipient hmove hAB hn _).1).trans (R0.storage k), + (moveEther_recipient hmove hAB hn (Target.storageKey 0)).2, R0.logs⟩ + exact processMessage_postL_move _ rfl rfl hv (precompileAddress_message code call) _ _ _ _ + st' _ hmove (h st' R) + obtain ⟨evm, hr, ssF, ⟨L, hL1, hL2⟩, herr, hout, hst⟩ := key + have hlogs := logs_of_match hL2 + have hL1' : ssF.logs.toList = L := by simpa [Substate.empty] using hL1 + have hfail : (SolarTV.Machine.observe call s halt).success = false → + (SolarTV.Machine.observe call s halt).logs = [] ∧ + (SolarTV.Machine.observe call s halt).storage = slotValue call.storage := by + cases halt <;> simp [SolarTV.Machine.observe] + have hok : (SolarTV.Machine.observe call s halt).success = true → + (SolarTV.Machine.observe call s halt).logs = SolarTV.Machine.logs s := by + cases halt <;> simp [SolarTV.Machine.observe] + simp only [Target.run, hr] + generalize SolarTV.Machine.observe call s halt = X at * + have hsucc : evm.1.error.isNone = X.success := by + rw [herr]; cases hX : X.success <;> simp [errorOf, hX] + congr 1 + cases X with + | mk success output logs storage => + simp only at hsucc hout hfail hok hst ⊢ + rw [SolarTV.Observable.mk.injEq] + refine ⟨hsucc, hout, ?_, ?_⟩ + · rw [hsucc] + cases hs : success + · simp [(hfail hs).1] + · simp only [ite_true] + rw [(hst hs).1, hL1', hlogs, hok hs] + rfl + · funext slot + rw [hsucc] + cases hs : success + · simp [(hfail hs).2] + · simp only [ite_true] + exact (hst hs).2 slot + +/-- EVM IR to bytecode, for every program and code the checker accepts: on every call, with or +without value, from any storage, under every oracle whose caller and hash are EthLib's when the +program reads them, every observable SolarTV's EVM IR semantics gives for p, EthLib gives for +code. -/ +theorem stage_of_check_env {p : Program} {code : ByteArray} {c : Cert} (hc : check p code c = true) + (o : SolarTV.Machine.Oracle) (ho : c.env = true → OracleOk o) (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.evmirSem o) SolidCore.Refinement.ethLib p + (show SolidCore.Refinement.ethLib.Prog from code) scope := by + obtain ⟨G, hseg, hneed0, hlen, hgas⟩ := glob_of_check hc + intro call _ obs hrun + change (SolarTV.EVM.Program.layer.result o p call).map _ = _ at hrun + obtain ⟨r, hr, rfl⟩ := Option.map_eq_some_iff.1 hrun + obtain ⟨n, hn⟩ := SolarTV.EVM.Program.layer.ends_of_result hr + have hm0 : memoryGasCost (ByteArray.empty).size = 0 := by decide + have I0 : Inv c code call (lowerFrom p c 0 (p.blocks.drop 0)) (cost p c 0) 0 [] + (SolarTV.Machine.State.initial call) .empty 10000000 := + ⟨by rw [List.drop_zero]; exact hseg, by simpa using hlen, by rw [hm0]; omega, + by simp, memRel_initial⟩ + exact run_of_rel code call r.2 r.1 fun st R => run_sim (msg := Target.message code call) + (ss0 := Substate.empty) G rfl (by simp [Target.message]) rfl rfl rfl ho n 0 [] [] _ 0 .empty + 10000000 st Substate.empty r (Nat.zero_le _) (by simp [hneed0]) (SR.nil c _) I0 R hn + +/-- +info: 'SolidCore.Refinement.Solar.Assemble.stage_of_check_env' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms stage_of_check_env + +/-- EVM IR to bytecode for a program that reads neither the caller nor a hash, under every +oracle: `stage_of_check_env`. -/ +theorem stage_of_check_all {p : Program} {code : ByteArray} {c : Cert} (hc : check p code c = true) + (o : SolarTV.Machine.Oracle) (scope : SolarTV.Call → Prop) (hpure : c.env = false := by rfl) : + SolarTV.Stage (SolarTV.evmirSem o) SolidCore.Refinement.ethLib p + (show SolidCore.Refinement.ethLib.Prog from code) scope := + stage_of_check_env hc o (fun h => absurd (h.symm.trans hpure) (by decide)) scope + +/-- EVM IR to bytecode under every oracle with EthLib's caller and hash. -/ +theorem stage_of_check_eth {p : Program} {code : ByteArray} {c : Cert} (hc : check p code c = true) + (o : SolarTV.Machine.Oracle) (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.evmirSem (ethOracle o)) SolidCore.Refinement.ethLib p + (show SolidCore.Refinement.ethLib.Prog from code) scope := + stage_of_check_env hc _ (fun _ => ethOracle_ok o) scope + +/-- +info: 'SolidCore.Refinement.Solar.Assemble.stage_of_check_all' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms stage_of_check_all + +end RunAny + +/-- EVM IR to bytecode, for every program and code the checker accepts, on a scope of calls with +no value: `stage_of_check_all`, which holds on every call, with any value. -/ +theorem stage_of_check {p : Program} {code : ByteArray} {c : Cert} (hc : check p code c = true) + (o : SolarTV.Machine.Oracle) {scope : SolarTV.Call → Prop} + (_hscope : ∀ call, scope call → call.callvalue = 0) (hpure : c.env = false := by rfl) : + SolarTV.Stage (SolarTV.evmirSem o) SolidCore.Refinement.ethLib p + (show SolidCore.Refinement.ethLib.Prog from code) scope := + stage_of_check_all hc o scope hpure + +/-- +info: 'SolidCore.Refinement.Solar.Assemble.stage_of_check' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms stage_of_check + +end SolidCore.Refinement.Solar.Assemble diff --git a/SolidCore/Refinement/Solar/AssembleStackN.lean b/SolidCore/Refinement/Solar/AssembleStackN.lean new file mode 100644 index 00000000..6c21d23a --- /dev/null +++ b/SolidCore/Refinement/Solar/AssembleStackN.lean @@ -0,0 +1,139 @@ +import EthLib.Execution.Evm.Instructions.StackOnly +import EthLib.Execution.Proofs.Evm.Logic.Rules +import SolarTV.Stages.Assembly +import SolarTV.EVMIR.Ops + +/-! +# DUPN, SWAPN and EXCHANGE against EthLib + +SolarTV's EVM IR takes `dup` and `swap` positions up to 255 and `exchange` pairs up to 31. +DUP1 to DUP16 and SWAP1 to SWAP16 reach the first sixteen; deeper ones, and EXCHANGE, are +EIP-8024's DUPN, SWAPN and EXCHANGE, opcodes with a one-byte immediate that exist from +Glamsterdam. This file ties SolarTV's encoding of them (`SolarTV.Assembly.encodeDepth`, +`encodePair`, as solar's assembler writes them) to EthLib's: + +* the immediates are EthLib's, byte for byte, both ways (`decodeSingle_eq`, `encodeSingle_eq`, + `decodePair_eq`, `encodePair_eq`); +* from Glamsterdam, DUPN, SWAPN and EXCHANGE at the immediate of an EVM IR `dup i`, `swap i` or + `exchange n m` do what SolarTV's `step` does, two bytes on, for 3 gas (`dupn_step`, + `swapn_step`, `exchange_step`); +* before Glamsterdam none of the three is an instruction (`stackN_fusaka`), so the assembly + check at Fusaka (`Assemble.check`) refuses every `dup` and `swap` past the sixteenth word and + every `exchange` (`Assemble.blockStep_dup`, `blockStep_swap`, `blockStep_exchange`). +-/ + +namespace SolidCore.Refinement.Solar.Assemble + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm GasCosts +open SolarTV.Assembly (encodeDepth decodeDepth depthOk encodePair decodePair pairOk) + +/-! ## The immediates are EthLib's -/ + +theorem decodeSingle_eq (x : UInt8) : decodeSingle x = decodeDepth x.toNat := rfl + +theorem encodeSingle_eq (n : Nat) : encodeSingle n = (encodeDepth n).toUInt8 := rfl + +theorem decodePair_eq (x : UInt8) : Evm.decodePair x = SolarTV.Assembly.decodePair x.toNat := rfl + +theorem encodePair_eq (n m : Nat) : + Evm.encodePair n m = (SolarTV.Assembly.encodePair n m).toUInt8 := rfl + +theorem toNat_encodeDepth (n : Nat) : (encodeDepth n).toUInt8.toNat = encodeDepth n := by + have := SolarTV.Assembly.encodeDepth_lt n + simp [Nat.toUInt8, Nat.mod_eq_of_lt this] + +/-! ## Before Glamsterdam the three are no instruction -/ + +theorem stackN_fusaka : + stackOnlyStep (Meter := Nat) .fusaka .dupn = none ∧ + stackOnlyStep (Meter := Nat) .fusaka .swapn = none ∧ + stackOnlyStep (Meter := Nat) .fusaka .exchange = none := by + refine ⟨?_, ?_, ?_⟩ <;> simp [stackOnlyStep] <;> decide + +/-! ## From Glamsterdam they do what SolarTV's step does -/ + +variable {fork : Fork} + +/-- DUPN at the immediate of EVM IR's `dup i` (depth `i + 1`, past the sixteenth) pushes the +word at position `i`, as `SolarTV.EVM.step` does, two bytes on, for 3 gas. -/ +theorem dupn_step {evm : Evm fork Nat} {i : Nat} {x : U256} + (hd : depthOk (i + 1) = true) + (himm : immediateByte evm.code evm.pc = (encodeDepth (i + 1)).toUInt8) + (hgas : 3 ≤ evm.gas) (hx : evm.stack.val[i]? = some x) + (hlen : evm.stack.val.length < STACK_LIMIT) : + ∃ after, dupnStep evm = .ok after ∧ after.stack.val = x :: evm.stack.val ∧ + after.pc = evm.pc + 2 ∧ after.gas = evm.gas - 3 := by + have hdec : decodeSingle (immediateByte evm.code evm.pc) = some (i + 1) := by + rw [himm, decodeSingle_eq, toNat_encodeDepth] + exact SolarTV.Assembly.decodeDepth_encodeDepth hd + have hne : evm.stack.val.length ≠ STACK_LIMIT := by omega + simp only [dupnStep, chargeGas, OPCODE_DUPN, VERY_LOW, Logic.charge_nat hgas, bind, Except.bind, + pure, Except.pure, hdec, Nat.add_sub_cancel, hx, pushWord, Stack.push, hne, dite_false] + exact ⟨_, rfl, rfl, rfl, rfl⟩ + +/-- SWAPN at the immediate of EVM IR's `swap i` (depth `i + 1`, past the sixteenth) exchanges the +top with the word below it at position `i`, as `SolarTV.EVM.step` does, two bytes on, for 3 gas. -/ +theorem swapn_step {evm : Evm fork Nat} {i : Nat} {top x : U256} {rest : List U256} + (hd : depthOk (i + 1) = true) + (himm : immediateByte evm.code evm.pc = (encodeDepth (i + 1)).toUInt8) + (hgas : 3 ≤ evm.gas) (hs : evm.stack.val = top :: rest) (hx : rest[i]? = some x) : + ∃ after, swapnStep evm = .ok after ∧ after.stack.val = x :: rest.set i top ∧ + after.pc = evm.pc + 2 ∧ after.gas = evm.gas - 3 := by + have hdec : decodeSingle (immediateByte evm.code evm.pc) = some (i + 1) := by + rw [himm, decodeSingle_eq, toNat_encodeDepth] + exact SolarTV.Assembly.decodeDepth_encodeDepth hd + have h0 : evm.stack.val[0]? = some top := by rw [hs]; rfl + have h1 : evm.stack.val[i + 1]? = some x := by rw [hs]; exact hx + simp only [swapnStep, chargeGas, OPCODE_SWAPN, VERY_LOW, Logic.charge_nat hgas, bind, + Except.bind, pure, Except.pure, hdec, exchangeItems, h0, h1] + refine ⟨_, rfl, ?_, rfl, rfl⟩ + simp only [advance, hs, List.set_cons_zero, List.set_cons_succ] + +/-- EXCHANGE at the immediate of EVM IR's `exchange n m` exchanges the words at positions `n` and +`m`, as `SolarTV.EVM.step` does, two bytes on, for 3 gas. -/ +theorem exchange_step {evm : Evm fork Nat} {n m : Nat} {a b : U256} + (hp : pairOk n m = true) + (himm : immediateByte evm.code evm.pc = (SolarTV.Assembly.encodePair n m).toUInt8) + (hgas : 3 ≤ evm.gas) (ha : evm.stack.val[n]? = some a) (hb : evm.stack.val[m]? = some b) : + ∃ after, exchangeStep evm = .ok after ∧ + after.stack.val = (evm.stack.val.set n b).set m a ∧ + after.pc = evm.pc + 2 ∧ after.gas = evm.gas - 3 := by + obtain ⟨hdp, hlt⟩ := SolarTV.Assembly.decodePair_encodePair hp + have hdec : Evm.decodePair (immediateByte evm.code evm.pc) = some (n, m) := by + rw [himm, decodePair_eq] + simpa [Nat.toUInt8, Nat.mod_eq_of_lt hlt] using hdp + simp only [exchangeStep, chargeGas, OPCODE_EXCHANGE, VERY_LOW, Logic.charge_nat hgas, bind, + Except.bind, pure, Except.pure, hdec, exchangeItems, ha, hb] + exact ⟨_, rfl, rfl, rfl, rfl⟩ + +/-- SolarTV's `step` of `exchange` is the exchange EthLib's EXCHANGE makes. -/ +theorem step_exchange (ctx : SolarTV.EVM.Context) (n m : Fin 32) (stack : List EvmRules.Word) + {a b : EvmRules.Word} (ha : stack[n.val]? = some a) (hb : stack[m.val]? = some b) : + SolarTV.EVM.step ctx (.exchange n m) stack = some ((stack.set n.val b).set m.val a) := by + simp [SolarTV.EVM.step, ha, hb] + +/-- SolarTV's `step` of `dup i` pushes the word at position `i`. -/ +theorem step_dup (ctx : SolarTV.EVM.Context) (i : Fin 256) (stack : List EvmRules.Word) + {x : EvmRules.Word} (hx : stack[i.val]? = some x) : + SolarTV.EVM.step ctx (.dup i) stack = some (x :: stack) := by + simp [SolarTV.EVM.step, hx] + +/-- SolarTV's `step` of `swap i` exchanges the top with the word below it at position `i`. -/ +theorem step_swap (ctx : SolarTV.EVM.Context) (i : Fin 256) (top : EvmRules.Word) + (rest : List EvmRules.Word) {x : EvmRules.Word} (hx : rest[i.val]? = some x) : + SolarTV.EVM.step ctx (.swap i) (top :: rest) = some (x :: rest.set i.val top) := by + simp [SolarTV.EVM.step, hx] + +/-- info: 'SolidCore.Refinement.Solar.Assemble.dupn_step' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms dupn_step + +/-- info: 'SolidCore.Refinement.Solar.Assemble.swapn_step' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms swapn_step + +/-- info: 'SolidCore.Refinement.Solar.Assemble.exchange_step' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms exchange_step + +end SolidCore.Refinement.Solar.Assemble diff --git a/SolidCore/Refinement/Solar/Bank/Assembly.lean b/SolidCore/Refinement/Solar/Bank/Assembly.lean new file mode 100644 index 00000000..05bcc04a --- /dev/null +++ b/SolidCore/Refinement/Solar/Bank/Assembly.lean @@ -0,0 +1,104 @@ +import SolidCore.Refinement.Solar.AssembleSim +import SolidCore.Refinement.Solar.AssembleFast +import bank.gen.Bank.Evm11 +import bank.gen.Bank.Bytecode +import bank.Proofs.Stages + +/-! +# bank: the final EVM IR to solar's bytecode + +solar-tv/milestone/bank/bank.sol (a `mapping(address => uint256)` of balances and a total, +credited by an internal function that `deposit(uint256)` calls for `msg.sender`, emitting the indexed +`Deposit` event, and that `depositFor(address,uint256)` calls, and `balanceOf(address)`) compiles with solar +0a455fda to the final EVM IR evm11 (after stack-reschedule) and to 454 bytes of runtime bytecode +(sha256 bff0578068ce4ab4a041f226e4e960c13d358c8b430718fefe9ce3a22d760543), both exported by +-Zemit-lean-stages into solar's solar-tv/milestone/bank and imported from there. Solar's +milestone proves the stages from the first lowered MIR to evm11 +(SolarTV.Milestone.Bank.bank_mir_to_evmir); this file proves the last one, evm11 to the +bytecode, with the generic assembler check: its mapping slots are KECCAK256 of the key and the +slot at constant offsets, `deposit` reads CALLER and logs with LOG2, and the internal function is +entered with a pushed return label (blocks 5 and 10, the certificate's `rets`) and returns with a +dynamic JUMP to it, which the certificate's stack types follow. + +The stage holds under every oracle whose CALLER is the caller of EthLib's calls and whose hash is +EthLib's KECCAK256 (`Assemble.OracleOk`), so for every calldata, mapping key, caller word the +bytecode sees, value and storage; `backend` composes it with the MIR to EVM IR stages, which hold for +every oracle. + +* check_ok: the checker accepts evm11 and the bytes with cert, by the kernel's evaluation of + its one-pass form (`Assemble.checkFast`, equal to it by `Assemble.check_eq_checkFast`). +* stageOk, stageEth: EVM IR to bytecode is a stage on every call, under every such oracle. +* backend: the first lowered MIR to the bytecode, on every call. +* Mutants.lean: the checker rejects one-byte mutants of the hash, the caller, the log, the + return label, the return jump and the mapping key. +-/ + +namespace SolidCore.Refinement.Solar.Bank + +open SolarTV.Assembly SolarTV.Export.Bank + +/-- The runtime bytecode solar exported. -/ +def code : ByteArray := ⟨(bytecode.map UInt8.ofNat).toArray⟩ + +/-- The certificate: each block's offset in the code, the stack height and the types each block +needs on entry (the internal function, block 4, finds its return label on top), the bound on +memory (the reverts' 128 bytes), each block's potential, the blocks a return label names, and +that the program reads the caller and hashes. -/ +def cert : Assemble.Cert := + { offsets := [0, 0x28, 0x2c, 0x3e, 0x4d, 0x87, 0xcb, 0xe1, 0xe5, 0xf8, 0x11b, 0x134, 0x147, + 0x161, 0x193, 0x1a6], + needs := [0, 0, 6, 1, 5, 3, 1, 3, 2, 1, 3, 2, 2, 1, 3, 8], top := 128, + costs := [137, 4, 10, 111, 100, 51, 24, 14, 11, 125, 35, 18, 24, 54, 18, 26], + types := [[], [], [some false, none, none, some false, some false, some false], [some false], + [some true, some false, some false, some false, some false], + [some false, some false, some false], [some false], [some false, some false, some false], + [some false, some false], [some false], [some false, some false, some false], + [some false, some false], [some false, some false], [some false], + [some false, some false, some false], + [some false, some false, some false, some true, some false, some false, some false, + some false]], + rets := [5, 10], env := true } + +set_option maxRecDepth 100000 in +/-- The checker accepts solar's bytecode for the program, by the kernel's evaluation. -/ +theorem check_ok : Assemble.check evm11 code cert = true := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +/-- EVM IR to bytecode is a stage for bank on every call, under every oracle whose caller and +hash are EthLib's. -/ +theorem stageOk (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) + (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.evmirSem o) SolidCore.Refinement.ethLib evm11 + (show SolidCore.Refinement.ethLib.Prog from code) scope := + Assemble.stage_of_check_env check_ok o (fun _ => ho) scope + +/-- The same for `Assemble.ethOracle o`, any oracle with EthLib's caller and hash. -/ +theorem stageEth (o : SolarTV.Machine.Oracle) (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.evmirSem (Assemble.ethOracle o)) SolidCore.Refinement.ethLib evm11 + (show SolidCore.Refinement.ethLib.Prog from code) scope := + Assemble.stage_of_check_eth check_ok o scope + +/-- The backend: solar-tv's stages from stage0 to evm11, then the assembly stage, on every call +(any calldata, mapping keys, value and storage), under every oracle with EthLib's caller and +hash. -/ +theorem backend (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) + (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.mirSem o) SolidCore.Refinement.ethLib stage0 + (show SolidCore.Refinement.ethLib.Prog from code) scope := + SolarTV.Stage.trans (B := SolarTV.evmirSem o) + (fun call _ => SolarTV.Milestone.Bank.bank_mir_to_evmir o call trivial) (stageOk o ho scope) + +/-- info: 'SolidCore.Refinement.Solar.Bank.check_ok' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms check_ok + +/-- info: 'SolidCore.Refinement.Solar.Bank.stageOk' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stageOk + +/-- info: 'SolidCore.Refinement.Solar.Bank.backend' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms backend + +end SolidCore.Refinement.Solar.Bank diff --git a/SolidCore/Refinement/Solar/Bank/Certified.lean b/SolidCore/Refinement/Solar/Bank/Certified.lean new file mode 100644 index 00000000..075abc5e --- /dev/null +++ b/SolidCore/Refinement/Solar/Bank/Certified.lean @@ -0,0 +1,215 @@ +import SolidCore.Refinement.Solar.Bank.Lowering +import SolidCore.Refinement.Solar.Bank.Assembly +import SolidCore.Refinement.Solar.Hex +import bank.gen.Bank.Manifest +import SolidCore.Refinement.Keccak.TwoWords + +/-! +# bank: SolidCore to solar's bytecode, through every stage + +The end-to-end translation of `Bank` (Lowering.lean has the contract), chaining with +`Stage.trans`: + +1. the source stage, SolidCore's checked `Bank` to solar's first lowered MIR stage0 + (`lowering`, `loweringValue`), under every oracle whose caller is SolidCore's + `callerAddress` and whose Keccak-256 of two words is SolidCore's (`Generic.SourceEnvOk`); +2. solar-tv's backend stages from stage0 to the final EVM IR, and the assembly stage to the + runtime bytecode (Assembly.lean, `backend`), under every oracle whose caller and hash are + EthLib's (`Assemble.OracleOk`). + +An oracle with EthLib's caller has SolidCore's caller (`callerOk_of`). SolidCore hashes with +evmyul's Keccak-256 and EthLib with its own: `certified` and `certifiedValue` take, as their one +hypothesis beyond `OracleOk`, that they agree on the 64 bytes of two words (`EthKeccakAgree`, +the inputs a mapping's slot hashes), and `certified'` and `certifiedValue'` discharge it: +Keccak/Agree.lean proves the two implementations equal on every 64-byte message (same padding, +same Keccak-f[1600] round by round, same squeeze), and Keccak/TwoWords.lean reads that as +`EthKeccakAgree` (`ethKeccakAgree`). `certified` holds for every call of `deposit`, `depositFor` and `balanceOf` on any argument words, +from any storage, with no value, and `certifiedValue` with any value. + +`certifiedManifest` binds both to the export's manifest (gen/…/Manifest.lean): the source's path +and sha256, the compiler's version and commit, its arguments, optimization and EVM version, the +bytecode's sha256 and hex, that the hex is the lowercase hex of the bytes the stages run +(`manifest_hex`, by the kernel's unfolding) and decodes to them (`bytecode_of_manifest`), and +the stages under `EthKeccakAgree`, as one conjunction. `mutant_hex_rejected`: a one-byte mutant's hex does not +decode to those bytes. The sha256s are of the files, checked outside the kernel (solar's +certify.sh; the source's, each stage's and the bytecode's match the files at solar c8ea95b8f). +`certifiedManifest'` is the same conjunction with `EthKeccakAgree` discharged (`ethKeccakAgree`). + +No sorry, native_decide or bv_decide: the theorems depend on propext, Classical.choice and +Quot.sound only (pinned below). +-/ + +namespace SolidCore.Refinement.Solar.Bank + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity + +/-- EthLib's Keccak-256 of the 64 bytes of two words is SolidCore's mapping-slot hash of them. -/ +def EthKeccakAgree : Prop := + ∀ a b, a < 2 ^ 256 → b < 2 ^ 256 → + (EthLib.Execution.Evm.keccak + ⟨((Generic.wordBytes a ++ Generic.wordBytes b).map UInt8.ofBitVec).toArray⟩).toNat = + Generic.solHash a b % 2 ^ 256 + +/-- EthLib's caller is SolidCore's `callerAddress`, as a word. -/ +theorem callerAddress_word : + (SolidCore.Refinement.Target.address SolidCore.Refinement.callerAddress).toU256.toNat = + Generic.callerWord := by + decide +kernel + +/-- An oracle with EthLib's caller has SolidCore's. -/ +theorem callerOk_of (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) : Generic.CallerOk o := by + unfold Generic.CallerOk + rw [ho.1] + exact callerAddress_word + +/-- An oracle with EthLib's caller and hash is one the source stage takes, when EthLib's and +SolidCore's Keccak-256 agree on two words. -/ +theorem sourceEnvOk_of (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) + (hk : EthKeccakAgree) : Generic.SourceEnvOk o := + ⟨callerOk_of o ho, fun a b ha hb => by rw [ho.2]; exact hk a b ha hb⟩ + +/-- **Bank from SolidCore to solar's bytecode**: every result SolidCore's `Bank` gives on a +call of `deposit`, `depositFor` and `balanceOf` on any argument words, no value, from any storage, the bytecode gives under +EthLib, for every oracle with EthLib's caller and hash. -/ +theorem certified (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) (hk : EthKeccakAgree) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) ethLib c code (fun call => ∃ σ, fullScope fns σ call) := + (lowering o (sourceEnvOk_of o ho hk) hc).trans (backend o ho _) + +/-- **Bank from SolidCore to solar's bytecode at every value**. -/ +theorem certifiedValue (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) + (hk : EthKeccakAgree) {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) ethLib c code (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := + (loweringValue o (sourceEnvOk_of o ho hk) hc).trans (backend o ho _) + +open SolarTV.Export.Bank Hex in +set_option maxRecDepth 100000 in +/-- The manifest's hex is the lowercase hex of the bytes the stages run. -/ +theorem manifest_hex : Manifest.bytecodeHex = String.ofList (hexChars bytecode) := by rfl + +open SolarTV.Export.Bank Hex in +set_option maxRecDepth 100000 in +/-- The bytes the stages run are the manifest's hex, which --emit=bin-runtime printed. -/ +theorem bytecode_of_manifest : hexBytes (codes Manifest.bytecodeHex) = some bytecode := by + rw [manifest_hex, codes, String.toList_ofList] + -- The instance is spelled out: with EvmYul in scope, instance search finds EvmYul's + -- `Stack.instDecidableEq` for `List Nat`. + exact @of_decide_eq_true _ + (@Option.instDecidableEq _ (@instDecidableEqList _ instDecidableEqNat) _ _) (by decide +kernel) + +open SolarTV.Export.Bank Hex in +set_option maxRecDepth 100000 in +/-- A one-byte mutant's hex (the first byte, CALLVALUE, as ORIGIN) does not decode to the bytes +the stages run: the link fails by mismatch. -/ +theorem mutant_hex_rejected : + hexBytes ((hexChars (bytecode.set 0 0x32)).map Char.toNat) ≠ some bytecode := by + exact @of_decide_eq_false (hexBytes ((hexChars (bytecode.set 0 0x32)).map Char.toNat) = some bytecode) + (@Option.instDecidableEq _ (@instDecidableEqList _ instDecidableEqNat) _ _) (by decide +kernel) + +open SolarTV.Export.Bank Hex in +/-- **The certified translation of bank**, bound to what it was compiled from and by: the source +(path and sha256), its arguments +(-Ogas, osaka), the bytecode with its sha256 and hex, the bytes the stages run as that bytecode, +and the stage from SolidCore's checked `Bank` to those bytes, with no value and with any value, +on every call of `deposit`, `depositFor` and `balanceOf` from any storage, under every oracle +with EthLib's caller and hash, given that EthLib's and SolidCore's Keccak-256 agree on the 64 bytes +of two words (`EthKeccakAgree`, kept explicit here; `certifiedManifest'` discharges it with +`ethKeccakAgree`). -/ +theorem certifiedManifest (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) + (hk : EthKeccakAgree) {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Manifest.sources = [("Certified/bank/bank.sol", + "2a29919999674ac221097e3f50ed43bcddf094d19a08da5f5c9704a0dd099d03")] ∧ + Manifest.arguments = ["Certified/bank/bank.sol", "-Ogas", "--evm-version", "osaka", + "--emit=bin-runtime", "-Zemit-lean-stages=Certified/bank/gen"] ∧ + Manifest.optimization = "Gas" ∧ Manifest.evmVersion = "osaka" ∧ + Manifest.bytecodeSha256 = "bff0578068ce4ab4a041f226e4e960c13d358c8b430718fefe9ce3a22d760543" ∧ + Manifest.bytecodeHex = bytecodeHex ∧ + Manifest.bytecodeHex = String.ofList (hexChars bytecode) ∧ + hexBytes (codes Manifest.bytecodeHex) = some bytecode ∧ + code = ⟨(bytecode.map UInt8.ofNat).toArray⟩ ∧ + Stage (solidCore fuel) ethLib c code (fun call => ∃ σ, fullScope fns σ call) ∧ + Stage (solidCore fuel) ethLib c code (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := + ⟨rfl, rfl, rfl, rfl, rfl, rfl, manifest_hex, bytecode_of_manifest, rfl, certified o ho hk hc, + certifiedValue o ho hk hc⟩ + +/-- EthLib's and SolidCore's Keccak-256 agree on the 64 bytes of two words (for every pair of +numbers, not only words). -/ +theorem ethKeccakAgree : EthKeccakAgree := + fun a b _ _ => Keccak.ethKeccak_twoWords a b + +/-- **Bank from SolidCore to solar's bytecode**, with no Keccak hypothesis: every result +SolidCore's `Bank` gives on a call of `deposit`, `depositFor` and `balanceOf` on any argument +words, no value, from any storage, the bytecode gives under EthLib, for every oracle with EthLib's +caller and hash. -/ +theorem certified' (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) ethLib c code (fun call => ∃ σ, fullScope fns σ call) := + certified o ho ethKeccakAgree hc + +/-- **Bank from SolidCore to solar's bytecode at every value**, with no Keccak hypothesis. -/ +theorem certifiedValue' (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) ethLib c code (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := + certifiedValue o ho ethKeccakAgree hc + +open SolarTV.Export.Bank Hex in +/-- **The certified translation of bank, with no Keccak hypothesis**, bound to its manifest: +`certifiedManifest`'s conjunction with `EthKeccakAgree` discharged by `ethKeccakAgree` (EthLib's +and evmyul's Keccak-256 proved equal on every 64-byte message). -/ +theorem certifiedManifest' (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Manifest.sources = [("Certified/bank/bank.sol", + "2a29919999674ac221097e3f50ed43bcddf094d19a08da5f5c9704a0dd099d03")] ∧ + Manifest.arguments = ["Certified/bank/bank.sol", "-Ogas", "--evm-version", "osaka", + "--emit=bin-runtime", "-Zemit-lean-stages=Certified/bank/gen"] ∧ + Manifest.optimization = "Gas" ∧ Manifest.evmVersion = "osaka" ∧ + Manifest.bytecodeSha256 = "bff0578068ce4ab4a041f226e4e960c13d358c8b430718fefe9ce3a22d760543" ∧ + Manifest.bytecodeHex = bytecodeHex ∧ + Manifest.bytecodeHex = String.ofList (hexChars bytecode) ∧ + hexBytes (codes Manifest.bytecodeHex) = some bytecode ∧ + code = ⟨(bytecode.map UInt8.ofNat).toArray⟩ ∧ + Stage (solidCore fuel) ethLib c code (fun call => ∃ σ, fullScope fns σ call) ∧ + Stage (solidCore fuel) ethLib c code (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := + certifiedManifest o ho ethKeccakAgree hc + +/-- info: 'SolidCore.Refinement.Solar.Bank.callerOk_of' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms callerOk_of + +/-- info: 'SolidCore.Refinement.Solar.Bank.ethKeccakAgree' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms ethKeccakAgree + +/-- info: 'SolidCore.Refinement.Solar.Bank.certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified + +/-- info: 'SolidCore.Refinement.Solar.Bank.certifiedValue' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedValue + +/-- info: 'SolidCore.Refinement.Solar.Bank.manifest_hex' does not depend on any axioms -/ +#guard_msgs in +#print axioms manifest_hex + +/-- info: 'SolidCore.Refinement.Solar.Bank.bytecode_of_manifest' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms bytecode_of_manifest + +/-- info: 'SolidCore.Refinement.Solar.Bank.certifiedManifest' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedManifest + +/-- info: 'SolidCore.Refinement.Solar.Bank.certified'' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified' + +/-- info: 'SolidCore.Refinement.Solar.Bank.certifiedValue'' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedValue' + +/-- info: 'SolidCore.Refinement.Solar.Bank.certifiedManifest'' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedManifest' + +end SolidCore.Refinement.Solar.Bank diff --git a/SolidCore/Refinement/Solar/Bank/Lowering.lean b/SolidCore/Refinement/Solar/Bank/Lowering.lean new file mode 100644 index 00000000..e26b49bc --- /dev/null +++ b/SolidCore/Refinement/Solar/Bank/Lowering.lean @@ -0,0 +1,631 @@ +import SolidCore.Refinement.Generic.Value +import SolidCore.Refinement.KernelCopies +import SolidCore.Refinement.KernelRfl +import SolidCore.Refinement.Source.Bank +import bank.gen.Bank.Stage0 + +/-! +# bank: the generic source stage on solar's own module + +solar-tv/milestone/bank/bank.sol (sha256 +2a29919999674ac221097e3f50ed43bcddf094d19a08da5f5c9704a0dd099d03, copied to +scripts/refinement/bank/bank.sol), + + contract Bank { mapping(address => uint256) balances; uint256 total; + event Deposit(address indexed who, uint256 amount); + function credit(address who, uint256 amount) internal returns (uint256) { + balances[who] += amount; total += amount; return balances[who]; } + function deposit(uint256 amount) external returns (uint256) { + uint256 b = credit(msg.sender, amount); emit Deposit(msg.sender, amount); return b; } + function depositFor(address who, uint256 amount) external returns (uint256) { + return credit(who, amount); } + function balanceOf(address who) external view returns (uint256) { return balances[who]; } } + +has a mapping from addresses, whose entries live at `keccak256(abi.encode(key, 0))`, an +internal function that both `deposit` (for `msg.sender`) and `depositFor` call, checked +additions into the entry and into `total`, and an event with an indexed address. +`SolarTV.Export.Bank.stage0` is solar's first lowered MIR module for it (solar 0a455fda, +-Ogas, osaka), from solar's solar-tv/milestone/bank, the module whose backend stages solar's +milestone proves (`SolarTV.Milestone.Bank.bank_mir_to_evmir`). Its `credit` is an internal +function of the module, called with `call` and left with `leave`; it hashes memory words 0 +and 1 for the entry's slot; `deposit` reads `caller` and logs with `log 2`; the facts it +relies on (`assume`: the address words fit in 160 bits) follow from the path's checks. + +SolidCore's core (`coreLit`, solc 0.8.35's AST through scripts/solc_ast_to_lean_source.py into +Source/Bank.lean and `TypeCheck.CheckedInput.contract`, printed and copied) inlines no call: +its `internalCall` runs `credit`'s body in a frame of its own. The generic check erases it +by inlining (`Generic.eraseStmt`) and runs the module symbolically with the environment flag +(`Generic.symTree … .all`): the caller is `callerWord`, a mapping slot the word +`hash key slot`, storage at a computed slot a select on the slot words. Both trees agree in +canonical form for every function. + +* `shape_eq`: `Bank` type checks, its core is `coreLit`, its constructor leaves no storage; +* `check_stage0`, `checkValue_stage0`: the generic check accepts stage0 for the three + external functions, at no value and at any value (`decide +kernel`); +* `check_rejects_slot`, `check_rejects_caller`, `check_rejects_topic`: it rejects stage0 + with `credit`'s mapping slot 1 for 0, with `deposit`'s caller replaced by its argument, and + with the `Deposit` topic changed; +* `lowering`, `loweringValue`: the stage from SolidCore to stage0 on every call of the three + functions, from any storage, under every oracle with SolidCore's caller and hash of two words + (`Generic.SourceEnvOk`). + +No sorry, native_decide or bv_decide. +-/ + +namespace SolidCore.Refinement.Solar.Bank + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity SolidCore.Solidity.Source + +/-- The interpreter fuel of SolidCore's runs. -/ +def fuel : Nat := 4096 + +/-- The interpreter fuel of the symbolic run of the module: steps along each path. -/ +def mirFuel : Nat := 40 + +/-- SolidCore's checked `Bank`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.Bank.importedSourceUnit "Bank" + +/-- The selector of `deposit(uint256)`. -/ +abbrev depositSel : Nat := 0xb6b55f25 + +/-- The selector of `depositFor(address,uint256)`. -/ +abbrev depositForSel : Nat := 0x2f4f21e2 + +/-- The selector of `balanceOf(address)`. -/ +abbrev balanceOfSel : Nat := 0x70a08231 + +/-- `deposit` and its parameter. -/ +def fnDeposit : Fn := ⟨depositSel, [.uint 256]⟩ + +/-- `depositFor` and its parameters (an address is a word of 160 bits). -/ +def fnDepositFor : Fn := ⟨depositForSel, [.uint 160, .uint 256]⟩ + +/-- `balanceOf` and its parameter. -/ +def fnBalanceOf : Fn := ⟨balanceOfSel, [.uint 160]⟩ + +/-- The external functions of `Bank`. -/ +def fns : List Fn := [fnDeposit, fnDepositFor, fnBalanceOf] + +/-- SolidCore's core contract of `Bank`, as the type checker leaves it. -/ +def coreLit : Contract := + { storageFields := [{ name := "balances", + slot := 0, + ty? := none, + layout? := some (SolidCore.Solidity.Source.StorageLayout.mapping + (SolidCore.Solidity.Source.Ty.address) + (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.uint256))), + transient := false, + packedOffset := 0, + packedBytes := 32, + packedSigned := false }, + { name := "total", + slot := 1, + ty? := some (SolidCore.Solidity.Source.Ty.uint256), + layout? := some (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.uint256)), + transient := false, + packedOffset := 0, + packedBytes := 32, + packedSigned := false }], + immutableFields := [], + eventDecls := [{ name := "Deposit", + indexedCount := 1, + topic? := some 102222681472383059465863322013072701928378550215632170212813623808969952268444, + fields := [{ ty := SolidCore.Solidity.Source.Ty.address, indexed := true }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := false }] }, + { name := "Bank.Deposit", + indexedCount := 1, + topic? := some 102222681472383059465863322013072701928378550215632170212813623808969952268444, + fields := [{ ty := SolidCore.Solidity.Source.Ty.address, indexed := true }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := false }] }], + errorDecls := [], + functions := [{ name := "deposit", + selector? := some 3065339685, + payable := false, + params := [{ name := "amount", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "amount") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "amount")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.uint256) + "_sol_hoist_0" + none, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.address) + "_ic_arg_0" + (some (SolidCore.Solidity.Source.Expr.caller)), + SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.uint256) + "_ic_arg_1" + (some (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "amount"))), + SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.uint256) + "_ret_credit_0" + none, + SolidCore.Solidity.Source.Stmt.captureReturn + ["_ret_credit_0"] + (SolidCore.Solidity.Source.Stmt.internalCall + ["_ret_credit_0"] + "__internal_credit(address,uint256)#[SolidCore.Solidity.Ty.address false, SolidCore.Solidity.Ty.uint 256]" + [SolidCore.Solidity.Source.Expr.var "_ic_arg_0", + SolidCore.Solidity.Source.Expr.var "_ic_arg_1"]), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "_sol_hoist_0") + (SolidCore.Solidity.Source.Expr.var "_ret_credit_0")], + SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.uint256) + "b" + (some (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "_sol_hoist_0"))), + SolidCore.Solidity.Source.Stmt.emitEvent + "Deposit" + [SolidCore.Solidity.Source.Expr.caller, SolidCore.Solidity.Source.Expr.var "amount"], + SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "b")]]], + dispatchId? := none }, + { name := "depositFor", + selector? := some 793715170, + payable := false, + params := [{ name := "who", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }, + { name := "amount", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.none, + SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "amount") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "amount")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.uint256) + "_sol_hoist_0" + none, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.address) + "_ic_arg_0" + (some (SolidCore.Solidity.Source.Expr.var "who")), + SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.uint256) + "_ic_arg_1" + (some (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "amount"))), + SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.uint256) + "_ret_credit_0" + none, + SolidCore.Solidity.Source.Stmt.captureReturn + ["_ret_credit_0"] + (SolidCore.Solidity.Source.Stmt.internalCall + ["_ret_credit_0"] + "__internal_credit(address,uint256)#[SolidCore.Solidity.Ty.address false, SolidCore.Solidity.Ty.uint 256]" + [SolidCore.Solidity.Source.Expr.var "_ic_arg_0", + SolidCore.Solidity.Source.Expr.var "_ic_arg_1"]), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "_sol_hoist_0") + (SolidCore.Solidity.Source.Expr.var "_ret_credit_0")], + SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "_sol_hoist_0")]]], + dispatchId? := none }, + { name := "balanceOf", + selector? := some 1889567281, + payable := false, + params := [{ name := "who", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.none], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.element) + "balances" + [SolidCore.Solidity.Source.Expr.var "who"])]]], + dispatchId? := none }, + { name := "__internal_credit(address,uint256)#[SolidCore.Solidity.Ty.address false, SolidCore.Solidity.Ty.uint 256]", + selector? := none, + payable := false, + params := [{ name := "who", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }, + { name := "amount", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.none, + SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "amount") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "amount")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.add)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 256)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.element) + "balances" + [SolidCore.Solidity.Source.Expr.var "who"]) + (SolidCore.Solidity.Source.Expr.var "amount")), + SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.add)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 256)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "total" + []) + (SolidCore.Solidity.Source.Expr.var "amount")), + SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.element) + "balances" + [SolidCore.Solidity.Source.Expr.var "who"])]]], + dispatchId? := none }, + { name := "__internal_deposit(uint256)#[SolidCore.Solidity.Ty.uint 256]", + selector? := none, + payable := false, + params := [{ name := "amount", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "amount") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "amount")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.uint256) + "_sol_hoist_0" + none, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.address) + "_ic_arg_0" + (some (SolidCore.Solidity.Source.Expr.caller)), + SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.uint256) + "_ic_arg_1" + (some (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "amount"))), + SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.uint256) + "_ret_credit_0" + none, + SolidCore.Solidity.Source.Stmt.captureReturn + ["_ret_credit_0"] + (SolidCore.Solidity.Source.Stmt.internalCall + ["_ret_credit_0"] + "__internal_credit(address,uint256)#[SolidCore.Solidity.Ty.address false, SolidCore.Solidity.Ty.uint 256]" + [SolidCore.Solidity.Source.Expr.var "_ic_arg_0", + SolidCore.Solidity.Source.Expr.var "_ic_arg_1"]), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "_sol_hoist_0") + (SolidCore.Solidity.Source.Expr.var "_ret_credit_0")], + SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.uint256) + "b" + (some (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "_sol_hoist_0"))), + SolidCore.Solidity.Source.Stmt.emitEvent + "Deposit" + [SolidCore.Solidity.Source.Expr.caller, SolidCore.Solidity.Source.Expr.var "amount"], + SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "b")]]], + dispatchId? := none }, + { name := "__internal_depositFor(address,uint256)#[SolidCore.Solidity.Ty.address false, SolidCore.Solidity.Ty.uint 256]", + selector? := none, + payable := false, + params := [{ name := "who", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }, + { name := "amount", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.none, + SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "amount") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "amount")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.uint256) + "_sol_hoist_0" + none, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.address) + "_ic_arg_0" + (some (SolidCore.Solidity.Source.Expr.var "who")), + SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.uint256) + "_ic_arg_1" + (some (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "amount"))), + SolidCore.Solidity.Source.Stmt.varDecl + (SolidCore.Solidity.Source.Ty.uint256) + "_ret_credit_0" + none, + SolidCore.Solidity.Source.Stmt.captureReturn + ["_ret_credit_0"] + (SolidCore.Solidity.Source.Stmt.internalCall + ["_ret_credit_0"] + "__internal_credit(address,uint256)#[SolidCore.Solidity.Ty.address false, SolidCore.Solidity.Ty.uint 256]" + [SolidCore.Solidity.Source.Expr.var "_ic_arg_0", + SolidCore.Solidity.Source.Expr.var "_ic_arg_1"]), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "_sol_hoist_0") + (SolidCore.Solidity.Source.Expr.var "_ret_credit_0")], + SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "_sol_hoist_0")]]], + dispatchId? := none }, + { name := "__internal_balanceOf(address)#[SolidCore.Solidity.Ty.address false]", + selector? := none, + payable := false, + params := [{ name := "who", ty := SolidCore.Solidity.Source.Ty.address, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.none], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.element) + "balances" + [SolidCore.Solidity.Source.Expr.var "who"])]]], + dispatchId? := none }] } + +/-! ## The selectors and the event's signature topic + +The type checker computes each external function's selector and the event's topic by +Keccak-256, which costs the kernel about 400 MB a hash: each is checked once, alone, and the +check of the shape below runs on copies that read them from tables. -/ +/-- The selector of `deposit(uint256)`, by Keccak-256 of its signature. -/ +def selDeposit : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "deposit(uint256)" + +kernel_rfl selDeposit_eq selDeposit depositSel +/-- The selector of `depositFor(address,uint256)`, by Keccak-256 of its signature. -/ +def selDepositFor : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "depositFor(address,uint256)" + +kernel_rfl selDepositFor_eq selDepositFor depositForSel +/-- The selector of `balanceOf(address)`, by Keccak-256 of its signature. -/ +def selBalanceOf : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "balanceOf(address)" + +kernel_rfl selBalanceOf_eq selBalanceOf balanceOfSel +/-- The topic of `Deposit(address,uint256)`, by Keccak-256 of its signature. -/ +def topic : Nat := SolidCore.Solidity.Source.Keccak.digestWord "Deposit(address,uint256)" + +kernel_rfl topic_eq topic 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c + +/-- `ABI.selectorFromSignature`, with `Bank`'s signatures by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "deposit(uint256)" then depositSel + else if s = "depositFor(address,uint256)" then depositForSel + else if s = "balanceOf(address)" then balanceOfSel + else SolidCore.Solidity.Source.ABI.selectorFromSignature s + +theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + split + · next h => subst h; exact selDeposit_eq + · split + · next h => subst h; exact selDepositFor_eq + · split + · next h => subst h; exact selBalanceOf_eq + · rfl + +/-- `Keccak.digestWord`, with the event's signature by table. -/ +def digestTable (s : String) : Nat := + if s = "Deposit(address,uint256)" then 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c else SolidCore.Solidity.Source.Keccak.digestWord s + +theorem digest_eq : SolidCore.Solidity.Source.Keccak.digestWord = digestTable := by + funext s + unfold digestTable + split + · next h => subst h; exact topic_eq + · rfl + +/-- SolidCore's checked core of `Bank`, and whether its constructor leaves no storage and no +logs, when `Bank` type checks. -/ +def shape? : Option (Contract × Bool) := + match contract? with + | .ok c => some (c.core, Wide.deployedAt fuel c []) + | .error _ => none + +-- `shape_eq : shape? = some (coreLit, true)`: `Bank` type checks, its core is `coreLit` and its +-- constructor leaves no storage, by the kernel's conversion check on the copy of `shape?` that +-- reads the selectors and the topic from their tables. +kernel_rfl shape_eq shape? (some (coreLit, true)) using selector_eq digest_eq + +/-! ## The check on solar's module -/ +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for `deposit`. -/ +theorem check_deposit : + Generic.check fuel mirFuel coreLit SolarTV.Export.Bank.stage0 [fnDeposit] .all = true := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for `depositFor`. -/ +theorem check_depositFor : + Generic.check fuel mirFuel coreLit SolarTV.Export.Bank.stage0 [fnDepositFor] .all = true := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for `balanceOf`. -/ +theorem check_balanceOf : + Generic.check fuel mirFuel coreLit SolarTV.Export.Bank.stage0 [fnBalanceOf] .all = true := by + decide +kernel + +/-- The generic check accepts stage0 for every external function. -/ +theorem check_stage0 : + Generic.check fuel mirFuel coreLit SolarTV.Export.Bank.stage0 fns .all = true := by + have h0 := check_deposit + have h1 := check_depositFor + have h2 := check_balanceOf + simp only [Generic.check, List.all_cons, List.all_nil, Bool.and_true] at h0 h1 h2 + simp only [Generic.check, fns, List.all_cons, List.all_nil, Bool.and_true, h0, h1, h2] + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: no function is payable, and stage0 reverts with empty output on a +call of each with a value other than 0. -/ +theorem checkValue_stage0 : + Generic.checkValue mirFuel coreLit SolarTV.Export.Bank.stage0 fns .all = true := by + decide +kernel + +/-! ## Mutants the check rejects -/ + +/-- stage0 with each instruction of function `i` changed by `f`. -/ +def mapFn (i : Nat) (f : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst) : + SolarTV.MIR.Lowered.Module := + { SolarTV.Export.Bank.stage0 with + functions := SolarTV.Export.Bank.stage0.functions.mapIdx fun j fn => + if j = i then { fn with blocks := fn.blocks.map fun b => { b with insts := b.insts.map f } } + else fn } +/-- `credit`'s mapping slot: the hash of the key and the word 1, not 0. -/ +def wrongSlot : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect none .mstore [.const 32, .const 0] => .effect none .mstore [.const 32, .const 1] + | i => i + +/-- `deposit` crediting its argument word instead of `msg.sender`. -/ +def noCaller : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect (some 1) .caller [] => .effect (some 1) .calldataload [.const 4] + | i => i + +/-- `deposit`'s log with another first topic. -/ +def wrongTopic : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect none (.log 2) [a, b, .const t, c] => .effect none (.log 2) [a, b, .const (t + 1), c] + | i => i + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects `depositFor` with `credit`'s slot changed. -/ +theorem check_rejects_slot : + Generic.check fuel mirFuel coreLit (mapFn 0 wrongSlot) [fnDepositFor] .all = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects `deposit` crediting its argument word. -/ +theorem check_rejects_caller : + Generic.check fuel mirFuel coreLit (mapFn 1 noCaller) [fnDeposit] .all = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects `deposit` with the wrong topic. -/ +theorem check_rejects_topic : + Generic.check fuel mirFuel coreLit (mapFn 1 wrongTopic) [fnDeposit] .all = false := by + decide +kernel + +/-! ## The stage -/ + +/-- The checked contract has the core `coreLit`, and its constructor leaves no storage. -/ +theorem deployed_of {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core = coreLit ∧ ∃ d, Wide.DeployedAt fuel c d [] := by + have h := shape_eq + unfold shape? at h + rw [hc] at h + obtain ⟨hk, hd⟩ := Prod.mk.inj (Option.some.inj h) + exact ⟨hk, Wide.deployedAt_of hd⟩ + +/-- **The source stage of `Bank`**: every call of `deposit`, `depositFor` and `balanceOf` on any argument words, no value, +from any storage, under every oracle whose caller is SolidCore's and whose Keccak-256 of two words +is SolidCore's (`Generic.SourceEnvOk`). -/ +theorem lowering (o : SolarTV.Machine.Oracle) (henv : Generic.SourceEnvOk o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Bank.stage0 (fun call => ∃ σ, fullScope fns σ call) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact Generic.stageEnv o henv hd (by rw [hk]; exact check_stage0) + +/-- **The source stage of `Bank` at every value**: the same calls with any value below `2 ^ 256`: no function is payable, and both sides revert with empty data. -/ +theorem loweringValue (o : SolarTV.Machine.Oracle) (henv : Generic.SourceEnvOk o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Bank.stage0 (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact Generic.stageValueEnv o henv hd (by rw [hk]; exact check_stage0) + (by rw [hk]; exact checkValue_stage0) + +#print axioms selector_eq + +#print axioms digest_eq + +#print axioms shape_eq + +#print axioms check_stage0 + +#print axioms checkValue_stage0 + +#print axioms check_rejects_slot + +#print axioms check_rejects_caller + +#print axioms check_rejects_topic + +#print axioms lowering + +#print axioms loweringValue + +end SolidCore.Refinement.Solar.Bank diff --git a/SolidCore/Refinement/Solar/Bank/Mutants.lean b/SolidCore/Refinement/Solar/Bank/Mutants.lean new file mode 100644 index 00000000..e2bf8b5a --- /dev/null +++ b/SolidCore/Refinement/Solar/Bank/Mutants.lean @@ -0,0 +1,62 @@ +import SolidCore.Refinement.Solar.Bank.Assembly + +/-! +# bank: one-byte mutants of the bytecode + +The assembler check rejects the bytecode with one byte changed where the assembly stage's +fragment for bank is new: the mapping slot's hash, the caller, the event's log, the return +label the internal call pushes, the internal function's return jump and the key it hashes. Each +rejection is the kernel's evaluation of the check's one-pass form (`Assemble.checkFast`). +-/ + +namespace SolidCore.Refinement.Solar.Bank + +open SolarTV.Assembly SolarTV.Export.Bank + +/-- The bytes with the byte at i replaced by b. -/ +def mutant (i b : Nat) : ByteArray := ⟨((bytecode.set i b).map UInt8.ofNat).toArray⟩ + +/-- The bytes the mutants replace: the mapping slot's KECCAK256 (0x58), `deposit`'s CALLER (0x4a), +its LOG2 (0xb0), the return label it pushes (0x4c, the immediate 0x87), the internal function's +return JUMP (0x86) and the DUP2 of the key it stores for the hash (0x4e). -/ +theorem mutated_bytes : bytecode[0x58]? = some 0x20 ∧ bytecode[0x4a]? = some 0x33 ∧ + bytecode[0xb0]? = some 0xa2 ∧ bytecode[0x4c]? = some 0x87 ∧ bytecode[0x86]? = some 0x56 ∧ + bytecode[0x4e]? = some 0x81 := by decide + +set_option maxRecDepth 100000 in +/-- ADD for the hash of the mapping slot: rejected. -/ +theorem mutantKeccak_check : Assemble.check evm11 (mutant 0x58 0x01) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +set_option maxRecDepth 100000 in +/-- ORIGIN for CALLER: rejected. -/ +theorem mutantCaller_check : Assemble.check evm11 (mutant 0x4a 0x32) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +set_option maxRecDepth 100000 in +/-- LOG1 for the event's LOG2: rejected. -/ +theorem mutantLog_check : Assemble.check evm11 (mutant 0xb0 0xa1) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +set_option maxRecDepth 100000 in +/-- A return label one byte past its block: rejected. -/ +theorem mutantLabel_check : Assemble.check evm11 (mutant 0x4c 0x88) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +set_option maxRecDepth 100000 in +/-- STOP for the return jump: rejected. -/ +theorem mutantReturn_check : Assemble.check evm11 (mutant 0x86 0x00) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +set_option maxRecDepth 100000 in +/-- DUP3 for the key's DUP2, so the hash reads another word as the key: rejected. -/ +theorem mutantKey_check : Assemble.check evm11 (mutant 0x4e 0x82) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +end SolidCore.Refinement.Solar.Bank diff --git a/SolidCore/Refinement/Solar/C4/Assembly.lean b/SolidCore/Refinement/Solar/C4/Assembly.lean new file mode 100644 index 00000000..3913a4f2 --- /dev/null +++ b/SolidCore/Refinement/Solar/C4/Assembly.lean @@ -0,0 +1,76 @@ +import SolidCore.Refinement.Solar.AssembleSim +import c4.gen.Main.Evm5 +import c4.gen.Main.Bytecode + +/-! +# c4: two packed uint8 fields, from any storage + +scripts/refinement/c4/c4.sol (`contract Main { uint8 v; uint8 w = 7; function add(uint8 x) ... }`: +`v += x; w ^= x; return v;`) compiles with solar's default options and -Zcheck-analyses=false to the +final EVM IR `evm5` (after `cfg-simplify-early`) and to 107 bytes of runtime bytecode, both exported +by -Zemit-lean-stages into solar's solar-tv/milestone/c4 and imported from there (c4.gen.Main.Evm5, +c4.gen.Main.Bytecode). solar's +solar-tv/milestone/c4 proves the stages from the first lowered MIR to `evm5` +(`SolarTV.Milestone.C4.c4_mir_to_evmir`); this file proves the last one, `evm5` to the bytecode. + +Both fields live in slot 0, `v` in its low byte and `w` in the next: the code reads the slot, +masks `v` out (AND 0xff), adds with the overflow check, merges it back (AND NOT 0xff, OR), reads +`w` with BYTE 30, XORs, shifts it back (SHL 8), merges it (AND NOT 0xff00, OR) and stores the slot. +The layout is three blocks, each jump forward, so the default certificate's potentials suffice. + +* `check_ok`: the checker accepts `evm5` and the bytes with `cert`, by the kernel's evaluation. +* `stage`: EVM IR to bytecode is a stage on every call with no value, from any storage, under + every oracle, from `Assemble.stage_of_check` at `check_ok`. +* `stageAll`: the same on every call, with any value, from `Assemble.stage_of_check_all`. +* `mutantSub_check`, `mutantShl_check`: the checker rejects one-byte mutants, SUB for the + addition's ADD and SHL for the BYTE that reads `w`. +-/ + +namespace SolidCore.Refinement.Solar.C4 + +open SolarTV.Assembly SolarTV.Export.Main + +/-- The runtime bytecode solar exported. -/ +def code : ByteArray := ⟨(bytecode.map UInt8.ofNat).toArray⟩ + +/-- The calls of the stage: no value, any call data, any storage. -/ +def scope (call : SolarTV.Call) : Prop := call.callvalue = 0 + +/-- The certificate: each block's offset in the code (bb3, the revert, at 0x55; bb7, the +Panic(0x11), at 0x59), the stack height each block needs on entry (none), and the bound on memory +(the return's and the panic's 64 bytes). -/ +def cert : Assemble.Cert := { offsets := [0, 0x55, 0x59], needs := [0, 0, 0], top := 64 } + +set_option maxRecDepth 100000 in +/-- The checker accepts solar's bytecode for the program, by the kernel's evaluation. -/ +theorem check_ok : Assemble.check evm5 code cert = true := by decide +kernel + +/-- EVM IR to bytecode is a stage for c4 on every call with no value, from any storage, under +every oracle: the generic theorem at check_ok. -/ +theorem stage (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) SolidCore.Refinement.ethLib evm5 + (show SolidCore.Refinement.ethLib.Prog from code) scope := + Assemble.stage_of_check check_ok o fun _ h => h + +/-- EVM IR to bytecode is a stage for c4 on every call, with any value, call data and storage, +under every oracle: `Assemble.stage_of_check_all` at check_ok. -/ +theorem stageAll (o : SolarTV.Machine.Oracle) (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.evmirSem o) SolidCore.Refinement.ethLib evm5 + (show SolidCore.Refinement.ethLib.Prog from code) scope := + Assemble.stage_of_check_all check_ok o scope + +/-- The bytes with the byte at `i` replaced by `b`. -/ +def mutant (i b : Nat) : ByteArray := ⟨((bytecode.set i b).map UInt8.ofNat).toArray⟩ + +/-- The addition's ADD, at offset 0x2b, and the BYTE that reads `w`, at offset 0x3d. -/ +theorem mutated_bytes : bytecode[0x2b]? = some 0x01 ∧ bytecode[0x3d]? = some 0x1a := by decide + +set_option maxRecDepth 100000 in +/-- SUB for the addition's ADD: the checker rejects it. -/ +theorem mutantSub_check : Assemble.check evm5 (mutant 0x2b 0x03) cert = false := by decide +kernel + +set_option maxRecDepth 100000 in +/-- SHL for the BYTE that reads `w`: the checker rejects it. -/ +theorem mutantShl_check : Assemble.check evm5 (mutant 0x3d 0x1b) cert = false := by decide +kernel + +end SolidCore.Refinement.Solar.C4 diff --git a/SolidCore/Refinement/Solar/C4/Certified.lean b/SolidCore/Refinement/Solar/C4/Certified.lean new file mode 100644 index 00000000..1ef16278 --- /dev/null +++ b/SolidCore/Refinement/Solar/C4/Certified.lean @@ -0,0 +1,184 @@ +import SolidCore.Refinement.Solar.C4.Lowering +import SolidCore.Refinement.Solar.C4.LoweringGeneric +import SolidCore.Refinement.Solar.C4.Assembly +import c4.Proofs.Stages +import c4.gen.Main.Manifest + +/-! +# c4: SolidCore to solar's bytecode, through every stage + +The end-to-end certified translation of the corpus contract c4 (scripts/refinement/corpus/c4.sol), + + contract Main { uint8 v; uint8 w = 7; + function add(uint8 x) external returns (uint8) { v += x; w ^= x; return v; } } + +by solar 7817979b with -Zcheck-analyses=false (default -Ogas, osaka), chaining with Stage.trans: + +1. the source stage, SolidCore's checked Main to solar's first lowered MIR stage0 + (C4.lowering from the deployed storage, C4.loweringAt from any storage that writes slot 0; + every call of add on any argument word, clean or dirty, no value, every oracle); +2. the backend stages of solar's solar-tv/milestone/c4, stage0 → mir1 (place-reads) → mir2 + (evm-inst-schedule) → sched (stack-schedule) → evm1 … evm5 (cfg-simplify-early, + compact-pushes, share-reverts, terminal-dedup, cfg-simplify-early), each a kernel-checked + symbolic run on every call with any call data, value and storage + (SolarTV.Milestone.C4.c4_mir_to_evmir); +3. the assembly stage, evm5 to the 107 bytes of runtime bytecode, by the generic assembler check + (Assembly.lean, stageAll from Assemble.stage_of_check_all). + +The backend and assembly stages hold on every call, so the source stages at every value +(C4.lowering_value, C4.loweringAt_value in LoweringGeneric.lean, where SolidCore reverts a call +with a nonzero value and the MIR takes its paid branch) compose with them too: +certified_deployed_value and certified_at_value are certified_deployed and certified_at on calls +with any value below 2 ^ 256. + +All three use the same exported modules (c4.gen.Main), so the stages compose by definition. +The bytes the assembly stage reaches (C4.code, the export's Bytecode.lean) are Corpus.C4.code, +the bytecode the specification and the corpus refinement speak of (code_eq, by the kernel). +The export's manifest (c4.gen.Main.Manifest) records the source's sha256, the compiler's version +and commit, its arguments, and the bytecode with its sha256; certified states them, and that the +bytes the stages run are the manifest's hex. solar's certify.sh checks the hashes against the +files (the source, each stage, the bytecode), outside the kernel. + +* certified_deployed, certified_at: the stage from SolidCore to Corpus.C4.code on Verify.C4.scope + (from the deployed storage) and on Verify.C4.scopeAt (any storage that writes slot 0). +* satisfies_at: Verify.C4's specification from any storage (postAt) holds of the bytecode, carried + through these stages (Satisfies.of_stage), not through the bytecode's direct symbolic run. +* certified: all of it bound to the manifest. + +No sorry, native_decide or bv_decide: the theorems depend on propext, Classical.choice and +Quot.sound only (pinned below). +-/ + +namespace SolidCore.Refinement.Solar.C4 + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity SolarTV.Export.Main + +/-- The value of a lowercase hex digit's ASCII code. -/ +def hexDigit (c : Nat) : Option Nat := + if 48 ≤ c ∧ c ≤ 57 then some (c - 48) + else if 97 ≤ c ∧ c ≤ 102 then some (c - 87) + else none + +/-- The bytes a string of lowercase hex digits spells, from its ASCII codes. -/ +def hexBytes : List Nat → Option (List Nat) + | [] => some [] + | a :: b :: rest => + match hexDigit a, hexDigit b, hexBytes rest with + | some x, some y, some r => some ((16 * x + y) :: r) + | _, _, _ => none + | [_] => none + +/-- The ASCII codes of a string. -/ +def codes (s : String) : List Nat := s.toUTF8.toList.map (·.toNat) + +set_option maxRecDepth 100000 in +/-- The bytes the stages run are the manifest's hex, which --emit=bin-runtime printed. -/ +theorem bytecode_of_manifest : hexBytes (codes Manifest.bytecodeHex) = some bytecode := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The export's bytecode is the corpus's: the bytes the specification speaks of. -/ +theorem code_eq : code = Corpus.C4.code := by + decide +kernel + +/-- The backend: solar-tv's stages from stage0 to evm5, then the assembly stage to the bytecode. -/ +theorem backend (o : SolarTV.Machine.Oracle) (scope : SolarTV.Call → Prop) : + Stage (SolarTV.MIR.Lowered.moduleSem o) ethLib stage0 Corpus.C4.code scope := + code_eq ▸ SolarTV.Stage.trans (B := SolarTV.evmirSem o) + ((SolarTV.Milestone.C4.c4_mir_to_evmir o).mono fun _ _ => trivial) (stageAll o scope) + +/-- **c4 from SolidCore to solar's bytecode**, from the deployed storage: every result +SolidCore's Main gives on a call of add on any argument word, no value, from the storage its +constructor leaves (slot 0 = 7 * 256), the bytecode gives under EthLib, for every oracle. -/ +theorem certified_deployed (o : SolarTV.Machine.Oracle) {c : TypeCheck.CheckedContract} + (hc : Corpus.C4.contract? = .ok c) : + Stage (solidCore Corpus.C4.fuel) ethLib c Corpus.C4.code Verify.C4.scope := + (lowering o hc).trans (backend o _) + +/-- **c4 from SolidCore to solar's bytecode**, from any storage that writes slot 0. -/ +theorem certified_at (o : SolarTV.Machine.Oracle) {c : TypeCheck.CheckedContract} + (hc : Corpus.C4.contract? = .ok c) : + Stage (solidCore Corpus.C4.fuel) ethLib c Corpus.C4.code Verify.C4.scopeAt := + (loweringAt o hc).trans (backend o _) + +/-- **c4 from SolidCore to solar's bytecode at every value**, from the deployed storage: every +result SolidCore's Main gives on a call of add on any argument word, with any value below 2 ^ 256, +from the storage its constructor leaves, the bytecode gives under EthLib, for every oracle. -/ +theorem certified_deployed_value (o : SolarTV.Machine.Oracle) {c : TypeCheck.CheckedContract} + (hc : Corpus.C4.contract? = .ok c) : + Stage (solidCore Corpus.C4.fuel) ethLib c Corpus.C4.code + (fun call => ∃ v, Generic.fullScopeValue Corpus.C4.fns Verify.C4.deployed v call) := + (lowering_value o hc).trans (backend o _) + +/-- **c4 from SolidCore to solar's bytecode at every value**, from any storage that writes +slot 0. -/ +theorem certified_at_value (o : SolarTV.Machine.Oracle) {c : TypeCheck.CheckedContract} + (hc : Corpus.C4.contract? = .ok c) : + Stage (solidCore Corpus.C4.fuel) ethLib c Corpus.C4.code scopeAtValue := + (loweringAt_value o hc).trans (backend o _) + +/-- **c4's specification on solar's bytecode through every stage**: Verify.C4.postAt, from any +storage that writes slot 0, carried from SolidCore by certified_at. -/ +theorem satisfies_at (o : SolarTV.Machine.Oracle) : + Satisfies ethLib Corpus.C4.code Verify.C4.scopeAt Verify.C4.pre Verify.C4.postAt := by + obtain ⟨c, hc, hspec⟩ := Verify.C4.satisfiesAt + exact SolidCore.Refinement.Satisfies.of_stage hspec (certified_at o hc) + +/-- **The certified translation of c4**, bound to what it was compiled from and by: the source +(path and sha256), its arguments +(-Zcheck-analyses=false, -Ogas, osaka), the bytecode with its sha256 and hex, the bytes the stages run +as that bytecode, and the stage from SolidCore's checked Main to those bytes, from the deployed +storage and from any storage that writes slot 0, with no value and with any value, under every +oracle, with the specification it carries. -/ +theorem certified (o : SolarTV.Machine.Oracle) {c : TypeCheck.CheckedContract} + (hc : Corpus.C4.contract? = .ok c) : + Manifest.sources = [("Certified/c4/c4.sol", + "31c39cd4e9c5cba0f78aff3a986d69be40c5f68cdb36fbf05ad3d0a5e950e858")] ∧ + Manifest.arguments = ["Certified/c4/c4.sol", "-Zcheck-analyses=false", + "--emit=bin-runtime", "-Zemit-lean-stages=Certified/c4/gen"] ∧ + Manifest.optimization = "Gas" ∧ Manifest.evmVersion = "osaka" ∧ + Manifest.bytecodeSha256 = "8a21bc207d9dd8be48d921a717eda3ecb7e5bfcb5397850bc3d64a29037fac47" ∧ + Manifest.bytecodeHex = bytecodeHex ∧ hexBytes (codes Manifest.bytecodeHex) = some bytecode ∧ + Corpus.C4.code = ⟨(bytecode.map UInt8.ofNat).toArray⟩ ∧ + Stage (solidCore Corpus.C4.fuel) ethLib c Corpus.C4.code Verify.C4.scope ∧ + Stage (solidCore Corpus.C4.fuel) ethLib c Corpus.C4.code Verify.C4.scopeAt ∧ + Stage (solidCore Corpus.C4.fuel) ethLib c Corpus.C4.code + (fun call => ∃ v, Generic.fullScopeValue Corpus.C4.fns Verify.C4.deployed v call) ∧ + Stage (solidCore Corpus.C4.fuel) ethLib c Corpus.C4.code scopeAtValue ∧ + Satisfies ethLib Corpus.C4.code Verify.C4.scopeAt Verify.C4.pre Verify.C4.postAt := + ⟨rfl, rfl, rfl, rfl, rfl, rfl, bytecode_of_manifest, code_eq.symm, certified_deployed o hc, + certified_at o hc, certified_deployed_value o hc, certified_at_value o hc, satisfies_at o⟩ + +/-- info: 'SolidCore.Refinement.Solar.C4.code_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms code_eq + +/-- info: 'SolidCore.Refinement.Solar.C4.backend' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms backend + +/-- info: 'SolidCore.Refinement.Solar.C4.certified_deployed' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified_deployed + +/-- info: 'SolidCore.Refinement.Solar.C4.certified_at' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified_at + +/-- info: 'SolidCore.Refinement.Solar.C4.certified_deployed_value' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified_deployed_value + +/-- info: 'SolidCore.Refinement.Solar.C4.certified_at_value' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified_at_value + +/-- info: 'SolidCore.Refinement.Solar.C4.satisfies_at' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms satisfies_at + +/-- info: 'SolidCore.Refinement.Solar.C4.certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified + +end SolidCore.Refinement.Solar.C4 diff --git a/SolidCore/Refinement/Solar/C4/Lowering.lean b/SolidCore/Refinement/Solar/C4/Lowering.lean new file mode 100644 index 00000000..094c062f --- /dev/null +++ b/SolidCore/Refinement/Solar/C4/Lowering.lean @@ -0,0 +1,1035 @@ +import Verify.C4 +import SolidCore.Refinement.Spec +import SolidCore.Refinement.Evm.WideStorage +import W1Proofs.Tactic +import c4.gen.Main.Stage0 + +/-! +# c4: SolidCore to solar's first lowered MIR, and on to its bytecode + +The source stage of the corpus contract c4 (scripts/refinement/corpus/c4.sol), + + contract Main { uint8 v; uint8 w = 7; + function add(uint8 x) external returns (uint8) { v += x; w ^= x; return v; } } + +from SolidCore's checked contract (Corpus.C4.contract?) to the first lowered MIR module solar +compiles for it (SolarTV.Export.Main.stage0, after lower-evm-shaped, so lower-abi's ABI +decoding and lower-dispatch's dispatcher included; c4.gen.Main.Stage0, solar's export in +solar-tv/milestone/c4), in SolarTV's +lowered MIR semantics under any oracle. Here the MIR side is a symbolic run of this one module; +C4/LoweringGeneric.lean derives the same stage, and the one from any storage that writes slot 0, +from the generic source stage. + +* mir_run_of: on every call whose call data reads as add(x) with a clean x < 2 ^ 8, no value, + from the deployed storage (slot 0 = 7 * 256), stage0 returns x and leaves slot 0 holding + x + (7 ^ x) * 256, by W1Proofs.Tactic's evaluation steps; the packed words are checked by + the kernel on every clean x (slot_word, low_byte: Evm.Wide.forall_of_lt_ofNat and + decide +kernel). mir_run_dirty_of: a dirty word reverts with empty data. +* mir_run: both, as expectedAt Verify.C4.deployed x, the observable of Verify.C4.model. +* lowering: the stage on Verify.C4.scope, every call of add on any argument word from the + deployed storage, with source_run (Verify.C4.run_add). +* mir_run_at: from any storage σ, on a symbolic slot-0 word, stage0 runs to expectedAt σ x, + clean or dirty, v + x in uint8 or a Panic(0x11) revert (mir_run_ok_of, mir_run_panic_of). + stage0's packed-word operations are computed through toNat for every slot-0 word + (slot_word_at, from Nat.testBit lemmas on the masks), not by the kernel's enumeration. +* loweringAt_of_runs: the stage on Verify.C4.scopeAt, any storage that writes slot 0, from + SolidCore's run there (source_run_at, Verify.C4.run_add_at) and a MIR module's run there + (hmir). loweringAt: the stage for stage0, with hmir from mir_run_at. +* target_run_at: EthLib runs solar's bytecode Corpus.C4.code from any storage to the same + observable, by Evm.WideStorage's steps on a named slot-0 word (tgt_slot_word). mir_assemblyAt: + the assembly-side stage from stage0 to the bytecode on scopeAt; certifiedAt: Verify.C4.postAt + of the bytecode on scopeAt through loweringAt and mir_assemblyAt; certifiedAt_of_backend: the + same through any backend stage to EVM IR; bytecode_satisfiesAll: postAt of the bytecode on + every call from every storage (scopeAll), slot 0 written or not, which SolidCore cannot give + since it runs a call from its storage written over the constructor's (slot 0 = 7 * 256). +* certified_of_backend: Verify.C4's specification holds of solar's bytecode Corpus.C4.code + through the stages, given the backend stage from stage0 to the final EVM IR (solar-tv's + SolarTV.Milestone.C4.c4_mir_to_evmir; C4/Certified.lean composes the three stages). The assembly + stage is derived from c4's direct refinement Corpus.C4.refines_full (assembly_of_refines), + not from the EVM IR. + +The names of solar's stages (SolarTV.Export.Main) are those of w1's and w4's too, so this +module cannot share an import closure with Solar.Lowering, Solar.W4Lowering or the library +root; lake build SolidCoreSolarC4 builds it. + +No sorry, native_decide or bv_decide: the theorems depend on propext, Quot.sound and +Classical.choice only (pinned below). +-/ + +namespace SolidCore.Refinement.Solar.C4 + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm +open SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Wide + +/-- The selector of add(uint8). -/ +abbrev addSelector : Nat := Bytecode.C4.Main.addSelector + +/-- What add(x) from the storage σ shows: the observable of Verify.C4.model. -/ +def expectedAt (σ : List (Nat × Nat)) (x : U256) : Observable := + Verify.observe (slotValue σ) (Verify.C4.model [x.toNat] (slotValue σ)) + +/-! ## The calls of the scope -/ + +theorem scopeAt_callAt {call : Call} (h : Verify.C4.scopeAt call) : + ∃ (x : U256) (σ : List (Nat × Nat)), (∃ kv ∈ σ, kv.1 % 2 ^ 256 = 0) ∧ + call = callAt addSelector [x] σ := by + obtain ⟨σ, hσ, fn, hfn, args, hlen, hlt, rfl⟩ := h + simp only [Corpus.C4.fns, List.mem_singleton] at hfn + subst hfn + match args, hlen with + | [a], _ => + refine ⟨BitVec.ofNat 256 a, σ, hσ, ?_⟩ + have ha : a % 2 ^ 256 = a := Nat.mod_eq_of_lt (hlt a (by simp)) + simp only [callAt, List.map_cons, List.map_nil, BitVec.toNat_ofNat, ha] + +theorem scope_callAt {call : Call} (h : Verify.C4.scope call) : + ∃ x : U256, call = callAt addSelector [x] Verify.C4.deployed := by + obtain ⟨fn, hfn, args, hlen, hlt, rfl⟩ := h + simp only [Corpus.C4.fns, List.mem_singleton] at hfn + subst hfn + match args, hlen with + | [a], _ => + refine ⟨BitVec.ofNat 256 a, ?_⟩ + have ha : a % 2 ^ 256 = a := Nat.mod_eq_of_lt (hlt a (by simp)) + simp only [callAt, List.map_cons, List.map_nil, BitVec.toNat_ofNat, ha] + +/-! ## SolidCore -/ + +/-- SolidCore runs c4's add on any argument word, from any storage σ that writes slot 0, to +expectedAt σ x. -/ +theorem source_run_at {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : Corpus.C4.contract? = .ok c) (x : U256) (σ : List (Nat × Nat)) + (hσ : ∃ kv ∈ σ, kv.1 % 2 ^ 256 = 0) : + Source.run Corpus.C4.fuel c (callAt addSelector [x] σ) = some (expectedAt σ x) := by + obtain ⟨hk, _, hdep⟩ := Verify.C4.shape_of hc + obtain ⟨d, hd⟩ := deployedAt_of hdep + exact Verify.C4.run_add_at hk hd x σ hσ + +/-! ## Call data -/ + +section Calldata + +open SolarTV SolarTV.Machine + +theorem shl_or_ofNat (acc b : Nat) (hb : b < 256) : + (BitVec.ofNat 256 acc <<< 8) ||| BitVec.ofNat 256 b = BitVec.ofNat 256 (acc * 256 + b) := by + have hand : (BitVec.ofNat 256 acc <<< 8) &&& BitVec.ofNat 256 b = 0 := by + ext i hi + rw [BitVec.getElem_and, BitVec.getElem_shiftLeft, ← BitVec.getLsbD_eq_getElem, + ← BitVec.getLsbD_eq_getElem, BitVec.getLsbD_ofNat] + by_cases h8 : i < 8 + · simp [h8] + · have : b.testBit i = false := + Nat.testBit_lt_two_pow (Nat.lt_of_lt_of_le hb + (by simpa using Nat.pow_le_pow_right (by decide : 0 < 2) (Nat.le_of_not_lt h8))) + simp [BitVec.getLsbD_ofNat, this] + rw [← BitVec.add_eq_or_of_and_eq_zero _ _ hand] + apply BitVec.eq_of_toNat_eq + simp only [BitVec.toNat_add, BitVec.toNat_shiftLeft, BitVec.toNat_ofNat, Nat.shiftLeft_eq] + omega + +theorem foldl_word (data : ByteArray) (off : Nat) : ∀ (l : List Nat) (acc : Nat), + l.foldl (fun (acc : BitVec 256) i => + (acc <<< 8) ||| BitVec.ofNat 256 (data.data.getD (off + i) 0).toNat) + (BitVec.ofNat 256 acc) = + BitVec.ofNat 256 (l.foldl (fun acc i => acc * 256 + (byteAt data (off + i)).toNat) acc) + | [], _ => rfl + | i :: l, acc => by + simp only [List.foldl_cons] + have hget : (data.data.getD (off + i) 0) = byteAt data (off + i) := rfl + rw [hget, shl_or_ofNat _ _ (byteAt data (off + i)).toNat_lt, foldl_word data off l] + +/-- CALLDATALOAD in SolarTV is EthLib's: the big-endian word of 32 bytes of call data from the +offset, zero past its end. -/ +theorem calldataWord_eq (call : Call) (off : BitVec 256) : + calldataWord call off = loadWord call.calldata off.toNat 32 := by + unfold calldataWord loadWord bufferRead bytesToNat + rw [show (0 : BitVec 256) = BitVec.ofNat 256 0 from rfl, foldl_word, List.foldl_map] + +theorem calldata_callAt (x : U256) (σ : List (Nat × Nat)) : + (callAt addSelector [x] σ).calldata = cdOf (selectorOf addSelector) [x] := by + have := calldata_eq_cdOf addSelector [x.toNat] (by + intro y hy + simp only [List.mem_cons, List.mem_nil_iff, or_false] at hy + rcases hy with rfl + exact BitVec.isLt _) + simpa [callAt, List.map_map, Function.comp_def] using this + +theorem word0 (x : U256) (σ : List (Nat × Nat)) : + EvmRules.Evm.shr 224 (calldataWord (callAt addSelector [x] σ) 0) = BitVec.ofNat 256 addSelector := by + rw [calldataWord_eq, calldata_callAt] + have := shr_cdOf_selectorOf addSelector [x] (by decide) + simpa [EvmRules.Evm.shr, bitwiseShr] using this + +theorem word4 (x : U256) (σ : List (Nat × Nat)) : calldataWord (callAt addSelector [x] σ) 4 = x := by + rw [calldataWord_eq, calldata_callAt] + exact loadWord_cdOf_getD _ [x] 4 (by simp [size_selectorOf]) (by simp [size_selectorOf]) + (by simp [size_selectorOf]) + +theorem word0' (x : U256) (σ : List (Nat × Nat)) : + EvmRules.Evm.shr 224 (calldataWord (callAt addSelector [x] σ) 0) = 33980010 := by + have h := word0 x σ + rw [show BitVec.ofNat 256 addSelector = 33980010 from rfl] at h + exact h + +theorem size_callAt (x : U256) (σ : List (Nat × Nat)) : + (callAt addSelector [x] σ).calldata.size = 36 := by + rw [calldata_callAt, size_cdOf, size_selectorOf]; rfl + +end Calldata + +/-! ## SolarTV's lowered MIR runs stage0 from the deployed storage -/ + +section Lowering + +open SolarTV SolarTV.Machine SolarTV.Milestone.W1 + +theorem bytes_toNat (len n : Nat) : + (List.range len).map (fun i => (n / 256 ^ (len - 1 - i)) % 256) = + (natToBytes len n).map (·.toNat) := by + induction len generalizing n with + | zero => rfl + | succ len ih => + rw [natToBytes_succ, List.map_append, ← ih, List.range_succ, List.map_append] + congr 1 + · apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [Nat.div_div_eq_div_mul, ← Nat.pow_succ'] + congr 3 + omega + · simp + +theorem byte_toNat (v : EvmRules.Word) (i : Nat) (_hi : i < 32) : + (SolarTV.Memory.byte v i).toNat = v.toNat / 256 ^ (31 - i) % 256 := by + unfold SolarTV.Memory.byte + rw [BitVec.toNat_setWidth, BitVec.toNat_ushiftRight, Nat.shiftRight_eq_div_pow, Nat.pow_mul] + +theorem read_store (m : Mem) (v : EvmRules.Word) : + (((m.store 0 v).expand 0 32).read 0 32).map BitVec.toNat = + (natToBytes 32 v.toNat).map (·.toNat) := by + rw [← bytes_toNat] + simp only [Mem.read, Mem.expand, Mem.store, List.map_map] + simp only [show (32 = 0) = False from by decide, ite_false] + apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + simp only [Function.comp_apply, Nat.zero_add, Nat.zero_le, true_and, hi, ite_true, Nat.sub_zero] + rw [byte_toNat v i hi] + +theorem gt_255 (x : EvmRules.Word) (hx : x.toNat < 256) : EvmRules.Evm.gt x 255 = 0 := by + have : (255#256).ult x = false := by simp [BitVec.ult]; omega + simp [EvmRules.Evm.gt, this] + +/-- What add(x) shows from the deployed storage, on a clean x: x returned, x + (7 ^ x) * 256 +in slot 0. -/ +def expectedD (x : EvmRules.Word) : Observable := + { success := true, output := SolidCore.Verify.word x.toNat, logs := [], + storage := fun k => if k % 2 ^ 256 = 0 then x.toNat + (7 ^^^ x.toNat) * 256 + else slotValue [(0, 1792)] k } + +/-- The word add writes to slot 0 from the deployed storage, for each clean x, by the kernel's +evaluation on every x below 256. -/ +theorem slot_word : ∀ x : EvmRules.Word, x.toNat < 256 → + EvmRules.Evm.or + (EvmRules.Evm.and + (EvmRules.Evm.or + (EvmRules.Evm.and 1792 115792089237316195423570985008687907853269984665640564039457584007913129639680) x) + 115792089237316195423570985008687907853269984665640564039457584007913129574655) + (EvmRules.Evm.shl 8 + (EvmRules.Evm.xor + (EvmRules.Evm.byte 30 + (EvmRules.Evm.or + (EvmRules.Evm.and 1792 + 115792089237316195423570985008687907853269984665640564039457584007913129639680) x)) x)) = + BitVec.ofNat 256 (x.toNat + (7 ^^^ x.toNat) * 256) := + SolidCore.Refinement.Evm.Wide.forall_of_lt_ofNat (by decide +kernel) + +theorem low_byte : ∀ x : EvmRules.Word, x.toNat < 256 → + EvmRules.Evm.and (BitVec.ofNat 256 (x.toNat + (7 ^^^ x.toNat) * 256)) 255 = x := + SolidCore.Refinement.Evm.Wide.forall_of_lt_ofNat (by decide +kernel) + +/-- The operands of commutative word operations in the order `sym_cond` puts them in (its +`word*Comm` simprocs), so that facts about them match the goal. -/ +syntax "comm_order" (Lean.Parser.Tactic.location)? : tactic + +macro_rules + | `(tactic| comm_order $[$loc]?) => `(tactic| simp only [SolarTV.Milestone.W1.wordAddComm, + SolarTV.Milestone.W1.wordMulComm, SolarTV.Milestone.W1.wordAndComm, + SolarTV.Milestone.W1.wordOrComm, SolarTV.Milestone.W1.wordXorComm] $[$loc]?) + +set_option linter.unusedSimpArgs false in +theorem mir_run_of (o : Oracle) (call : Call) (x : EvmRules.Word) (hv : call.callvalue = 0) + (hsize : call.calldata.size = 36) (h0 : EvmRules.Evm.shr 224 (calldataWord call 0) = 33980010) + (h4 : calldataWord call 4 = x) (hx : x.toNat < 256) (hst : call.storage = [(0, 1792)]) : + (MIR.Lowered.Module.run o SolarTV.Export.Main.stage0 call 12).map (fun r => observe call r.2 r.1) = some (expectedD x) := by + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + have hs0 : (State.initial call).storage 0 = 1792 := by simp [State.initial, hst, slotValue] + have hgt := gt_255 x hx + have ha : EvmRules.Evm.and 1792 255 = 0 := by decide + have hadd : EvmRules.Evm.add 0 x = x := by simp [EvmRules.Evm.add] + have hlt : ¬ (255 : EvmRules.Word) < x := by simp [BitVec.lt_def]; omega + try comm_order at ha hadd + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte, hs0, hgt, ha, hadd, hlt]) + have hsw := slot_word x hx + have hlb := low_byte x hx + -- `sym_eval` folds the constant `and 1792 mask` in the goal: fold it in the lemma too. + try dsimp only [SolarTV.Milestone.W1.foldAnd] at hsw + try comm_order at hsw hlb + rw [hsw] + try comm_order + rw [hlb] + simp only [observe, expectedD, Option.some.injEq, Observable.mk.injEq, true_and] + refine ⟨?_, rfl, ?_⟩ + · exact read_store _ x + · funext slot + simp only [storageOf, update] + have hv : x.toNat + (7 ^^^ x.toNat) * 256 < 2 ^ 256 := by + have := Nat.xor_lt_two_pow (n := 8) (x := 7) (y := x.toNat) (by decide) (by omega) + omega + split + · rename_i e + have h : slot % 2 ^ 256 = 0 := by simpa using congrArg BitVec.toNat e + rw [ite_eq_left_of_eq_true _ _ (eq_true h), BitVec.toNat_ofNat, Nat.mod_eq_of_lt hv] + · rename_i e + have h : ¬ slot % 2 ^ 256 = 0 := + fun h => e (BitVec.eq_of_toNat_eq (by simpa using h)) + rw [ite_eq_right_of_eq_false _ _ (eq_false h)] + simp only [State.initial, hst, BitVec.toNat_ofNat] + exact slotValue_mod_mod _ slot + +set_option linter.unusedSimpArgs false in +/-- On a dirty word, stage0 reverts with empty data and keeps the storage. -/ +theorem mir_run_dirty_of (o : Oracle) (call : Call) (x : EvmRules.Word) (hv : call.callvalue = 0) + (hsize : call.calldata.size = 36) (h0 : EvmRules.Evm.shr 224 (calldataWord call 0) = 33980010) + (h4 : calldataWord call 4 = x) (hx : ¬ x.toNat < 256) : + (MIR.Lowered.Module.run o SolarTV.Export.Main.stage0 call 12).map + (fun r => observe call r.2 r.1) = + some ⟨false, [], [], slotValue call.storage⟩ := by + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + have hgt : EvmRules.Evm.gt x 255 = 1 := by + have : (255#256).ult x = true := by simp [BitVec.ult]; omega + simp [EvmRules.Evm.gt, this] + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte, hgt]) + rfl + +/-- A run of a lowered MIR module that ends within some fuel is its fuel-free result. -/ +theorem mir_sem_of_run {o : Oracle} {m : MIR.Lowered.Module} {call : Call} {obs : Observable} + (n : Nat) (h : (MIR.Lowered.Module.run o m call n).map (fun r => observe call r.2 r.1) = some obs) : + (MIR.Lowered.moduleSem o).run m call = some obs := by + obtain ⟨r, hr, rfl⟩ := Option.map_eq_some_iff.1 h + have e : MIR.Lowered.moduleLayer.result o m call = some r := + MIR.Lowered.moduleLayer.result_of_ends ⟨n, hr⟩ + show (MIR.Lowered.moduleLayer.result o m call).map _ = _ + rw [e] + rfl + +/-- SolarTV's lowered MIR semantics runs c4's first lowered MIR module on every call of add(x) +from the deployed storage, under every oracle, to expectedAt Verify.C4.deployed x. -/ +theorem mir_run (o : Oracle) (x : U256) : + (MIR.Lowered.moduleSem o).run SolarTV.Export.Main.stage0 + (callAt addSelector [x] Verify.C4.deployed) = some (expectedAt Verify.C4.deployed x) := by + by_cases hx : x.toNat < 256 + · refine mir_sem_of_run 12 ((mir_run_of o _ x rfl (size_callAt x _) (word0' x _) (word4 x _) hx + rfl).trans ?_) + have h2 : slotValue Verify.C4.deployed 0 % 256 + x.toNat < 256 := by + simp [slotValue, Verify.C4.deployed]; omega + simp only [expectedAt, Verify.C4.model_ok x.toNat _ hx h2, Verify.observe, expectedD, + Option.some.injEq, Observable.mk.injEq, true_and] + have h0 : slotValue Verify.C4.deployed 0 = 1792 := rfl + refine ⟨by rw [h0]; simp, ?_⟩ + funext k + have hv : x.toNat + (7 ^^^ x.toNat) * 256 < 2 ^ 256 := by + have := Nat.xor_lt_two_pow (n := 8) (x := 7) (y := x.toNat) (by decide) (by omega) + omega + rw [h0] + split + · simp only [Nat.reduceDiv, Nat.reduceMod, Nat.zero_mul, Nat.zero_add] + rw [Nat.mod_eq_of_lt (by omega)] + omega + · rfl + · refine mir_sem_of_run 12 ((mir_run_dirty_of o _ x rfl (size_callAt x _) (word0' x _) + (word4 x _) hx).trans ?_) + simp only [expectedAt, Verify.C4.model_dirty x.toNat _ hx, Verify.observe] + rfl + +end Lowering + +/-! ## SolarTV's lowered MIR runs stage0 from any storage + +On a symbolic slot-0 word s, stage0's packed-word operations are computed through toNat: the +masks are multiples of powers of two with their bits counted by Nat.testBit (and_mask_high, +and_mask_byte1), and an OR of words with disjoint bits is their sum (toNat_or_disjoint, +or_byte1), so slot_word_at gives the word add writes, s's high bytes, w ^ x in byte 1 and v + x +in byte 0, for every s. -/ + +section Packed + +open SolarTV SolarTV.Machine SolarTV.Milestone.W1 + +/-- Masking a word below 2 ^ (k + w) with its bits from k up keeps the multiple of 2 ^ k below it. -/ +theorem and_mask_high (n k w : Nat) (hn : n < 2 ^ (k + w)) : + n &&& 2 ^ k * (2 ^ w - 1) = n / 2 ^ k * 2 ^ k := by + apply Nat.eq_of_testBit_eq + intro j + simp only [Nat.testBit_and, Nat.testBit_two_pow_mul, Nat.testBit_two_pow_sub_one, + Nat.testBit_mul_two_pow, Nat.testBit_div_two_pow] + by_cases hj : k ≤ j + · rw [Nat.sub_add_cancel hj] + by_cases hw : j < k + w + · simp [hj, show j - k < w by omega] + · have : n.testBit j = false := + Nat.testBit_lt_two_pow (Nat.lt_of_lt_of_le hn (Nat.pow_le_pow_right (by decide) (by omega))) + simp [this] + · simp [hj] + +/-- Masking a word with every bit but those of byte 1 clears byte 1. -/ +theorem and_mask_byte1 (n : Nat) (hn : n < 2 ^ 256) : + n &&& (2 ^ 16 * (2 ^ 240 - 1) + (2 ^ 8 - 1)) = 2 ^ 16 * (n / 2 ^ 16) + n % 2 ^ 8 := by + apply Nat.eq_of_testBit_eq + intro j + have h1 : 2 ^ 8 - 1 < 2 ^ 16 := by decide + have h2 : n % 2 ^ 8 < 2 ^ 16 := by omega + rw [Nat.testBit_and, Nat.testBit_two_pow_mul_add _ h1, Nat.testBit_two_pow_mul_add _ h2] + by_cases hj : j < 16 + · simp only [hj, ite_true, Nat.testBit_two_pow_sub_one, Nat.testBit_mod_two_pow] + by_cases h8 : j < 8 <;> simp [h8] + · simp only [hj, ite_false, Nat.testBit_two_pow_sub_one, Nat.testBit_div_two_pow] + rw [Nat.sub_add_cancel (by omega)] + by_cases hw : j < 256 + · simp [show j - 16 < 240 by omega] + · have : n.testBit j = false := + Nat.testBit_lt_two_pow (Nat.lt_of_lt_of_le hn (Nat.pow_le_pow_right (by decide) (by omega))) + simp [this] + +/-- A byte y placed in byte 1 of a word whose byte 1 is clear is added to it. -/ +theorem or_byte1 (H c y : Nat) (hc : c < 2 ^ 8) (hy : y < 2 ^ 8) : + (2 ^ 16 * H + c) ||| 2 ^ 8 * y = 2 ^ 16 * H + (2 ^ 8 * y + c) := by + have h1 : c < 2 ^ 16 := by omega + have h2 : 2 ^ 8 * y + c < 2 ^ 16 := by omega + rw [Nat.two_pow_add_eq_or_of_lt h1, Nat.two_pow_add_eq_or_of_lt h2, Nat.two_pow_add_eq_or_of_lt hc, + Nat.or_assoc, Nat.or_comm c] + +/-- AND with 255 keeps the low byte. -/ +theorem toNat_and_255 (s : EvmRules.Word) : (EvmRules.Evm.and s 255).toNat = s.toNat % 256 := by + unfold EvmRules.Evm.and + rw [BitVec.toNat_and, show (255 : EvmRules.Word).toNat = 2 ^ 8 - 1 from rfl, Nat.and_two_pow_sub_one_eq_mod] + +/-- AND with the mask that clears v's byte keeps every byte above it. -/ +theorem toNat_and_high (s : EvmRules.Word) : + (EvmRules.Evm.and s 115792089237316195423570985008687907853269984665640564039457584007913129639680).toNat = + s.toNat / 256 * 256 := by + unfold EvmRules.Evm.and + rw [BitVec.toNat_and, show (115792089237316195423570985008687907853269984665640564039457584007913129639680 : EvmRules.Word).toNat = 2 ^ 8 * (2 ^ 248 - 1) from rfl, + and_mask_high _ 8 248 s.isLt] + rfl + +/-- AND with the mask that clears w's byte keeps every other byte. -/ +theorem toNat_and_byte1 (s : EvmRules.Word) : + (EvmRules.Evm.and s 115792089237316195423570985008687907853269984665640564039457584007913129574655).toNat = + s.toNat / 65536 * 65536 + s.toNat % 256 := by + unfold EvmRules.Evm.and + rw [BitVec.toNat_and, show (115792089237316195423570985008687907853269984665640564039457584007913129574655 : EvmRules.Word).toNat = 2 ^ 16 * (2 ^ 240 - 1) + (2 ^ 8 - 1) from rfl, + and_mask_byte1 _ s.isLt] + omega + +/-- BYTE 30 reads byte 1 from the low end, w's. -/ +theorem toNat_byte30 (v : EvmRules.Word) : (EvmRules.Evm.byte 30 v).toNat = v.toNat / 256 % 256 := by + unfold EvmRules.Evm.byte + rw [show (30 : EvmRules.Word).ult 32 = true from rfl, Bool.cond_true, show ((31 : EvmRules.Word) - 30) * 8 = 8 from rfl, + BitVec.ushiftRight_eq', BitVec.toNat_and, BitVec.toNat_ushiftRight, show (255 : EvmRules.Word).toNat = 2 ^ 8 - 1 from rfl, + Nat.and_two_pow_sub_one_eq_mod, Nat.shiftRight_eq_div_pow] + rfl + +/-- SHL 8 of a byte places it in byte 1. -/ +theorem toNat_shl8 (v : EvmRules.Word) (hv : v.toNat < 256) : (EvmRules.Evm.shl 8 v).toNat = v.toNat * 256 := by + unfold EvmRules.Evm.shl + rw [show (8 : EvmRules.Word).ult 256 = true from rfl, Bool.cond_true, BitVec.shiftLeft_eq', BitVec.toNat_shiftLeft, Nat.shiftLeft_eq] + rw [show (8 : EvmRules.Word).toNat = 8 from rfl, Nat.mod_eq_of_lt (by omega)] + +/-- OR of a multiple of 2 ^ k and a word below 2 ^ k is their sum. -/ +theorem toNat_or_disjoint (a b : EvmRules.Word) (k : Nat) (ha : a.toNat % 2 ^ k = 0) (hb : b.toNat < 2 ^ k) : + (EvmRules.Evm.or a b).toNat = a.toNat + b.toNat := by + unfold EvmRules.Evm.or + rw [BitVec.toNat_or] + have : a.toNat = 2 ^ k * (a.toNat / 2 ^ k) := by + have := Nat.div_add_mod a.toNat (2 ^ k); omega + rw [this, ← Nat.two_pow_add_eq_or_of_lt hb] + +/-- v + x, when it fits in uint8, does not wrap. -/ +theorem toNat_add_low (s x : EvmRules.Word) (hc : s.toNat % 256 + x.toNat < 256) : + (EvmRules.Evm.add (EvmRules.Evm.and s 255) x).toNat = s.toNat % 256 + x.toNat := by + unfold EvmRules.Evm.add + rw [BitVec.toNat_add, toNat_and_255] + exact Nat.mod_eq_of_lt (by omega) + +/-- The word add writes to slot 0 from any slot-0 word s, when v + x fits in uint8: s's high +bytes, w ^ x in byte 1 and v + x in byte 0. -/ +theorem slot_word_at (s x : EvmRules.Word) (hx : x.toNat < 256) (hc : s.toNat % 256 + x.toNat < 256) : + (EvmRules.Evm.or + (EvmRules.Evm.and + (EvmRules.Evm.or + (EvmRules.Evm.and s 115792089237316195423570985008687907853269984665640564039457584007913129639680) + (EvmRules.Evm.add (EvmRules.Evm.and s 255) x)) + 115792089237316195423570985008687907853269984665640564039457584007913129574655) + (EvmRules.Evm.shl 8 + (EvmRules.Evm.xor + (EvmRules.Evm.byte 30 + (EvmRules.Evm.or + (EvmRules.Evm.and s 115792089237316195423570985008687907853269984665640564039457584007913129639680) + (EvmRules.Evm.add (EvmRules.Evm.and s 255) x))) + x))).toNat = + s.toNat / 65536 * 65536 + (s.toNat / 256 % 256 ^^^ x.toNat) * 256 + (s.toNat % 256 + x.toNat) := by + have h34 := toNat_add_low s x hc + have h11 : (EvmRules.Evm.or + (EvmRules.Evm.and s 115792089237316195423570985008687907853269984665640564039457584007913129639680) + (EvmRules.Evm.add (EvmRules.Evm.and s 255) x)).toNat = s.toNat / 256 * 256 + (s.toNat % 256 + x.toNat) := by + rw [toNat_or_disjoint _ _ 8 (by rw [toNat_and_high]; omega) (by rw [h34]; omega), + toNat_and_high, h34] + generalize EvmRules.Evm.or + (EvmRules.Evm.and s 115792089237316195423570985008687907853269984665640564039457584007913129639680) + (EvmRules.Evm.add (EvmRules.Evm.and s 255) x) = v at h11 ⊢ + have hy : (EvmRules.Evm.xor (EvmRules.Evm.byte 30 v) x).toNat = s.toNat / 256 % 256 ^^^ x.toNat := by + unfold EvmRules.Evm.xor + rw [BitVec.toNat_xor, toNat_byte30, h11] + congr 1 + omega + have hylt : s.toNat / 256 % 256 ^^^ x.toNat < 2 ^ 8 := + Nat.xor_lt_two_pow (by omega) (by omega) + generalize EvmRules.Evm.xor (EvmRules.Evm.byte 30 v) x = y at hy ⊢ + unfold EvmRules.Evm.or + rw [BitVec.toNat_or, toNat_and_byte1, toNat_shl8 y (by omega), h11, hy] + rw [show (s.toNat / 256 * 256 + (s.toNat % 256 + x.toNat)) / 65536 * 65536 + + (s.toNat / 256 * 256 + (s.toNat % 256 + x.toNat)) % 256 = + 2 ^ 16 * (s.toNat / 65536) + (s.toNat % 256 + x.toNat) by omega, + show (s.toNat / 256 % 256 ^^^ x.toNat) * 256 = 2 ^ 8 * (s.toNat / 256 % 256 ^^^ x.toNat) by omega, + or_byte1 _ _ _ (by omega) hylt] + omega + +/-- The low byte of that word is v + x, which add returns. -/ +theorem low_byte_at (s x : EvmRules.Word) (hc : s.toNat % 256 + x.toNat < 256) : + EvmRules.Evm.and (BitVec.ofNat 256 + (s.toNat / 65536 * 65536 + (s.toNat / 256 % 256 ^^^ x.toNat) * 256 + (s.toNat % 256 + x.toNat))) 255 = + BitVec.ofNat 256 (s.toNat % 256 + x.toNat) := by + apply BitVec.eq_of_toNat_eq + rw [toNat_and_255, BitVec.toNat_ofNat, BitVec.toNat_ofNat] + have := s.isLt + have hy : s.toNat / 256 % 256 ^^^ x.toNat < 2 ^ 8 := Nat.xor_lt_two_pow (by omega) (by omega) + omega + +set_option linter.unusedSimpArgs false in +/-- On a clean x where v + x fits in uint8, from any storage, stage0 runs as Verify.C4.model: +v + x returned, and slot 0 holding the high bytes of the call's slot-0 word, w ^ x and +v + x. -/ +theorem mir_run_ok_of (o : Oracle) (call : Call) (x : EvmRules.Word) (hv : call.callvalue = 0) + (hsize : call.calldata.size = 36) (h0 : EvmRules.Evm.shr 224 (calldataWord call 0) = 33980010) + (h4 : calldataWord call 4 = x) (hx : x.toNat < 256) + (hc : slotValue call.storage 0 % 256 + x.toNat < 256) : + (MIR.Lowered.Module.run o SolarTV.Export.Main.stage0 call 12).map (fun r => observe call r.2 r.1) = + some (SolidCore.Verify.observe (slotValue call.storage) + (SolidCore.Verify.C4.model [x.toNat] (slotValue call.storage))) := by + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + have hgt := gt_255 x hx + have hs : ((State.initial call).storage 0).toNat = slotValue call.storage 0 := by + show (BitVec.ofNat 256 (slotValue call.storage 0)).toNat = _ + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt (slotValue_lt _ _)] + have hc' : ((State.initial call).storage 0).toNat % 256 + x.toNat < 256 := by rw [hs]; exact hc + have hlt : ¬ 255 < EvmRules.Evm.add (EvmRules.Evm.and ((State.initial call).storage 0) 255) x := by + rw [BitVec.lt_def, toNat_add_low _ _ hc'] + show ¬ 255 < _ + omega + have hw := BitVec.eq_of_toNat_eq ((slot_word_at _ x hx hc').trans + (BitVec.toNat_ofNat _ _ |>.trans (Nat.mod_eq_of_lt (by + have := ((State.initial call).storage 0).isLt + have hy : ((State.initial call).storage 0).toNat / 256 % 256 ^^^ x.toNat < 2 ^ 8 := + Nat.xor_lt_two_pow (by omega) (by omega) + omega))).symm) + clear hs + try comm_order at hlt hw + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte, hgt]) + have hlb := low_byte_at _ x hc' + try comm_order at hlb + try comm_order + rw [hlb] + have hs : ((State.initial call).storage 0).toNat = slotValue call.storage 0 := by + show (BitVec.ofNat 256 (slotValue call.storage 0)).toNat = _ + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt (slotValue_lt _ _)] + rw [hs, SolidCore.Verify.C4.model_ok _ _ hx hc] + simp only [observe, SolidCore.Verify.observe, Option.some.injEq, Observable.mk.injEq] + have h0lt := slotValue_lt call.storage 0 + have hy : slotValue call.storage 0 / 256 % 256 ^^^ x.toNat < 2 ^ 8 := + Nat.xor_lt_two_pow (by omega) (by omega) + refine ⟨trivial, ?_, rfl, ?_⟩ + · refine (read_store _ _).trans ?_ + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt (by omega)] + rfl + · funext slot + simp only [storageOf, update] + split + · rename_i e + have h : slot % 2 ^ 256 = 0 := by simpa using congrArg BitVec.toNat e + rw [ite_eq_left_of_eq_true _ _ (eq_true h), BitVec.toNat_ofNat] + · rename_i e + have h : ¬ slot % 2 ^ 256 = 0 := + fun h => e (BitVec.eq_of_toNat_eq (by simpa using h)) + rw [ite_eq_right_of_eq_false _ _ (eq_false h)] + simp only [State.initial, BitVec.toNat_ofNat] + exact slotValue_mod_mod _ slot + +set_option linter.unusedSimpArgs false in +/-- On a clean x where v + x overflows uint8, from any storage, stage0 reverts with Panic(0x11) +as Verify.C4.model does. -/ +theorem mir_run_panic_of (o : Oracle) (call : Call) (x : EvmRules.Word) (hv : call.callvalue = 0) + (hsize : call.calldata.size = 36) (h0 : EvmRules.Evm.shr 224 (calldataWord call 0) = 33980010) + (h4 : calldataWord call 4 = x) (hx : x.toNat < 256) + (hc : ¬ slotValue call.storage 0 % 256 + x.toNat < 256) : + (MIR.Lowered.Module.run o SolarTV.Export.Main.stage0 call 12).map (fun r => observe call r.2 r.1) = + some (SolidCore.Verify.observe (slotValue call.storage) + (SolidCore.Verify.C4.model [x.toNat] (slotValue call.storage))) := by + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + have hgt := gt_255 x hx + have hs : ((State.initial call).storage 0).toNat = slotValue call.storage 0 := by + show (BitVec.ofNat 256 (slotValue call.storage 0)).toNat = _ + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt (slotValue_lt _ _)] + have hlt : 255 < EvmRules.Evm.add (EvmRules.Evm.and ((State.initial call).storage 0) 255) x := by + rw [BitVec.lt_def] + unfold EvmRules.Evm.add + rw [BitVec.toNat_add, toNat_and_255, hs, Nat.mod_eq_of_lt (by omega)] + show 255 < _ + omega + clear hs + try comm_order at hlt + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte, hgt]) + rw [SolidCore.Verify.C4.model_panic _ _ hx hc] + rfl + +/-- SolarTV's lowered MIR semantics runs c4's first lowered MIR module on every call of add(x) +from any storage σ, under every oracle, to expectedAt σ x: the MIR reads slot 0 of σ as it is, +so σ need not write slot 0. -/ +theorem mir_run_at (o : Oracle) (x : U256) (σ : List (Nat × Nat)) : + (MIR.Lowered.moduleSem o).run SolarTV.Export.Main.stage0 (callAt addSelector [x] σ) = + some (expectedAt σ x) := by + by_cases hx : x.toNat < 256 + · by_cases hc : slotValue σ 0 % 256 + x.toNat < 256 + · exact mir_sem_of_run 12 (mir_run_ok_of o _ x rfl (size_callAt x σ) (word0' x σ) (word4 x σ) + hx hc) + · exact mir_sem_of_run 12 (mir_run_panic_of o _ x rfl (size_callAt x σ) (word0' x σ) + (word4 x σ) hx hc) + · refine mir_sem_of_run 12 ((mir_run_dirty_of o _ x rfl (size_callAt x σ) (word0' x σ) + (word4 x σ) hx).trans ?_) + simp only [expectedAt, Verify.C4.model_dirty x.toNat _ hx, Verify.observe] + rfl + +end Packed + +/-! ## The source stage -/ + +/-- **The source stage of c4**: SolidCore to solar's first lowered MIR, which includes ABI +decoding and dispatch, on every call of add on any argument word, clean or dirty, from the +deployed storage, under every oracle. -/ +theorem lowering (o : SolarTV.Machine.Oracle) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : Corpus.C4.contract? = .ok c) : + Stage (solidCore Corpus.C4.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 Verify.C4.scope := by + intro call hscope obs hrun + obtain ⟨x, rfl⟩ := scope_callAt hscope + change Source.run Corpus.C4.fuel c (callAt addSelector [x] Verify.C4.deployed) = some obs at hrun + rw [source_run_at hc x Verify.C4.deployed ⟨(0, 7 * 256), List.mem_singleton_self _, rfl⟩] at hrun + cases hrun + exact mir_run o x + +/-- The source stage from any storage that writes slot 0, for any first lowered MIR module that +runs every such call of add as Verify.C4.model does (hmir). For solar's stage0, hmir is +mir_run_at (loweringAt). -/ +theorem loweringAt_of_runs (o : SolarTV.Machine.Oracle) {m : SolarTV.MIR.Lowered.Module} + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : Corpus.C4.contract? = .ok c) + (hmir : ∀ (x : U256) (σ : List (Nat × Nat)), (∃ kv ∈ σ, kv.1 % 2 ^ 256 = 0) → + (SolarTV.MIR.Lowered.moduleSem o).run m (callAt addSelector [x] σ) = some (expectedAt σ x)) : + Stage (solidCore Corpus.C4.fuel) (SolarTV.MIR.Lowered.moduleSem o) c m Verify.C4.scopeAt := by + intro call hscope obs hrun + obtain ⟨x, σ, hσ, rfl⟩ := scopeAt_callAt hscope + change Source.run Corpus.C4.fuel c (callAt addSelector [x] σ) = some obs at hrun + rw [source_run_at hc x σ hσ] at hrun + cases hrun + exact hmir x σ hσ + +/-- **The source stage of c4 from any storage**: SolidCore to solar's first lowered MIR, on every +call of add on any argument word, clean or dirty, with no value, from any storage that writes +slot 0, under every oracle: loweringAt_of_runs with stage0's run from any storage (mir_run_at). -/ +theorem loweringAt (o : SolarTV.Machine.Oracle) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : Corpus.C4.contract? = .ok c) : + Stage (solidCore Corpus.C4.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 Verify.C4.scopeAt := + loweringAt_of_runs o hc fun x σ _ => mir_run_at o x σ + +/-! ## To the bytecode -/ + +/-- A stage into EthLib from a program that agrees with SolidCore (chain), when the bytecode +refines SolidCore on the scope: each observable of the program is SolidCore's, which is the +bytecode's. -/ +theorem assembly_of_refines {fuel : Nat} {A : Sem} {p : A.Prog} + {c : SolidCore.Solidity.TypeCheck.CheckedContract} {code : ByteArray} {scope : Call → Prop} + (href : Refines fuel c code scope) (chain : Stage (solidCore fuel) A c p scope) : + Stage A ethLib p code scope := by + intro call hs obs hrun + obtain ⟨obs', h1, h2⟩ := href call hs + have := chain call hs obs' h1 + rw [hrun] at this + cases this + exact h2 + +/-- **c4 through solar's stages.** Given the backend stage from solar's first lowered MIR to +an EVM IR program evm (solar-tv's certify.sh proves it on every call for each contract it +certifies), Verify.C4's specification holds of solar's bytecode Corpus.C4.code under EthLib, on +every call of add from the deployed storage: bytecode_of_stages with the source stage +(lowering), the backend, and the assembly stage from c4's refinement (Corpus.C4.refines_full). -/ +theorem certified_of_backend (o : SolarTV.Machine.Oracle) {evmirSem : Sem} {evm : evmirSem.Prog} + (backend : Stage (SolarTV.MIR.Lowered.moduleSem o) evmirSem SolarTV.Export.Main.stage0 evm + Verify.C4.scope) : + Satisfies ethLib Corpus.C4.code Verify.C4.scope Verify.C4.pre Verify.C4.post := by + obtain ⟨c, hc, hs, hspec⟩ := Verify.C4.satisfies + obtain ⟨c', s, hc', hs', href⟩ := Corpus.C4.refines_full + rw [hc] at hc' + cases hc' + rw [hs] at hs' + cases hs' + have low := lowering o hc + exact bytecode_of_stages hspec low backend (assembly_of_refines href (low.trans backend)) + +/-! ## To the bytecode from any storage + +EthLib runs solar's bytecode Corpus.C4.code on every call of add from any storage σ to +expectedAt σ x (target_run_at), as stage0 does (mir_run_at): Evm.WideStorage's steps up to the +JUMPI on v + x, where the slot-0 word SLOAD read is named S, and then up to the RETURN or REVERT, +whose words tgt_slot_word and tgt_low_byte compute. Neither run needs σ to write slot 0; only +SolidCore's does (scopeAt), since it runs a call from σ written over the constructor's storage. + +* mir_assemblyAt: lowered MIR to bytecode, stage0 to Corpus.C4.code, on scopeAt. +* assemblyAt_of_chain: the assembly stage for any program that agrees with SolidCore on + scopeAt, such as the EVM IR a backend stage reaches from stage0. +* certifiedAt: Verify.C4's specification from any storage (postAt) holds of the bytecode through + loweringAt and mir_assemblyAt. certifiedAt_of_backend: the same through a backend stage + from stage0 to EVM IR (bytecode_of_stages). +* bytecode_satisfiesAll: the bytecode meets postAt on scopeAll, every call of add from every + storage, slot 0 written or not, from target_run_at alone. -/ + +section TargetAt + +open EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Symex SolidCore.Refinement.Evm.Logic + +/-- The low byte of a slot-0 word, as EthLib's AND leaves it. -/ +theorem ofNat_and_255 (S : Nat) (hS : S < 2 ^ 256) : + (BitVec.ofNat 256 S &&& 255#256) = BitVec.ofNat 256 (S % 256) := by + apply BitVec.eq_of_toNat_eq + have : (BitVec.ofNat 256 S &&& 255#256).toNat = S % 256 := by + rw [BitVec.toNat_and, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hS] + exact Nat.and_two_pow_sub_one_eq_mod S 8 + rw [this, BitVec.toNat_ofNat] + omega + +/-- The word solar's bytecode writes to slot 0 from the slot-0 word S, under EthLib's operations, +when v + x fits in uint8: slot_word_at, since EthLib's BYTE and SHL are EvmRules'. -/ +theorem tgt_slot_word (S : Nat) (x : U256) (hS : S < 2 ^ 256) (hx : x.toNat < 256) + (hc : S % 256 + x.toNat < 256) : + (115792089237316195423570985008687907853269984665640564039457584007913129574655#256 &&& + (115792089237316195423570985008687907853269984665640564039457584007913129639680#256 &&& + BitVec.ofNat 256 S ||| x + BitVec.ofNat 256 (S % 256)) ||| + bitwiseShl (8#256) + (getByte (30#256) + (115792089237316195423570985008687907853269984665640564039457584007913129639680#256 &&& + BitVec.ofNat 256 S ||| x + BitVec.ofNat 256 (S % 256)) ^^^ x)) = + BitVec.ofNat 256 (S / 65536 * 65536 + (S / 256 % 256 ^^^ x.toNat) * 256 + (S % 256 + x.toNat)) := by + have hs : (BitVec.ofNat 256 S).toNat = S := by rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt hS] + have hc' : (BitVec.ofNat 256 S).toNat % 256 + x.toNat < 256 := by rw [hs]; exact hc + have hlow : EvmRules.Evm.add (EvmRules.Evm.and (BitVec.ofNat 256 S) 255) x = x + BitVec.ofNat 256 (S % 256) := by + apply BitVec.eq_of_toNat_eq + rw [toNat_add_low _ _ hc', BitVec.toNat_add, hs] + simp only [BitVec.toNat_ofNat] + omega + have hb : ∀ v : U256, getByte (30#256) v = EvmRules.Evm.byte 30 v := fun v => rfl + have hsh : ∀ v : U256, bitwiseShl (8#256) v = EvmRules.Evm.shl 8 v := fun v => rfl + have e := slot_word_at (BitVec.ofNat 256 S) x hx hc' + rw [hs, hlow] at e + apply BitVec.eq_of_toNat_eq + have hy : S / 256 % 256 ^^^ x.toNat < 2 ^ 8 := Nat.xor_lt_two_pow (by omega) (by omega) + have hF : S / 65536 * 65536 + (S / 256 % 256 ^^^ x.toNat) * 256 + (S % 256 + x.toNat) < 2 ^ 256 := by + omega + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt hF, ← e, hb, hsh] + simp only [EvmRules.Evm.or, EvmRules.Evm.and, EvmRules.Evm.xor, BitVec.and_comm] + rfl + +/-- The low byte of that word, which the bytecode returns. -/ +theorem tgt_low_byte (S : Nat) (x : U256) (hS : S < 2 ^ 256) (hc : S % 256 + x.toNat < 256) : + 255#256 &&& BitVec.ofNat 256 (S / 65536 * 65536 + (S / 256 % 256 ^^^ x.toNat) * 256 + (S % 256 + x.toNat)) = + BitVec.ofNat 256 (S % 256 + x.toNat) := by + apply BitVec.eq_of_toNat_eq + have hy : S / 256 % 256 ^^^ x.toNat < 2 ^ 8 := Nat.xor_lt_two_pow (by omega) (by omega) + have hF : S / 65536 * 65536 + (S / 256 % 256 ^^^ x.toNat) * 256 + (S % 256 + x.toNat) < 2 ^ 256 := by + omega + simp only [BitVec.toNat_and, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hF] + rw [Nat.and_comm, show 255 % 2 ^ 256 = 2 ^ 8 - 1 from rfl, Nat.and_two_pow_sub_one_eq_mod] + omega + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- EthLib runs solar's bytecode on add(x) from any storage, when x is clean and v + x fits in +uint8, to expectedAt σ x. -/ +theorem target_run_ok (x : U256) (σ : List (Nat × Nat)) (hx : x.toNat < 256) + (hc : slotValue σ 0 % 256 + x.toNat < 256) : + Target.run Corpus.C4.code (callAt addSelector [x] σ) = some (expectedAt σ x) := by + simp only [expectedAt, Verify.C4.model_ok _ _ hx hc, Verify.observe] + refine run_of_postS_at Corpus.C4.code addSelector [x] σ _ rfl (fun h => by cases h) ?_ + intro msg hv hd hstat htgt + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + simp only [addSelector, Bytecode.C4.Main.addSelector] at hd + repeat wide_one_at [Corpus.C4.code, Bytecode.C4.Main.runtimeNat, Bytecode.C4.Main.runtimeSize, + Bytecode.C4.Main.addSelector] [hd, hv] hfork hstat htgt + -- Name the slot-0 word SLOAD read, which the steps above left as slotValue's fold over σ. + obtain ⟨S, hS⟩ : ∃ S, slotValue σ 0 = S := ⟨_, rfl⟩ + have hSlt : S < 2 ^ 256 := hS ▸ slotValue_lt σ 0 + rw [hS] at hc + simp only [slotValue, Nat.reduceMod, Nat.reducePow] at hS + simp only [hS] + have hlow := ofNat_and_255 S hSlt + simp only [hlow] + repeat wide_one_at [Corpus.C4.code, Bytecode.C4.Main.runtimeNat, Bytecode.C4.Main.runtimeSize, + Bytecode.C4.Main.addSelector] [hd, hv] hfork hstat htgt + have hW := tgt_slot_word S x hSlt hx hc + have hL := tgt_low_byte S x hSlt hc + simp only [hW, hL] + refine return_postS ?lt ?op ?gas ?succ ?out rfl ?store + case lt => evm_code [Corpus.C4.code, Bytecode.C4.Main.runtimeNat, Bytecode.C4.Main.runtimeSize] + case op => evm_code [Corpus.C4.code, Bytecode.C4.Main.runtimeNat, Bytecode.C4.Main.runtimeSize] + case gas => wide_mem; omega + case succ => rfl + case out => + wide_mem + rw [toList_wordBytes, BitVec.toNat_ofNat, Nat.mod_eq_of_lt (by omega)] + rfl + case store => + intro slot + simp only [htgt, getStorage_writeOf_of, getStorage_recordStorageRead, getStorage_preState_ofNat, + storage_callAt, storageKey_eq_toBeBytes, BitVec.toNat_ofNat] + simp only [Nat.reducePow, Nat.zero_mod, true_and] + by_cases h : slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 + · simp only [h, ↓reduceIte, BitVec.toNat_ofNat, Nat.reducePow] + · simp only [h, ↓reduceIte, BitVec.toNat_ofNat] + exact Nat.mod_eq_of_lt (slotValue_lt σ slot) + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- The same when v + x overflows uint8: a Panic(0x11) revert. -/ +theorem target_run_panic (x : U256) (σ : List (Nat × Nat)) (hx : x.toNat < 256) + (hc : ¬ slotValue σ 0 % 256 + x.toNat < 256) : + Target.run Corpus.C4.code (callAt addSelector [x] σ) = some (expectedAt σ x) := by + simp only [expectedAt, Verify.C4.model_panic _ _ hx hc, Verify.observe] + refine run_of_postS_at Corpus.C4.code addSelector [x] σ _ rfl (fun _ _ => rfl) ?_ + intro msg hv hd hstat htgt + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + simp only [addSelector, Bytecode.C4.Main.addSelector] at hd + repeat wide_one_at [Corpus.C4.code, Bytecode.C4.Main.runtimeNat, Bytecode.C4.Main.runtimeSize, + Bytecode.C4.Main.addSelector] [hd, hv] hfork hstat htgt + -- Name the slot-0 word SLOAD read, which the steps above left as slotValue's fold over σ. + obtain ⟨S, hS⟩ : ∃ S, slotValue σ 0 = S := ⟨_, rfl⟩ + have hSlt : S < 2 ^ 256 := hS ▸ slotValue_lt σ 0 + rw [hS] at hc + simp only [slotValue, Nat.reduceMod, Nat.reducePow] at hS + simp only [hS] + have hlow := ofNat_and_255 S hSlt + simp only [hlow] + repeat wide_one_at [Corpus.C4.code, Bytecode.C4.Main.runtimeNat, Bytecode.C4.Main.runtimeSize, + Bytecode.C4.Main.addSelector] [hd, hv] hfork hstat htgt + refine revert_postS (by decide) ?lt ?op ?gas ?succ ?out rfl + case lt => evm_code [Corpus.C4.code, Bytecode.C4.Main.runtimeNat, Bytecode.C4.Main.runtimeSize] + case op => evm_code [Corpus.C4.code, Bytecode.C4.Main.runtimeNat, Bytecode.C4.Main.runtimeSize] + case gas => wide_mem; omega + case succ => rfl + case out => + wide_mem + decide +kernel + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- The same on a dirty word: a revert with empty data, before the bytecode reads storage. -/ +theorem target_run_dirty (x : U256) (σ : List (Nat × Nat)) (hx : ¬ x.toNat < 256) : + Target.run Corpus.C4.code (callAt addSelector [x] σ) = some (expectedAt σ x) := by + simp only [expectedAt, Verify.C4.model_dirty _ _ hx, Verify.observe] + refine run_of_postS_at Corpus.C4.code addSelector [x] σ _ rfl (fun _ _ => rfl) ?_ + intro msg hv hd hstat htgt + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + simp only [addSelector, Bytecode.C4.Main.addSelector] at hd + repeat wide_one_at [Corpus.C4.code, Bytecode.C4.Main.runtimeNat, Bytecode.C4.Main.runtimeSize, + Bytecode.C4.Main.addSelector] [hd, hv] hfork hstat htgt + +/-- EthLib runs solar's bytecode on every call of add(x) from any storage σ to expectedAt σ x. -/ +theorem target_run_at (x : U256) (σ : List (Nat × Nat)) : + Target.run Corpus.C4.code (callAt addSelector [x] σ) = some (expectedAt σ x) := by + by_cases hx : x.toNat < 256 + · by_cases hc : slotValue σ 0 % 256 + x.toNat < 256 + · exact target_run_ok x σ hx hc + · exact target_run_panic x σ hx hc + · exact target_run_dirty x σ hx + +end TargetAt + +/-- **The assembly-side stage of c4 from any storage**: solar's first lowered MIR to its +bytecode on EthLib, on every call of add with no value from any storage that writes slot 0, +under every oracle. -/ +theorem mir_assemblyAt (o : SolarTV.Machine.Oracle) : + Stage (SolarTV.MIR.Lowered.moduleSem o) ethLib SolarTV.Export.Main.stage0 Corpus.C4.code + Verify.C4.scopeAt := by + intro call hs obs hrun + obtain ⟨x, σ, -, rfl⟩ := scopeAt_callAt hs + rw [mir_run_at o x σ] at hrun + cases hrun + exact target_run_at x σ + +/-- The assembly stage from any storage, for any program that agrees with SolidCore on scopeAt +(chain): each observable of the program is SolidCore's, which is the bytecode's. -/ +theorem assemblyAt_of_chain {A : Sem} {p : A.Prog} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : Corpus.C4.contract? = .ok c) (chain : Stage (solidCore Corpus.C4.fuel) A c p Verify.C4.scopeAt) : + Stage A ethLib p Corpus.C4.code Verify.C4.scopeAt := by + intro call hs obs hrun + obtain ⟨x, σ, hσ, rfl⟩ := scopeAt_callAt hs + have := chain _ hs _ (source_run_at hc x σ hσ) + rw [hrun] at this + cases this + exact target_run_at x σ + +/-- **c4 from any storage.** Verify.C4's specification from any storage that writes slot 0 +(postAt) holds of solar's bytecode under EthLib, through the source stage from any storage +(loweringAt) and the assembly-side stage (mir_assemblyAt). -/ +theorem certifiedAt (o : SolarTV.Machine.Oracle) : + Satisfies ethLib Corpus.C4.code Verify.C4.scopeAt Verify.C4.pre Verify.C4.postAt := by + obtain ⟨c, hc, hspec⟩ := Verify.C4.satisfiesAt + exact SolidCore.Refinement.Satisfies.of_stage hspec ((loweringAt o hc).trans (mir_assemblyAt o)) + +/-- **c4 from any storage through solar's stages.** The same through a backend stage from +stage0 to an EVM IR program evm on scopeAt: bytecode_of_stages with loweringAt, the backend +and the assembly stage from evm (assemblyAt_of_chain). -/ +theorem certifiedAt_of_backend (o : SolarTV.Machine.Oracle) {evmirSem : Sem} {evm : evmirSem.Prog} + (backend : Stage (SolarTV.MIR.Lowered.moduleSem o) evmirSem SolarTV.Export.Main.stage0 evm + Verify.C4.scopeAt) : + Satisfies ethLib Corpus.C4.code Verify.C4.scopeAt Verify.C4.pre Verify.C4.postAt := by + obtain ⟨c, hc, hspec⟩ := Verify.C4.satisfiesAt + have low := loweringAt o hc + exact bytecode_of_stages hspec low backend (assemblyAt_of_chain hc (low.trans backend)) + +/-! ### Every storage, on the bytecode -/ + +/-- The calls of add on any argument word, with no value, from every storage, whether or not +it writes slot 0. -/ +def scopeAll : Call → Prop := fun call => ∃ σ, fullScope Corpus.C4.fns σ call + +theorem scopeAll_callAt {call : Call} (h : scopeAll call) : + ∃ (x : U256) (σ : List (Nat × Nat)), call = callAt addSelector [x] σ := by + obtain ⟨σ, fn, hfn, args, hlen, hlt, rfl⟩ := h + simp only [Corpus.C4.fns, List.mem_singleton] at hfn + subst hfn + match args, hlen with + | [a], _ => + refine ⟨BitVec.ofNat 256 a, σ, ?_⟩ + have ha : a % 2 ^ 256 = a := Nat.mod_eq_of_lt (hlt a (by simp)) + simp only [callAt, List.map_cons, List.map_nil, BitVec.toNat_ofNat, ha] + +/-- The verification conditions of add from every storage: Verify.C4.vcsAt, whose proof does not +use the slot-0 write. -/ +theorem vcsAll : ∀ call, scopeAll call → Verify.C4.pre call → + Verify.vc Verify.C4.model (Verify.argWords 1) Verify.C4.postAt call := by + rintro call ⟨σ, hs⟩ hp + refine Verify.vcs_of_fullScope (fns := Corpus.C4.fns) (s := σ) (n := 1) (by simp [Corpus.C4.fns]) + ?_ call hs hp + intro fn hfn call args hcall hw hlen hargs hinit _ + subst hcall + match args, hlen with + | [x], _ => + have hx : x < 2 ^ 256 := hargs x (by simp) + have hs0 := slotValue_lt σ 0 + rw [Verify.wp_eq] + simp only [Verify.C4.postAt, hw, List.getD_cons_zero] + by_cases h1 : x < 256 + · by_cases h2 : slotValue σ 0 % 256 + x < 256 + · rw [Verify.C4.model_ok x _ h1 h2] + simp only [Nat.reducePow, h1, h2, ↓reduceIte, true_and] + refine ⟨fun slot => ?_, trivial⟩ + split + · exact Nat.mod_eq_of_lt (by + have := Nat.xor_lt_two_pow (n := 8) (x := slotValue σ 0 / 256 % 256) (y := x) + (by omega) (by omega) + omega) + · rfl + · rw [Verify.C4.model_panic x _ h1 h2] + simp [h1, h2] + · rw [Verify.C4.model_dirty x _ h1] + simp [h1] + +/-- **solar's bytecode for c4 meets postAt from every storage**, slot 0 written or not, under +EthLib: target_run_at runs it to the model's outcome from the call's storage, which vcsAll +shows meets postAt. SolidCore needs slot 0 written (scopeAt), the bytecode does not. -/ +theorem bytecode_satisfiesAll : + Satisfies ethLib Corpus.C4.code scopeAll Verify.C4.pre Verify.C4.postAt := by + intro call hs hp + have h := vcsAll call hs hp + obtain ⟨x, σ, rfl⟩ := scopeAll_callAt hs + refine ⟨_, target_run_at x σ, ?_⟩ + have hw : Verify.argWords 1 (callAt addSelector [x] σ) = [x.toNat] := by + obtain ⟨_, fn, hfn, args, hlen, hlt, hcall⟩ := hs + have := Verify.argWords_calldata addSelector [x.toNat] (by simp [x.isLt]) 0 σ + simpa [callAt] using this + have hi : Verify.initStorage (callAt addSelector [x] σ) = slotValue σ := rfl + simp only [Verify.vc, Verify.wp_eq, hw, hi] at h + show Verify.C4.postAt _ (Verify.observe (slotValue σ) (Verify.C4.model [x.toNat] (slotValue σ))) + revert h + rcases Verify.C4.model [x.toNat] (slotValue σ) with e | ⟨out, s'⟩ <;> exact id + +/-- info: 'SolidCore.Refinement.Solar.C4.mir_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms mir_run + +/-- info: 'SolidCore.Refinement.Solar.C4.lowering' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms lowering + +/-- info: 'SolidCore.Refinement.Solar.C4.loweringAt_of_runs' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loweringAt_of_runs + +/-- info: 'SolidCore.Refinement.Solar.C4.slot_word_at' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms slot_word_at + +/-- info: 'SolidCore.Refinement.Solar.C4.mir_run_at' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms mir_run_at + +/-- info: 'SolidCore.Refinement.Solar.C4.loweringAt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loweringAt + +/-- info: 'SolidCore.Refinement.Solar.C4.certified_of_backend' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified_of_backend + +/-- info: 'SolidCore.Refinement.Solar.C4.target_run_at' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms target_run_at + +/-- info: 'SolidCore.Refinement.Solar.C4.mir_assemblyAt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms mir_assemblyAt + +/-- info: 'SolidCore.Refinement.Solar.C4.certifiedAt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedAt + +/-- info: 'SolidCore.Refinement.Solar.C4.certifiedAt_of_backend' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedAt_of_backend + +/-- info: 'SolidCore.Refinement.Solar.C4.bytecode_satisfiesAll' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms bytecode_satisfiesAll + +end SolidCore.Refinement.Solar.C4 diff --git a/SolidCore/Refinement/Solar/C4/LoweringGeneric.lean b/SolidCore/Refinement/Solar/C4/LoweringGeneric.lean new file mode 100644 index 00000000..c68d4a55 --- /dev/null +++ b/SolidCore/Refinement/Solar/C4/LoweringGeneric.lean @@ -0,0 +1,171 @@ +import SolidCore.Refinement.Generic.Value +import Verify.C4 +import c4.gen.Main.Stage0 + +/-! +# c4's source stage, from the generic source stage + +The corpus contract c4 (scripts/refinement/corpus/c4.sol), + + contract Main { uint8 v; uint8 w = 7; + function add(uint8 x) external returns (uint8) { v += x; w ^= x; return v; } } + +has a narrow parameter that solar's lower-abi cleans (a dirty word reverts), a checked `uint8` +addition, two `uint8` fields packed in slot 0 (`v` at byte 0, `w` at byte 1) written by +read-modify-write, a compound `^=`, and a constructor that leaves slot 0 = `7 * 256`. +`Solar.C4.lowering` proves its source stage from the deployed storage by symbolic execution of +this one module. The generic source stage gives it from one evaluation by the kernel, and from +any storage that writes slot 0 too: + +* `check_stage0`: `Generic.check` accepts solar's first lowered MIR module + `SolarTV.Export.Main.stage0` (c4.gen.Main.Stage0, solar's export) for `Verify.C4.coreLit` and + `Corpus.C4.fns` (`decide +kernel`): the erased tree of `add` (the argument check, `v += x` + with `uint256`'s overflow check and `uint8`'s cleanup, `w ^= x`, the packed reads and writes + of slot 0) and the symbolic run of the module agree in canonical form. +* `lowering_generic`: the stage on `Verify.C4.scope` (every call of `add` on any argument word, + no value, from the deployed storage), under every oracle: the statement of + `Solar.C4.lowering`, from `Generic.stageDeployed`. +* `loweringAt_generic`: the stage on `Verify.C4.scopeAt` (from any storage that writes slot 0), + from `Generic.stageAt`, with no hypothesis on the MIR run: `Solar.C4.loweringAt_of_runs`'s + conclusion for solar's stage0. +* `check_rejects_bad`: the check rejects `badStage0`, stage0 with `w ^= x` compiled as + `w |= x`. +* `checkValue_stage0`: `Generic.checkValue` accepts stage0 (`decide +kernel`): `add` is not + payable and stage0 reverts with empty output on a call of it with a value other than 0, so + `lowering_value` and `loweringAt_value` are the two stages above at every value below + `2 ^ 256` (`Generic.stageDeployedValue`, `Generic.stageAtValue`). + +The names of solar's stages (`SolarTV.Export.Main`) are those of w1's and w4's too, so this +module is built by `lake build SolidCoreSolarC4`, outside the library root. + +No sorry, native_decide or bv_decide: `decide +kernel` is the kernel's evaluation, and the +theorems depend on propext, Classical.choice and Quot.sound only (pinned below). +-/ + +namespace SolidCore.Refinement.Solar.C4 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +/-- The interpreter fuel of the symbolic run of the module: blocks along each path. -/ +def mirFuel : Nat := 16 + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for c4's `add`. -/ +theorem check_stage0 : + Generic.check Corpus.C4.fuel mirFuel Verify.C4.coreLit SolarTV.Export.Main.stage0 + Corpus.C4.fns = true := by + decide +kernel + +/-- An instruction of stage0 with `xor` compiled as `or`. -/ +def mutateInst : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .pure dst .xor args => .pure dst .or args + | i => i + +/-- stage0 with `w ^= x` compiled as `w |= x`. -/ +def badStage0 : SolarTV.MIR.Lowered.Module := + { SolarTV.Export.Main.stage0 with + functions := SolarTV.Export.Main.stage0.functions.map fun f => + { f with blocks := f.blocks.map fun b => { b with insts := b.insts.map mutateInst } } } + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check rejects stage0 with `w |= x` for `w ^= x`. -/ +theorem check_rejects_bad : + Generic.check Corpus.C4.fuel mirFuel Verify.C4.coreLit badStage0 Corpus.C4.fns = false := by + decide +kernel + +/-- c4's checked contract has the core `Verify.C4.coreLit`, and its constructor leaves exactly +`Verify.C4.deployed`. -/ +theorem deployed_of {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : Corpus.C4.contract? = .ok c) : + c.core = Verify.C4.coreLit ∧ ∃ d, Wide.DeployedAt Corpus.C4.fuel c d Verify.C4.deployed := by + obtain ⟨hk, _, hdep⟩ := Verify.C4.shape_of hc + exact ⟨hk, Wide.deployedAt_of hdep⟩ + +/-- **The source stage of c4 from the deployed storage, from the generic source stage**: the +statement of `Solar.C4.lowering`. -/ +theorem lowering_generic (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : Corpus.C4.contract? = .ok c) : + Stage (solidCore Corpus.C4.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 Verify.C4.scope := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact Generic.stageDeployed o hd (by rw [hk]; exact check_stage0) + +/-- **The source stage of c4 from any storage that writes slot 0, from the generic source +stage**: every call of `add` on any argument word, no value, under every oracle. -/ +theorem loweringAt_generic (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : Corpus.C4.contract? = .ok c) : + Stage (solidCore Corpus.C4.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 Verify.C4.scopeAt := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + refine SolarTV.Stage.mono (Generic.stageAt o hd (by rw [hk]; exact check_stage0)) ?_ + rintro call ⟨σ, ⟨kv, hkv, h0⟩, hs⟩ + refine ⟨σ, ?_, hs⟩ + intro kv' hkv' + simp only [Verify.C4.deployed, List.mem_singleton] at hkv' + subst hkv' + exact ⟨kv, hkv, h0⟩ + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: `add` is not payable, and stage0 reverts with empty output on a call +of it with a value other than 0. -/ +theorem checkValue_stage0 : + Generic.checkValue mirFuel Verify.C4.coreLit SolarTV.Export.Main.stage0 Corpus.C4.fns = + true := by + decide +kernel + +/-- **The source stage of c4 from the deployed storage, at every value**: every call of `add` on +any argument word, with any value below `2 ^ 256`, under every oracle. -/ +theorem lowering_value (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : Corpus.C4.contract? = .ok c) : + Stage (solidCore Corpus.C4.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 + (fun call => ∃ v, Generic.fullScopeValue Corpus.C4.fns Verify.C4.deployed v call) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact Generic.stageDeployedValue o hd (by rw [hk]; exact check_stage0) + (by rw [hk]; exact checkValue_stage0) + +/-- The calls of `add` from any storage that writes slot 0, with any value. -/ +def scopeAtValue : Call → Prop := fun call => + ∃ σ v, (∃ kv ∈ σ, kv.1 % 2 ^ 256 = 0) ∧ Generic.fullScopeValue Corpus.C4.fns σ v call + +/-- **The source stage of c4 from any storage that writes slot 0, at every value**: every call +of `add` on any argument word, with any value below `2 ^ 256`, under every oracle. -/ +theorem loweringAt_value (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : Corpus.C4.contract? = .ok c) : + Stage (solidCore Corpus.C4.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 scopeAtValue := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + refine SolarTV.Stage.mono (Generic.stageAtValue o hd (by rw [hk]; exact check_stage0) + (by rw [hk]; exact checkValue_stage0)) ?_ + rintro call ⟨σ, v, ⟨kv, hkv, h0⟩, hs⟩ + refine ⟨σ, v, ?_, hs⟩ + intro kv' hkv' + simp only [Verify.C4.deployed, List.mem_singleton] at hkv' + subst hkv' + exact ⟨kv, hkv, h0⟩ + +/-- info: 'SolidCore.Refinement.Solar.C4.check_stage0' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms check_stage0 + +/-- info: 'SolidCore.Refinement.Solar.C4.lowering_generic' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms lowering_generic + +/-- info: 'SolidCore.Refinement.Solar.C4.loweringAt_generic' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loweringAt_generic + +/-- info: 'SolidCore.Refinement.Solar.C4.checkValue_stage0' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms checkValue_stage0 + +/-- info: 'SolidCore.Refinement.Solar.C4.lowering_value' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms lowering_value + +/-- info: 'SolidCore.Refinement.Solar.C4.loweringAt_value' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loweringAt_value + +end SolidCore.Refinement.Solar.C4 diff --git a/SolidCore/Refinement/Solar/Counter/AnyStorage.lean b/SolidCore/Refinement/Solar/Counter/AnyStorage.lean new file mode 100644 index 00000000..692241f9 --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/AnyStorage.lean @@ -0,0 +1,509 @@ +import SolidCore.Refinement.Solar.Counter.Assembly +import SolidCore.Refinement.Spec + +/-! +NOTE: ckpt3's SpecAt.lean, LoweringAt.lean and AssemblyAt.lean prove the same theorems under +the same names, which Counter.Milestone imports, so this module imports only what the +deployed-storage milestone needs and is not imported beside them. + +# The counter milestone from any storage + +`certified` (Milestone.lean) proves Counter's `inc` on calls from the deployed, empty storage, +where `x = 0`. A sequence of calls starts each call from the storage the previous one left, so +this module proves every stage of solar's pipeline, and the specification, from any storage `σ`: +`scopeAt` is every call of `inc` on any argument word below `2 ^ 256`, with no value, from any +storage. There the overflow branch is reached, and `expectedAt σ d` is what a call shows: when +`x + d` fits, with `x` slot 0 of `σ`, success with slot 0 holding `x + d` and every other slot +of `σ` kept; otherwise a revert with `Panic(0x11)` and `σ` kept. + +* Specification: `vcsAt` is `vcs` for each `σ` (Loom's weakest preconditions of `model` against + the existing `post`, which is stated from any storage), and `run_inc_at` runs SolidCore from + `σ` written over the deployed storage (`run_eq_at`, `getD_storage`), giving `implementsAt`, + `specAt` and `satisfiesAt`. +* Source stage: `loweringAt`, from `source_run_at` and `mir_run_at` (symbolic execution of + `stage0` with slot 0 read from `σ` and both branches of the overflow check). +* Backend: `SolarTV.Milestone.Counter.counter_mir_to_evmir`, already on every call. +* Assembly stage: `stageAt`, from `evmir_run_at` and `target_run_at`: EthLib's run of the + bytecode from `σ` (`run_of_postS_at`), SLOAD reading `σ`'s slot 0 + (`getStorage_preState_word`), and the final storage read through the write + (`getStorage_writeOf_any`) on the success path, and REVERT with `Panic(0x11)` on the overflow + path (`target_run_ok`, `target_run_overflow`). +* `certifiedAt`: the bytecode meets `post` on every call of `scopeAt`, through every stage. + +Nothing here uses `native_decide` or `bv_decide`. +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source SolidCore.Verify + +/-- Every call of `inc` on any argument word, with no value, from any storage. -/ +def scopeAt : Call → Prop := fun call => ∃ σ, fullScope fns σ call + +/-- What a call of `inc(d)` from the storage `σ` shows: with `x` slot 0 of `σ`, success with +slot 0 holding `x + d` and every other slot kept when `x + d` fits in 256 bits, and otherwise a +revert with `Panic(0x11)` and `σ` kept. -/ +def expectedAt (σ : List (Nat × Nat)) (d : U256) : Observable := + if slotValue σ 0 + d.toNat < 2 ^ 256 then + { success := true, output := [], logs := [], + storage := fun slot => if slot % 2 ^ 256 = 0 then slotValue σ 0 + d.toNat else slotValue σ slot } + else { success := false, output := panic 0x11, logs := [], storage := slotValue σ } + +theorem scopeAt_callOf {call : Call} (h : scopeAt call) : + ∃ d : U256, ∃ σ, call = { callOf incSelector [d] with storage := σ } := by + obtain ⟨σ, fn, hfn, args, hlen, hlt, rfl⟩ := h + simp only [fns, List.mem_singleton] at hfn + subst hfn + match args, hlen with + | [a], _ => + refine ⟨BitVec.ofNat 256 a, σ, ?_⟩ + have ha' : a % 2 ^ 256 = a := Nat.mod_eq_of_lt (hlt a (by simp)) + simp only [callOf, List.map_cons, List.map_nil, BitVec.toNat_ofNat, ha'] + +/-- `model` from the storage `σ` shows `expectedAt σ d`. -/ +theorem observe_model_at (d : U256) (σ : List (Nat × Nat)) : + observe (slotValue σ) (model [d.toNat] (slotValue σ)) = expectedAt σ d := by + unfold model expectedAt + by_cases h : slotValue σ 0 + d.toNat < 2 ^ 256 + · simp only [sload, sstore, bind, StateT.bind, pure, StateT.pure, Except.bind, Except.pure, + List.getD_cons_zero, h, ↓reduceIte, observe, Nat.zero_mod, Nat.mod_eq_of_lt h] + · simp only [sload, bind, StateT.bind, Except.bind, List.getD_cons_zero, h, ↓reduceIte, + observe, revert] + +/-- The verification conditions of `inc` from any storage, by Loom's weakest preconditions. -/ +theorem vcsAt : ∀ call, scopeAt call → pre call → vc model (argWords 1) post call := by + rintro call ⟨σ, hs⟩ hp + refine vcs_of_fullScope (s := σ) (by simp [fns]) ?_ call hs hp + intro fn hfn call args hcall hw hlen hargs hinit hpre + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst fn hcall + rcases args with _ | ⟨a, _ | _⟩ <;> simp at hlen + have ha : a < 2 ^ 256 := hargs a (by simp) + simp only [model, post, hw, wp_bind, wp_pure, wp_sload, wp_sstore, wp_revert, wp_ite, + List.getD_cons_zero] + by_cases h : slotValue σ 0 + a < 2 ^ 256 + · simp only [h, ↓reduceIte, Nat.zero_mod, Nat.mod_eq_of_lt h] + simp + · simp only [h, ↓reduceIte] + simp + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs `inc` on any argument word from any storage `σ` as `model` does. -/ +theorem run_inc_at {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d []) (w : U256) (σ : List (Nat × Nat)) : + Source.run fuel c (callAt incSelector [w] σ) = + some (Verify.observe (slotValue σ) (model [w.toNat] (slotValue σ))) := by + rw [run_eq_at hd] + have hev := hd.events + have h0 : ∀ q : Nat, d.storage[q]? = none := fun q => hd.getElem?_eq_none (by simp) + have hget := getD_storage h0 σ + generalize σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage = m at hget + simp only [hcore, List.map_cons, List.map_nil] + have hx0 : m[0]?.getD 0 = slotValue σ 0 := by simpa using hget 0 + have hN : (2 : Nat) ^ 256 = + 115792089237316195423570985008687907853269984665640564039457584007913129639936 := by + norm_num + have hlt := slotValue_lt σ 0 + have hw := w.isLt + rw [hN] at hlt hw + wide_symex [coreLit, fuel, ctxOf, hcore, incSelector, get?_insert] + case pos => + rename_i hp + have hnot : ¬ slotValue σ 0 + w.toNat < 2 ^ 256 := by + split at hp + · rename_i v heq + have hv : v = slotValue σ 0 := by simpa [heq] using hx0 + rw [hv] at hp + omega + · rename_i heq + have hv : slotValue σ 0 = 0 := by simpa [heq] using hx0.symm + rw [hv] + omega + simp only [model, sload, bind, StateT.bind, Except.bind, List.getD_cons_zero, hnot, ↓reduceIte, + revert] + simp [Source.observe, Verify.observe, callAt] + rfl + case h_1 => + rename_i hp _ v heq + have hv : v = slotValue σ 0 := by simpa [heq] using hx0 + subst hv + simp only [heq] at hp + have hyes : slotValue σ 0 + w.toNat < 2 ^ 256 := by omega + have hyes' : slotValue σ 0 + w.toNat < 115792089237316195423570985008687907853269984665640564039457584007913129639936 := by omega + simp only [model, sload, sstore, bind, StateT.bind, pure, StateT.pure, Except.bind, + Except.pure, List.getD_cons_zero, hyes, ↓reduceIte, Verify.observe, Nat.mod_eq_of_lt hyes] + simp [Source.observe, State.logEntries, State.loadSlot, StorageMap.lookup?] + funext slot + have hs := hget slot + rw [hN] at hs + simp only [Std.HashMap.getElem?_insert, Shared.norm, Shared.wordModulus, beq_iff_eq, + EvmYul.UInt256.size] + by_cases h : slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 + · simp [h, Nat.mod_eq_of_lt hyes'] + · have h' : ¬ 0 = slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 := fun e => h e.symm + simp only [h, h', ↓reduceIte] + rw [← hs] + cases m[slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936]? <;> rfl + case h_2 => + rename_i hp _ heq + have hv : slotValue σ 0 = 0 := by simpa [heq] using hx0.symm + have hyes : slotValue σ 0 + w.toNat < 2 ^ 256 := by rw [hv, hN]; omega + simp only [model, sload, sstore, bind, StateT.bind, pure, StateT.pure, Except.bind, + Except.pure, List.getD_cons_zero, hyes, ↓reduceIte, Verify.observe, Nat.mod_eq_of_lt hyes] + simp [Source.observe, State.logEntries, State.loadSlot, StorageMap.lookup?] + funext slot + have hs := hget slot + rw [hN] at hs + simp only [Std.HashMap.getElem?_insert, Shared.norm, Shared.wordModulus, beq_iff_eq, + EvmYul.UInt256.size] + by_cases h : slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 + · simp [h, hv] + · have h' : ¬ 0 = slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 := fun e => h e.symm + simp only [h, h', ↓reduceIte] + rw [← hs] + cases m[slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936]? <;> rfl + +section Lowering + +open SolarTV SolarTV.Machine SolarTV.Milestone.W1 + +/-- SolarTV's lowered MIR runs Counter's first lowered MIR module, on every call whose call data +reads as `inc(d)` with no value, to `expectedAt` of the call's storage. -/ +theorem mir_run_of_at (o : Oracle) (call : Call) (d : EvmRules.Word) (hv : call.callvalue = 0) + (hsize : call.calldata.size = 36) (h0 : EvmRules.Evm.shr 224 (calldataWord call 0) = 2166751455) + (h4 : calldataWord call 4 = d) : + (MIR.Lowered.Module.run o SolarTV.Export.Counter.stage0 call 9).map + (fun r => observe call r.2 r.1) = some (expectedAt call.storage d) := by + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte]) + have hx : ((State.initial call).storage 0).toNat = slotValue call.storage 0 := by + simp only [State.initial, BitVec.toNat_ofNat] + exact slotValue_mod_mod call.storage 0 + by_cases hof : slotValue call.storage 0 + d.toNat < 2 ^ 256 + all_goals + simp only [add_lt_self_iff_comm, hx, hof, not_true_eq_false, + not_false_eq_true, ↓reduceIte] + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte]) + · simp only [Machine.observe, expectedAt, hof, ↓reduceIte, Option.some.injEq, + Observable.mk.injEq, true_and] + refine ⟨rfl, ?_⟩ + funext slot + simp only [storageOf, update] + split + · rename_i e + have h : slot % 2 ^ 256 = 0 := by simpa using congrArg BitVec.toNat e + simp only [h, ↓reduceIte, EvmRules.Evm.add, BitVec.toNat_add, hx] + rw [Nat.add_comm (BitVec.toNat d)] + exact Nat.mod_eq_of_lt hof + · rename_i e + have h : ¬ slot % 2 ^ 256 = 0 := + fun h => e (BitVec.eq_of_toNat_eq (by simpa using h)) + simp only [h, ↓reduceIte, State.initial, BitVec.toNat_ofNat] + exact slotValue_mod_mod call.storage slot + · simp only [Machine.observe, expectedAt, hof, ↓reduceIte, Option.some.injEq, + Observable.mk.injEq] + refine ⟨trivial, ?_, trivial, trivial⟩ + try simp only [State.initial] + decide + +end Lowering + +section Target + +open EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts EthLib.Execution.State +open SolidCore.Refinement.Evm.Symex SolidCore.Refinement.Evm.Logic SolidCore.Refinement.Evm + +/-- `run_of_postS` from any storage `σ`: when the frame of every message of the call stops as +`PostS X` says from the call's state before it, `Target.run` of the call is `X`, when `X` +shows no logs and keeps `σ` when it fails. -/ +theorem run_of_postS_at (code : ByteArray) (s : Nat) (ws : List U256) (σ : List (Nat × Nat)) + (X : Observable) (hlogs : X.logs = []) + (hfail : X.success = false → ∀ slot, X.storage slot = slotValue σ slot) + (h : ∀ msg : Message .fusaka, msg.value = 0 → msg.data = cdOf (selectorOf s) ws → + msg.isStatic = false → msg.currentTarget = Target.address selfAddress → + Spec .fusaka (At code msg 0 [] .empty 10000000 + (Target.preState code { callOf s ws with storage := σ }) Substate.empty .empty) + (PostS X Substate.empty)) : + Target.run code { callOf s ws with storage := σ } = some X := by + have hd : Abi.calldata s (ws.map BitVec.toNat) = cdOf (selectorOf s) ws := by + rw [calldata_eq_cdOf s _ (by simpa using fun a _ => a.isLt)] + simp [List.map_map, Function.comp_def] + let c : Call := { callOf s ws with storage := σ } + obtain ⟨evm, hr, herr, hout, hst⟩ := processMessage_postS (Target.message code c) rfl rfl + (precompileAddress_message code c) X (Target.preState code c) Substate.empty + (h _ rfl (by simp [Target.message, c, callOf, hd]) rfl rfl) + show Target.run code c = some X + simp only [Target.run, hr] + have hsucc : evm.1.error.isNone = X.success := by + rw [herr]; cases hX : X.success <;> simp [errorOf, hX] + congr 1 + cases X with + | mk success output logs storage => + simp only at hsucc hout hlogs hfail hst ⊢ + subst hlogs + rw [Observable.mk.injEq] + refine ⟨hsucc, hout, ?_, ?_⟩ + · rw [hsucc] + cases hs : success + · rfl + · simp [(hst hs).1, Substate.empty] + · funext slot + rw [hsucc] + cases hs : success + · simp [c, hfail hs slot] + · simp only [ite_true] + exact (hst hs).2 slot + +/-- A read of the callee's storage before the call, at the key of a word, is the call's slot. -/ +theorem getStorage_preState_word (code : ByteArray) (c : Call) (key : U256) : + (Target.preState code c).getStorage (Target.address selfAddress) (U256.toBeBytes key) = + BitVec.ofNat 256 (slotValue c.storage key.toNat) := by + have hk : U256.toBeBytes key = Target.storageKey key.toNat := + ((storageKey_eq_toBeBytes key.toNat key).2 (Nat.mod_eq_of_lt key.isLt)).symm + rw [hk] + apply BitVec.eq_of_toNat_eq + rw [getStorage_preState, BitVec.toNat_ofNat, Nat.mod_eq_of_lt (slotValue_lt _ _)] + +/-- After a write of `v` at `k` of `a`, the written slot holds `v` and every other slot is +as before. -/ +theorem getStorage_writeOf_any (tx : TransactionState) (a : Address) (k : Bytes32) (v : U256) + (a' : Address) (k' : Bytes32) : + (writeOf tx a k v).getStorage a' k' = if a' = a ∧ k' = k then v else tx.getStorage a' k' := by + simp only [writeOf, TransactionState.getStorage, TransactionState.recordAccountRead, StorageMap.slot] + by_cases ha : a' = a + · subst ha + by_cases hk : k' = k + · subst hk; simp + · simp [hk, Std.ExtTreeMap.getElem?_insert] + simp only [show ¬ (k = k') from fun e => hk e.symm, ↓reduceIte] + have : (Std.ExtTreeMap.getD tx.storageWrites a' ∅)[k']? = + tx.storageWrites[a']?.bind fun slots => slots[k']? := by + rw [Std.ExtTreeMap.getD_eq_getD_getElem?] + cases tx.storageWrites[a']? <;> simp + rw [this] + rfl + · simp [ha, Std.ExtTreeMap.getElem?_insert] + simp only [show ¬ (a = a') from fun e => ha e.symm, ↓reduceIte] + rfl + +open Lean.Parser.Tactic in +/-- Steps one opcode of a path of `inc` from any storage: SLOAD of slot 0 (a cold key, read as +`σ`'s slot 0), SSTORE after it, and every other opcode as `wide_one_s`. -/ +syntax "counter_at_one" " [" simpLemma,* "]" " [" simpLemma,* "]" ident ident ident : tactic + +macro_rules + | `(tactic| counter_at_one [$ls,*] [$ns,*] $hf $hstat $htgt) => `(tactic| ((try unfold Spec) <;> first + | (refine' Triple.seq (sload (cold := true) (by decide) ?lt ?op ?cold ?gas) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case cold => simp [Substate.empty] + case gas => simp only [ite_true]; omega) <;> + (try simp only [$htgt:ident, getStorage_preState_word, Bool.true_eq, ↓reduceIte, + Nat.reduceSub]) <;> evm_tidy + | (refine' Triple.seq (sstore (by decide) (by decide) ?lt ?op $hstat rfl ?stip ?gas + (setStorage_ok _ _ ?acc)) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case stip => simp only [CALL_STIPEND]; omega + case gas => exact Nat.le_trans (sstoreCost_le _ _ _ _) (by omega) + case acc => simp only [getAccountOptional_recordStorageRead, $htgt:ident] + exact account_preState _ _) <;> evm_tidy + | wide_one_s [$ls,*] [$ns,*] $hf $hstat $htgt)) + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- When `x + d` fits, EthLib runs solar's bytecode on `inc(d)` from `σ` to `expectedAt σ d`: +every opcode stepped from pc 0 with 10M gas, SLOAD's read of `σ` and SSTORE's write and price +included. -/ +theorem target_run_ok (d : U256) (σ : List (Nat × Nat)) (hof : slotValue σ 0 + d.toNat < 2 ^ 256) : + Target.run code { callOf incSelector [d] with storage := σ } = some (expectedAt σ d) := by + have he : expectedAt σ d = ⟨true, [], [], fun slot => + if slot % 2 ^ 256 = 0 then slotValue σ 0 + d.toNat else slotValue σ slot⟩ := by + simp only [expectedAt, hof, ↓reduceIte] + rw [he] + refine run_of_postS_at code incSelector [d] σ _ rfl (fun h => by cases h) ?_ + intro msg hv hd hstat htgt + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + simp only [incSelector] at hd + repeat counter_at_one [code, runtimeNat, runtimeSize, incSelector] [hd, hv] hfork hstat htgt + refine stop_postS ?lt ?op rfl rfl rfl ?store + case lt => evm_code [code, runtimeNat, runtimeSize, incSelector] + case op => evm_code [code, runtimeNat, runtimeSize, incSelector] + case store => + intro slot + have hrd : ∀ (tx : TransactionState) a k a' k', + (tx.recordStorageRead a k).getStorage a' k' = tx.getStorage a' k' := + fun _ _ _ _ _ => rfl + rw [htgt, getStorage_writeOf_any, hrd, hrd] + have hk : Target.storageKey slot = U256.toBeBytes 0#256 ↔ slot % 2 ^ 256 = 0 := + storageKey_eq_toBeBytes slot 0#256 + by_cases h : slot % 2 ^ 256 = 0 + · have h' : slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 := h + simp only [hk.2 h, and_self, ↓reduceIte, h'] + rw [BitVec.toNat_add, BitVec.toNat_ofNat, Nat.mod_eq_of_lt (slotValue_lt σ 0), + Nat.mod_eq_of_lt hof] + · have h' : ¬ slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 := h + simp only [show ¬ Target.storageKey slot = U256.toBeBytes 0#256 from fun e => h (hk.1 e), + and_false, ↓reduceIte, h'] + exact getStorage_preState code _ slot + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- When `x + d` overflows, EthLib's run of the bytecode reverts with `Panic(0x11)`. -/ +theorem target_run_overflow (d : U256) (σ : List (Nat × Nat)) + (hof : ¬ slotValue σ 0 + d.toNat < 2 ^ 256) : + Target.run code { callOf incSelector [d] with storage := σ } = some (expectedAt σ d) := by + have he : expectedAt σ d = ⟨false, panic 0x11, [], slotValue σ⟩ := by + simp only [expectedAt, hof, ↓reduceIte] + rw [he] + refine run_of_postS_at code incSelector [d] σ _ rfl (fun _ _ => rfl) ?_ + intro msg hv hd hstat htgt + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + simp only [incSelector] at hd + have hc : BitVec.ofNat 256 (slotValue σ 0) + d < BitVec.ofNat 256 (slotValue σ 0) := by + have hN : (2 : Nat) ^ 256 = + 115792089237316195423570985008687907853269984665640564039457584007913129639936 := by + norm_num + have hlt := slotValue_lt σ 0 + have hw := d.isLt + rw [BitVec.lt_def, BitVec.toNat_add, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hlt] + rw [hN] at hlt hw hof ⊢ + omega + repeat counter_at_one [code, runtimeNat, runtimeSize, incSelector] [hd, hv, hc] hfork hstat htgt + refine revert_postS (by decide) ?_ ?_ ?_ rfl ?_ rfl + · evm_code [code, runtimeNat, runtimeSize, incSelector] + · evm_code [code, runtimeNat, runtimeSize, incSelector] + · wide_mem + · simp only [Verify.panic, Verify.word] + decide +kernel + +/-- EthLib runs solar's bytecode on every call of `inc(d)` from any storage `σ` to +`expectedAt σ d`. -/ +theorem target_run_at (d : U256) (σ : List (Nat × Nat)) : + Target.run code { callOf incSelector [d] with storage := σ } = some (expectedAt σ d) := by + by_cases hof : slotValue σ 0 + d.toNat < 2 ^ 256 + · exact target_run_ok d σ hof + · exact target_run_overflow d σ hof + +end Target + +section Stages + +open SolarTV SolarTV.Machine + +/-- SolarTV's lowered MIR runs `stage0` on `inc(d)` from any storage `σ` to `expectedAt σ d`. -/ +theorem mir_run_at (o : Oracle) (d : U256) (σ : List (Nat × Nat)) : + (MIR.Lowered.moduleSem o).run SolarTV.Export.Counter.stage0 + { callOf incSelector [d] with storage := σ } = some (expectedAt σ d) := + SolidCore.Refinement.Solar.W1.mir_sem_of_run 9 + (mir_run_of_at o _ d rfl (size_callOf d) + (by have h := word0 d; rw [show BitVec.ofNat 256 incSelector = 2166751455 from rfl] at h; exact h) + (word4 d)) + +/-- SolarTV's EVM IR runs `evm5` on `inc(d)` from any storage `σ` to `expectedAt σ d`. -/ +theorem evmir_run_at (o : Oracle) (d : U256) (σ : List (Nat × Nat)) : + (SolarTV.evmirSem o).run SolarTV.Export.Counter.evm5 + { callOf incSelector [d] with storage := σ } = some (expectedAt σ d) := + SolarTV.Milestone.Counter.counter_mir_to_evmir o _ trivial _ (mir_run_at o d σ) + +end Stages + +/-- `model` implements SolidCore's `Counter` on every call of `scopeAt`. -/ +theorem implementsAt {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d []) : Implements fuel c scopeAt (argWords 1) model := by + rintro call ⟨σ, hs⟩ + refine implements_of_run' (s := σ) (by simp [fns]) (fun fn hfn ws hl => ?_) call hs + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w, _ | _⟩ <;> simp at hl + exact run_inc_at hcore hd w σ + +/-- **The specification of Counter's `inc` from any storage**, as a triple against SolidCore. -/ +theorem specAt : ∃ c, contract? = .ok c ∧ Triple fuel c scopeAt pre post := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + exact ⟨c, hc, triple_of_wp (implementsAt hk (deployedAt_of_deployed hd)) vcsAt⟩ + +/-- The specification from any storage as `Satisfies` on SolidCore. -/ +theorem satisfiesAt : ∃ c, contract? = .ok c ∧ Satisfies (solidCore fuel) c scopeAt pre post := by + obtain ⟨c, hc, h⟩ := specAt + exact ⟨c, hc, satisfies_of_triple h⟩ + +/-- SolidCore runs `inc` on any argument word from any storage `σ` to `expectedAt σ d`. -/ +theorem source_run_at {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) (w : U256) + (σ : List (Nat × Nat)) : + Source.run fuel c { callOf incSelector [w] with storage := σ } = some (expectedAt σ w) := by + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + have := run_inc_at hk (deployedAt_of_deployed hd) w σ + rw [observe_model_at] at this + exact this + +/-- **The source stage of Counter from any storage**: SolidCore to solar's first lowered MIR on +every call of `inc` with no value from any storage, under every oracle. -/ +theorem loweringAt (o : SolarTV.Machine.Oracle) {c : TypeCheck.CheckedContract} + (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c SolarTV.Export.Counter.stage0 + scopeAt := by + intro call hscope obs hrun + obtain ⟨d, σ, rfl⟩ := scopeAt_callOf hscope + change Source.run fuel c { callOf incSelector [d] with storage := σ } = some obs at hrun + rw [source_run_at hc d σ] at hrun + cases hrun + exact mir_run_at o d σ + +/-- **The assembly stage of Counter from any storage**: EVM IR to bytecode on EthLib on every +call of `inc` with no value from any storage, under every oracle. -/ +theorem stageAt (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib SolarTV.Export.Counter.evm5 code scopeAt := by + intro call hc obs hrun + obtain ⟨d, σ, rfl⟩ := scopeAt_callOf hc + rw [evmir_run_at o d σ] at hrun + cases hrun + exact target_run_at d σ + +/-- **The counter milestone from any storage.** solar's runtime bytecode for Counter meets the +specification of `inc` (`post`: slot 0 holds `x + d` and every other slot is kept when `x + d` +fits, otherwise a revert with `Panic(0x11)` keeping the storage, never a log) on every call of +`inc` with no value from any storage, under EthLib, through every stage of solar's pipeline, each +proved from any storage. -/ +theorem certifiedAt : Satisfies ethLib code scopeAt pre post := by + obtain ⟨c, hc, hspec⟩ := satisfiesAt + exact bytecode_of_stages hspec (loweringAt W1.oracle hc) + ((SolarTV.Milestone.Counter.counter_mir_to_evmir W1.oracle).mono fun _ _ => trivial) + (stageAt W1.oracle) + +/-- info: 'SolidCore.Refinement.Solar.Counter.stageAt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stageAt + +/-- info: 'SolidCore.Refinement.Solar.Counter.certifiedAt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedAt + +end SolidCore.Refinement.Solar.Counter + + + + + + + + + + + + + + + + + + + + + + diff --git a/SolidCore/Refinement/Solar/Counter/Assembly.lean b/SolidCore/Refinement/Solar/Counter/Assembly.lean new file mode 100644 index 00000000..93d731c5 --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/Assembly.lean @@ -0,0 +1,219 @@ +import SolidCore.Refinement.Solar.Counter.Lowering +import SolidCore.Refinement.Evm.WideStorage +import SolidCore.Refinement.Solar.AssembleSim +import counter.Proofs.Stages +import counter.Proofs.Assembly +import counter.gen.Counter.Manifest + +/-! +# counter: solar's final EVM IR to its bytecode on EthLib + +The assembly stage of Counter (Spec.lean): from the final EVM IR solar compiles +(`SolarTV.Export.Counter.evm5`, after the last `cfg-simplify-early`) to its 83 bytes of runtime +bytecode `code` on EthLib, on every call of `scope`. + +* `bytes_exported`: `code` is the bytecode solar exported with its stages, byte for byte. +* `evmir_run`: SolarTV's EVM IR semantics runs `evm5` on every call of `inc(d)` to `expected d`, + from the source stage's MIR run (`mir_run`) and the backend stages + (`SolarTV.Milestone.Counter.counter_mir_to_evmir`, on every call), under every oracle. +* `target_run`: EthLib runs `code` on every such call to `expected d`: every opcode stepped by + EthLib's program logic from pc 0 with 10M gas (`counter_one`: `wide_tgt_s`'s steps and + SLOAD), SLOAD's read and SSTORE's write and price included, and its branches decided from the call data. +* `stage`: the stage, under every oracle, from the generic theorem for every program and code + the checker accepts (`Assemble.stage_of_check`, AssembleSim.lean) at `check_ok`, the kernel's + evaluation of the checker on `evm5`, `code` and `cert`. `stage_run` proves the same stage + from `evmir_run` and `target_run`, as a cross-check. +* `stageAnyStorage`: the same stage on every call of `inc` with no value from any storage, + from the same check. +* `mutantAdd_check`, `mutantStore_check`: the checker rejects the two one-byte mutants of + Milestone.lean, SUB for the ADD of `x + d` and SLOAD for the SSTORE of slot 0. + +solar-tv's `SolarTV.Milestone.Counter.decodes` separately checks the bytecode's linear decoding +against `evm5`'s instructions, the walk of the assembly checker. +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm.Wide +open SolidCore.Refinement.Wide + +/-- The runtime bytecode's bytes. -/ +def bytes : List Nat := code.data.toList.map (·.toNat) + +/-- `code` is the bytecode solar exported with its stages. -/ +theorem bytes_exported : bytes = SolarTV.Export.Counter.bytecode := by decide + +/-- SolarTV's EVM IR semantics runs Counter's final EVM IR on every call of `inc(d)`, under +every oracle, to the observable `expected d`. -/ +theorem evmir_run (o : SolarTV.Machine.Oracle) (d : U256) : + (SolarTV.evmirSem o).run SolarTV.Export.Counter.evm5 (callOf incSelector [d]) = + some (expected d) := + SolarTV.Milestone.Counter.counter_mir_to_evmir o _ trivial _ (mir_run o d) + +section Target + +open EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Symex SolidCore.Refinement.Evm.Logic + +open EthLib.Execution.State in +/-- A read of the deployed (empty) storage of a call of `callOf` is zero. -/ +theorem getStorage_preState_callOf (code : ByteArray) (s : Nat) (ws : List U256) (key : U256) : + (Target.preState code (callOf s ws)).getStorage (Target.address selfAddress) + (U256.toBeBytes key) = 0 := by + simp [Target.preState, callOf, TransactionState.getStorage, TransactionState.ofBlock, + StorageMap.slot, State.getStorage] + +open EthLib.Execution.State in +/-- Recording reads leaves the accounts as they are. -/ +theorem getAccountOptional_recordStorageRead (tx : TransactionState) (a : Address) (k : Bytes32) + (b : Address) : (tx.recordStorageRead a k).getAccountOptional b = tx.getAccountOptional b := + rfl + +open EthLib.Execution.State in +/-- The storage after SLOAD, SSTORE's own read and its write, from the empty storage of a call +of `callOf`: the written word at its key, zero elsewhere. -/ +theorem getStorage_writeOf_read (code : ByteArray) (s : Nat) (ws : List U256) (a1 a2 a : Address) + (k1 k2 k : Bytes32) (v : U256) (a' : Address) (k' : Bytes32) : + (writeOf (((Target.preState code (callOf s ws)).recordStorageRead a1 k1).recordStorageRead + a2 k2) a k v).getStorage a' k' = if a' = a ∧ k' = k then v else 0 := + getStorage_writeOf code (callOf s ws) rfl a k v a' k' + +open Lean.Parser.Tactic in +/-- Steps one opcode of a path of `inc`: SLOAD of the empty storage (zero, a cold key: no key +is warm at the frame's start), SSTORE after it, +STOP with the storage after the read and the write, and every other opcode as `wide_one_s`. -/ +syntax "counter_one" " [" simpLemma,* "]" " [" simpLemma,* "]" ident ident ident : tactic + +macro_rules + | `(tactic| counter_one [$ls,*] [$ns,*] $hf $hstat $htgt) => `(tactic| ((try unfold Spec) <;> first + | (refine' Triple.seq (sload (cold := true) (by decide) ?lt ?op ?cold ?gas) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case cold => simp [Substate.empty] + case gas => simp only [ite_true]; omega) <;> + (try simp only [$htgt:ident, getStorage_preState_callOf, Bool.true_eq, ↓reduceIte, + Nat.reduceSub]) <;> evm_tidy + | (refine' Triple.seq (sstore (by decide) (by decide) ?lt ?op $hstat rfl ?stip ?gas + (setStorage_ok _ _ ?acc)) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case stip => simp only [CALL_STIPEND]; omega + case gas => exact Nat.le_trans (sstoreCost_le _ _ _ _) (by omega) + case acc => simp only [getAccountOptional_recordStorageRead, $htgt:ident] + exact account_preState _ _) <;> evm_tidy + | (refine stop_postS ?lt ?op ?succ ?out rfl ?store + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case succ => rfl + case out => rfl + case store => intro slot; rw [$htgt:ident, getStorage_writeOf_read]; wide_store) + | wide_one_s [$ls,*] [$ns,*] $hf $hstat $htgt)) + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- EthLib runs solar's bytecode on every call of `inc(d)` to the observable `expected d`. -/ +theorem target_run (d : U256) : + Target.run code (callOf incSelector [d]) = some (expected d) := by + have he : expected d = + ⟨true, [], [], fun slot => if slot % 2 ^ 256 = 0 then d.toNat else 0⟩ := rfl + rw [he] + refine run_of_postS code incSelector [d] _ rfl (fun h => by cases h) ?_ + intro msg hv hd hstat htgt + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + simp only [incSelector] at hd + repeat counter_one [code, runtimeNat, runtimeSize, incSelector] [hd, hv] hfork hstat htgt + +end Target + +/-- The assembly stage of Counter by running both sides to the same observable, a cross-check of +`stage`. -/ +theorem stage_run (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib SolarTV.Export.Counter.evm5 code scope := by + intro call hc obs hrun + obtain ⟨d, rfl⟩ := scope_callOf hc + rw [evmir_run o d] at hrun + cases hrun + exact target_run d + +/-- info: 'SolidCore.Refinement.Solar.Counter.stage_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_run + +/-! ## The stage from the generic theorem -/ + +/-- The certificate of the check: each block's offset in the code (bb4 at 0x34, bb10 at 0x38, +bb8 at 0x41), the stack height each block needs on entry (none), and the bound on memory (64 +bytes, the end of the panic's revert data). -/ +def cert : Assemble.Cert := { offsets := [0, 0x34, 0x38, 0x41], needs := [0, 0, 0, 0], top := 64 } + +set_option maxRecDepth 100000 in +/-- The checker accepts solar's bytecode for the final EVM IR, by the kernel's evaluation. -/ +theorem check_ok : Assemble.check SolarTV.Export.Counter.evm5 code cert = true := by + decide +kernel + +theorem scope_value {call : Call} (h : scope call) : call.callvalue = 0 := by + obtain ⟨d, rfl⟩ := scope_callOf h + rfl + +/-- **The assembly stage of Counter**: EVM IR to bytecode on EthLib, on every call of `scope`, +under every oracle. It is the generic theorem for every program and code the checker accepts, +at `check_ok`. -/ +theorem stage (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib SolarTV.Export.Counter.evm5 code scope := + Assemble.stage_of_check check_ok o fun _ h => scope_value h + +/-- The assembly stage of Counter on every call of `inc` with no value from any storage `σ`, under +every oracle, from the same check. -/ +theorem stageAnyStorage (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib SolarTV.Export.Counter.evm5 code + (fun call => ∃ σ, fullScope fns σ call) := + Assemble.stage_of_check check_ok o fun _ ⟨_, _, _, _, _, _, h⟩ => by rw [h] + +/-- The assembly stage of Counter on every call, with any value, call data and storage, under +every oracle, from the same check. -/ +theorem stageAll (o : SolarTV.Machine.Oracle) (scope : Call → Prop) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib SolarTV.Export.Counter.evm5 code scope := + Assemble.stage_of_check_all check_ok o scope + +/-- `code` with SUB (0x03) for the ADD of `x + d` at offset 42. -/ +def mutantAddCode : ByteArray := EthLib.Execution.Evm.Logic.NatCode.ofNat + 0x346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581039081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd + runtimeSize + +/-- `code` with SLOAD (0x54) for the SSTORE of slot 0 at offset 50. -/ +def mutantStoreCode : ByteArray := EthLib.Execution.Evm.Logic.NatCode.ofNat + 0x346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f54005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd + runtimeSize + +set_option maxRecDepth 100000 in +/-- The checker rejects the ADD mutant: its walk decodes SUB where the program has ADD. -/ +theorem mutantAdd_check : Assemble.check SolarTV.Export.Counter.evm5 mutantAddCode cert = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The checker rejects the SSTORE mutant: its walk decodes SLOAD where the program has SSTORE. -/ +theorem mutantStore_check : + Assemble.check SolarTV.Export.Counter.evm5 mutantStoreCode cert = false := by + decide +kernel + +/-- info: 'SolidCore.Refinement.Solar.Counter.stage' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage + +/-- info: 'SolidCore.Refinement.Solar.Counter.stageAnyStorage' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stageAnyStorage + +/-- info: 'SolidCore.Refinement.Solar.Counter.check_ok' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms check_ok + +/-- info: 'SolidCore.Refinement.Solar.Counter.mutantAdd_check' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms mutantAdd_check + +/-- info: 'SolidCore.Refinement.Solar.Counter.mutantStore_check' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms mutantStore_check + +end SolidCore.Refinement.Solar.Counter diff --git a/SolidCore/Refinement/Solar/Counter/AssemblyAt.lean b/SolidCore/Refinement/Solar/Counter/AssemblyAt.lean new file mode 100644 index 00000000..e78146b6 --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/AssemblyAt.lean @@ -0,0 +1,171 @@ +import SolidCore.Refinement.Solar.Counter.Assembly +import SolidCore.Refinement.Evm.WideStorageAt +import SolidCore.Refinement.Solar.Counter.LoweringAt + +/-! +# counter: solar's final EVM IR to its bytecode on EthLib, from any storage + +The assembly stage of Counter (Assembly.lean) on `scopeAt` (SpecAt.lean): every call of +`inc(d)` with no value from any storage `σ`, whose slot 0 holds any word `x`, so both the write +of `x + d` and the Panic(0x11) revert on overflow are reached. + +* `target_run_at`: EthLib runs `code` on every such call to `expectedAt σ d`, every opcode + stepped by EthLib's program logic from pc 0 with 10M gas (`counter_one_at`): SLOAD reads + `σ`'s slot 0 from the call's state (`getStorage_preState_toBeBytes`), the overflow branch is + decided by whether `x + d` fits, SSTORE writes `x + d` over `σ` at its price, and the final + storage is read slot by slot (`storage_after_at`); `run_of_postS_at` turns the frame into + `Target.run`. +* `evmir_run_at`: SolarTV's EVM IR semantics runs `evm5` on the same calls to `expectedAt σ d`, + from the source stage's MIR run from `σ` (`mir_run_at`) and the backend stages, which hold on + every call. +* `stageAt`: the stage, under every oracle, from the generic theorem for every program and code + the checker accepts (`Assemble.stage_of_check`, AssembleSim.lean) at the same `check_ok` as + `stage`: it is `stageAnyStorage` (Assembly.lean), whose scope is `scopeAt` unfolded. + `stageAt_run` proves the same stage from `evmir_run_at` and `target_run_at`, as a cross-check. +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm.Wide +open SolidCore.Refinement.Wide + +section TargetAt + +open EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Symex SolidCore.Refinement.Evm.Logic + +open EthLib.Execution.State in +/-- The storage after SLOAD's and SSTORE's reads and the write of `v` to slot 0, from the +storage of any call: `v` in slot 0, the call's word in every other slot. -/ +theorem storage_after_at (code : ByteArray) (c : Call) (k1 k2 : Bytes32) (v : U256) (slot : Nat) : + ((writeOf (((Target.preState code c).recordStorageRead (Target.address selfAddress) k1).recordStorageRead + (Target.address selfAddress) k2) (Target.address selfAddress) (U256.toBeBytes (BitVec.ofNat 256 0)) v).getStorage + (Target.address selfAddress) (Target.storageKey slot)).toNat = + if slot % 2 ^ 256 = 0 then v.toNat else slotValue c.storage slot := by + rw [getStorage_writeOf_any, getStorage_recordStorageRead, getStorage_recordStorageRead] + by_cases hz : slot % 2 ^ 256 = 0 + · have hk : Target.storageKey slot = U256.toBeBytes (BitVec.ofNat 256 0) := + (storageKey_eq_toBeBytes slot _).2 (by simpa using hz) + simp only [hk, and_self, ↓reduceIte, hz] + · have hk : Target.storageKey slot ≠ U256.toBeBytes (BitVec.ofNat 256 0) := fun h => + hz (by simpa using (storageKey_eq_toBeBytes slot _).1 h) + simp only [hk, and_false, ↓reduceIte, hz] + exact getStorage_preState code c slot + +/-- A word read from storage plus `d`, when the sum fits, as a number. -/ +theorem toNat_ofNat_add {x : Nat} {d : U256} (h : x + d.toNat < 2 ^ 256) : + (BitVec.ofNat 256 x + d).toNat = x + d.toNat := by + rw [BitVec.toNat_add, BitVec.toNat_ofNat, Nat.mod_eq_of_lt (a := x) (by omega), + Nat.mod_eq_of_lt h] + +open Lean.Parser.Tactic in +/-- Steps one opcode of a path of `inc` from any storage: SLOAD of the call's storage (a cold +key: no key is warm at the frame's start), SSTORE after it, STOP with the storage after the +read and the write (`hval`: the stored sum as a number), REVERT with Panic(0x11), and every other +opcode as `wide_one_s`. -/ +syntax "counter_one_at" " [" simpLemma,* "]" " [" simpLemma,* "]" ident ident ident ident : tactic + +macro_rules + | `(tactic| counter_one_at [$ls,*] [$ns,*] $hf $hstat $htgt $hval) => `(tactic| ((try unfold Spec) <;> first + | (refine' Triple.seq (sload (cold := true) (by decide) ?lt ?op ?cold ?gas) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case cold => simp [Substate.empty] + case gas => simp only [ite_true]; omega) <;> + (try simp only [$htgt:ident, getStorage_preState_toBeBytes, BitVec.toNat_ofNat, + Nat.zero_mod, Bool.true_eq, ↓reduceIte, Nat.reduceSub]) <;> evm_tidy + | (refine' Triple.seq (sstore (by decide) (by decide) ?lt ?op $hstat rfl ?stip ?gas + (setStorage_ok _ _ ?acc)) ?next + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case stip => simp only [CALL_STIPEND]; omega + case gas => exact Nat.le_trans (sstoreCost_le _ _ _ _) (by omega) + case acc => simp only [getAccountOptional_recordStorageRead, $htgt:ident] + exact account_preState _ _) <;> evm_tidy + | (refine stop_postS ?lt ?op ?succ ?out rfl ?store + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case succ => rfl + case out => rfl + case store => intro slot; rw [$htgt:ident, storage_after_at, $hval:ident]; rfl) + | (refine revert_postS (by decide) ?lt ?op ?gas rfl ?out rfl + case lt => evm_code [$ls,*] + case op => evm_code [$ls,*] + case gas => (try wide_mem) <;> first | decide | omega | decide +kernel + case out => simp only [Verify.panic, Verify.word]; decide +kernel) + | wide_one_s [$ls,*] [$ns,*] $hf $hstat $htgt)) + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- EthLib runs solar's bytecode on every call of `inc(d)` from any storage `σ` to the +observable `expectedAt σ d`: when `x + d` fits, with `x` the word SLOAD reads from `σ`'s slot 0, +the write of `x + d` over `σ`; otherwise the revert with Panic(0x11), every opcode stepped by +EthLib's program logic from pc 0 with 10M gas and the overflow branch decided by the sum. -/ +theorem target_run_at (d : U256) (σ : List (Nat × Nat)) : + Target.run code { callOf incSelector [d] with storage := σ } = some (expectedAt σ d) := by + refine run_of_postS_at code incSelector [d] σ _ (by unfold expectedAt; split <;> rfl) ?_ ?_ + · intro h slot + unfold expectedAt at h ⊢ + split + · rename_i hc + simp only [hc, ↓reduceIte] at h + cases h + · rfl + intro msg hv hd hstat htgt + simp only [callAt] + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + have hlt := slotValue_lt σ 0 + have hw := d.isLt + simp only [incSelector] at hd + by_cases hof : slotValue σ 0 + d.toNat < 2 ^ 256 + · have he : expectedAt σ d = ⟨true, [], [], fun slot => + if slot % 2 ^ 256 = 0 then slotValue σ 0 + d.toNat else slotValue σ slot⟩ := by + simp only [expectedAt, hof, ↓reduceIte] + have hval := toNat_ofNat_add hof + rw [he] + repeat counter_one_at [code, runtimeNat, runtimeSize, incSelector] [hd, hv] hfork hstat htgt hval + · have he : expectedAt σ d = ⟨false, Verify.panic 0x11, [], slotValue σ⟩ := by + simp only [expectedAt, hof, ↓reduceIte] + rw [he] + repeat counter_one_at [code, runtimeNat, runtimeSize, incSelector] [hd, hv] hfork hstat htgt hfork + +end TargetAt + +/-- SolarTV's EVM IR semantics runs Counter's final EVM IR on every call of `inc(d)` from any +storage `σ`, under every oracle, to `expectedAt σ d`: the source stage's MIR run from `σ` +(`mir_run_at`) through the backend stages, which hold on every call. -/ +theorem evmir_run_at (o : SolarTV.Machine.Oracle) (d : U256) (σ : List (Nat × Nat)) : + (SolarTV.evmirSem o).run SolarTV.Export.Counter.evm5 + { callOf incSelector [d] with storage := σ } = some (expectedAt σ d) := + SolarTV.Milestone.Counter.counter_mir_to_evmir o _ trivial _ (mir_run_at o d σ) + +/-- **The assembly stage of Counter from any storage**: EVM IR to bytecode on EthLib, on every +call of `scopeAt`, under every oracle. It is the generic theorem at `check_ok` +(`stageAnyStorage`), since every call of `scopeAt` has no value. -/ +theorem stageAt (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib SolarTV.Export.Counter.evm5 code scopeAt := + stageAnyStorage o + +/-- The same stage from any storage proved directly, by running both sides to the same observable +(`evmir_run_at` and `target_run_at`), as a cross-check of `stageAt`. -/ +theorem stageAt_run (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib SolarTV.Export.Counter.evm5 code scopeAt := by + intro call hc obs hrun + obtain ⟨d, σ, rfl⟩ := scopeAt_callOf hc + rw [evmir_run_at o d σ] at hrun + cases hrun + exact target_run_at d σ + +/-- info: 'SolidCore.Refinement.Solar.Counter.stageAt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stageAt + +/-- info: 'SolidCore.Refinement.Solar.Counter.stageAt_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stageAt_run + +/-- info: 'SolidCore.Refinement.Solar.Counter.target_run_at' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms target_run_at + +end SolidCore.Refinement.Solar.Counter diff --git a/SolidCore/Refinement/Solar/Counter/Calls.lean b/SolidCore/Refinement/Solar/Counter/Calls.lean new file mode 100644 index 00000000..da3db20b --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/Calls.lean @@ -0,0 +1,323 @@ +import SolidCore.Refinement.Solar.Counter.Value +import SolidCore.Refinement.Dyn.Source + +/-! +# counter on every call: get, malformed call data and unknown selectors + +Counter has no fallback and no receive function, so SolidCore and solar's code reject every call +that names no function or whose arguments do not decode. This file proves each class of call +through the source stage, from any storage: + +* get(), with no value: success returning the word in slot 0, the storage kept + (source_run_get, mir_run_get). +* call data shorter than 4 bytes, with any bytes and any value: rejected (source_run_short). +* any 4-byte selector other than inc's and get's, followed by any bytes, with any value: + rejected (source_run_unknown). +* inc's selector followed by fewer than 32 bytes, with any value: rejected + (source_run_shortArgs). +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source SolidCore.Verify + +/-- Source.run of any call, once the constructor's result is known: the constructor runs with no +value whatever the call's, so it is the deployed state, and the ABI dispatcher of the core +contract runs on the call's bytes with its value. -/ +theorem run_eq_any {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : DeployedAt fuel c d s) (call : Call) : + Source.run fuel c call = + Option.map (Source.observe call) + (ABI.Contract.callCalldataAtFromWithContext? fuel c.core + { ctxOf c with value := call.callvalue } + { d with storage := + call.storage.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage } + selfAddress callerAddress call.callvalue (call.calldata.data.toList.map (·.toNat))) := by + obtain ⟨vs, hc⟩ := hd.cons + have hc' : TypeCheck.CheckedContract.constructWithContext? fuel c + { c.core.context with sender := callerAddress, self := selfAddress, value := call.callvalue } + State.empty selfAddress 0 [] = some (CallResult.returned d vs) := hc + simp only [Source.run, Source.result?] + rw [hc'] + rfl + +/-- The deployed state of SolidCore's checked Counter, with its core. -/ +theorem deployed_counter {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core = coreLit ∧ ∃ d, DeployedAt fuel c d [] := by + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + exact ⟨hk, d, deployedAt_of_deployed hd⟩ + +/-- SolidCore rejects every call whose call data is shorter than a selector, with any bytes and +any value, from any storage: no selector is read, and Counter has no receive or fallback +function. -/ +theorem source_run_short {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) (call : Call) + (hsize : call.calldata.size < 4) : + Source.run fuel c call = some (Abi.rejected call.storage) := by + obtain ⟨hcore, d, hd⟩ := deployed_counter hc + rw [run_eq_any hd, hcore] + have hsel : ABI.readSelector? (call.calldata.data.toList.map (·.toNat)) = none := by + simp only [ABI.readSelector?, ABI.readBytes?, ABI.selectorBytes, List.drop_zero, + List.length_map, Array.length_toList] + have h4 : call.calldata.data.size < 4 := hsize + rw [ite_eq_right_iff.mpr (by omega)] + simp only [ABI.Contract.callCalldataAtFromWithContext?, hsel] + simp only [ABI.Contract.callReceiveOrFallbackAtFromWithContext?, + ABI.Contract.callFallbackAtFromWithContext?, ABI.Contract.findReceive?, + ABI.Contract.findFallback?, Contract.findFunctionByName?, coreLit] + split <;> simp [ABI.Contract.missingFallbackCall?, ABI.Contract.revertedEmptyCall?, + ABI.Contract.revertedCall?, ABI.Contract.encodeRevertData?, Source.observe, Abi.rejected] + + +open SolidCore.Refinement.Dyn in +/-- SolidCore rejects every call of a selector other than inc's and get's, followed by any +bytes, and every call of inc whose argument is shorter than a word, with any value, from any +storage: Counter has no fallback, and inc's argument does not decode. -/ +theorem source_run_selector {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) (s : Nat) + (hs : s < 2 ^ 32) (data : ByteArray) + (h : (s ≠ incSelector ∧ s ≠ getSelector) ∨ (s = incSelector ∧ data.size < 32)) (v : Nat) + (σ : List (Nat × Nat)) : + Source.run fuel c { calldata := Evm.selectorOf s ++ data, callvalue := v, storage := σ } = + some (Abi.rejected σ) := by + obtain ⟨hcore, d, hd⟩ := deployed_counter hc + rw [run_eq_any hd, hcore] + simp only [ABI.Contract.callCalldataAtFromWithContext?, bytes_callOn, + readSelector_append _ hs] + have hm : s % 2 ^ 256 = s := Nat.mod_eq_of_lt (by omega) + rcases h with ⟨h1, h2⟩ | ⟨rfl, hlt⟩ + · have hw1 : wordEq 2166751455 s = false := by + simp only [wordEq, Shared.norm, Shared.wordModulus, beq_eq_false_iff_ne, ne_eq] + simp only [incSelector, getSelector] at h1 h2 + rw [show EvmYul.UInt256.size = 2 ^ 256 from rfl, hm] + exact fun e => h1 (by rw [← e]; exact Nat.mod_eq_of_lt (by decide)) + have hw2 : wordEq 1833756220 s = false := by + simp only [wordEq, Shared.norm, Shared.wordModulus, beq_eq_false_iff_ne, ne_eq] + simp only [incSelector, getSelector] at h1 h2 + rw [show EvmYul.UInt256.size = 2 ^ 256 from rfl, hm] + exact fun e => h2 (by rw [← e]; exact Nat.mod_eq_of_lt (by decide)) + simp only [Contract.findFunctionBySelector?, coreLit, List.find?, hw1, hw2] + simp [ABI.Contract.callFallbackAtFromWithContext?, ABI.Contract.findFallback?, + Contract.findFunctionByName?, ABI.Contract.missingFallbackCall?, + ABI.Contract.revertedEmptyCall?, ABI.Contract.revertedCall?, + ABI.Contract.encodeRevertData?, Source.observe, Abi.rejected] + · have hw1 : wordEq 2166751455 incSelector = true := by decide + simp only [Contract.findFunctionBySelector?, coreLit, List.find?, hw1] + rw [show ((natToBytes 4 incSelector).map (·.toNat) ++ srcBytes data).drop ABI.selectorBytes = + srcBytes data by simp [ABI.selectorBytes, natToBytes_length], + decode_malformed _ [.word (.uint 256)] (by decide) data + (Or.inl (by simpa [headWords, DParam.headWords] using hlt))] + simp [ABI.Contract.revertedCall?, ABI.Contract.encodeRevertData?, Source.observe, Abi.rejected] + + +/-! ## get() from any storage -/ + +/-- What a call of get() from the storage σ shows: success returning the word in slot 0, with +no logs and σ kept. -/ +def getAt (σ : List (Nat × Nat)) : Observable := + { success := true, output := Verify.word (slotValue σ 0), logs := [], storage := slotValue σ } + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs get() with no value from any storage σ to getAt σ. -/ +theorem source_run_get {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) + (σ : List (Nat × Nat)) : + Source.run fuel c (callAt getSelector [] σ) = some (getAt σ) := by + obtain ⟨hcore, d, hd⟩ := deployed_counter hc + rw [run_eq_at hd] + have hev := hd.events + have h0 : ∀ q : Nat, d.storage[q]? = none := fun q => hd.getElem?_eq_none (by simp) + have hget := getD_storage h0 σ + generalize σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage = m at hget + simp only [hcore, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, getSelector, get?_insert] + all_goals + have hlt := slotValue_lt σ 0 + have hlt' : slotValue σ 0 < + 115792089237316195423570985008687907853269984665640564039457584007913129639936 := hlt + have hx := hget 0 + simp only [Nat.zero_mod] at hx + case h_1 => + rename_i _ w heq + simp only [heq, Option.getD_some] at hx + subst hx + simp only [Nat.mod_eq_of_lt hlt'] + simp [Source.observe, State.logEntries, State.loadSlot, StorageMap.lookup?, getAt, Verify.word] + funext slot + have hs := hget slot + simp only [Shared.norm, Shared.wordModulus, EvmYul.UInt256.size] + simp only [Nat.reducePow] at hs + rw [← hs] + cases m[slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936]? <;> rfl + case h_2 => + rename_i _ heq + simp only [heq, Option.getD_none] at hx + simp [Source.observe, State.logEntries, State.loadSlot, StorageMap.lookup?, getAt, Verify.word, + ← hx] + funext slot + have hs := hget slot + simp only [Shared.norm, Shared.wordModulus, EvmYul.UInt256.size] + simp only [Nat.reducePow] at hs + rw [← hs] + cases m[slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936]? <;> rfl + + +section CallsMIR + +open SolarTV SolarTV.Machine SolarTV.Milestone.W1 + +/-- SolarTV's lowered MIR runs stage0 on every call of get's selector with no value, whatever +the rest of its call data, from any storage, to getAt: the storage read of slot 0 and its +return. -/ +theorem mir_run_get_of (o : Oracle) (call : Call) (hv : call.callvalue = 0) + (h0 : EvmRules.Evm.shr 224 (calldataWord call 0) = 1833756220) : + (MIR.Lowered.Module.run o SolarTV.Export.Counter.stage0 call 9).map + (fun r => observe call r.2 r.1) = some (getAt call.storage) := by + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte]) + have hX : ((State.initial call).storage 0).toNat = slotValue call.storage 0 := by + simp only [State.initial, BitVec.toNat_ofNat] + exact Nat.mod_eq_of_lt (slotValue_lt _ _) + simp only [Machine.observe, getAt, Option.some.injEq, Observable.mk.injEq, true_and] + refine ⟨?_, rfl, ?_⟩ + · rw [SolidCore.Refinement.Solar.W1.read_store_mir, hX] + rfl + · funext slot + simp [storageOf, State.initial] + exact slotValue_mod_mod call.storage slot + +/-- SolarTV's lowered MIR rejects every call with no value whose selector word is neither +inc's nor get's, and every call of inc's selector shorter than 36 bytes, from any storage. -/ +theorem mir_run_reject_of (o : Oracle) (call : Call) (hv : call.callvalue = 0) + (h : (EvmRules.Evm.shr 224 (calldataWord call 0) ≠ 1833756220 ∧ + EvmRules.Evm.shr 224 (calldataWord call 0) ≠ 2166751455) ∨ + (EvmRules.Evm.shr 224 (calldataWord call 0) = 2166751455 ∧ call.calldata.size < 36)) : + (MIR.Lowered.Module.run o SolarTV.Export.Counter.stage0 call 9).map + (fun r => observe call r.2 r.1) = some (Abi.rejected call.storage) := by + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + rcases h with ⟨h1, h2⟩ | ⟨h0, hs⟩ + · have h1' := Ne.symm h1 + have h2' := Ne.symm h2 + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte]) + simp [Machine.observe, Abi.rejected, Mem.read] + · have hlt : BitVec.ofNat 256 call.calldata.size < 36 := by + rw [BitVec.lt_def, BitVec.toNat_ofNat, Nat.mod_eq_of_lt (by omega)] + exact hs + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte]) + simp [Machine.observe, Abi.rejected, Mem.read] + +end CallsMIR + + +/-! ## The selector word -/ + +section Selector + +open SolarTV SolarTV.Machine EthLib.Execution.Evm SolidCore.Refinement.Evm + +/-- The selector the code reads: the first 4 bytes of the call data, zero past its end. -/ +def selWord (call : Call) : Nat := bytesToNat (bufferRead call.calldata 0 4) + +/-- SHR 224 of the first call data word is the selector word. -/ +theorem shr_word0 (call : Call) : + EvmRules.Evm.shr 224 (calldataWord call 0) = BitVec.ofNat 256 (selWord call) := by + rw [SolidCore.Refinement.Solar.W1.calldataWord_eq] + have h := bitwiseShr_loadWord_zero call.calldata 4 (by decide) (by decide) + rw [show BitVec.ofNat 256 (8 * (32 - 4)) = 224#256 from rfl] at h + simpa [EvmRules.Evm.shr, bitwiseShr, selWord] using h + +/-- The selector word of a selector followed by any bytes is the selector. -/ +theorem selWord_append (s : Nat) (hs : s < 2 ^ 32) (data : ByteArray) (v : Nat) + (σ : List (Nat × Nat)) : + selWord { calldata := selectorOf s ++ data, callvalue := v, storage := σ } = s := by + simp only [selWord] + rw [bufferRead_append_of_le _ _ (by simp [size_selectorOf]), ← size_selectorOf s, + bufferRead_zero_size, bytesToNat_selectorOf s hs] + +/-- The selector word of call data shorter than 4 bytes ends in a zero byte, so it is neither +inc's selector nor get's. -/ +theorem selWord_short (call : Call) (h : call.calldata.size < 4) : + selWord call ≠ getSelector ∧ selWord call ≠ incSelector := by + have hb3 : byteAt call.calldata 3 = 0 := by + unfold byteAt + rw [dite_eq_right_iff.mpr fun h' => absurd h' (by omega)] + have hr : List.range 4 = [0, 1, 2, 3] := rfl + simp only [selWord, bufferRead, hr, List.map, Nat.zero_add, hb3, bytesToNat, List.foldl, + UInt8.toNat_zero, Nat.add_zero, getSelector, incSelector] + omega + +/-- The selector word is below 2 ^ 32. -/ +theorem selWord_lt (call : Call) : selWord call < 2 ^ 32 := by + have h := bytesToNat_lt (bufferRead call.calldata 0 4) + simpa [bufferRead_length, selWord] using h + +/-- SHR 224 of the first call data word is a selector exactly when the selector word is. -/ +theorem shr_word0_eq (call : Call) (s : Nat) (hs : s < 2 ^ 32) : + EvmRules.Evm.shr 224 (calldataWord call 0) = BitVec.ofNat 256 s ↔ selWord call = s := by + rw [shr_word0] + constructor + · intro e + have := congrArg BitVec.toNat e + simp only [BitVec.toNat_ofNat] at this + have h1 := selWord_lt call + rw [Nat.mod_eq_of_lt (by omega), Nat.mod_eq_of_lt (by omega)] at this + exact this + · intro e + rw [e] + +end Selector + +open SolidCore.Refinement.Dyn in +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs get's selector followed by any bytes, with no value, from any storage σ, to +getAt σ: get takes no arguments, so the bytes after the selector are not read. -/ +theorem source_run_get_tail {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) + (data : ByteArray) (σ : List (Nat × Nat)) : + Source.run fuel c + { calldata := Evm.selectorOf getSelector ++ data, callvalue := 0, storage := σ } = + some (getAt σ) := by + obtain ⟨hcore, d, hd⟩ := deployed_counter hc + rw [run_eq_any hd, hcore] + simp only [ABI.Contract.callCalldataAtFromWithContext?, bytes_callOn, + readSelector_append _ (by decide : getSelector < 2 ^ 32)] + have hw1 : wordEq 2166751455 getSelector = false := by decide + have hw2 : wordEq 1833756220 getSelector = true := by decide + simp only [Contract.findFunctionBySelector?, coreLit, List.find?, hw1, hw2] + have hev := hd.events + have h0 : ∀ q : Nat, d.storage[q]? = none := fun q => hd.getElem?_eq_none (by simp) + have hget := getD_storage h0 σ + generalize σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage = m at hget + generalize srcBytes data = rest + wide_symex [coreLit, fuel, ctxOf, hcore, getSelector, get?_insert] + all_goals + have hlt := slotValue_lt σ 0 + have hlt' : slotValue σ 0 < + 115792089237316195423570985008687907853269984665640564039457584007913129639936 := hlt + have hx := hget 0 + simp only [Nat.zero_mod] at hx + case h_1 => + rename_i _ w heq + simp only [heq, Option.getD_some] at hx + subst hx + simp only [Nat.mod_eq_of_lt hlt'] + simp [Source.observe, State.logEntries, State.loadSlot, StorageMap.lookup?, getAt, Verify.word] + funext slot + have hs := hget slot + simp only [Shared.norm, Shared.wordModulus, EvmYul.UInt256.size] + simp only [Nat.reducePow] at hs + rw [← hs] + cases m[slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936]? <;> rfl + case h_2 => + rename_i _ heq + simp only [heq, Option.getD_none] at hx + simp [Source.observe, State.logEntries, State.loadSlot, StorageMap.lookup?, getAt, Verify.word, + ← hx] + funext slot + have hs := hget slot + simp only [Shared.norm, Shared.wordModulus, EvmYul.UInt256.size] + simp only [Nat.reducePow] at hs + rw [← hs] + cases m[slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936]? <;> rfl + +end SolidCore.Refinement.Solar.Counter diff --git a/SolidCore/Refinement/Solar/Counter/Every.lean b/SolidCore/Refinement/Solar/Counter/Every.lean new file mode 100644 index 00000000..b8fac021 --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/Every.lean @@ -0,0 +1,253 @@ +import SolidCore.Refinement.Solar.Counter.Calls +import SolidCore.Refinement.Solar.Counter.AssemblyAt + +/-! +# The counter on every call + +expectedEvery is what Counter does on any call, as solar's code reads it: a call with value is +rejected (neither function is payable); otherwise the selector word (the first 4 bytes of the +call data, zero past its end) picks get, which returns slot 0, or inc, which needs 36 bytes and +adds the word at byte 4 to slot 0 or panics on overflow; anything else is rejected, since +Counter has no fallback and no receive function. + +certifiedEvery states that solar's bytecode for Counter shows expectedEvery on every call of +scopeEvery, from any storage, under EthLib, through every stage of solar's pipeline: +scopeEvery is every call with a value below 2 ^ 256 whose call data is inc's ABI encoding of a +word, get's selector, shorter than a selector, or a selector followed by any bytes that is +neither inc's nor get's or is inc's with fewer than 32 bytes after it. + +* source: source_run_every, from SpecAt.lean (inc), Value.lean (any value) and Calls.lean + (get, short call data, unknown selectors, short arguments); mir_run_every, the lowered MIR's + run of the same calls; loweringEvery is the stage. +* backend: SolarTV.Milestone.Counter.counter_mir_to_evmir, which holds on every call. +* assembly: assemblyEvery is the generic theorem, Assemble.stage_of_check_all at check_ok + (stageAll), which holds on every call, with any value, call data and storage. + +Not covered: call data that encodes inc or get but carries extra bytes after the ABI encoding. +The bytecode and MIR accept such calls as solc does; SolidCore's run of them is not proved +here. +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Evm SolidCore.Solidity SolidCore.Verify + +/-- What Counter does on any call, from the call's storage. -/ +def expectedEvery (call : Call) : Observable := + if call.callvalue ≠ 0 then Abi.rejected call.storage + else if selWord call = getSelector then getAt call.storage + else if selWord call = incSelector ∧ 36 ≤ call.calldata.size then + expectedAt call.storage (EthLib.Execution.Evm.loadWord call.calldata 4 32) + else Abi.rejected call.storage + +/-- Every call with a value below 2 ^ 256, from any storage, whose call data is inc's ABI +encoding of a word, get's selector, shorter than a selector, or a selector followed by any +bytes that names no function or gives inc fewer than 32 bytes. -/ +def scopeEvery : Call → Prop := fun call => call.callvalue < 2 ^ 256 ∧ + ((∃ d : U256, call.calldata = (callOf incSelector [d]).calldata) ∨ + call.calldata = (callOf getSelector []).calldata ∨ + call.calldata.size < 4 ∨ + ∃ (s : Nat) (data : ByteArray), s < 2 ^ 32 ∧ call.calldata = selectorOf s ++ data ∧ + ((s ≠ incSelector ∧ s ≠ getSelector) ∨ (s = incSelector ∧ data.size < 32))) + +/-- The call shows expectedEvery. -/ +def postEvery (call : Call) (obs : Observable) : Prop := obs = expectedEvery call + +/-! ## The classes of calls -/ + +theorem calldata_inc (d : U256) : + (callOf incSelector [d]).calldata = selectorOf incSelector ++ wordsBytes [d] := by + rw [calldata_callOf] + rfl + +theorem calldata_get : (callOf getSelector []).calldata = selectorOf getSelector ++ .empty := by + have := calldata_eq_cdOf getSelector [] (by simp) + simpa [callOf, cdOf, wordsBytes] using this + +theorem call_eta (call : Call) : + call = { calldata := call.calldata, callvalue := call.callvalue, storage := call.storage } := + rfl + +theorem expectedEvery_value (call : Call) (hv : call.callvalue ≠ 0) : + expectedEvery call = Abi.rejected call.storage := by + simp [expectedEvery, hv] + +theorem expectedEvery_inc (d : U256) (σ : List (Nat × Nat)) : + expectedEvery { callOf incSelector [d] with storage := σ } = expectedAt σ d := by + have hs : selWord { callOf incSelector [d] with storage := σ } = incSelector := by + have := selWord_append incSelector (by decide) (wordsBytes [d]) 0 σ + rw [← calldata_inc] at this + exact this + have hsize := size_callOf d + have hw : EthLib.Execution.Evm.loadWord (callOf incSelector [d]).calldata 4 32 = d := by + have := word4 d + rwa [SolidCore.Refinement.Solar.W1.calldataWord_eq] at this + simp only [expectedEvery, hs] + simp [callOf, incSelector, getSelector] at hsize hw ⊢ + simp [hsize, hw] + +theorem expectedEvery_get (σ : List (Nat × Nat)) : + expectedEvery (callAt getSelector [] σ) = getAt σ := by + have hs : selWord (callAt getSelector [] σ) = getSelector := by + have := selWord_append getSelector (by decide) .empty 0 σ + rw [← calldata_get] at this + exact this + simp only [expectedEvery, hs, show (callAt getSelector [] σ).callvalue = 0 from rfl, + show (callAt getSelector [] σ).storage = σ from rfl] + rfl + +theorem expectedEvery_short (call : Call) (h : call.calldata.size < 4) (hv : call.callvalue = 0) : + expectedEvery call = Abi.rejected call.storage := by + obtain ⟨h1, h2⟩ := selWord_short call h + simp [expectedEvery, hv, h1, h2] + +theorem expectedEvery_selector (s : Nat) (hs : s < 2 ^ 32) (data : ByteArray) + (h : (s ≠ incSelector ∧ s ≠ getSelector) ∨ (s = incSelector ∧ data.size < 32)) + (σ : List (Nat × Nat)) : + expectedEvery { calldata := selectorOf s ++ data, callvalue := 0, storage := σ } = + Abi.rejected σ := by + have hw := selWord_append s hs data 0 σ + rcases h with ⟨h1, h2⟩ | ⟨rfl, hlt⟩ + · simp [expectedEvery, hw, h1, h2] + · have hsize : (selectorOf incSelector ++ data).size = 4 + data.size := by + simp [ByteArray.size_append, size_selectorOf] + simp only [expectedEvery, hw, hsize] + simp [incSelector, getSelector] + omega + + +/-! ## Every stage -/ + +/-- **SolidCore on every call of the scope**: it shows expectedEvery. -/ +theorem source_run_every {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) (call : Call) + (h : scopeEvery call) : Source.run fuel c call = some (expectedEvery call) := by + rcases call with ⟨cd, v, σ⟩ + obtain ⟨hv, hcl⟩ := h + dsimp only at hv hcl + rcases hcl with ⟨d, rfl⟩ | rfl | hshort | ⟨s, data, hs, rfl, hsel⟩ + · by_cases h0 : v = 0 + · subst h0 + have := expectedEvery_inc d σ + exact (source_run_at hc d σ).trans (congrArg some this.symm) + · rw [expectedEvery_value _ h0] + exact source_run_value hc incSelector [d] (Or.inl ⟨rfl, rfl⟩) v h0 hv σ + · by_cases h0 : v = 0 + · subst h0 + have := expectedEvery_get σ + exact (source_run_get hc σ).trans (congrArg some this.symm) + · rw [expectedEvery_value _ h0] + exact source_run_value hc getSelector [] (Or.inr ⟨rfl, rfl⟩) v h0 hv σ + · by_cases h0 : v = 0 + · subst h0 + rw [expectedEvery_short _ hshort rfl] + exact source_run_short hc _ hshort + · rw [expectedEvery_value _ h0] + exact source_run_short hc _ hshort + · by_cases h0 : v = 0 + · subst h0 + rw [expectedEvery_selector s hs data hsel σ] + exact source_run_selector hc s hs data hsel 0 σ + · rw [expectedEvery_value _ h0] + exact source_run_selector hc s hs data hsel v σ + +/-- The specification on every call of the scope holds of SolidCore's checked Counter. -/ +theorem satisfiesEvery : ∃ c, contract? = .ok c ∧ + Satisfies (solidCore fuel) c scopeEvery pre postEvery := by + obtain ⟨c, hc, -⟩ := satisfies + exact ⟨c, hc, fun call hs _ => ⟨_, source_run_every hc call hs, rfl⟩⟩ + +section EveryMIR + +open SolarTV SolarTV.Machine + +/-- **The lowered MIR on every call of the scope**: stage0 shows expectedEvery, under every +oracle. -/ +theorem mir_run_every (o : Oracle) (call : Call) (h : scopeEvery call) : + (MIR.Lowered.moduleSem o).run SolarTV.Export.Counter.stage0 call = + some (expectedEvery call) := by + rcases call with ⟨cd, v, σ⟩ + obtain ⟨hv, hcl⟩ := h + dsimp only at hv hcl + by_cases h0 : v = 0 + swap + · rw [expectedEvery_value _ h0] + exact mir_run_value o _ _ h0 hv _ + subst h0 + have hget : (1833756220 : EvmRules.Word) = BitVec.ofNat 256 getSelector := rfl + have hinc : (2166751455 : EvmRules.Word) = BitVec.ofNat 256 incSelector := rfl + rcases hcl with ⟨d, rfl⟩ | rfl | hshort | ⟨s, data, hs, rfl, hsel⟩ + · rw [show ({ calldata := (callOf incSelector [d]).calldata, callvalue := 0, storage := σ } : Call) = + { callOf incSelector [d] with storage := σ } from rfl, expectedEvery_inc d σ] + exact mir_run_at o d σ + · rw [show ({ calldata := (callOf getSelector []).calldata, callvalue := 0, storage := σ } : Call) = + callAt getSelector [] σ from rfl, expectedEvery_get σ] + refine SolidCore.Refinement.Solar.W1.mir_sem_of_run 9 (mir_run_get_of o _ rfl ?_) + rw [hget, shr_word0_eq _ _ (by decide)] + have := selWord_append getSelector (by decide) .empty 0 σ + rw [← calldata_get] at this + exact this + · rw [expectedEvery_short _ hshort rfl] + obtain ⟨h1, h2⟩ := selWord_short { calldata := cd, callvalue := 0, storage := σ } hshort + refine SolidCore.Refinement.Solar.W1.mir_sem_of_run 9 + (mir_run_reject_of o _ rfl (Or.inl ⟨?_, ?_⟩)) + · rw [hget, Ne, shr_word0_eq _ _ (by decide)] + exact h1 + · rw [hinc, Ne, shr_word0_eq _ _ (by decide)] + exact h2 + · rw [expectedEvery_selector s hs data hsel σ] + have hw := selWord_append s hs data 0 σ + refine SolidCore.Refinement.Solar.W1.mir_sem_of_run 9 (mir_run_reject_of o _ rfl ?_) + rcases hsel with ⟨h1, h2⟩ | ⟨rfl, hlt⟩ + · refine Or.inl ⟨?_, ?_⟩ + · rw [hget, Ne, shr_word0_eq _ _ (by decide), hw] + exact h2 + · rw [hinc, Ne, shr_word0_eq _ _ (by decide), hw] + exact h1 + · refine Or.inr ⟨?_, ?_⟩ + · rw [hinc, shr_word0_eq _ _ (by decide), hw] + · show (selectorOf incSelector ++ data).size < 36 + simp [ByteArray.size_append, size_selectorOf] + omega + +end EveryMIR + +/-- **The source stage on every call of the scope**, under every oracle. -/ +theorem loweringEvery (o : SolarTV.Machine.Oracle) {c : TypeCheck.CheckedContract} + (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c SolarTV.Export.Counter.stage0 + scopeEvery := by + intro call hs obs hrun + change Source.run fuel c call = some obs at hrun + rw [source_run_every hc call hs] at hrun + cases hrun + exact mir_run_every o call hs + +/-- **The assembly stage on every call with a value below 2 ^ 256**, whatever its call data +and storage, under every oracle: the generic theorem at check_ok, which holds on every call. -/ +theorem assemblyEvery (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib SolarTV.Export.Counter.evm5 code + (fun call => call.callvalue < 2 ^ 256) := + stageAll o _ + +/-- **The counter on every call.** solar's bytecode for Counter, with the same binding to +solar's exported stages as certified, shows expectedEvery on every call of scopeEvery (inc +and get, with or without value, malformed call data and unknown selectors, from any storage) +under EthLib, through every stage of solar's pipeline. -/ +theorem certifiedEvery : + bytes = SolarTV.Export.Counter.bytecode ∧ + SolarTV.Export.Counter.Manifest.bytecodeHex = runtimeHex ∧ + SolarTV.Export.Counter.Manifest.bytecodeSha256 = runtimeSha256 ∧ + Satisfies ethLib code scopeEvery pre postEvery := by + refine ⟨bytes_exported, rfl, rfl, ?_⟩ + obtain ⟨c, hc, hspec⟩ := satisfiesEvery + exact bytecode_of_stages hspec (loweringEvery SolidCore.Refinement.Solar.W1.oracle hc) + ((SolarTV.Milestone.Counter.counter_mir_to_evmir SolidCore.Refinement.Solar.W1.oracle).mono + fun _ _ => trivial) + ((assemblyEvery SolidCore.Refinement.Solar.W1.oracle).mono fun _ h => h.1) + +/-- info: 'SolidCore.Refinement.Solar.Counter.certifiedEvery' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms certifiedEvery + +end SolidCore.Refinement.Solar.Counter diff --git a/SolidCore/Refinement/Solar/Counter/EverySeq.lean b/SolidCore/Refinement/Solar/Counter/EverySeq.lean new file mode 100644 index 00000000..2347f892 --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/EverySeq.lean @@ -0,0 +1,71 @@ +import SolidCore.Refinement.Solar.Counter.Every +import SolidCore.Refinement.ComposeSeq + +/-! +# The counter on every sequence of calls + +certifiedSeqEvery lifts certifiedEvery (Every.lean) to sequences with ComposeSeq.lean's +bytecodeSeq_of_stages_invariant: solar's bytecode for Counter finishes every finite sequence of +calls of scopeEvery (inc and get, with or without value, malformed call data and unknown +selectors) from any initial storage under EthLib, each call showing expectedEvery from the +storage it starts from and leaving exactly the storage the next call starts from (writeBack of +slot 0, carries_every), through every stage of solar's pipeline. +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Verify + +/-- What each call of a sequence meets: expectedEvery, and the next call starts from exactly its +final storage. -/ +def postEverySeq (call : Call) (obs : Observable) : Prop := + postEvery call obs ∧ Carries (writeBack [0]) call obs + +/-- Every call changes slot 0 at most, so writing slot 0 back carries its final storage. -/ +theorem carries_every (call : Call) : Carries (writeBack [0]) call (expectedEvery call) := by + have base : ∀ obs : Observable, obs.storage = slotValue call.storage → + Carries (writeBack [0]) call obs := fun obs h => + carries_writeBack (fun slot _ => by rw [h]) + (fun slot => by rw [h]; exact (Evm.Wide.slotValue_mod call.storage slot).symm) + (fun slot => by rw [h]; exact Evm.Wide.slotValue_lt _ _) + unfold expectedEvery + split_ifs with h1 h2 h3 + · exact base _ rfl + · exact base _ rfl + · unfold expectedAt + split_ifs with hof + · refine carries_writeBack (fun slot hne => ?_) (fun slot => ?_) (fun slot => ?_) + · have hs : ¬ slot % 2 ^ 256 = 0 := fun e => + hne 0 List.mem_cons_self (by rw [e, Nat.zero_mod]) + simp only [hs, ↓reduceIte] + · dsimp only + rw [Nat.mod_mod, ← Evm.Wide.slotValue_mod call.storage slot] + · by_cases hs : slot % 2 ^ 256 = 0 + · simp only [hs, ↓reduceIte] + exact hof + · simp only [hs, ↓reduceIte] + exact Evm.Wide.slotValue_lt _ _ + · exact base _ rfl + · exact base _ rfl + +/-- **The counter on every sequence of calls.** solar's runtime bytecode for Counter finishes +every finite sequence of calls of scopeEvery from any initial storage under EthLib, each call +showing expectedEvery from the storage it starts from and leaving exactly the storage the next +call starts from, through every stage of solar's pipeline. -/ +theorem certifiedSeqEvery : + SatisfiesSeq ethLib code (writeBack [0]) (within (fun _ => True) fun m => scopeEvery (m.call [])) + (fun _ _ => True) (Each postEverySeq (writeBack [0])) := by + obtain ⟨c, hc, hspec⟩ := satisfiesEvery + exact bytecodeSeq_of_stages_invariant + (Satisfies.mono hspec fun call _ _ obs h => ⟨h, by rw [h]; exact carries_every call⟩) + (loweringEvery SolidCore.Refinement.Solar.W1.oracle hc) + ((SolarTV.Milestone.Counter.counter_mir_to_evmir SolidCore.Refinement.Solar.W1.oracle).mono + fun _ _ => trivial) + ((assemblyEvery SolidCore.Refinement.Solar.W1.oracle).mono fun _ h => h.1) + (fun _ _ _ hm => ⟨hm, trivial⟩) fun _ _ _ _ _ _ => trivial + +/-- info: 'SolidCore.Refinement.Solar.Counter.certifiedSeqEvery' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms certifiedSeqEvery + +end SolidCore.Refinement.Solar.Counter diff --git a/SolidCore/Refinement/Solar/Counter/Lowering.lean b/SolidCore/Refinement/Solar/Counter/Lowering.lean new file mode 100644 index 00000000..3454eabd --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/Lowering.lean @@ -0,0 +1,263 @@ +import SolidCore.Refinement.Solar.Counter.Spec +import SolidCore.Refinement.Solar.Lowering +import counter.gen.Counter.Stage0 + +/-! +# counter: SolidCore to solar's first lowered MIR + +The source stage of Counter (Spec.lean): from SolidCore's checked contract to the first lowered +MIR module solar compiles (SolarTV.Export.Counter.stage0, after lower-evm-shaped, so +lower-abi's ABI decoding and lower-dispatch's dispatcher included), in SolarTV's lowered MIR +semantics under any oracle, on every call of inc with any argument word, no value and empty +storage. + +* mir_run_of: SolarTV's lowered MIR runs stage0 on every such call to expected d, by symbolic + execution of the module (W1Proofs.Tactic's evaluation steps): entry's callvalue check and + selector switch, the tail call into inc, its calldatasize check, the argument load, the + storage read, the addition and its overflow check, and the storage write. +* lowering: the stage, with source_run (Spec.lean) for SolidCore. +* lowering_rejects_bad: the stage is false for badStage0, stage0 with the stored word d + 1 + instead of x + d, by the counterexample inc(0). +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm.Wide +open SolidCore.Refinement.Wide SolidCore.Refinement.Evm EthLib.Execution EthLib.Execution.Evm +open SolarTV.Milestone.W1 + +section Calldata + +open SolarTV SolarTV.Machine SolarTV.EVM.Program + +theorem calldata_callOf (d : U256) : + (callOf incSelector [d]).calldata = cdOf (selectorOf incSelector) [d] := by + have := calldata_eq_cdOf incSelector [d.toNat] (by + intro x hx + simp only [List.mem_cons, List.mem_nil_iff, or_false] at hx + rcases hx with rfl + exact BitVec.isLt _) + simpa [callOf, List.map_map, Function.comp_def] using this + +theorem word0 (d : U256) : + EvmRules.Evm.shr 224 (calldataWord (callOf incSelector [d]) 0) = BitVec.ofNat 256 incSelector := by + rw [SolidCore.Refinement.Solar.W1.calldataWord_eq, calldata_callOf] + have := shr_cdOf_selectorOf incSelector [d] (by decide) + simpa [EvmRules.Evm.shr, bitwiseShr] using this + +theorem word4 (d : U256) : calldataWord (callOf incSelector [d]) 4 = d := by + rw [SolidCore.Refinement.Solar.W1.calldataWord_eq, calldata_callOf] + exact loadWord_cdOf_getD _ [d] 4 (by simp [size_selectorOf]) (by simp [size_selectorOf]) + (by simp [size_selectorOf]) + +theorem size_callOf (d : U256) : (callOf incSelector [d]).calldata.size = 36 := by + rw [calldata_callOf, size_cdOf, size_selectorOf]; rfl + +end Calldata + +section Lowering + +open SolarTV SolarTV.Machine + +/-- add_lt_self_iff with the addition's operands in the order sym_cond's wordAddComm leaves +them when the first is not the smaller term. -/ +theorem add_lt_self_iff_comm (a b : EvmRules.Word) : + (EvmRules.Evm.add b a < a) = ¬ (a.toNat + b.toNat < 2 ^ 256) := by + rw [show EvmRules.Evm.add b a = EvmRules.Evm.add a b from BitVec.add_comm b a] + exact SolidCore.Refinement.Solar.W1.add_lt_self_iff a b + +theorem mir_run_of (o : Oracle) (call : Call) (d : EvmRules.Word) (hv : call.callvalue = 0) + (hsize : call.calldata.size = 36) (h0 : EvmRules.Evm.shr 224 (calldataWord call 0) = 2166751455) + (h4 : calldataWord call 4 = d) (hst : call.storage = []) : + (MIR.Lowered.Module.run o SolarTV.Export.Counter.stage0 call 9).map + (fun r => observe call r.2 r.1) = some (expected d) := by + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte]) + have hs0 : (State.initial call).storage 0 = 0 := by simp [State.initial, hst, slotValue] + have hlt : ¬ EvmRules.Evm.add 0 d < 0 := by simp [BitVec.lt_def] + have hlt' : ¬ EvmRules.Evm.add d 0 < 0 := by simp [BitVec.lt_def] + simp only [hs0, hlt, hlt', not_false_eq_true, ↓reduceIte] + repeat (first | sym_eval | sym_cond) + simp only [observe, expected, Option.some.injEq, Observable.mk.injEq, true_and] + refine ⟨rfl, ?_⟩ + funext slot + simp only [storageOf, update] + split + · rename_i e + have h : slot % + 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 := by + simpa using congrArg BitVec.toNat e + simp [h, EvmRules.Evm.add] + · rename_i e + have h : ¬ slot % + 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 := + fun h => e (BitVec.eq_of_toNat_eq (by simpa using h)) + simp [h, State.initial, hst, slotValue] + +/-- SolarTV's lowered MIR semantics runs Counter's first lowered MIR module on every call of +inc(d), under every oracle, to the observable expected d. -/ +theorem mir_run (o : Oracle) (d : U256) : + (MIR.Lowered.moduleSem o).run SolarTV.Export.Counter.stage0 (callOf incSelector [d]) = + some (expected d) := + SolidCore.Refinement.Solar.W1.mir_sem_of_run 9 + (mir_run_of o _ d rfl (size_callOf d) (by rw [word0]; rfl) (word4 d) rfl) + +end Lowering + +/-- **The source stage of Counter**: SolidCore to solar's first lowered MIR, which includes ABI +decoding and dispatch, on every call of inc on any argument word with no value and empty +storage, under every oracle. -/ +theorem lowering (o : SolarTV.Machine.Oracle) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c SolarTV.Export.Counter.stage0 scope := by + intro call hscope obs hrun + obtain ⟨d, rfl⟩ := scope_callOf hscope + change Source.run fuel c (callOf incSelector [d]) = some obs at hrun + rw [source_run hc d] at hrun + cases hrun + exact mir_run o d + +/-! ## A known-bad lowering is rejected + +badStage0 is stage0 with inc's addition compiled as a subtraction (value 4 is x - d, not x + d): +a wrong compilation of the source. lowering_rejects_bad shows the source stage false for it, by +a mismatch of observables: on inc(1) from empty storage, SolidCore stores 1 in slot 0, while +badStage0 computes 0 - 1 = 2 ^ 256 - 1, which its overflow check (2 ^ 256 - 1 < 0) lets +through, and stores that. -/ + +/-- stage0 with inc's addition compiled as a subtraction. -/ +def badStage0 : SolarTV.MIR.Lowered.Module := + { entry := 2, + functions := [ + -- @inc + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 36]], + .branch (.value 15) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 0, .value 4]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 17) .calldataload [.const 4], + .effect (some 2) .sload [.const 0], + .pure 4 .sub [.value 2, .value 17], + .pure 5 .lt [.value 4, .value 2]], + .branch (.value 5) 1 2⟩] }, + -- @get + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 0], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 4 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 4 [(.const 0x6d4ce63c, 2), (.const 0x812600df, 3)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + + +/-- What badStage0 shows on inc(1): success, and slot 0 holding 2 ^ 256 - 1. -/ +def badObs : Observable := + { success := true, output := [], logs := [], + storage := fun slot => if slot % 2 ^ 256 = 0 then 2 ^ 256 - 1 else 0 } + +section Bad + +open SolarTV SolarTV.Machine + +theorem bad_run_of (o : Oracle) (call : Call) (hv : call.callvalue = 0) + (hsize : call.calldata.size = 36) (h0 : EvmRules.Evm.shr 224 (calldataWord call 0) = 2166751455) + (h4 : calldataWord call 4 = 1) (hst : call.storage = []) : + (MIR.Lowered.Module.run o badStage0 call 9).map (fun r => observe call r.2 r.1) = + some badObs := by + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte]) + have hs0 : (State.initial call).storage 0 = 0 := by simp [State.initial, hst, slotValue] + have hlt : ¬ EvmRules.Evm.sub 0 1 < 0 := by simp [BitVec.lt_def] + simp only [hs0, hlt, not_false_eq_true, ↓reduceIte] + repeat (first | sym_eval | sym_cond) + simp only [observe, badObs, Option.some.injEq, Observable.mk.injEq, true_and] + refine ⟨rfl, ?_⟩ + funext slot + simp only [storageOf, update] + split + · rename_i e + have h : slot % + 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 := by + simpa using congrArg BitVec.toNat e + simp [h] + all_goals decide + · rename_i e + have h : ¬ slot % + 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 := + fun h => e (BitVec.eq_of_toNat_eq (by simpa using h)) + simp [h, State.initial, hst, slotValue] + +/-- On inc(1), badStage0 stores 2 ^ 256 - 1. -/ +theorem bad_run (o : Oracle) : + (MIR.Lowered.moduleSem o).run badStage0 (callOf incSelector [1]) = some badObs := + SolidCore.Refinement.Solar.W1.mir_sem_of_run 9 + (bad_run_of o _ rfl (size_callOf 1) (by rw [word0]; rfl) (word4 1) rfl) + +end Bad + +theorem inc1_scope : scope (callOf incSelector [1]) := + ⟨⟨incSelector, [(.uint 256)]⟩, List.mem_singleton_self _, [1], rfl, by simp, rfl⟩ + +/-- The source stage is false for the known-bad lowering, under every oracle: inc(1) is in the +scope, SolidCore stores 1 on it, and badStage0 stores 2 ^ 256 - 1. -/ +theorem lowering_rejects_bad (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + ¬ Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c badStage0 scope := by + intro h + have := h _ inc1_scope (expected 1) (source_run hc 1) + rw [bad_run] at this + have hs := congrArg (fun obs => obs.storage 0) (Option.some.inj this) + simp only [badObs, expected] at hs + exact absurd hs (by decide) + +/-- info: 'SolidCore.Refinement.Solar.Counter.lowering' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms lowering + +/-- info: 'SolidCore.Refinement.Solar.Counter.lowering_rejects_bad' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms lowering_rejects_bad + +end SolidCore.Refinement.Solar.Counter diff --git a/SolidCore/Refinement/Solar/Counter/LoweringAt.lean b/SolidCore/Refinement/Solar/Counter/LoweringAt.lean new file mode 100644 index 00000000..23532788 --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/LoweringAt.lean @@ -0,0 +1,92 @@ +import SolidCore.Refinement.Solar.Counter.Lowering +import SolidCore.Refinement.Solar.Counter.SpecAt + +/-! +# counter: SolidCore to solar's first lowered MIR, from any storage + +The source stage of Counter (Lowering.lean) on `scopeAt` (SpecAt.lean): every call of inc with +any argument word and no value, from any storage `σ`, where slot 0 holds any word `x`, so the +overflow branch is reached when `x + d` does not fit. + +* mir_run_of_at: SolarTV's lowered MIR runs stage0 on every such call to `expectedAt σ d`: the + storage read of `σ`'s slot 0, the overflow check decided by whether `x + d` fits + (`W1.add_lt_self_iff`), then the write of `x + d` over `σ` or the Panic(0x11) revert that + keeps `σ`. +* loweringAt: the stage, with source_run_at (SpecAt.lean) for SolidCore. +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm.Wide +open SolidCore.Refinement.Wide SolidCore.Refinement.Evm EthLib.Execution EthLib.Execution.Evm +open SolarTV.Milestone.W1 + +section LoweringAt + +open SolarTV SolarTV.Machine + +theorem mir_run_of_at (o : Oracle) (call : Call) (d : EvmRules.Word) (hv : call.callvalue = 0) + (hsize : call.calldata.size = 36) (h0 : EvmRules.Evm.shr 224 (calldataWord call 0) = 2166751455) + (h4 : calldataWord call 4 = d) : + (MIR.Lowered.Module.run o SolarTV.Export.Counter.stage0 call 9).map + (fun r => observe call r.2 r.1) = some (expectedAt call.storage d) := by + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte]) + have hX : ((State.initial call).storage 0).toNat = slotValue call.storage 0 := by + simp only [State.initial, BitVec.toNat_ofNat] + exact Nat.mod_eq_of_lt (slotValue_lt _ _) + by_cases hof : slotValue call.storage 0 + d.toNat < 2 ^ 256 + all_goals + simp only [add_lt_self_iff_comm, hX, hof, not_true_eq_false, + not_false_eq_true, ↓reduceIte] + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte]) + · simp only [observe, expectedAt, hof, ↓reduceIte, Option.some.injEq, Observable.mk.injEq, true_and] + refine ⟨rfl, ?_⟩ + funext slot + simp only [storageOf, update] + split + · rename_i e + have h : slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 := by simpa using congrArg BitVec.toNat e + have h' : slot % 2 ^ 256 = 0 := h + simp only [h', ↓reduceIte, EvmRules.Evm.add, BitVec.toNat_add, hX] + rw [Nat.add_comm (BitVec.toNat d)] + exact Nat.mod_eq_of_lt hof + · rename_i e + have h : ¬ slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 := fun h => e (BitVec.eq_of_toNat_eq (by simpa using h)) + have h' : ¬ slot % 2 ^ 256 = 0 := h + simp only [h', ↓reduceIte, State.initial, BitVec.toNat_ofNat] + exact slotValue_mod_mod call.storage slot + · simp only [observe, expectedAt, hof, ↓reduceIte, Option.some.injEq, Observable.mk.injEq] + refine ⟨trivial, ?_, trivial, trivial⟩ + try simp only [State.initial] + decide + +/-- The same from any storage ¤σ¤: SolarTV's lowered MIR runs stage0 on inc(d) from ¤σ¤ to +¤expectedAt σ d¤, the overflow branch included. -/ +theorem mir_run_at (o : Oracle) (d : U256) (σ : List (Nat × Nat)) : + (MIR.Lowered.moduleSem o).run SolarTV.Export.Counter.stage0 + { callOf incSelector [d] with storage := σ } = some (expectedAt σ d) := + SolidCore.Refinement.Solar.W1.mir_sem_of_run 9 (mir_run_of_at o _ d rfl (size_callOf d) + (by have h := word0 d; rw [show BitVec.ofNat 256 incSelector = 2166751455 from rfl] at h; exact h) + (word4 d)) + +end LoweringAt + +/-- **The source stage of Counter from any storage**: SolidCore to solar's first lowered MIR on +every call of inc on any argument word with no value, from any storage, under every oracle. -/ +theorem loweringAt (o : SolarTV.Machine.Oracle) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c SolarTV.Export.Counter.stage0 + scopeAt := by + intro call hscope obs hrun + obtain ⟨d, σ, rfl⟩ := scopeAt_callOf hscope + change Source.run fuel c { callOf incSelector [d] with storage := σ } = some obs at hrun + rw [source_run_at hc d σ] at hrun + cases hrun + exact mir_run_at o d σ + +/-- info: 'SolidCore.Refinement.Solar.Counter.loweringAt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loweringAt + +end SolidCore.Refinement.Solar.Counter diff --git a/SolidCore/Refinement/Solar/Counter/LoweringGeneric.lean b/SolidCore/Refinement/Solar/Counter/LoweringGeneric.lean new file mode 100644 index 00000000..62193e3f --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/LoweringGeneric.lean @@ -0,0 +1,109 @@ +import SolidCore.Refinement.Generic.Value +import SolidCore.Refinement.Solar.Counter.Lowering + +/-! +# counter's source stage, from the generic source stage + +`Counter.Lowering` proves the source stage of Counter + + contract Counter { uint256 x; function inc(uint256 d) external { x += d; } + function get() external view returns (uint256) { return x; } } + +for `inc` from empty storage, by symbolic execution of this one module. The generic source stage +`Generic.stage` gives more from one evaluation by the kernel: both functions, from any storage. + +* `check_stage0`: `Generic.check` accepts solar's first lowered MIR module + `SolarTV.Export.Counter.stage0` for `Counter.coreLit` and both functions, `allFns` + (`decide +kernel`): for `inc`, the erased tree (read slot 0, add `d` with solar's overflow check, + write slot 0) and the symbolic run agree, and for `get` (return slot 0) too. +* `loweringAt`: the stage on every call of `inc` or `get` on any argument words, no value, from any + storage, under every oracle; `lowering_generic`: on `Counter.scope`, the statement of + `Counter.lowering`. +* `check_rejects_bad`: the check rejects `badStage0` (`inc` storing `d + 1`). +* `checkValue_stage0`: `Generic.checkValue` accepts stage0 (`decide +kernel`): neither function + is payable and stage0 reverts with empty output on a call of either with a value other than 0, + so `loweringAtValue` is `loweringAt` at every value below `2 ^ 256` (`Generic.stageValue`). + +No sorry, native_decide or bv_decide; the axioms are pinned below. +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open SolidCore.Refinement SolidCore.Refinement.Abi + +/-- Both functions of Counter and their parameters. -/ +def allFns : List Fn := [⟨incSelector, [(.uint 256)]⟩, ⟨getSelector, []⟩] + +/-- Every call of `inc` or `get` on any argument words, with no value, from any storage. -/ +def scopeAt : Call → Prop := fun call => ∃ σ, fullScope allFns σ call + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for both functions. -/ +theorem check_stage0 : + Generic.check fuel 16 coreLit SolarTV.Export.Counter.stage0 allFns = true := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check rejects stage0 with `inc` storing `d + 1`. -/ +theorem check_rejects_bad : Generic.check fuel 16 coreLit badStage0 allFns = false := by + decide +kernel + +/-- **The source stage of Counter from any storage, for both functions**, from the generic +source stage. -/ +theorem loweringAt (o : SolarTV.Machine.Oracle) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c SolarTV.Export.Counter.stage0 + scopeAt := by + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := Wide.deployed_of hemp + exact Generic.stage o (Verify.deployedAt_of_deployed hd) + (by rw [hk]; exact check_stage0) + +/-- **The source stage of Counter's `inc`**, from the generic source stage: the statement of +`Counter.lowering`. -/ +theorem lowering_generic (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c SolarTV.Export.Counter.stage0 + scope := by + refine SolarTV.Stage.mono (loweringAt o hc) ?_ + rintro _ ⟨fn, hfn, args, hlen, hargs, rfl⟩ + simp only [fns, List.mem_singleton] at hfn + subst hfn + exact ⟨[], _, List.mem_cons_self, args, hlen, hargs, rfl⟩ + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: neither function is payable, and stage0 reverts with empty output on +a call of either with a value other than 0. -/ +theorem checkValue_stage0 : + Generic.checkValue 16 coreLit SolarTV.Export.Counter.stage0 allFns = true := by + decide +kernel + +/-- **The source stage of Counter from any storage, for both functions, at every value**: every +call of `inc` or `get` on any argument words, with any value below `2 ^ 256`, under every +oracle. -/ +theorem loweringAtValue (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c SolarTV.Export.Counter.stage0 + (fun call => ∃ σ v, Generic.fullScopeValue allFns σ v call) := by + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := Wide.deployed_of hemp + exact Generic.stageValue o (Verify.deployedAt_of_deployed hd) + (by rw [hk]; exact check_stage0) (by rw [hk]; exact checkValue_stage0) + +/-- info: 'SolidCore.Refinement.Solar.Counter.loweringAt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loweringAt + +/-- info: 'SolidCore.Refinement.Solar.Counter.lowering_generic' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms lowering_generic + +/-- info: 'SolidCore.Refinement.Solar.Counter.checkValue_stage0' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms checkValue_stage0 + +/-- info: 'SolidCore.Refinement.Solar.Counter.loweringAtValue' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loweringAtValue + +end SolidCore.Refinement.Solar.Counter diff --git a/SolidCore/Refinement/Solar/Counter/Milestone.lean b/SolidCore/Refinement/Solar/Counter/Milestone.lean new file mode 100644 index 00000000..9ff87ed7 --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/Milestone.lean @@ -0,0 +1,174 @@ +import SolidCore.Refinement.Solar.Counter.Assembly +import SolidCore.Refinement.Solar.Counter.AssemblyAt +import SolidCore.Refinement.Solar.Counter.EverySeq +import SolidCore.Refinement.Solar.Counter.NegativeAt +import SolidCore.Refinement.Solar.Counter.NegativeValue +import SolidCore.Refinement.Solar.Counter.Sequence +import SolidCore.Refinement.Spec + +/-! +# The counter milestone: solar's bytecode for a storage counter meets its verified specification + +The contract (scripts/refinement/counter/counter.sol; solar-tv/milestone/counter/counter.sol in +solar's tree, the same file), + + contract Counter { uint256 x; function inc(uint256 d) external { x += d; } + function get() external view returns (uint256) { return x; } } + +compiled by solar (compiler sources of commit 1134e61f, which are those of 7b1f8a1b, +`-Ogas --evm-version osaka`) to the 83 bytes of runtime bytecode `code`, whose sha256 is +`runtimeSha256` (daed21b0…f6ec). `certified` states, with no hypothesis, that `code` meets +the specification of `inc` (`Spec.lean`: from storage whose slot 0 holds `x`, `inc(d)` stores +`x + d` in slot 0 and keeps every other slot when `x + d` fits in 256 bits, and otherwise reverts +with `Panic(0x11)` and keeps the storage; it never logs) on EthLib, and that `code` is the bytecode +solar exported with its stages, as the manifest records it. The specification is proved of +SolidCore's checked contract with the Loom VC generator (`satisfies`, from `vcs` and +`implements`) and carried to the bytecode through solar's pipeline (`bytecode_of_stages`), +every stage a theorem: + +* source: SolidCore to the first lowered MIR, `lower-abi` and `lower-dispatch` included + (`lowering`, Lowering.lean); +* backend: the first lowered MIR through stack scheduling and the five EVM IR passes to the + final EVM IR (`SolarTV.Milestone.Counter.counter_mir_to_evmir`, solar-tv/milestone/counter, + generated by solar-tv/milestone/certify.sh, on every call: any call data, call value and + storage); +* assembly: the final EVM IR to the bytecode on EthLib (`stage`, Assembly.lean): + `Assemble.stage_of_check`, proved once for every EVM IR program of the fragment and every code + the checker accepts (AssembleSim.lean), at `check_ok`, the kernel's evaluation of the checker + on Counter's final EVM IR and bytecode. + +## Scope + +* Syntax: this one contract. The certificate is translation validation of this compilation. +* Calls: for `certified`, one call of `inc` (selector 0x812600df) with well-formed call data, + the selector and one word below 2^256 (36 bytes; `scope`, `Abi.fullScope`). `certifiedEvery` + (Every.lean) widens this to every call of `scopeEvery`, from any storage: inc and get, each + with or without value (Value.lean: neither is payable, so a call with value is rejected and + the storage kept), call data shorter than a selector, any other selector followed by any + bytes, and inc's selector with fewer than 32 bytes after it (Calls.lean: SolidCore and the + code reject them, as Counter has no fallback). There `code` shows `expectedEvery`, what the + bytecode reads from the call: its value, its selector word and inc's argument word. Call data + that encodes inc or get with extra bytes after the encoding is outside the scope. + `certifiedSeqEvery` (EverySeq.lean) lifts it to every finite sequence of such calls from any + storage, each call starting from the storage the previous one left. +* Call value: zero, except in `certifiedEvery`. Initial storage: for `certified`, the deployed + one, empty (checked by the kernel, `shape_eq`), so `x = 0` and the overflow branch is not reached. `certifiedAt` + widens this to any initial storage: on `scopeAt` (every call of `inc` with no value from any + storage `σ`, which the call writes over the deployed one), `code` meets the same `post`, so + the overflow branch, a revert with Panic(0x11) that keeps `σ`, is reached and proved + (`satisfiesAt`; `loweringAt`, LoweringAt.lean; the backend stages, on every call; `stageAt`, + AssemblyAt.lean, the same `Assemble.stage_of_check` at the same `check_ok`, with the direct + proof `stageAt_run`, where SLOAD reads `σ`'s slot 0 from EthLib's state, as a cross-check). +* Sequences: `refinesSeq` (Sequence.lean) lifts the runs from any storage to every finite + sequence of inc calls from the deployed storage, each call starting from exactly the storage the + previous one left (Sequence.lean's `refinesSeq_of_closed`), SolidCore and the bytecode showing + the same observables; `two_calls` spells out inc(d1) then inc(d2). +* Storage: the write of slot 0 is proved on every slot of the final storage, in SolidCore, the + MIR and EVM IR semantics and EthLib (SSTORE stepped by EthLib's rules, its price included). +* EVM: EthLib at Fusaka, one message frame from 0x2000 to 0x1000 with 10M gas, metered on every + step. + +## Unverified boundaries + +As for w5 (SolidCore/Refinement/Solar/Milestone.lean): the front end that parses counter.sol +into `Source.Counter` (scripts/refinement/counter/milestone.sh regenerates it with solc 0.8.35 +and compares), the exporter's printing of solar's IR as Lean (regenerated and compared byte for +byte), and the semantics themselves. +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open SolidCore.Refinement + +/-- **The counter milestone.** solar's runtime bytecode for Counter, which is the bytecode solar +exported with its stages (byte for byte, and as the hex and sha256 its manifest records with +`-Ogas` for osaka), meets the specification of `inc` verified on SolidCore, +under EthLib on every call of the scope, through every stage of solar's pipeline. -/ +theorem certified : + bytes = SolarTV.Export.Counter.bytecode ∧ + SolarTV.Export.Counter.Manifest.bytecodeHex = runtimeHex ∧ + SolarTV.Export.Counter.Manifest.bytecodeSha256 = runtimeSha256 ∧ + SolarTV.Export.Counter.Manifest.optimization = "Gas" ∧ + SolarTV.Export.Counter.Manifest.evmVersion = "osaka" ∧ + Satisfies ethLib code scope pre post := by + refine ⟨bytes_exported, rfl, rfl, rfl, rfl, ?_⟩ + obtain ⟨c, hc, hspec⟩ := satisfies + exact bytecode_of_stages hspec (lowering W1.oracle hc) + ((SolarTV.Milestone.Counter.counter_mir_to_evmir W1.oracle).mono fun _ _ => trivial) + (stage W1.oracle) + +/-- **The counter milestone from any storage.** The same bytecode, with the same binding to +solar's exported stages, meets the specification of `inc` on every call with no value from any +storage (`scopeAt`), the overflow revert included, under EthLib, through every stage of solar's +pipeline, each proved from any storage. -/ +theorem certifiedAt : + bytes = SolarTV.Export.Counter.bytecode ∧ + SolarTV.Export.Counter.Manifest.bytecodeHex = runtimeHex ∧ + SolarTV.Export.Counter.Manifest.bytecodeSha256 = runtimeSha256 ∧ + Satisfies ethLib code scopeAt pre post := by + refine ⟨bytes_exported, rfl, rfl, ?_⟩ + obtain ⟨c, hc, hspec⟩ := satisfiesAt + exact bytecode_of_stages hspec (loweringAt W1.oracle hc) + ((SolarTV.Milestone.Counter.counter_mir_to_evmir W1.oracle).mono fun _ _ => trivial) + (stageAt W1.oracle) + +/-! ## Mutated bytecode is rejected + +Two one-byte mutations of `code`, each a wrong compilation of `inc`: `mutantAdd` has SUB (0x03) +for the ADD (0x01) at offset 42 that computes `x + d`, and `mutantStore` has SLOAD (0x54) for the +SSTORE (0x55) at offset 50 that writes it. The assembly checker's walk rejects both against the +final EVM IR (`mutantAdd_no_walk`, `mutantStore_no_walk`), and their sha256 is not the pinned one +(milestone.sh). + +A third, the overflow check dropped, needs the overflow branch, which the deployed storage never +reaches, so the stages from any storage reject it (NegativeAt.lean), each by a mismatch of +observables on inc(1) from storage whose slot 0 holds 2 ^ 256 - 1, where SolidCore and the final +EVM IR revert with Panic(0x11): `loweringAt_rejects` proves the source stage false for +stage0 with both arms of the overflow branch going to the store, and `stageAt_rejects` +the assembly stage false for `mutantNoCheck`, `code` with the check's PUSH1 0x41 JUMPI (offsets +46 to 48) replaced by POP JUMPDEST JUMPDEST, which EthLib runs to a success storing the wrapped +sum (`mutantNoCheck_run_at`); the walk rejects it too (`mutantNoCheck_no_walk`), and so does +the generic checker (`mutantNoCheck_check`, as `mutantAdd_check` and `mutantStore_check`, +Assembly.lean, for the first two). + +A fourth, `mutantValue` (NegativeValue.lean), retargets the call value check's jump (offset 2, +0x34 to 0x41) to the Panic(0x11) block, which only calls with value reach: the assembly stage on +the value scope is false for it (`assemblyValue_rejects`), by a mismatch of observables on get() +with value 1, where the final EVM IR rejects the call with empty output and EthLib runs the +mutant to a revert with Panic(0x11) (`mutantValue_run`); the walk and the generic checker +reject it too (`mutantValue_no_walk`, `mutantValue_check`). -/ + +/-- `code`'s bytes with SUB for the ADD of `x + d`. -/ +def mutantAdd : List Nat := bytes.set 42 0x03 + +/-- `code`'s bytes with SLOAD for the SSTORE of slot 0. -/ +def mutantStore : List Nat := bytes.set 50 0x54 + +theorem bytes_add : bytes[42]? = some 0x01 := by decide +theorem bytes_store : bytes[50]? = some 0x55 := by decide + +theorem mutantAdd_no_walk : + SolarTV.Assembly.walk mutantAdd SolarTV.Milestone.Counter.offset 0 + SolarTV.Milestone.Counter.items = none := by decide + +theorem mutantStore_no_walk : + SolarTV.Assembly.walk mutantStore SolarTV.Milestone.Counter.offset 0 + SolarTV.Milestone.Counter.items = none := by decide + +/-- info: 'SolidCore.Refinement.Solar.Counter.certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified + +/-- info: 'SolidCore.Refinement.Solar.Counter.certifiedAt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedAt + +/-- info: 'SolidCore.Refinement.Solar.Counter.certifiedEvery' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedEvery + +/-- info: 'SolidCore.Refinement.Solar.Counter.certifiedSeqEvery' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedSeqEvery + +end SolidCore.Refinement.Solar.Counter diff --git a/SolidCore/Refinement/Solar/Counter/NegativeAt.lean b/SolidCore/Refinement/Solar/Counter/NegativeAt.lean new file mode 100644 index 00000000..349c7924 --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/NegativeAt.lean @@ -0,0 +1,252 @@ +import SolidCore.Refinement.Solar.Counter.AssemblyAt + +/-! +# counter: a dropped overflow check is rejected by the source and assembly stages + +From the deployed storage the overflow branch of inc is never reached (slot 0 holds 0), so a +compilation that drops the overflow check passes every stage proved on scope. From any +storage (scopeAt) it is reached, and both stages proved there reject such a compilation by a +mismatch of observables on the call inc(1) from storage whose slot 0 holds 2 ^ 256 - 1, where +SolidCore reverts with Panic(0x11) (expectedAt σMax 1): + +* loweringAt_rejects: the source stage is false for noCheckStage0, stage0 with both + arms of the overflow branch going to the store, which stores 0 and succeeds. +* stageAt_rejects: the assembly stage is false for mutantNoCheck, solar's bytecode + with the overflow check's PUSH1 0x41 JUMPI (offsets 46 to 48) replaced by POP JUMPDEST + JUMPDEST, so the condition is dropped and the addition's wrapped sum is stored: EthLib runs it + to a success storing x + d mod 2 ^ 256 from any storage (mutantNoCheck_run_at), every opcode + stepped by EthLib's program logic, while the final EVM IR reverts (evmir_run_at). +* mutantNoCheck_no_walk: the assembly checker's walk rejects the same bytecode, and + mutantNoCheck_check the generic checker (Assemble.check, whose acceptance stage_of_check turns + into the stage) too. +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm.Wide +open SolidCore.Refinement.Wide SolidCore.Refinement.Evm EthLib.Execution EthLib.Execution.Evm +open SolarTV.Milestone.W1 + +/-- Storage whose slot 0 holds the largest word, so any nonzero addition overflows. -/ +def σMax : List (Nat × Nat) := [(0, 2 ^ 256 - 1)] + +theorem scopeAt_σMax : scopeAt { callOf incSelector [1] with storage := σMax } := + ⟨σMax, ⟨incSelector, [(.uint 256)]⟩, List.mem_singleton_self _, [1], rfl, by simp, rfl⟩ + +/-- SolidCore's run of inc(1) from σMax fails: the sum overflows. -/ +theorem expectedAt_σMax : (expectedAt σMax 1).success = false := by + simp only [expectedAt, σMax] + decide + +/-! ## The source stage -/ + +/-- stage0 with the overflow check dropped: both arms of inc's overflow branch go to the store. -/ +def noCheckStage0 : SolarTV.MIR.Lowered.Module := + { entry := 2, + functions := [ + -- @inc + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 36]], + .branch (.value 15) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .sstore [.const 0, .value 4]], + .stop⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 17) .calldataload [.const 4], + .effect (some 2) .sload [.const 0], + .pure 4 .add [.value 2, .value 17], + .pure 5 .lt [.value 4, .value 2]], + .branch (.value 5) 2 2⟩] }, + -- @get + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 2) .sload [.const 0], + .effect none .mstore [.const 0, .value 2]], + .ret (.const 0) (.const 32)⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 4 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 4 [(.const 0x6d4ce63c, 2), (.const 0x812600df, 3)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 1 []⟩, + -- bb3 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb4 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +/-- What a run of inc(d) from σ shows without the overflow check: success, and slot 0 holding +the wrapped sum. -/ +def wrappedAt (σ : List (Nat × Nat)) (d : U256) : Observable := + { success := true, output := [], logs := [], + storage := fun slot => + if slot % 2 ^ 256 = 0 then (slotValue σ 0 + d.toNat) % 2 ^ 256 else slotValue σ slot } + +section NoCheck + +open SolarTV SolarTV.Machine + +theorem noCheck_run_of (o : Oracle) (call : Call) (d : EvmRules.Word) (hv : call.callvalue = 0) + (hsize : call.calldata.size = 36) (h0 : EvmRules.Evm.shr 224 (calldataWord call 0) = 2166751455) + (h4 : calldataWord call 4 = d) : + (MIR.Lowered.Module.run o noCheckStage0 call 9).map + (fun r => observe call r.2 r.1) = some (wrappedAt call.storage d) := by + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte, ite_self]) + have hX : ((State.initial call).storage 0).toNat = slotValue call.storage 0 := by + simp only [State.initial, BitVec.toNat_ofNat] + exact Nat.mod_eq_of_lt (slotValue_lt _ _) + simp only [observe, wrappedAt, Option.some.injEq, Observable.mk.injEq, true_and] + refine ⟨rfl, ?_⟩ + funext slot + simp only [storageOf, update] + split + · rename_i e + have h : slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 := by simpa using congrArg BitVec.toNat e + have h' : slot % 2 ^ 256 = 0 := h + simp only [h', ↓reduceIte, EvmRules.Evm.add, BitVec.toNat_add, hX] + rw [Nat.add_comm (BitVec.toNat d)] + · rename_i e + have h : ¬ slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 := fun h => e (BitVec.eq_of_toNat_eq (by simpa using h)) + have h' : ¬ slot % 2 ^ 256 = 0 := h + simp only [h', ↓reduceIte, State.initial, BitVec.toNat_ofNat] + exact slotValue_mod_mod call.storage slot + +theorem noCheck_run_at (o : Oracle) (d : U256) (σ : List (Nat × Nat)) : + (MIR.Lowered.moduleSem o).run noCheckStage0 + { callOf incSelector [d] with storage := σ } = some (wrappedAt σ d) := + SolidCore.Refinement.Solar.W1.mir_sem_of_run 9 (noCheck_run_of o _ d rfl (size_callOf d) + (by have h := word0 d; rw [show BitVec.ofNat 256 incSelector = 2166751455 from rfl] at h; exact h) + (word4 d)) + +end NoCheck + +/-- The source stage from any storage is false for the lowering without the overflow check, +under every oracle: on inc(1) from σMax SolidCore reverts, and noCheckStage0 succeeds. -/ +theorem loweringAt_rejects (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + ¬ Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c noCheckStage0 scopeAt := by + intro h + have := h _ scopeAt_σMax _ (source_run_at hc 1 σMax) + rw [noCheck_run_at] at this + have hs := congrArg (fun obs : Observable => obs.success) (Option.some.inj this) + rw [expectedAt_σMax] at hs + exact absurd hs (by simp [wrappedAt]) + +/-- info: 'SolidCore.Refinement.Solar.Counter.loweringAt_rejects' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms loweringAt_rejects + + +/-! ## The assembly stage -/ + +/-- solar's bytecode with the overflow check's PUSH1 0x41 JUMPI (offsets 46 to 48) replaced by +POP JUMPDEST JUMPDEST: the overflow condition is popped and the wrapped sum stored, as big-endian +number. -/ +def mutantNoCheckNat : Nat := + 0x346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f546004358101908110505b5b5f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd + +/-- The bytecode with the overflow check dropped, 83 bytes like solar's. -/ +def mutantNoCheck : ByteArray := + EthLib.Execution.Evm.Logic.NatCode.ofNat mutantNoCheckNat runtimeSize + +/-- The mutant is solar's bytecode with offsets 46, 47 and 48 (PUSH1 0x41 JUMPI) replaced by +POP JUMPDEST JUMPDEST, and is otherwise the same. -/ +theorem mutantNoCheck_bytes : + mutantNoCheck.data.toList.map (·.toNat) = ((bytes.set 46 0x50).set 47 0x5b).set 48 0x5b ∧ + bytes[46]? = some 0x60 ∧ bytes[47]? = some 0x41 ∧ bytes[48]? = some 0x57 := by + decide + +/-- The assembly checker's walk rejects the mutant against the final EVM IR. -/ +theorem mutantNoCheck_no_walk : + SolarTV.Assembly.walk (mutantNoCheck.data.toList.map (·.toNat)) SolarTV.Milestone.Counter.offset 0 + SolarTV.Milestone.Counter.items = none := by decide + +set_option maxRecDepth 100000 in +/-- The generic checker rejects the mutant: its walk decodes POP where the program has the +overflow check's PUSH1. -/ +theorem mutantNoCheck_check : + Assemble.check SolarTV.Export.Counter.evm5 mutantNoCheck cert = false := by + decide +kernel + +/-- info: 'SolidCore.Refinement.Solar.Counter.mutantNoCheck_check' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms mutantNoCheck_check + +section TargetNoCheck + +open EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Symex SolidCore.Refinement.Evm.Logic + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- EthLib runs the mutant on every call of inc(d) from any storage σ to a success that stores +the wrapped sum x + d mod 2 ^ 256 in slot 0, every opcode stepped by EthLib's program logic from +pc 0 with 10M gas. -/ +theorem mutantNoCheck_run_at (d : U256) (σ : List (Nat × Nat)) : + Target.run mutantNoCheck { callOf incSelector [d] with storage := σ } = some (wrappedAt σ d) := by + refine run_of_postS_at mutantNoCheck incSelector [d] σ _ rfl (fun h => by cases h) ?_ + intro msg hv hd hstat htgt + simp only [callAt] + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + simp only [incSelector] at hd + have hval : (BitVec.ofNat 256 (slotValue σ 0) + d).toNat = (slotValue σ 0 + d.toNat) % 2 ^ 256 := by + rw [BitVec.toNat_add, BitVec.toNat_ofNat, Nat.mod_eq_of_lt (a := slotValue σ 0) (slotValue_lt σ 0)] + unfold wrappedAt + repeat counter_one_at [mutantNoCheck, mutantNoCheckNat, runtimeSize, incSelector] [hd, hv] hfork hstat htgt hval + +end TargetNoCheck + +/-- The assembly stage from any storage is false for the bytecode without the overflow check, +under every oracle: on inc(1) from σMax the final EVM IR reverts with Panic(0x11), and EthLib +runs the mutant to a success. -/ +theorem stageAt_rejects (o : SolarTV.Machine.Oracle) : + ¬ SolarTV.Stage (SolarTV.evmirSem o) ethLib SolarTV.Export.Counter.evm5 mutantNoCheck scopeAt := by + intro h + have := h _ scopeAt_σMax _ (evmir_run_at o 1 σMax) + change Target.run mutantNoCheck _ = _ at this + rw [mutantNoCheck_run_at] at this + have hs := congrArg (fun obs : Observable => obs.success) (Option.some.inj this) + have he : (expectedAt σMax 1#256).success = false := expectedAt_σMax + exact absurd hs (by simp [wrappedAt, he]) + +/-- info: 'SolidCore.Refinement.Solar.Counter.mutantNoCheck_run_at' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms mutantNoCheck_run_at + +/-- info: 'SolidCore.Refinement.Solar.Counter.stageAt_rejects' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stageAt_rejects + +end SolidCore.Refinement.Solar.Counter diff --git a/SolidCore/Refinement/Solar/Counter/NegativeValue.lean b/SolidCore/Refinement/Solar/Counter/NegativeValue.lean new file mode 100644 index 00000000..c4af6e15 --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/NegativeValue.lean @@ -0,0 +1,139 @@ +import SolidCore.Refinement.Solar.Counter.Value +import SolidCore.Refinement.Solar.Counter.Assembly + +/-! +# counter: a wrong call value check in the bytecode is rejected + +mutantValue is solar's bytecode with the call value check's jump target (offset 2, the PUSH1 +operand 0x34 of CALLVALUE PUSH1 0x34 JUMPI) changed to 0x41, the Panic(0x11) block: on a call +with no value it behaves as solar's bytecode, and on a call with value it reverts with +Panic(0x11) instead of empty output. The assembly stage on the value scope (Value.lean) is false +for it by a mismatch of observables: on get() with value 1 from empty storage the final EVM IR +rejects the call with empty output, while EthLib runs the mutant to a revert with Panic(0x11) +(mutantValue_run, every opcode stepped by EthLib's program logic after the move of the value). +The assembly checker's walk and the generic checker reject it too (mutantValue_no_walk, +mutantValue_check), and its sha256 is not the pinned one (milestone.sh). +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm +open SolidCore.Refinement.Evm.Symex SolidCore.Refinement.Evm.Logic SolidCore.Refinement.Evm.Wide + +/-- solar's bytecode with the call value check jumping to the Panic(0x11) block (offset 2, 0x34 +to 0x41), as big-endian number. -/ +def mutantValueNat : Nat := + 0x346041575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd + +/-- The bytecode with the call value check retargeted, 83 bytes like solar's. -/ +def mutantValue : ByteArray := + EthLib.Execution.Evm.Logic.NatCode.ofNat mutantValueNat runtimeSize + +/-- The mutant is solar's bytecode with offset 2 (the value check's jump target 0x34) set to +0x41, and is otherwise the same. -/ +theorem mutantValue_bytes : + mutantValue.data.toList.map (·.toNat) = bytes.set 2 0x41 ∧ bytes[2]? = some 0x34 := by + decide + +/-- The assembly checker's walk rejects the mutant against the final EVM IR. -/ +theorem mutantValue_no_walk : + SolarTV.Assembly.walk (mutantValue.data.toList.map (·.toNat)) + SolarTV.Milestone.Counter.offset 0 SolarTV.Milestone.Counter.items = none := by decide + +set_option maxRecDepth 100000 in +/-- The generic checker rejects the mutant: the value check's PUSH1 pushes 0x41, not the +offset of the block it jumps to in the final EVM IR. -/ +theorem mutantValue_check : + Assemble.check SolarTV.Export.Counter.evm5 mutantValue cert = false := by + decide +kernel + +/-- What the mutant shows on a call with value from the storage σ: a revert with Panic(0x11) +that keeps σ. -/ +def panicked (σ : List (Nat × Nat)) : Observable := + { success := false, output := Verify.panic 0x11, logs := [], storage := slotValue σ } + +/-- A message that moves nonzero value, to code that is no precompile, whose frame fails as +PostS X says from every state: once the move of its value succeeds, processMessage at Fusaka +returns the revert with X's output. -/ +theorem processMessage_postS_value {c : ByteArray} (message : Message .fusaka) + (hcode : message.code = c) (htr : message.shouldTransferValue = true) + (hv : message.value ≠ 0) (hpre : precompileAddress .fusaka message = none) (X : Observable) + (hX : X.success = false) + (h : ∀ st ss, Spec .fusaka (At c message 0 [] .empty message.gas st ss .empty) (PostS X ss)) + (st st' : State.TransactionState) (ss : Substate) + (hmove : st.moveEther .fusaka message.caller message.currentTarget message.value = .ok st') : + ∃ evm, processMessage (Meter := Nat) .fusaka message st ss = .ok evm ∧ + evm.1.error = some .revert ∧ evm.1.output.toList.map (·.toNat) = X.output := by + rw [processMessage] + have hss : startState .fusaka message st = st := by + simp [startState, show ¬ (Fork.fusaka < Fork.paris) by decide] + simp only [hss, hpre, htr, ne_eq, hv, not_false_eq_true, and_self, ↓reduceIte, hmove] + simp only [pure, Except.pure, bind, Except.bind, Except.mapError] + split + · rename_i e hr + obtain ⟨after, h', -⟩ := runFrame_of_spec hcode (h _ _) hr + cases h' + · rename_i after hr + obtain ⟨after', h', -, herr, hout, -⟩ := runFrame_of_spec hcode (h _ _) hr + cases h' + simp only [errorOf, hX, Bool.false_eq_true, ↓reduceIte] at herr + refine ⟨_, rfl, ?_, ?_⟩ + · simp only [rollbackOnError]; split <;> simp [herr] + · simp only [rollbackOnError]; split <;> exact hout + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- The mutant's frame on every message with nonzero value, from every state: CALLVALUE PUSH1 +0x41 JUMPI jumps to the Panic(0x11) block, which reverts with Panic(0x11). -/ +theorem mutantValue_frame (msg : Message .fusaka) (hv : msg.value ≠ 0) + (st : State.TransactionState) (ss : Substate) : + Spec .fusaka (At mutantValue msg 0 [] .empty 10000000 st ss .empty) + (PostS (panicked []) ss) := by + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + unfold panicked + repeat counter_one_at [mutantValue, mutantValueNat, runtimeSize] [hv] hfork hfork hfork hfork + +/-- EthLib runs the mutant on every call with nonzero value, on any call data and from any +storage σ, to a revert with Panic(0x11) that keeps σ. -/ +theorem mutantValue_run (cd : ByteArray) (v : Nat) (hv0 : v ≠ 0) (hv : v < 2 ^ 256) + (σ : List (Nat × Nat)) : + Target.run mutantValue { calldata := cd, callvalue := v, storage := σ } = + some (panicked σ) := by + obtain ⟨st', hmove⟩ := + W1.moveEther_preState mutantValue { calldata := cd, callvalue := v, storage := σ } hv + obtain ⟨evm, hr, herr, hout⟩ := processMessage_postS_value + (Target.message mutantValue { calldata := cd, callvalue := v, storage := σ }) rfl rfl + (W1.ofNat_ne_zero hv0 hv) (precompileAddress_message mutantValue _) (panicked []) rfl + (fun st ss => mutantValue_frame _ (W1.ofNat_ne_zero hv0 hv) st ss) _ st' Substate.empty hmove + simp only [panicked] at hout + simpa [Target.run, hr, herr, panicked] using hout + +/-- The assembly stage on the value scope is false for the mutant, under every oracle: on get() +with value 1 from empty storage the final EVM IR rejects the call with empty output, and EthLib +runs the mutant to a revert with Panic(0x11). -/ +theorem assemblyValue_rejects (o : SolarTV.Machine.Oracle) : + ¬ SolarTV.Stage (SolarTV.evmirSem o) ethLib SolarTV.Export.Counter.evm5 mutantValue + scopeValue := by + intro h + have hs : scopeValue { calldata := (callOf getSelector []).calldata, callvalue := 1, storage := [] } := + ⟨getSelector, [], 1, [], Or.inr ⟨rfl, rfl⟩, by decide, by decide, rfl⟩ + have he := SolarTV.Milestone.Counter.counter_mir_to_evmir o _ trivial _ + (mir_run_value o (callOf getSelector []).calldata 1 (by decide) (by decide) []) + have := h _ hs _ he + change Target.run mutantValue _ = _ at this + rw [mutantValue_run _ 1 (by decide) (by decide) []] at this + have ho := congrArg (fun obs : Observable => obs.output) (Option.some.inj this) + simp only [panicked, Abi.rejected, Verify.panic, Verify.word] at ho + have hl := congrArg List.length ho + simp [natToBytes_length] at hl + +/-- info: 'SolidCore.Refinement.Solar.Counter.mutantValue_check' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms mutantValue_check + +/-- info: 'SolidCore.Refinement.Solar.Counter.assemblyValue_rejects' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms assemblyValue_rejects + +end SolidCore.Refinement.Solar.Counter diff --git a/SolidCore/Refinement/Solar/Counter/Sequence.lean b/SolidCore/Refinement/Solar/Counter/Sequence.lean new file mode 100644 index 00000000..a6b953b7 --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/Sequence.lean @@ -0,0 +1,121 @@ +import SolidCore.Refinement.Solar.Counter.AssemblyAt +import SolidCore.Refinement.Sequence + +/-! +# counter: every sequence of inc calls, storage carried between calls + +A deployed Counter sees a sequence of calls, each from the storage the previous one left. +refinesSeq states that SolidCore's checked Counter and solar's bytecode show the same +observables on every finite sequence of inc calls (any argument words, no value) from the +deployed storage, each call starting from the previous call's final storage exactly: the +lifting theorem of SolidCore/Refinement/Sequence.lean (refinesSeq_of_closed) applied to the +source and assembly runs from any storage (source_run_at, target_run_at), which both give +expectedAt σ d. + +* next obs, the storage list the next call starts from, is slot 0's word: [(0, obs.storage 0)]. +* onlySlot0 σ: σ holds nothing outside slot 0. The deployed storage [] does, and inc keeps it + (it writes only slot 0, or reverts and keeps σ), and on it next is exact: it reads back as the + whole final storage (exact_next). +* two_calls: the case of two calls spelled out, inc(d1) then inc(d2) from the deployed storage: + both sides show expectedAt [] d1, then expectedAt [(0, d1)] d2, the second call seeing slot 0 + holding d1. +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm.Wide + +/-- The storage list the next call starts from: slot 0's word. -/ +def next (obs : Observable) : List (Nat × Nat) := [(0, obs.storage 0)] + +/-- The messages of the sequences: inc on any argument word, with no value. -/ +def incMsg : Msg → Prop := fun m => ∃ d : U256, m = ⟨(callOf incSelector [d]).calldata, 0⟩ + +/-- Storage that holds nothing outside slot 0. -/ +def onlySlot0 (σ : List (Nat × Nat)) : Prop := ∀ slot, slot % 2 ^ 256 ≠ 0 → slotValue σ slot = 0 + +theorem slotValue_next (w slot : Nat) : + slotValue [(0, w)] slot = if slot % 2 ^ 256 = 0 then w % 2 ^ 256 else 0 := by + show (if 0 % 2 ^ 256 = slot % 2 ^ 256 then w % 2 ^ 256 else 0) = _ + by_cases h : slot % 2 ^ 256 = 0 + · rw [ite_eq_left (by rw [h, Nat.zero_mod]), ite_eq_left h] + · rw [ite_eq_right (by rw [Nat.zero_mod]; exact Ne.symm h), ite_eq_right h] + +theorem onlySlot0_next (obs : Observable) : onlySlot0 (next obs) := by + intro slot h + rw [next, slotValue_next, ite_eq_right h] + +/-- From storage with nothing outside slot 0, the storage list next gives after inc reads back +as exactly the final storage. -/ +theorem exact_next {σ : List (Nat × Nat)} (hσ : onlySlot0 σ) (d : U256) : + Exact next (expectedAt σ d) := by + funext slot + rw [next, slotValue_next] + have hlt := slotValue_lt σ 0 + have hmod := SolidCore.Refinement.Evm.Wide.slotValue_mod σ slot + have hz := hσ slot + unfold expectedAt + by_cases hof : slotValue σ 0 + d.toNat < 2 ^ 256 <;> + by_cases h : slot % 2 ^ 256 = 0 <;> + simp only [Nat.reducePow] at hof h hlt hmod hz ⊢ + · simp only [hof, h, ↓reduceIte, Nat.zero_mod] + exact Nat.mod_eq_of_lt hof + · simp only [hof, h, ↓reduceIte] + exact (hz h).symm + · simp only [hof, h, ↓reduceIte] + rw [Nat.mod_eq_of_lt hlt, ← hmod, h] + · simp only [hof, h, ↓reduceIte] + exact (hz h).symm + +theorem onlySlot0_nil : onlySlot0 [] := fun _ _ => rfl + +/-- **The counter on every sequence of inc calls**: from the deployed storage, SolidCore's +checked Counter and solar's bytecode on EthLib finish every finite sequence of inc calls with +the same observables, each call starting from exactly the storage the previous one left. -/ +theorem refinesSeq : ∃ c, contract? = .ok c ∧ RefinesSeq fuel c code next [] incMsg := by + obtain ⟨c, hc, -⟩ := satisfiesAt + refine ⟨c, hc, refinesSeq_of_closed onlySlot0 onlySlot0_nil ?_ ?_⟩ + · rintro σ - call ⟨m, ⟨d, rfl⟩, rfl⟩ + exact ⟨expectedAt σ d, source_run_at hc d σ, target_run_at d σ⟩ + · rintro σ hσ m ⟨d, rfl⟩ obs hrun + have h := target_run_at d σ + change Target.run code { callOf incSelector [d] with storage := σ } = some obs at hrun + rw [h] at hrun + cases hrun + exact ⟨exact_next hσ d, onlySlot0_next _⟩ + +/-- **Two calls**, spelled out: inc(d1) then inc(d2) from the deployed storage, on SolidCore and +on solar's bytecode, the second call starting from slot 0 holding d1. -/ +theorem two_calls {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) + (d1 d2 : U256) : + let ms : List Msg := [⟨(callOf incSelector [d1]).calldata, 0⟩, ⟨(callOf incSelector [d2]).calldata, 0⟩] + let obss := [expected d1, expectedAt [(0, d1.toNat)] d2] + runSeq (Source.run fuel c) next [] ms = some obss ∧ + runSeq (Target.run code) next [] ms = some obss := by + have hn : next (expected d1) = [(0, d1.toNat)] := by + simp [next, expected] + have hs1 : Source.run fuel c ⟨(callOf incSelector [d1]).calldata, 0, []⟩ = some (expected d1) := by + have h := source_run_at hc d1 [] + rwa [expectedAt_nil] at h + have ht1 : Target.run code ⟨(callOf incSelector [d1]).calldata, 0, []⟩ = some (expected d1) := by + have h := target_run_at d1 [] + rwa [expectedAt_nil] at h + have hs2 : Source.run fuel c ⟨(callOf incSelector [d2]).calldata, 0, next (expected d1)⟩ = + some (expectedAt [(0, d1.toNat)] d2) := by + rw [hn] + exact source_run_at hc d2 _ + have ht2 : Target.run code ⟨(callOf incSelector [d2]).calldata, 0, next (expected d1)⟩ = + some (expectedAt [(0, d1.toNat)] d2) := by + rw [hn] + exact target_run_at d2 _ + simp only [runSeq, Msg.call, hs1, hs2, ht1, ht2, Option.map_some, and_self] + +/-- info: 'SolidCore.Refinement.Solar.Counter.refinesSeq' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms refinesSeq + +/-- info: 'SolidCore.Refinement.Solar.Counter.two_calls' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms two_calls + +end SolidCore.Refinement.Solar.Counter diff --git a/SolidCore/Refinement/Solar/Counter/Sequences.lean b/SolidCore/Refinement/Solar/Counter/Sequences.lean new file mode 100644 index 00000000..fa0e5bb3 --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/Sequences.lean @@ -0,0 +1,168 @@ +import SolidCore.Refinement.Solar.Counter.Milestone +import SolidCore.Refinement.Solar.Sequences + +/-! +# The counter milestone on sequences of calls + +`certifiedAt` (Milestone.lean, from SpecAt.lean, LoweringAt.lean and AssemblyAt.lean) proves Counter's `inc` through every stage of solar's pipeline +from any storage, and every stage is proved from any storage, so the milestone lifts to every +finite sequence of calls (`bytecodeSeq_of_stages_invariant`, ComposeSeq.lean). Each call starts from +the storage the previous one left: the carry is `writeBack [0]`, the previous call's storage list with +slot 0 overwritten by its final word, which reads back as exactly the previous call's final +storage because `inc` changes no other slot (`carries_of_post`). + +* `certifiedSeq`: from any initial storage, solar's bytecode finishes every sequence of calls of + `inc` (any argument words below `2 ^ 256`, no value) under EthLib, and every call meets `post` + from the storage it starts from and leaves exactly the storage the next call starts from. +* `certifiedAt_single`: its one-call case is `certifiedAt` (`satisfiesSeq_single_iff`). +* `total`: a consequence on the bytecode itself: from any storage whose slot 0 holds `x`, the + calls `inc(d₁) … inc(dₙ)` all succeed when `x + d₁ + … + dₙ` fits in 256 bits, and the last + leaves slot 0 holding that sum. +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Verify + +/-- What each call of a sequence of `inc` meets: `post`, and the next call starts from exactly its +final storage. -/ +def postSeq (call : Call) (obs : Observable) : Prop := + post call obs ∧ Carries (writeBack [0]) call obs + +/-- The final storage `post` describes, slot by slot: slot 0 holds `x + d` when it fits, and every +other slot, or every slot on overflow, is the call's. -/ +theorem storage_of_post {call : Call} {obs : Observable} (h : post call obs) (slot : Nat) : + obs.storage slot = + if slotValue call.storage 0 + (argWords 1 call).getD 0 0 < 2 ^ 256 ∧ slot % 2 ^ 256 = 0 then + slotValue call.storage 0 + (argWords 1 call).getD 0 0 + else slotValue call.storage slot := by + simp only [post] at h + obtain ⟨-, h⟩ := h + split at h + · rename_i hf + rw [h.2.2 slot] + by_cases hs : slot % 2 ^ 256 = 0 + · simp only [hs, hf, and_self, ↓reduceIte] + · simp only [hs, and_false, ↓reduceIte] + · rename_i hf + rw [h.2.2 slot] + simp only [hf, false_and, ↓reduceIte] + +/-- A call that meets `post` is carried exactly by `writeBack [0]`: it changes slot 0 only. -/ +theorem carries_of_post {call : Call} {obs : Observable} (h : post call obs) : + Carries (writeBack [0]) call obs := by + refine carries_writeBack (fun slot hne => ?_) (fun slot => ?_) (fun slot => ?_) + · have hs : ¬ slot % 2 ^ 256 = 0 := fun e => + hne 0 List.mem_cons_self (by rw [e, Nat.zero_mod]) + rw [storage_of_post h slot] + simp only [hs, and_false, ↓reduceIte] + · rw [storage_of_post h slot, storage_of_post h (slot % 2 ^ 256), Nat.mod_mod, + Evm.Wide.slotValue_mod call.storage slot] + · rw [storage_of_post h slot] + split + · rename_i hc + exact hc.1 + · exact Evm.Wide.slotValue_lt _ _ + +/-- **The counter milestone on sequences.** solar's runtime bytecode for Counter finishes every +finite sequence of calls of `inc` (any argument words, no value) from any initial storage under +EthLib, each call meeting `inc`'s specification (`post`) from the storage it starts from and leaving +exactly the storage the next call starts from, through every stage of solar's pipeline, each +proved from any storage. -/ +theorem certifiedSeq : + SatisfiesSeq ethLib code (writeBack [0]) (within (fun _ => True) (fullMsgs fns)) + (fun _ _ => True) (Each postSeq (writeBack [0])) := by + obtain ⟨c, hc, hspec⟩ := satisfiesAt + exact bytecodeSeq_of_stages_invariant + (Satisfies.mono hspec fun _ _ _ _ h => ⟨h, carries_of_post h⟩) (loweringAt W1.oracle hc) + ((SolarTV.Milestone.Counter.counter_mir_to_evmir W1.oracle).mono fun _ _ => trivial) + (stageAt W1.oracle) (fun σ _ _ hm => ⟨⟨σ, fullScope_call hm σ⟩, trivial⟩) + fun _ _ _ _ _ _ => trivial + +/-- The one-call milestone from any storage is `certifiedSeq`'s length-1 case: `certifiedAt`'s +statement on the sequences of one message (`satisfiesSeq_single_iff`). -/ +theorem certifiedAt_single : + SatisfiesSeq ethLib code (writeBack [0]) (single scopeAt) (singlePre pre) (singlePost post) := + (satisfiesSeq_single_iff _).mpr certifiedAt.2.2.2 + +/-! ## The total -/ + +/-- The message of `inc(d)`, with no value. -/ +def incMsgOf (d : Nat) : Msg := { calldata := calldata incSelector [d], callvalue := 0 } + +theorem fullMsgs_incMsgOf {d : Nat} (hd : d < 2 ^ 256) : fullMsgs fns (incMsgOf d) := + ⟨_, List.mem_singleton_self _, [d], rfl, by simpa using hd, rfl⟩ + +theorem argWords_incMsgOf {d : Nat} (hd : d < 2 ^ 256) (σ : List (Nat × Nat)) : + argWords 1 ((incMsgOf d).call σ) = [d] := + Verify.argWords_calldata incSelector [d] (by simpa using hd) 0 σ + +/-- Along a run that meets `postSeq` on every call, the calls `inc(d₁) … inc(dₙ)` from a storage whose +slot 0 holds `x` all succeed when `x + d₁ + … + dₙ` fits, and the last leaves slot 0 holding it. -/ +theorem total_of_each : + ∀ (ds : List Nat) (σ : List (Nat × Nat)) (obss : List Observable), + Each postSeq (writeBack [0]) σ (ds.map incMsgOf) obss → (∀ d ∈ ds, d < 2 ^ 256) → + slotValue σ 0 + ds.sum < 2 ^ 256 → + (∀ obs ∈ obss, obs.success = true) ∧ + ∀ obs ∈ obss.getLast?, obs.storage 0 = slotValue σ 0 + ds.sum + | [], _, [], _, _, _ => ⟨by simp, by simp⟩ + | d :: ds, σ, obs :: os, ⟨⟨hpost, hcarry⟩, hrest⟩, hds, hsum => by + have hd : d < 2 ^ 256 := hds d List.mem_cons_self + have hw := argWords_incMsgOf hd σ + have hcall : ((incMsgOf d).call σ).storage = σ := rfl + have hfit : slotValue σ 0 + d < 2 ^ 256 := by simp only [List.sum_cons] at hsum; omega + have hpost' := hpost + simp only [post, hw, hcall, List.getD_cons_zero, hfit, ↓reduceIte] at hpost' + have h0 : obs.storage 0 = slotValue σ 0 + d := by + rw [hpost'.2.2.2 0] + simp + have hσ : slotValue (writeBack [0] ((incMsgOf d).call σ) obs) 0 = slotValue σ 0 + d := by + rw [hcarry, h0] + obtain ⟨hs, hl⟩ := total_of_each ds _ os hrest (fun d' h' => hds d' (List.mem_cons_of_mem _ h')) + (by rw [hσ]; simp only [List.sum_cons] at hsum; omega) + refine ⟨?_, ?_⟩ + · intro o ho + rcases List.mem_cons.mp ho with rfl | ho + · exact hpost'.2.1 + · exact hs o ho + · intro o ho + cases os with + | nil => + cases ds with + | nil => + simp only [List.getLast?_singleton, Option.mem_def, Option.some.injEq] at ho + subst ho + simp [h0] + | cons _ _ => exact hrest.elim + | cons o' os' => + rw [List.getLast?_cons_cons] at ho + rw [hl o ho, hσ, List.sum_cons] + omega + +/-- **The total.** From any storage `σ` whose slot 0 holds `x`, solar's bytecode for Counter runs the +calls `inc(d₁) … inc(dₙ)` one after the other under EthLib, each from the storage the previous one +left, and when `x + d₁ + … + dₙ` fits in 256 bits every call succeeds and the last leaves slot 0 +holding that sum. -/ +theorem total (ds : List Nat) (σ : List (Nat × Nat)) (hds : ∀ d ∈ ds, d < 2 ^ 256) + (hsum : slotValue σ 0 + ds.sum < 2 ^ 256) : + ∃ obss, seqRun ethLib code (writeBack [0]) σ (ds.map incMsgOf) = some obss ∧ + (∀ obs ∈ obss, obs.success = true) ∧ + ∀ obs ∈ obss.getLast?, obs.storage 0 = slotValue σ 0 + ds.sum := by + obtain ⟨obss, hrun, heach⟩ := certifiedSeq σ (ds.map incMsgOf) + ⟨trivial, fun m hm => by + obtain ⟨d, hd, rfl⟩ := List.mem_map.mp hm + exact fullMsgs_incMsgOf (hds d hd)⟩ trivial + exact ⟨obss, hrun, total_of_each ds σ obss heach hds hsum⟩ + +/-- info: 'SolidCore.Refinement.Solar.Counter.certifiedSeq' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedSeq + +/-- info: 'SolidCore.Refinement.Solar.Counter.total' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms total + +end SolidCore.Refinement.Solar.Counter + + + diff --git a/SolidCore/Refinement/Solar/Counter/Source.lean b/SolidCore/Refinement/Solar/Counter/Source.lean new file mode 100644 index 00000000..3b5f8291 --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/Source.lean @@ -0,0 +1,62 @@ +-- Generated by scripts/refinement/counter/milestone.sh from scripts/refinement/counter/counter.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace Counter + +def importedSourceName : String := "scripts/refinement/counter/counter.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Counter" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "x", + ty := Ty.uint 256, + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.function + { kind := FunctionKind.function, + name := some "inc", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "d", ty := Ty.uint 256, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "x") AssignOp.addAssign (Expr.ident "d"))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "get", + visibility := some Visibility.external_, + mutability := StateMutability.view, + params := [], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.ident "x"))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end Counter +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Solar/Counter/Spec.lean b/SolidCore/Refinement/Solar/Counter/Spec.lean new file mode 100644 index 00000000..ec19fb8c --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/Spec.lean @@ -0,0 +1,381 @@ +import Verify.Tactic +import SolidCore.Refinement.Wide.Refines +import SolidCore.Refinement.KernelCopies +import SolidCore.Refinement.KernelRfl +import SolidCore.Refinement.Solar.Counter.Source + +/-! +# counter: `inc(uint256 d)` adds `d` to the storage word `x`, or panics on overflow + +The contract (scripts/refinement/counter/counter.sol; Certified/counter/counter.sol in +solar's tree, the same file), + + contract Counter { uint256 x; function inc(uint256 d) external { x += d; } + function get() external view returns (uint256) { return x; } } + +compiled by solar with `-Ogas --evm-version osaka` to the 83 bytes of runtime bytecode `code`. + +* SolidCore's checked contract is `contract?`, the type checker on + `Source.Counter.importedSourceUnit`. The kernel checks `shape_eq` (`kernel_rfl`): that its + core is `coreLit` and that its constructor leaves no storage and no logs, by one conversion + check on copies of the type checker that read the selectors from a table (`selector_eq`, + each selector checked by Keccak-256 on its own). +* `model` is `inc` as a Loom program over the storage: it reads slot 0, panics with + `Panic(0x11)` when `x + d` does not fit in 256 bits, and otherwise writes `x + d` to slot 0. + It is stated for every storage; `run_inc` ties it to SolidCore on every argument word from the + deployed (empty) storage by symbolic evaluation of the interpreter (`wide_symex`). +* `scope` is every call of `inc` with any argument word below `2 ^ 256`, no value, from the + deployed storage. There `x = 0`, so `x + d` always fits and the call stores `d`: `post`. + The overflow branch of the model, and `get`, are outside the scope. + +Nothing here uses `native_decide` or `bv_decide`. +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source SolidCore.Verify + +/-- The interpreter fuel. -/ +def fuel : Nat := 4096 + +/-- solar's runtime bytecode of `Counter` (compiler sources of the commit the manifest names, +`-Ogas --evm-version osaka`), as hex. -/ +def runtimeHex : String := + "346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd" + +/-- The SHA-256 of the runtime bytecode. -/ +def runtimeSha256 : String := "daed21b0c790bb2c08bcf999c9ebc6fea950c213ea0a799418552aa14c18f6ec" + +/-- The runtime bytecode read big-endian. -/ +def runtimeNat : Nat := + 0x346034575f3560e01c80636d4ce63c146038578063812600df03603457602436106034575f5460043581019081106041575f55005b5f5ffd5b5f545f5260205ff35b6011602052634e487b715f526024601cfd + +/-- The runtime bytecode's length in bytes. -/ +def runtimeSize : Nat := 83 + +/-- solar's runtime bytecode of `Counter`. -/ +def code : ByteArray := EthLib.Execution.Evm.Logic.NatCode.ofNat runtimeNat runtimeSize + +/-- The selector of `inc(uint256)`. -/ +def incSelector : Nat := 0x812600df + +/-- The selector of `get()`. -/ +def getSelector : Nat := 0x6d4ce63c + +/-- SolidCore's checked `Counter`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.Counter.importedSourceUnit "Counter" + +/-- The function of the scope, `inc`, and its parameter. -/ +def fns : List Fn := [⟨incSelector, [(.uint 256)]⟩] + +/-- SolidCore's core contract of `Counter`, as the type checker leaves it. -/ +def coreLit : Contract := + { storageFields := [{ name := "x", + slot := 0, + ty? := some (SolidCore.Solidity.Source.Ty.uint256), + layout? := some (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.uint256)), + transient := false, + packedOffset := 0, + packedBytes := 32, + packedSigned := false }], + immutableFields := [], + eventDecls := [], + errorDecls := [], + functions := [{ name := "inc", + selector? := some 2166751455, + payable := false, + params := [{ name := "d", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "d") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "d")), + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.add)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 256)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "x" + []) + (SolidCore.Solidity.Source.Expr.var "d"))]], + dispatchId? := none }, + { name := "get", + selector? := some 1833756220, + payable := false, + params := [], + paramAbiCleanups := [], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.ref) + "x" + [])]]], + dispatchId? := none }, + { name := "__internal_inc(uint256)#[SolidCore.Solidity.Ty.uint 256]", + selector? := none, + payable := false, + params := [{ name := "d", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "d") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "d")), + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.add)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 256)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "x" + []) + (SolidCore.Solidity.Source.Expr.var "d"))]], + dispatchId? := none }, + { name := "__internal_get()#[]", + selector? := none, + payable := false, + params := [], + paramAbiCleanups := [], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.ref) + "x" + [])]]], + dispatchId? := none }] } + +/-! ## The selectors + +The type checker computes each external function's selector by Keccak-256 of its +signature, which costs the kernel about 400 MB a hash. Each is checked once, alone, and the +shape check below runs on copies that read them from `selectorTable` (`selector_eq`). -/ + +/-- `inc`'s selector, by Keccak-256 of its signature. -/ +def selInc : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "inc(uint256)" + +kernel_rfl selInc_eq selInc incSelector + +/-- `get`'s selector, by Keccak-256 of its signature. -/ +def selGet : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "get()" + +kernel_rfl selGet_eq selGet getSelector + +/-- `ABI.selectorFromSignature`, with `Counter`'s signatures by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "inc(uint256)" then incSelector + else if s = "get()" then getSelector + else SolidCore.Solidity.Source.ABI.selectorFromSignature s + +theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + by_cases h0 : s = "inc(uint256)" + · rw [ite_eq_left h0, h0] + exact selInc_eq + rw [ite_eq_right h0] + by_cases h1 : s = "get()" + · rw [ite_eq_left h1, h1] + exact selGet_eq + rw [ite_eq_right h1] + +/-- SolidCore's checked core of `Counter`, the storage its constructor leaves and whether it +leaves no storage and no logs, when `Counter` type checks. -/ +def shape? : Option (Contract × Option (List (Nat × Nat)) × Bool) := + match contract? with + | .ok c => some (c.core, deployedStorage fuel c, deployedEmpty fuel c) + | .error _ => none + +-- `shape_eq : shape? = some (coreLit, some [], true)`: `Counter` type checks, its core is +-- `coreLit` and its constructor leaves no storage and no logs, by the kernel's conversion check +-- on the copy of `shape?` that reads the selectors from `selectorTable` (`selector_eq`): one +-- check evaluates the type checker once and hashes nothing (`SolidCore.Refinement.KernelRfl`). +kernel_rfl shape_eq shape? (some (coreLit, some [], true)) using selector_eq + +/-- The checked contract has the core `coreLit`, and its constructor leaves no storage and no +logs. -/ +theorem shape_of {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core = coreLit ∧ deployedStorage fuel c = some [] ∧ deployedEmpty fuel c = true := by + have h := shape_eq + unfold shape? at h + rw [hc] at h + obtain ⟨hk, h⟩ := Prod.mk.inj (Option.some.inj h) + obtain ⟨hs, he⟩ := Prod.mk.inj h + exact ⟨hk, hs, he⟩ + +/-- `Counter` type checks. -/ +theorem contract_ok : ∃ c, contract? = .ok c := by + have h := shape_eq + unfold shape? at h + cases hc : contract? with + | ok c => exact ⟨c, rfl⟩ + | error _ => rw [hc] at h; simp at h + +/-- `inc` as a Loom program over the storage. -/ +def model (ws : List Nat) : SolM (List Nat) := do + let x ← sload 0 + if x + ws.getD 0 0 < 2 ^ 256 then do + sstore 0 (x + ws.getD 0 0) + pure [] + else revert (panic 0x11) + +/-- What a call of `inc(d)` from empty storage shows: success, no output, no logs, and slot 0 +holding `d`. -/ +def expected (d : U256) : Observable := + { success := true, output := [], logs := [], + storage := fun slot => if slot % 2 ^ 256 = 0 then d.toNat else 0 } + +theorem observe_model (d : U256) : + observe (fun _ => 0) (model [d.toNat] (fun _ => 0)) = expected d := by + have hd := d.isLt + simp only [model, sload, sstore, bind, StateT.bind, pure, StateT.pure, Except.bind, + Except.pure, List.getD_cons_zero, Nat.zero_add, hd, ↓reduceIte, observe, expected, + Nat.zero_mod, Nat.mod_eq_of_lt hd] + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs `inc` on any argument word, from the deployed storage, to `expected d`. -/ +theorem run_inc {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) (w : U256) : + Source.run fuel c (callOf incSelector [w]) = some (expected w) := by + rw [run_eq hd] + have hs := hd.storage + have hev := hd.events + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, incSelector, get?_insert] + case pos => + rename_i hp + exfalso + have hw := w.isLt + simp only [getElem?_of_isEmpty hs, Nat.zero_mod, Nat.zero_add] at hp + omega + case h_1 => + rename_i heq + simp [getElem?_of_isEmpty hs] at heq + case h_2 => + simp [Source.observe, expected, State.logEntries, State.loadSlot, StorageMap.lookup?] + funext slot + simp only [Std.HashMap.getElem?_insert, Shared.norm, Shared.wordModulus, beq_iff_eq] + try rw [show EvmYul.UInt256.size = 2 ^ 256 from rfl] + simp only [Nat.reducePow] + by_cases h : slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 + · simp [h] + · have h' : ¬0 = slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 := fun e => h e.symm + simp [h, h', getElem?_of_isEmpty hs] + +/-- Every call of `inc` on any argument word, with no value, from the deployed (empty) +storage. -/ +def scope : Call → Prop := fullScope fns [] + +/-- No precondition beyond the scope. -/ +def pre : Call → Prop := fun _ => True + +/-- `inc(d)` from the storage `σ` with slot 0 holding `x`: when `x + d` fits in 256 bits, the +call succeeds with no output and leaves slot 0 holding `x + d` and every other slot as it was; +otherwise it reverts with `Panic(0x11)` and the storage stays `σ`. It never logs. -/ +def post (call : Call) (obs : Observable) : Prop := + let d := (argWords 1 call).getD 0 0 + let x := slotValue call.storage 0 + obs.logs = [] ∧ + if x + d < 2 ^ 256 then + obs.success = true ∧ obs.output = [] ∧ + ∀ slot, obs.storage slot = if slot % 2 ^ 256 = 0 then x + d else slotValue call.storage slot + else + obs.success = false ∧ obs.output = panic 0x11 ∧ + ∀ slot, obs.storage slot = slotValue call.storage slot + +theorem scope_callOf {call : Call} (h : scope call) : ∃ d : U256, call = callOf incSelector [d] := by + obtain ⟨fn, hfn, args, hlen, hlt, rfl⟩ := h + simp only [fns, List.mem_singleton] at hfn + subst hfn + match args, hlen with + | [a], _ => + refine ⟨BitVec.ofNat 256 a, ?_⟩ + have ha' : a % 2 ^ 256 = a := Nat.mod_eq_of_lt (hlt a (by simp)) + simp only [callOf, List.map_cons, List.map_nil, BitVec.toNat_ofNat, ha'] + +theorem slotValue_nil : slotValue [] = fun _ => 0 := rfl + +/-- `model` implements SolidCore's `Counter` on every call of the scope. -/ +theorem implements {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) : Implements fuel c scope (argWords 1) model := + implements_of_run' (by simp [fns]) fun fn hfn ws hl => by + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w, _ | _⟩ <;> simp at hl + rw [slotValue_nil, List.map_singleton, observe_model] + exact run_inc hcore hd w + +/-- SolidCore runs `inc` on any argument word to `expected d`, from its checked contract. -/ +theorem source_run {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) (w : U256) : + Source.run fuel c (callOf incSelector [w]) = some (expected w) := by + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + exact run_inc hk hd w + +theorem argWords_inc (d : U256) : argWords 1 (callOf incSelector [d]) = [d.toNat] := by + have := argWords_calldata incSelector [d.toNat] (by simp [d.isLt]) 0 [] + simpa [callOf] using this + +/-- The verification conditions of `inc`, by Loom's weakest preconditions: `vcs_of_fullScope` +and the `wp` rules of `Verify.Basic`, as `sc_vcgen` applies them, then `simp` on the slots. -/ +theorem vcs : ∀ call, scope call → pre call → vc model (argWords 1) post call := by + refine vcs_of_fullScope (by simp [fns]) ?_ + intro fn hfn call args hcall hw hlen hargs hinit hpre + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst fn hcall + rcases args with _ | ⟨a, _ | _⟩ <;> simp at hlen + have ha : a < 2 ^ 256 := hargs a (by simp) + simp only [model, post, hw, wp_bind, wp_pure, wp_sload, wp_sstore, wp_revert, wp_ite, + List.getD_cons_zero, slotValue, List.foldl_nil, Nat.zero_add, ha, ↓reduceIte, Nat.zero_mod, + Nat.mod_eq_of_lt ha] + simp + +/-- **The specification of Counter's `inc`**, as a triple against SolidCore, from `model`'s +weakest precondition (`vcs`) and `implements`. -/ +theorem spec : ∃ c, contract? = .ok c ∧ Triple fuel c scope pre post := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + exact ⟨c, hc, triple_of_wp (implements hk hd) vcs⟩ + +/-- The specification of Counter's `inc` as `Satisfies` on SolidCore. -/ +theorem satisfies : ∃ c, contract? = .ok c ∧ Satisfies (solidCore fuel) c scope pre post := by + obtain ⟨c, hc, h⟩ := spec + exact ⟨c, hc, satisfies_of_triple h⟩ + +/-- info: 'SolidCore.Refinement.Solar.Counter.satisfies' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms satisfies + +/-- info: 'SolidCore.Refinement.Solar.Counter.source_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms source_run + +end SolidCore.Refinement.Solar.Counter diff --git a/SolidCore/Refinement/Solar/Counter/SpecAt.lean b/SolidCore/Refinement/Solar/Counter/SpecAt.lean new file mode 100644 index 00000000..383e89a4 --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/SpecAt.lean @@ -0,0 +1,201 @@ +import SolidCore.Refinement.Solar.Counter.Spec + +/-! +# counter: the specification of `inc` from any storage + +Spec.lean states `post` for any storage but proves it, and SolidCore's run, from the deployed +(empty) storage, where slot 0 holds 0 and the overflow branch is never reached. This file proves +both on `scopeAt`, every call of `inc(d)` with no value from any storage `σ`, which the call +writes over the deployed storage (`run_eq_at`). + +* `expectedAt σ d`: success with slot 0 holding `x + d` (`x` the word in slot 0 of `σ`) and every + other slot of `σ` kept when `x + d` fits; otherwise a revert with Panic(0x11) keeping `σ`. +* `run_inc_at`: SolidCore runs `inc` from `σ` to `expectedAt σ d`, by symbolic evaluation of the + interpreter (`wide_symex`), both branches of the overflow check included. +* `vcsAt`, `implementsAt`, `specAt`, `satisfiesAt`: Loom's verification conditions of `model` + on `scopeAt`, and the specification as a triple and as `Satisfies` on SolidCore. +* `source_run_at`: `run_inc_at` from the checked contract, for the source stage. +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source SolidCore.Verify + +/-- What a call of `inc(d)` from the storage `σ` shows, with `x` the word in slot 0: when +`x + d` fits, success with no output and slot 0 holding `x + d`; otherwise a revert with +`Panic(0x11)` that keeps `σ`. -/ +def expectedAt (σ : List (Nat × Nat)) (d : U256) : Observable := + if slotValue σ 0 + d.toNat < 2 ^ 256 then + { success := true, output := [], logs := [], + storage := fun slot => if slot % 2 ^ 256 = 0 then slotValue σ 0 + d.toNat else slotValue σ slot } + else { success := false, output := panic 0x11, logs := [], storage := slotValue σ } + +theorem observe_model_at (σ : List (Nat × Nat)) (d : U256) : + observe (slotValue σ) (model [d.toNat] (slotValue σ)) = expectedAt σ d := by + unfold expectedAt + by_cases h : slotValue σ 0 + d.toNat < 2 ^ 256 + · simp only [model, sload, sstore, bind, StateT.bind, pure, StateT.pure, Except.bind, + Except.pure, List.getD_cons_zero, h, ↓reduceIte, observe, Nat.zero_mod, Nat.mod_eq_of_lt h] + · simp only [model, sload, bind, StateT.bind, Except.bind, revert, List.getD_cons_zero, h, + ↓reduceIte, observe] + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +theorem run_inc_at {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d []) (w : U256) (σ : List (Nat × Nat)) : + Source.run fuel c (callAt incSelector [w] σ) = some (expectedAt σ w) := by + rw [run_eq_at hd] + have hev := hd.events + have h0 : ∀ q : Nat, d.storage[q]? = none := fun q => hd.getElem?_eq_none (by simp) + have hget := getD_storage h0 σ + generalize σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage = m at hget + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, incSelector, get?_insert] + all_goals + have hx0 := hget 0 + have hlt := slotValue_lt σ 0 + have hw := w.isLt + simp only [Nat.zero_mod] at hx0 + case pos => + rename_i hp + have hno : ¬ slotValue σ 0 + w.toNat < 2 ^ 256 := by + revert hp + cases hm : m[0]? with + | none => + simp only [hm, Option.getD_none] at hx0 + rw [← hx0] + simp only [Nat.reducePow] at hw ⊢ + omega + | some v => + simp only [hm, Option.getD_some] at hx0 + rw [← hx0] + rw [← hx0] at hlt + simp only [Nat.reducePow] at hw hlt ⊢ + omega + simp only [expectedAt, hno, ↓reduceIte, Source.observe, callAt] + rfl + case h_1 => + rename_i hp _ v heq + rw [heq] at hx0 hp + simp only [Option.getD_some] at hx0 + subst hx0 + have hyes : slotValue σ 0 + w.toNat < 2 ^ 256 := by + simp only [Nat.reducePow] at hw hlt hp ⊢ + omega + have hm : slotValue σ 0 % 2 ^ 256 = slotValue σ 0 := Nat.mod_eq_of_lt hlt + simp only [Nat.reducePow] at hm + try simp only [hm, Nat.mod_eq_of_lt hlt] + simp only [expectedAt, hyes, ↓reduceIte] + simp [Source.observe, State.logEntries, State.loadSlot, StorageMap.lookup?] + funext slot + have hs := hget slot + simp only [Nat.reducePow] at hs + simp only [Std.HashMap.getElem?_insert, Shared.norm, Shared.wordModulus, EvmYul.UInt256.size, beq_iff_eq] + rw [← hs] + have hyes' : slotValue σ 0 + w.toNat < 115792089237316195423570985008687907853269984665640564039457584007913129639936 := hyes + by_cases hz : slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 + · simp only [hz, ↓reduceIte, Nat.mod_eq_of_lt hyes'] + · have hz' : ¬ 0 = slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 := fun e => hz e.symm + simp only [hz, hz', ↓reduceIte] + cases m[slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936]? <;> rfl + case h_2 => + rename_i hp _ heq + rw [heq] at hx0 hp + simp only [Option.getD_none] at hx0 + have hyes : slotValue σ 0 + w.toNat < 2 ^ 256 := by rw [← hx0]; simpa using hw + unfold expectedAt + rw [← hx0, Nat.zero_add] + simp only [w.isLt, ↓reduceIte] + simp [Source.observe, State.logEntries, State.loadSlot, StorageMap.lookup?] + funext slot + have hs := hget slot + simp only [Nat.reducePow] at hs + simp only [Std.HashMap.getElem?_insert, Shared.norm, Shared.wordModulus, EvmYul.UInt256.size, beq_iff_eq] + rw [← hs] + have hyes' : slotValue σ 0 + w.toNat < 115792089237316195423570985008687907853269984665640564039457584007913129639936 := hyes + by_cases hz : slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 + · simp only [hz, ↓reduceIte, Nat.mod_eq_of_lt hyes'] + · have hz' : ¬ 0 = slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 := fun e => hz e.symm + simp only [hz, hz', ↓reduceIte] + cases m[slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936]? <;> rfl + + +/-- Every call of `inc` on any argument word, with no value, from any storage. -/ +def scopeAt : Call → Prop := fun call => ∃ σ, fullScope fns σ call + +theorem scopeAt_callOf {call : Call} (h : scopeAt call) : + ∃ d : U256, ∃ σ, call = { callOf incSelector [d] with storage := σ } := by + obtain ⟨σ, fn, hfn, args, hlen, hlt, rfl⟩ := h + simp only [fns, List.mem_singleton] at hfn + subst hfn + match args, hlen with + | [a], _ => + refine ⟨BitVec.ofNat 256 a, σ, ?_⟩ + have ha' : a % 2 ^ 256 = a := Nat.mod_eq_of_lt (hlt a (by simp)) + simp only [callOf, List.map_cons, List.map_nil, BitVec.toNat_ofNat, ha'] + +theorem expectedAt_nil (d : U256) : expectedAt [] d = expected d := by + have hd := d.isLt + simp only [expectedAt, slotValue_nil, Nat.zero_add, hd, ↓reduceIte, expected] + +/-- `model` implements SolidCore's `Counter` on every call of `scopeAt`. -/ +theorem implementsAt {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d []) : Implements fuel c scopeAt (argWords 1) model := by + rintro call ⟨σ, hs⟩ + refine implements_of_run' (s := σ) (by simp [fns]) (fun fn hfn ws hl => ?_) call hs + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w, _ | _⟩ <;> simp at hl + rw [List.map_singleton, observe_model_at] + exact run_inc_at hcore hd w σ + +/-- The verification conditions of `inc` from any storage, by Loom's weakest preconditions. -/ +theorem vcsAt : ∀ call, scopeAt call → pre call → vc model (argWords 1) post call := by + rintro call ⟨σ, hs⟩ hp + refine vcs_of_fullScope (s := σ) (by simp [fns]) ?_ call hs hp + intro fn hfn call args hcall hw hlen hargs hinit hpre + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst fn hcall + rcases args with _ | ⟨a, _ | _⟩ <;> simp at hlen + have ha : a < 2 ^ 256 := hargs a (by simp) + simp only [model, post, hw, wp_bind, wp_pure, wp_sload, wp_sstore, wp_revert, wp_ite, + List.getD_cons_zero] + split + · rename_i h + have h' : slotValue σ 0 + a < 115792089237316195423570985008687907853269984665640564039457584007913129639936 := h + simp + intro slot + rw [Nat.mod_eq_of_lt h'] + · rename_i h + simp + +/-- **The specification of Counter's `inc` from any storage**, as a triple against SolidCore. -/ +theorem specAt : ∃ c, contract? = .ok c ∧ Triple fuel c scopeAt pre post := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + exact ⟨c, hc, triple_of_wp (implementsAt hk (deployedAt_of_deployed hd)) vcsAt⟩ + +/-- The specification from any storage as `Satisfies` on SolidCore. -/ +theorem satisfiesAt : ∃ c, contract? = .ok c ∧ Satisfies (solidCore fuel) c scopeAt pre post := by + obtain ⟨c, hc, h⟩ := specAt + exact ⟨c, hc, satisfies_of_triple h⟩ + +/-- SolidCore runs `inc` on any argument word from any storage `σ` to `expectedAt σ d`. -/ +theorem source_run_at {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) (w : U256) + (σ : List (Nat × Nat)) : + Source.run fuel c { callOf incSelector [w] with storage := σ } = some (expectedAt σ w) := by + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + exact run_inc_at hk (deployedAt_of_deployed hd) w σ + +/-- info: 'SolidCore.Refinement.Solar.Counter.satisfiesAt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms satisfiesAt + +/-- info: 'SolidCore.Refinement.Solar.Counter.source_run_at' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms source_run_at + +end SolidCore.Refinement.Solar.Counter diff --git a/SolidCore/Refinement/Solar/Counter/Value.lean b/SolidCore/Refinement/Solar/Counter/Value.lean new file mode 100644 index 00000000..003a3586 --- /dev/null +++ b/SolidCore/Refinement/Solar/Counter/Value.lean @@ -0,0 +1,191 @@ +import SolidCore.Refinement.Solar.Counter.AssemblyAt +import SolidCore.Refinement.Solar.Counter.LoweringAt +import SolidCore.Refinement.Solar.W1Value + +/-! +# counter with a nonzero call value + +Neither inc nor get is payable, so every call of either that carries value is rejected. +certifiedValue states that solar's bytecode for Counter meets that specification (postValue: the +call reverts with empty output, emits no logs and keeps the call's storage) on scopeValue, every +call of inc on any argument word or of get, with a value v, 0 < v < 2 ^ 256, from any storage, +under EthLib, through every stage of solar's pipeline. It reuses W1Value.lean's approach: + +* source: source_run_value_inc and source_run_value_get, SolidCore's dispatcher decodes the + arguments, finds the function not payable and reverts with empty output (rejectedValueCall?), + from the run with value v (W1.run_eq_value); satisfiesValue is the specification on SolidCore. + mir_run_value: solar's first lowered MIR checks the call value first and reverts, on any call + data and storage. loweringValue is the stage. +* backend: SolarTV.Milestone.Counter.counter_mir_to_evmir, which holds on every call. +* assembly: assemblyValue is the generic theorem, Assemble.stage_of_check_all at check_ok + (stageAll), which holds on every call with any value from any storage. As a cross-check, + target_run_value runs EthLib's processMessage of the call directly: the move of v succeeds + (W1.moveEther_preState), the frame reverts with empty output from every state on every message + with nonzero value (frame_value: CALLVALUE PUSH1 0x34 JUMPI to JUMPDEST PUSH0 PUSH0 REVERT), + and processMessage returns that revert (W1.processMessage_reverts_value), on any call data; + assemblyValue_run is the stage from it. + +Not covered: the value's effect on balances (Observable has no balances, and the revert undoes +the move). +-/ + +namespace SolidCore.Refinement.Solar.Counter + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm +open SolidCore.Refinement.Evm.Symex SolidCore.Refinement.Evm.Logic + +/-- The frame of Counter's code reverts with empty output from every state on every message +with nonzero value: CALLVALUE PUSH1 0x34 JUMPI jumps to JUMPDEST PUSH0 PUSH0 REVERT. -/ +theorem frame_value (msg : Message .fusaka) (hv : msg.value ≠ 0) (st : State.TransactionState) + (ss : Substate) : Spec .fusaka (At code msg 0 [] .empty 10000000 st ss .empty) Reverted := by + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + repeat symex_one [code, runtimeNat, runtimeSize] [hv] hfork + +/-- **EthLib rejects every call of Counter's code with nonzero value**, on any call data and +from any storage: the move of the value succeeds, the frame reverts with empty output, and the +revert undoes the move. -/ +theorem target_run_value (cd : ByteArray) (v : Nat) (hv0 : v ≠ 0) (hv : v < 2 ^ 256) + (σ : List (Nat × Nat)) : + Target.run code { calldata := cd, callvalue := v, storage := σ } = some (Abi.rejected σ) := by + obtain ⟨st', hmove⟩ := + W1.moveEther_preState code { calldata := cd, callvalue := v, storage := σ } hv + obtain ⟨evm, hr, herr, hout⟩ := W1.processMessage_reverts_value + (Target.message code { calldata := cd, callvalue := v, storage := σ }) rfl rfl + (W1.ofNat_ne_zero hv0 hv) (precompileAddress_message code _) + (fun st ss => frame_value _ (W1.ofNat_ne_zero hv0 hv) st ss) _ st' Substate.empty hmove + simp [Target.run, hr, herr, hout, Abi.rejected] + +section ValueMIR + +open SolarTV SolarTV.Machine + +/-- SolarTV's lowered MIR runs Counter's stage0 on every call with nonzero value, whatever its +call data and storage, to the rejection: entry's call value check reverts with empty output. -/ +theorem mir_run_value_of (o : Oracle) (call : Call) (hv0 : call.callvalue ≠ 0) + (hv : call.callvalue < 2 ^ 256) : + (MIR.Lowered.Module.run o SolarTV.Export.Counter.stage0 call 9).map + (fun r => observe call r.2 r.1) = some (Abi.rejected call.storage) := by + have hb := W1.ofNat_ne_zero hv0 hv + repeat (first | sym_eval | simp (config := {decide := true}) only [↓reduceIte]) + have hne : EvmRules.Evm.ne (BitVec.ofNat 256 call.callvalue) 0 = 1 := by + simp [EvmRules.Evm.ne] + exact hb + simp only [hne, show (1 : EvmRules.Word) ≠ 0 by decide, ↓reduceIte] + repeat sym_eval + simp [observe, Abi.rejected, Mem.read] + +end ValueMIR + +/-- The lowered MIR's run with nonzero value, fuel-free. -/ +theorem mir_run_value (o : SolarTV.Machine.Oracle) (cd : ByteArray) (v : Nat) (hv0 : v ≠ 0) + (hv : v < 2 ^ 256) (σ : List (Nat × Nat)) : + (SolarTV.MIR.Lowered.moduleSem o).run SolarTV.Export.Counter.stage0 + { calldata := cd, callvalue := v, storage := σ } = some (Abi.rejected σ) := + W1.mir_sem_of_run 9 (mir_run_value_of o _ hv0 hv) + + +open SolidCore.Solidity SolidCore.Solidity.Source SolidCore.Refinement.Wide + SolidCore.Refinement.Evm.Wide in +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore rejects every call of inc or get with nonzero value, on any argument word, from +any storage: its dispatcher decodes the arguments, finds the function not payable and reverts +with empty output (rejectedValueCall?). -/ +theorem source_run_value {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) + (sel : Nat) (ws : List U256) (hsel : (sel = incSelector ∧ ws.length = 1) ∨ + (sel = getSelector ∧ ws = [])) (v : Nat) (hv0 : v ≠ 0) (hv : v < 2 ^ 256) + (σ : List (Nat × Nat)) : + Source.run fuel c + { calldata := (callOf sel ws).calldata, callvalue := v, storage := σ } = + some (Abi.rejected σ) := by + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + have hd' := Verify.deployedAt_of_deployed hd + have hcore := hk + have hm : v % EvmYul.UInt256.size = v := Nat.mod_eq_of_lt hv + have hw : wordEq v 0 = false := by + simp [wordEq, Shared.norm, Shared.wordModulus, hm, hv0] + rw [show (callOf sel ws).calldata = Abi.calldata sel (ws.map (·.toNat)) from rfl, + W1.run_eq_value hd'] + have hev := hd'.events + have h0 : ∀ q : Nat, d.storage[q]? = none := fun q => hd'.getElem?_eq_none (by simp) + generalize σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage = m + rcases hsel with ⟨rfl, hl⟩ | ⟨rfl, rfl⟩ + · match ws, hl with + | [w], _ => + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, incSelector, hw] + simp [Source.observe, Abi.rejected] + · simp only [hcore, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, getSelector, hw] + simp [Source.observe, Abi.rejected] + +/-! ## The value scope through every stage -/ + +open SolidCore.Refinement.Evm.Wide in +/-- Every call of inc on any argument word, or of get, with a nonzero value v < 2 ^ 256, from +any storage. -/ +def scopeValue : Call → Prop := fun call => + ∃ (sel : Nat) (ws : List U256) (v : Nat) (σ : List (Nat × Nat)), + ((sel = incSelector ∧ ws.length = 1) ∨ (sel = getSelector ∧ ws = [])) ∧ + v ≠ 0 ∧ v < 2 ^ 256 ∧ + call = { calldata := (callOf sel ws).calldata, callvalue := v, storage := σ } + +/-- Neither function is payable: a call with value reverts with empty output, emits no logs and +keeps the call's storage. -/ +def postValue (call : Call) (obs : Observable) : Prop := + obs.success = false ∧ obs.output = [] ∧ obs.logs = [] ∧ + ∀ slot, obs.storage slot = slotValue call.storage slot + +/-- The specification on the value scope holds of SolidCore's checked Counter. -/ +theorem satisfiesValue : ∃ c, contract? = .ok c ∧ + Satisfies (solidCore fuel) c scopeValue pre postValue := by + obtain ⟨c, hc, -⟩ := satisfies + refine ⟨c, hc, ?_⟩ + rintro call ⟨sel, ws, v, σ, hsel, hv0, hv, rfl⟩ - + exact ⟨_, source_run_value hc sel ws hsel v hv0 hv σ, rfl, rfl, rfl, fun _ => rfl⟩ + +/-- **The source stage on the value scope**, under every oracle. -/ +theorem loweringValue (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Counter.stage0 scopeValue := by + rintro call ⟨sel, ws, v, σ, hsel, hv0, hv, rfl⟩ obs hrun + change Source.run fuel c _ = some obs at hrun + rw [source_run_value hc sel ws hsel v hv0 hv σ] at hrun + cases hrun + exact mir_run_value o _ v hv0 hv σ + +/-- **The assembly stage on the value scope**, under every oracle: the generic theorem for every +program and code the checker accepts, at check_ok, which holds on every call with any value. -/ +theorem assemblyValue (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib SolarTV.Export.Counter.evm5 code scopeValue := + stageAll o scopeValue + +/-- The assembly stage on the value scope proved directly, as a cross-check of assemblyValue: the +final EVM IR runs to the rejection (the source stage's MIR run and the backend stages, which hold +on every call), and so does the bytecode on EthLib (target_run_value). -/ +theorem assemblyValue_run (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib SolarTV.Export.Counter.evm5 code scopeValue := by + rintro call ⟨sel, ws, v, σ, hsel, hv0, hv, rfl⟩ obs hrun + have he := SolarTV.Milestone.Counter.counter_mir_to_evmir o _ trivial _ + (mir_run_value o (SolidCore.Refinement.Evm.Wide.callOf sel ws).calldata v hv0 hv σ) + rw [he] at hrun + cases hrun + exact target_run_value _ v hv0 hv σ + +/-- **Counter with a nonzero call value**: solar's bytecode for Counter meets the specification +of every call of inc or get with value (neither is payable, so the call is rejected and the +storage kept) under EthLib, through every stage of solar's pipeline. -/ +theorem certifiedValue : Satisfies ethLib code scopeValue pre postValue := by + obtain ⟨c, hc, hspec⟩ := satisfiesValue + exact bytecode_of_stages hspec (loweringValue W1.oracle hc) + ((SolarTV.Milestone.Counter.counter_mir_to_evmir W1.oracle).mono fun _ _ => trivial) + (assemblyValue W1.oracle) + +/-- info: 'SolidCore.Refinement.Solar.Counter.certifiedValue' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms certifiedValue + +end SolidCore.Refinement.Solar.Counter diff --git a/SolidCore/Refinement/Solar/EndToEnd.lean b/SolidCore/Refinement/Solar/EndToEnd.lean new file mode 100644 index 00000000..41b6644a --- /dev/null +++ b/SolidCore/Refinement/Solar/EndToEnd.lean @@ -0,0 +1,78 @@ +import SolidCore.Refinement.Solar.AssembleSim +import SolidCore.Refinement.Solar.AssembleLoopWithin + +/-! +# The backend to exact bytecode, for any contract + +solar-tv's backend stages give, for each certified contract, the first lowered MIR `stage0` to the +final EVM IR `p` forwards (`_mir_to_evmir`, a `Stage`) and backwards +(`_certified_back`, a `Certified` from `p` to `stage0`). The assembler checks give the +final EVM IR to the exported bytes `code`: `Assemble.check` (straight-line code, gas bounded by +each block's potential) as a stage at EthLib's default gas, `AssembleLoop.checkL` (code with loops) +as `Within` at every gas. This file composes them once, so that a generated proof only supplies +the backend theorems and a check the kernel evaluates: + +* `stage_of_check`: stage0 to the bytes, forwards, at EthLib's default gas. +* `within_of_checkL`: at every gas, every result of the bytes is stage0's or a failure that + changes nothing. +* `holds_of_checkL`: a specification stage0 meets holds of the bytes at every gas. + +No hypothesis beyond the two checks' own: the oracle's caller and hash are EthLib's when the +certificate says the code reads them (`c.env`). +-/ + +namespace SolidCore.Refinement.Solar.EndToEnd + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Final + +variable {o : Oracle} + +/-- **stage0 to the exact bytes at EthLib's default gas**, from the backend stages and the +assembler check of straight-line code. -/ +theorem stage_of_check {stage0 : (mirSem o).Prog} {p : Assemble.Program} {code : ByteArray} + {c : Assemble.Cert} {S scope : Call → Prop} + (backend : Stage (mirSem o) (evmirSem o) stage0 p S) (hS : ∀ call, scope call → S call) + (hc : Assemble.check p code c = true) (ho : c.env = true → Assemble.OracleOk o) : + Stage (mirSem o) ethLib stage0 (show ethLib.Prog from code) scope := + Stage.trans (backend.mono hS) (Assemble.stage_of_check_env hc o ho scope) + +/-- **At every gas, every result of the exact bytes is stage0's or a failure that changes +nothing**, from the backend stages read backwards and the assembler check of code with loops. -/ +theorem within_of_checkL {stage0 : MIR.Lowered.moduleLayer.Prog} {p : Assemble.Program} + {code : ByteArray} {c : Assemble.Cert} {mx : List Nat} {S scope : Call → Prop} + (back : Certified EVM.Program.layer MIR.Lowered.moduleLayer o p stage0 S) + (hS : ∀ call, scope call → S call) + (hc : AssembleLoop.checkL p code c mx = true) (ho : c.env = true → Assemble.OracleOk o) + (gas : Nat) + (he : c.reads = true → Assemble.EnvOk o := by intro h; exact absurd h (by decide)) : + Within (mirSem o) (ethLibWith gas) stage0 code scope := by + intro call hcall obs hrun + rcases AssembleLoop.within_of_checkL hc o ho scope gas he call hcall obs hrun with h | h + · exact Or.inl (stage_of_certified back call (hS call hcall) obs h) + · exact Or.inr h + +/-- **A specification stage0 meets holds of the exact bytes at every gas.** -/ +theorem holds_of_checkL {St : Type} {spec : ContractSpec St} {stage0 : MIR.Lowered.moduleLayer.Prog} + {p : Assemble.Program} {code : ByteArray} {c : Assemble.Cert} {mx : List Nat} + {S : Call → Prop} (holds : Holds (mirSem o) stage0 spec) + (back : Certified EVM.Program.layer MIR.Lowered.moduleLayer o p stage0 S) + (hS : ∀ call, spec.Calls call → S call) + (hc : AssembleLoop.checkL p code c mx = true) (ho : c.env = true → Assemble.OracleOk o) + (gas : Nat) + (he : c.reads = true → Assemble.EnvOk o := by intro h; exact absurd h (by decide)) : + Holds (ethLibWith gas) code spec := + holds.of_within (within_of_checkL back hS hc ho gas he) + +/-- info: 'SolidCore.Refinement.Solar.EndToEnd.stage_of_check' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stage_of_check + +/-- info: 'SolidCore.Refinement.Solar.EndToEnd.within_of_checkL' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms within_of_checkL + +/-- info: 'SolidCore.Refinement.Solar.EndToEnd.holds_of_checkL' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holds_of_checkL + +end SolidCore.Refinement.Solar.EndToEnd diff --git a/SolidCore/Refinement/Solar/EthLibErr.lean b/SolidCore/Refinement/Solar/EthLibErr.lean new file mode 100644 index 00000000..b9035135 --- /dev/null +++ b/SolidCore/Refinement/Solar/EthLibErr.lean @@ -0,0 +1,523 @@ +import EthLib.Execution.Proofs.Evm.Call.StepRules +import EthLib.Execution.Proofs.Evm.Logic.LessGas + +/-! +# No step throws a revert, and only REVERT ends a frame with it + +EthLib's steps that are monotone in gas (`EthLib.Execution.Evm.Logic.GasMono`) count a revert as a +failure, so a run with less gas that reverts says nothing of the run with more gas. This file +classifies every step of the one-counter meter (`Nat`) by the error it carries: + +* `Good p evm r`: the result `r` throws no revert, and each frame it gives (through `p`) has + the revert error only when `evm` had it (`KR`). It composes through `bind`, so each + instruction is checked from its parts (`popWord`, `pushWord`, the charges, `keepReads`, the + reads of the state), by the tactic `good`. +* `good_instruction`: every instruction of the ten groups that give the next frame throws no + revert, and every one but REVERT keeps it out of its frame. `good_message`: the same for the + calls and the creations, whose result is the next frame or the caller of a message. +* `step_good`: a step throws no revert, and a step that gives a frame with the revert error + started from one, or ran REVERT. +-/ + +namespace EthLib.Execution.Evm.RevertErr + +open EthLib.Base (Address Fork U256) +open GasCosts + +variable {fork : Fork} + +/-- The frame `b` has the revert error only when `a` had it. -/ +def KR (a b : Evm fork Nat) : Prop := b.error = some .revert → a.error = some .revert + +theorem KR.refl (a : Evm fork Nat) : KR a a := id + +theorem KR.trans {a b c : Evm fork Nat} (h1 : KR a b) (h2 : KR b c) : KR a c := fun h => h1 (h2 h) + +theorem KR.of_eq {a b : Evm fork Nat} (h : b.error = a.error) : KR a b := fun h' => h ▸ h' + +/-- A result that throws no revert, whose frames carry the revert error only if `evm` did. -/ +def Good {α : Type} (p : α → Evm fork Nat) (evm : Evm fork Nat) (r : Except EvmError α) : Prop := + (∀ e, r = .error e → e ≠ .revert) ∧ ∀ a, r = .ok a → KR evm (p a) + +theorem Good.bind {α β : Type} {p : α → Evm fork Nat} {q : β → Evm fork Nat} {evm : Evm fork Nat} + {x : Except EvmError α} {f : α → Except EvmError β} (hx : Good p evm x) + (hf : ∀ a, Good q (p a) (f a)) : Good q evm (x >>= f) := by + refine ⟨fun e h => ?_, fun b h => ?_⟩ + · cases hxa : x with + | error e' => rw [hxa] at h; cases h; exact hx.1 _ hxa + | ok a => rw [hxa] at h; exact (hf a).1 e h + · cases hxa : x with + | error e' => rw [hxa] at h; cases h + | ok a => rw [hxa] at h; exact (hx.2 a hxa).trans ((hf a).2 b h) + +/-- A bind whose first part gives no frame: the rest runs from the same frame. -/ +theorem Good.bindc {α β : Type} {q : β → Evm fork Nat} {evm : Evm fork Nat} + {x : Except EvmError α} {f : α → Except EvmError β} (hx : Good (fun _ => evm) evm x) + (hf : ∀ a, Good q evm (f a)) : Good q evm (x >>= f) := + Good.bind hx hf + +theorem Good.pure_kr {α : Type} {p : α → Evm fork Nat} {evm : Evm fork Nat} {a : α} + (h : KR evm (p a)) : Good p evm (pure a : Except EvmError α) := + ⟨(fun _ h' => by cases h'), (fun _ h' => by cases h'; exact h)⟩ + +theorem Good.ok_kr {α : Type} {p : α → Evm fork Nat} {evm : Evm fork Nat} {a : α} + (h : KR evm (p a)) : Good p evm (.ok a : Except EvmError α) := Good.pure_kr h + +theorem Good.err {α : Type} {p : α → Evm fork Nat} {evm : Evm fork Nat} {e : EvmError} + (h : e ≠ .revert) : Good p evm (.error e : Except EvmError α) := + ⟨(fun _ h' => by cases h'; exact h), (fun _ h' => by cases h')⟩ + +theorem Good.throw_ {α : Type} {p : α → Evm fork Nat} {evm : Evm fork Nat} {e : EvmError} + (h : e ≠ .revert) : Good p evm (throw e : Except EvmError α) := Good.err h + +/-- The frame of a step's result: the next frame, or the caller of a message. -/ +def frameOf : StepResult fork Nat → Evm fork Nat + | .next b => b + | .child c _ _ => c + +theorem Good.map_next {evm : Evm fork Nat} {x : Except EvmError (Evm fork Nat)} + (h : Good id evm x) : Good frameOf evm (StepResult.next <$> x) := by + refine ⟨fun e h' => ?_, fun b h' => ?_⟩ + · cases hx : x with + | error e' => rw [hx] at h'; cases h'; exact h.1 _ hx + | ok a => rw [hx] at h'; cases h' + · cases hx : x with + | error e' => rw [hx] at h'; cases h' + | ok a => rw [hx] at h'; cases h'; exact h.2 a hx + +theorem Good.mapError {α ε : Type} {evm : Evm fork Nat} (f : ε → EvmError) + (hf : ∀ s, f s ≠ .revert) (x : Except ε α) : Good (fun _ => evm) evm (x.mapError f) := by + cases x with + | error s => exact Good.err (hf s) + | ok a => exact Good.ok_kr (KR.refl _) + +@[simp] theorem error_accessAddress (e : Evm fork Nat) (a : Address) : + (accessAddress e a).2.error = e.error := by + unfold accessAddress; split <;> rfl + +@[simp] theorem error_accessStorageKey (e : Evm fork Nat) (a : Address) (k : EthLib.Base.Bytes32) : + (accessStorageKey e a k).2.error = e.error := by + unfold accessStorageKey; split <;> rfl + +/-! ## The parts of the instructions -/ + +theorem good_popWord {evm e : Evm fork Nat} (h : KR evm e) : Good Prod.snd evm (popWord e) := by + unfold popWord + refine Good.bindc ?_ fun a => ?_ + · unfold Stack.pop + split + · exact Good.err (by decide) + · exact Good.ok_kr (KR.refl _) + · rcases a with ⟨x, s⟩ + exact Good.pure_kr h + +theorem good_pushWord {evm e : Evm fork Nat} (h : KR evm e) (x : U256) : + Good id evm (pushWord e x) := by + unfold pushWord + refine Good.bindc ?_ fun a => Good.pure_kr h + unfold Stack.push + split + · exact Good.err (by decide) + · exact Good.ok_kr (KR.refl _) + +theorem good_chargeGas {evm e : Evm fork Nat} (h : KR evm e) (c : Nat) : + Good id evm (chargeGas e c) := by + unfold chargeGas + refine Good.bindc ?_ fun a => Good.pure_kr h + simp only [GasMeter.charge] + split + · exact Good.err (by decide) + · exact Good.ok_kr (KR.refl _) + +theorem good_chargeStateGas {evm e : Evm fork Nat} (h : KR evm e) (c : Nat) : + Good id evm (chargeStateGas e c) := by + unfold chargeStateGas + refine Good.bindc ?_ fun a => Good.pure_kr h + simp only [GasMeter.chargeState] + split + · exact Good.err (by decide) + · exact Good.ok_kr (KR.refl _) + +theorem good_chargeGasAndMemory {evm e : Evm fork Nat} (h : KR evm e) (c : Nat) + (rs : List (U256 × U256)) : Good id evm (chargeGasAndMemory e c rs) := by + unfold chargeGasAndMemory + exact Good.bind (good_chargeGas h _) fun a => Good.pure_kr (KR.refl _) + +theorem good_checkGas (evm e : Evm fork Nat) (c : Nat) : + Good (fun _ => evm) evm (checkGas e c) := by + unfold checkGas + split + · exact Good.throw_ (by decide) + · exact Good.pure_kr (KR.refl _) + +theorem good_accountCode (evm e : Evm fork Nat) (a : Address) : + Good (fun _ => evm) evm (accountCode e a) := by + unfold accountCode + exact Good.mapError _ (by intro _ h; cases h) _ + +theorem good_creationAddress (evm : Evm fork Nat) (sender : Address) (nonce : Nat) + (salt : Option U256) (initCode : ByteArray) : + Good (fun _ => evm) evm (creationAddress sender nonce salt initCode) := by + unfold creationAddress + split + · exact Good.ok_kr (KR.refl _) + · exact Good.mapError _ (by intro _ h; cases h) _ + +/-- The rest of an instruction that keeps its reads: an error that does not abort becomes an +exceptional halt with that error, which is no revert. -/ +theorem good_keepReads {α : Type} {p : α → Evm fork Nat} {halted : Evm fork Nat → α} + (hp : ∀ x, p (halted x) = x) {evm e : Evm fork Nat} {rest : Except EvmError α} + (h : Good p evm rest) : Good p evm (keepReads e halted rest) := by + unfold keepReads + cases hr : rest with + | error err => + have hne := h.1 err hr + simp only + split + · exact Good.err hne + · refine Good.ok_kr fun hh => ?_ + rw [hp] at hh + simp only [exceptionalHalt, Option.some.injEq] at hh + exact absurd hh hne + | ok a => exact Good.ok_kr (h.2 a hr) + +/-- The frame relation in the goals the tactic leaves: the frame is built from the other with +the same error. -/ +macro "kr" : tactic => `(tactic| first + | exact KR.refl _ + | assumption + | (apply KR.of_eq; simp [advance, recordAccountRead, recordStorageRead, refillStateGas, + frameOf]; done) + | (apply KR.of_eq; rfl) + | (refine KR.trans (by assumption) ?_; apply KR.of_eq; simp [advance, recordAccountRead, + recordStorageRead, refillStateGas, frameOf]; done) + | (refine KR.trans (by assumption) ?_; apply KR.of_eq; rfl)) + +/-- After a split of a pair that is no part of a bind, name its frame by the expression. -/ +macro "pair_subst" : tactic => + `(tactic| (rename_i hpair; have h2 := congrArg Prod.snd hpair; dsimp only at h2; subst h2)) + +syntax "good_step" : tactic +macro_rules + | `(tactic| good_step) => `(tactic| first + | exact Good.err (by decide) + | exact Good.throw_ (by decide) + | exact Good.pure_kr (by kr) + | exact Good.ok_kr (by kr) + | (refine Good.bind (good_popWord (by kr)) ?_; rintro ⟨_, _⟩; dsimp only) + | (refine Good.bind (good_pushWord (by kr) _) ?_; intro _) + | (refine Good.bind (good_chargeGas (by kr) _) ?_; intro _) + | (refine Good.bind (good_chargeStateGas (by kr) _) ?_; intro _) + | (refine Good.bind (good_chargeGasAndMemory (by kr) _ _) ?_; intro _) + | (refine Good.bindc (good_checkGas _ _ _) ?_; intro _) + | (refine Good.bindc (good_accountCode _ _ _) ?_; intro _) + | (refine Good.bindc (good_creationAddress _ _ _ _ _) ?_; intro _) + | (refine Good.bindc (Good.mapError _ (by intro _ h; cases h) _) ?_; intro _) + | (refine good_keepReads (fun _ => rfl) ?_) + | (refine Good.map_next ?_) + | (split <;> try pair_subst) + | (refine Good.bindc ?_ (fun _ => ?_)) + | (dsimp only)) + +/-- Check a do-block part by part. -/ +macro "good" : tactic => `(tactic| repeat' good_step) + +/-! ## The instructions -/ + +theorem good_haltWithOutput {evm e : Evm fork Nat} (h : KR evm e) : + Good id evm (haltWithOutput e) := by + unfold haltWithOutput; good + +theorem good_readFrame {evm e : Evm fork Nat} (h : KR evm e) (c : Nat) (v : Evm fork Nat → U256) : + Good id evm (readFrame c v e) := by + unfold readFrame; good + +theorem good_popTopics {evm : Evm fork Nat} : ∀ (n : Nat) {e : Evm fork Nat}, KR evm e → + Good Prod.snd evm (popTopics e n) + | 0, e, h => by unfold popTopics; exact Good.ok_kr h + | n + 1, e, h => by + unfold popTopics + refine Good.bind (good_popWord h) ?_ + rintro ⟨_, e1⟩ + refine Good.bind (good_popTopics n (KR.refl e1)) ?_ + rintro ⟨_, e2⟩ + exact Good.pure_kr (KR.refl _) + +theorem good_stackOnly {op : Op} {run : Evm fork Nat → Except EvmError (Evm fork Nat)} + (hf : stackOnlyStep fork op = some run) (evm : Evm fork Nat) : Good id evm (run evm) := by + cases op <;> simp only [stackOnlyStep, Option.some.injEq, reduceCtorEq] at hf + all_goals (try split at hf) <;> (try simp only [Option.some.injEq, reduceCtorEq] at hf) <;> + (try subst hf) + all_goals first + | (cases hf; done) + | (simp only [binaryOp, unaryOp, ternaryOp, expStep, keccak256Step, popStep, pushN, dupN, + swapN, dupnStep, swapnStep, exchangeStep]; good) + +theorem good_controlFlow {op : Op} {run : Evm fork Nat → Except EvmError (Evm fork Nat)} + (hf : controlFlowStep op = some run) (evm : Evm fork Nat) : Good id evm (run evm) := by + cases op <;> simp only [controlFlowStep, Option.some.injEq, reduceCtorEq] at hf <;> subst hf + all_goals first + | exact good_readFrame (KR.refl _) _ _ + | (simp only [stopStep, jumpStep, jumpiStep, jumpdestStep]; good) + +theorem good_memoryData {op : Op} {run : Evm fork Nat → Except EvmError (Evm fork Nat)} + (hf : memoryDataStep op = some run) (evm : Evm fork Nat) : Good id evm (run evm) := by + cases op <;> simp only [memoryDataStep, Option.some.injEq, reduceCtorEq] at hf <;> subst hf + all_goals first + | exact good_readFrame (KR.refl _) _ _ + | (simp only [mloadStep, mstoreStep, mstore8Step, mcopyStep, calldataloadStep, copyToMemory, + returndatacopyStep]; good) + +theorem good_environment {op : Op} {run : Evm fork Nat → Except EvmError (Evm fork Nat)} + (hf : environmentStep fork op = some run) (evm : Evm fork Nat) : Good id evm (run evm) := by + cases op <;> simp only [environmentStep, Option.some.injEq, reduceCtorEq] at hf + all_goals (try split at hf) <;> (try simp only [Option.some.injEq, reduceCtorEq] at hf) <;> + (try subst hf) + all_goals first + | (cases hf; done) + | exact good_readFrame (KR.refl _) _ _ + | (simp only [blockhashStep, blobhashStep]; good) + +theorem good_account {op : Op} {run : Evm fork Nat → Except EvmError (Evm fork Nat)} + (hf : accountStep fork op = some run) (evm : Evm fork Nat) : Good id evm (run evm) := by + cases op <;> simp only [accountStep, Option.some.injEq, reduceCtorEq] at hf + all_goals (try split at hf) <;> (try simp only [Option.some.injEq, reduceCtorEq] at hf) <;> + (try subst hf) + all_goals first + | (cases hf; done) + | exact good_readFrame (KR.of_eq rfl) _ _ + | (simp only [balanceStep, extcodesizeStep, extcodecopyStep, extcodehashStep]; good) + +theorem good_storage {op : Op} {run : Evm fork Nat → Except EvmError (Evm fork Nat)} + (hf : storageStep op = some run) (evm : Evm fork Nat) : Good id evm (run evm) := by + cases op <;> simp only [storageStep, Option.some.injEq, reduceCtorEq] at hf <;> subst hf + all_goals (simp only [sloadStep, sstoreStep]; good) + +theorem good_transient {op : Op} {run : Evm fork Nat → Except EvmError (Evm fork Nat)} + (hf : transientStorageStep fork op = some run) (evm : Evm fork Nat) : + Good id evm (run evm) := by + cases op <;> simp only [transientStorageStep, reduceCtorEq] at hf <;> split at hf <;> + simp only [Option.some.injEq, reduceCtorEq] at hf <;> subst hf + all_goals (simp only [tloadStep, tstoreStep]; good) + +theorem good_log {op : Op} {run : Evm fork Nat → Except EvmError (Evm fork Nat)} + (hf : logOpStep op = some run) (evm : Evm fork Nat) : Good id evm (run evm) := by + cases op <;> simp only [logOpStep, Option.some.injEq, reduceCtorEq] at hf + subst hf + unfold logStep + refine Good.bind (good_popWord (KR.refl _)) ?_ + rintro ⟨_, e1⟩ + refine Good.bind (good_popWord (KR.refl _)) ?_ + rintro ⟨_, e2⟩ + refine Good.bind (good_popTopics _ (KR.refl _)) ?_ + rintro ⟨_, e3⟩ + dsimp only + good + +theorem good_finishSelfdestruct {evm e : Evm fork Nat} (h : KR evm e) (b : Address) (r : Nat) : + Good id evm (finishSelfdestruct fork b r e) := by + unfold finishSelfdestruct; good + +theorem good_selfdestruct {op : Op} {run : Evm fork Nat → Except EvmError (Evm fork Nat)} + (hf : selfdestructOpStep fork op = some run) (evm : Evm fork Nat) : Good id evm (run evm) := by + cases op <;> simp only [selfdestructOpStep, Option.some.injEq, reduceCtorEq] at hf + subst hf + unfold selfdestructStep + good + all_goals exact good_finishSelfdestruct (by kr) _ _ + +theorem good_returnOp {op : Op} {run : Evm fork Nat → Except EvmError (Evm fork Nat)} + (hf : returnOpStep fork op = some run) (evm : Evm fork Nat) : + (∀ e, run evm = .error e → e ≠ .revert) ∧ (op ≠ .revert → ∀ b, run evm = .ok b → KR evm b) := by + cases op <;> simp only [returnOpStep, Option.some.injEq, reduceCtorEq] at hf + · subst hf + have g := good_haltWithOutput (evm := evm) (e := evm) (KR.refl _) + exact ⟨g.1, fun _ => g.2⟩ + · split at hf + · simp only [Option.some.injEq] at hf + subst hf + refine ⟨fun e h => ?_, fun hne => absurd rfl hne⟩ + rw [revertStep_eq] at h + cases hr : returnStep evm with + | error e' => + rw [hr] at h; cases h + exact (good_haltWithOutput (KR.refl evm)).1 _ hr + | ok c => rw [hr] at h; cases h + · cases hf + +/-- **Every instruction that gives the next frame throws no revert**, and every one but REVERT +gives a frame with the revert error only from one. -/ +theorem good_instruction {op : Op} {run : Evm fork Nat → Except EvmError (Evm fork Nat)} + (hrun : instruction fork op = some run) (evm : Evm fork Nat) : + (∀ e, run evm = .error e → e ≠ .revert) ∧ (op ≠ .revert → ∀ b, run evm = .ok b → KR evm b) := by + have lift : Good id evm (run evm) → + (∀ e, run evm = .error e → e ≠ .revert) ∧ (op ≠ .revert → ∀ b, run evm = .ok b → KR evm b) := + fun h => ⟨h.1, fun _ => h.2⟩ + unfold instruction at hrun + rcases orElse_eq_some hrun with hf | hrun + · exact lift (good_stackOnly hf evm) + rcases orElse_eq_some hrun with hf | hrun + · exact lift (good_controlFlow hf evm) + rcases orElse_eq_some hrun with hf | hrun + · exact lift (good_memoryData hf evm) + rcases orElse_eq_some hrun with hf | hrun + · exact good_returnOp hf evm + rcases orElse_eq_some hrun with hf | hrun + · exact lift (good_environment hf evm) + rcases orElse_eq_some hrun with hf | hrun + · exact lift (good_account hf evm) + rcases orElse_eq_some hrun with hf | hrun + · exact lift (good_storage hf evm) + rcases orElse_eq_some hrun with hf | hrun + · exact lift (good_transient hf evm) + rcases orElse_eq_some hrun with hf | hf + · exact lift (good_log hf evm) + · exact lift (good_selfdestruct hf evm) + +/-! ## The calls and the creations -/ + +theorem good_skipCall {evm e : Evm fork Nat} (h : KR evm e) (g r : Nat) : + Good id evm (skipCall e g r) := by + unfold skipCall; good + +theorem good_popCallOperands {evm e : Evm fork Nat} (h : KR evm e) (kind : CallKind) : + Good Prod.snd evm (popCallOperands kind e) := by + unfold popCallOperands + refine Good.bind (good_popWord h) ?_ + rintro ⟨_, e1⟩ + refine Good.bind (good_popWord (KR.refl _)) ?_ + rintro ⟨_, e2⟩ + refine Good.bind (p := Prod.snd) ?_ ?_ + · unfold popCallValue + split + · exact good_popWord (KR.refl _) + · exact Good.ok_kr (KR.refl _) + rintro ⟨_, e3⟩ + dsimp only + good + +theorem good_popSalt {evm e : Evm fork Nat} (h : KR evm e) (create2 : Bool) : + Good Prod.snd evm (popSalt create2 e) := by + unfold popSalt + split + · good + · exact Good.ok_kr h + +theorem good_accessDelegation {evm e : Evm fork Nat} (h : KR evm e) (a : Address) (k : Nat) : + Good Prod.snd evm (accessDelegation e a k) := by + unfold accessDelegation + good + +theorem good_payCall {evm e : Evm fork Nat} (h : KR evm e) (kind : CallKind) (call : CallOperands) + (m x n : Nat) : Good Prod.snd evm (payCall kind call m x n e) := by + unfold payCall; good + +theorem good_genericCall {evm e : Evm fork Nat} (h : KR evm e) (message : Message fork) (n : Nat) + (o s : U256) : Good frameOf evm (genericCall e message n o s) := by + unfold genericCall + dsimp only + split + · exact Good.map_next (good_skipCall (by kr) _ _) + · exact Good.ok_kr (by kr) + +theorem good_finishCall {evm e : Evm fork Nat} (h : KR evm e) (kind : CallKind) + (call : CallOperands) (callee : Callee) (s n x : Nat) : + Good frameOf evm (finishCall kind call callee s n x e) := by + unfold finishCall + split + · exact Good.err (by decide) + · dsimp only + split + · exact Good.map_next (good_skipCall (by kr) _ _) + · exact good_genericCall (by kr) _ _ _ _ + +/-- The parts of the calls and the creations, for `good_call`. -/ +syntax "good_call_step" : tactic +macro_rules + | `(tactic| good_call_step) => `(tactic| first + | (refine Good.bind (good_popCallOperands (by kr) _) ?_; rintro ⟨_, _⟩; dsimp only) + | (refine Good.bind (good_popSalt (by kr) _) ?_; rintro ⟨_, _⟩; dsimp only) + | (refine Good.bind (good_accessDelegation (by kr) _ _) ?_; rintro ⟨_, _⟩; dsimp only) + | (refine Good.bind (good_payCall (by kr) _ _ _ _ _) ?_; rintro ⟨_, _⟩; dsimp only) + | exact good_finishCall (by kr) _ _ _ _ _ _ + | exact good_genericCall (by kr) _ _ _ _ + | exact Good.map_next (good_skipCall (by kr) _ _)) + +macro "good_call" : tactic => `(tactic| repeat' (first | good_call_step | good_step)) + +theorem good_callStep {evm : Evm fork Nat} (kind : CallKind) : + Good frameOf evm (callStep kind evm) := by + unfold callStep; good_call + +theorem good_launchCreate {evm e : Evm fork Nat} (h : KR evm e) (v : U256) (code : ByteArray) + (salt : Option U256) : Good frameOf evm (launchCreate e v code salt) := by + unfold launchCreate; good_call + +theorem good_createStep {evm : Evm fork Nat} (create2 : Bool) : + Good frameOf evm (createStep create2 evm) := by + unfold createStep genericCreate; good_call + all_goals exact good_launchCreate (by kr) _ _ _ + +/-- **Every call and creation throws no revert**, and its next frame, or the caller of its +message, has the revert error only from one. -/ +theorem good_message {op : Op} {run : Evm fork Nat → Except EvmError (StepResult fork Nat)} + (hrun : messageInstruction fork op = some run) (evm : Evm fork Nat) : + Good frameOf evm (run evm) := by + unfold messageInstruction at hrun + rcases orElse_eq_some hrun with hf | hf + · cases op <;> simp only [callInstruction, Option.some.injEq, reduceCtorEq] at hf + all_goals (try split at hf) <;> (try simp only [Option.some.injEq, reduceCtorEq] at hf) <;> + (try subst hf) + all_goals first | (cases hf; done) | exact good_callStep _ + · cases op <;> simp only [createInstruction, Option.some.injEq, reduceCtorEq] at hf + all_goals (try split at hf) <;> (try simp only [Option.some.injEq, reduceCtorEq] at hf) <;> + (try subst hf) + all_goals first | (cases hf; done) | exact good_createStep _ + +/-! ## The step -/ + +/-- **No step throws a revert, and only REVERT ends a frame with it**: a step of a frame throws no +revert, and a step that gives a frame with the revert error starts from a frame with it, or runs +REVERT. -/ +theorem step_good (low : Evm fork Nat) : + (∀ e, step fork low = .error e → e ≠ .revert) ∧ + ∀ b, step fork low = .ok (.next b) → b.error = some .revert → + low.error = some .revert ∨ + ∃ h : low.pc < low.code.size, Op.ofByte fork low.code[low.pc] = some .revert := by + unfold step + split + · rename_i hlt + dsimp only + split + · exact ⟨(fun e h => by cases h; intro h'; cases h'), (fun b h => by cases h)⟩ + · rename_i op hop + split + · rename_i run hrun + have g := good_instruction hrun low + refine ⟨fun e h => ?_, fun b h hb => ?_⟩ + · cases hr : run low with + | error e' => rw [hr] at h; cases h; exact g.1 _ hr + | ok c => rw [hr] at h; cases h + · cases hr : run low with + | error e' => rw [hr] at h; cases h + | ok c => + rw [hr] at h + cases h + by_cases hrev : op = .revert + · subst hrev; exact .inr ⟨hlt, hop⟩ + · exact .inl (g.2 hrev _ hr hb) + · split + · rename_i run hm + have g := good_message hm low + exact ⟨g.1, fun b h hb => .inl (g.2 _ h hb)⟩ + · exact ⟨(fun e h => by cases h; intro h'; cases h'), (fun b h => by cases h)⟩ + · refine ⟨(fun e h => by cases h), (fun b h hb => ?_)⟩ + simp only [stopStep, Functor.map, Except.map, Except.ok.injEq, StepResult.next.injEq] at h + subst h + exact .inl hb + +/-- info: 'EthLib.Execution.Evm.RevertErr.step_good' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms step_good + +end EthLib.Execution.Evm.RevertErr diff --git a/SolidCore/Refinement/Solar/EthLibErrLow.lean b/SolidCore/Refinement/Solar/EthLibErrLow.lean new file mode 100644 index 00000000..1f5de3f6 --- /dev/null +++ b/SolidCore/Refinement/Solar/EthLibErrLow.lean @@ -0,0 +1,199 @@ +import SolidCore.Refinement.Solar.EthLibErr + +/-! +# Runs with less gas that revert + +EthLib's `reaches_low` transfers a chain of steps monotone in gas, from a frame with `k` more gas, +to the run with less gas only when that run ends with no error: `StepFails` admits REVERT, so a +run that reverts says nothing of the run with more gas. By `step_good` (no step throws a +revert, and only REVERT ends a frame with it) the transfer holds for a run that reverts too: + +* `revert_step`: REVERT stops the frame, and with `k` more gas gives the same frame with `k` more + gas (REVERT keeps its gas left). +* `reaches_lowR`, `SpecG.lowR`: a chain of steps monotone in gas from `l` with `k` more gas, and a + run of `l` that ends with the revert error: the chain's end is the run's end with `k` more gas. +* `SpecG.lowE`: the same for a run that ends with no error or with the revert error. +-/ + +namespace EthLib.Execution.Evm.RevertErr + +open EthLib.Base (Fork U256) +open EthLib.Execution.Evm.Logic +open GasCosts + +variable {fork : Fork} + +/-- **REVERT keeps its gas left**: it stops the frame, and with `k` more gas it gives the same frame +with `k` more gas. -/ +theorem revert_step (hfork : .byzantium ≤ fork) {low b : Evm fork Nat} + (hlt : low.pc < low.code.size) (hop : Op.ofByte fork low.code[low.pc] = some .revert) + (h : step fork low = .ok (.next b)) : + b.running = false ∧ ∀ k, step fork (addGas k low) = .ok (.next (addGas k b)) := by + have hrun := instruction_revert (Meter := Nat) hfork + rw [step_of_instruction hlt hop hrun, revertStep_eq] at h + cases hc : returnStep low with + | error e => rw [hc] at h; cases h + | ok c => + rw [hc] at h + simp only [Functor.map, Except.map, Except.ok.injEq, StepResult.next.injEq] at h + subst h + refine ⟨(haltWithOutput_stops hc).2, fun k => ?_⟩ + rw [step_of_instruction (evm := addGas k low) hlt hop hrun, revertStep_eq] + obtain ⟨st, sz, rest, hs⟩ : ∃ st sz rest, low.stack.val = st :: sz :: rest := by + rcases hstk : low.stack with ⟨_ | ⟨x, _ | ⟨y, rest⟩⟩, hp⟩ + · simp [returnStep, haltWithOutput, popWord, Stack.pop, hstk, bind, Except.bind] at hc + · simp [returnStep, haltWithOutput, popWord, Stack.pop, hstk, bind, Except.bind, pure, + Except.pure] at hc + · exact ⟨x, y, rest, by simp⟩ + rw [returnStep_cons hs] at hc + rw [returnStep_cons (evm := addGas k low) hs] + have hf := follows_map_charge (fork := fork) (k := k) (gas := low.gas) + (cost := (extendMemory low.memory.size [(st, sz)]).cost) + (F := fun gas => { low with + stack := ⟨rest, by have := low.stack.property; rw [hs] at this; simp at this; omega⟩ + memory := memoryExtend low.memory (extendMemory low.memory.size [(st, sz)]).expandBy + gas + output := memoryReadBytes + (memoryExtend low.memory (extendMemory low.memory.size [(st, sz)]).expandBy) + st.toNat sz.toNat + running := false }) + (fun _ => rfl) + simp only [GasMeter.charge] at hc hf ⊢ + by_cases hlt' : low.gas < (extendMemory low.memory.size [(st, sz)]).cost + · simp [hlt', Except.map] at hc + · have h2 : ¬ low.gas + k < (extendMemory low.memory.size [(st, sz)]).cost := by omega + simp only [hlt', h2, ↓reduceIte, Except.map, Except.ok.injEq] at hc hf ⊢ + subst hc + have hg : low.gas + k - (extendMemory low.memory.size [(st, sz)]).cost = + low.gas - (extendMemory low.memory.size [(st, sz)]).cost + k := by omega + simp only [addGas] + simp only [h2, ↓reduceIte, Functor.map, Except.map, hg] + +theorem measure_next {low b : Evm fork Nat} (running : low.running = true) + (h : step fork low = .ok (.next b)) : measure b < measure low := + step_decreases fork running h + +section Loop + +variable {bound : Nat} {runChild : MessageRunner fork Nat bound} + +/-- **A chain of steps monotone in gas, and a run with less gas that reverts**: from `low` with +`k` more gas to `z`. When the loop runs `low`, which has no revert error, to a frame `s` with +the revert error, `z` is a frame `m` with `k` more gas, and the loop runs `m` to `s` too. -/ +theorem reaches_lowR (hfork : .byzantium ≤ fork) {hi z : Evm fork Nat} + (hr : Reaches (StepG fork) hi z) : + ∀ (k : Nat) (low : Evm fork Nat), hi = addGas k low → low.error ≠ some .revert → + ∀ (within : GasMeter.gasHeld low.gas ≤ bound) {s : Evm fork Nat}, + runFrame (step fork) (step_decreases fork) bound runChild low within = .ok s → + s.error = some .revert → ∃ m within', z = addGas k m ∧ + runFrame (step fork) (step_decreases fork) bound runChild m within' = .ok s := by + induction hr with + | refl => + rintro k low rfl - within s hs - + exact ⟨low, within, rfl, hs⟩ + | @step a b' c hstep hrest ih => + rintro k low rfl hlow within s hs hrev + obtain ⟨hstep, mono⟩ := hstep + have running : low.running = true := by simpa using hstep.running + have good := step_good (fork := fork) low + -- A stopped frame reaches only itself. + have stopped : ∀ {b' z' : Evm fork Nat}, b'.running = false → Reaches (StepG fork) b' z' → + z' = b' := by + intro b' z' hb' hr' + cases hr' with + | refl => rfl + | step h1 _ => + have := h1.1.running + rw [hb'] at this + cases this + -- A REVERT that the step from low runs ends the run there. + have atRevert : ∀ b, step fork low = .ok (.next b) → b.error = some .revert → + ∃ m within', c = addGas k m ∧ + runFrame (step fork) (step_decreases fork) bound runChild m within' = .ok s := by + intro b hb hbe + rcases good.2 b hb hbe with h | ⟨hlt, hop⟩ + · exact absurd h hlow + obtain ⟨hbr, hk⟩ := revert_step hfork hlt hop hb + have hn := hk k + have hb' : _ := hstep + cases hstep with + | next _ hn' => + rw [hn] at hn' + cases hn' + rw [runFrame_of_step_eq_next running hb, runFrame_of_running_eq_false hbr] at hs + cases hs + refine ⟨_, Nat.le_trans (gasHeld_le_of_measure_lt (measure_next running hb)) within, + stopped (by simpa using hbr) hrest, ?_⟩ + exact runFrame_of_running_eq_false hbr + | halt _ hn' _ => + rw [hn] at hn' + cases hn' + rcases mono k low rfl with fails | ⟨b, hb, hh⟩ + · rcases fails with ⟨e, he⟩ | ⟨b, hb, hbr, hbe⟩ + · have hne := good.1 e he + cases ab : e.aborts + · rw [runFrame_of_step_eq_error running he ab] at hs + cases hs + simp only [exceptionalHalt, Option.some.injEq] at hrev + exact absurd hrev hne + · rw [runFrame_of_step_eq_abort running he ab] at hs + cases hs + · have hsb : s = b := by + rw [runFrame_of_step_eq_next running hb, runFrame_of_running_eq_false hbr] at hs + cases hs; rfl + subst hsb + exact atRevert s hb hrev + · by_cases hbe : b.error = some .revert + · exact atRevert b hb hbe + rw [runFrame_of_step_eq_next running hb] at hs + cases hstep with + | next _ hn => + rw [hh] at hn + cases hn + exact ih k b rfl hbe _ hs hrev + | halt _ hn _ => + rw [hh] at hn + cases hn + +/-- A chain of steps monotone in gas from `low` with `k` more gas to a stopped `z`: when the loop +runs `low` to a frame `s` with the revert error, `z` is `s` with `k` more gas. -/ +theorem low_of_reachesR (hfork : .byzantium ≤ fork) {hi z : Evm fork Nat} + (hr : Reaches (StepG fork) hi z) (hz : z.running = false) (k : Nat) (low : Evm fork Nat) + (e : hi = addGas k low) (hlow : low.error ≠ some .revert) + (within : GasMeter.gasHeld low.gas ≤ bound) {s : Evm fork Nat} + (hs : runFrame (step fork) (step_decreases fork) bound runChild low within = .ok s) + (hrev : s.error = some .revert) : z = addGas k s := by + obtain ⟨m, _, rfl, hm⟩ := reaches_lowR hfork hr k low e hlow within hs hrev + rw [runFrame_of_running_eq_false (by simpa using hz)] at hm + cases hm + rfl + +/-- **`SpecG.low` for a run that reverts**: a specification over steps monotone in gas, from `l` +with `k` more gas, and a run of `l` (with no revert error) to a frame `s` with the revert error: +`s` with `k` more gas meets the postcondition. -/ +theorem SpecG.lowR (hfork : .byzantium ≤ fork) {P Q : Evm fork Nat → Prop} (h : SpecG fork P Q) + {k : Nat} {l : Evm fork Nat} (hp : P (addGas k l)) (hl : l.error ≠ some .revert) + (within : GasMeter.gasHeld l.gas ≤ bound) {s : Evm fork Nat} + (hs : Evm.runFrame (step fork) (step_decreases fork) bound runChild l within = .ok s) + (hrev : s.error = some .revert) : Q (addGas k s) := by + obtain ⟨z, hr, hz, hq⟩ := h _ hp + rw [← low_of_reachesR hfork hr hz k l rfl hl within hs hrev] + exact hq + +/-- **`SpecG.low` for a run that ends with no error or reverts.** -/ +theorem SpecG.lowE (hfork : .byzantium ≤ fork) {P Q : Evm fork Nat → Prop} (h : SpecG fork P Q) + {k : Nat} {l : Evm fork Nat} (hp : P (addGas k l)) (hl : l.error ≠ some .revert) + (within : GasMeter.gasHeld l.gas ≤ bound) {s : Evm fork Nat} + (hs : Evm.runFrame (step fork) (step_decreases fork) bound runChild l within = .ok s) + (hok : s.error = none ∨ s.error = some .revert) : Q (addGas k s) := by + rcases hok with hok | hrev + · exact SpecG.low h hp within hs hok + · exact SpecG.lowR hfork h hp hl within hs hrev + +end Loop + +/-- info: 'EthLib.Execution.Evm.RevertErr.SpecG.lowE' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms SpecG.lowE + +end EthLib.Execution.Evm.RevertErr diff --git a/SolidCore/Refinement/Solar/EventWords/Lowering.lean b/SolidCore/Refinement/Solar/EventWords/Lowering.lean new file mode 100644 index 00000000..3e8c70e1 --- /dev/null +++ b/SolidCore/Refinement/Solar/EventWords/Lowering.lean @@ -0,0 +1,397 @@ +import SolidCore.Refinement.Generic.Value +import SolidCore.Refinement.KernelCopies +import SolidCore.Refinement.KernelRfl +import SolidCore.Refinement.Source.EventWords +import event_words.gen.EventWords.Stage0 + +/-! +# event_words: the generic source stage on solar's own module + +scripts/refinement/mem/event_words.sol, + + contract EventWords { + event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, + uint256 amount0Out, uint256 amount1Out, address indexed to); + function swap(uint256 a0, uint256 a1, uint256 b0, uint256 b1, address to) external { + emit Swap(msg.sender, a0, a1, b0, b1, to); } } + +logs with three topics (the signature's, the caller, `to`) and four data words, the shape of +Uniswap v2's `Swap`, `Mint`, `Burn` and `Sync` events. Solar ABI-encodes the data at the free +memory pointer: its first lowered MIR module stores the entry heap `0x80` at `0x40` on entering +`swap` (`Function.entryHeap`), reads it back with `mload 0x40` against the `heap_floor`, and +writes the four words from there before `log 3`. The generic symbolic run takes the entry heap, +the heap floor and the constant `mload` (`Generic.symStart`, `symInsts`, `symEffect`). + +* `shape_eq`: `EventWords` type checks, its core is `coreLit`, its constructor leaves no storage; +* `check_stage0`, `checkValue_stage0`: the generic check with the caller-only flags accepts + stage0 for `swap` (`decide +kernel`), at no value and at any value; +* `check_rejects_caller`, `check_rejects_topic`, `check_rejects_order`, `check_rejects_data`, + `check_rejects_heap`: it rejects stage0 with the caller topic replaced by an argument, with the + signature topic changed, with the two indexed topics swapped, with two data words swapped and + with another entry heap; +* `lowering`, `loweringValue`: the stage from SolidCore to stage0 on every call of `swap`, from + any storage, under every oracle with SolidCore's caller (`Generic.CallerOk`). + +No sorry, native_decide or bv_decide. +-/ + +namespace SolidCore.Refinement.Solar.EventWords + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity SolidCore.Solidity.Source + +/-- The interpreter fuel of SolidCore's runs. -/ +def fuel : Nat := 4096 + +/-- The interpreter fuel of the symbolic run of the module: steps along each path. -/ +def mirFuel : Nat := 40 + +/-- SolidCore's checked `EventWords`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.EventWords.importedSourceUnit "EventWords" + +/-- The selector of `swap(uint256,uint256,uint256,uint256,address)`. -/ +abbrev swapSel : Nat := 0x562e19df + +/-- `swap` and its parameters. -/ +def fnSwap : Fn := ⟨swapSel, [.uint 256, .uint 256, .uint 256, .uint 256, .uint 160]⟩ + +/-- The external function of `EventWords`. -/ +def fns : List Fn := [fnSwap] + +/-- SolidCore's core contract of `EventWords`, as the type checker leaves it. -/ +def coreLit : Contract := + { storageFields := [], + immutableFields := [], + eventDecls := [{ name := "Swap", + indexedCount := 2, + topic? := some 97492587597809768260878645486617631645481691101407825574583615073533464008738, + fields := [{ ty := SolidCore.Solidity.Source.Ty.address, indexed := true }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := false }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := false }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := false }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := false }, + { ty := SolidCore.Solidity.Source.Ty.address, indexed := true }] }, + { name := "EventWords.Swap", + indexedCount := 2, + topic? := some 97492587597809768260878645486617631645481691101407825574583615073533464008738, + fields := [{ ty := SolidCore.Solidity.Source.Ty.address, indexed := true }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := false }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := false }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := false }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := false }, + { ty := SolidCore.Solidity.Source.Ty.address, indexed := true }] }], + errorDecls := [], + functions := [{ name := "swap", + selector? := some 1445861855, + payable := false, + params := [{ name := "a0", + ty := SolidCore.Solidity.Source.Ty.uint256, + isStorageRef := false }, + { name := "a1", + ty := SolidCore.Solidity.Source.Ty.uint256, + isStorageRef := false }, + { name := "b0", + ty := SolidCore.Solidity.Source.Ty.uint256, + isStorageRef := false }, + { name := "b1", + ty := SolidCore.Solidity.Source.Ty.uint256, + isStorageRef := false }, + { name := "to", + ty := SolidCore.Solidity.Source.Ty.address, + isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256, + SolidCore.Solidity.Source.AbiCleanup.uint 256, + SolidCore.Solidity.Source.AbiCleanup.uint 256, + SolidCore.Solidity.Source.AbiCleanup.uint 256, + SolidCore.Solidity.Source.AbiCleanup.none], + returns := [], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "a0") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "a0")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "a1") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "a1")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "b0") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "b0")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "b1") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "b1")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.emitEvent + "Swap" + [SolidCore.Solidity.Source.Expr.caller, + SolidCore.Solidity.Source.Expr.var "a0", + SolidCore.Solidity.Source.Expr.var "a1", + SolidCore.Solidity.Source.Expr.var "b0", + SolidCore.Solidity.Source.Expr.var "b1", + SolidCore.Solidity.Source.Expr.var "to"]]], + dispatchId? := none }, + { name := "__internal_swap(uint256,uint256,uint256,uint256,address)#[SolidCore.Solidity.Ty.uint 256, SolidCore.Solidity.Ty.uint 256, SolidCore.Solidity.Ty.uint 256, SolidCore.Solidity.Ty.uint 256, SolidCore.Solidity.Ty.address false]", + selector? := none, + payable := false, + params := [{ name := "a0", + ty := SolidCore.Solidity.Source.Ty.uint256, + isStorageRef := false }, + { name := "a1", + ty := SolidCore.Solidity.Source.Ty.uint256, + isStorageRef := false }, + { name := "b0", + ty := SolidCore.Solidity.Source.Ty.uint256, + isStorageRef := false }, + { name := "b1", + ty := SolidCore.Solidity.Source.Ty.uint256, + isStorageRef := false }, + { name := "to", + ty := SolidCore.Solidity.Source.Ty.address, + isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256, + SolidCore.Solidity.Source.AbiCleanup.uint 256, + SolidCore.Solidity.Source.AbiCleanup.uint 256, + SolidCore.Solidity.Source.AbiCleanup.uint 256, + SolidCore.Solidity.Source.AbiCleanup.none], + returns := [], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "a0") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "a0")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "a1") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "a1")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "b0") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "b0")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "b1") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "b1")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.emitEvent + "Swap" + [SolidCore.Solidity.Source.Expr.caller, + SolidCore.Solidity.Source.Expr.var "a0", + SolidCore.Solidity.Source.Expr.var "a1", + SolidCore.Solidity.Source.Expr.var "b0", + SolidCore.Solidity.Source.Expr.var "b1", + SolidCore.Solidity.Source.Expr.var "to"]]], + dispatchId? := none }] } + +/-! ## The selectors and the event's signature topic + +The type checker computes each external function's selector and the event's topic by +Keccak-256, which costs the kernel about 400 MB a hash: each is checked once, alone, and the +check of the shape below runs on copies that read them from tables. -/ +/-- The selector of `swap(uint256,uint256,uint256,uint256,address)`, by Keccak-256 of its signature. -/ +def selSwap : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "swap(uint256,uint256,uint256,uint256,address)" + +kernel_rfl selSwap_eq selSwap swapSel +/-- The topic of `Swap(address,uint256,uint256,uint256,uint256,address)`, by Keccak-256 of its signature. -/ +def topic : Nat := SolidCore.Solidity.Source.Keccak.digestWord "Swap(address,uint256,uint256,uint256,uint256,address)" + +kernel_rfl topic_eq topic 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822 + +/-- `ABI.selectorFromSignature`, with `EventWords`'s signatures by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "swap(uint256,uint256,uint256,uint256,address)" then swapSel + else SolidCore.Solidity.Source.ABI.selectorFromSignature s + +theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + split + · next h => subst h; exact selSwap_eq + · rfl + +/-- `Keccak.digestWord`, with the event's signature by table. -/ +def digestTable (s : String) : Nat := + if s = "Swap(address,uint256,uint256,uint256,uint256,address)" then 0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822 else SolidCore.Solidity.Source.Keccak.digestWord s + +theorem digest_eq : SolidCore.Solidity.Source.Keccak.digestWord = digestTable := by + funext s + unfold digestTable + split + · next h => subst h; exact topic_eq + · rfl + +/-- SolidCore's checked core of `EventWords`, and whether its constructor leaves no storage and no +logs, when `EventWords` type checks. -/ +def shape? : Option (Contract × Bool) := + match contract? with + | .ok c => some (c.core, Wide.deployedAt fuel c []) + | .error _ => none + +-- `shape_eq : shape? = some (coreLit, true)`: `EventWords` type checks, its core is `coreLit` and its +-- constructor leaves no storage, by the kernel's conversion check on the copy of `shape?` that +-- reads the selectors and the topic from their tables. +kernel_rfl shape_eq shape? (some (coreLit, true)) using selector_eq digest_eq + +/-! ## The check on solar's module -/ +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for `swap`. -/ +theorem check_swap : + Generic.check fuel mirFuel coreLit SolarTV.Export.EventWords.stage0 [fnSwap] .callerOnly = true := by + decide +kernel + +/-- The generic check accepts stage0 for every external function. -/ +theorem check_stage0 : + Generic.check fuel mirFuel coreLit SolarTV.Export.EventWords.stage0 fns .callerOnly = true := by + have h0 := check_swap + simp only [Generic.check, List.all_cons, List.all_nil, Bool.and_true] at h0 + simp only [Generic.check, fns, List.all_cons, List.all_nil, Bool.and_true, h0] + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: no function is payable, and stage0 reverts with empty output on a +call of each with a value other than 0. -/ +theorem checkValue_stage0 : + Generic.checkValue mirFuel coreLit SolarTV.Export.EventWords.stage0 fns .callerOnly = true := by + decide +kernel + +/-! ## Mutants the check rejects -/ + +/-- stage0 with each instruction of function `i` changed by `f`. -/ +def mapFn (i : Nat) (f : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst) : + SolarTV.MIR.Lowered.Module := + { SolarTV.Export.EventWords.stage0 with + functions := SolarTV.Export.EventWords.stage0.functions.mapIdx fun j fn => + if j = i then { fn with blocks := fn.blocks.map fun b => { b with insts := b.insts.map f } } + else fn } +/-- `swap` logging an argument word as the caller topic. -/ +def noCaller : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect (some 6) .caller [] => .effect (some 6) .calldataload [.const 4] + | i => i + +/-- `swap`'s log with another signature topic. -/ +def wrongTopic : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect none (.log 3) [a, b, .const t, c, d] => .effect none (.log 3) [a, b, .const (t + 1), c, d] + | i => i + +/-- `swap`'s log with its indexed topics swapped. -/ +def swapTopics : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect none (.log 3) [a, b, t, c, d] => .effect none (.log 3) [a, b, t, d, c] + | i => i + +/-- `swap` writing its first two data words in each other's place. -/ +def swapData : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect none .mstore [.value 45, .value 17] => .effect none .mstore [.value 45, .value 19] + | .effect none .mstore [.value 33, .value 19] => .effect none .mstore [.value 33, .value 17] + | i => i + +/-- stage0 with `swap`'s entry heap moved by a word, so that its `assume` on the free memory +pointer fails. -/ +def wrongHeap : SolarTV.MIR.Lowered.Module := + { SolarTV.Export.EventWords.stage0 with + functions := SolarTV.Export.EventWords.stage0.functions.mapIdx fun j fn => + if j = 0 then { fn with entryHeap := some 160 } else fn } + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects `swap` logging an argument as the caller. -/ +theorem check_rejects_caller : + Generic.check fuel mirFuel coreLit (mapFn 0 noCaller) fns .callerOnly = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects `swap` with the wrong signature topic. -/ +theorem check_rejects_topic : + Generic.check fuel mirFuel coreLit (mapFn 0 wrongTopic) fns .callerOnly = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects `swap` with its topics swapped. -/ +theorem check_rejects_order : + Generic.check fuel mirFuel coreLit (mapFn 0 swapTopics) fns .callerOnly = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects `swap` with two data words swapped. -/ +theorem check_rejects_data : + Generic.check fuel mirFuel coreLit (mapFn 0 swapData) fns .callerOnly = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects stage0 with another entry heap. -/ +theorem check_rejects_heap : + Generic.check fuel mirFuel coreLit wrongHeap fns .callerOnly = false := by + decide +kernel + +/-! ## The stage -/ + +/-- The checked contract has the core `coreLit`, and its constructor leaves no storage. -/ +theorem deployed_of {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core = coreLit ∧ ∃ d, Wide.DeployedAt fuel c d [] := by + have h := shape_eq + unfold shape? at h + rw [hc] at h + obtain ⟨hk, hd⟩ := Prod.mk.inj (Option.some.inj h) + exact ⟨hk, Wide.deployedAt_of hd⟩ + +/-- **The source stage of `EventWords`**: every call of `swap` on any argument words, no value, +from any storage, under every oracle whose caller is SolidCore's (`Generic.CallerOk`): `EventWords` +hashes nothing at run time, so the check runs with the caller-only flags. -/ +theorem lowering (o : SolarTV.Machine.Oracle) (henv : Generic.CallerOk o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.EventWords.stage0 (fun call => ∃ σ, fullScope fns σ call) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact Generic.stageCaller o henv hd (by rw [hk]; exact check_stage0) + +/-- **The source stage of `EventWords` at every value**: the same calls with any value below `2 ^ 256`: `swap` is not payable, and both sides revert with empty data. -/ +theorem loweringValue (o : SolarTV.Machine.Oracle) (henv : Generic.CallerOk o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.EventWords.stage0 (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact Generic.stageValueCaller o henv hd (by rw [hk]; exact check_stage0) + (by rw [hk]; exact checkValue_stage0) + +#print axioms selector_eq + +#print axioms digest_eq + +#print axioms shape_eq + +#print axioms check_stage0 + +#print axioms checkValue_stage0 + +#print axioms check_rejects_caller + +#print axioms check_rejects_topic + +#print axioms check_rejects_order + +#print axioms check_rejects_data + +#print axioms check_rejects_heap + +#print axioms lowering + +#print axioms loweringValue + +end SolidCore.Refinement.Solar.EventWords diff --git a/SolidCore/Refinement/Solar/Events/Assembly.lean b/SolidCore/Refinement/Solar/Events/Assembly.lean new file mode 100644 index 00000000..e70083c8 --- /dev/null +++ b/SolidCore/Refinement/Solar/Events/Assembly.lean @@ -0,0 +1,110 @@ +import SolidCore.Refinement.Solar.AssembleSim +import SolidCore.Refinement.Solar.AssembleFast +import events.gen.Events.Evm5 +import events.gen.Events.Bytecode +import events.Proofs.Stages + +/-! +# events: the final EVM IR to solar's bytecode + +solar-tv/milestone/events/events.sol (`transfer(uint256 id, uint256 value)` emitting +`Transfer(address indexed from, uint256 indexed id, uint256 value)` for `msg.sender`) compiles with +solar 0a455fda to the final EVM IR evm5 and to 130 bytes of runtime bytecode (sha256 +5ad38c8bca24e0ca8c4a5e95f1f07bf993aad9a02ac3bc0872fc41fab8a6298b), exported by +-Zemit-lean-stages into solar's solar-tv/milestone/events. Solar's milestone proves the stages +from the first lowered MIR to evm5 (SolarTV.Milestone.Events.events_mir_to_evmir); this file +proves evm5 to the bytecode with the generic assembler check: LOG3 with the event's signature, +the caller and the id as topics and the value's word at offset 0 as data, under every oracle whose +CALLER is the caller of EthLib's calls (`Assemble.OracleOk`). + +* check_ok: the checker accepts evm5 and the bytes with cert, by the kernel's evaluation of its + one-pass form (`Assemble.checkFast`, equal to it by `Assemble.check_eq_checkFast`). +* stageOk, backend: EVM IR to bytecode, and the first lowered MIR to bytecode, on every call. +* mutant…_check: the checker rejects one-byte mutants of the caller, the log's topic count, its + signature topic, its data size and its data offset. +-/ + +namespace SolidCore.Refinement.Solar.Events + +open SolarTV.Assembly SolarTV.Export.Events + +/-- The runtime bytecode solar exported. -/ +def code : ByteArray := ⟨(bytecode.map UInt8.ofNat).toArray⟩ + +/-- The certificate: the three blocks' offsets (the dispatcher and transfer, the empty revert at +0x53 and the address check's revert at 0x57, which reads one data word from its entry stack), +the reverts' 128 bytes of memory, each block's potential and that the program reads the caller. -/ +def cert : Assemble.Cert := + { offsets := [0, 0x53, 0x57], needs := [0, 0, 1], top := 128, costs := [58, 4, 22], + types := [[], [], [some false]], env := true } + +set_option maxRecDepth 100000 in +/-- The checker accepts solar's bytecode for the program, by the kernel's evaluation. -/ +theorem check_ok : Assemble.check evm5 code cert = true := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +/-- EVM IR to bytecode is a stage for events on every call, under every oracle whose caller +and hash are EthLib's. -/ +theorem stageOk (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) + (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.evmirSem o) SolidCore.Refinement.ethLib evm5 + (show SolidCore.Refinement.ethLib.Prog from code) scope := + Assemble.stage_of_check_env check_ok o (fun _ => ho) scope + +/-- The backend: solar-tv's stages from stage0 to evm5, then the assembly stage. -/ +theorem backend (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) + (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.mirSem o) SolidCore.Refinement.ethLib stage0 + (show SolidCore.Refinement.ethLib.Prog from code) scope := + SolarTV.Stage.trans (B := SolarTV.evmirSem o) + (fun call _ => SolarTV.Milestone.Events.events_mir_to_evmir o call trivial) (stageOk o ho scope) + +/-- The bytes with the byte at i replaced by b. -/ +def mutant (i b : Nat) : ByteArray := ⟨((bytecode.set i b).map UInt8.ofNat).toArray⟩ + +/-- The bytes the mutants replace: CALLER (0x22), the signature topic's first byte (0x24), the +data size's immediate (0x45), the data offset's PUSH0 (0x46) and LOG3 (0x47). -/ +theorem mutated_bytes : bytecode[0x22]? = some 0x33 ∧ bytecode[0x24]? = some 0x7f ∧ + bytecode[0x45]? = some 0x20 ∧ bytecode[0x46]? = some 0x5f ∧ bytecode[0x47]? = some 0xa3 := by + decide + +set_option maxRecDepth 100000 in +/-- ORIGIN for CALLER: rejected. -/ +theorem mutantCaller_check : Assemble.check evm5 (mutant 0x22 0x32) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +set_option maxRecDepth 100000 in +/-- LOG2 for LOG3: rejected. -/ +theorem mutantLog_check : Assemble.check evm5 (mutant 0x47 0xa2) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +set_option maxRecDepth 100000 in +/-- Another signature topic: rejected. -/ +theorem mutantTopic_check : Assemble.check evm5 (mutant 0x24 0x7e) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +set_option maxRecDepth 100000 in +/-- Two words of data for one: rejected. -/ +theorem mutantSize_check : Assemble.check evm5 (mutant 0x45 0x40) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +set_option maxRecDepth 100000 in +/-- The data at MSIZE, another offset: rejected. -/ +theorem mutantOffset_check : Assemble.check evm5 (mutant 0x46 0x59) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +/-- info: 'SolidCore.Refinement.Solar.Events.check_ok' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms check_ok + +/-- info: 'SolidCore.Refinement.Solar.Events.backend' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms backend + +end SolidCore.Refinement.Solar.Events diff --git a/SolidCore/Refinement/Solar/Events/Certified.lean b/SolidCore/Refinement/Solar/Events/Certified.lean new file mode 100644 index 00000000..dd3e1bc1 --- /dev/null +++ b/SolidCore/Refinement/Solar/Events/Certified.lean @@ -0,0 +1,136 @@ +import SolidCore.Refinement.Solar.Events.Lowering +import SolidCore.Refinement.Solar.Events.Assembly +import SolidCore.Refinement.Solar.Hex +import events.gen.Events.Manifest + +/-! +# events: SolidCore to solar's bytecode, through every stage + +The end-to-end translation of `Events` (Lowering.lean has the contract), chaining with +`Stage.trans`: + +1. the source stage, SolidCore's checked `Events` to solar's first lowered MIR stage0 + (`lowering`, `loweringValue`), under every oracle whose caller is SolidCore's + `callerAddress` (`Generic.CallerOk`): `Events` hashes nothing at run time; +2. solar-tv's backend stages from stage0 to the final EVM IR, and the assembly stage to the + runtime bytecode (Assembly.lean, `backend`), under every oracle whose caller and hash are + EthLib's (`Assemble.OracleOk`). + +An oracle with EthLib's caller has SolidCore's (`callerOk_of`), so `certified` holds under +`Assemble.OracleOk` alone, for every call of `transfer` on any argument words, from any +storage, with no value, and `certifiedValue` with any value. + +`certifiedManifest` binds both to the export's manifest (gen/…/Manifest.lean): the source's path +and sha256, the compiler's version and commit, its arguments, optimization and EVM version, the +bytecode's sha256 and hex, that the hex is the lowercase hex of the bytes the stages run +(`manifest_hex`, by the kernel's unfolding) and decodes to them (`bytecode_of_manifest`), and +the stages as one conjunction. `mutant_hex_rejected`: a one-byte mutant's hex does not +decode to those bytes. The sha256s are of the files, checked outside the kernel (solar's +certify.sh; the source's, each stage's and the bytecode's match the files at solar c8ea95b8f). + +No sorry, native_decide or bv_decide: the theorems depend on propext, Classical.choice and +Quot.sound only (pinned below). +-/ + +namespace SolidCore.Refinement.Solar.Events + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity + +/-- EthLib's caller is SolidCore's `callerAddress`, as a word. -/ +theorem callerAddress_word : + (SolidCore.Refinement.Target.address SolidCore.Refinement.callerAddress).toU256.toNat = + Generic.callerWord := by + decide +kernel + +/-- An oracle with EthLib's caller has SolidCore's. -/ +theorem callerOk_of (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) : Generic.CallerOk o := by + unfold Generic.CallerOk + rw [ho.1] + exact callerAddress_word + +/-- **Events from SolidCore to solar's bytecode**: every result SolidCore's `Events` gives on a +call of `transfer` on any argument words, no value, from any storage, the bytecode gives under +EthLib, for every oracle with EthLib's caller and hash. -/ +theorem certified (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) ethLib c code (fun call => ∃ σ, fullScope fns σ call) := + (lowering o (callerOk_of o ho) hc).trans (backend o ho _) + +/-- **Events from SolidCore to solar's bytecode at every value**. -/ +theorem certifiedValue (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) ethLib c code (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := + (loweringValue o (callerOk_of o ho) hc).trans (backend o ho _) + +open SolarTV.Export.Events Hex in +set_option maxRecDepth 100000 in +/-- The manifest's hex is the lowercase hex of the bytes the stages run. -/ +theorem manifest_hex : Manifest.bytecodeHex = String.ofList (hexChars bytecode) := by rfl + +open SolarTV.Export.Events Hex in +set_option maxRecDepth 100000 in +/-- The bytes the stages run are the manifest's hex, which --emit=bin-runtime printed. -/ +theorem bytecode_of_manifest : hexBytes (codes Manifest.bytecodeHex) = some bytecode := by + rw [manifest_hex, codes, String.toList_ofList] + -- The instance is spelled out: with EvmYul in scope, instance search finds EvmYul's + -- `Stack.instDecidableEq` for `List Nat`. + exact @of_decide_eq_true _ + (@Option.instDecidableEq _ (@instDecidableEqList _ instDecidableEqNat) _ _) (by decide +kernel) + +open SolarTV.Export.Events Hex in +set_option maxRecDepth 100000 in +/-- A one-byte mutant's hex (the first byte, CALLVALUE, as ORIGIN) does not decode to the bytes +the stages run: the link fails by mismatch. -/ +theorem mutant_hex_rejected : + hexBytes ((hexChars (bytecode.set 0 0x32)).map Char.toNat) ≠ some bytecode := by + exact @of_decide_eq_false (hexBytes ((hexChars (bytecode.set 0 0x32)).map Char.toNat) = some bytecode) + (@Option.instDecidableEq _ (@instDecidableEqList _ instDecidableEqNat) _ _) (by decide +kernel) + +open SolarTV.Export.Events Hex in +/-- **The certified translation of events**, bound to what it was compiled from and by: the +source (path and sha256), its arguments (-Ogas, osaka), +the bytecode with its sha256 and hex, the bytes the stages run as that bytecode, and the stage +from SolidCore's checked `Events` to those bytes, with no value and with any value, on every call +of `transfer` from any storage, under every oracle with EthLib's caller and hash. -/ +theorem certifiedManifest (o : SolarTV.Machine.Oracle) (ho : Assemble.OracleOk o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Manifest.sources = [("Certified/events/events.sol", + "c935cf243f303a252e4ee0bb10c9c75130eef92ca6c4a954830e67af9a939214")] ∧ + Manifest.arguments = ["Certified/events/events.sol", "-Ogas", "--evm-version", "osaka", + "--emit=bin-runtime", "-Zemit-lean-stages=Certified/events/gen"] ∧ + Manifest.optimization = "Gas" ∧ Manifest.evmVersion = "osaka" ∧ + Manifest.bytecodeSha256 = "5ad38c8bca24e0ca8c4a5e95f1f07bf993aad9a02ac3bc0872fc41fab8a6298b" ∧ + Manifest.bytecodeHex = bytecodeHex ∧ + Manifest.bytecodeHex = String.ofList (hexChars bytecode) ∧ + hexBytes (codes Manifest.bytecodeHex) = some bytecode ∧ + code = ⟨(bytecode.map UInt8.ofNat).toArray⟩ ∧ + Stage (solidCore fuel) ethLib c code (fun call => ∃ σ, fullScope fns σ call) ∧ + Stage (solidCore fuel) ethLib c code (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := + ⟨rfl, rfl, rfl, rfl, rfl, rfl, manifest_hex, bytecode_of_manifest, rfl, certified o ho hc, + certifiedValue o ho hc⟩ + +/-- info: 'SolidCore.Refinement.Solar.Events.callerOk_of' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms callerOk_of + +/-- info: 'SolidCore.Refinement.Solar.Events.certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified + +/-- info: 'SolidCore.Refinement.Solar.Events.certifiedValue' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedValue + +/-- info: 'SolidCore.Refinement.Solar.Events.manifest_hex' does not depend on any axioms -/ +#guard_msgs in +#print axioms manifest_hex + +/-- info: 'SolidCore.Refinement.Solar.Events.bytecode_of_manifest' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms bytecode_of_manifest + +/-- info: 'SolidCore.Refinement.Solar.Events.certifiedManifest' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedManifest + +end SolidCore.Refinement.Solar.Events diff --git a/SolidCore/Refinement/Solar/Events/Lowering.lean b/SolidCore/Refinement/Solar/Events/Lowering.lean new file mode 100644 index 00000000..266d6427 --- /dev/null +++ b/SolidCore/Refinement/Solar/Events/Lowering.lean @@ -0,0 +1,296 @@ +import SolidCore.Refinement.Generic.Value +import SolidCore.Refinement.KernelCopies +import SolidCore.Refinement.KernelRfl +import SolidCore.Refinement.Source.Events +import events.gen.Events.Stage0 + +/-! +# events: the generic source stage on solar's own module + +solar-tv/milestone/events/events.sol (sha256 +c935cf243f303a252e4ee0bb10c9c75130eef92ca6c4a954830e67af9a939214, copied to +scripts/refinement/events/events.sol), + + contract Events { + event Transfer(address indexed from, uint256 indexed id, uint256 value); + function transfer(uint256 id, uint256 value) external { emit Transfer(msg.sender, id, value); } } + +logs with three topics (the signature's, the caller, `id`) and `value`'s word as data. +`SolarTV.Export.Events.stage0` is solar's first lowered MIR module for it (solar 0a455fda), +from solar's solar-tv/milestone/events, whose backend stages solar's milestone proves +(`SolarTV.Milestone.Events.events_mir_to_evmir`): `log 3` of the memory word 0 with the +signature, `caller` and the first argument as topics. + +* `shape_eq`: `Events` type checks, its core is `coreLit`, its constructor leaves no storage; +* `check_stage0`, `checkValue_stage0`: the generic check with the caller-only flags accepts + stage0 for `transfer` (`decide +kernel`), at no value and at any value; +* `check_rejects_caller`, `check_rejects_topic`, `check_rejects_order`: it rejects stage0 + with the caller topic replaced by the value, with the signature topic changed, and with the + two indexed topics swapped; +* `lowering`, `loweringValue`: the stage from SolidCore to stage0 on every call of + `transfer`, from any storage, under every oracle with SolidCore's caller (`Generic.CallerOk`). + +No sorry, native_decide or bv_decide. +-/ + +namespace SolidCore.Refinement.Solar.Events + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity SolidCore.Solidity.Source + +/-- The interpreter fuel of SolidCore's runs. -/ +def fuel : Nat := 4096 + +/-- The interpreter fuel of the symbolic run of the module: steps along each path. -/ +def mirFuel : Nat := 40 + +/-- SolidCore's checked `Events`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.Events.importedSourceUnit "Events" + +/-- The selector of `transfer(uint256,uint256)`. -/ +abbrev transferSel : Nat := 0x0cf79e0a + +/-- `transfer` and its parameters. -/ +def fnTransfer : Fn := ⟨transferSel, [.uint 256, .uint 256]⟩ + +/-- The external function of `Events`. -/ +def fns : List Fn := [fnTransfer] + +/-- SolidCore's core contract of `Events`, as the type checker leaves it. -/ +def coreLit : Contract := + { storageFields := [], + immutableFields := [], + eventDecls := [{ name := "Transfer", + indexedCount := 2, + topic? := some 57743509088182381206199446994789903859235539828100749539486038820882091805673, + fields := [{ ty := SolidCore.Solidity.Source.Ty.address, indexed := true }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := true }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := false }] }, + { name := "Events.Transfer", + indexedCount := 2, + topic? := some 57743509088182381206199446994789903859235539828100749539486038820882091805673, + fields := [{ ty := SolidCore.Solidity.Source.Ty.address, indexed := true }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := true }, + { ty := SolidCore.Solidity.Source.Ty.uint256, indexed := false }] }], + errorDecls := [], + functions := [{ name := "transfer", + selector? := some 217554442, + payable := false, + params := [{ name := "id", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }, + { name := "value", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256, + SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "id") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "id")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "value") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "value")), + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.emitEvent + "Transfer" + [SolidCore.Solidity.Source.Expr.caller, + SolidCore.Solidity.Source.Expr.var "id", + SolidCore.Solidity.Source.Expr.var "value"]]], + dispatchId? := none }, + { name := "__internal_transfer(uint256,uint256)#[SolidCore.Solidity.Ty.uint 256, SolidCore.Solidity.Ty.uint 256]", + selector? := none, + payable := false, + params := [{ name := "id", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }, + { name := "value", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 256, + SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "id") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "id")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "value") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "value")), + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.emitEvent + "Transfer" + [SolidCore.Solidity.Source.Expr.caller, + SolidCore.Solidity.Source.Expr.var "id", + SolidCore.Solidity.Source.Expr.var "value"]]], + dispatchId? := none }] } + +/-! ## The selectors and the event's signature topic + +The type checker computes each external function's selector and the event's topic by +Keccak-256, which costs the kernel about 400 MB a hash: each is checked once, alone, and the +check of the shape below runs on copies that read them from tables. -/ +/-- The selector of `transfer(uint256,uint256)`, by Keccak-256 of its signature. -/ +def selTransfer : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "transfer(uint256,uint256)" + +kernel_rfl selTransfer_eq selTransfer transferSel +/-- The topic of `Transfer(address,uint256,uint256)`, by Keccak-256 of its signature. -/ +def topic : Nat := SolidCore.Solidity.Source.Keccak.digestWord "Transfer(address,uint256,uint256)" + +kernel_rfl topic_eq topic 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9 + +/-- `ABI.selectorFromSignature`, with `Events`'s signatures by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "transfer(uint256,uint256)" then transferSel + else SolidCore.Solidity.Source.ABI.selectorFromSignature s + +theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + split + · next h => subst h; exact selTransfer_eq + · rfl + +/-- `Keccak.digestWord`, with the event's signature by table. -/ +def digestTable (s : String) : Nat := + if s = "Transfer(address,uint256,uint256)" then 0x7fa9aafeb8bb803d77de5d84bc2f2edbd842ca91b20cd5020aa21dfe26ab0be9 else SolidCore.Solidity.Source.Keccak.digestWord s + +theorem digest_eq : SolidCore.Solidity.Source.Keccak.digestWord = digestTable := by + funext s + unfold digestTable + split + · next h => subst h; exact topic_eq + · rfl + +/-- SolidCore's checked core of `Events`, and whether its constructor leaves no storage and no +logs, when `Events` type checks. -/ +def shape? : Option (Contract × Bool) := + match contract? with + | .ok c => some (c.core, Wide.deployedAt fuel c []) + | .error _ => none + +-- `shape_eq : shape? = some (coreLit, true)`: `Events` type checks, its core is `coreLit` and its +-- constructor leaves no storage, by the kernel's conversion check on the copy of `shape?` that +-- reads the selectors and the topic from their tables. +kernel_rfl shape_eq shape? (some (coreLit, true)) using selector_eq digest_eq + +/-! ## The check on solar's module -/ +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for `transfer`. -/ +theorem check_transfer : + Generic.check fuel mirFuel coreLit SolarTV.Export.Events.stage0 [fnTransfer] .callerOnly = true := by + decide +kernel + +/-- The generic check accepts stage0 for every external function. -/ +theorem check_stage0 : + Generic.check fuel mirFuel coreLit SolarTV.Export.Events.stage0 fns .callerOnly = true := by + have h0 := check_transfer + simp only [Generic.check, List.all_cons, List.all_nil, Bool.and_true] at h0 + simp only [Generic.check, fns, List.all_cons, List.all_nil, Bool.and_true, h0] + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: no function is payable, and stage0 reverts with empty output on a +call of each with a value other than 0. -/ +theorem checkValue_stage0 : + Generic.checkValue mirFuel coreLit SolarTV.Export.Events.stage0 fns .callerOnly = true := by + decide +kernel + +/-! ## Mutants the check rejects -/ + +/-- stage0 with each instruction of function `i` changed by `f`. -/ +def mapFn (i : Nat) (f : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst) : + SolarTV.MIR.Lowered.Module := + { SolarTV.Export.Events.stage0 with + functions := SolarTV.Export.Events.stage0.functions.mapIdx fun j fn => + if j = i then { fn with blocks := fn.blocks.map fun b => { b with insts := b.insts.map f } } + else fn } +/-- `transfer` logging its value word as the caller topic. -/ +def noCaller : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect (some 3) .caller [] => .effect (some 3) .calldataload [.const 36] + | i => i + +/-- `transfer`'s log with another signature topic. -/ +def wrongTopic : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect none (.log 3) [a, b, .const t, c, d] => .effect none (.log 3) [a, b, .const (t + 1), c, d] + | i => i + +/-- `transfer`'s log with its indexed topics swapped. -/ +def swapTopics : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .effect none (.log 3) [a, b, t, c, d] => .effect none (.log 3) [a, b, t, d, c] + | i => i + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects `transfer` logging the value as the caller. -/ +theorem check_rejects_caller : + Generic.check fuel mirFuel coreLit (mapFn 0 noCaller) fns .callerOnly = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects `transfer` with the wrong signature topic. -/ +theorem check_rejects_topic : + Generic.check fuel mirFuel coreLit (mapFn 0 wrongTopic) fns .callerOnly = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects `transfer` with its topics swapped. -/ +theorem check_rejects_order : + Generic.check fuel mirFuel coreLit (mapFn 0 swapTopics) fns .callerOnly = false := by + decide +kernel + +/-! ## The stage -/ + +/-- The checked contract has the core `coreLit`, and its constructor leaves no storage. -/ +theorem deployed_of {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core = coreLit ∧ ∃ d, Wide.DeployedAt fuel c d [] := by + have h := shape_eq + unfold shape? at h + rw [hc] at h + obtain ⟨hk, hd⟩ := Prod.mk.inj (Option.some.inj h) + exact ⟨hk, Wide.deployedAt_of hd⟩ + +/-- **The source stage of `Events`**: every call of `transfer` on any argument words, no value, +from any storage, under every oracle whose caller is SolidCore's (`Generic.CallerOk`): `Events` +hashes nothing at run time, so the check runs with the caller-only flags. -/ +theorem lowering (o : SolarTV.Machine.Oracle) (henv : Generic.CallerOk o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Events.stage0 (fun call => ∃ σ, fullScope fns σ call) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact Generic.stageCaller o henv hd (by rw [hk]; exact check_stage0) + +/-- **The source stage of `Events` at every value**: the same calls with any value below `2 ^ 256`: `transfer` is not payable, and both sides revert with empty data. -/ +theorem loweringValue (o : SolarTV.Machine.Oracle) (henv : Generic.CallerOk o) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Events.stage0 (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact Generic.stageValueCaller o henv hd (by rw [hk]; exact check_stage0) + (by rw [hk]; exact checkValue_stage0) + +#print axioms selector_eq + +#print axioms digest_eq + +#print axioms shape_eq + +#print axioms check_stage0 + +#print axioms checkValue_stage0 + +#print axioms check_rejects_caller + +#print axioms check_rejects_topic + +#print axioms check_rejects_order + +#print axioms lowering + +#print axioms loweringValue + +end SolidCore.Refinement.Solar.Events diff --git a/SolidCore/Refinement/Solar/Hex.lean b/SolidCore/Refinement/Solar/Hex.lean new file mode 100644 index 00000000..c1981f13 --- /dev/null +++ b/SolidCore/Refinement/Solar/Hex.lean @@ -0,0 +1,50 @@ +/-! +# Hex: the bytes a manifest's hex spells + +The decoder the certified theorems use to tie the bytes their stages run to the hex an export's +manifest records (the hex `--emit=bin-runtime` printed): `hexBytes (codes s)` is the list of +bytes the lowercase hex string `s` spells, or `none` when `s` is not one, and `hexChars bs` is +the lowercase hex of the bytes `bs`. + +The kernel unfolds a string literal to `String.ofList` of its characters cheaply, but evaluating +`String.toUTF8` or `String.toList` of a literal of a few hundred characters exhausts 3 GB. So a +manifest's hex is tied to the bytes in two steps: the literal is `String.ofList (hexChars bytes)` +by the kernel's definitional unfolding (`rfl`), and `String.toList_ofList` turns its codes into +`(hexChars bytes).map Char.toNat`, which the kernel decodes. +-/ + +namespace SolidCore.Refinement.Solar.Hex + +/-- The value of a lowercase hex digit's ASCII code. -/ +def hexDigit (c : Nat) : Option Nat := + if 48 ≤ c ∧ c ≤ 57 then some (c - 48) + else if 97 ≤ c ∧ c ≤ 102 then some (c - 87) + else none + +/-- The bytes a string of lowercase hex digits spells, from its ASCII codes. -/ +def hexBytes : List Nat → Option (List Nat) + | [] => some [] + | a :: b :: rest => + match hexDigit a, hexDigit b, hexBytes rest with + | some x, some y, some r => some ((16 * x + y) :: r) + | _, _, _ => none + | [_] => none + +/-- The ASCII codes of a string. -/ +def codes (s : String) : List Nat := s.toList.map (·.toNat) + +/-- The lowercase hex digit of a number below 16. -/ +def hexChar (n : Nat) : Char := if n < 10 then Char.ofNat (48 + n) else Char.ofNat (87 + n) + +/-- The lowercase hex of a list of bytes, two digits a byte. -/ +def hexChars : List Nat → List Char + | [] => [] + | b :: rest => hexChar (b / 16) :: hexChar (b % 16) :: hexChars rest + +/-- A string that is not hex spells nothing: the decoder fails closed. -/ +theorem hexBytes_odd : hexBytes (codes "abc") = none := by decide +kernel + +/-- An uppercase digit is not lowercase hex. -/ +theorem hexBytes_upper : hexBytes (codes "0A") = none := by decide +kernel + +end SolidCore.Refinement.Solar.Hex diff --git a/SolidCore/Refinement/Solar/Lowering.lean b/SolidCore/Refinement/Solar/Lowering.lean new file mode 100644 index 00000000..fb9ba19b --- /dev/null +++ b/SolidCore/Refinement/Solar/Lowering.lean @@ -0,0 +1,306 @@ +import SolidCore.Refinement.Solar.W1 +import Verify.W5 +import W1Proofs.Tactic +import gen.Main.Stage0 + +/-! +# w5: SolidCore to solar's first lowered MIR + +The source stage of the milestone contract w5 (solar's w1), + + contract Main { function f(uint256 a, uint256 b) external pure returns (uint256) { + return a + b; } } + +from SolidCore's checked contract (Corpus.W5.contract?, the type checker's output on the parsed +source, which the kernel checks has the core Corpus.W5.coreLit and deploys to empty storage) +to the first lowered MIR module solar compiles (SolarTV.Export.Main.stage0, after +lower-evm-shaped, so lower-abi's ABI decoding and lower-dispatch's dispatcher included), in +SolarTV's lowered MIR semantics under any oracle. + +* mir_run_of: SolarTV's lowered MIR runs stage0, on every call whose call data reads as f(a, b) + with no value, to expected a b with the call's storage kept (expectedAt), by symbolic + execution of the module with W1Proofs.Tactic's evaluation steps: entry's callvalue check and selector switch, the tail + call into f, f's calldatasize check, the two argument loads, the addition and its overflow + check, and the return of a + b or the Panic(0x11) revert. mir_run is its fuel-free form. +* source_run: SolidCore runs f to the same observable (Verify.W5.run_f, observe_model). +* lowering: the stage on Verify.W5.scope, every call of f on any two argument words with no + value and empty storage. +* loweringAt: the stage on Verify.W5.scopeAt, the same calls from any storage σ (mir_run_at, + source_run_at, from Verify.W5.run_f_at), to expectedAt σ a b. +* lowering_rejects_bad: the stage is false for badStage0, stage0 with the addition compiled as + a subtraction, by the counterexample f(2, 1). + +No sorry, native_decide or bv_decide: the theorems depend on propext, Quot.sound and +Classical.choice only (pinned below). +-/ + +namespace SolidCore.Refinement.Solar.W1 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm.Wide +open SolidCore.Refinement.Wide SolarTV.Milestone.W1 + +section Lowering + +open SolarTV SolarTV.Machine + +theorem add_lt_self_iff (a b : EvmRules.Word) : + (EvmRules.Evm.add a b < a) = ¬ (a.toNat + b.toNat < 2 ^ 256) := by + unfold EvmRules.Evm.add + have ha := a.isLt + have hb := b.isLt + apply propext + rw [BitVec.lt_def, BitVec.toNat_add] + by_cases h : a.toNat + b.toNat < 2 ^ 256 + · rw [Nat.mod_eq_of_lt h]; omega + · rw [Nat.mod_eq_sub_mod (by omega), Nat.mod_eq_of_lt (by omega)]; omega + +/-- read_store on a store without the expansion: lowered MIR's `mstore` writes the bytes and +grows the active size in one step, and reads ignore the active size. -/ +theorem read_store_mir (m : Mem) (v : EvmRules.Word) : + ((m.store 0 v).read 0 32).map BitVec.toNat = (natToBytes 32 v.toNat).map (·.toNat) := by + have e : ((m.store 0 v).expand 0 32).read 0 32 = (m.store 0 v).read 0 32 := by + unfold Mem.expand; split <;> rfl + rw [← e]; exact read_store m v + +theorem mir_run_of (o : Oracle) (call : Call) (a b : EvmRules.Word) (hv : call.callvalue = 0) + (hsize : call.calldata.size = 68) (h0 : EvmRules.Evm.shr 224 (calldataWord call 0) = 332507694) + (h4 : calldataWord call 4 = a) (h36 : calldataWord call 36 = b) : + (MIR.Lowered.Module.run o SolarTV.Export.Main.stage0 call 9).map + (fun r => observe call r.2 r.1) = some (expectedAt call.storage a b) := by + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte]) + by_cases hof : a.toNat + b.toNat < 2 ^ 256 + all_goals + simp only [add_lt_self_iff, hof, not_true_eq_false, not_false_eq_true, ↓reduceIte] + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte]) + · simp only [BitVec.reduceToNat, observe, expectedAt, expected, hof, ↓reduceIte, + Option.some.injEq, Observable.mk.injEq, true_and] + refine ⟨?_, ?_, ?_⟩ + · rw [read_store_mir] + simp only [EvmRules.Evm.add, BitVec.toNat_add, Nat.mod_eq_of_lt hof] + · rfl + · funext slot + simp [storageOf, State.initial] + exact slotValue_mod_mod call.storage slot + · simp only [BitVec.reduceToNat, observe, expectedAt, expected, hof, ↓reduceIte, + Option.some.injEq, Observable.mk.injEq] + refine ⟨trivial, ?_, trivial, ?_⟩ + · decide + · trivial + +/-- A run of a lowered MIR module that ends within some fuel is its fuel-free result. -/ +theorem mir_sem_of_run {o : Oracle} {m : MIR.Lowered.Module} {call : Call} {obs : Observable} + (n : Nat) (h : (MIR.Lowered.Module.run o m call n).map (fun r => observe call r.2 r.1) = some obs) : + (MIR.Lowered.moduleSem o).run m call = some obs := by + obtain ⟨r, hr, rfl⟩ := Option.map_eq_some_iff.1 h + have e : MIR.Lowered.moduleLayer.result o m call = some r := + MIR.Lowered.moduleLayer.result_of_ends ⟨n, hr⟩ + show (MIR.Lowered.moduleLayer.result o m call).map _ = _ + rw [e] + rfl + +/-- SolarTV's lowered MIR semantics runs w5's first lowered MIR module on every call of f(a, b), +under every oracle, to the observable expected a b. -/ +theorem mir_run (o : Oracle) (a b : U256) : + (MIR.Lowered.moduleSem o).run SolarTV.Export.Main.stage0 (callOf fSelector [a, b]) = + some (expected a b) := by + rw [← expectedAt_nil] + exact mir_sem_of_run 9 (mir_run_of o _ a b rfl (size_callOf a b) (by rw [word0]; rfl) (word4 a b) + (word36 a b)) + +/-- The same from any storage `σ`, which the module keeps. -/ +theorem mir_run_at (o : Oracle) (a b : U256) (σ : List (Nat × Nat)) : + (MIR.Lowered.moduleSem o).run SolarTV.Export.Main.stage0 + { callOf fSelector [a, b] with storage := σ } = some (expectedAt σ a b) := + mir_sem_of_run 9 (mir_run_of o _ a b rfl (size_callOf a b) + (by have h := word0 a b; rw [show BitVec.ofNat 256 fSelector = 332507694 from rfl] at h; exact h) + (word4 a b) (word36 a b)) + +end Lowering + +/-- The model SolidCore runs f as shows expected a b. -/ +theorem observe_model (a b : U256) : + Verify.observe (fun _ => 0) (Verify.W5.model [a.toNat, b.toNat] (fun _ => 0)) = expected a b := by + unfold Verify.W5.model expected + by_cases h : a.toNat + b.toNat < 2 ^ 256 + · simp only [List.getD_cons_zero, List.getD_cons_succ, h, ↓reduceIte] + rfl + · simp only [List.getD_cons_zero, List.getD_cons_succ, h, ↓reduceIte] + rfl + +/-- SolidCore runs w5's f on any two argument words to expected a b. -/ +theorem source_run {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : Corpus.W5.contract? = .ok c) (a b : U256) : + Source.run Corpus.W5.fuel c (callOf fSelector [a, b]) = some (expected a b) := by + obtain ⟨hk, _, hemp⟩ := Corpus.W5.shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + rw [show fSelector = Bytecode.W5.Main.fSelector from rfl, + Verify.W5.run_f hk hd a b, observe_model] + +/-- **The source stage of w5**: SolidCore to solar's first lowered MIR, which includes ABI +decoding and dispatch, on every call of f on any two argument words with no value and empty +storage, under every oracle. -/ +theorem lowering (o : SolarTV.Machine.Oracle) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : Corpus.W5.contract? = .ok c) : + Stage (solidCore Corpus.W5.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 Verify.W5.scope := by + intro call hscope obs hrun + obtain ⟨a, b, rfl⟩ := scope_callOf hscope + change Source.run Corpus.W5.fuel c (callOf fSelector [a, b]) = some obs at hrun + rw [source_run hc a b] at hrun + cases hrun + exact mir_run o a b + +/-- The model SolidCore runs f as from any storage `σ` shows expectedAt σ a b. -/ +theorem observe_model_at (a b : U256) (σ : List (Nat × Nat)) : + Verify.observe (slotValue σ) (Verify.W5.model [a.toNat, b.toNat] (slotValue σ)) = + expectedAt σ a b := by + unfold Verify.W5.model expectedAt expected + by_cases h : a.toNat + b.toNat < 2 ^ 256 + · simp only [List.getD_cons_zero, List.getD_cons_succ, h, ↓reduceIte] + rfl + · simp only [List.getD_cons_zero, List.getD_cons_succ, h, ↓reduceIte] + rfl + +/-- SolidCore runs w5's f on any two argument words from any storage `σ` to expectedAt σ a b. -/ +theorem source_run_at {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : Corpus.W5.contract? = .ok c) (a b : U256) (σ : List (Nat × Nat)) : + Source.run Corpus.W5.fuel c { callOf fSelector [a, b] with storage := σ } = + some (expectedAt σ a b) := by + obtain ⟨hk, _, hemp⟩ := Corpus.W5.shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + have := Verify.W5.run_f_at hk (Verify.deployedAt_of_deployed hd) a b σ + rw [observe_model_at] at this + exact this + +/-- **The source stage of w5 from any storage**: SolidCore to solar's first lowered MIR on every +call of f on any two argument words with no value, from any storage, under every oracle. -/ +theorem loweringAt (o : SolarTV.Machine.Oracle) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : Corpus.W5.contract? = .ok c) : + Stage (solidCore Corpus.W5.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 Verify.W5.scopeAt := by + intro call hscope obs hrun + obtain ⟨a, b, σ, rfl⟩ := scopeAt_callOf hscope + change Source.run Corpus.W5.fuel c { callOf fSelector [a, b] with storage := σ } = some obs at hrun + rw [source_run_at hc a b σ] at hrun + cases hrun + exact mir_run_at o a b σ + +/-! ## A known-bad lowering is rejected + +badStage0 is stage0 with f's addition compiled as a subtraction (value 4 is sub, not add, of +the two argument words): a wrong compilation of the source. lowering_rejects_bad shows the +source stage false for it, by a mismatch of observables: on f(2, 1), SolidCore returns 3, +while badStage0 computes 2 - 1 = 1, which its overflow check (1 < 2) takes for an overflow, +and reverts with Panic(0x11). -/ + +/-- stage0 with f's addition compiled as a subtraction. -/ +def badStage0 : SolarTV.MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @f + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 68]], + .branch (.value 15) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 4]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 17) .calldataload [.const 4], + .effect (some 19) .calldataload [.const 36], + .pure 4 .sub [.value 17, .value 19], + .pure 5 .lt [.value 4, .value 17]], + .branch (.value 5) 1 2⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 3 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x13d1aa2e, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +/-- What badStage0 shows on f(2, 1): a revert with Panic(0x11). -/ +def badObs : Observable := + { success := false, + output := (natToBytes 4 0x4e487b71).map (·.toNat) ++ (natToBytes 32 0x11).map (·.toNat), + logs := [], storage := fun _ => 0 } + +section Bad + +open SolarTV SolarTV.Machine + +theorem bad_run_of (o : Oracle) (call : Call) (hv : call.callvalue = 0) + (hsize : call.calldata.size = 68) (h0 : EvmRules.Evm.shr 224 (calldataWord call 0) = 332507694) + (h4 : calldataWord call 4 = 2) (h36 : calldataWord call 36 = 1) (hst : call.storage = []) : + (MIR.Lowered.Module.run o badStage0 call 9).map (fun r => observe call r.2 r.1) = + some badObs := by + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte]) + simp only [BitVec.reduceToNat, observe, badObs, Option.some.injEq, Observable.mk.injEq] + refine ⟨trivial, ?_, trivial, ?_⟩ + · decide + · funext slot + simp [hst, slotValue] + +/-- On f(2, 1), badStage0 reverts with Panic(0x11), the observable of an overflowing call. -/ +theorem bad_run (o : Oracle) : + (MIR.Lowered.moduleSem o).run badStage0 call21 = some badObs := + mir_sem_of_run 9 (bad_run_of o _ rfl (size_callOf 2 1) (by rw [call21, word0]; rfl) + (word4 2 1) (word36 2 1) rfl) + +end Bad + +/-- The source stage is false for the known-bad lowering, under every oracle: f(2, 1) is in the +scope, SolidCore returns 3 on it, and badStage0 reverts. -/ +theorem lowering_rejects_bad (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : Corpus.W5.contract? = .ok c) : + ¬ Stage (solidCore Corpus.W5.fuel) (SolarTV.MIR.Lowered.moduleSem o) c badStage0 + Verify.W5.scope := by + intro h + have := h call21 call21_scope (expected 2 1) (source_run hc 2 1) + rw [bad_run] at this + have hs := congrArg (fun obs => obs.success) (Option.some.inj this) + have h21 : (expected 2 1).success = true := by + have h3 : (2 : U256).toNat + (1 : U256).toNat < 2 ^ 256 := by decide + simp only [expected, h3, ↓reduceIte] + rw [h21] at hs + exact Bool.false_ne_true hs + +/-- info: 'SolidCore.Refinement.Solar.W1.lowering' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms lowering + +/-- info: 'SolidCore.Refinement.Solar.W1.lowering_rejects_bad' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms lowering_rejects_bad + +end SolidCore.Refinement.Solar.W1 diff --git a/SolidCore/Refinement/Solar/LoweringGeneric.lean b/SolidCore/Refinement/Solar/LoweringGeneric.lean new file mode 100644 index 00000000..575cad34 --- /dev/null +++ b/SolidCore/Refinement/Solar/LoweringGeneric.lean @@ -0,0 +1,117 @@ +import SolidCore.Refinement.Generic.Value +import SolidCore.Refinement.Solar.Lowering + +/-! +# w5's source stage as an instance of the generic source stage + +`Solar.Lowering` proves the source stage of w5 (solar's w1, `f(a, b)` returning `a + b`) by +symbolic execution of this one module. Here the same stages follow from the generic source stage +`Generic.stage` and one evaluation by the kernel: + +* `check_stage0`: `Generic.check` accepts solar's first lowered MIR module + `SolarTV.Export.Main.stage0` for SolidCore's core `Corpus.W5.coreLit` and `Corpus.W5.fns`, by + `decide +kernel`: the erased tree of `f` and the symbolic run of the module on `f`'s selector + agree in normal form. +* `loweringAt_generic`: the stage on `Verify.W5.scopeAt` (every call of `f` on any two words, no + value, any storage), under every oracle; `lowering_generic` on `Verify.W5.scope` (empty + storage), the statements of `Solar.W1.loweringAt` and `Solar.W1.lowering`. +* `check_rejects_bad`: the check rejects `badStage0`, stage0 with the addition compiled as a + subtraction. +* `checkValue_stage0`: `Generic.checkValue` accepts stage0 (`decide +kernel`): `f` is not + payable and stage0 reverts with empty output on a call of it with a value other than 0, so + `loweringAt_value` and `lowering_value` are the two stages above at every value below + `2 ^ 256` (`Generic.stageValue`). + +No sorry, native_decide or bv_decide: `decide +kernel` is the kernel's evaluation, and the +theorems depend on propext, Classical.choice and Quot.sound only (pinned below). +-/ + +namespace SolidCore.Refinement.Solar.W1 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +/-- The interpreter fuel of the symbolic run of the module: blocks along each path. -/ +def mirFuel : Nat := 16 + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for w5's `f`. -/ +theorem check_stage0 : + Generic.check Corpus.W5.fuel mirFuel Corpus.W5.coreLit SolarTV.Export.Main.stage0 + Corpus.W5.fns = true := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check rejects stage0 with `a - b` for `a + b`. -/ +theorem check_rejects_bad : + Generic.check Corpus.W5.fuel mirFuel Corpus.W5.coreLit badStage0 Corpus.W5.fns = false := by + decide +kernel + +/-- **The source stage of w5 from any storage, from the generic source stage.** -/ +theorem loweringAt_generic (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : Corpus.W5.contract? = .ok c) : + Stage (solidCore Corpus.W5.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 Verify.W5.scopeAt := by + obtain ⟨hk, _, hemp⟩ := Corpus.W5.shape_of hc + obtain ⟨d, hd⟩ := Wide.deployed_of hemp + exact Generic.stage o (Verify.deployedAt_of_deployed hd) + (by rw [hk]; exact check_stage0) + +/-- **The source stage of w5, from the generic source stage**: every call of `f` with no value +and empty storage. -/ +theorem lowering_generic (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : Corpus.W5.contract? = .ok c) : + Stage (solidCore Corpus.W5.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 Verify.W5.scope := + SolarTV.Stage.mono (loweringAt_generic o hc) fun _ h => ⟨[], h⟩ + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: `f` is not payable, and stage0 reverts with empty output on a call of +it with a value other than 0. -/ +theorem checkValue_stage0 : + Generic.checkValue mirFuel Corpus.W5.coreLit SolarTV.Export.Main.stage0 Corpus.W5.fns = + true := by + decide +kernel + +/-- **The source stage of w5 from any storage, at every value**: every call of `f` on any two +words, with any value below `2 ^ 256`, under every oracle. -/ +theorem loweringAt_value (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : Corpus.W5.contract? = .ok c) : + Stage (solidCore Corpus.W5.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 + (fun call => ∃ σ v, Generic.fullScopeValue Corpus.W5.fns σ v call) := by + obtain ⟨hk, _, hemp⟩ := Corpus.W5.shape_of hc + obtain ⟨d, hd⟩ := Wide.deployed_of hemp + exact Generic.stageValue o (Verify.deployedAt_of_deployed hd) + (by rw [hk]; exact check_stage0) + (by rw [hk]; exact checkValue_stage0) + +/-- **The source stage of w5 at every value**: every call of `f` with any value below `2 ^ 256` +and empty storage. -/ +theorem lowering_value (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : Corpus.W5.contract? = .ok c) : + Stage (solidCore Corpus.W5.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 + (fun call => ∃ v, Generic.fullScopeValue Corpus.W5.fns [] v call) := + SolarTV.Stage.mono (loweringAt_value o hc) fun _ ⟨v, h⟩ => ⟨[], v, h⟩ + +/-- info: 'SolidCore.Refinement.Solar.W1.loweringAt_generic' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loweringAt_generic + +/-- info: 'SolidCore.Refinement.Solar.W1.lowering_generic' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms lowering_generic + +/-- info: 'SolidCore.Refinement.Solar.W1.checkValue_stage0' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms checkValue_stage0 + +/-- info: 'SolidCore.Refinement.Solar.W1.loweringAt_value' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loweringAt_value + +/-- info: 'SolidCore.Refinement.Solar.W1.lowering_value' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms lowering_value + +end SolidCore.Refinement.Solar.W1 diff --git a/SolidCore/Refinement/Solar/Milestone.lean b/SolidCore/Refinement/Solar/Milestone.lean new file mode 100644 index 00000000..c9c506dc --- /dev/null +++ b/SolidCore/Refinement/Solar/Milestone.lean @@ -0,0 +1,123 @@ +import SolidCore.Refinement.Solar.Lowering +import SolidCore.Refinement.Spec +import W1Proofs.Stages +import gen.Main.Manifest + +/-! +# The w5 milestone: solar's bytecode meets w5's verified specification, every stage proved + +The contract (scripts/refinement/corpus/w5.sol; solar-tv/milestone/w1/w1.sol in solar's tree, +the same contract), + + contract Main { function f(uint256 a, uint256 b) external pure returns (uint256) { + return a + b; } } + +compiled by solar (compiler sources of commit 81dbc26c, -Ogas --evm-version osaka) to the 68 +bytes of runtime bytecode code, whose sha256 is runtimeSha256. certified states, with no +hypothesis, that code meets w5's specification (Verify.W5: f(a, b) returns the word a + b when +it fits in 256 bits and otherwise reverts with Panic(0x11), logs nothing, and leaves storage +empty) on EthLib, and that code is the bytecode solar exported with its stages, as the +manifest records it. The specification is proved of SolidCore's checked contract with the +Loom VC generator (Verify.W5.satisfies) and carried to the bytecode through solar's actual +pipeline (bytecode_of_stages), every stage a theorem: + +* source: SolidCore to the first lowered MIR, lower-abi and lower-dispatch included + (lowering, SolidCore/Refinement/Solar/Lowering.lean); +* backend: the first lowered MIR through stack scheduling and the four EVM IR passes to the + final EVM IR (SolarTV.Milestone.W1.w1_mir_to_evmir, solar-tv/milestone/w1/proofs); +* assembly: the final EVM IR to the bytecode on EthLib (stage, SolidCore/Refinement/Solar/W1.lean): + Assemble.stage_of_check, proved once for every EVM IR program of the fragment and every code + the checker accepts (SolidCore/Refinement/Solar/AssembleSim.lean), at check_ok, the kernel's + evaluation of the checker on w1's final EVM IR and bytecode. + +The stages hold under every oracle of SolarTV's semantics; the composition uses oracle, the +environment of EthLib's call. + +## Scope + +* Syntax: this one contract, a single external pure function of two uint256 parameters + returning their checked sum. Nothing else is claimed for any other source: the certificate + is translation validation of this compilation, and another source or compiler output fails + the stage proofs (the procedures leave goals) or the artifact checks of + scripts/refinement/w5-milestone.sh. +* Calls: one call (no call sequences) of f, selector 0x13d1aa2e, with well-formed call data, + the selector followed by two words below 2^256 (68 bytes; Verify.W5.scope, Abi.fullScope). + Short, long or otherwise malformed call data, other selectors, and nonzero call value are + outside the scope; the stages say nothing about them. +* Call value: zero. Initial storage: empty, the storage SolidCore's constructor leaves + (checked by the kernel, Corpus.W5.shape_eq); the bytecode reads no storage. + certifiedAt widens this to any initial storage: on Verify.W5.scopeAt (every call of f with + no value from any storage σ, which the call writes over the deployed one), code meets + Verify.W5.postAt (the same result, with every slot of σ kept), through loweringAt, + w1_mir_to_evmir and stageAt, each proved from any storage (EthLib's preState reads σ, + getStorage_preState); stageAt is the same Assemble.stage_of_check at the same check_ok. +* Reverts: the overflow path, a revert with Panic(0x11) data, is in the scope and proved. +* Logs: none, proved (the specification states logs = []). External calls: none. +* EVM: EthLib at Fusaka (solar's --evm-version osaka), one message frame from 0x2000 to 0x1000 + with 10M gas (Statement.lean's Target.run). Gas is metered and checked on every step of the + bytecode run, so the theorem includes that 10M gas suffices on every path. Proof fuel is + separate: SolidCore runs with interpreter fuel Corpus.W5.fuel = 4096, SolarTV's MIR and EVM + IR semantics are fuel-free (each run ends within a few blocks), and none of it is EVM gas. + +## Unverified boundaries + +* Source parsing into SolidCore: SolidCore's checked contract is Corpus.W5.contract?, the + type checker on Source.W5.importedSourceUnit, which scripts/refinement/gen.sh produces from + w5.sol with solidity-lean's front end. That front end, and that w5.sol is the source solar + compiled (the check script compares the two files modulo comments and whitespace and + compiles both), are outside the proof. The type checker's output on the parsed source is + checked by the kernel. +* Artifact import: solar's stages enter Lean as text it writes (-Zemit-lean-stages, gen/Main); + that the printed terms are the compiler's internal IR is not proved. The check script + regenerates them with solar and compares them byte for byte, and checks that the bytecode + literal is solar's --emit=bin-runtime output and its sha256. +* The semantics themselves (SolidCore, SolarTV's MIR and EVM IR, EthLib) are the trusted + definitions the theorems are stated in. +-/ + +namespace SolidCore.Refinement.Solar.W1 + +open SolidCore.Refinement + +/-- **The milestone.** solar's runtime bytecode for w5, which is the bytecode solar exported +with its stages (byte for byte, and as the hex and sha256 its manifest records for compiler +81dbc26c with -Ogas for osaka), meets w5's specification verified on SolidCore, under EthLib +on every call of the scope, through every stage of solar's pipeline. -/ +theorem certified : + bytes = SolarTV.Export.Main.bytecode ∧ + SolarTV.Export.Main.Manifest.bytecodeHex = runtimeHex ∧ + SolarTV.Export.Main.Manifest.bytecodeSha256 = runtimeSha256 ∧ + SolarTV.Export.Main.Manifest.optimization = "Gas" ∧ + SolarTV.Export.Main.Manifest.evmVersion = "osaka" ∧ + Satisfies ethLib code Verify.W5.scope Verify.W5.pre Verify.W5.post := by + refine ⟨bytes_exported, rfl, rfl, rfl, rfl, ?_⟩ + obtain ⟨c, hc, hspec⟩ := Verify.W5.satisfies + exact bytecode_of_stages hspec (lowering oracle hc) + ((SolarTV.Milestone.W1.w1_mir_to_evmir oracle).mono fun _ _ => trivial) (stage oracle) + +/-- **The milestone from any storage.** The same bytecode meets w5's specification from any +storage (`Verify.W5.specAt`: on every call of f with no value from any storage `σ`, the result +of `post` with `σ` kept), under EthLib, through every stage of solar's pipeline, each proved on +every call from any storage. -/ +theorem certifiedAt : Satisfies ethLib code Verify.W5.scopeAt Verify.W5.pre Verify.W5.postAt := by + obtain ⟨c, hc, hspec⟩ := Verify.W5.satisfiesAt + exact bytecode_of_stages hspec (loweringAt oracle hc) + ((SolarTV.Milestone.W1.w1_mir_to_evmir oracle).mono fun _ _ => trivial) (stageAt oracle) + +/-- The bytecode is the corpus's: solidity-lean's own compilation of w5.sol with solar -Ogas +(Corpus.W5.code, commit 9688f215) is the same 68 bytes. -/ +theorem code_eq_corpus : code = Corpus.W5.code := rfl + +/-- info: 'SolidCore.Refinement.Solar.W1.lowering' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms lowering + +/-- info: 'SolidCore.Refinement.Solar.W1.certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified + +/-- info: 'SolidCore.Refinement.Solar.W1.certifiedAt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedAt + +end SolidCore.Refinement.Solar.W1 diff --git a/SolidCore/Refinement/Solar/MulX/Assembly.lean b/SolidCore/Refinement/Solar/MulX/Assembly.lean new file mode 100644 index 00000000..d40b403a --- /dev/null +++ b/SolidCore/Refinement/Solar/MulX/Assembly.lean @@ -0,0 +1,84 @@ +import SolidCore.Refinement.Solar.AssembleSim +import SolidCore.Refinement.Solar.AssembleFast +import mulx.gen.Main.Evm8 +import mulx.gen.Main.Bytecode + +/-! +# mulx: the final EVM IR to solar's bytecode + +The test contract scripts/refinement/mulx/mul.sol compiles with solar a8179dfc and +-Zcheck-analyses=false to the final EVM IR evm8 (after terminal-layout) and to 186 bytes of +runtime bytecode (sha256 42ecdc71b09d339299d2b7ce61e121c77b141c5386eb9cbf18792a9ba9ca4cfe), +both exported by -Zemit-lean-stages into solar's solar-tv/milestone/mulx and imported from +there. Solar's milestone proves the stages from the first lowered MIR to evm8 +(SolarTV.Milestone.Mulx.mulx_mir_to_evmir); this file proves the last one, evm8 to the +bytecode, with the generic assembler check, whose fragment includes MUL and DIV for this +contract's products and the overflow test of uint256(a) * b * c. + +The layout is five blocks: the dispatcher, the empty revert (bb4, at 0x1d), the Panic(0x11) +revert (bb8, at 0x21), n (bb10, at 0x33) and m (bb5, at 0x6d). n and m jump back to the two +reverts, so the certificate gives each block its potential: the reverts' items, a bound on n's +and m's, and the dispatcher's on top of them. + +* check_ok: the checker accepts evm8 and the bytes with cert, by the kernel's evaluation of + its one-pass form (`Assemble.checkFast`, equal to it by `Assemble.check_eq_checkFast`). +* stageAll: EVM IR to bytecode is a stage on every call, with any value, call data and storage, + under every oracle (Assemble.stage_of_check_all). +* mutantAdd_check, mutantSdiv_check: the checker rejects one-byte mutants, ADD for n's first + MUL and SDIV for the DIV of its overflow test. +-/ + +namespace SolidCore.Refinement.Solar.MulX + +open SolarTV.Assembly SolarTV.Export.Main + +/-- The runtime bytecode solar exported. -/ +def code : ByteArray := ⟨(bytecode.map UInt8.ofNat).toArray⟩ + +/-- The certificate: each block's offset in the code, the stack height each block needs on +entry (none), the bound on memory (the return's and the panic's 64 bytes) and each block's +potential, a bound on the items its runs execute. -/ +def cert : Assemble.Cert := + { offsets := [0, 0x1d, 0x21, 0x33, 0x6d], needs := [0, 0, 0, 0, 0], top := 64, + costs := [200, 4, 10, 100, 100] } + +set_option maxRecDepth 100000 in +/-- The checker accepts solar's bytecode for the program, by the kernel's evaluation. -/ +theorem check_ok : Assemble.check evm8 code cert = true := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +/-- EVM IR to bytecode is a stage for mulx on every call, with any value, call data and +storage, under every oracle. -/ +theorem stageAll (o : SolarTV.Machine.Oracle) (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.evmirSem o) SolidCore.Refinement.ethLib evm8 + (show SolidCore.Refinement.ethLib.Prog from code) scope := + Assemble.stage_of_check_all check_ok o scope + +/-- The bytes with the byte at i replaced by b. -/ +def mutant (i b : Nat) : ByteArray := ⟨((bytecode.set i b).map UInt8.ofNat).toArray⟩ + +/-- n's first MUL, at offset 0x53, and the DIV of its overflow test, at offset 0x5c. -/ +theorem mutated_bytes : bytecode[0x53]? = some 0x02 ∧ bytecode[0x5c]? = some 0x04 := by decide + +set_option maxRecDepth 100000 in +/-- ADD for n's first MUL: the checker rejects it. -/ +theorem mutantAdd_check : Assemble.check evm8 (mutant 0x53 0x01) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +set_option maxRecDepth 100000 in +/-- SDIV for the DIV of n's overflow test: the checker rejects it. -/ +theorem mutantSdiv_check : Assemble.check evm8 (mutant 0x5c 0x05) cert = false := by + rw [Assemble.check_eq_checkFast] + decide +kernel + +/-- info: 'SolidCore.Refinement.Solar.MulX.check_ok' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms check_ok + +/-- info: 'SolidCore.Refinement.Solar.MulX.stageAll' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stageAll + +end SolidCore.Refinement.Solar.MulX diff --git a/SolidCore/Refinement/Solar/MulX/Certified.lean b/SolidCore/Refinement/Solar/MulX/Certified.lean new file mode 100644 index 00000000..0be3332d --- /dev/null +++ b/SolidCore/Refinement/Solar/MulX/Certified.lean @@ -0,0 +1,151 @@ +import SolidCore.Refinement.Solar.MulX.Lowering +import SolidCore.Refinement.Solar.MulX.Assembly +import mulx.Proofs.Stages +import mulx.gen.Main.Manifest + +/-! +# mulx: SolidCore to solar's bytecode, through every stage + +The end-to-end certified translation of the test contract scripts/refinement/mulx/mul.sol, + + contract Main { uint8 x8; uint16 y16 = 3; uint256 z; + function m(uint8 a, uint16 b) external { x8 *= a; y16 *= b; } + function n(uint8 a, uint16 b, uint256 c) external returns (uint256) { + z = uint256(a) * b * c; return z; } } + +by solar a8179dfc with -Zcheck-analyses=false (default -Ogas, osaka), chaining with +Stage.trans: + +1. the source stage, SolidCore's checked Main to solar's first lowered MIR stage0 + (MulX.lowering from the deployed storage, MulX.loweringAt from any storage that writes + slot 0; every call of m and n on any argument words, no value, every oracle); +2. the backend stages of solar's solar-tv/milestone/mulx, stage0 → mir1 (place-reads) → mir2 + (spell-width-tests) → mir3 (evm-inst-schedule) → sched (stack-schedule) → evm1 … evm8 + (cfg-simplify-early, compact-pushes, block-layout, terminal-dedup, cfg-simplify-early, + block-layout, stack-reschedule, terminal-layout), each a kernel-checked symbolic run on + every call with any call data, value and storage (SolarTV.Milestone.Mulx.mulx_mir_to_evmir); +3. the assembly stage, evm8 to the 186 bytes of runtime bytecode (Assembly.lean, stageAll). + +The backend stages hold on every call, so the source stages at every value (MulX.loweringValue, +MulX.loweringAtValue) compose with them too: certified_deployed_value and certified_at_value +are certified_deployed and certified_at on calls with any value below 2 ^ 256. + +All three use the same exported modules (mulx.gen.Main), so the stages compose by definition. +The export's manifest (mulx.gen.Main.Manifest) records the source's sha256, the compiler's +version and commit, its arguments, and the bytecode with its sha256; certified states them, and +that the bytes the stages run are the manifest's hex. solar's certify.sh checks the hashes +against the files (the source, each stage, the bytecode), outside the kernel. + +No sorry, native_decide or bv_decide: the theorems depend on propext, Classical.choice and +Quot.sound only (pinned below). +-/ + +namespace SolidCore.Refinement.Solar.MulX + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity SolarTV.Export.Main + +/-- The value of a lowercase hex digit's ASCII code. -/ +def hexDigit (c : Nat) : Option Nat := + if 48 ≤ c ∧ c ≤ 57 then some (c - 48) + else if 97 ≤ c ∧ c ≤ 102 then some (c - 87) + else none + +/-- The bytes a string of lowercase hex digits spells, from its ASCII codes. -/ +def hexBytes : List Nat → Option (List Nat) + | [] => some [] + | a :: b :: rest => + match hexDigit a, hexDigit b, hexBytes rest with + | some x, some y, some r => some ((16 * x + y) :: r) + | _, _, _ => none + | [_] => none + +/-- The ASCII codes of a string. -/ +def codes (s : String) : List Nat := s.toUTF8.toList.map (·.toNat) + +set_option maxRecDepth 100000 in +/-- The bytes the stages run are the manifest's hex, which --emit=bin-runtime printed. -/ +theorem bytecode_of_manifest : hexBytes (codes Manifest.bytecodeHex) = some bytecode := by + decide +kernel + +/-- The backend: solar-tv's stages from stage0 to evm8, then the assembly stage. -/ +theorem backend (o : SolarTV.Machine.Oracle) (scope : SolarTV.Call → Prop) : + Stage (SolarTV.MIR.Lowered.moduleSem o) ethLib stage0 code scope := + SolarTV.Stage.trans (B := SolarTV.evmirSem o) + ((SolarTV.Milestone.Mulx.mulx_mir_to_evmir o).mono fun _ _ => trivial) (stageAll o scope) + +/-- **mulx from SolidCore to solar's bytecode**, from the deployed storage: every result +SolidCore's Main gives on a call of m or n on any argument words, no value, from the storage +its constructor leaves (slot 0 = 3 * 256), the bytecode gives under EthLib, for every oracle. -/ +theorem certified_deployed (o : SolarTV.Machine.Oracle) {c : TypeCheck.CheckedContract} + (hc : contract? = .ok c) : + Stage (solidCore fuel) ethLib c code (fullScope fns deployed) := + (lowering o hc).trans (backend o _) + +/-- **mulx from SolidCore to solar's bytecode**, from any storage that writes slot 0. -/ +theorem certified_at (o : SolarTV.Machine.Oracle) {c : TypeCheck.CheckedContract} + (hc : contract? = .ok c) : + Stage (solidCore fuel) ethLib c code scopeAt := + (loweringAt o hc).trans (backend o _) + +/-- **mulx from SolidCore to solar's bytecode at every value**, from the deployed storage: every +result SolidCore's Main gives on a call of m or n on any argument words, with any value below +2 ^ 256, from the storage its constructor leaves, the bytecode gives under EthLib, for every +oracle. -/ +theorem certified_deployed_value (o : SolarTV.Machine.Oracle) {c : TypeCheck.CheckedContract} + (hc : contract? = .ok c) : + Stage (solidCore fuel) ethLib c code + (fun call => ∃ v, Generic.fullScopeValue fns deployed v call) := + (loweringValue o hc).trans (backend o _) + +/-- **mulx from SolidCore to solar's bytecode at every value**, from any storage that writes +slot 0. -/ +theorem certified_at_value (o : SolarTV.Machine.Oracle) {c : TypeCheck.CheckedContract} + (hc : contract? = .ok c) : + Stage (solidCore fuel) ethLib c code scopeAtValue := + (loweringAtValue o hc).trans (backend o _) + +/-- **The certified translation of mulx**, bound to what it was compiled from and by: the +source (path and sha256), its arguments +(-Zcheck-analyses=false, -Ogas, osaka), the bytecode with its sha256, the bytes the stages run +as that bytecode, and the stage from SolidCore's checked Main to those bytes, from the deployed +storage and from any storage that writes slot 0, under every oracle. -/ +theorem certified (o : SolarTV.Machine.Oracle) {c : TypeCheck.CheckedContract} + (hc : contract? = .ok c) : + Manifest.sources = [("Certified/mulx/mulx.sol", + "c0dd0ad4558b8273ffd8b9e9abd7431eb429a29524df0b7cbe931076e0eb46d1")] ∧ + Manifest.arguments = ["Certified/mulx/mulx.sol", "-Zcheck-analyses=false", + "--emit=bin-runtime", "-Zemit-lean-stages=Certified/mulx/gen"] ∧ + Manifest.optimization = "Gas" ∧ Manifest.evmVersion = "osaka" ∧ + Manifest.bytecodeSha256 = "42ecdc71b09d339299d2b7ce61e121c77b141c5386eb9cbf18792a9ba9ca4cfe" ∧ + Manifest.bytecodeHex = bytecodeHex ∧ hexBytes (codes Manifest.bytecodeHex) = some bytecode ∧ + code = ⟨(bytecode.map UInt8.ofNat).toArray⟩ ∧ + Stage (solidCore fuel) ethLib c code (fullScope fns deployed) ∧ + Stage (solidCore fuel) ethLib c code scopeAt := + ⟨rfl, rfl, rfl, rfl, rfl, rfl, bytecode_of_manifest, rfl, certified_deployed o hc, + certified_at o hc⟩ + +/-- info: 'SolidCore.Refinement.Solar.MulX.backend' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms backend + +/-- info: 'SolidCore.Refinement.Solar.MulX.certified_deployed' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified_deployed + +/-- info: 'SolidCore.Refinement.Solar.MulX.certified_at' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified_at + +/-- info: 'SolidCore.Refinement.Solar.MulX.certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified + +/-- info: 'SolidCore.Refinement.Solar.MulX.certified_deployed_value' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified_deployed_value + +/-- info: 'SolidCore.Refinement.Solar.MulX.certified_at_value' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified_at_value + +end SolidCore.Refinement.Solar.MulX diff --git a/SolidCore/Refinement/Solar/MulX/Lowering.lean b/SolidCore/Refinement/Solar/MulX/Lowering.lean new file mode 100644 index 00000000..877e92c5 --- /dev/null +++ b/SolidCore/Refinement/Solar/MulX/Lowering.lean @@ -0,0 +1,593 @@ +import SolidCore.Refinement.Generic.Value +import SolidCore.Refinement.KernelCopies +import SolidCore.Refinement.KernelRfl +import SolidCore.Refinement.Source.MulX +import mulx.gen.Main.Stage0 + +/-! +# Narrow checked multiplication: the generic source stage on solar's own module + +The test contract scripts/refinement/mulx/mul.sol (sha256 +c0dd0ad4558b8273ffd8b9e9abd7431eb429a29524df0b7cbe931076e0eb46d1), + + contract Main { uint8 x8; uint16 y16 = 3; uint256 z; + function m(uint8 a, uint16 b) external { x8 *= a; y16 *= b; } + function n(uint8 a, uint16 b, uint256 c) external returns (uint256) { + z = uint256(a) * b * c; return z; } } + +has checked `uint8` and `uint16` compound multiplications into two fields packed in slot 0 +(`x8` at byte 0, `y16` at bytes 1 and 2), a constructor that leaves slot 0 = `3 * 256`, and a +`uint256` product of widened narrow parameters (`uint256(a) * b`, which cannot overflow, then +`* c`, which can). `SolarTV.Export.Main.stage0` is solar's first lowered MIR module for it, +exported by `solar -Zemit-lean-stages` at solar a8179dfc with `-Zcheck-analyses=false` into +solar's solar-tv/milestone/mulx and imported from there (`mulx.gen.Main.Stage0`, sha256 +2b9c8cec1601216327fccf673b46da96524d9a9f370a59ba48c0e8c681ab04d3, the export manifest's), the +same module whose backend stages solar's milestone proves, so that the two compose +(Certified.lean). solar checks `x8 *= a` and `y16 *= b` with one range check each on the +exact product, joined by `or`; it drops the check of `uint256(a) * b` by its range analysis +and checks `* c` with `or (eq c 0) (eq (div p c) ab)`, branching to success when it holds. +SolidCore's core (`coreLit`, solc 0.8.35's AST through scripts/solc_ast_to_lean_source.py +into Source/MulX.lean and `TypeCheck.CheckedInput.contract`, printed and copied) checks both +products with `uint256`'s mul overflow check and then each narrow cleanup. + +* `selM_eq`, `selN_eq`, `selector_eq`: the selectors of `m` and `n` by Keccak-256, each + checked alone, so `ABI.selectorFromSignature` is `selectorTable`; +* `shape_eq`: `Main` type checks, its core is `coreLit` and its constructor leaves slot 0 = + `3 * 256`, by one kernel conversion check (`kernel_rfl`) that evaluates the type checker + once, on copies that read the selectors from `selectorTable`; there is no `Bool` + recognizer of `coreLit`, whose `match` on the whole literal and `split` cost 3 GB and + half a minute to elaborate; +* `check_m`, `check_n`: `Generic.check` accepts stage0 for `m` and for `n` + (`decide +kernel`), so `check_stage0` for both; +* `lowering`: the stage from the deployed storage, under every oracle (`Generic.stageDeployed`); +* `loweringAt`: the stage from any storage that writes slot 0 (`Generic.stageAt`); +* `checkValue_stage0`: `Generic.checkValue` accepts stage0 for both functions (`decide +kernel`): + `m` and `n` are not payable, and stage0 reverts with empty output on a call of either with a + value other than 0, so `loweringValue` and `loweringAtValue` are `lowering` and `loweringAt` + at every value below `2 ^ 256` (`Generic.stageDeployedValue`, `Generic.stageAtValue`); + `checkValue_rejects_payable`: it rejects stage0 with the dispatcher's value check dropped; +* `check_rejects_unchecked`: the check rejects stage0 with `m`'s `uint8` check dropped from + its panic branch, and `check_rejects_add`: with `n`'s second `mul` compiled as `add`. + +The names of solar's stages (`SolarTV.Export.Main`) are those of w1's, w4's and c4's too, so +this module is built by `lake build SolidCoreSolarMulX`, outside the library root. + +No sorry, native_decide or bv_decide: `decide +kernel` and `kernel_rfl` are the kernel's +evaluation, and the theorems depend on propext, Classical.choice and Quot.sound only (pinned +below). +-/ + +namespace SolidCore.Refinement.Solar.MulX + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity SolidCore.Solidity.Source + +/-- The interpreter fuel of SolidCore's runs. -/ +def fuel : Nat := 4096 + +/-- The interpreter fuel of the symbolic run of the module: blocks along each path. -/ +def mirFuel : Nat := 16 + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.MulX.importedSourceUnit "Main" + +/-- The selector of `m(uint8,uint16)`. -/ +abbrev mSel : Nat := 0x16ea58cb + +/-- The selector of `n(uint8,uint16,uint256)`. -/ +abbrev nSel : Nat := 0x9db20e58 + +/-- `m` and its parameters. -/ +def fnM : Fn := ⟨mSel, [.uint 8, .uint 16]⟩ + +/-- `n` and its parameters. -/ +def fnN : Fn := ⟨nSel, [.uint 8, .uint 16, .uint 256]⟩ + +/-- Both functions of `Main`. -/ +def fns : List Fn := [fnM, fnN] + +/-- SolidCore's core contract of `Main`, as the type checker leaves it. -/ +def coreLit : Contract := + { storageFields := [{ name := "x8", + slot := 0, + ty? := some (SolidCore.Solidity.Source.Ty.uint256), + layout? := some (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.uint256)), + transient := false, + packedOffset := 0, + packedBytes := 1, + packedSigned := false }, + { name := "y16", + slot := 0, + ty? := some (SolidCore.Solidity.Source.Ty.uint256), + layout? := some (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.uint256)), + transient := false, + packedOffset := 1, + packedBytes := 2, + packedSigned := false }, + { name := "z", + slot := 1, + ty? := some (SolidCore.Solidity.Source.Ty.uint256), + layout? := some (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.uint256)), + transient := false, + packedOffset := 0, + packedBytes := 32, + packedSigned := false }], + immutableFields := [], + eventDecls := [], + errorDecls := [], + functions := [{ name := "m", + selector? := some 384456907, + payable := false, + params := [{ name := "a", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }, + { name := "b", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8, + SolidCore.Solidity.Source.AbiCleanup.uint 16], + returns := [], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "a") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "a")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "b") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 16 + (SolidCore.Solidity.Source.Expr.var "b")), + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.mul)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 8)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "x8" + []) + (SolidCore.Solidity.Source.Expr.var "a")), + SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.mul)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 16)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "y16" + []) + (SolidCore.Solidity.Source.Expr.var "b"))]], + dispatchId? := none }, + { name := "n", + selector? := some 2645691992, + payable := false, + params := [{ name := "a", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }, + { name := "b", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }, + { name := "c", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8, + SolidCore.Solidity.Source.AbiCleanup.uint 16, + SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "a") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "a")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "b") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 16 + (SolidCore.Solidity.Source.Expr.var "b")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "c") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "c")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.storage "z") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.mul) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.mul) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 256 + (SolidCore.Solidity.Source.Expr.var "a"))) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "b"))))) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "c"))))), + SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.ref) + "z" + [])]]], + dispatchId? := none }, + { name := "__internal_m(uint8,uint16)#[SolidCore.Solidity.Ty.uint 8, SolidCore.Solidity.Ty.uint 16]", + selector? := none, + payable := false, + params := [{ name := "a", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }, + { name := "b", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8, + SolidCore.Solidity.Source.AbiCleanup.uint 16], + returns := [], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "a") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "a")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "b") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 16 + (SolidCore.Solidity.Source.Expr.var "b")), + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.mul)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 8)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "x8" + []) + (SolidCore.Solidity.Source.Expr.var "a")), + SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.mul)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 16)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "y16" + []) + (SolidCore.Solidity.Source.Expr.var "b"))]], + dispatchId? := none }, + { name := "__internal_n(uint8,uint16,uint256)#[SolidCore.Solidity.Ty.uint 8, SolidCore.Solidity.Ty.uint 16, SolidCore.Solidity.Ty.uint 256]", + selector? := none, + payable := false, + params := [{ name := "a", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }, + { name := "b", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }, + { name := "c", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8, + SolidCore.Solidity.Source.AbiCleanup.uint 16, + SolidCore.Solidity.Source.AbiCleanup.uint 256], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "a") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "a")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "b") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 16 + (SolidCore.Solidity.Source.Expr.var "b")), + SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "c") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "c")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.storage "z") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.mul) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.mul) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 256 + (SolidCore.Solidity.Source.Expr.var "a"))) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "b"))))) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.var "c"))))), + SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 256 + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.ref) + "z" + [])]]], + dispatchId? := none }] } + +/-! ## The selectors + +The type checker computes each external function's selector by Keccak-256 of its +signature, which costs the kernel about 400 MB a hash. Each is checked once, alone, and +the check of the shape below runs on copies that read them from a table. -/ + +/-- `m`'s selector, by Keccak-256 of its signature. -/ +def selM : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "m(uint8,uint16)" + +/-- `n`'s selector, by Keccak-256 of its signature. -/ +def selN : SolidCore.Solidity.Shared.Word := + SolidCore.Solidity.Source.ABI.selectorFromSignature "n(uint8,uint16,uint256)" + +kernel_rfl selM_eq selM mSel +kernel_rfl selN_eq selN nSel + +/-- `ABI.selectorFromSignature`, with `Main`'s two signatures by table. -/ +def selectorTable (s : String) : SolidCore.Solidity.Shared.Word := + if s = "m(uint8,uint16)" then mSel + else if s = "n(uint8,uint16,uint256)" then nSel + else SolidCore.Solidity.Source.ABI.selectorFromSignature s + +theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by + funext s + unfold selectorTable + split + · next h => subst h; exact selM_eq + · split + · next h => subst h; exact selN_eq + · rfl + +/-- The storage the constructor leaves: `x8 = 0` in the low byte of slot 0, `y16 = 3` in the +next two. -/ +def deployed : List (Nat × Nat) := [(0, 3 * 256)] + +/-- SolidCore's checked core of `Main`, and whether its constructor leaves exactly `deployed` +and no logs, when `Main` type checks. -/ +def shape? : Option (Contract × Bool) := + match contract? with + | .ok c => some (c.core, Wide.deployedAt fuel c deployed) + | .error _ => none + +-- `shape_eq : shape? = some (coreLit, true)`: `Main` type checks, its core is `coreLit` and its +-- constructor leaves exactly `deployed`, by the kernel's conversion check on the copy of +-- `shape?` that reads the selectors from `selectorTable` (`selector_eq`): one check evaluates +-- the type checker once and hashes nothing, where a `Bool` test of the core would need a +-- decision procedure for equality of cores (`KernelRfl.lean`). +kernel_rfl shape_eq shape? (some (coreLit, true)) using selector_eq + +/-! ## The check on solar's module -/ + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for `m`. -/ +theorem check_m : + Generic.check fuel mirFuel coreLit SolarTV.Export.Main.stage0 [fnM] = true := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts stage0 for `n`. -/ +theorem check_n : + Generic.check fuel mirFuel coreLit SolarTV.Export.Main.stage0 [fnN] = true := by + decide +kernel + +/-- The generic check accepts stage0 for both functions. -/ +theorem check_stage0 : + Generic.check fuel mirFuel coreLit SolarTV.Export.Main.stage0 fns = true := by + have hm := check_m + have hn := check_n + simp only [Generic.check, List.all_cons, List.all_nil, Bool.and_true] at hm hn + simp only [Generic.check, fns, List.all_cons, List.all_nil, Bool.and_true, hm, hn] + +/-! ## Mutants the check rejects -/ + +/-- stage0 with each instruction of function `i` changed by `f`. -/ +def mapFn (i : Nat) (f : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst) : + SolarTV.MIR.Lowered.Module := + { SolarTV.Export.Main.stage0 with + functions := SolarTV.Export.Main.stage0.functions.mapIdx fun j fn => + if j = i then { fn with blocks := fn.blocks.map fun b => { b with insts := b.insts.map f } } + else fn } + +/-- `m`'s panic condition without `x8`'s range check: `or v45 v45` for `or v33 v45`. -/ +def dropX8Check : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .pure 76 .or [.value 33, b] => .pure 76 .or [b, b] + | i => i + +/-- `n`'s product `uint256(a) * b * c` with its second `mul` compiled as `add`. -/ +def mulToAdd : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .pure 11 .mul args => .pure 11 .add args + | i => i + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects `m` without `x8`'s overflow check. -/ +theorem check_rejects_unchecked : + Generic.check fuel mirFuel coreLit (mapFn 0 dropX8Check) [fnM] = false := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the check rejects `n` with `add` for its second `mul`. -/ +theorem check_rejects_add : + Generic.check fuel mirFuel coreLit (mapFn 1 mulToAdd) [fnN] = false := by + decide +kernel + +/-! ## The stage -/ + +/-- The checked contract has the core `coreLit`, and its constructor leaves exactly +`deployed`. -/ +theorem deployed_of {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core = coreLit ∧ ∃ d, Wide.DeployedAt fuel c d deployed := by + have h := shape_eq + unfold shape? at h + rw [hc] at h + obtain ⟨hk, hd⟩ := Prod.mk.inj (Option.some.inj h) + exact ⟨hk, Wide.deployedAt_of hd⟩ + +/-- **The source stage of `Main` from the deployed storage**: every call of `m` and `n` on any +argument words, no value, from the storage the constructor leaves, under every oracle. -/ +theorem lowering (o : SolarTV.Machine.Oracle) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 (fullScope fns deployed) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact Generic.stageDeployed o hd (by rw [hk]; exact check_stage0) + +/-- The calls from any storage that writes slot 0, the slot the constructor writes. -/ +def scopeAt : Call → Prop := + fun call => ∃ σ, (∃ kv ∈ σ, kv.1 % 2 ^ 256 = 0) ∧ fullScope fns σ call + +/-- **The source stage of `Main` from any storage that writes slot 0**: every call of `m` and +`n` on any argument words, no value, under every oracle. -/ +theorem loweringAt (o : SolarTV.Machine.Oracle) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 scopeAt := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + refine SolarTV.Stage.mono (Generic.stageAt o hd (by rw [hk]; exact check_stage0)) ?_ + rintro call ⟨σ, ⟨kv, hkv, h0⟩, hs⟩ + refine ⟨σ, ?_, hs⟩ + intro kv' hkv' + simp only [deployed, List.mem_singleton] at hkv' + subst hkv' + exact ⟨kv, hkv, h0⟩ + +/-- info: 'SolidCore.Refinement.Solar.MulX.selector_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms selector_eq + +/-- info: 'SolidCore.Refinement.Solar.MulX.shape_eq' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms shape_eq + +/-! ## The stage at every value -/ + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: neither function is payable, and stage0 reverts with empty output on +a call of either with a value other than 0. -/ +theorem checkValue_stage0 : + Generic.checkValue mirFuel coreLit SolarTV.Export.Main.stage0 fns = true := by + decide +kernel + +/-- The dispatcher's value check `ne(callvalue, 0)` as `ne(0, 0)`: a dispatcher that accepts a +value. -/ +def dropValueCheck : SolarTV.MIR.Lowered.Inst → SolarTV.MIR.Lowered.Inst + | .ne dst _ b => .ne dst (.const 0) b + | i => i + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the value check rejects stage0 with the dispatcher's value check +dropped (function 3 is the entry). -/ +theorem checkValue_rejects_payable : + Generic.checkValue mirFuel coreLit (mapFn 3 dropValueCheck) fns = false := by + decide +kernel + +/-- **The source stage of `Main` from the deployed storage, at every value**: every call of `m` +and `n` on any argument words, with any value below `2 ^ 256`, from the storage the constructor +leaves, under every oracle. -/ +theorem loweringValue (o : SolarTV.Machine.Oracle) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 + (fun call => ∃ v, Generic.fullScopeValue fns deployed v call) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact Generic.stageDeployedValue o hd (by rw [hk]; exact check_stage0) + (by rw [hk]; exact checkValue_stage0) + +/-- The calls from any storage that writes slot 0, with any value. -/ +def scopeAtValue : Call → Prop := + fun call => ∃ σ v, (∃ kv ∈ σ, kv.1 % 2 ^ 256 = 0) ∧ Generic.fullScopeValue fns σ v call + +/-- **The source stage of `Main` from any storage that writes slot 0, at every value**: every +call of `m` and `n` on any argument words, with any value below `2 ^ 256`, under every +oracle. -/ +theorem loweringAtValue (o : SolarTV.Machine.Oracle) + {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Stage (solidCore fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 scopeAtValue := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + refine SolarTV.Stage.mono (Generic.stageAtValue o hd (by rw [hk]; exact check_stage0) + (by rw [hk]; exact checkValue_stage0)) ?_ + rintro call ⟨σ, v, ⟨kv, hkv, h0⟩, hs⟩ + refine ⟨σ, v, ?_, hs⟩ + intro kv' hkv' + simp only [deployed, List.mem_singleton] at hkv' + subst hkv' + exact ⟨kv, hkv, h0⟩ + +/-- info: 'SolidCore.Refinement.Solar.MulX.check_stage0' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms check_stage0 + +/-- info: 'SolidCore.Refinement.Solar.MulX.check_rejects_unchecked' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms check_rejects_unchecked + +/-- info: 'SolidCore.Refinement.Solar.MulX.check_rejects_add' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms check_rejects_add + +/-- info: 'SolidCore.Refinement.Solar.MulX.lowering' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms lowering + +/-- info: 'SolidCore.Refinement.Solar.MulX.loweringAt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loweringAt + +/-- info: 'SolidCore.Refinement.Solar.MulX.checkValue_stage0' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms checkValue_stage0 + +/-- info: 'SolidCore.Refinement.Solar.MulX.checkValue_rejects_payable' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms checkValue_rejects_payable + +/-- info: 'SolidCore.Refinement.Solar.MulX.loweringValue' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loweringValue + +/-- info: 'SolidCore.Refinement.Solar.MulX.loweringAtValue' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loweringAtValue + +end SolidCore.Refinement.Solar.MulX diff --git a/SolidCore/Refinement/Solar/RequireModulo/Assembly.lean b/SolidCore/Refinement/Solar/RequireModulo/Assembly.lean new file mode 100644 index 00000000..b64d6933 --- /dev/null +++ b/SolidCore/Refinement/Solar/RequireModulo/Assembly.lean @@ -0,0 +1,96 @@ +import SolidCore.Refinement.Solar.AssembleSim +import SolidCore.Refinement.Solar.RequireModulo.Evm10 +import SolidCore.Refinement.Solar.RequireModulo.Bytecode + +/-! +# RequireModuloCases: a turned branch, fallthroughs and a backward jump + +solar's UI test tests/ui/codegen/lowering/evm-ir/constructs/require_modulo_chain.sol compiles +`RequireModuloCases` (`chain(a, b)`: `require(a % b == 0)`, `require(b % 3 == 0 || a % 2 == 0)`, +`return a + b`) with -Ogas --evm-version osaka to the final EVM IR `evm10` (after `block-layout`, +Evm10.lean) and to 103 bytes of runtime bytecode (Bytecode.lean), both exported by +-Zemit-lean-stages and committed verbatim. + +Its layout needs what the generic assembly theorem used to reject: block 0 ends in +`jumpi 1; jump 2` with block 1 next, which the assembler turns into `ISZERO; PUSH bb2; JUMPI` +falling into block 1; blocks 1 and 4 end in a jump to the next block, which the code falls into; +and block 6 jumps back to block 5 (the shared panic tail), which the default potentials, the items +to the end of the layout, cannot bound. + +* `check_ok`: the checker accepts `evm10` and the bytes with `cert`, by the kernel's evaluation. +* `stage`: EVM IR to bytecode is a stage on every call with no value, from any storage, under + every oracle, from `Assemble.stage_of_check` at `check_ok`. +* `stageAll`: the same on every call, with any value, from `Assemble.stage_of_check_all`. +* `unturned_check`, `forward_check`: without the turned block or without the potentials the + checker rejects the same bytes, so the stage needs both. +* `mutantNot_check`, `mutantDiv_check`: the checker rejects one-byte mutants, NOT for the turned + branch's ISZERO and DIV for the first MOD. +-/ + +namespace SolidCore.Refinement.Solar.RequireModulo + +open SolarTV.Assembly SolarTV.Export.RequireModuloCases + +/-- The runtime bytecode solar exported. -/ +def code : ByteArray := ⟨(bytecode.map UInt8.ofNat).toArray⟩ + +/-- The calls of the stage: no value, any call data, any storage. -/ +def scope (call : SolarTV.Call) : Prop := call.callvalue = 0 + +/-- The certificate: each block's offset, the stack height each block needs on entry, the bound +on memory (the panic's 64 bytes), block 0's branch turned, and each block's potential, the most +items a run from it executes. -/ +def cert : Assemble.Cert := + { offsets := [0, 0x33, 0x3a, 0x4a, 0x4e, 0x51, 0x61], needs := [0, 3, 3, 0, 2, 3, 2], top := 64, + turned := [0], costs := [62, 26, 21, 3, 10, 8, 12] } + +set_option maxRecDepth 100000 in +/-- The checker accepts solar's bytecode for the program, by the kernel's evaluation. -/ +theorem check_ok : Assemble.check evm10 code cert = true := by decide +kernel + +/-- EVM IR to bytecode is a stage for RequireModuloCases on every call with no value, from any +storage, under every oracle: the generic theorem at check_ok. -/ +theorem stage (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) SolidCore.Refinement.ethLib evm10 + (show SolidCore.Refinement.ethLib.Prog from code) scope := + Assemble.stage_of_check check_ok o fun _ h => h + +/-- EVM IR to bytecode is a stage for RequireModuloCases on every call, with any value, call data and storage, +under every oracle: `Assemble.stage_of_check_all` at check_ok. -/ +theorem stageAll (o : SolarTV.Machine.Oracle) (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.evmirSem o) SolidCore.Refinement.ethLib evm10 + (show SolidCore.Refinement.ethLib.Prog from code) scope := + Assemble.stage_of_check_all check_ok o scope + +set_option maxRecDepth 100000 in +/-- Without block 0 turned, the lowering expects `PUSH bb1; JUMPI` where the code has +`ISZERO; PUSH bb2; JUMPI`: the walk fails, and so does the checker. -/ +theorem unturned_check : Assemble.check evm10 code { cert with turned := [] } = false ∧ + walk (Assemble.bytesOf code) cert.offset 0 (Assemble.lower evm10 { cert with turned := [] }) + = none := by + decide +kernel + +set_option maxRecDepth 100000 in +/-- With the default potentials the walk still matches, but block 6's jump back to block 5 finds +the items from block 5 to the end of the layout more than those left in block 6, and the block +check fails. -/ +theorem forward_check : Assemble.check evm10 code { cert with costs := [] } = false ∧ + (walk (Assemble.bytesOf code) cert.offset 0 (Assemble.lower evm10 cert)).isSome ∧ + Assemble.blocksOk evm10 { cert with costs := [] } 0 evm10.blocks = false := by + decide +kernel + +/-- The bytes with the byte at `i` replaced by `b`. -/ +def mutant (i b : Nat) : ByteArray := ⟨((bytecode.set i b).map UInt8.ofNat).toArray⟩ + +/-- The turned branch's ISZERO, at offset 47, and the first MOD, at offset 39. -/ +theorem mutated_bytes : bytecode[47]? = some 0x15 ∧ bytecode[39]? = some 0x06 := by decide + +set_option maxRecDepth 100000 in +/-- NOT for the turned branch's ISZERO: the checker rejects it. -/ +theorem mutantNot_check : Assemble.check evm10 (mutant 47 0x19) cert = false := by decide +kernel + +set_option maxRecDepth 100000 in +/-- DIV for the first MOD: the checker rejects it. -/ +theorem mutantDiv_check : Assemble.check evm10 (mutant 39 0x04) cert = false := by decide +kernel + +end SolidCore.Refinement.Solar.RequireModulo diff --git a/SolidCore/Refinement/Solar/RequireModulo/Bytecode.lean b/SolidCore/Refinement/Solar/RequireModulo/Bytecode.lean new file mode 100644 index 00000000..9cf2a1e0 --- /dev/null +++ b/SolidCore/Refinement/Solar/RequireModulo/Bytecode.lean @@ -0,0 +1,20 @@ +-- solar-lean-stage: kind=bytecode index=0 pass=assemble +/-! Generated by `solar -Zemit-lean-stages` for `RequireModuloCases`; do not edit. -/ + +namespace SolarTV.Export.RequireModuloCases + +/-- The runtime bytecode, byte by byte. -/ +def bytecode : List Nat := + [0x34, 0x60, 0x4a, 0x57, 0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x80, 0x63, 0x1e, 0xa7, 0x71, 0x44, 0x03, + 0x60, 0x4a, 0x57, 0x60, 0x44, 0x36, 0x10, 0x60, 0x4a, 0x57, 0x60, 0x24, 0x35, 0x80, 0x15, 0x60, + 0x4e, 0x57, 0x60, 0x04, 0x35, 0x81, 0x81, 0x06, 0x60, 0x4a, 0x57, 0x60, 0x03, 0x82, 0x06, 0x15, + 0x60, 0x3a, 0x57, 0x60, 0x01, 0x81, 0x16, 0x60, 0x4a, 0x57, 0x5b, 0x90, 0x81, 0x01, 0x90, 0x81, + 0x10, 0x60, 0x61, 0x57, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x60, + 0x12, 0x5b, 0x60, 0x20, 0x52, 0x63, 0x4e, 0x48, 0x7b, 0x71, 0x5f, 0x52, 0x60, 0x24, 0x60, 0x1c, + 0xfd, 0x5b, 0x60, 0x11, 0x60, 0x51, 0x56] + +/-- The runtime bytecode in hex, as `--emit=bin-runtime` prints it. -/ +def bytecodeHex : String := + "34604a575f3560e01c80631ea7714403604a5760443610604a576024358015604e57600435818106604a576003820615603a5760018116604a575b9081019081106061575f5260205ff35b5f5ffd5b60125b602052634e487b715f526024601cfd5b6011605156" + +end SolarTV.Export.RequireModuloCases diff --git a/SolidCore/Refinement/Solar/RequireModulo/Evm10.lean b/SolidCore/Refinement/Solar/RequireModulo/Evm10.lean new file mode 100644 index 00000000..46492042 --- /dev/null +++ b/SolidCore/Refinement/Solar/RequireModulo/Evm10.lean @@ -0,0 +1,81 @@ +-- solar-lean-stage: kind=evm index=10 pass=block-layout +import SolarTV.EVMIR.Program + +/-! Generated by `solar -Zemit-lean-stages` for `RequireModuloCases`; do not edit. -/ + +namespace SolarTV.Export.RequireModuloCases + +/-- The runtime EVM IR after `block-layout`. -/ +def evm10 : EVM.Program.Program := + { blocks := [ + -- bb0 + [.effect .callvalue 0, + .jumpi 3, + .op (.stack (.push 0)), + .effect .calldataload 1, + .op (.stack (.push 224)), + .op (.stack .shr), + .op (.stack (.dup 0)), + .op (.stack (.push 0x1ea77144)), + .op (.stack .sub), + .jumpi 3, + .op (.stack (.push 68)), + .op (.stack .calldatasize), + .op (.stack .lt), + .jumpi 3, + .op (.stack (.push 36)), + .effect .calldataload 1, + .op (.stack (.dup 0)), + .op (.stack .iszero), + .jumpi 4, + .op (.stack (.push 4)), + .effect .calldataload 1, + .op (.stack (.dup 1)), + .op (.stack (.dup 1)), + .op (.stack .mod), + .jumpi 3, + .op (.stack (.push 3)), + .op (.stack (.dup 2)), + .op (.stack .mod), + .jumpi 1, + .jump 2], + -- bb9 + [.op (.stack (.push 1)), + .op (.stack (.dup 1)), + .op (.stack .and), + .jumpi 3, + .jump 2], + -- bb10 + [.op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .add), + .op (.stack (.swap 0)), + .op (.stack (.dup 1)), + .op (.stack .lt), + .jumpi 6, + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 32)), + .op (.stack (.push 0)), + .ret], + -- bb3 + [.op (.stack (.push 0)), + .op (.stack (.push 0)), + .revert], + -- bb8 + [.op (.stack (.push 18)), + .jump 5], + -- bb13 + [.op (.stack (.push 32)), + .op .store, + .op (.stack (.push 0x4e487b71)), + .op (.stack (.push 0)), + .op .store, + .op (.stack (.push 36)), + .op (.stack (.push 28)), + .revert], + -- bb12 + [.op (.stack (.push 17)), + .jump 5]] } + +end SolarTV.Export.RequireModuloCases diff --git a/SolidCore/Refinement/Solar/RunOracle.lean b/SolidCore/Refinement/Solar/RunOracle.lean new file mode 100644 index 00000000..76cc2353 --- /dev/null +++ b/SolidCore/Refinement/Solar/RunOracle.lean @@ -0,0 +1,291 @@ +import SolidCore.Refinement.Solar.AssembleLoopWithin + +/-! +# One oracle per run + +A call's outcomes in EthLib depend on the gas and on the other accounts: what GAS pushes, whether +a call succeeds, what it returns and the storage after it. No single SolarTV oracle describes every +run, and a fixed oracle constrained to agree with EthLib on all of them at once is unsatisfiable. +So the theorem from EVM IR to bytecode takes this form (`WithinRun`): for every gas and every call +of the scope, there is an oracle `o`, meeting the constraints `Ok` the certificate names, under +which every result of the bytecode on that call at that gas is the EVM IR's or a failure that +changes nothing. It composes with stages and specifications proved for every oracle +(`holds_of_withinRun`), which is how the MIR and source stages are stated. + +`tableOracle` is the oracle a run gives: its answers to GAS, to RETURNDATASIZE and RETURNDATACOPY, +to the success of a call or creation and to the storage after it are read from tables indexed by +how many such events the world holds, so they are a function of the world by construction and +every table is realised (no consistency hypothesis needs a satisfiability argument beyond the +definition). Appending a log or a GAS read keeps the return data (`rd_log`, `rd_read`), as EthLib +does. `tableOracle` keeps the caller, the hash and the reads of the block and the transaction of +the oracle it extends, so `OracleOk` and `EnvOk` carry over (`tableOracle_oracleOk`, +`tableOracle_envOk`). + +`withinRun_of_checkL` restates the assembly theorem for code with loops in this form, choosing the +oracle; for code with neither GAS nor calls the choice is any oracle meeting `OracleOk` and `EnvOk`. +-/ + +namespace SolidCore.Refinement.Solar.RunOracle + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Final +open SolidCore.Refinement.Solar.Assemble +open EthLib.Base (byteAt) + +/-! ## The theorem form -/ + +/-- **Per-run refinement**: for every gas and every call of the scope there is an oracle meeting +`Ok`, under which every result of `code` on that call at that gas is the result of `p` in +`sem o`, or a failure that leaves the storage and logs nothing. -/ +def WithinRun (sem : Oracle → Sem) (p : ∀ o, (sem o).Prog) (code : ByteArray) (scope : Call → Prop) + (Ok : Oracle → Prop) : Prop := + ∀ gas call, scope call → ∃ o, Ok o ∧ Within (sem o) (ethLibWith gas) (p o) code (· = call) + +/-- A refinement under one oracle meeting `Ok` at every gas is a per-run refinement. -/ +theorem WithinRun.of_fixed {sem : Oracle → Sem} {p : ∀ o, (sem o).Prog} {code : ByteArray} + {scope : Call → Prop} {Ok : Oracle → Prop} (o : Oracle) (ho : Ok o) + (h : ∀ gas, Within (sem o) (ethLibWith gas) (p o) code scope) : + WithinRun sem p code scope Ok := + fun gas call hc => ⟨o, ho, fun call' h' obs hrun => h gas call' (h' ▸ hc) obs hrun⟩ + +/-- Stages proved for every oracle meeting `Ok` before a per-run refinement, with the earlier +program defined wherever the later one is, give a per-run refinement from the earlier program. -/ +theorem WithinRun.of_stage {A sem : Oracle → Sem} {q : ∀ o, (A o).Prog} {p : ∀ o, (sem o).Prog} + {code : ByteArray} {scope : Call → Prop} {Ok : Oracle → Prop} + (stage : ∀ o, Ok o → Stage (A o) (sem o) (q o) (p o) scope) + (defined : ∀ o, Ok o → ∀ call, scope call → (A o).run (q o) call = none → + (sem o).run (p o) call = none) + (h : WithinRun sem p code scope Ok) : WithinRun A q code scope Ok := by + intro gas call hc + obtain ⟨o, ho, hw⟩ := h gas call hc + refine ⟨o, ho, fun call' h' obs hrun => ?_⟩ + subst h' + rcases hw call' rfl obs hrun with e | e + · left + cases hq : (A o).run (q o) call' with + | none => rw [defined o ho call' hc hq] at e; cases e + | some obs' => + have := stage o ho call' hc obs' hq + rw [this] at e + rw [e] + · exact Or.inr e + +/-- **A specification proved for every oracle meeting `Ok` holds of the bytecode at every gas.** -/ +theorem holds_of_withinRun {St : Type} {sem : Oracle → Sem} {p : ∀ o, (sem o).Prog} + {code : ByteArray} {spec : ContractSpec St} {Ok : Oracle → Prop} + (holds : ∀ o, Ok o → Holds (sem o) (p o) spec) (h : WithinRun sem p code spec.Calls Ok) + (gas : Nat) : Holds (ethLibWith gas) code spec := by + intro f hf args ht v hv σ hinv hreq obs hrun + have hc : spec.Calls (f.call args v σ) := ⟨f, hf, args, ht, v, hv, σ, rfl⟩ + obtain ⟨o, ho, hw⟩ := h gas _ hc + rcases hw _ rfl obs hrun with e | ⟨hs, hst, hl⟩ + · exact holds o ho f hf args ht v hv σ hinv hreq obs e + · exact ⟨fun h'' => absurd (hs.symm.trans h'') (by decide), fun _ => ⟨hst, hl⟩⟩ + +/-! ## The oracle of a run -/ + +/-- An event that sends a message: a call or a creation. Their results, return data and the +storage after them are what the oracle answers. -/ +def Event.sends : Event → Bool + | .call .. | .create .. => true + | .log .. | .read _ => false + +/-- An event that reads the gas left. -/ +def Event.readsGas : Event → Bool + | .read n => n == "gas" + | _ => false + +/-- The messages a world has sent. -/ +def sent (w : List Event) : Nat := (w.filter Event.sends).length + +/-- The GAS reads of a world. -/ +def gasReads (w : List Event) : Nat := (w.filter Event.readsGas).length + +/-- What a run of the bytecode answers, in order: for each message it sends, its success, its +return data and the storage and transient storage after it; for each GAS read, the gas pushed. -/ +structure RunTable where + oks : List Bool := [] + outs : List ByteArray := [] + stores : List (Word → Word) := [] + transients : List (Word → Word) := [] + gases : List Nat := [] + +/-- The return data a world leaves under the table: the last message's, empty before any. -/ +def RunTable.out (T : RunTable) (w : List Event) : ByteArray := + if sent w = 0 then .empty else T.outs.getD (sent w - 1) .empty + +/-- The oracle a run gives, over `base` for everything a run does not decide. -/ +def tableOracle (base : Oracle) (T : RunTable) : Oracle := + { base with + env := fun name w args => + if name = "returndatasize" ∧ args = [] then BitVec.ofNat 256 (T.out w).size + else if name = "returndata" then + match args with + | [i] => BitVec.ofNat 256 (byteAt (T.out w) i.toNat).toNat + | _ => base.env name w args + else if name = "gas" ∧ args = [] ∧ gasReads w ≠ 0 then + BitVec.ofNat 256 (T.gases.getD (gasReads w - 1) 0) + else base.env name w args + result := fun w => if sent w ≠ 0 ∧ T.oks.getD (sent w - 1) false = true then 1 else 0 + storageAfter := fun w => + if sent w = 0 then base.storageAfter w else T.stores.getD (sent w - 1) (base.storageAfter w) + transientAfter := fun w => + if sent w = 0 then base.transientAfter w + else T.transients.getD (sent w - 1) (base.transientAfter w) } + +/-! ## What the oracle of a run answers -/ + +@[simp] theorem sent_append (w w' : List Event) : sent (w ++ w') = sent w + sent w' := by + simp [sent, List.filter_append] + +@[simp] theorem gasReads_append (w w' : List Event) : + gasReads (w ++ w') = gasReads w + gasReads w' := by + simp [gasReads, List.filter_append] + +@[simp] theorem sent_log (t : List Word) (d : List Memory.Byte) : sent [.log t d] = 0 := rfl +@[simp] theorem sent_read (n : String) : sent [.read n] = 0 := rfl +@[simp] theorem sent_call (k : CallKind) (ops : List Word) (i : List Memory.Byte) + (s t : Word → Word) : sent [.call k ops i s t] = 1 := rfl +@[simp] theorem gasReads_gas : gasReads [.read "gas"] = 1 := rfl +@[simp] theorem gasReads_log (t : List Word) (d : List Memory.Byte) : gasReads [.log t d] = 0 := rfl +@[simp] theorem gasReads_call (k : CallKind) (ops : List Word) (i : List Memory.Byte) + (s t : Word → Word) : gasReads [.call k ops i s t] = 0 := rfl + +/-- The size of the return data is the table's. -/ +theorem returndataSize_table (base : Oracle) (T : RunTable) (w : List Event) : + returndataSize (tableOracle base T) w = BitVec.ofNat 256 (T.out w).size := by + simp [returndataSize, tableOracle] + +/-- Each byte of the return data is the table's. -/ +theorem returndataByte_table (base : Oracle) (T : RunTable) (w : List Event) (i : Nat) + (hi : i < 2 ^ 256) : + returndataByte (tableOracle base T) w i = (byteAt (T.out w) i).toBitVec := by + simp only [returndataByte, tableOracle] + simp only [show ¬("returndata" = "returndatasize" ∧ [BitVec.ofNat 256 i] = []) by simp, ite_false, + ite_true, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hi] + apply BitVec.eq_of_toNat_eq + simp only [BitVec.toNat_setWidth, BitVec.toNat_ofNat, UInt8.toNat_toBitVec] + have := (byteAt (T.out w) i).toNat_lt + rw [Nat.mod_eq_of_lt (by omega), Nat.mod_eq_of_lt (by omega)] + +/-- The `k`-th GAS read pushes the table's `k`-th gas. -/ +theorem gas_table (base : Oracle) (T : RunTable) (w : List Event) : + (tableOracle base T).env "gas" (w ++ [.read "gas"]) [] = + BitVec.ofNat 256 (T.gases.getD (gasReads w) 0) := by + simp [tableOracle] + +/-- A call's success flag is the table's. -/ +theorem callFlag_table (base : Oracle) (T : RunTable) (w : List Event) (k : CallKind) + (ops : List Word) (i : List Memory.Byte) (s t : Word → Word) : + callFlag (tableOracle base T) (w ++ [.call k ops i s t]) = + if T.oks.getD (sent w) false = true then 1 else 0 := by + simp only [callFlag, tableOracle, sent_append, sent_call] + cases h : T.oks[sent w]?.getD false <;> simp [List.getD_eq_getElem?_getD, h] + +/-- The storage after the call is the table's. -/ +theorem storageAfter_table (base : Oracle) (T : RunTable) (w : List Event) (k : CallKind) + (ops : List Word) (i : List Memory.Byte) (s t : Word → Word) : + (tableOracle base T).storageAfter (w ++ [.call k ops i s t]) = + T.stores.getD (sent w) (base.storageAfter (w ++ [.call k ops i s t])) := by + simp [tableOracle] + +/-- After a call the return data is the call's output in the table. -/ +theorem out_call (T : RunTable) (w : List Event) (k : CallKind) (ops : List Word) + (i : List Memory.Byte) (s t : Word → Word) : + T.out (w ++ [.call k ops i s t]) = T.outs.getD (sent w) .empty := by + simp [RunTable.out] + +/-- A log keeps the return data. -/ +theorem rd_log (T : RunTable) (w : List Event) (t : List Word) (d : List Memory.Byte) : + T.out (w ++ [.log t d]) = T.out w := by + simp [RunTable.out] + +/-- A read of the world, GAS among them, keeps the return data. -/ +theorem rd_read (T : RunTable) (w : List Event) (n : String) : T.out (w ++ [.read n]) = T.out w := by + simp [RunTable.out] + +/-- Before any message the return data is empty, as EthLib's frame starts with. -/ +theorem out_nil (T : RunTable) : T.out [] = .empty := rfl + +/-- The oracle of a run keeps the caller and the hash. -/ +theorem tableOracle_oracleOk {base : Oracle} (T : RunTable) (h : OracleOk base) : + OracleOk (tableOracle base T) := h + +/-- The oracle of a run keeps the reads of the block and the transaction. -/ +theorem tableOracle_envOk {base : Oracle} (T : RunTable) (h : EnvOk base) : + EnvOk (tableOracle base T) := by + intro name byte w he world + have hn : name ≠ "returndatasize" ∧ name ≠ "returndata" ∧ name ≠ "gas" := by + unfold envRead at he + refine ⟨?_, ?_, ?_⟩ <;> (rintro rfl; simp at he) + simp only [tableOracle, hn.1, hn.2.1, hn.2.2, false_and, ite_false] + exact h name byte w he world + +/-- Every oracle extends to one meeting `OracleOk` and `EnvOk`, with any table: the constraints +the assembly theorem puts on the oracle of a run are satisfiable together. -/ +theorem table_ok (o : Oracle) (T : RunTable) : + OracleOk (tableOracle (envOracle (ethOracle o)) T) ∧ + EnvOk (tableOracle (envOracle (ethOracle o)) T) := + ⟨tableOracle_oracleOk T (ethOracle_ok o), tableOracle_envOk T (envOracle_ok _)⟩ + +/-! ## The assembly theorem in this form -/ + +/-- The constraints the certificate puts on the oracle of a run. -/ +def CertOk (c : Cert) (o : Oracle) : Prop := + (c.env = true → OracleOk o) ∧ (c.reads = true → EnvOk o) + +/-- An oracle: what a per-run theorem extends with the tables of a run. -/ +def anyOracle : Oracle := ⟨fun _ _ _ => 0, fun _ => 0, fun _ _ => 0, fun _ _ => 0, fun _ => 0, 0⟩ + +/-- **EVM IR to bytecode, run by run, for code with loops.** -/ +theorem withinRun_of_checkL {p : Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (hc : AssembleLoop.checkL p code c mx = true) (scope : Call → Prop) : + WithinRun evmirSem (fun _ => p) code scope (CertOk c) := by + have hok := table_ok anyOracle {} + refine WithinRun.of_fixed (tableOracle (envOracle (ethOracle anyOracle)) {}) + ⟨fun _ => hok.1, fun _ => hok.2⟩ fun gas => ?_ + exact AssembleLoop.within_of_checkL hc _ (fun _ => hok.1) scope gas (fun _ => hok.2) + +/-- Stages read backwards (every result of the later program is the earlier one's), for every +oracle meeting `Ok`, before a per-run refinement give a per-run refinement from the earlier program. -/ +theorem WithinRun.of_back {A sem : Oracle → Sem} {q : ∀ o, (A o).Prog} {p : ∀ o, (sem o).Prog} + {code : ByteArray} {scope : Call → Prop} {Ok : Oracle → Prop} + (back : ∀ o, Ok o → Stage (sem o) (A o) (p o) (q o) scope) + (h : WithinRun sem p code scope Ok) : WithinRun A q code scope Ok := by + intro gas call hc + obtain ⟨o, ho, hw⟩ := h gas call hc + refine ⟨o, ho, fun call' h' obs hrun => ?_⟩ + subst h' + rcases hw call' rfl obs hrun with e | e + · exact Or.inl (back o ho call' hc obs e) + · exact Or.inr e + +/-- **The first lowered MIR to the exact bytecode, run by run**: the backend stages read backwards +and the assembly checker for code with loops give, for every gas and every call, an oracle meeting +the certificate's constraints under which every result of the bytecode is the first lowered MIR's +or a failure that changes nothing. -/ +theorem withinRun_mir_of_checkL {stage0 : MIR.Lowered.moduleLayer.Prog} {p : Program} + {code : ByteArray} {c : Cert} {mx : List Nat} {S scope : Call → Prop} + (back : ∀ o, Certified EVM.Program.layer MIR.Lowered.moduleLayer o p stage0 S) + (hS : ∀ call, scope call → S call) (hc : AssembleLoop.checkL p code c mx = true) : + WithinRun mirSem (fun _ => stage0) code scope (CertOk c) := + WithinRun.of_back (fun o _ => fun call hcall obs h => + stage_of_certified (back o) call (hS call hcall) obs h) + (withinRun_of_checkL hc scope) + +/-- info: 'SolidCore.Refinement.Solar.RunOracle.holds_of_withinRun' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holds_of_withinRun + +/-- info: 'SolidCore.Refinement.Solar.RunOracle.withinRun_of_checkL' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms withinRun_of_checkL + +/-- info: 'SolidCore.Refinement.Solar.RunOracle.withinRun_mir_of_checkL' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms withinRun_mir_of_checkL + +/-- info: 'SolidCore.Refinement.Solar.RunOracle.table_ok' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms table_ok + +end SolidCore.Refinement.Solar.RunOracle diff --git a/SolidCore/Refinement/Solar/RunOracleSource.lean b/SolidCore/Refinement/Solar/RunOracleSource.lean new file mode 100644 index 00000000..1a536003 --- /dev/null +++ b/SolidCore/Refinement/Solar/RunOracleSource.lean @@ -0,0 +1,77 @@ +import SolidCore.Refinement.Solar.RunOracle +import SolidCore.Refinement.SourceOracleSat + +/-! +# The assembly premise of the composition under a call oracle + +`Verify/SourceOracle.holds_of_runs` composes a specification proved of SolidCore in every open world +with the stages for every oracle and an assembly premise run by run: for every gas and call, an +oracle `o` and an open world `W` that agree (`CallsAgree o W`) under which the EVM IR gives the +bytecode's result or a failure that changes nothing. For a program the checker of code with loops +accepts, `assembly_of_checkL` gives that premise: the reads the certificate asks of the oracle +(`CertOk`: the caller, the hash, the block and the transaction) touch none of what `CallsAgree` +constrains (call results, storage after calls, return data, code sizes), so the failing world's +oracle with EthLib's caller, hash and environment meets both. +-/ + +namespace SolidCore.Refinement.Solar.RunOracle + +open SolarTV SolarTV.Machine SolidCore.Refinement SolidCore.Refinement.Final +open SolidCore.Refinement.Solar.Assemble + +/-- EthLib's caller, hash and environment reads leave every other read of the oracle. -/ +theorem env_envEth (o : Oracle) (n : String) (w : List Event) (a : List Word) + (h : envRead n = none) : (envOracle (ethOracle o)).env n w a = o.env n w a := by + simp [envOracle, ethOracle, h] + +theorem codesAgree_envEth (o : Oracle) (w : List Event) (code : Nat → List SolidCore.Solidity.Byte) : + CodesAgree (envOracle (ethOracle o)) w code ↔ CodesAgree o w code := by + unfold CodesAgree + simp only [env_envEth o "extcodesize" _ _ rfl] + +theorem returndataSize_envEth (o : Oracle) (w : List Event) : + returndataSize (envOracle (ethOracle o)) w = returndataSize o w := + env_envEth o "returndatasize" w [] rfl + +theorem returndataByte_envEth (o : Oracle) (w : List Event) (j : Nat) : + returndataByte (envOracle (ethOracle o)) w j = returndataByte o w j := by + unfold returndataByte + rw [env_envEth o "returndata" w _ rfl] + +/-- EthLib's caller, hash and environment reads keep the oracle hypothesis of the open world. -/ +theorem callsAgree_envEth {o : Oracle} {W : World} (h : CallsAgree o W) : + CallsAgree (envOracle (ethOracle o)) W := by + refine ⟨fun w hw => (codesAgree_envEth o _ _).2 (h.codes w hw), ?_, h.static⟩ + intro hh world req a ha w k s i st tr hl hm hst hcod + obtain ⟨h1, h2, h3⟩ := h.calls hh world req a ha w k s i st tr hl hm hst + ((codesAgree_envEth o _ _).1 hcod) + refine ⟨h1, h2, fun rest hr => ?_⟩ + obtain ⟨r1, r2, r3⟩ := h3 rest hr + exact ⟨by rw [returndataSize_envEth]; exact r1, + fun j hj hj' => by rw [returndataByte_envEth]; exact r2 j hj hj', (codesAgree_envEth o _ _).2 r3⟩ + +/-- `envOracle` keeps EthLib's caller and hash. -/ +theorem envOracle_oracleOk {o : Oracle} : OracleOk (envOracle (ethOracle o)) := ethOracle_ok o + +/-- An oracle and an open world that agree, under which the certificate's reads are EthLib's. -/ +theorem certOk_callsAgree (c : Cert) : + ∃ (o : Oracle) (W : World), W.Open ∧ CallsAgree o W ∧ CertOk c o := + ⟨envOracle (ethOracle Witness.failOracle), Witness.failWorld, Witness.failWorld_open, + callsAgree_envEth Witness.failAgree, + fun _ => envOracle_oracleOk, fun _ => envOracle_ok _⟩ + +/-- **The assembly premise of `holds_of_runs`** for every program the checker of code with loops +accepts. -/ +theorem assembly_of_checkL {p : Program} {code : ByteArray} {c : Cert} {mx : List Nat} + (hc : AssembleLoop.checkL p code c mx = true) (scope : Call → Prop) : + ∀ gas call, scope call → ∃ (o : Oracle) (W : World), W.Open ∧ CallsAgree o W ∧ + Within (evmirSem o) (ethLibWith gas) p code (· = call) := by + intro gas call _ + obtain ⟨o, W, hW, hagree, hok⟩ := certOk_callsAgree c + exact ⟨o, W, hW, hagree, AssembleLoop.within_of_checkL hc o hok.1 _ gas hok.2⟩ + +/-- info: 'SolidCore.Refinement.Solar.RunOracle.assembly_of_checkL' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms assembly_of_checkL + +end SolidCore.Refinement.Solar.RunOracle diff --git a/SolidCore/Refinement/Solar/Sequences.lean b/SolidCore/Refinement/Solar/Sequences.lean new file mode 100644 index 00000000..0f335766 --- /dev/null +++ b/SolidCore/Refinement/Solar/Sequences.lean @@ -0,0 +1,77 @@ +import SolidCore.Refinement.Solar.Milestone +import SolidCore.Refinement.ComposeSeq + +/-! +# The w5 milestone on sequences of calls + +\`certifiedAt\` (Milestone.lean) states w5's specification from any storage for one call, through +every stage of solar's pipeline. Each stage is proved from any storage, so the stages lift to +sequences of calls (\`StageSeq.of_anyStorage\`, through \`bytecodeSeq_of_stages_invariant\`), and +\`certifiedSeq\` states it for every finite sequence of calls of \`f\`, from any initial storage: +solar's bytecode finishes every call of the sequence, each call meets \`Verify.W5.postAt\`, and +the storage list each call starts from (\`writeBack []\`: the previous call's list, since \`f\` +writes no slot) reads as exactly the previous call's final storage (\`Carries\`). + +\`fullMsgs fns\` is the messages of \`fullScope fns\`: a function of \`fns\` on argument words +below \`2 ^ 256\`, with no value, without the storage the sequence supplies. +-/ + +namespace SolidCore.Refinement.Abi + +/-- Every message of a function of \`fns\` on argument words below \`2 ^ 256\`, with no value: the +calls of \`fullScope fns\`, without their storage. -/ +def fullMsgs (fns : List Fn) (m : Msg) : Prop := + ∃ fn ∈ fns, ∃ args : List Nat, args.length = fn.params.length ∧ (∀ a ∈ args, a < 2 ^ 256) ∧ + m = { calldata := calldata fn.sel args, callvalue := 0 } + +/-- A message of \`fullMsgs fns\` from any storage is a call of \`fullScope fns\`. -/ +theorem fullScope_call {fns : List Fn} {m : Msg} (h : fullMsgs fns m) (σ : List (Nat × Nat)) : + fullScope fns σ (m.call σ) := by + obtain ⟨fn, hfn, args, hlen, hlt, rfl⟩ := h + exact ⟨fn, hfn, args, hlen, hlt, rfl⟩ + +end SolidCore.Refinement.Abi + +namespace SolidCore.Refinement.Solar.W1 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +/-- What each call of a sequence of w5 meets: \`Verify.W5.postAt\`, and the next call starts +from exactly its final storage. -/ +def postSeq (call : Call) (obs : Observable) : Prop := + Verify.W5.postAt call obs ∧ Carries (writeBack []) call obs + +/-- A call that keeps its storage is carried exactly by \`writeBack []\`. -/ +theorem carries_of_postAt {call : Call} {obs : Observable} (h : Verify.W5.postAt call obs) : + Carries (writeBack []) call obs := by + funext slot + simp only [writeBack, List.map_nil, List.append_nil] + exact (h.2.2 slot).symm + +/-- **The w5 milestone on sequences.** solar's runtime bytecode for w5 finishes every finite +sequence of calls of \`f\` (any argument words, no value) from any initial storage under EthLib, +each call meeting w5's specification from its storage (\`Verify.W5.postAt\`) and leaving exactly +the storage the next call starts from, through every stage of solar's pipeline, each proved from +any storage. -/ +theorem certifiedSeq : + SatisfiesSeq ethLib code (writeBack []) (within (fun _ => True) (fullMsgs Corpus.W5.fns)) + (fun _ _ => True) (Each postSeq (writeBack [])) := by + obtain ⟨c, hc, hspec⟩ := Verify.W5.satisfiesAt + exact bytecodeSeq_of_stages_invariant + (Satisfies.mono hspec fun _ _ _ _ h => ⟨h, carries_of_postAt h⟩) (loweringAt oracle hc) + ((SolarTV.Milestone.W1.w1_mir_to_evmir oracle).mono fun _ _ => trivial) (stageAt oracle) + (fun σ _ _ hm => ⟨⟨σ, fullScope_call hm σ⟩, trivial⟩) fun _ _ _ _ _ _ => trivial + +/-- The one-call milestone from any storage is \`certifiedSeq\`'s length-1 case: +\`certifiedAt\`'s statement as a statement on sequences of one message +(\`satisfiesSeq_single_iff\`). -/ +theorem certifiedAt_single : + SatisfiesSeq ethLib code (writeBack []) (single Verify.W5.scopeAt) (singlePre Verify.W5.pre) + (singlePost Verify.W5.postAt) := + (satisfiesSeq_single_iff _).mpr certifiedAt + +/-- info: 'SolidCore.Refinement.Solar.W1.certifiedSeq' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedSeq + +end SolidCore.Refinement.Solar.W1 diff --git a/SolidCore/Refinement/Solar/Total.lean b/SolidCore/Refinement/Solar/Total.lean new file mode 100644 index 00000000..1a91b0d4 --- /dev/null +++ b/SolidCore/Refinement/Solar/Total.lean @@ -0,0 +1,100 @@ +import SolidCore.Refinement.Generic.Total +import SolidCore.Refinement.Keccak.TwoWords +import SolidCore.Refinement.Solar.Bank.Lowering +import SolidCore.Refinement.Solar.Events.Lowering + +/-! +# bank and events: what makes their stages total + +`Bank.certified` and `Events.certified` are stages from SolidCore to solar's bytecode under every +oracle `o` with EthLib's caller and hash (`Assemble.OracleOk o`). Two things could make such a +theorem hold for no reason: no oracle could satisfy its hypothesis, or SolidCore could finish no +call of its scope (a stage is vacuous there). This module rules out both: + +* `ethOracle_sourceEnvOk`: an oracle with EthLib caller and Keccak-256 (the fields `Assemble.ethOracle` + sets, for which `Assemble.ethOracle_ok` proves `Assemble.OracleOk`) is one the generic source + stage takes (`Generic.SourceEnvOk`), since EthLib and SolidCore Keccak-256 agree on two words + (`Keccak.ethKeccak_twoWords`). +* `Bank.defined`, `Events.defined`: SolidCore finishes every call of their scope (every function, any + argument words, any storage, no value), from the generic stage's `Generic.defined`. +* `Bank.refines_of_stage`, `Events.refines_of_stage`: any stage from SolidCore to bytecode on that + scope is therefore `Refines`, so + `Bank.refines_of_stage hc (Bank.certified (Assemble.ethOracle o) + (Assemble.ethOracle_ok o) Bank.ethKeccakAgree hc)` is the + hypothesis-free total refinement of bank, and likewise for events. + +The composition itself is not stated here: `Bank.certified` and `Events.certified` import the assembly +stage (`Solar/Assemble.lean`), which does not build against the pinned solar-tv. +-/ + +namespace SolidCore.Refinement.Solar + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity + +/-- The oracle with EthLib's caller and Keccak-256 and every other field constant: the fields +`Assemble.ethOracle` sets, on a constant oracle. -/ +def ethOracle : SolarTV.Machine.Oracle := + { env := fun _ _ _ => 0, result := fun _ => 0, storageAfter := fun _ _ => 0, + transientAfter := fun _ _ => 0, + keccak := fun bytes => EthLib.Execution.Evm.keccak ⟨(bytes.map UInt8.ofBitVec).toArray⟩, + caller := BitVec.ofNat 160 SolidCore.Refinement.callerAddress } + +/-- It is one the generic source stage takes: its caller is SolidCore's and its Keccak-256 of two +words is SolidCore's slot hash. So the source stages' oracle hypothesis is satisfiable. -/ +theorem ethOracle_sourceEnvOk : Generic.SourceEnvOk ethOracle := + ⟨by unfold Generic.CallerOk; decide +kernel, + fun a b _ _ => Keccak.ethKeccak_twoWords a b⟩ + +theorem sourceEnvOk_exists : ∃ o, Generic.SourceEnvOk o := ⟨ethOracle, ethOracle_sourceEnvOk⟩ + +namespace Bank + +/-- SolidCore finishes every call of `deposit`, `depositFor` and `balanceOf` on any argument +words, no value, from any storage. -/ +theorem defined {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Defined (solidCore fuel) c (fun call => ∃ σ, fullScope fns σ call) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact Generic.defined hd (by rw [hk]; exact check_stage0) + +/-- A stage from bank's SolidCore contract to any bytecode on that scope is a total refinement. -/ +theorem refines_of_stage {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) {code : ByteArray} + (st : Stage (solidCore fuel) ethLib c code (fun call => ∃ σ, fullScope fns σ call)) : + Refines fuel c code (fun call => ∃ σ, fullScope fns σ call) := + refines_iff_total.mpr (total_iff_stage.mpr ⟨st, defined hc⟩) + +end Bank + +namespace Events + +/-- SolidCore finishes every call of `transfer` on any argument words, no value, from any storage. -/ +theorem defined {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Defined (solidCore fuel) c (fun call => ∃ σ, fullScope fns σ call) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact Generic.defined hd (by rw [hk]; exact check_stage0) + +/-- A stage from events' SolidCore contract to any bytecode on that scope is a total +refinement. -/ +theorem refines_of_stage {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) {code : ByteArray} + (st : Stage (solidCore fuel) ethLib c code (fun call => ∃ σ, fullScope fns σ call)) : + Refines fuel c code (fun call => ∃ σ, fullScope fns σ call) := + refines_iff_total.mpr (total_iff_stage.mpr ⟨st, defined hc⟩) + +end Events + +/-- info: 'SolidCore.Refinement.Solar.ethOracle_sourceEnvOk' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms ethOracle_sourceEnvOk + +/-- +info: 'SolidCore.Refinement.Solar.Bank.refines_of_stage' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms Bank.refines_of_stage + +/-- +info: 'SolidCore.Refinement.Solar.Events.refines_of_stage' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms Events.refines_of_stage + +end SolidCore.Refinement.Solar diff --git a/SolidCore/Refinement/Solar/Totality.lean b/SolidCore/Refinement/Solar/Totality.lean new file mode 100644 index 00000000..688b1160 --- /dev/null +++ b/SolidCore/Refinement/Solar/Totality.lean @@ -0,0 +1,505 @@ +import SolidCore.Refinement.Generic.Total +import SolidCore.Refinement.Generic.Value +import SolidCore.Refinement.Solar.Total +import SolidCore.Refinement.Solar.Bank.Certified +import SolidCore.Refinement.Solar.Events.Certified +import SolidCore.Refinement.Solar.MulX.Certified + +/-! +# bank, events and mulx: SolidCore ends, so the certified stages are total + +`Bank.certified`, `Events.certified` and `MulX.certified_*` are stages: if SolidCore finishes a +call of the scope within its fuel (4096 statements), the bytecode gives the same observable. A +stage says nothing on a call SolidCore does not finish (`Stage.of_never`), so on their own they +could hold because SolidCore ends on no call. This module closes that gap for the three +contracts, as `counter` and `c4` already do: + +* `.source_ends` (and `source_ends_value`, `source_ends_at`, `source_ends_at_value` where the + certified theorems have those scopes): SolidCore finishes every call of the scope within fuel + `.fuel = 4096`, read off the generic source stage's check (`Generic.definedAt`, and + `Generic.definedAtValue` below for calls with a value, which SolidCore rejects). +* `.certified_total` (and the other scopes): the end-to-end statement as `Refines`, a total + refinement (`Total (solidCore fuel) ethLib`): on every call of the scope both SolidCore and the + bytecode under EthLib finish, with the same observable, so every behaviour of the bytecode + there is SolidCore's (`Refines.backward`). Each is `bytecode_total_of_stages` applied to the + source stage, solar-tv's backend stages and the assembly stage, with the specification + "SolidCore ends" (`satisfies_of_defined`); no oracle hypothesis is left, since the stages hold + under `Assemble.ethOracle o` for any `o`. +* `.scope_inhabited`: each scope has a call, so none of these statements is vacuous. +* `Generic.not_defined_of_none`, `not_refines_of_none`: a scope with a call on which SolidCore + returns nothing refutes `Defined` and `Refines` (running out of fuel is a failure of the + theorem, never a vacuous success). +* `.not_source_ends_two`, `.not_certified_total_two`: the negatives. With fuel 2 SolidCore + returns nothing on the scope's `probeCall` (`run2_eq`, the kernel's evaluation; with fuel 3 it + finishes), so `source_ends` and `certified_total` fail at fuel 2, by mismatch. + +No sorry, native_decide or bv_decide: the theorems depend on propext, Classical.choice and +Quot.sound only (pinned below). +-/ + +namespace SolidCore.Refinement.Generic +open SolarTV SolarTV.Machine SolarTV.MIR.Lowered SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement SolidCore.Refinement.Abi + +/-- SolidCore finishes every call of the generic stage's scope at every value: at value 0 by +`definedAt`, and at any other value because the check on values (`checkValue`) says the +function is not payable, so SolidCore rejects the call (`source_run_value`). -/ +theorem definedAtValue {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d s) {m : Module} + {fns : List Fn} {env : EnvFlags} (hchk : check fuel mirFuel c.core m fns env = true) + (hval : checkValue mirFuel c.core m fns env = true) : + Defined (solidCore fuel) c (fun call => ∃ σ v, Covers s σ ∧ fullScopeValue fns σ v call) := by + rintro _ ⟨σ, v, hcov, hv, f, hf, args, hlen, hargs, rfl⟩ + by_cases hv0 : v = 0 + · subst hv0 + exact definedAt hd hchk _ ⟨σ, hcov, f, hf, args, hlen, hargs, rfl⟩ + have hcf := List.all_eq_true.mp hchk f hf + have hcv := List.all_eq_true.mp hval f hf + unfold checkFn at hcf + unfold checkValueFn at hcv + cases hfind : c.core.findFunctionBySelector? f.sel with + | none => simp [hfind] at hcf + | some fn => + cases ht1 : eraseFn (envOf c.core) fuel fn with + | none => simp [hfind, ht1] at hcf + | some t1 => + cases ht2 : symTreeValue m f.sel f.params.length mirFuel env with + | none => simp [hfind, ht2] at hcv + | some T => + simp only [hfind, ht1, Bool.and_eq_true, decide_eq_true_eq] at hcf + obtain ⟨hsel, hpl, -⟩ := hcf + simp only [hfind, ht2, Bool.and_eq_true, Bool.not_eq_true'] at hcv + obtain ⟨hpay, -⟩ := hcv + obtain ⟨ws, hw⟩ := eraseFn_widths ht1 + have hsrc := source_run_value hd hsel hfind hw hpay args (by rw [hlen, hpl]) hargs hv0 hv σ + change (Source.run fuel c _).isSome = true + rw [hsrc] + rfl + +/-- At every value, from any storage, for a constructor that leaves no storage. -/ +theorem definedValue {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + (hd : SolidCore.Refinement.Wide.DeployedAt fuel c d []) {m : Module} {fns : List Fn} + {env : EnvFlags} (hchk : check fuel mirFuel c.core m fns env = true) + (hval : checkValue mirFuel c.core m fns env = true) : + Defined (solidCore fuel) c (fun call => ∃ σ v, fullScopeValue fns σ v call) := + fun call ⟨σ, v, h⟩ => + definedAtValue hd hchk hval call ⟨σ, v, fun _ hkv => absurd hkv List.not_mem_nil, h⟩ + +/-- A program that finishes every call of the scope satisfies the specification "it ends". -/ +theorem satisfies_of_defined {S : Sem} {p : S.Prog} {scope : Call → Prop} + (h : Defined S p scope) : Satisfies S p scope (fun _ => True) (fun _ _ => True) := + fun call hc _ => + let ⟨obs, hobs⟩ := Option.isSome_iff_exists.mp (h call hc) + ⟨obs, hobs, trivial⟩ + +/-- `bytecode_total_of_stages` with the specification "SolidCore ends": three stages from a +source that finishes every call of the scope are a total refinement on it. -/ +theorem refines_of_defined_stages {fuel : Nat} {mirSem evmirSem : Sem} + {c : TypeCheck.CheckedContract} {mir : mirSem.Prog} {evmir : evmirSem.Prog} {code : ByteArray} + {scope : Call → Prop} (ends : Defined (solidCore fuel) c scope) + (lowering : Stage (solidCore fuel) mirSem c mir scope) + (backend : Stage mirSem evmirSem mir evmir scope) + (assembly : Stage evmirSem ethLib evmir code scope) : + Refines fuel c code scope := + fun call hc => + (bytecode_total_of_stages (satisfies_of_defined ends) lowering backend assembly).1 call + ⟨hc, trivial⟩ + +/-- **Negative**: a call of the scope on which SolidCore returns nothing (it runs out of fuel or +fails) refutes `Defined`. -/ +theorem not_defined_of_none {fuel : Nat} {c : TypeCheck.CheckedContract} {scope : Call → Prop} + {call : Call} (hc : scope call) (hnone : Source.run fuel c call = none) : + ¬ Defined (solidCore fuel) c scope := fun h => by + have := h call hc + change (Source.run fuel c call).isSome = true at this + rw [hnone] at this + exact Bool.false_ne_true this + +/-- **Negative**: and so refutes `Refines`, whatever the bytecode: running out of fuel is a failure +of the total refinement, never a vacuous success. -/ +theorem not_refines_of_none {fuel : Nat} {c : TypeCheck.CheckedContract} {code : ByteArray} + {scope : Call → Prop} {call : Call} (hc : scope call) + (hnone : Source.run fuel c call = none) : ¬ Refines fuel c code scope := fun h => + not_defined_of_none hc hnone ((refines_iff_total.mp h).source_defined) + +end SolidCore.Refinement.Generic + +namespace SolidCore.Refinement.Solar + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity + +namespace Bank + +/-- The fuel the statements are at. -/ +theorem fuel_eq : fuel = 4096 := rfl + +/-- **SolidCore's `Bank` ends**: every call of `deposit`, `depositFor` and `balanceOf` on any +argument words, no value, from any storage, finishes within fuel 4096. -/ +theorem source_ends {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Defined (solidCore fuel) c (fun call => ∃ σ, fullScope fns σ call) := + defined hc + +/-- **SolidCore's `Bank` ends at every value**: with a value it reverts, so it finishes too. -/ +theorem source_ends_value {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Defined (solidCore fuel) c (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact Generic.definedValue hd (by rw [hk]; exact check_stage0) + (by rw [hk]; exact checkValue_stage0) + +/-- **Bank, SolidCore to solar's bytecode, total**: on every call of `deposit`, `depositFor` and +`balanceOf` on any argument words, no value, from any storage, SolidCore and the bytecode under +EthLib both finish, with the same observable. -/ +theorem certified_total {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Refines fuel c code (fun call => ∃ σ, fullScope fns σ call) := + let o := Assemble.ethOracle ethOracle + let ho := Assemble.ethOracle_ok ethOracle + Generic.refines_of_defined_stages (source_ends hc) + (lowering o (sourceEnvOk_of o ho ethKeccakAgree) hc) + (fun call _ => SolarTV.Milestone.Bank.bank_mir_to_evmir o call trivial) (stageOk o ho _) + +/-- **Bank, total at every value**. -/ +theorem certified_total_value {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Refines fuel c code (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := + let o := Assemble.ethOracle ethOracle + let ho := Assemble.ethOracle_ok ethOracle + Generic.refines_of_defined_stages (source_ends_value hc) + (loweringValue o (sourceEnvOk_of o ho ethKeccakAgree) hc) + (fun call _ => SolarTV.Milestone.Bank.bank_mir_to_evmir o call trivial) (stageOk o ho _) + +/-- The scope has a call (`balanceOf(0)` from empty storage): `certified_total` is not vacuous. -/ +theorem scope_inhabited : ∃ call, ∃ σ, fullScope fns σ call := + ⟨_, [], fnBalanceOf, by simp [fns], [0], rfl, by simp, rfl⟩ + +end Bank + +namespace Events + +theorem fuel_eq : fuel = 4096 := rfl + +/-- **SolidCore's `Events` ends**: every call of `transfer` on any argument words, no value, from +any storage, finishes within fuel 4096. -/ +theorem source_ends {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Defined (solidCore fuel) c (fun call => ∃ σ, fullScope fns σ call) := + defined hc + +/-- **SolidCore's `Events` ends at every value**. -/ +theorem source_ends_value {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Defined (solidCore fuel) c (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact Generic.definedValue hd (by rw [hk]; exact check_stage0) + (by rw [hk]; exact checkValue_stage0) + +/-- **Events, SolidCore to solar's bytecode, total**: on every call of `transfer` on any argument +words, no value, from any storage, SolidCore and the bytecode under EthLib both finish, with the +same observable. -/ +theorem certified_total {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Refines fuel c code (fun call => ∃ σ, fullScope fns σ call) := + let o := Assemble.ethOracle ethOracle + let ho := Assemble.ethOracle_ok ethOracle + Generic.refines_of_defined_stages (source_ends hc) (lowering o (callerOk_of o ho) hc) + (fun call _ => SolarTV.Milestone.Events.events_mir_to_evmir o call trivial) (stageOk o ho _) + +/-- **Events, total at every value**. -/ +theorem certified_total_value {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Refines fuel c code (fun call => ∃ σ v, Generic.fullScopeValue fns σ v call) := + let o := Assemble.ethOracle ethOracle + let ho := Assemble.ethOracle_ok ethOracle + Generic.refines_of_defined_stages (source_ends_value hc) (loweringValue o (callerOk_of o ho) hc) + (fun call _ => SolarTV.Milestone.Events.events_mir_to_evmir o call trivial) (stageOk o ho _) + +/-- The scope has a call (`transfer(0, 0)` from empty storage). -/ +theorem scope_inhabited : ∃ call, ∃ σ, fullScope fns σ call := + ⟨_, [], fnTransfer, by simp [fns], [0, 0], rfl, by simp, rfl⟩ + +end Events + +namespace MulX + +open SolarTV.Export.Main + +theorem fuel_eq : fuel = 4096 := rfl + +/-- **SolidCore's `Main` ends from the deployed storage**: every call of `m` and `n` on any +argument words, no value, from the storage the constructor leaves, finishes within fuel 4096. -/ +theorem source_ends {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Defined (solidCore fuel) c (fullScope fns deployed) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact fun call h => Generic.definedAt hd (by rw [hk]; exact check_stage0) call + ⟨deployed, fun kv hkv => ⟨kv, hkv, rfl⟩, h⟩ + +/-- **SolidCore's `Main` ends from any storage that writes slot 0**. -/ +theorem source_ends_at {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Defined (solidCore fuel) c scopeAt := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + rintro call ⟨σ, ⟨kv, hkv, h0⟩, hs⟩ + refine Generic.definedAt hd (by rw [hk]; exact check_stage0) call ⟨σ, ?_, hs⟩ + intro kv' hkv' + simp only [deployed, List.mem_singleton] at hkv' + subst hkv' + exact ⟨kv, hkv, h0⟩ + +/-- **SolidCore's `Main` ends from the deployed storage at every value**. -/ +theorem source_ends_value {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Defined (solidCore fuel) c (fun call => ∃ v, Generic.fullScopeValue fns deployed v call) := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + exact fun call ⟨v, h⟩ => Generic.definedAtValue hd (by rw [hk]; exact check_stage0) + (by rw [hk]; exact checkValue_stage0) call ⟨deployed, v, fun kv hkv => ⟨kv, hkv, rfl⟩, h⟩ + +/-- **SolidCore's `Main` ends from any storage that writes slot 0 at every value**. -/ +theorem source_ends_at_value {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Defined (solidCore fuel) c scopeAtValue := by + obtain ⟨hk, d, hd⟩ := deployed_of hc + rintro call ⟨σ, v, ⟨kv, hkv, h0⟩, hs⟩ + refine Generic.definedAtValue hd (by rw [hk]; exact check_stage0) + (by rw [hk]; exact checkValue_stage0) call ⟨σ, v, ?_, hs⟩ + intro kv' hkv' + simp only [deployed, List.mem_singleton] at hkv' + subst hkv' + exact ⟨kv, hkv, h0⟩ + +/-- The backend stages from stage0 to evm8, on any scope. -/ +theorem mirToEvmir (o : SolarTV.Machine.Oracle) (scope : SolarTV.Call → Prop) : + SolarTV.Stage (SolarTV.mirSem o) (SolarTV.evmirSem o) stage0 evm8 scope := + (SolarTV.Milestone.Mulx.mulx_mir_to_evmir o).mono fun _ _ => trivial + +/-- **mulx, SolidCore to solar's bytecode, total, from the deployed storage**: on every call of `m` +and `n` on any argument words, no value, from the storage the constructor leaves, SolidCore and +the bytecode under EthLib both finish, with the same observable. -/ +theorem certified_total {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Refines fuel c code (fullScope fns deployed) := + let o : SolarTV.Machine.Oracle := Solar.ethOracle + Generic.refines_of_defined_stages (source_ends hc) (lowering o hc) (mirToEvmir o _) + (stageAll o _) + +/-- **mulx, total, from any storage that writes slot 0**. -/ +theorem certified_total_at {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Refines fuel c code scopeAt := + let o : SolarTV.Machine.Oracle := Solar.ethOracle + Generic.refines_of_defined_stages (source_ends_at hc) (loweringAt o hc) (mirToEvmir o _) + (stageAll o _) + +/-- **mulx, total, from the deployed storage at every value**. -/ +theorem certified_total_value {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Refines fuel c code (fun call => ∃ v, Generic.fullScopeValue fns deployed v call) := + let o : SolarTV.Machine.Oracle := Solar.ethOracle + Generic.refines_of_defined_stages (source_ends_value hc) (loweringValue o hc) (mirToEvmir o _) + (stageAll o _) + +/-- **mulx, total, from any storage that writes slot 0 at every value**. -/ +theorem certified_total_at_value {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Refines fuel c code scopeAtValue := + let o : SolarTV.Machine.Oracle := Solar.ethOracle + Generic.refines_of_defined_stages (source_ends_at_value hc) (loweringAtValue o hc) + (mirToEvmir o _) (stageAll o _) + +/-- The scope has a call (`n(0, 0, 0)` from the deployed storage). -/ +theorem scope_inhabited : ∃ call, fullScope fns deployed call := + ⟨_, fnN, by simp [fns], [0, 0, 0], rfl, by simp, rfl⟩ + +end MulX + +/-! ### Bank: fuel matters -/ + +namespace Bank + +/-- `balanceOf(0)` from empty storage, the call `scope_inhabited` exhibits. -/ +def probeCall : Call := + { calldata := calldata fnBalanceOf.sel [0], callvalue := 0, storage := [] } + +/-- Whether SolidCore returns nothing on `probeCall` with fuel 2, when the contract checks. -/ +def run2? : Option Bool := + match contract? with + | .ok c => some (Source.run 2 c probeCall).isNone + | .error _ => none + +-- `run2_eq`: the kernel's evaluation (the selectors and digests read from their tables, as in +-- `shape_eq`): with fuel 2 SolidCore returns nothing on `probeCall` (with fuel 3 it finishes). +kernel_rfl run2_eq run2? (some true) using selector_eq digest_eq + +theorem run2_none {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Source.run 2 c probeCall = none := by + have h := run2_eq + unfold run2? at h + rw [hc] at h + exact Option.isNone_iff_eq_none.mp (Option.some.inj h) + +theorem probeCall_scope : ∃ σ, fullScope fns σ probeCall := + ⟨[], fnBalanceOf, by simp [fns], [0], rfl, by simp, rfl⟩ + +/-- **Negative**: with fuel 2 SolidCore does not end on the scope, so `source_ends` is a claim +about fuel 4096, not one every fuel satisfies. -/ +theorem not_source_ends_two {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + ¬ Defined (solidCore 2) c (fun call => ∃ σ, fullScope fns σ call) := + Generic.not_defined_of_none probeCall_scope (run2_none hc) + +/-- **Negative**: and the total refinement at fuel 2 fails, by SolidCore returning nothing on +`probeCall` (a mismatch the kernel evaluates, not a timeout). -/ +theorem not_certified_total_two {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + ¬ Refines 2 c code (fun call => ∃ σ, fullScope fns σ call) := + Generic.not_refines_of_none probeCall_scope (run2_none hc) + +end Bank + +/-! ### Events: fuel matters -/ + +namespace Events + +/-- `transfer(0, 0)` from empty storage, the call `scope_inhabited` exhibits. -/ +def probeCall : Call := + { calldata := calldata fnTransfer.sel [0, 0], callvalue := 0, storage := [] } + +/-- Whether SolidCore returns nothing on `probeCall` with fuel 2, when the contract checks. -/ +def run2? : Option Bool := + match contract? with + | .ok c => some (Source.run 2 c probeCall).isNone + | .error _ => none + +-- `run2_eq`: the kernel's evaluation (the selectors and digests read from their tables, as in +-- `shape_eq`): with fuel 2 SolidCore returns nothing on `probeCall` (with fuel 3 it finishes). +kernel_rfl run2_eq run2? (some true) using selector_eq digest_eq + +theorem run2_none {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Source.run 2 c probeCall = none := by + have h := run2_eq + unfold run2? at h + rw [hc] at h + exact Option.isNone_iff_eq_none.mp (Option.some.inj h) + +theorem probeCall_scope : ∃ σ, fullScope fns σ probeCall := + ⟨[], fnTransfer, by simp [fns], [0, 0], rfl, by simp, rfl⟩ + +/-- **Negative**: with fuel 2 SolidCore does not end on the scope, so `source_ends` is a claim +about fuel 4096, not one every fuel satisfies. -/ +theorem not_source_ends_two {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + ¬ Defined (solidCore 2) c (fun call => ∃ σ, fullScope fns σ call) := + Generic.not_defined_of_none probeCall_scope (run2_none hc) + +/-- **Negative**: and the total refinement at fuel 2 fails, by SolidCore returning nothing on +`probeCall` (a mismatch the kernel evaluates, not a timeout). -/ +theorem not_certified_total_two {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + ¬ Refines 2 c code (fun call => ∃ σ, fullScope fns σ call) := + Generic.not_refines_of_none probeCall_scope (run2_none hc) + +end Events + +/-! ### MulX: fuel matters -/ + +namespace MulX + +open SolarTV.Export.Main + +/-- `n(0, 0, 0)` from the deployed storage, the call `scope_inhabited` exhibits. -/ +def probeCall : Call := + { calldata := calldata fnN.sel [0, 0, 0], callvalue := 0, storage := deployed } + +/-- Whether SolidCore returns nothing on `probeCall` with fuel 2, when the contract checks. -/ +def run2? : Option Bool := + match contract? with + | .ok c => some (Source.run 2 c probeCall).isNone + | .error _ => none + +-- `run2_eq`: the kernel's evaluation (the selectors and digests read from their tables, as in +-- `shape_eq`): with fuel 2 SolidCore returns nothing on `probeCall` (with fuel 3 it finishes). +kernel_rfl run2_eq run2? (some true) using selector_eq + +theorem run2_none {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + Source.run 2 c probeCall = none := by + have h := run2_eq + unfold run2? at h + rw [hc] at h + exact Option.isNone_iff_eq_none.mp (Option.some.inj h) + +theorem probeCall_scope : fullScope fns deployed probeCall := + ⟨fnN, by simp [fns], [0, 0, 0], rfl, by simp, rfl⟩ + +/-- **Negative**: with fuel 2 SolidCore does not end on the scope, so `source_ends` is a claim +about fuel 4096, not one every fuel satisfies. -/ +theorem not_source_ends_two {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + ¬ Defined (solidCore 2) c (fullScope fns deployed) := + Generic.not_defined_of_none probeCall_scope (run2_none hc) + +/-- **Negative**: and the total refinement at fuel 2 fails, by SolidCore returning nothing on +`probeCall` (a mismatch the kernel evaluates, not a timeout). -/ +theorem not_certified_total_two {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + ¬ Refines 2 c code (fullScope fns deployed) := + Generic.not_refines_of_none probeCall_scope (run2_none hc) + +end MulX + +/-- info: 'SolidCore.Refinement.Generic.definedAtValue' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Generic.definedAtValue + +/-- info: 'SolidCore.Refinement.Generic.not_refines_of_none' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Generic.not_refines_of_none + +/-- info: 'SolidCore.Refinement.Solar.Bank.source_ends' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Bank.source_ends + +/-- info: 'SolidCore.Refinement.Solar.Bank.certified_total' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Bank.certified_total + +/-- info: 'SolidCore.Refinement.Solar.Bank.certified_total_value' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Bank.certified_total_value + +/-- info: 'SolidCore.Refinement.Solar.Events.source_ends' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Events.source_ends + +/-- info: 'SolidCore.Refinement.Solar.Events.certified_total' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Events.certified_total + +/-- info: 'SolidCore.Refinement.Solar.Events.certified_total_value' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Events.certified_total_value + +/-- info: 'SolidCore.Refinement.Solar.MulX.source_ends' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms MulX.source_ends + +/-- info: 'SolidCore.Refinement.Solar.MulX.certified_total' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms MulX.certified_total + +/-- info: 'SolidCore.Refinement.Solar.MulX.certified_total_at' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms MulX.certified_total_at + +/-- info: 'SolidCore.Refinement.Solar.MulX.certified_total_value' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms MulX.certified_total_value + +/-- info: 'SolidCore.Refinement.Solar.MulX.certified_total_at_value' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms MulX.certified_total_at_value + +/-- info: 'SolidCore.Refinement.Solar.Bank.not_source_ends_two' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Bank.not_source_ends_two + +/-- info: 'SolidCore.Refinement.Solar.Bank.not_certified_total_two' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Bank.not_certified_total_two + +/-- info: 'SolidCore.Refinement.Solar.Events.not_source_ends_two' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Events.not_source_ends_two + +/-- info: 'SolidCore.Refinement.Solar.Events.not_certified_total_two' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms Events.not_certified_total_two + +/-- info: 'SolidCore.Refinement.Solar.MulX.not_source_ends_two' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms MulX.not_source_ends_two + +/-- info: 'SolidCore.Refinement.Solar.MulX.not_certified_total_two' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms MulX.not_certified_total_two + +end SolidCore.Refinement.Solar diff --git a/SolidCore/Refinement/Solar/W1.lean b/SolidCore/Refinement/Solar/W1.lean new file mode 100644 index 00000000..1e3a3357 --- /dev/null +++ b/SolidCore/Refinement/Solar/W1.lean @@ -0,0 +1,741 @@ +import SolidCore.Refinement.Evm.WideStorage +import SolidCore.Refinement.Dirty.Source +import SolidCore.Refinement.Compose +import SolarTV.Composition +import SolarTV.Stages.AssemblyCheck +import gen.Main.Evm4 +import gen.Main.Bytecode +import SolidCore.Refinement.Solar.AssembleSim + +/-! +# w1: solar's EVM IR to bytecode on EthLib + +The milestone contract w1, + + contract Main { function f(uint256 a, uint256 b) external pure returns (uint256) { + return a + b; } } + +compiled by solar at commit c7ac11c0 with -Ogas for osaka. program is the final EVM IR program +the assembler lays out (solar -Zemit-lean-stages, the output of the last EVM IR pass, the same +program -Zdump=evm-ir-runtime prints) in SolarTV's EVM IR semantics, and code is the runtime +bytecode solar emits for it, as a literal: bytes_exported checks it against the bytecode solar +exported with the program, and scripts/refinement/check-solar-w1.sh checks its sha256 +(runtimeSha256) against solar's --emit=bin-runtime. + +* checked and decodes: the bytecode decodes, linearly from offset 0, to exactly the program's + instructions at the layout -Zvalidate-assembly finds (bb3 at 0x2e, bb7 at 0x32), by the + kernel's evaluation of SolarTV.Assembly.walk. +* evmir_run: SolarTV's EVM IR semantics runs program on every call f(a, b) of the scope, under + every oracle, to expected a b, in three blocks of proof fuel. +* target_run: EthLib runs code on the same call to expected a b: one processMessage at Fusaka + (osaka) from 0x2000 to 0x1000 with 10M gas in one frame (Statement.lean's Target.run), stepped + opcode by opcode with EthLib's program logic, each step's gas side condition discharged with + the gas left; the overflow path reaches its REVERT with 9,999,861 gas left. So 10M gas + suffices on every path of the scope, and runtime gas never makes the bytecode fail there. +* stage: EVM IR to bytecode is a stage on the scope under every oracle, from the generic + theorem Assemble.stage_of_check (AssembleSim.lean) and check_ok, the kernel's evaluation of + the checker on program, code and cert; stage_ethLib and assembly (SolarTV.AssemblyStage) with + oracle, the environment of EthLib's call. stage_run proves the same stage directly, by + running both sides to the same observable (evmir_run and target_run), as a cross-check. +* mutant_check: the checker rejects the mutant below. +* mutant_not_stage: replacing ADD (0x01, offset 33) by SUB (0x03) makes the stage false, with + the counterexample f(2, 1), where the program returns 3 and the mutant reverts with + Panic(0x11); mutant_no_walk: the checker's walk rejects the mutant, because offset 33 decodes + as SUB where the program has ADD (mutant_decodes_sub). + +The scope is every call of f with any two argument words below 2^256, no value and empty +storage (fullScope), as solidity-lean's specifications state. +stageAt is the stage on scopeAt, the same calls from any storage σ, from the same generic +theorem and check_ok. stageAt_run proves it directly, as a cross-check: evmir_run_at and +target_run_at run both sides to expectedAt σ a b, expected a b with σ kept. EthLib's frames +(frame_ok, frame_overflow) hold from every state, so only the reads of the final storage change +(run_of_post_at). + +stage no longer depends on this contract's runs: the checker relates the final EVM IR program +to the bytes directly (its lowering to assembly is inside the checker and the generic theorem), +so what is trusted for w1 is the exporter's EVM IR program and the kernel's evaluation of +check_ok. stage_run, the direct proof, remains as a cross-check. Proof fuel (the EVM IR semantics' blocks) and runtime +gas (EthLib's metered 10M) are separate: the first is existential in SolarTV's fuel-free +semantics, the second is checked on every step. + +No sorry, native_decide or bv_decide: the theorems below depend on propext, Quot.sound and +Classical.choice only. +-/ + +namespace SolidCore.Refinement.Solar.W1 + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm +open SolidCore.Refinement.Evm.Wide + +/-! ## The artifacts -/ + +/-- The runtime bytecode solar emits for w1, as hex. -/ +def runtimeHex : String := + "34602e575f3560e01c806313d1aa2e03602e5760443610602e5760043560243581019081106032575f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd" + +/-- The sha256 of the runtime bytecode, which the check script compares with solar's output. -/ +def runtimeSha256 : String := "24d2438e4d77b39b2530aac7af63774b10576eabc3c093d282620ab44403778b" + +/-- The runtime bytecode, read big-endian. -/ +def runtimeNat : Nat := + 0x34602e575f3560e01c806313d1aa2e03602e5760443610602e5760043560243581019081106032575f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd + +def runtimeSize : Nat := 68 + +/-- The runtime bytecode. -/ +def code : ByteArray := EthLib.Execution.Evm.Logic.NatCode.ofNat runtimeNat runtimeSize + +/-- Its bytes. -/ +def bytes : List Nat := code.data.toList.map (·.toNat) + +/-- The selector of `f(uint256,uint256)`. -/ +def fSelector : Nat := 0x13d1aa2e + +/-- The final EVM IR program of w1's runtime in SolarTV's EVM IR, as solar exports it +(-Zemit-lean-stages, solar-tv/milestone/w1/gen/Main/Evm4.lean: the output of the last EVM IR +pass, cfg-simplify-early), with EVM IR's block ids: block 0 is bb0, 1 is bb3 and 2 is bb7. -/ +def program : SolarTV.EVM.Program.Program := SolarTV.Export.Main.evm4 + +/-- The literal is the bytecode solar exported with the program. -/ +theorem bytes_exported : bytes = SolarTV.Export.Main.bytecode := by decide + +/-! ## The bytecode is the program's linear decoding -/ + +open SolarTV.Assembly + +/-- The assembly items of the program in layout order: each instruction as its opcode, a +jump as a push of its label and the jump, and a label (a `JUMPDEST`) at each jumped-to block. -/ +def items : List Item := + [.op 0x34, .pushLabel 1, .op 0x57, + .push 0, .op 0x35, .push 224, .op 0x1c, .op 0x80, .push 0x13d1aa2e, .op 0x03, + .pushLabel 1, .op 0x57, + .push 68, .op 0x36, .op 0x10, .pushLabel 1, .op 0x57, + .push 4, .op 0x35, .push 36, .op 0x35, .op 0x81, .op 0x01, .op 0x90, .op 0x81, .op 0x10, + .pushLabel 2, .op 0x57, + .push 0, .op 0x52, .push 32, .push 0, .op 0xf3, + .label 1, .push 0, .push 0, .op 0xfd, + .label 2, .push 17, .push 32, .op 0x52, .push 0x4e487b71, .push 0, .op 0x52, .push 36, + .push 28, .op 0xfd] + +/-- The layout -Zvalidate-assembly finds: bb3 at 0x2e, bb7 at 0x32. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x2e else if label = 2 then 0x32 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytes offset 0 items).getD [] + +theorem walk_eq : walk bytes offset 0 items = some stream := by decide + +/-- The checker's walk over w1's bytecode exists: its linear decoding is the program's +instructions at the layout, and each label is a `JUMPDEST` that decoding reaches. -/ +theorem checked : Walk bytes offset 0 items stream := walk_sound walk_eq + +theorem decodes : decodeFrom bytes (bytes.length + 1) 0 = stream := by + have := walk_length checked + exact walk_decodes checked _ (by omega) + +/-! ## The calls of the scope -/ + +/-- `f` and its parameters. -/ +def fns : List Fn := [⟨fSelector, [.uint 256, .uint 256]⟩] + +/-- Every call of `f` on any two argument words, with no value and empty storage. -/ +def scope : Call → Prop := fullScope fns [] + +/-- What the call of `f(a, b)` shows: the word `a + b` when it fits in 256 bits, and otherwise +a revert with `Panic(0x11)`; no logs, and storage stays empty. -/ +def expected (a b : U256) : Observable := + if a.toNat + b.toNat < 2 ^ 256 then + { success := true, output := (natToBytes 32 (a.toNat + b.toNat)).map (·.toNat), logs := [], + storage := fun _ => 0 } + else + { success := false, + output := (natToBytes 4 0x4e487b71).map (·.toNat) ++ (natToBytes 32 0x11).map (·.toNat), + logs := [], storage := fun _ => 0 } + +theorem scope_callOf {call : Call} (h : scope call) : + ∃ a b : U256, call = callOf fSelector [a, b] := by + obtain ⟨fn, hfn, args, hlen, hlt, rfl⟩ := h + simp only [fns, List.mem_singleton] at hfn + subst hfn + match args, hlen with + | [a, b], _ => + refine ⟨BitVec.ofNat 256 a, BitVec.ofNat 256 b, ?_⟩ + have ha := hlt a (by simp) + have hb := hlt b (by simp) + have ha' : a % 2 ^ 256 = a := Nat.mod_eq_of_lt ha + have hb' : b % 2 ^ 256 = b := Nat.mod_eq_of_lt hb + simp only [callOf, List.map_cons, List.map_nil, BitVec.toNat_ofNat, ha', hb'] + +/-- Every call of `f` on any two argument words, with no value, from any storage. -/ +def scopeAt : Call → Prop := fun call => ∃ σ, fullScope fns σ call + +/-- What the call of `f(a, b)` from the storage `σ` shows: `expected a b`, with `σ` kept. -/ +def expectedAt (σ : List (Nat × Nat)) (a b : U256) : Observable := + { expected a b with storage := slotValue σ } + +theorem expectedAt_nil (a b : U256) : expectedAt [] a b = expected a b := by + unfold expectedAt expected + split <;> rfl + +theorem scopeAt_callOf {call : Call} (h : scopeAt call) : + ∃ a b : U256, ∃ σ, call = { callOf fSelector [a, b] with storage := σ } := by + obtain ⟨σ, fn, hfn, args, hlen, hlt, rfl⟩ := h + simp only [fns, List.mem_singleton] at hfn + subst hfn + match args, hlen with + | [a, b], _ => + refine ⟨BitVec.ofNat 256 a, BitVec.ofNat 256 b, σ, ?_⟩ + have ha' : a % 2 ^ 256 = a := Nat.mod_eq_of_lt (hlt a (by simp)) + have hb' : b % 2 ^ 256 = b := Nat.mod_eq_of_lt (hlt b (by simp)) + simp only [callOf, List.map_cons, List.map_nil, BitVec.toNat_ofNat, ha', hb'] + +/-! ## SolarTV's EVM IR runs the program to `expected` -/ + +section Evmir + +open SolarTV SolarTV.Machine + +theorem shl_or_ofNat (acc b : Nat) (hb : b < 256) : + (BitVec.ofNat 256 acc <<< 8) ||| BitVec.ofNat 256 b = BitVec.ofNat 256 (acc * 256 + b) := by + have hand : (BitVec.ofNat 256 acc <<< 8) &&& BitVec.ofNat 256 b = 0 := by + ext i hi + rw [BitVec.getElem_and, BitVec.getElem_shiftLeft, ← BitVec.getLsbD_eq_getElem, ← BitVec.getLsbD_eq_getElem, BitVec.getLsbD_ofNat] + by_cases h8 : i < 8 + · simp [h8] + · have : b.testBit i = false := + Nat.testBit_lt_two_pow (Nat.lt_of_lt_of_le hb + (by simpa using Nat.pow_le_pow_right (by decide : 0 < 2) (Nat.le_of_not_lt h8))) + simp [BitVec.getLsbD_ofNat, this] + rw [← BitVec.add_eq_or_of_and_eq_zero _ _ hand] + apply BitVec.eq_of_toNat_eq + simp only [BitVec.toNat_add, BitVec.toNat_shiftLeft, BitVec.toNat_ofNat, Nat.shiftLeft_eq] + omega + +theorem foldl_word (data : ByteArray) (off : Nat) : ∀ (l : List Nat) (acc : Nat), + l.foldl (fun (acc : BitVec 256) i => + (acc <<< 8) ||| BitVec.ofNat 256 (data.data.getD (off + i) 0).toNat) + (BitVec.ofNat 256 acc) = + BitVec.ofNat 256 (l.foldl (fun acc i => acc * 256 + (byteAt data (off + i)).toNat) acc) + | [], _ => rfl + | i :: l, acc => by + simp only [List.foldl_cons] + have hget : (data.data.getD (off + i) 0) = byteAt data (off + i) := rfl + rw [hget, shl_or_ofNat _ _ (byteAt data (off + i)).toNat_lt, foldl_word data off l] + +/-- CALLDATALOAD in SolarTV is EthLib's: the big-endian word of 32 bytes of call data from the +offset, zero past its end. -/ +theorem calldataWord_eq (call : Call) (off : BitVec 256) : + calldataWord call off = loadWord call.calldata off.toNat 32 := by + unfold calldataWord loadWord bufferRead bytesToNat + rw [show (0 : BitVec 256) = BitVec.ofNat 256 0 from rfl, foldl_word, List.foldl_map] + +end Evmir + +section EvmirRun + +open SolarTV SolarTV.Machine SolarTV.EVM.Program + +theorem sem_of_run {o : Oracle} {p : SolarTV.EVM.Program.Program} {call : Call} {obs : Observable} + (n : Nat) (h : (SolarTV.EVM.Program.run o p call n).map (fun r => observe call r.2 r.1) = some obs) : + (SolarTV.evmirSem o).run p call = some obs := by + obtain ⟨r, hr, rfl⟩ := Option.map_eq_some_iff.1 h + have e : SolarTV.EVM.Program.layer.result o p call = some r := + SolarTV.EVM.Program.layer.result_of_ends ⟨n, hr⟩ + show (SolarTV.EVM.Program.layer.result o p call).map _ = _ + rw [e] + rfl + +/-- The call data facts the program reads. -/ +theorem calldata_callOf (a b : U256) : + (callOf fSelector [a, b]).calldata = cdOf (selectorOf fSelector) [a, b] := by + have := calldata_eq_cdOf fSelector [a.toNat, b.toNat] (by + intro x hx + simp only [List.mem_cons, List.mem_nil_iff, or_false] at hx + rcases hx with rfl | rfl <;> exact BitVec.isLt _) + simpa [callOf, List.map_map, Function.comp_def] using this + +theorem word0 (a b : U256) : + EvmRules.Evm.shr 224 (calldataWord (callOf fSelector [a, b]) 0) = BitVec.ofNat 256 fSelector := by + rw [calldataWord_eq, calldata_callOf] + have := shr_cdOf_selectorOf fSelector [a, b] (by decide) + simpa [EvmRules.Evm.shr, bitwiseShr] using this + +theorem word4 (a b : U256) : calldataWord (callOf fSelector [a, b]) 4 = a := by + rw [calldataWord_eq, calldata_callOf] + exact loadWord_cdOf_getD _ [a, b] 4 (by simp [size_selectorOf]) (by simp [size_selectorOf]) + (by simp [size_selectorOf]) + +theorem word36 (a b : U256) : calldataWord (callOf fSelector [a, b]) 36 = b := by + rw [calldataWord_eq, calldata_callOf] + exact loadWord_cdOf_getD _ [a, b] 36 (by simp [size_selectorOf]) (by simp [size_selectorOf]) + (by simp [size_selectorOf]) + +theorem size_callOf (a b : U256) : (callOf fSelector [a, b]).calldata.size = 68 := by + rw [calldata_callOf, size_cdOf, size_selectorOf]; rfl + +namespace Exec +variable {o : Oracle} {call : Call} {b : Nat} {rest : List SolarTV.EVM.Program.Instr} {s : State} + +abbrev W := EvmRules.Word + +theorem exec_push {v : W} {st : List W} (h : st.length < 1024) : + exec o call b (.op (.stack (.push v)) :: rest) st s = exec o call b rest (v :: st) s := by + have h1 : ¬ 1024 < st.length := by omega + have h2 : ¬ 1024 < st.length + 1 := by omega + simp [exec, stepOp, SolarTV.EVM.stepChecked, SolarTV.EVM.step, Except.map, h1, h2] + +theorem exec_bin {op : SolarTV.EVM.Op} {f : W → W → W} {x y : W} {st : List W} + (hf : ∀ ctx x y st, SolarTV.EVM.step ctx op (x :: y :: st) = some (f x y :: st)) + (h : st.length < 1023) : + exec o call b (.op (.stack op) :: rest) (x :: y :: st) s = exec o call b rest (f x y :: st) s := by + have h1 : ¬ 1024 < st.length + 1 + 1 := by omega + have h2 : ¬ 1024 < st.length + 1 := by omega + simp [exec, stepOp, SolarTV.EVM.stepChecked, hf, Except.map, h1, h2] + +theorem exec_calldatasize {st : List W} (h : st.length < 1024) : + exec o call b (.op (.stack .calldatasize) :: rest) st s = + exec o call b rest (BitVec.ofNat 256 call.calldata.size :: st) s := by + have h1 : ¬ 1024 < st.length := by omega + have h2 : ¬ 1024 < st.length + 1 := by omega + simp [exec, stepOp, SolarTV.EVM.stepChecked, SolarTV.EVM.step, Except.map, h1, h2, context] + +theorem exec_dup0 {x : W} {st : List W} (h : st.length < 1023) : + exec o call b (.op (.stack (.dup 0)) :: rest) (x :: st) s = exec o call b rest (x :: x :: st) s := by + have h1 : ¬ 1024 < st.length + 1 := by omega + have h2 : ¬ 1024 < st.length + 1 + 1 := by omega + simp [exec, stepOp, SolarTV.EVM.stepChecked, SolarTV.EVM.step, Except.map, h1, h2] + +theorem exec_dup1 {x y : W} {st : List W} (h : st.length < 1022) : + exec o call b (.op (.stack (.dup 1)) :: rest) (x :: y :: st) s = + exec o call b rest (y :: x :: y :: st) s := by + have h1 : ¬ 1024 < st.length + 1 + 1 := by omega + have h2 : ¬ 1024 < st.length + 1 + 1 + 1 := by omega + simp [exec, stepOp, SolarTV.EVM.stepChecked, SolarTV.EVM.step, Except.map, h1, h2] + +theorem exec_swap0 {x y : W} {st : List W} (h : st.length < 1023) : + exec o call b (.op (.stack (.swap 0)) :: rest) (x :: y :: st) s = + exec o call b rest (y :: x :: st) s := by + have h1 : ¬ 1024 < st.length + 1 + 1 := by omega + simp [exec, stepOp, SolarTV.EVM.stepChecked, SolarTV.EVM.step, Except.map, h1] + +theorem exec_store {x y : W} {st : List W} (h : st.length < 1023) : + exec o call b (.op .store :: rest) (x :: y :: st) s = + exec o call b rest st { s with memory := s.memory.store x.toNat y } := by + have h1 : ¬ 1024 < st.length + 1 + 1 := by omega + simp [exec, stepOp, h1] + +theorem exec_callvalue {st : List W} (h : st.length < 1024) : + exec o call b (.effect .callvalue 0 :: rest) st s = + exec o call b rest (BitVec.ofNat 256 call.callvalue :: st) s := by + have h1 : ¬ 1024 < st.length + 1 := by omega + simp [exec, Effect.apply, h1] + +theorem exec_calldataload {x : W} {st : List W} (h : st.length < 1024) : + exec o call b (.effect .calldataload 1 :: rest) (x :: st) s = + exec o call b rest (calldataWord call x :: st) s := by + have h1 : ¬ 1024 < st.length + 1 := by omega + simp [exec, Effect.apply, h1] + +theorem exec_jumpi {t : Nat} {c : W} {st : List W} (h : st.length < 1023) : + exec o call b (.jumpi t :: rest) (c :: st) s = + if c = 0 then exec o call b rest st s else .inr (t, st, s) := by + have h1 : ¬ 1024 < st.length + 1 + 1 := by omega + simp [exec, h1] + +theorem exec_ret {st : List W} : exec o call b (.ret :: rest) st s = .inl (output s st false) := by + simp [exec] + +theorem exec_revert {st : List W} : exec o call b (.revert :: rest) st s = .inl (output s st true) := by + simp [exec] + + +theorem step_shr (ctx : EVM.Context) (x y : W) (st : List W) : + SolarTV.EVM.step ctx .shr (x :: y :: st) = some (EvmRules.Evm.shr x y :: st) := rfl +theorem step_sub (ctx : EVM.Context) (x y : W) (st : List W) : + SolarTV.EVM.step ctx .sub (x :: y :: st) = some (EvmRules.Evm.sub x y :: st) := rfl +theorem step_lt (ctx : EVM.Context) (x y : W) (st : List W) : + SolarTV.EVM.step ctx .lt (x :: y :: st) = some (EvmRules.Evm.lt x y :: st) := rfl +theorem step_add (ctx : EVM.Context) (x y : W) (st : List W) : + SolarTV.EVM.step ctx .add (x :: y :: st) = some (EvmRules.Evm.add x y :: st) := rfl + +end Exec + +open Exec + +theorem lt_add_self (a b : W) : + EvmRules.Evm.lt (EvmRules.Evm.add a b) a = if a.toNat + b.toNat < 2 ^ 256 then 0 else 1 := by + unfold EvmRules.Evm.lt EvmRules.Evm.add + by_cases h : a.toNat + b.toNat < 2 ^ 256 + · have : ¬ (a + b).ult a := by + simp only [BitVec.ult, BitVec.toNat_add, decide_eq_true_eq, Nat.mod_eq_of_lt h]; omega + simp only [h, this, ite_true, Bool.cond_false] + · have : (a + b).ult a := by + have ha := a.isLt; have hb := b.isLt + simp only [BitVec.ult, BitVec.toNat_add, decide_eq_true_eq] + rw [Nat.mod_eq_sub_mod (by omega), Nat.mod_eq_of_lt (by omega)]; omega + simp only [h, this, ite_false, Bool.cond_true] + +theorem bytes_toNat (len n : Nat) : + (List.range len).map (fun i => (n / 256 ^ (len - 1 - i)) % 256) = + (natToBytes len n).map (·.toNat) := by + induction len generalizing n with + | zero => rfl + | succ len ih => + rw [natToBytes_succ, List.map_append, ← ih, List.range_succ, List.map_append] + congr 1 + · apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [Nat.div_div_eq_div_mul, ← Nat.pow_succ'] + congr 3 + omega + · simp + +theorem byte_toNat (v : W) (i : Nat) (hi : i < 32) : + (SolarTV.Memory.byte v i).toNat = v.toNat / 256 ^ (31 - i) % 256 := by + unfold SolarTV.Memory.byte + rw [BitVec.toNat_setWidth, BitVec.toNat_ushiftRight, Nat.shiftRight_eq_div_pow, Nat.pow_mul] + +theorem read_store (m : Mem) (v : W) : + (((m.store 0 v).expand 0 32).read 0 32).map BitVec.toNat = (natToBytes 32 v.toNat).map (·.toNat) := by + rw [← bytes_toNat] + simp only [Mem.read, Mem.expand, Mem.store, List.map_map] + simp only [show (32 = 0) = False from by decide, ite_false] + apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + simp only [Function.comp_apply, Nat.zero_add, Nat.zero_le, true_and, hi, ite_true, Nat.sub_zero] + rw [byte_toNat v i hi] + +theorem evmir_run_of (o : Oracle) (call : Call) (a b : W) (hv : call.callvalue = 0) + (hsize : call.calldata.size = 68) (h0 : EvmRules.Evm.shr 224 (calldataWord call 0) = 332507694) + (h4 : calldataWord call 4 = a) (h36 : calldataWord call 36 = b) : + (SolarTV.EVM.Program.run o program call 2).map (fun r => observe call r.2 r.1) = + some (expectedAt call.storage a b) := by + simp only [SolarTV.EVM.Program.run, iterate, block, program, SolarTV.Export.Main.evm4, + List.getElem?_cons_zero] + simp (disch := simp) only [exec_push, exec_callvalue, exec_jumpi, exec_calldataload, + exec_bin (step_shr), exec_bin (step_sub), exec_bin (step_lt), exec_bin (step_add), + exec_dup0, exec_dup1, exec_swap0, exec_store, exec_calldatasize, exec_ret] + simp only [hv, hsize, h0, h4, h36, lt_add_self] + by_cases hof : a.toNat + b.toNat < 2 ^ 256 + · simp only [hof, ite_true] + simp (config := {decide := true}) only [BitVec.ofNat_eq_ofNat, ite_true, output, Option.map_some] + simp only [↓reduceIte, BitVec.reduceToNat, observe, expectedAt, expected, hof, + Option.some.injEq, Observable.mk.injEq, true_and] + refine ⟨?_, rfl, ?_⟩ + · rw [read_store] + simp only [EvmRules.Evm.add, BitVec.toNat_add, Nat.mod_eq_of_lt hof] + · funext slot + simp [storageOf, State.initial] + exact slotValue_mod_mod call.storage slot + · simp only [hof, ite_false] + simp (config := {decide := true}) only [BitVec.ofNat_eq_ofNat, ite_true, ite_false, + List.getElem?_cons_succ, List.getElem?_cons_zero] + simp (disch := simp) only [exec_push, exec_store, exec_revert] + simp only [output, Option.map_some, ↓reduceIte, BitVec.reduceToNat, observe, expectedAt, + expected, hof, Option.some.injEq, Observable.mk.injEq] + refine ⟨trivial, ?_, trivial, ?_⟩ + · try simp only [State.initial] + decide + · trivial + +/-- SolarTV's EVM IR semantics runs w1's final program on every call of f(a, b), under every +oracle, to the observable expected a b. -/ +theorem evmir_run (o : Oracle) (a b : U256) : + (SolarTV.evmirSem o).run program (callOf fSelector [a, b]) = some (expected a b) := by + rw [← expectedAt_nil] + exact sem_of_run 2 (evmir_run_of o _ a b rfl (size_callOf a b) (by rw [word0]; rfl) (word4 a b) + (word36 a b)) + +/-- The same from any storage `σ`, which the program keeps. -/ +theorem evmir_run_at (o : Oracle) (a b : U256) (σ : List (Nat × Nat)) : + (SolarTV.evmirSem o).run program { callOf fSelector [a, b] with storage := σ } = + some (expectedAt σ a b) := + sem_of_run 2 (evmir_run_of o _ a b rfl (size_callOf a b) + (by have h := word0 a b; rw [show BitVec.ofNat 256 fSelector = 332507694 from rfl] at h; exact h) + (word4 a b) (word36 a b)) + +end EvmirRun + +/-! ## EthLib runs the bytecode to the same observable -/ + +section Target + +open EthLib.Execution.Evm.Logic GasCosts SolidCore.Refinement.Evm.Symex SolidCore.Refinement.Evm.Logic + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- When $a + b$ fits, EthLib's frame returns the word from every state: every opcode stepped by +EthLib's program logic from pc 0 with 10M gas, its branches decided from the call data and the +bound. -/ +theorem frame_ok (a b : U256) (hof : a.toNat + b.toNat < 2 ^ 256) : + ∀ msg : Message .fusaka, msg.value = 0 → msg.data = cdOf (selectorOf fSelector) [a, b] → + ∀ st ss, Spec .fusaka (At code msg 0 [] .empty 10000000 st ss .empty) + (Post (expected a b) st ss) := by + have he : expected a b = + ⟨true, (natToBytes 32 (a.toNat + b.toNat)).map (fun x => x.toNat), [], fun _ => 0⟩ := by + rw [expected, ite_cond_eq_true _ _ (eq_true hof)] + rw [he] + wide_tgt [code, runtimeNat, runtimeSize, fSelector] + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- When it overflows, EthLib's frame reverts with Panic(0x11) from every state. -/ +theorem frame_overflow (a b : U256) (hof : ¬ a.toNat + b.toNat < 2 ^ 256) : + ∀ msg : Message .fusaka, msg.value = 0 → msg.data = cdOf (selectorOf fSelector) [a, b] → + ∀ st ss, Spec .fusaka (At code msg 0 [] .empty 10000000 st ss .empty) + (Post (expected a b) st ss) := by + have he : expected a b = + ⟨false, (natToBytes 4 0x4e487b71).map (fun x => x.toNat) ++ + (natToBytes 32 0x11).map (fun x => x.toNat), [], fun _ => 0⟩ := by + rw [expected, ite_cond_eq_false _ _ (eq_false hof)] + rw [he] + wide_tgt [code, runtimeNat, runtimeSize, fSelector] + refine revert_post (by decide) ?_ ?_ ?_ rfl ?_ + · evm_code [code, runtimeNat, runtimeSize, fSelector] + · evm_code [code, runtimeNat, runtimeSize, fSelector] + · wide_mem + · simp only + decide +kernel + +/-- EthLib's frame of every call of f(a, b) stops as expected a b shows, from every state. -/ +theorem frame (a b : U256) : + ∀ msg : Message .fusaka, msg.value = 0 → msg.data = cdOf (selectorOf fSelector) [a, b] → + ∀ st ss, Spec .fusaka (At code msg 0 [] .empty 10000000 st ss .empty) + (Post (expected a b) st ss) := by + by_cases hof : a.toNat + b.toNat < 2 ^ 256 + · exact frame_ok a b hof + · exact frame_overflow a b hof + +theorem expected_logs (a b : U256) : (expected a b).logs = [] := by + unfold expected; split <;> rfl + +/-- EthLib runs solar's bytecode on every call of f(a, b) to the observable expected a b. -/ +theorem target_run (a b : U256) : + Target.run code (callOf fSelector [a, b]) = some (expected a b) := + run_of_post code fSelector [a, b] _ (expected_logs a b) + (fun _ => by unfold expected; split <;> rfl) (frame a b) + +/-- EthLib runs solar's bytecode on every call of f(a, b) from any storage `σ` to the +observable expectedAt σ a b. -/ +theorem target_run_at (a b : U256) (σ : List (Nat × Nat)) : + Target.run code { callOf fSelector [a, b] with storage := σ } = some (expectedAt σ a b) := + run_of_post_at code fSelector [a, b] σ _ (expected_logs a b) (fun _ => rfl) (frame a b) + +end Target + +/-! ## The stage -/ + +/-- The oracle of EthLib's call: one frame at 0x1000 called by 0x2000 (also the origin), in +Target.blockEnv (chain 1, block 1 at time 1, gas limit 30M, coinbase 0, base fee 0) and +Target.txEnv (gas price 0). No call has returned, so return data is empty, and the frame calls +nothing, so call results never arise. GAS, balances and every other read the EVM IR semantics +asks the oracle for are 0: w1 reads none of them, and the stage holds under every oracle +(stage). -/ +def oracle : SolarTV.Machine.Oracle where + env name _ _ := + if name = "caller" ∨ name = "origin" then BitVec.ofNat 256 callerAddress + else if name = "address" then BitVec.ofNat 256 selfAddress + else if name = "chainid" ∨ name = "number" ∨ name = "timestamp" then 1 + else if name = "gaslimit" then 30000000 + else 0 + result _ := 0 + storageAfter _ _ := 0 + transientAfter _ _ := 0 + keccak _ := 0 + caller := BitVec.ofNat 160 callerAddress + +/-- The same stage, shown directly by running both sides to the same observable: the +cross-check of stage. -/ +theorem stage_run (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib program code scope := by + intro call hc obs hrun + obtain ⟨a, b, rfl⟩ := scope_callOf hc + rw [evmir_run o a b] at hrun + cases hrun + exact target_run a b + +/-- The certificate of the check: each block's offset (bb3 at 0x2e, bb7 at 0x32), the stack +height each block needs on entry (none), and the bound on memory (64 bytes). -/ +def cert : Assemble.Cert := { offsets := [0, 0x2e, 0x32], needs := [0, 0, 0], top := 64 } + +/-- The checker's lowering of the program is the item list above. -/ +theorem lower_eq : Assemble.lower program cert = items := by decide +kernel + +set_option maxRecDepth 100000 in +/-- The checker accepts solar's bytecode for the program, by the kernel's evaluation. -/ +theorem check_ok : Assemble.check program code cert = true := by decide +kernel + +theorem scope_facts {call : Call} (h : scope call) : call.callvalue = 0 ∧ call.storage = [] := by + obtain ⟨a, b, rfl⟩ := scope_callOf h + exact ⟨rfl, rfl⟩ + +/-- EVM IR to bytecode is a stage for w1 on the scope, under every oracle: every observable +SolarTV's EVM IR semantics gives for the final program, EthLib gives for solar's bytecode. It +is the generic theorem for every program and code the checker accepts, at check_ok. -/ +theorem stage (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib program code scope := + Assemble.stage_of_check check_ok o fun _ h => (scope_facts h).1 + +/-- EVM IR to bytecode is a stage for w1 on every call, with any value, call data and storage, +under every oracle: the generic theorem at check_ok. -/ +theorem stageAll (o : SolarTV.Machine.Oracle) (scope : Call → Prop) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib program code scope := + Assemble.stage_of_check_all check_ok o scope + +/-- The same with EthLib's environment as the oracle. -/ +theorem stage_ethLib : SolarTV.Stage (SolarTV.evmirSem oracle) ethLib program code scope := stage oracle + +/-- EVM IR to bytecode is a stage for w1 on every call of f with no value from any storage, under +every oracle: the generic theorem at the same check_ok, since every call of scopeAt has no +value. -/ +theorem stageAt (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib program code scopeAt := + Assemble.stage_of_check check_ok o fun _ ⟨_, _, _, _, _, _, h⟩ => by rw [h] + +/-- The same stage from any storage proved directly, by running both sides to the same observable +(evmir_run_at and target_run_at), as a cross-check of stageAt. -/ +theorem stageAt_run (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib program code scopeAt := by + intro call hc obs hrun + obtain ⟨a, b, σ, rfl⟩ := scopeAt_callOf hc + rw [evmir_run_at o a b σ] at hrun + cases hrun + exact target_run_at a b σ + +/-- It is SolarTV's assembly stage, which mir_to_bytecode composes. -/ +theorem assembly : SolarTV.AssemblyStage ethLib oracle program (show ethLib.Prog from code) scope := + stage oracle + +/-! ## A one-byte mutation is caught -/ + +/-- The bytecode with its ADD (0x01, at offset 33) replaced by SUB (0x03). -/ +def mutantNat : Nat := + 0x34602e575f3560e01c806313d1aa2e03602e5760443610602e5760043560243581039081106032575f5260205ff35b5f5ffd5b6011602052634e487b715f526024601cfd + +def mutant : ByteArray := EthLib.Execution.Evm.Logic.NatCode.ofNat mutantNat runtimeSize + +def mutantBytes : List Nat := mutant.data.toList.map (·.toNat) + +/-- It differs from solar's bytecode in exactly one byte, at offset 33. -/ +theorem mutant_one_byte : + mutantBytes.length = bytes.length ∧ bytes[33]? = some 0x01 ∧ mutantBytes[33]? = some 0x03 ∧ + ∀ i, i ≠ 33 → mutantBytes[i]? = bytes[i]? := by + refine ⟨by decide, by decide, by decide, fun i hi => ?_⟩ + by_cases h : i < 68 + · revert hi; revert i; decide + · have h1 : bytes.length = 68 := by decide + have h2 : mutantBytes.length = 68 := by decide + rw [List.getElem?_eq_none (by omega), List.getElem?_eq_none (by omega)] + +/-- The checker rejects the mutant: at offset 33 it decodes SUB where the program has ADD. -/ +theorem mutant_decodes_sub : decode mutantBytes 33 = some (.op 0x03, 34) ∧ + items[22]? = some (.op 0x01) := by decide + +theorem mutant_rejected : walk mutantBytes offset 0 items = none := by decide + +set_option maxRecDepth 100000 in +/-- The generic checker rejects the mutant too. -/ +theorem mutant_check : Assemble.check program mutant cert = false := by decide +kernel + +theorem mutant_no_walk (stream : List (Nat × Instr)) : ¬ Walk mutantBytes offset 0 items stream := + no_walk mutant_rejected stream + +/-- The call f(2, 1). -/ +def call21 : Call := callOf fSelector [2, 1] + +theorem call21_scope : scope call21 := + ⟨⟨fSelector, [.uint 256, .uint 256]⟩, List.mem_singleton_self _, [2, 1], rfl, + by intro x hx; simp only [List.mem_cons, List.mem_nil_iff, or_false] at hx; omega, rfl⟩ + +/-- On f(2, 1) the final EVM IR program returns 3. -/ +theorem evmir_call21 (o : SolarTV.Machine.Oracle) : + (SolarTV.evmirSem o).run program call21 = + some ⟨true, (natToBytes 32 3).map (·.toNat), [], fun _ => 0⟩ := by + rw [call21, evmir_run o 2 1, expected, if_pos (by decide)] + rfl + +section Mutant + +open EthLib.Execution.Evm.Logic GasCosts SolidCore.Refinement.Evm.Symex SolidCore.Refinement.Evm.Logic + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- On f(2, 1) the mutant computes 2 - 1 = 1, which its overflow check takes for an overflow +since 1 < 2: it reverts with Panic(0x11). -/ +theorem mutant_call21 : + Target.run mutant call21 = + some ⟨false, (natToBytes 4 0x4e487b71).map (fun x => x.toNat) ++ + (natToBytes 32 0x11).map (fun x => x.toNat), [], fun _ => 0⟩ := by + refine run_of_post mutant fSelector [2, 1] _ rfl (fun _ => rfl) ?_ + wide_tgt [mutant, mutantNat, runtimeSize, fSelector] + refine revert_post (by decide) ?_ ?_ ?_ rfl ?_ + · evm_code [mutant, mutantNat, runtimeSize, fSelector] + · evm_code [mutant, mutantNat, runtimeSize, fSelector] + · wide_mem + · simp only + decide +kernel + +end Mutant + +/-- The mutation makes the stage false: on f(2, 1), in the scope, the program returns 3 and the +mutant reverts. -/ +theorem mutant_not_stage (o : SolarTV.Machine.Oracle) : + ¬ SolarTV.Stage (SolarTV.evmirSem o) ethLib program mutant scope := by + intro h + have := h call21 call21_scope _ (evmir_call21 o) + change Target.run mutant call21 = _ at this + rw [mutant_call21] at this + cases this + +/-- info: 'SolidCore.Refinement.Solar.W1.stage' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage + +/-- +info: 'SolidCore.Refinement.Solar.W1.stage_run' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms stage_run + +/-- info: 'SolidCore.Refinement.Solar.W1.stageAt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stageAt + +/-- +info: 'SolidCore.Refinement.Solar.W1.stageAt_run' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms stageAt_run + +/-- info: 'SolidCore.Refinement.Solar.W1.check_ok' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms check_ok + +/-- info: 'SolidCore.Refinement.Solar.W1.mutant_check' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms mutant_check + +/-- +info: 'SolidCore.Refinement.Solar.W1.assembly' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms assembly + +/-- +info: 'SolidCore.Refinement.Solar.W1.mutant_not_stage' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms mutant_not_stage + +/-- info: 'SolidCore.Refinement.Solar.W1.mutant_no_walk' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms mutant_no_walk + +/-- info: 'SolidCore.Refinement.Solar.W1.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms decodes + +end SolidCore.Refinement.Solar.W1 diff --git a/SolidCore/Refinement/Solar/W1Value.lean b/SolidCore/Refinement/Solar/W1Value.lean new file mode 100644 index 00000000..c5071d80 --- /dev/null +++ b/SolidCore/Refinement/Solar/W1Value.lean @@ -0,0 +1,417 @@ +import SolidCore.Refinement.Solar.Milestone + +/-! +# w1 with a nonzero call value + +f is not payable, so every call of it that carries value is rejected. certifiedValue states that +solar's bytecode for w1 meets that specification (postValue: the call reverts with empty output, +emits no logs and keeps the call's storage) on scopeValue, every call of f on any two argument +words with a value v, 0 < v < 2 ^ 256, from any storage, under EthLib, through every stage of +solar's pipeline: + +* source: source_run_value, SolidCore's dispatcher decodes the arguments, finds f not payable + and reverts with empty output (rejectedValueCall?); run_eq_value runs Source.run with value v + (the constructor runs with no value whatever the call's, so DeployedAt still applies), and + satisfiesValue is the specification on SolidCore. mir_run_value: solar's first lowered MIR + checks the call value first and reverts, on any call data and storage. loweringValue is the + stage. +* backend: SolarTV.Milestone.W1.w1_mir_to_evmir, which holds on every call (any call data, call + value and storage). +* assembly: assemblyValue is the generic theorem, Assemble.stage_of_check_all at check_ok, which + holds on every call with any value from any storage. As a cross-check, target_run_value runs + EthLib's processMessage of the call directly: the move of v from the caller (which holds + exactly v) to the contract succeeds (moveEther_preState), the frame reverts with empty output + from every state on every message with nonzero value (frame_value: CALLVALUE PUSH1 0x2e JUMPI + to JUMPDEST PUSH0 PUSH0 REVERT, every opcode stepped by EthLib's program logic), and + processMessage returns that revert (processMessage_reverts_value), on any call data; + assemblyValue_run is the stage from it. + +loweringValue_rejects: the source stage on scopeValue is false for noValueStage0, stage0 with +the call value check dropped, by a mismatch of observables on f(1, 2) with value 1, where +SolidCore rejects the call and noValueStage0 returns 3. + +Not covered: the value's effect on balances (Observable has no balances, and the revert undoes +the move), and payable functions, which w1 has none of. +-/ + +namespace SolidCore.Refinement.Solar.W1 + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm +open SolidCore.Refinement.Evm.Symex SolidCore.Refinement.Evm.Logic + +/-- A message that moves nonzero value, to code that is no precompile, whose frame reverts with +empty output from every state: once the move of its value succeeds, processMessage at Fusaka +returns the revert with empty output. -/ +theorem processMessage_reverts_value {c : ByteArray} (message : Message .fusaka) + (hcode : message.code = c) (htr : message.shouldTransferValue = true) + (hv : message.value ≠ 0) (hpre : precompileAddress .fusaka message = none) + (h : ∀ st ss, Spec .fusaka (At c message 0 [] .empty message.gas st ss .empty) Reverted) + (st st' : State.TransactionState) (ss : Substate) + (hmove : st.moveEther .fusaka message.caller message.currentTarget message.value = .ok st') : + ∃ evm, processMessage (Meter := Nat) .fusaka message st ss = .ok evm ∧ + evm.1.error = some .revert ∧ evm.1.output = .empty := by + rw [processMessage] + have hss : startState .fusaka message st = st := by + simp [startState, show ¬ (Fork.fusaka < Fork.paris) by decide] + simp only [hss, hpre, htr, ne_eq, hv, not_false_eq_true, and_self, ↓reduceIte, hmove] + simp only [pure, Except.pure, bind, Except.bind, Except.mapError] + split + · rename_i e hr + obtain ⟨after, h', -⟩ := runFrame_of_spec hcode (h _ _) hr + cases h' + · rename_i after hr + obtain ⟨after', h', -, herr, hout⟩ := runFrame_of_spec hcode (h _ _) hr + cases h' + refine ⟨_, rfl, ?_, ?_⟩ + · simp only [rollbackOnError]; split <;> simp [herr] + · simp only [rollbackOnError]; split <;> simp [hout] + + +/-- The call value as a word is nonzero. -/ +theorem ofNat_ne_zero {v : Nat} (hv0 : v ≠ 0) (hv : v < 2 ^ 256) : BitVec.ofNat 256 v ≠ 0 := by + intro h + have := congrArg BitVec.toNat h + rw [BitVec.toNat_ofNat, Nat.mod_eq_of_lt hv] at this + exact hv0 this + +/-- A choice between two successes succeeds. -/ +theorem exists_ite_pure {ε α : Type} (c : Prop) [Decidable c] (a b : α) : + ∃ x, (if c then (pure a : Except ε α) else pure b) = .ok x := + ⟨if c then a else b, by split <;> rfl⟩ + +open EthLib.Execution.State in +/-- The caller of a call holds exactly its value, and the contract holds none: moving the value +from the caller to the contract succeeds. -/ +theorem moveEther_preState (code : ByteArray) (call : Call) (hv : call.callvalue < 2 ^ 256) : + ∃ st', (Target.preState code call).moveEther .fusaka (Target.address callerAddress) + (Target.address selfAddress) (BitVec.ofNat 256 call.callvalue) = .ok st' := by + simp only [TransactionState.moveEther, TransactionState.modifyState, bind, Except.bind] + have hAB : Target.address callerAddress ≠ Target.address selfAddress := by decide + simp [TransactionState.getAccount, TransactionState.getAccountOptional, + TransactionState.recordAccountRead, TransactionState.setAccount, Target.preState, + TransactionState.ofBlock, State.getAccountOptional, Account.debit, Account.credit, + TransactionState.destroyAccount, hAB.symm, BitVec.toNat_ofNat] + have hv' : call.callvalue % + 115792089237316195423570985008687907853269984665640564039457584007913129639936 = + call.callvalue := Nat.mod_eq_of_lt hv + have hv2 : call.callvalue < + 115792089237316195423570985008687907853269984665640564039457584007913129639936 := hv + split_ifs + all_goals + simp [hv', hv2, Std.ExtTreeMap.getElem_insert, Std.ExtTreeMap.getElem_insert_self, + pure, Except.pure, TransactionState.destroyStorage, hAB, BitVec.toNat_ofNat] + all_goals exact exists_ite_pure _ _ _ + +/-- The frame of w1's code reverts with empty output from every state on every message with +nonzero value: CALLVALUE PUSH1 0x2e JUMPI jumps to JUMPDEST PUSH0 PUSH0 REVERT. -/ +theorem frame_value (msg : Message .fusaka) (hv : msg.value ≠ 0) (st : State.TransactionState) + (ss : Substate) : Spec .fusaka (At code msg 0 [] .empty 10000000 st ss .empty) Reverted := by + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + repeat symex_one [code, runtimeNat, runtimeSize] [hv] hfork + + +section ValueMIR + +open SolarTV SolarTV.Machine + +/-- SolarTV's lowered MIR runs w1's stage0 on every call with nonzero value, whatever its call +data and storage, to the rejection: entry's call value check reverts with empty output. -/ +theorem mir_run_value_of (o : Oracle) (call : Call) (hv0 : call.callvalue ≠ 0) + (hv : call.callvalue < 2 ^ 256) : + (MIR.Lowered.Module.run o SolarTV.Export.Main.stage0 call 9).map + (fun r => observe call r.2 r.1) = some (Abi.rejected call.storage) := by + have hb := ofNat_ne_zero hv0 hv + repeat (first | sym_eval | simp (config := {decide := true}) only [↓reduceIte]) + have hne : EvmRules.Evm.ne (BitVec.ofNat 256 call.callvalue) 0 = 1 := by + simp [EvmRules.Evm.ne] + exact hb + simp only [hne, show (1 : EvmRules.Word) ≠ 0 by decide, ↓reduceIte] + repeat sym_eval + simp [observe, Abi.rejected, Mem.read] + +end ValueMIR + + +/-- **EthLib rejects every call of w1's code with nonzero value**, on any call data and from any +storage: the move of the value succeeds, the frame reverts with empty output, and the revert +undoes the move. -/ +theorem target_run_value (cd : ByteArray) (v : Nat) (hv0 : v ≠ 0) (hv : v < 2 ^ 256) + (σ : List (Nat × Nat)) : + Target.run code { calldata := cd, callvalue := v, storage := σ } = some (Abi.rejected σ) := by + obtain ⟨st', hmove⟩ := moveEther_preState code { calldata := cd, callvalue := v, storage := σ } hv + obtain ⟨evm, hr, herr, hout⟩ := processMessage_reverts_value + (Target.message code { calldata := cd, callvalue := v, storage := σ }) rfl rfl + (ofNat_ne_zero hv0 hv) (precompileAddress_message code _) + (fun st ss => frame_value _ (ofNat_ne_zero hv0 hv) st ss) _ st' Substate.empty hmove + simp [Target.run, hr, herr, hout, Abi.rejected] + +/-- The lowered MIR's run, fuel-free. -/ +theorem mir_run_value (o : SolarTV.Machine.Oracle) (cd : ByteArray) (v : Nat) (hv0 : v ≠ 0) + (hv : v < 2 ^ 256) (σ : List (Nat × Nat)) : + (SolarTV.MIR.Lowered.moduleSem o).run SolarTV.Export.Main.stage0 + { calldata := cd, callvalue := v, storage := σ } = some (Abi.rejected σ) := + mir_sem_of_run 9 (mir_run_value_of o _ hv0 hv) + +open SolidCore.Solidity SolidCore.Solidity.Source SolidCore.Refinement.Wide in +/-- Source.run of a call with value v from the storage σ, once the constructor's result is +known: the constructor runs with no value whatever the call's (constructWithContext? sets it), +so it is the deployed state, and the ABI dispatcher of the core contract runs with v. -/ +theorem run_eq_value {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : DeployedAt fuel c d s) (sel : Nat) (ws : List U256) + (v : Nat) (σ : List (Nat × Nat)) : + Source.run fuel c + { calldata := Abi.calldata sel (ws.map (·.toNat)), callvalue := v, storage := σ } = + Option.map (Source.observe + { calldata := Abi.calldata sel (ws.map (·.toNat)), callvalue := v, storage := σ }) + (ABI.Contract.callCalldataAtFromWithContext? fuel c.core { ctxOf c with value := v } + { d with storage := σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage } + selfAddress callerAddress v + ((natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes (ws.map (·.toNat)))) := by + obtain ⟨vs, hc⟩ := hd.cons + have hc' : TypeCheck.CheckedContract.constructWithContext? fuel c + { c.core.context with sender := callerAddress, self := selfAddress, value := v } + State.empty selfAddress 0 [] = some (CallResult.returned d vs) := hc + simp only [Source.run, Source.result?] + rw [hc'] + simp only [TypeCheck.CheckedContract.callCalldataAtFromWithContext?, Dirty.bytes_calldata] + rfl + + +open SolidCore.Solidity SolidCore.Solidity.Source SolidCore.Refinement.Wide + SolidCore.Refinement.Evm.Wide in +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore rejects every call of w5's f with nonzero value, on any argument words, from any +storage: its dispatcher decodes the arguments, finds f not payable and reverts with empty +output (rejectedValueCall?). -/ +theorem source_run_value {c : TypeCheck.CheckedContract} (hc : Corpus.W5.contract? = .ok c) + (a b : U256) (v : Nat) (hv0 : v ≠ 0) (hv : v < 2 ^ 256) (σ : List (Nat × Nat)) : + Source.run Corpus.W5.fuel c + { calldata := (callOf fSelector [a, b]).calldata, callvalue := v, storage := σ } = + some (Abi.rejected σ) := by + obtain ⟨hk, _, hemp⟩ := Corpus.W5.shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + have hd' := Verify.deployedAt_of_deployed hd + have hcore := hk + have hm : v % EvmYul.UInt256.size = v := Nat.mod_eq_of_lt hv + have hw : wordEq v 0 = false := by + simp [wordEq, Shared.norm, Shared.wordModulus, hm, hv0] + rw [show (callOf fSelector [a, b]).calldata = + Abi.calldata Bytecode.W5.Main.fSelector ([a, b].map (·.toNat)) from rfl, run_eq_value hd'] + have hev := hd'.events + have h0 : ∀ q : Nat, d.storage[q]? = none := fun q => hd'.getElem?_eq_none (by simp) + generalize σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage = m + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [Corpus.W5.coreLit, Corpus.W5.fuel, ctxOf, hcore, Bytecode.W5.Main.fSelector, hw] + simp [Source.observe, Abi.rejected] + + +/-! ## The value scope through every stage -/ + +open SolidCore.Refinement.Evm.Wide in +/-- Every call of f on any two argument words with a nonzero value v < 2 ^ 256, from any +storage. -/ +def scopeValue : Call → Prop := fun call => + ∃ (a b : U256) (v : Nat) (σ : List (Nat × Nat)), v ≠ 0 ∧ v < 2 ^ 256 ∧ + call = { calldata := (callOf fSelector [a, b]).calldata, callvalue := v, storage := σ } + +/-- f is not payable: a call with value reverts with empty output, emits no logs and keeps the +call's storage. -/ +def postValue (call : Call) (obs : Observable) : Prop := + obs.success = false ∧ obs.output = [] ∧ obs.logs = [] ∧ + ∀ slot, obs.storage slot = slotValue call.storage slot + +/-- No precondition beyond the scope. -/ +def preValue : Call → Prop := fun _ => True + +/-- The specification on the value scope holds of SolidCore's checked w5. -/ +theorem satisfiesValue : ∃ c, Corpus.W5.contract? = .ok c ∧ + Satisfies (solidCore Corpus.W5.fuel) c scopeValue preValue postValue := by + obtain ⟨c, hc, -⟩ := Verify.W5.satisfies + refine ⟨c, hc, ?_⟩ + rintro call ⟨a, b, v, σ, hv0, hv, rfl⟩ - + exact ⟨_, source_run_value hc a b v hv0 hv σ, rfl, rfl, rfl, fun _ => rfl⟩ + +/-- **The source stage on the value scope**, under every oracle. -/ +theorem loweringValue (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : Corpus.W5.contract? = .ok c) : + Stage (solidCore Corpus.W5.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 scopeValue := by + rintro call ⟨a, b, v, σ, hv0, hv, rfl⟩ obs hrun + change Source.run Corpus.W5.fuel c _ = some obs at hrun + rw [source_run_value hc a b v hv0 hv σ] at hrun + cases hrun + exact mir_run_value o _ v hv0 hv σ + +/-- **The assembly stage on the value scope**, under every oracle: the generic theorem for every +program and code the checker accepts, at check_ok, which holds on every call with any value. -/ +theorem assemblyValue (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib program code scopeValue := + Assemble.stage_of_check_all check_ok o scopeValue + +/-- The assembly stage on the value scope proved directly, as a cross-check of assemblyValue: +the final EVM IR runs to the rejection (the source stage's MIR run and the backend stages, which +hold on every call), and so does the bytecode on EthLib (target_run_value). -/ +theorem assemblyValue_run (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib program code scopeValue := by + rintro call ⟨a, b, v, σ, hv0, hv, rfl⟩ obs hrun + have he := SolarTV.Milestone.W1.w1_mir_to_evmir o _ trivial _ + (mir_run_value o (SolidCore.Refinement.Evm.Wide.callOf fSelector [a, b]).calldata v hv0 hv σ) + rw [show program = SolarTV.Export.Main.evm4 from rfl, he] at hrun + cases hrun + exact target_run_value _ v hv0 hv σ + +/-- **w1 with a nonzero call value**: solar's bytecode for w1 meets f's specification on every +call with value (it is not payable, so the call is rejected and the storage kept) under +EthLib, through every stage of solar's pipeline. -/ +theorem certifiedValue : Satisfies ethLib code scopeValue preValue postValue := by + obtain ⟨c, hc, hspec⟩ := satisfiesValue + exact bytecode_of_stages hspec (loweringValue oracle hc) + ((SolarTV.Milestone.W1.w1_mir_to_evmir oracle).mono fun _ _ => trivial) (assemblyValue oracle) + +/-- info: 'SolidCore.Refinement.Solar.W1.certifiedValue' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms certifiedValue + +/-- info: 'SolidCore.Refinement.Solar.W1.target_run_value' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms target_run_value + +/-- info: 'SolidCore.Refinement.Solar.W1.source_run_value' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms source_run_value + +/-- info: 'SolidCore.Refinement.Solar.W1.loweringValue' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms loweringValue + +/-- info: 'SolidCore.Refinement.Solar.W1.assemblyValue' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms assemblyValue + + +/-! ## A lowering without the call value check is rejected + +noValueStage0 is stage0 with entry's call value check dropped (both arms of its branch go on +to the selector switch), so f runs whatever the value. loweringValue_rejects shows the source +stage on the value scope false for it, by a mismatch of observables: on f(1, 2) with value 1, +SolidCore rejects the call and noValueStage0 returns 3. -/ + +/-- stage0 with the call value check dropped. -/ +def noValueStage0 : SolarTV.MIR.Lowered.Module := + { entry := 1, + functions := [ + -- @f + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 13) .calldatasize [], + .pure 15 .lt [.value 13, .const 68]], + .branch (.value 15) 3 4⟩, + -- bb1 + ⟨[], + [.effect none .mstore [.const 32, .const 17], + .effect none .mstore [.const 0, .const 0x4e487b71]], + .revert (.const 28) (.const 36)⟩, + -- bb2 + ⟨[], + [.effect none .mstore [.const 0, .value 4]], + .ret (.const 0) (.const 32)⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩, + -- bb4 + ⟨[], + [.effect (some 17) .calldataload [.const 4], + .effect (some 19) .calldataload [.const 36], + .pure 4 .add [.value 17, .value 19], + .pure 5 .lt [.value 4, .value 17]], + .branch (.value 5) 1 2⟩] }, + -- @entry + { params := [], + blocks := [ + -- bb0 + ⟨[], + [.effect (some 0) .callvalue [], + .ne 2 (.value 0) (.const 0)], + .branch (.value 2) 1 1⟩, + -- bb1 + ⟨[], + [.effect (some 4) .calldataload [.const 0], + .pure 6 .shr [.const 224, .value 4]], + .switch (.value 6) 3 [(.const 0x13d1aa2e, 2)]⟩, + -- bb2 + ⟨[], + [], + .tailCall 0 []⟩, + -- bb3 + ⟨[], + [], + .revert (.const 0) (.const 0)⟩] }] } + +section NoValue + +open SolarTV SolarTV.Machine SolarTV.Milestone.W1 + +/-- noValueStage0 runs f on every call of f(a, b), whatever its value, as stage0 does on calls +with no value. -/ +theorem noValue_run_of (o : Oracle) (call : Call) (a b : EvmRules.Word) + (hsize : call.calldata.size = 68) (h0 : EvmRules.Evm.shr 224 (calldataWord call 0) = 332507694) + (h4 : calldataWord call 4 = a) (h36 : calldataWord call 36 = b) : + (MIR.Lowered.Module.run o noValueStage0 call 9).map + (fun r => observe call r.2 r.1) = some (expectedAt call.storage a b) := by + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte, ite_self]) + by_cases hof : a.toNat + b.toNat < 2 ^ 256 + all_goals + simp only [add_lt_self_iff, hof, not_true_eq_false, not_false_eq_true, ↓reduceIte] + repeat (first | sym_eval | sym_cond | simp (config := {decide := true}) only [↓reduceIte]) + · simp only [BitVec.reduceToNat, observe, expectedAt, expected, hof, ↓reduceIte, + Option.some.injEq, Observable.mk.injEq, true_and] + refine ⟨?_, ?_, ?_⟩ + · rw [read_store_mir] + simp only [EvmRules.Evm.add, BitVec.toNat_add, Nat.mod_eq_of_lt hof] + · rfl + · funext slot + simp [storageOf, State.initial] + exact SolidCore.Refinement.Evm.Wide.slotValue_mod_mod call.storage slot + · simp only [BitVec.reduceToNat, observe, expectedAt, expected, hof, ↓reduceIte, + Option.some.injEq, Observable.mk.injEq] + refine ⟨trivial, ?_, trivial, ?_⟩ + · try simp only [State.initial] + decide + · trivial + +end NoValue + +open SolidCore.Refinement.Evm.Wide in +/-- The source stage on the value scope is false for the lowering without the call value check, +under every oracle: on f(1, 2) with value 1 from empty storage SolidCore rejects the call, and +noValueStage0 succeeds. -/ +theorem loweringValue_rejects (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : Corpus.W5.contract? = .ok c) : + ¬ Stage (solidCore Corpus.W5.fuel) (SolarTV.MIR.Lowered.moduleSem o) c noValueStage0 + scopeValue := by + intro h + have hs : scopeValue + { calldata := (callOf fSelector [1, 2]).calldata, callvalue := 1, storage := [] } := + ⟨1, 2, 1, [], by decide, by decide, rfl⟩ + have := h _ hs _ (source_run_value hc 1 2 1 (by decide) (by decide) []) + have hrun : (SolarTV.MIR.Lowered.moduleSem o).run noValueStage0 + { calldata := (callOf fSelector [1, 2]).calldata, callvalue := 1, storage := [] } = + some (expectedAt [] 1 2) := + mir_sem_of_run 9 (noValue_run_of o _ 1 2 (size_callOf 1 2) + (by have h := word0 1 2; rw [show BitVec.ofNat 256 fSelector = 332507694 from rfl] at h; exact h) + (word4 1 2) (word36 1 2)) + rw [hrun] at this + have hsucc := congrArg (fun obs : Observable => obs.success) (Option.some.inj this) + simp [expectedAt, expected, Abi.rejected] at hsucc + +/-- info: 'SolidCore.Refinement.Solar.W1.loweringValue_rejects' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms loweringValue_rejects + +end SolidCore.Refinement.Solar.W1 diff --git a/SolidCore/Refinement/Solar/W4/Milestone.lean b/SolidCore/Refinement/Solar/W4/Milestone.lean new file mode 100644 index 00000000..38581af3 --- /dev/null +++ b/SolidCore/Refinement/Solar/W4/Milestone.lean @@ -0,0 +1,268 @@ +import SolidCore.Refinement.Solar.W4Lowering +import Verify.W4 +import SolidCore.Refinement.Evm.WideStorage +import SolidCore.Refinement.Spec +import w4.Proofs +import w4.gen.Main.Manifest + +/-! +# The w4 milestone: solar's bytecode meets w4's verified specification, every stage proved + +The contract (scripts/refinement/corpus/w4.sol; solar-tv/milestone/w4/w4.sol in solar's tree, +the same contract), + + contract Main { uint256 x; function set(uint256 v) external { x = v; } } + +compiled by solar (-Ogas --evm-version osaka) to the 36 bytes of runtime bytecode +Corpus.W4.code, which is the bytecode solar exported with its stages (bytes_exported) and the +corpus's own compilation of w4.sol at solar 9688f215 (Bytecode.W4). certified states, with no +hypothesis, that this bytecode meets w4's specification (Verify.W4: set(v) succeeds with no +output and no logs, and leaves v in slot 0 and 0 elsewhere) on EthLib, and certifiedAt the same +from any storage (Verify.W4.postAt: v in slot 0, every other slot kept). The specification is +proved of SolidCore's checked contract with the Loom VC generator (Verify.W4.satisfies, +satisfiesAt) and carried to the bytecode through solar's actual pipeline (bytecode_of_stages), +every stage a theorem: + +* source: SolidCore to the first lowered MIR, lower-abi and lower-dispatch included + (lowering, loweringAt, SolidCore/Refinement/Solar/W4Lowering.lean, from the generic source + stage SolidCore.Refinement.Generic.stage); +* backend: the first lowered MIR through stack scheduling and the four EVM IR passes to the + final EVM IR (SolarTV.Milestone.W4.w4_mir_to_evmir, solar-tv/milestone/w4/Proofs, on every + call: any call data, call value and storage); +* assembly: the final EVM IR to the bytecode on EthLib (stage, stageAt, below). + +The stages hold under every oracle of SolarTV's semantics; the composition uses oracle, the +environment of EthLib's call. + +## The assembly stage + +* evmir_run_at: SolarTV's EVM IR semantics runs evm4 on every call of set(v) from any storage + σ to expectedAt σ v: SolidCore's run (source_run_at, from Verify.W4.run_set_at) carried + through the source stage (mir_run_at) and the backend stages. +* target_run_at: EthLib runs the bytecode on the same call to expectedAt σ v: every opcode + stepped by EthLib's program logic from pc 0 with 10M gas (wide_tgt_at: SSTORE's write and + price included, STOP against the observable, the call's storage σ read through + Target.preState), its branches decided from the call data. +* stageAt and stage: the stage on Verify.W4.scopeAt and Verify.W4.scope, under every oracle. + +solar-tv's SolarTV.Milestone.W4.decodes separately checks the bytecode's linear decoding +against evm4's instructions, the walk of the assembly checker. + +## Scope + +* Syntax: this one contract. The certificate is translation validation of this compilation. +* Calls: one call of set (selector 0x60fe47b1) with well-formed call data, the selector and one + word below 2^256 (36 bytes; Abi.fullScope). Malformed call data, other selectors and nonzero + call value are outside the scope. +* Storage: the deployed (empty) storage for certified, any storage for certifiedAt. The write + of slot 0 is proved on every slot of the final storage in SolidCore, the MIR and EVM IR + semantics and EthLib. +* EVM: EthLib at Fusaka, one message frame from 0x2000 to 0x1000 with 10M gas, metered on every + step. + +## Unverified boundaries + +As for w5 (SolidCore/Refinement/Solar/Milestone.lean): the front end that parses w4.sol into +SolidCore (Source.W4), the exporter's printing of solar's IR as Lean (solar-tv/milestone/w4/gen), +and the semantics themselves. + +No sorry, native_decide or bv_decide: the theorems depend on propext, Quot.sound and +Classical.choice only (pinned below). +-/ + +namespace SolidCore.Refinement.Solar.W4 + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm +open SolidCore.Refinement.Evm.Wide SolidCore.Refinement.Wide + +/-- The selector of set(uint256). -/ +abbrev setSelector : Nat := Bytecode.W4.Main.setSelector + +/-! ## The calls of the scope and what they show -/ + +theorem scopeAt_callAt {call : Call} (h : Verify.W4.scopeAt call) : + ∃ (v : U256) (σ : List (Nat × Nat)), call = callAt setSelector [v] σ := by + obtain ⟨σ, fn, hfn, args, hlen, hlt, rfl⟩ := h + simp only [Corpus.W4.fns, List.mem_singleton] at hfn + subst hfn + match args, hlen with + | [a], _ => + refine ⟨BitVec.ofNat 256 a, σ, ?_⟩ + have ha : a % 2 ^ 256 = a := Nat.mod_eq_of_lt (hlt a (by simp)) + simp only [callAt, List.map_cons, List.map_nil, BitVec.toNat_ofNat, ha] + +/-- The deployed scope is the scope from any storage at the deployed storage, none. -/ +theorem scopeAt_of_scope {call : Call} (h : Verify.W4.scope call) : Verify.W4.scopeAt call := + ⟨[], h⟩ + +/-- What set(v) from the storage σ shows: success with no output and no logs, v in slot 0 and +every other slot of σ kept. -/ +def expectedAt (σ : List (Nat × Nat)) (v : U256) : Observable := + { success := true, output := [], logs := [], + storage := fun slot => if slot % 2 ^ 256 = 0 then v.toNat else slotValue σ slot } + +/-- The model SolidCore runs set as, from the storage σ, shows expectedAt σ v. -/ +theorem observe_model_at (v : U256) (σ : List (Nat × Nat)) : + Verify.observe (slotValue σ) (Verify.W4.model [v.toNat] (slotValue σ)) = expectedAt σ v := by + simp only [Verify.W4.model, Verify.observe, Verify.sstore, bind, StateT.bind, pure, StateT.pure, + Except.bind, Except.pure, expectedAt, List.getD_cons_zero, Nat.zero_mod, + Nat.mod_eq_of_lt v.isLt] + +/-- SolidCore runs w4's set on any argument word from any storage σ to expectedAt σ v +(Verify.W4.run_set_at). -/ +theorem source_run_at {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : Corpus.W4.contract? = .ok c) (v : U256) (σ : List (Nat × Nat)) : + Source.run Corpus.W4.fuel c (callAt setSelector [v] σ) = some (expectedAt σ v) := by + obtain ⟨hk, _, hemp⟩ := Corpus.W4.shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + have := Verify.W4.run_set_at hk (Verify.deployedAt_of_deployed hd) v σ + rw [observe_model_at] at this + exact this + +/-- SolarTV's lowered MIR semantics runs w4's first lowered MIR module on every call of set(v) +from any storage σ, under every oracle, to expectedAt σ v: SolidCore's run carried by the +generic source stage (loweringAt, Solar/W4Lowering.lean). -/ +theorem mir_run_at (o : SolarTV.Machine.Oracle) (v : U256) (σ : List (Nat × Nat)) : + (SolarTV.MIR.Lowered.moduleSem o).run SolarTV.Export.Main.stage0 (callAt setSelector [v] σ) = + some (expectedAt σ v) := by + obtain ⟨c, hc, -⟩ := Verify.W4.satisfies + exact loweringAt o hc _ ⟨σ, _, List.mem_singleton_self _, [v.toNat], rfl, + by simpa using v.isLt, rfl⟩ _ (source_run_at hc v σ) + +/-! ## The bytecode -/ + +/-- The runtime bytecode's bytes. -/ +def bytes : List Nat := Corpus.W4.code.data.toList.map (·.toNat) + +/-- The corpus's bytecode is the bytecode solar exported with w4's stages. -/ +theorem bytes_exported : bytes = SolarTV.Export.Main.bytecode := by decide + +/-- The runtime bytecode as hex, as the manifest records it. -/ +def runtimeHex : String := "346020575f3560e01c806360fe47b103602057602436106020576004355f55005b5f5ffd" + +/-- SolarTV's EVM IR semantics runs w4's final EVM IR on every call of set(v) from any storage +σ, under every oracle, to the observable expectedAt σ v. -/ +theorem evmir_run_at (o : SolarTV.Machine.Oracle) (v : U256) (σ : List (Nat × Nat)) : + (SolarTV.evmirSem o).run SolarTV.Export.Main.evm4 (callAt setSelector [v] σ) = + some (expectedAt σ v) := + SolarTV.Milestone.W4.w4_mir_to_evmir o _ trivial _ (mir_run_at o v σ) + +section Target + +open EthLib.Execution.Evm.Logic GasCosts +open SolidCore.Refinement.Evm.Symex SolidCore.Refinement.Evm.Logic + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- EthLib runs solar's bytecode on every call of set(v) from any storage σ to the observable +expectedAt σ v. -/ +theorem target_run_at (v : U256) (σ : List (Nat × Nat)) : + Target.run Corpus.W4.code (callAt setSelector [v] σ) = some (expectedAt σ v) := by + have he : expectedAt σ v = ⟨true, [], [], + fun slot => if slot % 2 ^ 256 = 0 then v.toNat else slotValue σ slot⟩ := rfl + rw [he] + refine run_of_postS_at Corpus.W4.code setSelector [v] σ _ rfl (fun h => by cases h) ?_ + intro msg hv hd hstat htgt + have hfork : Fork.fusaka ≤ Fork.fusaka := by decide + simp only [Bytecode.W4.Main.setSelector] at hd + repeat wide_one_at [Corpus.W4.code, Bytecode.W4.Main.runtimeNat, Bytecode.W4.Main.runtimeSize, + Bytecode.W4.Main.setSelector] [hd, hv] hfork hstat htgt + refine stop_postS ?lt ?op ?succ ?out rfl ?store + case lt => evm_code [Corpus.W4.code, Bytecode.W4.Main.runtimeNat, Bytecode.W4.Main.runtimeSize] + case op => evm_code [Corpus.W4.code, Bytecode.W4.Main.runtimeNat, Bytecode.W4.Main.runtimeSize] + case succ => rfl + case out => rfl + case store => + intro slot + simp only [htgt, getStorage_writeOf_of, getStorage_recordStorageRead, getStorage_preState_ofNat, + storage_callAt, true_and, storageKey_eq_toBeBytes, BitVec.toNat_ofNat] + simp only [Nat.reducePow, Nat.zero_mod] + by_cases h : slot % + 115792089237316195423570985008687907853269984665640564039457584007913129639936 = 0 + · simp only [h, ↓reduceIte] + · simp only [h, ↓reduceIte, BitVec.toNat_ofNat] + exact Nat.mod_eq_of_lt (slotValue_lt σ slot) + +end Target + +/-! ## The assembly stage -/ + +/-- **The assembly stage of w4 from any storage**: EVM IR to bytecode on EthLib, on every call +of set with no value from any storage, under every oracle. -/ +theorem stageAt (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib SolarTV.Export.Main.evm4 Corpus.W4.code + Verify.W4.scopeAt := by + intro call hc obs hrun + obtain ⟨v, σ, rfl⟩ := scopeAt_callAt hc + rw [evmir_run_at o v σ] at hrun + cases hrun + exact target_run_at v σ + +/-- **The assembly stage of w4**: the same on the deployed (empty) storage. -/ +theorem stage (o : SolarTV.Machine.Oracle) : + SolarTV.Stage (SolarTV.evmirSem o) ethLib SolarTV.Export.Main.evm4 Corpus.W4.code + Verify.W4.scope := + (stageAt o).mono fun _ h => scopeAt_of_scope h + +/-- The oracle of EthLib's call, as for w5 (SolidCore.Refinement.Solar.W1.oracle): one frame at +0x1000 called by 0x2000 (also the origin), in Target.blockEnv and Target.txEnv; every other +read is 0. w4 reads none of them, and every stage holds under every oracle. -/ +def oracle : SolarTV.Machine.Oracle where + env name _ _ := + if name = "caller" ∨ name = "origin" then BitVec.ofNat 256 callerAddress + else if name = "address" then BitVec.ofNat 256 selfAddress + else if name = "chainid" ∨ name = "number" ∨ name = "timestamp" then 1 + else if name = "gaslimit" then 30000000 + else 0 + result _ := 0 + storageAfter _ _ := 0 + transientAfter _ _ := 0 + keccak _ := 0 + caller := BitVec.ofNat 160 callerAddress + +/-! ## The milestone -/ + +/-- **The w4 milestone.** solar's runtime bytecode for w4, which is the bytecode solar exported +with its stages (byte for byte, and as the hex its manifest records for -Ogas at osaka), meets +w4's specification verified on SolidCore, under EthLib on every call of set from the deployed +storage, through every stage of solar's pipeline: the source stage (lowering), the backend +(SolarTV.Milestone.W4.w4_mir_to_evmir) and the assembly stage (stage). -/ +theorem certified : + bytes = SolarTV.Export.Main.bytecode ∧ + SolarTV.Export.Main.Manifest.bytecodeHex = runtimeHex ∧ + SolarTV.Export.Main.Manifest.optimization = "Gas" ∧ + SolarTV.Export.Main.Manifest.evmVersion = "osaka" ∧ + Satisfies ethLib Corpus.W4.code Verify.W4.scope Verify.W4.pre Verify.W4.post := by + refine ⟨bytes_exported, rfl, rfl, rfl, ?_⟩ + obtain ⟨c, hc, hspec⟩ := Verify.W4.satisfies + exact bytecode_of_stages hspec (lowering oracle hc) + ((SolarTV.Milestone.W4.w4_mir_to_evmir oracle).mono fun _ _ => trivial) (stage oracle) + +/-- **The w4 milestone from any storage.** The same bytecode meets w4's specification from any +storage (Verify.W4.postAt: on every call of set with no value from any storage σ, v in slot 0 +and every other slot of σ kept), under EthLib, through every stage of solar's pipeline, each +proved on every call from any storage. -/ +theorem certifiedAt : + Satisfies ethLib Corpus.W4.code Verify.W4.scopeAt Verify.W4.pre Verify.W4.postAt := by + obtain ⟨c, hc, hspec⟩ := Verify.W4.satisfiesAt + exact bytecode_of_stages hspec (loweringAt oracle hc) + ((SolarTV.Milestone.W4.w4_mir_to_evmir oracle).mono fun _ _ => trivial) (stageAt oracle) + +/-- info: 'SolidCore.Refinement.Solar.W4.target_run_at' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms target_run_at + +/-- info: 'SolidCore.Refinement.Solar.W4.stageAt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stageAt + +/-- info: 'SolidCore.Refinement.Solar.W4.certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certified + +/-- info: 'SolidCore.Refinement.Solar.W4.certifiedAt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms certifiedAt + +end SolidCore.Refinement.Solar.W4 diff --git a/SolidCore/Refinement/Solar/W4Lowering.lean b/SolidCore/Refinement/Solar/W4Lowering.lean new file mode 100644 index 00000000..1b5fa369 --- /dev/null +++ b/SolidCore/Refinement/Solar/W4Lowering.lean @@ -0,0 +1,114 @@ +import SolidCore.Refinement.Generic.Value +import SolidCore.Refinement.Corpus.W4 +import w4.gen.Main.Stage0 + +/-! +# w4's source stage, from the generic source stage + +The milestone contract w4 (solar-tv/milestone/w4/w4.sol, the corpus's w4), + + contract Main { uint256 x; function set(uint256 v) external { x = v; } } + +from SolidCore's checked contract (`Corpus.W4.contract?`, whose core the kernel checks is +`Corpus.W4.coreLit` and whose constructor leaves no storage) to the first lowered MIR module +solar compiles for it (`SolarTV.Export.Main.stage0` of solar-tv's `w4.gen.Main.Stage0`, after +`lower-evm-shaped`), in SolarTV's lowered MIR semantics under any oracle. Nothing here is +specific to w4 beyond one evaluation by the kernel: + +* `check_stage0`: `Generic.check` accepts the module for `Corpus.W4.fns` (`decide +kernel`): the + erased tree of `set` (write argument 0 to slot 0, return nothing) is the symbolic run's. +* `loweringAt`: the stage on every call of `set` on any word, no value, from any storage; + `lowering`: on `fullScope Corpus.W4.fns []` (`Verify.W4.scope`), from empty storage. +* `checkValue_stage0`: `Generic.checkValue` accepts the module (`decide +kernel`): `set` is not + payable and the module reverts with empty output on a call of it with a value other than 0, + so `loweringAtValue` and `loweringValue` are the two stages above at every value below + `2 ^ 256` (`Generic.stageValue`). + +solar-tv's w4 and w1 modules both declare `SolarTV.Export.Main.stage0`, so this module cannot be +imported together with `Solar.Lowering`, and the library root leaves it out; build it on its own +(`lake build SolidCore.Refinement.Solar.W4Lowering`). + +No sorry, native_decide or bv_decide; the axioms are pinned below. +-/ + +namespace SolidCore.Refinement.Solar.W4 + +open SolidCore.Refinement SolidCore.Refinement.Abi + +/-- Every call of `set` on any argument word, with no value, from any storage. -/ +def scopeAt : Call → Prop := fun call => ∃ σ, fullScope Corpus.W4.fns σ call + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: the generic check accepts w4's first lowered MIR module. -/ +theorem check_stage0 : + Generic.check Corpus.W4.fuel 16 Corpus.W4.coreLit SolarTV.Export.Main.stage0 + Corpus.W4.fns = true := by + decide +kernel + +/-- **The source stage of w4 from any storage**, from the generic source stage. -/ +theorem loweringAt (o : SolarTV.Machine.Oracle) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : Corpus.W4.contract? = .ok c) : + Stage (solidCore Corpus.W4.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 scopeAt := by + obtain ⟨hk, _, hemp⟩ := Corpus.W4.shape_of hc + obtain ⟨d, hd⟩ := Wide.deployed_of hemp + exact Generic.stage o (Verify.deployedAt_of_deployed hd) + (by rw [hk]; exact check_stage0) + +/-- **The source stage of w4**: every call of `set` with no value and empty storage. -/ +theorem lowering (o : SolarTV.Machine.Oracle) {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (hc : Corpus.W4.contract? = .ok c) : + Stage (solidCore Corpus.W4.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 (fullScope Corpus.W4.fns []) := + SolarTV.Stage.mono (loweringAt o hc) fun _ h => ⟨[], h⟩ + +set_option maxRecDepth 100000 in +/-- The kernel's evaluation: `set` is not payable, and the module reverts with empty output on a +call of it with a value other than 0. -/ +theorem checkValue_stage0 : + Generic.checkValue 16 Corpus.W4.coreLit SolarTV.Export.Main.stage0 Corpus.W4.fns = true := by + decide +kernel + +/-- **The source stage of w4 from any storage, at every value**: every call of `set` on any +word, with any value below `2 ^ 256`, under every oracle. -/ +theorem loweringAtValue (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : Corpus.W4.contract? = .ok c) : + Stage (solidCore Corpus.W4.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 + (fun call => ∃ σ v, Generic.fullScopeValue Corpus.W4.fns σ v call) := by + obtain ⟨hk, _, hemp⟩ := Corpus.W4.shape_of hc + obtain ⟨d, hd⟩ := Wide.deployed_of hemp + exact Generic.stageValue o (Verify.deployedAt_of_deployed hd) + (by rw [hk]; exact check_stage0) + (by rw [hk]; exact checkValue_stage0) + +/-- **The source stage of w4 at every value**: every call of `set` with any value below +`2 ^ 256` and empty storage. -/ +theorem loweringValue (o : SolarTV.Machine.Oracle) + {c : SolidCore.Solidity.TypeCheck.CheckedContract} (hc : Corpus.W4.contract? = .ok c) : + Stage (solidCore Corpus.W4.fuel) (SolarTV.MIR.Lowered.moduleSem o) c + SolarTV.Export.Main.stage0 + (fun call => ∃ v, Generic.fullScopeValue Corpus.W4.fns [] v call) := + SolarTV.Stage.mono (loweringAtValue o hc) fun _ ⟨v, h⟩ => ⟨[], v, h⟩ + +/-- info: 'SolidCore.Refinement.Solar.W4.loweringAt' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loweringAt + +/-- info: 'SolidCore.Refinement.Solar.W4.lowering' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms lowering + +/-- info: 'SolidCore.Refinement.Solar.W4.checkValue_stage0' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms checkValue_stage0 + +/-- info: 'SolidCore.Refinement.Solar.W4.loweringAtValue' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loweringAtValue + +/-- info: 'SolidCore.Refinement.Solar.W4.loweringValue' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loweringValue + +end SolidCore.Refinement.Solar.W4 diff --git a/SolidCore/Refinement/Source/AbiEncode.lean b/SolidCore/Refinement/Source/AbiEncode.lean new file mode 100644 index 00000000..b5ebb0be --- /dev/null +++ b/SolidCore/Refinement/Source/AbiEncode.lean @@ -0,0 +1,46 @@ +-- Generated from scripts/refinement/mem/abi_encode.sol with solc 0.8.35 the way scripts/refinement/gen.sh writes Source/NAME.lean. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace AbiEncode + +def importedSourceName : String := "scripts/refinement/mem/abi_encode.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "AbiEncode" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "hashPair", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "a", ty := Ty.uint 256, location := none }, { name := some "b", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.bytesN 32, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.ident "keccak256") [Arg.positional (Expr.call (Expr.member (Expr.ident "abi") "encode") [Arg.positional (Expr.ident "a"), Arg.positional (Expr.ident "b")])]))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.0", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end AbiEncode +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/AbiHash.lean b/SolidCore/Refinement/Source/AbiHash.lean new file mode 100644 index 00000000..c1759596 --- /dev/null +++ b/SolidCore/Refinement/Source/AbiHash.lean @@ -0,0 +1,46 @@ +-- Generated from scripts/refinement/mem/abi_hash.sol with solc 0.8.35 the way scripts/refinement/gen.sh writes Source/NAME.lean. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace AbiHash + +def importedSourceName : String := "scripts/refinement/mem/abi_hash.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "AbiHash" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "hashPair", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "a", ty := Ty.uint 256, location := none }, { name := some "b", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.typeName (Ty.uint 256)) [Arg.positional (Expr.call (Expr.ident "keccak256") [Arg.positional (Expr.call (Expr.member (Expr.ident "abi") "encode") [Arg.positional (Expr.ident "a"), Arg.positional (Expr.ident "b")])])]))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.0", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end AbiHash +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/ArraySum.lean b/SolidCore/Refinement/Source/ArraySum.lean new file mode 100644 index 00000000..e0df4dbe --- /dev/null +++ b/SolidCore/Refinement/Source/ArraySum.lean @@ -0,0 +1,46 @@ +-- Generated from scripts/refinement/mem/array_sum.sol with solc 0.8.35 the way scripts/refinement/gen.sh writes Source/NAME.lean. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace ArraySum + +def importedSourceName : String := "scripts/refinement/mem/array_sum.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "ArraySum" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "sum", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "xs", ty := Ty.array (Ty.uint 256) (none), location := some DataLocation.calldata }], + returns := [{ name := some "s", ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.forLoop (some (Stmt.varDecl [{ name := some "i", ty := Ty.uint 256, location := none }] (some (Expr.literal (Literal.number "0"))))) (some (Expr.binary BinaryOp.lt (Expr.ident "i") (Expr.member (Expr.ident "xs") "length"))) (some (Expr.unary UnaryOp.postIncrement (Expr.ident "i"))) (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "s") AssignOp.addAssign (Expr.index (Expr.ident "xs") (Expr.ident "i")))])]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.0", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end ArraySum +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/B1.lean b/SolidCore/Refinement/Source/B1.lean new file mode 100644 index 00000000..b25f1a23 --- /dev/null +++ b/SolidCore/Refinement/Source/B1.lean @@ -0,0 +1,72 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b1.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace B1 + +def importedSourceName : String := "scripts/refinement/corpus/b1.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "s", + ty := Ty.uint 8, + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.function + { kind := FunctionKind.function, + name := some "word", + visibility := some Visibility.internal_, + mutability := StateMutability.view, + params := [], + returns := [{ name := none, ty := Ty.bytesN 2, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.typeName (Ty.bytesN 2)) [Arg.positional (Expr.call (Expr.typeName (Ty.uint 16)) [Arg.positional (Expr.ident "s")])]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "pick", + visibility := some Visibility.internal_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "s") AssignOp.assign (Expr.literal (Literal.number "7"))), Stmt.returnValues (some (Expr.literal (Literal.number "1")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "x", ty := Ty.uint 8, location := none }], + returns := [{ name := none, ty := Ty.bytesN 1, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "s") AssignOp.assign (Expr.ident "x")), Stmt.returnValues (some (Expr.index (Expr.call (Expr.ident "word") []) (Expr.call (Expr.ident "pick") [])))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end B1 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/B2.lean b/SolidCore/Refinement/Source/B2.lean new file mode 100644 index 00000000..59a22658 --- /dev/null +++ b/SolidCore/Refinement/Source/B2.lean @@ -0,0 +1,57 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b2.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace B2 + +def importedSourceName : String := "scripts/refinement/corpus/b2.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "x", + ty := Ty.uint 8, + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), ContractItem.modifierDecl + { name := "m" + params := [{ name := some "k", ty := Ty.uint 8, location := none }] + virtual := false + override? := none + body := some (Stmt.block [Stmt.ifElse (Expr.binary BinaryOp.eq (Expr.ident "k") (Expr.literal (Literal.number "2"))) (Stmt.returnValues none) none, Stmt.modifierPlaceholder, Stmt.expr (Expr.assign (Expr.ident "x") AssignOp.assign (Expr.ident "k"))]) }, (ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "b", ty := Ty.bool, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [{ target := { segments := ["m"] }, args := [Arg.positional (Expr.ternary (Expr.ident "b") (Expr.literal (Literal.number "1")) (Expr.literal (Literal.number "3")))], hasArgList := true }, { target := { segments := ["m"] }, args := [Arg.positional (Expr.literal (Literal.number "2"))], hasArgList := true }], + body := some (Stmt.block []) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end B2 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/B3.lean b/SolidCore/Refinement/Source/B3.lean new file mode 100644 index 00000000..bcf32493 --- /dev/null +++ b/SolidCore/Refinement/Source/B3.lean @@ -0,0 +1,52 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b3.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace B3 + +def importedSourceName : String := "scripts/refinement/corpus/b3.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "X", + ty := Ty.bytesN 1, + visibility := some Visibility.internal_, + mutability := VarMutability.constant, + override? := none, + init := some (Expr.call (Expr.typeName (Ty.bytesN 1)) [Arg.positional (Expr.binary BinaryOp.add (Expr.call (Expr.typeName (Ty.uint 8)) [Arg.positional (Expr.literal (Literal.number "255"))]) (Expr.call (Expr.typeName (Ty.uint 8)) [Arg.positional (Expr.literal (Literal.number "1"))]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "b", ty := Ty.bool, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.ifElse (Expr.ident "b") (Stmt.returnValues (some (Expr.member (Expr.ident "X") "length"))) none, Stmt.returnValues (some (Expr.literal (Literal.number "3")))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end B3 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/B4.lean b/SolidCore/Refinement/Source/B4.lean new file mode 100644 index 00000000..9ef4dff5 --- /dev/null +++ b/SolidCore/Refinement/Source/B4.lean @@ -0,0 +1,58 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b4.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace B4 + +def importedSourceName : String := "scripts/refinement/corpus/b4.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.structDecl + { name := "S", + fields := [{ name := "x", ty := Ty.uint 8 }] }), (ContractItem.function + { kind := FunctionKind.function, + name := some "make", + visibility := some Visibility.internal_, + mutability := StateMutability.pure, + params := [{ name := some "a", ty := Ty.uint 8, location := none }], + returns := [{ name := none, ty := Ty.user ({ segments := ["S"] }), location := some DataLocation.memory }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.typeName (Ty.user ({ segments := ["S"] }))) [Arg.positional (Expr.binary BinaryOp.add (Expr.ident "a") (Expr.literal (Literal.number "1")))]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "a", ty := Ty.uint 8, location := none }], + returns := [{ name := none, ty := Ty.uint 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.unchecked (Stmt.block [Stmt.returnValues (some (Expr.member (Expr.call (Expr.ident "make") [Arg.positional (Expr.ident "a")]) "x"))])]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end B4 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/B5.lean b/SolidCore/Refinement/Source/B5.lean new file mode 100644 index 00000000..7803a3cd --- /dev/null +++ b/SolidCore/Refinement/Source/B5.lean @@ -0,0 +1,62 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b5.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace B5 + +def importedSourceName : String := "scripts/refinement/corpus/b5.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "v", + ty := Ty.array (Ty.uint 8) (none), + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.function + { kind := FunctionKind.function, + name := some "push", + visibility := some Visibility.internal_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.member (Expr.ident "v") "push") [Arg.positional (Expr.literal (Literal.number "7"))]), Stmt.returnValues (some (Expr.literal (Literal.number "1")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "b", ty := Ty.bool, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.unary UnaryOp.delete (Expr.ident "v")), Stmt.ifElse (Expr.ident "b") (Stmt.block [Stmt.varDecl [{ name := some "c", ty := Ty.array (Ty.uint 8) (none), location := some DataLocation.memory }, { name := some "m", ty := Ty.uint 8, location := none }] (some (Expr.tuple [TupleItem.value (Expr.ident "v"), TupleItem.value (Expr.call (Expr.ident "push") [])])), Stmt.returnValues (some (Expr.binary BinaryOp.add (Expr.member (Expr.ident "c") "length") (Expr.ident "m")))]) none, Stmt.returnValues (some (Expr.member (Expr.ident "v") "length"))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end B5 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/B6.lean b/SolidCore/Refinement/Source/B6.lean new file mode 100644 index 00000000..b8c1caec --- /dev/null +++ b/SolidCore/Refinement/Source/B6.lean @@ -0,0 +1,64 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b6.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace B6 + +def importedSourceName : String := "scripts/refinement/corpus/b6.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.structDecl + { name := "S", + fields := [{ name := "a", ty := Ty.array (Ty.uint 8) (none) }, { name := "m", ty := Ty.uint 8 }] }), (ContractItem.stateVar + { name := "v", + ty := Ty.array (Ty.uint 8) (none), + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.function + { kind := FunctionKind.function, + name := some "push", + visibility := some Visibility.internal_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.member (Expr.ident "v") "push") [Arg.positional (Expr.literal (Literal.number "7"))]), Stmt.returnValues (some (Expr.literal (Literal.number "1")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "b", ty := Ty.bool, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.unary UnaryOp.delete (Expr.ident "v")), Stmt.ifElse (Expr.ident "b") (Stmt.block [Stmt.varDecl [{ name := some "s", ty := Ty.user ({ segments := ["S"] }), location := some DataLocation.memory }] (some (Expr.call (Expr.typeName (Ty.user ({ segments := ["S"] }))) [Arg.positional (Expr.ident "v"), Arg.positional (Expr.call (Expr.ident "push") [])])), Stmt.returnValues (some (Expr.binary BinaryOp.add (Expr.member (Expr.member (Expr.ident "s") "a") "length") (Expr.member (Expr.ident "s") "m")))]) none, Stmt.returnValues (some (Expr.member (Expr.ident "v") "length"))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end B6 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/B7.lean b/SolidCore/Refinement/Source/B7.lean new file mode 100644 index 00000000..da29b689 --- /dev/null +++ b/SolidCore/Refinement/Source/B7.lean @@ -0,0 +1,72 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/b7.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace B7 + +def importedSourceName : String := "scripts/refinement/corpus/b7.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "v", + ty := Ty.array (Ty.uint 8) (none), + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.function + { kind := FunctionKind.function, + name := some "push", + visibility := some Visibility.internal_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.member (Expr.ident "v") "push") [Arg.positional (Expr.literal (Literal.number "7"))]), Stmt.returnValues (some (Expr.literal (Literal.number "1")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "pair", + visibility := some Visibility.internal_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.array (Ty.uint 8) (none), location := some DataLocation.memory }, { name := none, ty := Ty.uint 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.tuple [TupleItem.value (Expr.ident "v"), TupleItem.value (Expr.call (Expr.ident "push") [])]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "b", ty := Ty.bool, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.unary UnaryOp.delete (Expr.ident "v")), Stmt.ifElse (Expr.ident "b") (Stmt.block [Stmt.varDecl [{ name := some "c", ty := Ty.array (Ty.uint 8) (none), location := some DataLocation.memory }, { name := some "m", ty := Ty.uint 8, location := none }] (some (Expr.call (Expr.ident "pair") [])), Stmt.returnValues (some (Expr.binary BinaryOp.add (Expr.member (Expr.ident "c") "length") (Expr.ident "m")))]) none, Stmt.returnValues (some (Expr.member (Expr.ident "v") "length"))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end B7 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/Bank.lean b/SolidCore/Refinement/Source/Bank.lean new file mode 100644 index 00000000..47cb8489 --- /dev/null +++ b/SolidCore/Refinement/Source/Bank.lean @@ -0,0 +1,91 @@ +-- Generated from scripts/refinement/bank/bank.sol with solc 0.8.35 the way scripts/refinement/gen.sh writes Source/NAME.lean. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace Bank + +def importedSourceName : String := "scripts/refinement/bank/bank.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Bank" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "balances", + ty := Ty.mapping (Ty.address false) (Ty.uint 256), + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "total", + ty := Ty.uint 256, + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.eventDecl + { name := "Deposit", + params := [{ name := some "who", ty := Ty.address false, indexed := true }, { name := some "amount", ty := Ty.uint 256, indexed := false }], + anonymous := false }), (ContractItem.function + { kind := FunctionKind.function, + name := some "credit", + visibility := some Visibility.internal_, + mutability := StateMutability.nonpayable, + params := [{ name := some "who", ty := Ty.address false, location := none }, { name := some "amount", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.index (Expr.ident "balances") (Expr.ident "who")) AssignOp.addAssign (Expr.ident "amount")), Stmt.expr (Expr.assign (Expr.ident "total") AssignOp.addAssign (Expr.ident "amount")), Stmt.returnValues (some (Expr.index (Expr.ident "balances") (Expr.ident "who")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "deposit", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "amount", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.varDecl [{ name := some "b", ty := Ty.uint 256, location := none }] (some (Expr.call (Expr.ident "credit") [Arg.positional (Expr.member (Expr.ident "msg") "sender"), Arg.positional (Expr.ident "amount")])), Stmt.emitEvent (Expr.call (Expr.ident "Deposit") [Arg.positional (Expr.member (Expr.ident "msg") "sender"), Arg.positional (Expr.ident "amount")]), Stmt.returnValues (some (Expr.ident "b"))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "depositFor", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "who", ty := Ty.address false, location := none }, { name := some "amount", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.ident "credit") [Arg.positional (Expr.ident "who"), Arg.positional (Expr.ident "amount")]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "balanceOf", + visibility := some Visibility.external_, + mutability := StateMutability.view, + params := [{ name := some "who", ty := Ty.address false, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.index (Expr.ident "balances") (Expr.ident "who")))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end Bank +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/C1.lean b/SolidCore/Refinement/Source/C1.lean new file mode 100644 index 00000000..b42f3c50 --- /dev/null +++ b/SolidCore/Refinement/Source/C1.lean @@ -0,0 +1,46 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c1.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace C1 + +def importedSourceName : String := "scripts/refinement/corpus/c1.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "x", ty := Ty.uint 8, location := none }], + returns := [{ name := none, ty := Ty.uint 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.binary BinaryOp.add (Expr.binary BinaryOp.mul (Expr.ident "x") (Expr.literal (Literal.number "3"))) (Expr.literal (Literal.number "1"))))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end C1 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/C10.lean b/SolidCore/Refinement/Source/C10.lean new file mode 100644 index 00000000..077c87b7 --- /dev/null +++ b/SolidCore/Refinement/Source/C10.lean @@ -0,0 +1,46 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c10.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace C10 + +def importedSourceName : String := "scripts/refinement/corpus/c10.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "c", ty := Ty.uint 8, location := none }], + returns := [{ name := none, ty := Ty.bytesN 32, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.typeName (Ty.bytesN 32)) [Arg.positional (Expr.binary BinaryOp.shr (Expr.call (Expr.typeName (Ty.bytesN 2)) [Arg.positional (Expr.literal (Literal.number "0x1234"))]) (Expr.ident "c"))]))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end C10 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/C11.lean b/SolidCore/Refinement/Source/C11.lean new file mode 100644 index 00000000..d80fc625 --- /dev/null +++ b/SolidCore/Refinement/Source/C11.lean @@ -0,0 +1,48 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c11.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace C11 + +def importedSourceName : String := "scripts/refinement/corpus/c11.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "x", ty := Ty.uint 8, location := none }], + returns := [{ name := none, ty := Ty.user ({ segments := ["U"] }), location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.member (Expr.typeName (Ty.user ({ segments := ["U"] }))) "wrap") [Arg.positional (Expr.call (Expr.typeName (Ty.int 8)) [Arg.positional (Expr.ident "x")])]))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.freeUserValueType + { name := "U", + underlying := Ty.int 8 }, SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end C11 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/C2.lean b/SolidCore/Refinement/Source/C2.lean new file mode 100644 index 00000000..33056a54 --- /dev/null +++ b/SolidCore/Refinement/Source/C2.lean @@ -0,0 +1,46 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c2.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace C2 + +def importedSourceName : String := "scripts/refinement/corpus/c2.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "a", ty := Ty.int 8, location := none }, { name := some "b", ty := Ty.int 8, location := none }], + returns := [{ name := none, ty := Ty.int 8, location := none }, { name := none, ty := Ty.int 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.tuple [TupleItem.value (Expr.binary BinaryOp.div (Expr.ident "a") (Expr.ident "b")), TupleItem.value (Expr.binary BinaryOp.mod (Expr.ident "a") (Expr.ident "b"))]))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end C2 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/C3.lean b/SolidCore/Refinement/Source/C3.lean new file mode 100644 index 00000000..4b284962 --- /dev/null +++ b/SolidCore/Refinement/Source/C3.lean @@ -0,0 +1,46 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c3.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace C3 + +def importedSourceName : String := "scripts/refinement/corpus/c3.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "x", ty := Ty.uint 8, location := none }, { name := some "s", ty := Ty.uint 8, location := none }], + returns := [{ name := none, ty := Ty.uint 8, location := none }, { name := none, ty := Ty.uint 8, location := none }, { name := none, ty := Ty.uint 8, location := none }, { name := none, ty := Ty.int 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.unchecked (Stmt.block [Stmt.returnValues (some (Expr.tuple [TupleItem.value (Expr.binary BinaryOp.shl (Expr.ident "x") (Expr.ident "s")), TupleItem.value (Expr.binary BinaryOp.shr (Expr.ident "x") (Expr.ident "s")), TupleItem.value (Expr.binary BinaryOp.mul (Expr.ident "x") (Expr.ident "x")), TupleItem.value (Expr.binary BinaryOp.shr (Expr.call (Expr.typeName (Ty.int 8)) [Arg.positional (Expr.ident "x")]) (Expr.binary BinaryOp.mod (Expr.ident "s") (Expr.literal (Literal.number "9"))))]))])]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end C3 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/C4.lean b/SolidCore/Refinement/Source/C4.lean new file mode 100644 index 00000000..fdf428fb --- /dev/null +++ b/SolidCore/Refinement/Source/C4.lean @@ -0,0 +1,58 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c4.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace C4 + +def importedSourceName : String := "scripts/refinement/corpus/c4.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "v", + ty := Ty.uint 8, + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "w", + ty := Ty.uint 8, + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := some (Expr.literal (Literal.number "7")) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "add", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "x", ty := Ty.uint 8, location := none }], + returns := [{ name := none, ty := Ty.uint 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "v") AssignOp.addAssign (Expr.ident "x")), Stmt.expr (Expr.assign (Expr.ident "w") AssignOp.bitXorAssign (Expr.ident "x")), Stmt.returnValues (some (Expr.ident "v"))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end C4 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/C5.lean b/SolidCore/Refinement/Source/C5.lean new file mode 100644 index 00000000..8f031e7e --- /dev/null +++ b/SolidCore/Refinement/Source/C5.lean @@ -0,0 +1,52 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c5.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace C5 + +def importedSourceName : String := "scripts/refinement/corpus/c5.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "m", + ty := Ty.mapping (Ty.uint 8) (Ty.uint 16), + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.function + { kind := FunctionKind.function, + name := some "inc", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "k", ty := Ty.uint 8, location := none }], + returns := [{ name := none, ty := Ty.uint 16, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.index (Expr.ident "m") (Expr.ident "k")) AssignOp.addAssign (Expr.literal (Literal.number "300"))), Stmt.expr (Expr.assign (Expr.index (Expr.ident "m") (Expr.binary BinaryOp.bitXor (Expr.ident "k") (Expr.literal (Literal.number "1")))) AssignOp.assign (Expr.ident "k")), Stmt.returnValues (some (Expr.index (Expr.ident "m") (Expr.ident "k")))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end C5 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/C6.lean b/SolidCore/Refinement/Source/C6.lean new file mode 100644 index 00000000..85679afa --- /dev/null +++ b/SolidCore/Refinement/Source/C6.lean @@ -0,0 +1,46 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c6.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace C6 + +def importedSourceName : String := "scripts/refinement/corpus/c6.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "sum", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "n", ty := Ty.uint 8, location := none }], + returns := [{ name := some "s", ty := Ty.uint 256, location := none }, { name := some "c", ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.forLoop (some (Stmt.varDecl [{ name := some "i", ty := Ty.uint 256, location := none }] (some (Expr.literal (Literal.number "0"))))) (some (Expr.binary BinaryOp.lt (Expr.ident "i") (Expr.ident "n"))) (some (Expr.unary UnaryOp.postIncrement (Expr.ident "i"))) (Stmt.block [Stmt.ifElse (Expr.binary BinaryOp.eq (Expr.binary BinaryOp.mod (Expr.ident "i") (Expr.literal (Literal.number "7"))) (Expr.literal (Literal.number "3"))) (Stmt.continue) none, Stmt.expr (Expr.assign (Expr.ident "s") AssignOp.addAssign (Expr.binary BinaryOp.mul (Expr.ident "i") (Expr.ident "i"))), Stmt.expr (Expr.unary UnaryOp.postIncrement (Expr.ident "c")), Stmt.ifElse (Expr.binary BinaryOp.gt (Expr.ident "s") (Expr.literal (Literal.number "100000"))) (Stmt.break) none])]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end C6 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/C7.lean b/SolidCore/Refinement/Source/C7.lean new file mode 100644 index 00000000..5ab7880d --- /dev/null +++ b/SolidCore/Refinement/Source/C7.lean @@ -0,0 +1,48 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c7.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace C7 + +def importedSourceName : String := "scripts/refinement/corpus/c7.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.enumDecl + { name := "E", + cases := ["A", "B", "C"] }), (ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "e", ty := Ty.user ({ segments := ["E"] }), location := none }, { name := some "b", ty := Ty.bool, location := none }], + returns := [{ name := none, ty := Ty.uint 8, location := none }, { name := none, ty := Ty.bool, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.tuple [TupleItem.value (Expr.binary BinaryOp.mul (Expr.call (Expr.typeName (Ty.uint 8)) [Arg.positional (Expr.ident "e")]) (Expr.literal (Literal.number "2"))), TupleItem.value (Expr.binary BinaryOp.ne (Expr.ident "b") (Expr.binary BinaryOp.eq (Expr.ident "e") (Expr.member (Expr.typeName (Ty.user ({ segments := ["E"] }))) "B")))]))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end C7 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/C8.lean b/SolidCore/Refinement/Source/C8.lean new file mode 100644 index 00000000..6337a318 --- /dev/null +++ b/SolidCore/Refinement/Source/C8.lean @@ -0,0 +1,61 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c8.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace C8 + +def importedSourceName : String := "scripts/refinement/corpus/c8.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "fib", + visibility := some Visibility.internal_, + mutability := StateMutability.pure, + params := [{ name := some "n", ty := Ty.uint 8, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.ternary (Expr.binary BinaryOp.lt (Expr.ident "n") (Expr.literal (Literal.number "2"))) (Expr.ident "n") (Expr.binary BinaryOp.add (Expr.call (Expr.ident "fib") [Arg.positional (Expr.binary BinaryOp.sub (Expr.ident "n") (Expr.literal (Literal.number "1")))]) (Expr.call (Expr.ident "fib") [Arg.positional (Expr.binary BinaryOp.sub (Expr.ident "n") (Expr.literal (Literal.number "2")))]))))]) }), ContractItem.modifierDecl + { name := "m" + params := [{ name := some "x", ty := Ty.uint 8, location := none }] + virtual := false + override? := none + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.ident "require") [Arg.positional (Expr.binary BinaryOp.lt (Expr.ident "x") (Expr.literal (Literal.number "25"))), Arg.positional (Expr.literal (Literal.string "big"))]), Stmt.modifierPlaceholder]) }, (ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "x", ty := Ty.uint 8, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [{ target := { segments := ["m"] }, args := [Arg.positional (Expr.ident "x")], hasArgList := true }], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.ident "fib") [Arg.positional (Expr.binary BinaryOp.mod (Expr.ident "x") (Expr.literal (Literal.number "13")))]))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end C8 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/C9.lean b/SolidCore/Refinement/Source/C9.lean new file mode 100644 index 00000000..7dda0c73 --- /dev/null +++ b/SolidCore/Refinement/Source/C9.lean @@ -0,0 +1,62 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/c9.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace C9 + +def importedSourceName : String := "scripts/refinement/corpus/c9.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "a", + ty := Ty.array (Ty.uint 256) (none), + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.function + { kind := FunctionKind.function, + name := some "g", + visibility := some Visibility.internal_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.member (Expr.ident "a") "push") [Arg.positional (Expr.literal (Literal.number "5"))]), Stmt.returnValues (some (Expr.literal (Literal.number "1")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "x", ty := Ty.uint 8, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }, { name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.member (Expr.ident "a") "push") [Arg.positional (Expr.ident "x")]), Stmt.varDecl [{ name := some "m", ty := Ty.array (Ty.uint 256) (none), location := some DataLocation.memory }] (some (Expr.newExpr (Ty.array (Ty.uint 256) (none)) [Arg.positional (Expr.literal (Literal.number "3"))])), Stmt.expr (Expr.assign (Expr.index (Expr.ident "m") (Expr.call (Expr.ident "g") [])) AssignOp.assign (Expr.ident "x")), Stmt.returnValues (some (Expr.tuple [TupleItem.value (Expr.member (Expr.ident "a") "length"), TupleItem.value (Expr.index (Expr.ident "m") (Expr.literal (Literal.number "1")))]))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end C9 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/D1.lean b/SolidCore/Refinement/Source/D1.lean new file mode 100644 index 00000000..84f03650 --- /dev/null +++ b/SolidCore/Refinement/Source/D1.lean @@ -0,0 +1,46 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d1.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace D1 + +def importedSourceName : String := "scripts/refinement/corpus/d1.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "b", ty := Ty.bytes, location := some DataLocation.calldata }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.member (Expr.ident "b") "length"))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end D1 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/D2.lean b/SolidCore/Refinement/Source/D2.lean new file mode 100644 index 00000000..581824b6 --- /dev/null +++ b/SolidCore/Refinement/Source/D2.lean @@ -0,0 +1,46 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d2.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace D2 + +def importedSourceName : String := "scripts/refinement/corpus/d2.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "a", ty := Ty.array (Ty.uint 8) (none), location := some DataLocation.calldata }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.ternary (Expr.binary BinaryOp.eq (Expr.member (Expr.ident "a") "length") (Expr.literal (Literal.number "0"))) (Expr.literal (Literal.number "0")) (Expr.index (Expr.ident "a") (Expr.literal (Literal.number "0")))))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end D2 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/D3.lean b/SolidCore/Refinement/Source/D3.lean new file mode 100644 index 00000000..482a066c --- /dev/null +++ b/SolidCore/Refinement/Source/D3.lean @@ -0,0 +1,48 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d3.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace D3 + +def importedSourceName : String := "scripts/refinement/corpus/d3.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.structDecl + { name := "S", + fields := [{ name := "x", ty := Ty.uint 8 }, { name := "y", ty := Ty.bool }] }), (ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "s", ty := Ty.user ({ segments := ["S"] }), location := some DataLocation.calldata }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.ternary (Expr.member (Expr.ident "s") "y") (Expr.member (Expr.ident "s") "x") (Expr.literal (Literal.number "3"))))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end D3 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/D4.lean b/SolidCore/Refinement/Source/D4.lean new file mode 100644 index 00000000..72015360 --- /dev/null +++ b/SolidCore/Refinement/Source/D4.lean @@ -0,0 +1,48 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/d4.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace D4 + +def importedSourceName : String := "scripts/refinement/corpus/d4.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.structDecl + { name := "S", + fields := [{ name := "x", ty := Ty.uint 8 }, { name := "y", ty := Ty.bool }] }), (ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "s", ty := Ty.user ({ segments := ["S"] }), location := some DataLocation.calldata }], + returns := [{ name := none, ty := Ty.user ({ segments := ["S"] }), location := some DataLocation.calldata }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.ident "s"))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end D4 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/EventDyn.lean b/SolidCore/Refinement/Source/EventDyn.lean new file mode 100644 index 00000000..e19dfc66 --- /dev/null +++ b/SolidCore/Refinement/Source/EventDyn.lean @@ -0,0 +1,49 @@ +-- Generated from scripts/refinement/mem/event_dyn.sol with solc 0.8.35 the way scripts/refinement/gen.sh writes Source/NAME.lean. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace EventDyn + +def importedSourceName : String := "scripts/refinement/mem/event_dyn.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "EventDyn" + abstract := false + bases := [] + items := [(ContractItem.eventDecl + { name := "Note", + params := [{ name := some "who", ty := Ty.address false, indexed := true }, { name := some "data", ty := Ty.bytes, indexed := false }], + anonymous := false }), (ContractItem.function + { kind := FunctionKind.function, + name := some "note", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "data", ty := Ty.bytes, location := some DataLocation.calldata }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.emitEvent (Expr.call (Expr.ident "Note") [Arg.positional (Expr.member (Expr.ident "msg") "sender"), Arg.positional (Expr.ident "data")])]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.0", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end EventDyn +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/EventWords.lean b/SolidCore/Refinement/Source/EventWords.lean new file mode 100644 index 00000000..f6f19d4c --- /dev/null +++ b/SolidCore/Refinement/Source/EventWords.lean @@ -0,0 +1,49 @@ +-- Generated from scripts/refinement/mem/event_words.sol with solc 0.8.35 the way scripts/refinement/gen.sh writes Source/NAME.lean. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace EventWords + +def importedSourceName : String := "scripts/refinement/mem/event_words.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "EventWords" + abstract := false + bases := [] + items := [(ContractItem.eventDecl + { name := "Swap", + params := [{ name := some "sender", ty := Ty.address false, indexed := true }, { name := some "amount0In", ty := Ty.uint 256, indexed := false }, { name := some "amount1In", ty := Ty.uint 256, indexed := false }, { name := some "amount0Out", ty := Ty.uint 256, indexed := false }, { name := some "amount1Out", ty := Ty.uint 256, indexed := false }, { name := some "to", ty := Ty.address false, indexed := true }], + anonymous := false }), (ContractItem.function + { kind := FunctionKind.function, + name := some "swap", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "a0", ty := Ty.uint 256, location := none }, { name := some "a1", ty := Ty.uint 256, location := none }, { name := some "b0", ty := Ty.uint 256, location := none }, { name := some "b1", ty := Ty.uint 256, location := none }, { name := some "to", ty := Ty.address false, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.emitEvent (Expr.call (Expr.ident "Swap") [Arg.positional (Expr.member (Expr.ident "msg") "sender"), Arg.positional (Expr.ident "a0"), Arg.positional (Expr.ident "a1"), Arg.positional (Expr.ident "b0"), Arg.positional (Expr.ident "b1"), Arg.positional (Expr.ident "to")])]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.0", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end EventWords +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/Events.lean b/SolidCore/Refinement/Source/Events.lean new file mode 100644 index 00000000..dcbe8007 --- /dev/null +++ b/SolidCore/Refinement/Source/Events.lean @@ -0,0 +1,49 @@ +-- Generated from scripts/refinement/events/events.sol with solc 0.8.35 the way scripts/refinement/gen.sh writes Source/NAME.lean. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace Events + +def importedSourceName : String := "scripts/refinement/events/events.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Events" + abstract := false + bases := [] + items := [(ContractItem.eventDecl + { name := "Transfer", + params := [{ name := some "from", ty := Ty.address false, indexed := true }, { name := some "id", ty := Ty.uint 256, indexed := true }, { name := some "value", ty := Ty.uint 256, indexed := false }], + anonymous := false }), (ContractItem.function + { kind := FunctionKind.function, + name := some "transfer", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "id", ty := Ty.uint 256, location := none }, { name := some "value", ty := Ty.uint 256, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.emitEvent (Expr.call (Expr.ident "Transfer") [Arg.positional (Expr.member (Expr.ident "msg") "sender"), Arg.positional (Expr.ident "id"), Arg.positional (Expr.ident "value")])]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end Events +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/KeccakMem.lean b/SolidCore/Refinement/Source/KeccakMem.lean new file mode 100644 index 00000000..020e56b9 --- /dev/null +++ b/SolidCore/Refinement/Source/KeccakMem.lean @@ -0,0 +1,46 @@ +-- Generated from scripts/refinement/mem/keccak_mem.sol with solc 0.8.35 the way scripts/refinement/gen.sh writes Source/NAME.lean. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace KeccakMem + +def importedSourceName : String := "scripts/refinement/mem/keccak_mem.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "KeccakMem" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "salt", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "token0", ty := Ty.address false, location := none }, { name := some "token1", ty := Ty.address false, location := none }], + returns := [{ name := none, ty := Ty.bytesN 32, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.ident "keccak256") [Arg.positional (Expr.call (Expr.member (Expr.ident "abi") "encodePacked") [Arg.positional (Expr.ident "token0"), Arg.positional (Expr.ident "token1")])]))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.0", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end KeccakMem +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/MemFmp.lean b/SolidCore/Refinement/Source/MemFmp.lean new file mode 100644 index 00000000..da1b3fe4 --- /dev/null +++ b/SolidCore/Refinement/Source/MemFmp.lean @@ -0,0 +1,46 @@ +-- Generated from scripts/refinement/mem/mem_fmp.sol with solc 0.8.35 the way scripts/refinement/gen.sh writes Source/NAME.lean. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace MemFmp + +def importedSourceName : String := "scripts/refinement/mem/mem_fmp.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "MemFmp" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "pair", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "a", ty := Ty.uint 256, location := none }, { name := some "b", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.varDecl [{ name := some "x", ty := Ty.array (Ty.uint 256) (some 2), location := some DataLocation.memory }] none, Stmt.expr (Expr.assign (Expr.index (Expr.ident "x") (Expr.literal (Literal.number "0"))) AssignOp.assign (Expr.ident "a")), Stmt.expr (Expr.assign (Expr.index (Expr.ident "x") (Expr.literal (Literal.number "1"))) AssignOp.assign (Expr.ident "b")), Stmt.returnValues (some (Expr.binary BinaryOp.bitXor (Expr.index (Expr.ident "x") (Expr.literal (Literal.number "0"))) (Expr.index (Expr.ident "x") (Expr.literal (Literal.number "1")))))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.0", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end MemFmp +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/MulX.lean b/SolidCore/Refinement/Source/MulX.lean new file mode 100644 index 00000000..045b5b8a --- /dev/null +++ b/SolidCore/Refinement/Source/MulX.lean @@ -0,0 +1,74 @@ +-- Generated from scripts/refinement/mulx/mul.sol with solc 0.8.35 the way scripts/refinement/gen.sh writes Source/NAME.lean. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace MulX + +def importedSourceName : String := "scripts/refinement/mulx/mul.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "x8", + ty := Ty.uint 8, + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "y16", + ty := Ty.uint 16, + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := some (Expr.literal (Literal.number "3")) }), (ContractItem.stateVar + { name := "z", + ty := Ty.uint 256, + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.function + { kind := FunctionKind.function, + name := some "m", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "a", ty := Ty.uint 8, location := none }, { name := some "b", ty := Ty.uint 16, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "x8") AssignOp.mulAssign (Expr.ident "a")), Stmt.expr (Expr.assign (Expr.ident "y16") AssignOp.mulAssign (Expr.ident "b"))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "n", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "a", ty := Ty.uint 8, location := none }, { name := some "b", ty := Ty.uint 16, location := none }, { name := some "c", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "z") AssignOp.assign (Expr.binary BinaryOp.mul (Expr.binary BinaryOp.mul (Expr.call (Expr.typeName (Ty.uint 256)) [Arg.positional (Expr.ident "a")]) (Expr.ident "b")) (Expr.ident "c"))), Stmt.returnValues (some (Expr.ident "z"))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end MulX +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/RetDecode.lean b/SolidCore/Refinement/Source/RetDecode.lean new file mode 100644 index 00000000..6930c25f --- /dev/null +++ b/SolidCore/Refinement/Source/RetDecode.lean @@ -0,0 +1,63 @@ +-- Generated from scripts/refinement/mem/ret_decode.sol with solc 0.8.35 the way scripts/refinement/gen.sh writes Source/NAME.lean. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace RetDecode + +def importedSourceName : String := "scripts/refinement/mem/ret_decode.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.interface + name := "IToken" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "balanceOf", + visibility := some Visibility.external_, + mutability := StateMutability.view, + params := [{ name := some "owner", ty := Ty.address false, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := none })] } + +def importedContractDecl1 : ContractDecl := +{ kind := ContractKind.contract + name := "RetDecode" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "held", + visibility := some Visibility.external_, + mutability := StateMutability.view, + params := [{ name := some "token", ty := Ty.user ({ segments := ["IToken"] }), location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.member (Expr.ident "token") "balanceOf") [Arg.positional (Expr.call (Expr.typeName (Ty.address false)) [Arg.positional (Expr.ident "this")])]))]) })] } + +def importedContract : ContractDecl := + importedContractDecl1 + +def importedContracts : List ContractDecl := + [importedContractDecl0, importedContractDecl1] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.0", SourceItem.contract importedContractDecl0, SourceItem.contract importedContractDecl1] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end RetDecode +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/SafeTransfer.lean b/SolidCore/Refinement/Source/SafeTransfer.lean new file mode 100644 index 00000000..ed0bb0fd --- /dev/null +++ b/SolidCore/Refinement/Source/SafeTransfer.lean @@ -0,0 +1,52 @@ +-- Generated from scripts/refinement/mem/safe_transfer.sol with solc 0.8.35 the way scripts/refinement/gen.sh writes Source/NAME.lean. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace SafeTransfer + +def importedSourceName : String := "scripts/refinement/mem/safe_transfer.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "SafeTransfer" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "SELECTOR", + ty := Ty.bytesN 4, + visibility := some Visibility.private_, + mutability := VarMutability.constant, + override? := none, + init := some (Expr.call (Expr.typeName (Ty.bytesN 4)) [Arg.positional (Expr.call (Expr.ident "keccak256") [Arg.positional (Expr.call (Expr.typeName (Ty.bytes)) [Arg.positional (Expr.literal (Literal.string "transfer(address,uint256)"))])])]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "pay", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "token", ty := Ty.address false, location := none }, { name := some "to", ty := Ty.address false, location := none }, { name := some "value", ty := Ty.uint 256, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.varDecl [{ name := some "success", ty := Ty.bool, location := none }, { name := some "data", ty := Ty.bytes, location := some DataLocation.memory }] (some (Expr.call (Expr.member (Expr.ident "token") "call") [Arg.positional (Expr.call (Expr.member (Expr.ident "abi") "encodeWithSelector") [Arg.positional (Expr.ident "SELECTOR"), Arg.positional (Expr.ident "to"), Arg.positional (Expr.ident "value")])])), Stmt.expr (Expr.call (Expr.ident "require") [Arg.positional (Expr.binary BinaryOp.boolAnd (Expr.ident "success") (Expr.binary BinaryOp.boolOr (Expr.binary BinaryOp.eq (Expr.member (Expr.ident "data") "length") (Expr.literal (Literal.number "0"))) (Expr.call (Expr.member (Expr.ident "abi") "decode") [Arg.positional (Expr.ident "data"), Arg.positional (Expr.tuple [TupleItem.value (Expr.typeName (Ty.bool))])]))), Arg.positional (Expr.literal (Literal.string "TRANSFER_FAILED"))])]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.0", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end SafeTransfer +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/TryCatch.lean b/SolidCore/Refinement/Source/TryCatch.lean new file mode 100644 index 00000000..f4a122a1 --- /dev/null +++ b/SolidCore/Refinement/Source/TryCatch.lean @@ -0,0 +1,63 @@ +-- Generated from scripts/refinement/mem/try_catch.sol with solc 0.8.35 the way scripts/refinement/gen.sh writes Source/NAME.lean. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace TryCatch + +def importedSourceName : String := "scripts/refinement/mem/try_catch.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.interface + name := "IPrice" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "price", + visibility := some Visibility.external_, + mutability := StateMutability.view, + params := [], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := none })] } + +def importedContractDecl1 : ContractDecl := +{ kind := ContractKind.contract + name := "TryCatch" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "priceOr", + visibility := some Visibility.external_, + mutability := StateMutability.view, + params := [{ name := some "o", ty := Ty.user ({ segments := ["IPrice"] }), location := none }, { name := some "dflt", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.tryCatchReturns (Expr.call (Expr.member (Expr.ident "o") "price") []) [{ name := some "p", ty := Ty.uint 256, location := none }] (Stmt.block [Stmt.returnValues (some (Expr.ident "p"))]) [CatchClause.clause none [] (Stmt.block [Stmt.returnValues (some (Expr.ident "dflt"))])]]) })] } + +def importedContract : ContractDecl := + importedContractDecl1 + +def importedContracts : List ContractDecl := + [importedContractDecl0, importedContractDecl1] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.0", SourceItem.contract importedContractDecl0, SourceItem.contract importedContractDecl1] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end TryCatch +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/W1.lean b/SolidCore/Refinement/Source/W1.lean new file mode 100644 index 00000000..afa9abe5 --- /dev/null +++ b/SolidCore/Refinement/Source/W1.lean @@ -0,0 +1,46 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/w1.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace W1 + +def importedSourceName : String := "scripts/refinement/corpus/w1.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "x", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.binary BinaryOp.add (Expr.ident "x") (Expr.literal (Literal.number "1"))))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end W1 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/W2.lean b/SolidCore/Refinement/Source/W2.lean new file mode 100644 index 00000000..6120a333 --- /dev/null +++ b/SolidCore/Refinement/Source/W2.lean @@ -0,0 +1,46 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/w2.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace W2 + +def importedSourceName : String := "scripts/refinement/corpus/w2.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "a", ty := Ty.uint 256, location := none }, { name := some "b", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.ternary (Expr.binary BinaryOp.gt (Expr.ident "a") (Expr.ident "b")) (Expr.binary BinaryOp.sub (Expr.ident "a") (Expr.ident "b")) (Expr.binary BinaryOp.sub (Expr.ident "b") (Expr.ident "a"))))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end W2 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/W3.lean b/SolidCore/Refinement/Source/W3.lean new file mode 100644 index 00000000..8d3105b8 --- /dev/null +++ b/SolidCore/Refinement/Source/W3.lean @@ -0,0 +1,46 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/w3.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace W3 + +def importedSourceName : String := "scripts/refinement/corpus/w3.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "a", ty := Ty.address false, location := none }], + returns := [{ name := none, ty := Ty.uint 160, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.binary BinaryOp.bitXor (Expr.call (Expr.typeName (Ty.uint 160)) [Arg.positional (Expr.ident "a")]) (Expr.literal (Literal.number "1"))))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end W3 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/W4.lean b/SolidCore/Refinement/Source/W4.lean new file mode 100644 index 00000000..84606202 --- /dev/null +++ b/SolidCore/Refinement/Source/W4.lean @@ -0,0 +1,52 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/w4.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace W4 + +def importedSourceName : String := "scripts/refinement/corpus/w4.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "x", + ty := Ty.uint 256, + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.function + { kind := FunctionKind.function, + name := some "set", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [{ name := some "v", ty := Ty.uint 256, location := none }], + returns := [], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "x") AssignOp.assign (Expr.ident "v"))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end W4 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/Source/W5.lean b/SolidCore/Refinement/Source/W5.lean new file mode 100644 index 00000000..4239a04f --- /dev/null +++ b/SolidCore/Refinement/Source/W5.lean @@ -0,0 +1,46 @@ +-- Generated by scripts/refinement/gen.sh from scripts/refinement/corpus/w5.sol with solc 0.8.35. Do not edit. + +import SolidCore.Solidity.Checked + +open SolidCore.Solidity + +namespace SolidCore +namespace Refinement +namespace Source +namespace W5 + +def importedSourceName : String := "scripts/refinement/corpus/w5.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "Main" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "a", ty := Ty.uint 256, location := none }, { name := some "b", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.binary BinaryOp.add (Expr.ident "a") (Expr.ident "b")))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end W5 +end Source +end Refinement +end SolidCore diff --git a/SolidCore/Refinement/SourceOracle.lean b/SolidCore/Refinement/SourceOracle.lean new file mode 100644 index 00000000..663c4f15 --- /dev/null +++ b/SolidCore/Refinement/SourceOracle.lean @@ -0,0 +1,356 @@ +import SolidCore.Refinement.Compose +import SolarTV.Machine + +/-! +# SolidCore's source semantics under a call oracle + +`Source.run` folds every function body's interaction tree with the closed responder +(`SolI.runWith []`): an external call that is not a precompile has no answer, so the fold fails +and the call shows nothing (`none`). Its context also knows no other account's code, so a +high-level call (`IERC20(token).balanceOf(...)`) reverts at solc's `extcodesize` guard before it is made. +A contract that calls out (UniswapV2's pair reading `balanceOf` and transferring tokens) then has +no successful behaviour in SolidCore, and a triple about it holds vacuously. + +This module runs the source semantics in a world `W : World`, the source side of the call oracle the +MIR and EVM IR stages run under (`SolarTV.Machine.Oracle`): + +* `Ans`: given the exchanges so far and a query, its answer, or `none` for no answer; + `foldAns` folds an interaction tree, answering each query by `ans` from its history; +* `World`: an answerer and the other accounts' code; +* `Source.runIn W fuel` and `solidCoreIn W fuel : Sem`: `Source.run` with the context's account code + `W.codes` and every function body folded by `W.ans` (the dispatcher, constructor, decoding and + encoding are `Source.run`'s); +* `World.closed`: the closed responder and the contract's own context, so that + `Source.runIn World.closed = Source.run` (`runIn_closed`) and + `solidCoreIn World.closed = solidCore` (`solidCoreIn_closed`): every theorem about `Source.run` is + the closed-world instance; +* `World.Open`: a world of the open world, which answers every external call and creation and + keeps SolidCore's in-semantics precompile answers and resource defaults; +* `CallsAgree o W`: the oracle hypothesis that connects `W` to a MIR oracle `o`. + +`Verify/SourceOracle.lean` composes the stages to the bytecode under a world, with `CallsAgree o W` +a premise of the end-to-end theorem. +-/ + +namespace SolidCore.Refinement + +open SolidCore.Solidity SolidCore.Solidity.Source EvmCompiler.Simulation + +/-- A source call oracle: the answer to a query given the exchanges before it, or `none` when it +has no answer (the fold then fails). -/ +abbrev Ans := List Interaction.Exchange → (q : Query) → Option (Answer q) + +/-- Fold an interaction tree under `ans`, from the history `h`: `none` when a query has no answer +or the tree ends in a failure (a revert caught into a value never reaches here; out of fuel). -/ +def foldAns {α : Type} (ans : Ans) : List Interaction.Exchange → SolI α → Option α + | _, .done (.ok a) => some a + | _, .done (.error _) => none + | h, .request q k => + match ans h q with + | some a => foldAns ans (h ++ [⟨q, a⟩]) (k a) + | none => none + +/-- The closed responder of `Source.run` (`SolI.runWith []`): precompile calls answered in the +semantics, resources by their default, no other external call or creation answered. -/ +def closedAns : Ans := fun _ q => + match q with + | .resource r => some (Query.defaultAnswer (.resource r)) + | .external world (.call request) => precompileAnswerCall? world request + | .external _ (.create _) => none + +theorem answerCall?_nil (world : SolidCore.Solidity.Shared.OpenWorld) (request : CallRequest) : + ScriptedResponder.answerCall? [] world request = none := by + simp [ScriptedResponder.answerCall?, ScriptedResponder.callRows] + +theorem answerCreate?_nil (world : SolidCore.Solidity.Shared.OpenWorld) (request : CreateRequest) : + ScriptedResponder.answerCreate? [] world request = none := by + simp [ScriptedResponder.answerCreate?, ScriptedResponder.createRows] + +/-- Folding under `closedAns` is `Source.run`'s fold under the empty responder. -/ +theorem foldAns_closed {α : Type} (t : SolI α) : ∀ h, + foldAns closedAns h t = (match SolI.runWith [] t with | .ok r => some r | .error _ => none) := by + induction t with + | done r => + intro h + cases r <;> rfl + | request q k ih => + intro h + cases q with + | resource r => + simp only [foldAns, closedAns, SolI.runWith] + exact ih _ _ + | external world req => + cases req with + | call request => + simp only [foldAns, closedAns, SolI.runWith, answerCall?_nil] + cases hp : precompileAnswerCall? world request with + | none => rfl + | some a => exact ih _ _ + | create request => + simp only [foldAns, closedAns, SolI.runWith, answerCreate?_nil] + +/-- The world a source call runs in: the call oracle `ans`, and the code of the other accounts +before the call (`codes`, which SolidCore's existence check before a high-level call reads, as +solc's `extcodesize` guard does); `none` keeps the contract's own context, which knows no other +account's code, so that every high-level call reverts before it reaches `ans`. -/ +structure World where + ans : Ans + codes : Option ByteMap := none + +/-- The closed world of `Source.run`. -/ +def World.closed : World := { ans := closedAns } + +namespace Source + +/-- `FunctionDef.call?` with the body folded by `ans`. -/ +def callAns (ans : Ans) (fuel : Nat) (table : FunctionTable) (context : Context) + (function : FunctionDef) (state : State) (args : List Value) : Option CallResult := + (function.call fuel table context state args).bind fun tree => foldAns ans [] tree + +theorem callAns_closed (fuel : Nat) (table : FunctionTable) (context : Context) + (function : FunctionDef) (state : State) (args : List Value) : + callAns closedAns fuel table context function state args = + function.call? fuel table context state args := by + unfold callAns FunctionDef.call? + cases function.call fuel table context state args with + | none => rfl + | some tree => + simp only [Option.bind_some, foldAns_closed] + cases SolI.runWith [] tree <;> rfl + +end Source + +namespace Source.ABI.Oracle + +open SolidCore.Solidity.Source.ABI + +/-- `ABI.Contract.callCalldataAtFromWithContext?` with the selected function's body folded by +`ans`. The fallback and receive paths are `Source.run`'s. -/ +def callCalldata (ans : Ans) (fuel : Nat) (contract : Contract) (base : Context) (state : State) + (self sender value : SolidCore.Solidity.Source.Word) (calldata : Bytes) : Option AbiCallResult := do + match readSelector? calldata with + | some selector => + match contract.findFunctionBySelector? selector with + | some function => + match decodeFunctionArgs? function (calldata.drop ABI.selectorBytes) with + | Except.ok args => + let context := + Contract.callContextAtWithBase contract base self sender value calldata + if function.acceptsValue value then + match Source.callAns ans fuel contract.table context function state args with + | some (CallResult.returned state' values) => do + let output ← encodeValues? (function.returns.map BindingDecl.ty) values + some { success := true, output, state := state' } + | some (CallResult.reverted state' revert) => do + let output ← Contract.encodeRevertData? contract revert + some { success := false, output, state := state' } + | none => none + else + Contract.rejectedValueCall? contract state + | Except.error revert => Contract.revertedCall? contract state revert + | none => + Contract.callFallbackAtFromWithContext? fuel contract base state self sender value calldata + | none => + Contract.callReceiveOrFallbackAtFromWithContext? fuel contract base state self sender value + calldata + +set_option linter.unusedSimpArgs false in +theorem callCalldata_closed (fuel : Nat) (contract : Contract) (base : Context) (state : State) + (self sender value : SolidCore.Solidity.Source.Word) (calldata : Bytes) : + callCalldata closedAns fuel contract base state self sender value calldata = + Contract.callCalldataAtFromWithContext? fuel contract base state self sender value + calldata := by + unfold callCalldata Contract.callCalldataAtFromWithContext? + simp only [Source.callAns_closed] + cases readSelector? calldata with + | none => rfl + | some selector => + cases contract.findFunctionBySelector? selector with + | none => rfl + | some function => + cases decodeFunctionArgs? function (List.drop ABI.selectorBytes calldata) with + | error revert => rfl + | ok args => + by_cases hv : function.acceptsValue value = true + · simp only [hv, ↓reduceIte] + cases FunctionDef.call? fuel contract.table + (Contract.callContextAtWithBase contract base self sender value calldata) function state + args with + | none => rfl + | some r => cases r <;> rfl + · simp only [hv] + rfl + +end Source.ABI.Oracle + +namespace Source + +/-- `Source.result?` in the world `W`: during the call the other accounts' code is `W.codes`, and +every function body is folded by `W.ans`. The contract was deployed before the call, as +`Source.result?` deploys it, in its own context. -/ +def resultIn? (W : World) (fuel : Nat) (contract : TypeCheck.CheckedContract) (call : Call) : + Option TypeCheck.CoreAbiCallResult := + let base := contract.core.context + let deploy := { base with sender := callerAddress, self := selfAddress, value := call.callvalue } + let context := { deploy with accountCodes := W.codes.getD base.accountCodes } + match TypeCheck.CheckedContract.constructWithContext? fuel contract deploy + State.empty selfAddress 0 [] with + | some (CallResult.returned deployed _) => + let storage := call.storage.foldl + (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) deployed.storage + Source.ABI.Oracle.callCalldata W.ans fuel contract.core context + { deployed with storage := storage } selfAddress callerAddress call.callvalue + (call.calldata.data.toList.map (·.toNat)) + | _ => none + +/-- Run `call` against `contract` in SolidCore with `fuel`, in the world `W`. -/ +def runIn (W : World) (fuel : Nat) (contract : TypeCheck.CheckedContract) (call : Call) : + Option Observable := + (resultIn? W fuel contract call).map (observe call) + +theorem resultIn?_closed (fuel : Nat) (contract : TypeCheck.CheckedContract) (call : Call) : + resultIn? World.closed fuel contract call = result? fuel contract call := by + unfold resultIn? result? + simp only [World.closed, Option.getD_none, Source.ABI.Oracle.callCalldata_closed] + rfl + +/-- **The closed world is `Source.run`.** -/ +theorem runIn_closed : runIn World.closed = run := by + funext fuel contract call + simp only [runIn, run, resultIn?_closed] + +end Source + +/-- SolidCore in the world `W`, with statement fuel `fuel`. -/ +def solidCoreIn (W : World) (fuel : Nat) : Sem := + { Prog := SolidCore.Solidity.TypeCheck.CheckedContract, run := Source.runIn W fuel } + +theorem solidCoreIn_closed (fuel : Nat) : solidCoreIn World.closed fuel = solidCore fuel := by + simp only [solidCoreIn, solidCore, Source.runIn_closed] + +/-! ## The open world -/ + +/-- A world of the open world: it answers every external call and creation, keeps SolidCore's +in-semantics answers to precompile calls and its resource defaults, and gives the other accounts' +code. -/ +structure World.Open (W : World) : Prop where + calls : ∀ h world request, (W.ans h (.external world (.call request))).isSome + creates : ∀ h world request, (W.ans h (.external world (.create request))).isSome + precompiles : ∀ h world request a, precompileAnswerCall? world request = some a → + W.ans h (.external world (.call request)) = some a + resources : ∀ h r, W.ans h (.resource r) = some (Query.defaultAnswer (.resource r)) + codes : W.codes.isSome + +/-! ## The world after a call + +SolidCore adopts the world a call answers (`adoptWorld`): the caller's storage and transient storage +become its account's in the answered world, and every later read of another account's code reads +the answered world (`State.envAccountCode`). The oracle hypothesis says the MIR oracle shows the +same world after the call. -/ + +/-- The account at the address `a` in a world, as SolidCore reads it (absent: the empty account). -/ +def accountIn (world : SolidCore.Solidity.Shared.OpenWorld) (a : Nat) : + EvmCompiler.Simulation.OpenAccount := + (world.accounts.find? (wordToAddress a)).getD default + +/-- The word at `slot` of the caller's storage in a world, as SolidCore adopts it. -/ +def storageIn (world : SolidCore.Solidity.Shared.OpenWorld) (slot : Nat) : Nat := + (StorageMap.lookup? (storageToWordMap (accountIn world selfAddress).storage) slot).getD 0 + +/-- The word at `slot` of the caller's transient storage in a world, as SolidCore adopts it. -/ +def transientIn (world : SolidCore.Solidity.Shared.OpenWorld) (slot : Nat) : Nat := + (StorageMap.lookup? (storageToWordMap (accountIn world selfAddress).transientStorage) slot).getD 0 + +/-- The code of the account `a` in a world, as SolidCore reads it after adopting the world. -/ +def codeIn (world : SolidCore.Solidity.Shared.OpenWorld) (a : Nat) : List SolidCore.Solidity.Byte := + byteArrayToBytes (accountIn world a).codeBytes + +/-- The code of the account `a` after the exchanges `h`, as SolidCore reads it: the world the +last call or creation answered (`State.envAccountCode` after an adoption), else `W.codes`. -/ +def codeAfter (W : World) : List Interaction.Exchange → Nat → List SolidCore.Solidity.Byte + | h, a => + match h.reverse.find? (fun e => match e.query with | .external _ _ => true | _ => false) with + | some ⟨.external _ (.call _), r⟩ => codeIn r.postWorld a + | some ⟨.external _ (.create _), r⟩ => codeIn r.postWorld a + | _ => SolidCore.Solidity.Shared.Account.codeAt (W.codes.getD []) a + +/-! ## The oracle hypothesis -/ + +/-- The MIR call kind of a source call. -/ +def machineKind : CallKind → SolarTV.Machine.CallKind + | .call => .call + | .callcode => .callcode + | .delegatecall => .delegatecall + | .staticcall => .staticcall + +/-- The source calls of a history: kind, callee, value and input bytes. -/ +def sourceCalls : List Interaction.Exchange → List (SolarTV.Machine.CallKind × Nat × Nat × List Nat) + | [] => [] + | ⟨.external _ (.call r), _⟩ :: rest => + (machineKind r.kind, addressToWord r.codeAddress, u256ToWord r.transferValue, + byteArrayToBytes r.calldata) :: sourceCalls rest + | _ :: rest => sourceCalls rest + +/-- The calls of a MIR world: kind, callee, value (zero for `DELEGATECALL` and `STATICCALL`) and +input bytes. -/ +def machineCalls : List SolarTV.Machine.Event → List (SolarTV.Machine.CallKind × Nat × Nat × List Nat) + | [] => [] + | .call kind seen input _ _ :: rest => + (kind, (seen.getD 1 0).toNat % 2 ^ 160, + (if kind = .call ∨ kind = .callcode then (seen.getD 2 0).toNat else 0), + input.map BitVec.toNat) :: machineCalls rest + | _ :: rest => machineCalls rest + +/-- The MIR oracle's code test for every address in the world `w`: `extcodesize` is zero exactly +when `code` gives the address no code. -/ +def CodesAgree (o : SolarTV.Machine.Oracle) (w : List SolarTV.Machine.Event) + (code : Nat → List SolidCore.Solidity.Byte) : Prop := + ∀ a < 2 ^ 160, (o.env "extcodesize" w [BitVec.ofNat 256 a] = 0) ↔ (code a).isEmpty + +/-- **The oracle hypothesis**: the world `W` and the MIR oracle `o` agree. + +* `codes`: in every MIR world with no call yet, `o`'s `extcodesize` of an address is zero + exactly when `W` gives it no code; +* `calls`: for every history and call request `W.ans` answers, and every MIR world that ends + in a call, whose calls are the source's (`sourceCalls` of the history with the request, by kind, + callee, value and input), whose storage and transient storage at the call are the caller's in + the world sent with the request and whose code test before the call is that world's, `o` answers that call as `W.ans` does: the success flag; for + a call that is not a `STATICCALL`, the storage and transient storage after it, the caller's in + the answered world, which SolidCore adopts; and, in that world followed by events with no call + (gas reads), the size of the return data (as a word), its bytes (at word indices), and every + account's code (the answered + world's, which SolidCore reads after adopting it); +* `static`: a `STATICCALL` answers a world in which the caller's storage and transient storage + are those of the world sent with it, as the MIR frame keeps them. + +The callee's answer may depend on the calls before it and on the caller's storage at the call, +never on what the source cannot see (the gas forwarded, memory offsets, gas reads). -/ +structure CallsAgree (o : SolarTV.Machine.Oracle) (W : World) : Prop where + codes : ∀ w, machineCalls w = [] → + CodesAgree o w (SolidCore.Solidity.Shared.Account.codeAt (W.codes.getD [])) + calls : ∀ h world request a, W.ans h (.external world (.call request)) = some a → + ∀ (w : List SolarTV.Machine.Event) k s i st tr, + w.getLast? = some (.call k s i st tr) → + machineCalls w = sourceCalls (h ++ [⟨.external world (.call request), a⟩]) → + (∀ slot < 2 ^ 256, (st (BitVec.ofNat 256 slot)).toNat = storageIn world slot ∧ + (tr (BitVec.ofNat 256 slot)).toNat = transientIn world slot) → + CodesAgree o w.dropLast (codeIn world) → + ((SolarTV.Machine.callFlag o w = 1) ↔ a.success = true) ∧ + (request.kind ≠ .staticcall → ∀ slot < 2 ^ 256, + (o.storageAfter w (BitVec.ofNat 256 slot)).toNat = storageIn a.postWorld slot ∧ + (o.transientAfter w (BitVec.ofNat 256 slot)).toNat = transientIn a.postWorld slot) ∧ + ∀ rest : List SolarTV.Machine.Event, machineCalls rest = [] → + (SolarTV.Machine.returndataSize o (w ++ rest)).toNat = a.returnData.size % 2 ^ 256 ∧ + (∀ j < a.returnData.size, j < 2 ^ 256 → + (SolarTV.Machine.returndataByte o (w ++ rest) j).toNat = (a.returnData.get! j).toNat) ∧ + CodesAgree o (w ++ rest) (codeAfter W (h ++ [⟨.external world (.call request), a⟩])) + static : ∀ h world request a, W.ans h (.external world (.call request)) = some a → + request.kind = .staticcall → + ∀ slot, storageIn a.postWorld slot = storageIn world slot ∧ + transientIn a.postWorld slot = transientIn world slot + +/-- info: 'SolidCore.Refinement.Source.runIn_closed' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms Source.runIn_closed + +end SolidCore.Refinement diff --git a/SolidCore/Refinement/SourceOracleMono.lean b/SolidCore/Refinement/SourceOracleMono.lean new file mode 100644 index 00000000..e1649518 --- /dev/null +++ b/SolidCore/Refinement/SourceOracleMono.lean @@ -0,0 +1,135 @@ +import SolidCore.Refinement.SourceOracle + +/-! +# What the closed world shows, every open world shows + +`Source.run` answers resources by their defaults and precompile calls in the semantics, and nothing +else (`closedAns`); every open world answers those the same way (`World.Open`). So a run that +finishes in the closed world finishes the same way in every open world whose account code during +the call is the contract's own context's (`runIn_of_run`): the fold takes the same answers along +the same path (`foldAns_mono`). A function whose only external calls are precompile calls +(`ecrecover` in a token's `permit`) then has, in every such open world, exactly its closed-world +outcomes wherever the closed world finishes, and a stage from `Source.run` that also finishes on +its scope is a stage from `Source.runIn W` (`stageIn_of_stage`). +-/ + +namespace SolidCore.Refinement + +open SolidCore.Solidity SolidCore.Solidity.Source EvmCompiler.Simulation + +/-- `W.ans` answers every query `closedAns` answers, the same way. -/ +def ExtendsClosed (W : World) : Prop := ∀ h q a, closedAns h q = some a → W.ans h q = some a + +/-- Every open world extends the closed responder. -/ +theorem World.Open.extendsClosed {W : World} (hW : W.Open) : ExtendsClosed W := by + intro h q a ha + cases q with + | resource r => + simp only [closedAns, Option.some.injEq] at ha + rw [hW.resources, ha] + | external world req => + cases req with + | call request => exact hW.precompiles h world request a ha + | create request => simp [closedAns] at ha + +/-- A fold that finishes under `closedAns` finishes the same way under every extension. -/ +theorem foldAns_mono {W : World} (hW : ExtendsClosed W) {α : Type} (t : SolI α) : + ∀ h r, foldAns closedAns h t = some r → foldAns W.ans h t = some r := by + induction t with + | done r => + intro h r' hr + cases r <;> simpa [foldAns] using hr + | request q k ih => + intro h r hr + simp only [foldAns] at hr ⊢ + cases hq : closedAns h q with + | none => rw [hq] at hr; simp at hr + | some a => + rw [hq] at hr + rw [hW h q a hq] + exact ih a _ _ hr + +theorem callAns_mono {W : World} (hW : ExtendsClosed W) {fuel : Nat} {table : FunctionTable} + {context : Context} {fn : FunctionDef} {st : Source.State} {args : List Value} {r : CallResult} + (h : Source.callAns closedAns fuel table context fn st args = some r) : + Source.callAns W.ans fuel table context fn st args = some r := by + unfold Source.callAns at h ⊢ + cases ht : fn.call fuel table context st args with + | none => rw [ht] at h; simp at h + | some t => + rw [ht] at h + simp only [Option.bind_some] at h ⊢ + exact foldAns_mono hW t [] r h + +theorem callCalldata_mono {W : World} (hW : ExtendsClosed W) (fuel : Nat) (contract : Contract) + (base : Context) (state : Source.State) (self sender value : SolidCore.Solidity.Source.Word) + (calldata : ABI.Bytes) {x : ABI.AbiCallResult} + (h : Source.ABI.Oracle.callCalldata closedAns fuel contract base state self sender value calldata = + some x) : + Source.ABI.Oracle.callCalldata W.ans fuel contract base state self sender value calldata = + some x := by + unfold Source.ABI.Oracle.callCalldata at h ⊢ + split at h + · rename_i selector _ + split at h + · rename_i function _ + split at h + · rename_i args _ + split at h + · rename_i hv + simp only [hv, ↓reduceIte] + dsimp only at h ⊢ + cases hc : Source.callAns closedAns fuel contract.table + (ABI.Contract.callContextAtWithBase contract base self sender value calldata) + function state args with + | none => rw [hc] at h; simp at h + | some r => + rw [hc] at h + rw [callAns_mono hW hc] + exact h + · rename_i hv + simp only [hv] + exact h + · exact h + · exact h + · exact h + +/-- **A closed-world run is a run in every world that extends it**, when the account code during the +call is the contract's own context's. -/ +theorem runIn_of_run {W : World} (hW : ExtendsClosed W) {fuel : Nat} + {c : TypeCheck.CheckedContract} (hcodes : W.codes.getD c.core.context.accountCodes = + c.core.context.accountCodes) {call : Call} {obs : Observable} + (h : Source.run fuel c call = some obs) : Source.runIn W fuel c call = some obs := by + rw [← Source.runIn_closed] at h + unfold Source.runIn Source.resultIn? at h ⊢ + simp only [World.closed, Option.getD_none] at h + simp only [hcodes] + revert h + split + · intro h + obtain ⟨x, hx, rfl⟩ := Option.map_eq_some_iff.mp h + rw [callCalldata_mono hW _ _ _ _ _ _ _ _ hx] + rfl + · intro h; simp at h + +/-- **A stage from `Source.run` that finishes on its scope is a stage from `Source.runIn W`**, for +every world that extends the closed one with the contract's own account code. -/ +theorem stageIn_of_stage {W : World} (hW : ExtendsClosed W) {fuel : Nat} {B : SolarTV.Sem} + {c : TypeCheck.CheckedContract} {q : B.Prog} {scope : Call → Prop} + (hcodes : W.codes.getD c.core.context.accountCodes = c.core.context.accountCodes) + (stage : SolarTV.Stage (solidCore fuel) B c q scope) + (fin : ∀ call, scope call → (Source.run fuel c call).isSome) : + SolarTV.Stage (solidCoreIn W fuel) B c q scope := by + intro call hs obs hrun + obtain ⟨obs', h'⟩ := Option.isSome_iff_exists.mp (fin call hs) + have hin := runIn_of_run hW hcodes h' + change Source.runIn W fuel c call = some obs at hrun + rw [hin] at hrun + cases hrun + exact stage call hs obs h' + +/-- info: 'SolidCore.Refinement.stageIn_of_stage' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stageIn_of_stage + +end SolidCore.Refinement diff --git a/SolidCore/Refinement/SourceOracleSat.lean b/SolidCore/Refinement/SourceOracleSat.lean new file mode 100644 index 00000000..b09774e7 --- /dev/null +++ b/SolidCore/Refinement/SourceOracleSat.lean @@ -0,0 +1,192 @@ +import SolidCore.Refinement.SourceOracle + +/-! +# The oracle hypothesis is satisfiable + +`callsAgree_sat`: an open world and a MIR oracle that agree (`CallsAgree`), so that a theorem with the +hypothesis `CallsAgree o W` is not vacuous for want of a world. In `failWorld` every external call that +is not to a precompile fails with empty return data and leaves the world as it was sent; a +precompile call is answered by SolidCore's precompile semantics, as every open world answers it; +no other account has code. `failOracle` computes the same answers from what the MIR frame sees of a +call (kind, callee, value, input), keeps the storage it had at the call, and reports no code. +-/ + +namespace SolidCore.Refinement + +open SolidCore.Solidity SolidCore.Solidity.Source EvmCompiler.Simulation + +namespace Witness + +/-- The success flag and return data of a call in the failing world, from what both sides see of +it: a `STATICCALL` with no value to a precompile runs it, every other call fails with no data. -/ +def failResp (k : SolarTV.Machine.CallKind) (callee value : Nat) (input : List Nat) : Bool × ByteArray := + if k = .staticcall ∧ value = 0 then + match SolidCore.Solidity.Shared.Precompile.kindOfAddress? callee with + | some kind => + match SolidCore.Solidity.Shared.Precompile.execute? kind input with + | some (success, output) => (success, bytesToByteArray output) + | none => (false, ByteArray.empty) + | none => (false, ByteArray.empty) + else (false, ByteArray.empty) + +/-- The failing world's answer to a call: SolidCore's precompile answer, else a failure with no +data that leaves the sent world. -/ +def failCall (world : SolidCore.Solidity.Shared.OpenWorld) (request : CallRequest) : CallResponse := + (precompileAnswerCall? world request).getD + { success := false, returnData := ByteArray.empty, postWorld := world, + returnedGas := EvmYul.UInt256.ofNat 0 } + +/-- The failing world's answerer. -/ +def failAns : Ans := fun _ q => + match q with + | .resource r => some (Query.defaultAnswer (.resource r)) + | .external world (.call request) => some (failCall world request) + | .external world (.create request) => some (Query.defaultAnswer (.external world (.create request))) + +/-- The failing world: `failAns`, and no other account has code. -/ +def failWorld : World := { ans := failAns, codes := some [] } + +theorem failCall_postWorld (world : SolidCore.Solidity.Shared.OpenWorld) (request : CallRequest) : + (failCall world request).postWorld = world := by + unfold failCall precompileAnswerCall? + repeat' split + all_goals simp_all + +theorem failCall_resp (world : SolidCore.Solidity.Shared.OpenWorld) (request : CallRequest) : + ((failCall world request).success, (failCall world request).returnData) = + failResp (machineKind request.kind) (addressToWord request.codeAddress) + (u256ToWord request.transferValue) (byteArrayToBytes request.calldata) := by + unfold failCall precompileAnswerCall? failResp + cases hk : request.kind <;> simp [machineKind] + by_cases hv : u256ToWord request.transferValue = 0 + · simp only [hv, beq_self_eq_true, ↓reduceIte] + cases SolidCore.Solidity.Shared.Precompile.kindOfAddress? (addressToWord request.codeAddress) with + | none => rfl + | some kind => + simp only + cases SolidCore.Solidity.Shared.Precompile.execute? kind (byteArrayToBytes request.calldata) with + | some r => rfl + | none => + simp only + split <;> rfl + · simp [hv] + +theorem failWorld_open : failWorld.Open where + calls := by intros; rfl + creates := by intros; rfl + precompiles := by + intro h world request a ha + show some (failCall world request) = some a + simp [failCall, ha] + resources := by intros; rfl + codes := rfl + +/-- The failing oracle: the failing world's answers from the last call the frame made, the +storage it had at the call, no code at any address. -/ +def failOracle : SolarTV.Machine.Oracle where + env := fun name w args => + match name, args, (machineCalls w).getLast? with + | "returndatasize", [], some (k, c, v, i) => BitVec.ofNat 256 (failResp k c v i).2.size + | "returndata", [j], some (k, c, v, i) => BitVec.ofNat 256 ((failResp k c v i).2.get! j.toNat).toNat + | _, _, _ => 0 + result := fun w => + match (machineCalls w).getLast? with + | some (k, c, v, i) => if (failResp k c v i).1 then 1 else 0 + | none => 0 + storageAfter := fun w => + match w.getLast? with + | some (.call _ _ _ st _) => st + | _ => fun _ => 0 + transientAfter := fun w => + match w.getLast? with + | some (.call _ _ _ _ tr) => tr + | _ => fun _ => 0 + keccak := fun _ => 0 + caller := 0 + +theorem machineCalls_append (w rest : List SolarTV.Machine.Event) : + machineCalls (w ++ rest) = machineCalls w ++ machineCalls rest := by + induction w with + | nil => rfl + | cons e w ih => + cases e <;> simp [machineCalls, ih] + +theorem sourceCalls_append (h : List Interaction.Exchange) (e : Interaction.Exchange) : + sourceCalls (h ++ [e]) = sourceCalls h ++ sourceCalls [e] := by + induction h with + | nil => rfl + | cons x h ih => + obtain ⟨q, a⟩ := x + cases q with + | resource r => simp [sourceCalls, ih] + | external world req => + cases req <;> simp [sourceCalls, ih] + +theorem failOracle_codes (w : List SolarTV.Machine.Event) (a : Nat) : + failOracle.env "extcodesize" w [BitVec.ofNat 256 a] = 0 := by + simp [failOracle] + +/-- **The failing world and the failing oracle agree.** -/ +theorem failAgree : CallsAgree failOracle failWorld where + codes := by + intro w _ a _ + simp [failOracle_codes, failWorld, SolidCore.Solidity.Shared.Account.codeAt, + SolidCore.Solidity.Shared.Account.lookupBytes?] + calls := by + intro h world request a ha w k s i st tr hlast hm hst hcodes + have ha' : a = failCall world request := by + simp only [failWorld, failAns] at ha + exact (Option.some.inj ha).symm + subst ha' + have hresp := failCall_resp world request + have hpost := failCall_postWorld world request + have hl : (machineCalls w).getLast? = some (machineKind request.kind, + addressToWord request.codeAddress, u256ToWord request.transferValue, + byteArrayToBytes request.calldata) := by + rw [hm, sourceCalls_append] + simp [sourceCalls] + refine ⟨?_, ?_, ?_⟩ + · simp only [SolarTV.Machine.callFlag, failOracle, hl] + rw [Prod.ext_iff] at hresp + rw [← hresp.1] + cases (failCall world request).success <;> simp + · intro _ slot hslot + have := hst slot hslot + simp only [failOracle, hlast, hpost] + exact this + · intro rest hrest + have hl' : (machineCalls (w ++ rest)).getLast? = (machineCalls w).getLast? := by + rw [machineCalls_append, hrest, List.append_nil] + rw [Prod.ext_iff] at hresp + refine ⟨?_, ?_, ?_⟩ + · simp only [SolarTV.Machine.returndataSize, failOracle, hl', hl, BitVec.toNat_ofNat] + rw [← hresp.2] + · intro j _ hj + simp only [SolarTV.Machine.returndataByte, failOracle, hl', hl, ← hresp.2, + BitVec.toNat_ofNat, Nat.mod_eq_of_lt hj, BitVec.toNat_setWidth] + have := ((failCall world request).returnData.get! j).toNat_lt + omega + · intro x hx + have h0 := (hcodes x hx).mp (failOracle_codes _ _) + simp only [failOracle_codes, true_iff] + simpa [codeAfter, hpost] using h0 + static := by + intro h world request a ha _ slot + have ha' : a = failCall world request := by + simp only [failWorld, failAns] at ha + exact (Option.some.inj ha).symm + subst ha' + rw [failCall_postWorld] + exact ⟨rfl, rfl⟩ + +end Witness + +/-- **The oracle hypothesis is satisfiable in the open world.** -/ +theorem callsAgree_sat : ∃ (o : SolarTV.Machine.Oracle) (W : World), W.Open ∧ CallsAgree o W := + ⟨_, _, Witness.failWorld_open, Witness.failAgree⟩ + +/-- info: 'SolidCore.Refinement.callsAgree_sat' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms callsAgree_sat + +end SolidCore.Refinement diff --git a/SolidCore/Refinement/Spec.lean b/SolidCore/Refinement/Spec.lean new file mode 100644 index 00000000..7b198e22 --- /dev/null +++ b/SolidCore/Refinement/Spec.lean @@ -0,0 +1,71 @@ +import SolidCore.Refinement.Compose + +/-! +# Specifications carried from SolidCore to bytecode + +A specification of a contract is a precondition on the call and a postcondition on +the call and its observable. `Satisfies S p scope pre post` says that the program +`p` of the semantics `S` finishes every call in `scope` that meets `pre` with an +observable that meets `post`: total correctness, stated over the same `Call` and +`Observable` as every stage. + +A stage preserves every observable a finished run gives, so it carries a specification +from its source to its target (`Satisfies.of_stage`). This gives the end-to-end form +used for verified contracts: a specification proved of SolidCore holds of the bytecode + +* directly, from a proof of `Refines` (`bytecode_of_refines`), or +* through a compiler's stages (`bytecode_of_stages`): SolidCore to lowered MIR, lowered + MIR to EVM IR, and EVM IR to bytecode. Each stage is a hypothesis named after the + obligation that discharges it. + +`C1.satisfies_bytecode` (`SolidCore.Refinement.C1.Spec`, outside the default library, since its +SolidCore side uses `native_decide`) instantiates the first form for c1 with no hypothesis left, +and `C1.satisfies_bytecode_staged` the second, with its three stages as hypotheses. +-/ + +namespace SolidCore.Refinement + +/-- `p` finishes every call of `scope` that meets `pre`, with an observable that meets +`post`. -/ +def Satisfies (S : Sem) (p : S.Prog) (scope : Call → Prop) (pre : Call → Prop) + (post : Call → Observable → Prop) : Prop := + ∀ call, scope call → pre call → ∃ obs, S.run p call = some obs ∧ post call obs + +/-- A stage carries a specification from its source program to its target program. -/ +theorem Satisfies.of_stage {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + {pre : Call → Prop} {post : Call → Observable → Prop} + (h : Satisfies A p scope pre post) (stage : Stage A B p q scope) : + Satisfies B q scope pre post := by + intro call hc hp + obtain ⟨obs, hrun, hpost⟩ := h call hc hp + exact ⟨obs, stage call hc obs hrun, hpost⟩ + +/-- A specification SolidCore satisfies holds of bytecode that refines it. -/ +theorem bytecode_of_refines {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {code : ByteArray} {scope : Call → Prop} {pre : Call → Prop} + {post : Call → Observable → Prop} + (spec : Satisfies (solidCore fuel) contract scope pre post) + (refines : Refines fuel contract code scope) : + Satisfies ethLib code scope pre post := + spec.of_stage (stage_of_refines refines) + +/-- A specification SolidCore satisfies holds of the bytecode a compiler produces through +lowered MIR and EVM IR, given each of its stages. + +* `lowering`: SolidCore to lowered MIR, including ABI decoding and dispatch + (`lower-abi`, `lower-dispatch`); this library's stage, not yet proved generically. +* `backend`: lowered MIR through the MIR passes, stack scheduling and the EVM IR passes; + solar's `mir_to_evmir_certified`, from per-pass certificates. +* `assembly`: EVM IR to runtime bytecode on EthLib; solar's `AssemblyStage`. -/ +theorem bytecode_of_stages {fuel : Nat} {mirSem evmirSem : Sem} + {contract : SolidCore.Solidity.TypeCheck.CheckedContract} {mir : mirSem.Prog} + {evmir : evmirSem.Prog} {code : ByteArray} {scope : Call → Prop} {pre : Call → Prop} + {post : Call → Observable → Prop} + (spec : Satisfies (solidCore fuel) contract scope pre post) + (lowering : Stage (solidCore fuel) mirSem contract mir scope) + (backend : Stage mirSem evmirSem mir evmir scope) + (assembly : Stage evmirSem ethLib evmir code scope) : + Satisfies ethLib code scope pre post := + spec.of_stage ((lowering.trans backend).trans assembly) + +end SolidCore.Refinement diff --git a/SolidCore/Refinement/Statement.lean b/SolidCore/Refinement/Statement.lean new file mode 100644 index 00000000..7ee9c35d --- /dev/null +++ b/SolidCore/Refinement/Statement.lean @@ -0,0 +1,191 @@ +import SolidCore.Solidity.Checked +import EthLib.Execution.Evm.Call.MessageCall +import SolarTV.Sem + +/-! +# Refinement of solar's runtime bytecode against SolidCore + +This module states, once, what it means for compiled bytecode to implement a +contract of the source semantics. + +A call runs on both sides with the same call data, call value and initial +storage of the callee: + +* `Source.run` constructs the contract in SolidCore, replaces its storage with + the call's initial storage and calls it through the ABI dispatcher + (`CheckedContract.callCalldataAtFromWithContext?`); +* `Target.run` installs the bytecode at `selfAddress` in EthLib's state and runs + one `processMessage` from `callerAddress` at the Fusaka fork. + +Each side yields an `Observable`: whether the call succeeded, its return or +revert data, the logs it emitted and the callee's final storage. +`Refines fuel contract code scope` says that for every call in `scope` both +sides produce the same observable. + +## Assumptions + +The statement fixes the following, and a theorem about it proves nothing +outside them: + +* **One frame, fixed environment.** The caller is `callerAddress`, the callee + `selfAddress`, the fork Fusaka, and the block and transaction environment + `Target.blockEnv` and `Target.txEnv`. Contracts that read the block, the + origin, balances or other accounts, or that call out, are out of scope. +* **Gas.** The message carries `gasLimit` gas. A call the source semantics + completes but the bytecode runs out of gas on is a counterexample, not an + excluded case, so a theorem must show the bytecode stays within it. +* **Deployment.** `Target.run` starts from the runtime bytecode with the call's + storage, while `Source.run` runs the constructor first and then overwrites + storage. Contracts whose constructor leaves other state (immutables, logs) + are out of scope. +* **Failure.** A failed call keeps the initial storage and emits no logs on + both sides, so `Observable` records exactly that rather than either + semantics' intermediate state. +* **Keccak.** SolidCore hashes with evmyul's Keccak-256 and EthLib with its own. + A theorem about a contract that hashes (mappings, dynamic arrays, events with + signatures) must prove the two agree on the inputs it uses. +* **Fuel.** SolidCore's interpreter takes fuel; `Refines` fixes it, and running + out of fuel makes `Source.run` return `none`, which refutes the statement. +-/ + +namespace SolidCore.Refinement + +-- One external call (Call), what it shows outside the callee (Observable) and the +-- value of a slot in a call's storage (slotValue) are solar's SolarTV.Sem definitions, +-- used directly so that a stage solar proves is a stage of this library with no bridge. +-- A Call is the call data, the call value and the callee's storage before the call as +-- (slot, value) pairs, where a later pair for the same slot wins; an Observable is whether +-- the call returned, its return or revert data, its logs (empty when it failed) as topics +-- and data bytes, and the callee's storage after it (its initial storage when it failed). +export SolarTV (Call Call.mk Observable Observable.mk Observable.mk.injEq slotValue) + +/-- The account that sends every call. -/ +def callerAddress : Nat := 0x2000 + +/-- The account the contract runs at. -/ +def selfAddress : Nat := 0x1000 + +/-- The gas every call carries. -/ +def gasLimit : Nat := 10000000 + +namespace Source + +open SolidCore.Solidity SolidCore.Solidity.Source + +/-- SolidCore's result for `call` against `contract` with `fuel`: construct the +contract, replace its storage with the call's and call it through the ABI +dispatcher. `none` when the interpreter fails, runs out of fuel or the constructor +reverts. -/ +def result? (fuel : Nat) (contract : TypeCheck.CheckedContract) (call : Call) : + Option TypeCheck.CoreAbiCallResult := + let base := contract.core.context + let context := + { base with sender := callerAddress, self := selfAddress, value := call.callvalue } + match TypeCheck.CheckedContract.constructWithContext? fuel contract context + State.empty selfAddress 0 [] with + | some (CallResult.returned deployed _) => + let storage := call.storage.foldl + (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) deployed.storage + TypeCheck.CheckedContract.callCalldataAtFromWithContext? fuel contract context + { deployed with storage := storage } selfAddress callerAddress call.callvalue + (call.calldata.data.toList.map (·.toNat)) + | _ => none + +/-- What `result` shows outside the callee. -/ +def observe (call : Call) (result : TypeCheck.CoreAbiCallResult) : Observable := + { success := result.success + output := result.output + logs := + if result.success then + (result.state.logEntries selfAddress).map fun entry => (entry.topics, entry.data) + else [] + storage := fun slot => + if result.success then result.state.loadSlot slot else slotValue call.storage slot } + +/-- Run `call` against `contract` in SolidCore with `fuel`. -/ +def run (fuel : Nat) (contract : TypeCheck.CheckedContract) (call : Call) : + Option Observable := + (result? fuel contract call).map (observe call) + +end Source + +namespace Target + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.State + +/-- The 20-byte address with value `n`. -/ +def address (n : Nat) : Address := + ⟨(natToBytes 20 n).toArray, by simp [natToBytes_length]⟩ + +/-- The 32-byte storage key with value `n`. -/ +def storageKey (n : Nat) : Bytes32 := + ⟨(natToBytes 32 n).toArray, by simp [natToBytes_length]⟩ + +/-- The block every call runs in. -/ +def blockEnv : BlockEnvironment .fusaka := + { chainId := 1, coinbase := address 0, number := 1, gasLimit := 30000000, timestamp := 1, + difficulty := 0, blockHashes := [], baseFeePerGas := fun _ => 0, + prevRandao := fun _ => storageKey 0, excessBlobGas := fun _ => 0, + parentBeaconBlockRoot := fun _ => (default : Hash32), slotNumber := fun _ => 0 } + +/-- The transaction every call belongs to. -/ +def txEnv : TransactionEnvironment .fusaka := + { origin := address callerAddress, gasPrice := 0, blobVersionedHashes := fun _ => [] } + +/-- The state before the call: `code` at `selfAddress` with the call's storage, +and a caller that holds exactly the call value. -/ +def preState (code : ByteArray) (call : Call) : TransactionState := + let hash := EthLib.Cryptography.Hash.Keccak.keccak256 code + let storage : Std.ExtTreeMap Bytes32 U256 := + call.storage.foldl (fun m kv => m.insert (storageKey kv.1) (BitVec.ofNat 256 kv.2)) ∅ + let pre : State := + { accounts := ((∅ : Std.ExtTreeMap Address Account).insert (address selfAddress) + { nonce := 1, balance := 0, codeHash := hash }).insert (address callerAddress) + { nonce := 0, balance := BitVec.ofNat 256 call.callvalue, + codeHash := EthLib.Cryptography.Hash.Keccak.keccak256 .empty }, + storage := (∅ : Std.ExtTreeMap Address (Std.ExtTreeMap Bytes32 U256)).insert + (address selfAddress) storage, + code := (∅ : Std.ExtTreeMap Hash32 ByteArray).insert hash code } + TransactionState.ofBlock + { preState := pre, accountWrites := ∅, storageWrites := ∅, codeWrites := ∅, + storageClears := ∅ } + +/-- The message of the call: `gasLimit` gas from `callerAddress` to `selfAddress`. -/ +def message (code : ByteArray) (call : Call) : Message .fusaka := + { blockEnv, txEnv, caller := address callerAddress, target := some (address selfAddress), + currentTarget := address selfAddress, gas := gasLimit, value := call.callvalue, + data := call.calldata, codeAddress := some (address selfAddress), + code, depth := 0, shouldTransferValue := true, isStatic := false, + disablePrecompiles := false } + +/-- Run `call` against `code` in EthLib. `none` when `processMessage` raises. -/ +def run (code : ByteArray) (call : Call) : Option Observable := + match processMessage (Meter := Nat) .fusaka (message code call) (preState code call) + Substate.empty with + | .error _ => none + | .ok ⟨evm, _⟩ => + let success := evm.error.isNone + some + { success + output := evm.output.toList.map (·.toNat) + logs := + if success then + evm.substate.logs.toList.map fun log => + (log.topics.map fun topic => bytesToNat topic.toList, + log.data.toList.map (·.toNat)) + else [] + storage := fun slot => + if success then (evm.state.getStorage (address selfAddress) (storageKey slot)).toNat + else slotValue call.storage slot } + +end Target + +/-- `code` implements `contract` on every call `scope` admits: SolidCore with +`fuel` and EthLib both finish and show the same observable. -/ +def Refines (fuel : Nat) (contract : SolidCore.Solidity.TypeCheck.CheckedContract) + (code : ByteArray) (scope : Call → Prop) : Prop := + ∀ call, scope call → + ∃ obs, Source.run fuel contract call = some obs ∧ Target.run code call = some obs + +end SolidCore.Refinement + diff --git a/SolidCore/Refinement/Wide/Clean.lean b/SolidCore/Refinement/Wide/Clean.lean new file mode 100644 index 00000000..225fddb0 --- /dev/null +++ b/SolidCore/Refinement/Wide/Clean.lean @@ -0,0 +1,79 @@ +import SolidCore.Refinement.Dirty.Source + +/-! +# The clean scope inside the full scope + +A contract whose refinement is proved symbolically (`SolidCore.Refinement.Wide`) gets it on +`Abi.fullScope`, every call on any argument words below `2 ^ 256`. `refines_of_full` gives +from it the refinement on `Abi.calls`, the clean calls the enumeration route checks one by +one, when every parameter's clean words are words (`Param.fits`, which `decide` checks for +a contract's list of functions). +-/ + +namespace SolidCore.Refinement.Wide + +open SolidCore.Refinement.Abi + +/-- Whether every clean word of the parameter is below `2 ^ 256`. -/ +def paramFits : Param → Bool + | .uint b => decide (b ≤ 256) + | .int b => decide (0 < b ∧ b ≤ 256) + | .bool => true + | .enum n => decide (n ≤ 2 ^ 256) + +theorem lt_of_mem_values {p : Param} (hp : paramFits p = true) {v : Nat} (hv : v ∈ p.values) : + v < 2 ^ 256 := by + cases p with + | uint b => + simp only [paramFits, decide_eq_true_eq] at hp + simp only [Param.values, List.mem_range] at hv + exact Nat.lt_of_lt_of_le hv (Nat.pow_le_pow_right (by decide) hp) + | int b => + simp only [paramFits, decide_eq_true_eq] at hp + have hle : 2 ^ (b - 1) ≤ 2 ^ 256 := Nat.pow_le_pow_right (by decide) (by omega) + simp only [Param.values, List.mem_append, List.mem_map, List.mem_range] at hv + rcases hv with ⟨i, hi, rfl⟩ | hv + · omega + · omega + | bool => + simp only [Param.values, List.mem_cons, List.not_mem_nil, or_false] at hv + rcases hv with rfl | rfl <;> decide + | enum n => + simp only [paramFits, decide_eq_true_eq] at hp + simp only [Param.values, List.mem_range] at hv + omega + +theorem of_mem_tuples : ∀ {ps : List Param}, ps.all paramFits = true → ∀ {args : List Nat}, + args ∈ tuples ps → args.length = ps.length ∧ ∀ a ∈ args, a < 2 ^ 256 + | [], _, args, h => by + simp only [tuples, List.mem_cons, List.not_mem_nil, or_false] at h + subst h + simp + | p :: ps, hps, args, h => by + simp only [List.all_cons, Bool.and_eq_true] at hps + simp only [tuples, List.mem_flatMap, List.mem_map] at h + obtain ⟨v, hv, rest, hrest, rfl⟩ := h + obtain ⟨hl, hlt⟩ := of_mem_tuples hps.2 hrest + refine ⟨by simp [hl], fun a ha => ?_⟩ + simp only [List.mem_cons] at ha + rcases ha with rfl | ha + · exact lt_of_mem_values hps.1 hv + · exact hlt a ha + +/-- A clean call is in the full scope. -/ +theorem fullScope_of_mem_calls {fns : List Fn} (hf : fns.all (·.params.all paramFits) = true) + {s : List (Nat × Nat)} {call : Call} (h : call ∈ calls fns [s]) : fullScope fns s call := by + simp only [calls, List.flatMap_cons, List.flatMap_nil, List.append_nil, List.mem_flatMap, + List.mem_map] at h + obtain ⟨fn, hfn, args, hargs, rfl⟩ := h + obtain ⟨hl, hlt⟩ := of_mem_tuples (List.all_eq_true.mp hf fn hfn) hargs + exact ⟨fn, hfn, args, hl, hlt, rfl⟩ + +/-- The refinement on the full scope gives it on the clean calls. -/ +theorem refines_of_full {fuel : Nat} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {code : ByteArray} {fns : List Fn} {s : List (Nat × Nat)} + (hf : fns.all (·.params.all paramFits) = true) (h : Refines fuel c code (fullScope fns s)) : + Refines fuel c code (· ∈ calls fns [s]) := + fun call hc => h call (fullScope_of_mem_calls hf hc) + +end SolidCore.Refinement.Wide diff --git a/SolidCore/Refinement/Wide/Refines.lean b/SolidCore/Refinement/Wide/Refines.lean new file mode 100644 index 00000000..386b6d47 --- /dev/null +++ b/SolidCore/Refinement/Wide/Refines.lean @@ -0,0 +1,196 @@ +import SolidCore.Refinement.Wide.Source +import SolidCore.Refinement.Evm.WideStorage + +/-! +# Refinement for functions with wide parameters + +A corpus function with a `uint256`, `address`, `int256` or `bytes32` parameter has 2^256 +argument words per parameter, so `Check.lean`'s evaluation of every call is out of +reach. Its refinement is proved one function at a time, symbolically on both sides: + +1. SolidCore: `Wide.Tactic`'s `src_symex`, with the rules of `Wide.Source` + (`wide_symex`), runs `Source.run` on the call `callOf sel ws` with free argument + words `ws`. It splits on every condition on the words the interpreter meets and + leaves, on each path, the goal that EthLib shows SolidCore's observable `X` there. +2. EthLib: `run_of_post` (`Evm.Wide`) reduces that goal to a frame specification, + which `wide_tgt` proves by stepping solar's bytecode under the path's conditions. + +This module holds what the per-contract proofs share: the context SolidCore's +`Source.result?` builds (`ctxOf`), the rewrite of `Source.run` on a call once the +constructor's result is known (`run_eq`), and `refines_of_calls`, which turns one +theorem per function into `Refines` on `Abi.fullScope`, every call of every function on +any argument words below `2 ^ 256`, from the storage SolidCore's constructor leaves: empty, or +the storage `deployedAt` checks, for `refines_of_calls_at`. + +The per-contract facts a proof needs about SolidCore's checked contract, which comes +out of the type checker and so is opaque to the kernel, are checked once, in the kernel: that +its core contract is a literal the generator printed, and that its constructor leaves empty +storage, or the storage `deployedAt` names, and no logs, by one conversion check +(`kernel_rfl shape_eq`, `SolidCore.Refinement.KernelRfl`) on copies of the type checker that +read each function's selector from a table checked by Keccak-256 once per selector. +-/ + +namespace SolidCore.Refinement.Wide + +open EthLib.Base SolidCore.Solidity SolidCore.Solidity.Source SolidCore.Refinement.Evm.Wide + +/-- The context SolidCore's `Source.result?` calls the contract in. -/ +def ctxOf (c : TypeCheck.CheckedContract) : Source.Context := + { c.core.context with sender := callerAddress, self := selfAddress, value := 0 } + +/-- What the constructor of `c` leaves: the state `d`, with no storage and no logs. -/ +structure Deployed (fuel : Nat) (c : TypeCheck.CheckedContract) (d : Source.State) : Prop where + cons : ∃ vs, TypeCheck.CheckedContract.constructWithContext? fuel c (ctxOf c) State.empty + selfAddress 0 [] = some (CallResult.returned d vs) + storage : d.storage.isEmpty = true + events : d.events = [] + +/-- Whether the constructor of `c` leaves no storage and no logs, as a `Bool`. -/ +def deployedEmpty (fuel : Nat) (c : TypeCheck.CheckedContract) : Bool := + match TypeCheck.CheckedContract.constructWithContext? fuel c (ctxOf c) State.empty selfAddress + 0 [] with + | some (CallResult.returned d _) => d.storage.isEmpty && d.events.isEmpty + | _ => false + +theorem deployed_of {fuel : Nat} {c : TypeCheck.CheckedContract} + (h : deployedEmpty fuel c = true) : ∃ d, Deployed fuel c d := by + unfold deployedEmpty at h + split at h + next d vs hc => + simp only [Bool.and_eq_true, List.isEmpty_iff] at h + exact ⟨d, ⟨vs, hc⟩, h.1, h.2⟩ + next => simp at h + +theorem getElem?_of_isEmpty {m : Std.HashMap Nat Nat} (h : m.isEmpty = true) (k : Nat) : + m[k]? = none := + Std.HashMap.getElem?_eq_none (Std.HashMap.isEmpty_iff_forall_not_mem.mp h _) + +/-- `Source.run` of a call with empty storage, once the constructor's result is known: the +ABI dispatcher of the core contract on the call data, byte by byte. -/ +theorem run_eq {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + (hd : Deployed fuel c d) (s : Nat) (ws : List U256) : + Source.run fuel c (callOf s ws) = + Option.map (Source.observe (callOf s ws)) + (ABI.Contract.callCalldataAtFromWithContext? fuel c.core (ctxOf c) d selfAddress + callerAddress 0 ((natToBytes 4 s).map (·.toNat) ++ Dirty.argBytes (ws.map (·.toNat)))) := by + obtain ⟨vs, hc⟩ := hd.cons + simp only [Source.run, Source.result?, show (callOf s ws).callvalue = 0 from rfl, + show (callOf s ws).storage = [] from rfl, + show (callOf s ws).calldata = Abi.calldata s (ws.map (·.toNat)) from rfl] + rw [show ({ c.core.context with sender := callerAddress, self := selfAddress, value := 0 } : + Source.Context) = ctxOf c from rfl, hc] + simp only [List.foldl_nil, TypeCheck.CheckedContract.callCalldataAtFromWithContext?, + Dirty.bytes_calldata] + +/-- One theorem per function, on free argument words, gives the refinement on every call of +every function on any argument words below `2 ^ 256`, from empty storage. -/ +theorem refines_of_calls {fuel : Nat} {c : TypeCheck.CheckedContract} {code : ByteArray} + {fns : List Abi.Fn} + (h : ∀ fn ∈ fns, ∀ ws : List U256, ws.length = fn.params.length → + ∃ obs, Source.run fuel c (callOf fn.sel ws) = some obs ∧ + Target.run code (callOf fn.sel ws) = some obs) : + Refines fuel c code (Abi.fullScope fns []) := by + rintro _ ⟨fn, hfn, args, hlen, hargs, rfl⟩ + have hws : (args.map (BitVec.ofNat 256)).map BitVec.toNat = args := by + rw [List.map_map] + conv_rhs => rw [← List.map_id args] + apply List.map_congr_left + intro a ha + simpa using hargs a ha + have := h fn hfn (args.map (BitVec.ofNat 256)) (by simpa using hlen) + simp only [callOf, hws] at this + exact this + +/-! ## Calls from the storage the constructor leaves + +A constructor that leaves storage `s` makes every call of `Abi.fullScope fns s` start from it: +`callAt sel ws s` (`Evm.Wide`). `deployedAt` checks what the constructor leaves, `run_eq_at` +rewrites `Source.run` of such a call as `run_eq` does from empty storage, and +`refines_of_calls_at` is `refines_of_calls` from `s`. -/ + +/-- What the constructor of `c` leaves: the state `d`, whose storage holds exactly the +entries `s`, with no logs. -/ +structure DeployedAt (fuel : Nat) (c : TypeCheck.CheckedContract) (d : Source.State) + (s : List (Nat × Nat)) : Prop where + cons : ∃ vs, TypeCheck.CheckedContract.constructWithContext? fuel c (ctxOf c) State.empty + selfAddress 0 [] = some (CallResult.returned d vs) + storage : d.storage.toList = s + events : d.events = [] + +/-- Whether the constructor of `c` leaves exactly the storage entries `s` and no logs. -/ +def deployedAt (fuel : Nat) (c : TypeCheck.CheckedContract) (s : List (Nat × Nat)) : Bool := + match TypeCheck.CheckedContract.constructWithContext? fuel c (ctxOf c) State.empty selfAddress + 0 [] with + | some (CallResult.returned d _) => d.storage.toList == s && d.events.isEmpty + | _ => false + +theorem deployedAt_of {fuel : Nat} {c : TypeCheck.CheckedContract} {s : List (Nat × Nat)} + (h : deployedAt fuel c s = true) : ∃ d, DeployedAt fuel c d s := by + unfold deployedAt at h + split at h + next d vs hc => + simp only [Bool.and_eq_true, beq_iff_eq, List.isEmpty_iff] at h + exact ⟨d, ⟨vs, hc⟩, h.1, h.2⟩ + next => simp at h + +/-- A slot the deployed storage has no entry for reads as none. -/ +theorem DeployedAt.getElem?_eq_none {fuel : Nat} {c : TypeCheck.CheckedContract} + {d : Source.State} {s : List (Nat × Nat)} (hd : DeployedAt fuel c d s) {k : Nat} + (hk : ∀ v, (k, v) ∉ s) : d.storage[k]? = none := by + rcases h : d.storage[k]? with _ | v + · rfl + · exact absurd (hd.storage ▸ Std.HashMap.mem_toList_iff_getElem?_eq_some.mpr h) (hk v) + +/-- A lookup after an insert, for the evaluator. -/ +theorem get?_insert (m : Std.HashMap Nat Nat) (k v q : Nat) : + (m.insert k v).get? q = if k = q then some v else m.get? q := by + simp only [Std.HashMap.get?_eq_getElem?, Std.HashMap.getElem?_insert, beq_iff_eq] + +/-- `Source.run` of a call from the storage `σ`, once the constructor's result is known: +the ABI dispatcher of the core contract on the call data, from the deployed state with `σ` +written over its storage. -/ +theorem run_eq_at {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : DeployedAt fuel c d s) (sel : Nat) (ws : List U256) + (σ : List (Nat × Nat)) : + Source.run fuel c (callAt sel ws σ) = + Option.map (Source.observe (callAt sel ws σ)) + (ABI.Contract.callCalldataAtFromWithContext? fuel c.core (ctxOf c) + { d with storage := σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage } + selfAddress callerAddress 0 + ((natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes (ws.map (·.toNat)))) := by + obtain ⟨vs, hc⟩ := hd.cons + simp only [Source.run, Source.result?, show (callAt sel ws σ).callvalue = 0 from rfl, + show (callAt sel ws σ).storage = σ from rfl, + show (callAt sel ws σ).calldata = Abi.calldata sel (ws.map (·.toNat)) from rfl] + rw [show ({ c.core.context with sender := callerAddress, self := selfAddress, value := 0 } : + Source.Context) = ctxOf c from rfl, hc] + simp only [TypeCheck.CheckedContract.callCalldataAtFromWithContext?, Dirty.bytes_calldata] + +theorem map_ofNat_toNat (args : List Nat) (hargs : ∀ a ∈ args, a < 2 ^ 256) : + (args.map (BitVec.ofNat 256)).map BitVec.toNat = args := by + rw [List.map_map] + conv_rhs => rw [← List.map_id args] + apply List.map_congr_left + intro a ha + simpa using Nat.mod_eq_of_lt (hargs a ha) + +/-- A call of `Abi.fullScope` is `callAt` of its argument words. -/ +theorem callAt_of_args (sel : Nat) (args : List Nat) (hargs : ∀ a ∈ args, a < 2 ^ 256) + (s : List (Nat × Nat)) : + ({ calldata := Abi.calldata sel args, callvalue := 0, storage := s } : Call) = + callAt sel (args.map (BitVec.ofNat 256)) s := by + simp only [callAt, map_ofNat_toNat args hargs] + +/-- One theorem per function on free argument words, from the storage `s`, gives the refinement +on every call of every function on any argument words below `2 ^ 256`, from `s`. -/ +theorem refines_of_calls_at {fuel : Nat} {c : TypeCheck.CheckedContract} {code : ByteArray} + {fns : List Abi.Fn} {s : List (Nat × Nat)} + (h : ∀ fn ∈ fns, ∀ ws : List U256, ws.length = fn.params.length → + ∃ obs, Source.run fuel c (callAt fn.sel ws s) = some obs ∧ + Target.run code (callAt fn.sel ws s) = some obs) : + Refines fuel c code (Abi.fullScope fns s) := by + rintro _ ⟨fn, hfn, args, hlen, hargs, rfl⟩ + rw [callAt_of_args _ _ hargs] + exact h fn hfn _ (by simpa using hlen) + +end SolidCore.Refinement.Wide diff --git a/SolidCore/Refinement/Wide/Source.lean b/SolidCore/Refinement/Wide/Source.lean new file mode 100644 index 00000000..ff1117d0 --- /dev/null +++ b/SolidCore/Refinement/Wide/Source.lean @@ -0,0 +1,141 @@ +import SolidCore.Refinement.Wide.Tactic +import SolidCore.Refinement.Dirty.Source + +/-! +# Rewrite rules for evaluating a call of a wide function in SolidCore + +`Wide.Tactic`'s evaluator runs SolidCore's interpreter by unfolding it. A few of +its functions are better rewritten than unfolded, because unfolding them on a +free argument word gives a term no later step simplifies: + +* the ABI decoder reads its argument words from `Dirty.argBytes args`, the call + data after the selector; `readWord_argBytes'` reads a word back as the argument + (rather than refolding 32 symbolic bytes), and `drop_selector` strips the + selector; +* the encoder writes a returned word big-endian; `wordToBytesBE_eq` states it as + EthLib's `natToBytes`, the form EthLib's return data takes; +* SolidCore's word operations (`Shared.addWord` and the rest) go through + evmyul's `UInt256`, a `Fin`; `addWord_eq` and its siblings state them as + operations on `BitVec 256`, the words of EthLib, and the comparisons as `if`s + on the words' values, so that the source's results and branch conditions are + terms `bv_decide` and `bv_omega` relate to the bytecode's. + +`wide_symex [lemmas]` is `src_symex` with all of them. +-/ + +namespace SolidCore.Refinement.Wide + +open EthLib.Base SolidCore.Solidity SolidCore.Solidity.Source + +theorem drop_selector (sel : Nat) (args : List Nat) : + ((natToBytes 4 sel).map (·.toNat) ++ Dirty.argBytes args).drop 4 = Dirty.argBytes args := by + simp [natToBytes_length] + +/-- The word at a word-aligned offset of the argument bytes is that argument. -/ +theorem readWord_argBytes' (args : List Nat) (hargs : ∀ a ∈ args, a < 2 ^ 256) (off : Nat) + (hmod : off % 32 = 0) (hlt : off / 32 < args.length) : + ABI.readWord? (Dirty.argBytes args) off = some (args.getD (off / 32) 0) := by + have := Dirty.readWord_argBytes args hargs (off / 32) hlt + rw [show 32 * (off / 32) = off by omega] at this + rw [this, List.getD_eq_getElem?_getD, List.getElem?_eq_getElem hlt, Option.getD_some] + +theorem normByte_eq (v : Nat) : normByte v = v % 256 := by + simp [normByte, Shared.Account.byte] + +/-- SolidCore writes a word big-endian as EthLib does. -/ +theorem wordToBytesBE_eq (n v : Nat) : + ABI.wordToBytesBE n v = (natToBytes n v).map (·.toNat) := by + induction n generalizing v with + | zero => rfl + | succ n ih => + rw [ABI.wordToBytesBE, natToBytes_succ, ih, List.map_append] + simp [normByte_eq] + +/-! ## Word operations as bit-vector operations -/ + +namespace Words + +open Shared + +theorem toNat_ofNat_u256 (n : Nat) : (EvmYul.UInt256.ofNat n).toNat = n % 2 ^ 256 := + Fin.val_ofNat _ _ +theorem toNat_add_u256 (x y : EvmYul.UInt256) : (x.add y).toNat = (x.toNat + y.toNat) % 2 ^ 256 := + Fin.val_add _ _ +theorem toNat_sub_u256 (x y : EvmYul.UInt256) : + (x.sub y).toNat = (2 ^ 256 - y.toNat + x.toNat) % 2 ^ 256 := + Fin.val_sub _ _ +theorem toNat_mul_u256 (x y : EvmYul.UInt256) : (x.mul y).toNat = (x.toNat * y.toNat) % 2 ^ 256 := + Fin.val_mul _ _ +theorem toNat_xor_u256 (x y : EvmYul.UInt256) : + (x.xor y).toNat = (x.toNat ^^^ y.toNat) % 2 ^ 256 := by + simp [EvmYul.UInt256.xor, EvmYul.UInt256.toNat, Fin.xor]; rfl +theorem toNat_land_u256 (x y : EvmYul.UInt256) : + (x.land y).toNat = (x.toNat &&& y.toNat) % 2 ^ 256 := by + simp [EvmYul.UInt256.land, EvmYul.UInt256.toNat, Fin.land]; rfl +theorem toNat_lor_u256 (x y : EvmYul.UInt256) : + (x.lor y).toNat = (x.toNat ||| y.toNat) % 2 ^ 256 := by + simp [EvmYul.UInt256.lor, EvmYul.UInt256.toNat, Fin.lor]; rfl + +theorem size_eq : EvmYul.UInt256.size = 2 ^ 256 := rfl + +end Words + +open Shared Words in +theorem addWord_eq (a b : Nat) : addWord a b = (BitVec.ofNat 256 a + BitVec.ofNat 256 b).toNat := by + simp only [addWord, liftEvmBinary, ofEvmWord, toEvmWord, norm, Shared.wordModulus, toNat_add_u256, + toNat_ofNat_u256, EvmYul.UInt256.size, BitVec.toNat_add, BitVec.toNat_ofNat, Nat.reducePow, Nat.mod_mod] + +open Shared Words in +theorem subWord_eq (a b : Nat) : subWord a b = (BitVec.ofNat 256 a - BitVec.ofNat 256 b).toNat := by + simp only [subWord, liftEvmBinary, ofEvmWord, toEvmWord, norm, Shared.wordModulus, toNat_sub_u256, + toNat_ofNat_u256, EvmYul.UInt256.size, BitVec.toNat_sub, BitVec.toNat_ofNat, Nat.reducePow, Nat.mod_mod] + +open Shared Words in +theorem mulWord_eq (a b : Nat) : mulWord a b = (BitVec.ofNat 256 a * BitVec.ofNat 256 b).toNat := by + simp only [mulWord, liftEvmBinary, ofEvmWord, toEvmWord, norm, Shared.wordModulus, toNat_mul_u256, + toNat_ofNat_u256, EvmYul.UInt256.size, BitVec.toNat_mul, BitVec.toNat_ofNat, Nat.reducePow, Nat.mod_mod] + +open Shared Words in +theorem xorWord_eq (a b : Nat) : xorWord a b = (BitVec.ofNat 256 a ^^^ BitVec.ofNat 256 b).toNat := by + simp only [xorWord, liftEvmBinary, ofEvmWord, toEvmWord, norm, Shared.wordModulus, toNat_xor_u256, + toNat_ofNat_u256, EvmYul.UInt256.size, BitVec.toNat_xor, BitVec.toNat_ofNat, Nat.reducePow, Nat.mod_mod] + exact Nat.mod_eq_of_lt (Nat.xor_lt_two_pow (n := 256) (Nat.mod_lt _ (by decide)) + (Nat.mod_lt _ (by decide))) + +open Shared Words in +theorem andWord_eq (a b : Nat) : andWord a b = (BitVec.ofNat 256 a &&& BitVec.ofNat 256 b).toNat := by + simp only [andWord, liftEvmBinary, ofEvmWord, toEvmWord, norm, Shared.wordModulus, toNat_land_u256, + toNat_ofNat_u256, EvmYul.UInt256.size, BitVec.toNat_and, BitVec.toNat_ofNat, Nat.reducePow, Nat.mod_mod] + exact Nat.mod_eq_of_lt (Nat.lt_of_le_of_lt Nat.and_le_left (Nat.mod_lt (y := 2 ^ 256) _ (by decide))) + +open Shared Words in +theorem orWord_eq (a b : Nat) : orWord a b = (BitVec.ofNat 256 a ||| BitVec.ofNat 256 b).toNat := by + simp only [orWord, liftEvmBinary, ofEvmWord, toEvmWord, norm, Shared.wordModulus, toNat_lor_u256, + toNat_ofNat_u256, EvmYul.UInt256.size, BitVec.toNat_or, BitVec.toNat_ofNat, Nat.reducePow, Nat.mod_mod] + exact Nat.mod_eq_of_lt (Nat.or_lt_two_pow (n := 256) (Nat.mod_lt _ (by decide)) + (Nat.mod_lt _ (by decide))) + +open Shared Words in +theorem ltWord_eq (a b : Nat) : ltWord a b = if a % 2 ^ 256 < b % 2 ^ 256 then 1 else 0 := by + have key : (EvmYul.UInt256.ofNat (norm a) < EvmYul.UInt256.ofNat (norm b)) ↔ + a % 2 ^ 256 < b % 2 ^ 256 := by + show (EvmYul.UInt256.ofNat (norm a)).toNat < (EvmYul.UInt256.ofNat (norm b)).toNat ↔ _ + rw [toNat_ofNat_u256, toNat_ofNat_u256] + simp [norm, Shared.wordModulus, EvmYul.UInt256.size] + unfold ltWord liftEvmBinary ofEvmWord toEvmWord EvmYul.UInt256.lt EvmYul.UInt256.fromBool + Bool.toUInt256 + by_cases h : a % 2 ^ 256 < b % 2 ^ 256 + · rw [if_pos (decide_eq_true (key.mpr h)), if_pos h]; rfl + · rw [if_neg (by simpa using fun h' => h (key.mp h')), if_neg h]; rfl + +open Shared in +theorem gtWord_eq (a b : Nat) : gtWord a b = if b % 2 ^ 256 < a % 2 ^ 256 then 1 else 0 := by + rw [← ltWord_eq]; rfl + +/-- The rewrite rules of a call of a wide function, for `src_symex`. -/ +macro "wide_symex" " [" ts:term,* "]" : tactic => + `(tactic| src_symex [Dirty.readSelector_calldata, drop_selector, readWord_argBytes', + wordToBytesBE_eq, Dirty.length_argBytes, addWord_eq, subWord_eq, mulWord_eq, xorWord_eq, + andWord_eq, orWord_eq, ltWord_eq, gtWord_eq, BitVec.ofNat_toNat, BitVec.setWidth_eq, $ts,*]) + +end SolidCore.Refinement.Wide diff --git a/SolidCore/Refinement/Wide/Tactic.lean b/SolidCore/Refinement/Wide/Tactic.lean new file mode 100644 index 00000000..838c75fc --- /dev/null +++ b/SolidCore/Refinement/Wide/Tactic.lean @@ -0,0 +1,486 @@ +import Lean +import SolidCore.Solidity.Checked + +/-! +# A symbolic evaluator for SolidCore's interpreter + +SolidCore's interpreter (`SolidCore.Solidity.Interpreter`) is an ordinary Lean +function: structural recursion on fuel and on the syntax, over `Nat` words, in +the interaction monad `SolI`. For a fixed contract and a call whose argument +words are free variables, everything but the arithmetic on those variables is +concrete, so `simp` can run the interpreter: it unfolds each definition when it +meets it, reduces the matches and `if`s whose discriminants become constructors +or decidable ground facts, and leaves the terms on the free words. + +`src_eval [lemmas]` does that to a fixed point. Each round it collects the +definitions of the interpreter (`SolidCore.Solidity.Source`, `SolidCore.Solidity.Shared` +and the interaction monad `EvmCompiler.Simulation.Interaction`), the monad helpers +and the instances of the monad classes that occur in the goal, adds their +equations to `simp`'s set, and simplifies with them, the lemmas given, the +hypotheses in context, `monadLemmas`, which turn the monad operations of `SolI`, +`Except` and `Option` into their definitions, and `wordLemmas`. It unfolds only +what occurs, so it generates equations for the few hundred definitions a call +reaches rather than for the thousands the interpreter has. Definitions by +well-founded recursion stay folded, since their equations would unfold forever. + +`src_symex [lemmas]` adds path splitting: when the goal no longer simplifies, +it splits on the innermost condition of an `if` it still holds (`by_cases`), or else +on its first `match` (`split`), and continues on each branch with the branch +condition as a hypothesis that later rounds rewrite with. A branch whose +conditions contradict each other by `omega` is closed. It leaves a branch that +neither simplifies nor splits to the caller. + +`wordLemmas` are the facts about a 256-bit word `w.toNat` the evaluator needs +to see that SolidCore's normalisation of words does not change it, and the +bounds of `&&&`, `^^^` and `|||` at each byte width (`widthLemmas`), which +discharge the range checks of SolidCore's casts and cleanups. + +Measured on the corpus: unfolding every definition of the interpreter up front +(1119 to 1844 of them) fails, since generating their equations exceeds the +recursion and heartbeat limits; unfolding on demand reaches a fixed point in +about 15 rounds and 240 definitions for `w1`. +-/ + +open Lean Meta Elab Tactic + +namespace SolidCore.Refinement.Wide + +/-- The name prefixes whose definitions the source evaluator unfolds. -/ +def evalPrefixes : List Name := + [`SolidCore.Solidity.Source, `SolidCore.Solidity.Shared, `EvmCompiler.Simulation.Interaction] + +/-- Whether `n` is a definition of the interpreter: in one of `evalPrefixes`, and not an +auxiliary or a matcher. -/ +def interpreterDef (env : Environment) (n : Name) : Option ConstantInfo := + match env.find? n with + | some ci@(.defnInfo _) => + if evalPrefixes.any (·.isPrefixOf n) && !n.isInternalDetail && !isAuxRecursor env n && + !isNoConfusion env n && !(Meta.isMatcherCore env n) then some ci else none + | _ => none + +/-- Whether the evaluator unfolds `n`: a definition of the interpreter that is not by +well-founded recursion, or one by well-founded recursion that matches on its arguments, so +that each of its several equations fires only on its constructors. An unconditional equation +of a function by well-founded recursion would unfold forever. -/ +def unfoldable (n : Name) : MetaM Bool := do + let some ci := interpreterDef (← getEnv) n | return false + unless ci.value!.getUsedConstants.contains ``WellFounded.fix do return true + match ← tryCatchRuntimeEx (getEqnsFor? n) (fun _ => pure none) with + | some eqs => return eqs.size > 1 + | none => return false + +/-- The monad classes whose instances the evaluator unfolds. -/ +def monadClasses : List Name := + [`Monad, `Bind, `Pure, `Functor, `Applicative, `Seq, `SeqLeft, `SeqRight, `MonadLift, + `MonadLiftT, `MonadExcept, `MonadExceptOf, `MonadFunctor, `MonadFunctorT] + +/-- Monad and option helpers the evaluator unfolds. -/ +def monadHelpers : List Name := + [`liftM, `Except.map, `Except.bind, `Except.pure, `Except.tryCatch, `Except.mapError, + `Function.comp, `Option.bind, `Option.map, `Option.getD, `Option.orElse, `Option.isSome, + `Option.isNone] + +/-- Whether `n` is an instance of one of the monad classes. -/ +def isMonadInstance (n : Name) : MetaM Bool := do + unless isInstanceCore (← getEnv) n do return false + let ci ← getConstInfo n + forallTelescopeReducing ci.type fun _ body => do + let body ← whnfR body + return monadClasses.contains body.getAppFn.constName + +/-- The constants of `e` the evaluator unfolds. -/ +def unfoldableIn (e : Expr) : MetaM NameSet := do + let mut s : NameSet := {} + for n in e.getUsedConstants do + if (← unfoldable n) || monadHelpers.contains n || (← isMonadInstance n) then + s := s.insert n + return s + +section MonadLemmas + +open EvmCompiler.Simulation SolidCore.Solidity.Source + +variable {E α β : Type} + +theorem interaction_bind (x : Interaction E α) (f : α → Interaction E β) : + x >>= f = Interaction.bind x f := rfl +theorem interaction_pure (a : α) : (pure a : Interaction E α) = .done (.ok a) := rfl +theorem interaction_map (f : α → β) (x : Interaction E α) : + f <$> x = Interaction.bind x (fun a => .done (.ok (f a))) := rfl +theorem interaction_throw (e : E) : (throw e : Interaction E α) = .done (.error e) := rfl +theorem interaction_tryCatch (x : Interaction E α) (h : E → Interaction E α) : + tryCatch x h = Interaction.tryCatch x h := rfl +theorem interaction_tryCatchThe (x : Interaction E α) (h : E → Interaction E α) : + tryCatchThe E x h = Interaction.tryCatch x h := rfl +theorem solI_lift (x : Except RevertData α) : (monadLift x : SolI α) = SolI.ofExcept x := rfl +theorem solI_liftM (x : Except RevertData α) : (liftM x : SolI α) = SolI.ofExcept x := rfl +theorem except_bind {ε : Type} (x : Except ε α) (f : α → Except ε β) : + x >>= f = Except.bind x f := rfl +theorem except_pure {ε : Type} (a : α) : (pure a : Except ε α) = .ok a := rfl +theorem except_map {ε : Type} (f : α → β) (x : Except ε α) : f <$> x = Except.map f x := rfl +theorem except_throw {ε : Type} (e : ε) : (throw e : Except ε α) = .error e := rfl +theorem option_bind (x : Option α) (f : α → Option β) : x >>= f = Option.bind x f := rfl +theorem option_pure (a : α) : (pure a : Option α) = some a := rfl +theorem option_map (f : α → β) (x : Option α) : f <$> x = Option.map f x := rfl + +end MonadLemmas + +/-- The monad lemmas the evaluator always uses. -/ +def monadLemmas : List Name := + [``interaction_bind, ``interaction_pure, ``interaction_map, ``interaction_throw, + ``interaction_tryCatch, ``interaction_tryCatchThe, ``solI_lift, ``solI_liftM, + ``except_bind, ``except_pure, ``except_map, ``except_throw, ``option_bind, + ``option_pure, ``option_map] + +/-! ## Words -/ + +/-- The number of 256-bit words, as the literal `simp` reduces `2 ^ 256` to. -/ +abbrev wordCount : Nat := + 115792089237316195423570985008687907853269984665640564039457584007913129639936 + +theorem uint256_size : EvmYul.UInt256.size = 115792089237316195423570985008687907853269984665640564039457584007913129639936 := rfl +theorem wordModulus_eq : SolidCore.Solidity.Shared.wordModulus = 115792089237316195423570985008687907853269984665640564039457584007913129639936 := rfl +theorem toNat_mod_word (w : BitVec 256) : w.toNat % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = w.toNat := + Nat.mod_eq_of_lt w.isLt +theorem toNat_lt_word (w : BitVec 256) : w.toNat < 115792089237316195423570985008687907853269984665640564039457584007913129639936 := w.isLt +theorem not_word_le_toNat (w : BitVec 256) : ¬ 115792089237316195423570985008687907853269984665640564039457584007913129639936 ≤ w.toNat := Nat.not_le.mpr w.isLt +theorem mod_word_lt (x : Nat) : x % 115792089237316195423570985008687907853269984665640564039457584007913129639936 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 := Nat.mod_lt _ (by decide) +theorem not_word_le_mod (x : Nat) : ¬ 115792089237316195423570985008687907853269984665640564039457584007913129639936 ≤ x % 115792089237316195423570985008687907853269984665640564039457584007913129639936 := Nat.not_le.mpr (Nat.mod_lt _ (by decide)) + +theorem ite_mod_word (p : Prop) [Decidable p] (a b : Nat) : + (if p then a else b) % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = if p then a % 115792089237316195423570985008687907853269984665640564039457584007913129639936 else b % 115792089237316195423570985008687907853269984665640564039457584007913129639936 := by + split <;> rfl + +theorem mod_mod_of_le (x m n : Nat) (hm : 0 < m) (h : m ≤ n) : x % m % n = x % m := + Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le (Nat.mod_lt _ hm) h) + +theorem mod_lt_of_le (x m n : Nat) (hm : 0 < m) (h : m ≤ n) : x % m < n := + Nat.lt_of_lt_of_le (Nat.mod_lt _ hm) h + +theorem and_lt_of_lt (a b m : Nat) (ha : a < m) : a &&& b < m := + Nat.lt_of_le_of_lt Nat.and_le_left ha + +/-! The bounds of `^^^` and `|||` on words of each width that is a whole number of bytes, with +the width's number of words as the literal `simp` reduces `2 ^ k` to. -/ + +theorem xor_lt_8 (a b : Nat) (ha : a < 256) (hb : b < 256) : a ^^^ b < 256 := + Nat.xor_lt_two_pow (n := 8) ha hb + +theorem or_lt_8 (a b : Nat) (ha : a < 256) (hb : b < 256) : a ||| b < 256 := + Nat.or_lt_two_pow (n := 8) ha hb + +theorem xor_lt_16 (a b : Nat) (ha : a < 65536) (hb : b < 65536) : a ^^^ b < 65536 := + Nat.xor_lt_two_pow (n := 16) ha hb + +theorem or_lt_16 (a b : Nat) (ha : a < 65536) (hb : b < 65536) : a ||| b < 65536 := + Nat.or_lt_two_pow (n := 16) ha hb + +theorem xor_lt_24 (a b : Nat) (ha : a < 16777216) (hb : b < 16777216) : a ^^^ b < 16777216 := + Nat.xor_lt_two_pow (n := 24) ha hb + +theorem or_lt_24 (a b : Nat) (ha : a < 16777216) (hb : b < 16777216) : a ||| b < 16777216 := + Nat.or_lt_two_pow (n := 24) ha hb + +theorem xor_lt_32 (a b : Nat) (ha : a < 4294967296) (hb : b < 4294967296) : a ^^^ b < 4294967296 := + Nat.xor_lt_two_pow (n := 32) ha hb + +theorem or_lt_32 (a b : Nat) (ha : a < 4294967296) (hb : b < 4294967296) : a ||| b < 4294967296 := + Nat.or_lt_two_pow (n := 32) ha hb + +theorem xor_lt_40 (a b : Nat) (ha : a < 1099511627776) (hb : b < 1099511627776) : a ^^^ b < 1099511627776 := + Nat.xor_lt_two_pow (n := 40) ha hb + +theorem or_lt_40 (a b : Nat) (ha : a < 1099511627776) (hb : b < 1099511627776) : a ||| b < 1099511627776 := + Nat.or_lt_two_pow (n := 40) ha hb + +theorem xor_lt_48 (a b : Nat) (ha : a < 281474976710656) (hb : b < 281474976710656) : a ^^^ b < 281474976710656 := + Nat.xor_lt_two_pow (n := 48) ha hb + +theorem or_lt_48 (a b : Nat) (ha : a < 281474976710656) (hb : b < 281474976710656) : a ||| b < 281474976710656 := + Nat.or_lt_two_pow (n := 48) ha hb + +theorem xor_lt_56 (a b : Nat) (ha : a < 72057594037927936) (hb : b < 72057594037927936) : a ^^^ b < 72057594037927936 := + Nat.xor_lt_two_pow (n := 56) ha hb + +theorem or_lt_56 (a b : Nat) (ha : a < 72057594037927936) (hb : b < 72057594037927936) : a ||| b < 72057594037927936 := + Nat.or_lt_two_pow (n := 56) ha hb + +theorem xor_lt_64 (a b : Nat) (ha : a < 18446744073709551616) (hb : b < 18446744073709551616) : a ^^^ b < 18446744073709551616 := + Nat.xor_lt_two_pow (n := 64) ha hb + +theorem or_lt_64 (a b : Nat) (ha : a < 18446744073709551616) (hb : b < 18446744073709551616) : a ||| b < 18446744073709551616 := + Nat.or_lt_two_pow (n := 64) ha hb + +theorem xor_lt_72 (a b : Nat) (ha : a < 4722366482869645213696) (hb : b < 4722366482869645213696) : a ^^^ b < 4722366482869645213696 := + Nat.xor_lt_two_pow (n := 72) ha hb + +theorem or_lt_72 (a b : Nat) (ha : a < 4722366482869645213696) (hb : b < 4722366482869645213696) : a ||| b < 4722366482869645213696 := + Nat.or_lt_two_pow (n := 72) ha hb + +theorem xor_lt_80 (a b : Nat) (ha : a < 1208925819614629174706176) (hb : b < 1208925819614629174706176) : a ^^^ b < 1208925819614629174706176 := + Nat.xor_lt_two_pow (n := 80) ha hb + +theorem or_lt_80 (a b : Nat) (ha : a < 1208925819614629174706176) (hb : b < 1208925819614629174706176) : a ||| b < 1208925819614629174706176 := + Nat.or_lt_two_pow (n := 80) ha hb + +theorem xor_lt_88 (a b : Nat) (ha : a < 309485009821345068724781056) (hb : b < 309485009821345068724781056) : a ^^^ b < 309485009821345068724781056 := + Nat.xor_lt_two_pow (n := 88) ha hb + +theorem or_lt_88 (a b : Nat) (ha : a < 309485009821345068724781056) (hb : b < 309485009821345068724781056) : a ||| b < 309485009821345068724781056 := + Nat.or_lt_two_pow (n := 88) ha hb + +theorem xor_lt_96 (a b : Nat) (ha : a < 79228162514264337593543950336) (hb : b < 79228162514264337593543950336) : a ^^^ b < 79228162514264337593543950336 := + Nat.xor_lt_two_pow (n := 96) ha hb + +theorem or_lt_96 (a b : Nat) (ha : a < 79228162514264337593543950336) (hb : b < 79228162514264337593543950336) : a ||| b < 79228162514264337593543950336 := + Nat.or_lt_two_pow (n := 96) ha hb + +theorem xor_lt_104 (a b : Nat) (ha : a < 20282409603651670423947251286016) (hb : b < 20282409603651670423947251286016) : a ^^^ b < 20282409603651670423947251286016 := + Nat.xor_lt_two_pow (n := 104) ha hb + +theorem or_lt_104 (a b : Nat) (ha : a < 20282409603651670423947251286016) (hb : b < 20282409603651670423947251286016) : a ||| b < 20282409603651670423947251286016 := + Nat.or_lt_two_pow (n := 104) ha hb + +theorem xor_lt_112 (a b : Nat) (ha : a < 5192296858534827628530496329220096) (hb : b < 5192296858534827628530496329220096) : a ^^^ b < 5192296858534827628530496329220096 := + Nat.xor_lt_two_pow (n := 112) ha hb + +theorem or_lt_112 (a b : Nat) (ha : a < 5192296858534827628530496329220096) (hb : b < 5192296858534827628530496329220096) : a ||| b < 5192296858534827628530496329220096 := + Nat.or_lt_two_pow (n := 112) ha hb + +theorem xor_lt_120 (a b : Nat) (ha : a < 1329227995784915872903807060280344576) (hb : b < 1329227995784915872903807060280344576) : a ^^^ b < 1329227995784915872903807060280344576 := + Nat.xor_lt_two_pow (n := 120) ha hb + +theorem or_lt_120 (a b : Nat) (ha : a < 1329227995784915872903807060280344576) (hb : b < 1329227995784915872903807060280344576) : a ||| b < 1329227995784915872903807060280344576 := + Nat.or_lt_two_pow (n := 120) ha hb + +theorem xor_lt_128 (a b : Nat) (ha : a < 340282366920938463463374607431768211456) (hb : b < 340282366920938463463374607431768211456) : a ^^^ b < 340282366920938463463374607431768211456 := + Nat.xor_lt_two_pow (n := 128) ha hb + +theorem or_lt_128 (a b : Nat) (ha : a < 340282366920938463463374607431768211456) (hb : b < 340282366920938463463374607431768211456) : a ||| b < 340282366920938463463374607431768211456 := + Nat.or_lt_two_pow (n := 128) ha hb + +theorem xor_lt_136 (a b : Nat) (ha : a < 87112285931760246646623899502532662132736) (hb : b < 87112285931760246646623899502532662132736) : a ^^^ b < 87112285931760246646623899502532662132736 := + Nat.xor_lt_two_pow (n := 136) ha hb + +theorem or_lt_136 (a b : Nat) (ha : a < 87112285931760246646623899502532662132736) (hb : b < 87112285931760246646623899502532662132736) : a ||| b < 87112285931760246646623899502532662132736 := + Nat.or_lt_two_pow (n := 136) ha hb + +theorem xor_lt_144 (a b : Nat) (ha : a < 22300745198530623141535718272648361505980416) (hb : b < 22300745198530623141535718272648361505980416) : a ^^^ b < 22300745198530623141535718272648361505980416 := + Nat.xor_lt_two_pow (n := 144) ha hb + +theorem or_lt_144 (a b : Nat) (ha : a < 22300745198530623141535718272648361505980416) (hb : b < 22300745198530623141535718272648361505980416) : a ||| b < 22300745198530623141535718272648361505980416 := + Nat.or_lt_two_pow (n := 144) ha hb + +theorem xor_lt_152 (a b : Nat) (ha : a < 5708990770823839524233143877797980545530986496) (hb : b < 5708990770823839524233143877797980545530986496) : a ^^^ b < 5708990770823839524233143877797980545530986496 := + Nat.xor_lt_two_pow (n := 152) ha hb + +theorem or_lt_152 (a b : Nat) (ha : a < 5708990770823839524233143877797980545530986496) (hb : b < 5708990770823839524233143877797980545530986496) : a ||| b < 5708990770823839524233143877797980545530986496 := + Nat.or_lt_two_pow (n := 152) ha hb + +theorem xor_lt_160 (a b : Nat) (ha : a < 1461501637330902918203684832716283019655932542976) (hb : b < 1461501637330902918203684832716283019655932542976) : a ^^^ b < 1461501637330902918203684832716283019655932542976 := + Nat.xor_lt_two_pow (n := 160) ha hb + +theorem or_lt_160 (a b : Nat) (ha : a < 1461501637330902918203684832716283019655932542976) (hb : b < 1461501637330902918203684832716283019655932542976) : a ||| b < 1461501637330902918203684832716283019655932542976 := + Nat.or_lt_two_pow (n := 160) ha hb + +theorem xor_lt_168 (a b : Nat) (ha : a < 374144419156711147060143317175368453031918731001856) (hb : b < 374144419156711147060143317175368453031918731001856) : a ^^^ b < 374144419156711147060143317175368453031918731001856 := + Nat.xor_lt_two_pow (n := 168) ha hb + +theorem or_lt_168 (a b : Nat) (ha : a < 374144419156711147060143317175368453031918731001856) (hb : b < 374144419156711147060143317175368453031918731001856) : a ||| b < 374144419156711147060143317175368453031918731001856 := + Nat.or_lt_two_pow (n := 168) ha hb + +theorem xor_lt_176 (a b : Nat) (ha : a < 95780971304118053647396689196894323976171195136475136) (hb : b < 95780971304118053647396689196894323976171195136475136) : a ^^^ b < 95780971304118053647396689196894323976171195136475136 := + Nat.xor_lt_two_pow (n := 176) ha hb + +theorem or_lt_176 (a b : Nat) (ha : a < 95780971304118053647396689196894323976171195136475136) (hb : b < 95780971304118053647396689196894323976171195136475136) : a ||| b < 95780971304118053647396689196894323976171195136475136 := + Nat.or_lt_two_pow (n := 176) ha hb + +theorem xor_lt_184 (a b : Nat) (ha : a < 24519928653854221733733552434404946937899825954937634816) (hb : b < 24519928653854221733733552434404946937899825954937634816) : a ^^^ b < 24519928653854221733733552434404946937899825954937634816 := + Nat.xor_lt_two_pow (n := 184) ha hb + +theorem or_lt_184 (a b : Nat) (ha : a < 24519928653854221733733552434404946937899825954937634816) (hb : b < 24519928653854221733733552434404946937899825954937634816) : a ||| b < 24519928653854221733733552434404946937899825954937634816 := + Nat.or_lt_two_pow (n := 184) ha hb + +theorem xor_lt_192 (a b : Nat) (ha : a < 6277101735386680763835789423207666416102355444464034512896) (hb : b < 6277101735386680763835789423207666416102355444464034512896) : a ^^^ b < 6277101735386680763835789423207666416102355444464034512896 := + Nat.xor_lt_two_pow (n := 192) ha hb + +theorem or_lt_192 (a b : Nat) (ha : a < 6277101735386680763835789423207666416102355444464034512896) (hb : b < 6277101735386680763835789423207666416102355444464034512896) : a ||| b < 6277101735386680763835789423207666416102355444464034512896 := + Nat.or_lt_two_pow (n := 192) ha hb + +theorem xor_lt_200 (a b : Nat) (ha : a < 1606938044258990275541962092341162602522202993782792835301376) (hb : b < 1606938044258990275541962092341162602522202993782792835301376) : a ^^^ b < 1606938044258990275541962092341162602522202993782792835301376 := + Nat.xor_lt_two_pow (n := 200) ha hb + +theorem or_lt_200 (a b : Nat) (ha : a < 1606938044258990275541962092341162602522202993782792835301376) (hb : b < 1606938044258990275541962092341162602522202993782792835301376) : a ||| b < 1606938044258990275541962092341162602522202993782792835301376 := + Nat.or_lt_two_pow (n := 200) ha hb + +theorem xor_lt_208 (a b : Nat) (ha : a < 411376139330301510538742295639337626245683966408394965837152256) (hb : b < 411376139330301510538742295639337626245683966408394965837152256) : a ^^^ b < 411376139330301510538742295639337626245683966408394965837152256 := + Nat.xor_lt_two_pow (n := 208) ha hb + +theorem or_lt_208 (a b : Nat) (ha : a < 411376139330301510538742295639337626245683966408394965837152256) (hb : b < 411376139330301510538742295639337626245683966408394965837152256) : a ||| b < 411376139330301510538742295639337626245683966408394965837152256 := + Nat.or_lt_two_pow (n := 208) ha hb + +theorem xor_lt_216 (a b : Nat) (ha : a < 105312291668557186697918027683670432318895095400549111254310977536) (hb : b < 105312291668557186697918027683670432318895095400549111254310977536) : a ^^^ b < 105312291668557186697918027683670432318895095400549111254310977536 := + Nat.xor_lt_two_pow (n := 216) ha hb + +theorem or_lt_216 (a b : Nat) (ha : a < 105312291668557186697918027683670432318895095400549111254310977536) (hb : b < 105312291668557186697918027683670432318895095400549111254310977536) : a ||| b < 105312291668557186697918027683670432318895095400549111254310977536 := + Nat.or_lt_two_pow (n := 216) ha hb + +theorem xor_lt_224 (a b : Nat) (ha : a < 26959946667150639794667015087019630673637144422540572481103610249216) (hb : b < 26959946667150639794667015087019630673637144422540572481103610249216) : a ^^^ b < 26959946667150639794667015087019630673637144422540572481103610249216 := + Nat.xor_lt_two_pow (n := 224) ha hb + +theorem or_lt_224 (a b : Nat) (ha : a < 26959946667150639794667015087019630673637144422540572481103610249216) (hb : b < 26959946667150639794667015087019630673637144422540572481103610249216) : a ||| b < 26959946667150639794667015087019630673637144422540572481103610249216 := + Nat.or_lt_two_pow (n := 224) ha hb + +theorem xor_lt_232 (a b : Nat) (ha : a < 6901746346790563787434755862277025452451108972170386555162524223799296) (hb : b < 6901746346790563787434755862277025452451108972170386555162524223799296) : a ^^^ b < 6901746346790563787434755862277025452451108972170386555162524223799296 := + Nat.xor_lt_two_pow (n := 232) ha hb + +theorem or_lt_232 (a b : Nat) (ha : a < 6901746346790563787434755862277025452451108972170386555162524223799296) (hb : b < 6901746346790563787434755862277025452451108972170386555162524223799296) : a ||| b < 6901746346790563787434755862277025452451108972170386555162524223799296 := + Nat.or_lt_two_pow (n := 232) ha hb + +theorem xor_lt_240 (a b : Nat) (ha : a < 1766847064778384329583297500742918515827483896875618958121606201292619776) (hb : b < 1766847064778384329583297500742918515827483896875618958121606201292619776) : a ^^^ b < 1766847064778384329583297500742918515827483896875618958121606201292619776 := + Nat.xor_lt_two_pow (n := 240) ha hb + +theorem or_lt_240 (a b : Nat) (ha : a < 1766847064778384329583297500742918515827483896875618958121606201292619776) (hb : b < 1766847064778384329583297500742918515827483896875618958121606201292619776) : a ||| b < 1766847064778384329583297500742918515827483896875618958121606201292619776 := + Nat.or_lt_two_pow (n := 240) ha hb + +theorem xor_lt_248 (a b : Nat) (ha : a < 452312848583266388373324160190187140051835877600158453279131187530910662656) (hb : b < 452312848583266388373324160190187140051835877600158453279131187530910662656) : a ^^^ b < 452312848583266388373324160190187140051835877600158453279131187530910662656 := + Nat.xor_lt_two_pow (n := 248) ha hb + +theorem or_lt_248 (a b : Nat) (ha : a < 452312848583266388373324160190187140051835877600158453279131187530910662656) (hb : b < 452312848583266388373324160190187140051835877600158453279131187530910662656) : a ||| b < 452312848583266388373324160190187140051835877600158453279131187530910662656 := + Nat.or_lt_two_pow (n := 248) ha hb + +theorem xor_lt_256 (a b : Nat) (ha : a < 115792089237316195423570985008687907853269984665640564039457584007913129639936) (hb : b < 115792089237316195423570985008687907853269984665640564039457584007913129639936) : a ^^^ b < 115792089237316195423570985008687907853269984665640564039457584007913129639936 := + Nat.xor_lt_two_pow (n := 256) ha hb + +theorem or_lt_256 (a b : Nat) (ha : a < 115792089237316195423570985008687907853269984665640564039457584007913129639936) (hb : b < 115792089237316195423570985008687907853269984665640564039457584007913129639936) : a ||| b < 115792089237316195423570985008687907853269984665640564039457584007913129639936 := + Nat.or_lt_two_pow (n := 256) ha hb + +/-- The bounds of `^^^` and `|||` at each width. -/ +def widthLemmas : List Name := + [``xor_lt_8, ``or_lt_8, ``xor_lt_16, ``or_lt_16, ``xor_lt_24, ``or_lt_24, ``xor_lt_32, ``or_lt_32, ``xor_lt_40, ``or_lt_40, ``xor_lt_48, ``or_lt_48, ``xor_lt_56, ``or_lt_56, ``xor_lt_64, ``or_lt_64, ``xor_lt_72, ``or_lt_72, ``xor_lt_80, ``or_lt_80, ``xor_lt_88, ``or_lt_88, ``xor_lt_96, ``or_lt_96, ``xor_lt_104, ``or_lt_104, ``xor_lt_112, ``or_lt_112, ``xor_lt_120, ``or_lt_120, ``xor_lt_128, ``or_lt_128, ``xor_lt_136, ``or_lt_136, ``xor_lt_144, ``or_lt_144, ``xor_lt_152, ``or_lt_152, ``xor_lt_160, ``or_lt_160, ``xor_lt_168, ``or_lt_168, ``xor_lt_176, ``or_lt_176, ``xor_lt_184, ``or_lt_184, ``xor_lt_192, ``or_lt_192, ``xor_lt_200, ``or_lt_200, ``xor_lt_208, ``or_lt_208, ``xor_lt_216, ``or_lt_216, ``xor_lt_224, ``or_lt_224, ``xor_lt_232, ``or_lt_232, ``xor_lt_240, ``or_lt_240, ``xor_lt_248, ``or_lt_248, ``xor_lt_256, ``or_lt_256] + +/-- The word lemmas the evaluator always uses. -/ +def wordLemmas : List Name := + [``uint256_size, ``wordModulus_eq, ``toNat_mod_word, ``toNat_lt_word, ``not_word_le_toNat, + ``mod_word_lt, ``not_word_le_mod, ``ite_mod_word, ``mod_mod_of_le, ``mod_lt_of_le, + ``and_lt_of_lt, ``Nat.mod_eq_of_lt, ``Nat.not_le_of_lt] ++ widthLemmas + +/-! ## The tactics -/ + +/-- The simp set of the given lemmas and the monad and word lemmas. Given lemmas come at +high priority, so that they rewrite before a definition they mention is unfolded. -/ +def baseTheorems (ts : Array Syntax) : TacticM SimpTheorems := do (← getMainGoal).withContext do + let mut thms ← getSimpTheorems + for n in monadLemmas ++ wordLemmas do + thms ← thms.addConst n + for t in ts do + if t.isIdent then + if let some n ← (try some <$> realizeGlobalConstNoOverload t catch _ => pure none) then + if ((← getEnv).find? n).any ConstantInfo.isDefinition then + thms ← thms.addDeclToUnfold n + continue + let e ← elabTerm t none + thms ← thms.add (.stx (← mkFreshId) t) #[] e (prio := 2000) + return thms + +/-- Runs the evaluator on `g` to a fixed point; `none` when it closes the goal. -/ +def evalGoal (base : SimpTheorems) (g : MVarId) : TacticM (Option MVarId) := do + let mut thms := base + let mut done : NameSet := {} + let mut g := g + for _ in [0:400] do + let names ← unfoldableIn (← instantiateMVars (← g.getType)) + for n in names.toList do + unless done.contains n do + done := done.insert n + thms ← tryCatchRuntimeEx (thms.addDeclToUnfold n) (fun _ => pure thms) + let thms' := thms + let (r, _) ← g.withContext do + let mut thmsH := thms' + for h in (← getLCtx) do + if !h.isImplementationDetail && (← isProp h.type) then + thmsH ← thmsH.add (.fvar h.fvarId) #[] h.toExpr + let ctx ← Simp.mkContext + (config := { decide := true, maxSteps := 100000000, maxDischargeDepth := 4 }) + (simpTheorems := #[thmsH]) (congrTheorems := ← getSimpCongrTheorems) + try simpGoal g ctx (simprocs := #[← Simp.getSimprocs]) + catch _ => pure (some (#[], g), {}) + match r with + | none => return none + | some (_, g') => + if g' == g then return some g + g := g' + return some g + +/-- Symbolic evaluation of SolidCore's interpreter, without splitting. -/ +syntax "src_eval" (" [" term,* "]")? : tactic + +elab_rules : tactic + | `(tactic| src_eval $[[$ts,*]]?) => do + let base ← baseTheorems (ts.map (·.getElems.map (·.raw)) |>.getD #[]) + match ← evalGoal base (← getMainGoal) with + | none => replaceMainGoal [] + | some g => replaceMainGoal [g] + +/-- The condition of an `if` in `e` that mentions no bound variable, if any, innermost +first. -/ +partial def closedCond? (e : Expr) : Option Expr := + if (e.isAppOfArity ``ite 5 || e.isAppOfArity ``dite 5) && !e.appFn!.appFn!.appFn!.appArg!.hasLooseBVars then + let c := e.appFn!.appFn!.appFn!.appArg! + -- An `if` inside the condition comes first, so that each split is on an atomic fact. + (closedCond? c).orElse fun _ => some c + else + match e with + | .app f a => (closedCond? f).orElse fun _ => closedCond? a + | .lam _ t b _ | .forallE _ t b _ => (closedCond? t).orElse fun _ => closedCond? b + | .letE _ t v b _ => ((closedCond? t).orElse fun _ => closedCond? v).orElse fun _ => closedCond? b + | .mdata _ b => closedCond? b + | .proj _ _ b => closedCond? b + | _ => none + +/-- Evaluates `g`, and on each branch that no longer simplifies splits on the condition of an +`if` it still holds (by `by_cases`), or else on its first `match` (by `split`), up to +`depth` splits deep. Returns the goals left. -/ +partial def symexGoal (base : SimpTheorems) (depth : Nat) (g : MVarId) : + TacticM (List MVarId) := do + match ← evalGoal base g with + | none => return [] + | some g => + if depth = 0 then return [g] + let ty ← g.withContext do instantiateMVars (← g.getType) + let split? ← try + some <$> (do + setGoals [g] + match closedCond? ty with + | some c => + let hc ← g.withContext do Term.exprToSyntax c + evalTactic (← `(tactic| by_cases hpath : $hc)) + | none => evalTactic (← `(tactic| split)) + getGoals) + catch _ => pure none + match split? with + | none => return [g] + | some gs => + let mut out := [] + for g' in gs do + -- A branch whose path conditions contradict each other by linear arithmetic is closed. + let closed ← try + setGoals [g'] + evalTactic (← `(tactic| (exfalso; omega))) + pure true + catch _ => pure false + unless closed do + out := out ++ (← symexGoal base (depth - 1) g') + return out + +/-- Symbolic evaluation of SolidCore's interpreter with path splitting. -/ +syntax "src_symex" (" [" term,* "]")? : tactic + +elab_rules : tactic + | `(tactic| src_symex $[[$ts,*]]?) => do + let base ← baseTheorems (ts.map (·.getElems.map (·.raw)) |>.getD #[]) + let rest := (← getGoals).drop 1 + let gs ← symexGoal base 16 (← getMainGoal) + setGoals (gs ++ rest) + +end SolidCore.Refinement.Wide diff --git a/SolidCore/Solidity/ABI.lean b/SolidCore/Solidity/ABI.lean index ffe593c3..3a07726e 100644 --- a/SolidCore/Solidity/ABI.lean +++ b/SolidCore/Solidity/ABI.lean @@ -422,6 +422,29 @@ def decodeBytesTailWrap? (argData : Bytes) (base relSlot : Nat) : else Except.ok (Value.bytes (readBytesZeroPad argData addr2 length)) +/-- Decode `remaining` values in a row with `decode`, starting at head index `index`; +each value after the first starts `step` head words after the one before. `step` is +read after each value, so a value's own error comes first. -/ +def decodeValueSeq? (decode : Nat -> Except RevertData Value) (step : Option Nat) : + Nat -> Nat -> Except RevertData (List Value) + | 0, _ => Except.ok [] + | remaining + 1, index => do + let value ← decode index + let width ← abiArgOpt step + let rest ← decodeValueSeq? decode step remaining (index + width) + Except.ok (value :: rest) + +/-- Decode one value of each type in `tys` with `decode`, starting at head index +`index` and advancing by each type's head words, read after its value. -/ +def decodeValueList? (decode : Ty -> Nat -> Except RevertData Value) : + List Ty -> Nat -> Except RevertData (List Value) + | [], _ => Except.ok [] + | ty :: tys, index => do + let value ← decode ty index + let width ← abiArgOpt (Ty.abiHeadWords? ty) + let rest ← decodeValueList? decode tys (index + width) + Except.ok (value :: rest) + -- Returns `Except RevertData Value`: `Except.error RevertData.empty` is solc's -- empty `revert(0, 0)` (bounds / dirty-value / enum-range failure), while -- `Except.error RevertData.memoryAllocationTooLarge` is Panic(0x41), raised only @@ -506,11 +529,8 @@ def decodeValueAtWithFuel? : Nat -> Bool -> Bytes -> Nat -> Ty -> Except RevertD -- termination measure is preserved. `lazy` is threaded unchanged into the -- element decode, so an eager array of eager reference elements fires each -- element's own Panic(0x41) guard. - let rec decodeDynamicArrayValues? : - Nat -> Nat -> Except RevertData (List Value) - | 0, _ => Except.ok [] - | remaining + 1, index => do - let value ← + let decodeDynamicArrayValues? := + decodeValueSeq? (fun index => match decodeValueAtWithFuel? fuel lazy (argData.drop (offset + wordBytes)) index elementTy @@ -553,9 +573,7 @@ def decodeValueAtWithFuel? : Nat -> Bool -> Bytes -> Nat -> Ty -> Except RevertD | _ => Except.ok (Value.calldataDeferredInvalid elementTy) else Except.error e - let step ← abiArgOpt (Ty.abiHeadWords? elementTy) - let rest ← decodeDynamicArrayValues? remaining (index + step) - Except.ok (value :: rest) + ) (Ty.abiHeadWords? elementTy) let step ← abiArgOpt (Ty.abiHeadWords? elementTy) -- Head-area presence check (solc `abi_decode_available_length_*_array`: -- `srcEnd := add(arrayPos, mul(length, headStride)); if gt(srcEnd, end)`): @@ -581,11 +599,8 @@ def decodeValueAtWithFuel? : Nat -> Bool -> Bytes -> Nat -> Ty -> Except RevertD -- constant (`size`), never attacker-controlled, so no length-panic arises -- here; an oversized inner *dynamic* element fires its own guard via the -- threaded (`lazy = false`) element decode below. - let rec decodeArrayValues? (arrayData : Bytes) : - Nat -> Nat -> Except RevertData (List Value) - | 0, _ => Except.ok [] - | remaining + 1, index => do - let value ← + let decodeArrayValues? := fun (arrayData : Bytes) => + decodeValueSeq? (fun index => match decodeValueAtWithFuel? fuel lazy arrayData index elementTy with | Except.ok v => Except.ok v | Except.error e => @@ -597,9 +612,7 @@ def decodeValueAtWithFuel? : Nat -> Bool -> Bytes -> Nat -> Ty -> Except RevertD Except.ok (Value.calldataDeferredInvalid elementTy) else Except.error e - let step ← abiArgOpt (Ty.abiHeadWords? elementTy) - let rest ← decodeArrayValues? arrayData remaining (index + step) - Except.ok (value :: rest) + ) (Ty.abiHeadWords? elementTy) if Ty.isDynamicAbi elementTy then do let offset ← abiArgOpt (readWord? argData (wordBytes * headIndex)) @@ -630,11 +643,8 @@ def decodeValueAtWithFuel? : Nat -> Bool -> Bytes -> Nat -> Ty -> Except RevertD let values ← decodeArrayValues? argData size headIndex Except.ok (Value.fixedArray values) | fuel + 1, lazy, argData, headIndex, Ty.tuple elementTys => - let rec decodeTupleValues? (tupleData : Bytes) : - List Ty -> Nat -> Except RevertData (List Value) - | [], _ => Except.ok [] - | ty :: tys, index => do - let value ← + let decodeTupleValues? := fun (tupleData : Bytes) => + decodeValueList? (fun ty index => match decodeValueAtWithFuel? fuel lazy tupleData index ty with | Except.ok v => Except.ok v | Except.error e => @@ -648,9 +658,7 @@ def decodeValueAtWithFuel? : Nat -> Bool -> Bytes -> Nat -> Ty -> Except RevertD Except.ok (Value.calldataDeferredInvalid ty) else Except.error e - let step ← abiArgOpt (Ty.abiHeadWords? ty) - let rest ← decodeTupleValues? tupleData tys (index + step) - Except.ok (value :: rest) + ) if Ty.listHasDynamicAbi elementTys then do let offset ← abiArgOpt (readWord? argData (wordBytes * headIndex)) @@ -820,7 +828,7 @@ def encodeReturnOutputForDispatch? (dispatchKind : AbiDispatchKind) match dispatchKind, returns, values with | AbiDispatchKind.fallback, [], [] => some [] | AbiDispatchKind.fallback, - [{ ty := Ty.bytesCalldata, name := _ }], [Value.bytes bytes] => + [{ ty := Ty.bytesCalldata, name := _, .. }], [Value.bytes bytes] => some (normalizeBytes bytes) | _, _, _ => encodeValues? (returns.map BindingDecl.ty) values @@ -864,7 +872,7 @@ def FunctionDef.encodeFallbackOutput? (function : FunctionDef) (values : List Value) : Option Bytes := match function.returns, values with | [], [] => some [] - | [{ ty := Ty.bytesCalldata, name := _ }], [Value.bytes bytes] => + | [{ ty := Ty.bytesCalldata, name := _, .. }], [Value.bytes bytes] => some (normalizeBytes bytes) | _, _ => encodeValues? (function.returns.map BindingDecl.ty) values diff --git a/SolidCore/Solidity/AdoptionLaws.lean b/SolidCore/Solidity/AdoptionLaws.lean index ec0f3ce6..d3c28d99 100644 --- a/SolidCore/Solidity/AdoptionLaws.lean +++ b/SolidCore/Solidity/AdoptionLaws.lean @@ -194,7 +194,7 @@ theorem find?_storage_foldl (L : List (Word × Word)) (init : EvmYul.Storage) rw [compare_wordToU256_eq_iff, wordEq_iff_norm] exact ((wordEq_iff_norm _ _).1 hb).symm simp only [hb, Option.elim] - rw [Batteries.RBMap.find?_insert_of_eq _ hc] + rw [RBTree.RBMap.find?_insert_of_eq _ hc] · have hbf : wordEq kv.1 k = false := by cases hh : wordEq kv.1 k · rfl @@ -206,7 +206,7 @@ theorem find?_storage_foldl (L : List (Word × Word)) (init : EvmYul.Storage) rw [wordEq_iff_norm] at hkk ⊢; exact hkk.symm exact hb hsym simp only [hbf, Option.elim] - rw [Batteries.RBMap.find?_insert_of_ne _ hc] + rw [RBTree.RBMap.find?_insert_of_ne _ hc] /-- First-match `find?` is determined by membership + uniqueness. -/ theorem list_find?_eq_some_of_unique {α : Type} {l : List α} {p : α → Bool} @@ -238,7 +238,7 @@ theorem toList_find?_eq_findEntry? (T : EvmYul.Storage) (u : EvmYul.UInt256) : T.findEntry? u := by cases hFind : T.findEntry? u with | some y => - have hMem := (Batteries.RBMap.findEntry?_some.1 hFind) + have hMem := (RBTree.RBMap.findEntry?_some.1 hFind) apply list_find?_eq_some_of_unique hMem.1 · simp [hMem.2] · intro z hz hpz @@ -256,17 +256,17 @@ theorem toList_find?_eq_findEntry? (T : EvmYul.Storage) (u : EvmYul.UInt256) : have h₂ := Std.TransCmp.congr_left (cmp := compare) h₁ (c := y.1) rw [h₂] exact hMem.2 - exact Batteries.RBSet.mem_toList_unique hz hMem.1 hyz + exact RBTree.RBSet.mem_toList_unique hz hMem.1 hyz | none => apply List.find?_eq_none.2 intro z hz by_contra hpz have hzEq : compare u z.1 = Ordering.eq := by cases hc : compare u z.1 <;> simp_all - have hMemP : Batteries.RBSet.MemP (fun kv => compare u kv.1) T := by - exact Batteries.RBNode.memP_def.2 - ⟨z, Batteries.RBSet.mem_toList.1 hz, hzEq⟩ - have := (Batteries.RBSet.memP_iff_findP?.1 hMemP) + have hMemP : RBTree.RBSet.MemP (fun kv => compare u kv.1) T := by + exact RBTree.RBNode.memP_def.2 + ⟨z, RBTree.RBSet.mem_toList.1 hz, hzEq⟩ + have := (RBTree.RBSet.memP_iff_findP?.1 hMemP) rcases this with ⟨y, hy⟩ rw [show T.findEntry? u = T.findP? (fun kv => compare u kv.1) from rfl] at hFind @@ -340,7 +340,7 @@ theorem lookup?_storageToWordMap (T : EvmYul.Storage) (k : Word) : rw [hs, hxe]; rfl have h₂ := Std.TransCmp.congr_left (cmp := compare) h₁ (c := y.1) rw [h₂]; exact hye - exact Batteries.RBSet.mem_toList_unique hx hy hxy)] + exact RBTree.RBSet.mem_toList_unique hx hy hxy)] rw [toList_find?_eq_findEntry?] show (T.findEntry? (wordToU256 k)).elim none (fun kv => some (u256ToWord kv.2)) = ((T.findEntry? (wordToU256 k)).map (·.2)).map u256ToWord @@ -438,14 +438,14 @@ theorem snapshotWorld_find_self (context : Context) (s : State) cases hw : s.envWorld? with | none => simp [snapshotWorld, hw, snapshotWorldSeed, - Batteries.RBMap.find?_insert_of_eq _ hEq] + RBTree.RBMap.find?_insert_of_eq _ hEq] | some w => have hm : s.worldMutatedSinceAdoption = true := by rcases h with h | h · rw [hw] at h; cases h · exact h simp [snapshotWorld, hw, hm, - Batteries.RBMap.find?_insert_of_eq _ hEq] + RBTree.RBMap.find?_insert_of_eq _ hEq] /-- Echo adoption is a no-op on every interpreter-observable state component (the rebuild branches; adopted-clean states are covered exactly by diff --git a/SolidCore/Solidity/Ast.lean b/SolidCore/Solidity/Ast.lean index 08ba31b0..e72f2a1e 100644 --- a/SolidCore/Solidity/Ast.lean +++ b/SolidCore/Solidity/Ast.lean @@ -95,7 +95,148 @@ inductive Ty where List Ty -> List (Option DataLocation) -> List Ty -> List (Option DataLocation) -> StateMutability -> Visibility -> Ty - deriving Repr, BEq + deriving Repr + +mutual + +/-- Structural equality of types, field by field as `deriving BEq` compares them. +Written out because the derived instance of a nested inductive is a `partial` def, +which the kernel cannot unfold. -/ +def Ty.beq : Ty -> Ty -> Bool + | .bool, .bool => true + | .address a, .address b => a == b + | .uint a, .uint b => a == b + | .int a, .int b => a == b + | .fixed a b, .fixed c d => a == c && b == d + | .ufixed a b, .ufixed c d => a == c && b == d + | .bytesN a, .bytesN b => a == b + | .bytes, .bytes => true + | .string, .string => true + | .fixedBytes a, .fixedBytes b => a == b + | .array a n, .array b m => Ty.beq a b && n == m + | .mapping a b, .mapping c d => Ty.beq a c && Ty.beq b d + | .tuple as, .tuple bs => Ty.beqList as bs + | .struct p as, .struct q bs => p == q && Ty.beqList as bs + | .user p, .user q => p == q + | .enum p n, .enum q m => p == q && n == m + | .functionWithLocations a b c d e f, .functionWithLocations a' b' c' d' e' f' => + Ty.beqList a a' && b == b' && Ty.beqList c c' && d == d' && e == e' && f == f' + | _, _ => false + +/-- `Ty.beq` on lists, as `List`'s `BEq` compares them. -/ +def Ty.beqList : List Ty -> List Ty -> Bool + | [], [] => true + | a :: as, b :: bs => Ty.beq a b && Ty.beqList as bs + | _, _ => false + +end + +instance : BEq Ty := ⟨Ty.beq⟩ + +/-! ### A flat print of types + +`Ty.reprFlat` prints a type as its derived `Repr` instance does when the print fits on +one line, by structural recursion, so the kernel can evaluate it (the derived instance +goes through `Std.Format.pretty`, a `partial` def). -/ + +/-- The print of a constructor applied to the prints of its arguments, in parentheses in +argument position (even with no arguments), as derived `Repr` instances print one on a +single line. -/ +def Ty.reprApp (ctor : String) (args : List String) (arg : Bool) : String := + let s := ctor ++ String.join (args.map (" " ++ ·)) + if arg then "(" ++ s ++ ")" else s + +/-- A list's elements, as `List.repr` prints them on one line. -/ +def Ty.reprBrackets (items : List String) : String := + "[" ++ ", ".intercalate items ++ "]" + +/-- A path, as its derived `Repr` prints it on one line. -/ +def Ty.reprPath (p : Path) : String := + "{ segments := " ++ Ty.reprBrackets (p.segments.map String.quote) ++ " }" + +/-- An optional data location, as `Option`'s `Repr` prints it on one line. -/ +def Ty.reprLocation : Option DataLocation -> String + | none => "none" + | some .storage => "some (SolidCore.Solidity.DataLocation.storage)" + | some .memory => "some (SolidCore.Solidity.DataLocation.memory)" + | some .calldata => "some (SolidCore.Solidity.DataLocation.calldata)" + +/-- A state mutability, as its derived `Repr` prints it. -/ +def Ty.reprMutability : StateMutability -> String + | .pure => "SolidCore.Solidity.StateMutability.pure" + | .view => "SolidCore.Solidity.StateMutability.view" + | .nonpayable => "SolidCore.Solidity.StateMutability.nonpayable" + | .payable => "SolidCore.Solidity.StateMutability.payable" + +/-- A visibility, as its derived `Repr` prints it. -/ +def Ty.reprVisibility : Visibility -> String + | .public_ => "SolidCore.Solidity.Visibility.public_" + | .private_ => "SolidCore.Solidity.Visibility.private_" + | .internal_ => "SolidCore.Solidity.Visibility.internal_" + | .external_ => "SolidCore.Solidity.Visibility.external_" + +mutual + +/-- A type, as its derived `Repr` prints it on one line; `arg` is argument position. -/ +def Ty.reprFlat : Ty -> Bool -> String + | .bool, arg => Ty.reprApp "SolidCore.Solidity.Ty.bool" [] arg + | .address b, arg => Ty.reprApp "SolidCore.Solidity.Ty.address" [toString b] arg + | .uint n, arg => Ty.reprApp "SolidCore.Solidity.Ty.uint" [toString n] arg + | .int n, arg => Ty.reprApp "SolidCore.Solidity.Ty.int" [toString n] arg + | .fixed m n, arg => Ty.reprApp "SolidCore.Solidity.Ty.fixed" [toString m, toString n] arg + | .ufixed m n, arg => Ty.reprApp "SolidCore.Solidity.Ty.ufixed" [toString m, toString n] arg + | .bytesN n, arg => Ty.reprApp "SolidCore.Solidity.Ty.bytesN" [toString n] arg + | .bytes, arg => Ty.reprApp "SolidCore.Solidity.Ty.bytes" [] arg + | .string, arg => Ty.reprApp "SolidCore.Solidity.Ty.string" [] arg + | .fixedBytes n, arg => Ty.reprApp "SolidCore.Solidity.Ty.fixedBytes" [toString n] arg + | .array t n, arg => + Ty.reprApp "SolidCore.Solidity.Ty.array" + [Ty.reprFlat t true, match n with | none => "none" | some n => "(some " ++ toString n ++ ")"] arg + | .mapping k v, arg => + Ty.reprApp "SolidCore.Solidity.Ty.mapping" [Ty.reprFlat k true, Ty.reprFlat v true] arg + | .tuple ts, arg => Ty.reprApp "SolidCore.Solidity.Ty.tuple" [Ty.reprFlatList ts] arg + | .struct p ts, arg => + Ty.reprApp "SolidCore.Solidity.Ty.struct" [Ty.reprPath p, Ty.reprFlatList ts] arg + | .user p, arg => Ty.reprApp "SolidCore.Solidity.Ty.user" [Ty.reprPath p] arg + | .enum p n, arg => Ty.reprApp "SolidCore.Solidity.Ty.enum" [Ty.reprPath p, toString n] arg + | .functionWithLocations ps pl rs rl m v, arg => + Ty.reprApp "SolidCore.Solidity.Ty.functionWithLocations" + [Ty.reprFlatList ps, Ty.reprBrackets (pl.map Ty.reprLocation), Ty.reprFlatList rs, + Ty.reprBrackets (rl.map Ty.reprLocation), "(" ++ Ty.reprMutability m ++ ")", "(" ++ Ty.reprVisibility v ++ ")"] arg + +/-- A list of types, as `List.repr` prints it on one line. -/ +def Ty.reprFlatList (ts : List Ty) : String := + "[" ++ Ty.reprFlatItems ts ++ "]" + +/-- The elements of a list of types, separated by `, `. -/ +def Ty.reprFlatItems : List Ty -> String + | [] => "" + | [t] => Ty.reprFlat t false + | t :: ts => Ty.reprFlat t false ++ ", " ++ Ty.reprFlatItems ts + +end + +/-- `toString (repr ts)`, by the flat print when it is short enough to fit on one line +(`Std.Format.defWidth` is 120 columns) and so is the derived print itself: up to 120 +characters. The kernel cannot evaluate the longer case (`Std.Format`'s printer is +`partial`), so the translation's keys use `Ty.reprListString` instead. -/ +def Ty.reprListStringDerived (ts : List Ty) : String := + let s := Ty.reprFlatList ts + if s.length ≤ 120 then s else toString (repr ts) + +/-- A structural identity of a list of types, for the keys of internal functions and of +external call kinds: the flat print `Ty.reprFlatList`, which the kernel evaluates at any +length. It is `Ty.reprListStringDerived` whenever that is the flat print, so every key of +up to 120 characters of parameter types is unchanged (`Ty.reprListString_eq_derived`); +longer lists of parameter types (such as a seven-argument `permit`) get their one-line +print instead of the derived print's line breaks. -/ +def Ty.reprListString (ts : List Ty) : String := + Ty.reprFlatList ts + +theorem Ty.reprListString_eq_derived (ts : List Ty) + (h : (Ty.reprFlatList ts).length ≤ 120) : + Ty.reprListString ts = Ty.reprListStringDerived ts := by + simp [Ty.reprListString, Ty.reprListStringDerived, h] def Ty.function (params returns : List Ty) (mutability : StateMutability) (visibility : Visibility) : Ty := @@ -294,6 +435,13 @@ inductive Stmt where | continue | unchecked : Stmt -> Stmt | inlineAssembly : String -> Stmt + /-- An inline assembly block of exactly one Yul assignment + `target := create2(value, add(code, 32), mload(code), salt)`, where `target` and `code` are + Solidity locals (`code` a `bytes memory`) and `value`, `salt` are Yul literals or + Solidity locals: CREATE2 of the bytes of `code` as init code, endowed with `value`, salted + with `salt`, assigning the new account's address, or 0 when the creation fails (EVM's + CREATE2, which never reverts the caller). Fields: target, value, code, salt. -/ + | assemblyCreate2 : Expr -> Expr -> Expr -> Expr -> Stmt | modifierPlaceholder deriving Repr diff --git a/SolidCore/Solidity/FuelExtension.lean b/SolidCore/Solidity/FuelExtension.lean new file mode 100644 index 00000000..55059d28 --- /dev/null +++ b/SolidCore/Solidity/FuelExtension.lean @@ -0,0 +1,810 @@ +import SolidCore.Solidity.Checked + +/-! +# Fuel extension for the source interpreter, along every path + +`FuelMonotonicity.lean` proves that a call tree with no reachable `outOfFuel` leaf is the tree +at every higher fuel. That needs the whole tree, for every answer at every request, to be free of +`outOfFuel`, which a successful fold under one responder does not give: the fold follows one path. + +This module proves the unconditional, per-path form. `SolI.Ext lo hi` says `hi` is `lo` with some +of its `outOfFuel` leaves replaced by arbitrary trees, and every evaluator of the statement cluster +at fuel `n` is `Ext`-below itself at any fuel `m ≥ n` (`Stmt.eval_fuel_ext` and its siblings). A +fold that ends anywhere but `outOfFuel` ends the same way on an extension (`SolI.Ext.runWith`), so +`FunctionDef.call?` (`FunctionDef.call?_fuel_mono`) and the checked contract's call and +construction are fuel-monotone: a result a fuel gives is the result every higher fuel gives. +Running out of fuel therefore never produces a result of its own; it only withholds one. + +The induction is `FuelMonotonicity.lean`'s, arm for arm, with `SolI.Ext.bind` in place of +`SolI.bind_fuel_congr`. +-/ + +set_option linter.unusedSimpArgs false +set_option linter.deprecated false +set_option linter.unusedTactic false + +namespace SolidCore +namespace Solidity +namespace Source + +open EvmCompiler.Simulation (Interaction Answer Query) + +/-- `hi` is `lo` with some of its `outOfFuel` leaves replaced. -/ +inductive SolI.Ext {α : Type} : SolI α → SolI α → Prop + | stop (hi : SolI α) : SolI.Ext (.done (.error .outOfFuel)) hi + | done (r : Except SolidityFailure α) : SolI.Ext (.done r) (.done r) + | request {q : Query} {k k' : Answer q → SolI α} : + (∀ a, SolI.Ext (k a) (k' a)) → SolI.Ext (.request q k) (.request q k') + +theorem SolI.Ext.refl {α : Type} : ∀ (t : SolI α), SolI.Ext t t + | .done r => .done r + | .request _ k => .request fun a => SolI.Ext.refl (k a) + +theorem SolI.Ext.bind {α β : Type} {t t' : SolI α} {k k' : α → SolI β} + (h : SolI.Ext t t') (hk : ∀ v, SolI.Ext (k v) (k' v)) : + SolI.Ext (t >>= k) (t' >>= k') := by + induction h with + | stop hi => exact .stop _ + | done r => + cases r with + | ok v => exact hk v + | error e => exact .done _ + | request _ ih => exact .request fun a => ih a + +theorem SolI.Ext.bind_refl {α β : Type} {t t' : SolI α} {k : α → SolI β} + (h : SolI.Ext t t') : SolI.Ext (t >>= k) (t' >>= k) := + h.bind fun v => SolI.Ext.refl (k v) + +theorem SolI.Ext.map {α β : Type} {t t' : SolI α} {f : α → β} + (h : SolI.Ext t t') : SolI.Ext (f <$> t) (f <$> t') := + h.bind fun v => SolI.Ext.refl _ + +/-- Close an `Ext` goal from an `Ext` fact about its prefix. -/ +macro "ext_close " h:term : tactic => + `(tactic| first + | exact $h + | exact SolI.Ext.bind_refl $h + | exact SolI.Ext.map $h) + +/-- `Stmt.evalList` is fuel-monotone at any pair of fuels at which `Stmt.eval` + is (the list evaluator passes its fuel through unchanged). -/ +private theorem evalList_ext_of (n m : Nat) + (hEval : ∀ (table : FunctionTable) (context : Context) (runtime : Runtime) + (stmt : Stmt), + SolI.Ext (Stmt.eval n table context runtime stmt) (Stmt.eval m table context runtime stmt)) : + ∀ (table : FunctionTable) (context : Context) (stmts : List Stmt) + (runtime : Runtime), + SolI.Ext (Stmt.evalList n table context runtime stmts) (Stmt.evalList m table context runtime stmts) := by + intro table context stmts + induction stmts with + | nil => intro runtime; simp only [Stmt.evalList]; exact SolI.Ext.refl _ + | cons s rest ihRest => + intro runtime + simp only [Stmt.evalList] + refine SolI.Ext.bind (hEval _ _ _ _) ?_ + intro v + cases v with + | normal runtime' => exact ihRest runtime' + | returned runtime' values => exact SolI.Ext.refl _ + | selfdestructed runtime' => exact SolI.Ext.refl _ + | reverted runtime' err => exact SolI.Ext.refl _ + | broke runtime' => exact SolI.Ext.refl _ + | continued runtime' => exact SolI.Ext.refl _ + +private theorem evalWhile_ext_step (n m : Nat) + (hEval : ∀ (table : FunctionTable) (context : Context) (runtime : Runtime) + (stmt : Stmt), + SolI.Ext (Stmt.eval n table context runtime stmt) (Stmt.eval m table context runtime stmt)) + (hWhile : ∀ (table : FunctionTable) (context : Context) (runtime : Runtime) + (cond : Expr) (body : Stmt), + SolI.Ext (Stmt.evalWhile n table context runtime cond body) (Stmt.evalWhile m table context runtime cond body)) : + ∀ (table : FunctionTable) (context : Context) (runtime : Runtime) + (cond : Expr) (body : Stmt), + SolI.Ext (Stmt.evalWhile (n + 1) table context runtime cond body) (Stmt.evalWhile (m + 1) table context runtime cond body) := by + intro table context runtime cond body + simp only [Stmt.evalWhile] + refine SolI.Ext.bind (SolI.Ext.refl _) ?_ + intro v + cases v with + | error err => exact SolI.Ext.refl _ + | ok p => + obtain ⟨value, runtime'⟩ := p + try simp only [] + cases hw : value.expectWord with + | error err => exact SolI.Ext.refl _ + | ok word => + try simp only [] + cases ht : wordTruthy word with + | false => exact SolI.Ext.refl _ + | true => + refine SolI.Ext.bind (hEval _ _ _ _) ?_ + intro w + cases w with + | normal r2 => exact hWhile _ _ _ _ _ + | continued r2 => exact hWhile _ _ _ _ _ + | returned r2 vs => exact SolI.Ext.refl _ + | selfdestructed r2 => exact SolI.Ext.refl _ + | reverted r2 e => exact SolI.Ext.refl _ + | broke r2 => exact SolI.Ext.refl _ + +private theorem evalDoWhile_ext_step (n m : Nat) + (hEval : ∀ (table : FunctionTable) (context : Context) (runtime : Runtime) + (stmt : Stmt), + SolI.Ext (Stmt.eval n table context runtime stmt) (Stmt.eval m table context runtime stmt)) + (hDoWhile : ∀ (table : FunctionTable) (context : Context) + (runtime : Runtime) (body : Stmt) (cond : Expr), + SolI.Ext (Stmt.evalDoWhile n table context runtime body cond) (Stmt.evalDoWhile m table context runtime body cond)) : + ∀ (table : FunctionTable) (context : Context) (runtime : Runtime) + (body : Stmt) (cond : Expr), + SolI.Ext (Stmt.evalDoWhile (n + 1) table context runtime body cond) (Stmt.evalDoWhile (m + 1) table context runtime body cond) := by + intro table context runtime body cond + simp only [Stmt.evalDoWhile] + refine SolI.Ext.bind (hEval _ _ _ _) ?_ + intro v + cases v with + | returned r' vs => exact SolI.Ext.refl _ + | selfdestructed r' => exact SolI.Ext.refl _ + | reverted r' e => exact SolI.Ext.refl _ + | broke r' => exact SolI.Ext.refl _ + | normal runtime' => + try simp only [] + refine SolI.Ext.bind (SolI.Ext.refl _) ?_ + intro w + cases w with + | error err => exact SolI.Ext.refl _ + | ok p => + obtain ⟨value, runtime''⟩ := p + try simp only [Bool.false_eq_true, if_true, if_false] + cases hword : value.expectWord with + | error e => exact SolI.Ext.refl _ + | ok word => + try simp only [Bool.false_eq_true, if_true, if_false] + cases ht : wordTruthy word with + | false => exact SolI.Ext.refl _ + | true => + exact hDoWhile _ _ _ _ _ + | continued runtime' => + try simp only [] + refine SolI.Ext.bind (SolI.Ext.refl _) ?_ + intro w + cases w with + | error err => exact SolI.Ext.refl _ + | ok p => + obtain ⟨value, runtime''⟩ := p + try simp only [Bool.false_eq_true, if_true, if_false] + cases hword : value.expectWord with + | error e => exact SolI.Ext.refl _ + | ok word => + try simp only [Bool.false_eq_true, if_true, if_false] + cases ht : wordTruthy word with + | false => exact SolI.Ext.refl _ + | true => + exact hDoWhile _ _ _ _ _ + +private theorem evalFor_ext_step (n m : Nat) + (hEval : ∀ (table : FunctionTable) (context : Context) (runtime : Runtime) + (stmt : Stmt), + SolI.Ext (Stmt.eval n table context runtime stmt) (Stmt.eval m table context runtime stmt)) + (hFor : ∀ (table : FunctionTable) (context : Context) (runtime : Runtime) + (cond : Expr) (post : Stmt) (body : Stmt), + SolI.Ext (Stmt.evalFor n table context runtime cond post body) (Stmt.evalFor m table context runtime cond post body)) : + ∀ (table : FunctionTable) (context : Context) (runtime : Runtime) + (cond : Expr) (post : Stmt) (body : Stmt), + SolI.Ext (Stmt.evalFor (n + 1) table context runtime cond post body) (Stmt.evalFor (m + 1) table context runtime cond post body) := by + intro table context runtime cond post body + simp only [Stmt.evalFor] + refine SolI.Ext.bind (SolI.Ext.refl _) ?_ + intro v + cases v with + | error err => exact SolI.Ext.refl _ + | ok p => + obtain ⟨value, runtime'⟩ := p + try simp only [] + cases hw : value.expectWord with + | error err => exact SolI.Ext.refl _ + | ok word => + try simp only [] + cases ht : wordTruthy word with + | false => exact SolI.Ext.refl _ + | true => + refine SolI.Ext.bind (hEval _ _ _ _) ?_ + intro w + cases w with + | returned r2 vs => exact SolI.Ext.refl _ + | selfdestructed r2 => exact SolI.Ext.refl _ + | reverted r2 e => exact SolI.Ext.refl _ + | broke r2 => exact SolI.Ext.refl _ + | normal r2 => + try simp only [] + refine SolI.Ext.bind (hEval _ _ _ _) ?_ + intro u + cases u with + | normal posted => exact hFor _ _ _ _ _ _ + | returned r3 vs => exact SolI.Ext.refl _ + | selfdestructed r3 => exact SolI.Ext.refl _ + | reverted r3 e => exact SolI.Ext.refl _ + | broke r3 => exact SolI.Ext.refl _ + | continued r3 => exact SolI.Ext.refl _ + | continued r2 => + try simp only [] + refine SolI.Ext.bind (hEval _ _ _ _) ?_ + intro u + cases u with + | normal posted => exact hFor _ _ _ _ _ _ + | returned r3 vs => exact SolI.Ext.refl _ + | selfdestructed r3 => exact SolI.Ext.refl _ + | reverted r3 e => exact SolI.Ext.refl _ + | broke r3 => exact SolI.Ext.refl _ + | continued r3 => exact SolI.Ext.refl _ + +set_option maxHeartbeats 1600000 in +/-- One fuel layer of `Stmt.eval`, given monotonicity of the whole cluster at + the previous fuel. One `case` per fuel-dependent statement arm; every + fuel-free arm is discharged by the unfolding `simp` itself. -/ +private theorem eval_ext_step (n m : Nat) + (hEval : ∀ (table : FunctionTable) (context : Context) (runtime : Runtime) + (stmt : Stmt), + SolI.Ext (Stmt.eval n table context runtime stmt) (Stmt.eval m table context runtime stmt)) + (hList : ∀ (table : FunctionTable) (context : Context) (runtime : Runtime) + (stmts : List Stmt), + SolI.Ext (Stmt.evalList n table context runtime stmts) (Stmt.evalList m table context runtime stmts)) + (hWhile : ∀ (table : FunctionTable) (context : Context) (runtime : Runtime) + (cond : Expr) (body : Stmt), + SolI.Ext (Stmt.evalWhile n table context runtime cond body) (Stmt.evalWhile m table context runtime cond body)) + (hDoWhile : ∀ (table : FunctionTable) (context : Context) + (runtime : Runtime) (body : Stmt) (cond : Expr), + SolI.Ext (Stmt.evalDoWhile n table context runtime body cond) (Stmt.evalDoWhile m table context runtime body cond)) + (hFor : ∀ (table : FunctionTable) (context : Context) (runtime : Runtime) + (cond : Expr) (post : Stmt) (body : Stmt), + SolI.Ext (Stmt.evalFor n table context runtime cond post body) (Stmt.evalFor m table context runtime cond post body)) : + ∀ (table : FunctionTable) (context : Context) (runtime : Runtime) + (stmt : Stmt), + SolI.Ext (Stmt.eval (n + 1) table context runtime stmt) (Stmt.eval (m + 1) table context runtime stmt) := by + intro table context runtime stmt + cases stmt <;> simp only [Stmt.eval] <;> try exact SolI.Ext.refl _ + case block body => + ext_close (hList _ _ _ _) + case captureReturn returnNames body => + ext_close (hEval _ _ _ _) + case internalCall targets callee args => + refine SolI.Ext.bind (SolI.Ext.refl _) ?_ + intro v + cases v with + | error err => exact SolI.Ext.refl _ + | ok p => + obtain ⟨argValues, runtime'⟩ := p + try simp only [] + cases hlk : table.lookup? callee with + | none => exact SolI.Ext.refl _ + | some fn => + try simp only [] + cases hen : internalCallEnter? fn argValues runtime' with + | none => exact SolI.Ext.refl _ + | some pr => + obtain ⟨calleeRuntime, savedLocals⟩ := pr + try simp only [] + ext_close (hEval _ _ _ _) + case internalCallPtr targets fnExpr args => + refine SolI.Ext.bind (SolI.Ext.refl _) ?_ + intro v + cases v with + | error err => exact SolI.Ext.refl _ + | ok p => + obtain ⟨value, runtimeFn⟩ := p + cases value <;> try exact SolI.Ext.refl _ + case internalFunction id => + try simp only [] + refine SolI.Ext.bind (SolI.Ext.refl _) ?_ + intro w + cases w with + | error err => exact SolI.Ext.refl _ + | ok q => + obtain ⟨argValues, runtime'⟩ := q + try simp only [Bool.false_eq_true, if_true, if_false] + cases hlk : table.lookupById? id with + | none => exact SolI.Ext.refl _ + | some fn => + try simp only [Bool.false_eq_true, if_true, if_false] + cases hen : internalCallEnter? fn argValues runtime' with + | none => exact SolI.Ext.refl _ + | some pr => + obtain ⟨calleeRuntime, savedLocals⟩ := pr + try simp only [Bool.false_eq_true, if_true, if_false] + ext_close (hEval _ _ _ _) + case ifElse cond thenBranch elseBranch => + refine SolI.Ext.bind (SolI.Ext.refl _) ?_ + intro v + cases v with + | error err => exact SolI.Ext.refl _ + | ok p => + obtain ⟨value, runtime'⟩ := p + try simp only [] + cases hw : value.expectWord with + | error err => exact SolI.Ext.refl _ + | ok word => + try simp only [] + cases ht : wordTruthy word with + | false => + exact hEval _ _ _ _ + | true => + exact hEval _ _ _ _ + case «switch» discr cs defaultBranch => + refine SolI.Ext.bind (SolI.Ext.refl _) ?_ + intro v + cases v with + | error err => exact SolI.Ext.refl _ + | ok p => + obtain ⟨value, runtime'⟩ := p + try simp only [] + cases hw : value.expectWord with + | error err => exact SolI.Ext.refl _ + | ok word => + try simp only [] + cases hb : Stmt.findSwitchBranch? word cs with + | some branch => + cases defaultBranch with + | some d => exact hEval _ _ _ _ + | none => exact hEval _ _ _ _ + | none => + cases defaultBranch with + | some branch => exact hEval _ _ _ _ + | none => exact SolI.Ext.refl _ + case whileLoop cond body => + exact hWhile _ _ _ _ _ + case doWhile body cond => + exact hDoWhile _ _ _ _ _ + case forLoop init cond post body => + refine SolI.Ext.bind (hEval _ _ _ _) ?_ + intro v + cases v with + | returned r' vs => exact SolI.Ext.refl _ + | selfdestructed r' => exact SolI.Ext.refl _ + | reverted r' e => exact SolI.Ext.refl _ + | broke r' => exact SolI.Ext.refl _ + | continued r' => exact SolI.Ext.refl _ + | normal initialized => + try simp only [] + ext_close (hFor _ _ _ _ _ _) + case tryExternalCall kind targetExpr calldataExpr valueExpr gasExprOpt + gasFirst checkTargetCode rets retCleanups successBody catchClauses => + cases h1 : targetExpr.evalWithRuntimeByContext context runtime with + | error err => exact SolI.Ext.refl _ + | ok p1 => + obtain ⟨targetValue, runtime'⟩ := p1 + try simp only [] + cases h2 : targetValue.expectWord with + | error err => exact SolI.Ext.refl _ + | ok target => + try simp only [] + -- New eval order (gap EO1): the call options (value/gas ordered by + -- `gasFirst`) are evaluated BEFORE the calldata argument. Split the + -- options result FIRST, thread its runtime (`runtimeOpts`) into the + -- calldata evaluation, then the calldata, `asBytes?`, and finally the + -- missingCode `if` + the two bind branches. + split + next value gasOpt runtimeOpts heq => + try simp only [] + cases h3 : calldataExpr.evalWithRuntimeByContext context runtimeOpts with + | error err => exact SolI.Ext.refl _ + | ok p2 => + obtain ⟨calldataValue, runtime'''⟩ := p2 + try simp only [] + cases h4 : calldataValue.asBytes? with + | none => exact SolI.Ext.refl _ + | some calldata => + try simp only [] + -- gap A1/A3: the `extcodesize` existence guard now reverts the + -- caller UNCATCHABLY *before* the CALL. Split it: the missing-code + -- branch is a fuel-free `Result.reverted` (closed by `simp` as a + -- reflexivity goal), so only the has-code branch — which performs + -- the CALL — carries the fuel-dependent continuation. + split <;> (try exact SolI.Ext.refl _) + refine SolI.Ext.bind (SolI.Ext.refl _) ?_ + intro w + obtain ⟨callResult, adoptedState⟩ := w + try simp only [Bool.false_eq_true, if_true, if_false] + cases hs : callResult.success with + | false => + try simp only [Bool.false_eq_true, if_true, if_false] + cases hcm : TryCatchClause.findMatch? + (callResult.output.map normByte) catchClauses with + | none => exact SolI.Ext.refl _ + | some fb => + obtain ⟨frame, body⟩ := fb + try simp only [Bool.false_eq_true, if_true, if_false] + ext_close (hEval _ _ _ _) + | true => + try simp only [Bool.false_eq_true, if_true, if_false] + -- TC-OOM1: the success-return decode now uses the Except view so + -- an oversized dynamic length propagates Panic(0x41) uncaught. + -- `Except.error` (empty OR 0x41) is a fuel-free `Result.reverted`; + -- only `Except.ok` carries the fuel-dependent success body. + cases habi : abiDecodeValuesExcept? (rets.map BindingDecl.ty) + (callResult.output.map normByte) with + | error revertData => exact SolI.Ext.refl _ + | ok decoded => + try simp only [Bool.false_eq_true, if_true, if_false] + cases hacc : AbiCleanups.acceptOrUnspecified + retCleanups decoded with + | false => exact SolI.Ext.refl _ + | true => + try simp only [Bool.false_eq_true, if_true, if_false] + cases hbind : BindingDecl.bindArgs? rets decoded with + | none => exact SolI.Ext.refl _ + | some frame => + try simp only [Bool.false_eq_true, if_true, if_false] + ext_close (hEval _ _ _ _) + next runtimeFailed err heq => exact SolI.Ext.refl _ + case tryContractCreate contractName ctorArgsExpr valueExpr saltExprOpt + valueBeforeSalt rets successBody catchClauses => + -- New eval order (gap DIV-CREATE-1/2): the creation options (value/salt + -- ordered by `valueBeforeSalt`) are evaluated BEFORE the constructor args. + -- Split the options result FIRST, thread its runtime (`runtimeOpts`) into + -- the args evaluation, then `asBytes?`, and finally the two bind branches. + split + next value saltOpt runtimeOpts heq => + try simp only [] + cases h1 : ctorArgsExpr.evalWithRuntimeByContext context runtimeOpts with + | error err => exact SolI.Ext.refl _ + | ok p1 => + obtain ⟨argsValue, runtime'''⟩ := p1 + try simp only [] + cases h2 : argsValue.asBytes? with + | none => exact SolI.Ext.refl _ + | some constructorArgs => + try simp only [] + refine SolI.Ext.bind (SolI.Ext.refl _) ?_ + intro w + obtain ⟨createResult, adoptedState⟩ := w + try simp only [Bool.false_eq_true, if_true, if_false] + cases hs : createResult.success with + | false => + try simp only [Bool.false_eq_true, if_true, if_false] + cases hcm : TryCatchClause.findMatch? + (createResult.output.map normByte) catchClauses with + | none => exact SolI.Ext.refl _ + | some fb => + obtain ⟨frame, body⟩ := fb + try simp only [Bool.false_eq_true, if_true, if_false] + ext_close (hEval _ _ _ _) + | true => + simp only [Bool.false_eq_true, if_true, if_false] + cases hB : BindingDecl.bindArgs? rets + (if rets.isEmpty then [] else [Value.word createResult.address]) with + | none => exact SolI.Ext.refl _ + | some frame => + simp only [] + ext_close (hEval _ _ _ _) + next runtimeErr err heq => exact SolI.Ext.refl _ + case checked body => + exact hEval _ _ _ _ + case unchecked body => + exact hEval _ _ _ _ + +/-! ### The mutual induction -/ + +private theorem fuelExtAll (n : Nat) : + (∀ m, n ≤ m → ∀ (table : FunctionTable) (context : Context) + (runtime : Runtime) (stmt : Stmt), + SolI.Ext (Stmt.eval n table context runtime stmt) (Stmt.eval m table context runtime stmt)) ∧ + (∀ m, n ≤ m → ∀ (table : FunctionTable) (context : Context) + (runtime : Runtime) (stmts : List Stmt), + SolI.Ext (Stmt.evalList n table context runtime stmts) + (Stmt.evalList m table context runtime stmts)) ∧ + (∀ m, n ≤ m → ∀ (table : FunctionTable) (context : Context) + (runtime : Runtime) (cond : Expr) (body : Stmt), + SolI.Ext (Stmt.evalWhile n table context runtime cond body) + (Stmt.evalWhile m table context runtime cond body)) ∧ + (∀ m, n ≤ m → ∀ (table : FunctionTable) (context : Context) + (runtime : Runtime) (body : Stmt) (cond : Expr), + SolI.Ext (Stmt.evalDoWhile n table context runtime body cond) + (Stmt.evalDoWhile m table context runtime body cond)) ∧ + (∀ m, n ≤ m → ∀ (table : FunctionTable) (context : Context) + (runtime : Runtime) (cond : Expr) (post : Stmt) (body : Stmt), + SolI.Ext (Stmt.evalFor n table context runtime cond post body) + (Stmt.evalFor m table context runtime cond post body)) := by + induction n with + | zero => + have hEval0 : ∀ m, 0 ≤ m → ∀ (table : FunctionTable) (context : Context) + (runtime : Runtime) (stmt : Stmt), + SolI.Ext (Stmt.eval 0 table context runtime stmt) (Stmt.eval m table context runtime stmt) := by + intro m _ table context runtime stmt + simp only [Stmt.eval] + exact .stop _ + refine ⟨hEval0, ?_, ?_, ?_, ?_⟩ + · intro m hm table context runtime stmts + exact evalList_ext_of 0 m + (fun tb c r s => hEval0 m hm tb c r s) + table context stmts runtime + · intro m hm table context runtime cond body + simp only [Stmt.evalWhile] + exact .stop _ + · intro m hm table context runtime body cond + simp only [Stmt.evalDoWhile] + exact .stop _ + · intro m hm table context runtime cond post body + simp only [Stmt.evalFor] + exact .stop _ + | succ n ihn => + obtain ⟨ihEval, ihList, ihWhile, ihDoWhile, ihFor⟩ := ihn + have hEvalS : ∀ m, n + 1 ≤ m → ∀ (table : FunctionTable) + (context : Context) (runtime : Runtime) (stmt : Stmt), + SolI.Ext (Stmt.eval (n + 1) table context runtime stmt) + (Stmt.eval m table context runtime stmt) := by + intro m hm table context runtime stmt + cases m with + | zero => exact absurd hm (Nat.not_succ_le_zero n) + | succ m' => + have hm' : n ≤ m' := Nat.le_of_succ_le_succ hm + exact eval_ext_step n m' + (fun tb c r s => ihEval m' hm' tb c r s) + (fun tb c r ss => ihList m' hm' tb c r ss) + (fun tb c r cd bd => ihWhile m' hm' tb c r cd bd) + (fun tb c r bd cd => ihDoWhile m' hm' tb c r bd cd) + (fun tb c r cd ps bd => ihFor m' hm' tb c r cd ps bd) + table context runtime stmt + refine ⟨hEvalS, ?_, ?_, ?_, ?_⟩ + · intro m hm table context runtime stmts + exact evalList_ext_of (n + 1) m + (fun tb c r s => hEvalS m hm tb c r s) + table context stmts runtime + · intro m hm table context runtime cond body + cases m with + | zero => exact absurd hm (Nat.not_succ_le_zero n) + | succ m' => + have hm' : n ≤ m' := Nat.le_of_succ_le_succ hm + exact evalWhile_ext_step n m' + (fun tb c r s => ihEval m' hm' tb c r s) + (fun tb c r cd bd => ihWhile m' hm' tb c r cd bd) + table context runtime cond body + · intro m hm table context runtime body cond + cases m with + | zero => exact absurd hm (Nat.not_succ_le_zero n) + | succ m' => + have hm' : n ≤ m' := Nat.le_of_succ_le_succ hm + exact evalDoWhile_ext_step n m' + (fun tb c r s => ihEval m' hm' tb c r s) + (fun tb c r bd cd => ihDoWhile m' hm' tb c r bd cd) + table context runtime body cond + · intro m hm table context runtime cond post body + cases m with + | zero => exact absurd hm (Nat.not_succ_le_zero n) + | succ m' => + have hm' : n ≤ m' := Nat.le_of_succ_le_succ hm + exact evalFor_ext_step n m' + (fun tb c r s => ihEval m' hm' tb c r s) + (fun tb c r cd ps bd => ihFor m' hm' tb c r cd ps bd) + table context runtime cond post body + +/-- **Fuel extension, statements.** -/ +theorem Stmt.eval_fuel_ext {n m : Nat} (hnm : n ≤ m) (table : FunctionTable) (context : Context) + (runtime : Runtime) (stmt : Stmt) : + SolI.Ext (Stmt.eval n table context runtime stmt) (Stmt.eval m table context runtime stmt) := + (fuelExtAll n).1 m hnm table context runtime stmt + + +/-! ### Folding an extension -/ + +/-- A fold that does not end in `outOfFuel` ends the same way on every extension. -/ +theorem SolI.Ext.runWith {α : Type} {responder : ScriptedResponder} {t t' : SolI α} + (h : SolI.Ext t t') {r : Except ResponderFailure α} (hrun : SolI.runWith responder t = r) + (hr : r ≠ .error (.solidity .outOfFuel)) : SolI.runWith responder t' = r := by + induction h generalizing r with + | stop hi => + simp only [SolI.runWith] at hrun + exact absurd hrun.symm hr + | done r' => exact hrun + | request hk ih => + rename_i q k k' + cases q with + | resource res => + simp only [SolI.runWith] at hrun ⊢ + exact ih _ hrun hr + | external world req => + cases req with + | call request => + simp only [SolI.runWith] at hrun ⊢ + cases ha : responder.answerCall? world request <;> simp only [ha] at hrun ⊢ + · cases hp : precompileAnswerCall? world request <;> simp only [hp] at hrun ⊢ + · exact hrun + · exact ih _ hrun hr + · exact ih _ hrun hr + | create request => + simp only [SolI.runWith] at hrun ⊢ + cases ha : responder.answerCreate? world request <;> simp only [ha] at hrun ⊢ + · exact hrun + · exact ih _ hrun hr + +/-- An ok fold is the fold of every extension. -/ +theorem SolI.Ext.runWith_ok {α : Type} {responder : ScriptedResponder} {t t' : SolI α} + (h : SolI.Ext t t') {a : α} (hrun : SolI.runWith responder t = .ok a) : + SolI.runWith responder t' = .ok a := + h.runWith hrun (by simp) + + +/-! ### The public seams -/ + +theorem FunctionDef.evalBodyEntry_fuel_ext {n m : Nat} (hnm : n ≤ m) + {table : FunctionTable} {context : Context} {function : FunctionDef} + {state : State} {args : List Value} {tree : SolI Result} + (h : FunctionDef.evalBodyEntry n table context function state args = some tree) : + ∃ tree', FunctionDef.evalBodyEntry m table context function state args = some tree' ∧ + SolI.Ext tree tree' := by + simp only [FunctionDef.evalBodyEntry] at h ⊢ + cases hacc : function.acceptsValue context.value with + | false => + simp only [hacc, Bool.false_eq_true, ite_false, ite_true] at h ⊢ + exact ⟨tree, h, SolI.Ext.refl _⟩ + | true => + simp only [hacc, ite_true] at h ⊢ + cases hframe : function.initialFrame? args with + | none => + rw [hframe] at h + simp at h + | some frame => + simp only [hframe] at h ⊢ + injection h with h + subst h + exact ⟨_, rfl, by ext_close (Stmt.eval_fuel_ext hnm _ _ _ _)⟩ + +theorem FunctionDef.call_fuel_ext {n m : Nat} (hnm : n ≤ m) + {table : FunctionTable} {context : Context} {function : FunctionDef} + {state : State} {args : List Value} {tree : SolI CallResult} + (h : FunctionDef.call n table context function state args = some tree) : + ∃ tree', FunctionDef.call m table context function state args = some tree' ∧ + SolI.Ext tree tree' := by + unfold FunctionDef.call at h ⊢ + cases hentry : FunctionDef.evalBodyEntry n table context function state args with + | none => + rw [hentry] at h + simp at h + | some t0 => + rw [hentry] at h + obtain ⟨t1, h1, hx⟩ := FunctionDef.evalBodyEntry_fuel_ext hnm hentry + rw [h1] + simp only [Option.map_some, Option.some.injEq] at h + subst h + exact ⟨_, rfl, hx.map⟩ + +/-- **A finished call is the call at every higher fuel.** -/ +theorem FunctionDef.call?_fuel_mono {n m : Nat} (hnm : n ≤ m) + {table : FunctionTable} {context : Context} {function : FunctionDef} + {state : State} {args : List Value} {r : CallResult} + (h : FunctionDef.call? n table context function state args = some r) : + FunctionDef.call? m table context function state args = some r := by + unfold FunctionDef.call? at h ⊢ + cases hc : FunctionDef.call n table context function state args with + | none => + rw [hc] at h + simp at h + | some t => + rw [hc] at h + obtain ⟨t', hc', hx⟩ := FunctionDef.call_fuel_ext hnm hc + rw [hc'] + simp only [Option.bind_some] at h ⊢ + cases hrun : SolI.runWith [] t with + | error e => + rw [hrun] at h + simp at h + | ok a => + rw [hrun] at h + rw [hx.runWith_ok hrun] + exact h + + +namespace ABI + +theorem Contract.callFallbackAtFromWithContext?_fuel_mono {n m : Nat} (hnm : n ≤ m) + {contract : Contract} {base : Context} {state : State} {self sender value : Word} + {calldata : Bytes} {r : AbiCallResult} + (h : Contract.callFallbackAtFromWithContext? n contract base state self sender value calldata + = some r) : + Contract.callFallbackAtFromWithContext? m contract base state self sender value calldata + = some r := by + unfold Contract.callFallbackAtFromWithContext? at h ⊢ + split at h + next function hf => + try simp only [hf] + cases hargs : FunctionDef.fallbackArgs? function calldata <;> + simp only [hargs, Option.bind_some, Option.bind_none, Option.bind_eq_bind] at h ⊢ + · cases h + · split at h + next hacc => + try simp only [hacc, ite_true] + try dsimp only at h ⊢ + split at h + next heq => rw [FunctionDef.call?_fuel_mono hnm heq]; exact h + next heq => rw [FunctionDef.call?_fuel_mono hnm heq]; exact h + next => cases h + next hacc => + try simp only [hacc] + exact h + next hf => + try simp only [hf] + exact h + + +theorem Contract.callReceiveOrFallbackAtFromWithContext?_fuel_mono {n m : Nat} (hnm : n ≤ m) + {contract : Contract} {base : Context} {state : State} {self sender value : Word} + {calldata : Bytes} {r : AbiCallResult} + (h : Contract.callReceiveOrFallbackAtFromWithContext? n contract base state self sender value + calldata = some r) : + Contract.callReceiveOrFallbackAtFromWithContext? m contract base state self sender value + calldata = some r := by + unfold Contract.callReceiveOrFallbackAtFromWithContext? at h ⊢ + split at h + next hempty => + try simp only [hempty, ite_true] + split at h + next function hf => + try simp only [hf] + split at h + next hacc => + try simp only [hacc, ite_true] + dsimp only at h ⊢ + split at h + next heq => rw [FunctionDef.call?_fuel_mono hnm heq]; exact h + next heq => rw [FunctionDef.call?_fuel_mono hnm heq]; exact h + next => cases h + next hacc => + try simp only [hacc] + exact h + next hf => + try simp only [hf] + exact Contract.callFallbackAtFromWithContext?_fuel_mono hnm h + next hempty => + try simp only [hempty] + exact Contract.callFallbackAtFromWithContext?_fuel_mono hnm h + +/-- **ABI dispatch is fuel-monotone**: a result the dispatcher gives at some fuel, it gives at +every higher fuel, from any base context (whose self-dispatch hook, if any, does not depend on +the fuel). -/ +theorem Contract.callCalldataAtFromWithContext?_fuel_mono {n m : Nat} (hnm : n ≤ m) + {contract : Contract} {base : Context} {state : State} {self sender value : Word} + {calldata : Bytes} {r : AbiCallResult} + (h : Contract.callCalldataAtFromWithContext? n contract base state self sender value calldata + = some r) : + Contract.callCalldataAtFromWithContext? m contract base state self sender value calldata + = some r := by + unfold Contract.callCalldataAtFromWithContext? at h ⊢ + split at h + next selector hsel => + try simp only [hsel] + split at h + next function hfind => + try simp only [hfind] + split at h + next args hdec => + try simp only [hdec] + split at h + next hacc => + try simp only [hacc, ite_true] + dsimp only at h ⊢ + split at h + next heq => rw [FunctionDef.call?_fuel_mono hnm heq]; exact h + next heq => rw [FunctionDef.call?_fuel_mono hnm heq]; exact h + next => cases h + next hacc => + try simp only [hacc] + exact h + next revert hdec => + try simp only [hdec] + exact h + next hfind => + try simp only [hfind] + exact Contract.callFallbackAtFromWithContext?_fuel_mono hnm h + next hsel => + try simp only [hsel] + exact Contract.callReceiveOrFallbackAtFromWithContext?_fuel_mono hnm h + +end ABI + +end Source +end Solidity +end SolidCore + +/-- +info: 'SolidCore.Solidity.Source.FunctionDef.call?_fuel_mono' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolidCore.Solidity.Source.FunctionDef.call?_fuel_mono diff --git a/SolidCore/Solidity/Interface/Contracts.lean b/SolidCore/Solidity/Interface/Contracts.lean index 28ec8c1c..796c4723 100644 --- a/SolidCore/Solidity/Interface/Contracts.lean +++ b/SolidCore/Solidity/Interface/Contracts.lean @@ -952,17 +952,50 @@ def ContractDecl.resolveStructsInHierarchy (env : StructEnv) def FunctionDecl.names (functions : List FunctionDecl) : List Name := functions.filterMap (fun function => function.name) +/-- The entries of `later` that no entry of `earlier` overrides: one with the same +function name and parameter types. In a dispatch order (most derived first), a +contract's function or public getter overrides a base's declaration of the same +external signature, such as a getter implementing an interface function, so the +base's entry is never the one a lookup finds. -/ +def ExternalCallKindEntries.notOverridden (earlier later : List ExternalCallKindEntry) : + List ExternalCallKindEntry := + later.filter fun e => + !earlier.any fun d => d.functionName == e.functionName && Ty.beqList d.paramTys e.paramTys + +/-- With no entry of `later` overridden, `notOverridden` keeps all of them. -/ +theorem ExternalCallKindEntries.notOverridden_eq_self (earlier later : List ExternalCallKindEntry) + (h : ∀ e ∈ later, ∀ d ∈ earlier, + (d.functionName == e.functionName && Ty.beqList d.paramTys e.paramTys) = false) : + ExternalCallKindEntries.notOverridden earlier later = later := by + unfold ExternalCallKindEntries.notOverridden + rw [List.filter_eq_self] + intro e he + simp only [Bool.not_eq_true', List.any_eq_false] + intro d hd + simpa using h e he d hd + +/-- Every entry `notOverridden` keeps is one of `later`'s. -/ +theorem ExternalCallKindEntries.mem_notOverridden {earlier later : List ExternalCallKindEntry} + {e : ExternalCallKindEntry} (h : e ∈ ExternalCallKindEntries.notOverridden earlier later) : + e ∈ later := + (List.mem_filter.mp h).1 + def ContractDecl.externalCallKindEntries? (contracts : List ContractDecl) (decl : ContractDecl) : Option (List ExternalCallKindEntry) := -- BUG#6: the same struct env `directCoreFunctions?` renders the callee-side -- library dispatch selectors with — caller payload and callee dispatch must -- hash the SAME library-qualified signature. let structEnv := ContractDecl.structEnvFromContracts contracts + -- Along the dispatch order (most derived first), a base's entry that an + -- earlier contract overrides is left out: it duplicated the overriding entry's + -- key, which no lookup reaches, and every duplicate multiplied the work of the + -- translation (an interface's functions implemented by getters). let entriesFrom (decls : List ContractDecl) := - concatMapList - (fun d => - ContractDecl.directExternalCallKindEntriesAs decl.name d structEnv) - decls + decls.foldl + (fun acc d => + acc ++ ExternalCallKindEntries.notOverridden acc + (ContractDecl.directExternalCallKindEntriesAs decl.name d structEnv)) + [] match ContractDecl.dispatchOrder? contracts decl with | some dispatchOrder => some (entriesFrom dispatchOrder) | none => @@ -977,6 +1010,597 @@ def ExternalCallKindEnv.fromContracts? (contracts : List ContractDecl) : mapOption ContractDecl.constructorCallKindEntry? contracts some (concatLists groups ++ constructors) +/-! ### The contracts a translation can call + +The external call kind environment needs entries only for the contracts the +translated code can name: a call's callee contract is the type of its target +(a variable's declared type, a conversion `C(x)`, `this`, a base), and a type +names its contract. `ContractDecl.mentionedNames` collects every name the +declarations write (identifiers, member names, type path segments, base and +modifier paths, `using` paths); `ContractDecls.externalCallKindScope` closes the +target's linearization, every library and the file-level functions, `using` +declarations and constants under it. The traversals take fuel, and exhausted +fuel answers `mentionWildcard`, which keeps every contract. -/ + +/-- The name an exhausted traversal answers: it keeps every contract in scope. -/ +def mentionWildcard : Name := "*" + +/-- The fuel of the name traversals: the nesting depth they follow. -/ +def mentionFuel : Nat := 1024 + +def Ty.mentionedNamesFuel : Nat -> Ty -> List Name + | 0, _ => [mentionWildcard] + | fuel + 1, ty => + let go := Ty.mentionedNamesFuel fuel + match ty with + | Ty.array element _ => go element + | Ty.mapping key value => go key ++ go value + | Ty.tuple tys => concatMapList go tys + | Ty.struct path tys => path.segments ++ concatMapList go tys + | Ty.user path => path.segments + | Ty.enum path _ => path.segments + | Ty.functionWithLocations params _ returns _ _ _ => + concatMapList go params ++ concatMapList go returns + | _ => [] + +def Expr.mentionedNamesFuel : Nat -> Expr -> List Name + | 0, _ => [mentionWildcard] + | fuel + 1, expr => + let go := Expr.mentionedNamesFuel fuel + let goTy := Ty.mentionedNamesFuel fuel + let goOpt : Option Expr -> List Name + | some value => go value + | none => [] + let goArg : Arg -> List Name + | Arg.positional value => go value + | Arg.named name value => name :: go value + let goOption : CallOption -> List Name + | CallOption.named name value => name :: go value + let goItem : TupleItem -> List Name + | TupleItem.hole => [] + | TupleItem.value value => go value + match expr with + | Expr.literal _ => [] + | Expr.ident name => [name] + | Expr.typeName ty => goTy ty + | Expr.member target name => name :: go target + | Expr.index base index => go base ++ go index + | Expr.slice base start stop => go base ++ goOpt start ++ goOpt stop + | Expr.call callee args => go callee ++ concatMapList goArg args + | Expr.callWithOptions callee options args => + go callee ++ concatMapList goOption options ++ concatMapList goArg args + | Expr.newExpr ty args => goTy ty ++ concatMapList goArg args + | Expr.tuple items => concatMapList goItem items + | Expr.array values => concatMapList go values + | Expr.enumFromUInt _ value => go value + | Expr.unary _ value => go value + | Expr.binary _ lhs rhs => go lhs ++ go rhs + | Expr.ternary cond thenValue elseValue => + go cond ++ go thenValue ++ go elseValue + | Expr.assign lhs _ rhs => go lhs ++ go rhs + | Expr.payableConversion value => go value + +def Stmt.mentionedNamesFuel : Nat -> Stmt -> List Name + | 0, _ => [mentionWildcard] + | fuel + 1, stmt => + let go := Stmt.mentionedNamesFuel fuel + let goExpr := Expr.mentionedNamesFuel fuel + let goTy := Ty.mentionedNamesFuel fuel + let goOptExpr : Option Expr -> List Name + | some value => goExpr value + | none => [] + let goOptStmt : Option Stmt -> List Name + | some body => go body + | none => [] + let goParams : List Parameter -> List Name := + concatMapList (fun param => goTy param.ty) + let goBinding : VarBinding -> List Name := fun binding => + match binding.ty with + | some ty => goTy ty + | none => [] + let goClause : CatchClause -> List Name + | CatchClause.clause _ params body => goParams params ++ go body + match stmt with + | Stmt.empty => [] + | Stmt.block stmts => concatMapList go stmts + | Stmt.varDecl bindings init => + concatMapList goBinding bindings ++ goOptExpr init + | Stmt.expr value => goExpr value + | Stmt.ifElse cond thenBranch elseBranch => + goExpr cond ++ go thenBranch ++ goOptStmt elseBranch + | Stmt.whileLoop cond body => goExpr cond ++ go body + | Stmt.doWhile body cond => go body ++ goExpr cond + | Stmt.forLoop init cond step body => + goOptStmt init ++ goOptExpr cond ++ goOptExpr step ++ go body + | Stmt.tryCatch call clauses => goExpr call ++ concatMapList goClause clauses + | Stmt.tryCatchReturns call returns body clauses => + goExpr call ++ goParams returns ++ go body ++ concatMapList goClause clauses + | Stmt.emitEvent value => goExpr value + | Stmt.revertCall value => goExpr value + | Stmt.returnValues value => goOptExpr value + | Stmt.break => [] + | Stmt.continue => [] + | Stmt.unchecked body => go body + | Stmt.inlineAssembly _ => [] + | Stmt.assemblyCreate2 t v c s => goExpr t ++ goExpr v ++ goExpr c ++ goExpr s + | Stmt.modifierPlaceholder => [] + +def Ty.mentionedNames (ty : Ty) : List Name := + Ty.mentionedNamesFuel mentionFuel ty + +def Expr.mentionedNames (expr : Expr) : List Name := + Expr.mentionedNamesFuel mentionFuel expr + +def Stmt.mentionedNames (stmt : Stmt) : List Name := + Stmt.mentionedNamesFuel mentionFuel stmt + +def Option.mentionedNamesWith {α : Type} (f : α -> List Name) : Option α -> List Name + | some value => f value + | none => [] + +def Parameters.mentionedNames (params : List Parameter) : List Name := + concatMapList (fun param => Ty.mentionedNames param.ty) params + +def Args.mentionedNames (args : List Arg) : List Name := + Expr.mentionedNames (Expr.call (Expr.literal (Literal.bool true)) args) + +def OverrideSpecifier.mentionedNames (spec : OverrideSpecifier) : List Name := + concatMapList Path.segments spec.bases + +def StateVarDecl.mentionedNames (decl : StateVarDecl) : List Name := + Ty.mentionedNames decl.ty ++ + Option.mentionedNamesWith OverrideSpecifier.mentionedNames decl.override? ++ + Option.mentionedNamesWith Expr.mentionedNames decl.init + +def FunctionDecl.mentionedNames (decl : FunctionDecl) : List Name := + Parameters.mentionedNames decl.params ++ Parameters.mentionedNames decl.returns ++ + Option.mentionedNamesWith OverrideSpecifier.mentionedNames decl.override? ++ + concatMapList + (fun invocation => invocation.target.segments ++ Args.mentionedNames invocation.args) + decl.modifiers ++ + Option.mentionedNamesWith Stmt.mentionedNames decl.body + +def ModifierDecl.mentionedNames (decl : ModifierDecl) : List Name := + Parameters.mentionedNames decl.params ++ + Option.mentionedNamesWith OverrideSpecifier.mentionedNames decl.override? ++ + Option.mentionedNamesWith Stmt.mentionedNames decl.body + +def UsingDecl.mentionedNames (decl : UsingDecl) : List Name := + decl.library.segments ++ + concatMapList (fun fn => fn.function.segments) decl.functions ++ + Option.mentionedNamesWith Ty.mentionedNames decl.target + +def ContractItem.mentionedNames : ContractItem -> List Name + | ContractItem.stateVar decl => StateVarDecl.mentionedNames decl + | ContractItem.function decl => FunctionDecl.mentionedNames decl + | ContractItem.modifierDecl decl => ModifierDecl.mentionedNames decl + | ContractItem.eventDecl decl => + concatMapList (fun param => Ty.mentionedNames param.ty) decl.params + | ContractItem.errorDecl decl => Parameters.mentionedNames decl.params + | ContractItem.structDecl decl => + concatMapList (fun field => Ty.mentionedNames field.ty) decl.fields + | ContractItem.enumDecl _ => [] + | ContractItem.userValueTypeDecl decl => Ty.mentionedNames decl.underlying + | ContractItem.usingDecl decl => UsingDecl.mentionedNames decl + +/-- Every name `decl` writes: its bases and their arguments, and every name in +its items (types, expressions, statements, modifier and `using` paths). -/ +def ContractDecl.mentionedNames (decl : ContractDecl) : List Name := + Option.mentionedNamesWith Expr.mentionedNames decl.layoutBase ++ + concatMapList (fun base => base.base.segments ++ Args.mentionedNames base.args) + decl.bases ++ + concatMapList ContractItem.mentionedNames decl.items + +/-- The names of the contracts of `all` reachable from `kept` through +`mentioned`: each round keeps the contracts `mentioned` names and adds the names +they mention. Out of fuel, or on `mentionWildcard`, every contract. -/ +def ContractDecls.closeMentions (all : List ContractDecl) : + Nat -> List Name -> List Name -> List Name + | 0, _, _ => all.map ContractDecl.name + | fuel + 1, kept, mentioned => + if mentioned.contains mentionWildcard then + all.map ContractDecl.name + else + let new := all.filter fun decl => + !kept.contains decl.name && mentioned.contains decl.name + match new with + | [] => kept + | _ => + ContractDecls.closeMentions all fuel + (kept ++ new.map ContractDecl.name) + (concatMapList ContractDecl.mentionedNames new) + +/-- The contracts whose external call kinds the translation of `dispatchOrder` +(the target's linearization) can look up: those it, every library, and the +file-level functions, `using` declarations and constants name, closed under the +names those contracts write. -/ +def ContractDecls.externalCallKindScope (allContracts dispatchOrder : List ContractDecl) + (sourceFunctions : List FunctionDecl) (sourceUsingDecls : List UsingDecl) + (sourceConstants : List StateVarDecl) : List Name := + let libraries := allContracts.filter fun decl => decl.kind == ContractKind.library + let seeds := dispatchOrder ++ libraries + ContractDecls.closeMentions allContracts (allContracts.length + 1) + (seeds.map ContractDecl.name) + (concatMapList ContractDecl.mentionedNames seeds ++ + concatMapList FunctionDecl.mentionedNames sourceFunctions ++ + concatMapList UsingDecl.mentionedNames sourceUsingDecls ++ + concatMapList StateVarDecl.mentionedNames sourceConstants) + +/-- `ExternalCallKindEnv.fromContracts?` for the contracts of `contracts` named in +`scope`, each entry still computed against all of `contracts` (its bases). -/ +def ExternalCallKindEnv.fromContractsFor? (contracts : List ContractDecl) + (scope : List Name) : Option ExternalCallKindEnv := do + let inScope := contracts.filter fun decl => scope.contains decl.name + let groups ← + mapOption (ContractDecl.externalCallKindEntries? contracts) inScope + let constructors ← + mapOption ContractDecl.constructorCallKindEntry? inScope + some (concatLists groups ++ constructors) + +/-- With every contract in scope, `fromContractsFor?` is `fromContracts?`. -/ +theorem ExternalCallKindEnv.fromContractsFor?_all (contracts : List ContractDecl) : + ExternalCallKindEnv.fromContractsFor? contracts (contracts.map ContractDecl.name) = + ExternalCallKindEnv.fromContracts? contracts := by + have h : (contracts.filter fun decl => (contracts.map ContractDecl.name).contains decl.name) = + contracts := by + rw [List.filter_eq_self] + intro decl hdecl + simp only [List.contains_iff_mem, List.mem_map] + exact ⟨decl, hdecl, rfl⟩ + unfold ExternalCallKindEnv.fromContractsFor? ExternalCallKindEnv.fromContracts? + simp only [h] + +/-! The restricted environment is the whole one's entries for the contracts in +scope (`fromContractsFor?_eq_filter`), and every lookup about a contract in scope +answers as in the whole environment (`lookup?_filter`, +`lookupConstructorEntry?_filter`, `lookupAbiCall?_filter`). -/ + +theorem FunctionDecl.externalCallKindEntry?_contractName {c : Name} {fn : FunctionDecl} + {e : ExternalCallKindEntry} (h : FunctionDecl.externalCallKindEntry? c fn = some e) : + e.contractName = c := by + unfold FunctionDecl.externalCallKindEntry? at h + split at h <;> (try cases h) <;> (try rfl) + +theorem StateVarDecl.externalCallKindEntry?_contractName {c : Name} {decl : StateVarDecl} + {e : ExternalCallKindEntry} (h : StateVarDecl.externalCallKindEntry? c decl = some e) : + e.contractName = c := by + unfold StateVarDecl.externalCallKindEntry? at h + simp only [bind, Option.bind] at h + split at h + · cases h + · split at h + · cases h + · cases h; rfl + +theorem ContractDecl.directExternalCallKindEntriesAs_contractName {t : Name} + {decl : ContractDecl} {structEnv : StructEnv} {e : ExternalCallKindEntry} + (h : e ∈ ContractDecl.directExternalCallKindEntriesAs t decl structEnv) : + e.contractName = t := by + unfold ContractDecl.directExternalCallKindEntriesAs at h + simp only [List.mem_append, List.mem_filterMap] at h + rcases h with ⟨fn, _, hfn⟩ | ⟨sv, _, hsv⟩ + · cases hentry : FunctionDecl.externalCallKindEntry? t fn with + | none => simp [hentry] at hfn + | some entry => + have hc := FunctionDecl.externalCallKindEntry?_contractName hentry + simp only [hentry, bind, Option.bind] at hfn + split at hfn <;> cases hfn <;> exact hc + · exact StateVarDecl.externalCallKindEntry?_contractName hsv + +theorem ContractDecl.externalCallKindEntries?_contractName {contracts : List ContractDecl} + {decl : ContractDecl} {es : List ExternalCallKindEntry} + (h : ContractDecl.externalCallKindEntries? contracts decl = some es) : + ∀ e ∈ es, e.contractName = decl.name := by + unfold ContractDecl.externalCallKindEntries? at h + split at h + · cases h + have key : ∀ (order : List ContractDecl) (acc : List ExternalCallKindEntry), + (∀ e ∈ acc, e.contractName = decl.name) → + ∀ e ∈ order.foldl (fun acc d => acc ++ ExternalCallKindEntries.notOverridden acc + (ContractDecl.directExternalCallKindEntriesAs decl.name d + (ContractDecl.structEnvFromContracts contracts))) acc, + e.contractName = decl.name := by + intro order + induction order with + | nil => intro acc hacc e he; exact hacc e he + | cons d rest ih => + intro acc hacc e he + refine ih _ ?_ e he + intro e' he' + rcases List.mem_append.mp he' with h1 | h1 + · exact hacc e' h1 + · exact ContractDecl.directExternalCallKindEntriesAs_contractName + (ExternalCallKindEntries.mem_notOverridden h1) + exact key _ [] (by simp) + · cases h + intro e he + exact ContractDecl.directExternalCallKindEntriesAs_contractName he + +theorem ContractDecl.constructorCallKindEntry?_contractName {decl : ContractDecl} + {e : ExternalCallKindEntry} (h : ContractDecl.constructorCallKindEntry? decl = some e) : + e.contractName = decl.name := by + unfold ContractDecl.constructorCallKindEntry? at h + simp only [bind, Option.bind] at h + split at h + · cases h + · dsimp only at h + split at h + · unfold FunctionDecl.constructorCallKindEntry? at h + split at h + · cases h; rfl + · cases h + · cases h; rfl + +theorem mapOption_filter_concat {α γ : Type} (f : α -> Option (List γ)) (p : α -> Bool) + (q : γ -> Bool) (hpq : ∀ x zs, f x = some zs -> ∀ z ∈ zs, q z = p x) : + ∀ (l : List α) (ys : List (List γ)), mapOption f l = some ys -> + ∃ ys', mapOption f (l.filter p) = some ys' ∧ + concatLists ys' = (concatLists ys).filter q := by + intro l + induction l with + | nil => intro ys h; cases h; exact ⟨[], rfl, rfl⟩ + | cons x rest ih => + intro ys h + unfold mapOption at h + cases hx : f x with + | none => simp [hx] at h + | some zs => + cases hr : mapOption f rest with + | none => simp [hx, hr] at h + | some yr => + simp only [hx, hr, bind, Option.bind] at h + cases h + obtain ⟨ys', h1, h2⟩ := ih yr hr + have hz := hpq x zs hx + cases hp : p x with + | true => + refine ⟨zs :: ys', ?_, ?_⟩ + · simp only [List.filter_cons, hp, ↓reduceIte] + unfold mapOption + simp [hx, h1] + · simp only [concatLists, List.filter_append, h2] + congr 1 + refine (List.filter_eq_self.mpr ?_).symm + intro z hzm + rw [hz z hzm, hp] + | false => + refine ⟨ys', ?_, ?_⟩ + · simp only [List.filter_cons, hp, Bool.false_eq_true, ↓reduceIte] + exact h1 + · simp only [concatLists, List.filter_append, h2] + have : zs.filter q = [] := by + rw [List.filter_eq_nil_iff] + intro z hzm + rw [hz z hzm, hp] + simp + rw [this, List.nil_append] + +theorem mapOption_filter_single {α γ : Type} (f : α -> Option γ) (p : α -> Bool) + (q : γ -> Bool) (hpq : ∀ x z, f x = some z -> q z = p x) : + ∀ (l : List α) (ys : List γ), mapOption f l = some ys -> + mapOption f (l.filter p) = some (ys.filter q) := by + intro l + induction l with + | nil => intro ys h; cases h; rfl + | cons x rest ih => + intro ys h + unfold mapOption at h + cases hx : f x with + | none => simp [hx] at h + | some z => + cases hr : mapOption f rest with + | none => simp [hx, hr] at h + | some yr => + simp only [hx, hr, bind, Option.bind] at h + cases h + have h1 := ih yr hr + have hz := hpq x z hx + cases hp : p x with + | true => + simp only [List.filter_cons, hp, ↓reduceIte, hz] + unfold mapOption + simp [hx, h1] + | false => + simp only [List.filter_cons, hp, hz, Bool.false_eq_true, ↓reduceIte] + exact h1 + +/-- Whenever the whole source unit's external call kind environment exists, the +environment of the contracts in `scope` is exactly its entries for those contracts. -/ +theorem ExternalCallKindEnv.fromContractsFor?_eq_filter {contracts : List ContractDecl} + {scope : List Name} {full : ExternalCallKindEnv} + (h : ExternalCallKindEnv.fromContracts? contracts = some full) : + ExternalCallKindEnv.fromContractsFor? contracts scope = + some (full.filter fun e => scope.contains e.contractName) := by + unfold ExternalCallKindEnv.fromContracts? at h + cases hg : mapOption (ContractDecl.externalCallKindEntries? contracts) contracts with + | none => simp [hg] at h + | some groups => + cases hc : mapOption ContractDecl.constructorCallKindEntry? contracts with + | none => simp [hg, hc] at h + | some ctors => + simp only [hg, hc, bind, Option.bind] at h + cases h + obtain ⟨groups', hg', hcat⟩ := mapOption_filter_concat + (ContractDecl.externalCallKindEntries? contracts) + (fun decl => scope.contains decl.name) (fun e => scope.contains e.contractName) + (fun x zs hx z hz => by + rw [ContractDecl.externalCallKindEntries?_contractName hx z hz]) + contracts groups hg + have hc' := mapOption_filter_single ContractDecl.constructorCallKindEntry? + (fun decl => scope.contains decl.name) (fun e => scope.contains e.contractName) + (fun x z hx => by rw [ContractDecl.constructorCallKindEntry?_contractName hx]) + contracts ctors hc + unfold ExternalCallKindEnv.fromContractsFor? + simp only [hg', hc', bind, Option.bind, hcat, List.filter_append] + +theorem ExternalCallKindEnv.lookup?_filter (keep : Name -> Bool) {c : Name} + (hc : keep c = true) (functionName : Name) (paramTys : List Ty) : + ∀ env : ExternalCallKindEnv, + ExternalCallKindEnv.lookup? (env.filter fun e => keep e.contractName) c functionName paramTys = + ExternalCallKindEnv.lookup? env c functionName paramTys := by + intro env + induction env with + | nil => rfl + | cons e rest ih => + cases hk : keep e.contractName with + | true => + simp only [List.filter_cons, hk, ↓reduceIte] + unfold ExternalCallKindEnv.lookup? + rw [ih] + | false => + simp only [List.filter_cons, hk, Bool.false_eq_true, ↓reduceIte] + rw [ih] + conv => rhs; unfold ExternalCallKindEnv.lookup? + have hne : (e.contractName == c) = false := by + cases heq : e.contractName == c + · rfl + · have := beq_iff_eq.mp heq; rw [this, hc] at hk; cases hk + simp [hne] + +theorem ExternalCallKindEnv.lookupConstructorEntry?_filter (keep : Name -> Bool) {c : Name} + (hc : keep c = true) : + ∀ env : ExternalCallKindEnv, + ExternalCallKindEnv.lookupConstructorEntry? (env.filter fun e => keep e.contractName) c = + ExternalCallKindEnv.lookupConstructorEntry? env c := by + intro env + induction env with + | nil => rfl + | cons e rest ih => + cases hk : keep e.contractName with + | true => + simp only [List.filter_cons, hk, ↓reduceIte] + unfold ExternalCallKindEnv.lookupConstructorEntry? + rw [ih] + | false => + simp only [List.filter_cons, hk, Bool.false_eq_true, ↓reduceIte] + rw [ih] + conv => rhs; unfold ExternalCallKindEnv.lookupConstructorEntry? + have hne : (e.contractName == c) = false := by + cases heq : e.contractName == c + · rfl + · have := beq_iff_eq.mp heq; rw [this, hc] at hk; cases hk + simp [hne] + +theorem ExternalCallKindEnv.lookupAbiCall?_filter (keep : Name -> Bool) {c : Name} + (hc : keep c = true) (storageNames : List Name) (functionName : Name) (args : List Arg) : + ∀ env : ExternalCallKindEnv, + ExternalCallKindEnv.lookupAbiCall? storageNames + (env.filter fun e => keep e.contractName) c functionName args = + ExternalCallKindEnv.lookupAbiCall? storageNames env c functionName args := by + intro env + induction env with + | nil => rfl + | cons e rest ih => + cases hk : keep e.contractName with + | true => + simp only [List.filter_cons, hk, ↓reduceIte] + unfold ExternalCallKindEnv.lookupAbiCall? + rw [ih] + | false => + simp only [List.filter_cons, hk, Bool.false_eq_true, ↓reduceIte] + rw [ih] + conv => rhs; unfold ExternalCallKindEnv.lookupAbiCall? + have hne : (e.contractName == c) = false := by + cases heq : e.contractName == c + · rfl + · have := beq_iff_eq.mp heq; rw [this, hc] at hk; cases hk + simp [hne] + +/-- Dropping entries of an external call kind environment keeps the type environment +it makes: a lookup of a key that only kept entries carry answers as before. -/ +theorem ExternalCallKindEnv.toTypeEnv?_filter (p : ExternalCallKindEntry -> Bool) : + ∀ (env : ExternalCallKindEnv) (typeEnv : TypeEnv), + ExternalCallKindEnv.toTypeEnv? env = some typeEnv -> + ∃ typeEnv', ExternalCallKindEnv.toTypeEnv? (env.filter p) = some typeEnv' ∧ + ∀ key : Name, + (∀ e ∈ env, ∀ ty, e.toTypeEnvEntry? = some (some (key, ty)) -> p e = true) -> + TypeEnv.lookup? typeEnv' key = TypeEnv.lookup? typeEnv key := by + intro env + induction env with + | nil => + intro typeEnv h + cases h + exact ⟨[], rfl, fun _ _ => rfl⟩ + | cons e rest ih => + intro typeEnv h + unfold ExternalCallKindEnv.toTypeEnv? filterMapOption at h + cases he : e.toTypeEnvEntry? with + | none => simp [he] at h + | some hd => + cases hr : filterMapOption ExternalCallKindEntry.toTypeEnvEntry? rest with + | none => simp [he, hr] at h + | some tail => + simp only [he, hr, bind, Option.bind] at h + obtain ⟨tail', h1, h2⟩ := ih tail hr + have hrest : ∀ key : Name, + (∀ e' ∈ e :: rest, ∀ ty, e'.toTypeEnvEntry? = some (some (key, ty)) -> + p e' = true) -> + (∀ e' ∈ rest, ∀ ty, e'.toTypeEnvEntry? = some (some (key, ty)) -> + p e' = true) := + fun key hk e' he' => hk e' (List.mem_cons_of_mem _ he') + cases hp : p e with + | true => + cases hd with + | none => + simp only at h + cases h + refine ⟨tail', ?_, fun key hk => h2 key (hrest key hk)⟩ + simp only [List.filter_cons, hp, ↓reduceIte] + unfold ExternalCallKindEnv.toTypeEnv? filterMapOption + unfold ExternalCallKindEnv.toTypeEnv? at h1 + simp [he, h1] + | some entry => + simp only at h + cases h + refine ⟨entry :: tail', ?_, ?_⟩ + · simp only [List.filter_cons, hp, ↓reduceIte] + unfold ExternalCallKindEnv.toTypeEnv? filterMapOption + unfold ExternalCallKindEnv.toTypeEnv? at h1 + simp [he, h1] + · intro key hk + obtain ⟨k0, ty0⟩ := entry + unfold TypeEnv.lookup? + rw [h2 key (hrest key hk)] + | false => + have h1' : ExternalCallKindEnv.toTypeEnv? ((e :: rest).filter p) = some tail' := by + simp only [List.filter_cons, hp, Bool.false_eq_true, ↓reduceIte] + exact h1 + refine ⟨tail', h1', ?_⟩ + intro key hk + rw [h2 key (hrest key hk)] + cases hd with + | none => simp only at h; cases h; rfl + | some entry => + simp only at h + cases h + obtain ⟨k0, ty0⟩ := entry + have hne : (k0 == key) = false := by + cases heq : k0 == key + · rfl + · have hk0 := beq_iff_eq.mp heq + subst hk0 + have := hk e (List.mem_cons_self) ty0 he + rw [hp] at this + cases this + conv => rhs; unfold TypeEnv.lookup? + simp [hne] + +/-- The type environment of the restricted call kind environment answers every key +that only entries of contracts in scope carry as the whole one's does. -/ +theorem ExternalCallKindEnv.fromContractsFor?_typeEnv {contracts : List ContractDecl} + {scope : List Name} {full : ExternalCallKindEnv} {typeEnv : TypeEnv} + (hfull : ExternalCallKindEnv.fromContracts? contracts = some full) + (htype : ExternalCallKindEnv.toTypeEnv? full = some typeEnv) : + ∃ env typeEnv', ExternalCallKindEnv.fromContractsFor? contracts scope = some env ∧ + ExternalCallKindEnv.toTypeEnv? env = some typeEnv' ∧ + ∀ key : Name, + (∀ e ∈ full, ∀ ty, e.toTypeEnvEntry? = some (some (key, ty)) -> + scope.contains e.contractName = true) -> + TypeEnv.lookup? typeEnv' key = TypeEnv.lookup? typeEnv key := by + obtain ⟨typeEnv', h1, h2⟩ := + ExternalCallKindEnv.toTypeEnv?_filter (fun e => scope.contains e.contractName) full typeEnv htype + exact ⟨_, typeEnv', ExternalCallKindEnv.fromContractsFor?_eq_filter hfull, h1, h2⟩ + structure StoragePackingCursor where slot : Nat offset : Nat := 0 @@ -1744,6 +2368,47 @@ def CoreFunctionDefs.dedupInternalByName if fn.selector?.isNone then fn.name :: seen else seen)) ([], [])).1 +/-- The core function of one direct function of a contract, with the function: what + `ContractDecl.directCoreFunctions?` elaborates per function. -/ +def ContractDecl.directCoreFunctionPair? (storageNames : List Name) + (constants : ConstantEnv) + (extraEnv : TypeEnv) (externalCallKindEnv : ExternalCallKindEnv) + (contracts : List ContractDecl) + (dispatchOrder : List ContractDecl) + (usingDecls : List UsingDecl) + (modifiers : List SourceModifierDecl) (functions : List FunctionDecl) + (freeFunctions : List FunctionDecl) + (eventArgEnv errorArgEnv : NamedArgParamEnv) + (internalFnIds : List (Name × Nat)) + (eventIndexedEnv : EventIndexedEnv) + (overloadEvents : List EventDecl) + (decl : ContractDecl) (fn : FunctionDecl) : + Option (FunctionDecl × CoreFunctionDef) := do + let supers ← ContractDecls.afterName? dispatchOrder decl.name + let fd ← + FunctionDecl.toCore? + storageNames constants extraEnv contracts usingDecls modifiers + functions freeFunctions fn + (concatMapList ContractDecl.directOrdinaryFunctions supers) + (some decl.name) (dispatchOrder.map ContractDecl.name) + externalCallKindEnv eventArgEnv errorArgEnv internalFnIds + (structEnv := ContractDecl.structEnvFromContracts contracts) + (eventIndexedEnv := eventIndexedEnv) + (overloadEvents := overloadEvents) + -- BUG#6: a LIBRARY's dispatch entrypoints answer to the + -- library-qualified selector (what solc's delegatecall dispatch + -- hashes), keeping callee dispatch symmetric with the caller-side + -- payload. Contract entrypoints keep the external-ABI selector. + let fd := + if decl.kind == ContractKind.library then + { fd with + selector? := + FunctionDecl.libraryAbiSelector? + (ContractDecl.structEnvFromContracts contracts) fn } + else + fd + some (fn, fd) + def ContractDecl.directCoreFunctions? (storageNames : List Name) (constants : ConstantEnv) (extraEnv : TypeEnv) (externalCallKindEnv : ExternalCallKindEnv) @@ -1772,31 +2437,10 @@ def ContractDecl.directCoreFunctions? (storageNames : List Name) -- whole-contract elaboration cost on entrypoint-heavy lanes.) let functionPairs ← mapOption - (fun fn => do - let supers ← ContractDecls.afterName? dispatchOrder decl.name - let fd ← - FunctionDecl.toCore? - storageNames constants extraEnv contracts usingDecls modifiers - functions freeFunctions fn - (concatMapList ContractDecl.directOrdinaryFunctions supers) - (some decl.name) (dispatchOrder.map ContractDecl.name) - externalCallKindEnv eventArgEnv errorArgEnv internalFnIds - (structEnv := ContractDecl.structEnvFromContracts contracts) - (eventIndexedEnv := eventIndexedEnv) - (overloadEvents := overloadEvents) - -- BUG#6: a LIBRARY's dispatch entrypoints answer to the - -- library-qualified selector (what solc's delegatecall dispatch - -- hashes), keeping callee dispatch symmetric with the caller-side - -- payload. Contract entrypoints keep the external-ABI selector. - let fd := - if decl.kind == ContractKind.library then - { fd with - selector? := - FunctionDecl.libraryAbiSelector? - (ContractDecl.structEnvFromContracts contracts) fn } - else - fd - some (fn, fd)) + (ContractDecl.directCoreFunctionPair? + storageNames constants extraEnv externalCallKindEnv contracts dispatchOrder + usingDecls modifiers functions freeFunctions eventArgEnv errorArgEnv + internalFnIds eventIndexedEnv overloadEvents decl) ((ContractDecl.directOrdinaryFunctions decl).filter (fun fn => (FunctionDecl.isCoreEntrypoint fn || @@ -2005,7 +2649,48 @@ def ContractDecl.constructorBodyForDeployment? some (params, initStmts, baseArgCore, [bodyCore]) | _ => none -def ContractDecl.toCoreFromOrders? (allContracts : List ContractDecl) +/-! ### Staged translation + +The translation of a contract in three stages, so that a check of one contract's translation can +take them one at a time, each in a declaration of its own: the context every function body is +translated in (`ContractDecl.fromOrdersCtx?`: the resolved declarations and environments), the +function groups, one per contract of the dispatch order (`FromOrdersCtx.group?`), and their +assembly with the context into the core contract (`FromOrdersCtx.assemble?`). +`ContractDecl.toCoreFromOrders?` is their composition by definition. -/ + +/-- The context `ContractDecl.toCoreFromOrders?` translates function bodies in. -/ +structure FromOrdersCtx where + allContracts : List ContractDecl + sourceUsingDecls : List UsingDecl + sourceFunctions : List FunctionDecl + dispatchOrder : List ContractDecl + structEnv : StructEnv + stateVars : List StateVarDecl + constants : ConstantEnv + storageStateVars : List StateVarDecl + transientStateVars : List StateVarDecl + storageNames : List Name + layoutBaseSlot : Word + externalCallKindEnv : ExternalCallKindEnv + externalCallKindTypeEnv : TypeEnv + stateEnv : TypeEnv + sharedConstantTail : ConstantEnv + modifiers : List SourceModifierDecl + libraryHelpers : List FunctionDecl + baseHelpers : List FunctionDecl + superHelpers : List FunctionDecl + availableFunctions : List FunctionDecl + internalFnIds : List (Name × Nat) + contractEvents : List EventDecl + visibleSourceEvents : List EventDecl + contractErrors : List ErrorDecl + visibleSourceErrors : List ErrorDecl + eventArgEnv : NamedArgParamEnv + eventIndexedEnv : EventIndexedEnv + errorArgEnv : NamedArgParamEnv + +/-- The context of `ContractDecl.toCoreFromOrders?`: its code up to the function groups. -/ +def ContractDecl.fromOrdersCtx? (allContracts : List ContractDecl) (sourceUsingDecls : List UsingDecl) (sourceFunctions : List FunctionDecl) (sourceEvents : List EventDecl) (sourceErrors : List ErrorDecl) @@ -2013,7 +2698,7 @@ def ContractDecl.toCoreFromOrders? (allContracts : List ContractDecl) (sourceUserValueTypes : List UserValueTypeDecl) (sourceEnums : List EnumDecl) (sourceStructs : List StructDecl) (storageOrder dispatchOrder : List ContractDecl) : - Option CoreContract := do + Option FromOrdersCtx := do let allContracts := appendUniqueContracts allContracts (appendUniqueContracts storageOrder dispatchOrder) @@ -2348,7 +3033,12 @@ def ContractDecl.toCoreFromOrders? (allContracts : List ContractDecl) none else some () - let externalCallKindEnv ← ExternalCallKindEnv.fromContracts? allContracts + -- Only the contracts the translated code can name: the others' entries are + -- never looked up, and each one adds to every lookup's work. + let externalCallKindEnv ← + ExternalCallKindEnv.fromContractsFor? allContracts + (ContractDecls.externalCallKindScope allContracts dispatchOrder + sourceFunctions sourceUsingDecls sourceConstants) let externalCallKindTypeEnv ← ExternalCallKindEnv.toTypeEnv? externalCallKindEnv let stateEnv := StateVars.extendTypeEnv externalCallKindTypeEnv stateVars -- Per-contract constant scope: each contract's own/inherited constants (C3, @@ -2426,17 +3116,78 @@ def ContractDecl.toCoreFromOrders? (allContracts : List ContractDecl) -- storage/immutable variable that shadows a same-name file-level constant is -- read from storage instead of being constant-folded (and a derived -- contract's constant does not leak into a base entrypoint body). - let functionGroups ← - mapOption - (fun decl => - ContractDecl.directCoreFunctions? - storageNames - (ContractDecl.scopedConstantEnv dispatchOrder sharedConstantTail decl) - stateEnv externalCallKindEnv allContracts - dispatchOrder sourceUsingDecls modifiers availableFunctions - sourceFunctions eventArgEnv errorArgEnv internalFnIds eventIndexedEnv - (contractEvents ++ visibleSourceEvents) decl) - dispatchOrder + some + { allContracts := allContracts, + sourceUsingDecls := sourceUsingDecls, + sourceFunctions := sourceFunctions, + dispatchOrder := dispatchOrder, + structEnv := structEnv, + stateVars := stateVars, + constants := constants, + storageStateVars := storageStateVars, + transientStateVars := transientStateVars, + storageNames := storageNames, + layoutBaseSlot := layoutBaseSlot, + externalCallKindEnv := externalCallKindEnv, + externalCallKindTypeEnv := externalCallKindTypeEnv, + stateEnv := stateEnv, + sharedConstantTail := sharedConstantTail, + modifiers := modifiers, + libraryHelpers := libraryHelpers, + baseHelpers := baseHelpers, + superHelpers := superHelpers, + availableFunctions := availableFunctions, + internalFnIds := internalFnIds, + contractEvents := contractEvents, + visibleSourceEvents := visibleSourceEvents, + contractErrors := contractErrors, + visibleSourceErrors := visibleSourceErrors, + eventArgEnv := eventArgEnv, + eventIndexedEnv := eventIndexedEnv, + errorArgEnv := errorArgEnv } + +/-- The function group of one contract of the dispatch order. -/ +def FromOrdersCtx.group? (c : FromOrdersCtx) (decl : ContractDecl) : + Option (List CoreFunctionDef) := + ContractDecl.directCoreFunctions? + c.storageNames + (ContractDecl.scopedConstantEnv c.dispatchOrder c.sharedConstantTail decl) + c.stateEnv c.externalCallKindEnv c.allContracts + c.dispatchOrder c.sourceUsingDecls c.modifiers c.availableFunctions + c.sourceFunctions c.eventArgEnv c.errorArgEnv c.internalFnIds c.eventIndexedEnv + (c.contractEvents ++ c.visibleSourceEvents) decl + +/-- The core contract of the context and the function groups: the rest of `ContractDecl.toCoreFromOrders?`. -/ +def FromOrdersCtx.assemble? (c : FromOrdersCtx) (functionGroups : List (List CoreFunctionDef)) : + Option CoreContract := do + let allContracts := c.allContracts + let sourceUsingDecls := c.sourceUsingDecls + let sourceFunctions := c.sourceFunctions + let dispatchOrder := c.dispatchOrder + let structEnv := c.structEnv + let stateVars := c.stateVars + let constants := c.constants + let storageStateVars := c.storageStateVars + let transientStateVars := c.transientStateVars + let storageNames := c.storageNames + let layoutBaseSlot := c.layoutBaseSlot + let externalCallKindEnv := c.externalCallKindEnv + let externalCallKindTypeEnv := c.externalCallKindTypeEnv + let stateEnv := c.stateEnv + let sharedConstantTail := c.sharedConstantTail + let modifiers := c.modifiers + let libraryHelpers := c.libraryHelpers + let baseHelpers := c.baseHelpers + let superHelpers := c.superHelpers + let availableFunctions := c.availableFunctions + let internalFnIds := c.internalFnIds + let contractEvents := c.contractEvents + let visibleSourceEvents := c.visibleSourceEvents + let contractErrors := c.contractErrors + let visibleSourceErrors := c.visibleSourceErrors + let eventArgEnv := c.eventArgEnv + let eventIndexedEnv := c.eventIndexedEnv + let errorArgEnv := c.errorArgEnv -- Function-boundary refactor stage 3: value-boundary synthetic helpers -- (library `__library_*`, super/base helpers) get selector-less table entries -- under the same `internalTableKey?` the call-site emits. Elaborated once via @@ -2620,6 +3371,23 @@ def ContractDecl.toCoreFromOrders? (allContracts : List ContractDecl) errorDecls := errorDecls functions := functions } +/-- The core contract of a contract: its context, function groups and their assembly. -/ +def ContractDecl.toCoreFromOrders? (allContracts : List ContractDecl) + (sourceUsingDecls : List UsingDecl) + (sourceFunctions : List FunctionDecl) (sourceEvents : List EventDecl) + (sourceErrors : List ErrorDecl) + (sourceConstants : List StateVarDecl) + (sourceUserValueTypes : List UserValueTypeDecl) + (sourceEnums : List EnumDecl) (sourceStructs : List StructDecl) + (storageOrder dispatchOrder : List ContractDecl) : + Option CoreContract := + (do + let c ← ContractDecl.fromOrdersCtx? allContracts sourceUsingDecls sourceFunctions + sourceEvents sourceErrors sourceConstants sourceUserValueTypes sourceEnums + sourceStructs storageOrder dispatchOrder + let functionGroups ← mapOption c.group? c.dispatchOrder + c.assemble? functionGroups) + /-- Assemble the constructor-body statements from the per-contract pieces in DESCENT order (most-derived first), reproducing solc's legacy control flow (`ContractCompiler::appendBaseConstructor` + the constructor `visit`): at @@ -2978,7 +3746,12 @@ def ContractDecl.constructorFunctionFromOrders? let storageNames := storageAliases ++ stateNamesFrom (storageStateVars ++ transientStateVars) immutableStateVars - let externalCallKindEnv ← ExternalCallKindEnv.fromContracts? allContracts + -- Only the contracts the translated code can name: the others' entries are + -- never looked up, and each one adds to every lookup's work. + let externalCallKindEnv ← + ExternalCallKindEnv.fromContractsFor? allContracts + (ContractDecls.externalCallKindScope allContracts dispatchOrder + sourceFunctions (sourceUsingDecls ++ constructorUsingDecls) sourceConstants) let externalCallKindTypeEnv ← ExternalCallKindEnv.toTypeEnv? externalCallKindEnv let stateEnv := StateVars.extendTypeEnv externalCallKindTypeEnv stateVars -- Per-contract constant scope: each contract's own/inherited constants (C3, diff --git a/SolidCore/Solidity/Interface/Expressions.lean b/SolidCore/Solidity/Interface/Expressions.lean index 718dca69..97ddda7f 100644 --- a/SolidCore/Solidity/Interface/Expressions.lean +++ b/SolidCore/Solidity/Interface/Expressions.lean @@ -216,8 +216,23 @@ def Expr.toCoreFixedBytesBitOpWithEnvFuel? (fuel : Nat) | Expr.call (Expr.typeName (Ty.fixedBytes castSize)) [Arg.positional inner] => if castSize == size then - Expr.toCoreFixedBytesBitOpWithEnvFuel? - fuel storageNames env size inner + -- The operand of a `bytesN` conversion runs at its own width + -- (see `Expr.toCoreFixedBytesBitOp?`): convert after the + -- operator, never widen the leaves first. + match (Expr.abiTyWithEnv? env inner).bind Ty.fixedBytesSize? with + | some innerSize => + if innerSize != size && Expr.isFixedBytesBitOpShape inner then do + let innerCore ← + Expr.toCoreFixedBytesBitOpWithEnvFuel? + fuel storageNames env innerSize inner + some (SolidCore.Solidity.Source.Expr.fixedBytesCast + size innerSize innerCore) + else + Expr.toCoreFixedBytesBitOpWithEnvFuel? + fuel storageNames env size inner + | none => + Expr.toCoreFixedBytesBitOpWithEnvFuel? + fuel storageNames env size inner else Expr.toCoreAsWithEnvDirect? storageNames env (Ty.bytesN size) expr @@ -2548,6 +2563,8 @@ def Stmt.annotateAbiInSeqFuel : | Stmt.continue => (Stmt.continue, env) | Stmt.unchecked body => (Stmt.unchecked (annotateStmt body), env) | Stmt.inlineAssembly code => (Stmt.inlineAssembly code, env) + | Stmt.assemblyCreate2 t v c s => + (Stmt.assemblyCreate2 (annotateExpr t) (annotateExpr v) (annotateExpr c) (annotateExpr s), env) | Stmt.modifierPlaceholder => (Stmt.modifierPlaceholder, env) def Stmt.annotateAbiFuel (fuel : Nat) (env : TypeEnv) (stmt : Stmt) : @@ -2990,8 +3007,9 @@ def FunctionDecl.internalTableKey? (decl : FunctionDecl) : Option Name := do -- a structural identity of the parameter types (derived `repr`, which preserves -- struct `Path`, enum tag, and user `Path`) so the key is unique per resolved -- callee. Computed identically at the call-site emit and the table build (both - -- from the same resolved `FunctionDecl`), so the two never drift. - let identity := toString (repr (decl.params.map Parameter.ty)) + -- from the same resolved `FunctionDecl`), so the two never drift. `Ty.reprListString` + -- is the flat print, which the kernel evaluates (the derived print when short). + let identity := Ty.reprListString (decl.params.map Parameter.ty) some ("__internal_" ++ sig ++ "#" ++ identity) /-- A parameter/return that the function boundary can carry across a framed @@ -3375,6 +3393,8 @@ def Stmt.resolveInterfaceIdsFuel : Nat -> InterfaceIdEnv -> Stmt -> Stmt | Stmt.continue => Stmt.continue | Stmt.unchecked body => Stmt.unchecked (resolveStmt body) | Stmt.inlineAssembly code => Stmt.inlineAssembly code + | Stmt.assemblyCreate2 t v c s => + Stmt.assemblyCreate2 (resolveExpr t) (resolveExpr v) (resolveExpr c) (resolveExpr s) | Stmt.modifierPlaceholder => Stmt.modifierPlaceholder def CatchClause.resolveInterfaceIdsFuel : @@ -3661,6 +3681,8 @@ def Stmt.resolveSelectorsFuel : | Stmt.continue => Stmt.continue | Stmt.unchecked body => Stmt.unchecked (resolveStmt body) | Stmt.inlineAssembly code => Stmt.inlineAssembly code + | Stmt.assemblyCreate2 t v c s => + Stmt.assemblyCreate2 (resolveExpr t) (resolveExpr v) (resolveExpr c) (resolveExpr s) | Stmt.modifierPlaceholder => Stmt.modifierPlaceholder def CatchClause.resolveSelectorsFuel : @@ -3954,6 +3976,8 @@ def Stmt.resolveEventSelectorsFuel : | Stmt.continue => Stmt.continue | Stmt.unchecked body => Stmt.unchecked (resolveStmt body) | Stmt.inlineAssembly code => Stmt.inlineAssembly code + | Stmt.assemblyCreate2 t v c s => + Stmt.assemblyCreate2 (resolveExpr t) (resolveExpr v) (resolveExpr c) (resolveExpr s) | Stmt.modifierPlaceholder => Stmt.modifierPlaceholder def CatchClause.resolveEventSelectorsFuel : @@ -4138,6 +4162,8 @@ def Stmt.resolveFunctionAddressesFuel : | Stmt.continue => Stmt.continue | Stmt.unchecked body => Stmt.unchecked (resolveStmt body) | Stmt.inlineAssembly code => Stmt.inlineAssembly code + | Stmt.assemblyCreate2 t v c s => + Stmt.assemblyCreate2 (resolveExpr t) (resolveExpr v) (resolveExpr c) (resolveExpr s) | Stmt.modifierPlaceholder => Stmt.modifierPlaceholder def CatchClause.resolveFunctionAddressesFuel : @@ -4314,6 +4340,8 @@ def Stmt.resolveNamedEventErrorArgsFuel : | Stmt.continue => Stmt.continue | Stmt.unchecked body => Stmt.unchecked (resolveStmt body) | Stmt.inlineAssembly code => Stmt.inlineAssembly code + | Stmt.assemblyCreate2 t v c s => + Stmt.assemblyCreate2 t v c s | Stmt.modifierPlaceholder => Stmt.modifierPlaceholder def CatchClause.resolveNamedEventErrorArgsFuel : @@ -4612,6 +4640,8 @@ def Stmt.renameIdentsFuel : Nat -> NameAliasEnv -> Stmt -> Stmt | fuel + 1, env, Stmt.unchecked body => Stmt.unchecked (Stmt.renameIdentsFuel fuel env body) | _ + 1, _, Stmt.inlineAssembly code => Stmt.inlineAssembly code + | fuel + 1, env, Stmt.assemblyCreate2 t v c s => + Stmt.assemblyCreate2 (Expr.renameIdentsFuel fuel env t) (Expr.renameIdentsFuel fuel env v) (Expr.renameIdentsFuel fuel env c) (Expr.renameIdentsFuel fuel env s) | _ + 1, _, Stmt.modifierPlaceholder => Stmt.modifierPlaceholder termination_by fuel _ _ => fuel @@ -6512,6 +6542,8 @@ def Stmt.inlineInternalFunctionAliasesFuel (Stmt.inlineInternalFunctionAliasesFuel functions freeFunctions fuel aliasEnv body) | _ + 1, _, Stmt.inlineAssembly code => Stmt.inlineAssembly code + | fuel + 1, aliasEnv, Stmt.assemblyCreate2 t v c s => + Stmt.assemblyCreate2 (Expr.inlineInternalFunctionAliasesFuel fuel aliasEnv t) (Expr.inlineInternalFunctionAliasesFuel fuel aliasEnv v) (Expr.inlineInternalFunctionAliasesFuel fuel aliasEnv c) (Expr.inlineInternalFunctionAliasesFuel fuel aliasEnv s) | _ + 1, _, Stmt.modifierPlaceholder => Stmt.modifierPlaceholder termination_by fuel _ _ => fuel @@ -7795,6 +7827,66 @@ def Expr.reorderNamedInternalCallArgs | none => args | _ => args +/-- Call-free, side-effect-free expression shapes (reads, pure operators and + elementary conversions). -/ +def Expr.argPosCallFreeFuel : Nat -> Expr -> Bool + | 0, _ => false + | fuel + 1, e => + match e with + | Expr.literal _ => true + | Expr.ident _ => true + | Expr.member base _ => Expr.argPosCallFreeFuel fuel base + | Expr.index base key => + Expr.argPosCallFreeFuel fuel base && Expr.argPosCallFreeFuel fuel key + | Expr.unary UnaryOp.logicalNot x + | Expr.unary UnaryOp.bitNot x + | Expr.unary UnaryOp.neg x => Expr.argPosCallFreeFuel fuel x + | Expr.binary _ l r => + Expr.argPosCallFreeFuel fuel l && Expr.argPosCallFreeFuel fuel r + | Expr.call (Expr.typeName _) [Arg.positional x] => + Expr.argPosCallFreeFuel fuel x + | Expr.enumFromUInt _ x => Expr.argPosCallFreeFuel fuel x + | Expr.payableConversion x => Expr.argPosCallFreeFuel fuel x + | _ => false + +def Expr.argPosCallFree (e : Expr) : Bool := + Expr.argPosCallFreeFuel 10000 e + +/-- Values no later call can change: literals and hoist-temp reads. -/ +def Expr.argPosSettled : Expr -> Bool + | Expr.literal _ => true + | Expr.unary UnaryOp.neg (Expr.literal _) => true + | Expr.ident name => + name.startsWith "_sol_argpos_" || name.startsWith "_sol_hoist_" + | Expr.call (Expr.typeName _) [Arg.positional (Expr.ident name)] => + name.startsWith "_sol_argpos_" || name.startsWith "_sol_hoist_" + | _ => false + +def Ty.argPosParkable : Ty -> Bool + | Ty.bool | Ty.address _ | Ty.uint _ | Ty.int _ | Ty.bytesN _ + | Ty.fixedBytes _ | Ty.enum _ _ => true + | _ => false + +/-- Sibling parking for the argument-position hoister. solc evaluates call + arguments, tuple components and inline-array elements left to right + (`ExpressionCompiler.cpp`), so a call nested in a LATER sibling must not be + hoisted ahead of an EARLIER sibling that reads state the call may change + (`abi.encodePacked(n, bump())` reads `n` before `bump()` runs). Such an + earlier sibling, when call-free and value-typed, is returned in place of + the call: the caller binds it to the temp first, and the call is peeled on + the next round. Settled siblings (literals, temp reads) are left alone. -/ +def Expr.argPosPark? (env : TypeEnv) (tmp : Name) (e : Expr) : + Option (Expr × Ty × Expr) := + if Expr.argPosSettled e || !(Expr.argPosCallFree e) then none + else + match Expr.abiTyWithEnv? env e with + | some ty => + if Ty.argPosParkable ty then + some (e, ty, + Expr.call (Expr.typeName ty) [Arg.positional (Expr.ident tmp)]) + else none + | none => none + mutual def Expr.findArgPosInnerCall? (functions : List FunctionDecl) @@ -7930,21 +8022,34 @@ def Expr.findArgPosInnerCall? (functions : List FunctionDecl) | some (c, t, m') => some (c, t, Expr.call callee [a, b, Arg.withExpr m' m]) | none => + -- An operand evaluated before the operand holding the call + -- (the modulus, then the second operand) is parked first. + let parkM := fun (fallback : Option (Expr × Ty × Expr)) => + match Expr.argPosPark? env tmp mExpr with + | some (p, pt, m') => + some (p, pt, Expr.call callee [a, b, Arg.withExpr m' m]) + | none => fallback match Expr.findArgPosInnerCall? functions env tmp false fuel bExpr with | some (c, t, b') => - some (c, t, - Expr.call callee [a, Arg.withExpr b' b, m]) + parkM (some (c, t, + Expr.call callee [a, Arg.withExpr b' b, m])) | none => match Expr.findArgPosInnerCall? functions env tmp false fuel aExpr with | some (c, t, a') => - some (c, t, - Expr.call callee [Arg.withExpr a' a, b, m]) + parkM + (match Expr.argPosPark? env tmp bExpr with + | some (p, pt, b') => + some (p, pt, + Expr.call callee [a, Arg.withExpr b' b, m]) + | none => + some (c, t, + Expr.call callee [Arg.withExpr a' a, b, m])) | none => normal else normal @@ -7967,7 +8072,10 @@ def Expr.findArgPosInnerCallExprs? (functions : List FunctionDecl) | some (c, t, e') => some (c, t, e' :: rest) | none => match Expr.findArgPosInnerCallExprs? functions env tmp fuel rest with - | some (c, t, rest') => some (c, t, e :: rest') + | some (c, t, rest') => + match Expr.argPosPark? env tmp e with + | some (p, pt, e') => some (p, pt, e' :: rest) + | none => some (c, t, e :: rest') | none => none termination_by fuel _ => fuel @@ -7985,7 +8093,10 @@ def Expr.findArgPosInnerCallArgs? (functions : List FunctionDecl) | some (c, t, e') => some (c, t, Arg.withExpr e' arg :: rest) | none => match Expr.findArgPosInnerCallArgs? functions env tmp fuel rest with - | some (c, t, rest') => some (c, t, arg :: rest') + | some (c, t, rest') => + match Expr.argPosPark? env tmp argExpr with + | some (p, pt, e') => some (p, pt, Arg.withExpr e' arg :: rest) + | none => some (c, t, arg :: rest') | none => none termination_by fuel _ => fuel @@ -8005,7 +8116,10 @@ def Expr.findArgPosInnerCallTuple? (functions : List FunctionDecl) | some (c, t, e') => some (c, t, TupleItem.value e' :: rest) | none => match Expr.findArgPosInnerCallTuple? functions env tmp fuel rest with - | some (c, t, rest') => some (c, t, item :: rest') + | some (c, t, rest') => + match Expr.argPosPark? env tmp expr with + | some (p, pt, e') => some (p, pt, TupleItem.value e' :: rest) + | none => some (c, t, item :: rest') | none => none termination_by fuel _ => fuel @@ -8291,9 +8405,44 @@ def Expr.anfHoist let (c1, pm, m') := rec1 c m let (c2, pb, b') := rec1 c1 b let (c3, pa, a') := rec1 c2 a - ( c3 - , pm ++ pb ++ pa - , [Arg.positional a', Arg.positional b', Arg.positional m'] ) + -- A later-evaluated operand's hoisted calls must not run + -- before an earlier-evaluated operand is read: park the + -- modulus (and check it for zero, as solc does before the + -- operands) ahead of the operand preludes, and the second + -- operand ahead of the first operand's prelude. + let park := fun (cc : Nat) (x : Expr) => + match x with + | Expr.literal _ => (cc, [], x) + | _ => + let t := anfHoistName cc + ( cc + 1 + , [Stmt.varDecl + [{ name := some t, ty := some (Ty.uint 256), + location := none }] + (some x)] + , Expr.ident t ) + let (c4, mFix, m'') := + if pb.isEmpty && pa.isEmpty then (c3, [], m') + else + match park c3 m' with + | (cc, [], x) => (cc, [], x) + | (cc, decls, x) => + let chk := anfHoistName cc + ( cc + 1 + , decls ++ + [Stmt.varDecl + [{ name := some chk, ty := some (Ty.uint 256), + location := none }] + (some (Expr.call (Expr.ident name) + [ Arg.positional (Expr.literal (Literal.number "0")) + , Arg.positional (Expr.literal (Literal.number "0")) + , Arg.positional x ]))] + , x ) + let (c5, bFix, b'') := + if pa.isEmpty then (c4, [], b') else park c4 b' + ( c5 + , pm ++ mFix ++ pb ++ bFix ++ pa + , [Arg.positional a', Arg.positional b'', Arg.positional m''] ) else recArgs c args | _, _ => recArgs c args @@ -8543,4 +8692,38 @@ def Stmt.anfNormalizeSelf? if pre.isEmpty then none else done pre (Stmt.revertCall e') | _ => none + +/-- A member path rooted at a state variable (`v`, `s.a`, `s.inner.b`): its + storage slot is fixed, so evaluating it computes nothing that a later call + could change. -/ +def Expr.isStateMemberPath (storageNames : List Name) (env : TypeEnv) : + Expr -> Bool + | Expr.ident name => (stateNameRuntimeKey? name storageNames).isSome + | Expr.member base _ => Expr.isStateMemberPath storageNames env base + -- A struct field, which lowering spells as a literal index into the struct. + | Expr.index base (Expr.literal (Literal.number _)) => + (match Expr.abiTyWithEnv? env base with + | some (Ty.struct _ _) => true + | _ => false) && + Expr.isStateMemberPath storageNames env base + | _ => false + +/-- A tuple component that is a storage array, struct, `bytes` or `string` at a + state member path. solc evaluates such a component to a storage reference + and copies it to memory only when the whole tuple is converted to its + target types, after every later component ran (legacy + `ExpressionCompiler::visit(TupleExpression)` then `convertType`, via-IR + `IRGeneratorForStatements` likewise), so the copy reads storage as the + later components left it. -/ +def Expr.isDeferredStorageAggregate (storageNames : List Name) (env : TypeEnv) + (targetTy : Ty) (expr : Expr) : Bool := + let isAggregate : Ty -> Bool + | Ty.array _ _ | Ty.struct _ _ | Ty.bytes | Ty.string => true + | _ => false + -- A state member path converting to an aggregate is itself one; the + -- component's own type covers targets named through a user type. + Expr.isStateMemberPath storageNames env expr && + (isAggregate targetTy || + ((Expr.abiTyWithEnv? env expr).map isAggregate).getD false) + end SolidCore.Solidity.Executable diff --git a/SolidCore/Solidity/Interface/Foundation.lean b/SolidCore/Solidity/Interface/Foundation.lean index c91ae1cf..1a5af396 100644 --- a/SolidCore/Solidity/Interface/Foundation.lean +++ b/SolidCore/Solidity/Interface/Foundation.lean @@ -346,6 +346,8 @@ def Stmt.inlineConstantsFuel : Nat -> ConstantEnv -> Stmt -> Stmt | Stmt.continue => Stmt.continue | Stmt.unchecked body => Stmt.unchecked (inlineStmt body) | Stmt.inlineAssembly code => Stmt.inlineAssembly code + | Stmt.assemblyCreate2 t v c s => + Stmt.assemblyCreate2 (inlineExpr t) (inlineExpr v) (inlineExpr c) (inlineExpr s) | Stmt.modifierPlaceholder => Stmt.modifierPlaceholder /-- Rewrite a statement list in source order. A local declaration shadows a @@ -533,6 +535,8 @@ def Stmt.rewriteSuperCallsFuel (contractName : Name) : Nat -> Stmt -> Stmt | Stmt.continue => Stmt.continue | Stmt.unchecked body => Stmt.unchecked (rewriteStmt body) | Stmt.inlineAssembly code => Stmt.inlineAssembly code + | Stmt.assemblyCreate2 t v c s => + Stmt.assemblyCreate2 (rewriteExpr t) (rewriteExpr v) (rewriteExpr c) (rewriteExpr s) | Stmt.modifierPlaceholder => Stmt.modifierPlaceholder def CatchClause.rewriteSuperCallsFuel (contractName : Name) : @@ -740,6 +744,8 @@ def Stmt.rewriteBaseCallsFuel (baseNames stateNames : List Name) : | Stmt.continue => Stmt.continue | Stmt.unchecked body => Stmt.unchecked (rewriteStmt body) | Stmt.inlineAssembly code => Stmt.inlineAssembly code + | Stmt.assemblyCreate2 t v c s => + Stmt.assemblyCreate2 (rewriteExpr t) (rewriteExpr v) (rewriteExpr c) (rewriteExpr s) | Stmt.modifierPlaceholder => Stmt.modifierPlaceholder def CatchClause.rewriteBaseCallsFuel (baseNames stateNames : List Name) : @@ -1228,6 +1234,8 @@ def Stmt.resolveUserTypesFuel : Nat -> UserTypeEnv -> Stmt -> Stmt | Stmt.continue => Stmt.continue | Stmt.unchecked body => Stmt.unchecked (resolveStmt body) | Stmt.inlineAssembly code => Stmt.inlineAssembly code + | Stmt.assemblyCreate2 t v c s => + Stmt.assemblyCreate2 (resolveExpr t) (resolveExpr v) (resolveExpr c) (resolveExpr s) | Stmt.modifierPlaceholder => Stmt.modifierPlaceholder def CatchClause.resolveUserTypesFuel : @@ -1565,6 +1573,8 @@ def Stmt.resolveEnumsFuel : Nat -> EnumEnv -> Stmt -> Stmt | Stmt.continue => Stmt.continue | Stmt.unchecked body => Stmt.unchecked (resolveStmt body) | Stmt.inlineAssembly code => Stmt.inlineAssembly code + | Stmt.assemblyCreate2 t v c s => + Stmt.assemblyCreate2 (resolveExpr t) (resolveExpr v) (resolveExpr c) (resolveExpr s) | Stmt.modifierPlaceholder => Stmt.modifierPlaceholder def CatchClause.resolveEnumsFuel : @@ -2207,6 +2217,8 @@ def Stmt.resolveStructsInSeqFuel : | Stmt.continue => (Stmt.continue, typeEnv) | Stmt.unchecked body => (Stmt.unchecked (resolveStmt body), typeEnv) | Stmt.inlineAssembly code => (Stmt.inlineAssembly code, typeEnv) + | Stmt.assemblyCreate2 t v c s => + (Stmt.assemblyCreate2 (resolveExpr t) (resolveExpr v) (resolveExpr c) (resolveExpr s), typeEnv) | Stmt.modifierPlaceholder => (Stmt.modifierPlaceholder, typeEnv) end @@ -4631,10 +4643,11 @@ def externalCallKindTypeEnvName? (contractName functionName : Name) -- identity of the resolved parameter types (derived `repr`, which carries -- the canonical enum path and struct path) — computed identically at entry -- build and lookup, so the key stays symmetric. Repr-identity only: the - -- key never reaches an ABI boundary. + -- key never reaches an ABI boundary. `Ty.reprListString` is the flat print, + -- which the kernel evaluates (the derived print when short). some (externalCallKindTypeEnvPrefix ++ contractName ++ ":" ++ signature ++ - "#" ++ toString (repr paramTys)) + "#" ++ Ty.reprListString paramTys) def ExternalCallKindEntry.toTypeEnvEntry? (entry : ExternalCallKindEntry) : Option (Option (Name × Ty)) := do @@ -7930,7 +7943,21 @@ def Expr.toCoreFixedBytesBitOp? (storageNames : List Name) (env : TypeEnv) | Expr.call (Expr.typeName (Ty.bytesN castSize)) [Arg.positional inner] | Expr.call (Expr.typeName (Ty.fixedBytes castSize)) [Arg.positional inner] => if castSize == size then - Expr.toCoreFixedBytesBitOp? storageNames env size inner + -- A conversion to `bytesN size` of a narrower (or wider) shift/bitwise + -- operand: the operator runs at the OPERAND's width, then the result + -- is converted. Walking the operand at `size` would widen the leaves + -- first, so `bytes32(bytes2(x) >> c)` kept the bits shifted below the + -- 2-byte lane instead of discarding them. + match (Expr.abiTyWithEnv? env inner).bind Ty.fixedBytesSize? with + | some innerSize => + if innerSize != size && Expr.isFixedBytesBitOpShape inner then do + let innerCore ← + Expr.toCoreFixedBytesBitOp? storageNames env innerSize inner + some (SolidCore.Solidity.Source.Expr.fixedBytesCast + size innerSize innerCore) + else + Expr.toCoreFixedBytesBitOp? storageNames env size inner + | none => Expr.toCoreFixedBytesBitOp? storageNames env size inner else Expr.toCoreAsWithEnvDirect? storageNames env (Ty.bytesN size) diff --git a/SolidCore/Solidity/Interface/Statements.lean b/SolidCore/Solidity/Interface/Statements.lean index b435051b..8a768d2d 100644 --- a/SolidCore/Solidity/Interface/Statements.lean +++ b/SolidCore/Solidity/Interface/Statements.lean @@ -2981,6 +2981,17 @@ def FunctionDecl.tupleItemsUseCoreWithInternalCalls? Option CoreStmt | _, [], [], useItems => some (useItems []) | index, targetTy :: targetTys, TupleItem.value expr :: rest, useItems => do + -- A storage aggregate component is copied when the tuple is used, after + -- the later components ran (`Expr.isDeferredStorageAggregate`). + if Expr.isDeferredStorageAggregate storageNames env targetTy expr then + if let some coreExpr := + (Expr.toCoreAsWithEnv? storageNames env targetTy expr).orElse + (fun _ => Expr.toCore? storageNames expr) then + return ← FunctionDecl.tupleItemsUseCoreWithInternalCalls? + internalFuel storageRefEnv env externalCallKindEnv storageNames + modifiers functions freeFunctions fallbackPrefix + (index + 1) targetTys rest + (fun coreExprs => useItems (coreExpr :: coreExprs)) let tmp := internalCallArgTempName fallbackPrefix index let tmpTy ← Ty.toCore? targetTy let assignCore ← @@ -3345,6 +3356,12 @@ def Stmt.argPositionHoist? (internalFuel : Nat) | some (callExpr, retTy, replacedExpr) => do let retCoreTy ← Ty.toCore? retTy let callCore ← + if Expr.argPosCallFree callExpr then do + -- A parked earlier sibling (`Expr.argPosPark?`): bind its value. + let valueCore ← Expr.toCoreAsWithEnv? storageNames env retTy callExpr + some (SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var tmp) valueCore) + else FunctionDecl.internalExprSingleReturnUseCore? fuel storageRefEnv env externalCallKindEnv storageNames modifiers functions freeFunctions callExpr @@ -3390,6 +3407,13 @@ def Expr.argPositionHoistPrefix? (internalFuel : Nat) (do let retCoreTy ← Ty.toCore? retTy let callCore ← + if Expr.argPosCallFree callExpr then do + -- A parked earlier sibling (`Expr.argPosPark?`): bind its value. + let valueCore ← + Expr.toCoreAsWithEnv? storageNames env retTy callExpr + some (SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var tmp) valueCore) + else FunctionDecl.internalExprSingleReturnUseCore? fuel storageRefEnv env externalCallKindEnv storageNames modifiers functions freeFunctions callExpr @@ -3612,6 +3636,14 @@ def storageTernaryBranchAliasPieces? (internalFuel : Nat) [ SolidCore.Solidity.Source.Stmt.storageAlias localName "" , SolidCore.Solidity.Source.Stmt.ifElse condCore thenCore elseCore ] +/-- A Yul operand of `Stmt.assemblyCreate2`: a number literal, or a local read as its word. -/ +def Expr.assemblyWordCore? : Expr -> Option CoreExpr + | Expr.ident name => some (SolidCore.Solidity.Source.Expr.var name) + | Expr.literal (Literal.number text) => do + let value ← parseNumberNat? text + if value < 2 ^ 256 then some (SolidCore.Solidity.Source.Expr.word value) else none + | _ => none + def Stmt.lowerCore? (internalFuel : Nat) (ctx? : Option StmtLoweringCtx) (storageNames : List Name) (stmt : Stmt) : Option CoreStmt := -- ITEM-2 (§3c collapse, phase 1): statements whose lowering is IDENTICAL @@ -3629,6 +3661,14 @@ def Stmt.lowerCore? (internalFuel : Nat) (ctx? : Option StmtLoweringCtx) match stmt with | Stmt.empty => some SolidCore.Solidity.Source.Stmt.skip | Stmt.inlineAssembly "" => some SolidCore.Solidity.Source.Stmt.skip + -- Inline assembly `target := create2(value, add(code, 32), mload(code), salt)` over locals + -- (checked by `checkAssemblyCreate2`): a Yul assignment writes the local's word as it is. + | Stmt.assemblyCreate2 (Expr.ident target) value (Expr.ident code) salt => do + let valueCore ← Expr.assemblyWordCore? value + let saltCore ← Expr.assemblyWordCore? salt + some (SolidCore.Solidity.Source.Stmt.assign (SolidCore.Solidity.Source.LValue.var target) + (SolidCore.Solidity.Source.Expr.create2Bytes valueCore + (SolidCore.Solidity.Source.Expr.var code) saltCore)) -- Solidity accepts the special base-dispatch namespace as a bare -- expression statement (`super;`). Merely evaluating that namespace has -- no runtime effect; only a member call such as `super.f()` dispatches. @@ -9855,7 +9895,7 @@ def Stmt.anfPreprocess (structEnv : StructEnv) (internalFuel : Nat) match normalized? with | some stmt2 => stmt2 | none => stmt1 -termination_by fuel _ => fuel +termination_by structural fuel _ => fuel def defaultAnfPreprocessFuel : Nat := 1024 @@ -10888,6 +10928,68 @@ def UsingDecls.rewriteCall? (contracts : List ContractDecl) UsingDecls.rewriteCall? contracts freeFunctions env receiver method args rest +/-- USING-FOR on an external call's result (`IERC20(t).balanceOf(a).sub(b)`): + the receiver's type is the single return type of the function the call + names, declared directly on the interface or contract it converts to. + `Expr.abiTyWithEnv?` cannot type a call result, so without this the + attached call stays unresolved and the contract fails to translate. -/ +def Expr.externalCallReturnTy? (contracts : List ContractDecl) : + Expr -> Option Ty + | Expr.call (Expr.member (Expr.call (Expr.typeName (Ty.user path)) + [Arg.positional _]) method) _ => do + let name ← pathLast? path + let decl ← contracts.find? (fun d => d.name == name) + if decl.kind == ContractKind.library then none else some () + let fns := decl.items.filterMap (fun item => + match item with + | ContractItem.function fn => + if fn.name == some method then some fn else none + | _ => none) + match fns with + | [fn] => + match fn.returns with + | [ret] => some ret.ty + | _ => none + | _ => none + | _ => none + +/-- The name the attached call on an external call's result binds its + receiver to while it resolves: not a Solidity identifier, so no local + shadows it. -/ +def usingReceiverName : Name := "using receiver" + +/-- `rewritten` with its receiver argument, `Expr.ident usingReceiverName`, + replaced by `receiver`: the two shapes the attached-call rewrite builds + (`f(self, args)` and that call under its return conversion). -/ +def Expr.replaceUsingReceiver? (receiver : Expr) : Expr -> Option Expr + | Expr.call (Expr.ident helper) (Arg.positional (Expr.ident x) :: rest) => + if x == usingReceiverName then + some (Expr.call (Expr.ident helper) (Arg.positional receiver :: rest)) + else none + | Expr.call (Expr.typeName ty) + [Arg.positional + (Expr.call (Expr.ident helper) (Arg.positional (Expr.ident x) :: rest))] => + if x == usingReceiverName then + some (Expr.call (Expr.typeName ty) + [Arg.positional + (Expr.call (Expr.ident helper) (Arg.positional receiver :: rest))]) + else none + | _ => none + +/-- `UsingDecls.rewriteCall?` for a receiver that is an external call: it + resolves the attached call on a fresh name of the call's return type, then + puts the call back in the receiver's place. -/ +def UsingDecls.rewriteCallOnExternalResult? (contracts : List ContractDecl) + (freeFunctions : List FunctionDecl) + (env : TypeEnv) (receiver : Expr) (method : Name) + (args : List Arg) (usingDecls : List UsingDecl) : Option Expr := do + let ty ← Expr.externalCallReturnTy? contracts receiver + let rewritten ← + UsingDecls.rewriteCall? contracts freeFunctions + ((usingReceiverName, ty) :: env) (Expr.ident usingReceiverName) method + args usingDecls + Expr.replaceUsingReceiver? receiver rewritten + def UsingDecls.rewriteBinaryOperator? (freeFunctions : List FunctionDecl) (env : TypeEnv) (op : BinaryOp) (lhs rhs : Expr) : List UsingDecl -> Option Expr @@ -11192,7 +11294,12 @@ def Expr.expandUsingFuel : contracts freeFunctions env receiver' method args' usingDecls with | some rewritten => rewritten - | none => Expr.call (Expr.member receiver' method) args' + | none => + match UsingDecls.rewriteCallOnExternalResult? + contracts freeFunctions env receiver' method args' + usingDecls with + | some rewritten => rewritten + | none => Expr.call (Expr.member receiver' method) args' | Expr.call fn args => Expr.call (expand fn) (args.map expandArg) | Expr.callWithOptions (Expr.member receiver method) options args => @@ -11485,6 +11592,8 @@ def Stmt.expandUsingInSeqFuel : | Stmt.continue => (Stmt.continue, env) | Stmt.unchecked body => (Stmt.unchecked (expandStmt body), env) | Stmt.inlineAssembly code => (Stmt.inlineAssembly code, env) + | Stmt.assemblyCreate2 t v c s => + (Stmt.assemblyCreate2 (expandExpr t) (expandExpr v) (expandExpr c) (expandExpr s), env) | Stmt.modifierPlaceholder => (Stmt.modifierPlaceholder, env) def Stmt.expandUsing (contracts : List ContractDecl) @@ -11777,6 +11886,9 @@ def Stmt.rewriteLibraryInternalCallsFuel (libraryName : Name) (Stmt.rewriteLibraryInternalCallsFuel libraryName libraryFunctions env fuel body) | _ + 1, Stmt.inlineAssembly code => Stmt.inlineAssembly code + | fuel + 1, Stmt.assemblyCreate2 t v c s => + let go := Expr.rewriteLibraryInternalCallsFuel libraryName libraryFunctions env fuel + Stmt.assemblyCreate2 (go t) (go v) (go c) (go s) | _ + 1, Stmt.modifierPlaceholder => Stmt.modifierPlaceholder termination_by fuel _ => fuel diff --git a/SolidCore/Solidity/Interpreter.lean b/SolidCore/Solidity/Interpreter.lean index 7cbefcf2..90710f99 100644 --- a/SolidCore/Solidity/Interpreter.lean +++ b/SolidCore/Solidity/Interpreter.lean @@ -2327,7 +2327,7 @@ def evmLogEntryToShared (e : EvmYul.LogEntry) : data := byteArrayToBytes e.data } def addressSetOfWords (words : List Word) : - Batteries.RBSet EvmCompiler.Simulation.OpenAddress compare := + RBTree.RBSet EvmCompiler.Simulation.OpenAddress compare := words.foldl (fun acc w => acc.insert (wordToAddress w)) default /-- Canonical log series: the adopted prefix (whatever the last answered @@ -2820,6 +2820,28 @@ def emitContractCreation (context : Context) (state : State) ( decodeCreateResponse response name args value salt? , adoptWorld response.postWorld context state ))) +/-- Emit inline assembly's CREATE2 of the init code `code` as a `Query.external` creation + of the sent world, and resume on its `CreateResponse`: the new account's address (0 when + the creation failed, the EVM convention) and the adopted world. The request's init code is + `code` itself, so an environment that runs it (EIP-1014's address of the creator, salt and + `keccak256(code)`, the init code's execution as a callee) answers what the EVM does. -/ +def create2BytesRequest (context : Context) (code : List Byte) (value salt : Word) : + EvmCompiler.Simulation.CreateRequest := + { kind := EvmCompiler.Simulation.CreateKind.create2 + creator := wordToAddress context.self + value := wordToU256 value + initCode := bytesToByteArray code + salt := some (wordToU256 salt) + permission := true } + +def emitCreate2Bytes (context : Context) (state : State) (code : List Byte) + (value salt : Word) : SolI (Word × State) := + .request + (EvmCompiler.Simulation.Query.external (snapshotWorld context state) + (EvmCompiler.Simulation.ExternalRequest.create (create2BytesRequest context code value salt))) + (fun response => + .done (.ok (u256ToWord response.address, adoptWorld response.postWorld context state))) + /-- The stage-3 context answerer: external queries get `Query.defaultAnswer` (the context no longer carries oracle rows; see `SolI.runFromContext`), and the reserved `resource .gas` arm (A3) is answered ambiently with the context's @@ -6405,6 +6427,11 @@ inductive Expr where -- `Bool` records whether the `{value, salt}` options were written value-before- -- salt in source (solc evaluates the options in source order — DIV-CREATE-2). | contractCreate : String -> Expr -> Expr -> Option Expr -> Bool -> Expr + /-- `create2Bytes value code salt`: EVM CREATE2 with the bytes of `code` as init code, + endowed with `value` and salted with `salt` (inline assembly + `create2(value, add(code, 32), mload(code), salt)`): the new account's address, or 0 when + the creation fails. It never reverts the caller, unlike `contractCreate`. -/ + | create2Bytes : Expr -> Expr -> Expr -> Expr | newBytes : Expr -> Expr | newDynamicArray : Ty -> Expr -> Expr | externalHash : ExternalHashKind -> Expr -> Expr @@ -7331,6 +7358,8 @@ def Expr.orderFuel : Expr -> Nat (match salt? with | some salt => Expr.orderFuel salt | none => 0) + 1 + | Expr.create2Bytes value code salt => + Expr.orderFuel value + Expr.orderFuel code + Expr.orderFuel salt + 1 | Expr.newBytes expr => Expr.orderFuel expr + 1 | Expr.newDynamicArray _ expr => Expr.orderFuel expr + 1 | Expr.externalHash _ expr => Expr.orderFuel expr + 1 @@ -7654,9 +7683,12 @@ def Expr.evalFuel (fuel : Nat) let value ← BinaryOp.apply context.checked op lhsValue rhsValue pure (value, runtime'') | Expr.addMod lhs rhs modulus => do - -- Legacy codegen evaluates builtin arguments right-to-left. + -- Legacy codegen evaluates builtin arguments right-to-left and + -- checks the modulus for zero before evaluating the operands + -- (solc ExpressionCompiler.cpp, Kind::AddMod/MulMod). let (modulusValue, runtime') ← Expr.evalFuel fuel context runtime modulus + let _ ← checkedAddMod 0 0 (← modulusValue.expectWord) let (rhsValue, runtime'') ← Expr.evalFuel fuel context runtime' rhs let (lhsValue, runtime''') ← @@ -7669,6 +7701,7 @@ def Expr.evalFuel (fuel : Nat) | Expr.mulMod lhs rhs modulus => do let (modulusValue, runtime') ← Expr.evalFuel fuel context runtime modulus + let _ ← checkedMulMod 0 0 (← modulusValue.expectWord) let (rhsValue, runtime'') ← Expr.evalFuel fuel context runtime' rhs let (lhsValue, runtime''') ← @@ -7978,6 +8011,26 @@ def Expr.evalFuel (fuel : Nat) (ExternalInteraction.contractCreation result) ) else throw <| SolidityFailure.revert (RevertData.fromRawBytes result.output) + | Expr.create2Bytes valueExpr codeExpr saltExpr => do + -- Yul evaluates a builtin's arguments right to left: the salt, then the init + -- code (`mload(code)` before `add(code, 32)`), then the value. Each operand is + -- a literal or a local, so the order has no effect beyond the runtime threading. + let (saltValue, runtimeSalt) ← + Expr.evalFuel fuel context runtime saltExpr + let salt ← saltValue.expectWord + let (codeValue, runtimeCode) ← + Expr.evalFuel fuel context runtimeSalt codeExpr + let codeValue ← SolI.ofExcept (runtimeCode.derefMemoryValue codeValue) + let code ← + match codeValue.asBytes? with + | some bytes => pure bytes + | none => throw <| SolidityFailure.revert RevertData.typeMismatch + let (valueValue, runtime') ← + Expr.evalFuel fuel context runtimeCode valueExpr + let value ← valueValue.expectWord + let (address, adoptedState) ← + emitCreate2Bytes context runtime'.state code value salt + pure (Value.word address, { runtime' with state := adoptedState }) | Expr.newBytes lengthExpr => do let (lengthValue, runtime') ← Expr.evalFuel fuel context runtime @@ -9027,6 +9080,12 @@ def Expr.normalizeStorageValueUses (pos : StoragePosition) : Expr -> Expr (Expr.normalizeStorageValueUses StoragePosition.pointerUse value) (Expr.normalizeStorageValueUsesOpt StoragePosition.pointerUse salt?) valueBeforeSalt + | Expr.create2Bytes value code salt => + -- The init code is consumed as bytes contents; value and salt are scalar words. + Expr.create2Bytes + (Expr.normalizeStorageValueUses StoragePosition.pointerUse value) + (Expr.normalizeStorageValueUses StoragePosition.valueUse code) + (Expr.normalizeStorageValueUses StoragePosition.pointerUse salt) | Expr.newBytes expr => -- The length operand is a scalar word; value-use per the boundary -- family it belongs to (inert for scalars). diff --git a/SolidCore/Solidity/Staged.lean b/SolidCore/Solidity/Staged.lean new file mode 100644 index 00000000..c8845b0d --- /dev/null +++ b/SolidCore/Solidity/Staged.lean @@ -0,0 +1,75 @@ +import SolidCore.Solidity.Checked + +/-! +# A contract's translation from its stages + +`CheckedInput.contract_ok_of_stages`: a source unit's contract type checks and translates when the +type check returns the source, the type resolution of the checked program finds the contract, +and the raw declaration's translation by its storage and dispatch orders succeeds. Each premise is +a closed computation a contract's module checks in a declaration of its own, the last one through +the stages of `ContractDecl.toCoreFromOrders?` (its context, function groups and assembly), so +that no single kernel check holds the whole translation. +-/ + +namespace SolidCore.Solidity.TypeCheck + +/-- A source unit's contract type checks and translates by its stages. -/ +theorem CheckedInput.contract_ok_of_stages (src : SourceUnitAst) (name : Name) + (rd : SourceContractDecl) (so dO : List SourceContractDecl) + (hck : TypecheckedInput.checkedSourceUnit src = .ok { source := src }) + (hf : (match (CheckedProgram.fromChecked? { source := src }).bind + (fun p => CheckedProgram.findSourceContract? p name) with + | some d => d.name == name + | none => false) = true) + (hraw : Executable.SourceUnit.findContract? src name = some rd) + (hso : Executable.ContractDecl.storageOrder? (Executable.SourceUnit.contracts src) rd = some so) + (hdo : Executable.ContractDecl.dispatchOrder? (Executable.SourceUnit.contracts src) rd = some dO) + (hcore : ∃ core, Executable.ContractDecl.toCoreFromOrders? (Executable.SourceUnit.contracts src) + (Executable.SourceUnit.usingDecls src) (Executable.SourceUnit.freeFunctions src) + (Executable.SourceUnit.freeEvents src) (Executable.SourceUnit.freeErrors src) + (Executable.SourceUnit.freeConstants src) (Executable.SourceUnit.freeUserValueTypes src) + (Executable.SourceUnit.freeEnums src) (Executable.SourceUnit.freeStructs src) so dO = some core) : + ∃ c, CheckedInput.contract src name = .ok c := by + obtain ⟨core, hcore⟩ := hcore + cases hp : CheckedProgram.fromChecked? { source := src } with + | none => rw [hp] at hf; cases hf + | some p => + rw [hp] at hf + cases hd : CheckedProgram.findSourceContract? p name with + | none => simp only [Option.bind, hd] at hf; cases hf + | some d => + simp only [Option.bind, hd, beq_iff_eq] at hf + have hpc : p.checked = { source := src } := by + unfold CheckedProgram.fromChecked? at hp + revert hp + cases Executable.SourceUnit.resolveSourceTypesContextual? src with + | none => intro hp; cases hp + | some s => intro hp; cases hp; rfl + have hcontract : CheckedProgram.contract? p name = some { program := p, decl := d, core := core } := by + unfold CheckedProgram.contract? CheckedProgram.toCoreContractFor? + simp only [bind, Option.bind, hd, CheckedProgram.findRawSourceContract?, CheckedProgram.rawSource, + CheckedProgram.rawUsingDecls, CheckedProgram.rawFreeFunctions, CheckedProgram.rawFreeEvents, + CheckedProgram.rawFreeErrors, CheckedProgram.rawFreeConstants, CheckedProgram.rawFreeUserValueTypes, + CheckedProgram.rawFreeEnums, CheckedProgram.rawFreeStructs, CheckedProgram.rawContracts, hpc, hf, hraw] + unfold Executable.ContractDecl.toCoreWithBasesAndUsing? + simp only [bind, Option.bind, hso, hdo, hcore] + refine ⟨{ program := p, decl := d, core := core }, ?_⟩ + show (do + let p ← (do + let checked ← TypecheckedInput.checkedSourceUnit src + CheckedProgram.fromChecked checked) + CheckedProgram.contract p name) = _ + rw [hck] + show (do let p ← CheckedProgram.fromChecked { source := src }; CheckedProgram.contract p name) = _ + unfold CheckedProgram.fromChecked + rw [hp] + show CheckedProgram.contract p name = _ + unfold CheckedProgram.contract + rw [hcontract] + rfl + +/-- info: 'SolidCore.Solidity.TypeCheck.CheckedInput.contract_ok_of_stages' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms CheckedInput.contract_ok_of_stages + +end SolidCore.Solidity.TypeCheck diff --git a/SolidCore/Solidity/StagedK.lean b/SolidCore/Solidity/StagedK.lean new file mode 100644 index 00000000..eec5070b --- /dev/null +++ b/SolidCore/Solidity/StagedK.lean @@ -0,0 +1,268 @@ +import SolidCore.Solidity.Staged + +/-! +# Staged translation checks: kernel-cheap equal forms and assembly lemmas + +Equal forms of functions the translation calls (`TypeEnv.shadowedStateNames_eq_K`, +`stringDecEq_eq_K`, `toByteArray_eq_K`) for `kernel_rfl … using`, and the lemmas that assemble a +contract's translation from its context, its function groups (each from its functions' +translations) and its assembly, each checked in a module of its own. +-/ + + +namespace SolidCore.Solidity.Executable + +/-! ### Kernel-cheap equal forms + +The kernel evaluates a string comparison by expanding both literals to their UTF-8 bytes and +comparing them byte by byte, so `TypeEnv.shadowedStateNames`, which compares every pair of a type +environment's names and runs at every statement the lowering visits, costs gigabytes under a +contract whose environment holds many long `__external_call_kind:` keys. `bytesKey` and +`nameKey` number a string by its bytes injectively, so the kernel compares two names as two +numbers; `TypeEnv.shadowedStateNames_eq_K` and `stringDecEq_eq_K` let `kernel_rfl … using` +evaluate the translation with these equal forms. -/ + +/-- A byte list as a number: its bytes are the base-257 digits 1..256. -/ +def bytesKey (l : List UInt8) : Nat := l.foldr (fun b acc => b.toNat + 1 + 257 * acc) 0 + +theorem bytesKey_inj : ∀ {l₁ l₂ : List UInt8}, bytesKey l₁ = bytesKey l₂ → l₁ = l₂ + | [], [], _ => rfl + | [], c :: cs, h => by simp [bytesKey] at h; omega + | b :: bs, [], h => by simp [bytesKey] at h + | b :: bs, c :: cs, h => by + have hb := UInt8.toNat_lt b + have hc := UInt8.toNat_lt c + simp only [bytesKey, List.foldr_cons] at h + have h1 : b.toNat = c.toNat := by omega + have h2 : bytesKey bs = bytesKey cs := by unfold bytesKey; omega + rw [bytesKey_inj h2, UInt8.toNat_inj.mp h1] + +/-- A string as a number: its UTF-8 bytes by `bytesKey`. -/ +def nameKey (s : String) : Nat := bytesKey s.toByteArray.data.toList + +theorem nameKey_inj {s₁ s₂ : String} (h : nameKey s₁ = nameKey s₂) : s₁ = s₂ := by + have h' := bytesKey_inj h + rcases s₁ with ⟨⟨⟨l₁⟩⟩, p₁⟩ + rcases s₂ with ⟨⟨⟨l₂⟩⟩, p₂⟩ + simp at h' + subst h' + rfl + +/-- `TypeEnv.shadowedStateNames`, comparing names by `nameKey`. -/ +def TypeEnv.shadowedStateNamesK (env : TypeEnv) : List Name := + let keyed := (env.map Prod.fst).map (fun n => (n, nameKey n)) + (keyed.filter (fun p => (keyed.filter (fun q => q.2 == p.2)).length ≥ 2)).map Prod.fst + +theorem TypeEnv.shadowedStateNames_eq_K : + TypeEnv.shadowedStateNames = TypeEnv.shadowedStateNamesK := by + funext env + have hk : ∀ m n : Name, (nameKey m == nameKey n) = (m == n) := by + intro m n + by_cases h : m = n + · subst h; simp + · have : nameKey m ≠ nameKey n := fun e => h (nameKey_inj e) + simp [h, this] + simp only [TypeEnv.shadowedStateNames, TypeEnv.shadowedStateNamesK, List.filter_map, + List.map_map, Function.comp_def, List.length_map, hk] + +/-- String equality decided by `nameKey`. -/ +def stringDecEqK (a b : String) : Decidable (a = b) := + if h : nameKey a = nameKey b then isTrue (nameKey_inj h) else isFalse (fun e => h (e ▸ rfl)) + +theorem stringDecEq_eq_K : String.decEq = stringDecEqK := by + funext a b; exact Subsingleton.elim _ _ + +/-! ### Assembling the staged checks -/ + +-- The unused-variables linter takes gigabytes on this many hypotheses. +set_option linter.unusedVariables false in +/-- A context the translation computes, from its fields one by one. -/ +theorem FromOrdersCtx.some_eq_of_fields {o : Option FromOrdersCtx} {c : FromOrdersCtx} + (h0 : Option.map FromOrdersCtx.allContracts o = some c.allContracts) + (h1 : Option.map FromOrdersCtx.sourceUsingDecls o = some c.sourceUsingDecls) + (h2 : Option.map FromOrdersCtx.sourceFunctions o = some c.sourceFunctions) + (h3 : Option.map FromOrdersCtx.dispatchOrder o = some c.dispatchOrder) + (h4 : Option.map FromOrdersCtx.structEnv o = some c.structEnv) + (h5 : Option.map FromOrdersCtx.stateVars o = some c.stateVars) + (h6 : Option.map FromOrdersCtx.constants o = some c.constants) + (h7 : Option.map FromOrdersCtx.storageStateVars o = some c.storageStateVars) + (h8 : Option.map FromOrdersCtx.transientStateVars o = some c.transientStateVars) + (h9 : Option.map FromOrdersCtx.storageNames o = some c.storageNames) + (h10 : Option.map FromOrdersCtx.layoutBaseSlot o = some c.layoutBaseSlot) + (h11 : Option.map FromOrdersCtx.externalCallKindEnv o = some c.externalCallKindEnv) + (h12 : Option.map FromOrdersCtx.externalCallKindTypeEnv o = some c.externalCallKindTypeEnv) + (h13 : Option.map FromOrdersCtx.stateEnv o = some c.stateEnv) + (h14 : Option.map FromOrdersCtx.sharedConstantTail o = some c.sharedConstantTail) + (h15 : Option.map FromOrdersCtx.modifiers o = some c.modifiers) + (h16 : Option.map FromOrdersCtx.libraryHelpers o = some c.libraryHelpers) + (h17 : Option.map FromOrdersCtx.baseHelpers o = some c.baseHelpers) + (h18 : Option.map FromOrdersCtx.superHelpers o = some c.superHelpers) + (h19 : Option.map FromOrdersCtx.availableFunctions o = some c.availableFunctions) + (h20 : Option.map FromOrdersCtx.internalFnIds o = some c.internalFnIds) + (h21 : Option.map FromOrdersCtx.contractEvents o = some c.contractEvents) + (h22 : Option.map FromOrdersCtx.visibleSourceEvents o = some c.visibleSourceEvents) + (h23 : Option.map FromOrdersCtx.contractErrors o = some c.contractErrors) + (h24 : Option.map FromOrdersCtx.visibleSourceErrors o = some c.visibleSourceErrors) + (h25 : Option.map FromOrdersCtx.eventArgEnv o = some c.eventArgEnv) + (h26 : Option.map FromOrdersCtx.eventIndexedEnv o = some c.eventIndexedEnv) + (h27 : Option.map FromOrdersCtx.errorArgEnv o = some c.errorArgEnv) : + o = some c := by + cases o with + | none => exact absurd h0 (by simp) + | some x => + have e0 : x.allContracts = c.allContracts := Option.some.inj h0 + have e1 : x.sourceUsingDecls = c.sourceUsingDecls := Option.some.inj h1 + have e2 : x.sourceFunctions = c.sourceFunctions := Option.some.inj h2 + have e3 : x.dispatchOrder = c.dispatchOrder := Option.some.inj h3 + have e4 : x.structEnv = c.structEnv := Option.some.inj h4 + have e5 : x.stateVars = c.stateVars := Option.some.inj h5 + have e6 : x.constants = c.constants := Option.some.inj h6 + have e7 : x.storageStateVars = c.storageStateVars := Option.some.inj h7 + have e8 : x.transientStateVars = c.transientStateVars := Option.some.inj h8 + have e9 : x.storageNames = c.storageNames := Option.some.inj h9 + have e10 : x.layoutBaseSlot = c.layoutBaseSlot := Option.some.inj h10 + have e11 : x.externalCallKindEnv = c.externalCallKindEnv := Option.some.inj h11 + have e12 : x.externalCallKindTypeEnv = c.externalCallKindTypeEnv := Option.some.inj h12 + have e13 : x.stateEnv = c.stateEnv := Option.some.inj h13 + have e14 : x.sharedConstantTail = c.sharedConstantTail := Option.some.inj h14 + have e15 : x.modifiers = c.modifiers := Option.some.inj h15 + have e16 : x.libraryHelpers = c.libraryHelpers := Option.some.inj h16 + have e17 : x.baseHelpers = c.baseHelpers := Option.some.inj h17 + have e18 : x.superHelpers = c.superHelpers := Option.some.inj h18 + have e19 : x.availableFunctions = c.availableFunctions := Option.some.inj h19 + have e20 : x.internalFnIds = c.internalFnIds := Option.some.inj h20 + have e21 : x.contractEvents = c.contractEvents := Option.some.inj h21 + have e22 : x.visibleSourceEvents = c.visibleSourceEvents := Option.some.inj h22 + have e23 : x.contractErrors = c.contractErrors := Option.some.inj h23 + have e24 : x.visibleSourceErrors = c.visibleSourceErrors := Option.some.inj h24 + have e25 : x.eventArgEnv = c.eventArgEnv := Option.some.inj h25 + have e26 : x.eventIndexedEnv = c.eventIndexedEnv := Option.some.inj h26 + have e27 : x.errorArgEnv = c.errorArgEnv := Option.some.inj h27 + have hx : x = ⟨x.allContracts, x.sourceUsingDecls, x.sourceFunctions, x.dispatchOrder, x.structEnv, x.stateVars, x.constants, x.storageStateVars, x.transientStateVars, x.storageNames, x.layoutBaseSlot, x.externalCallKindEnv, x.externalCallKindTypeEnv, x.stateEnv, x.sharedConstantTail, x.modifiers, x.libraryHelpers, x.baseHelpers, x.superHelpers, x.availableFunctions, x.internalFnIds, x.contractEvents, x.visibleSourceEvents, x.contractErrors, x.visibleSourceErrors, x.eventArgEnv, x.eventIndexedEnv, x.errorArgEnv⟩ := rfl + have hc : c = ⟨c.allContracts, c.sourceUsingDecls, c.sourceFunctions, c.dispatchOrder, c.structEnv, c.stateVars, c.constants, c.storageStateVars, c.transientStateVars, c.storageNames, c.layoutBaseSlot, c.externalCallKindEnv, c.externalCallKindTypeEnv, c.stateEnv, c.sharedConstantTail, c.modifiers, c.libraryHelpers, c.baseHelpers, c.superHelpers, c.availableFunctions, c.internalFnIds, c.contractEvents, c.visibleSourceEvents, c.contractErrors, c.visibleSourceErrors, c.eventArgEnv, c.eventIndexedEnv, c.errorArgEnv⟩ := rfl + rw [hx, hc, e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27] + +/-- The contract translation from its context, function groups and assembly. -/ +theorem ContractDecl.toCoreFromOrders?_of_stages {allContracts : List ContractDecl} + {sourceUsingDecls : List UsingDecl} {sourceFunctions : List FunctionDecl} + {sourceEvents : List EventDecl} {sourceErrors : List ErrorDecl} + {sourceConstants : List StateVarDecl} {sourceUserValueTypes : List UserValueTypeDecl} + {sourceEnums : List EnumDecl} {sourceStructs : List StructDecl} + {storageOrder dispatchOrder : List ContractDecl} {c : FromOrdersCtx} + {groups : List (List CoreFunctionDef)} {core : CoreContract} + (hc : ContractDecl.fromOrdersCtx? allContracts sourceUsingDecls sourceFunctions sourceEvents + sourceErrors sourceConstants sourceUserValueTypes sourceEnums sourceStructs storageOrder + dispatchOrder = some c) + (hg : mapOption c.group? c.dispatchOrder = some groups) + (ha : c.assemble? groups = some core) : + ContractDecl.toCoreFromOrders? allContracts sourceUsingDecls sourceFunctions sourceEvents + sourceErrors sourceConstants sourceUserValueTypes sourceEnums sourceStructs storageOrder + dispatchOrder = some core := by + unfold ContractDecl.toCoreFromOrders? + rw [hc] + show (mapOption c.group? c.dispatchOrder).bind c.assemble? = some core + rw [hg] + exact ha + +/-- info: 'SolidCore.Solidity.Executable.TypeEnv.shadowedStateNames_eq_K' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms TypeEnv.shadowedStateNames_eq_K + +/-- info: 'SolidCore.Solidity.Executable.stringDecEq_eq_K' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms stringDecEq_eq_K + +/-- info: 'SolidCore.Solidity.Executable.FromOrdersCtx.some_eq_of_fields' depends on axioms: [propext] -/ +#guard_msgs (whitespace := lax) in +#print axioms FromOrdersCtx.some_eq_of_fields + +/-- info: 'SolidCore.Solidity.Executable.ContractDecl.toCoreFromOrders?_of_stages' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms ContractDecl.toCoreFromOrders?_of_stages + +end SolidCore.Solidity.Executable + +namespace SolidCore.Solidity.Executable + +/-! ### A function group from its functions -/ + +/-- The functions of a contract that `ContractDecl.directCoreFunctions?` translates. -/ +def FromOrdersCtx.fnsOf (decl : ContractDecl) : List FunctionDecl := + (ContractDecl.directOrdinaryFunctions decl).filter + (fun fn => (FunctionDecl.isCoreEntrypoint fn || FunctionDecl.isBoundaryCallee fn) && fn.body.isSome) + +/-- The translation of one function of a contract in the context, as `FromOrdersCtx.group?` does. -/ +def FromOrdersCtx.pairF (c : FromOrdersCtx) (decl : ContractDecl) (fn : FunctionDecl) : + Option (FunctionDecl × CoreFunctionDef) := + ContractDecl.directCoreFunctionPair? c.storageNames + (ContractDecl.scopedConstantEnv c.dispatchOrder c.sharedConstantTail decl) + c.stateEnv c.externalCallKindEnv c.allContracts c.dispatchOrder + (ContractDecl.directUsingDecls decl ++ c.sourceUsingDecls) c.modifiers c.availableFunctions + c.sourceFunctions c.eventArgEnv c.errorArgEnv c.internalFnIds c.eventIndexedEnv + (c.contractEvents ++ c.visibleSourceEvents) decl fn + +/-- The public state variables' getters of a contract in the context. -/ +def FromOrdersCtx.getters? (c : FromOrdersCtx) (decl : ContractDecl) : Option (List CoreFunctionDef) := + filterMapOption + (StateVarDecl.toCoreGetterIfPublic? c.storageNames + (ContractDecl.scopedConstantEnv c.dispatchOrder c.sharedConstantTail decl)) + (ContractDecl.directStateVars decl) + +/-- A function group from its getters and its functions' translations. -/ +def groupOfPairs (getters : List CoreFunctionDef) (pairs : List (FunctionDecl × CoreFunctionDef)) : + List CoreFunctionDef := + getters ++ (pairs.filter (fun pair => FunctionDecl.isCoreEntrypoint pair.fst)).map Prod.snd ++ + pairs.filterMap (fun pair => + if FunctionDecl.isBoundaryCallee pair.fst then + (FunctionDecl.internalTableKey? pair.fst).map + (fun key => { pair.snd with name := key, selector? := none }) + else none) + +/-- `FromOrdersCtx.group?` is its getters and its functions' translations, one by one. -/ +theorem FromOrdersCtx.group?_of_pairs {c : FromOrdersCtx} {decl : ContractDecl} + {getters : List CoreFunctionDef} {pairs : List (FunctionDecl × CoreFunctionDef)} + (hg : c.getters? decl = some getters) + (hp : mapOption (c.pairF decl) (FromOrdersCtx.fnsOf decl) = some pairs) : + c.group? decl = some (groupOfPairs getters pairs) := by + have e : c.group? decl = (c.getters? decl).bind (fun g => + (mapOption (c.pairF decl) (FromOrdersCtx.fnsOf decl)).bind + (fun ps => some (groupOfPairs g ps))) := rfl + rw [e, hg, hp] + rfl + +theorem mapOption_nil' {α β : Type} (f : α → Option β) : mapOption f [] = some [] := rfl + +theorem mapOption_cons' {α β : Type} {f : α → Option β} {x : α} {xs : List α} {y : β} {ys : List β} + (h : f x = some y) (hs : mapOption f xs = some ys) : mapOption f (x :: xs) = some (y :: ys) := by + simp only [mapOption, h, hs, bind, Option.bind] + +/-- info: 'SolidCore.Solidity.Executable.FromOrdersCtx.group?_of_pairs' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms FromOrdersCtx.group?_of_pairs + +end SolidCore.Solidity.Executable + +namespace SolidCore.Solidity.Executable + +/-- `List.toByteArray` as one constructor application, without its pushes: the kernel builds a +string literal's bytes through `List.toByteArray`, whose pushes copy the list once per byte. -/ +def toByteArrayK (bs : List UInt8) : ByteArray := ⟨⟨bs⟩⟩ + +theorem toByteArray_loop : ∀ (bs : List UInt8) (r : ByteArray), + List.toByteArray.loop bs r = ⟨⟨r.data.toList ++ bs⟩⟩ + | [], ⟨⟨l⟩⟩ => by simp [List.toByteArray.loop] + | b :: bs, r => by + rw [List.toByteArray.loop, toByteArray_loop bs] + cases r with + | mk a => cases a with + | mk l => simp [ByteArray.push, Array.push] + +theorem toByteArray_eq_K : List.toByteArray = toByteArrayK := by + funext bs + simp [List.toByteArray, toByteArray_loop, toByteArrayK, ByteArray.empty, ByteArray.emptyWithCapacity] <;> rfl + +/-- info: 'SolidCore.Solidity.Executable.toByteArray_eq_K' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms toByteArray_eq_K + +end SolidCore.Solidity.Executable diff --git a/SolidCore/Solidity/StagedL.lean b/SolidCore/Solidity/StagedL.lean new file mode 100644 index 00000000..e4164bce --- /dev/null +++ b/SolidCore/Solidity/StagedL.lean @@ -0,0 +1,323 @@ +import SolidCore.Solidity.StagedK + +/-! +# The translation of one function in stages + +`FunctionDecl.toCore?` lowers a function's body after a run of cheap passes; for the largest +functions the kernel cannot evaluate it in one declaration within 6 GB. This module splits it +into the passes before the lowering (`FunctionDecl.toCorePre?`), the ANF preprocessing and the +lowering of the body, and the rest (`FunctionDecl.toCoreRest?`), and proves the composition +equal to `FunctionDecl.toCore?` (`FunctionDecl.toCore_eq_staged`) and, for a contract's context, +to `FromOrdersCtx.pairF` (`FromOrdersCtx.pairF_of_stages`), so each stage is checked in a module of +its own. +-/ + +namespace SolidCore.Solidity.Executable + +/-- What `FunctionDecl.toCore?` computes before it lowers the body. -/ +structure ToCorePre where + decl : FunctionDecl + name : Name + params : List SolidCore.Solidity.Source.BindingDecl + paramAbiCleanups : List SolidCore.Solidity.Source.AbiCleanup + returns : List SolidCore.Solidity.Source.BindingDecl + body : Stmt + env : TypeEnv + storageRefEnv : StorageRefEnv + modifiers : List SourceModifierDecl + modifierInvocations : List SourceModifierInvocation + functions : List FunctionDecl + bodyStorageNames : List Name + deriving Repr + +/-- `FunctionDecl.toCore?` up to the lowering of the body. -/ +def FunctionDecl.toCorePre? (storageNames : List Name) (constants : ConstantEnv) + (extraEnv : TypeEnv) + (contracts : List ContractDecl) (usingDecls : List UsingDecl) + (modifiers : List SourceModifierDecl) (functions : List FunctionDecl) + (freeFunctions : List FunctionDecl) + (decl : FunctionDecl) (superFunctions : List FunctionDecl := []) + (contractName? : Option Name := none) + (baseNames : List Name := []) + (externalCallKindEnv : ExternalCallKindEnv := []) + (eventArgEnv : NamedArgParamEnv := []) + (errorArgEnv : NamedArgParamEnv := []) + (internalFnIds : List (Name × Nat) := []) + (structEnv : StructEnv := []) + (eventIndexedEnv : EventIndexedEnv := []) + (overloadEvents : List EventDecl := []) : + Option ToCorePre := do + let decl := FunctionDecl.inlineConstants constants decl + let selectorEnv := + FunctionDecls.selectorEntries (decl :: functions ++ freeFunctions) + let decl := FunctionDecl.resolveFunctionAddresses selectorEnv decl + let decl := FunctionDecl.resolveSelectors selectorEnv decl + let name ← FunctionDecl.coreName? decl + let params ← Parameters.toCoreBindings? "_arg" decl.params + let paramAbiCleanups ← + mapOption + (fun (param : Parameter) => + if param.location == some DataLocation.storage then + some SolidCore.Solidity.Source.AbiCleanup.none + else do + let cleanup ← Ty.toCoreAbiCleanup? param.ty + if param.location == some DataLocation.memory then + some (SolidCore.Solidity.Source.AbiCleanup.memoryEager cleanup) + else + some cleanup) + decl.params + let returns ← Parameters.toCoreBindings? "_ret" decl.returns + let body ← decl.body + let body := Stmt.dropStrayLibraryFunctionValues contracts body + let modifiers := + modifiers.map (fun modifier => + { modifier with + body := modifier.body.map + (Stmt.dropStrayLibraryFunctionValues contracts) }) + let env := FunctionDecl.typeEnv + (TypeEnv.extendThis extraEnv contractName?) decl + let usingFunctionScope := functions ++ freeFunctions + let body := + if usingDecls.isEmpty && !ContractDecls.hasLibrary contracts then + body + else + Stmt.expandUsing contracts usingFunctionScope usingDecls env body + let modifiers := + if usingDecls.isEmpty && !ContractDecls.hasLibrary contracts then + modifiers + else + modifiers.map + (ModifierDecl.expandUsing contracts usingFunctionScope usingDecls env) + let modifierInvocations := + if usingDecls.isEmpty && !ContractDecls.hasLibrary contracts then + decl.modifiers + else + decl.modifiers.map + (ModifierInvocation.expandUsing + contracts usingFunctionScope usingDecls env) + let body := + match contractName? with + | some contractName => Stmt.rewriteSuperCalls contractName body + | none => body + let body := Stmt.rewriteBaseCalls baseNames storageNames body + let body := Stmt.resolveNamedEventErrorArgs eventArgEnv errorArgEnv body + let modifiers := + modifiers.map + (fun modifier => + { modifier with + body := modifier.body.map + (Stmt.resolveNamedEventErrorArgs eventArgEnv errorArgEnv) }) + let body := Stmt.resolveOverloadedEventEmits overloadEvents env body + let modifiers := + modifiers.map + (fun modifier => + { modifier with + body := modifier.body.map + (Stmt.resolveOverloadedEventEmits overloadEvents + (Parameters.extendTypeEnv "_mod" env modifier.params)) }) + let body := Stmt.inlineInternalFunctionAliasesInBody functions freeFunctions body + let body := Stmt.distributeTernaryCallCallee body + let body := + Stmt.rewriteInternalFnValueIdents internalFnIds + (FunctionDecl.fnValueScopeBoundNames decl) body + let modifiers := + modifiers.map + (fun modifier => + { modifier with + body := + modifier.body.map + (Stmt.rewriteInternalFnValueIdents internalFnIds + (Parameters.boundNames modifier.params)) }) + let body := Stmt.rewriteStorageReturnAssignments "_ret" decl.returns body + let body := Stmt.annotateAbi env body + let storageRefEnv := + Parameters.extendStorageRefEnv "_ret" + (Parameters.extendStorageRefEnv "_arg" [] decl.params) decl.returns + let functions := + match contractName? with + | some contractName => + functions ++ FunctionDecl.superHelpers contractName superFunctions + | none => functions + let bodyStorageNames := + stateNamesExcludingBound (FunctionDecl.fnValueScopeBoundNames decl) + storageNames + pure (ToCorePre.mk decl name params paramAbiCleanups returns body env storageRefEnv modifiers + modifierInvocations functions bodyStorageNames) + +/-- `functionExpandModifiersToCoreWithInternalCallsFull?` given the lowering of the body. -/ +def expandWith? (internalFuel : Nat) (storageRefEnv : StorageRefEnv) (env : TypeEnv) + (externalCallKindEnv : ExternalCallKindEnv) (storageNames returnNames : List Name) + (available : List SourceModifierDecl) (functions freeFunctions : List FunctionDecl) + (returnTys : List Ty) (inner : Option CoreStmt) (structEnv : StructEnv) + (eventIndexedEnv : EventIndexedEnv) : List SourceModifierInvocation → Option CoreStmt + | [] => inner + | invocation :: rest => do + let inner ← expandWith? internalFuel storageRefEnv env externalCallKindEnv storageNames + returnNames available functions freeFunctions returnTys inner structEnv eventIndexedEnv rest + let modifierDecl ← modifierResolve? available invocation.target + modifierApplyToCoreWithInternalCalls? internalFuel storageRefEnv env + externalCallKindEnv storageNames returnNames available functions + freeFunctions returnTys modifierDecl invocation inner + (structEnv := structEnv) (eventIndexedEnv := eventIndexedEnv) + +theorem expand_eq (internalFuel : Nat) (storageRefEnv : StorageRefEnv) (env : TypeEnv) + (externalCallKindEnv : ExternalCallKindEnv) (storageNames bodyStorageNames returnNames : List Name) + (available : List SourceModifierDecl) (functions freeFunctions : List FunctionDecl) + (returnTys : List Ty) (body : Stmt) (structEnv : StructEnv) (eventIndexedEnv : EventIndexedEnv) : + ∀ invocations : List SourceModifierInvocation, + functionExpandModifiersToCoreWithInternalCallsFull? internalFuel storageRefEnv env + externalCallKindEnv storageNames bodyStorageNames returnNames available functions + freeFunctions returnTys invocations body (structEnv := structEnv) + (eventIndexedEnv := eventIndexedEnv) = + expandWith? internalFuel storageRefEnv env externalCallKindEnv storageNames returnNames + available functions freeFunctions returnTys + (Stmt.toCoreWithInternalCalls? internalFuel storageRefEnv env externalCallKindEnv + bodyStorageNames available functions freeFunctions returnTys + (Stmt.anfPreprocess structEnv internalFuel storageRefEnv env externalCallKindEnv + bodyStorageNames available functions freeFunctions returnTys eventIndexedEnv + defaultAnfPreprocessFuel body)) + structEnv eventIndexedEnv invocations + | [] => by rw [functionExpandModifiersToCoreWithInternalCallsFull?]; rfl + | invocation :: rest => by + rw [functionExpandModifiersToCoreWithInternalCallsFull?, expandWith?, + expand_eq internalFuel storageRefEnv env externalCallKindEnv storageNames bodyStorageNames + returnNames available functions freeFunctions returnTys body structEnv eventIndexedEnv rest] + +/-- The lowering of a function's body after its ANF preprocessing, as +`functionExpandModifiersToCoreWithInternalCallsFull?` does. -/ +def ToCorePre.anf (pre : ToCorePre) (externalCallKindEnv : ExternalCallKindEnv) + (freeFunctions : List FunctionDecl) (structEnv : StructEnv) (eventIndexedEnv : EventIndexedEnv) : + Stmt := + Stmt.anfPreprocess structEnv defaultInternalCallInlineFuel pre.storageRefEnv pre.env + externalCallKindEnv pre.bodyStorageNames pre.modifiers pre.functions freeFunctions + (pre.decl.returns.map Parameter.ty) eventIndexedEnv defaultAnfPreprocessFuel pre.body + +/-- The lowering of a function's preprocessed body. -/ +def ToCorePre.lower (pre : ToCorePre) (externalCallKindEnv : ExternalCallKindEnv) + (freeFunctions : List FunctionDecl) (body : Stmt) : Option CoreStmt := + Stmt.toCoreWithInternalCalls? defaultInternalCallInlineFuel pre.storageRefEnv pre.env + externalCallKindEnv pre.bodyStorageNames pre.modifiers pre.functions freeFunctions + (pre.decl.returns.map Parameter.ty) body + +/-- `FunctionDecl.toCore?` after the lowering of the body. -/ +def FunctionDecl.toCoreRest? (storageNames : List Name) (freeFunctions : List FunctionDecl) + (externalCallKindEnv : ExternalCallKindEnv) (structEnv : StructEnv) + (eventIndexedEnv : EventIndexedEnv) (pre : ToCorePre) (inner : Option CoreStmt) : + Option CoreFunctionDef := do + let decl := pre.decl + let name := pre.name + let params := pre.params + let paramAbiCleanups := pre.paramAbiCleanups + let returns := pre.returns + let bodyCore ← + expandWith? defaultInternalCallInlineFuel pre.storageRefEnv pre.env externalCallKindEnv + storageNames (returns.map SolidCore.Solidity.Source.BindingDecl.name) pre.modifiers + pre.functions freeFunctions (decl.returns.map Parameter.ty) inner structEnv eventIndexedEnv + pre.modifierInvocations + let paramCleanups ← Parameters.toCoreCleanupStmts? "_arg" decl.params + let returnMemoryLocalizes ← + Parameters.toCoreMemoryLocalizeStmts? "_ret" decl.returns + (localizeCalldata := + match decl.visibility with + | some Visibility.external_ => true + | some Visibility.public_ => true + | _ => false) + let bodyCore := + SolidCore.Solidity.Source.Stmt.block + (paramCleanups ++ returnMemoryLocalizes ++ [bodyCore]) + let bodyCore := + SolidCore.Solidity.Source.Stmt.normalizeStorageValueUses bodyCore + some + { name := name + selector? := FunctionDecl.abiSelector? decl + payable := FunctionDecl.isPayable decl + params := params + paramAbiCleanups := paramAbiCleanups + returns := returns + body := bodyCore } +theorem FunctionDecl.toCore_eq_staged (storageNames : List Name) (constants : ConstantEnv) + (extraEnv : TypeEnv) + (contracts : List ContractDecl) (usingDecls : List UsingDecl) + (modifiers : List SourceModifierDecl) (functions : List FunctionDecl) + (freeFunctions : List FunctionDecl) + (decl : FunctionDecl) (superFunctions : List FunctionDecl) + (contractName? : Option Name) + (baseNames : List Name) + (externalCallKindEnv : ExternalCallKindEnv) + (eventArgEnv : NamedArgParamEnv) + (errorArgEnv : NamedArgParamEnv) + (internalFnIds : List (Name × Nat)) + (structEnv : StructEnv) + (eventIndexedEnv : EventIndexedEnv) + (overloadEvents : List EventDecl) : + FunctionDecl.toCore? storageNames constants extraEnv contracts usingDecls modifiers functions + freeFunctions decl superFunctions contractName? baseNames externalCallKindEnv eventArgEnv + errorArgEnv internalFnIds structEnv eventIndexedEnv overloadEvents = + (FunctionDecl.toCorePre? storageNames constants extraEnv contracts usingDecls modifiers + functions freeFunctions decl superFunctions contractName? baseNames externalCallKindEnv + eventArgEnv errorArgEnv internalFnIds structEnv eventIndexedEnv overloadEvents) >>= + fun pre => FunctionDecl.toCoreRest? storageNames freeFunctions externalCallKindEnv structEnv + eventIndexedEnv pre + (pre.lower externalCallKindEnv freeFunctions + (pre.anf externalCallKindEnv freeFunctions structEnv eventIndexedEnv)) := by + simp only [FunctionDecl.toCore?, FunctionDecl.toCorePre?, FunctionDecl.toCoreRest?, + ToCorePre.lower, ToCorePre.anf, expand_eq, bind_assoc, pure_bind] + rfl + +/-- `FromOrdersCtx.pairF` up to the lowering of the function's body. -/ +def FromOrdersCtx.preF (c : FromOrdersCtx) (decl : ContractDecl) (fn : FunctionDecl) : + Option ToCorePre := do + let supers ← ContractDecls.afterName? c.dispatchOrder decl.name + FunctionDecl.toCorePre? c.storageNames + (ContractDecl.scopedConstantEnv c.dispatchOrder c.sharedConstantTail decl) + c.stateEnv c.allContracts (ContractDecl.directUsingDecls decl ++ c.sourceUsingDecls) + c.modifiers c.availableFunctions c.sourceFunctions fn + (concatMapList ContractDecl.directOrdinaryFunctions supers) + (some decl.name) (c.dispatchOrder.map ContractDecl.name) + c.externalCallKindEnv c.eventArgEnv c.errorArgEnv c.internalFnIds + (ContractDecl.structEnvFromContracts c.allContracts) c.eventIndexedEnv + (c.contractEvents ++ c.visibleSourceEvents) + +/-- The ANF preprocessing of a function's body in a contract's context. -/ +def FromOrdersCtx.anfF (c : FromOrdersCtx) (pre : ToCorePre) : Stmt := + pre.anf c.externalCallKindEnv c.sourceFunctions + (ContractDecl.structEnvFromContracts c.allContracts) c.eventIndexedEnv + +/-- The lowering of a function's preprocessed body in a contract's context. -/ +def FromOrdersCtx.lowF (c : FromOrdersCtx) (pre : ToCorePre) (body : Stmt) : Option CoreStmt := + pre.lower c.externalCallKindEnv c.sourceFunctions body + +/-- `FromOrdersCtx.pairF` after the lowering of the function's body. -/ +def FromOrdersCtx.restF (c : FromOrdersCtx) (decl : ContractDecl) (fn : FunctionDecl) + (pre : ToCorePre) (inner : Option CoreStmt) : Option (FunctionDecl × CoreFunctionDef) := do + let fd ← FunctionDecl.toCoreRest? c.storageNames c.sourceFunctions c.externalCallKindEnv + (ContractDecl.structEnvFromContracts c.allContracts) c.eventIndexedEnv pre inner + let fd := + if decl.kind == ContractKind.library then + { fd with + selector? := + FunctionDecl.libraryAbiSelector? + (ContractDecl.structEnvFromContracts c.allContracts) fn } + else + fd + some (fn, fd) + +theorem FromOrdersCtx.pairF_eq_staged (c : FromOrdersCtx) (decl : ContractDecl) + (fn : FunctionDecl) : + c.pairF decl fn = c.preF decl fn >>= fun pre => c.restF decl fn pre (c.lowF pre (c.anfF pre)) := by + simp only [FromOrdersCtx.pairF, ContractDecl.directCoreFunctionPair?, FromOrdersCtx.preF, + FromOrdersCtx.restF, FromOrdersCtx.lowF, FromOrdersCtx.anfF, FunctionDecl.toCore_eq_staged, + bind_assoc] + +/-- A function's translation in a contract's context from its stages. -/ +theorem FromOrdersCtx.pairF_of_stages {c : FromOrdersCtx} {decl : ContractDecl} {fn : FunctionDecl} + {pre : ToCorePre} {body : Stmt} {inner : CoreStmt} {p : FunctionDecl × CoreFunctionDef} + (h₁ : c.preF decl fn = some pre) (h₂ : some (c.anfF pre) = some body) + (h₃ : c.lowF pre body = some inner) (h₄ : c.restF decl fn pre (some inner) = some p) : + c.pairF decl fn = some p := by + rw [FromOrdersCtx.pairF_eq_staged, h₁] + show c.restF decl fn pre (c.lowF pre (c.anfF pre)) = some p + rw [Option.some.inj h₂, h₃] + exact h₄ + +end SolidCore.Solidity.Executable diff --git a/SolidCore/Solidity/TypeCheck.lean b/SolidCore/Solidity/TypeCheck.lean index 284aa998..fe4c12ac 100644 --- a/SolidCore/Solidity/TypeCheck.lean +++ b/SolidCore/Solidity/TypeCheck.lean @@ -2200,6 +2200,40 @@ def requireLogOrCreateAllowed (env : CheckEnv) (what : String) : require (mutabilityAllowsLogOrCreate env.currentMutability) (TypeError.mutabilityViolation what) +/-- The operands of `Stmt.assemblyCreate2 target value code salt` (inline assembly + `target := create2(value, add(code, 32), mload(code), salt)`): `target` a local + `address`, `code` a local `bytes memory`, `value` a number literal below `2^256` or a + local `uint256`, and `salt` the same or a local `bytes32` (a full word, which Yul reads + as it is). Locals exclude state variables, constants and storage references. -/ +def checkAssemblyCreate2 (env : CheckEnv) (target value code salt : Solidity.Expr) : + Except TypeError Unit := do + let isLocal (e : Solidity.Expr) (ok : Ty -> Bool) : Bool := + match e with + | .ident name => + env.isLocalName name && !env.isLocalStorageRef name && + (match env.lookupConstantBinding? name with | some true => false | _ => true) && + (match env.lookupVar? name with | some ty => ok ty | none => false) + | _ => false + let isWord (e : Solidity.Expr) (ok : Ty -> Bool) : Bool := + isLocal e ok || + (match e with + | .literal (.number text) => + match Solidity.Executable.parseNumberNat? text with + | some n => decide (n < 2 ^ 256) + | none => false + | _ => false) + require (isLocal target (fun ty => ty == Ty.address false || ty == Ty.address true)) + (TypeError.unsupported "create2 target other than a local address") + require (isLocal code (fun ty => ty == Ty.bytes) && + (match code with + | .ident name => env.lookupLocalDataLocation? name == some Solidity.DataLocation.memory + | _ => false)) + (TypeError.unsupported "create2 init code other than a local bytes memory") + require (isWord value (fun ty => ty == Ty.uint 256)) + (TypeError.unsupported "create2 value other than a literal or a local uint256") + require (isWord salt (fun ty => ty == Ty.uint 256 || ty == Ty.bytesN 32)) + (TypeError.unsupported "create2 salt other than a literal or a local uint256 or bytes32") + def requireCallMutabilityAllowed (env : CheckEnv) (callee : Solidity.StateMutability) : Except TypeError Unit := @@ -10185,7 +10219,7 @@ def constantDepStep (adj : List (Name × List Name)) /-- Whether `start` can reach itself through the `constant`-dependency graph `adj` (i.e. lies on a cycle). Fuel-bounded by the node count. -/ -partial def constantReachesSelf (adj : List (Name × List Name)) +def constantReachesSelf (adj : List (Name × List Name)) (start : Name) : Bool := let rec go (fuel : Nat) (reached : List Name) : Bool := if reached.contains start then true @@ -11258,6 +11292,10 @@ def checkStmt (env : CheckEnv) : Except.ok { source := stmt } | Solidity.Stmt.inlineAssembly _ => Except.error (TypeError.unsupported "inline assembly") + | stmt@(Solidity.Stmt.assemblyCreate2 target value code salt) => do + requireLogOrCreateAllowed env "create2 in view or pure function" + checkAssemblyCreate2 env target value code salt + Except.ok { source := stmt } | stmt@Solidity.Stmt.modifierPlaceholder => do require env.inModifier TypeError.modifierPlaceholderOutsideModifier require (!env.inUnchecked) (TypeError.unsupported @@ -11570,6 +11608,35 @@ def checkNoInheritedSiblingIdentifierClashes "inherited identifier already declared") checkNoInheritedSiblingIdentifierClashes funcNames eventNames rest +-- GETTER-IMPLEMENTS (solc: a public state variable may implement an external +-- function of a base it inherits, e.g. `string public constant name` for an +-- interface's `function name() external`; the two are one member of the +-- contract's scope, not a clash). The inherited function names that some +-- inherited contract's public state variable implements: every inherited +-- contract that declares a function of that name directly is one of that +-- contract's own bases. The own-contract override checks already ran on that +-- contract, so only the derived contract's sibling clash check skips them; a +-- function of that name from any other base still clashes. +def ContractDecls.getterImplementedFunctionNames + (allContracts inherited : List Solidity.ContractDecl) : List Name := + let declarers (n : Name) : List Name := + (inherited.filter fun d => + (ContractDecl.directFunctionSigs d).any fun s => s.name == n).map + (·.name) + inherited.flatMap fun d => + match Solidity.Executable.ContractDecl.dispatchOrder? allContracts d with + | none => [] + | some order => + let bases := (order.drop 1).map (·.name) + (ContractDecl.visibleStateVars d).filterMap fun v => + match v.visibility with + | some Solidity.Visibility.public_ => + let ds := declarers v.name + if !ds.isEmpty && ds.all (fun b => bases.contains b) then + some v.name + else none + | _ => none + structure OverrideMember where origin : Path originKind : Solidity.ContractKind @@ -13555,6 +13622,9 @@ def Stmt.pointerReturnFlowFuel : Stmt.pointerReturnFlowFuel fuel env requirements placeholder assigned body | _ + 1, _, _, _, _, Solidity.Stmt.inlineAssembly _ => { unsafeReturn := true } + -- It writes an address local and only reads its other operands: no pointer flow. + | _ + 1, _, _, _, assigned, Solidity.Stmt.assemblyCreate2 _ _ _ _ => + { normal? := some assigned } | fuel + 1, env, requirements, placeholder, assigned, Solidity.Stmt.modifierPlaceholder => match placeholder with @@ -13999,6 +14069,8 @@ def Stmt.pointerLocalFlowFuel : Stmt.pointerLocalFlowFuel fuel name assigned body | _ + 1, _, _, Solidity.Stmt.inlineAssembly _ => { unsafeReturn := true } + | _ + 1, _, assigned, Solidity.Stmt.assemblyCreate2 _ _ _ _ => + { normal? := some assigned } | _ + 1, _, assigned, Solidity.Stmt.modifierPlaceholder => { normal? := some assigned } @@ -15261,7 +15333,12 @@ def ContractDecl.check (sourceFunctions : List FunctionSig) -- may not coincide with an event name. Names come from `ancestorPaths` / -- `inheritedContracts` (the C3 linearization, each base once), so a single -- declaration reached via multiple diamond paths appears once and is safe. - let inheritedClashFuncNames := inheritedFunctionSigs.map (·.name) + let getterImplementedNames := + ContractDecls.getterImplementedFunctionNames allContracts + inheritedContracts + let inheritedClashFuncNames := + (inheritedFunctionSigs.map (·.name)).filter fun n => + !Solidity.Executable.nameIn n getterImplementedNames let inheritedNonOverloadableNames := inheritedStateVarNames ++ inheritedNonEventTypeNames checkNoInheritedSiblingIdentifierClashes diff --git a/SolidCore/Witness/AddmodArgOrder.lean b/SolidCore/Witness/AddmodArgOrder.lean new file mode 100644 index 00000000..3372f76f --- /dev/null +++ b/SolidCore/Witness/AddmodArgOrder.lean @@ -0,0 +1,240 @@ +import SolidCore.Solidity.Checked +import SolidCore.Witness.Checked + +set_option maxHeartbeats 8000000 + +/-! +ADDMOD-ARG-ORDER (regression): `addmod`/`mulmod` evaluate their arguments +RIGHT to LEFT in solc 0.8.35 legacy codegen (`ExpressionCompiler.cpp`, +`Kind::AddMod`/`Kind::MulMod`): the modulus first, then a zero check +(`Panic(0x12)`), then the second operand, then the first. + +```solidity +contract C { + uint256 n; + + function bump() internal returns (uint256) { + n += 1; + return n; + } + + function boom(uint256 x) internal pure returns (uint256) { + return x + 200; + } + + function f() external returns (uint256) { + return addmod(bump(), n, 100); + } + + function g() external returns (uint256) { + return mulmod(bump(), n + 5, 100); + } + + function h(uint256 x, uint256 m) external pure returns (uint256) { + return addmod(x + 200, 1, m); + } + + function k(uint256 x, uint256 m) external pure returns (uint256) { + return mulmod(boom(x), 1, m); + } + + function t() external returns (uint256, uint256) { + return (7, addmod(bump(), n, 100)); + } + + function ctl() external returns (uint256) { + return addmod(n, bump(), 100); + } +} +``` + +The call hoisters ran `bump()` (the first operand) ahead of the residual +`addmod(_t, n, 100)`, so `n` was read after `bump()` incremented it; and the +interpreter checked the modulus for zero only after evaluating both operands, +so an overflowing operand reported `Panic(0x11)` instead of `Panic(0x12)`. +Both hoisters now bind the operands evaluated first (and the ANF hoister checks +a non-literal modulus for zero) ahead of the earlier operands' calls, and the +interpreter checks the modulus right after evaluating it. + +Real solc 0.8.35 + EVM ground truth (from `n = 0`): `f() = 1`, `g() = 5`, +`h(2^256-101, 0)` and `k(2^256-101, 0)` revert `Panic(0x12)`, `t() = (7, 1)`, +`ctl() = 2`. +-/ + +namespace SolidCore +namespace Solidity +namespace SolcAstImport +namespace AddmodArgOrder + +open SolidCore.Solidity.Source + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "C" + abstract := false + bases := [] + items := [(ContractItem.stateVar + { name := "n", + ty := Ty.uint 256, + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.function + { kind := FunctionKind.function, + name := some "bump", + visibility := some Visibility.internal_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.assign (Expr.ident "n") AssignOp.addAssign (Expr.literal (Literal.number "1"))), Stmt.returnValues (some (Expr.ident "n"))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "boom", + visibility := some Visibility.internal_, + mutability := StateMutability.pure, + params := [{ name := some "x", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.binary BinaryOp.add (Expr.ident "x") (Expr.literal (Literal.number "200"))))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "f", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.ident "addmod") [Arg.positional (Expr.call (Expr.ident "bump") []), Arg.positional (Expr.ident "n"), Arg.positional (Expr.literal (Literal.number "100"))]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "g", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.ident "mulmod") [Arg.positional (Expr.call (Expr.ident "bump") []), Arg.positional (Expr.binary BinaryOp.add (Expr.ident "n") (Expr.literal (Literal.number "5"))), Arg.positional (Expr.literal (Literal.number "100"))]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "h", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "x", ty := Ty.uint 256, location := none }, { name := some "m", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.ident "addmod") [Arg.positional (Expr.binary BinaryOp.add (Expr.ident "x") (Expr.literal (Literal.number "200"))), Arg.positional (Expr.literal (Literal.number "1")), Arg.positional (Expr.ident "m")]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "k", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "x", ty := Ty.uint 256, location := none }, { name := some "m", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.ident "mulmod") [Arg.positional (Expr.call (Expr.ident "boom") [Arg.positional (Expr.ident "x")]), Arg.positional (Expr.literal (Literal.number "1")), Arg.positional (Expr.ident "m")]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "t", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 256, location := none }, { name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.tuple [TupleItem.value (Expr.literal (Literal.number "7")), TupleItem.value (Expr.call (Expr.ident "addmod") [Arg.positional (Expr.call (Expr.ident "bump") []), Arg.positional (Expr.ident "n"), Arg.positional (Expr.literal (Literal.number "100"))])]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "ctl", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.ident "addmod") [Arg.positional (Expr.ident "n"), Arg.positional (Expr.call (Expr.ident "bump") []), Arg.positional (Expr.literal (Literal.number "100"))]))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end AddmodArgOrder +end SolcAstImport +end Solidity +end SolidCore + +namespace SolidCore +namespace Solidity +namespace Witness +namespace AddmodArgOrder + +open SolidCore.Solidity.Source +open SolidCore.Solidity.TypeCheck + +abbrev Fam := SolidCore.Solidity.SolcAstImport.AddmodArgOrder.importedContract + +def accepted : Bool := + SolidCore.Solidity.SolcAstImport.AddmodArgOrder.importedContractAccepted + +private def isOkTrue : Except TypeError Bool → Bool + | Except.ok true => true + | _ => false + +private def big : SolidCore.Solidity.Source.Value := + SolidCore.Solidity.Source.Value.word + (115792089237316195423570985008687907853269984665640564039457584007913129639935 - 100) + +private def zero : SolidCore.Solidity.Source.Value := + SolidCore.Solidity.Source.Value.word 0 + +-- `addmod(bump(), n, 100)`: `n` is read (0) before `bump()` runs. +def f_is_1 : Except TypeError Bool := + Examples.checkedOwnCallWordMatches 256 Fam "f" State.empty [] 1 + +-- `mulmod(bump(), n + 5, 100)`: `n + 5` is 5, `bump()` is 1. +def g_is_5 : Except TypeError Bool := + Examples.checkedOwnCallWordMatches 256 Fam "g" State.empty [] 5 + +-- The zero modulus is reported before the overflowing first operand. +def h_panics_0x12 : Except TypeError Bool := + Examples.checkedOwnCallPanicMatches 256 Fam "h" State.empty [big, zero] 0x12 + +-- ... and before a first-operand call that would itself overflow. +def k_panics_0x12 : Except TypeError Bool := + Examples.checkedOwnCallPanicMatches 256 Fam "k" State.empty [big, zero] 0x12 + +-- The same order inside a returned tuple (argument-position hoister). +def t_is_7_1 : Except TypeError Bool := + Examples.checkedOwnCallWordPairMatches 256 Fam "t" State.empty [] 7 1 + +-- Control: the call is the second operand, so it runs before `n` is read. +def ctl_is_2 : Except TypeError Bool := + Examples.checkedOwnCallWordMatches 256 Fam "ctl" State.empty [] 2 + +#guard accepted +#guard isOkTrue f_is_1 +#guard isOkTrue g_is_5 +#guard isOkTrue h_panics_0x12 +#guard isOkTrue k_panics_0x12 +#guard isOkTrue t_is_7_1 +#guard isOkTrue ctl_is_2 + +end AddmodArgOrder +end Witness +end Solidity +end SolidCore diff --git a/SolidCore/Witness/BytesNShiftConversionWidth.lean b/SolidCore/Witness/BytesNShiftConversionWidth.lean new file mode 100644 index 00000000..aa49c081 --- /dev/null +++ b/SolidCore/Witness/BytesNShiftConversionWidth.lean @@ -0,0 +1,224 @@ +import SolidCore.Solidity.Checked +import SolidCore.Witness.Checked + +set_option maxHeartbeats 8000000 + +/-! +Regression for a conversion of a fixed-bytes shift result to another width. + +The shift runs at the operand's own width and the result is converted +afterwards: bytes2(0x1234) >> 4 is the bytes2 value 0x0123, so +bytes32(bytes2(0x1234) >> 4) is 0x0123 followed by zero bytes. The bytesN +shift/bitwise lowering walked the operand at the conversion's target width, +widening the leaves before the shift, so the bits shifted below the 2-byte +lane survived (0x01234000...). Covers widening (bytes32, bytes16 via a +local), narrowing (bytes1), left shift, complement, an ABI-encoded widening, the same-width conversion, and the +already-correct shift through a bytes2 local as a control. +-/ + +namespace SolidCore.Solidity.Witness.BytesNShiftConversionWidth + +open SolidCore.Solidity +open SolidCore.Solidity.Source +open SolidCore.Solidity.TypeCheck + +/-- Solidity source of the contract below (imported AST): + + contract C { + function widenShr(uint256 c) external pure returns (bytes32) { + return bytes32(bytes2(0x1234) >> c); + } + function widenShr7(uint256 c) external pure returns (bytes32) { + return bytes32(bytes7(0x11223344556677) >> c); + } + function widenShrLocal(uint256 c) external pure returns (bytes32) { + bytes32 r = bytes16(bytes2(0x1234) >> c); + return r; + } + function widenShl(uint256 c) external pure returns (bytes32) { + return bytes32(bytes2(0x1234) << c); + } + function widenNot() external pure returns (bytes32) { + return bytes32(~bytes2(0x1234)); + } + function widenShrEncode(uint256 c) external pure returns (bytes memory) { + return abi.encode(bytes32(bytes2(0x1234) >> c)); + } + function narrowShr(uint256 c) external pure returns (bytes1) { + return bytes1(bytes2(0x1234) >> c); + } + function sameWidthShr(uint256 c) external pure returns (bytes2) { + return bytes2(bytes2(0x1234) >> c); + } + function viaLocalControl(uint256 c) external pure returns (bytes32) { + bytes2 t = bytes2(0x1234) >> c; + return bytes32(t); + } + } +-/ +def contract : ContractDecl := +{ kind := ContractKind.contract + name := "C" + abstract := false + bases := [] + items := [(ContractItem.function + { kind := FunctionKind.function, + name := some "widenShr", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "c", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.bytesN 32, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.typeName (Ty.bytesN 32)) [Arg.positional (Expr.binary BinaryOp.shr (Expr.call (Expr.typeName (Ty.bytesN 2)) [Arg.positional (Expr.literal (Literal.number "0x1234"))]) (Expr.ident "c"))]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "widenShr7", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "c", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.bytesN 32, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.typeName (Ty.bytesN 32)) [Arg.positional (Expr.binary BinaryOp.shr (Expr.call (Expr.typeName (Ty.bytesN 7)) [Arg.positional (Expr.literal (Literal.number "0x11223344556677"))]) (Expr.ident "c"))]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "widenShrLocal", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "c", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.bytesN 32, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.varDecl [{ name := some "r", ty := Ty.bytesN 32, location := none }] (some (Expr.call (Expr.typeName (Ty.bytesN 16)) [Arg.positional (Expr.binary BinaryOp.shr (Expr.call (Expr.typeName (Ty.bytesN 2)) [Arg.positional (Expr.literal (Literal.number "0x1234"))]) (Expr.ident "c"))])), Stmt.returnValues (some (Expr.ident "r"))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "widenShl", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "c", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.bytesN 32, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.typeName (Ty.bytesN 32)) [Arg.positional (Expr.binary BinaryOp.shl (Expr.call (Expr.typeName (Ty.bytesN 2)) [Arg.positional (Expr.literal (Literal.number "0x1234"))]) (Expr.ident "c"))]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "widenNot", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [], + returns := [{ name := none, ty := Ty.bytesN 32, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.typeName (Ty.bytesN 32)) [Arg.positional (Expr.unary UnaryOp.bitNot (Expr.call (Expr.typeName (Ty.bytesN 2)) [Arg.positional (Expr.literal (Literal.number "0x1234"))]))]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "widenShrEncode", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "c", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.bytes, location := some DataLocation.memory }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.member (Expr.ident "abi") "encode") [Arg.positional (Expr.call (Expr.typeName (Ty.bytesN 32)) [Arg.positional (Expr.binary BinaryOp.shr (Expr.call (Expr.typeName (Ty.bytesN 2)) [Arg.positional (Expr.literal (Literal.number "0x1234"))]) (Expr.ident "c"))])]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "narrowShr", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "c", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.bytesN 1, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.typeName (Ty.bytesN 1)) [Arg.positional (Expr.binary BinaryOp.shr (Expr.call (Expr.typeName (Ty.bytesN 2)) [Arg.positional (Expr.literal (Literal.number "0x1234"))]) (Expr.ident "c"))]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "sameWidthShr", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "c", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.bytesN 2, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.call (Expr.typeName (Ty.bytesN 2)) [Arg.positional (Expr.binary BinaryOp.shr (Expr.call (Expr.typeName (Ty.bytesN 2)) [Arg.positional (Expr.literal (Literal.number "0x1234"))]) (Expr.ident "c"))]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "viaLocalControl", + visibility := some Visibility.external_, + mutability := StateMutability.pure, + params := [{ name := some "c", ty := Ty.uint 256, location := none }], + returns := [{ name := none, ty := Ty.bytesN 32, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.varDecl [{ name := some "t", ty := Ty.bytesN 2, location := none }] (some (Expr.binary BinaryOp.shr (Expr.call (Expr.typeName (Ty.bytesN 2)) [Arg.positional (Expr.literal (Literal.number "0x1234"))]) (Expr.ident "c"))), Stmt.returnValues (some (Expr.call (Expr.typeName (Ty.bytesN 32)) [Arg.positional (Expr.ident "t")]))]) })] } + +def sourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.35", + SourceItem.contract contract] } + +private def ok : Except TypeCheck.TypeError Bool -> Bool + | Except.ok true => true + | _ => false + +def accepted : Bool := + TypeCheck.Result.isOk + (TypeCheck.TypecheckedInput.checkedSourceUnit sourceUnit) + +-- widenShr +def widen_shr_discards_low_bits : Except TypeCheck.TypeError Bool := + Examples.checkedOwnCallWordMatches 1024 contract "widenShr" State.empty [Value.word 4] + (0x0123 * 2 ^ 240) + +-- widenShr7 +def widen_shr7_discards_low_bits : Except TypeCheck.TypeError Bool := + Examples.checkedOwnCallWordMatches 1024 contract "widenShr7" State.empty [Value.word 8] + (0x00112233445566 * 2 ^ 200) + +-- widenShrLocal +def widen_shr_bytes16_local : Except TypeCheck.TypeError Bool := + Examples.checkedOwnCallWordMatches 1024 contract "widenShrLocal" State.empty [Value.word 4] + (0x0123 * 2 ^ 240) + +-- widenShl +def widen_shl : Except TypeCheck.TypeError Bool := + Examples.checkedOwnCallWordMatches 1024 contract "widenShl" State.empty [Value.word 4] + (0x2340 * 2 ^ 240) + +-- widenNot +def widen_bitnot : Except TypeCheck.TypeError Bool := + Examples.checkedOwnCallWordMatches 1024 contract "widenNot" State.empty [] + (0xedcb * 2 ^ 240) + +-- widenShrEncode +def widen_shr_encode : Except TypeCheck.TypeError Bool := + Examples.checkedOwnCallBytesMatches 1024 contract "widenShrEncode" State.empty [Value.word 4] + ([0x01, 0x23] ++ List.replicate 30 0) + +-- narrowShr +def narrow_shr : Except TypeCheck.TypeError Bool := + Examples.checkedOwnCallWordMatches 1024 contract "narrowShr" State.empty [Value.word 4] + 0x01 + +-- sameWidthShr +def same_width_shr : Except TypeCheck.TypeError Bool := + Examples.checkedOwnCallWordMatches 1024 contract "sameWidthShr" State.empty [Value.word 4] + 0x0123 + +-- viaLocalControl +def via_local_control : Except TypeCheck.TypeError Bool := + Examples.checkedOwnCallWordMatches 1024 contract "viaLocalControl" State.empty [Value.word 4] + (0x0123 * 2 ^ 240) + +#guard accepted +#guard ok widen_shr_discards_low_bits +#guard ok widen_shr7_discards_low_bits +#guard ok widen_shr_bytes16_local +#guard ok widen_shl +#guard ok widen_bitnot +#guard ok widen_shr_encode +#guard ok narrow_shr +#guard ok same_width_shr +#guard ok via_local_control + +end SolidCore.Solidity.Witness.BytesNShiftConversionWidth diff --git a/SolidCore/Witness/TupleStorageCopyOrder.lean b/SolidCore/Witness/TupleStorageCopyOrder.lean new file mode 100644 index 00000000..6bc113b7 --- /dev/null +++ b/SolidCore/Witness/TupleStorageCopyOrder.lean @@ -0,0 +1,320 @@ +import SolidCore.Solidity.Checked +import SolidCore.Witness.Checked + +set_option maxHeartbeats 8000000 + +/-! +TUPLE-STORAGE-COPY-ORDER: a tuple component that names a storage array, +struct, `bytes` or `string` is evaluated to a storage reference and copied to +memory only when the whole tuple is converted to its target types, after the +later components ran. So in `return` (`pairV` below) and in a tuple +assignment, a later component's internal call that pushes to the same storage +is visible in the copy. A value read such as `v.length` is taken where it +stands, before the later call. + +```solidity +contract C { + struct S { uint8[] a; uint8 k; } + uint8[] v; + S s; + bytes b; + + function pushV() internal returns (uint8) { v.push(7); return 1; } + function pushS() internal returns (uint8) { s.a.push(7); return 1; } + function pushB() internal returns (uint8) { b.push(0x07); return 1; } + + function pairV() internal returns (uint8[] memory, uint8) { return (v, pushV()); } + function pairS() internal returns (S memory, uint8) { return (s, pushS()); } + function pairM() internal returns (uint8[] memory, uint8) { return (s.a, pushS()); } + function pairB() internal returns (bytes memory, uint8) { return (b, pushB()); } + function pairLen() internal returns (uint256, uint8) { return (v.length, pushV()); } + + function ret() external returns (uint256) { + delete v; + (uint8[] memory c, uint8 m) = pairV(); + return c.length + m; + } + + function retStruct() external returns (uint256) { + delete s; + (S memory c, uint8 m) = pairS(); + return c.a.length + m; + } + + function retMember() external returns (uint256) { + delete s; + (uint8[] memory c, uint8 m) = pairM(); + return c.length + m; + } + + function retBytes() external returns (uint256) { + delete b; + (bytes memory c, uint8 m) = pairB(); + return c.length + m; + } + + function assign() external returns (uint256) { + delete v; + uint8[] memory c; + uint8 m; + (c, m) = (v, pushV()); + return c.length + m; + } + + function len() external returns (uint256) { + delete v; + (uint256 c, uint8 m) = pairLen(); + return c + m; + } +} +``` + +Ground truth, solc 0.8.35 legacy and via-IR on the EVM, from empty storage: +`ret`, `retStruct`, `retMember`, `retBytes` and `assign` return 2 (the copy has +the pushed element), `len` returns 1. +-/ + +namespace SolidCore +namespace Solidity +namespace SolcAstImport +namespace TupleStorageCopyOrder + +def importedSourceName : String := "tuple-storage-copy-order.sol" + +def importedContractDecl0 : ContractDecl := +{ kind := ContractKind.contract + name := "C" + abstract := false + bases := [] + items := [(ContractItem.structDecl + { name := "S", + fields := [{ name := "a", ty := Ty.array (Ty.uint 8) (none) }, { name := "k", ty := Ty.uint 8 }] }), (ContractItem.stateVar + { name := "v", + ty := Ty.array (Ty.uint 8) (none), + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "s", + ty := Ty.user ({ segments := ["S"] }), + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.stateVar + { name := "b", + ty := Ty.bytes, + visibility := some Visibility.internal_, + mutability := VarMutability.mutable, + override? := none, + init := none }), (ContractItem.function + { kind := FunctionKind.function, + name := some "pushV", + visibility := some Visibility.internal_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.member (Expr.ident "v") "push") [Arg.positional (Expr.literal (Literal.number "7"))]), Stmt.returnValues (some (Expr.literal (Literal.number "1")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "pushS", + visibility := some Visibility.internal_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.member (Expr.member (Expr.ident "s") "a") "push") [Arg.positional (Expr.literal (Literal.number "7"))]), Stmt.returnValues (some (Expr.literal (Literal.number "1")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "pushB", + visibility := some Visibility.internal_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.call (Expr.member (Expr.ident "b") "push") [Arg.positional (Expr.literal (Literal.number "0x07"))]), Stmt.returnValues (some (Expr.literal (Literal.number "1")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "pairV", + visibility := some Visibility.internal_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.array (Ty.uint 8) (none), location := some DataLocation.memory }, { name := none, ty := Ty.uint 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.tuple [TupleItem.value (Expr.ident "v"), TupleItem.value (Expr.call (Expr.ident "pushV") [])]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "pairS", + visibility := some Visibility.internal_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.user ({ segments := ["S"] }), location := some DataLocation.memory }, { name := none, ty := Ty.uint 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.tuple [TupleItem.value (Expr.ident "s"), TupleItem.value (Expr.call (Expr.ident "pushS") [])]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "pairM", + visibility := some Visibility.internal_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.array (Ty.uint 8) (none), location := some DataLocation.memory }, { name := none, ty := Ty.uint 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.tuple [TupleItem.value (Expr.member (Expr.ident "s") "a"), TupleItem.value (Expr.call (Expr.ident "pushS") [])]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "pairB", + visibility := some Visibility.internal_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.bytes, location := some DataLocation.memory }, { name := none, ty := Ty.uint 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.tuple [TupleItem.value (Expr.ident "b"), TupleItem.value (Expr.call (Expr.ident "pushB") [])]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "pairLen", + visibility := some Visibility.internal_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 256, location := none }, { name := none, ty := Ty.uint 8, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.returnValues (some (Expr.tuple [TupleItem.value (Expr.member (Expr.ident "v") "length"), TupleItem.value (Expr.call (Expr.ident "pushV") [])]))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "ret", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.unary UnaryOp.delete (Expr.ident "v")), Stmt.varDecl [{ name := some "c", ty := Ty.array (Ty.uint 8) (none), location := some DataLocation.memory }, { name := some "m", ty := Ty.uint 8, location := none }] (some (Expr.call (Expr.ident "pairV") [])), Stmt.returnValues (some (Expr.binary BinaryOp.add (Expr.member (Expr.ident "c") "length") (Expr.ident "m")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "retStruct", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.unary UnaryOp.delete (Expr.ident "s")), Stmt.varDecl [{ name := some "c", ty := Ty.user ({ segments := ["S"] }), location := some DataLocation.memory }, { name := some "m", ty := Ty.uint 8, location := none }] (some (Expr.call (Expr.ident "pairS") [])), Stmt.returnValues (some (Expr.binary BinaryOp.add (Expr.member (Expr.member (Expr.ident "c") "a") "length") (Expr.ident "m")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "retMember", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.unary UnaryOp.delete (Expr.ident "s")), Stmt.varDecl [{ name := some "c", ty := Ty.array (Ty.uint 8) (none), location := some DataLocation.memory }, { name := some "m", ty := Ty.uint 8, location := none }] (some (Expr.call (Expr.ident "pairM") [])), Stmt.returnValues (some (Expr.binary BinaryOp.add (Expr.member (Expr.ident "c") "length") (Expr.ident "m")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "retBytes", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.unary UnaryOp.delete (Expr.ident "b")), Stmt.varDecl [{ name := some "c", ty := Ty.bytes, location := some DataLocation.memory }, { name := some "m", ty := Ty.uint 8, location := none }] (some (Expr.call (Expr.ident "pairB") [])), Stmt.returnValues (some (Expr.binary BinaryOp.add (Expr.member (Expr.ident "c") "length") (Expr.ident "m")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "assign", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.unary UnaryOp.delete (Expr.ident "v")), Stmt.varDecl [{ name := some "c", ty := Ty.array (Ty.uint 8) (none), location := some DataLocation.memory }] none, Stmt.varDecl [{ name := some "m", ty := Ty.uint 8, location := none }] none, Stmt.expr (Expr.assign (Expr.tuple [TupleItem.value (Expr.ident "c"), TupleItem.value (Expr.ident "m")]) AssignOp.assign (Expr.tuple [TupleItem.value (Expr.ident "v"), TupleItem.value (Expr.call (Expr.ident "pushV") [])])), Stmt.returnValues (some (Expr.binary BinaryOp.add (Expr.member (Expr.ident "c") "length") (Expr.ident "m")))]) }), (ContractItem.function + { kind := FunctionKind.function, + name := some "len", + visibility := some Visibility.external_, + mutability := StateMutability.nonpayable, + params := [], + returns := [{ name := none, ty := Ty.uint 256, location := none }], + virtual := false, + override? := none, + modifiers := [], + body := some (Stmt.block [Stmt.expr (Expr.unary UnaryOp.delete (Expr.ident "v")), Stmt.varDecl [{ name := some "c", ty := Ty.uint 256, location := none }, { name := some "m", ty := Ty.uint 8, location := none }] (some (Expr.call (Expr.ident "pairLen") [])), Stmt.returnValues (some (Expr.binary BinaryOp.add (Expr.ident "c") (Expr.ident "m")))]) })] } + +def importedContract : ContractDecl := + importedContractDecl0 + +def importedContracts : List ContractDecl := + [importedContractDecl0] + +def importedSourceUnit : SourceUnit := + { items := [SourceItem.pragma "solidity" "^0.8.28", SourceItem.contract importedContractDecl0] } + +def importedContractAccepted : Bool := + TypeCheck.Result.isOk (TypeCheck.TypecheckedInput.checkedSourceUnit importedSourceUnit) + +end TupleStorageCopyOrder +end SolcAstImport +end Solidity +end SolidCore + +namespace SolidCore +namespace Solidity +namespace Witness +namespace TupleStorageCopyOrder + +open SolidCore.Solidity.Source +open SolidCore.Solidity.TypeCheck + +abbrev Fam := SolidCore.Solidity.SolcAstImport.TupleStorageCopyOrder.importedContract + +def accepted : Bool := + SolidCore.Solidity.SolcAstImport.TupleStorageCopyOrder.importedContractAccepted + +private def isOkTrue : Except TypeError Bool → Bool + | Except.ok true => true + | _ => false + +-- `(v, pushV())` returned from an internal function: the copy has the push. +def ret_is_2 : Except TypeError Bool := + Examples.checkedOwnCallWordMatches 4096 Fam "ret" State.empty [] 2 + +-- The same for a storage struct whose array member the call pushes to. +def retStruct_is_2 : Except TypeError Bool := + Examples.checkedOwnCallWordMatches 4096 Fam "retStruct" State.empty [] 2 + +-- ... for a member path into that struct. +def retMember_is_2 : Except TypeError Bool := + Examples.checkedOwnCallWordMatches 4096 Fam "retMember" State.empty [] 2 + +-- ... for a storage `bytes`. +def retBytes_is_2 : Except TypeError Bool := + Examples.checkedOwnCallWordMatches 4096 Fam "retBytes" State.empty [] 2 + +-- ... and for a tuple assignment to memory locals. +def assign_is_2 : Except TypeError Bool := + Examples.checkedOwnCallWordMatches 4096 Fam "assign" State.empty [] 2 + +-- Control: `v.length` is a value, read before the later call. +def len_is_1 : Except TypeError Bool := + Examples.checkedOwnCallWordMatches 4096 Fam "len" State.empty [] 1 + +#guard accepted +#guard isOkTrue ret_is_2 +#guard isOkTrue retStruct_is_2 +#guard isOkTrue retMember_is_2 +#guard isOkTrue retBytes_is_2 +#guard isOkTrue assign_is_2 +#guard isOkTrue len_is_1 + +end TupleStorageCopyOrder +end Witness +end Solidity +end SolidCore diff --git a/Verify.lean b/Verify.lean new file mode 100644 index 00000000..94951435 --- /dev/null +++ b/Verify.lean @@ -0,0 +1,14 @@ +import Verify.Basic +import Verify.Abi +import Verify.Finite +import Verify.Run +import Verify.Tactic +import Verify.C1 +import Verify.W1 +import Verify.W4 +import Verify.C4 +import Verify.W5 +import Verify.Fuel +import Verify.CounterBump +import Verify.Final +import Verify.SourceOracle diff --git a/Verify/Abi.lean b/Verify/Abi.lean new file mode 100644 index 00000000..23717aa8 --- /dev/null +++ b/Verify/Abi.lean @@ -0,0 +1,38 @@ +import Verify.Basic +import SolidCore.Refinement.Wide.Refines + +/-! +# Argument words of a call + +A specification speaks about a call's argument words. `argWords n call` reads the +first `n` of them from the call data after the selector, as SolidCore's ABI decoder +does; on a call of `Abi.fullScope` they are the words the call was built from +(`argWords_calldata`). +-/ + +namespace SolidCore.Verify + +open SolidCore.Refinement SolidCore.Solidity SolidCore.Solidity.Source + +/-- The first `n` argument words of `call`: the 32-byte words after the selector. -/ +def argWords (n : Nat) (call : Call) : List Nat := + (List.range n).map fun i => + (ABI.readWord? ((call.calldata.data.toList.map (·.toNat)).drop 4) (32 * i)).getD 0 + +theorem argWords_calldata (sel : Nat) (args : List Nat) (hargs : ∀ a ∈ args, a < 2 ^ 256) + (cv : Nat) (st : List (Nat × Nat)) : + argWords args.length { calldata := Abi.calldata sel args, callvalue := cv, storage := st } = + args := by + simp only [argWords, Dirty.bytes_calldata, Wide.drop_selector] + apply List.ext_getElem (by simp) + intro i h1 h2 + simp [Dirty.readWord_argBytes args hargs i h2] + +/-- The bytes of a 32-byte big-endian word. -/ +def word (v : Nat) : List Nat := (EthLib.Base.natToBytes 32 v).map (·.toNat) + +/-- The revert data of `Panic(code)`. -/ +def panic (code : Nat) : List Nat := (EthLib.Base.natToBytes 4 0x4e487b71).map (·.toNat) ++ word code + +end SolidCore.Verify + diff --git a/Verify/Basic.lean b/Verify/Basic.lean new file mode 100644 index 00000000..fcaad920 --- /dev/null +++ b/Verify/Basic.lean @@ -0,0 +1,306 @@ +import Loom.MonadAlgebras.WP.Basic +import Loom.MonadAlgebras.WP.Variant +import Loom.MonadAlgebras.Instances.ExceptTErr +import SolidCore.Refinement.Compose + +/-! +# A verification-condition generator for SolidCore, on Loom + +A specification of an external function says what a call must show, from what holds +before it. Its triple (`Triple`) is stated directly against SolidCore's +`Source.run`: every call of the scope that meets the precondition finishes with some +observable, and every observable it can finish with meets the postcondition. + +The verification conditions come from Loom's weakest preconditions. A function is +modelled as a program in `SolM`, a state monad over the callee's storage whose +failures are reverts with their revert data. `SolM` is a Loom ordered monad algebra +(`MAlgOrdered`) whose assertions take, besides the storage, a predicate on the revert +data a failure must meet, so that one weakest precondition covers both outcomes of a +call. Loom's `wp_bind` and `wp_pure` and the rules below for storage and reverts +compute the weakest precondition of a model by `simp`; what is left is a goal on words +that `omega` or `bv_decide` closes. + +A model is tied to SolidCore by `Implements`: on every call of the scope, +`Source.run` finishes with the observable the model's outcome shows. Each contract +proves it once, by symbolic evaluation of SolidCore's interpreter (`Wide.Tactic`). +`triple_of_wp` then turns the weakest precondition into the triple, and +`satisfies_of_triple` into `Satisfies` on `solidCore fuel`, the form the refinement +theorems carry to bytecode. + +The triple is total: it includes that `Source.run` returns `some`, so running out +of fuel or an interpreter failure refutes it. +-/ + +namespace SolidCore.Verify + +open SolidCore.Refinement + +/-- The callee's storage, slot to word. -/ +abbrev Storage := Nat → Nat + +/-- The data a call reverts with. -/ +abbrev Revert := List Nat + +/-- A model of an external function: a program over the storage that fails with its +revert data. -/ +abbrev SolM := StateT Storage (Except Revert) + +/-- An assertion on what a model leaves: given the predicate a revert's data must meet, +a predicate on the storage. -/ +abbrev Assn := (Revert → Prop) → Storage → Prop + +/-- What a model's outcome means for an assertion: a result's assertion at its final +storage, or the revert predicate on the revert data. -/ +def Assn.ofOutcome : Except Revert (Assn × Storage) → (Revert → Prop) → Prop + | .ok (p, s'), herr => p herr s' + | .error e, herr => herr e + +/-- `SolM` is a Loom ordered monad algebra on `Assn`. -/ +instance : MAlgOrdered SolM Assn where + μ x := fun herr s => Assn.ofOutcome (x s) herr + μ_ord_pure := by intro l; rfl + μ_ord_bind := by + intro α f g h x herr s + show Assn.ofOutcome ((x s).bind fun a => f a.1 a.2) herr → + Assn.ofOutcome ((x s).bind fun a => g a.1 a.2) herr + rcases x s with e | ⟨a, s'⟩ + · exact id + · exact h a herr s' + +/-! ## Weakest preconditions of the model's primitives -/ + +theorem wp_eq (x : SolM α) (post : α → Assn) : + wp x post = fun herr s => match x s with + | .ok (a, s') => post a herr s' + | .error e => herr e := by + funext herr s + show Assn.ofOutcome ((post <$> x) s) herr = _ + simp only [Functor.map, StateT.map] + rcases h : x s with e | ⟨a, s'⟩ <;> simp [h, Assn.ofOutcome, bind, Except.bind, pure, Except.pure] + +/-- Read a storage slot. -/ +def sload (slot : Nat) : SolM Nat := fun s => .ok (s slot, s) + +/-- Write a storage slot. Slots and values are 256-bit words, as in `slotValue` and +SolidCore's storage: a write to `slot` is a write to every slot equal to it modulo +`2 ^ 256`. -/ +def sstore (slot v : Nat) : SolM Unit := + fun s => .ok ((), fun k => if k % 2 ^ 256 = slot % 2 ^ 256 then v % 2 ^ 256 else s k) + +/-- Revert with `data`. -/ +def revert (data : Revert) : SolM α := fun _ => .error data + +@[simp] theorem wp_sload (slot : Nat) (post : Nat → Assn) : + wp (sload slot) post = fun herr s => post (s slot) herr s := by + rw [wp_eq]; rfl + +@[simp] theorem wp_sstore (slot v : Nat) (post : Unit → Assn) : + wp (sstore slot v) post = fun herr s => + post () herr (fun k => if k % 2 ^ 256 = slot % 2 ^ 256 then v % 2 ^ 256 else s k) := by + rw [wp_eq]; rfl + +@[simp] theorem wp_revert (data : Revert) (post : α → Assn) : + wp (revert data : SolM α) post = fun herr _ => herr data := by + rw [wp_eq]; rfl + +@[simp] theorem wp_ite (c : Prop) [Decidable c] (x y : SolM α) (post : α → Assn) : + wp (if c then x else y) post = if c then wp x post else wp y post := by + split <;> rfl + + +/-! ## `SolM`'s algebra is Loom's `StateT` algebra over the error-aware `Except` algebra + +Loom's `StateT` algebra over `Except Revert`'s error-aware algebra (`MAlgExceptErrProp`) +has assertions `Storage → (Revert → Prop) → Prop`; `Assn` takes the same two arguments in +the other order. `wp_eq_loom` says that the two weakest preconditions are the same, so every +rule of Loom's generic algebras holds of `SolM`'s. -/ + +/-- Loom's algebra of `SolM`: the `StateT` algebra over `Except Revert`'s error-aware one. -/ +noncomputable abbrev loomAlg : MAlgOrdered SolM (Storage → (Revert → Prop) → Prop) := + instMAlgOrderedStateTForallOfLawfulMonad Storage ((Revert → Prop) → Prop) (Except Revert) + +theorem wp_eq_loom (x : SolM α) (post : α → Assn) : + wp x post = fun herr s => + wp (mprop := loomAlg) x (fun a s' herr' => post a herr' s') s herr := by + funext herr s + rw [wp_eq] + show _ = Except.errProp herr ((fun fs : (Storage → (Revert → Prop) → Prop) × Storage => fs.1 fs.2) <$> + (StateT.map (fun a s' herr' => post a herr' s') x s)) + simp only [StateT.map] + rcases h : x s with e | ⟨a, s'⟩ <;> rfl + +@[simp] theorem wp_get (post : Storage → Assn) : + wp (get : SolM Storage) post = fun herr s => post s herr s := by + rw [wp_eq]; rfl + +@[simp] theorem wp_set (s' : Storage) (post : PUnit → Assn) : + wp (set s' : SolM PUnit) post = fun herr _ => post () herr s' := by + rw [wp_eq]; rfl + +@[simp] theorem wp_modify (f : Storage → Storage) (post : PUnit → Assn) : + wp (modify f : SolM PUnit) post = fun herr s => post () herr (f s) := by + rw [wp_eq]; rfl + +@[simp] theorem wp_throw (e : Revert) (post : α → Assn) : + wp (throw e : SolM α) post = fun herr _ => herr e := by + rw [wp_eq]; rfl + +/-! ## Loops + +A loop of a model is `Loop.whileBounded` (Loom's `WP.Variant`): a model cannot diverge, so +it is given the number of iterations to allow. `triple_while` proves it from an invariant and +a variant; with fuel above the variant the loop never runs out, so the model is the +unbounded loop's. -/ + +/-- A `while` loop of a model, run at most `fuel` times; out of fuel, it reverts with no data +(which the variant rule shows unreachable). -/ +abbrev whileM (cond : β → Bool) (body : β → SolM β) (fuel : Nat) (b : β) : SolM β := + Loop.whileBounded (fun _ => revert []) cond body fuel b + +/-- The total-correctness rule for a model's loop, on `Assn`. -/ +theorem triple_whileM (cond : β → Bool) (body : β → SolM β) (inv : β → Assn) + (measure : β → Nat) + (hbody : ∀ b, cond b = true → + triple (inv b) (body b) (fun b' => inv b' ⊓ ⌜measure b' < measure b⌝)) + (fuel : Nat) (init : β) (hfuel : measure init < fuel) : + triple (inv init) (whileM cond body fuel init) (fun b => inv b ⊓ ⌜cond b = false⌝) := + triple_while _ cond body inv measure hbody fuel init hfuel + +/-! ## Models, triples and the generator -/ + +/-- The observable of a model's outcome, from the initial storage `s`: a returned word +list and the final storage, or a revert with its data and the initial storage. A model +emits no logs. -/ +def observe (s : Storage) : Except Revert (List Nat × Storage) → Observable + | .ok (out, s') => { success := true, output := out, logs := [], storage := s' } + | .error e => { success := false, output := e, logs := [], storage := s } + +/-- The storage a call starts from, as a function. -/ +def initStorage (call : Call) : Storage := slotValue call.storage + +/-- `model` implements `contract` on `scope`: on every call of it, SolidCore with `fuel` +finishes with the observable of the model on the call's argument words `args call`. -/ +def Implements (fuel : Nat) (contract : SolidCore.Solidity.TypeCheck.CheckedContract) + (scope : Call → Prop) (args : Call → List Nat) (model : List Nat → SolM (List Nat)) : Prop := + ∀ call, scope call → + Source.run fuel contract call = some (observe (initStorage call) (model (args call) (initStorage call))) + +/-- The triple `{pre} contract {post}` on `scope`, against SolidCore: every call of the +scope that meets `pre` finishes, and every observable it finishes with meets `post`. -/ +def Triple (fuel : Nat) (contract : SolidCore.Solidity.TypeCheck.CheckedContract) + (scope : Call → Prop) (pre : Call → Prop) (post : Call → Observable → Prop) : Prop := + ∀ call, scope call → pre call → + (Source.run fuel contract call).isSome ∧ + ∀ obs, Source.run fuel contract call = some obs → post call obs + +/-- Total correctness of `p` in `S` on `scope`: every call that meets `pre` finishes with an +observable that meets `post`. The same statement as the refinement's `Satisfies`. -/ +def Satisfies (S : Sem) (p : S.Prog) (scope : Call → Prop) (pre : Call → Prop) + (post : Call → Observable → Prop) : Prop := + ∀ call, scope call → pre call → ∃ obs, S.run p call = some obs ∧ post call obs + +/-- The verification condition of a model: Loom's weakest precondition of the model on +the call's argument words, for the postcondition on a success and on a revert, at the +call's initial storage. -/ +def vc (model : List Nat → SolM (List Nat)) (args : Call → List Nat) + (post : Call → Observable → Prop) (call : Call) : Prop := + wp (model (args call)) + (fun out _ s' => post call { success := true, output := out, logs := [], storage := s' }) + (fun e => post call { success := false, output := e, logs := [], storage := initStorage call }) + (initStorage call) + +/-- The generator's soundness: a model that implements the contract and whose +verification condition holds under the precondition gives the triple. -/ +theorem triple_of_wp {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope : Call → Prop} {args : Call → List Nat} {model : List Nat → SolM (List Nat)} + {pre : Call → Prop} {post : Call → Observable → Prop} + (himpl : Implements fuel contract scope args model) + (hvc : ∀ call, scope call → pre call → vc model args post call) : + Triple fuel contract scope pre post := by + intro call hs hp + have hrun := himpl call hs + have h := hvc call hs hp + simp only [vc, wp_eq] at h + refine ⟨by simp [hrun], fun obs hobs => ?_⟩ + rw [hrun] at hobs + cases hobs + revert h + rcases model (args call) (initStorage call) with e | ⟨out, s'⟩ <;> exact id + +theorem satisfies_iff_triple {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope pre : Call → Prop} {post : Call → Observable → Prop} : + Satisfies (solidCore fuel) contract scope pre post ↔ Triple fuel contract scope pre post := by + constructor + · intro h call hs hp + obtain ⟨obs, hrun, hpost⟩ := h call hs hp + exact ⟨by simp [solidCore] at hrun; simp [hrun], fun o ho => by + simp [solidCore] at hrun; rw [hrun] at ho; cases ho; exact hpost⟩ + · intro h call hs hp + obtain ⟨hsome, hpost⟩ := h call hs hp + obtain ⟨obs, hobs⟩ := Option.isSome_iff_exists.mp hsome + exact ⟨obs, hobs, hpost obs hobs⟩ + +theorem satisfies_of_triple {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope pre : Call → Prop} {post : Call → Observable → Prop} + (h : Triple fuel contract scope pre post) : + Satisfies (solidCore fuel) contract scope pre post := + satisfies_iff_triple.mpr h + + +/-! ## Termination + +The triple includes that the call finishes: `Triple.finishes` gives the observable at the +triple's fuel. A model with a loop needs fuel that grows with its arguments, so +`ImplementsSome` asks for some fuel per call, `TripleSome` concludes that each call finishes +at some fuel with an observable that meets the postcondition, and `tripleSome_of_wp` is the +generator's soundness for it. -/ + +theorem Triple.finishes {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope pre : Call → Prop} {post : Call → Observable → Prop} + (h : Triple fuel contract scope pre post) : + ∀ call, scope call → pre call → ∃ obs, Source.run fuel contract call = some obs ∧ post call obs := by + intro call hs hp + obtain ⟨hsome, hpost⟩ := h call hs hp + obtain ⟨obs, hobs⟩ := Option.isSome_iff_exists.mp hsome + exact ⟨obs, hobs, hpost obs hobs⟩ + +/-- `model` implements `contract` on `scope` at some fuel per call. -/ +def ImplementsSome (contract : SolidCore.Solidity.TypeCheck.CheckedContract) + (scope : Call → Prop) (args : Call → List Nat) (model : List Nat → SolM (List Nat)) : Prop := + ∀ call, scope call → ∃ fuel, + Source.run fuel contract call = some (observe (initStorage call) (model (args call) (initStorage call))) + +/-- Every call of the scope that meets `pre` finishes at some fuel, and every observable it +finishes with at that fuel meets `post`. -/ +def TripleSome (contract : SolidCore.Solidity.TypeCheck.CheckedContract) + (scope : Call → Prop) (pre : Call → Prop) (post : Call → Observable → Prop) : Prop := + ∀ call, scope call → pre call → ∃ fuel obs, Source.run fuel contract call = some obs ∧ post call obs + +theorem Implements.some {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope : Call → Prop} {args : Call → List Nat} {model : List Nat → SolM (List Nat)} + (h : Implements fuel contract scope args model) : ImplementsSome contract scope args model := + fun call hs => ⟨fuel, h call hs⟩ + +theorem tripleSome_of_wp {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope : Call → Prop} {args : Call → List Nat} {model : List Nat → SolM (List Nat)} + {pre : Call → Prop} {post : Call → Observable → Prop} + (himpl : ImplementsSome contract scope args model) + (hvc : ∀ call, scope call → pre call → vc model args post call) : + TripleSome contract scope pre post := by + intro call hs hp + obtain ⟨fuel, hrun⟩ := himpl call hs + have h := hvc call hs hp + simp only [vc, wp_eq] at h + refine ⟨fuel, _, hrun, ?_⟩ + revert h + rcases model (args call) (initStorage call) with e | ⟨out, s'⟩ <;> exact id + +theorem Triple.some {fuel : Nat} {contract : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope pre : Call → Prop} {post : Call → Observable → Prop} + (h : Triple fuel contract scope pre post) : TripleSome contract scope pre post := by + intro call hs hp + obtain ⟨obs, hobs, hpost⟩ := h.finishes call hs hp + exact ⟨fuel, obs, hobs, hpost⟩ + +end SolidCore.Verify + diff --git a/Verify/C1.lean b/Verify/C1.lean new file mode 100644 index 00000000..8558a063 --- /dev/null +++ b/Verify/C1.lean @@ -0,0 +1,222 @@ +import Verify.Tactic +import SolidCore.Refinement.Corpus.C1 + +/-! +# c1: `f(uint8 x)` returns `x * 3 + 1`, or panics on overflow + +The specification of `Main.f` in `scripts/refinement/corpus/c1.sol`, proved against SolidCore +with the Loom VC generator of `Verify.Basic`: on every call of `f` with a clean argument +word `x < 256`, from the deployed (empty) storage, the call returns the word `3 * x + 1` when +`x ≤ 84`, and reverts with `Panic(0x11)` when `x ≥ 85`, the first argument for which +`x * 3 + 1` does not fit in `uint8`; it emits no logs and leaves storage empty. + +`model` is the function as a `SolM` program. `run_f` ties it to SolidCore by symbolic +evaluation of the interpreter on a free clean word (`wide_symex`), once `shape_of` gives +that the checked contract's core is the literal `coreLit` and its constructor leaves empty +storage and no logs, from c1's refinement (`Corpus.C1.shape_of`, the kernel's one conversion +check of the type checker's output, `kernel_rfl`); `implements_of_run` turns it into +`Implements`. `sc_vcgen` proves the verification conditions on every argument word, which +`vcs_mono` restricts to the scope. +-/ + +namespace SolidCore.Verify.C1 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement.Corpus.C1 + +/-- `f` as a Loom program over the storage. -/ +def model (ws : List Nat) : SolM (List Nat) := + if ws.getD 0 0 * 3 + 1 < 2 ^ 8 then pure (word (ws.getD 0 0 * 3 + 1)) else revert (panic 0x11) + +/-- The calls of the specification: `f` on every clean argument word, from the deployed +storage, the scope of c1's refinement (`Corpus.C1.scope []`). -/ +def scope : Call → Prop := (· ∈ calls fns [[]]) + +/-- The precondition: none beyond the scope. -/ +def pre : Call → Prop := fun _ => True + +/-- `f(x)` returns `3 * x + 1` for `x ≤ 84` and reverts with `Panic(0x11)` for `x ≥ 85`, +with no logs and empty storage. -/ +def post (call : Call) (obs : Observable) : Prop := + let x := (argWords 1 call).getD 0 0 + (x ≤ 84 → obs.success = true ∧ obs.output = word (3 * x + 1)) ∧ + (85 ≤ x → obs.success = false ∧ obs.output = panic 0x11) ∧ + obs.logs = [] ∧ ∀ slot, obs.storage slot = 0 + +/-- SolidCore's core contract of c1's `Main`, as the type checker leaves it. -/ +def coreLit : Contract := + { storageFields := [], + immutableFields := [], + eventDecls := [], + errorDecls := [], + functions := [{ name := "f", + selector? := some 824235060, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.add) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.mul) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 8 + (SolidCore.Solidity.Source.Expr.word 3))))) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 8 + (SolidCore.Solidity.Source.Expr.word 1))))]]], + dispatchId? := none }, + { name := "__internal_f(uint8)#[SolidCore.Solidity.Ty.uint 8]", + selector? := none, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.add) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.binary + (SolidCore.Solidity.Source.BinaryOp.mul) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 8 + (SolidCore.Solidity.Source.Expr.word 3))))) + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCast) + 8 + (SolidCore.Solidity.Source.Expr.word 1))))]]], + dispatchId? := none }] } + +/-- `coreLit` is the refinement's print of the core, `Corpus.C1.coreLit`. -/ +theorem coreLit_eq : coreLit = Corpus.C1.coreLit := rfl + +/-- The checked contract has the core `coreLit`, and its constructor leaves empty storage and +no logs: `Corpus.C1.shape_of`, the kernel's conversion check of the type checker's output +(`kernel_rfl`). -/ +theorem shape_of {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core = coreLit ∧ deployedStorage fuel c = some [] ∧ ∃ d, DeployedAt fuel c d [] := by + obtain ⟨hk, hs, he⟩ := Corpus.C1.shape_of hc + obtain ⟨d, hd⟩ := deployed_of he + exact ⟨hk.trans coreLit_eq.symm, hs, d, deployedAt_of_deployed hd⟩ + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs `f` on any clean argument word as `model` does. -/ +theorem run_f {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d []) (w : U256) (hw : w.toNat < 2 ^ 8) : + Source.run fuel c (callAt Bytecode.C1.Main.fSelector [w] []) = + some (observe (slotValue []) (model [w.toNat] (slotValue []))) := by + rw [run_eq_at hd] + have hev := hd.events + have hs : d.storage.isEmpty = true := by + rw [← Std.HashMap.isEmpty_toList, hd.storage]; rfl + simp only [Nat.reducePow] at hw + simp only [hcore, List.map_cons, List.map_nil, List.foldl_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.C1.Main.fSelector] + all_goals + simp only [model, List.getD_cons_zero] + split + all_goals + try rw [Nat.mod_eq_of_lt (by omega)] + simp [Source.observe, observe, revert, pure, StateT.pure, Except.pure, panic, word, + State.logEntries, State.loadSlot, StorageMap.lookup?, getElem?_of_isEmpty hs, hev, + slotValue, callAt] + all_goals first + | (funext k; rfl) + | (simp (disch := omega) only [Nat.reducePow, Nat.mod_eq_of_lt] at *; omega) + +/-- Every call of the scope is a call of `Abi.fullScope` on a clean word. -/ +theorem scope_sub (call : Call) (h : scope call) : + fullScope fns [] call ∧ (argWords 1 call).getD 0 0 < 2 ^ 8 := by + simp only [scope, calls, fns, tuples, Param.values, List.flatMap_cons, List.flatMap_nil, + List.append_nil, List.mem_flatMap, List.mem_map, List.mem_range, List.mem_cons, + List.not_mem_nil, or_false, exists_eq_left] at h + obtain ⟨_, ⟨a, ha, rfl⟩, rfl⟩ := h + have hb : ∀ b ∈ [a], b < 2 ^ 256 := by simp; omega + refine ⟨⟨_, List.mem_singleton_self _, [a], rfl, hb, rfl⟩, ?_⟩ + rw [show argWords 1 _ = [a] from argWords_calldata _ [a] hb 0 []] + simpa using ha + +/-- `model` implements SolidCore's `Main` on every call of the scope. -/ +theorem implements {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d []) : Implements fuel c scope (argWords 1) model := + (implements_of_run (ok := fun ws => ws.getD 0 0 < 2 ^ 8) (by simp [fns]) + fun fn hfn ws hl hok => by + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w, _ | _⟩ <;> simp at hl + exact run_f hcore hd w (by simpa using hok)).mono scope_sub + +/-- The verification conditions of `f`, by Loom's weakest preconditions. -/ +theorem vcs : ∀ call, scope call → pre call → vc model (argWords 1) post call := + vcs_mono (scope := fullScope fns []) (by sc_vcgen [fns, model, post]) + fun call h => (scope_sub call h).1 + +/-- **The specification of `c1`'s `f`**, as a triple against SolidCore. -/ +theorem spec : ∃ c, contract? = .ok c ∧ deployedStorage fuel c = some [] ∧ + Triple fuel c scope pre post := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, hs, d, hd⟩ := shape_of hc + exact ⟨c, hc, hs, triple_of_wp (implements hk hd) vcs⟩ + +/-- The specification of `c1`'s `f` as `Satisfies` on SolidCore. -/ +theorem satisfies : ∃ c, contract? = .ok c ∧ deployedStorage fuel c = some [] ∧ + Satisfies (solidCore fuel) c scope pre post := by + obtain ⟨c, hc, hs, h⟩ := spec + exact ⟨c, hc, hs, satisfies_of_triple h⟩ + +end SolidCore.Verify.C1 diff --git a/Verify/C4.lean b/Verify/C4.lean new file mode 100644 index 00000000..f2d170af --- /dev/null +++ b/Verify/C4.lean @@ -0,0 +1,458 @@ +import Verify.Tactic +import SolidCore.Refinement.Corpus.C4 + +/-! +# c4: `add(uint8 x)` adds to a packed `uint8 v` and xors a packed `uint8 w` + +The specification of `Main.add` in `scripts/refinement/corpus/c4.sol` +(`uint8 v; uint8 w = 7;` `v += x; w ^= x; return v;`), proved against SolidCore with the Loom +VC generator of `Verify.Basic`, on the scope of c4's refinement: every call of `add` on any +argument word below `2 ^ 256`, from the storage the constructor leaves. `v` and `w` share +slot 0, `v` in its low byte and `w` in the next, so the deployed storage is slot 0 = `7 * 256`. + +From there `v + x` never overflows, so a clean `x < 2 ^ 8` returns `x` and leaves slot 0 +holding `x + (7 ^ x) * 256`; the `Panic(0x11)` branch of the model is unreachable on the +scope. A dirty word reverts with empty data in SolidCore's ABI decoder and keeps the storage. + +`model` is the function as a `SolM` program on any storage: it reads slot 0, panics when +`v + x` does not fit in `uint8`, and writes the packed `(v + x, w ^ x)` back, keeping the +slot's higher bytes. `run_add` ties it to SolidCore by symbolic evaluation of the interpreter +on a free word (`wide_symex`, clean and dirty alike), from the deployed state with the call's +storage written over it (`run_eq_at`), once `shape_of` gives that the checked contract's core +is the literal `coreLit` and its constructor leaves exactly slot 0 = `7 * 256` and no logs, +from c4's refinement (`Corpus.C4.shape_of`, the kernel's one conversion check of the type +checker's output, `kernel_rfl`). `sc_vcgen` proves the verification conditions. + +`specAt` widens it to any storage that writes slot 0 (`scopeAt`): `run_add_at` runs SolidCore +on a symbolic slot-0 word, and `postAt` is the model's outcome from it (`model_ok`, +`model_panic`, `model_dirty`). +-/ + +namespace SolidCore.Verify.C4 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement.Corpus.C4 + +/-- SolidCore's core contract of c4's `Main`, as the type checker leaves it. -/ +def coreLit : Contract := + { storageFields := [{ name := "v", + slot := 0, + ty? := some (SolidCore.Solidity.Source.Ty.uint256), + layout? := some (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.uint256)), + transient := false, + packedOffset := 0, + packedBytes := 1, + packedSigned := false }, + { name := "w", + slot := 0, + ty? := some (SolidCore.Solidity.Source.Ty.uint256), + layout? := some (SolidCore.Solidity.Source.StorageLayout.scalar + (SolidCore.Solidity.Source.Ty.uint256)), + transient := false, + packedOffset := 1, + packedBytes := 1, + packedSigned := false }], + immutableFields := [], + eventDecls := [], + errorDecls := [], + functions := [{ name := "add", + selector? := some 33980010, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.add)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 8)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "v" + []) + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.bitXor)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 8)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "w" + []) + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.ref) + "v" + [])]]], + dispatchId? := none }, + { name := "__internal_add(uint8)#[SolidCore.Solidity.Ty.uint 8]", + selector? := none, + payable := false, + params := [{ name := "x", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + paramAbiCleanups := [SolidCore.Solidity.Source.AbiCleanup.uint 8], + returns := [{ name := "_ret0", ty := SolidCore.Solidity.Source.Ty.uint256, isStorageRef := false }], + body := SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.assign + (SolidCore.Solidity.Source.LValue.var "x") + (SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.skip, + SolidCore.Solidity.Source.Stmt.block + [SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.add)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 8)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "v" + []) + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.exprStmt + (SolidCore.Solidity.Source.Expr.assignment + (some (SolidCore.Solidity.Source.BinaryOp.bitXor)) + (some (SolidCore.Solidity.Source.ValueCleanup.uint 8)) + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.header) + "w" + []) + (SolidCore.Solidity.Source.Expr.var "x")), + SolidCore.Solidity.Source.Stmt.returnValues + [SolidCore.Solidity.Source.Expr.castOp + (SolidCore.Solidity.Source.CastKind.uintCleanup) + 8 + (SolidCore.Solidity.Source.Expr.storageRead + (SolidCore.Solidity.Source.StorageReadMode.ref) + "v" + [])]]], + dispatchId? := none }] } + +/-- `coreLit` is the refinement's print of the core, `Corpus.C4.coreLit`. -/ +theorem coreLit_eq : coreLit = Corpus.C4.coreLit := rfl + +/-- The storage the constructor leaves: `v = 0` in the low byte of slot 0, `w = 7` in the +next. -/ +def deployed : List (Nat × Nat) := [(0, 7 * 256)] + +/-- `add` as a Loom program over the storage: a dirty word reverts with empty data; else +`v` (the low byte of slot 0) plus `x` panics when it overflows `uint8`, and otherwise slot 0 +gets `v + x` in its low byte and `w ^ x` in the next, and the call returns `v + x`. -/ +def model (ws : List Nat) : SolM (List Nat) := + if ws.getD 0 0 < 2 ^ 8 then do + let s0 ← sload 0 + if s0 % 2 ^ 8 + ws.getD 0 0 < 2 ^ 8 then do + sstore 0 (s0 / 2 ^ 16 * 2 ^ 16 + (s0 / 2 ^ 8 % 2 ^ 8 ^^^ ws.getD 0 0) * 2 ^ 8 + + (s0 % 2 ^ 8 + ws.getD 0 0)) + pure (word (s0 % 2 ^ 8 + ws.getD 0 0)) + else revert (panic 0x11) + else revert [] + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs `add` on any argument word, from the deployed storage, as `model` does. -/ +theorem run_add {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d deployed) (w : U256) : + Source.run fuel c (callAt Bytecode.C4.Main.addSelector [w] deployed) = + some (observe (slotValue deployed) (model [w.toNat] (slotValue deployed))) := by + rw [run_eq_at hd] + have hev := hd.events + have hnone : ∀ k, k ≠ 0 → d.storage.get? k = none := fun k hk => by + rw [Std.HashMap.get?_eq_getElem?] + exact hd.getElem?_eq_none (by simp [deployed]; omega) + simp only [hcore, List.map_cons, List.map_nil, deployed, List.foldl_cons, List.foldl_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.C4.Main.addSelector, + get?_insert] + all_goals + have hw := w.isLt + generalize BitVec.toNat w = x at * + simp only [Nat.reducePow] at hw + · have h1 : (1792 + x) % 2 ^ 256 = 1792 + x := Nat.mod_eq_of_lt (by omega) + simp only [Nat.reducePow] at h1 + have h2 : (1792 + x) / 256 % 256 = 7 := by omega + have h3 : 1792 + x - 7 * 256 = x := by omega + have h4 : (7 ^^^ x) < 256 := Nat.xor_lt_two_pow (n := 8) (by omega) (by omega) + simp only [h1, h2, h3] + simp [Source.observe, observe, model, sload, sstore, bind, StateT.bind, pure, StateT.pure, + Except.bind, Except.pure, slotValue, callAt, State.loadSlot, StorageMap.lookup?, get?_insert, + hev, State.logEntries, *, Nat.mod_eq_of_lt, word] + funext slot + simp only [Std.HashMap.getElem?_insert, Shared.norm, Shared.wordModulus, beq_iff_eq] + try rw [show EvmYul.UInt256.size = 2 ^ 256 from rfl] + generalize slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = k + by_cases h : k = 0 + · subst h; simp; rw [Nat.add_comm] + · have h' : ¬0 = k := fun e => h e.symm + have := hnone k h + rw [Std.HashMap.get?_eq_getElem?] at this + simp [h, h', this] + · simp [Source.observe, observe, model, revert, slotValue, callAt, State.loadSlot, + StorageMap.lookup?, get?_insert, hev, State.logEntries, *] + funext k + simp only [slotValue, List.foldl_cons, List.foldl_nil] + +/-- The calls of the specification: `add` on any argument word, clean or dirty, from the +deployed storage, the scope of c4's refinement (`Corpus.C4.refines_full`). -/ +def scope : Call → Prop := fullScope fns deployed + +/-- No precondition beyond the scope. -/ +def pre : Call → Prop := fun _ => True + +/-- `add(x)` from the deployed storage (`v = 0`, `w = 7`): on a clean `x < 2 ^ 8` it returns +`v + x = x` and leaves slot 0 holding `v' = x` in its low byte and `w' = 7 ^ x` in the next, +every other slot 0; on a dirty word it reverts with empty data and keeps the storage. It +emits no logs. -/ +def post (call : Call) (obs : Observable) : Prop := + let x := (argWords 1 call).getD 0 0 + (if x < 2 ^ 8 then + obs.success = true ∧ obs.output = word x ∧ + ∀ slot, obs.storage slot = if slot % 2 ^ 256 = 0 then x + (7 ^^^ x) * 2 ^ 8 else 0 + else + obs.success = false ∧ obs.output = [] ∧ ∀ slot, obs.storage slot = slotValue deployed slot) ∧ + obs.logs = [] + +/-- The checked contract has the core `coreLit`, and its constructor leaves exactly +`deployed` and no logs: `Corpus.C4.shape_of`, the kernel's conversion check of the type +checker's output (`kernel_rfl`). -/ +theorem shape_of {c : TypeCheck.CheckedContract} (hc : contract? = .ok c) : + c.core = coreLit ∧ deployedStorage fuel c = some deployed ∧ + deployedAt fuel c deployed = true := by + obtain ⟨hk, hs, he⟩ := Corpus.C4.shape_of hc + exact ⟨hk.trans coreLit_eq.symm, hs, he⟩ + +/-- `model` implements SolidCore's `Main` on every call of the scope. -/ +theorem implements {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d deployed) : Implements fuel c scope (argWords 1) model := + implements_of_run' (by simp [fns]) fun fn hfn ws hl => by + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w, _ | _⟩ <;> simp at hl + exact run_add hcore hd w + +/-- The verification conditions of `add`, by Loom's weakest preconditions. -/ +theorem vcs : ∀ call, scope call → pre call → vc model (argWords 1) post call := by + sc_vcgen [scope, fns, model, post, deployed] + +/-- **The specification of `c4`'s `add`**, as a triple against SolidCore. -/ +theorem spec : ∃ c, contract? = .ok c ∧ deployedStorage fuel c = some deployed ∧ + Triple fuel c scope pre post := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, hs, hdep⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployedAt_of hdep + exact ⟨c, hc, hs, triple_of_wp (implements hk hd) vcs⟩ + +/-- The specification of `c4`'s `add` as `Satisfies` on SolidCore. -/ +theorem satisfies : ∃ c, contract? = .ok c ∧ deployedStorage fuel c = some deployed ∧ + Satisfies (solidCore fuel) c scope pre post := by + obtain ⟨c, hc, hs, h⟩ := spec + exact ⟨c, hc, hs, satisfies_of_triple h⟩ + +/-! ## From any storage + +specAt states the specification on scopeAt, every call of add with no value from any storage σ +that gives slot 0 a word (an entry whose key is 0 modulo 2 ^ 256), the slot v and w share. +SolidCore runs a call from σ written over the deployed storage (run_eq_at), so a storage without +an entry for slot 0 would read the constructor's word 7 * 256 there, which the call's storage +does not show; every other slot reads as σ's, since the constructor writes slot 0 alone. +postAt is the model's outcome from σ: with s0 = slotValue σ 0, a clean x < 2 ^ 8 returns +v + x = s0 % 2 ^ 8 + x and leaves slot 0 with its high bytes kept, w ^ x in its second byte and +v + x in its low byte when v + x fits in uint8, and otherwise reverts with Panic(0x11); a dirty +word reverts with empty data. A revert keeps σ, and no call logs. -/ + +/-- The last write of a slot among σ, over any earlier word, is slotValue's when σ writes the +slot. -/ +theorem foldl_some_of_mem (σ : List (Nat × Nat)) (q : Nat) (hq : q < 2 ^ 256) (a : Option Nat) + (b : Nat) (h : a = some b ∨ ∃ kv ∈ σ, kv.1 % 2 ^ 256 = q) : + σ.foldl (fun acc kv => if Shared.norm kv.1 = q then some (Shared.norm kv.2) else acc) a = + some (σ.foldl (fun acc kv => if kv.1 % 2 ^ 256 = q % 2 ^ 256 then kv.2 % 2 ^ 256 else acc) b) := by + induction σ generalizing a b with + | nil => + rcases h with h | ⟨_, h, _⟩ + · simpa using h + · simp at h + | cons kv σ ih => + simp only [List.foldl_cons] + apply ih + by_cases hk : kv.1 % 2 ^ 256 = q + · left + rw [ite_eq_left_of_eq_true _ _ (eq_true (show Shared.norm kv.1 = q from hk)), + ite_eq_left_of_eq_true _ _ (eq_true (show kv.1 % 2 ^ 256 = q % 2 ^ 256 by + rw [Nat.mod_eq_of_lt hq]; exact hk))] + rfl + · rw [ite_eq_right_of_eq_false _ _ (eq_false (show ¬ Shared.norm kv.1 = q from hk)), + ite_eq_right_of_eq_false _ _ (eq_false (show ¬ kv.1 % 2 ^ 256 = q % 2 ^ 256 by + rw [Nat.mod_eq_of_lt hq]; exact hk))] + rcases h with h | ⟨kv', h', hq'⟩ + · exact Or.inl h + · rcases List.mem_cons.1 h' with rfl | h' + · exact absurd hq' hk + · exact Or.inr ⟨kv', h', hq'⟩ + +theorem model_dirty (x : Nat) (s : Storage) (hx : ¬ x < 256) : model [x] s = .error [] := by + simp [model, hx, revert] + +theorem model_panic (x : Nat) (s : Storage) (hx : x < 256) (h : ¬ s 0 % 256 + x < 256) : + model [x] s = .error (panic 0x11) := by + simp [model, hx, h, revert, sload, bind, StateT.bind, Except.bind] + +theorem model_ok (x : Nat) (s : Storage) (hx : x < 256) (h : s 0 % 256 + x < 256) : + model [x] s = .ok (word (s 0 % 256 + x), fun k => if k % 2 ^ 256 = 0 then + (s 0 / 65536 * 65536 + (s 0 / 256 % 256 ^^^ x) * 256 + (s 0 % 256 + x)) % 2 ^ 256 + else s k) := by + simp [model, hx, h, sload, sstore, bind, StateT.bind, Except.bind, pure, StateT.pure, Except.pure] + +/-- The calls of add on any argument word, with no value, from any storage that writes slot 0. -/ +def scopeAt : Call → Prop := fun call => ∃ σ, (∃ kv ∈ σ, kv.1 % 2 ^ 256 = 0) ∧ fullScope fns σ call + +/-- The deployed scope is the scope from any storage at the deployed storage, which writes +slot 0. -/ +theorem scopeAt_of_scope {call : Call} (h : scope call) : scopeAt call := + ⟨deployed, ⟨(0, 7 * 256), List.mem_singleton_self _, rfl⟩, h⟩ + +/-- add(x) from the storage of the call, with s0 its slot 0: v + x = s0 % 2 ^ 8 + x returned and +slot 0 holding s0's high bytes, w ^ x and v + x when x is clean and v + x fits in uint8, a +Panic(0x11) revert when it does not, and a revert with empty data on a dirty word. A revert +keeps the storage, and no call logs. -/ +def postAt (call : Call) (obs : Observable) : Prop := + let x := (argWords 1 call).getD 0 0 + let s0 := slotValue call.storage 0 + (if x < 2 ^ 8 then + if s0 % 2 ^ 8 + x < 2 ^ 8 then + obs.success = true ∧ obs.output = word (s0 % 2 ^ 8 + x) ∧ + ∀ slot, obs.storage slot = if slot % 2 ^ 256 = 0 then + s0 / 2 ^ 16 * 2 ^ 16 + (s0 / 2 ^ 8 % 2 ^ 8 ^^^ x) * 2 ^ 8 + (s0 % 2 ^ 8 + x) + else slotValue call.storage slot + else + obs.success = false ∧ obs.output = panic 0x11 ∧ + ∀ slot, obs.storage slot = slotValue call.storage slot + else + obs.success = false ∧ obs.output = [] ∧ ∀ slot, obs.storage slot = slotValue call.storage slot) ∧ + obs.logs = [] + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs add on any argument word, from any storage σ that writes slot 0, as model +does. -/ +theorem run_add_at {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d deployed) (w : U256) (σ : List (Nat × Nat)) + (hσ : ∃ kv ∈ σ, kv.1 % 2 ^ 256 = 0) : + Source.run fuel c (callAt Bytecode.C4.Main.addSelector [w] σ) = + some (observe (slotValue σ) (model [w.toNat] (slotValue σ))) := by + rw [run_eq_at hd] + have hev := hd.events + have hm0 : (σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage)[0]? = + some (slotValue σ 0) := by + rw [getElem?_foldl_insertLoop] + exact foldl_some_of_mem σ 0 (by decide) _ 0 (Or.inr hσ) + have hmk : ∀ k, k % 2 ^ 256 ≠ 0 → + ((σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage)[k % 2 ^ 256]?).getD 0 = + slotValue σ k := by + intro k hk + rw [getElem?_foldl_insertLoop, hd.getElem?_eq_none (by simp [deployed]; omega)] + exact getD_foldl σ k none 0 rfl + generalize σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage = m at hm0 hmk + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.C4.Main.addSelector, hm0] + all_goals + have hw := w.isLt + have hs := slotValue_lt σ 0 + generalize BitVec.toNat w = x at * + simp only [Nat.reducePow] at hw hs + · -- Panic(0x11): v + x overflows uint8. + rw [model_panic x _ (by omega) (by omega)] + simp [Source.observe, observe, callAt, panic, word] + · -- v + x fits. + rw [model_ok x _ (by omega) (by omega)] + generalize slotValue σ 0 = s0 at * + have hA : (s0 % 2 ^ 256 - s0 % 256 + (s0 + x) % 256) % 2 ^ 256 = s0 + x := by omega + have hW : (s0 + x) / 256 % 256 = s0 / 256 % 256 := by omega + have hO : (s0 + x - s0 / 256 % 256 * 256) % 256 = s0 % 256 + x := by omega + simp only [Nat.reducePow] at hA + simp only [hA, hW, hO] + have hy : (s0 / 256 % 256 ^^^ x) < 256 := Nat.xor_lt_two_pow (n := 8) (by omega) (by omega) + generalize (s0 / 256 % 256 ^^^ x) = y at * + have hB : s0 + x - s0 / 256 % 256 * 256 + y * 256 = + s0 / 65536 * 65536 + y * 256 + (s0 % 256 + x) := by omega + simp only [hB] + simp [Source.observe, observe, State.loadSlot, StorageMap.lookup?, State.logEntries, word] + funext slot + have hk := hmk slot + simp only [Std.HashMap.getElem?_insert, Shared.norm, Shared.wordModulus, beq_iff_eq, + EvmYul.UInt256.size, Nat.reducePow] at hk ⊢ + generalize slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = k at hk ⊢ + by_cases h : k = 0 + · subst h + simp + · have h' : ¬0 = k := fun e => h e.symm + rw [← hk h] + simp only [h, h', ↓reduceIte] + cases m[k]? <;> rfl + · -- A dirty word reverts with no data. + rw [model_dirty x _ (by omega)] + simp [Source.observe, observe, callAt] + +/-- model implements SolidCore's Main on every call of scopeAt. -/ +theorem implementsAt {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d deployed) : Implements fuel c scopeAt (argWords 1) model := by + rintro call ⟨σ, hσ, hs⟩ + refine implements_of_run' (s := σ) (by simp [fns]) (fun fn hfn ws hl => ?_) call hs + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w, _ | _⟩ <;> simp at hl + exact run_add_at hcore hd w σ hσ + +/-- The verification conditions of add from any storage, from model's outcomes. -/ +theorem vcsAt : ∀ call, scopeAt call → pre call → vc model (argWords 1) postAt call := by + rintro call ⟨σ, -, hs⟩ hp + refine vcs_of_fullScope (fns := fns) (s := σ) (n := 1) (by simp [fns]) ?_ call hs hp + intro fn hfn call args hcall hw hlen hargs hinit _ + subst hcall + match args, hlen with + | [x], _ => + have hx : x < 2 ^ 256 := hargs x (by simp) + have hs0 := slotValue_lt σ 0 + rw [wp_eq] + simp only [postAt, hw, List.getD_cons_zero] + by_cases h1 : x < 256 + · by_cases h2 : slotValue σ 0 % 256 + x < 256 + · rw [model_ok x _ h1 h2] + simp only [Nat.reducePow, h1, h2, ↓reduceIte, true_and] + refine ⟨fun slot => ?_, trivial⟩ + split + · exact Nat.mod_eq_of_lt (by + have := Nat.xor_lt_two_pow (n := 8) (x := slotValue σ 0 / 256 % 256) (y := x) + (by omega) (by omega) + omega) + · rfl + · rw [model_panic x _ h1 h2] + simp [h1, h2] + · rw [model_dirty x _ h1] + simp [h1] + +/-- **The specification of c4's add from any storage**, as a triple against SolidCore. -/ +theorem specAt : ∃ c, contract? = .ok c ∧ Triple fuel c scopeAt pre postAt := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, _, hdep⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployedAt_of hdep + exact ⟨c, hc, triple_of_wp (implementsAt hk hd) vcsAt⟩ + +/-- The specification from any storage as Satisfies on SolidCore. -/ +theorem satisfiesAt : ∃ c, contract? = .ok c ∧ Satisfies (solidCore fuel) c scopeAt pre postAt := by + obtain ⟨c, hc, h⟩ := specAt + exact ⟨c, hc, satisfies_of_triple h⟩ + +end SolidCore.Verify.C4 diff --git a/Verify/CounterBump.lean b/Verify/CounterBump.lean new file mode 100644 index 00000000..09fb7d72 --- /dev/null +++ b/Verify/CounterBump.lean @@ -0,0 +1,110 @@ +import Verify.Abi + +/-! +# Counter's `bump(n)`: a loop proved with Loom's invariant and variant rule + +`bump` of `crates/verify/examples/Counter.sol` (solar), with `count` in slot 0 and `limit` +in slot 1: + + function bump(uint256 n) external { + require(count + n <= limit, "over"); + /// @custom:invariant i <= n + /// @custom:invariant count == old(count) + i + /// @custom:decreases n - i + for (uint256 i = 0; i < n; i++) { count++; } + } + +`model` is the function as a `SolM` program: the checked `count + n` of the `require` panics +with `Panic(0x11)` when it overflows, the `require` reverts with `Error("over")`, and the loop +is `whileM` over `i` with the checked `count++` in its body. The loop is given `n + 1` +iterations, more than its variant `n - i` allows, so it never runs out (`triple_whileM`). + +`bump_spec` proves the annotated specification from the annotated invariant and variant with +Loom's loop rule: from storage whose `count` is a word, a call either returns with `count` +increased by `n` and every other slot unchanged, or reverts with `Error("over")` when +`count + n > limit`, or with `Panic(0x11)` when `count + n` overflows. `bump_vc` is the same +statement as the verification condition `vc` of `Verify.Basic` against the observable. +-/ + +namespace SolidCore.Verify.CounterBump + +open SolidCore.Refinement + +/-- The revert data of `require(..., msg)`: `Error(string)` with `msg`. -/ +def errorString (msg : String) : List Nat := + let bytes := msg.toUTF8.toList.map (·.toNat) + (EthLib.Base.natToBytes 4 0x08c379a0).map (·.toNat) ++ word 32 ++ word bytes.length ++ + bytes ++ List.replicate ((32 - bytes.length % 32) % 32) 0 + +/-- One iteration: the checked `count++`, then `i++`. -/ +def body (i : Nat) : SolM Nat := do + let c ← sload 0 + if c + 1 < 2 ^ 256 then pure () else revert (panic 0x11) + sstore 0 (c + 1) + pure (i + 1) + +/-- `bump(n)` as a `SolM` program. -/ +def model (n : Nat) : SolM (List Nat) := do + let c ← sload 0 + let lim ← sload 1 + if c + n < 2 ^ 256 then pure () else revert (panic 0x11) + if c + n ≤ lim then pure () else revert (errorString "over") + let _ ← whileM (fun i => decide (i < n)) body (n + 1) 0 + pure [] + +/-- The loop's invariant, from the annotations, with what the loop must keep about the +storage: `i <= n`, `count == old(count) + i`, the other slots unchanged, and the bound the +`require` established. -/ +def inv (n : Nat) (s : Storage) (i : Nat) : Assn := fun _ s' => + i ≤ n ∧ s' 0 = s 0 + i ∧ (∀ k, k % 2 ^ 256 ≠ 0 → s' k = s k) ∧ + s 0 + n < 2 ^ 256 + +/-- The annotated variant. -/ +def variant (n : Nat) (i : Nat) : Nat := n - i + +theorem body_step (n : Nat) (s : Storage) (i : Nat) (hi : decide (i < n) = true) : + triple (inv n s i) (body i) (fun i' => inv n s i' ⊓ ⌜variant n i' < variant n i⌝) := by + have hlt : i < n := by simpa using hi + intro herr s' ⟨hle, hc, hframe, hbound⟩ + simp only [body, wp_bind, wp_sload, wp_ite, wp_pure, wp_revert, wp_sstore] + have h1 : s' 0 + 1 < 2 ^ 256 := by omega + simp only [h1, ite_true] + refine ⟨⟨by omega, ?_, ?_, hbound⟩, ?_⟩ + · simp only [ite_true] + rw [Nat.mod_eq_of_lt h1]; omega + · intro k hk + simp only [Nat.zero_mod, hk, ite_false] + exact hframe k hk + · show (⌜variant n (i + 1) < variant n i⌝ : Assn) herr _ + have hv : variant n (i + 1) < variant n i := by simp only [variant]; omega + simp only [LE.pure, hv]; trivial + +/-- `bump`'s specification, proved with Loom's loop rule from the annotated invariant and +variant. -/ +theorem bump_spec (n : Nat) (s : Storage) (herr : Revert → Prop) + (hover : s 0 + n < 2 ^ 256 → ¬ s 0 + n ≤ s 1 → herr (errorString "over")) + (hpanic : ¬ s 0 + n < 2 ^ 256 → herr (panic 0x11)) : + wp (model n) + (fun _ _ s' => s' 0 = s 0 + n ∧ ∀ k, k % 2 ^ 256 ≠ 0 → s' k = s k) + herr s := by + simp only [model, wp_bind, wp_sload, wp_ite, wp_pure, wp_revert] + by_cases hb : s 0 + n < 2 ^ 256 + · simp only [hb, ite_true] + by_cases hl : s 0 + n ≤ s 1 + · simp only [hl, ite_true] + have hloop := triple_whileM (fun i => decide (i < n)) body (inv n s) (variant n) + (body_step n s) (n + 1) 0 (by simp [variant]) + have h0 : inv n s 0 herr s := ⟨Nat.zero_le _, by simp, fun _ _ => rfl, hb⟩ + have := wp_cons _ _ (fun (_ : Nat) => fun (_ : Revert → Prop) s' => + s' 0 = s 0 + n ∧ ∀ k, k % 2 ^ 256 ≠ 0 → s' k = s k) ?_ herr s (hloop herr s h0) + · simpa [wp_pure] using this + · intro i herr' s' ⟨⟨hle, hc, hframe, _⟩, hdone⟩ + have hni : n ≤ i := by + by_contra hne + have : decide (i < n) = true := by simp; omega + simp [LE.pure, this] at hdone + exact ⟨by rw [hc]; congr 1; omega, hframe⟩ + · simp only [hl, ite_false]; exact hover hb hl + · simp only [hb, ite_false]; exact hpanic hb + +end SolidCore.Verify.CounterBump diff --git a/Verify/Discharge.lean b/Verify/Discharge.lean new file mode 100644 index 00000000..2e817a04 --- /dev/null +++ b/Verify/Discharge.lean @@ -0,0 +1,21 @@ +import Verify.Obligation +import Verify.Discharge.Lemmas +import Verify.Discharge.Search +import Verify.Discharge.Valid +import Verify.Discharge.Sat +import Verify.Discharge.Leaf +import Verify.Discharge.Lite + +/-! Kernel-checked certificates for exported obligations. A VC counts as discharged only when a +certificate the Lean kernel checks proves `ob.Valid` (Verify/Obligation/Vc.lean), and the proof +uses only the axioms `propext`, `Classical.choice` and `Quot.sound`. The backends are: + +- `vc_smt` (Verify/Discharge/Reconstruct, a package of its own) reconstructs a cvc5 proof step + by step as a Lean term. +- `vc_valid` (`Search`, `Valid`) builds the proof itself; its leaves are `omega` and + `vc_ground`, which decides closed hypotheses by kernel evaluation (`Sat.Ground`, `Leaf`). +- `cert`: a theorem written for the obligation, such as one under Contracts//, named in + a certificate list; its proof may check an LRAT certificate with `Sat` (`check_sound`). + +The driver, Verify/Discharge/discharge.sh, states every obligation itself and applies every +check to every backend alike; see Verify/Discharge/README.md. -/ diff --git a/Verify/Discharge/IteApply.lean b/Verify/Discharge/IteApply.lean new file mode 100644 index 00000000..6ea991f0 --- /dev/null +++ b/Verify/Discharge/IteApply.lean @@ -0,0 +1,35 @@ +import Lean + +/-! +# Applying a conditional array + +An exported store into a nested array evaluates to a function whose value at a key is a +conditional between two functions, applied to the inner key: `(if c then f else g) x`. The +condition's instance then decides the proposition `vc_eval` started from (an equality of +`Srt.beq`), not the one `simp` rewrote it to, so no `simp` lemma over `ite` unifies with it. +`iteFunApply` matches the term's shape instead and pushes the argument in, with the proof +`ite_fun_apply` at the term's own instance; the kernel checks that instance's type up to +unfolding. +-/ + +namespace SolarVerify.Discharge + +theorem ite_fun_apply {α : Sort u} {β : Sort v} {c : Prop} {h : Decidable c} (f g : α → β) + (x : α) : (@ite (α → β) c h f g) x = @ite β c h (f x) (g x) := by + cases h <;> rfl + +open Lean Meta Simp in +/-- `(if c then f else g) x` to `if c then f x else g x`, at the term's own instance. -/ +simproc_decl iteFunApply (@ite (_ → _) _ _ _ _ _) := fun e => do + unless e.isAppOfArity ``ite 6 do return .continue + let args := e.getAppArgs + let .forallE _ α β _ ← whnfD args[0]! | return .continue + if β.hasLooseBVars then return .continue + let uα ← getLevel α + let uβ ← getLevel β + let (c, h, f, g, x) := (args[1]!, args[2]!, args[3]!, args[4]!, args[5]!) + let pf := mkAppN (mkConst ``ite_fun_apply [uα, uβ]) #[α, β, c, h, f, g, x] + let rhs := mkAppN (mkConst ``ite [uβ]) #[β, c, h, (mkApp f x).headBeta, (mkApp g x).headBeta] + return .visit { expr := rhs, proof? := some pf } + +end SolarVerify.Discharge diff --git a/Verify/Discharge/Leaf.lean b/Verify/Discharge/Leaf.lean new file mode 100644 index 00000000..60e8b241 --- /dev/null +++ b/Verify/Discharge/Leaf.lean @@ -0,0 +1,42 @@ +import Verify.Discharge.Search +import Verify.Discharge.Sat.Ground +import Verify.Discharge.Nonlinear + +/-! The search's leaves (`vc_leaf`, Search.lean): besides `omega`, a goal one of whose closed +hypotheses the kernel decides to be false is closed by `vc_ground` (Sat/Ground.lean). Lean tries +the rules from the last one added, so `vc_ground` runs first and fails at once when no hypothesis +is closed; `omega` then gets the goal unchanged. -/ + +macro_rules | `(tactic| vc_leaf) => `(tactic| vc_ground) + +namespace SolarVerify.Discharge + +/-- The search's goals spell SMT-LIB's `div` and `mod` as `Int.ediv` and `Int.emod`, which +`omega` reads as atoms; these turn them back into `/` and `%`, which it understands. -/ +theorem ediv_eq_div (a b : Int) : a.ediv b = a / b := rfl + +theorem emod_eq_mod (a b : Int) : a.emod b = a % b := rfl + +end SolarVerify.Discharge + +/-! A goal with `div` or `mod` gets `omega` after `ediv_eq_div` and `emod_eq_mod`; without them +`simp` fails and the rules above take the goal unchanged. -/ + +/-- `omega` after reading `Int.ediv` and `Int.emod` as `/` and `%`. -/ +macro "vc_div_omega" : tactic => `(tactic| ( + simp only [SolarVerify.Discharge.ediv_eq_div, SolarVerify.Discharge.emod_eq_mod] at * + omega)) + +macro_rules | `(tactic| vc_leaf) => `(tactic| vc_div_omega) + +/-! A goal with a product of variables or a division by one gets `omega` with the facts +`vc_nl_facts` adds (Nonlinear.lean); without such a term `vc_nl_facts` fails and the rules above +take the goal unchanged. -/ + +/-- `omega` with the nonlinear facts of Nonlinear.lean. -/ +macro "vc_nl_omega" : tactic => `(tactic| ( + try simp only [SolarVerify.Discharge.ediv_eq_div, SolarVerify.Discharge.emod_eq_mod] at * + vc_nl_facts + omega)) + +macro_rules | `(tactic| vc_leaf) => `(tactic| vc_nl_omega) diff --git a/Verify/Discharge/Lemmas.lean b/Verify/Discharge/Lemmas.lean new file mode 100644 index 00000000..b8c97ee5 --- /dev/null +++ b/Verify/Discharge/Lemmas.lean @@ -0,0 +1,65 @@ +/- +Lemmas the discharge tactic (`SolarVerify.Discharge`) builds proofs from. Nothing an obligation +means depends on this file. +-/ +namespace SolarVerify.Discharge + +/-! Rewrites the tactic uses; `omega` reads disjunctions but not implications. -/ + +theorem imp_iff_not_or (a b : Prop) : (a → b) ↔ ¬a ∨ b := + ⟨fun h => (Classical.em a).elim (fun ha => .inr (h ha)) .inl, + fun h ha => h.elim (fun hn => absurd ha hn) id⟩ + +theorem ite_pos {α : Type} {c : Prop} {_ : Decidable c} (h : c) (a b : α) : ite c a b = a := by + simp [h] + +theorem ite_neg {α : Type} {c : Prop} {_ : Decidable c} (h : ¬c) (a b : α) : ite c a b = b := by + simp [h] + +/-! Congruence, as disjunctions `omega` can case on (Ackermann's reduction). -/ + +theorem congr1 {β : Type} (f : Int → β) (a b : Int) : ¬a = b ∨ f a = f b := + (Classical.em (a = b)).elim (fun h => .inr (h ▸ rfl)) .inl + +theorem congr2 {β : Type} (f : Int → Int → β) (a b c d : Int) : + ¬a = c ∨ ¬b = d ∨ f a b = f c d := + (Classical.em (a = c)).elim + (fun h => (Classical.em (b = d)).elim (fun h' => .inr (.inr (h ▸ h' ▸ rfl))) (fun h' => .inr (.inl h'))) + .inl + +theorem congr3 {β : Type} (f : Int → Int → Int → β) (a b c d e g : Int) : + ¬a = d ∨ ¬b = e ∨ ¬c = g ∨ f a b c = f d e g := + (Classical.em (a = d)).elim + (fun h => (Classical.em (b = e)).elim + (fun h' => (Classical.em (c = g)).elim (fun h'' => .inr (.inr (.inr (h ▸ h' ▸ h'' ▸ rfl)))) + (fun h'' => .inr (.inr (.inl h'')))) + (fun h' => .inr (.inl h'))) + .inl + +theorem true_eq_iff (b : Bool) : (true = b) ↔ (b = true) := ⟨Eq.symm, Eq.symm⟩ + +theorem false_eq_iff (b : Bool) : (false = b) ↔ (b = false) := ⟨Eq.symm, Eq.symm⟩ + +/-- `decide` at any instance, such as the classical one quantifiers evaluate with. -/ +theorem decide_any_eq_true {p : Prop} {_ : Decidable p} : (decide p = true) = p := by simp + +/-- The classical `if` a quantifier evaluates with, as a function of its condition alone, so +`simp` can rewrite the condition without a `Decidable` instance for the new one. -/ +noncomputable def qite {α : Type} (p : Prop) (a b : α) : α := @ite α p (Classical.propDecidable p) a b + +/-- The classical `decide` a quantifier evaluates with. -/ +noncomputable def qdec (p : Prop) : Bool := @decide p (Classical.propDecidable p) + +theorem qite_true {α : Type} (a b : α) : qite True a b = a := by simp [qite] +theorem qite_false {α : Type} (a b : α) : qite False a b = b := by simp [qite] +theorem qdec_eq_true (p : Prop) : (qdec p = true) = p := by simp [qdec] + +/-- Every `if` as a `qite`, whose condition `simp` rewrites like any other proposition. -/ +theorem ite_eq_qite {α : Type} {c : Prop} {_ : Decidable c} (a b : α) : ite c a b = qite c a b := by + unfold qite; split <;> simp_all + +theorem qite_pos {α : Type} {c : Prop} (h : c) (a b : α) : qite c a b = a := by simp [qite, h] + +theorem qite_neg {α : Type} {c : Prop} (h : ¬c) (a b : α) : qite c a b = b := by simp [qite, h] + +end SolarVerify.Discharge diff --git a/Verify/Discharge/Lite.lean b/Verify/Discharge/Lite.lean new file mode 100644 index 00000000..43161d33 --- /dev/null +++ b/Verify/Discharge/Lite.lean @@ -0,0 +1,31 @@ +import Verify.Discharge.Valid +import Verify.Discharge.Leaf + +/-! # A direct leaf for shallow obligations + +`vc_lite` closes an obligation whose hypotheses are equations defining its symbols and linear or +Newton-step facts, without the search: after `vc_valid_prep` it substitutes the defining equations, +reads SMT-LIB's Boolean connectives and `div`/`mod` as Lean's (a division by a divisor `omega` +shows nonzero as the plain quotient), adds Nonlinear.lean's facts and +calls `omega`; failing that, it first settles the remaining `if`s from the hypotheses (`simp_all`). +On the Uniswap V2 `Math.sqrt` exports the search instead exceeds `simp`'s step bound on the same +goals. It is tried before `vc_valid`'s search, and fails at once (an `omega` failure, never a +timeout) where it does not apply, leaving the goal to the search. +-/ + +/-- The leaf of `vc_lite`: `omega` with Nonlinear.lean's facts, then the same after settling the +remaining `if`s, then the same after splitting on the condition of every `if`. -/ +macro "vc_lite_leaf" : tactic => `(tactic| first + | ((try vc_nl_facts) <;> omega) + | ((try simp_all only [ite_true, ite_false]) <;> (try vc_nl_facts) <;> omega) + | ((vc_split_ite <;> repeat' vc_split_ite) <;> (try simp only [Bool.and_eq_false_iff, Bool.not_eq_false', Bool.not_eq_true', Bool.and_eq_true, Bool.or_eq_true, decide_eq_false_iff_not, decide_eq_true_eq, or_true, true_or, or_false, false_or, not_true_eq_false, not_false_eq_true, not_or, Classical.not_not, and_true, true_and] at *) <;> (try vc_nl_facts) <;> omega)) + +/-- The direct leaf: see the module comment. -/ +macro "vc_lite" : tactic => `(tactic| (vc_valid_prep <;> (subst_vars; (try simp only [ + SolarVerify.Discharge.ediv_eq_div, + SolarVerify.Discharge.emod_eq_mod, Int.reduceEq, decide_false, Bool.not_false, Bool.and_true, + decide_eq_true_eq, ite_false, ite_true, Bool.not_eq_true, Bool.and_eq_true, decide_eq_true_iff, + Bool.false_eq_true, or_false, SolarVerify.Discharge.true_eq_iff, Bool.or_eq_true, not_or, + not_and, Bool.not_eq_true', decide_eq_false_iff_not] at *); (try (vc_fun_defs; subst_vars; simp only [SolarVerify.Discharge.iteFunApply, Bool.and_eq_true, decide_eq_true_eq] at *)); (try simp only [Classical.not_forall, Classical.not_imp, not_and] at *); (try vc_open_exists); (try simp only [Bool.and_eq_false_iff, Bool.not_eq_false', Bool.not_eq_true', Bool.and_eq_true, Bool.or_eq_true, decide_eq_false_iff_not, decide_eq_true_eq, or_true, true_or, or_false, false_or, not_true_eq_false, not_false_eq_true, not_or, Classical.not_not, and_true, true_and] at *); (try simp (disch := omega) only [SolarVerify.Discharge.Nonlinear.ite_div_of_ne] at *); all_goals vc_lite_leaf))) + +macro_rules | `(tactic| vc_valid) => `(tactic| vc_lite) diff --git a/Verify/Discharge/Nonlinear.lean b/Verify/Discharge/Nonlinear.lean new file mode 100644 index 00000000..bfc0c118 --- /dev/null +++ b/Verify/Discharge/Nonlinear.lean @@ -0,0 +1,349 @@ +import Lean + +/-! +# Nonlinear facts for the search's leaves + +`omega` reads a product of two variables, or a division by a variable, as an atom it knows +nothing about. `vc_nl_facts` adds, for the terms of the context, facts proved once here that +relate those atoms to the rest, so that `omega` can finish: + +* for every square `P * P`: `2 * P - 1 ≤ P * P` and `4 * P - 4 ≤ P * P` (from + `0 ≤ (P - k) * (P - k)`); +* for every `y / x` with `x` not a literal: `x * (y / x) ≤ y < x * (y / x) + x` when `1 ≤ x`, and + when also `0 ≤ y`: `0 ≤ y / x ≤ y`, `1 ≤ y / x` when `x ≤ y`, `y / x = 0` when `y < x`; +* for every Newton step `(y / x + x) / 2` of the integer square root: the step's successor + squared exceeds `y` (the arithmetic-geometric mean inequality), and the step is below `x` + unless `x * x ≤ y`. + +Every fact is a theorem below, so a leaf closed this way is closed by `omega` from true premises; +`discharge.sh` checks each proof's axioms in any case. +-/ + +namespace SolarVerify.Discharge.Nonlinear + +theorem sq_nonneg (a : Int) : 0 ≤ a * a := by + rcases Int.le_total 0 a with h | h + · exact Int.mul_nonneg h h + · rw [← Int.neg_mul_neg]; exact Int.mul_nonneg (by omega) (by omega) + +theorem sq_ge_one (P : Int) : 2 * P - 1 ≤ P * P := by + have h := sq_nonneg (P - 1) + simp only [Int.sub_mul, Int.mul_sub, Int.mul_one, Int.one_mul] at h + omega + +theorem sq_ge_two (P : Int) : 4 * P - 4 ≤ P * P := by + have h := sq_nonneg (P - 2) + simp only [Int.sub_mul, Int.mul_sub] at h + have : (2 : Int) * P = P * 2 := Int.mul_comm 2 P + omega + +theorem div_bounds (y x : Int) : ¬ 1 ≤ x ∨ (x * (y / x) ≤ y ∧ y < x * (y / x) + x) := by + refine Classical.or_iff_not_imp_left.mpr fun hx => ?_ + have hx : 1 ≤ x := Classical.not_not.mp hx + have h1 := Int.emod_def y x + have h2 := Int.emod_nonneg y (by omega : x ≠ 0) + have h3 := Int.emod_lt_of_pos y (by omega : 0 < x) + omega + + +/-- The quotient of a nonnegative `y` by a positive `x`: nonnegative, at most `y`, at least 1 when +`x ≤ y`, and 0 when `y < x`. -/ +theorem div_facts (y x : Int) : ¬ 1 ≤ x ∨ ¬ 0 ≤ y ∨ + (0 ≤ y / x ∧ y / x ≤ y ∧ (¬ x ≤ y ∨ 1 ≤ y / x) ∧ (¬ y < x ∨ y / x = 0)) := by + refine Classical.or_iff_not_imp_left.mpr fun hx => Classical.or_iff_not_imp_left.mpr fun hy => ?_ + have hx : 1 ≤ x := Classical.not_not.mp hx + have hy : 0 ≤ y := Classical.not_not.mp hy + have hb := (div_bounds y x).resolve_left (by omega) + have hq0 : 0 ≤ y / x := Int.ediv_nonneg hy (by omega) + have hxq : 1 * (y / x) ≤ x * (y / x) := Int.mul_le_mul_of_nonneg_right hx hq0 + rw [Int.one_mul] at hxq + refine ⟨hq0, by omega, ?_, ?_⟩ + · refine Classical.or_iff_not_imp_left.mpr fun hxy => ?_ + have hxy : x ≤ y := Classical.not_not.mp hxy + refine Classical.byContradiction fun hc => ?_ + have h0 : y / x = 0 := by omega + rw [h0, Int.mul_zero] at hb + omega + · refine Classical.or_iff_not_imp_left.mpr fun hlt => ?_ + have hlt : y < x := Classical.not_not.mp hlt + refine Classical.byContradiction fun hc => ?_ + have h1 : 1 ≤ y / x := by omega + have := Int.mul_le_mul_of_nonneg_left h1 (by omega : 0 ≤ x) + rw [Int.mul_one] at this + omega + +theorem newton_lt (y x : Int) : + ¬ 1 ≤ x ∨ ¬ 0 ≤ y ∨ y < ((y / x + x) / 2 + 1) * ((y / x + x) / 2 + 1) := by + refine Classical.or_iff_not_imp_left.mpr fun hx => Classical.or_iff_not_imp_left.mpr fun hy => ?_ + have hx : 1 ≤ x := Classical.not_not.mp hx + have hy : 0 ≤ y := Classical.not_not.mp hy + have h2 := ((div_bounds y x).resolve_left (by omega)).2 + have hq0 : 0 ≤ y / x := Int.ediv_nonneg hy (by omega) + generalize hq : y / x = q at * + generalize hm : (q + x) / 2 + 1 = m + have hm2 : q + 1 + x ≤ 2 * m := by omega + have hsq : (q + 1 + x) * (q + 1 + x) ≤ (2 * m) * (2 * m) := + Int.mul_le_mul hm2 hm2 (by omega) (by omega) + have e : (2 * m) * (2 * m) = 2 * (2 * (m * m)) := by + rw [Int.mul_assoc, Int.mul_left_comm m 2 m] + rw [e] at hsq + have hamgm := sq_nonneg (q + 1 - x) + simp only [Int.add_mul, Int.mul_add, Int.sub_mul, Int.mul_sub, Int.mul_one, Int.one_mul] at hsq hamgm + have c1 : q * x = x * q := Int.mul_comm q x + omega + +theorem newton_le (y x : Int) : ¬ 1 ≤ x ∨ ¬ x ≤ (y / x + x) / 2 ∨ x * x ≤ y := by + refine Classical.or_iff_not_imp_left.mpr fun hx => Classical.or_iff_not_imp_left.mpr fun h => ?_ + have hx : 1 ≤ x := Classical.not_not.mp hx + have h : x ≤ (y / x + x) / 2 := Classical.not_not.mp h + have h1 := ((div_bounds y x).resolve_left (by omega)).1 + have hq : x ≤ y / x := by omega + have := Int.mul_le_mul_of_nonneg_left hq (by omega : 0 ≤ x) + omega + +/-- Comparing a quotient with a bound `k` is comparing `y` with `x * k`. -/ +theorem div_ge_iff (y x k : Int) (hx : 1 ≤ x) : + (k ≤ y / x → x * k ≤ y) ∧ (y / x < k → y < x * k) := by + have hb := (div_bounds y x).resolve_left (by omega) + refine ⟨fun hk => ?_, fun hk => ?_⟩ + · have := Int.mul_le_mul_of_nonneg_left hk (by omega : 0 ≤ x) + omega + · have hk' : y / x + 1 ≤ k := by omega + have := Int.mul_le_mul_of_nonneg_left hk' (by omega : 0 ≤ x) + rw [Int.mul_add, Int.mul_one] at this + omega + +/-- A square's successor expanded. -/ +theorem sq_succ (a : Int) : (a + 1) * (a + 1) = a * a + 2 * a + 1 := by + simp only [Int.add_mul, Int.mul_add, Int.mul_one, Int.one_mul] + omega + +/-- The quotient `y / x` against `2`, `x`, `x + 1`, `x + 2` and `x + 3`, read as linear facts over the atom +`x * x` (the comparisons the integer square root's Newton steps need). -/ +theorem div_cmp (y x : Int) : ¬ 1 ≤ x ∨ + ((y < x * x ∨ x ≤ y / x) ∧ (x * x ≤ y ∨ y / x < x) ∧ + (y < x * x + x ∨ x + 1 ≤ y / x) ∧ (x * x + x ≤ y ∨ y / x < x + 1) ∧ + (y < x * x + 2 * x ∨ x + 2 ≤ y / x) ∧ (x * x + 2 * x ≤ y ∨ y / x < x + 2) ∧ + (y < x * x + 3 * x ∨ x + 3 ≤ y / x) ∧ (x * x + 3 * x ≤ y ∨ y / x < x + 3) ∧ + (y < 2 * x ∨ 2 ≤ y / x) ∧ (2 * x ≤ y ∨ y / x < 2) ∧ + (x + 1) * (x + 1) = x * x + 2 * x + 1 ∧ 4 * x - 4 ≤ x * x ∧ 2 * x - 1 ≤ x * x) := by + refine Classical.or_iff_not_imp_left.mpr fun hx => ?_ + have hx : 1 ≤ x := Classical.not_not.mp hx + have h0 := div_ge_iff y x x hx + have h1 := div_ge_iff y x (x + 1) hx + have h2 := div_ge_iff y x (x + 2) hx + have h3 := div_ge_iff y x (x + 3) hx + have h4 := div_ge_iff y x 2 hx + rw [Int.mul_comm x 2] at h4 + rw [Int.mul_add, Int.mul_one] at h1 + rw [Int.mul_add] at h2 + have e : x * 2 = 2 * x := Int.mul_comm x 2 + rw [e] at h2 + rw [Int.mul_add] at h3 + have e3 : x * 3 = 3 * x := Int.mul_comm x 3 + rw [e3] at h3 + have s1 := sq_ge_one x + have s2 := sq_ge_two x + have s3 := sq_succ x + refine ⟨?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, s3, s2, s1⟩ + · exact Classical.or_iff_not_imp_left.mpr fun h => Classical.byContradiction fun h' => h (h0.2 (by omega)) + · exact Classical.or_iff_not_imp_right.mpr fun h => h0.1 (by omega) + · exact Classical.or_iff_not_imp_left.mpr fun h => Classical.byContradiction fun h' => h (h1.2 (by omega)) + · exact Classical.or_iff_not_imp_right.mpr fun h => h1.1 (by omega) + · exact Classical.or_iff_not_imp_left.mpr fun h => Classical.byContradiction fun h' => h (h2.2 (by omega)) + · exact Classical.or_iff_not_imp_right.mpr fun h => h2.1 (by omega) + · exact Classical.or_iff_not_imp_left.mpr fun h => Classical.byContradiction fun h' => h (h3.2 (by omega)) + · exact Classical.or_iff_not_imp_right.mpr fun h => h3.1 (by omega) + · exact Classical.or_iff_not_imp_left.mpr fun h => Classical.byContradiction fun h' => h (h4.2 (by omega)) + · exact Classical.or_iff_not_imp_right.mpr fun h => h4.1 (by omega) + +/-- A Newton step from `x ≥ 1` on `y ≥ 4` stays at least 2 (from `newton_lt`). -/ +theorem newton_ge_two (y x : Int) : ¬ 1 ≤ x ∨ ¬ 4 ≤ y ∨ 2 ≤ (y / x + x) / 2 := by + refine Classical.or_iff_not_imp_left.mpr fun hx => Classical.or_iff_not_imp_left.mpr fun hy => ?_ + have hx : 1 ≤ x := Classical.not_not.mp hx + have hy : 4 ≤ y := Classical.not_not.mp hy + have h := ((newton_lt y x).resolve_left (by omega)).resolve_left (by omega) + have hq0 : 0 ≤ y / x := Int.ediv_nonneg (by omega) (by omega) + have hn0 : 0 ≤ (y / x + x) / 2 := by omega + generalize (y / x + x) / 2 = n at * + refine Classical.byContradiction fun hc => ?_ + have : n = 0 ∨ n = 1 := by omega + rcases this with rfl | rfl <;> simp at h <;> omega + +/-- SMT-LIB's total division, `if x = 0 then divZero y else y / x`, is `y / x` off zero. -/ +theorem ite_div (x a y : Int) (inst : Decidable (x = 0)) : + x = 0 ∨ @ite Int (x = 0) inst a (y / x) = y / x := by + refine Classical.or_iff_not_imp_left.mpr fun h => ?_ + exact @if_neg (x = 0) inst h Int a (y / x) + +/-- `ite_div` as a rewrite, for `simp` with a discharger that proves `x ≠ 0`. -/ +theorem ite_div_of_ne {x a y : Int} [Decidable (x = 0)] (h : ¬ x = 0) : + (if x = 0 then a else y / x) = y / x := if_neg h + +open Lean Meta Elab Tactic + +/-- Whether `e` is a numeral. -/ +def isNumeral (e : Expr) : Bool := + e.isAppOfArity ``OfNat.ofNat 3 || e.nat?.isSome || e.int?.isSome + +/-- Whether `e` is the numeral 2. -/ +def isTwo (e : Expr) : Bool := + e.nat? == some 2 || e.int? == some 2 || + (e.isAppOfArity ``OfNat.ofNat 3 && (e.getArg! 1).rawNatLit? == some 2) + +/-- Whether `e` is the numeral 1. -/ +def isOne (e : Expr) : Bool := + e.nat? == some 1 || e.int? == some 1 || + (e.isAppOfArity ``OfNat.ofNat 3 && (e.getArg! 1).rawNatLit? == some 1) + +/-- The facts the terms of `e` call for: a lemma and its arguments. -/ +partial def scan (e : Expr) (acc : Array (Name × Array Expr)) : MetaM (Array (Name × Array Expr)) := do + let mut acc := acc + if !e.hasLooseBVars then + -- SMT-LIB's total division: `if x = 0 then a else y / x` + if e.isAppOfArity ``ite 5 then + let c := e.getArg! 1 + let b := e.getArg! 4 + if c.isAppOfArity ``Eq 3 && b.isAppOfArity ``HDiv.hDiv 6 && b.getArg! 5 == c.getArg! 1 then + acc := acc.push (``ite_div, #[c.getArg! 1, e.getArg! 3, b.getArg! 4, e.getArg! 2]) + if e.isAppOfArity ``HDiv.hDiv 6 && (e.getArg! 0).isConstOf ``Int then + let a := e.getArg! 4 + let b := e.getArg! 5 + if !isNumeral b then + acc := acc.push (``div_bounds, #[a, b]) + acc := acc.push (``div_facts, #[a, b]) + acc := acc.push (``div_cmp, #[a, b]) + else if a.isAppOfArity ``HAdd.hAdd 6 && isTwo b then + let l := a.getArg! 4 + let r := a.getArg! 5 + if l.isAppOfArity ``HDiv.hDiv 6 && l.getArg! 5 == r then + acc := acc.push (``newton_lt, #[l.getArg! 4, r]) + acc := acc.push (``newton_le, #[l.getArg! 4, r]) + acc := acc.push (``newton_ge_two, #[l.getArg! 4, r]) + else if e.isAppOfArity ``HMul.hMul 6 && (e.getArg! 0).isConstOf ``Int && e.getArg! 4 == e.getArg! 5 then + acc := acc.push (``sq_ge_one, #[e.getArg! 4]) + acc := acc.push (``sq_ge_two, #[e.getArg! 4]) + let p := e.getArg! 4 + if p.isAppOfArity ``HAdd.hAdd 6 && isOne (p.getArg! 5) then + acc := acc.push (``sq_succ, #[p.getArg! 4]) + match e with + | .app f a => scan a (← scan f acc) + | .lam _ t b _ | .forallE _ t b _ => scan b (← scan t acc) + | .mdata _ b => scan b acc + | _ => pure acc + +/-- Adds the nonlinear facts the context's terms call for; fails when there are none. -/ +def addFacts : TacticM Unit := withMainContext do + let g ← getMainGoal + let mut acc := #[] + acc ← scan (← instantiateMVars (← g.getType)) acc + for d in ← getLCtx do + if d.isImplementationDetail then continue + if ← isProp d.type then acc ← scan (← instantiateMVars d.type) acc + let mut seen : Array Expr := #[] + let mut g := g + for (n, args) in acc do + let pf ← mkAppM n args + if seen.contains pf then continue + seen := seen.push pf + let (_, g') ← (← g.assert `nl (← inferType pf) pf).intro1P + g := g' + if seen.isEmpty then throwError "vc_nl_facts: no nonlinear term" + replaceMainGoal [g] + +/-- Adds the facts above for the terms of the context (see the module comment). -/ +elab "vc_nl_facts" : tactic => addFacts + +/-- The condition of an `if` over a non-proposition in `e` (not a division's zero test), if any. -/ +partial def findIteCond (e : Expr) : MetaM (Option Expr) := do + if !e.hasLooseBVars && e.isAppOfArity ``ite 5 then + let c := e.getArg! 1 + let isDivZero := c.isAppOfArity ``Eq 3 && (e.getArg! 4).isAppOfArity ``HDiv.hDiv 6 + if !isDivZero && !(← isProp (e.getArg! 0)) && !c.hasLooseBVars then return some c + match e with + | .app f a => match ← findIteCond f with | some c => pure (some c) | none => findIteCond a + | .lam _ t b _ | .forallE _ t b _ => + match ← findIteCond t with | some c => pure (some c) | none => findIteCond b + | .mdata _ b => findIteCond b + | _ => pure none + +/-- Splits on the condition `c` of an `if` in the context: the goal becomes `c ∨ ¬ c → G`. -/ +def splitIte : TacticM Unit := withMainContext do + let g ← getMainGoal + let mut cond ← findIteCond (← instantiateMVars (← g.getType)) + for d in ← getLCtx do + if cond.isSome then break + if d.isImplementationDetail then continue + if ← isProp d.type then cond ← findIteCond (← instantiateMVars d.type) + let some c := cond | throwError "vc_split_ite: no if" + let pf ← mkAppM ``Classical.em #[c] + replaceMainGoal [← g.assert `vc_ite_h (← inferType pf) pf] + +elab "vc_ite_em" : tactic => splitIte + +/-- Case split on the condition of an `if` in the context, which `simp` then removes. -/ +macro "vc_split_ite" : tactic => `(tactic| (vc_ite_em; rintro (hc | hc) <;> + (first | simp only [ite_cond_eq_true _ _ (eq_true hc)] at * | simp only [ite_cond_eq_false _ _ (eq_false hc)] at *) <;> + try subst_vars)) + +/-- A pointwise definition of a function symbol as an equation `subst` can use. -/ +theorem fun_eq_of_forall {α β : Sort _} {f : α → β} {g : α → β} (h : ∀ k, f k = g k) : + f = fun k => g k := funext h + +/-- A pointwise definition of a two-argument function symbol (a nested array). -/ +theorem fun_eq_of_forall2 {α β γ : Sort _} {f : α → β → γ} {g : α → β → γ} (h : ∀ k j, f k j = g k j) : + f = fun k j => g k j := funext fun k => funext (h k) + +/-- Turns each hypothesis `h : ∀ k, f k = e[k]` with `f` a local variable into `f = fun k => e[k]`. -/ +def funDefs : TacticM Unit := withMainContext do + let mut changed := false + for d in ← getLCtx do + if d.isImplementationDetail then continue + let ty ← instantiateMVars d.type + let .forallE n dom body _ := ty | continue + -- two levels: `∀ k j, f k j = e[k, j]` + if let .forallE n2 dom2 body2 _ := body then + if body2.isAppOfArity ``Eq 3 && !dom2.hasLooseBVars then + let lhs := body2.getArg! 1 + if lhs.isApp && lhs.appArg! == .bvar 0 && lhs.appFn!.isApp && lhs.appFn!.appArg! == .bvar 1 && + lhs.appFn!.appFn!.isFVar && !(body2.getArg! 2).containsFVar lhs.appFn!.appFn!.fvarId! then + let rhsLam := Expr.lam n dom (Expr.lam n2 dom2 (body2.getArg! 2) .default) .default + let g ← getMainGoal + let pf ← mkAppOptM ``fun_eq_of_forall2 #[none, none, none, some lhs.appFn!.appFn!, some rhsLam, + some (.fvar d.fvarId)] + let g ← g.assert `vc_fdef (← inferType pf) pf + let (_, g) ← g.intro1P + let g ← g.tryClear d.fvarId + replaceMainGoal [g] + changed := true + continue + unless body.isAppOfArity ``Eq 3 do continue + let lhs := body.getArg! 1 + unless lhs.isApp && lhs.appArg! == .bvar 0 && lhs.appFn!.isFVar do continue + if (body.getArg! 2).containsFVar lhs.appFn!.fvarId! then continue + let rhsLam := Expr.lam n dom (body.getArg! 2) .default + let g ← getMainGoal + let pf ← mkAppOptM ``fun_eq_of_forall #[none, none, some lhs.appFn!, some rhsLam, some (.fvar d.fvarId)] + let g ← g.assert `vc_fdef (← inferType pf) pf + let (_, g) ← g.intro1P + let g ← g.tryClear d.fvarId + replaceMainGoal [g] + changed := true + unless changed do throwError "vc_fun_defs: none" + +elab "vc_fun_defs" : tactic => funDefs + +/-- Destructures every hypothesis that is an `∃` or an `∧`. -/ +partial def openExists : TacticM Unit := withMainContext do + for d in ← getLCtx do + if d.isImplementationDetail then continue + let ty ← instantiateMVars d.type + if ty.isAppOfArity ``Exists 2 || ty.isAppOfArity ``And 2 then + let gs ← (← getMainGoal).cases d.fvarId + replaceMainGoal (gs.map (·.mvarId)).toList + openExists + return + +elab "vc_open_exists" : tactic => openExists + +end SolarVerify.Discharge.Nonlinear diff --git a/Verify/Discharge/README.md b/Verify/Discharge/README.md new file mode 100644 index 00000000..6d387b02 --- /dev/null +++ b/Verify/Discharge/README.md @@ -0,0 +1,68 @@ +# Discharging solar-verify's VCs in the kernel + +`solar-verify --emit-lean DIR FILE.sol` (solar, `crates/verify`) writes each query it sends a +solver as a Lean term `ob : Obligation` whose `ob.Valid` (Verify/Obligation/Vc.lean) holds exactly +when the query is unsatisfiable. This directory decides which of them are proved. A VC is +accepted only when a certificate the Lean kernel checks proves `ob.Valid` and the proof uses no +axiom but `propext`, `Classical.choice` and `Quot.sound`; a solver's answer alone never counts. + +## Backends + +| Backend | What proves `ob.Valid` | Where | +| --- | --- | --- | +| `vc_smt` | cvc5 refutes the goal (in-process, through lean-cvc5's plugin) and lean-smt rebuilds its proof step by step as a Lean term; a step it cannot rebuild is a `sorryAx` and fails the row's axiom check | Reconstruct/ (a package of its own, so building this repository fetches no solver) | +| `vc_valid` | unfolds the obligation to a shallow goal and searches for a proof (case splits, congruence, `omega`, and `vc_ground`, which decides closed hypotheses by kernel evaluation) | Search.lean, Valid.lean, Leaf.lean, Sat/Ground.lean | +| `cert` | a theorem written for the obligation (such as one under Contracts//), named in a certificate list; its proof may check an LRAT certificate with `Sat` | DISCHARGE_CERTS | + +`Sat` (Cnf, Lrat, Load) checks LRAT refutations of CNF formulas in the kernel (`check_sound`); +test/sat/Sat.lean checks one. It reaches a VC only through a `cert` certificate: turning an +obligation into CNF needs a bit-blaster with a soundness proof, which is parked until a VC needs it. + +## Running + +```text +(cd Verify/Discharge/Reconstruct && lake build -KleanMemory=3000) +DISCHARGE_LOCK=Verify/Discharge/frozen/v2/.sha256 DISCHARGE_SOURCE_ROOT= \ + Verify/Discharge/discharge.sh DIR [TIMEOUT_SECONDS] +``` + +One runner, one library build (Reconstruct/, which compiles Verify/Obligation and +Verify/Discharge from this repository's sources), backends tried in the order +DISCHARGE_BACKENDS gives, default `smt=vc_smt;vc_valid=vc_valid`30`: cvc5 reconstruction first, +`vc_valid` as the fallback with 30 s. The script states every obligation itself +(`theorem obligation : .Valid := ...`), so every backend is checked against the exported +statement, and applies the same checks to all: the manifest format and version, the hashes of +Smt.lean and Vc.lean the export was written for, no unchecked construct in Verify/Obligation, +every required obligation present once, the inputs against DISCHARGE_LOCK, and per row the exit +status, errors, a timeout and the axioms `Lean.collectAxioms` reports. Backend sources are never +grepped: lean-smt's contain `sorry`, and only what a row's proof actually uses counts. + +It writes DIR/discharge/results.tsv (one row per obligation and backend tried) and summary.tsv +(per obligation, the backends that proved it, and `vacuous`), and exits 0 only when every +required obligation is proved. The `vacuous` column (DISCHARGE_VACUITY, on by default) tries +`{ ob with goal := .bool false }` with `vc_smt`: `yes` when the kernel proves it with clean axioms, +so the row's hypotheses are contradictory and it holds vacuously (the path it covers is +unreachable); `no` when cvc5 finds a model of the hypotheses; `unknown` otherwise. It never +changes a verdict. DISCHARGE_ALL=1 tries every backend on every obligation to measure coverage. +The header of discharge.sh lists the other settings. + +Version-1 exports (and the version-2 locks derived from them) say `import SolarVerify` and record the hash of +Vc.lean with its old first line; the script compiles them with `import Verify.Obligation` and +accepts either hash, nothing else. + +## Frozen inputs and negatives + +frozen/.sha256 and frozen/PINS are solar's version-1 locks of the Counter, Token, Vault and +ArrayMax exports, kept as they were. frozen/v2/ holds the version-2 locks, provisional (frozen/v2/PINS says +how they were made). test/negatives.sh corrupts one input at a time (an edited source, an edited +module, a deleted required obligation without a lock, a duplicated obligation, an absolute source +path, version 1) and requires each run to fail with its message before any Lean runs. +test/smt-negatives.sh edits one obligation at a time so that it no longer holds (Counter +increment's goal and the assertion defining the new count read as `+ 2`, Vault withdraw#0's +and ArrayMax max#8's goals negated) and requires every backend to fail on it by a counterexample +or an incomplete answer, never a timeout, while the same untouched rows are proved. + +## Results on the frozen version-2 locks + +results/v2/ holds the run of the default backends on the four locked exports +(results/v2/README.md). diff --git a/Verify/Discharge/Reconstruct/.gitignore b/Verify/Discharge/Reconstruct/.gitignore new file mode 100644 index 00000000..bfb30ec8 --- /dev/null +++ b/Verify/Discharge/Reconstruct/.gitignore @@ -0,0 +1 @@ +/.lake diff --git a/Verify/Discharge/Reconstruct/README.md b/Verify/Discharge/Reconstruct/README.md new file mode 100644 index 00000000..460c6c4f --- /dev/null +++ b/Verify/Discharge/Reconstruct/README.md @@ -0,0 +1,102 @@ +# Reconstructing cvc5 proofs of exported VCs + +This package proves the obligations `solar-verify --emit-lean` exports from cvc5's proofs, +reconstructed in Lean by [lean-smt](https://github.com/ufmg-smite/lean-smt) at 6b26285 (with +lean-cvc5 d19a134, Lean v4.35.0; see lake-manifest.json). It is a package of its own so that +building solidity-lean fetches no solver: it compiles Verify/Obligation and Verify/Discharge from +this repository's sources (`srcDir := "../../.."`) beside its tactic, and +Verify/Discharge/discharge.sh runs every backend, `vc_smt` and `vc_valid`, against this one build. +It was moved here from solar's `crates/verify/lean/reconstruct` (paradigmxyz/solar 9525e73c), +whose `reconstruct.sh` discharge.sh replaces. + +```bash +(cd Verify/Discharge/Reconstruct && lake build -KleanMemory=3000) # fetches lean-smt, lean-auto, lean-cvc5 +DISCHARGE_LOCK=Verify/Discharge/frozen/v2/Counter.sha256 DISCHARGE_SOURCE_ROOT= \ + Verify/Discharge/discharge.sh 120 +``` + +## How a proof is built + +`vc_smt` (Tactic.lean): + +1. `vc_valid_prep` (Verify/Discharge) evaluates `Obligation.Valid ob` symbolically into a + shallow goal: `False` under the script's assertions and the guard, over `Int`, `Bool` and + functions (arrays). +2. `vc_smt_norm` substitutes away local definitions and turns Booleans into propositions, + conditions of `if` included, so that the quantifiers the export evaluates classically + (`qdec (∀ x, …)`) reach cvc5 as quantified formulas. +3. lean-smt's `smt` translates the goal to SMT-LIB, runs cvc5 in-process (lean-cvc5's plugin, + which discharge.sh passes to `lean --plugin`) with proofs on, and replays cvc5's CPC proof + rule by rule as Lean tactics and lemma applications. cvc5 gets 60 s; `sat` or `unknown` + fails the proof. + +The result is an ordinary Lean proof term that the kernel checks. cvc5, lean-smt's tactic code +and the plugin are untrusted: they can only make a proof fail. lean-smt's own sources contain +`sorry` (such as its `eq_eq_beq` lemma), so no check reads them; a proof that reaches one, or +a step lean-smt cannot replay, has `sorryAx` among its axioms, and discharge.sh accepts a row +only when Lean exits cleanly and `collectAxioms` reports nothing beyond `propext`, +`Classical.choice` and `Quot.sound`. + +## What cvc5's proofs use + +cvc5 1.4.2 proves every `unsat` query of the four examples in 7–31 ms (`--produce-proofs`). +One ArrayMax query (`max`, a quantified loop invariant) is `unknown` to cvc5 alone; after +`vc_smt_norm` the corresponding obligation is proved. + +CPC proofs (all 4 examples, 52 unsat queries), rules by frequency: + +``` +cong:1239 trans:1083 eq_resolve:689 nary_cong:661 refl:655 arith_poly_norm:623 +arith_poly_norm_rel:349 aci_norm:214 evaluate:200 scope:172 symm:146 +bool-double-not-elim:131 and_elim:122 arith-elim-leq:118 chain_m_resolution:104 +arith-leq-norm:81 arith-elim-lt:79 process_scope:77 arith-geq-tighten:65 and_intro:53 +reordering:46 modus_ponens:41 bool-and-de-morgan:39 arith_mult_neg:35 true_elim:32 +not_and:28 implies_elim:28 contra:26 arith_sum_ub:24 resolution:22 bool-impl-elim:22 +cnf_or_neg:22 eq-refl:21 int_tight_ub:17 cnf_and_pos:15 arith-elim-gt:13 exists-elim:9 +skolem_intro:8 ite_eq:8 ite_elim2:8 arith_trichotomy:7 ite_elim1:6 false_intro:6 +skolemize:6 instantiate:6 array-read-over-write:5 cnf_or_pos:5 true_intro:4 eq-symm:4 +array-read-over-write-split:3 equiv_elim1:2 bool-eq-false:2 arith-geq-norm1-int:2 +false_elim:2 cnf_and_neg:2 not_implies_elim2:2 not_implies_elim1:2 arrays_read_over_write:2 +chain_resolution:1 not_not_elim:1 bool-eq-true:1 bool-impl-false1:1 int_tight_lb:1 +quant-unused-vars:1 bool-or-taut:1 ite-else-true:1 eq-ite-lift:1 +``` + +The fragment is QF_UFLIA plus quantifiers over `Int` and `Int → Int` arrays: congruence and +equality reasoning, `arith_poly_norm`/`arith_poly_norm_rel` (polynomial normalisation), +Farkas-style `arith_sum_ub`/`arith_mult_*`/`int_tight_*`, the RARE rewrites +(`arith-elim-*`, `bool-*`), CNF and resolution, `skolemize`/`skolem_intro`/`exists-elim` +and `instantiate` for the quantifiers, and `array-read-over-write(-split)`. lean-smt replays +all of them. The arrays reach cvc5 as functions after `vc_valid_prep` beta-reduces `store`, +so the theory of arrays is used only where the export keeps an array equality. + +Alethe proofs of the same queries are not usable as certificates: cvc5 1.4.2 writes 2,889 +`hole` steps across them (the steps it cannot express in Alethe, mostly normalisation and +rewrites), which a checker would have to trust. CPC has none. + +## Bit-vectors: not covered yet + +None of the four examples has a bit-vector; `bvlower` emits them only for bitwise operations +and casts (`tests/cases/rewrites.sol`, `speclang.sol`). On these +lean-smt does not yet produce clean proofs: + +- bit-blasting steps (`bv_bitblast_step`) are left as unsolved goals even at width 8, and + lean-smt's `eq_eq_beq`, which the bit-blasting replay uses, is itself a `sorry`; +- mixed terms `(bv2nat x)` fail translation (`BitVec w has variable width`), and `2^256` + written as a power fails (`incorrect number of universe levels instPowNat`); +- cvc5's default bit-blasting proof of a 256-bit `bv2nat (bvand x c)` query does not finish in + 120 s. With `--solve-bv-as-int=sum` it is `unsat` at once with a 32 KB arithmetic proof, + but that proof has 2 `trust INT_BLASTER` steps (the translation of each bit-vector term into + integers), which would need reconstructing. + +So bit-vector VCs need either a reconstruction of the int-blaster's steps (lemmas such as +`(x &&& c).toNat = …` for constant masks, provable in the kernel), or VCs that keep such +terms in `Int` before they reach a solver. Pure bit-vector identities (`f &&& g = g &&& f` at +width 256) already reconstruct cleanly through cvc5's rewrite rules. + +## Scaling + +Per obligation the cost is Lean start-up and the import of lean-smt (about 1.3 s), cvc5 +(milliseconds), and the replay, which grows with the proof: the largest CPC proof among the +examples is 65 KB (ArrayMax) and replays in about 1.5 s. Obligations are independent, so they +run in parallel. What does not scale today is the bit-vector fragment above, and replay of +`arith_poly_norm` on wide nonlinear terms, which lean-smt does by normalising in Lean. diff --git a/Verify/Discharge/Reconstruct/Tactic.lean b/Verify/Discharge/Reconstruct/Tactic.lean new file mode 100644 index 00000000..58072735 --- /dev/null +++ b/Verify/Discharge/Reconstruct/Tactic.lean @@ -0,0 +1,42 @@ +import Verify.Discharge +import Smt + +/-! +`vc_smt` proves an exported obligation `Obligation.Valid ob` from a cvc5 proof: + +1. `vc_valid_prep` (Verify/Discharge) reduces it to a shallow goal `False` over Int, Bool and + functions; +2. `vc_smt_norm` substitutes away the definitions `x = t` of local symbols and turns Booleans, + conditions of `if` included, into propositions, so that a quantifier the export evaluates + classically (`qdec (∀ x, …)`) reaches cvc5 as a quantified formula rather than an opaque Bool; +3. lean-smt's `smt` asks cvc5 for a refutation of the hypotheses and reconstructs its proof + (CPC rules) as a Lean proof term, step by step. cvc5 gets 60 seconds; `unknown` fails the proof. + +The kernel checks the term; cvc5 and lean-smt's tactic code are not trusted. A step lean-smt cannot +reconstruct becomes a hole (`sorryAx`), which discharge.sh rejects by its per-row axiom check, so the proof fails closed. +-/ + +namespace SolarVerify.Reconstruct + +/-- An `if` at any instance is the classical one, whose condition `simp` can rewrite without a +`Decidable` instance for the result (such as a condition with a quantifier). -/ +theorem ite_eq_qite {α : Type} (c : Prop) [h : Decidable c] (a b : α) : + @ite α c h a b = SolarVerify.Discharge.qite c a b := by + unfold SolarVerify.Discharge.qite; congr + +end SolarVerify.Reconstruct + +/-- Substitutes local definitions and turns Booleans into propositions: see the module comment. -/ +macro "vc_smt_norm" : tactic => `(tactic| ( + try subst_vars + try simp -failIfUnchanged only [SolarVerify.Reconstruct.ite_eq_qite] at * + try simp -failIfUnchanged only [Bool.and_eq_true, Bool.or_eq_true, Bool.not_eq_true', + Bool.not_eq_eq_eq_not, Bool.not_true, Bool.not_false, Bool.and_true, Bool.true_and, + Bool.and_false, Bool.false_and, Bool.or_true, Bool.true_or, Bool.or_false, Bool.false_or, + SolarVerify.Discharge.decide_any_eq_true, SolarVerify.Discharge.qdec_eq_true, + decide_eq_true_eq, decide_eq_false_iff_not, Bool.decide_and, Bool.decide_or, + decide_not, Bool.eq_false_iff, ne_eq, SolarVerify.Discharge.true_eq_iff, + SolarVerify.Discharge.false_eq_iff] at * + try simp -failIfUnchanged only [SolarVerify.Discharge.qite] at *)) + +macro "vc_smt" : tactic => `(tactic| (vc_valid_prep <;> (intros; vc_smt_norm; smt (timeout := .some 60) [*]))) diff --git a/Verify/Discharge/Reconstruct/lake-manifest.json b/Verify/Discharge/Reconstruct/lake-manifest.json new file mode 100644 index 00000000..51c8f38d --- /dev/null +++ b/Verify/Discharge/Reconstruct/lake-manifest.json @@ -0,0 +1,46 @@ +{"version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": + [{"url": "https://github.com/ufmg-smite/lean-smt.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "6b26285ece45e38fc0d21809b944522233039829", + "name": "smt", + "manifestFile": "lake-manifest.json", + "inputRev": "6b26285ece45e38fc0d21809b944522233039829", + "inherited": false, + "configFile": "lakefile.lean"}, + {"url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "", + "rev": "dce0ad79c486cb1fb504af04f953c3466b0c6db8", + "name": "quote4", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.35.0", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/abdoo8080/lean-cvc5.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d19a134c237ec7f0cb86c2027062eedeb577a9a9", + "name": "cvc5", + "manifestFile": "lake-manifest.json", + "inputRev": "d19a134", + "inherited": true, + "configFile": "lakefile.lean"}, + {"url": "https://github.com/leanprover-community/lean-auto.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "30f46ddb9a68d6878f5a1337eb2565ba4e70126b", + "name": "auto", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.35.0", + "inherited": true, + "configFile": "lakefile.lean"}], + "name": "verify_reconstruct", + "lakeDir": ".lake", + "fixedToolchain": false} diff --git a/Verify/Discharge/Reconstruct/lakefile.lean b/Verify/Discharge/Reconstruct/lakefile.lean new file mode 100644 index 00000000..d3480b09 --- /dev/null +++ b/Verify/Discharge/Reconstruct/lakefile.lean @@ -0,0 +1,17 @@ +import Lake +open Lake DSL + +-- cvc5 proof reconstruction for exported VCs (`vc_smt`, Tactic.lean), a package of its own so +-- that building solidity-lean fetches no solver. It builds the obligation and discharge +-- modules from this repository's sources (srcDir "../../..") rather than requiring the root +-- package, whose Mathlib and EVM dependencies it does not need. discharge.sh runs every backend +-- (`vc_valid` and `vc_smt`) against this one build. +require smt from git "https://github.com/ufmg-smite/lean-smt.git" @ "6b26285ece45e38fc0d21809b944522233039829" + +package verify_reconstruct where + leanOptions := #[⟨`maxHeartbeats, (200000 : Nat)⟩, ⟨`backward.do.legacy, false⟩] + +@[default_target] +lean_lib VerifyReconstruct where + srcDir := "../../.." + roots := #[`Verify.Obligation, `Verify.Discharge, `Verify.Discharge.Reconstruct.Tactic] diff --git a/Verify/Discharge/Reconstruct/lean-toolchain b/Verify/Discharge/Reconstruct/lean-toolchain new file mode 100644 index 00000000..a6aff065 --- /dev/null +++ b/Verify/Discharge/Reconstruct/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.35.0 diff --git a/Verify/Discharge/Sat.lean b/Verify/Discharge/Sat.lean new file mode 100644 index 00000000..c0c8a560 --- /dev/null +++ b/Verify/Discharge/Sat.lean @@ -0,0 +1,4 @@ +import Verify.Discharge.Sat.Cnf +import Verify.Discharge.Sat.Lrat +import Verify.Discharge.Sat.Load +import Verify.Discharge.Sat.Ground diff --git a/Verify/Discharge/Sat/Cnf.lean b/Verify/Discharge/Sat/Cnf.lean new file mode 100644 index 00000000..dfaa48b1 --- /dev/null +++ b/Verify/Discharge/Sat/Cnf.lean @@ -0,0 +1,74 @@ +/-! +Propositional formulas in conjunctive normal form, with literals coded as natural numbers so +that the kernel evaluates them with its built-in arithmetic. + +This is the meaning of what `SolarVerify.Sat.Lrat` checks: a formula is unsatisfiable when every +assignment of its variables falsifies one of its clauses. +-/ +namespace SolarVerify.Sat + +/-- A literal: `2 * v` is variable `v`, and `2 * v + 1` its negation. -/ +abbrev Lit := Nat + +/-- A clause: the disjunction of its literals. -/ +abbrev Clause := List Lit + +/-- A formula: the conjunction of its clauses. -/ +abbrev Cnf := List Clause + +/-- A value for every variable. -/ +abbrev Assignment := Nat → Bool + +/-- The literal of variable `v` with polarity `pos`. -/ +def Lit.mk (v : Nat) (pos : Bool) : Lit := if pos then 2 * v else 2 * v + 1 + +/-- The negation of a literal. -/ +def Lit.neg (l : Lit) : Lit := bif Nat.beq (l % 2) 0 then l + 1 else l - 1 + +/-- The value of a literal. -/ +def Lit.eval (a : Assignment) (l : Lit) : Bool := if l % 2 = 0 then a (l / 2) else !a (l / 2) + +/-- The value of a clause: some literal is true. -/ +def Clause.eval (a : Assignment) (c : Clause) : Bool := c.any (Lit.eval a) + +/-- The value of a formula: every clause is true. -/ +def Cnf.eval (a : Assignment) (f : Cnf) : Bool := f.all (Clause.eval a) + +/-- No assignment satisfies the formula. -/ +def Cnf.Unsat (f : Cnf) : Prop := ∀ a, Cnf.eval a f = false + +theorem Lit.eval_neg (a : Assignment) (l : Nat) : Lit.eval a (Lit.neg l) = !Lit.eval a l := by + unfold Lit.eval Lit.neg + by_cases h : l % 2 = 0 + · have h1 : ¬ (l + 1) % 2 = 0 := by omega + have h2 : (l + 1) / 2 = l / 2 := by omega + simp [h, h1, h2] + · have h1 : (l - 1) % 2 = 0 := by omega + have h2 : (l - 1) / 2 = l / 2 := by omega + have hb : Nat.beq (l % 2) 0 = false := by + cases e : Nat.beq (l % 2) 0 + · rfl + · exact absurd (Nat.eq_of_beq_eq_true e) h + simp [hb, h, h1, h2] + +theorem Lit.eval_mk (a : Assignment) (v : Nat) (pos : Bool) : + Lit.eval a (Lit.mk v pos) = (a v == pos) := by + have h1 : 2 * v % 2 = 0 := by omega + have h2 : 2 * v / 2 = v := by omega + have h3 : ¬ (2 * v + 1) % 2 = 0 := by omega + have h4 : (2 * v + 1) / 2 = v := by omega + cases pos <;> cases h : a v <;> simp [Lit.mk, Lit.eval, h1, h2, h4, h] + +theorem Clause.eval_cons (a : Assignment) (l : Lit) (c : Clause) : + Clause.eval a (l :: c) = (Lit.eval a l || Clause.eval a c) := by + simp [Clause.eval] + +theorem Clause.eval_eq_true (a : Assignment) (c : Clause) : + Clause.eval a c = true ↔ ∃ l ∈ c, Lit.eval a l = true := by + simp [Clause.eval] + +theorem Cnf.eval_eq_true (a : Assignment) (f : Cnf) : + Cnf.eval a f = true ↔ ∀ c ∈ f, Clause.eval a c = true := by + simp [Cnf.eval] + +end SolarVerify.Sat diff --git a/Verify/Discharge/Sat/Ground.lean b/Verify/Discharge/Sat/Ground.lean new file mode 100644 index 00000000..285df597 --- /dev/null +++ b/Verify/Discharge/Sat/Ground.lean @@ -0,0 +1,73 @@ +import Lean +/-! +A leaf for the discharge search: hypotheses without free variables are decided by kernel +evaluation. + +After `vc_valid_prep`, a hypothesis built only from literals (such as one about +`(511#256 &&& 255#256).toNat`) still carries the casts `Val.as` leaves at bit-vector sorts and +`List.foldl` from n-ary operators, which `omega` cannot read. Their value needs no search: the +kernel computes it, reducing the casts over proofs of `s = s` as it reduces any `Eq.rec` whose +indices agree. + +`vc_ground` looks for a closed hypothesis `h : P` whose negation the kernel decides: +`decide (¬P)` must be definitionally `true` to the kernel itself (`Kernel.isDefEq`, not the +elaborator's reduction). It then closes the goal with `absurd h (of_decide_eq_true rfl)`, which +the kernel checks again when the theorem is added. Nothing runs natively and nothing joins the trusted base. +It fails, leaving the goal to the rest of the search, when no closed hypothesis is false. +-/ +namespace SolarVerify.Sat +open Lean Elab Tactic Meta + +/-- A `Decidable` instance the kernel reduces, built along `¬`, `∧`, `∨` and `=`; an equation +is decided by the instance of its type's weak head normal form, so that `Srt.Den .bool` reads as +`Bool`. -/ +partial def mkDecidable (p : Expr) : MetaM (Option Expr) := do + match_expr p with + | Not q => + let some d ← mkDecidable q | return none + return some (mkApp2 (mkConst ``instDecidableNot) q d) + | And a b => + let some da ← mkDecidable a | return none + let some db ← mkDecidable b | return none + return some (mkApp4 (mkConst ``instDecidableAnd) a b da db) + | Or a b => + let some da ← mkDecidable a | return none + let some db ← mkDecidable b | return none + return some (mkApp4 (mkConst ``instDecidableOr) a b da db) + | Eq ty a b => + let ty' ← whnfD ty + let some u ← (try pure (some (← getLevel ty')) catch _ => pure none) | return none + let some inst ← (try synthInstance? (mkApp (mkConst ``DecidableEq [u]) ty') catch _ => pure none) + | return none + return some (mkApp2 inst a b) + | _ => try synthInstance? (mkApp (mkConst ``Decidable) p) catch _ => pure none + +/-- `absurd h (of_decide_eq_true rfl)` for a closed hypothesis `h : P` that the kernel decides +false, or none. -/ +def refuteClosed (goalTy : Expr) (d : LocalDecl) : MetaM (Option Expr) := do + let ty ← instantiateMVars d.type + if ty.hasFVar || ty.hasMVar || ty.hasLooseBVars then return none + unless ← isProp ty do return none + let notTy := mkNot ty + let some inst ← mkDecidable notTy | return none + let inst ← instantiateMVars inst + let dec := mkApp2 (mkConst ``Decidable.decide) notTy inst + let ok ← try ofExceptKernelException (Kernel.isDefEq (← getEnv) {} dec (mkConst ``Bool.true)) + catch _ => pure false + unless ok do return none + let rflTrue := mkApp2 (mkConst ``Eq.refl [1]) (mkConst ``Bool) (mkConst ``Bool.true) + let hn := mkApp3 (mkConst ``of_decide_eq_true) notTy inst rflTrue + return some (mkApp4 (mkConst ``absurd [← getLevel goalTy]) ty goalTy d.toExpr hn) + +elab "vc_ground" : tactic => withMainContext do + let g ← getMainGoal + let goalTy ← g.getType + for d in ← getLCtx do + if d.isImplementationDetail then continue + if let some p ← refuteClosed goalTy d then + g.assign p + replaceMainGoal [] + return + throwError "vc_ground: no closed hypothesis is false" + +end SolarVerify.Sat diff --git a/Verify/Discharge/Sat/Load.lean b/Verify/Discharge/Sat/Load.lean new file mode 100644 index 00000000..5d660fa8 --- /dev/null +++ b/Verify/Discharge/Sat/Load.lean @@ -0,0 +1,218 @@ +import Lean +import Verify.Discharge.Sat.Lrat +/-! +Reading a DIMACS formula and a textual LRAT proof from files into terms the kernel checks. + +Nothing here is trusted: a wrong term only makes `check` return `false`. Long lists and the proof +become balanced trees of appends and `Proof.seq`, so the terms stay shallow. +-/ +namespace SolarVerify.Sat.Load +open Lean Elab Command Meta + +/-- The literal code of a nonzero DIMACS literal. -/ +def litOfInt (i : Int) : Nat := if i > 0 then 2 * i.toNat else 2 * i.natAbs + 1 + +def ints (line : String) : Except String (List Int) := + (line.splitOn " ").filter (· ≠ "") |>.mapM fun w => + match w.toInt? with + | some i => .ok i + | none => .error s!"not a number: {w}" + +/-- The clauses of a DIMACS file. -/ +def parseDimacs (s : String) : Except String (Array (List Nat)) := do + let mut out := #[] + let mut cur : List Nat := [] + for line in s.splitOn "\n" do + let line := line.trimAscii.toString + if line.isEmpty || line.startsWith "c" || line.startsWith "p" then continue + for i in ← ints line do + if i == 0 then + out := out.push cur.reverse + cur := [] + else + cur := litOfInt i :: cur + return out + +/-- The addition steps of a textual LRAT proof; deletions are skipped and RAT hints rejected. -/ +def parseLrat (s : String) : Except String (Array Step) := do + let mut out := #[] + for line in s.splitOn "\n" do + let line := line.trimAscii.toString + if line.isEmpty || line.startsWith "c" then continue + let ws := (line.splitOn " ").filter (· ≠ "") + if ws.length ≥ 2 && ws[1]! == "d" then continue + let xs ← ints line + match xs with + | [] => continue + | id :: rest => + let literals := rest.takeWhile (· ≠ 0) + let hints := (rest.dropWhile (· ≠ 0)).drop 1 |>.takeWhile (· ≠ 0) + if hints.any (· < 0) then throw s!"step {id}: RAT steps are not supported" + out := out.push { id := id.toNat, clause := literals.map litOfInt, hints := hints.map Int.toNat } + return out + +def listTy (ty : Expr) : Expr := mkApp (mkConst ``List [0]) ty + +/-- A list literal, as a balanced tree of appends above 64 elements. -/ +partial def mkList (ty : Expr) (xs : Array Expr) (lo hi : Nat) : Expr := + if hi - lo ≤ 64 then + (List.range (hi - lo)).foldr (init := mkApp (mkConst ``List.nil [0]) ty) fun i acc => + mkApp3 (mkConst ``List.cons [0]) ty xs[lo + i]! acc + else + let mid := (lo + hi) / 2 + mkApp3 (mkConst ``List.append [0]) ty (mkList ty xs lo mid) (mkList ty xs mid hi) + +def mkNatList (xs : List Nat) : Expr := + let a := xs.toArray.map mkRawNatLit + mkList (mkConst ``Nat) a 0 a.size + +def mkStep (s : Step) : Expr := + mkApp (mkConst ``Proof.step) <| + mkApp3 (mkConst ``Step.mk) (mkRawNatLit s.id) (mkNatList s.clause) (mkNatList s.hints) + +partial def mkProof (ss : Array Step) (lo hi : Nat) : Expr := + if hi - lo == 1 then mkStep ss[lo]! + else + let mid := (lo + hi) / 2 + mkApp2 (mkConst ``Proof.seq) (mkProof ss lo mid) (mkProof ss mid hi) + +def addDef (n : Name) (ty v : Expr) : CoreM Unit := + addDecl <| .defnDecl (mkDefinitionValEx n [] ty v (.regular 0) .safe []) + +/-- `sat_load n "f.cnf" "f.lrat"` defines `n.cnf : Cnf` and `n.proof : Proof` from the files, +relative to the current file. -/ +elab "sat_load " n:ident cnf:str lrat:str : command => do + let dir := (System.FilePath.mk (← getFileName)).parent.getD "." + let cs ← IO.FS.readFile (dir / cnf.getString) + let ps ← IO.FS.readFile (dir / lrat.getString) + let clauses ← match parseDimacs cs with | .ok c => pure c | .error e => throwError e + let steps ← match parseLrat ps with | .ok c => pure c | .error e => throwError e + if steps.isEmpty then throwError "the proof adds no clauses" + let base := (← getCurrNamespace) ++ n.getId + let cnfVal := mkList (listTy (mkConst ``Nat)) (clauses.map (mkNatList ·)) 0 clauses.size + liftCoreM do + addDef (base ++ `cnf) (mkConst ``Cnf) cnfVal + addDef (base ++ `proof) (mkConst ``Proof) (mkProof steps 0 steps.size) + logInfo m!"{clauses.size} clauses, {steps.size} proof steps" + + +/-! ## One declaration per step -/ + +def natE (n : Nat) : Expr := mkRawNatLit n +def boolTrue : Expr := mkConst ``Bool.true +def eqTrue (b : Expr) : Expr := mkApp3 (mkConst ``Eq [1]) (mkConst ``Bool) b boolTrue +def reflTrue : Expr := mkApp2 (mkConst ``Eq.refl [1]) (mkConst ``Bool) boolTrue +def clauseListTy : Expr := listTy (mkConst ``Clause) +def consE (ty x xs : Expr) : Expr := mkApp3 (mkConst ``List.cons [0]) ty x xs +def nilE (ty : Expr) : Expr := mkApp (mkConst ``List.nil [0]) ty + +/-- The formula as a balanced tree of appends over chunks of at most 16 clauses, each subtree its +own definition `base.cnfN` so that the kernel reads its type rather than inferring it again in +every lemma. Returns the subtree's constant and, for each of its clauses, a function giving the +proof that the clause is a member. -/ +partial def cnfTree (base : Name) (cs : Array Expr) (lo hi : Nat) : + StateT Nat CoreM (Expr × Array (Unit → Expr)) := do + let idx ← modifyGet fun n => (n, n + 1) + let name := base ++ Name.mkSimple s!"cnf{idx}" + let k := mkConst name + if hi - lo ≤ 16 then + let n := hi - lo + let mut acc : Array Expr := #[nilE (mkConst ``Clause)] + for j in [0:n] do + acc := acc.push (consE (mkConst ``Clause) cs[hi - 1 - j]! acc.back!) + let suffixes := acc.reverse -- suffixes[j] is the list from lo + j + liftM (addDef name clauseListTy suffixes[0]! : CoreM Unit) + let mems := (List.range n).toArray.map fun j => fun (_ : Unit) => Id.run do + let mut p := mkApp2 (mkConst ``SolarVerify.Sat.mem_head) cs[lo + j]! suffixes[j + 1]! + for k' in [0:j] do + let i := j - 1 - k' + p := mkApp4 (mkConst ``SolarVerify.Sat.mem_tail) cs[lo + j]! cs[lo + i]! suffixes[i + 1]! p + return p + return (k, mems) + else + let mid := (lo + hi) / 2 + let (l, ml) ← cnfTree base cs lo mid + let (r, mr) ← cnfTree base cs mid hi + liftM (addDef name clauseListTy (mkApp3 (mkConst ``List.append [0]) (mkConst ``Clause) l r) : CoreM Unit) + let ml' := (List.range ml.size).toArray.map fun i => fun (_ : Unit) => + mkApp4 (mkConst ``SolarVerify.Sat.mem_append_left) cs[lo + i]! l r (ml[i]! ()) + let mr' := (List.range mr.size).toArray.map fun i => fun (_ : Unit) => + mkApp4 (mkConst ``SolarVerify.Sat.mem_append_right) cs[mid + i]! l r (mr[i]! ()) + return (k, ml' ++ mr') + +def addThm (n : Name) (ty v : Expr) : CoreM Unit := + addDecl <| .thmDecl { name := n, levelParams := [], type := ty, value := v } + +/-- `∀ a, Cnf.eval a F = true → Clause.eval a c = true` -/ +def stepTy (F c : Expr) : Expr := + mkForall `a .default (mkConst ``Assignment) <| + mkForall `h .default (eqTrue (mkApp2 (mkConst ``Cnf.eval) (.bvar 0) F)) <| + eqTrue (mkApp2 (mkConst ``Clause.eval) (.bvar 1) c) + +def lamAH (F body : Expr) : Expr := + mkLambda `a .default (mkConst ``Assignment) <| + mkLambda `h .default (eqTrue (mkApp2 (mkConst ``Cnf.eval) (.bvar 0) F)) body + +/-- `sat_prove n "f.cnf" "f.lrat"` defines `n.cnf : Cnf` from the DIMACS file and proves +`n.unsat : n.cnf.Unsat` from the LRAT proof, one kernel-checked lemma per needed step. -/ +elab "sat_prove " n:ident cnf:str lrat:str : command => do + let dir := (System.FilePath.mk (← getFileName)).parent.getD "." + let cs ← IO.FS.readFile (dir / cnf.getString) + let ps ← IO.FS.readFile (dir / lrat.getString) + let clauses ← match parseDimacs cs with | .ok c => pure c | .error e => throwError e + let steps ← match parseLrat ps with | .ok c => pure c | .error e => throwError e + let some last := steps.findIdx? (·.clause.isEmpty) | throwError "the proof never adds the empty clause" + -- Keep only the steps the empty clause depends on. + let nIn := clauses.size + let mut byId : Std.HashMap Nat Nat := {} + for i in [0:last + 1] do byId := byId.insert steps[i]!.id i + let mut need : Std.HashSet Nat := {} + let mut needIn : Std.HashSet Nat := {} + let mut todo := [last] + need := need.insert last + while !todo.isEmpty do + let i := todo.head! + todo := todo.tail! + for h in steps[i]!.hints do + if h ≥ 1 && h ≤ nIn then needIn := needIn.insert h + else match byId[h]? with + | some j => if !need.contains j then need := need.insert j; todo := j :: todo + | none => throwError "step {steps[i]!.id}: unknown hint {h}" + let base := (← getCurrNamespace) ++ n.getId + let cExprs := clauses.map mkNatList + let ((fRoot, mems), _) ← liftCoreM <| (cnfTree base cExprs 0 nIn).run 0 + let F := mkConst (base ++ `cnf) + liftCoreM <| addDef (base ++ `cnf) (mkConst ``Cnf) fRoot + let lemmaOf (h : Nat) : Name := + if h ≤ nIn then base ++ Name.mkSimple s!"in{h}" else base ++ Name.mkSimple s!"s{h}" + -- Input clauses the proof uses. + for h in needIn.toArray.qsort (· < ·) do + let c := cExprs[h - 1]! + let v := lamAH F <| mkApp5 (mkConst ``Cnf.eval_mem) (.bvar 1) F c (.bvar 0) (mems[h - 1]! ()) + liftCoreM <| addThm (lemmaOf h) (stepTy F c) v + -- Derived clauses, in order. + let mut stepClause : Std.HashMap Nat Expr := {} + let mut count : Nat := 0 + for i in [0:last + 1] do + unless need.contains i do continue + let s := steps[i]! + let c := mkNatList s.clause + stepClause := stepClause.insert s.id c + let hcs := s.hints.toArray.map fun h => if h ≤ nIn then cExprs[h - 1]! else stepClause[h]! + -- suffix lists of hint clauses and the AllSat proof, from the end + let mut lst := nilE (mkConst ``Clause) + let mut prf := mkApp (mkConst ``AllSat.nil) (.bvar 1) + for j' in [0:hcs.size] do + let j := hcs.size - 1 - j' + let hp := mkApp2 (mkConst (lemmaOf s.hints[j]!)) (.bvar 1) (.bvar 0) + prf := mkApp5 (mkConst ``AllSat.cons) (.bvar 1) hcs[j]! lst hp prf + lst := consE (mkConst ``Clause) hcs[j]! lst + let v := lamAH F <| mkApp5 (mkConst ``rup_clause) (.bvar 1) c lst reflTrue prf + liftCoreM <| addThm (lemmaOf s.id) (stepTy F c) v + count := count + 1 + let emptyLemma := mkConst (lemmaOf steps[last]!.id) + liftCoreM <| addThm (base ++ `unsat) (mkApp (mkConst ``Cnf.Unsat) F) + (mkApp2 (mkConst ``unsat_of_empty) F emptyLemma) + logInfo m!"{nIn} clauses, {steps.size} proof steps, {count} needed, {needIn.size} input clauses used" + +end SolarVerify.Sat.Load diff --git a/Verify/Discharge/Sat/Lrat.lean b/Verify/Discharge/Sat/Lrat.lean new file mode 100644 index 00000000..b87e3dac --- /dev/null +++ b/Verify/Discharge/Sat/Lrat.lean @@ -0,0 +1,410 @@ +import Verify.Discharge.Sat.Cnf +/-! +A checker for LRAT proofs of unsatisfiability that the kernel runs, and its soundness. + +A proof adds clauses, each by reverse unit propagation (RUP) from earlier clauses its hints name, +until it adds the empty clause. RAT steps are not supported: a proof that needs one fails to +check. Deletions only free memory, so a proof here leaves them out and every clause stays +available. + +Everything reduces in the kernel by structural recursion over lists, the proof tree and a fuel +bound, with arithmetic on `Nat` literals (which the kernel computes natively), so +`check f p = true` closes by `decide +kernel` and `check_sound` turns it into `f.Unsat`. +-/ +namespace SolarVerify.Sat + +noncomputable section + +/-- Membership of a number in a list, by the kernel's `Nat.beq`. Written with the recursor, as are +`unfalsified` and `rup`, because the kernel reduces that in fewer steps than structural recursion +compiled through `brecOn`. -/ +noncomputable def memb (x : Nat) (l : List Nat) : Bool := + List.rec false (fun y _ r => Nat.beq x y || r) l + +theorem memb_nil (x : Nat) : memb x [] = false := rfl +theorem memb_cons (x y : Nat) (ys : List Nat) : memb x (y :: ys) = (Nat.beq x y || memb x ys) := rfl + +theorem memb_iff {x : Nat} {l : List Nat} : memb x l = true ↔ x ∈ l := by + induction l with + | nil => simp [memb_nil] + | cons y ys ih => simp [memb_cons, ih, Nat.beq_eq] + +/-- The literals of `c` that the literals `A` (assumed true) do not falsify. -/ +noncomputable def unfalsified (A : List Lit) (c : Clause) : List Lit := + List.rec [] (fun l _ r => bif memb (Lit.neg l) A then r else l :: r) c + +theorem unfalsified_cons (A : List Lit) (l : Lit) (ls : Clause) : + unfalsified A (l :: ls) = + bif memb (Lit.neg l) A then unfalsified A ls else l :: unfalsified A ls := rfl + +/-- One hint clause: it must leave one literal, which then holds while propagation goes on with +`r`, or none, a conflict, which ends the check successfully. -/ +def rupStep (r : List Lit → Bool) (A : List Lit) (c : Clause) : Bool := + match unfalsified A c with + | [] => true + | [l] => r (l :: A) + | _ => false + +/-- Unit propagation along the hint clauses `hs`, from the literals `A`. -/ +noncomputable def rup (hs : List Clause) (A : List Lit) : Bool := + List.rec (motive := fun _ => List Lit → Bool) (fun _ => false) (fun c _ r A => rupStep r A c) hs A + +theorem rup_nil (A : List Lit) : rup [] A = false := rfl +theorem rup_cons (c : Clause) (cs : List Clause) (A : List Lit) : + rup (c :: cs) A = rupStep (rup cs) A c := rfl + +/-- A binary trie from clause IDs to clauses: key 0 at the root, then the key's bits from the +least significant one choose the left (1) or right (0) branch. -/ +inductive Trie where + | leaf + | node (v : Option Clause) (l r : Trie) + +namespace Trie + +def root : Trie → Option Clause + | leaf => none + | node v _ _ => v + +def left : Trie → Trie + | leaf => leaf + | node _ l _ => l + +def right : Trie → Trie + | leaf => leaf + | node _ _ r => r + +/-- The clause at key `k`, looking at most `fuel` levels down. -/ +def find? : (fuel : Nat) → Trie → Nat → Option Clause + | 0, t, k => if k = 0 then t.root else none + | f + 1, t, k => + if k = 0 then t.root + else if k % 2 = 1 then find? f t.left (k / 2) else find? f t.right (k / 2) + +/-- Store a clause at key `k`; a key deeper than `fuel` is dropped. -/ +def insert : (fuel : Nat) → Trie → Nat → Clause → Trie + | 0, t, k, c => if k = 0 then node (some c) t.left t.right else t + | f + 1, t, k, c => + if k = 0 then node (some c) t.left t.right + else if k % 2 = 1 then node t.root (insert f t.left (k / 2) c) t.right + else node t.root t.left (insert f t.right (k / 2) c) + +/-- Every clause stored in the trie has property `P`. -/ +def All (P : Clause → Prop) : Trie → Prop + | leaf => True + | node v l r => (∀ c, v = some c → P c) ∧ All P l ∧ All P r + +theorem All.root {P : Clause → Prop} {t : Trie} (h : t.All P) {c : Clause} (e : t.root = some c) : + P c := by + cases t with + | leaf => simp [Trie.root] at e + | node v l r => exact h.1 c e + +theorem All.left {P : Clause → Prop} {t : Trie} (h : t.All P) : t.left.All P := by + cases t with + | leaf => trivial + | node v l r => exact h.2.1 + +theorem All.right {P : Clause → Prop} {t : Trie} (h : t.All P) : t.right.All P := by + cases t with + | leaf => trivial + | node v l r => exact h.2.2 + +theorem find?_all {P : Clause → Prop} : + ∀ (fuel : Nat) (t : Trie) (k : Nat) (c : Clause), t.All P → t.find? fuel k = some c → P c + | 0, t, k, c, h, e => by + simp only [find?] at e + split at e + · exact h.root e + · simp at e + | f + 1, t, k, c, h, e => by + simp only [find?] at e + split at e + · exact h.root e + · split at e + · exact find?_all f _ _ c h.left e + · exact find?_all f _ _ c h.right e + +theorem insert_all {P : Clause → Prop} : + ∀ (fuel : Nat) (t : Trie) (k : Nat) (c : Clause), t.All P → P c → (t.insert fuel k c).All P + | 0, t, k, c, h, hc => by + simp only [insert] + split + · exact ⟨fun d e => by cases e; exact hc, h.left, h.right⟩ + · exact h + | f + 1, t, k, c, h, hc => by + simp only [insert] + split + · exact ⟨fun d e => by cases e; exact hc, h.left, h.right⟩ + · split + · exact ⟨fun d e => h.root e, insert_all f _ _ c h.left hc, h.right⟩ + · exact ⟨fun d e => h.root e, h.left, insert_all f _ _ c h.right hc⟩ + +end Trie + +/-- How deep the clause trie goes: IDs below `2 ^ 64` are stored. -/ +def fuel : Nat := 64 + +/-- One added clause: its ID, its literals, and the IDs of the clauses its RUP check uses, in +order. -/ +structure Step where + id : Nat + clause : Clause + hints : List Nat + deriving Inhabited + +/-- A proof: its steps in order, as a tree so that the term stays shallow for the kernel. -/ +inductive Proof where + | step (s : Step) + | seq (a b : Proof) + +/-- How running a proof ends: it failed, it derived the empty clause, or it goes on with these +clauses. -/ +inductive Res where + | fail + | done + | db (t : Trie) + +/-- The clauses hint IDs name, or none when one is missing. -/ +def lookupAll (t : Trie) : List Nat → Option (List Clause) + | [] => some [] + | i :: is => + match t.find? fuel i with + | none => none + | some c => + match lookupAll t is with + | none => none + | some cs => some (c :: cs) + +def Step.run (t : Trie) (s : Step) : Res := + match lookupAll t s.hints with + | none => .fail + | some hs => + if rup hs (s.clause.map Lit.neg) then + match s.clause with + | [] => .done + | _ :: _ => .db (t.insert fuel s.id s.clause) + else .fail + +def Proof.run : Trie → Proof → Res + | t, .step s => s.run t + | t, .seq p q => + match p.run t with + | .db t' => q.run t' + | r => r + +/-- The clauses of a formula, numbered from `i`. -/ +def Trie.ofCnf (t : Trie) (i : Nat) : Cnf → Trie + | [] => t + | c :: cs => Trie.ofCnf (t.insert fuel i c) (i + 1) cs + +/-- The formula's clauses, numbered from 1 as in DIMACS, then the proof, which must end by adding +the empty clause. -/ +def check (f : Cnf) (p : Proof) : Bool := + match p.run (Trie.ofCnf .leaf 1 f) with + | .done => true + | _ => false + +/-! ## Soundness -/ + +section sound +variable (a : Assignment) + +/-- Every literal of `A` is true. -/ +def AllTrue (A : List Lit) : Prop := ∀ l ∈ A, Lit.eval a l = true + +/-- The clauses an assignment satisfies. -/ +abbrev Sat (c : Clause) : Prop := Clause.eval a c = true + +theorem unfalsified_spec {A : List Lit} (hA : AllTrue a A) : + ∀ c : Clause, Clause.eval a c = true → ∃ l ∈ unfalsified A c, Lit.eval a l = true + | [], h => by simp [Clause.eval] at h + | l :: ls, h => by + rw [Clause.eval_cons] at h + rw [unfalsified_cons] + cases hm : memb (Lit.neg l) A + · simp only [Bool.cond_false] + by_cases hl : Lit.eval a l = true + · exact ⟨l, List.mem_cons_self, hl⟩ + · have hls : Clause.eval a ls = true := by simpa [hl] using h + obtain ⟨x, hx, hxv⟩ := unfalsified_spec hA ls hls + exact ⟨x, List.mem_cons_of_mem _ hx, hxv⟩ + · simp only [Bool.cond_true] + have hn := hA _ (memb_iff.mp hm) + rw [Lit.eval_neg] at hn + have hl : Lit.eval a l = false := by simpa using hn + rw [hl] at h + exact unfalsified_spec hA ls (by simpa using h) + +theorem rup_sound : + ∀ (hs : List Clause) (A : List Lit), AllTrue a A → (∀ c ∈ hs, Clause.eval a c = true) → + rup hs A = true → False + | [], _, _, _, h => by simp [rup_nil] at h + | c :: cs, A, hA, hc, h => by + obtain ⟨l, hl, hlv⟩ := unfalsified_spec a hA c (hc c List.mem_cons_self) + rw [rup_cons] at h + unfold rupStep at h + split at h + · next e => rw [e] at hl; simp at hl + · next l' e => + rw [e] at hl + simp at hl + subst hl + refine rup_sound cs (l :: A) ?_ (fun d hd => hc d (List.mem_cons_of_mem _ hd)) h + intro x hx + rcases List.mem_cons.mp hx with rfl | hx + · exact hlv + · exact hA x hx + · simp at h + +theorem allTrue_neg_of_false (c : Clause) (h : Clause.eval a c = false) : + AllTrue a (c.map Lit.neg) := by + intro l hl + obtain ⟨x, hx, rfl⟩ := List.mem_map.mp hl + rw [Lit.eval_neg] + have hn : ¬ (∃ l ∈ c, Lit.eval a l = true) := by + rw [← Clause.eval_eq_true]; simp [h] + have hx' : Lit.eval a x ≠ true := fun e => hn ⟨x, hx, e⟩ + simpa using hx' + +theorem lookupAll_sat {t : Trie} (ht : t.All (Sat a)) : + ∀ (is : List Nat) (hs : List Clause), lookupAll t is = some hs → + ∀ c ∈ hs, Clause.eval a c = true + | [], hs, e => by simp [lookupAll] at e; subst e; simp + | i :: is, hs, e => by + simp only [lookupAll] at e + split at e + · simp at e + · next c hc => + split at e + · simp at e + · next cs hcs => + simp at e; subst e + intro d hd + rcases List.mem_cons.mp hd with rfl | hd + · exact Trie.find?_all fuel t i d ht hc + · exact lookupAll_sat ht is cs hcs d hd + +theorem Step.run_sound {t : Trie} (ht : t.All (Sat a)) (s : Step) : + (s.run t = .done → False) ∧ (∀ t', s.run t = .db t' → t'.All (Sat a)) := by + unfold Step.run + split + · simp + · next hs ehs => + have hsat := lookupAll_sat a ht _ hs ehs + split + · next hr => + -- The added clause is true: otherwise its negation propagates to a conflict. + have hc : Clause.eval a s.clause = true := by + cases e : Clause.eval a s.clause + · exact (rup_sound a hs _ (allTrue_neg_of_false a _ e) hsat hr).elim + · rfl + split + · next e => rw [e] at hc; simp [Clause.eval] at hc + · refine ⟨by simp, fun t' e => ?_⟩ + simp at e; subst e + exact Trie.insert_all fuel t s.id s.clause ht hc + · simp + +theorem Proof.run_sound : + ∀ (p : Proof) (t : Trie), t.All (Sat a) → + (p.run t = .done → False) ∧ (∀ t', p.run t = .db t' → t'.All (Sat a)) + | .step s, t, ht => Step.run_sound a ht s + | .seq p q, t, ht => by + simp only [Proof.run] + have hp := Proof.run_sound p t ht + split + · next t' e => exact Proof.run_sound q t' (hp.2 t' e) + · next r h1 => + refine ⟨fun e => hp.1 e, fun t' e => ?_⟩ + exact (h1 t' e).elim + +theorem Trie.ofCnf_all (f : Cnf) (hf : ∀ c ∈ f, Clause.eval a c = true) : + ∀ (t : Trie) (i : Nat), t.All (Sat a) → ∀ g : Cnf, (∀ c ∈ g, c ∈ f) → + (Trie.ofCnf t i g).All (Sat a) + | t, _, ht, [], _ => ht + | t, i, ht, c :: cs, hg => by + simp only [Trie.ofCnf] + exact Trie.ofCnf_all f hf _ _ (Trie.insert_all fuel t i c ht (hf c (hg c List.mem_cons_self))) + cs (fun d hd => hg d (List.mem_cons_of_mem _ hd)) + +end sound + +/-- A proof that checks shows the formula unsatisfiable. -/ +theorem check_sound (f : Cnf) (p : Proof) (h : check f p = true) : f.Unsat := by + intro a + cases e : Cnf.eval a f + · rfl + · have hf := (Cnf.eval_eq_true a f).mp e + have h0 := Trie.ofCnf_all a f hf .leaf 1 trivial f (fun _ h => h) + have hr := (Proof.run_sound a p _ h0).1 + unfold check at h + split at h + · next e' => exact (hr e').elim + · simp at h + + +/-! ## Checking one step at a time + +For large proofs, a single evaluation of `check` keeps every intermediate clause database in the +kernel's caches. Instead, each step can be its own declaration, a lemma that every assignment +satisfying the formula satisfies the step's clause, proved from the lemmas of its hints by one +small `rup` evaluation. The environment then plays the clause database. These are the lemmas such +declarations apply. -/ + +section steps +variable (a : Assignment) + +/-- Every clause of the list is true. -/ +def AllSat : List Clause → Prop + | [] => True + | c :: cs => Clause.eval a c = true ∧ AllSat cs + +theorem AllSat.nil : AllSat a [] := trivial + +theorem AllSat.cons (c : Clause) (cs : List Clause) (h : Clause.eval a c = true) + (hs : AllSat a cs) : AllSat a (c :: cs) := ⟨h, hs⟩ + +theorem AllSat.mem : ∀ (hs : List Clause), AllSat a hs → ∀ c ∈ hs, Clause.eval a c = true + | [], _, c, hc => by simp at hc + | d :: ds, ⟨hd, hds⟩, c, hc => by + rcases List.mem_cons.mp hc with rfl | hc + · exact hd + · exact AllSat.mem ds hds c hc + +/-- A clause that unit propagation derives from true hint clauses is true. -/ +theorem rup_clause (c : Clause) (hs : List Clause) (hr : rup hs (c.map Lit.neg) = true) + (h : AllSat a hs) : Clause.eval a c = true := by + cases e : Clause.eval a c + · exact (rup_sound a hs _ (allTrue_neg_of_false a c e) (AllSat.mem a hs h) hr).elim + · rfl + +theorem Cnf.eval_mem (f : Cnf) (c : Clause) (h : Cnf.eval a f = true) (hc : c ∈ f) : + Clause.eval a c = true := + (Cnf.eval_eq_true a f).mp h c hc + +theorem mem_head (c : Clause) (l : List Clause) : c ∈ c :: l := List.mem_cons_self + +theorem mem_tail (c d : Clause) (l : List Clause) (h : c ∈ l) : c ∈ d :: l := + List.mem_cons_of_mem _ h + +theorem mem_append_left (c : Clause) (l r : List Clause) (h : c ∈ l) : c ∈ List.append l r := + List.mem_append_left r h + +theorem mem_append_right (c : Clause) (l r : List Clause) (h : c ∈ r) : c ∈ List.append l r := + List.mem_append_right l h + +end steps + +/-- A formula from which every satisfying assignment would satisfy the empty clause is +unsatisfiable. -/ +theorem unsat_of_empty (f : Cnf) (h : ∀ a, Cnf.eval a f = true → Clause.eval a [] = true) : + f.Unsat := by + intro a + cases e : Cnf.eval a f + · rfl + · have := h a e + simp [Clause.eval] at this + +end + +end SolarVerify.Sat diff --git a/Verify/Discharge/Search.lean b/Verify/Discharge/Search.lean new file mode 100644 index 00000000..42edc3b1 --- /dev/null +++ b/Verify/Discharge/Search.lean @@ -0,0 +1,409 @@ +/- +The search that closes a shallow obligation: hypotheses over integers, Booleans as propositions, +arrays as functions and quantifiers over the integers, and the goal `False`. It only builds +proof terms; the kernel checks every one, so a bug here can make a proof fail, never make a +false statement proved. + +1. `vc_defs`: definitions `x = t` and `g ↔ φ` of local symbols are substituted away; +2. `vc_norm`: negations are pushed in, implications become disjunctions (which `omega` reads), + constants fold; +3. the search splits conjunctions, existentials (whose witnesses it names) and disjunctions with + quantifiers, instantiates universal hypotheses at the witnesses and at the arguments that + match their array reads (E-matching on one-variable triggers), splits conditionals and + propositional atoms, adds congruence facts for array reads, and runs `omega` (linear integer + arithmetic, with literal divisors) on each case. +-/ +import Lean +import Verify.Discharge.Lemmas + +open Lean Meta Elab Tactic + +namespace SolarVerify.Discharge + +/-- Replaces one hypothesis `h : a ↔ b` whose side is a local proposition by `propext h : a = b`, +so that `subst_vars` can eliminate it, and repeats on the new context until none is left. -/ +partial def iffToEq : TacticM Unit := withMainContext do + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail then continue + let ty ← instantiateMVars ldecl.type + if let some (a, b) := ty.iff? then + if a.isFVar || b.isFVar then + let pf ← mkAppM `propext #[ldecl.toExpr] + let r ← (← getMainGoal).replace ldecl.fvarId pf + replaceMainGoal [r.mvarId] + iffToEq + return + +/-- Whether `e` has a quantifier: an `∃`, or a `∀` over the integers (the only sort the verifier +quantifies over). -/ +partial def hasQuantifier (e : Expr) : Bool := + match e with + | .forallE _ d b _ => d == mkConst `Int || hasQuantifier d || hasQuantifier b + | .app f a => (e.isAppOfArity `Exists 2) || hasQuantifier f || hasQuantifier a + | .lam _ t b _ => hasQuantifier t || hasQuantifier b + | .mdata _ b => hasQuantifier b + | _ => false + +/-- The prefix of the names of the witnesses `splitHyps` takes out of existentials. -/ +def witnessPrefix : String := "vc_w" + +/-- Splits one hypothesis that is a conjunction or an existential, naming the witness of an +existential `vc_w…`, and repeats until none is left. -/ +partial def splitHyps : TacticM Unit := withMainContext do + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail then continue + let ty ← instantiateMVars ldecl.type + let isEx := ty.isAppOfArity `Exists 2 + let quantOr := ty.isAppOfArity `Or 2 && hasQuantifier ty + if ty.isAppOfArity `And 2 || isEx || quantOr then + let gs ← (← getMainGoal).cases ldecl.fvarId + let mut out := [] + for sg in gs do + let mut g := sg.mvarId + if isEx then + if let some (Expr.fvar w) := (sg.fields[0]? : Option Expr) then + g ← g.rename w (← mkFreshUserName (Name.mkSimple witnessPrefix)) + out := out ++ [g] + replaceMainGoal out + -- each case of a disjunction is a goal of its own: split them all + let gs ← getGoals + let mut done := [] + for g in gs do + setGoals [g] + splitHyps + done := done ++ (← getGoals) + setGoals done + return + +/-- The witnesses `splitHyps` named. -/ +def witnesses : TacticM (Array Expr) := withMainContext do + let mut out := #[] + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail then continue + if !(ldecl.userName.toString.startsWith witnessPrefix) then continue + if (← instantiateMVars ldecl.type) == mkConst `Int then out := out.push ldecl.toExpr + return out + +/-- The subterms `f a₁ … aₙ` of `e` whose head `f` is a local, with no loose bound variables. -/ +partial def localApps (e : Expr) (acc : Array Expr := #[]) : Array Expr := + let acc := if e.isApp && e.getAppFn.isFVar && !e.hasLooseBVars then acc.push e else acc + match e with + | .app f a => localApps a (localApps f acc) + | .lam _ t b _ | .forallE _ t b _ => localApps b (localApps t acc) + | .letE _ t v b _ => localApps b (localApps v (localApps t acc)) + | .mdata _ b | .proj _ _ b => localApps b acc + | _ => acc + +/-- The triggers of a quantifier body for its variable `x` (the bound variable `depth`): the local +functions `f` the body applies to `x`, with the arity and the argument position. -/ +partial def triggers (e : Expr) (depth : Nat := 0) (acc : Array (FVarId × Nat × Nat) := #[]) : + Array (FVarId × Nat × Nat) := + let acc := if e.isApp && e.getAppFn.isFVar then + let args := e.getAppArgs + (List.range args.size).foldl (init := acc) fun acc i => + if args[i]! == .bvar depth then acc.push (e.getAppFn.fvarId!, args.size, i) else acc + else acc + match e with + | .app f a => triggers a depth (triggers f depth acc) + | .lam _ t b _ | .forallE _ t b _ => triggers b (depth + 1) (triggers t depth acc) + | .letE _ t v b _ => triggers b (depth + 1) (triggers v depth (triggers t depth acc)) + | .mdata _ b | .proj _ _ b => triggers b depth acc + | _ => acc + +/-- Instantiates each hypothesis `∀ x : Int, P x` at each witness in `ws`, and at each `t` such +that `P` applies a local function `f` to `x` and the context applies `f` to `t` in the same place +(E-matching on single-variable triggers). Returns whether it added an instance. -/ +def instantiate (ws : Array Expr) (seen : Std.HashSet (Expr × Expr)) : + TacticM (Bool × Std.HashSet (Expr × Expr)) := withMainContext do + let mut seen := seen + let mut ground : Array Expr := #[] + for ldecl in (← getLCtx) do + if !ldecl.isImplementationDetail then + ground := localApps (← instantiateMVars ldecl.type) ground + let hyps := (← getLCtx).foldl (init := #[]) fun acc d => + if d.isImplementationDetail then acc else acc.push d + let mut added := false + for ldecl in hyps do + let ty ← instantiateMVars ldecl.type + if let .forallE _ d body _ := ty then + if d == mkConst `Int && (← isProp ty) then + let mut ts := ws + for (f, n, i) in triggers body do + for e in ground do + if e.getAppFn == .fvar f && e.getAppNumArgs == n then + let t := e.getArg! i + if !(ts.contains t) then ts := ts.push t + for t in ts do + -- each quantifier once per term, however later steps rewrite its instance + if seen.contains (ty, t) then continue + seen := seen.insert (ty, t) + let v := mkApp ldecl.toExpr t + let vty ← instantiateMVars (← whnfR (← inferType v)) + -- an instance the context already has adds nothing + let known := (← getLCtx).any fun d => !d.isImplementationDetail && d.type == vty + if known then continue + let g ← getMainGoal + let (_, g') ← (← g.assert (← mkFreshUserName `inst) vty v).intro1P + replaceMainGoal [g'] + added := true + return (added, seen) + +/-- Clears the hypotheses with quantifiers, which `omega` cannot use. -/ +def clearQuantified : TacticM Unit := withMainContext do + let mut g ← getMainGoal + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail then continue + let ty ← instantiateMVars ldecl.type + if (← isProp ty) && hasQuantifier ty then + g ← g.tryClear ldecl.fvarId + replaceMainGoal [g] + +/-- The condition of the first `if c then _ else _` in the goal or a hypothesis whose condition +has no loose bound variables. -/ +def findIteCond : TacticM (Option Expr) := withMainContext do + let mut tys := #[← getMainTarget] + for ldecl in (← getLCtx) do + if !ldecl.isImplementationDetail then tys := tys.push ldecl.type + for ty in tys do + let ty ← instantiateMVars ty + if let some e := ty.find? (fun e => (e.isAppOfArity `ite 5 || e.isAppOfArity ``SolarVerify.Discharge.qite 4) && !(e.getArg! 1).hasLooseBVars) then + return some (e.getArg! 1) + return none + +/-- A propositional atom of the goal or a hypothesis: a local proposition (an SMT `Bool` +constant), or a local function applied to integers that returns one (a `Bool` array read), with +no loose bound variables. `omega` reads neither, so the search cases on them. -/ +def findPropAtom : TacticM (Option Expr) := withMainContext do + let mut tys := #[← getMainTarget] + for ldecl in (← getLCtx) do + if !ldecl.isImplementationDetail then tys := tys.push (← instantiateMVars ldecl.type) + for ty in tys do + for e in localApps ty do + if !(← whnfR (← inferType e)).isForall && (← isProp e) then return some e + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail then continue + if (← instantiateMVars ldecl.type).isProp then + for ty in tys do + if ty.containsFVar ldecl.fvarId then return some ldecl.toExpr + return none + +/-- The applications `f a₁ … aₙ` (`n ≤ 3`, not partial) of a local function `f` to integers in the +goal and the hypotheses, grouped by `f`. -/ +def applications : TacticM (Std.HashMap FVarId (Array (Array Expr))) := withMainContext do + let mut out : Std.HashMap FVarId (Array (Array Expr)) := {} + let mut tys := #[← getMainTarget] + for ldecl in (← getLCtx) do + if !ldecl.isImplementationDetail then tys := tys.push (← instantiateMVars ldecl.type) + for ty in tys do + for e in localApps ty do + let f := e.getAppFn.fvarId! + let args := e.getAppArgs + if args.size == 0 || args.size > 3 then continue + if (← whnfR (← inferType e)).isForall then continue + let mut ok := true + for a in args do + if (← inferType a) != mkConst `Int then ok := false + if !ok then continue + let prev := out.getD f #[] + if !(prev.any (· == args)) then out := out.insert f (prev.push args) + return out + +/-- Adds, for each two applications of the same local function, that they are equal or their +arguments differ. -/ +def congruence : TacticM Unit := withMainContext do + for (f, apps) in (← applications) do + for i in [0:apps.size] do + for j in [i+1:apps.size] do + let (a, b) := (apps[i]!, apps[j]!) + let lemma := match a.size with + | 1 => `SolarVerify.Discharge.congr1 + | 2 => `SolarVerify.Discharge.congr2 + | _ => `SolarVerify.Discharge.congr3 + let pf ← mkAppM lemma (#[mkFVar f] ++ a ++ b) + let g ← getMainGoal + let (_, g') ← (← g.assert (← mkFreshUserName `cong) (← inferType pf) pf).intro1P + replaceMainGoal [g'] + +end SolarVerify.Discharge + +open SolarVerify.Discharge + +/-- For each two applications of the same array or function, adds that they are equal or their +arguments differ. -/ +elab "vc_congr" : tactic => congruence + +/-- Substitutes away the definitions `x = t` and `g ↔ φ` of local symbols. -/ +elab "vc_defs" : tactic => do + iffToEq + evalTactic (← `(tactic| subst_vars)) + +/-- The leaf of the search: closes a quantifier-free goal `False` or fails. It is `omega` here; +another module adds a procedure with +`macro_rules | `(tactic| vc_leaf) => `(tactic| my_tactic)`, and Lean then tries the rules from +the last one added back to `omega`, taking the first that closes the goal. Whatever a rule does, +`discharge.sh` still checks the axioms of every proof. -/ +syntax "vc_leaf" : tactic + +macro_rules | `(tactic| vc_leaf) => `(tactic| omega) + +/-- Pushes negations in, turns implications into disjunctions and Booleans into propositions, +and folds constants. -/ +macro "vc_norm" : tactic => `(tactic| simp -failIfUnchanged only [Classical.not_forall, not_exists, not_imp, + Classical.not_and_iff_not_or_not, not_or, SolarVerify.Discharge.imp_iff_not_or, Classical.not_not, ge_iff_le, + gt_iff_lt, true_and, and_true, false_and, and_false, true_or, or_true, false_or, or_false, + not_true_eq_false, not_false_eq_true, eq_self_iff_true, iff_self, true_implies, false_implies, + implies_true, Bool.and_eq_true, Bool.or_eq_true, Bool.not_eq_true', Bool.not_eq_eq_eq_not, + Bool.not_true, Bool.not_false, decide_eq_true_eq, SolarVerify.Discharge.decide_any_eq_true, SolarVerify.Discharge.qdec_eq_true, SolarVerify.Discharge.ite_eq_qite, SolarVerify.Discharge.qite_true, SolarVerify.Discharge.qite_false, Bool.not_eq_false, Bool.and_eq_false_iff, Bool.or_eq_false_iff, decide_eq_false_iff_not, Bool.and_true, + Bool.true_and, Bool.and_false, Bool.false_and, Bool.or_true, Bool.true_or, Bool.or_false, + Bool.false_or, Bool.true_eq_false, Bool.false_eq_true, SolarVerify.Discharge.true_eq_iff, + SolarVerify.Discharge.false_eq_iff] at *) + +/-- Splits conjunctions and existentials among the hypotheses. -/ +elab "vc_split_hyps" : tactic => splitHyps + +namespace SolarVerify.Discharge + +/-- Simplifies the goal and every hypothesis but the last one (the case hypothesis just +introduced, which the simp set rewrites with) by `stx`. Leaving the case hypothesis alone keeps +it: rewriting it with an earlier copy of itself would turn it into `True`. -/ +def simpCase (stx : Syntax) : TacticM Unit := withMainContext do + let some h := (← getLCtx).lastDecl | throwError "no case hypothesis" + let { ctx, simprocs, .. } ← mkSimpContext stx (eraseLocal := false) + let mut fvars := #[] + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail || ldecl.fvarId == h.fvarId then continue + if ← isProp ldecl.type then fvars := fvars.push ldecl.fvarId + match ← simpGoal (← getMainGoal) ctx simprocs (fvarIdsToSimp := fvars) with + | (none, _) => replaceMainGoal [] + | (some (_, g), _) => replaceMainGoal [g] + +/-- Proves a condition from the context without splitting on it: a conjunction part by part, a +`∀ x : Int` by instantiating every quantified hypothesis at a fresh `x`, an `∃ x : Int` at a +witness or an integer the context applies a function to, and the rest by `assumption` or +`omega`. A condition that guards a loop's next state restates the invariant the context already +has; proving it avoids a split whose negative case unfolds every quantifier again. -/ +partial def provePos (fuel : Nat) : TacticM Unit := withMainContext do + if fuel = 0 then throwError "vc_prove: depth exhausted" + let t ← whnfR (← instantiateMVars (← getMainTarget)) + if t.isAppOfArity ``And 2 then + evalTactic (← `(tactic| constructor)) + let gs ← getGoals + for g in gs do + setGoals [g] + provePos (fuel - 1) + setGoals [] + else if t.isForall && t.bindingDomain! == mkConst ``Int && !(← isProp t.bindingDomain!) then + let (x, g) ← (← getMainGoal).intro1P + replaceMainGoal [g] + withMainContext do + let mut g ← getMainGoal + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail then continue + let ty ← instantiateMVars ldecl.type + if let .forallE _ d _ _ := ty then + if d == mkConst ``Int && (← isProp ty) then + let v := mkApp ldecl.toExpr (.fvar x) + let vty ← instantiateMVars (← whnfR (← inferType v)) + let (_, g') ← (← g.assert (← mkFreshUserName `inst) vty v).intro1P + g := g' + replaceMainGoal [g] + evalTactic (← `(tactic| omega)) + else if t.isAppOfArity ``Exists 2 && (t.getArg! 0) == mkConst ``Int then + let mut cands := (← witnesses) + for ldecl in (← getLCtx) do + if ldecl.isImplementationDetail then continue + for e in localApps (← instantiateMVars ldecl.type) do + for a in e.getAppArgs do + if !a.hasLooseBVars && (← inferType a) == mkConst ``Int && !cands.contains a then + cands := cands.push a + for c in cands do + let s ← saveState + try + let cStx ← Term.exprToSyntax c + evalTactic (← `(tactic| refine ⟨$cStx, ?_⟩)) + provePos (fuel - 1) + return + catch _ => s.restore + throwError "vc_prove: no witness" + else + evalTactic (← `(tactic| first | assumption | omega)) + +/-- Proves the goal with `provePos`. -/ +elab "vc_prove_pos" : tactic => provePos 8 + +/-- Splits on the condition of one `if`, simplifying each case; fails when there is none. -/ +def splitIte : TacticM Unit := do + let some c ← findIteCond | throwError "no conditional" + let hcI := mkIdent (← mkFreshUserName `hc) + let cStx ← Term.exprToSyntax c + -- a quantified condition the context implies: take the case where it holds, and no other + if hasQuantifier c then + let s ← saveState + try + evalTactic (← `(tactic| have $hcI : $cStx := by vc_prove_pos)) + simpCase (← `(tactic| simp only [↓reduceIte, SolarVerify.Discharge.ite_pos $hcI, SolarVerify.Discharge.qite_pos $hcI])) + return + catch _ => s.restore + evalTactic (← `(tactic| by_cases $hcI : $cStx)) + let gs ← getGoals + let mut out := [] + -- `by_cases` leaves the case where `c` holds first + for (g, pos) in gs.zip [true, false] do + setGoals [g] + if pos then + simpCase (← `(tactic| simp only [↓reduceIte, SolarVerify.Discharge.ite_pos $hcI, SolarVerify.Discharge.qite_pos $hcI])) + else + simpCase (← `(tactic| simp only [↓reduceIte, SolarVerify.Discharge.ite_neg $hcI, SolarVerify.Discharge.qite_neg $hcI])) + out := out ++ (← getGoals) + setGoals out + +/-- Cases on the propositional atom `p`, rewriting it to `True` or `False` everywhere. -/ +def splitProp (p : Expr) : TacticM Unit := do + let hpI := mkIdent (← mkFreshUserName `hp) + let pStx ← Term.exprToSyntax p + evalTactic (← `(tactic| by_cases $hpI : $pStx)) + let gs ← getGoals + let mut out := [] + for g in gs do + setGoals [g] + simpCase (← `(tactic| simp only [$hpI:ident])) + out := out ++ (← getGoals) + setGoals out + +/-- The search: on each goal, split hypotheses, instantiate quantifiers, and split one +conditional, until nothing changes; then clear the quantified hypotheses, add congruence +facts and run `omega`. `fuel` bounds the depth, so a hopeless goal fails rather than loops. -/ +partial def search (seen : Std.HashSet (Expr × Expr)) (fuel : Nat) : TacticM Unit := do + if fuel = 0 then throwError "vc_auto: search depth exhausted" + for g in (← getGoals) do + setGoals [g] + evalTactic (← `(tactic| vc_norm)) + if (← getGoals).isEmpty then continue + splitHyps + let gs ← getGoals + for g in gs do + setGoals [g] + -- what was instantiated is per branch: a sibling's instances are not in this context + let (added, seen) ← instantiate (← witnesses) seen + if added then + search seen (fuel - 1) + else if (← findIteCond).isSome then + splitIte + search seen (fuel - 1) + else if let some p ← findPropAtom then + splitProp p + search seen (fuel - 1) + else + clearQuantified + congruence + evalTactic (← `(tactic| vc_leaf)) + setGoals [] + +end SolarVerify.Discharge + +/-- Closes a shallow obligation whose hypotheses are still in the goal: see the module comment. -/ +elab "vc_search" : tactic => do + evalTactic (← `(tactic| intros)) + SolarVerify.Discharge.iffToEq + evalTactic (← `(tactic| subst_vars)) + SolarVerify.Discharge.search {} 32 diff --git a/Verify/Discharge/Valid.lean b/Verify/Discharge/Valid.lean new file mode 100644 index 00000000..3c4d27b5 --- /dev/null +++ b/Verify/Discharge/Valid.lean @@ -0,0 +1,322 @@ +/- +`vc_valid` proves an obligation `solar-verify --emit-lean` exported: `Obligation.Valid ob`, for +every interpretation `env` of the declared symbols. + +1. It unfolds the obligation's definitions and evaluates `Term.eval` symbolically: on the + exported terms every sort check decides and every `Option` is `some`, so the formula becomes a + Boolean expression over the symbols' values `env.fn f [] s ()` (and `env.divZero`, + `env.modZero`). A formula that does not reduce so, such as an ill-sorted one, leaves the proof + stuck: it fails, and is never vacuous. +2. It generalizes each such value to a variable of its sort's Lean type (`Int`, `Bool`, + `Int → Int`, …), turns the Boolean formula into propositions, and assumes the guard and the + script's assertions. +3. The search of `SolarVerify.Discharge.Search` closes what is left. + +Every step builds a proof term the kernel checks; nothing here is trusted. +-/ +import Lean +import Verify.Obligation.Vc +import Verify.Discharge.Search +import Verify.Discharge.IteApply + +open Lean Meta Elab Tactic + +namespace SolarVerify.Discharge + +open SolarVerify.Smt SolarVerify.Vc + +/-- An SMT `ite` of one sort evaluates to a value of that sort. -/ +theorem ite_val (s : Srt) (c : Bool) (a b : s.Den) : + (if c = true then (⟨s, a⟩ : Val) else ⟨s, b⟩) = ⟨s, if c = true then a else b⟩ := by + cases c <;> rfl + +/-- `ite_val` for integer branches stated over `Int`, which `simp` matches against literal +branches such as `⟨.int, 1⟩` (where `Srt.Den .int` is not reducibly `Int`). -/ +theorem ite_val_int (c : Bool) (a b : Int) : + (if c = true then (⟨.int, a⟩ : Val) else ⟨.int, b⟩) = ⟨.int, if c = true then a else b⟩ := by + cases c <;> rfl + +/-! Binders: a quantifier over the values of a list of sorts becomes one quantifier per sort, +over the sort's Lean type. -/ + +theorem forall_denList_nil {P : Srt.DenList [] → Prop} : (∀ xs, P xs) ↔ P () := + ⟨fun h => h (), fun h _ => h⟩ + +theorem forall_denList_cons {s : Srt} {ss : List Srt} {P : Srt.DenList (s :: ss) → Prop} : + (∀ xs, P xs) ↔ ∀ (x : s.Den) (xs : Srt.DenList ss), P (x, xs) := + ⟨fun h x xs => h (x, xs), fun h p => h p.1 p.2⟩ + +theorem exists_denList_nil {P : Srt.DenList [] → Prop} : (∃ xs, P xs) ↔ P () := + ⟨fun ⟨_, h⟩ => h, fun h => ⟨(), h⟩⟩ + +theorem exists_denList_cons {s : Srt} {ss : List Srt} {P : Srt.DenList (s :: ss) → Prop} : + (∃ xs, P xs) ↔ ∃ (x : s.Den) (xs : Srt.DenList ss), P (x, xs) := + ⟨fun ⟨p, h⟩ => ⟨p.1, p.2, h⟩, fun ⟨x, xs, h⟩ => ⟨(x, xs), h⟩⟩ + +theorem forall_den_int {P : Srt.Den .int → Prop} : (∀ x, P x) ↔ ∀ x : Int, P x := Iff.rfl +theorem forall_den_bool {P : Srt.Den .bool → Prop} : (∀ x, P x) ↔ ∀ x : Bool, P x := Iff.rfl +theorem exists_den_int {P : Srt.Den .int → Prop} : (∃ x, P x) ↔ ∃ x : Int, P x := Iff.rfl +theorem exists_den_bool {P : Srt.Den .bool → Prop} : (∃ x, P x) ↔ ∃ x : Bool, P x := Iff.rfl + + + +/-- Extensional equality of arrays, as a `qdec` `simp` can rewrite inside. -/ +theorem beq_array (i e : Srt) (a b : Srt.Den (.array i e)) : + Srt.beq (.array i e) a b = qdec (∀ k : Srt.Den i, Srt.beq e (a k) (b k) = true) := by + rw [Srt.beq]; rfl + +/-! Quantifiers over one to four integers, the ones the exporter emits so far: each binder becomes a +Lean `∀ x : Int` (`∃`), with the bound value at the head of the locals. -/ + +theorem eval_forall_int (env : Env) (decls : List Decl) (locals : Locals) (body : SolarVerify.Smt.Term) : + Term.eval env decls locals (.forall [.int] body) = + qite (∀ x : Int, (boolOf (Term.eval env decls (⟨.int, x⟩ :: locals) body)).isSome) + (some ⟨.bool, qdec (∀ x : Int, + boolOf (Term.eval env decls (⟨.int, x⟩ :: locals) body) = some true)⟩) + none := by + rw [Term.eval] + have h1 : (∀ xs : Srt.DenList [.int], + (boolOf (Term.eval env decls (bindAll [.int] xs locals) body)).isSome) = + ∀ x : Int, (boolOf (Term.eval env decls (⟨.int, x⟩ :: locals) body)).isSome := + propext ⟨fun h x => h (x, ()), fun h p => h p.1⟩ + have h2 : (∀ xs : Srt.DenList [.int], + boolOf (Term.eval env decls (bindAll [.int] xs locals) body) = some true) = + ∀ x : Int, boolOf (Term.eval env decls (⟨.int, x⟩ :: locals) body) = some true := + propext ⟨fun h x => h (x, ()), fun h p => h p.1⟩ + rw [h1, h2]; rfl + +theorem eval_exists_int (env : Env) (decls : List Decl) (locals : Locals) (body : SolarVerify.Smt.Term) : + Term.eval env decls locals (.exists [.int] body) = + qite (∀ x : Int, (boolOf (Term.eval env decls (⟨.int, x⟩ :: locals) body)).isSome) + (some ⟨.bool, qdec (∃ x : Int, + boolOf (Term.eval env decls (⟨.int, x⟩ :: locals) body) = some true)⟩) + none := by + rw [Term.eval] + have h1 : (∀ xs : Srt.DenList [.int], + (boolOf (Term.eval env decls (bindAll [.int] xs locals) body)).isSome) = + ∀ x : Int, (boolOf (Term.eval env decls (⟨.int, x⟩ :: locals) body)).isSome := + propext ⟨fun h x => h (x, ()), fun h p => h p.1⟩ + have h2 : (∃ xs : Srt.DenList [.int], + boolOf (Term.eval env decls (bindAll [.int] xs locals) body) = some true) = + ∃ x : Int, boolOf (Term.eval env decls (⟨.int, x⟩ :: locals) body) = some true := + propext ⟨fun ⟨p, h⟩ => ⟨p.1, h⟩, fun ⟨x, h⟩ => ⟨(x, ()), h⟩⟩ + rw [h1, h2]; rfl +/-- `forall` over 2 integers: the binders become Lean binders, the last one at the head of the locals. -/ +theorem eval_forall_int2 (env : Env) (decls : List Decl) (locals : Locals) (body : SolarVerify.Smt.Term) : + Term.eval env decls locals (.forall [.int, .int] body) = + qite (∀ x y : Int, (boolOf (Term.eval env decls (⟨.int, y⟩ :: ⟨.int, x⟩ :: locals) body)).isSome) + (some ⟨.bool, qdec (∀ x y : Int, + boolOf (Term.eval env decls (⟨.int, y⟩ :: ⟨.int, x⟩ :: locals) body) = some true)⟩) + none := by + rw [Term.eval] + have h1 : (∀ xs : Srt.DenList [.int, .int], + (boolOf (Term.eval env decls (bindAll [.int, .int] xs locals) body)).isSome) = + ∀ x y : Int, (boolOf (Term.eval env decls (⟨.int, y⟩ :: ⟨.int, x⟩ :: locals) body)).isSome := + propext ⟨fun h x y => h (x, (y, ())), fun h p => h p.1 p.2.1⟩ + have h2 : (∀ xs : Srt.DenList [.int, .int], + boolOf (Term.eval env decls (bindAll [.int, .int] xs locals) body) = some true) = + ∀ x y : Int, boolOf (Term.eval env decls (⟨.int, y⟩ :: ⟨.int, x⟩ :: locals) body) = some true := + propext ⟨fun h x y => h (x, (y, ())), fun h p => h p.1 p.2.1⟩ + rw [h1, h2]; rfl + +/-- `forall` over 3 integers: the binders become Lean binders, the last one at the head of the locals. -/ +theorem eval_forall_int3 (env : Env) (decls : List Decl) (locals : Locals) (body : SolarVerify.Smt.Term) : + Term.eval env decls locals (.forall [.int, .int, .int] body) = + qite (∀ x y z : Int, (boolOf (Term.eval env decls (⟨.int, z⟩ :: ⟨.int, y⟩ :: ⟨.int, x⟩ :: locals) body)).isSome) + (some ⟨.bool, qdec (∀ x y z : Int, + boolOf (Term.eval env decls (⟨.int, z⟩ :: ⟨.int, y⟩ :: ⟨.int, x⟩ :: locals) body) = some true)⟩) + none := by + rw [Term.eval] + have h1 : (∀ xs : Srt.DenList [.int, .int, .int], + (boolOf (Term.eval env decls (bindAll [.int, .int, .int] xs locals) body)).isSome) = + ∀ x y z : Int, (boolOf (Term.eval env decls (⟨.int, z⟩ :: ⟨.int, y⟩ :: ⟨.int, x⟩ :: locals) body)).isSome := + propext ⟨fun h x y z => h (x, (y, (z, ()))), fun h p => h p.1 p.2.1 p.2.2.1⟩ + have h2 : (∀ xs : Srt.DenList [.int, .int, .int], + boolOf (Term.eval env decls (bindAll [.int, .int, .int] xs locals) body) = some true) = + ∀ x y z : Int, boolOf (Term.eval env decls (⟨.int, z⟩ :: ⟨.int, y⟩ :: ⟨.int, x⟩ :: locals) body) = some true := + propext ⟨fun h x y z => h (x, (y, (z, ()))), fun h p => h p.1 p.2.1 p.2.2.1⟩ + rw [h1, h2]; rfl + +/-- `forall` over 4 integers: the binders become Lean binders, the last one at the head of the locals. -/ +theorem eval_forall_int4 (env : Env) (decls : List Decl) (locals : Locals) (body : SolarVerify.Smt.Term) : + Term.eval env decls locals (.forall [.int, .int, .int, .int] body) = + qite (∀ x y z w : Int, (boolOf (Term.eval env decls (⟨.int, w⟩ :: ⟨.int, z⟩ :: ⟨.int, y⟩ :: ⟨.int, x⟩ :: locals) body)).isSome) + (some ⟨.bool, qdec (∀ x y z w : Int, + boolOf (Term.eval env decls (⟨.int, w⟩ :: ⟨.int, z⟩ :: ⟨.int, y⟩ :: ⟨.int, x⟩ :: locals) body) = some true)⟩) + none := by + rw [Term.eval] + have h1 : (∀ xs : Srt.DenList [.int, .int, .int, .int], + (boolOf (Term.eval env decls (bindAll [.int, .int, .int, .int] xs locals) body)).isSome) = + ∀ x y z w : Int, (boolOf (Term.eval env decls (⟨.int, w⟩ :: ⟨.int, z⟩ :: ⟨.int, y⟩ :: ⟨.int, x⟩ :: locals) body)).isSome := + propext ⟨fun h x y z w => h (x, (y, (z, (w, ())))), fun h p => h p.1 p.2.1 p.2.2.1 p.2.2.2.1⟩ + have h2 : (∀ xs : Srt.DenList [.int, .int, .int, .int], + boolOf (Term.eval env decls (bindAll [.int, .int, .int, .int] xs locals) body) = some true) = + ∀ x y z w : Int, boolOf (Term.eval env decls (⟨.int, w⟩ :: ⟨.int, z⟩ :: ⟨.int, y⟩ :: ⟨.int, x⟩ :: locals) body) = some true := + propext ⟨fun h x y z w => h (x, (y, (z, (w, ())))), fun h p => h p.1 p.2.1 p.2.2.1 p.2.2.2.1⟩ + rw [h1, h2]; rfl + +/-- `exists` over 2 integers: the binders become Lean binders, the last one at the head of the locals. -/ +theorem eval_exists_int2 (env : Env) (decls : List Decl) (locals : Locals) (body : SolarVerify.Smt.Term) : + Term.eval env decls locals (.exists [.int, .int] body) = + qite (∀ x y : Int, (boolOf (Term.eval env decls (⟨.int, y⟩ :: ⟨.int, x⟩ :: locals) body)).isSome) + (some ⟨.bool, qdec (∃ x y : Int, + boolOf (Term.eval env decls (⟨.int, y⟩ :: ⟨.int, x⟩ :: locals) body) = some true)⟩) + none := by + rw [Term.eval] + have h1 : (∀ xs : Srt.DenList [.int, .int], + (boolOf (Term.eval env decls (bindAll [.int, .int] xs locals) body)).isSome) = + ∀ x y : Int, (boolOf (Term.eval env decls (⟨.int, y⟩ :: ⟨.int, x⟩ :: locals) body)).isSome := + propext ⟨fun h x y => h (x, (y, ())), fun h p => h p.1 p.2.1⟩ + have h2 : (∃ xs : Srt.DenList [.int, .int], + boolOf (Term.eval env decls (bindAll [.int, .int] xs locals) body) = some true) = + ∃ x y : Int, boolOf (Term.eval env decls (⟨.int, y⟩ :: ⟨.int, x⟩ :: locals) body) = some true := + propext ⟨fun ⟨p, h⟩ => ⟨p.1, p.2.1, h⟩, fun ⟨x, y, h⟩ => ⟨(x, (y, ())), h⟩⟩ + rw [h1, h2]; rfl +/-- A value's view at its own sort. -/ +theorem as_self (s : Srt) (x : s.Den) : Val.as ⟨s, x⟩ s = some x := by + simp [Val.as] + +theorem as_int (x : Int) : Val.as ⟨.int, x⟩ .int = some x := rfl + +theorem as_bool (x : Bool) : Val.as ⟨.bool, x⟩ .bool = some x := rfl + +/-- A sort check that holds by reflexivity, at any instance. -/ +theorem dite_self {α : Sort u} {s : Srt} {_ : Decidable (s = s)} (t : s = s → α) (e : ¬s = s → α) : + dite (s = s) t e = t rfl := by + simp + +/-! A Boolean value as a value of sort `bool`: the same type, though not syntactically. -/ + +theorem isSome_some_den (b : Srt.Den .bool) : @Option.isSome Bool (@some (Srt.Den .bool) b) = true := + rfl + +theorem some_den_eq_some_true (b : Srt.Den .bool) : + (@Eq (Option Bool) (@some (Srt.Den .bool) b) (some true)) = ((b : Bool) = true) := + propext (Option.some_inj (α := Bool)) + +theorem holds_of {b : Bool} (h : b = true) : (some b : Option Bool) = some true := by + rw [h] + +theorem of_imp {a b : Bool} (h : a = true → b = true) : (!a || b) = true := by + cases a <;> cases b <;> simp_all + +theorem of_imp_and {a b : Bool} (h : a = true → b = true) : (!(a && true) || b) = true := by + cases a <;> cases b <;> simp_all + +/-- Unfolds the definitions of the exported module (namespace `SolarVerifyVc`) in the goal. -/ +def unfoldExported : TacticM Unit := withMainContext do + let g ← getMainGoal + let t ← instantiateMVars (← g.getType) + let t' ← deltaExpand t (fun n => n.getRoot == `SolarVerifyVc) + replaceMainGoal [← g.replaceTargetDefEq t'] + +/-- Replaces `Srt.Den s` by the Lean type it is for each concrete sort `s` in `e` (`Int`, `Bool`, +functions for arrays), and a classical `decide` by `qdec`. The result is definitionally equal; `simp` needs it, since it matches +`Bool` against `Srt.Den .bool` only up to reducible definitions. -/ +partial def normDen (e : Expr) : MetaM Expr := + Meta.transform e (post := fun e => do + if e.isAppOfArity ``SolarVerify.Smt.Srt.Den 1 && !(e.getArg! 0).hasLooseBVars && !(e.getArg! 0).hasFVar then + let r ← whnfD e + if r != e then return .done (← normDen r) + -- a classical `decide` whose instance names its proposition before `simp` rewrote it + if e.isAppOfArity ``Decidable.decide 2 && (e.getArg! 1).isAppOfArity ``Classical.propDecidable 1 then + return .done (mkApp (mkConst ``SolarVerify.Discharge.qdec) (e.getArg! 0)) + return .continue) + +/-- The subterms of `e` that are values of `env`'s symbols: `env.fn f [] s ()`, `env.divZero` and +`env.modZero`, with no loose bound variables. -/ +partial def envAtoms (env : Expr) (e : Expr) (acc : Array Expr := #[]) : Array Expr := + let isAtom := + !e.hasLooseBVars && + ((e.isAppOfArity ``SolarVerify.Smt.Env.fn 5 && e.getArg! 0 == env && (e.getArg! 2).isAppOfArity `List.nil 1) || + ((e.isAppOfArity ``SolarVerify.Smt.Env.divZero 1 || e.isAppOfArity ``SolarVerify.Smt.Env.modZero 1) && e.getArg! 0 == env)) + if isAtom then (if acc.contains e then acc else acc.push e) else + match e with + | .app f a => envAtoms env a (envAtoms env f acc) + | .lam _ t b _ | .forallE _ t b _ => envAtoms env b (envAtoms env t acc) + | .letE _ t v b _ => envAtoms env b (envAtoms env v (envAtoms env t acc)) + | .mdata _ b | .proj _ _ b => envAtoms env b acc + | _ => acc + +/-- Replaces each value of a symbol in the goal by a variable of its sort's Lean type, universally +quantified: the goal becomes `∀ x, G[x]`, which implies `G[env.fn f [] s ()]`. -/ +def generalizeAtoms (env : Expr) : TacticM Unit := withMainContext do + let g ← getMainGoal + let t ← instantiateMVars (← g.getType) + let atoms := envAtoms env t + let mut binders : Array (Name × Expr) := #[] + for (e, i) in atoms.zipIdx do + let ty ← normDen (← Meta.reduce (← inferType e) (skipTypes := false)) + let k := if e.getAppNumArgs ≥ 2 then (e.getArg! 1).nat? else none + binders := binders.push (Name.mkSimple (match k with | some k => s!"x{k}" | none => s!"z{i}"), ty) + let newTy ← withLocalDeclsD (binders.map fun (n, ty) => (n, fun _ => pure ty)) fun xs => do + let mut b := t + for (x, e) in xs.zip atoms do + b := (← kabstract b e).instantiate1 x + normDen (← mkForallFVars xs b) + let ng ← mkFreshExprSyntheticOpaqueMVar newTy + g.assign (mkAppN ng atoms) + replaceMainGoal [ng.mvarId!] + +end SolarVerify.Discharge + +/-- Runs the tactic unless an earlier step already closed the goal. -/ +def SolarVerify.Discharge.step (tac : Syntax) : TacticM Unit := do + unless (← getGoals).isEmpty do evalTactic tac + +/-- Evaluates the exported terms symbolically: see the module comment. -/ +macro "vc_eval" : tactic => `(tactic| simp -failIfUnchanged only [SolarVerify.Vc.Obligation.Valid, SolarVerify.Vc.Obligation.formula, + SolarVerify.Smt.Holds, ↓SolarVerify.Discharge.eval_forall_int, + ↓SolarVerify.Discharge.eval_exists_int, ↓SolarVerify.Discharge.eval_forall_int2, ↓SolarVerify.Discharge.eval_forall_int3, + ↓SolarVerify.Discharge.eval_forall_int4, ↓SolarVerify.Discharge.eval_exists_int2, SolarVerify.Smt.Term.eval, SolarVerify.Smt.Term.evalList, + SolarVerify.Smt.Op.apply, SolarVerify.Smt.boolOf, SolarVerify.Smt.bools, SolarVerify.Smt.ints, + SolarVerify.Smt.Val.asList, SolarVerify.Smt.intRel, SolarVerify.Smt.chain, + SolarVerify.Smt.impliesChain, SolarVerify.Smt.foldl2, SolarVerify.Smt.sameSort, + SolarVerify.Smt.pairwise, SolarVerify.Smt.intDiv, SolarVerify.Smt.intMod, Option.bind, + ↓SolarVerify.Discharge.dite_self, ↓SolarVerify.Discharge.beq_array, ↓SolarVerify.Discharge.as_int, ↓SolarVerify.Discharge.as_bool, SolarVerify.Smt.Val.as, + List.take, List.cons_append, List.nil_append, List.all, List.any, + List.reverse, List.reverseAux, List.foldl, id, bind, pure, List.getElem?_cons_succ, + List.getElem?_cons_zero, SolarVerify.Smt.Srt.beq, ↓reduceDIte, ↓reduceIte, Option.some.injEq, SolarVerify.Discharge.ite_val, SolarVerify.Discharge.ite_val_int, + SolarVerify.Smt.bindAll, SolarVerify.Smt.Srt.unpack, List.reverse_cons, List.reverse_nil, + List.singleton_append, SolarVerify.Discharge.forall_denList_nil, + SolarVerify.Discharge.forall_denList_cons, SolarVerify.Discharge.exists_denList_nil, + SolarVerify.Discharge.exists_denList_cons, SolarVerify.Discharge.forall_den_int, + SolarVerify.Discharge.forall_den_bool, SolarVerify.Discharge.exists_den_int, + SolarVerify.Discharge.exists_den_bool, SolarVerify.Discharge.decide_any_eq_true, + Option.isSome_some, implies_true, SolarVerify.Discharge.qite_true, + SolarVerify.Discharge.qdec_eq_true, eq_self_iff_true, dite_true, + SolarVerify.Discharge.isSome_some_den, SolarVerify.Discharge.some_den_eq_some_true, + Bool.and_true, Bool.not_not]) + +/-- Rewrites the goal with `normDen`. -/ +def SolarVerify.Discharge.normDenGoal : TacticM Unit := withMainContext do + let g ← getMainGoal + let t ← instantiateMVars (← g.getType) + replaceMainGoal [← g.replaceTargetDefEq (← normDen t)] + +open SolarVerify.Discharge in +/-- Reduces `Obligation.Valid ob` to a shallow goal `False` under its hypotheses. -/ +elab "vc_valid_prep" : tactic => do + unfoldExported + evalTactic (← `(tactic| unfold SolarVerify.Vc.Obligation.Valid)) + let (envFv, g) ← (← getMainGoal).intro `env + replaceMainGoal [g] + evalTactic (← `(tactic| vc_eval)) + unless (← getGoals).isEmpty do normDenGoal + step (← `(tactic| vc_eval)) + step (← `(tactic| first | refine SolarVerify.Discharge.holds_of ?_ | skip)) + unless (← getGoals).isEmpty do generalizeAtoms (.fvar envFv) + step (← `(tactic| intros)) + step (← `(tactic| first | apply SolarVerify.Discharge.of_imp_and | apply SolarVerify.Discharge.of_imp)) + step (← `(tactic| intro hyps)) + step (← `(tactic| simp -failIfUnchanged only [Bool.and_eq_true, Bool.or_eq_true, Bool.not_eq_true', + SolarVerify.Discharge.decide_any_eq_true, SolarVerify.Discharge.qdec_eq_true, decide_eq_true_eq, + decide_eq_false_iff_not, Bool.and_true, Bool.true_and] at *)) + step (← `(tactic| refine Classical.byContradiction ?_)) + step (← `(tactic| intro)) + step (← `(tactic| vc_split_hyps)) + -- a nested store applied to its inner key (IteApply.lean) + step (← `(tactic| all_goals simp -failIfUnchanged only [SolarVerify.Discharge.iteFunApply] at *)) + +/-- Proves `Obligation.Valid ob` for an exported obligation `ob`: see the module comment. -/ +macro "vc_valid" : tactic => `(tactic| (vc_valid_prep <;> vc_search)) diff --git a/Verify/Discharge/discharge.sh b/Verify/Discharge/discharge.sh new file mode 100755 index 00000000..d78072e5 --- /dev/null +++ b/Verify/Discharge/discharge.sh @@ -0,0 +1,364 @@ +#!/usr/bin/env bash +# Discharges in the Lean kernel the obligations 'solar-verify --emit-lean DIR' exported. An +# obligation is accepted only when a proof the kernel checks proves '.Valid' and, per row, +# Lean.collectAxioms reports no axiom but propext, Classical.choice and Quot.sound. Backends are +# untrusted: their sources are never inspected, a step one cannot justify ends as an error or a +# 'sorryAx' in that row's axioms, and the row fails. +# +# Backends (DISCHARGE_BACKENDS, 'name=tactic[@seconds];...', tried in order, each obligation +# stopping at the first that proves it; default 'smt=vc_smt;vc_valid=vc_valid@30'): +# +# vc_smt cvc5 refutes the goal through lean-cvc5's plugin and lean-smt rebuilds its proof +# step by step as a Lean term (Verify/Discharge/Reconstruct). +# vc_valid a proof the discharge library searches for itself (Verify/Discharge). +# cert a theorem written for the obligation, listed in DISCHARGE_CERTS (see below). +# +# '@seconds' caps that backend's attempt below TIMEOUT_SECONDS. Every backend runs against one +# build, the package in Verify/Discharge/Reconstruct (Lean v4.35.0, lean-smt 6b26285, lean-cvc5 +# d19a134), which compiles Verify/Obligation and Verify/Discharge from this repository's sources. +# +# Writes DIR/discharge/results.tsv (one row per required obligation and backend tried, with time, +# memory and axioms), DIR/discharge/summary.tsv (per obligation, the backend that proved it and +# whether its hypotheses are contradictory) and DIR/discharge/inputs.sha256, and exits 0 only +# when every required obligation is proved. A unit that was not exported, a missing, duplicate or +# changed input, an error, a timeout, another axiom, or a semantics that is not the one the +# export was written for is a failure, never a pass. +# +# Verify/Discharge/discharge.sh DIR [TIMEOUT_SECONDS] +# +# Environment: +# DISCHARGE_BACKENDS as above. +# DISCHARGE_ALL 1: try every backend on every obligation (coverage per backend) rather than +# stop at the first that proves it. +# DISCHARGE_VACUITY 1 (default): per required row, also try '{ ob with goal := .bool false }' +# with DISCHARGE_VACUITY_TACTIC (default vc_smt, at most 60 s): 'yes' when the +# kernel accepts it with clean axioms (the hypotheses are contradictory, so the +# row holds vacuously), 'no' when cvc5 finds a model of them, else 'unknown'. +# Informational: it never makes a row pass or fail. 0 skips it ('-'). +# DISCHARGE_ONLY a regex on obligation ids; the others are skipped (and the run fails). +# DISCHARGE_LOCK a sha256sum file of the inputs (as inputs.sha256 is written): the run fails +# unless the manifest and every exported module match it. +# DISCHARGE_CERTS for backend 'cert': a TSV of 'idmoduletheorem'. The probe imports +# the module and states 'theorem obligation : .Valid := ', so the +# kernel checks that the theorem proves exactly the exported obligation. +# DISCHARGE_CERT_PATH LEAN_PATH entries where those modules are built, searched after the +# compiled exports; none may hold a module named like an exported one. +# DISCHARGE_CERT_EXPORTS the directory of the exported modules those modules import: each +# must equal the locked input (or its copy with the import read as below), and +# every exported module must be there. +# DISCHARGE_SOURCE_ROOT the repository root the manifest's sources are named relative to: +# each must hash as the manifest says, and inputs.sha256 then lists them. +# DISCHARGE_INPUTS_ONLY 1: check the inputs only, then stop before any Lean runs. +# DISCHARGE_HEAVY a command to prefix the library build with (a build-slot wrapper). +# +# The exported modules say 'import SolarVerify' (solar's former Lean package); they are compiled +# with that line read as 'import Verify.Obligation', the same library under its path here. The +# manifest's semantics hashes must match Verify/Obligation/Smt.lean and Vc.lean, Vc.lean read +# with its first line as 'import SolarVerify.Smt' when the export predates the move. +set -euo pipefail +dir=$(cd "$1" && pwd) +limit=${2:-600} +here=$(cd "$(dirname "$0")" && pwd) +root=$(cd "$here/../.." && pwd) +export LEAN_NUM_THREADS=${LEAN_NUM_THREADS:-1} +heavy=${DISCHARGE_HEAVY:-} +manifest="$dir/manifest.json" +# The toolchain this repository pins, wherever the script runs lean from. +leanbin=$(cd "$root" && elan which lean 2>/dev/null || command -v lean) +allowed="propext Classical.choice Quot.sound" +pkg="$root/Verify/Discharge/Reconstruct" +plugin="$pkg/.lake/packages/cvc5/.lake/build/lib/libcvc5_cvc5.so" +IFS=';' read -r -a backends <<<"${DISCHARGE_BACKENDS:-smt=vc_smt;vc_valid=vc_valid@30}" +vacuity=${DISCHARGE_VACUITY:-1} +vac_tactic=${DISCHARGE_VACUITY_TACTIC:-vc_smt} +only=${DISCHARGE_ONLY:-} +out="$dir/discharge" +rm -rf "$out" +mkdir -p "$out/src" + +fail() { echo "error: $*" >&2; exit 1; } +# name=tactic[@seconds] per backend. +declare -A btactic blimit +bnames=() +for b in "${backends[@]}"; do + [[ $b =~ ^([A-Za-z0-9_]+)=(vc_smt|vc_valid|cert)(@([0-9]+))?$ ]] || fail "backend $b is not name=vc_smt|vc_valid|cert[@seconds]" + name=${BASH_REMATCH[1]} + [[ -z ${btactic[$name]:-} ]] || fail "backend $name listed twice" + btactic[$name]=${BASH_REMATCH[2]} + blimit[$name]=$limit + if [[ -n ${BASH_REMATCH[4]} && ${BASH_REMATCH[4]} -lt $limit ]]; then blimit[$name]=${BASH_REMATCH[4]}; fi + bnames+=("$name") +done +[[ ${#bnames[@]} -gt 0 ]] || fail "no backend" +case $vac_tactic in vc_smt|vc_valid) ;; *) fail "DISCHARGE_VACUITY_TACTIC is vc_smt or vc_valid" ;; esac +[[ $(jq -r .format "$manifest") == solar-verify-lean ]] || fail "not a solar-verify-lean manifest" +[[ $(jq -r .version "$manifest") == 2 ]] || fail "format version $(jq -r .version "$manifest"), this checker reads 2" +# Version 2 names every source relative to the repository root it was exported from, so that an +# export and its lock mean the same files on every machine; run.json (the run's own record, such +# as solver versions and timings) is neither read nor hashed. +nonportable=$(jq -r '(.sources // [])[] | .path | select(type != "string" or startswith("/") or test("(^|/)\\.\\.?(/|$)") or contains("\\") or . == "")' "$manifest") +[[ -z $nonportable ]] || fail "sources not named relative to the repository root: $nonportable" +[[ $(jq '(.sources // []) | length' "$manifest") -gt 0 ]] || fail "the manifest names no sources" +badmod=$(jq -r '.units[] | .module // empty | select(startswith("/") or test("(^|/)\\.\\.?(/|$)") or contains("\\") or (endswith(".lean") | not))' "$manifest") +[[ -z $badmod ]] || fail "modules not named relative to the export: $badmod" + +# The proofs must read the terms with the semantics they were written for. +smt_have=$(sha256sum "$root/Verify/Obligation/Smt.lean" | cut -d' ' -f1) +vc_have=$(sha256sum "$root/Verify/Obligation/Vc.lean" | cut -d' ' -f1) +vc_legacy=$(sed '1s/^import Verify\.Obligation\.Smt$/import SolarVerify.Smt/' "$root/Verify/Obligation/Vc.lean" | sha256sum | cut -d' ' -f1) +[[ $(jq -r '.lean.smt_sha256 // empty' "$manifest") == "$smt_have" ]] || fail "Verify/Obligation/Smt.lean is not the one the export was written for" +vc_want=$(jq -r '.lean.vc_sha256 // empty' "$manifest") +[[ $vc_want == "$vc_have" || $vc_want == "$vc_legacy" ]] || fail "Verify/Obligation/Vc.lean is not the one the export was written for" + +# The statement the obligations are read in (Verify/Obligation) may assume nothing beyond the +# kernel. Proof libraries and backends are not read here: each row's axioms decide. +if grep -rnE '\b(sorry|admit|native_decide|bv_decide|ofReduceBool|ofReduceNat|implemented_by|extern|unsafe|axiom|decide \+native)\b' \ + "$root"/Verify/Obligation.lean "$root"/Verify/Obligation; then + fail "the obligation library uses a construct the kernel does not check" +fi + +# Every list is read whole before any lean runs: Lean's runtime inherits the descriptor a +# 'while read ... done < <(...)' loop reads from, and the loop then ends early. +mapfile -t modules < <(jq -r '.units[] | select(.module != null) | .module' "$manifest" | sort -u) +mapfile -t rows < <(jq -r '.units[] | select(.module != null) as $u | $u.obligations[] | select(.required) | [$u.module, .id, .lean, .role, .answer] | @tsv' "$manifest") +mapfile -t unexported < <(jq -r '.units[] | select(.module == null) | [.name, (.status // "not-exported")] | @tsv' "$manifest") +want=$(jq '[.units[] | .obligations[]? | select(.required)] | length' "$manifest") +total=$(jq '[.units[] | .obligations[]?] | length' "$manifest") +dups=$(jq -r '([.units[] | .obligations[]? | .id], [.units[] | .obligations[]? | select(.required) | .lean]) | group_by(.) | map(select(length > 1) | .[0]) | .[]' "$manifest") +[[ -z $dups ]] || fail "listed twice: $dups" +for module in "${modules[@]}"; do + [[ -f $dir/$module ]] || fail "missing exported module $module" +done +(cd "$dir" && sha256sum manifest.json "${modules[@]}") >"$out/inputs.sha256" +# The sources, from the repository root they are named relative to, must be the ones exported. +mapfile -t sources < <(jq -r '.sources[] | [.path, .sha256] | @tsv' "$manifest") +if [[ -n ${DISCHARGE_SOURCE_ROOT:-} ]]; then + srcroot=$(cd "$DISCHARGE_SOURCE_ROOT" && pwd) + srcpaths=() + for s in "${sources[@]}"; do + IFS=$'\t' read -r path sha <<<"$s" + [[ -f $srcroot/$path ]] || fail "missing source $path" + have=$(sha256sum "$srcroot/$path" | cut -d' ' -f1) + [[ $have == "$sha" ]] || fail "source $path is not the one exported" + srcpaths+=("$path") + done + (cd "$srcroot" && sha256sum "${srcpaths[@]}") >>"$out/inputs.sha256" +fi +# Every obligation a module defines is listed, and every listed one is defined: an obligation +# deleted from the manifest fails here even without a lock. +mapfile -t units < <(jq -r '.units[] | select(.module != null) | [.module, (.obligations | length), ([.obligations[].lean | split(".") | last] | join(" "))] | @tsv' "$manifest") +for u in "${units[@]}"; do + IFS=$'\t' read -r module n names <<<"$u" + defined=$(grep -cE '^def ob[0-9]+ : Obligation' "$dir/$module" || true) + [[ $defined -eq $n ]] || fail "$module defines $defined obligations, the manifest lists $n" + for nm in $names; do + grep -qE "^def $nm : Obligation" "$dir/$module" || fail "$module does not define $nm" + done +done +if [[ -n ${DISCHARGE_LOCK:-} ]]; then + diff <(sort -k2 "$DISCHARGE_LOCK") <(sort -k2 "$out/inputs.sha256") >&2 \ + || fail "the inputs are not the ones $DISCHARGE_LOCK pins" +fi +nunexp=$(jq '[.units[] | select(.module == null) | .obligations[]? | select(.required)] | length' "$manifest") +[[ $(( ${#rows[@]} + nunexp )) -eq $want ]] || fail "$want required obligations, ${#rows[@]} with a module" +echo "discharge: ${#modules[@]} modules, $want required of $total obligations, ${#unexported[@]} units not exported; backends ${backends[*]}" >&2 + +# Certificates written as theorems: the exports they were written against must be every locked +# input, and nothing on their LEAN_PATH may hold a module of the export's name, which would shadow +# the compiled input. The probe's LEAN_PATH puts the compiled inputs first in any case. +declare -A certmod certthm +if [[ " ${btactic[*]} " == *" cert "* ]]; then + [[ -n ${DISCHARGE_CERTS:-} && -f $DISCHARGE_CERTS ]] || fail "backend cert needs DISCHARGE_CERTS" + [[ -n ${DISCHARGE_CERT_EXPORTS:-} && -d $DISCHARGE_CERT_EXPORTS ]] || fail "backend cert needs DISCHARGE_CERT_EXPORTS" + for module in "${modules[@]}"; do + f="$DISCHARGE_CERT_EXPORTS/$module" + [[ -f $f ]] || fail "the certificates' exports lack $module" + sed '1,20s/^import SolarVerify$/import Verify.Obligation/' "$dir/$module" | cmp -s "$f" - || cmp -s "$f" "$dir/$module" \ + || fail "the certificates import a $module that is not the exported one" + done + IFS=':' read -r -a certpath <<<"${DISCHARGE_CERT_PATH:-}" + for p in "${certpath[@]}"; do + [[ -n $p ]] || continue + for module in "${modules[@]}"; do + mod=${module%.lean} + for ext in olean ilean lean; do + [[ ! -e $p/$mod.$ext ]] || fail "DISCHARGE_CERT_PATH entry $p holds $mod.$ext, which would shadow the exported module" + done + done + done + mapfile -t certrows < <(grep -v '^#' "$DISCHARGE_CERTS" | grep -v '^$' || true) + for c in "${certrows[@]}"; do + IFS=$'\t' read -r cid cmod cthm <<<"$c" + [[ -n $cid && -n $cmod && -n $cthm ]] || fail "certificate row '$c' is not idmoduletheorem" + [[ -z ${certthm[$cid]:-} ]] || fail "two certificates for $cid" + certmod[$cid]=$cmod + certthm[$cid]=$cthm + done +fi + +# DISCHARGE_INPUTS_ONLY=1 stops here, after every check of the inputs and before any Lean runs. +if [[ ${DISCHARGE_INPUTS_ONLY:-0} == 1 ]]; then + echo "inputs: ok" >&2 + exit 0 +fi + +# The exported modules with the library's import path. +for module in "${modules[@]}"; do + mkdir -p "$out/src/$(dirname "$module")" + sed '1,20s/^import SolarVerify$/import Verify.Obligation/' "$dir/$module" >"$out/src/$module" + grep -q '^import Verify.Obligation$' "$out/src/$module" || fail "$module does not import the obligation library" +done + +# One library for every backend, and the exports compiled against it. +(cd "$pkg" && $heavy lake build -KleanMemory=3000 -q &2) || fail "could not build $pkg" +lp=$(cd "$pkg" && lake env printenv LEAN_PATH) +[[ -f $plugin ]] || fail "missing the cvc5 plugin $plugin" +mkdir -p "$out/build" +for module in "${modules[@]}"; do + mod=${module%.lean} + mkdir -p "$out/build/$(dirname "$mod")" + (cd "$out/src" && LEAN_PATH="$lp:$out/build" "$leanbin" -R "$out/src" -o "$out/build/$mod.olean" "$out/src/$module" /dev/null) \ + || fail "could not compile the exported module $module" +done + +# Runs a command and prints its wall time and peak memory as 'MEMTIME seconds megabytes'. +measure() { + python3 -c ' +import resource, subprocess, sys, time +t = time.time() +r = subprocess.run(sys.argv[1:], stdin=subprocess.DEVNULL) +mb = resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss // 1024 +sys.stderr.write("MEMTIME %.1f %d\n" % (time.time() - t, mb)) +sys.exit(r.returncode)' "$@" +} + +results="$out/results.tsv" +printf 'id\trole\tanswer\tbackend\tstatus\tseconds\tpeak_mb\taxioms\n' >"$results" +summary="$out/summary.tsv" +printf 'id\trole\tanswer\tstatus\tbackends\tvacuous\n' >"$summary" +pass=0 bad=0 +for row in "${unexported[@]}"; do + [[ -n $row ]] || continue + IFS=$'\t' read -r name status <<<"$row" + printf '%s\t-\t-\t-\tfailed: unit not exported (%s)\t0\t-\t-\n' "$name" "$status" >>"$results" + printf '%s\t-\t-\tfailed: unit not exported (%s)\t-\t-\n' "$name" "$status" >>"$summary" + bad=$((bad + 1)) +done + +# One probe: states 'obligation : STMT', proves it with TACTIC, reports its axioms, under LIM s. +probe_one() { + local tactic=$1 tag=$2 id=$3 stmt=$4 modname=$5 lim=$6 probe proof imports res code + local extra=() plp="$lp:$out/build" + mkdir -p "$out/probe" + probe="$out/probe/$(echo "$id.$tag" | tr -c 'A-Za-z0-9_\n' '_').lean" + case $tactic in + vc_valid) imports="import Verify.Discharge"; proof="by vc_valid" ;; + vc_smt) imports="import Verify.Discharge.Reconstruct.Tactic"; proof="by vc_smt"; extra=("--plugin=$plugin") ;; + cert) + if [[ -z ${certthm[$id]:-} ]]; then echo NOCERT; return 0; fi + imports="import Verify.Discharge +import ${certmod[$id]}" + proof="${certthm[$id]}" + plp="$plp${DISCHARGE_CERT_PATH:+:$DISCHARGE_CERT_PATH}" ;; + esac + { + echo "$imports" + echo "import $modname" + echo + echo "theorem obligation : $stmt := $proof" + echo + echo "open Lean Elab Command in" + echo "#eval show CommandElabM Unit from do" + echo " let axs ← Lean.collectAxioms (Name.mkSimple \"obligation\")" + echo " IO.println s!\"AXIOMS: {String.intercalate \" \" (axs.toList.map toString)}\"" + } >"$probe" + set +e + res=$(cd "$out/probe" && LEAN_PATH="$plp" measure timeout "$lim" "$leanbin" "${extra[@]}" -DmaxHeartbeats=0 -DmaxRecDepth=100000 "$probe" 2>&1) + code=$? + set -e + printf 'CODE %s\n%s\n' "$code" "$res" +} + +# The verdict on one probe's output: sets status ('proved' or 'failed: '), secs, peak and +# axioms. Proved only on exit 0, no error, an axiom report, and only the allowed axioms. +verdict() { + local res=$1 lim=$2 code body a + code=$(printf '%s\n' "$res" | sed -n '1s/^CODE //p') + body=$(printf '%s\n' "$res" | sed 1d) + secs=$(printf '%s\n' "$body" | sed -n 's/^MEMTIME \([^ ]*\) .*/\1/p') + peak=$(printf '%s\n' "$body" | sed -n 's/^MEMTIME [^ ]* //p') + axioms=$(printf '%s\n' "$body" | sed -n 's/^AXIOMS: *//p') + status=proved + if [[ $code -eq 124 ]]; then + status="failed: timeout after ${lim}s" + elif [[ $code -ne 0 ]] || grep -q 'error' <<<"$body"; then + # Here-strings, not pipes from printf: grep stopping at its first match must not end the + # script by SIGPIPE under pipefail. + status="failed: $(grep -m1 -A2 'error' <<<"$body" | tr '\t\n' ' ' | cut -c1-240)" + elif [[ -z $axioms ]]; then + status="failed: no axiom report" + else + for a in $axioms; do + [[ " $allowed " == *" $a "* ]] || status="failed: uses axiom $a" + done + fi +} + +for row in "${rows[@]}"; do + IFS=$'\t' read -r module id lean role answer <<<"$row" + if [[ -n $only && ! $id =~ $only ]]; then + printf '%s\t%s\t%s\t-\tfailed: skipped\t0\t-\t-\n' "$id" "$role" "$answer" >>"$results" + printf '%s\t%s\t%s\tfailed: skipped\t-\t-\n' "$id" "$role" "$answer" >>"$summary" + bad=$((bad + 1)); continue + fi + modname=${module%.lean} + modname=${modname//\//.} + proving=() + for name in "${bnames[@]}"; do + res=$(probe_one "${btactic[$name]}" "$name" "$id" "$lean.Valid" "$modname" "${blimit[$name]}") + if [[ $res == NOCERT ]]; then + printf '%s\t%s\t%s\t%s\tfailed: no certificate\t0\t-\t-\n' "$id" "$role" "$answer" "$name" >>"$results" + continue + fi + verdict "$res" "${blimit[$name]}" + printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$id" "$role" "$answer" "$name" "$status" "${secs:-0}" "${peak:--}" "${axioms:-none}" >>"$results" + echo "$name: $status $id (${secs:-0}s, ${peak:--} MB)" >&2 + if [[ $status == proved ]]; then + proving+=("$name") + [[ ${DISCHARGE_ALL:-0} == 1 ]] || break + fi + done + # Vacuity: are the row's hypotheses alone contradictory? It never changes the verdict. + vac=- + if [[ $vacuity == 1 ]]; then + vlim=$(( limit < 60 ? limit : 60 )) + res=$(probe_one "$vac_tactic" vacuity "$id" "({ $lean with goal := .bool false } : SolarVerify.Vc.Obligation).Valid" "$modname" "$vlim") + verdict "$res" "$vlim" + if [[ $status == proved ]]; then vac=yes + elif [[ $status == *"either it is false"* ]]; then vac=no + else vac=unknown + fi + echo "vacuity: $vac $id" >&2 + fi + if [[ ${#proving[@]} -gt 0 ]]; then + printf '%s\t%s\t%s\tproved\t%s\t%s\n' "$id" "$role" "$answer" "$(IFS=,; echo "${proving[*]}")" "$vac" >>"$summary" + pass=$((pass + 1)) + else + printf '%s\t%s\t%s\tfailed\t-\t%s\n' "$id" "$role" "$answer" "$vac" >>"$summary" + bad=$((bad + 1)) + fi +done + +if [[ $((pass + bad - ${#unexported[@]})) -ne ${#rows[@]} ]]; then + echo "error: ${#rows[@]} exported required obligations, $((pass + bad - ${#unexported[@]})) checked" >&2 + bad=$((want - pass)) +fi +for name in "${bnames[@]}"; do + n=$(awk -F'\t' -v k="$name" '$4 == k && $5 == "proved"' "$results" | wc -l) + echo "discharge: backend $name proved $n" >&2 +done +if [[ $vacuity == 1 ]]; then + echo "discharge: $(awk -F'\t' '$6 == "yes"' "$summary" | wc -l) rows hold vacuously (summary.tsv, column vacuous)" >&2 +fi +echo "discharge: $pass of $want required obligations proved, $bad not ($summary)" >&2 +[[ $bad -eq 0 && $pass -eq $want ]] diff --git a/Verify/Discharge/frozen/ArrayMax.sha256 b/Verify/Discharge/frozen/ArrayMax.sha256 new file mode 100644 index 00000000..62894797 --- /dev/null +++ b/Verify/Discharge/frozen/ArrayMax.sha256 @@ -0,0 +1,5 @@ +fd6ba812db32525b609d720b646fa1db1c6f847553ffe5689aa569c0a0213241 manifest.json +1a02fe322248251cb404d8f56ad9110bbf4ead96cf56ad1117976351eeca0f5a ArrayMax/clamp.lean +a39b2942dcd59cf63faa1ced3aa86bb2834f362bfa894d7be9878f0ba66a44c6 ArrayMax/max.lean +fdda1a5f2c6049ddb1b7136571217dc2d743845728edbd4bbc4cfe2256ef5bd9 ArrayMaxEntry/constructor.lean +9bd919a6e290d34c0723dd1529e9bd64004112cd5c1ba5c91d13425f080329ed ArrayMaxEntry/max.lean diff --git a/Verify/Discharge/frozen/Counter.sha256 b/Verify/Discharge/frozen/Counter.sha256 new file mode 100644 index 00000000..f7b81750 --- /dev/null +++ b/Verify/Discharge/frozen/Counter.sha256 @@ -0,0 +1,5 @@ +98c3c05695d52e1801de6a84ebe49e85f619850a17143583859d2e17e4bde305 manifest.json +4bb27f47e1eced3ed032dbcbcecb69ed2b4632fb0f00f63ad112aa0da7727c0e Counter/bump.lean +a481a4b1e0dc5c77a83729023e710e268cd1c3aa4cdf281a9c5bcc03e1efbcdf Counter/constructor.lean +a60ddafeeec741a6c6f69fe958b7df8f94fb003a0a848024a0e04515e3ce4c74 Counter/increment.lean +cd1d94b409422123ddeb4f7340c349f5eb148e67b1edd1271388bdcffbf4e567 Counter/max.lean diff --git a/Verify/Discharge/frozen/PINS b/Verify/Discharge/frozen/PINS new file mode 100644 index 00000000..fb5b60bd --- /dev/null +++ b/Verify/Discharge/frozen/PINS @@ -0,0 +1,8 @@ +exporter paradigmxyz/solar 7f4e94e065c8e90c2e8d265813533c71cd59c1dc (solar-verify --emit-lean, release build) +sources crates/verify/examples/{Counter,Token,Vault,ArrayMax}.sol at that commit +command solar-verify --emit-lean vc-exports/ crates/verify/examples/.sol, from the repository root +semantics SolarVerify/Smt.lean 2c92f3bcd927369da89250662bd5a6174d3c06d0c3c38f5021509fe8810036e3 + SolarVerify/Vc.lean 7275fa354f077a4826dd9fe56124cbffee2337d7a21975b477534fc5f45d7cfe +toolchain leanprover/lean4:v4.35.0 +solvers z3 4.13.4, cvc5 1.3.1 (recorded in each manifest) +required Counter 14, Token 13, Vault 17, ArrayMax 19 (63) diff --git a/Verify/Discharge/frozen/Token.sha256 b/Verify/Discharge/frozen/Token.sha256 new file mode 100644 index 00000000..45b64a05 --- /dev/null +++ b/Verify/Discharge/frozen/Token.sha256 @@ -0,0 +1,5 @@ +86b2d80ed2642128959ac13bf9dbbc34ad69206dd2e100cfceb8ea6889a2b2f8 manifest.json +7c3e619cb4f5c051df2bee25f1bd6227b815bccda2471249090e0f2e6fbff187 Token/burn.lean +bb81d4917461c58b296936eb8bfc4d3092ffb768a02814deca6e92811d4ff0a7 Token/constructor.lean +e87f0a2d6ebb9410a449656844b724df569d84c317afeb866f1f1a2845b4d2a1 Token/mint.lean +fa074a46ec5bd2686cae08af09ec1af0aecd1aa5eb7720ef1896f237886cc246 Token/transfer.lean diff --git a/Verify/Discharge/frozen/Vault.sha256 b/Verify/Discharge/frozen/Vault.sha256 new file mode 100644 index 00000000..0014a46c --- /dev/null +++ b/Verify/Discharge/frozen/Vault.sha256 @@ -0,0 +1,4 @@ +2589125ac7c0b22969b81edb8b4f4bba10b7404351cd3e1276974c2b25849edb manifest.json +93b5b6971bf6f4c4c907a55e8d270c15b831e41ce858493d1c02da1ddcacfc41 Vault/constructor.lean +de6d589769c68862abcf874f9f8a316923ce34478346ebd2ef62d9af5cd0ca74 Vault/deposit.lean +b7fc9bfd454493489523a9c64689393906408761f5f5fb42612e2fdd4b71320a Vault/withdraw.lean diff --git a/Verify/Discharge/frozen/v2/ArrayMax.sha256 b/Verify/Discharge/frozen/v2/ArrayMax.sha256 new file mode 100644 index 00000000..893d1608 --- /dev/null +++ b/Verify/Discharge/frozen/v2/ArrayMax.sha256 @@ -0,0 +1,6 @@ +dcc0c005e8cbca26ada22669566face573161ce024ca35e78e988cffaf6c9d3d manifest.json +1a02fe322248251cb404d8f56ad9110bbf4ead96cf56ad1117976351eeca0f5a ArrayMax/clamp.lean +a39b2942dcd59cf63faa1ced3aa86bb2834f362bfa894d7be9878f0ba66a44c6 ArrayMax/max.lean +fdda1a5f2c6049ddb1b7136571217dc2d743845728edbd4bbc4cfe2256ef5bd9 ArrayMaxEntry/constructor.lean +9bd919a6e290d34c0723dd1529e9bd64004112cd5c1ba5c91d13425f080329ed ArrayMaxEntry/max.lean +904535ac694498a9823f530ca158ee0c762fd1adcc56f3e7b73ca0e457e61f4a crates/verify/examples/ArrayMax.sol diff --git a/Verify/Discharge/frozen/v2/Counter.sha256 b/Verify/Discharge/frozen/v2/Counter.sha256 new file mode 100644 index 00000000..5c504e93 --- /dev/null +++ b/Verify/Discharge/frozen/v2/Counter.sha256 @@ -0,0 +1,6 @@ +3752220c134c4b5e09b90bc4cc198341a7b7c76a8ed6e65513de7a5b47247f9f manifest.json +4bb27f47e1eced3ed032dbcbcecb69ed2b4632fb0f00f63ad112aa0da7727c0e Counter/bump.lean +a481a4b1e0dc5c77a83729023e710e268cd1c3aa4cdf281a9c5bcc03e1efbcdf Counter/constructor.lean +a60ddafeeec741a6c6f69fe958b7df8f94fb003a0a848024a0e04515e3ce4c74 Counter/increment.lean +cd1d94b409422123ddeb4f7340c349f5eb148e67b1edd1271388bdcffbf4e567 Counter/max.lean +f1c87a334b8db31fc8f80541febeaf8617318d20b685634f44e26c74146ad326 crates/verify/examples/Counter.sol diff --git a/Verify/Discharge/frozen/v2/PINS b/Verify/Discharge/frozen/v2/PINS new file mode 100644 index 00000000..79d1f164 --- /dev/null +++ b/Verify/Discharge/frozen/v2/PINS @@ -0,0 +1,18 @@ +status PROVISIONAL. These locks are not the output of a version-2 exporter run: they were + derived by hand from the version-1 exports below (the manifest rewritten to version 2, + each source named relative to the repository root), and stand in until solar-verify's + own format-2 export of the same sources, with the same solvers, replaces them. The + version-1 locks (../.sha256, ../PINS) stay as they were. A format-2 export by the + verify crate's current exporter on this machine (z3 4.8.12, no cvc5) is not + comparable: its required sets differ (Counter 63, Token 13, Vault 17, ArrayMax 51), so + regenerating needs the exporter commit and solver versions pinned with it. +format solar-verify-lean version 2 +derived from the version-1 exports frozen/PINS names (solar 7f4e94e, regenerated byte-identical + to frozen/.sha256): manifest.json with version 2 and each source named relative to + the repository root (crates/verify/examples/.sol); every module is unchanged, as + the module lines of frozen/.sha256 and frozen/v2/.sha256 show +lock frozen/v2/.sha256 lists manifest.json and the modules relative to the export + directory, then the sources relative to the repository root (DISCHARGE_SOURCE_ROOT) +check DISCHARGE_LOCK=frozen/v2/.sha256 DISCHARGE_SOURCE_ROOT= + Verify/Discharge/discharge.sh +required Counter 14, Token 13, Vault 17, ArrayMax 19 (63) diff --git a/Verify/Discharge/frozen/v2/Token.sha256 b/Verify/Discharge/frozen/v2/Token.sha256 new file mode 100644 index 00000000..4f84c276 --- /dev/null +++ b/Verify/Discharge/frozen/v2/Token.sha256 @@ -0,0 +1,6 @@ +ca345407953c0f38594ec92a836909667756115648a5fb362b8ecfe7158e9854 manifest.json +7c3e619cb4f5c051df2bee25f1bd6227b815bccda2471249090e0f2e6fbff187 Token/burn.lean +bb81d4917461c58b296936eb8bfc4d3092ffb768a02814deca6e92811d4ff0a7 Token/constructor.lean +e87f0a2d6ebb9410a449656844b724df569d84c317afeb866f1f1a2845b4d2a1 Token/mint.lean +fa074a46ec5bd2686cae08af09ec1af0aecd1aa5eb7720ef1896f237886cc246 Token/transfer.lean +45b62aa1152c4ec09e76735ac7257a06bf3e4be0f435fdacdc174f41e8c8e75c crates/verify/examples/Token.sol diff --git a/Verify/Discharge/frozen/v2/Vault.sha256 b/Verify/Discharge/frozen/v2/Vault.sha256 new file mode 100644 index 00000000..f303de56 --- /dev/null +++ b/Verify/Discharge/frozen/v2/Vault.sha256 @@ -0,0 +1,5 @@ +b529bd7e3e8b9820785433e8af56262d5fade9247285007e2ff20d0206c697e6 manifest.json +93b5b6971bf6f4c4c907a55e8d270c15b831e41ce858493d1c02da1ddcacfc41 Vault/constructor.lean +de6d589769c68862abcf874f9f8a316923ce34478346ebd2ef62d9af5cd0ca74 Vault/deposit.lean +b7fc9bfd454493489523a9c64689393906408761f5f5fb42612e2fdd4b71320a Vault/withdraw.lean +0e2017a2679b3fc98aa539d29ce350f9776dd0d14a0085aed88d9b26a9921526 crates/verify/examples/Vault.sol diff --git a/Verify/Discharge/results/v2/ArrayMax/inputs.sha256 b/Verify/Discharge/results/v2/ArrayMax/inputs.sha256 new file mode 100644 index 00000000..893d1608 --- /dev/null +++ b/Verify/Discharge/results/v2/ArrayMax/inputs.sha256 @@ -0,0 +1,6 @@ +dcc0c005e8cbca26ada22669566face573161ce024ca35e78e988cffaf6c9d3d manifest.json +1a02fe322248251cb404d8f56ad9110bbf4ead96cf56ad1117976351eeca0f5a ArrayMax/clamp.lean +a39b2942dcd59cf63faa1ced3aa86bb2834f362bfa894d7be9878f0ba66a44c6 ArrayMax/max.lean +fdda1a5f2c6049ddb1b7136571217dc2d743845728edbd4bbc4cfe2256ef5bd9 ArrayMaxEntry/constructor.lean +9bd919a6e290d34c0723dd1529e9bd64004112cd5c1ba5c91d13425f080329ed ArrayMaxEntry/max.lean +904535ac694498a9823f530ca158ee0c762fd1adcc56f3e7b73ca0e457e61f4a crates/verify/examples/ArrayMax.sol diff --git a/Verify/Discharge/results/v2/ArrayMax/results.tsv b/Verify/Discharge/results/v2/ArrayMax/results.tsv new file mode 100644 index 00000000..a7abee54 --- /dev/null +++ b/Verify/Discharge/results/v2/ArrayMax/results.tsv @@ -0,0 +1,20 @@ +id role answer backend status seconds peak_mb axioms +ArrayMax.max#0 obligation unsat smt proved 2.3 1789 propext Classical.choice Quot.sound +ArrayMax.max#1 obligation unsat smt proved 2.4 1791 propext Classical.choice Quot.sound +ArrayMax.max#2 obligation unsat smt proved 2.7 1801 propext Classical.choice Quot.sound +ArrayMax.max#3 obligation unsat smt proved 2.7 1797 propext Classical.choice Quot.sound +ArrayMax.max#4 obligation unsat smt proved 2.7 1800 propext Classical.choice Quot.sound +ArrayMax.max#5 obligation unsat smt proved 2.3 1789 propext Classical.choice Quot.sound +ArrayMax.max#6 obligation unsat smt proved 4.0 1855 propext Classical.choice Quot.sound +ArrayMax.max#7 obligation unsat smt proved 3.9 1855 propext Classical.choice Quot.sound +ArrayMax.max#8 obligation unsat smt proved 4.6 1885 propext Classical.choice Quot.sound +ArrayMax.max#9 obligation unsat smt proved 4.4 1878 propext Classical.choice Quot.sound +ArrayMax.max#10 obligation unsat smt proved 4.5 1879 propext Classical.choice Quot.sound +ArrayMax.max#11 obligation unsat smt proved 3.9 1855 propext Classical.choice Quot.sound +ArrayMax.max#12 obligation unsat smt proved 4.1 1858 propext Classical.choice Quot.sound +ArrayMax.max#14 obligation unsat smt proved 4.1 1854 propext Classical.choice Quot.sound +ArrayMax.max#15 obligation unsat smt proved 4.1 1836 propext Classical.choice Quot.sound +ArrayMax.clamp#1 obligation unsat smt proved 2.5 1793 propext Classical.choice Quot.sound +ArrayMaxEntry.max#0 obligation unsat smt proved 2.5 1786 propext Classical.choice Quot.sound +ArrayMaxEntry.max#2 obligation unsat smt proved 3.0 1803 propext Classical.choice Quot.sound +ArrayMaxEntry.max#3 obligation unsat smt proved 2.8 1802 propext Classical.choice Quot.sound diff --git a/Verify/Discharge/results/v2/ArrayMax/summary.tsv b/Verify/Discharge/results/v2/ArrayMax/summary.tsv new file mode 100644 index 00000000..87fd431b --- /dev/null +++ b/Verify/Discharge/results/v2/ArrayMax/summary.tsv @@ -0,0 +1,20 @@ +id role answer status backends vacuous +ArrayMax.max#0 obligation unsat proved smt no +ArrayMax.max#1 obligation unsat proved smt no +ArrayMax.max#2 obligation unsat proved smt no +ArrayMax.max#3 obligation unsat proved smt no +ArrayMax.max#4 obligation unsat proved smt no +ArrayMax.max#5 obligation unsat proved smt no +ArrayMax.max#6 obligation unsat proved smt unknown +ArrayMax.max#7 obligation unsat proved smt unknown +ArrayMax.max#8 obligation unsat proved smt unknown +ArrayMax.max#9 obligation unsat proved smt unknown +ArrayMax.max#10 obligation unsat proved smt unknown +ArrayMax.max#11 obligation unsat proved smt unknown +ArrayMax.max#12 obligation unsat proved smt unknown +ArrayMax.max#14 obligation unsat proved smt unknown +ArrayMax.max#15 obligation unsat proved smt unknown +ArrayMax.clamp#1 obligation unsat proved smt no +ArrayMaxEntry.max#0 obligation unsat proved smt no +ArrayMaxEntry.max#2 obligation unsat proved smt unknown +ArrayMaxEntry.max#3 obligation unsat proved smt unknown diff --git a/Verify/Discharge/results/v2/Counter/inputs.sha256 b/Verify/Discharge/results/v2/Counter/inputs.sha256 new file mode 100644 index 00000000..5c504e93 --- /dev/null +++ b/Verify/Discharge/results/v2/Counter/inputs.sha256 @@ -0,0 +1,6 @@ +3752220c134c4b5e09b90bc4cc198341a7b7c76a8ed6e65513de7a5b47247f9f manifest.json +4bb27f47e1eced3ed032dbcbcecb69ed2b4632fb0f00f63ad112aa0da7727c0e Counter/bump.lean +a481a4b1e0dc5c77a83729023e710e268cd1c3aa4cdf281a9c5bcc03e1efbcdf Counter/constructor.lean +a60ddafeeec741a6c6f69fe958b7df8f94fb003a0a848024a0e04515e3ce4c74 Counter/increment.lean +cd1d94b409422123ddeb4f7340c349f5eb148e67b1edd1271388bdcffbf4e567 Counter/max.lean +f1c87a334b8db31fc8f80541febeaf8617318d20b685634f44e26c74146ad326 crates/verify/examples/Counter.sol diff --git a/Verify/Discharge/results/v2/Counter/results.tsv b/Verify/Discharge/results/v2/Counter/results.tsv new file mode 100644 index 00000000..f2f323ba --- /dev/null +++ b/Verify/Discharge/results/v2/Counter/results.tsv @@ -0,0 +1,15 @@ +id role answer backend status seconds peak_mb axioms +Counter.constructor#1 obligation unsat smt proved 2.5 1783 propext Classical.choice Quot.sound +Counter.constructor#2 obligation unsat smt proved 2.6 1783 propext Classical.choice Quot.sound +Counter.increment#1 obligation unsat smt proved 2.5 1791 propext Classical.choice Quot.sound +Counter.increment#2 obligation unsat smt proved 2.7 1794 propext Classical.choice Quot.sound +Counter.bump#0 obligation unsat smt proved 2.4 1799 propext Classical.choice Quot.sound +Counter.bump#1 obligation unsat smt proved 2.6 1799 propext Classical.choice Quot.sound +Counter.bump#2 obligation unsat smt proved 3.2 1819 propext Classical.choice Quot.sound +Counter.bump#3 obligation unsat smt proved 3.1 1820 propext Classical.choice Quot.sound +Counter.bump#4 obligation unsat smt proved 3.3 1821 propext Classical.choice Quot.sound +Counter.bump#6 obligation unsat smt proved 3.1 1826 propext Classical.choice Quot.sound +Counter.bump#7 obligation unsat smt proved 3.0 1828 propext Classical.choice Quot.sound +Counter.max#1 obligation unsat smt proved 3.0 1806 propext Classical.choice Quot.sound +Counter.max#2 obligation unsat smt proved 2.7 1809 propext Classical.choice Quot.sound +Counter.max#3 obligation settled smt proved 2.5 1800 propext Classical.choice Quot.sound diff --git a/Verify/Discharge/results/v2/Counter/summary.tsv b/Verify/Discharge/results/v2/Counter/summary.tsv new file mode 100644 index 00000000..5a3203ee --- /dev/null +++ b/Verify/Discharge/results/v2/Counter/summary.tsv @@ -0,0 +1,15 @@ +id role answer status backends vacuous +Counter.constructor#1 obligation unsat proved smt no +Counter.constructor#2 obligation unsat proved smt no +Counter.increment#1 obligation unsat proved smt no +Counter.increment#2 obligation unsat proved smt no +Counter.bump#0 obligation unsat proved smt no +Counter.bump#1 obligation unsat proved smt no +Counter.bump#2 obligation unsat proved smt no +Counter.bump#3 obligation unsat proved smt no +Counter.bump#4 obligation unsat proved smt no +Counter.bump#6 obligation unsat proved smt no +Counter.bump#7 obligation unsat proved smt no +Counter.max#1 obligation unsat proved smt no +Counter.max#2 obligation unsat proved smt no +Counter.max#3 obligation settled proved smt no diff --git a/Verify/Discharge/results/v2/README.md b/Verify/Discharge/results/v2/README.md new file mode 100644 index 00000000..60594d10 --- /dev/null +++ b/Verify/Discharge/results/v2/README.md @@ -0,0 +1,38 @@ +# Default backends on the frozen version-2 locks + +Kernel-checked proofs of the 63 required obligations of the four example exports, by +`Verify/Discharge/discharge.sh` with its defaults (`DISCHARGE_BACKENDS='smt=vc_smt;vc_valid=vc_valid@30'`, +vacuity on), 120 s per attempt, `LEAN_NUM_THREADS=1`. Formula-level evidence only: each row +proves `.Valid` over Verify/Obligation; nothing here relates the SMT encoding to source or +bytecode semantics. + +Inputs: the exports frozen/v2/.sha256 pins (provisional, see frozen/v2/PINS), each run with +`DISCHARGE_LOCK=frozen/v2/.sha256` and `DISCHARGE_SOURCE_ROOT` a paradigmxyz/solar checkout at +7f4e94e; each `/inputs.sha256` equals its lock. Backend: Verify/Discharge/Reconstruct (Lean +v4.35.0, lean-smt 6b26285, lean-cvc5 d19a134 with its bundled cvc5, in-process via `--plugin`). + +| Contract | Proved | By smt | By vc_valid | Vacuous | +|---|---|---|---|---| +| Counter | 14/14 | 14 | 0 | 0 | +| Token | 13/13 | 13 | 0 | 0 | +| Vault | 17/17 | 17 | 0 | 5 | +| ArrayMax | 19/19 | 19 | 0 | 0 | +| Total | 63/63 | 63 | 0 | 5 | + +Every proof's axioms are exactly `propext Classical.choice Quot.sound` (`/results.tsv`, +column axioms). smt took at most 6.4 s and 1,885 MB per obligation, 219 s for all 63; the +vc_valid fallback was never needed. + +Vacuous (`/summary.tsv`, column vacuous): the kernel also proves `{ ob with goal := .bool false }` +for Vault.deposit#6, deposit#7, withdraw#6, withdraw#7 and withdraw#8, all in the script that +re-enters while `locked`: their hypotheses are contradictory, so they hold only because that path +is unreachable. Of the other 58, cvc5 finds a model of the hypotheses for 27 (`no`) and gives up +on 31 (`unknown`, quantified hypotheses). + +Negatives: test/negatives.sh, 11/11 on each of the four exports (input mismatches, including a +missing certificate export and a stale same-name module on the certificate path, all failing +before any Lean runs). test/smt-negatives.sh, run with both default backends (`smt-negatives.tsv`): every +edited obligation fails under smt by a cvc5 model (N2, N3; "either it is false") or an +incomplete answer (N4), in at most 3.7 s, never a timeout, while the same untouched rows are +proved. vc_valid fails N2, N3 and N4 on Vault by an omega counterexample, but the negated ArrayMax +max#8 only by its 30 s timeout, so the script now checks the smt backend alone by default. diff --git a/Verify/Discharge/results/v2/Token/inputs.sha256 b/Verify/Discharge/results/v2/Token/inputs.sha256 new file mode 100644 index 00000000..4f84c276 --- /dev/null +++ b/Verify/Discharge/results/v2/Token/inputs.sha256 @@ -0,0 +1,6 @@ +ca345407953c0f38594ec92a836909667756115648a5fb362b8ecfe7158e9854 manifest.json +7c3e619cb4f5c051df2bee25f1bd6227b815bccda2471249090e0f2e6fbff187 Token/burn.lean +bb81d4917461c58b296936eb8bfc4d3092ffb768a02814deca6e92811d4ff0a7 Token/constructor.lean +e87f0a2d6ebb9410a449656844b724df569d84c317afeb866f1f1a2845b4d2a1 Token/mint.lean +fa074a46ec5bd2686cae08af09ec1af0aecd1aa5eb7720ef1896f237886cc246 Token/transfer.lean +45b62aa1152c4ec09e76735ac7257a06bf3e4be0f435fdacdc174f41e8c8e75c crates/verify/examples/Token.sol diff --git a/Verify/Discharge/results/v2/Token/results.tsv b/Verify/Discharge/results/v2/Token/results.tsv new file mode 100644 index 00000000..5e0ff333 --- /dev/null +++ b/Verify/Discharge/results/v2/Token/results.tsv @@ -0,0 +1,14 @@ +id role answer backend status seconds peak_mb axioms +Token.constructor#1 obligation unsat smt proved 1.9 1757 propext Classical.choice Quot.sound +Token.constructor#2 obligation unsat smt proved 2.0 1756 propext Classical.choice Quot.sound +Token.mint#1 obligation unsat smt proved 3.5 1821 propext Classical.choice Quot.sound +Token.mint#2 obligation unsat smt proved 4.1 1816 propext Classical.choice Quot.sound +Token.mint#3 obligation unsat smt proved 4.6 1831 propext Classical.choice Quot.sound +Token.mint#4 obligation unsat smt proved 5.5 1819 propext Classical.choice Quot.sound +Token.transfer#1 obligation unsat smt proved 4.6 1835 propext Classical.choice Quot.sound +Token.transfer#2 obligation unsat smt proved 4.0 1837 propext Classical.choice Quot.sound +Token.transfer#3 obligation unsat smt proved 4.4 1840 propext Classical.choice Quot.sound +Token.transfer#4 obligation unsat smt proved 3.1 1789 propext Classical.choice Quot.sound +Token.transfer#5 obligation settled smt proved 3.4 1824 propext Classical.choice Quot.sound +Token.burn#1 obligation unsat smt proved 3.4 1811 propext Classical.choice Quot.sound +Token.burn#2 obligation unsat smt proved 3.0 1810 propext Classical.choice Quot.sound diff --git a/Verify/Discharge/results/v2/Token/summary.tsv b/Verify/Discharge/results/v2/Token/summary.tsv new file mode 100644 index 00000000..4f245d82 --- /dev/null +++ b/Verify/Discharge/results/v2/Token/summary.tsv @@ -0,0 +1,14 @@ +id role answer status backends vacuous +Token.constructor#1 obligation unsat proved smt no +Token.constructor#2 obligation unsat proved smt no +Token.mint#1 obligation unsat proved smt unknown +Token.mint#2 obligation unsat proved smt unknown +Token.mint#3 obligation unsat proved smt unknown +Token.mint#4 obligation unsat proved smt unknown +Token.transfer#1 obligation unsat proved smt unknown +Token.transfer#2 obligation unsat proved smt unknown +Token.transfer#3 obligation unsat proved smt unknown +Token.transfer#4 obligation unsat proved smt unknown +Token.transfer#5 obligation settled proved smt unknown +Token.burn#1 obligation unsat proved smt unknown +Token.burn#2 obligation unsat proved smt unknown diff --git a/Verify/Discharge/results/v2/Vault/inputs.sha256 b/Verify/Discharge/results/v2/Vault/inputs.sha256 new file mode 100644 index 00000000..f303de56 --- /dev/null +++ b/Verify/Discharge/results/v2/Vault/inputs.sha256 @@ -0,0 +1,5 @@ +b529bd7e3e8b9820785433e8af56262d5fade9247285007e2ff20d0206c697e6 manifest.json +93b5b6971bf6f4c4c907a55e8d270c15b831e41ce858493d1c02da1ddcacfc41 Vault/constructor.lean +de6d589769c68862abcf874f9f8a316923ce34478346ebd2ef62d9af5cd0ca74 Vault/deposit.lean +b7fc9bfd454493489523a9c64689393906408761f5f5fb42612e2fdd4b71320a Vault/withdraw.lean +0e2017a2679b3fc98aa539d29ce350f9776dd0d14a0085aed88d9b26a9921526 crates/verify/examples/Vault.sol diff --git a/Verify/Discharge/results/v2/Vault/results.tsv b/Verify/Discharge/results/v2/Vault/results.tsv new file mode 100644 index 00000000..360ea828 --- /dev/null +++ b/Verify/Discharge/results/v2/Vault/results.tsv @@ -0,0 +1,18 @@ +id role answer backend status seconds peak_mb axioms +Vault.constructor#1 obligation unsat smt proved 2.6 1759 propext Classical.choice Quot.sound +Vault.constructor#2 obligation unsat smt proved 3.5 1784 propext Classical.choice Quot.sound +Vault.deposit#0 side unsat smt proved 3.7 1775 propext Classical.choice Quot.sound +Vault.deposit#2 obligation unsat smt proved 6.4 1841 propext Classical.choice Quot.sound +Vault.deposit#3 obligation unsat smt proved 3.3 1804 propext Classical.choice Quot.sound +Vault.deposit#4 obligation unsat smt proved 3.7 1840 propext Classical.choice Quot.sound +Vault.deposit#5 obligation unsat smt proved 5.1 1843 propext Classical.choice Quot.sound +Vault.deposit#6 side unsat smt proved 3.1 1769 propext Classical.choice Quot.sound +Vault.deposit#7 obligation unsat smt proved 4.2 1832 propext Classical.choice Quot.sound +Vault.withdraw#0 obligation unsat smt proved 3.5 1832 propext Classical.choice Quot.sound +Vault.withdraw#1 side unsat smt proved 2.9 1796 propext Classical.choice Quot.sound +Vault.withdraw#3 obligation unsat smt proved 4.0 1803 propext Classical.choice Quot.sound +Vault.withdraw#4 obligation unsat smt proved 5.6 1843 propext Classical.choice Quot.sound +Vault.withdraw#5 obligation unsat smt proved 4.7 1844 propext Classical.choice Quot.sound +Vault.withdraw#6 obligation unsat smt proved 5.3 1824 propext Classical.choice Quot.sound +Vault.withdraw#7 side unsat smt proved 3.5 1791 propext Classical.choice Quot.sound +Vault.withdraw#8 obligation unsat smt proved 3.8 1837 propext Classical.choice Quot.sound diff --git a/Verify/Discharge/results/v2/Vault/summary.tsv b/Verify/Discharge/results/v2/Vault/summary.tsv new file mode 100644 index 00000000..606db0f4 --- /dev/null +++ b/Verify/Discharge/results/v2/Vault/summary.tsv @@ -0,0 +1,18 @@ +id role answer status backends vacuous +Vault.constructor#1 obligation unsat proved smt no +Vault.constructor#2 obligation unsat proved smt no +Vault.deposit#0 side unsat proved smt no +Vault.deposit#2 obligation unsat proved smt unknown +Vault.deposit#3 obligation unsat proved smt unknown +Vault.deposit#4 obligation unsat proved smt unknown +Vault.deposit#5 obligation unsat proved smt unknown +Vault.deposit#6 side unsat proved smt yes +Vault.deposit#7 obligation unsat proved smt yes +Vault.withdraw#0 obligation unsat proved smt unknown +Vault.withdraw#1 side unsat proved smt unknown +Vault.withdraw#3 obligation unsat proved smt unknown +Vault.withdraw#4 obligation unsat proved smt unknown +Vault.withdraw#5 obligation unsat proved smt unknown +Vault.withdraw#6 obligation unsat proved smt yes +Vault.withdraw#7 side unsat proved smt yes +Vault.withdraw#8 obligation unsat proved smt yes diff --git a/Verify/Discharge/results/v2/smt-negatives.tsv b/Verify/Discharge/results/v2/smt-negatives.tsv new file mode 100644 index 00000000..31325805 --- /dev/null +++ b/Verify/Discharge/results/v2/smt-negatives.tsv @@ -0,0 +1,11 @@ +case backend id status seconds peak_mb axioms +N2-goal smt Counter.increment#1 failed: Counter_increment_1_smt.lean:4:69: error: unable to prove goal, either it is false or you need to provide more facts. Try adding '+model' config option to display a potential counter-example (experiment 2.5 1789 propext sorryAx Classical.choice Quot.sound +N2-goal vc_valid Counter.increment#1 failed: Counter_increment_1_vc_valid.lean:4:69: error: omega could not prove the goal: a possible counterexample may satisfy the constraints 0 ≤ q ≤ 1157920892373161954235709850086879078532699846656405640 2.3 1586 propext sorryAx Classical.choice Quot.sound +N3-assert smt Counter.increment#1 failed: Counter_increment_1_smt.lean:4:69: error: unable to prove goal, either it is false or you need to provide more facts. Try adding '+model' config option to display a potential counter-example (experiment 2.6 1788 propext sorryAx Classical.choice Quot.sound +N3-assert vc_valid Counter.increment#1 failed: Counter_increment_1_vc_valid.lean:4:69: error: omega could not prove the goal: a possible counterexample may satisfy the constraints 0 ≤ q ≤ 1157920892373161954235709850086879078532699846656405640 2.4 1586 propext sorryAx Classical.choice Quot.sound +N3-assert smt Counter.increment#2 failed: Counter_increment_2_smt.lean:4:69: error: unable to prove goal, either it is false or you need to provide more facts. Try adding '+model' config option to display a potential counter-example (experiment 2.4 1788 propext sorryAx Classical.choice Quot.sound +N3-assert vc_valid Counter.increment#2 failed: Counter_increment_2_vc_valid.lean:4:69: error: omega could not prove the goal: a possible counterexample may satisfy the constraints 0 ≤ p ≤ 1157920892373161954235709850086879078532699846656405640 2.1 1586 propext sorryAx Classical.choice Quot.sound +N4-withdraw0-negated smt Vault.withdraw#0 failed: Vault_withdraw_0_smt.lean:4:66: error: unable to prove goal. Try providing more hints. Reason: INCOMPLETE AXIOMS: propext sorryAx Classical.choice Quot.sound MEMTIME 3.1 1820 3.1 1820 propext sorryAx Classical.choice Quot.sound +N4-withdraw0-negated vc_valid Vault.withdraw#0 failed: Vault_withdraw_0_vc_valid.lean:4:66: error: omega could not prove the goal: a possible counterexample may satisfy the constraints 0 ≤ t ≤ 1157920892373161954235709850086879078532699846656405640394 2.9 1617 propext sorryAx Classical.choice Quot.sound +N4-max8-negated smt ArrayMax.max#8 failed: ArrayMax_max_8_smt.lean:4:64: error: unable to prove goal. Try providing more hints. Reason: INCOMPLETE AXIOMS: propext sorryAx Classical.choice Quot.sound MEMTIME 3.7 1835 3.7 1835 propext sorryAx Classical.choice Quot.sound +N4-max8-negated vc_valid ArrayMax.max#8 failed: timeout after 30s 30.1 2687 none diff --git a/Verify/Discharge/test/negatives.sh b/Verify/Discharge/test/negatives.sh new file mode 100755 index 00000000..9247f81e --- /dev/null +++ b/Verify/Discharge/test/negatives.sh @@ -0,0 +1,141 @@ +#!/usr/bin/env bash +# Negative checks of discharge.sh's inputs: each corrupts one input of a frozen export and requires +# the run to fail with the expected message before any Lean runs (by mismatch, never a timeout). +# +# Verify/Discharge/test/negatives.sh EXPORT_DIR LOCK SOURCE_ROOT +# +# EXPORT_DIR is a format-2 export that passes LOCK (frozen/v2/.sha256) with SOURCE_ROOT. +set -euo pipefail +src=$(cd "$1" && pwd) +lock=$(cd "$(dirname "$2")" && pwd)/$(basename "$2") +root=$(cd "$3" && pwd) +here=$(cd "$(dirname "$0")/.." && pwd) +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +pass=0 bad=0 + +# A copy of the export and of its sources, under a root of their own. +fresh() { + rm -rf "$work/x" "$work/root" + mkdir -p "$work/x" "$work/root" + (cd "$src" && tar cf - --exclude=./discharge --exclude='./discharge-*' .) | (cd "$work/x" && tar xf -) + mapfile -t paths < <(jq -r '.sources[].path' "$src/manifest.json") + for path in "${paths[@]}"; do + mkdir -p "$work/root/$(dirname "$path")" + cp "$root/$path" "$work/root/$path" + done +} + +check() { + if [[ $1 == lock ]]; then + DISCHARGE_LOCK="$lock" DISCHARGE_SOURCE_ROOT="$work/root" DISCHARGE_INPUTS_ONLY=1 "$here/discharge.sh" "$work/x" 2>&1 + else + DISCHARGE_SOURCE_ROOT="$work/root" DISCHARGE_INPUTS_ONLY=1 "$here/discharge.sh" "$work/x" 2>&1 + fi +} + +# expect NAME MESSAGE lock|nolock: the input checks fail with MESSAGE. +expect() { + local name=$1 msg=$2 out code + set +e + out=$(check "$3") + code=$? + set -e + if [[ $code -ne 0 ]] && grep -qF -- "$msg" <<<"$out" && ! grep -q '^inputs: ok' <<<"$out"; then + echo "ok: $name"; pass=$((pass + 1)) + else + echo "FAILED: $name (exit $code): $(tail -2 <<<"$out" | tr '\n' ' ')"; bad=$((bad + 1)) + fi +} + +fresh +set +e +out=$(check lock) +code=$? +set -e +if [[ $code -eq 0 ]] && grep -q '^inputs: ok' <<<"$out"; then + echo "ok: the untouched export passes"; pass=$((pass + 1)) +else + echo "FAILED: the untouched export: $out"; bad=$((bad + 1)) +fi + +fresh +s=$(jq -r '.sources[0].path' "$work/x/manifest.json") +echo '// edited' >>"$work/root/$s" +expect "edited source" "source $s is not the one exported" lock + +fresh +m=$(jq -r '[.units[] | .module // empty][0]' "$work/x/manifest.json") +sed -i 's/^set_option maxRecDepth 100000$/set_option maxRecDepth 100001/' "$work/x/$m" +expect "edited module" "are not the ones" lock + +fresh +jq '(.units[] | select(.module != null) | select([.obligations[] | select(.required)] | length > 0) | .obligations) |= (map(select(.required | not)) + (map(select(.required)) | .[1:]))' \ + "$work/x/manifest.json" >"$work/m" +mv "$work/m" "$work/x/manifest.json" +expect "deleted required obligation, no lock" "obligations, the manifest lists" nolock + +fresh +jq '(.units[[.units[] | .module != null] | index(true)].obligations) |= (. + [.[-1]])' \ + "$work/x/manifest.json" >"$work/m" +mv "$work/m" "$work/x/manifest.json" +expect "duplicated obligation" "listed twice" nolock + +fresh +jq --arg r "$root" '.sources[0].path = ($r + "/" + .sources[0].path)' "$work/x/manifest.json" >"$work/m" +mv "$work/m" "$work/x/manifest.json" +expect "absolute source path" "sources not named relative to the repository root" nolock + +fresh +jq '.version = 1' "$work/x/manifest.json" >"$work/m" +mv "$work/m" "$work/x/manifest.json" +expect "format version 1" "this checker reads 2" nolock + +# Certificates written as theorems (backend cert): the exports they were written against must be +# every locked module, and no DISCHARGE_CERT_PATH entry may hold a module named like an export. +certsetup() { + rm -rf "$work/cx" "$work/cp" + mkdir -p "$work/cx" "$work/cp" + (cd "$work/x" && tar cf - --exclude=./manifest.json --exclude='./*.smt2' --exclude='./*/*.smt2' .) | (cd "$work/cx" && tar xf -) + m1=$(jq -r '[.units[] | .module // empty][0]' "$work/x/manifest.json") + c1=$(jq -r '[.units[] | select(.module != null) | .obligations[] | select(.required) | .id][0]' "$work/x/manifest.json") + printf '%s\tCert.Module\tCert.theorem\n' "$c1" >"$work/certs.tsv" +} +certcheck() { + DISCHARGE_LOCK="$lock" DISCHARGE_SOURCE_ROOT="$work/root" DISCHARGE_INPUTS_ONLY=1 DISCHARGE_BACKENDS='cert=cert' \ + DISCHARGE_CERTS="$work/certs.tsv" DISCHARGE_CERT_EXPORTS="$work/cx" DISCHARGE_CERT_PATH="$work/cp" \ + "$here/discharge.sh" "$work/x" 2>&1 +} +certexpect() { + local name=$1 msg=$2 out code + set +e + out=$(certcheck) + code=$? + set -e + if [[ -z $msg && $code -eq 0 ]] && grep -q '^inputs: ok' <<<"$out"; then + echo "ok: $name"; pass=$((pass + 1)) + elif [[ -n $msg && $code -ne 0 ]] && grep -qF -- "$msg" <<<"$out" && ! grep -q '^inputs: ok' <<<"$out"; then + echo "ok: $name"; pass=$((pass + 1)) + else + echo "FAILED: $name (exit $code): $(tail -2 <<<"$out" | tr '\n' ' ')"; bad=$((bad + 1)) + fi +} + +fresh; certsetup +certexpect "certificate inputs, untouched" "" + +fresh; certsetup +rm "$work/cx/$m1" +certexpect "missing certificate export" "the certificates' exports lack $m1" + +fresh; certsetup +echo '-- edited' >>"$work/cx/$m1" +certexpect "edited certificate export" "the certificates import a $m1 that is not the exported one" + +fresh; certsetup +mkdir -p "$work/cp/$(dirname "$m1")" +: >"$work/cp/${m1%.lean}.olean" +certexpect "stale same-name module on the certificate path" "which would shadow the exported module" + +echo "negatives: $pass passed, $bad failed" +[[ $bad -eq 0 ]] diff --git a/Verify/Discharge/test/sat/Sat.lean b/Verify/Discharge/test/sat/Sat.lean new file mode 100644 index 00000000..960ef397 --- /dev/null +++ b/Verify/Discharge/test/sat/Sat.lean @@ -0,0 +1,58 @@ +import Verify.Discharge.Sat +/-! +Checks of the SAT certificate library on a small proof, run with +`LEAN_PATH=/.lake/build/lib/lean lean Sat.lean` from this directory +after `lake build VerifyDischarge`. + +`b8.cnf` is Lean's bit-blasting of `(x &&& y) + (x ||| y) = x + y` over 8 bits, negated, and +`b8.lrat` CaDiCaL's LRAT proof that it is unsatisfiable. +-/ +open SolarVerify.Sat + +-- The whole proof in one kernel evaluation. +sat_load b8 "b8.cnf" "b8.lrat" +theorem b8_check : Cnf.Unsat b8.cnf := check_sound b8.cnf b8.proof (by decide +kernel) + +/-- info: 'b8_check' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms b8_check + +-- One kernel-checked lemma per step. +namespace stepwise +sat_prove b8 "b8.cnf" "b8.lrat" +end stepwise + +/-- info: 'stepwise.b8.unsat' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms stepwise.b8.unsat + +-- x1 and not x1: the empty clause follows from clauses 1 and 2. +example : check [[2], [3]] (.step ⟨3, [], [1, 2]⟩) = true := by decide +kernel +-- x1 and x2 are satisfiable: the same step does not check. +example : check [[2], [4]] (.step ⟨3, [], [1, 2]⟩) = false := by decide +kernel +-- A hint naming no clause fails. +example : check [[2], [3]] (.step ⟨3, [], [1, 7]⟩) = false := by decide +kernel +-- A proof that never adds the empty clause fails. +example : check [[2, 4], [3]] (.step ⟨3, [4], [1, 2]⟩) = false := by decide +kernel + +-- Mutations of the real proof's inputs. Each flips the first literal of one clause of b8.cnf; +-- CaDiCaL finds every one of these mutated formulas satisfiable, so the proof must not check. +def flipFirst : Cnf → Nat → Cnf + | [], _ => [] + | c :: cs, 0 => (match c with | [] => [] | l :: ls => Lit.neg l :: ls) :: cs + | c :: cs, n + 1 => c :: flipFirst cs n + +example : check (flipFirst b8.cnf 4) b8.proof = false := by decide +kernel +example : check (flipFirst b8.cnf 120) b8.proof = false := by decide +kernel +example : check (flipFirst b8.cnf 346) b8.proof = false := by decide +kernel +-- Dropping the last clause shifts no IDs but removes a clause the proof needs. +example : check b8.cnf.dropLast b8.proof = false := by decide +kernel + +-- vc_ground: a closed hypothesis that the kernel evaluates to false closes the goal. +example (h : ¬ ((511#256 &&& 255#256).toNat = 255)) : False := by vc_ground +example (h : (0xff#8 - (1#8 ||| 2#8 ||| 4#8)) &&& 0x05#8 ≠ 0#8) : False := by vc_ground +-- A closed hypothesis that holds, or one with a free variable, gives no contradiction. +/-- error: vc_ground: no closed hypothesis is false -/ +#guard_msgs in +example (h : (511#256 &&& 255#256).toNat = 255) : False := by vc_ground +/-- error: vc_ground: no closed hypothesis is false -/ +#guard_msgs in +example (x : BitVec 8) (h : x &&& 0xf8#8 ≠ 0#8) : False := by vc_ground diff --git a/Verify/Discharge/test/sat/b8.cnf b/Verify/Discharge/test/sat/b8.cnf new file mode 100644 index 00000000..175ab9a3 --- /dev/null +++ b/Verify/Discharge/test/sat/b8.cnf @@ -0,0 +1,348 @@ +p cnf 168 347 +8 -159 0 +-8 159 0 +16 -167 0 +-16 167 0 +-24 8 0 +-24 16 0 +24 -8 -16 0 +-32 -8 0 +-32 -16 0 +32 8 16 0 +-72 24 0 +-72 -32 0 +72 -24 32 0 +7 -158 0 +-7 158 0 +15 -166 0 +-15 166 0 +-23 7 0 +-23 15 0 +23 -7 -15 0 +-31 -7 0 +-31 -15 0 +31 7 15 0 +-65 23 0 +-65 -31 0 +65 -23 31 0 +6 -157 0 +-6 157 0 +14 -165 0 +-14 165 0 +-22 6 0 +-22 14 0 +22 -6 -14 0 +-30 -6 0 +-30 -14 0 +30 6 14 0 +-58 22 0 +-58 -30 0 +58 -22 30 0 +5 -156 0 +-5 156 0 +13 -164 0 +-13 164 0 +-21 5 0 +-21 13 0 +21 -5 -13 0 +-29 -5 0 +-29 -13 0 +29 5 13 0 +-51 21 0 +-51 -29 0 +51 -21 29 0 +4 -155 0 +-4 155 0 +12 -163 0 +-12 163 0 +-20 4 0 +-20 12 0 +20 -4 -12 0 +-28 -4 0 +-28 -12 0 +28 4 12 0 +-44 20 0 +-44 -28 0 +44 -20 28 0 +3 -154 0 +-3 154 0 +11 -162 0 +-11 162 0 +-19 3 0 +-19 11 0 +19 -3 -11 0 +-27 -3 0 +-27 -11 0 +27 3 11 0 +-37 19 0 +-37 -27 0 +37 -19 27 0 +2 -153 0 +-2 153 0 +10 -161 0 +-10 161 0 +-18 2 0 +-18 10 0 +18 -2 -10 0 +-26 -2 0 +-26 -10 0 +26 2 10 0 +-34 18 0 +-34 -26 0 +34 -18 26 0 +-19 -27 39 0 +-19 27 -39 0 +19 27 39 0 +19 -27 -39 0 +-40 34 0 +-40 39 0 +40 -34 -39 0 +-43 -37 0 +-43 -40 0 +43 37 40 0 +-20 -28 46 0 +-20 28 -46 0 +20 28 46 0 +20 -28 -46 0 +-47 -43 0 +-47 46 0 +47 43 -46 0 +-50 -44 0 +-50 -47 0 +50 44 47 0 +-21 -29 53 0 +-21 29 -53 0 +21 29 53 0 +21 -29 -53 0 +-54 -50 0 +-54 53 0 +54 50 -53 0 +-57 -51 0 +-57 -54 0 +57 51 54 0 +-22 -30 60 0 +-22 30 -60 0 +22 30 60 0 +22 -30 -60 0 +-61 -57 0 +-61 60 0 +61 57 -60 0 +-64 -58 0 +-64 -61 0 +64 58 61 0 +-23 -31 67 0 +-23 31 -67 0 +23 31 67 0 +23 -31 -67 0 +-68 -64 0 +-68 67 0 +68 64 -67 0 +-71 -65 0 +-71 -68 0 +71 65 68 0 +-24 -32 74 0 +-24 32 -74 0 +24 32 74 0 +24 -32 -74 0 +-75 -71 0 +-75 74 0 +75 71 -74 0 +-78 -72 0 +-78 -75 0 +78 72 75 0 +9 -160 0 +-9 160 0 +17 -168 0 +-17 168 0 +-25 9 0 +-25 17 0 +25 -9 -17 0 +-33 -9 0 +-33 -17 0 +33 9 17 0 +-25 -33 81 0 +-25 33 -81 0 +25 33 81 0 +25 -33 -81 0 +78 81 84 0 +78 -81 -84 0 +-78 -81 84 0 +-78 81 -84 0 +-3 11 87 0 +-3 -11 -87 0 +3 -11 87 0 +3 11 -87 0 +-88 18 0 +-88 87 0 +88 -18 -87 0 +-91 -19 0 +-91 -88 0 +91 19 88 0 +-4 12 92 0 +-4 -12 -92 0 +4 -12 92 0 +4 12 -92 0 +-93 -91 0 +-93 92 0 +93 91 -92 0 +-96 -20 0 +-96 -93 0 +96 20 93 0 +-5 13 97 0 +-5 -13 -97 0 +5 -13 97 0 +5 13 -97 0 +-98 -96 0 +-98 97 0 +98 96 -97 0 +-101 -21 0 +-101 -98 0 +101 21 98 0 +-6 14 102 0 +-6 -14 -102 0 +6 -14 102 0 +6 14 -102 0 +-103 -101 0 +-103 102 0 +103 101 -102 0 +-106 -22 0 +-106 -103 0 +106 22 103 0 +-7 15 107 0 +-7 -15 -107 0 +7 -15 107 0 +7 15 -107 0 +-108 -106 0 +-108 107 0 +108 106 -107 0 +-111 -23 0 +-111 -108 0 +111 23 108 0 +-8 16 112 0 +-8 -16 -112 0 +8 -16 112 0 +8 16 -112 0 +-113 -111 0 +-113 112 0 +113 111 -112 0 +-116 -24 0 +-116 -113 0 +116 24 113 0 +-9 17 117 0 +-9 -17 -117 0 +9 -17 117 0 +9 17 -117 0 +116 117 120 0 +116 -117 -120 0 +-116 -117 120 0 +-116 117 -120 0 +-84 -120 145 0 +-84 120 -145 0 +84 120 145 0 +84 -120 -145 0 +71 74 77 0 +71 -74 -77 0 +-71 -74 77 0 +-71 74 -77 0 +111 112 115 0 +111 -112 -115 0 +-111 -112 115 0 +-111 112 -115 0 +-77 -115 142 0 +-77 115 -142 0 +77 115 142 0 +77 -115 -142 0 +64 67 70 0 +64 -67 -70 0 +-64 -67 70 0 +-64 67 -70 0 +106 107 110 0 +106 -107 -110 0 +-106 -107 110 0 +-106 107 -110 0 +-70 -110 139 0 +-70 110 -139 0 +70 110 139 0 +70 -110 -139 0 +57 60 63 0 +57 -60 -63 0 +-57 -60 63 0 +-57 60 -63 0 +101 102 105 0 +101 -102 -105 0 +-101 -102 105 0 +-101 102 -105 0 +-63 -105 136 0 +-63 105 -136 0 +63 105 136 0 +63 -105 -136 0 +50 53 56 0 +50 -53 -56 0 +-50 -53 56 0 +-50 53 -56 0 +96 97 100 0 +96 -97 -100 0 +-96 -97 100 0 +-96 97 -100 0 +-56 -100 133 0 +-56 100 -133 0 +56 100 133 0 +56 -100 -133 0 +43 46 49 0 +43 -46 -49 0 +-43 -46 49 0 +-43 46 -49 0 +91 92 95 0 +91 -92 -95 0 +-91 -92 95 0 +-91 92 -95 0 +-49 -95 130 0 +-49 95 -130 0 +49 95 130 0 +49 -95 -130 0 +-18 -26 36 0 +-18 26 -36 0 +18 26 36 0 +18 -26 -36 0 +-2 10 86 0 +-2 -10 -86 0 +2 -10 86 0 +2 10 -86 0 +-36 -86 124 0 +-36 86 -124 0 +36 86 124 0 +36 -86 -124 0 +-34 39 42 0 +-34 -39 -42 0 +34 -39 42 0 +34 39 -42 0 +-18 87 90 0 +-18 -87 -90 0 +18 -87 90 0 +18 87 -90 0 +-42 -90 127 0 +-42 90 -127 0 +42 90 127 0 +42 -90 -127 0 +-146 124 0 +-146 127 0 +146 -124 -127 0 +-147 130 0 +-147 146 0 +147 -130 -146 0 +-148 133 0 +-148 147 0 +148 -133 -147 0 +-149 136 0 +-149 148 0 +149 -136 -148 0 +-150 139 0 +-150 149 0 +150 -139 -149 0 +-151 142 0 +-151 150 0 +151 -142 -150 0 +-152 145 0 +-152 151 0 +152 -145 -151 0 +-152 0 diff --git a/Verify/Discharge/test/sat/b8.lrat b/Verify/Discharge/test/sat/b8.lrat new file mode 100644 index 00000000..43eeaa7e --- /dev/null +++ b/Verify/Discharge/test/sat/b8.lrat @@ -0,0 +1,240 @@ +348 -2 146 39 87 -10 0 87 307 85 91 303 318 314 312 322 328 0 +349 -3 147 46 92 -10 -11 0 87 74 171 72 78 93 177 99 294 290 298 331 348 83 308 89 321 304 317 310 324 328 0 +350 -18 124 -10 0 87 83 303 307 312 0 +351 124 -10 0 87 350 85 304 308 310 0 +351 d 350 0 +352 18 127 -39 -87 0 89 320 316 322 0 +353 127 -39 -87 26 0 352 91 319 315 324 0 +354 -18 130 -39 -87 46 92 26 0 91 176 98 178 100 294 290 298 0 +355 -4 148 53 97 -10 -11 -12 0 351 87 74 61 181 59 65 103 187 109 282 278 286 334 349 70 172 76 94 353 328 331 354 89 174 96 179 101 297 293 300 0 +356 19 18 -146 -46 -92 20 148 53 97 0 89 96 174 63 76 179 101 184 296 106 292 189 111 298 285 281 331 288 334 0 +357 -19 -146 -46 -92 148 53 97 27 0 78 177 99 295 186 291 108 188 300 110 282 331 278 334 286 0 +358 -146 -46 -92 20 148 53 97 26 -11 0 74 357 72 94 356 172 91 176 98 178 100 295 186 291 108 188 300 110 282 331 278 334 286 0 +359 19 127 26 -11 0 74 72 94 172 353 0 +360 146 -10 -11 0 351 87 74 328 359 70 93 171 348 83 89 321 317 324 0 +361 97 148 -46 -92 -19 -146 27 -13 0 48 192 357 46 113 0 +362 148 -46 -92 -19 -146 27 -13 0 177 295 78 99 291 300 331 108 110 186 188 48 334 361 283 191 288 44 279 114 0 +362 d 361 0 +363 -97 136 -133 50 96 60 102 0 283 196 287 198 278 270 118 274 120 266 0 +364 -92 -19 149 60 102 -146 27 -12 -13 0 78 99 177 61 48 181 186 57 188 104 108 110 362 332 337 363 192 46 52 197 119 270 266 274 0 +365 -148 50 96 149 60 102 -13 0 48 332 337 363 192 46 52 197 119 270 266 274 0 +366 97 148 -4 -10 -11 -12 -13 0 48 192 355 46 113 0 +367 -19 149 60 102 -10 -11 -12 -13 0 360 74 61 48 70 364 182 59 65 103 187 109 349 365 334 366 283 191 288 44 279 114 0 +368 92 130 96 -87 -39 19 26 28 0 76 185 189 103 354 89 174 96 179 101 297 293 300 0 +369 50 100 96 -53 148 -87 -39 19 -146 26 -12 0 61 279 288 334 331 368 181 57 63 104 189 111 184 106 295 291 300 0 +370 96 -53 -97 148 -87 -39 19 -146 26 -12 0 61 283 369 109 110 65 104 189 108 184 100 179 98 174 91 0 +371 -97 148 -87 -39 19 -146 26 -12 -13 0 76 61 48 191 44 114 370 187 188 284 59 63 104 182 186 178 296 176 89 96 101 106 292 111 298 280 331 286 334 0 +372 148 19 -10 -11 -12 -13 0 72 172 74 94 360 87 61 48 371 192 366 46 57 182 113 104 358 0 +373 -21 136 60 102 29 0 52 197 119 270 266 274 0 +374 96 -148 149 60 102 -13 0 48 337 373 46 192 114 332 283 365 287 280 0 +374 d 365 0 +375 -6 150 67 107 -10 -11 -12 -13 -14 0 48 35 201 33 39 123 207 129 258 254 262 340 367 372 332 337 373 46 50 114 192 374 194 284 199 289 273 279 276 116 269 121 0 +376 -96 -53 21 -97 136 -133 -60 -102 0 50 194 284 199 289 272 279 274 116 268 121 0 +377 -53 21 -102 -97 136 -133 -60 0 376 283 196 287 198 280 271 118 276 120 267 0 +377 d 376 0 +378 -97 136 -133 -60 -102 -13 0 48 191 44 114 377 0 +379 -148 149 -60 -102 -13 0 48 332 337 378 192 46 52 197 119 271 267 276 0 +380 4 -19 148 -146 27 -12 -13 0 61 57 182 104 362 0 +381 148 -10 -11 -12 -13 0 360 74 61 48 372 70 380 181 59 366 65 103 187 191 109 349 283 44 334 114 288 279 0 +381 d 372 366 0 +382 -20 -53 -97 139 -60 -102 67 107 28 0 65 187 109 196 118 198 120 206 128 208 130 258 254 262 0 +383 -19 -92 -46 -53 -97 139 -60 -102 67 107 27 0 78 177 99 108 186 110 188 118 196 120 198 128 206 130 208 254 258 262 0 +384 96 -53 -97 139 -60 -102 67 107 -133 0 283 196 287 198 280 206 118 208 120 258 128 262 130 254 0 +385 -101 139 -136 -60 -102 22 67 107 0 37 204 272 209 277 261 267 264 126 257 131 0 +386 139 107 -136 -60 -102 22 67 0 385 271 206 275 208 268 258 128 262 130 254 0 +386 d 385 0 +387 -7 151 74 112 -10 -11 -12 -13 -14 -15 0 381 35 22 211 20 26 133 217 139 246 242 250 343 375 31 202 124 379 335 340 386 0 +388 -115 -142 139 -67 -107 23 74 112 0 24 249 253 219 245 214 141 259 136 264 255 0 +389 -142 139 112 -67 -107 23 74 0 388 246 251 218 242 216 140 260 138 262 256 0 +389 d 388 0 +390 115 142 -136 -60 58 -102 65 -107 74 112 0 246 252 218 245 216 141 208 136 206 131 272 126 277 267 0 +391 142 -136 -60 22 -102 -67 -107 23 74 112 0 37 24 390 249 250 219 242 214 140 209 138 204 130 271 128 275 268 0 +392 -102 -67 -107 23 151 74 112 -148 -13 -14 0 35 201 31 124 379 335 391 343 389 340 0 +393 -8 81 117 -10 -11 -12 -13 -14 -15 -16 0 347 381 332 48 35 22 9 221 7 13 143 227 149 234 166 238 346 387 18 212 134 392 202 33 39 123 207 129 259 216 255 138 218 264 140 246 242 250 343 340 337 374 373 194 46 50 114 199 192 273 284 276 289 269 279 121 116 0 +394 102 -142 -67 -107 -139 -74 -112 81 117 -148 -13 -14 0 347 332 48 35 202 33 39 123 207 129 216 138 218 140 226 148 228 150 234 166 238 346 343 340 337 374 373 194 46 50 114 199 192 273 284 276 289 269 279 121 116 0 +395 111 145 -142 -74 -112 81 117 0 247 226 251 228 244 234 148 238 150 166 0 +396 -142 -67 -107 -139 -74 -112 24 81 117 -148 -13 -14 0 347 11 35 394 201 31 124 379 340 343 346 395 224 248 229 253 237 243 240 146 169 151 0 +397 -111 142 -67 65 -107 -139 -74 -112 0 218 248 216 250 260 244 265 141 255 136 0 +398 -107 -139 -74 -112 24 81 117 -148 -13 -14 -15 0 22 211 18 24 134 396 397 219 247 214 252 259 243 263 140 256 138 0 +399 -139 -74 -112 24 81 117 -10 -11 -12 -13 -14 -15 0 347 381 35 22 398 212 20 26 133 217 139 247 243 252 395 346 343 375 340 31 202 379 124 0 +400 107 111 139 -10 -11 -12 -13 -14 31 0 338 381 35 215 219 133 375 31 202 124 379 386 335 0 +401 111 -142 139 -74 -112 -10 -11 -12 -13 -14 -15 0 22 247 251 244 400 211 18 24 134 219 141 214 136 259 255 264 0 +402 -142 139 -74 -112 -10 -11 -12 -13 -14 -15 0 22 401 217 218 248 20 134 253 212 243 216 140 260 138 262 256 0 +402 d 401 0 +403 -12 43 93 20 148 -13 0 59 182 186 177 178 76 101 96 97 89 95 84 176 381 170 75 0 +404 -13 50 149 98 21 -102 -60 0 46 379 192 196 187 188 63 111 106 107 105 403 62 180 186 177 178 76 101 96 97 89 90 315 95 176 318 325 359 170 75 0 +405 -91 43 0 177 178 76 101 96 97 89 90 315 95 176 318 325 359 170 75 0 +406 12 92 28 0 62 180 0 +407 -102 -61 103 0 127 126 267 206 197 198 272 50 277 121 335 116 117 115 404 49 190 196 187 188 63 111 106 107 105 405 186 406 59 182 0 +408 -14 102 22 0 33 202 0 +409 -61 -106 0 208 207 127 125 407 408 200 36 0 +410 -107 139 -111 0 218 217 216 207 260 37 262 409 131 256 134 21 22 213 0 +411 15 31 107 0 210 23 0 +412 -15 107 23 0 20 212 0 +413 -106 61 67 107 139 0 207 261 37 264 131 257 0 +414 13 53 101 0 45 199 114 195 47 193 0 +415 53 51 101 0 414 48 114 52 0 +416 -20 44 0 57 65 60 0 +417 -21 51 0 44 52 47 0 +418 11 40 91 0 71 179 174 175 83 173 86 73 91 94 98 0 +419 -46 -92 91 -97 47 -53 -60 -102 67 107 139 0 108 100 418 74 383 179 94 174 98 83 91 86 0 +420 -60 -103 61 67 107 139 0 205 204 128 119 120 415 118 109 110 416 417 199 194 195 189 184 185 419 104 60 61 183 0 +421 22 61 67 107 139 0 413 209 205 420 124 34 35 203 0 +422 61 139 67 107 0 413 258 262 254 129 421 31 39 34 0 +422 d 413 0 +423 139 107 67 0 422 130 409 254 258 262 0 +423 d 422 0 +424 139 -111 0 217 410 412 411 135 423 0 +424 d 410 0 +425 -22 -60 0 31 123 34 0 +426 -26 124 10 0 84 86 305 309 312 0 +427 -11 146 91 0 74 360 84 89 174 179 70 93 171 317 321 324 328 426 88 304 306 310 0 +428 146 91 0 427 71 418 179 96 97 174 175 90 84 353 351 328 0 +428 d 427 0 +429 11 -97 50 -53 -93 148 0 185 184 295 279 188 283 288 334 428 331 300 71 418 179 96 97 100 175 90 291 370 107 58 111 63 0 +430 19 26 27 -49 -97 -53 -93 148 0 184 428 188 185 179 94 174 175 370 91 58 183 98 60 100 104 291 0 +431 -20 -92 0 57 58 181 0 +432 51 -93 148 101 57 0 185 431 63 184 428 295 188 121 415 417 116 199 279 195 283 288 334 331 300 111 106 107 291 0 +433 43 -46 -100 53 -146 95 148 0 291 108 300 110 331 278 334 286 0 +434 -46 -100 97 53 -13 -92 91 148 0 431 428 295 433 100 418 74 358 362 86 356 83 0 +435 -93 148 101 57 0 184 185 188 431 432 50 51 44 45 113 191 282 434 104 60 61 183 0 +435 d 432 0 +436 91 147 92 -12 46 -13 148 0 294 428 331 298 290 99 100 418 74 381 78 84 179 174 0 +437 -11 146 19 0 74 360 72 94 84 172 352 328 426 88 304 306 310 0 +438 124 18 0 351 426 88 304 306 310 0 +439 27 127 18 11 19 0 75 94 170 352 0 +440 18 146 19 0 437 89 438 328 439 73 95 173 317 321 324 0 +441 147 92 148 -12 46 -13 0 436 177 178 297 405 100 293 300 331 440 83 84 176 86 348 91 98 0 +441 d 436 0 +442 96 46 97 -13 53 93 148 0 189 282 58 416 431 109 278 286 334 441 0 +443 146 0 428 177 178 405 440 100 83 84 176 86 348 91 98 0 +444 124 0 443 326 0 +445 127 0 443 327 0 +446 -91 130 92 46 0 297 405 300 293 0 +447 130 46 92 0 445 446 294 298 290 99 100 418 74 78 94 179 98 316 174 175 323 319 0 +447 d 446 0 +448 46 97 -13 53 93 148 0 443 107 442 187 285 63 104 111 60 61 281 183 288 334 331 447 0 +448 d 442 0 +449 12 92 -46 0 58 406 105 0 +450 92 -46 0 449 61 182 103 59 0 +450 d 449 0 +451 97 -13 148 53 93 0 443 448 450 186 431 296 405 63 189 106 292 111 285 298 281 331 288 334 0 +451 d 448 0 +452 53 93 148 101 0 414 415 50 44 191 451 0 +453 -13 148 101 57 0 435 452 48 113 50 199 121 194 195 116 189 283 279 58 431 288 450 334 441 0 +454 148 57 101 0 443 435 452 453 45 50 199 121 194 195 116 189 283 279 431 288 450 334 447 331 0 +454 d 435 0 +455 -61 149 0 126 127 409 267 425 209 204 205 271 276 337 454 0 +456 -103 61 67 107 -139 0 205 208 258 265 257 131 37 31 32 201 0 +457 -60 102 0 425 125 408 200 36 0 +458 -28 -92 0 60 61 183 0 +459 101 148 0 454 119 120 415 417 118 199 109 110 194 195 416 189 184 185 458 104 108 99 100 292 418 74 78 179 430 174 87 84 0 +459 d 454 0 +460 -43 91 0 445 99 100 418 74 78 94 179 98 316 174 175 323 319 0 +461 13 29 97 0 49 190 0 +462 -93 148 0 443 459 198 197 184 185 188 295 431 458 196 104 282 460 433 115 461 46 192 0 +463 97 29 21 0 461 46 192 0 +464 -46 -53 148 0 443 459 198 197 115 463 196 187 63 284 462 450 186 296 405 106 292 111 298 280 331 286 334 0 +465 -53 148 0 443 459 198 197 115 463 196 284 187 63 464 107 104 111 458 280 447 286 331 334 0 +465 d 464 0 +466 -100 133 148 0 459 197 465 114 47 48 193 462 285 286 189 278 416 109 0 +467 133 47 148 0 459 197 465 114 47 48 193 466 282 288 187 281 63 111 0 +468 130 46 0 447 431 458 104 0 +468 d 447 0 +469 46 148 0 443 107 467 334 331 468 0 +470 148 0 443 462 469 450 186 296 405 106 292 467 298 334 331 0 +471 133 0 470 332 0 +472 147 0 470 333 0 +473 130 0 472 329 0 +474 102 -57 -101 136 0 457 273 269 276 0 +475 -30 -102 0 34 35 203 0 +476 -57 -101 136 0 474 272 274 268 475 124 31 32 201 0 +476 d 474 0 +477 21 98 54 136 0 50 199 121 476 0 +478 -21 136 103 0 44 197 206 457 373 47 0 +479 101 136 103 0 471 478 50 206 199 415 457 194 195 283 363 287 280 0 +480 98 136 21 0 471 477 116 117 279 115 289 463 196 284 0 +480 d 477 0 +481 136 103 0 478 479 198 480 0 +481 d 478 0 +482 107 81 120 -139 -115 23 72 -74 0 347 470 24 412 411 135 137 141 146 244 151 250 169 240 346 343 340 455 456 337 481 0 +483 81 120 -111 72 -74 -112 0 470 347 424 217 24 248 218 482 216 207 208 260 409 37 481 265 131 337 136 257 340 141 397 343 146 346 151 240 169 0 +484 -96 50 0 187 188 63 111 106 107 405 450 186 0 +485 -17 25 117 0 232 158 0 +486 33 -81 117 0 163 485 230 161 0 +487 -81 117 0 486 159 165 156 0 +487 d 486 0 +488 117 -116 -111 72 -74 -112 0 237 483 487 0 +489 -33 -81 0 159 165 156 0 +490 -107 61 -150 -81 -120 -111 72 -74 -112 0 347 424 217 24 218 216 207 260 37 265 131 136 257 141 397 146 343 151 346 168 238 0 +491 -71 -150 -81 -120 -115 72 -74 0 347 146 244 151 250 168 343 238 346 0 +492 71 -111 -74 -112 0 424 217 24 248 243 141 253 137 135 397 411 412 0 +493 149 -111 0 470 424 218 217 455 337 481 208 216 412 456 411 135 0 +494 -25 -117 0 156 157 231 0 +495 -111 24 -74 -112 0 11 224 248 229 424 488 236 492 493 340 491 494 164 159 160 233 0 +496 -117 81 0 494 164 159 160 233 0 +497 -23 65 0 18 26 21 0 +498 -31 -107 0 21 22 213 0 +499 -71 -139 111 0 139 140 497 219 214 215 259 263 498 134 256 138 0 +500 -22 -102 0 31 32 201 0 +501 149 0 470 471 337 481 204 205 475 500 124 379 45 414 480 377 195 0 +502 136 0 501 335 0 +503 -23 -107 0 18 19 211 0 +504 -107 31 -103 81 111 -74 -112 0 502 501 347 205 475 500 124 204 271 275 268 128 130 208 496 247 259 503 134 138 255 140 264 243 340 252 343 395 346 0 +505 31 -103 81 111 -74 -112 0 501 347 496 247 504 215 219 26 133 139 423 243 340 252 343 395 346 0 +505 d 504 0 +506 -31 111 0 21 498 18 215 219 0 +507 -23 81 111 -74 -112 0 501 347 496 506 247 26 133 503 139 423 243 340 252 343 395 346 0 +508 81 111 -74 -112 0 501 347 506 247 496 505 507 219 134 214 215 209 259 425 122 39 129 138 255 140 264 243 340 252 343 395 346 0 +508 d 507 505 0 +509 71 -67 65 110 120 -81 115 -74 0 347 501 243 148 141 252 150 136 167 255 240 264 346 340 343 0 +510 -22 58 0 425 122 39 0 +511 -108 120 -81 31 115 -74 0 502 214 215 259 503 24 134 509 140 138 129 130 510 209 204 205 271 475 275 124 268 128 0 +512 111 -74 -112 0 501 347 247 226 228 506 508 487 235 511 219 26 133 503 139 423 243 148 340 252 150 343 167 346 240 0 +512 d 508 0 +513 -111 -74 -112 0 495 5 143 8 0 +513 d 495 0 +514 -74 -112 0 512 513 0 +514 d 512 513 0 +515 -24 -112 0 5 6 221 0 +516 -112 0 514 515 144 8 9 223 0 +517 -113 0 516 225 0 +518 107 31 23 0 411 412 0 +519 -81 145 -78 -116 0 487 168 236 238 0 +520 145 -78 -116 0 519 496 169 237 240 0 +520 d 519 0 +521 -111 151 74 0 516 501 217 218 249 424 24 340 343 252 245 141 136 137 255 135 265 518 260 216 0 +522 -142 -107 151 74 0 516 501 521 506 503 134 389 343 340 0 +523 -107 151 74 0 516 502 521 506 246 503 219 134 214 522 250 242 140 138 129 510 209 205 475 391 124 0 +523 d 522 0 +524 151 74 0 501 516 521 246 506 523 518 26 133 139 423 242 340 250 343 0 +524 d 521 0 +525 74 24 0 517 347 229 11 147 151 520 346 524 0 +526 8 32 0 516 222 10 0 +527 -8 24 0 516 7 220 0 +527 d 7 0 +528 -74 24 0 145 526 527 0 +528 d 145 0 +529 24 0 525 528 0 +530 8 0 529 5 0 +531 16 0 529 6 0 +532 -116 0 529 227 0 +533 159 0 530 2 0 +534 -32 0 530 8 0 +535 167 0 531 4 0 +536 -74 0 534 529 143 0 +537 72 0 534 529 13 0 +538 -75 0 536 147 0 +539 151 0 536 524 0 +540 -78 0 537 149 0 +541 142 0 539 341 0 +542 150 0 539 342 0 +543 -145 0 539 347 346 0 +544 139 0 542 338 0 +545 81 0 540 532 543 496 166 234 238 0 +546 117 0 545 487 0 +547 -33 0 545 489 0 +548 -84 0 545 540 167 0 +549 -120 0 546 532 235 0 +550 -25 0 546 494 0 +551 0 548 549 543 240 0 diff --git a/Verify/Discharge/test/smt-negatives.sh b/Verify/Discharge/test/smt-negatives.sh new file mode 100755 index 00000000..f20476a8 --- /dev/null +++ b/Verify/Discharge/test/smt-negatives.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# Negative checks of the proofs: each edits one exported obligation so that it no longer holds and +# requires every backend to fail on it by a counterexample or an incomplete answer, never by a +# timeout, while the untouched export of the same rows is proved. Without a lock (an edited module +# fails any lock before Lean runs: see negatives.sh), with the sources still checked. +# +# Verify/Discharge/test/smt-negatives.sh EXPORTS SOURCE_ROOT [OUT.tsv] +# +# EXPORTS holds the format-2 exports Counter/, Vault/ and ArrayMax/ (frozen/v2 locks). +# DISCHARGE_BACKENDS defaults to 'smt=vc_smt', the cvc5 backend these cases check. With the +# vc_valid fallback added, N4 on ArrayMax.max#8 also records vc_valid's 30 s timeout, so the +# no-timeout check then fails: a fallback's search has no counterexample to report. +# +# N2-goal Counter.increment#1: goal 'count = old + 1' read as '+ 2' +# N3-assert Counter.increment#1/#2: the assertion defining the new count read as '+ 2' +# N4-negated Vault.withdraw#0: goal negated +# N4-negated ArrayMax.max#8: goal (the loop invariant's preservation) negated +set -euo pipefail +exports=$(cd "$1" && pwd) +srcroot=$(cd "$2" && pwd) +tsv=${3:-/dev/stdout} +here=$(cd "$(dirname "$0")/.." && pwd) +work=$(mktemp -d) +rowsout="$work/rows" +: >"$rowsout" +trap 'rm -rf "$work"' EXIT +pass=0 bad=0 +export DISCHARGE_BACKENDS=${DISCHARGE_BACKENDS:-smt=vc_smt} + +copy() { + rm -rf "$work/x" + mkdir -p "$work/x" + (cd "$exports/$1" && tar cf - --exclude=./discharge --exclude='./discharge-*' .) | (cd "$work/x" && tar xf -) +} + +run() { + DISCHARGE_SOURCE_ROOT="$srcroot" DISCHARGE_VACUITY=0 DISCHARGE_ONLY="$1" \ + "$here/discharge.sh" "$work/x" 120 >"$work/log" 2>&1 || true +} + +# case_ NAME CONTRACT ID_REGEX FILE SED_EXPR: the control proves every row ID_REGEX selects, the +# edited copy proves none, and no attempt on it times out. +case_() { + local name=$1 c=$2 ids=$3 file=$4 expr=$5 ok=1 want proved tried proved_bad timeouts + copy "$c" + run "$ids" + want=$(jq --arg r "$ids" '[.units[] | .obligations[]? | select(.required) | select(.id | test($r))] | length' "$work/x/manifest.json") + proved=$(awk -F'\t' -v r="$ids" 'NR > 1 && $1 ~ r && $4 == "proved"' "$work/x/discharge/summary.tsv" 2>/dev/null | wc -l) + [[ $want -gt 0 && $proved -eq $want ]] || { echo "FAILED: $name control: $proved of $want untouched rows proved"; ok=0; } + copy "$c" + cp "$work/x/$file" "$work/before" + sed -i "$expr" "$work/x/$file" + if cmp -s "$work/before" "$work/x/$file"; then echo "FAILED: $name: the edit changed nothing"; ok=0; fi + run "$ids" + if [[ ! -f $work/x/discharge/results.tsv ]]; then + echo "FAILED: $name: no results ($(tail -1 "$work/log"))"; ok=0 + else + awk -F'\t' -v r="$ids" -v n="$name" 'NR > 1 && $1 ~ r {print n "\t" $4 "\t" $1 "\t" $5 "\t" $6 "\t" $7 "\t" $8}' \ + "$work/x/discharge/results.tsv" >>"$rowsout" + tried=$(awk -F'\t' -v r="$ids" 'NR > 1 && $1 ~ r' "$work/x/discharge/results.tsv" | wc -l) + proved_bad=$(awk -F'\t' -v r="$ids" 'NR > 1 && $1 ~ r && $5 == "proved"' "$work/x/discharge/results.tsv" | wc -l) + timeouts=$(awk -F'\t' -v r="$ids" 'NR > 1 && $1 ~ r && $5 ~ /timeout/' "$work/x/discharge/results.tsv" | wc -l) + [[ $tried -gt 0 ]] || { echo "FAILED: $name: no attempt recorded"; ok=0; } + [[ $proved_bad -eq 0 ]] || { echo "FAILED: $name: an edited obligation was proved"; ok=0; } + [[ $timeouts -eq 0 ]] || { echo "FAILED: $name: $timeouts attempts timed out"; ok=0; } + fi + if [[ $ok == 1 ]]; then echo "ok: $name"; pass=$((pass + 1)); else bad=$((bad + 1)); fi +} + +case_ N2-goal Counter '^Counter\.increment#1$' Counter/increment.lean \ + '77s/^ goal := .app .eq \[.fn 23 \[\], .app .add \[.fn 16 \[\], .int 1\]\]$/ goal := .app .eq [.fn 23 [], .app .add [.fn 16 [], .int 2]]/' +case_ N3-assert Counter '^Counter\.increment#[12]$' Counter/increment.lean \ + '61s/^ .app .eq \[.fn 23 \[\], .app .add \[.fn 16 \[\], .int 1\]\],$/ .app .eq [.fn 23 [], .app .add [.fn 16 [], .int 2]],/' +case_ N4-withdraw0-negated Vault '^Vault\.withdraw#0$' Vault/withdraw.lean \ + '194s/^ goal := \(.*\)$/ goal := .app .not [\1]/' +case_ N4-max8-negated ArrayMax '^ArrayMax\.max#8$' ArrayMax/max.lean \ + '159s/^ goal := \(.*\)$/ goal := .app .not [\1]/' + +{ printf 'case\tbackend\tid\tstatus\tseconds\tpeak_mb\taxioms\n'; cat "$rowsout"; } >"$tsv" +echo "smt-negatives: $pass passed, $bad failed" >&2 +[[ $bad -eq 0 ]] diff --git a/Verify/Final.lean b/Verify/Final.lean new file mode 100644 index 00000000..5c4ef1a6 --- /dev/null +++ b/Verify/Final.lean @@ -0,0 +1,630 @@ +import SolidCore.Refinement.ComposeSeq +import SolidCore.Refinement.Abi +import Verify.Basic + +/-! +# The final statement: a verified specification holds of deployed bytecode + +This module states, once and for every contract, what the end-to-end certificate of a +compilation says, and proves how the stages of the pipeline compose into it. + +## What is certified + +A contract is runtime bytecode `code`, bound by a `Manifest` to the source's SHA-256, the +compiler's commit, its options and the bytecode's own SHA-256 (`Bound`, checked by the kernel +for the bytecode: its hex and its SHA-256 by EthLib's FIPS 180-4 implementation). Its +specification (`ContractSpec`) is solar-verify's, read over an abstract state `St` that the +storage layout gives from the slot function of a storage (`abs`): the contract invariants +(`@custom:invariant`) and, for each public or external function of the specification, its +selector, its ABI parameters, its precondition (`@custom:requires`) and its postcondition +(`@custom:ensures`, which may read `old` state, the new state and the return data). + +`Certificate` holds two theorems about `code`: + +* (a) **refinement** (`Agree`): on every call of a specified function, on any clean argument + words, with any call value and from any storage, SolidCore's run of the checked contract and + EthLib's run of `code` both finish and show the same observable: success, return or revert + data, logs and the final storage. SolidCore and EthLib are deterministic, so this is both + directions at once: every bytecode result is a source result (`Agree.backward`), reverts + and exceptional halts included, and every source result is the bytecode's. +* (b) **the specification holds of the bytecode** (`Holds ethLib code spec`), in + solar-verify's semantics: from a storage whose abstract state meets the invariants and the + function's precondition, a call that returns meets the postcondition and the invariants, and + a non-payable function returns only without value (so no balance moves); a call that fails, + for any reason, leaves the storage as it was and logs nothing. + +## Composition + +`Stage A B p q scope` (SolarTV's, which every stage of the pipeline proves) only preserves the +results of runs of `p` that finish: when `p` finishes no call of the scope, every `q` is a +stage of it (`stage_of_never`). A stage chain therefore gives agreement only with the source's +termination (`agree_of_stage`), and a specification holds of the target only through +agreement (`Holds.of_agree`): partial correctness of a source that never finishes says nothing. +`certificate_of_stages` composes the source stage (SolidCore to lowered MIR: solidity-lean's +Generic stage), the backend (solar-tv: lowered MIR through scheduling and the EVM IR passes) and +the assembly stage (EVM IR to bytecode on EthLib) with the source's specification and +termination into (a) and (b). + +## Out of gas + +`Target.run` carries `gasLimit` gas. `Target.runWith gas` is the same run with any gas, and +`ethLibWith gas` its semantics. In solar-verify's semantics a failed call owes nothing but +rolling back, which `runWith` gives for every failure (`runWith_failure`), out of gas included. +So the specification holds at every gas (`Holds.allGas`) once every success at any gas is the +success at `gasLimit` (`GasStable`), and then every bytecode result at any gas is the source's +result or a failure that changes nothing (`RefinesAtAnyGas`, `refinesAtAnyGas`). `GasStable` is +a separate obligation; the stages prove the run at `gasLimit`. + +## Transactions, external calls and reentrancy + +`Holds.trace` lifts the invariants across transactions: on every sequence of calls of the +specification from a storage that meets the invariants, each call starting from the storage the +one before left (`Carries`), the invariants hold at the start of every call and each call whose +precondition holds there meets its specification. This is the whole story for code that runs in +one frame: `FrameLocal code` (decided by the kernel on the linear decoding of the bytecode, which +is every offset execution can reach) says the code has no instruction that runs other code or +reads state outside the frame (`CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE`, +`CREATE2`, `SELFDESTRUCT`, balances, other accounts' code, the block and transaction +environment, the caller and origin, `GAS`, transient storage). Then no other contract runs while +it does, so it cannot be reentered, and the fixed caller, callee and environment of `Target.run` +are not read. A contract that calls out or reads its environment fails the check, so no +certificate exists for it: the README's assumptions for external calls (the invariants hold +before each call, the storage is havocked across it) need a semantics with other frames, which +this one is not. + +## Not covered + +Deployment: `Target.run` starts from the runtime bytecode and the call's storage, so the +constructor's `@custom:ensures` and the invariants after deployment are the source's claims +about the first storage, not theorems about initcode. Calls outside the specified functions' +clean ABI encodings are outside the scope of (a) and (b) unless a contract's certificate widens +it. +-/ + +namespace SolidCore.Refinement.Final + +open SolidCore.Refinement + +/-! ## Agreement: refinement in both directions -/ + +/-- `q` agrees with `p` on `scope`: on every call of the scope both finish with the same +observable. -/ +def Agree (A B : Sem) (p : A.Prog) (q : B.Prog) (scope : Call → Prop) : Prop := + ∀ call, scope call → ∃ obs, A.run p call = some obs ∧ B.run q call = some obs + +/-- A stage whose source finishes every call of the scope is agreement. -/ +theorem agree_of_stage {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (stage : Stage A B p q scope) (fin : ∀ call, scope call → (A.run p call).isSome) : + Agree A B p q scope := by + intro call hc + obtain ⟨obs, h⟩ := Option.isSome_iff_exists.mp (fin call hc) + exact ⟨obs, h, stage call hc obs h⟩ + +/-- Agreement is a stage. -/ +theorem Agree.stage {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (h : Agree A B p q scope) : Stage A B p q scope := by + intro call hc obs hobs + obtain ⟨o, h1, h2⟩ := h call hc + rw [Option.some.inj (hobs.symm.trans h1)] + exact h2 + +/-- **Every result of the target is a result of the source.** -/ +theorem Agree.backward {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (h : Agree A B p q scope) {call : Call} (hc : scope call) {obs : Observable} + (hq : B.run q call = some obs) : A.run p call = some obs := by + obtain ⟨o, h1, h2⟩ := h call hc + rw [Option.some.inj (hq.symm.trans h2)] + exact h1 + +/-- The target finishes every call of the scope. -/ +theorem Agree.finishes {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (h : Agree A B p q scope) {call : Call} (hc : scope call) : (B.run q call).isSome := by + obtain ⟨o, -, h2⟩ := h call hc + simp [h2] + +theorem Agree.trans {A B C : Sem} {p : A.Prog} {q : B.Prog} {r : C.Prog} {scope : Call → Prop} + (first : Agree A B p q scope) (second : Agree B C q r scope) : Agree A C p r scope := by + intro call hc + obtain ⟨o, h1, h2⟩ := first call hc + exact ⟨o, h1, second.stage call hc o h2⟩ + +theorem Agree.mono {A B : Sem} {p : A.Prog} {q : B.Prog} {scope narrower : Call → Prop} + (h : Agree A B p q scope) (within : ∀ call, narrower call → scope call) : + Agree A B p q narrower := + fun call hc => h call (within call hc) + +/-- **What a stage alone does not say.** A source that finishes no call of the scope has a stage +to every target program, whatever it does. -/ +theorem stage_of_never {A B : Sem} {p : A.Prog} (q : B.Prog) {scope : Call → Prop} + (never : ∀ call, scope call → A.run p call = none) : Stage A B p q scope := by + intro call hc obs h + rw [never call hc] at h + cases h + +/-- Agreement rules that out on every call of its scope. -/ +theorem Agree.not_never {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (h : Agree A B p q scope) {call : Call} (hc : scope call) : A.run p call ≠ none := by + obtain ⟨o, h1, -⟩ := h call hc + simp [h1] + +/-- `Refines` is agreement between SolidCore and EthLib. -/ +theorem agree_iff_refines {fuel : Nat} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {code : ByteArray} {scope : Call → Prop} : + Agree (solidCore fuel) ethLib c code scope ↔ Refines fuel c code scope := Iff.rfl + +/-! ## Specifications -/ + +/-- A public or external function and its specification in solar-verify's terms, over the +abstract state `St`. -/ +structure FnSpec (St : Type) where + /-- The function's name, for reading only. -/ + name : String + /-- Its selector. -/ + sel : Nat + /-- Its ABI parameters. -/ + params : List Abi.Param + /-- `@custom:requires`: of the argument words and the state before the call. -/ + requires : List Nat → St → Prop + /-- `@custom:ensures`: of the argument words, the state before the call (`old`), the state + after it and the return data. -/ + ensures : List Nat → St → St → List Nat → Prop + /-- Whether the function is `payable`. -/ + payable : Bool + +/-- A contract's specification: its storage layout, as the abstract state of a storage read +slot by slot, its invariants and its functions' specifications. -/ +structure ContractSpec (St : Type) where + abs : (Nat → Nat) → St + invariant : St → Prop + fns : List (FnSpec St) + +namespace FnSpec + +variable {St : Type} + +/-- The argument words are a clean ABI encoding of the parameters. -/ +def Typed (f : FnSpec St) (args : List Nat) : Prop := + List.Forall₂ (fun (p : Abi.Param) (a : Nat) => p.clean a = true) f.params args + +/-- The call of `f` on `args` with `value` wei from the storage `storage`. -/ +def call (f : FnSpec St) (args : List Nat) (value : Nat) (storage : List (Nat × Nat)) : Call := + { calldata := Abi.calldata f.sel args, callvalue := value, storage } + +end FnSpec + +namespace ContractSpec + +variable {St : Type} + +/-- The abstract state of the storage a call starts from. -/ +def pre (spec : ContractSpec St) (call : Call) : St := spec.abs (slotValue call.storage) + +/-- The calls of the specification: a specified function, on clean argument words, with any +value below `2 ^ 256`, from any storage. -/ +def Calls (spec : ContractSpec St) (call : Call) : Prop := + ∃ f ∈ spec.fns, ∃ args, f.Typed args ∧ ∃ v, v < 2 ^ 256 ∧ ∃ σ, call = f.call args v σ + +/-- What solar-verify promises of a call of `f` on `args` that shows `obs`: a return meets the +postcondition and the invariants, and is without value unless `f` is payable; a failure, for any +reason, leaves the storage and logs nothing. -/ +def Outcome (spec : ContractSpec St) (f : FnSpec St) (args : List Nat) (call : Call) + (obs : Observable) : Prop := + (obs.success = true → + f.ensures args (spec.pre call) (spec.abs obs.storage) obs.output ∧ + spec.invariant (spec.abs obs.storage) ∧ (f.payable = false → call.callvalue = 0)) ∧ + (obs.success = false → obs.storage = slotValue call.storage ∧ obs.logs = []) + +end ContractSpec + +open ContractSpec + +/-- **The specification holds of `p`**, in solar-verify's semantics (partial correctness): every +result `p` shows for a call of a specified function from a storage that meets the invariants +and the precondition meets `Outcome`. -/ +def Holds {St : Type} (S : Sem) (p : S.Prog) (spec : ContractSpec St) : Prop := + ∀ f ∈ spec.fns, ∀ args, f.Typed args → ∀ v, v < 2 ^ 256 → ∀ σ, + spec.invariant (spec.abs (slotValue σ)) → f.requires args (spec.abs (slotValue σ)) → + ∀ obs, S.run p (f.call args v σ) = some obs → spec.Outcome f args (f.call args v σ) obs + +/-- A specification holds of every program that agrees with one it holds of. -/ +theorem Holds.of_agree {St : Type} {A B : Sem} {p : A.Prog} {q : B.Prog} {spec : ContractSpec St} + (h : Holds A p spec) (agree : Agree A B p q spec.Calls) : Holds B q spec := by + intro f hf args ht v hv σ hinv hreq obs hrun + exact h f hf args ht v hv σ hinv hreq obs + (agree.backward ⟨f, hf, args, ht, v, hv, σ, rfl⟩ hrun) + +/-! ## Composition -/ + +/-- **The composition.** A specification SolidCore's contract meets and finishes, and the stages +from SolidCore to lowered MIR, through the backend to EVM IR and from EVM IR to the bytecode on +EthLib, on the specification's calls, give (a) agreement of the bytecode with the source and (b) +the specification on the bytecode. -/ +theorem certificate_of_stages {St : Type} {fuel : Nat} {mirSem evmirSem : Sem} + {c : SolidCore.Solidity.TypeCheck.CheckedContract} {mir : mirSem.Prog} {evmir : evmirSem.Prog} + {code : ByteArray} {spec : ContractSpec St} + (source : Holds (solidCore fuel) c spec) + (fin : ∀ call, spec.Calls call → (Source.run fuel c call).isSome) + (lowering : Stage (solidCore fuel) mirSem c mir spec.Calls) + (backend : Stage mirSem evmirSem mir evmir spec.Calls) + (assembly : Stage evmirSem ethLib evmir code spec.Calls) : + Agree (solidCore fuel) ethLib c code spec.Calls ∧ Holds ethLib code spec := by + have agree := agree_of_stage ((lowering.trans backend).trans assembly) fin + exact ⟨agree, source.of_agree agree⟩ + +/-! ## What each half alone does not say -/ + +/-- **Partial correctness alone is weak.** Code that fails every call, rolling back, meets every +specification in solar-verify's semantics: this is why a certificate carries agreement too. -/ +theorem Holds.of_fails {St : Type} {S : Sem} {p : S.Prog} (spec : ContractSpec St) + (fails : ∀ call obs, S.run p call = some obs → + obs.success = false ∧ obs.storage = slotValue call.storage ∧ obs.logs = []) : + Holds S p spec := by + intro f _ args _ v _ σ _ _ obs hrun + obtain ⟨hs, hst, hl⟩ := fails _ obs hrun + exact ⟨fun h => absurd (hs.symm.trans h) (by decide), fun _ => ⟨hst, hl⟩⟩ + +/-! ## Any source semantics -/ + +/-- The composition for any source semantics \`S\`, such as SolidCore with as much fuel as a call +needs (\`solidCoreAny\`). -/ +theorem compose {St : Type} {S mirSem evmirSem : Sem} {p : S.Prog} {mir : mirSem.Prog} + {evmir : evmirSem.Prog} {code : ByteArray} {spec : ContractSpec St} + (source : Holds S p spec) (fin : ∀ call, spec.Calls call → (S.run p call).isSome) + (lowering : Stage S mirSem p mir spec.Calls) (backend : Stage mirSem evmirSem mir evmir spec.Calls) + (assembly : Stage evmirSem ethLib evmir code spec.Calls) : + Agree S ethLib p code spec.Calls ∧ Holds ethLib code spec := by + have agree := agree_of_stage ((lowering.trans backend).trans assembly) fin + exact ⟨agree, source.of_agree agree⟩ + +open Classical in +/-- SolidCore with as much fuel as the call needs: the run at the least fuel that finishes it. +A contract whose loops run as many times as an argument says finishes no such call at any fixed +fuel for every argument, while it finishes each call at some fuel. -/ +noncomputable def solidCoreAny : Sem where + Prog := SolidCore.Solidity.TypeCheck.CheckedContract + run c call := if h : ∃ n, (Source.run n c call).isSome then Source.run (Nat.find h) c call else none + +/-- More fuel does not change a finished run of SolidCore: the statement at \`Source.run\` of the +source interpreter's fuel monotonicity (\`SolidCore.Solidity.FuelMonotonicity\` proves it for the +interpreter's trees). -/ +def FuelStable (c : SolidCore.Solidity.TypeCheck.CheckedContract) : Prop := + ∀ n m call obs, n ≤ m → Source.run n c call = some obs → Source.run m c call = some obs + +/-- A run of SolidCore at a fixed fuel is the run with as much fuel as it needs. -/ +theorem solidCoreAny_run {c : SolidCore.Solidity.TypeCheck.CheckedContract} (stable : FuelStable c) + {fuel : Nat} {call : Call} {obs : Observable} (h : Source.run fuel c call = some obs) : + solidCoreAny.run c call = some obs := by + classical + have hex : ∃ n, (Source.run n c call).isSome := ⟨fuel, by simp [h]⟩ + show (if h : ∃ n, (Source.run n c call).isSome then Source.run (Nat.find h) c call else none) = _ + rw [dif_pos hex] + obtain ⟨o, ho⟩ := Option.isSome_iff_exists.mp (Nat.find_spec hex) + have hle : Nat.find hex ≤ fuel := Nat.find_min' hex (by simp [h]) + rw [ho] + have := stable _ _ _ _ hle ho + rw [h] at this + exact this.symm + +/-- The stage from SolidCore at a fixed fuel to SolidCore with as much fuel as a call needs. -/ +theorem stage_solidCoreAny {c : SolidCore.Solidity.TypeCheck.CheckedContract} (stable : FuelStable c) + (fuel : Nat) (scope : Call → Prop) : Stage (solidCore fuel) solidCoreAny c c scope := + fun _ _ _ h => solidCoreAny_run stable h + +/-! ## Loom: the source obligation from a triple -/ + +/-- **The source obligation from Loom.** A triple `{pre} c {post}` against SolidCore on the +specification's calls (`SolidCore.Verify.Triple`, which `triple_of_wp` gives from Loom's weakest +precondition of a model), whose precondition every specified call from a storage meeting the +invariants and the function's precondition meets, and whose postcondition gives `Outcome` there, +gives the specification on SolidCore. -/ +theorem Holds.of_triple {St : Type} {fuel : Nat} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {spec : ContractSpec St} {pre : Call → Prop} {post : Call → Observable → Prop} + (h : SolidCore.Verify.Triple fuel c spec.Calls pre post) + (hpre : ∀ f ∈ spec.fns, ∀ args, f.Typed args → ∀ v, v < 2 ^ 256 → ∀ σ, + spec.invariant (spec.abs (slotValue σ)) → f.requires args (spec.abs (slotValue σ)) → + pre (f.call args v σ)) + (hpost : ∀ f ∈ spec.fns, ∀ args, f.Typed args → ∀ v, v < 2 ^ 256 → ∀ σ, + spec.invariant (spec.abs (slotValue σ)) → f.requires args (spec.abs (slotValue σ)) → + ∀ obs, post (f.call args v σ) obs → spec.Outcome f args (f.call args v σ) obs) : + Holds (solidCore fuel) c spec := by + intro f hf args ht v hv σ hinv hreq obs hrun + have hc : spec.Calls (f.call args v σ) := ⟨f, hf, args, ht, v, hv, σ, rfl⟩ + exact hpost f hf args ht v hv σ hinv hreq obs + ((h _ hc (hpre f hf args ht v hv σ hinv hreq)).2 obs hrun) + +/-- A triple whose precondition holds on every call of the specification gives the source's +termination there, which agreement needs (`agree_of_stage`). -/ +theorem finishes_of_triple {St : Type} {fuel : Nat} + {c : SolidCore.Solidity.TypeCheck.CheckedContract} {spec : ContractSpec St} + {post : Call → Observable → Prop} + (h : SolidCore.Verify.Triple fuel c spec.Calls (fun _ => True) post) : + ∀ call, spec.Calls call → (Source.run fuel c call).isSome := + fun call hc => (h call hc trivial).1 + +/-! ## Transactions -/ + +/-- One call of a sequence: the function, its argument words and the call value. -/ +structure Step (St : Type) where + f : FnSpec St + args : List Nat + value : Nat + +/-- A sequence of calls run with `run` from `σ`, each from the storage `carry` gives after the one +before: the invariants hold at the start of every call reached, and every call whose precondition +holds there meets its specification on whatever it shows. -/ +def Trace {St : Type} (spec : ContractSpec St) (run : Call → Option Observable) (carry : Carry) : + List (Nat × Nat) → List (Step St) → Prop + | _, [] => True + | σ, s :: rest => spec.invariant (spec.abs (slotValue σ)) ∧ + (s.f.requires s.args (spec.abs (slotValue σ)) → + ∀ obs, run (s.f.call s.args s.value σ) = some obs → + spec.Outcome s.f s.args (s.f.call s.args s.value σ) obs ∧ + Trace spec run carry (carry (s.f.call s.args s.value σ) obs) rest) + +/-- **The invariants across transactions.** When the specification holds of `p` and the storage +carried to each call is exactly the storage the call before left, every sequence of specified +calls from a storage that meets the invariants is a `Trace`. -/ +theorem Holds.trace {St : Type} {S : Sem} {p : S.Prog} {spec : ContractSpec St} {carry : Carry} + (h : Holds S p spec) (exact : ∀ call obs, S.run p call = some obs → Carries carry call obs) : + ∀ σ (steps : List (Step St)), spec.invariant (spec.abs (slotValue σ)) → + (∀ s ∈ steps, s.f ∈ spec.fns ∧ s.f.Typed s.args ∧ s.value < 2 ^ 256) → + Trace spec (S.run p) carry σ steps := by + intro σ steps + induction steps generalizing σ with + | nil => intro _ _; trivial + | cons s rest ih => + intro hinv hsteps + obtain ⟨hf, ht, hv⟩ := hsteps s List.mem_cons_self + refine ⟨hinv, fun hreq obs hrun => ?_⟩ + have hout := h s.f hf s.args ht s.value hv σ hinv hreq obs hrun + refine ⟨hout, ih _ ?_ fun s' hs' => hsteps s' (List.mem_cons_of_mem _ hs')⟩ + rw [exact _ _ hrun] + cases hs : obs.success + · rw [(hout.2 hs).1] + exact hinv + · exact (hout.1 hs).2.1 + +/-! ## Gas -/ + +namespace Target + +open EthLib.Base EthLib.Execution EthLib.Execution.Evm + +/-- The message of `Target.message` with `gas` gas. -/ +def messageWith (gas : Nat) (code : ByteArray) (call : Call) : Message .fusaka := + { Refinement.Target.message code call with gas } + +/-- `Target.run` with the message `msg`. -/ +def runMsg (msg : Message .fusaka) (code : ByteArray) (call : Call) : Option Observable := + match processMessage (Meter := Nat) .fusaka msg (Refinement.Target.preState code call) + Substate.empty with + | .error _ => none + | .ok ⟨evm, _⟩ => + let success := evm.error.isNone + some + { success + output := evm.output.toList.map (·.toNat) + logs := + if success then + evm.substate.logs.toList.map fun log => + (log.topics.map fun topic => bytesToNat topic.toList, + log.data.toList.map (·.toNat)) + else [] + storage := fun slot => + if success then + (evm.state.getStorage (Refinement.Target.address selfAddress) + (Refinement.Target.storageKey slot)).toNat + else slotValue call.storage slot } + +/-- `Target.run` with `gas` gas. -/ +def runWith (gas : Nat) (code : ByteArray) (call : Call) : Option Observable := + runMsg (messageWith gas code call) code call + +theorem messageWith_gasLimit (code : ByteArray) (call : Call) : + messageWith gasLimit code call = Refinement.Target.message code call := rfl + +theorem runMsg_message (code : ByteArray) (call : Call) : + runMsg (Refinement.Target.message code call) code call = Refinement.Target.run code call := by + unfold runMsg Refinement.Target.run + split <;> rename_i h <;> rw [h] + +theorem runWith_gasLimit (code : ByteArray) (call : Call) : + runWith gasLimit code call = Refinement.Target.run code call := by + unfold runWith + rw [messageWith_gasLimit] + exact runMsg_message code call + +/-- A failed run, at any gas and for any reason, out of gas included, leaves the storage as it +was and logs nothing. -/ +theorem runWith_failure {gas : Nat} {code : ByteArray} {call : Call} {obs : Observable} + (h : runWith gas code call = some obs) (hf : obs.success = false) : + obs.storage = slotValue call.storage ∧ obs.logs = [] := by + unfold runWith runMsg at h + split at h + · cases h + · cases h + simp only at hf + simp [hf] + +end Target + +/-- EthLib on runtime bytecode with `gas` gas. -/ +def ethLibWith (gas : Nat) : Sem := { Prog := ByteArray, run := Target.runWith gas } + +/-- Every success at any gas, on a call of the scope, is the success at `gasLimit`. -/ +def GasStable (code : ByteArray) (scope : Call → Prop) : Prop := + ∀ gas call obs, scope call → Target.runWith gas code call = some obs → obs.success = true → + Refinement.Target.run code call = some obs + +/-- **The specification at every gas.** -/ +theorem Holds.allGas {St : Type} {code : ByteArray} {spec : ContractSpec St} + (h : Holds ethLib code spec) (stable : GasStable code spec.Calls) (gas : Nat) : + Holds (ethLibWith gas) code spec := by + intro f hf args ht v hv σ hinv hreq obs hrun + change Target.runWith gas code _ = some obs at hrun + cases hs : obs.success + · exact ⟨fun h' => absurd (hs.symm.trans h') (by decide), + fun _ => Target.runWith_failure hrun hs⟩ + · exact h f hf args ht v hv σ hinv hreq obs + (stable gas _ obs ⟨f, hf, args, ht, v, hv, σ, rfl⟩ hrun hs) + +/-- Every result of the bytecode, at any gas, on a call of the scope, is the source's result or a +failure that leaves the storage and logs nothing. -/ +def RefinesAtAnyGas (fuel : Nat) (c : SolidCore.Solidity.TypeCheck.CheckedContract) + (code : ByteArray) (scope : Call → Prop) : Prop := + ∀ gas call obs, scope call → Target.runWith gas code call = some obs → + Source.run fuel c call = some obs ∨ + (obs.success = false ∧ obs.storage = slotValue call.storage ∧ obs.logs = []) + +theorem refinesAtAnyGas {fuel : Nat} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {code : ByteArray} {scope : Call → Prop} (agree : Agree (solidCore fuel) ethLib c code scope) + (stable : GasStable code scope) : RefinesAtAnyGas fuel c code scope := by + intro gas call obs hc hrun + cases hs : obs.success + · exact Or.inr ⟨rfl, Target.runWith_failure hrun hs⟩ + · exact Or.inl (agree.backward hc (stable gas call obs hc hrun hs)) + +/-! ## The code runs in one frame -/ + +/-- The bytes of the immediate of an opcode: `PUSH1` to `PUSH32` take 1 to 32. -/ +def immediate (op : Nat) : Nat := if 0x60 ≤ op ∧ op ≤ 0x7f then op - 0x5f else 0 + +/-- The opcodes of the linear decoding of `bytes`, skipping push immediates: every offset +execution can reach, as a jump into an immediate is not a valid jump destination. -/ +def opsFrom : Nat → List Nat → List Nat + | 0, _ => [] + | _, [] => [] + | n + 1, op :: rest => op :: opsFrom n (rest.drop (immediate op)) + +/-- The opcodes of `code`. -/ +def opcodes (code : ByteArray) : List Nat := opsFrom code.size (code.data.toList.map (·.toNat)) + +/-- Opcodes that run other code or read state outside the frame: `ADDRESS`, `BALANCE`, +`ORIGIN`, `CALLER`, `GASPRICE`, `EXTCODESIZE`, `EXTCODECOPY`, `EXTCODEHASH`, the block's +`BLOCKHASH` to `BLOBBASEFEE` (`SELFBALANCE` among them), `GAS`, `TLOAD`, `TSTORE`, `CREATE`, +`CALL`, `CALLCODE`, `DELEGATECALL`, `CREATE2`, `STATICCALL` and `SELFDESTRUCT`. -/ +def outsideFrame : List Nat := + [0x30, 0x31, 0x32, 0x33, 0x3a, 0x3b, 0x3c, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, + 0x47, 0x48, 0x49, 0x4a, 0x5a, 0x5c, 0x5d, 0xf0, 0xf1, 0xf2, 0xf4, 0xf5, 0xfa, 0xff] + +/-- `code` runs in one frame and reads nothing of its environment but its call. -/ +def FrameLocal (code : ByteArray) : Bool := (opcodes code).all fun op => !outsideFrame.contains op + +/-! ## Binding -/ + +/-- What a certificate is bound to. -/ +structure Manifest where + contract : String + sourceSha256 : String + compilerCommit : String + options : List String + runtimeHex : String + runtimeSha256 : String + +/-- The lowercase hex of bytes. -/ +def hexOf (bytes : List Nat) : String := + String.join (bytes.map fun b => + let d := fun n : Nat => if n < 10 then Char.ofNat (48 + n) else Char.ofNat (87 + n) + String.ofList [d (b / 16 % 16), d (b % 16)]) + +/-- The bytes of a hex string, two digits a byte. -/ +def bytesOfHex (s : String) : ByteArray := + let digit (c : Char) : Nat := + if '0' ≤ c ∧ c ≤ '9' then c.toNat - 48 else if 'a' ≤ c ∧ c ≤ 'f' then c.toNat - 87 else 0 + let rec go : List Char → List UInt8 + | a :: b :: rest => (digit a * 16 + digit b).toUInt8 :: go rest + | _ => [] + ⟨(go s.toList).toArray⟩ + +/-- The bytecode is the manifest's, byte for byte: its hex is the manifest's hex. The manifest's +`runtimeSha256` is recorded with it, not checked: exact equality already binds the bytes. -/ +def Bound (m : Manifest) (code : ByteArray) : Prop := + hexOf (code.data.toList.map (·.toNat)) = m.runtimeHex + +/-- **The certificate of a compilation**: the bytecode bound to its manifest, running in one +frame, (a) agreeing with SolidCore's checked contract on every call of the specification, and +(b) meeting the specification, which SolidCore's contract meets too. -/ +structure Certificate {St : Type} (spec : ContractSpec St) (m : Manifest) where + code : ByteArray + fuel : Nat + source : SolidCore.Solidity.TypeCheck.CheckedContract + bound : Bound m code + frameLocal : FrameLocal code = true + sourceHolds : Holds (solidCore fuel) source spec + refines : Agree (solidCore fuel) ethLib source code spec.Calls + holds : Holds ethLib code spec + +/-! ## Refinement with out of gas -/ + +/-- **Every result of `q` on the scope is a result of `p`, or a failure that leaves the storage +and logs nothing**: the direction of refinement that admits running out of gas, or any other +exceptional halt, where the source does not. -/ +def Within (A B : Sem) (p : A.Prog) (q : B.Prog) (scope : Call → Prop) : Prop := + ∀ call, scope call → ∀ obs, B.run q call = some obs → + A.run p call = some obs ∨ (obs.success = false ∧ obs.storage = slotValue call.storage ∧ obs.logs = []) + +theorem Agree.within {A B : Sem} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + (h : Agree A B p q scope) : Within A B p q scope := + fun _ hc _ hq => Or.inl (h.backward hc hq) + +/-- Agreement, then refinement with failures. -/ +theorem Agree.trans_within {A B C : Sem} {p : A.Prog} {q : B.Prog} {r : C.Prog} + {scope : Call → Prop} (first : Agree A B p q scope) (second : Within B C q r scope) : + Within A C p r scope := by + intro call hc obs hr + rcases second call hc obs hr with h | h + · exact Or.inl (first.backward hc h) + · exact Or.inr h + +/-- A specification holds of every program within one it holds of. -/ +theorem Holds.of_within {St : Type} {A B : Sem} {p : A.Prog} {q : B.Prog} {spec : ContractSpec St} + (h : Holds A p spec) (within : Within A B p q spec.Calls) : Holds B q spec := by + intro f hf args ht v hv σ hinv hreq obs hrun + rcases within _ ⟨f, hf, args, ht, v, hv, σ, rfl⟩ obs hrun with h' | ⟨hs, hst, hl⟩ + · exact h f hf args ht v hv σ hinv hreq obs h' + · exact ⟨fun h'' => absurd (hs.symm.trans h'') (by decide), fun _ => ⟨hst, hl⟩⟩ + +/-- With enough gas, the bytecode shows exactly what the source does: every call of the scope has +a gas from which on `runWith` gives the source's result. -/ +def EventuallyAgree (S : Sem) (p : S.Prog) (code : ByteArray) (scope : Call → Prop) : Prop := + ∀ call, scope call → ∃ obs G, S.run p call = some obs ∧ ∀ gas, G ≤ gas → + Target.runWith gas code call = some obs + +/-- **The composition at every gas.** A specification the source meets and finishes, the stages +from the source to lowered MIR and through the backend to EVM IR, and an assembly stage that at +every gas gives the EVM IR's result or a failure, give at every gas: every result of the bytecode +is the source's or a failure that changes nothing, and the specification holds of the bytecode. -/ +theorem compose_anyGas {St : Type} {S mirSem evmirSem : Sem} {p : S.Prog} {mir : mirSem.Prog} + {evmir : evmirSem.Prog} {code : ByteArray} {spec : ContractSpec St} + (source : Holds S p spec) (fin : ∀ call, spec.Calls call → (S.run p call).isSome) + (lowering : Stage S mirSem p mir spec.Calls) (backend : Stage mirSem evmirSem mir evmir spec.Calls) + (assembly : ∀ gas, Within evmirSem (ethLibWith gas) evmir code spec.Calls) (gas : Nat) : + Within S (ethLibWith gas) p code spec.Calls ∧ Holds (ethLibWith gas) code spec := by + have agree := agree_of_stage (lowering.trans backend) fin + have within := agree.trans_within (assembly gas) + exact ⟨within, source.of_within within⟩ + +/-- At `gasLimit`, a stage into EthLib is a stage into `ethLibWith gasLimit`. -/ +theorem stage_ethLibWith_gasLimit {A : Sem} {p : A.Prog} {code : ByteArray} {scope : Call → Prop} + (h : Stage A ethLib p code scope) : Stage A (ethLibWith gasLimit) p code scope := by + intro call hc obs hobs + show Target.runWith gasLimit code call = some obs + rw [Target.runWith_gasLimit] + exact h call hc obs hobs + +/-- **The certificate of a compilation at every gas**, for code whose gas use the call's arguments +bound, such as a loop over one: the bytecode bound to its manifest, running in one frame; at every +gas, every result is SolidCore's (with as much fuel as the call needs) or a failure that changes +nothing; with enough gas, it is SolidCore's; and the specification holds of SolidCore and of the +bytecode at every gas. -/ +structure CertificateAnyGas {St : Type} (spec : ContractSpec St) (m : Manifest) where + code : ByteArray + source : SolidCore.Solidity.TypeCheck.CheckedContract + bound : Bound m code + frameLocal : FrameLocal code = true + sourceHolds : Holds solidCoreAny source spec + within : ∀ gas, Within solidCoreAny (ethLibWith gas) source code spec.Calls + enough : EventuallyAgree solidCoreAny source code spec.Calls + holds : ∀ gas, Holds (ethLibWith gas) code spec + +end SolidCore.Refinement.Final diff --git a/Verify/Finite.lean b/Verify/Finite.lean new file mode 100644 index 00000000..61d2e3a9 --- /dev/null +++ b/Verify/Finite.lean @@ -0,0 +1,75 @@ +import Verify.Abi + +/-! +# Models of functions that touch neither storage nor logs, on finite scopes + +A function with only small parameters has finitely many clean calls, so the +model's agreement with SolidCore (`Implements`) can be checked call by call, as the +refinement corpus checks its finite scopes. `ofPure f` is the model of a function +that returns `f` of its argument words or reverts, leaving storage alone and +emitting no logs; `checkPure` evaluates SolidCore on every call of a list and +compares its result with `f`, and `implements_of_checkPure` turns a successful check +into `Implements` on the list. The check runs by `native_decide`. +-/ + +namespace SolidCore.Verify + +open SolidCore.Refinement SolidCore.Solidity SolidCore.Solidity.Source + +/-- The model of a function that touches neither storage nor logs. -/ +def ofPure (f : List Nat → Except Revert (List Nat)) (ws : List Nat) : SolM (List Nat) := + fun s => (f ws).map (·, s) + +@[simp] theorem wp_ofPure (f : List Nat → Except Revert (List Nat)) (ws : List Nat) + (post : List Nat → Assn) : + wp (ofPure f ws) post = fun herr s => match f ws with + | .ok out => post out herr s + | .error e => herr e := by + rw [wp_eq]; funext herr s + simp only [ofPure] + rcases f ws with e | out <;> rfl + +/-- Whether SolidCore's result `r` is `o`: the same success and output, and on success +empty storage and no logs. -/ +def resultMatches (r : TypeCheck.CoreAbiCallResult) : Except Revert (List Nat) → Bool + | .ok out => r.success && r.output == out && r.state.storage.isEmpty && + (r.state.logEntries selfAddress).isEmpty + | .error e => !r.success && r.output == e + +/-- Whether SolidCore with `fuel` runs every call of `calls`, from empty storage, as `f` +of its first `n` argument words says. -/ +def checkPure (fuel : Nat) (contract : TypeCheck.CheckedContract) (n : Nat) + (f : List Nat → Except Revert (List Nat)) (calls : List Call) : Bool := + calls.all fun call => call.storage.isEmpty && + match Source.result? fuel contract call with + | some r => resultMatches r (f (argWords n call)) + | none => false + +theorem implements_of_checkPure {fuel : Nat} {contract : TypeCheck.CheckedContract} {n : Nat} + {f : List Nat → Except Revert (List Nat)} {calls : List Call} + (h : checkPure fuel contract n f calls = true) : + Implements fuel contract (· ∈ calls) (argWords n) (ofPure f) := by + intro call hcall + have h1 := List.all_eq_true.mp h call hcall + simp only [Bool.and_eq_true, List.isEmpty_iff] at h1 + obtain ⟨hst, h2⟩ := h1 + have hinit : initStorage call = fun _ => 0 := by + funext k; simp [initStorage, hst, slotValue] + split at h2 + next r hr => + simp only [Source.run, hr, Option.map_some, hinit, ofPure] + unfold resultMatches at h2 + rcases hf : f (argWords n call) with e | out <;> rw [hf] at h2 + · simp only [Bool.and_eq_true, Bool.not_eq_true', beq_iff_eq] at h2 + obtain ⟨hs, ho⟩ := h2 + simp [Source.observe, observe, hs, ho, Except.map, hst, slotValue] + · simp only [Bool.and_eq_true, beq_iff_eq, List.isEmpty_iff] at h2 + obtain ⟨⟨⟨hs, ho⟩, hstore⟩, hlogs⟩ := h2 + simp only [Source.observe, observe, hs, ho, hlogs, Except.map, if_true, List.map_nil, + Option.some.injEq] + congr + funext slot + simp [State.loadSlot, StorageMap.lookup?, Wide.getElem?_of_isEmpty hstore] + next => simp at h2 + +end SolidCore.Verify diff --git a/Verify/Fuel.lean b/Verify/Fuel.lean new file mode 100644 index 00000000..caa3c383 --- /dev/null +++ b/Verify/Fuel.lean @@ -0,0 +1,160 @@ +import Verify.Basic + +/-! +# Termination with as much fuel as a call needs + +A model with a loop needs interpreter fuel that grows with its arguments: each call finishes +at some fuel (`ImplementsSome`, `TripleSome`: for every call, some fuel). That is not one +fuel for every call, and no fuel-monotonicity lemma turns the one into the other: for every +call some fuel is not some fuel for every call. This module gives the two honest ways on. + +**Pointwise, without any monotonicity.** `runAny c call` is SolidCore's run at the least fuel +that finishes the call (`none` if none does): the same definition as the composition's +`Final.solidCoreAny`'s run, so `solidCoreAny.run c call = runAny c call` is `rfl`. +`ImplementsAny` and `TripleAny` state the model and the triple against it, and +`tripleAny_of_wp` is the generator's soundness for them. `TripleAny` is exactly the source's +termination and correctness that `Final.compose` takes with `S := solidCoreAny`. + +**Through fuel stability, as an explicit hypothesis.** `FuelStable c` (the composition's +`Final.FuelStable`, the same definition): more fuel does not change a finished run. It speaks only +of runs that finish (`some`), so an out-of-fuel run (`none`) may become any result, a revert +included, with more fuel, while a revert or a return at some fuel stays that result at every +higher fuel; a revert never stands for running out of fuel. Given it: + +* `runAny_of_run`, `implementsAny_of_some`, `tripleAny_of_some`: the some-fuel forms give the + least-fuel ones; +* `triple_of_within`: a **bounded** some-fuel triple (`TripleWithin B`: every call finishes at + some fuel at most `B`) gives the fixed-fuel `Triple B`. The bound is a hypothesis to prove + for the contract (for a loop over a word, from the word's bound), not an assumption. + +`FuelStable` is not proved here: `Verify.FuelStable` derives it (`fuelStable_of_ctorStable`) from +`SolidCore.Refinement.Source.run_fuel_mono`, `Source.run`'s fuel monotonicity along every path, +given the constructor's stability (`CtorStable`) as a hypothesis. +-/ + +namespace SolidCore.Verify + +open SolidCore.Refinement + +open Classical in +/-- SolidCore's run of `c` on `call` at the least fuel that finishes it; `none` when no fuel +does. The same as `Final.solidCoreAny`'s run. -/ +noncomputable def runAny (c : SolidCore.Solidity.TypeCheck.CheckedContract) (call : Call) : + Option Observable := + if h : ∃ n, (Source.run n c call).isSome then Source.run (Nat.find h) c call else none + +/-- More fuel does not change a finished run of `c` (the same as `Final.FuelStable`). -/ +def FuelStable (c : SolidCore.Solidity.TypeCheck.CheckedContract) : Prop := + ∀ n m call obs, n ≤ m → Source.run n c call = some obs → Source.run m c call = some obs + +theorem runAny_isSome_iff {c : SolidCore.Solidity.TypeCheck.CheckedContract} {call : Call} : + (runAny c call).isSome ↔ ∃ n, (Source.run n c call).isSome := by + classical + unfold runAny + constructor + · intro h + by_contra hne + rw [dif_neg hne] at h + simp at h + · intro hex + rw [dif_pos hex] + exact Nat.find_spec hex + +/-- A result of `runAny` is SolidCore's result at some fuel. -/ +theorem runAny_spec {c : SolidCore.Solidity.TypeCheck.CheckedContract} {call : Call} + {obs : Observable} (h : runAny c call = some obs) : ∃ n, Source.run n c call = some obs := by + classical + unfold runAny at h + by_cases hex : ∃ n, (Source.run n c call).isSome + · rw [dif_pos hex] at h; exact ⟨_, h⟩ + · rw [dif_neg hex] at h; cases h + +/-- With fuel stability, a run that finishes at some fuel is `runAny`'s. -/ +theorem runAny_of_run {c : SolidCore.Solidity.TypeCheck.CheckedContract} (stable : FuelStable c) + {fuel : Nat} {call : Call} {obs : Observable} (h : Source.run fuel c call = some obs) : + runAny c call = some obs := by + classical + have hex : ∃ n, (Source.run n c call).isSome := ⟨fuel, by simp [h]⟩ + unfold runAny + rw [dif_pos hex] + obtain ⟨o, ho⟩ := Option.isSome_iff_exists.mp (Nat.find_spec hex) + have hle : Nat.find hex ≤ fuel := Nat.find_min' hex (by simp [h]) + have := stable _ _ _ _ hle ho + rw [h] at this + rw [ho, Option.some.inj this] + +/-- `model` implements `c` on `scope` with as much fuel as each call needs. -/ +def ImplementsAny (c : SolidCore.Solidity.TypeCheck.CheckedContract) (scope : Call → Prop) + (args : Call → List Nat) (model : List Nat → SolM (List Nat)) : Prop := + ∀ call, scope call → + runAny c call = some (observe (initStorage call) (model (args call) (initStorage call))) + +/-- Every call of the scope that meets `pre` finishes with as much fuel as it needs, with an +observable that meets `post`. -/ +def TripleAny (c : SolidCore.Solidity.TypeCheck.CheckedContract) (scope : Call → Prop) + (pre : Call → Prop) (post : Call → Observable → Prop) : Prop := + ∀ call, scope call → pre call → ∃ obs, runAny c call = some obs ∧ post call obs + +/-- The generator's soundness with as much fuel as each call needs; no fuel monotonicity. -/ +theorem tripleAny_of_wp {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope : Call → Prop} {args : Call → List Nat} {model : List Nat → SolM (List Nat)} + {pre : Call → Prop} {post : Call → Observable → Prop} + (himpl : ImplementsAny c scope args model) + (hvc : ∀ call, scope call → pre call → vc model args post call) : + TripleAny c scope pre post := by + intro call hs hp + have h := hvc call hs hp + simp only [vc, wp_eq] at h + refine ⟨_, himpl call hs, ?_⟩ + revert h + rcases model (args call) (initStorage call) with e | ⟨out, s'⟩ <;> exact id + +/-- `TripleAny` gives every call of the scope that meets `pre` a finishing fuel. -/ +theorem TripleAny.some {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {scope pre : Call → Prop} {post : Call → Observable → Prop} + (h : TripleAny c scope pre post) : TripleSome c scope pre post := by + intro call hs hp + obtain ⟨obs, hrun, hpost⟩ := h call hs hp + obtain ⟨n, hn⟩ := runAny_spec hrun + exact ⟨n, obs, hn, hpost⟩ + +theorem implementsAny_of_some {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (stable : FuelStable c) {scope : Call → Prop} {args : Call → List Nat} + {model : List Nat → SolM (List Nat)} (h : ImplementsSome c scope args model) : + ImplementsAny c scope args model := by + intro call hs + obtain ⟨fuel, hrun⟩ := h call hs + exact runAny_of_run stable hrun + +theorem tripleAny_of_some {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (stable : FuelStable c) {scope pre : Call → Prop} {post : Call → Observable → Prop} + (h : TripleSome c scope pre post) : TripleAny c scope pre post := by + intro call hs hp + obtain ⟨fuel, obs, hrun, hpost⟩ := h call hs hp + exact ⟨obs, runAny_of_run stable hrun, hpost⟩ + +/-- Every call of the scope that meets `pre` finishes at some fuel at most `B`, with an +observable that meets `post`. -/ +def TripleWithin (B : Nat) (c : SolidCore.Solidity.TypeCheck.CheckedContract) + (scope : Call → Prop) (pre : Call → Prop) (post : Call → Observable → Prop) : Prop := + ∀ call, scope call → pre call → ∃ fuel ≤ B, ∃ obs, Source.run fuel c call = some obs ∧ post call obs + +/-- **A bounded some-fuel triple is a fixed-fuel triple**, given fuel stability. -/ +theorem triple_of_within {B : Nat} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (stable : FuelStable c) {scope pre : Call → Prop} {post : Call → Observable → Prop} + (h : TripleWithin B c scope pre post) : Triple B c scope pre post := by + intro call hs hp + obtain ⟨fuel, hle, obs, hrun, hpost⟩ := h call hs hp + have hB := stable _ _ _ _ hle hrun + refine ⟨by simp [hB], fun o ho => ?_⟩ + rw [hB] at ho + cases ho + exact hpost + +/-- A fixed-fuel triple is a least-fuel one, given fuel stability. -/ +theorem Triple.any {fuel : Nat} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + (stable : FuelStable c) {scope pre : Call → Prop} {post : Call → Observable → Prop} + (h : Triple fuel c scope pre post) : TripleAny c scope pre post := + tripleAny_of_some stable h.some + +end SolidCore.Verify diff --git a/Verify/FuelStable.lean b/Verify/FuelStable.lean new file mode 100644 index 00000000..2898e53d --- /dev/null +++ b/Verify/FuelStable.lean @@ -0,0 +1,240 @@ +import Verify.Fuel +import Verify.VC.Obligations +import SolidCore.Refinement.Fuel + +/-! +# Fuel: one fuel for every call, from a run at one fuel + +`Verify.Fuel` keeps two notions apart: **for every call, some fuel** (`TripleSome`, `runAny`) and +**one fuel for every call** (`Triple fuel`). This module adds the uniform notion above a fuel: + +* `UniformFrom n c scope`: on every call of `scope`, every fuel `m ≥ n` gives SolidCore's run at + `n`, the same result, finished or not. It is a property of the scope's calls, not of every call + of `c`, so it is weaker than `FuelStable c` and says nothing below `n`. +* `Triple.mono_of_uniform`: a triple at `n` is a triple at every `m ≥ n`. + +and proves it for the generic source stage, where the fuel enters twice: in the constructor's run +(`Wide.DeployedAt fuel`) and in the erasure (`eraseFn _ fuel`, which runs a statement with the +fuel SolidCore runs it with). + +* `eraseStmt_mono`, `eraseFn_mono` (proved): an erasure that finishes at fuel `n` is the same + tree at every `m ≥ n`. The erasure counts fuel only to stop, so more fuel never changes a + finished erasure. +* `DeployStable n c s`: the constructor leaves the entries `s` at every fuel `m ≥ n`. A + hypothesis: the constructor runs through `constructWithContext?`, whose context installs a + self-dispatch hook built from the fuel, so the interpreter-level monotonicity of + `SolidCore.Solidity.FuelMonotonicity` (one tree, one context) does not reach it as stated. +* `uniformFrom_stage`: with `DeployStable`, every function the stage erases at fuel `n` runs + every call of its scope the same at every `m ≥ n`: as its tree. +* `triple_of_binds_from`: the generic theorem from an erased function to its obligations + (`triple_of_binds`), at every fuel from `n` on. + +None of this turns "for every call, some fuel" into one fuel: `UniformFrom` is proved from one +fuel `n` that already finishes every call of the scope (`source_run` at `n`). A loop whose +calls need fuel that grows with their arguments has no such `n`; for it the honest statements +stay `TripleSome` and `TripleAny` (`Verify.Fuel`), or `TripleWithin B` with a bound `B` +proved for the contract. +-/ + +namespace SolidCore.Verify + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Generic SolidCore.Solidity + +local notation "Br" => SolidCore.Refinement.Generic.Br +local notation "SymState" => SolidCore.Refinement.Generic.SymState + +/-! ## Uniform fuel on a scope -/ + +/-- On every call of `scope`, every fuel from `n` on gives the run at `n`. -/ +def UniformFrom (n : Nat) (c : TypeCheck.CheckedContract) (scope : Call → Prop) : Prop := + ∀ call, scope call → ∀ m, n ≤ m → Source.run m c call = Source.run n c call + +/-- A triple at `n` is a triple at every fuel from `n` on, on a scope where the runs are +uniform from `n`. -/ +theorem Triple.mono_of_uniform {n m : Nat} {c : TypeCheck.CheckedContract} + {scope pre : Call → Prop} {post : Call → Observable → Prop} + (hu : UniformFrom n c scope) (hnm : n ≤ m) (h : Triple n c scope pre post) : + Triple m c scope pre post := by + intro call hs hp + rw [hu call hs m hnm] + exact h call hs hp + +/-! ## The erasure is monotone in its fuel -/ + +namespace Erase + +theorem Br.bind_mono {k k' : SymState → Option Br} + (hk : ∀ S r, k S = some r → k' S = some r) : ∀ {b r : Br}, b.bind k = some r → b.bind k' = some r + | .leaf (.normal S), r, h => hk S r h + | .leaf (.returned _ _), _, h => h + | .leaf (.reverted _), _, h => h + | .ite c t e, r, h => by + simp only [Br.bind, Option.bind_eq_bind, Option.bind_eq_some_iff, Option.some.injEq] at h ⊢ + obtain ⟨t', ht, e', he, rfl⟩ := h + exact ⟨t', Br.bind_mono hk ht, e', Br.bind_mono hk he, rfl⟩ + +theorem eraseSeq_mono {f g : SolidCore.Solidity.Source.Stmt → SymState → Option Br} + (hfg : ∀ s S b, f s S = some b → g s S = some b) : + ∀ (ss : List SolidCore.Solidity.Source.Stmt) (S : SymState) (b : Br), eraseSeq f ss S = some b → eraseSeq g ss S = some b + | [], _, _, h => h + | s :: rest, S, b, h => by + simp only [eraseSeq, Option.bind_eq_bind, Option.bind_eq_some_iff] at h ⊢ + obtain ⟨b0, h0, hb⟩ := h + exact ⟨b0, hfg s S b0 h0, Br.bind_mono (fun S' r hr => eraseSeq_mono hfg rest S' r hr) hb⟩ + +/-- **An erasure that finishes at fuel `n` is the same at every `m ≥ n`.** -/ +theorem eraseStmt_mono (E : EraseEnv) : ∀ (n m : Nat), n ≤ m → + ∀ (s : SolidCore.Solidity.Source.Stmt) (S : SymState) (b : Br), eraseStmt E n s S = some b → eraseStmt E m s S = some b + | 0, _, _, _, _, _, h => by simp [eraseStmt] at h + | n + 1, 0, hnm, _, _, _, _ => absurd hnm (by omega) + | n + 1, m + 1, hnm, s, S, b, h => by + have ih : ∀ s S b, eraseStmt E n s S = some b → eraseStmt E m s S = some b := + eraseStmt_mono E n m (by omega) + unfold eraseStmt at h ⊢ + split at h + all_goals (try dsimp only) + all_goals (try exact h) + all_goals (try (simp at h; done)) + case h_2 => + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h ⊢ + obtain ⟨b0, h0, hb⟩ := h + exact ⟨b0, eraseSeq_mono ih _ _ _ h0, hb⟩ + case h_9 => + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h ⊢ + obtain ⟨⟨gs, v⟩, hp, h⟩ := h + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨bt, ht, be, he, hb⟩ := h + exact ⟨⟨gs, v⟩, hp, by + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] + exact ⟨bt, ih _ _ _ ht, be, ih _ _ _ he, hb⟩⟩ + case h_15 => + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h ⊢ + obtain ⟨fn, hfn, h⟩ := h + refine ⟨fn, hfn, ?_⟩ + split at h + · rename_i hc + rw [if_pos hc] + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h ⊢ + obtain ⟨⟨gs, vs⟩, hp, h⟩ := h + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨b0, h0, b1, h1, hb⟩ := h + exact ⟨⟨gs, vs⟩, hp, by + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] + exact ⟨b0, ih _ _ _ h0, b1, h1, hb⟩⟩ + · simp at h + case h_16 => + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h ⊢ + obtain ⟨b0, h0, hb⟩ := h + exact ⟨b0, ih _ _ _ h0, hb⟩ + -- An `unchecked` block: its erasure needs fuel 2 and does not recurse. + all_goals + split at h + · rw [if_pos (by omega)]; exact h + · simp at h + +/-- **An erased function's tree at fuel `n` is its tree at every `m ≥ n`.** -/ +theorem eraseFn_mono {E : EraseEnv} {n m : Nat} (hnm : n ≤ m) {fn : Source.FunctionDef} {T : Tree} + (h : eraseFn E n fn = some T) : eraseFn E m fn = some T := by + unfold eraseFn at h ⊢ + split at h + · simp at h + split at h + case isFalse => simp at h + rename_i hret + rw [if_pos hret] + simp only [Option.bind_eq_bind, Option.bind_eq_some_iff] at h ⊢ + obtain ⟨b, hb, t, ht, hT⟩ := h + exact ⟨b, eraseStmt_mono _ n m hnm _ _ _ hb, t, ht, hT⟩ + +end Erase + +/-! ## The generic source stage, uniformly from one fuel -/ + +/-- The constructor of `c` leaves the entries `s` and no logs at every fuel from `n` on. -/ +def DeployStable (n : Nat) (c : TypeCheck.CheckedContract) (s : List (Nat × Nat)) : Prop := + ∀ m, n ≤ m → ∃ d, Wide.DeployedAt m c d s + +/-- **Every function the generic source stage erases at `n` runs uniformly from `n`** on the +stage's scope, given that the constructor's result is stable from `n`. -/ +theorem uniformFrom_stage {n : Nat} {c : TypeCheck.CheckedContract} {s : List (Nat × Nat)} + (hdep : DeployStable n c s) {fn : Fn} {f : Source.FunctionDef} (hsel : fn.sel < 2 ^ 32) + (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) n f = some T) : + UniformFrom n c (VC.stageScope fn s) := by + rintro _ ⟨σ, hcov, fn', hfn', args, hl, hargs, rfl⟩ m hnm + simp only [List.mem_singleton] at hfn' + subst hfn' + obtain ⟨dm, hdm⟩ := hdep m hnm + obtain ⟨dn, hdn⟩ := hdep n (Nat.le_refl n) + rw [source_run hdm hcov hsel hfind (Erase.eraseFn_mono hnm hT) args (hl.trans hlen.symm) hargs, + source_run hdn hcov hsel hfind hT args (hl.trans hlen.symm) hargs] + +/-- **The generic theorem from an erased function to its obligations, at every fuel from `n` +on.** -/ +theorem triple_of_binds_from {n m : Nat} (hnm : n ≤ m) {c : TypeCheck.CheckedContract} + {s : List (Nat × Nat)} (hdep : DeployStable n c s) {fn : Fn} {f : Source.FunctionDef} + (hsel : fn.sel < 2 ^ 32) (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) n f = some T) {obs : List (List VC.Tm × VC.Tm)} + {env : List Nat → Storage → VC.Env} {P : List Nat → Storage → Observable → Prop} + (hobs : VC.ObsValid obs) (hbind : VC.Binds fn T obs env P) : + Triple m c (VC.stageScope fn s) (fun _ => True) (VC.treePost fn P) := by + obtain ⟨d, hd⟩ := hdep n (Nat.le_refl n) + exact Triple.mono_of_uniform (uniformFrom_stage hdep hsel hfind hlen hT) hnm + (VC.triple_of_binds hd hsel hfind hlen hT hobs hbind) + +/-! ## `Source.run` fuel monotonicity, wired + +`SolidCore.Refinement.Source.run_fuel_mono` (`SolidCore/Refinement/Fuel.lean`, on +`SolidCore.Solidity.FuelExtension`'s per-path extension) proves that a finished run is the run +at every higher fuel, for a constructor that gives the same result at both fuels +(`CtorStable`). `FuelStable` of `Verify.Fuel` is that statement for every pair of fuels; the +constructor's stability stays a hypothesis there, for the reason `Refinement/Fuel.lean` gives +(the hook's depth is the fuel, and its unreachability during construction is not proved). + +* `fuelStable_of_ctorStable`: constructor stability at every pair of fuels gives `FuelStable`, + so every some-fuel form of `Verify.Fuel` (`tripleAny_of_some`, `triple_of_within`) applies. +* `Triple.mono_of_ctorStable`, `uniformFrom_of_triple`: a triple at `n` (every call of the scope + finishes at `n`) is a triple at every `m ≥ n`, and the runs are uniform from `n`, given only + constructor stability on the scope's calls, with no argument about the function. +-/ + +/-- Constructor stability at every pair of fuels gives fuel stability. -/ +theorem fuelStable_of_ctorStable {c : TypeCheck.CheckedContract} + (hctor : ∀ n m call, n ≤ m → CtorStable n m c call) : FuelStable c := + fun n m call _ hnm h => Source.run_fuel_mono hnm (hctor n m call hnm) h + +/-- A triple at `n` is a triple at every `m ≥ n` whose constructor run is the one at `n`. -/ +theorem Triple.mono_of_ctorStable {n m : Nat} (hnm : n ≤ m) {c : TypeCheck.CheckedContract} + {scope pre : Call → Prop} {post : Call → Observable → Prop} + (hctor : ∀ call, scope call → CtorStable n m c call) (h : Triple n c scope pre post) : + Triple m c scope pre post := by + intro call hs hp + obtain ⟨hsome, hpost⟩ := h call hs hp + obtain ⟨obs, hobs⟩ := Option.isSome_iff_exists.mp hsome + have hm := Source.run_fuel_mono hnm (hctor call hs) hobs + refine ⟨by simp [hm], fun o ho => ?_⟩ + rw [hm] at ho + cases ho + exact hpost obs hobs + +/-- The runs of a scope on which a triple holds at `n` are uniform from `n`, given constructor +stability on the scope's calls. -/ +theorem uniformFrom_of_triple {n : Nat} {c : TypeCheck.CheckedContract} + {scope pre : Call → Prop} {post : Call → Observable → Prop} + (hctor : ∀ m, n ≤ m → ∀ call, scope call → CtorStable n m c call) + (h : Triple n c scope (fun _ => True) post) : UniformFrom n c scope := by + intro call hs m hnm + obtain ⟨hsome, -⟩ := h call hs trivial + obtain ⟨obs, hobs⟩ := Option.isSome_iff_exists.mp hsome + rw [hobs, Source.run_fuel_mono hnm (hctor m hnm call hs) hobs] + +#print axioms fuelStable_of_ctorStable +#print axioms Triple.mono_of_ctorStable +#print axioms uniformFrom_of_triple +#print axioms Erase.eraseFn_mono +#print axioms uniformFrom_stage +#print axioms triple_of_binds_from + +end SolidCore.Verify diff --git a/Verify/Infer/README.md b/Verify/Infer/README.md new file mode 100644 index 00000000..cdf84c18 --- /dev/null +++ b/Verify/Infer/README.md @@ -0,0 +1,45 @@ +# Loop-invariant reconstruction: evidence + +What this directory shows: three loops' invariants, returned unedited by z3's Spacer engine, are +proved by the Lean kernel to satisfy initiation, preservation and use, with no axiom beyond +`propext`, `Classical.choice` and `Quot.sound`. Nothing here is built by `lake build`: the +default library roots are under `SolidCore`, and these files are checked on their own. + +## What is and is not proved + +- The Horn clauses (`chc/*.smt2`) and the Lean statements of each obligation were written by hand + from the Solidity source of each loop. They are **not** solar-verify's emitted verification + conditions, and nothing here proves that they match the EVM, the compiler or solar-verify's + encoding. Treat them as a reconstruction method, not as a certificate for any contract. +- The `*_u256` variants model Solidity 0.8 checked arithmetic as path guards: every arithmetic + result lies in `[0, 2^256)`, and a path that would overflow reverts and is dropped. They do not + prove that the loops never revert. The `*_int` variants use unbounded integers with the + `uint` inputs nonnegative; they say nothing about EVM words. +- Only the invariant is searched for by an untrusted solver; the proofs check it. + +Loops: `counter` (`for (i = 0; i < n; i++) count++` under `require(count + n <= limit)`, ensures +`count == old(count) + n && count <= limit`), `okwhile` (`i = 0; while (i < n) i++`, ensures +`i == n`), `drain` (`a = n; b = 0; while (a > 0) { a--; b++; }`, ensures `b == n`). + +For a loop whose cut solar-verify exports (--emit-loopvc) rather than a person writes, and whose +obligations are generated and discharged by Verify/Discharge, see [loopvc/](loopvc/README.md) +(Counter.bump: initiation, preservation, termination and exit rows, kernel-checked). + +## Files + +- `Reconstruct.lean`: Lean core only. Each `Inv_*` is generated by `smt2lean_inv.py` from the + Spacer model in `chc/*.spacer.out` (a 1:1 operator translation, `let` kept, no simplification), + and each obligation is closed by `simp only [Inv_*]; omega`. Generated by `gen_reconstruct.sh`. + Check with `lean Reconstruct.lean` on `leanprover/lean4:v4.35.0`: 18 theorems, 0.45 s, 480 MB + peak; output in `reconstruct-4.35.axioms.txt`. +- `SpacerPath.lean`: the same three loops through the `spacer` tactic of + [LeanHorn/Flex](https://github.com/LeanHorn/Flex) at `79bdae0d3d7069e5239174d52e1fc26fa035d249` + (it calls Spacer, imports the model, and certifies with `grind`). It needs Flex, so it does + not build here; output in `spacerpath-4.35.out` (6 theorems, 3.5 s, 1.95 GB). Flex builds on + 4.35.0 with the lakefile change in `flex-4.35-bump.diff` and no source change. Flex's + `flex_auto` (a trusted SMT axiom) was not used, and its own certificate check does not reject + `native_decide`, so every theorem was gated by `#print axioms`. Flex's `fix` path fails on + `counter` (recursion depth, then a heartbeat timeout), so it is not used. +- `chc/`: the Horn problems in SMT-LIB and Spacer's answers (z3 5.4.1). + +Checksums are in `SHA256SUMS`. diff --git a/Verify/Infer/Reconstruct.lean b/Verify/Infer/Reconstruct.lean new file mode 100644 index 00000000..93ad4f34 --- /dev/null +++ b/Verify/Infer/Reconstruct.lean @@ -0,0 +1,107 @@ +/-! Kernel-checked initiation / preservation / use for the three loops. + Each Inv_* below is generated by smt2lean_inv.py from the z3 Spacer model, unedited. + Only Lean core is imported (no Flex, no Mathlib). -/ +namespace FlexEval + +/-- Verbatim from chc/counter_int.spacer.out (z3 Spacer model for Inv). -/ +def Inv_counter_int (x_0 : Int) (x_1 : Int) (x_2 : Int) (x_3 : Int) (x_4 : Int) : Prop := + (let a_1 : Prop := (¬ ((x_0 + x_3 + ((-(1 : Int)) * x_4)) ≤ (-(1 : Int)))); (let a_2 : Prop := (¬ ((x_0 + x_1 + ((-(1 : Int)) * x_4)) ≤ (-(1 : Int)))); (let a_3 : Prop := (¬ ((x_0 + x_3 + ((-(1 : Int)) * x_4)) ≥ (1 : Int))); (let a_4 : Prop := (¬ ((x_1 + ((-(1 : Int)) * x_2) + ((-(1 : Int)) * x_3) + x_4) ≥ (1 : Int))); (a_1 ∧ a_2 ∧ a_3 ∧ a_4))))) + +/-- Verbatim from chc/counter_u256.spacer.out (z3 Spacer model for Inv). -/ +def Inv_counter_u256 (x_0 : Int) (x_1 : Int) (x_2 : Int) (x_3 : Int) (x_4 : Int) : Prop := + (let a_1 : Prop := (¬ ((x_0 + x_3 + ((-(1 : Int)) * x_4)) ≤ (-(1 : Int)))); (let a_2 : Prop := (¬ ((x_0 + x_1 + ((-(1 : Int)) * x_4)) ≤ (-(1 : Int)))); (let a_3 : Prop := (¬ ((x_0 + x_3 + ((-(1 : Int)) * x_4)) ≥ (1 : Int))); (let a_4 : Prop := (¬ ((x_1 + ((-(1 : Int)) * x_2) + ((-(1 : Int)) * x_3) + x_4) ≥ (1 : Int))); (a_1 ∧ a_2 ∧ a_3 ∧ a_4))))) + +/-- Verbatim from chc/okwhile_int.spacer.out (z3 Spacer model for Inv). -/ +def Inv_okwhile_int (x_0 : Int) (x_1 : Int) : Prop := + (¬ ((x_0 + ((-(1 : Int)) * x_1)) ≤ (-(1 : Int)))) + +/-- Verbatim from chc/okwhile_u256.spacer.out (z3 Spacer model for Inv). -/ +def Inv_okwhile_u256 (x_0 : Int) (x_1 : Int) : Prop := + (¬ ((x_0 + ((-(1 : Int)) * x_1)) ≤ (-(1 : Int)))) + +/-- Verbatim from chc/drain_int.spacer.out (z3 Spacer model for Inv). -/ +def Inv_drain_int (x_0 : Int) (x_1 : Int) (x_2 : Int) : Prop := + (let a_1 : Prop := (¬ ((x_0 + ((-(1 : Int)) * x_1) + ((-(1 : Int)) * x_2)) ≤ (-(1 : Int)))); (let a_2 : Prop := (¬ ((x_0 + ((-(1 : Int)) * x_2)) ≤ (-(1 : Int)))); (let a_3 : Prop := (¬ ((x_0 + ((-(1 : Int)) * x_1) + ((-(1 : Int)) * x_2)) ≥ (1 : Int))); (a_1 ∧ a_2 ∧ a_3)))) + +/-- Verbatim from chc/drain_u256.spacer.out (z3 Spacer model for Inv). -/ +def Inv_drain_u256 (x_0 : Int) (x_1 : Int) (x_2 : Int) : Prop := + (let a_1 : Prop := (¬ ((x_0 + ((-(1 : Int)) * x_1) + ((-(1 : Int)) * x_2)) ≤ (-(1 : Int)))); (let a_2 : Prop := (¬ ((x_0 + ((-(1 : Int)) * x_2)) ≤ (-(1 : Int)))); (let a_3 : Prop := (¬ ((x_0 + ((-(1 : Int)) * x_1) + ((-(1 : Int)) * x_2)) ≥ (1 : Int))); (a_1 ∧ a_2 ∧ a_3)))) + +/-! ## (a) Counter.bump — vars (c0 = old count, n, lim, i, c = count) -/ + +-- mathematical Int (uint inputs nonnegative, no overflow guards) +theorem counter_int_init : ∀ c0 n lim : Int, + 0 ≤ c0 → 0 ≤ n → 0 ≤ lim → c0 ≤ lim → c0 + n ≤ lim → Inv_counter_int c0 n lim 0 c0 := by + intros; simp only [Inv_counter_int]; omega +theorem counter_int_pres : ∀ c0 n lim i c : Int, + Inv_counter_int c0 n lim i c → i < n → Inv_counter_int c0 n lim (i + 1) (c + 1) := by + intros; simp only [Inv_counter_int] at *; omega +theorem counter_int_use : ∀ c0 n lim i c : Int, + Inv_counter_int c0 n lim i c → ¬ (i < n) → c = c0 + n ∧ c ≤ lim := by + intros; simp only [Inv_counter_int] at *; omega + +-- uint256 with Solidity 0.8 checked arithmetic: every op result must lie in [0, 2^256) +theorem counter_u256_init : ∀ c0 n lim : Int, + 0 ≤ c0 → c0 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → 0 ≤ n → n < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → 0 ≤ lim → lim < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → c0 ≤ lim → + 0 ≤ c0 + n → c0 + n < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → c0 + n ≤ lim → Inv_counter_u256 c0 n lim 0 c0 := by + intros; simp only [Inv_counter_u256]; omega +theorem counter_u256_pres : ∀ c0 n lim i c : Int, + Inv_counter_u256 c0 n lim i c → i < n → + 0 ≤ c + 1 → c + 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → 0 ≤ i + 1 → i + 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → + Inv_counter_u256 c0 n lim (i + 1) (c + 1) := by + intros; simp only [Inv_counter_u256] at *; omega +theorem counter_u256_use : ∀ c0 n lim i c : Int, + Inv_counter_u256 c0 n lim i c → ¬ (i < n) → c = c0 + n ∧ c ≤ lim := by + intros; simp only [Inv_counter_u256] at *; omega + +/-! ## (b) ok_while — vars (n, i) -/ +theorem okwhile_int_init : ∀ n : Int, 0 ≤ n → Inv_okwhile_int n 0 := by + intros; simp only [Inv_okwhile_int]; omega +theorem okwhile_int_pres : ∀ n i : Int, Inv_okwhile_int n i → i < n → Inv_okwhile_int n (i + 1) := by + intros; simp only [Inv_okwhile_int] at *; omega +theorem okwhile_int_use : ∀ n i : Int, Inv_okwhile_int n i → ¬ (i < n) → i = n := by + intros; simp only [Inv_okwhile_int] at *; omega + +theorem okwhile_u256_init : ∀ n : Int, 0 ≤ n → n < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → Inv_okwhile_u256 n 0 := by + intros; simp only [Inv_okwhile_u256]; omega +theorem okwhile_u256_pres : ∀ n i : Int, Inv_okwhile_u256 n i → i < n → + 0 ≤ i + 1 → i + 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → Inv_okwhile_u256 n (i + 1) := by + intros; simp only [Inv_okwhile_u256] at *; omega +theorem okwhile_u256_use : ∀ n i : Int, Inv_okwhile_u256 n i → ¬ (i < n) → i = n := by + intros; simp only [Inv_okwhile_u256] at *; omega + +/-! ## (c) drain — vars (n, a, b) -/ +theorem drain_int_init : ∀ n : Int, 0 ≤ n → Inv_drain_int n n 0 := by + intros; simp only [Inv_drain_int]; omega +theorem drain_int_pres : ∀ n a b : Int, Inv_drain_int n a b → a > 0 → Inv_drain_int n (a - 1) (b + 1) := by + intros; simp only [Inv_drain_int] at *; omega +theorem drain_int_use : ∀ n a b : Int, Inv_drain_int n a b → ¬ (a > 0) → b = n := by + intros; simp only [Inv_drain_int] at *; omega + +theorem drain_u256_init : ∀ n : Int, 0 ≤ n → n < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → Inv_drain_u256 n n 0 := by + intros; simp only [Inv_drain_u256]; omega +theorem drain_u256_pres : ∀ n a b : Int, Inv_drain_u256 n a b → a > 0 → + 0 ≤ a - 1 → a - 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → 0 ≤ b + 1 → b + 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → Inv_drain_u256 n (a - 1) (b + 1) := by + intros; simp only [Inv_drain_u256] at *; omega +theorem drain_u256_use : ∀ n a b : Int, Inv_drain_u256 n a b → ¬ (a > 0) → b = n := by + intros; simp only [Inv_drain_u256] at *; omega + +end FlexEval +#print axioms FlexEval.counter_int_init +#print axioms FlexEval.counter_int_pres +#print axioms FlexEval.counter_int_use +#print axioms FlexEval.counter_u256_init +#print axioms FlexEval.counter_u256_pres +#print axioms FlexEval.counter_u256_use +#print axioms FlexEval.okwhile_int_init +#print axioms FlexEval.okwhile_int_pres +#print axioms FlexEval.okwhile_int_use +#print axioms FlexEval.okwhile_u256_init +#print axioms FlexEval.okwhile_u256_pres +#print axioms FlexEval.okwhile_u256_use +#print axioms FlexEval.drain_int_init +#print axioms FlexEval.drain_int_pres +#print axioms FlexEval.drain_int_use +#print axioms FlexEval.drain_u256_init +#print axioms FlexEval.drain_u256_pres +#print axioms FlexEval.drain_u256_use diff --git a/Verify/Infer/SHA256SUMS b/Verify/Infer/SHA256SUMS new file mode 100644 index 00000000..d113db79 --- /dev/null +++ b/Verify/Infer/SHA256SUMS @@ -0,0 +1,19 @@ +673aca7661560d45057a06403d02a3a16feca2b1f637dfcee3372ec514e0e1fd Reconstruct.lean +efca9dbbff32afbb2573d138cb1e0e3a38ec56e456172a191d604ebc731b5c90 SpacerPath.lean +157f485074857d8e11eca42524f1116a2b795cc1404e90b845f989246971ae31 smt2lean_inv.py +6a4bb9a858e3e460bcfc250a2972c7b39cad4fbdc9ac845a7eba86b954416583 gen_reconstruct.sh +293cfc981e4fbd1b05d625905bdf6d92b7358bf9f0bc7dbe58e96af84f2c60ff flex-4.35-bump.diff +08369f395413723dccd13dfe9ceb297229dd514f5eac12dc501b5467e33aff3a reconstruct-4.35.axioms.txt +9141801fdacc2936d9133ffc03f3dd6dc84614a4d9ae6dcd643900a6f58794df spacerpath-4.35.out +cc3ee632f13e149b021c78b773c52a9863018b22ec6c13731500ea25f227e396 chc/counter_int.smt2 +4d40ed36d01ce06f15ffa4beabb178d857919ce05cb835121c0e69eded24a9c4 chc/counter_int.spacer.out +7040ff503425ed654fc6be72d31722d752b1918f0aaea19dd4a3c5f7e6985371 chc/counter_u256.smt2 +4d40ed36d01ce06f15ffa4beabb178d857919ce05cb835121c0e69eded24a9c4 chc/counter_u256.spacer.out +a9ca18a4324f01aa5a9db43137178ddc756ef43a2f3c8e81b877c66229496360 chc/drain_int.smt2 +c01c2caa8918b8778822d969b8635241f08b89073c0ab7b866236cb9aa496fce chc/drain_int.spacer.out +0af97cde8a836def4b7789e30bda1cd52a9b424dbae81b0d0479ca7686c18478 chc/drain_u256.smt2 +c01c2caa8918b8778822d969b8635241f08b89073c0ab7b866236cb9aa496fce chc/drain_u256.spacer.out +6e1eb36aaa4cc820b6fdf8c846cf5ef5389cd121cab826cf08086ba1fb4d8c3a chc/okwhile_int.smt2 +a294c8fda0224319cae15af3ddb21f63d69933d769fae83390c0976e7cb6384b chc/okwhile_int.spacer.out +21c65b3c859069bdd10f084da85aefdcc64753dc4f88909fd3fa3637fe1d7ceb chc/okwhile_u256.smt2 +a294c8fda0224319cae15af3ddb21f63d69933d769fae83390c0976e7cb6384b chc/okwhile_u256.spacer.out diff --git a/Verify/Infer/SpacerPath.lean b/Verify/Infer/SpacerPath.lean new file mode 100644 index 00000000..fbcd4695 --- /dev/null +++ b/Verify/Infer/SpacerPath.lean @@ -0,0 +1,64 @@ +import Flex.Tactic.Tactics.Spacer +/-! Flex's spacer path: export CHC to z3 Spacer, import its model, instantiate the invariant, + certify predicate heads (init/step) with grind; the remaining query VC (use) is closed by grind. + No invariant is written by hand. -/ +namespace FlexEval.SpacerPath + +theorem counter_int : + ∃ inv : Int → Int → Int → Int → Int → Prop, + (∀ c0 n lim, 0 ≤ c0 → 0 ≤ n → 0 ≤ lim → c0 ≤ lim → c0 + n ≤ lim → inv c0 n lim 0 c0) ∧ + (∀ c0 n lim i c, inv c0 n lim i c → i < n → inv c0 n lim (i + 1) (c + 1)) ∧ + (∀ c0 n lim i c, inv c0 n lim i c → ¬ (i < n) → c = c0 + n ∧ c ≤ lim) := by + spacer + grind + +theorem counter_u256 : + ∃ inv : Int → Int → Int → Int → Int → Prop, + (∀ c0 n lim, 0 ≤ c0 → c0 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → 0 ≤ n → n < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → 0 ≤ lim → lim < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → c0 ≤ lim → + 0 ≤ c0 + n → c0 + n < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → c0 + n ≤ lim → inv c0 n lim 0 c0) ∧ + (∀ c0 n lim i c, inv c0 n lim i c → i < n → + 0 ≤ c + 1 → c + 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → 0 ≤ i + 1 → i + 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → inv c0 n lim (i + 1) (c + 1)) ∧ + (∀ c0 n lim i c, inv c0 n lim i c → ¬ (i < n) → c = c0 + n ∧ c ≤ lim) := by + spacer + grind + +theorem okwhile_int : + ∃ inv : Int → Int → Prop, + (∀ n, 0 ≤ n → inv n 0) ∧ + (∀ n i, inv n i → i < n → inv n (i + 1)) ∧ + (∀ n i, inv n i → ¬ (i < n) → i = n) := by + spacer + grind + +theorem okwhile_u256 : + ∃ inv : Int → Int → Prop, + (∀ n, 0 ≤ n → n < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → inv n 0) ∧ + (∀ n i, inv n i → i < n → 0 ≤ i + 1 → i + 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → inv n (i + 1)) ∧ + (∀ n i, inv n i → ¬ (i < n) → i = n) := by + spacer + grind + +theorem drain_int : + ∃ inv : Int → Int → Int → Prop, + (∀ n, 0 ≤ n → inv n n 0) ∧ + (∀ n a b, inv n a b → a > 0 → inv n (a - 1) (b + 1)) ∧ + (∀ n a b, inv n a b → ¬ (a > 0) → b = n) := by + spacer + grind + +theorem drain_u256 : + ∃ inv : Int → Int → Int → Prop, + (∀ n, 0 ≤ n → n < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → inv n n 0) ∧ + (∀ n a b, inv n a b → a > 0 → 0 ≤ a - 1 → a - 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → 0 ≤ b + 1 → b + 1 < 115792089237316195423570985008687907853269984665640564039457584007913129639936 → + inv n (a - 1) (b + 1)) ∧ + (∀ n a b, inv n a b → ¬ (a > 0) → b = n) := by + spacer + grind + +end FlexEval.SpacerPath +#print axioms FlexEval.SpacerPath.counter_int +#print axioms FlexEval.SpacerPath.counter_u256 +#print axioms FlexEval.SpacerPath.okwhile_int +#print axioms FlexEval.SpacerPath.okwhile_u256 +#print axioms FlexEval.SpacerPath.drain_int +#print axioms FlexEval.SpacerPath.drain_u256 diff --git a/Verify/Infer/chc/counter_int.smt2 b/Verify/Infer/chc/counter_int.smt2 new file mode 100644 index 00000000..38b66168 --- /dev/null +++ b/Verify/Infer/chc/counter_int.smt2 @@ -0,0 +1,21 @@ +; Counter.bump CHC, mathematical Int (uint params >= 0, no overflow guards) semantics +; vars: c0 = old(count), n, lim = limit, i, c = count +(set-logic HORN) +(declare-fun Inv (Int Int Int Int Int) Bool) +; init: entry state satisfies param ranges, contract invariant c0 <= lim, require(count + n <= limit) (checked add), i = 0, count = c0 +(assert (forall ((c0 Int) (n Int) (lim Int)) + (=> (and (<= 0 c0) (<= 0 n) (<= 0 lim) (<= c0 lim) + (<= (+ c0 n) lim)) + (Inv c0 n lim 0 c0)))) +; step: body count++ (checked) then i++ (checked); a reverting op drops the path +(assert (forall ((c0 Int) (n Int) (lim Int) (i Int) (c Int)) + (=> (and (Inv c0 n lim i c) (< i n) + ) + (Inv c0 n lim (+ i 1) (+ c 1))))) +; safety: on exit, ensures count == old(count) + n and contract invariant count <= limit +(assert (forall ((c0 Int) (n Int) (lim Int) (i Int) (c Int)) + (=> (and (Inv c0 n lim i c) (not (< i n)) + (not (and (= c (+ c0 n)) (<= c lim)))) + false))) +(check-sat) +(get-model) diff --git a/Verify/Infer/chc/counter_int.spacer.out b/Verify/Infer/chc/counter_int.spacer.out new file mode 100644 index 00000000..716e2ad9 --- /dev/null +++ b/Verify/Infer/chc/counter_int.spacer.out @@ -0,0 +1,9 @@ +sat +( + (define-fun Inv ((x!0 Int) (x!1 Int) (x!2 Int) (x!3 Int) (x!4 Int)) Bool + (let ((a!1 (not (<= (+ x!0 x!3 (* (- 1) x!4)) (- 1)))) + (a!2 (not (<= (+ x!0 x!1 (* (- 1) x!4)) (- 1)))) + (a!3 (not (>= (+ x!0 x!3 (* (- 1) x!4)) 1))) + (a!4 (not (>= (+ x!1 (* (- 1) x!2) (* (- 1) x!3) x!4) 1)))) + (and a!1 a!2 a!3 a!4))) +) diff --git a/Verify/Infer/chc/counter_u256.smt2 b/Verify/Infer/chc/counter_u256.smt2 new file mode 100644 index 00000000..cacc17cf --- /dev/null +++ b/Verify/Infer/chc/counter_u256.smt2 @@ -0,0 +1,21 @@ +; Counter.bump CHC, uint256 checked-arithmetic semantics +; vars: c0 = old(count), n, lim = limit, i, c = count +(set-logic HORN) +(declare-fun Inv (Int Int Int Int Int) Bool) +; init: entry state satisfies param ranges, contract invariant c0 <= lim, require(count + n <= limit) (checked add), i = 0, count = c0 +(assert (forall ((c0 Int) (n Int) (lim Int)) + (=> (and (and (<= 0 c0) (< c0 115792089237316195423570985008687907853269984665640564039457584007913129639936)) (and (<= 0 n) (< n 115792089237316195423570985008687907853269984665640564039457584007913129639936)) (and (<= 0 lim) (< lim 115792089237316195423570985008687907853269984665640564039457584007913129639936)) (<= c0 lim) + (and (<= 0 (+ c0 n)) (< (+ c0 n) 115792089237316195423570985008687907853269984665640564039457584007913129639936)) (<= (+ c0 n) lim)) + (Inv c0 n lim 0 c0)))) +; step: body count++ (checked) then i++ (checked); a reverting op drops the path +(assert (forall ((c0 Int) (n Int) (lim Int) (i Int) (c Int)) + (=> (and (Inv c0 n lim i c) (< i n) + (and (<= 0 (+ c 1)) (< (+ c 1) 115792089237316195423570985008687907853269984665640564039457584007913129639936)) (and (<= 0 (+ i 1)) (< (+ i 1) 115792089237316195423570985008687907853269984665640564039457584007913129639936))) + (Inv c0 n lim (+ i 1) (+ c 1))))) +; safety: on exit, ensures count == old(count) + n and contract invariant count <= limit +(assert (forall ((c0 Int) (n Int) (lim Int) (i Int) (c Int)) + (=> (and (Inv c0 n lim i c) (not (< i n)) + (not (and (= c (+ c0 n)) (<= c lim)))) + false))) +(check-sat) +(get-model) diff --git a/Verify/Infer/chc/counter_u256.spacer.out b/Verify/Infer/chc/counter_u256.spacer.out new file mode 100644 index 00000000..716e2ad9 --- /dev/null +++ b/Verify/Infer/chc/counter_u256.spacer.out @@ -0,0 +1,9 @@ +sat +( + (define-fun Inv ((x!0 Int) (x!1 Int) (x!2 Int) (x!3 Int) (x!4 Int)) Bool + (let ((a!1 (not (<= (+ x!0 x!3 (* (- 1) x!4)) (- 1)))) + (a!2 (not (<= (+ x!0 x!1 (* (- 1) x!4)) (- 1)))) + (a!3 (not (>= (+ x!0 x!3 (* (- 1) x!4)) 1))) + (a!4 (not (>= (+ x!1 (* (- 1) x!2) (* (- 1) x!3) x!4) 1)))) + (and a!1 a!2 a!3 a!4))) +) diff --git a/Verify/Infer/chc/drain_int.smt2 b/Verify/Infer/chc/drain_int.smt2 new file mode 100644 index 00000000..6d260420 --- /dev/null +++ b/Verify/Infer/chc/drain_int.smt2 @@ -0,0 +1,10 @@ +; Drain.drain (a = n; b = 0; while (a > 0) { a--; b++; } return b; ensures result == n) CHC, mathematical Int (uint param >= 0, no overflow guards) semantics +(set-logic HORN) +(declare-fun Inv (Int Int Int) Bool) +(assert (forall ((n Int)) (=> (<= 0 n) (Inv n n 0)))) +(assert (forall ((n Int) (a Int) (b Int)) + (=> (and (Inv n a b) (> a 0) ) (Inv n (- a 1) (+ b 1))))) +(assert (forall ((n Int) (a Int) (b Int)) + (=> (and (Inv n a b) (not (> a 0)) (not (= b n))) false))) +(check-sat) +(get-model) diff --git a/Verify/Infer/chc/drain_int.spacer.out b/Verify/Infer/chc/drain_int.spacer.out new file mode 100644 index 00000000..f0a0494d --- /dev/null +++ b/Verify/Infer/chc/drain_int.spacer.out @@ -0,0 +1,8 @@ +sat +( + (define-fun Inv ((x!0 Int) (x!1 Int) (x!2 Int)) Bool + (let ((a!1 (not (<= (+ x!0 (* (- 1) x!1) (* (- 1) x!2)) (- 1)))) + (a!2 (not (<= (+ x!0 (* (- 1) x!2)) (- 1)))) + (a!3 (not (>= (+ x!0 (* (- 1) x!1) (* (- 1) x!2)) 1)))) + (and a!1 a!2 a!3))) +) diff --git a/Verify/Infer/chc/drain_u256.smt2 b/Verify/Infer/chc/drain_u256.smt2 new file mode 100644 index 00000000..bc04675a --- /dev/null +++ b/Verify/Infer/chc/drain_u256.smt2 @@ -0,0 +1,10 @@ +; Drain.drain (a = n; b = 0; while (a > 0) { a--; b++; } return b; ensures result == n) CHC, uint256 checked-arithmetic semantics +(set-logic HORN) +(declare-fun Inv (Int Int Int) Bool) +(assert (forall ((n Int)) (=> (and (<= 0 n) (< n 115792089237316195423570985008687907853269984665640564039457584007913129639936)) (Inv n n 0)))) +(assert (forall ((n Int) (a Int) (b Int)) + (=> (and (Inv n a b) (> a 0) (and (<= 0 (- a 1)) (< (- a 1) 115792089237316195423570985008687907853269984665640564039457584007913129639936)) (and (<= 0 (+ b 1)) (< (+ b 1) 115792089237316195423570985008687907853269984665640564039457584007913129639936))) (Inv n (- a 1) (+ b 1))))) +(assert (forall ((n Int) (a Int) (b Int)) + (=> (and (Inv n a b) (not (> a 0)) (not (= b n))) false))) +(check-sat) +(get-model) diff --git a/Verify/Infer/chc/drain_u256.spacer.out b/Verify/Infer/chc/drain_u256.spacer.out new file mode 100644 index 00000000..f0a0494d --- /dev/null +++ b/Verify/Infer/chc/drain_u256.spacer.out @@ -0,0 +1,8 @@ +sat +( + (define-fun Inv ((x!0 Int) (x!1 Int) (x!2 Int)) Bool + (let ((a!1 (not (<= (+ x!0 (* (- 1) x!1) (* (- 1) x!2)) (- 1)))) + (a!2 (not (<= (+ x!0 (* (- 1) x!2)) (- 1)))) + (a!3 (not (>= (+ x!0 (* (- 1) x!1) (* (- 1) x!2)) 1)))) + (and a!1 a!2 a!3))) +) diff --git a/Verify/Infer/chc/okwhile_int.smt2 b/Verify/Infer/chc/okwhile_int.smt2 new file mode 100644 index 00000000..60a1a33f --- /dev/null +++ b/Verify/Infer/chc/okwhile_int.smt2 @@ -0,0 +1,10 @@ +; Control.ok_no_invariant (ok_while) CHC, mathematical Int (uint param >= 0, no overflow guards) semantics +(set-logic HORN) +(declare-fun Inv (Int Int) Bool) +(assert (forall ((n Int)) (=> (<= 0 n) (Inv n 0)))) +(assert (forall ((n Int) (i Int)) + (=> (and (Inv n i) (< i n) ) (Inv n (+ i 1))))) +(assert (forall ((n Int) (i Int)) + (=> (and (Inv n i) (not (< i n)) (not (= i n))) false))) +(check-sat) +(get-model) diff --git a/Verify/Infer/chc/okwhile_int.spacer.out b/Verify/Infer/chc/okwhile_int.spacer.out new file mode 100644 index 00000000..1442c652 --- /dev/null +++ b/Verify/Infer/chc/okwhile_int.spacer.out @@ -0,0 +1,5 @@ +sat +( + (define-fun Inv ((x!0 Int) (x!1 Int)) Bool + (not (<= (+ x!0 (* (- 1) x!1)) (- 1)))) +) diff --git a/Verify/Infer/chc/okwhile_u256.smt2 b/Verify/Infer/chc/okwhile_u256.smt2 new file mode 100644 index 00000000..4967d69e --- /dev/null +++ b/Verify/Infer/chc/okwhile_u256.smt2 @@ -0,0 +1,10 @@ +; Control.ok_no_invariant (ok_while) CHC, uint256 checked-arithmetic semantics +(set-logic HORN) +(declare-fun Inv (Int Int) Bool) +(assert (forall ((n Int)) (=> (and (<= 0 n) (< n 115792089237316195423570985008687907853269984665640564039457584007913129639936)) (Inv n 0)))) +(assert (forall ((n Int) (i Int)) + (=> (and (Inv n i) (< i n) (and (<= 0 (+ i 1)) (< (+ i 1) 115792089237316195423570985008687907853269984665640564039457584007913129639936))) (Inv n (+ i 1))))) +(assert (forall ((n Int) (i Int)) + (=> (and (Inv n i) (not (< i n)) (not (= i n))) false))) +(check-sat) +(get-model) diff --git a/Verify/Infer/chc/okwhile_u256.spacer.out b/Verify/Infer/chc/okwhile_u256.spacer.out new file mode 100644 index 00000000..1442c652 --- /dev/null +++ b/Verify/Infer/chc/okwhile_u256.spacer.out @@ -0,0 +1,5 @@ +sat +( + (define-fun Inv ((x!0 Int) (x!1 Int)) Bool + (not (<= (+ x!0 (* (- 1) x!1)) (- 1)))) +) diff --git a/Verify/Infer/flex-4.35-bump.diff b/Verify/Infer/flex-4.35-bump.diff new file mode 100644 index 00000000..ed2760eb --- /dev/null +++ b/Verify/Infer/flex-4.35-bump.diff @@ -0,0 +1,216 @@ +diff --git a/lake-manifest.json b/lake-manifest.json +index 30aaa280..e05df5e1 100644 +--- a/lake-manifest.json ++++ b/lake-manifest.json +@@ -1,7 +1,17 @@ +-{"version": "1.2.0", ++{"version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": +- [{"url": "https://github.com/LeanHorn/SMTLib-to-Lean.git", ++ [{"url": "https://github.com/leanprover-community/mathlib4", ++ "type": "git", ++ "subDir": null, ++ "scope": "", ++ "rev": "56a005855ea17e0b0958f73ec801ae140b0a1679", ++ "name": "mathlib", ++ "manifestFile": "lake-manifest.json", ++ "inputRev": "v4.35.0", ++ "inherited": false, ++ "configFile": "lakefile.lean"}, ++ {"url": "https://github.com/LeanHorn/SMTLib-to-Lean.git", + "type": "git", + "subDir": null, + "scope": "", +@@ -11,71 +21,51 @@ + "inputRev": "89667053aa420284b6794b6d6caabd551c1f7c79", + "inherited": false, + "configFile": "lakefile.toml"}, +- {"url": "https://github.com/ufmg-smite/lean-smt.git", ++ {"url": "https://github.com/abdoo8080/lean-cvc5.git", + "type": "git", + "subDir": null, + "scope": "", +- "rev": "79ef7b3d5e06608d031d75b6d015949b90016875", +- "name": "smt", ++ "rev": "d19a134c237ec7f0cb86c2027062eedeb577a9a9", ++ "name": "cvc5", + "manifestFile": "lake-manifest.json", +- "inputRev": "79ef7b3d5e06608d031d75b6d015949b90016875", ++ "inputRev": "d19a134c237ec7f0cb86c2027062eedeb577a9a9", + "inherited": false, + "configFile": "lakefile.lean"}, +- {"url": "https://github.com/leanprover-community/lean-auto.git", ++ {"url": "https://github.com/ufmg-smite/lean-smt.git", + "type": "git", + "subDir": null, + "scope": "", +- "rev": "92d628ba41801bd12c9d81f9be12fde97f0ad177", +- "name": "auto", ++ "rev": "cbec5bd226c79d80ce0c2d2ea28e1e6359c5f207", ++ "name": "smt", + "manifestFile": "lake-manifest.json", +- "inputRev": "92d628ba41801bd12c9d81f9be12fde97f0ad177", ++ "inputRev": "cbec5bd226c79d80ce0c2d2ea28e1e6359c5f207", + "inherited": false, + "configFile": "lakefile.lean"}, +- {"url": "https://github.com/leanprover-community/aesop", ++ {"url": "https://github.com/leanprover-community/lean-auto.git", + "type": "git", + "subDir": null, + "scope": "", +- "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", +- "name": "aesop", ++ "rev": "30f46ddb9a68d6878f5a1337eb2565ba4e70126b", ++ "name": "auto", + "manifestFile": "lake-manifest.json", +- "inputRev": "355695d523e41d0554926416cba2a2b3544fbbc9", ++ "inputRev": "v4.35.0", + "inherited": false, +- "configFile": "lakefile.toml"}, +- {"url": "https://github.com/leanprover-community/mathlib4.git", +- "type": "git", +- "subDir": null, +- "scope": "", +- "rev": "5ed2965256430c3649e86755f9576b54eca72435", +- "name": "mathlib", +- "manifestFile": "lake-manifest.json", +- "inputRev": "v4.34.0", +- "inherited": true, + "configFile": "lakefile.lean"}, +- {"url": "https://github.com/abdoo8080/lean-cvc5.git", ++ {"url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "", +- "rev": "41e47796d4d15712e6064b064ca5d251a1283955", +- "name": "cvc5", ++ "rev": "4a174c490d8707121c4a9290800489f105d85e07", ++ "name": "aesop", + "manifestFile": "lake-manifest.json", +- "inputRev": "41e47796d4d15712e6064b064ca5d251a1283955", ++ "inputRev": "v4.35.0", + "inherited": false, +- "configFile": "lakefile.lean"}, +- {"url": "https://github.com/leanprover-community/batteries", +- "type": "git", +- "subDir": null, +- "scope": "leanprover-community", +- "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", +- "name": "batteries", +- "manifestFile": "lake-manifest.json", +- "inputRev": "main", +- "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", +- "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", ++ "rev": "dfa4f38190d07c37e315953e08b90fe2d95b3c24", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", +@@ -85,7 +75,7 @@ + "type": "git", + "subDir": null, + "scope": "leanprover-community", +- "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", ++ "rev": "d6b4c7be5be75ec4917c873ac50c756dc1436372", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", +@@ -95,7 +85,7 @@ + "type": "git", + "subDir": null, + "scope": "leanprover-community", +- "rev": "e928b72544873815af278d38681b31c0293588e3", ++ "rev": "a41f0e9a4dea23188ea9cc1c41ac9f8bbafe0b93", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", +@@ -105,7 +95,7 @@ + "type": "git", + "subDir": null, + "scope": "leanprover-community", +- "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", ++ "rev": "df72b022e558978a1c50264cfc4d7fec86fa8e04", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", +@@ -115,20 +105,30 @@ + "type": "git", + "subDir": null, + "scope": "leanprover-community", +- "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", ++ "rev": "dce0ad79c486cb1fb504af04f953c3466b0c6db8", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml"}, ++ {"url": "https://github.com/leanprover-community/batteries", ++ "type": "git", ++ "subDir": null, ++ "scope": "leanprover-community", ++ "rev": "66e469188fe07963e5cf666c7d4433f45b8131c5", ++ "name": "batteries", ++ "manifestFile": "lake-manifest.json", ++ "inputRev": "main", ++ "inherited": true, ++ "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", +- "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", ++ "rev": "c24fe6078c630e89b489bffe59b3e20ac30d12c8", + "name": "Cli", + "manifestFile": "lake-manifest.json", +- "inputRev": "v4.34.0", ++ "inputRev": "v4.35.0", + "inherited": true, + "configFile": "lakefile.toml"}], + "name": "Flex", +diff --git a/lakefile.lean b/lakefile.lean +index 2a8d92ac..bccb3cf2 100644 +--- a/lakefile.lean ++++ b/lakefile.lean +@@ -10,21 +10,26 @@ package «Flex» where + -- mathlib as a transitive package dependency but its `Smt` import does not use it. + -- Keep these pins aligned with lean-smt's Lean v4.34.0 dependency set. + require aesop from git +- "https://github.com/leanprover-community/aesop" @ "355695d523e41d0554926416cba2a2b3544fbbc9" ++ "https://github.com/leanprover-community/aesop" @ "v4.35.0" + + require auto from git +- "https://github.com/leanprover-community/lean-auto.git" @ "92d628ba41801bd12c9d81f9be12fde97f0ad177" ++ "https://github.com/leanprover-community/lean-auto.git" @ "v4.35.0" + + require smt from git +- "https://github.com/ufmg-smite/lean-smt.git" @ "79ef7b3d5e06608d031d75b6d015949b90016875" ++ "https://github.com/ufmg-smite/lean-smt.git" @ "cbec5bd226c79d80ce0c2d2ea28e1e6359c5f207" + + -- CHC model import uses the same cvc5 parser as the SMT integration. + require cvc5 from git +- "https://github.com/abdoo8080/lean-cvc5.git" @ "41e47796d4d15712e6064b064ca5d251a1283955" ++ "https://github.com/abdoo8080/lean-cvc5.git" @ "d19a134c237ec7f0cb86c2027062eedeb577a9a9" + + require smt2lean from git + "https://github.com/LeanHorn/SMTLib-to-Lean.git" @ "89667053aa420284b6794b6d6caabd551c1f7c79" + ++-- flex-eval: pin mathlib to the v4.35.0 tag; declared last so Lake resolves it first ++-- (otherwise smt2lean's manifest drags in mathlib v4.33.0 and its deps). ++require mathlib from git ++ "https://github.com/leanprover-community/mathlib4" @ "v4.35.0" ++ + @[default_target] + lean_lib «Flex» where + +diff --git a/lean-toolchain b/lean-toolchain +index 12359f92..a6aff065 100644 +--- a/lean-toolchain ++++ b/lean-toolchain +@@ -1 +1 @@ +-leanprover/lean4:v4.34.0 ++leanprover/lean4:v4.35.0 diff --git a/Verify/Infer/gen_reconstruct.sh b/Verify/Infer/gen_reconstruct.sh new file mode 100755 index 00000000..86e0c072 --- /dev/null +++ b/Verify/Infer/gen_reconstruct.sh @@ -0,0 +1,82 @@ +#!/bin/sh +# Generates Reconstruct.lean: invariants pasted mechanically from z3 Spacer models; CHC clauses as stated in chc/*.smt2. +set -eu +cd "$(dirname "$0")" +W=115792089237316195423570985008687907853269984665640564039457584007913129639936 +out=Reconstruct.lean +{ +echo '/-! Kernel-checked initiation / preservation / use for the three loops.' +echo ' Each Inv_* below is generated by smt2lean_inv.py from the z3 Spacer model, unedited.' +echo ' Only Lean core is imported (no Flex, no Mathlib). -/' +echo 'namespace FlexEval' +echo +for v in counter_int counter_u256 okwhile_int okwhile_u256 drain_int drain_u256; do + python3 smt2lean_inv.py chc/$v.spacer.out Inv_$v; echo +done +cat < 0 → Inv_drain_int n (a - 1) (b + 1) := by + intros; simp only [Inv_drain_int] at *; omega +theorem drain_int_use : ∀ n a b : Int, Inv_drain_int n a b → ¬ (a > 0) → b = n := by + intros; simp only [Inv_drain_int] at *; omega + +theorem drain_u256_init : ∀ n : Int, 0 ≤ n → n < $W → Inv_drain_u256 n n 0 := by + intros; simp only [Inv_drain_u256]; omega +theorem drain_u256_pres : ∀ n a b : Int, Inv_drain_u256 n a b → a > 0 → + 0 ≤ a - 1 → a - 1 < $W → 0 ≤ b + 1 → b + 1 < $W → Inv_drain_u256 n (a - 1) (b + 1) := by + intros; simp only [Inv_drain_u256] at *; omega +theorem drain_u256_use : ∀ n a b : Int, Inv_drain_u256 n a b → ¬ (a > 0) → b = n := by + intros; simp only [Inv_drain_u256] at *; omega + +end FlexEval +EOF +for v in counter_int counter_u256 okwhile_int okwhile_u256 drain_int drain_u256; do + for k in init pres use; do echo "#print axioms FlexEval.${v}_$k"; done +done +} > $out +echo generated $out diff --git a/Verify/Infer/loopvc/README.md b/Verify/Infer/loopvc/README.md new file mode 100644 index 00000000..2da54cb1 --- /dev/null +++ b/Verify/Infer/loopvc/README.md @@ -0,0 +1,99 @@ +# Generated loop obligations: Counter.bump + +This directory turns solar-verify's loop-cut interface for one loop and a candidate invariant into +the exact obligations of initiation, preservation (every back edge), termination and exit, and +discharges them with the existing runner, [`Verify/Discharge/discharge.sh`](../../Discharge/discharge.sh). +Unlike [`../chc`](../chc) (Horn clauses written by hand), nothing here is written by hand except +the mutated candidate of the negative test. + +The loop is `Counter.bump` of [`Certified/verify_counter/verify_counter.sol`](../../../Certified/verify_counter/verify_counter.sol): +`for (uint256 i = 0; i < n; i++) count++;` after `require(count + n <= limit)`, annotated with +`i <= n`, `count == old(count) + i` and `decreases n - i`. + +## Input + +- `solar/`: the loop-cut interface solar-verify writes (`--emit-loopvc`, format 1, solar's + `docs/loopvc-interface.md`), at the solar commit in `solar/REV`, run from this repository's root: + + solar-verify --no-infer --only Counter.bump --emit-loopvc DIR Certified/verify_counter/verify_counter.sol + + `Counter/bump.loopvc.json` (cut, parameters, edges, templates, revert paths, the run's + candidate), `Counter/bump.horn.smt2` (the Horn view), `Counter/bump.script0.smt2` (the run's + script), `Counter/bump.lean` (the run's obligations, `--emit-lean`), `Counter/bump_loopvc.lean` + (the templates, with the run's candidate abstracted, and `tK_exact`: their instances at the run's + candidate are the run's obligations, by `rfl`) and `LoopVc.lean` (`Template.instances`). +- `spacer/Counter.bump.spacer.out`: z3 4.13.4's Spacer answer for the Horn view, unedited. +- `candidates/Counter.bump.mutant.json`: the annotated candidate with `count == old(count) + i` + changed to `+ i + 1`. + +## Obligations + +`smt2lean_inv.py loopvc --export solar --unit Counter.bump [--candidate F | --spacer F]` writes the +candidate's obligations as a `solar-verify-lean` version-2 export (`export//`): + +- The candidate (the interface's own, a candidate file in its shape, or Spacer's model of the cut + predicate with the interface's ranking function) is translated into the embedding, numbered as + the run's script declares its symbols; a term naming anything but the cut's parameters is refused. +- Lean computes the obligations: `Template.instances` of every template at the candidate, printed as + terms, one `obK` per instance. Nothing re-implements the instantiation. +- `bridge/.../*_bridge.lean` proves, by `rfl`, that each template's instances at the candidate are + exactly those `obK` (and, for the annotated candidate, that it is the run's candidate, so its + obligations are the run's own through the interface's `tK_exact`). The generator checks it and + its axioms before it writes the manifest. + +| Template | Edge | Obligations (manifest `kind`) | +| --- | --- | --- | +| `invariant` | entry | one per conjunct (`initiation`) | +| `invariant` | back | one per conjunct, each assuming the whole invariant at the head (`preservation`) | +| `rank` | back | `0 <= r` and `r` decreases, under the invariant (`termination`) | +| `path` | exit | postcondition, contract invariant (`exit`) | + +Revert paths owe nothing without `succeeds-if` (the interface's contract): the manifest lists them, +with their conditions, and they have no row. Out of gas is not in solar-verify's encoding. + +`discharge.sh` applies its own checks unchanged: semantics hashes, required manifest, locked +inputs, per-row axioms, vacuity. Nothing is proved by a solver's answer: `vc_smt` rebuilds cvc5's +proof in the kernel. A failed, unknown or timed-out row is not proved. + +`smt2lean_inv.py cti DIR`, after a discharge, asks z3 for a model of each open obligation's query +(the template's SMT-LIB with the candidate put back, `LoopVc/.../*.obK.smt2`) and writes +`discharge/cti.json` (candidate, template, edge, source location, the cut's parameters before and +after the edge) and `discharge/residual/.lean`, the exact goal left open. A model is a +counterexample to induction: it rejects the candidate on that edge, and says nothing about whether +the state is reachable. + +## Results + +`check.sh` is the acceptance check; [`results/`](results) holds its run (z3 4.13.4, cvc5 through +lean-smt `6b26285`, Lean 4.35.0): + +| Candidate | Obligations | Proved | Vacuous | Axioms | +| --- | --- | --- | --- | --- | +| annotated (`i <= n`, `count == old(count) + i`, `decreases n - i`) | 7 | 7 (`vc_smt`) | none | propext, Classical.choice, Quot.sound | +| Spacer's, with the annotated ranking function | 9 | 9 (`vc_smt`) | none | propext, Classical.choice, Quot.sound | +| mutant (`count == old(count) + i + 1`) | 7 | 4 | none | rejected: 3 rows with a counterexample | + +The mutant's counterexamples: on the entry edge (`t0`), `count = i = n = old(count) = 0` after +it, where the mutant needs `count = 1`; on the exit edge, the postcondition (`t3`) and the +contract invariant (`t4`) from the head state `count = 1, i = n = old(count) = 0`. + + bash Verify/Infer/loopvc/check.sh [WORKDIR] + +needs the library build of `Verify/Discharge/Reconstruct` (`Verify/Discharge/README.md`) and z3 on +`PATH`. With `SOLAR_VERIFY` set to a solar-verify built at `solar/REV`, it first checks that +solar-verify writes the committed interface files. It then regenerates both exports and compares +them byte for byte with `export/` (the bridge checks in that step), discharges each against its lock +(`export/.sha256`), requires every row proved, non-vacuous and with the three axioms, and +requires the mutant to fail with a counterexample on the entry edge. CI runs it (`.github/workflows/loopvc.yml`). + +## Not covered + +- Not composed by `Verify/VC/EndToEnd`: the obligations are not yet part of a script that + `checkScript` binds to the function's erased tree (`Binds`), so no bytecode theorem uses them. +- Out of gas: solar-verify has no gas model. Revert paths carry no obligation (no `succeeds-if`). +- The interface's limits (format 1): one loop per function, no call in the loop, Int and Bool cut + parameters, inference off. +- CI does not rebuild solar to recheck the interface files (`SOLAR_VERIFY` unset there); the + committed files' hashes are pinned in the locks. +- No bounded replay of a counterexample, and no strengthening from it. `vc_valid` proves none of the + rows within its 30 s; `vc_smt` proves them all. diff --git a/Verify/Infer/loopvc/candidates/Counter.bump.mutant.json b/Verify/Infer/loopvc/candidates/Counter.bump.mutant.json new file mode 100644 index 00000000..f6446905 --- /dev/null +++ b/Verify/Infer/loopvc/candidates/Counter.bump.mutant.json @@ -0,0 +1,35 @@ +{ + "id": "mutant", + "conjuncts": [ + { + "term": "(<= |i@28| |n@21|)", + "text": "i <= n", + "origin": "annotation", + "site": { + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23, + "column": 14 + } + }, + { + "term": "(= |count@27| (+ |count@17| |i@28| 1))", + "text": "count == old(count) + i + 1 (mutated from count == old(count) + i)", + "origin": "mutant", + "site": { + "file": "Certified/verify_counter/verify_counter.sol", + "line": 24, + "column": 14 + } + } + ], + "rank": { + "term": "(- |n@21| |i@28|)", + "text": "n - i", + "origin": "annotation", + "site": { + "file": "Certified/verify_counter/verify_counter.sol", + "line": 25, + "column": 14 + } + } +} diff --git a/Verify/Infer/loopvc/check.sh b/Verify/Infer/loopvc/check.sh new file mode 100755 index 00000000..26c2ca75 --- /dev/null +++ b/Verify/Infer/loopvc/check.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# Acceptance check of the generated loop obligations of Counter.bump (README.md): +# +# 0. with SOLAR_VERIFY set (a solar-verify built at solar/REV), solar-verify --emit-loopvc +# writes exactly the committed interface files in solar/; +# 1. smt2lean_inv.py loopvc regenerates, from that interface, exactly the pinned export of each +# candidate (export//, byte for byte), and its bridge module checks: each +# template's Template.instances at the candidate equals the generated obligations (rfl); +# 2. Verify/Discharge/discharge.sh proves every required obligation of each, against the +# pinned inputs (export/.sha256), with only propext, Classical.choice and +# Quot.sound, and finds every row's hypotheses satisfiable (vacuous = no); +# 3. a wrong invariant (candidates/Counter.bump.mutant.json) is rejected, and smt2lean_inv.py +# cti reports a counterexample to induction for it on the entry edge. +# +# bash Verify/Infer/loopvc/check.sh [WORKDIR] +# +# Needs the library build of Verify/Discharge/Reconstruct (Verify/Discharge/README.md) and z3 on +# PATH (or SOLAR_VERIFY_Z3) for step 3. +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +root=$(cd "$here/../../.." && pwd) +work=${1:-$(mktemp -d)} +mkdir -p "$work" +fail() { echo "loopvc check: FAIL: $*" >&2; exit 1; } + +if [[ -n ${SOLAR_VERIFY:-} ]]; then + rm -rf "$work/solar" + (cd "$root" && "$SOLAR_VERIFY" --no-infer --only Counter.bump --emit-loopvc "$work/solar" \ + Certified/verify_counter/verify_counter.sol >&2) + for f in LoopVc.lean Counter/bump.lean Counter/bump.loopvc.json Counter/bump.horn.smt2 \ + Counter/bump.script0.smt2 Counter/bump_loopvc.lean; do + cmp "$here/solar/$f" "$work/solar/$f" || fail "solar-verify does not write the committed $f" + done + echo "loopvc check: the interface files are solar-verify's" >&2 +fi + +gen=(python3 "$root/Verify/Infer/smt2lean_inv.py" loopvc --export "$here/solar" --unit Counter.bump --root "$root") +for c in annotated spacer; do + args=() + [[ $c == spacer ]] && args=(--spacer "$here/spacer/Counter.bump.spacer.out") + rm -rf "$work/$c" + "${gen[@]}" --out "$work/$c" "${args[@]}" + diff -r "$here/export/$c" "$work/$c" >&2 || fail "the generated $c export is not the pinned one" + DISCHARGE_LOCK="$here/export/$c.sha256" DISCHARGE_SOURCE_ROOT="$root" \ + "$root/Verify/Discharge/discharge.sh" "$work/$c" 300 || fail "discharge of the $c candidate failed" + awk -F'\t' 'NR > 1 && ($4 != "proved" || $6 != "no") { print; bad = 1 } END { exit bad }' \ + "$work/$c/discharge/summary.tsv" >&2 || fail "$c: a row is not proved, or its hypotheses are not shown satisfiable" + awk -F'\t' 'NR > 1 && $5 == "proved" && $8 != "propext Classical.choice Quot.sound" { print; bad = 1 } END { exit bad }' \ + "$work/$c/discharge/results.tsv" >&2 || fail "$c: a proof uses another axiom" + ! grep -rnE '\b(sorry|admit|native_decide)\b' "$work/$c" --include='*.lean' >&2 || fail "$c: an unchecked construct" + echo "loopvc check: $c: $(($(wc -l <"$work/$c/discharge/summary.tsv") - 1)) obligations proved, none vacuous" >&2 +done + +rm -rf "$work/mutant" +"${gen[@]}" --out "$work/mutant" --candidate "$here/candidates/Counter.bump.mutant.json" +if DISCHARGE_SOURCE_ROOT="$root" "$root/Verify/Discharge/discharge.sh" "$work/mutant" 300; then + fail "the mutated invariant was accepted" +fi +python3 "$root/Verify/Infer/smt2lean_inv.py" cti "$work/mutant" +jq -e '[.[] | select(.verdict == "cti" and .edge == "entry" and .kind == "initiation" + and (.spec.text | startswith("count == old(count) + i + 1")) and .post.count != null)] | length == 1' \ + "$work/mutant/discharge/cti.json" >/dev/null || fail "no counterexample to induction for the mutant on the entry edge" +jq -e '[.[] | select(.verdict != "cti")] | length == 0' "$work/mutant/discharge/cti.json" >/dev/null \ + || fail "an open obligation of the mutant has no counterexample" +echo "loopvc check: the mutant is rejected: $(jq -r 'map(.id) | join(", ")' "$work/mutant/discharge/cti.json")" >&2 +echo "loopvc check: ok" >&2 diff --git a/Verify/Infer/loopvc/export/annotated.sha256 b/Verify/Infer/loopvc/export/annotated.sha256 new file mode 100644 index 00000000..105eca71 --- /dev/null +++ b/Verify/Infer/loopvc/export/annotated.sha256 @@ -0,0 +1,9 @@ +79f7f351bbf8e703b21a64769946882ed4d3a04096df74979043b6b4add0c71a manifest.json +c5ef202ba64b79f1bda1e1fbbd91820ccd71900fbcae5cbbd5ba2952d4b4b649 LoopVc/Counter/bump_annotated.lean +524779d300a8349448949e7e9da8a2552a955d413eb443ee6e1d6348dfb442f8 Verify/Infer/loopvc/solar/Counter/bump.loopvc.json +88f69aaad5735250f8e4c8f3fd2d6c1dd94603c9cec4c92ff797ef62d8c3fe54 Verify/Infer/loopvc/solar/Counter/bump.horn.smt2 +8b5f650e16a217b5b843f8ca623a22f6c0dc6c0afc44e07251fac2559d4b2e82 Verify/Infer/loopvc/solar/LoopVc.lean +e954bfd845f141aa6c87166c42f430eb1b188e0e1615629688fed955278fcf94 Verify/Infer/loopvc/solar/Counter/bump.lean +ba357e2ed64efdd84a9d28afc5faf54497a9353b63429c7d0b655ace57d5d221 Verify/Infer/loopvc/solar/Counter/bump_loopvc.lean +b596fcfdf4d8d9d5ad138db6403d355309821c6629be9de9fb72636b1b9f0236 Verify/Infer/loopvc/solar/Counter/bump.script0.smt2 +f1c87a334b8db31fc8f80541febeaf8617318d20b685634f44e26c74146ad326 Certified/verify_counter/verify_counter.sol diff --git a/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.lean b/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.lean new file mode 100644 index 00000000..3b7316cd --- /dev/null +++ b/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.lean @@ -0,0 +1,63 @@ +-- Generated by Verify/Infer/smt2lean_inv.py loopvc; do not edit. +-- The instances of Counter.bump's loop-cut templates (Verify/Infer/loopvc/solar/Counter/bump.loopvc.json) at candidate annotated. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.LoopVc.Counter.bump_annotated +open SolarVerify.Smt SolarVerify.Vc + +/-- The function's script with the candidate at the loop head. -/ +def script0 : Script := + { decls := [{ name := "|this@1|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|msg.sender@2|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|msg.value@3|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.timestamp@4|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.number@5|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.chainid@6|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|tx.origin@7|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|tx.gasprice@8|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|msg.sig@9|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|msg.data@10|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.basefee@11|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.blobbasefee@12|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.coinbase@13|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.prevrandao@14|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.difficulty@15|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.gaslimit@16|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|count@17|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|limit@18|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|__balance@19|", args := [], ret := SolarVerify.Smt.Srt.array (SolarVerify.Smt.Srt.int) (SolarVerify.Smt.Srt.int) }, { name := "|__code_epoch@20|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|n@21|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|g@22|", args := [], ret := SolarVerify.Smt.Srt.bool }, { name := "|g@23|", args := [], ret := SolarVerify.Smt.Srt.bool }, { name := "|arith@24|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|g@25|", args := [], ret := SolarVerify.Smt.Srt.bool }, { name := "|g@26|", args := [], ret := SolarVerify.Smt.Srt.bool }, { name := "|count@27|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|i@28|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|g@29|", args := [], ret := SolarVerify.Smt.Srt.bool }, { name := "|g@30|", args := [], ret := SolarVerify.Smt.Srt.bool }, { name := "|arith@31|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|g@32|", args := [], ret := SolarVerify.Smt.Srt.bool }, { name := "|arith@33|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|g@34|", args := [], ret := SolarVerify.Smt.Srt.bool }, { name := "|g@35|", args := [], ret := SolarVerify.Smt.Srt.bool }], asserts := [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 0 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 0 [], SolarVerify.Smt.Term.int 1461501637330902918203684832716283019655932542975]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.not) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 0 [], SolarVerify.Smt.Term.int 0]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 1 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 1 [], SolarVerify.Smt.Term.int 1461501637330902918203684832716283019655932542975]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.not) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 1 [], SolarVerify.Smt.Term.int 0]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 2 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 2 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 3 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 3 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 4 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 4 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 5 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 5 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 6 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 6 [], SolarVerify.Smt.Term.int 1461501637330902918203684832716283019655932542975]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 7 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 7 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 8 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 8 [], SolarVerify.Smt.Term.int 4294967295]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 10 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 10 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 11 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 11 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 12 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 12 [], SolarVerify.Smt.Term.int 1461501637330902918203684832716283019655932542975]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 13 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 13 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 14 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 14 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 15 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 15 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 16 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 17 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 17 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 19 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 19 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 20 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 20 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 21 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.bool true, SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.fn 17 []]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 22 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.fn 21 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 2 [], SolarVerify.Smt.Term.int 0]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 23 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.fn 20 []]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 24 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.fn 22 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 23 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 23 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 25 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.fn 24 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 23 [], SolarVerify.Smt.Term.fn 17 []]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 26 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 26 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 27 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 27 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 28 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.fn 25 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 27 [], SolarVerify.Smt.Term.fn 20 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 26 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.fn 27 []]]]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 29 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.fn 28 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.lt) [SolarVerify.Smt.Term.fn 27 [], SolarVerify.Smt.Term.fn 20 []]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 30 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 26 [], SolarVerify.Smt.Term.int 1]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 31 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.fn 29 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 30 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 30 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 32 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 27 [], SolarVerify.Smt.Term.int 1]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 33 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.fn 31 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 32 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 32 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 34 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.fn 28 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.not) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.lt) [SolarVerify.Smt.Term.fn 27 [], SolarVerify.Smt.Term.fn 20 []]]]]] } + +/-- Counter.bump@L0#t0.c0: initiation of edge entry (template t0, invariant), conjunct "i <= n", candidate annotated. -/ +def ob0 : Obligation where + script := script0 + upto := 26 + guard := SolarVerify.Smt.Term.fn 25 [] + goal := SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 20 []] + +/-- Counter.bump@L0#t0.c1: initiation of edge entry (template t0, invariant), conjunct "count == old(count) + i", candidate annotated. -/ +def ob1 : Obligation where + script := script0 + upto := 26 + guard := SolarVerify.Smt.Term.fn 25 [] + goal := SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.int 0]] + +/-- Counter.bump@L0#t1.c0: preservation of edge back (template t1, invariant), conjunct "i <= n", candidate annotated. -/ +def ob2 : Obligation where + script := script0 + upto := 34 + guard := SolarVerify.Smt.Term.fn 33 [] + goal := SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 32 [], SolarVerify.Smt.Term.fn 20 []] + +/-- Counter.bump@L0#t1.c1: preservation of edge back (template t1, invariant), conjunct "count == old(count) + i", candidate annotated. -/ +def ob3 : Obligation where + script := script0 + upto := 34 + guard := SolarVerify.Smt.Term.fn 33 [] + goal := SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 30 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.fn 32 []]] + +/-- Counter.bump@L0#t2: termination of edge back (template t2, rank), candidate annotated. -/ +def ob4 : Obligation where + script := script0 + upto := 34 + guard := SolarVerify.Smt.Term.fn 33 [] + goal := SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.fn 20 [], SolarVerify.Smt.Term.fn 27 []]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.lt) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.fn 20 [], SolarVerify.Smt.Term.fn 32 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.fn 20 [], SolarVerify.Smt.Term.fn 27 []]]] + +/-- Counter.bump@L0#t3: exit of edge exit (template t3, path), candidate annotated. -/ +def ob5 : Obligation where + script := script0 + upto := 35 + guard := SolarVerify.Smt.Term.fn 34 [] + goal := SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 26 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.fn 20 []]] + +/-- Counter.bump@L0#t4: exit of edge exit (template t4, path), candidate annotated. -/ +def ob6 : Obligation where + script := script0 + upto := 35 + guard := SolarVerify.Smt.Term.fn 34 [] + goal := SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 26 [], SolarVerify.Smt.Term.fn 17 []] + +end SolarVerifyVc.LoopVc.Counter.bump_annotated diff --git a/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob0.smt2 b/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob0.smt2 new file mode 100644 index 00000000..3cd3d1b1 --- /dev/null +++ b/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob0.smt2 @@ -0,0 +1,55 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(assert |g@26|) +(assert (not (<= 0 |n@21|))) +(check-sat) diff --git a/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob1.smt2 b/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob1.smt2 new file mode 100644 index 00000000..161b1e41 --- /dev/null +++ b/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob1.smt2 @@ -0,0 +1,55 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(assert |g@26|) +(assert (not (= |count@17| (+ |count@17| 0)))) +(check-sat) diff --git a/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob2.smt2 b/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob2.smt2 new file mode 100644 index 00000000..5e2d0eec --- /dev/null +++ b/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob2.smt2 @@ -0,0 +1,71 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(declare-const |count@27| Int) +(assert (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |i@28| Int) +(assert (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@29| Bool) +(assert (= |g@29| (and |g@26| (and (<= |i@28| |n@21|) (= |count@27| (+ |count@17| |i@28|)))))) +(declare-const |g@30| Bool) +(assert (= |g@30| (and |g@29| (< |i@28| |n@21|)))) +(declare-const |arith@31| Int) +(assert (= |arith@31| (+ |count@27| 1))) +(declare-const |g@32| Bool) +(assert (= |g@32| (and |g@30| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |arith@33| Int) +(assert (= |arith@33| (+ |i@28| 1))) +(declare-const |g@34| Bool) +(assert (= |g@34| (and |g@32| (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(assert |g@34|) +(assert (not (<= |arith@33| |n@21|))) +(check-sat) diff --git a/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob3.smt2 b/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob3.smt2 new file mode 100644 index 00000000..a381fcdf --- /dev/null +++ b/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob3.smt2 @@ -0,0 +1,71 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(declare-const |count@27| Int) +(assert (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |i@28| Int) +(assert (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@29| Bool) +(assert (= |g@29| (and |g@26| (and (<= |i@28| |n@21|) (= |count@27| (+ |count@17| |i@28|)))))) +(declare-const |g@30| Bool) +(assert (= |g@30| (and |g@29| (< |i@28| |n@21|)))) +(declare-const |arith@31| Int) +(assert (= |arith@31| (+ |count@27| 1))) +(declare-const |g@32| Bool) +(assert (= |g@32| (and |g@30| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |arith@33| Int) +(assert (= |arith@33| (+ |i@28| 1))) +(declare-const |g@34| Bool) +(assert (= |g@34| (and |g@32| (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(assert |g@34|) +(assert (not (= |arith@31| (+ |count@17| |arith@33|)))) +(check-sat) diff --git a/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob4.smt2 b/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob4.smt2 new file mode 100644 index 00000000..15cf91f4 --- /dev/null +++ b/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob4.smt2 @@ -0,0 +1,71 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(declare-const |count@27| Int) +(assert (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |i@28| Int) +(assert (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@29| Bool) +(assert (= |g@29| (and |g@26| (and (<= |i@28| |n@21|) (= |count@27| (+ |count@17| |i@28|)))))) +(declare-const |g@30| Bool) +(assert (= |g@30| (and |g@29| (< |i@28| |n@21|)))) +(declare-const |arith@31| Int) +(assert (= |arith@31| (+ |count@27| 1))) +(declare-const |g@32| Bool) +(assert (= |g@32| (and |g@30| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |arith@33| Int) +(assert (= |arith@33| (+ |i@28| 1))) +(declare-const |g@34| Bool) +(assert (= |g@34| (and |g@32| (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(assert |g@34|) +(assert (not (and (<= 0 (- |n@21| |i@28|)) (< (- |n@21| |arith@33|) (- |n@21| |i@28|))))) +(check-sat) diff --git a/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob5.smt2 b/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob5.smt2 new file mode 100644 index 00000000..32ddf63f --- /dev/null +++ b/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob5.smt2 @@ -0,0 +1,73 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(declare-const |count@27| Int) +(assert (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |i@28| Int) +(assert (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@29| Bool) +(assert (= |g@29| (and |g@26| (and (<= |i@28| |n@21|) (= |count@27| (+ |count@17| |i@28|)))))) +(declare-const |g@30| Bool) +(assert (= |g@30| (and |g@29| (< |i@28| |n@21|)))) +(declare-const |arith@31| Int) +(assert (= |arith@31| (+ |count@27| 1))) +(declare-const |g@32| Bool) +(assert (= |g@32| (and |g@30| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |arith@33| Int) +(assert (= |arith@33| (+ |i@28| 1))) +(declare-const |g@34| Bool) +(assert (= |g@34| (and |g@32| (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@35| Bool) +(assert (= |g@35| (and |g@29| (not (< |i@28| |n@21|))))) +(assert |g@35|) +(assert (not (= |count@27| (+ |count@17| |n@21|)))) +(check-sat) diff --git a/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob6.smt2 b/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob6.smt2 new file mode 100644 index 00000000..a8bee1f5 --- /dev/null +++ b/Verify/Infer/loopvc/export/annotated/LoopVc/Counter/bump_annotated.ob6.smt2 @@ -0,0 +1,73 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(declare-const |count@27| Int) +(assert (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |i@28| Int) +(assert (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@29| Bool) +(assert (= |g@29| (and |g@26| (and (<= |i@28| |n@21|) (= |count@27| (+ |count@17| |i@28|)))))) +(declare-const |g@30| Bool) +(assert (= |g@30| (and |g@29| (< |i@28| |n@21|)))) +(declare-const |arith@31| Int) +(assert (= |arith@31| (+ |count@27| 1))) +(declare-const |g@32| Bool) +(assert (= |g@32| (and |g@30| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |arith@33| Int) +(assert (= |arith@33| (+ |i@28| 1))) +(declare-const |g@34| Bool) +(assert (= |g@34| (and |g@32| (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@35| Bool) +(assert (= |g@35| (and |g@29| (not (< |i@28| |n@21|))))) +(assert |g@35|) +(assert (not (<= |count@27| |limit@18|))) +(check-sat) diff --git a/Verify/Infer/loopvc/export/annotated/bridge/LoopVc/Counter/bump_annotated_bridge.lean b/Verify/Infer/loopvc/export/annotated/bridge/LoopVc/Counter/bump_annotated_bridge.lean new file mode 100644 index 00000000..d6732977 --- /dev/null +++ b/Verify/Infer/loopvc/export/annotated/bridge/LoopVc/Counter/bump_annotated_bridge.lean @@ -0,0 +1,31 @@ +import Lean +import Counter.bump_loopvc +import LoopVc.Counter.bump_annotated + +open SolarVerify.Smt SolarVerify.Vc SolarVerify.LoopVc + +namespace SolarVerifyVc.LoopVc.Counter.bump_annotated.Bridge + +/-- The candidate, in the interface's terms. -/ +def cand : Cand := { conj := [.app .le [.fn 27 [], .fn 20 []], .app .eq [.fn 26 [], .app .add [.fn 16 [], .fn 27 []]]], rank := some (.app .sub [.fn 20 [], .fn 27 []]) } + +/-- It is the candidate of the run. -/ +theorem cand_eq : cand = SolarVerifyLoopVc.Counter.bump.cand := rfl + +theorem t0_exact : SolarVerifyLoopVc.Counter.bump.t0.instances SolarVerifyLoopVc.Counter.bump.cut cand = [SolarVerifyVc.LoopVc.Counter.bump_annotated.ob0, SolarVerifyVc.LoopVc.Counter.bump_annotated.ob1] := rfl + +theorem t1_exact : SolarVerifyLoopVc.Counter.bump.t1.instances SolarVerifyLoopVc.Counter.bump.cut cand = [SolarVerifyVc.LoopVc.Counter.bump_annotated.ob2, SolarVerifyVc.LoopVc.Counter.bump_annotated.ob3] := rfl + +theorem t2_exact : SolarVerifyLoopVc.Counter.bump.t2.instances SolarVerifyLoopVc.Counter.bump.cut cand = [SolarVerifyVc.LoopVc.Counter.bump_annotated.ob4] := rfl + +theorem t3_exact : SolarVerifyLoopVc.Counter.bump.t3.instances SolarVerifyLoopVc.Counter.bump.cut cand = [SolarVerifyVc.LoopVc.Counter.bump_annotated.ob5] := rfl + +theorem t4_exact : SolarVerifyLoopVc.Counter.bump.t4.instances SolarVerifyLoopVc.Counter.bump.cut cand = [SolarVerifyVc.LoopVc.Counter.bump_annotated.ob6] := rfl + +end SolarVerifyVc.LoopVc.Counter.bump_annotated.Bridge + +open Lean Elab Command in +#eval show CommandElabM Unit from do + for n in [`SolarVerifyVc.LoopVc.Counter.bump_annotated.Bridge.t0_exact, `SolarVerifyVc.LoopVc.Counter.bump_annotated.Bridge.t1_exact, `SolarVerifyVc.LoopVc.Counter.bump_annotated.Bridge.t2_exact, `SolarVerifyVc.LoopVc.Counter.bump_annotated.Bridge.t3_exact, `SolarVerifyVc.LoopVc.Counter.bump_annotated.Bridge.t4_exact] do + let axs ← Lean.collectAxioms n + IO.println s!"AXIOMS {n}: {String.intercalate " " (axs.toList.map toString)}" diff --git a/Verify/Infer/loopvc/export/annotated/manifest.json b/Verify/Infer/loopvc/export/annotated/manifest.json new file mode 100644 index 00000000..e14e7ff4 --- /dev/null +++ b/Verify/Infer/loopvc/export/annotated/manifest.json @@ -0,0 +1,393 @@ +{ + "format": "solar-verify-lean", + "generator": { + "interface": { + "format": "solar-verify-loopvc", + "formulas_sha256": "f8b5887986ea82259e3bc90c12abea85773dc969a7d8788af39535ec590e2de2", + "version": 1 + }, + "name": "Verify/Infer/smt2lean_inv.py loopvc" + }, + "lean": { + "smt_sha256": "2c92f3bcd927369da89250662bd5a6174d3c06d0c3c38f5021509fe8810036e3", + "toolchain": "leanprover/lean4:v4.35.0", + "vc_sha256": "648d461056fe1649754b1ec259c2d1c48e8db8a4c11e5af281e73796399bc96a" + }, + "sources": [ + { + "path": "Verify/Infer/loopvc/solar/Counter/bump.loopvc.json", + "sha256": "524779d300a8349448949e7e9da8a2552a955d413eb443ee6e1d6348dfb442f8" + }, + { + "path": "Verify/Infer/loopvc/solar/Counter/bump.horn.smt2", + "sha256": "88f69aaad5735250f8e4c8f3fd2d6c1dd94603c9cec4c92ff797ef62d8c3fe54" + }, + { + "path": "Verify/Infer/loopvc/solar/LoopVc.lean", + "sha256": "8b5f650e16a217b5b843f8ca623a22f6c0dc6c0afc44e07251fac2559d4b2e82" + }, + { + "path": "Verify/Infer/loopvc/solar/Counter/bump.lean", + "sha256": "e954bfd845f141aa6c87166c42f430eb1b188e0e1615629688fed955278fcf94" + }, + { + "path": "Verify/Infer/loopvc/solar/Counter/bump_loopvc.lean", + "sha256": "ba357e2ed64efdd84a9d28afc5faf54497a9353b63429c7d0b655ace57d5d221" + }, + { + "path": "Verify/Infer/loopvc/solar/Counter/bump.script0.smt2", + "sha256": "b596fcfdf4d8d9d5ad138db6403d355309821c6629be9de9fb72636b1b9f0236" + }, + { + "path": "Certified/verify_counter/verify_counter.sol", + "sha256": "f1c87a334b8db31fc8f80541febeaf8617318d20b685634f44e26c74146ad326" + } + ], + "units": [ + { + "bridge": "bridge/LoopVc/Counter/bump_annotated_bridge.lean", + "candidate": { + "conjuncts": [ + { + "origin": "annotation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23 + }, + "term": "(<= |i@28| |n@21|)", + "text": "i <= n" + }, + { + "origin": "annotation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 24 + }, + "term": "(= |count@27| (+ |count@17| |i@28|))", + "text": "count == old(count) + i" + } + ], + "head_assumption": "(assert (= |g@29| (and |g@26| (and (<= |i@28| |n@21|) (= |count@27| (+ |count@17| |i@28|))))))", + "id": "annotated", + "rank": { + "origin": "annotation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 25 + }, + "term": "(- |n@21| |i@28|)", + "text": "n - i" + } + }, + "module": "LoopVc/Counter/bump_annotated.lean", + "name": "Counter.bump L0 [annotated]", + "namespace": "SolarVerifyVc.LoopVc.Counter.bump_annotated", + "obligations": [ + { + "answer": "not-run", + "candidate": "annotated", + "cutpoint": "L0", + "edge": "entry", + "id": "Counter.bump@L0#t0.c0", + "kind": "initiation", + "lean": "SolarVerifyVc.LoopVc.Counter.bump_annotated.ob0", + "post": { + "count": "|count@17|", + "i": "0", + "n": "|n@21|", + "old(count)": "|count@17|" + }, + "pre": {}, + "required": true, + "role": "obligation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23 + }, + "smt": "LoopVc/Counter/bump_annotated.ob0.smt2", + "smt_sha256": "3c4658c39034e79e52d9ab5c9c910953d40fec7d6d515bddf8f60e3c6ddb4b1f", + "spec": { + "span": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23 + }, + "text": "i <= n" + }, + "template": "t0", + "template_role": "invariant" + }, + { + "answer": "not-run", + "candidate": "annotated", + "cutpoint": "L0", + "edge": "entry", + "id": "Counter.bump@L0#t0.c1", + "kind": "initiation", + "lean": "SolarVerifyVc.LoopVc.Counter.bump_annotated.ob1", + "post": { + "count": "|count@17|", + "i": "0", + "n": "|n@21|", + "old(count)": "|count@17|" + }, + "pre": {}, + "required": true, + "role": "obligation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 24 + }, + "smt": "LoopVc/Counter/bump_annotated.ob1.smt2", + "smt_sha256": "f1ad733f8bda39adab5ac523b1676ed59540783912a7a15d6bd2a4f3e6dc7394", + "spec": { + "span": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 24 + }, + "text": "count == old(count) + i" + }, + "template": "t0", + "template_role": "invariant" + }, + { + "answer": "not-run", + "candidate": "annotated", + "cutpoint": "L0", + "edge": "back", + "id": "Counter.bump@L0#t1.c0", + "kind": "preservation", + "lean": "SolarVerifyVc.LoopVc.Counter.bump_annotated.ob2", + "post": { + "count": "|arith@31|", + "i": "|arith@33|", + "n": "|n@21|", + "old(count)": "|count@17|" + }, + "pre": { + "L0": { + "count": "|count@27|", + "i": "|i@28|", + "n": "|n@21|", + "old(count)": "|count@17|" + } + }, + "required": true, + "role": "obligation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23 + }, + "smt": "LoopVc/Counter/bump_annotated.ob2.smt2", + "smt_sha256": "8e9a52da00bfe779eb3268295c3c9ad31b6882ce4449b1b3fb288f9d145ea485", + "spec": { + "span": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23 + }, + "text": "i <= n" + }, + "template": "t1", + "template_role": "invariant" + }, + { + "answer": "not-run", + "candidate": "annotated", + "cutpoint": "L0", + "edge": "back", + "id": "Counter.bump@L0#t1.c1", + "kind": "preservation", + "lean": "SolarVerifyVc.LoopVc.Counter.bump_annotated.ob3", + "post": { + "count": "|arith@31|", + "i": "|arith@33|", + "n": "|n@21|", + "old(count)": "|count@17|" + }, + "pre": { + "L0": { + "count": "|count@27|", + "i": "|i@28|", + "n": "|n@21|", + "old(count)": "|count@17|" + } + }, + "required": true, + "role": "obligation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 24 + }, + "smt": "LoopVc/Counter/bump_annotated.ob3.smt2", + "smt_sha256": "42d79032109a0be83e48f557762682cd48c24a3f277c07ea028506b83b9c8d66", + "spec": { + "span": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 24 + }, + "text": "count == old(count) + i" + }, + "template": "t1", + "template_role": "invariant" + }, + { + "answer": "not-run", + "candidate": "annotated", + "cutpoint": "L0", + "edge": "back", + "id": "Counter.bump@L0#t2", + "kind": "termination", + "lean": "SolarVerifyVc.LoopVc.Counter.bump_annotated.ob4", + "post": {}, + "pre": { + "L0": { + "count": "|count@27|", + "i": "|i@28|", + "n": "|n@21|", + "old(count)": "|count@17|" + } + }, + "required": true, + "role": "obligation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 25 + }, + "smt": "LoopVc/Counter/bump_annotated.ob4.smt2", + "smt_sha256": "bf922edda138cff9c0e93ff23a0fa9548c1fb15933877aa14aed7ee86a841a22", + "spec": { + "span": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 25 + }, + "text": "n - i" + }, + "template": "t2", + "template_role": "rank" + }, + { + "answer": "not-run", + "candidate": "annotated", + "cutpoint": "L0", + "edge": "exit", + "id": "Counter.bump@L0#t3", + "kind": "exit", + "lean": "SolarVerifyVc.LoopVc.Counter.bump_annotated.ob5", + "post": {}, + "pre": { + "L0": { + "count": "|count@27|", + "i": "|i@28|", + "n": "|n@21|", + "old(count)": "|count@17|" + } + }, + "required": true, + "role": "obligation", + "site": { + "column": 10, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 20 + }, + "smt": "LoopVc/Counter/bump_annotated.ob5.smt2", + "smt_sha256": "d3090ea2aee8171933ea7a198c851eb5630cabe3c1028dff48aa0700b20b52c8", + "spec": { + "span": { + "column": 10, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 20 + }, + "text": "postcondition not satisfied" + }, + "template": "t3", + "template_role": "path" + }, + { + "answer": "not-run", + "candidate": "annotated", + "cutpoint": "L0", + "edge": "exit", + "id": "Counter.bump@L0#t4", + "kind": "exit", + "lean": "SolarVerifyVc.LoopVc.Counter.bump_annotated.ob6", + "post": {}, + "pre": { + "L0": { + "count": "|count@27|", + "i": "|i@28|", + "n": "|n@21|", + "old(count)": "|count@17|" + } + }, + "required": true, + "role": "obligation", + "site": { + "column": 5, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 21 + }, + "smt": "LoopVc/Counter/bump_annotated.ob6.smt2", + "smt_sha256": "24b1bd91593f695ecbdd42782926cf4dfaea3c00e39cf77489b687147ac71531", + "spec": { + "span": { + "column": 5, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 21 + }, + "text": "contract invariant not preserved" + }, + "template": "t4", + "template_role": "path" + } + ], + "reverts": [ + { + "asserts": 24, + "commands": 48, + "from": "entry", + "guard": "(and |g@23| (not (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))", + "id": "r0", + "script": 0 + }, + { + "asserts": 25, + "commands": 50, + "from": "entry", + "guard": "(and |g@25| (not (<= |arith@24| |limit@18|)))", + "id": "r1", + "script": 0 + }, + { + "asserts": 31, + "commands": 62, + "from": "body", + "guard": "(and |g@30| (not (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))", + "id": "r2", + "script": 0 + }, + { + "asserts": 33, + "commands": 66, + "from": "body", + "guard": "(and |g@32| (not (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))", + "id": "r3", + "script": 0 + } + ], + "status": "generated" + } + ], + "version": 2 +} diff --git a/Verify/Infer/loopvc/export/spacer.sha256 b/Verify/Infer/loopvc/export/spacer.sha256 new file mode 100644 index 00000000..1977a13e --- /dev/null +++ b/Verify/Infer/loopvc/export/spacer.sha256 @@ -0,0 +1,10 @@ +86cf294527c5590676bed8e19d88af7570ce3f39a0f0069a0eb303d3beabff6a manifest.json +71210b036b2cab22df904f5a07d28b0a5d2f836c2be0d789652d35073afffb2d LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.lean +524779d300a8349448949e7e9da8a2552a955d413eb443ee6e1d6348dfb442f8 Verify/Infer/loopvc/solar/Counter/bump.loopvc.json +88f69aaad5735250f8e4c8f3fd2d6c1dd94603c9cec4c92ff797ef62d8c3fe54 Verify/Infer/loopvc/solar/Counter/bump.horn.smt2 +8b5f650e16a217b5b843f8ca623a22f6c0dc6c0afc44e07251fac2559d4b2e82 Verify/Infer/loopvc/solar/LoopVc.lean +e954bfd845f141aa6c87166c42f430eb1b188e0e1615629688fed955278fcf94 Verify/Infer/loopvc/solar/Counter/bump.lean +ba357e2ed64efdd84a9d28afc5faf54497a9353b63429c7d0b655ace57d5d221 Verify/Infer/loopvc/solar/Counter/bump_loopvc.lean +a7c6e0d6ea1ecd73de493f7d3ab09728e7caa5a1054cbb5e786ee4e3a52d6dc7 Verify/Infer/loopvc/spacer/Counter.bump.spacer.out +b596fcfdf4d8d9d5ad138db6403d355309821c6629be9de9fb72636b1b9f0236 Verify/Infer/loopvc/solar/Counter/bump.script0.smt2 +f1c87a334b8db31fc8f80541febeaf8617318d20b685634f44e26c74146ad326 Certified/verify_counter/verify_counter.sol diff --git a/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.lean b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.lean new file mode 100644 index 00000000..251bf0d8 --- /dev/null +++ b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.lean @@ -0,0 +1,77 @@ +-- Generated by Verify/Infer/smt2lean_inv.py loopvc; do not edit. +-- The instances of Counter.bump's loop-cut templates (Verify/Infer/loopvc/solar/Counter/bump.loopvc.json) at candidate spacer-a7c6e0d6ea1e. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e +open SolarVerify.Smt SolarVerify.Vc + +/-- The function's script with the candidate at the loop head. -/ +def script0 : Script := + { decls := [{ name := "|this@1|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|msg.sender@2|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|msg.value@3|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.timestamp@4|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.number@5|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.chainid@6|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|tx.origin@7|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|tx.gasprice@8|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|msg.sig@9|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|msg.data@10|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.basefee@11|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.blobbasefee@12|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.coinbase@13|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.prevrandao@14|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.difficulty@15|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|block.gaslimit@16|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|count@17|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|limit@18|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|__balance@19|", args := [], ret := SolarVerify.Smt.Srt.array (SolarVerify.Smt.Srt.int) (SolarVerify.Smt.Srt.int) }, { name := "|__code_epoch@20|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|n@21|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|g@22|", args := [], ret := SolarVerify.Smt.Srt.bool }, { name := "|g@23|", args := [], ret := SolarVerify.Smt.Srt.bool }, { name := "|arith@24|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|g@25|", args := [], ret := SolarVerify.Smt.Srt.bool }, { name := "|g@26|", args := [], ret := SolarVerify.Smt.Srt.bool }, { name := "|count@27|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|i@28|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|g@29|", args := [], ret := SolarVerify.Smt.Srt.bool }, { name := "|g@30|", args := [], ret := SolarVerify.Smt.Srt.bool }, { name := "|arith@31|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|g@32|", args := [], ret := SolarVerify.Smt.Srt.bool }, { name := "|arith@33|", args := [], ret := SolarVerify.Smt.Srt.int }, { name := "|g@34|", args := [], ret := SolarVerify.Smt.Srt.bool }, { name := "|g@35|", args := [], ret := SolarVerify.Smt.Srt.bool }], asserts := [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 0 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 0 [], SolarVerify.Smt.Term.int 1461501637330902918203684832716283019655932542975]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.not) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 0 [], SolarVerify.Smt.Term.int 0]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 1 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 1 [], SolarVerify.Smt.Term.int 1461501637330902918203684832716283019655932542975]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.not) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 1 [], SolarVerify.Smt.Term.int 0]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 2 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 2 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 3 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 3 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 4 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 4 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 5 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 5 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 6 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 6 [], SolarVerify.Smt.Term.int 1461501637330902918203684832716283019655932542975]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 7 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 7 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 8 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 8 [], SolarVerify.Smt.Term.int 4294967295]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 10 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 10 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 11 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 11 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 12 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 12 [], SolarVerify.Smt.Term.int 1461501637330902918203684832716283019655932542975]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 13 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 13 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 14 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 14 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 15 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 15 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 16 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 17 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 17 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 19 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 19 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 20 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 20 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 21 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.bool true, SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.fn 17 []]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 22 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.fn 21 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 2 [], SolarVerify.Smt.Term.int 0]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 23 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.fn 20 []]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 24 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.fn 22 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 23 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 23 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 25 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.fn 24 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 23 [], SolarVerify.Smt.Term.fn 17 []]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 26 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 26 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 27 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 27 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 28 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.fn 25 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.not) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.mul) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.int 1], SolarVerify.Smt.Term.fn 26 []], SolarVerify.Smt.Term.fn 27 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.int 1]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.not) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.ge) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.mul) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.int 1], SolarVerify.Smt.Term.fn 26 []], SolarVerify.Smt.Term.fn 27 []], SolarVerify.Smt.Term.int 1]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.not) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.mul) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.int 1], SolarVerify.Smt.Term.fn 26 []], SolarVerify.Smt.Term.fn 20 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.int 1]]]]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 29 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.fn 28 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.lt) [SolarVerify.Smt.Term.fn 27 [], SolarVerify.Smt.Term.fn 20 []]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 30 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 26 [], SolarVerify.Smt.Term.int 1]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 31 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.fn 29 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 30 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 30 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 32 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 27 [], SolarVerify.Smt.Term.int 1]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 33 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.fn 31 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.fn 32 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 32 [], SolarVerify.Smt.Term.int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 34 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.fn 28 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.not) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.lt) [SolarVerify.Smt.Term.fn 27 [], SolarVerify.Smt.Term.fn 20 []]]]]] } + +/-- Counter.bump@L0#t0.c0: initiation of edge entry (template t0, invariant), conjunct "(not (<= (+ |count@17| (* (- 1) |count@27|) |i@28|) (- 1)))", candidate spacer-a7c6e0d6ea1e. -/ +def ob0 : Obligation where + script := script0 + upto := 26 + guard := SolarVerify.Smt.Term.fn 25 [] + goal := SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.not) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.mul) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.int 1], SolarVerify.Smt.Term.fn 16 []], SolarVerify.Smt.Term.int 0], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.int 1]]] + +/-- Counter.bump@L0#t0.c1: initiation of edge entry (template t0, invariant), conjunct "(not (>= (+ |count@17| (* (- 1) |count@27|) |i@28|) 1))", candidate spacer-a7c6e0d6ea1e. -/ +def ob1 : Obligation where + script := script0 + upto := 26 + guard := SolarVerify.Smt.Term.fn 25 [] + goal := SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.not) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.ge) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.mul) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.int 1], SolarVerify.Smt.Term.fn 16 []], SolarVerify.Smt.Term.int 0], SolarVerify.Smt.Term.int 1]] + +/-- Counter.bump@L0#t0.c2: initiation of edge entry (template t0, invariant), conjunct "(not (<= (+ |count@17| (* (- 1) |count@27|) |n@21|) (- 1)))", candidate spacer-a7c6e0d6ea1e. -/ +def ob2 : Obligation where + script := script0 + upto := 26 + guard := SolarVerify.Smt.Term.fn 25 [] + goal := SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.not) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.mul) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.int 1], SolarVerify.Smt.Term.fn 16 []], SolarVerify.Smt.Term.fn 20 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.int 1]]] + +/-- Counter.bump@L0#t1.c0: preservation of edge back (template t1, invariant), conjunct "(not (<= (+ |count@17| (* (- 1) |count@27|) |i@28|) (- 1)))", candidate spacer-a7c6e0d6ea1e. -/ +def ob3 : Obligation where + script := script0 + upto := 34 + guard := SolarVerify.Smt.Term.fn 33 [] + goal := SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.not) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.mul) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.int 1], SolarVerify.Smt.Term.fn 30 []], SolarVerify.Smt.Term.fn 32 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.int 1]]] + +/-- Counter.bump@L0#t1.c1: preservation of edge back (template t1, invariant), conjunct "(not (>= (+ |count@17| (* (- 1) |count@27|) |i@28|) 1))", candidate spacer-a7c6e0d6ea1e. -/ +def ob4 : Obligation where + script := script0 + upto := 34 + guard := SolarVerify.Smt.Term.fn 33 [] + goal := SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.not) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.ge) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.mul) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.int 1], SolarVerify.Smt.Term.fn 30 []], SolarVerify.Smt.Term.fn 32 []], SolarVerify.Smt.Term.int 1]] + +/-- Counter.bump@L0#t1.c2: preservation of edge back (template t1, invariant), conjunct "(not (<= (+ |count@17| (* (- 1) |count@27|) |n@21|) (- 1)))", candidate spacer-a7c6e0d6ea1e. -/ +def ob5 : Obligation where + script := script0 + upto := 34 + guard := SolarVerify.Smt.Term.fn 33 [] + goal := SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.not) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.mul) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.int 1], SolarVerify.Smt.Term.fn 30 []], SolarVerify.Smt.Term.fn 20 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.int 1]]] + +/-- Counter.bump@L0#t2: termination of edge back (template t2, rank), candidate spacer-a7c6e0d6ea1e. -/ +def ob6 : Obligation where + script := script0 + upto := 34 + guard := SolarVerify.Smt.Term.fn 33 [] + goal := SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.and) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.int 0, SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.fn 20 [], SolarVerify.Smt.Term.fn 27 []]], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.lt) [SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.fn 20 [], SolarVerify.Smt.Term.fn 32 []], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.sub) [SolarVerify.Smt.Term.fn 20 [], SolarVerify.Smt.Term.fn 27 []]]] + +/-- Counter.bump@L0#t3: exit of edge exit (template t3, path), candidate spacer-a7c6e0d6ea1e. -/ +def ob7 : Obligation where + script := script0 + upto := 35 + guard := SolarVerify.Smt.Term.fn 34 [] + goal := SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.eq) [SolarVerify.Smt.Term.fn 26 [], SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.add) [SolarVerify.Smt.Term.fn 16 [], SolarVerify.Smt.Term.fn 20 []]] + +/-- Counter.bump@L0#t4: exit of edge exit (template t4, path), candidate spacer-a7c6e0d6ea1e. -/ +def ob8 : Obligation where + script := script0 + upto := 35 + guard := SolarVerify.Smt.Term.fn 34 [] + goal := SolarVerify.Smt.Term.app (SolarVerify.Smt.Op.le) [SolarVerify.Smt.Term.fn 26 [], SolarVerify.Smt.Term.fn 17 []] + +end SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e diff --git a/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob0.smt2 b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob0.smt2 new file mode 100644 index 00000000..4772945d --- /dev/null +++ b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob0.smt2 @@ -0,0 +1,55 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(assert |g@26|) +(assert (not (not (<= (+ |count@17| (* (- 1) |count@17|) 0) (- 1))))) +(check-sat) diff --git a/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob1.smt2 b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob1.smt2 new file mode 100644 index 00000000..737c9bc1 --- /dev/null +++ b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob1.smt2 @@ -0,0 +1,55 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(assert |g@26|) +(assert (not (not (>= (+ |count@17| (* (- 1) |count@17|) 0) 1)))) +(check-sat) diff --git a/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob2.smt2 b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob2.smt2 new file mode 100644 index 00000000..ef820761 --- /dev/null +++ b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob2.smt2 @@ -0,0 +1,55 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(assert |g@26|) +(assert (not (not (<= (+ |count@17| (* (- 1) |count@17|) |n@21|) (- 1))))) +(check-sat) diff --git a/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob3.smt2 b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob3.smt2 new file mode 100644 index 00000000..d849f003 --- /dev/null +++ b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob3.smt2 @@ -0,0 +1,71 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(declare-const |count@27| Int) +(assert (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |i@28| Int) +(assert (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@29| Bool) +(assert (= |g@29| (and |g@26| (and (not (<= (+ |count@17| (* (- 1) |count@27|) |i@28|) (- 1))) (not (>= (+ |count@17| (* (- 1) |count@27|) |i@28|) 1)) (not (<= (+ |count@17| (* (- 1) |count@27|) |n@21|) (- 1))))))) +(declare-const |g@30| Bool) +(assert (= |g@30| (and |g@29| (< |i@28| |n@21|)))) +(declare-const |arith@31| Int) +(assert (= |arith@31| (+ |count@27| 1))) +(declare-const |g@32| Bool) +(assert (= |g@32| (and |g@30| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |arith@33| Int) +(assert (= |arith@33| (+ |i@28| 1))) +(declare-const |g@34| Bool) +(assert (= |g@34| (and |g@32| (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(assert |g@34|) +(assert (not (not (<= (+ |count@17| (* (- 1) |arith@31|) |arith@33|) (- 1))))) +(check-sat) diff --git a/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob4.smt2 b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob4.smt2 new file mode 100644 index 00000000..53e3c5a0 --- /dev/null +++ b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob4.smt2 @@ -0,0 +1,71 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(declare-const |count@27| Int) +(assert (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |i@28| Int) +(assert (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@29| Bool) +(assert (= |g@29| (and |g@26| (and (not (<= (+ |count@17| (* (- 1) |count@27|) |i@28|) (- 1))) (not (>= (+ |count@17| (* (- 1) |count@27|) |i@28|) 1)) (not (<= (+ |count@17| (* (- 1) |count@27|) |n@21|) (- 1))))))) +(declare-const |g@30| Bool) +(assert (= |g@30| (and |g@29| (< |i@28| |n@21|)))) +(declare-const |arith@31| Int) +(assert (= |arith@31| (+ |count@27| 1))) +(declare-const |g@32| Bool) +(assert (= |g@32| (and |g@30| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |arith@33| Int) +(assert (= |arith@33| (+ |i@28| 1))) +(declare-const |g@34| Bool) +(assert (= |g@34| (and |g@32| (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(assert |g@34|) +(assert (not (not (>= (+ |count@17| (* (- 1) |arith@31|) |arith@33|) 1)))) +(check-sat) diff --git a/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob5.smt2 b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob5.smt2 new file mode 100644 index 00000000..6bb579a1 --- /dev/null +++ b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob5.smt2 @@ -0,0 +1,71 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(declare-const |count@27| Int) +(assert (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |i@28| Int) +(assert (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@29| Bool) +(assert (= |g@29| (and |g@26| (and (not (<= (+ |count@17| (* (- 1) |count@27|) |i@28|) (- 1))) (not (>= (+ |count@17| (* (- 1) |count@27|) |i@28|) 1)) (not (<= (+ |count@17| (* (- 1) |count@27|) |n@21|) (- 1))))))) +(declare-const |g@30| Bool) +(assert (= |g@30| (and |g@29| (< |i@28| |n@21|)))) +(declare-const |arith@31| Int) +(assert (= |arith@31| (+ |count@27| 1))) +(declare-const |g@32| Bool) +(assert (= |g@32| (and |g@30| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |arith@33| Int) +(assert (= |arith@33| (+ |i@28| 1))) +(declare-const |g@34| Bool) +(assert (= |g@34| (and |g@32| (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(assert |g@34|) +(assert (not (not (<= (+ |count@17| (* (- 1) |arith@31|) |n@21|) (- 1))))) +(check-sat) diff --git a/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob6.smt2 b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob6.smt2 new file mode 100644 index 00000000..114db9b6 --- /dev/null +++ b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob6.smt2 @@ -0,0 +1,71 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(declare-const |count@27| Int) +(assert (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |i@28| Int) +(assert (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@29| Bool) +(assert (= |g@29| (and |g@26| (and (not (<= (+ |count@17| (* (- 1) |count@27|) |i@28|) (- 1))) (not (>= (+ |count@17| (* (- 1) |count@27|) |i@28|) 1)) (not (<= (+ |count@17| (* (- 1) |count@27|) |n@21|) (- 1))))))) +(declare-const |g@30| Bool) +(assert (= |g@30| (and |g@29| (< |i@28| |n@21|)))) +(declare-const |arith@31| Int) +(assert (= |arith@31| (+ |count@27| 1))) +(declare-const |g@32| Bool) +(assert (= |g@32| (and |g@30| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |arith@33| Int) +(assert (= |arith@33| (+ |i@28| 1))) +(declare-const |g@34| Bool) +(assert (= |g@34| (and |g@32| (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(assert |g@34|) +(assert (not (and (<= 0 (- |n@21| |i@28|)) (< (- |n@21| |arith@33|) (- |n@21| |i@28|))))) +(check-sat) diff --git a/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob7.smt2 b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob7.smt2 new file mode 100644 index 00000000..1bac0449 --- /dev/null +++ b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob7.smt2 @@ -0,0 +1,73 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(declare-const |count@27| Int) +(assert (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |i@28| Int) +(assert (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@29| Bool) +(assert (= |g@29| (and |g@26| (and (not (<= (+ |count@17| (* (- 1) |count@27|) |i@28|) (- 1))) (not (>= (+ |count@17| (* (- 1) |count@27|) |i@28|) 1)) (not (<= (+ |count@17| (* (- 1) |count@27|) |n@21|) (- 1))))))) +(declare-const |g@30| Bool) +(assert (= |g@30| (and |g@29| (< |i@28| |n@21|)))) +(declare-const |arith@31| Int) +(assert (= |arith@31| (+ |count@27| 1))) +(declare-const |g@32| Bool) +(assert (= |g@32| (and |g@30| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |arith@33| Int) +(assert (= |arith@33| (+ |i@28| 1))) +(declare-const |g@34| Bool) +(assert (= |g@34| (and |g@32| (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@35| Bool) +(assert (= |g@35| (and |g@29| (not (< |i@28| |n@21|))))) +(assert |g@35|) +(assert (not (= |count@27| (+ |count@17| |n@21|)))) +(check-sat) diff --git a/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob8.smt2 b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob8.smt2 new file mode 100644 index 00000000..45d7b824 --- /dev/null +++ b/Verify/Infer/loopvc/export/spacer/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob8.smt2 @@ -0,0 +1,73 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(declare-const |count@27| Int) +(assert (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |i@28| Int) +(assert (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@29| Bool) +(assert (= |g@29| (and |g@26| (and (not (<= (+ |count@17| (* (- 1) |count@27|) |i@28|) (- 1))) (not (>= (+ |count@17| (* (- 1) |count@27|) |i@28|) 1)) (not (<= (+ |count@17| (* (- 1) |count@27|) |n@21|) (- 1))))))) +(declare-const |g@30| Bool) +(assert (= |g@30| (and |g@29| (< |i@28| |n@21|)))) +(declare-const |arith@31| Int) +(assert (= |arith@31| (+ |count@27| 1))) +(declare-const |g@32| Bool) +(assert (= |g@32| (and |g@30| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |arith@33| Int) +(assert (= |arith@33| (+ |i@28| 1))) +(declare-const |g@34| Bool) +(assert (= |g@34| (and |g@32| (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@35| Bool) +(assert (= |g@35| (and |g@29| (not (< |i@28| |n@21|))))) +(assert |g@35|) +(assert (not (<= |count@27| |limit@18|))) +(check-sat) diff --git a/Verify/Infer/loopvc/export/spacer/bridge/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e_bridge.lean b/Verify/Infer/loopvc/export/spacer/bridge/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e_bridge.lean new file mode 100644 index 00000000..bb7600d3 --- /dev/null +++ b/Verify/Infer/loopvc/export/spacer/bridge/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e_bridge.lean @@ -0,0 +1,28 @@ +import Lean +import Counter.bump_loopvc +import LoopVc.Counter.bump_spacer_a7c6e0d6ea1e + +open SolarVerify.Smt SolarVerify.Vc SolarVerify.LoopVc + +namespace SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.Bridge + +/-- The candidate, in the interface's terms. -/ +def cand : Cand := { conj := [.app .not [.app .le [.app .add [.fn 16 [], .app .mul [.app .sub [.int 1], .fn 26 []], .fn 27 []], .app .sub [.int 1]]], .app .not [.app .ge [.app .add [.fn 16 [], .app .mul [.app .sub [.int 1], .fn 26 []], .fn 27 []], .int 1]], .app .not [.app .le [.app .add [.fn 16 [], .app .mul [.app .sub [.int 1], .fn 26 []], .fn 20 []], .app .sub [.int 1]]]], rank := some (.app .sub [.fn 20 [], .fn 27 []]) } + +theorem t0_exact : SolarVerifyLoopVc.Counter.bump.t0.instances SolarVerifyLoopVc.Counter.bump.cut cand = [SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob0, SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob1, SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob2] := rfl + +theorem t1_exact : SolarVerifyLoopVc.Counter.bump.t1.instances SolarVerifyLoopVc.Counter.bump.cut cand = [SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob3, SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob4, SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob5] := rfl + +theorem t2_exact : SolarVerifyLoopVc.Counter.bump.t2.instances SolarVerifyLoopVc.Counter.bump.cut cand = [SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob6] := rfl + +theorem t3_exact : SolarVerifyLoopVc.Counter.bump.t3.instances SolarVerifyLoopVc.Counter.bump.cut cand = [SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob7] := rfl + +theorem t4_exact : SolarVerifyLoopVc.Counter.bump.t4.instances SolarVerifyLoopVc.Counter.bump.cut cand = [SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob8] := rfl + +end SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.Bridge + +open Lean Elab Command in +#eval show CommandElabM Unit from do + for n in [`SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.Bridge.t0_exact, `SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.Bridge.t1_exact, `SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.Bridge.t2_exact, `SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.Bridge.t3_exact, `SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.Bridge.t4_exact] do + let axs ← Lean.collectAxioms n + IO.println s!"AXIOMS {n}: {String.intercalate " " (axs.toList.map toString)}" diff --git a/Verify/Infer/loopvc/export/spacer/manifest.json b/Verify/Infer/loopvc/export/spacer/manifest.json new file mode 100644 index 00000000..12c35dc3 --- /dev/null +++ b/Verify/Infer/loopvc/export/spacer/manifest.json @@ -0,0 +1,447 @@ +{ + "format": "solar-verify-lean", + "generator": { + "interface": { + "format": "solar-verify-loopvc", + "formulas_sha256": "f8b5887986ea82259e3bc90c12abea85773dc969a7d8788af39535ec590e2de2", + "version": 1 + }, + "name": "Verify/Infer/smt2lean_inv.py loopvc" + }, + "lean": { + "smt_sha256": "2c92f3bcd927369da89250662bd5a6174d3c06d0c3c38f5021509fe8810036e3", + "toolchain": "leanprover/lean4:v4.35.0", + "vc_sha256": "648d461056fe1649754b1ec259c2d1c48e8db8a4c11e5af281e73796399bc96a" + }, + "sources": [ + { + "path": "Verify/Infer/loopvc/solar/Counter/bump.loopvc.json", + "sha256": "524779d300a8349448949e7e9da8a2552a955d413eb443ee6e1d6348dfb442f8" + }, + { + "path": "Verify/Infer/loopvc/solar/Counter/bump.horn.smt2", + "sha256": "88f69aaad5735250f8e4c8f3fd2d6c1dd94603c9cec4c92ff797ef62d8c3fe54" + }, + { + "path": "Verify/Infer/loopvc/solar/LoopVc.lean", + "sha256": "8b5f650e16a217b5b843f8ca623a22f6c0dc6c0afc44e07251fac2559d4b2e82" + }, + { + "path": "Verify/Infer/loopvc/solar/Counter/bump.lean", + "sha256": "e954bfd845f141aa6c87166c42f430eb1b188e0e1615629688fed955278fcf94" + }, + { + "path": "Verify/Infer/loopvc/solar/Counter/bump_loopvc.lean", + "sha256": "ba357e2ed64efdd84a9d28afc5faf54497a9353b63429c7d0b655ace57d5d221" + }, + { + "path": "Verify/Infer/loopvc/spacer/Counter.bump.spacer.out", + "sha256": "a7c6e0d6ea1ecd73de493f7d3ab09728e7caa5a1054cbb5e786ee4e3a52d6dc7" + }, + { + "path": "Verify/Infer/loopvc/solar/Counter/bump.script0.smt2", + "sha256": "b596fcfdf4d8d9d5ad138db6403d355309821c6629be9de9fb72636b1b9f0236" + }, + { + "path": "Certified/verify_counter/verify_counter.sol", + "sha256": "f1c87a334b8db31fc8f80541febeaf8617318d20b685634f44e26c74146ad326" + } + ], + "units": [ + { + "bridge": "bridge/LoopVc/Counter/bump_spacer_a7c6e0d6ea1e_bridge.lean", + "candidate": { + "conjuncts": [ + { + "origin": "spacer", + "site": null, + "term": "(not (<= (+ |count@17| (* (- 1) |count@27|) |i@28|) (- 1)))", + "text": "(not (<= (+ |count@17| (* (- 1) |count@27|) |i@28|) (- 1)))" + }, + { + "origin": "spacer", + "site": null, + "term": "(not (>= (+ |count@17| (* (- 1) |count@27|) |i@28|) 1))", + "text": "(not (>= (+ |count@17| (* (- 1) |count@27|) |i@28|) 1))" + }, + { + "origin": "spacer", + "site": null, + "term": "(not (<= (+ |count@17| (* (- 1) |count@27|) |n@21|) (- 1)))", + "text": "(not (<= (+ |count@17| (* (- 1) |count@27|) |n@21|) (- 1)))" + } + ], + "id": "spacer-a7c6e0d6ea1e", + "rank": { + "origin": "annotation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 25 + }, + "term": "(- |n@21| |i@28|)", + "text": "n - i" + } + }, + "module": "LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.lean", + "name": "Counter.bump L0 [spacer-a7c6e0d6ea1e]", + "namespace": "SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e", + "obligations": [ + { + "answer": "not-run", + "candidate": "spacer-a7c6e0d6ea1e", + "cutpoint": "L0", + "edge": "entry", + "id": "Counter.bump@L0#t0.c0", + "kind": "initiation", + "lean": "SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob0", + "post": { + "count": "|count@17|", + "i": "0", + "n": "|n@21|", + "old(count)": "|count@17|" + }, + "pre": {}, + "required": true, + "role": "obligation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23 + }, + "smt": "LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob0.smt2", + "smt_sha256": "27e021711178e732bc1a857fc79dcdfc0c229b1df42ff5a7b2eb23c3b0761526", + "spec": { + "span": null, + "text": "(not (<= (+ |count@17| (* (- 1) |count@27|) |i@28|) (- 1)))" + }, + "template": "t0", + "template_role": "invariant" + }, + { + "answer": "not-run", + "candidate": "spacer-a7c6e0d6ea1e", + "cutpoint": "L0", + "edge": "entry", + "id": "Counter.bump@L0#t0.c1", + "kind": "initiation", + "lean": "SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob1", + "post": { + "count": "|count@17|", + "i": "0", + "n": "|n@21|", + "old(count)": "|count@17|" + }, + "pre": {}, + "required": true, + "role": "obligation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23 + }, + "smt": "LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob1.smt2", + "smt_sha256": "c31ae0c00b709ff35cd98dc81b4b3822017c0691af282ab47946fafd368f161d", + "spec": { + "span": null, + "text": "(not (>= (+ |count@17| (* (- 1) |count@27|) |i@28|) 1))" + }, + "template": "t0", + "template_role": "invariant" + }, + { + "answer": "not-run", + "candidate": "spacer-a7c6e0d6ea1e", + "cutpoint": "L0", + "edge": "entry", + "id": "Counter.bump@L0#t0.c2", + "kind": "initiation", + "lean": "SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob2", + "post": { + "count": "|count@17|", + "i": "0", + "n": "|n@21|", + "old(count)": "|count@17|" + }, + "pre": {}, + "required": true, + "role": "obligation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23 + }, + "smt": "LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob2.smt2", + "smt_sha256": "b1e0986bb495183c4d8b1bedaa46e6ee649aa981a80f51fa5a441b56c87e990c", + "spec": { + "span": null, + "text": "(not (<= (+ |count@17| (* (- 1) |count@27|) |n@21|) (- 1)))" + }, + "template": "t0", + "template_role": "invariant" + }, + { + "answer": "not-run", + "candidate": "spacer-a7c6e0d6ea1e", + "cutpoint": "L0", + "edge": "back", + "id": "Counter.bump@L0#t1.c0", + "kind": "preservation", + "lean": "SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob3", + "post": { + "count": "|arith@31|", + "i": "|arith@33|", + "n": "|n@21|", + "old(count)": "|count@17|" + }, + "pre": { + "L0": { + "count": "|count@27|", + "i": "|i@28|", + "n": "|n@21|", + "old(count)": "|count@17|" + } + }, + "required": true, + "role": "obligation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23 + }, + "smt": "LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob3.smt2", + "smt_sha256": "d2b9ba5b5031f10f0acd9f948794fd00dac15473080f97feb420c7340272e3d7", + "spec": { + "span": null, + "text": "(not (<= (+ |count@17| (* (- 1) |count@27|) |i@28|) (- 1)))" + }, + "template": "t1", + "template_role": "invariant" + }, + { + "answer": "not-run", + "candidate": "spacer-a7c6e0d6ea1e", + "cutpoint": "L0", + "edge": "back", + "id": "Counter.bump@L0#t1.c1", + "kind": "preservation", + "lean": "SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob4", + "post": { + "count": "|arith@31|", + "i": "|arith@33|", + "n": "|n@21|", + "old(count)": "|count@17|" + }, + "pre": { + "L0": { + "count": "|count@27|", + "i": "|i@28|", + "n": "|n@21|", + "old(count)": "|count@17|" + } + }, + "required": true, + "role": "obligation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23 + }, + "smt": "LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob4.smt2", + "smt_sha256": "0517eda9cb26faf5cbea2d332d7d256b09c670a9a6639b61082512d03405093d", + "spec": { + "span": null, + "text": "(not (>= (+ |count@17| (* (- 1) |count@27|) |i@28|) 1))" + }, + "template": "t1", + "template_role": "invariant" + }, + { + "answer": "not-run", + "candidate": "spacer-a7c6e0d6ea1e", + "cutpoint": "L0", + "edge": "back", + "id": "Counter.bump@L0#t1.c2", + "kind": "preservation", + "lean": "SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob5", + "post": { + "count": "|arith@31|", + "i": "|arith@33|", + "n": "|n@21|", + "old(count)": "|count@17|" + }, + "pre": { + "L0": { + "count": "|count@27|", + "i": "|i@28|", + "n": "|n@21|", + "old(count)": "|count@17|" + } + }, + "required": true, + "role": "obligation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23 + }, + "smt": "LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob5.smt2", + "smt_sha256": "671fff4a1e0f9461bd05d44ae44f1b2594aa170890a75d1f6dffe82d4cba312a", + "spec": { + "span": null, + "text": "(not (<= (+ |count@17| (* (- 1) |count@27|) |n@21|) (- 1)))" + }, + "template": "t1", + "template_role": "invariant" + }, + { + "answer": "not-run", + "candidate": "spacer-a7c6e0d6ea1e", + "cutpoint": "L0", + "edge": "back", + "id": "Counter.bump@L0#t2", + "kind": "termination", + "lean": "SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob6", + "post": {}, + "pre": { + "L0": { + "count": "|count@27|", + "i": "|i@28|", + "n": "|n@21|", + "old(count)": "|count@17|" + } + }, + "required": true, + "role": "obligation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 25 + }, + "smt": "LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob6.smt2", + "smt_sha256": "e343e8dd3c73a4f06dbaf0454fa2820502394134a7433751c4d234e59e03ccc5", + "spec": { + "span": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 25 + }, + "text": "n - i" + }, + "template": "t2", + "template_role": "rank" + }, + { + "answer": "not-run", + "candidate": "spacer-a7c6e0d6ea1e", + "cutpoint": "L0", + "edge": "exit", + "id": "Counter.bump@L0#t3", + "kind": "exit", + "lean": "SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob7", + "post": {}, + "pre": { + "L0": { + "count": "|count@27|", + "i": "|i@28|", + "n": "|n@21|", + "old(count)": "|count@17|" + } + }, + "required": true, + "role": "obligation", + "site": { + "column": 10, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 20 + }, + "smt": "LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob7.smt2", + "smt_sha256": "94a0a602a8b81d7802672dde384c54b739d72cff9d7c784f02102a49a77a7a55", + "spec": { + "span": { + "column": 10, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 20 + }, + "text": "postcondition not satisfied" + }, + "template": "t3", + "template_role": "path" + }, + { + "answer": "not-run", + "candidate": "spacer-a7c6e0d6ea1e", + "cutpoint": "L0", + "edge": "exit", + "id": "Counter.bump@L0#t4", + "kind": "exit", + "lean": "SolarVerifyVc.LoopVc.Counter.bump_spacer_a7c6e0d6ea1e.ob8", + "post": {}, + "pre": { + "L0": { + "count": "|count@27|", + "i": "|i@28|", + "n": "|n@21|", + "old(count)": "|count@17|" + } + }, + "required": true, + "role": "obligation", + "site": { + "column": 5, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 21 + }, + "smt": "LoopVc/Counter/bump_spacer_a7c6e0d6ea1e.ob8.smt2", + "smt_sha256": "3a8a04d9d2c4895f0367a4cfc7df12833eec19c4bf3f5d0a7d4becc1b2a4fa84", + "spec": { + "span": { + "column": 5, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 21 + }, + "text": "contract invariant not preserved" + }, + "template": "t4", + "template_role": "path" + } + ], + "reverts": [ + { + "asserts": 24, + "commands": 48, + "from": "entry", + "guard": "(and |g@23| (not (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))", + "id": "r0", + "script": 0 + }, + { + "asserts": 25, + "commands": 50, + "from": "entry", + "guard": "(and |g@25| (not (<= |arith@24| |limit@18|)))", + "id": "r1", + "script": 0 + }, + { + "asserts": 31, + "commands": 62, + "from": "body", + "guard": "(and |g@30| (not (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))", + "id": "r2", + "script": 0 + }, + { + "asserts": 33, + "commands": 66, + "from": "body", + "guard": "(and |g@32| (not (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))", + "id": "r3", + "script": 0 + } + ], + "status": "generated" + } + ], + "version": 2 +} diff --git a/Verify/Infer/loopvc/results/annotated/results.tsv b/Verify/Infer/loopvc/results/annotated/results.tsv new file mode 100644 index 00000000..171016a4 --- /dev/null +++ b/Verify/Infer/loopvc/results/annotated/results.tsv @@ -0,0 +1,8 @@ +id role answer backend status seconds peak_mb axioms +Counter.bump@L0#t0.c0 obligation not-run smt proved 1.9 1827 propext Classical.choice Quot.sound +Counter.bump@L0#t0.c1 obligation not-run smt proved 1.9 1828 propext Classical.choice Quot.sound +Counter.bump@L0#t1.c0 obligation not-run smt proved 2.1 1846 propext Classical.choice Quot.sound +Counter.bump@L0#t1.c1 obligation not-run smt proved 2.3 1846 propext Classical.choice Quot.sound +Counter.bump@L0#t2 obligation not-run smt proved 2.4 1850 propext Classical.choice Quot.sound +Counter.bump@L0#t3 obligation not-run smt proved 2.5 1855 propext Classical.choice Quot.sound +Counter.bump@L0#t4 obligation not-run smt proved 2.2 1855 propext Classical.choice Quot.sound diff --git a/Verify/Infer/loopvc/results/annotated/summary.tsv b/Verify/Infer/loopvc/results/annotated/summary.tsv new file mode 100644 index 00000000..2bd01b7a --- /dev/null +++ b/Verify/Infer/loopvc/results/annotated/summary.tsv @@ -0,0 +1,8 @@ +id role answer status backends vacuous +Counter.bump@L0#t0.c0 obligation not-run proved smt no +Counter.bump@L0#t0.c1 obligation not-run proved smt no +Counter.bump@L0#t1.c0 obligation not-run proved smt no +Counter.bump@L0#t1.c1 obligation not-run proved smt no +Counter.bump@L0#t2 obligation not-run proved smt no +Counter.bump@L0#t3 obligation not-run proved smt no +Counter.bump@L0#t4 obligation not-run proved smt no diff --git a/Verify/Infer/loopvc/results/mutant/cti.json b/Verify/Infer/loopvc/results/mutant/cti.json new file mode 100644 index 00000000..1f65037b --- /dev/null +++ b/Verify/Infer/loopvc/results/mutant/cti.json @@ -0,0 +1,86 @@ +[ + { + "candidate": "mutant", + "edge": "entry", + "id": "Counter.bump@L0#t0.c1", + "kind": "initiation", + "post": { + "count": "0", + "i": "0", + "n": "0", + "old(count)": "0" + }, + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 24 + }, + "solver": "Z3 version 4.13.4 - 64 bit", + "spec": { + "span": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 24 + }, + "text": "count == old(count) + i + 1 (mutated from count == old(count) + i)" + }, + "status": "failed", + "verdict": "cti" + }, + { + "candidate": "mutant", + "edge": "exit", + "id": "Counter.bump@L0#t3", + "kind": "exit", + "pre": { + "count": "1", + "i": "0", + "n": "0", + "old(count)": "0" + }, + "site": { + "column": 10, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 20 + }, + "solver": "Z3 version 4.13.4 - 64 bit", + "spec": { + "span": { + "column": 10, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 20 + }, + "text": "postcondition not satisfied" + }, + "status": "failed", + "verdict": "cti" + }, + { + "candidate": "mutant", + "edge": "exit", + "id": "Counter.bump@L0#t4", + "kind": "exit", + "pre": { + "count": "1", + "i": "0", + "n": "0", + "old(count)": "0" + }, + "site": { + "column": 5, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 21 + }, + "solver": "Z3 version 4.13.4 - 64 bit", + "spec": { + "span": { + "column": 5, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 21 + }, + "text": "contract invariant not preserved" + }, + "status": "failed", + "verdict": "cti" + } +] diff --git a/Verify/Infer/loopvc/results/mutant/results.tsv b/Verify/Infer/loopvc/results/mutant/results.tsv new file mode 100644 index 00000000..abe90489 --- /dev/null +++ b/Verify/Infer/loopvc/results/mutant/results.tsv @@ -0,0 +1,11 @@ +id role answer backend status seconds peak_mb axioms +Counter.bump@L0#t0.c0 obligation not-run smt proved 2.2 1827 propext Classical.choice Quot.sound +Counter.bump@L0#t0.c1 obligation not-run smt failed: Counter_bump_L0_t0_c1_smt.lean:4:78: error: unable to prove goal, either it is false or you need to provide more facts. Try adding '+model' config option to display a potential counter-example (experim 1.8 1822 propext sorryAx Classical.choice Quot.sound +Counter.bump@L0#t0.c1 obligation not-run vc_valid failed: Counter_bump_L0_t0_c1_vc_valid.lean:4:78: error: omega could not prove the goal: a possible counterexample may satisfy the constraints 0 ≤ r ≤ 1157920892373161954235709850086879078532699846656405 2.4 1619 propext sorryAx Classical.choice Quot.sound +Counter.bump@L0#t1.c0 obligation not-run smt proved 2.4 1846 propext Classical.choice Quot.sound +Counter.bump@L0#t1.c1 obligation not-run smt proved 2.3 1847 propext Classical.choice Quot.sound +Counter.bump@L0#t2 obligation not-run smt proved 2.2 1850 propext Classical.choice Quot.sound +Counter.bump@L0#t3 obligation not-run smt failed: Counter_bump_L0_t3_smt.lean:4:78: error: unable to prove goal, either it is false or you need to provide more facts. Try adding '+model' config option to display a potential counter-example (experiment 2.1 1839 propext sorryAx Classical.choice Quot.sound +Counter.bump@L0#t3 obligation not-run vc_valid failed: Counter_bump_L0_t3_vc_valid.lean:4:78: error: omega could not prove the goal: a possible counterexample may satisfy the constraints 0 ≤ r ≤ 1157920892373161954235709850086879078532699846656405640 2.9 1641 propext sorryAx Classical.choice Quot.sound +Counter.bump@L0#t4 obligation not-run smt failed: Counter_bump_L0_t4_smt.lean:4:78: error: unable to prove goal, either it is false or you need to provide more facts. Try adding '+model' config option to display a potential counter-example (experiment 2.2 1841 propext sorryAx Classical.choice Quot.sound +Counter.bump@L0#t4 obligation not-run vc_valid failed: Counter_bump_L0_t4_vc_valid.lean:4:78: error: omega could not prove the goal: a possible counterexample may satisfy the constraints 0 ≤ q ≤ 1157920892373161954235709850086879078532699846656405640 2.9 1641 propext sorryAx Classical.choice Quot.sound diff --git a/Verify/Infer/loopvc/results/mutant/summary.tsv b/Verify/Infer/loopvc/results/mutant/summary.tsv new file mode 100644 index 00000000..630e96bc --- /dev/null +++ b/Verify/Infer/loopvc/results/mutant/summary.tsv @@ -0,0 +1,8 @@ +id role answer status backends vacuous +Counter.bump@L0#t0.c0 obligation not-run proved smt no +Counter.bump@L0#t0.c1 obligation not-run failed - no +Counter.bump@L0#t1.c0 obligation not-run proved smt no +Counter.bump@L0#t1.c1 obligation not-run proved smt no +Counter.bump@L0#t2 obligation not-run proved smt no +Counter.bump@L0#t3 obligation not-run failed - no +Counter.bump@L0#t4 obligation not-run failed - no diff --git a/Verify/Infer/loopvc/results/spacer/results.tsv b/Verify/Infer/loopvc/results/spacer/results.tsv new file mode 100644 index 00000000..894bd75e --- /dev/null +++ b/Verify/Infer/loopvc/results/spacer/results.tsv @@ -0,0 +1,10 @@ +id role answer backend status seconds peak_mb axioms +Counter.bump@L0#t0.c0 obligation not-run smt proved 2.0 1830 propext Classical.choice Quot.sound +Counter.bump@L0#t0.c1 obligation not-run smt proved 1.9 1829 propext Classical.choice Quot.sound +Counter.bump@L0#t0.c2 obligation not-run smt proved 1.9 1829 propext Classical.choice Quot.sound +Counter.bump@L0#t1.c0 obligation not-run smt proved 2.4 1850 propext Classical.choice Quot.sound +Counter.bump@L0#t1.c1 obligation not-run smt proved 2.4 1850 propext Classical.choice Quot.sound +Counter.bump@L0#t1.c2 obligation not-run smt proved 2.2 1853 propext Classical.choice Quot.sound +Counter.bump@L0#t2 obligation not-run smt proved 2.5 1852 propext Classical.choice Quot.sound +Counter.bump@L0#t3 obligation not-run smt proved 2.4 1854 propext Classical.choice Quot.sound +Counter.bump@L0#t4 obligation not-run smt proved 2.5 1854 propext Classical.choice Quot.sound diff --git a/Verify/Infer/loopvc/results/spacer/summary.tsv b/Verify/Infer/loopvc/results/spacer/summary.tsv new file mode 100644 index 00000000..d4d1545c --- /dev/null +++ b/Verify/Infer/loopvc/results/spacer/summary.tsv @@ -0,0 +1,10 @@ +id role answer status backends vacuous +Counter.bump@L0#t0.c0 obligation not-run proved smt no +Counter.bump@L0#t0.c1 obligation not-run proved smt no +Counter.bump@L0#t0.c2 obligation not-run proved smt no +Counter.bump@L0#t1.c0 obligation not-run proved smt no +Counter.bump@L0#t1.c1 obligation not-run proved smt no +Counter.bump@L0#t1.c2 obligation not-run proved smt no +Counter.bump@L0#t2 obligation not-run proved smt no +Counter.bump@L0#t3 obligation not-run proved smt no +Counter.bump@L0#t4 obligation not-run proved smt no diff --git a/Verify/Infer/loopvc/solar/Counter/bump.horn.smt2 b/Verify/Infer/loopvc/solar/Counter/bump.horn.smt2 new file mode 100644 index 00000000..37cf2f1e --- /dev/null +++ b/Verify/Infer/loopvc/solar/Counter/bump.horn.smt2 @@ -0,0 +1,23 @@ +; Generated by solar-verify --emit-loopvc (format 1); do not edit. +; Counter.bump: constrained Horn clauses over |Inv@L0| (count, i, n, old(count)), one per obligation template of the +; cut that does not mention |Rank@L0|, then one per revert path. See loopvc.json. +(set-logic HORN) +(declare-fun |Inv@L0| (Int Int Int Int) Bool) +(declare-fun |Reverted| () Bool) +; t0: entry edge, invariant +(assert (forall ((|this@1| Int) (|msg.sender@2| Int) (|msg.value@3| Int) (|block.timestamp@4| Int) (|block.number@5| Int) (|block.chainid@6| Int) (|tx.origin@7| Int) (|tx.gasprice@8| Int) (|msg.sig@9| Int) (|msg.data@10| Int) (|block.basefee@11| Int) (|block.blobbasefee@12| Int) (|block.coinbase@13| Int) (|block.prevrandao@14| Int) (|block.difficulty@15| Int) (|block.gaslimit@16| Int) (|count@17| Int) (|limit@18| Int) (|__balance@19| (Array Int Int)) (|__code_epoch@20| Int) (|n@21| Int) (|g@22| Bool) (|g@23| Bool) (|arith@24| Int) (|g@25| Bool) (|g@26| Bool)) (=> (and (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)) (not (= |this@1| 0)) (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)) (not (= |msg.sender@2| 0)) (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)) (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)) (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)) (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (= |g@22| (and true (<= |count@17| |limit@18|))) (= |g@23| (and |g@22| (= |msg.value@3| 0))) (= |arith@24| (+ |count@17| |n@21|)) (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))) (= |g@26| (and |g@25| (<= |arith@24| |limit@18|))) |g@26|) (|Inv@L0| |count@17| 0 |n@21| |count@17|)))) +; t1: back edge, invariant +(assert (forall ((|this@1| Int) (|msg.sender@2| Int) (|msg.value@3| Int) (|block.timestamp@4| Int) (|block.number@5| Int) (|block.chainid@6| Int) (|tx.origin@7| Int) (|tx.gasprice@8| Int) (|msg.sig@9| Int) (|msg.data@10| Int) (|block.basefee@11| Int) (|block.blobbasefee@12| Int) (|block.coinbase@13| Int) (|block.prevrandao@14| Int) (|block.difficulty@15| Int) (|block.gaslimit@16| Int) (|count@17| Int) (|limit@18| Int) (|__balance@19| (Array Int Int)) (|__code_epoch@20| Int) (|n@21| Int) (|g@22| Bool) (|g@23| Bool) (|arith@24| Int) (|g@25| Bool) (|g@26| Bool) (|count@27| Int) (|i@28| Int) (|g@29| Bool) (|g@30| Bool) (|arith@31| Int) (|g@32| Bool) (|arith@33| Int) (|g@34| Bool)) (=> (and (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)) (not (= |this@1| 0)) (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)) (not (= |msg.sender@2| 0)) (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)) (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)) (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)) (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (= |g@22| (and true (<= |count@17| |limit@18|))) (= |g@23| (and |g@22| (= |msg.value@3| 0))) (= |arith@24| (+ |count@17| |n@21|)) (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))) (= |g@26| (and |g@25| (<= |arith@24| |limit@18|))) (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (= |g@29| |g@26|) (|Inv@L0| |count@27| |i@28| |n@21| |count@17|) (= |g@30| (and |g@29| (< |i@28| |n@21|))) (= |arith@31| (+ |count@27| 1)) (= |g@32| (and |g@30| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))) (= |arith@33| (+ |i@28| 1)) (= |g@34| (and |g@32| (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))) |g@34|) (|Inv@L0| |arith@31| |arith@33| |n@21| |count@17|)))) +; t3: exit edge, path +(assert (forall ((|this@1| Int) (|msg.sender@2| Int) (|msg.value@3| Int) (|block.timestamp@4| Int) (|block.number@5| Int) (|block.chainid@6| Int) (|tx.origin@7| Int) (|tx.gasprice@8| Int) (|msg.sig@9| Int) (|msg.data@10| Int) (|block.basefee@11| Int) (|block.blobbasefee@12| Int) (|block.coinbase@13| Int) (|block.prevrandao@14| Int) (|block.difficulty@15| Int) (|block.gaslimit@16| Int) (|count@17| Int) (|limit@18| Int) (|__balance@19| (Array Int Int)) (|__code_epoch@20| Int) (|n@21| Int) (|g@22| Bool) (|g@23| Bool) (|arith@24| Int) (|g@25| Bool) (|g@26| Bool) (|count@27| Int) (|i@28| Int) (|g@29| Bool) (|g@30| Bool) (|arith@31| Int) (|g@32| Bool) (|arith@33| Int) (|g@34| Bool) (|g@35| Bool)) (=> (and (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)) (not (= |this@1| 0)) (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)) (not (= |msg.sender@2| 0)) (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)) (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)) (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)) (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (= |g@22| (and true (<= |count@17| |limit@18|))) (= |g@23| (and |g@22| (= |msg.value@3| 0))) (= |arith@24| (+ |count@17| |n@21|)) (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))) (= |g@26| (and |g@25| (<= |arith@24| |limit@18|))) (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (= |g@29| |g@26|) (|Inv@L0| |count@27| |i@28| |n@21| |count@17|) (= |g@30| (and |g@29| (< |i@28| |n@21|))) (= |arith@31| (+ |count@27| 1)) (= |g@32| (and |g@30| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))) (= |arith@33| (+ |i@28| 1)) (= |g@34| (and |g@32| (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))) (= |g@35| (and |g@29| (not (< |i@28| |n@21|)))) |g@35| (not (= |count@27| (+ |count@17| |n@21|)))) false))) +; t4: exit edge, path +(assert (forall ((|this@1| Int) (|msg.sender@2| Int) (|msg.value@3| Int) (|block.timestamp@4| Int) (|block.number@5| Int) (|block.chainid@6| Int) (|tx.origin@7| Int) (|tx.gasprice@8| Int) (|msg.sig@9| Int) (|msg.data@10| Int) (|block.basefee@11| Int) (|block.blobbasefee@12| Int) (|block.coinbase@13| Int) (|block.prevrandao@14| Int) (|block.difficulty@15| Int) (|block.gaslimit@16| Int) (|count@17| Int) (|limit@18| Int) (|__balance@19| (Array Int Int)) (|__code_epoch@20| Int) (|n@21| Int) (|g@22| Bool) (|g@23| Bool) (|arith@24| Int) (|g@25| Bool) (|g@26| Bool) (|count@27| Int) (|i@28| Int) (|g@29| Bool) (|g@30| Bool) (|arith@31| Int) (|g@32| Bool) (|arith@33| Int) (|g@34| Bool) (|g@35| Bool)) (=> (and (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)) (not (= |this@1| 0)) (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)) (not (= |msg.sender@2| 0)) (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)) (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)) (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)) (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (= |g@22| (and true (<= |count@17| |limit@18|))) (= |g@23| (and |g@22| (= |msg.value@3| 0))) (= |arith@24| (+ |count@17| |n@21|)) (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))) (= |g@26| (and |g@25| (<= |arith@24| |limit@18|))) (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (= |g@29| |g@26|) (|Inv@L0| |count@27| |i@28| |n@21| |count@17|) (= |g@30| (and |g@29| (< |i@28| |n@21|))) (= |arith@31| (+ |count@27| 1)) (= |g@32| (and |g@30| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))) (= |arith@33| (+ |i@28| 1)) (= |g@34| (and |g@32| (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))) (= |g@35| (and |g@29| (not (< |i@28| |n@21|)))) |g@35| (not (<= |count@27| |limit@18|))) false))) +; r0: revert path leaving the entry +(assert (forall ((|this@1| Int) (|msg.sender@2| Int) (|msg.value@3| Int) (|block.timestamp@4| Int) (|block.number@5| Int) (|block.chainid@6| Int) (|tx.origin@7| Int) (|tx.gasprice@8| Int) (|msg.sig@9| Int) (|msg.data@10| Int) (|block.basefee@11| Int) (|block.blobbasefee@12| Int) (|block.coinbase@13| Int) (|block.prevrandao@14| Int) (|block.difficulty@15| Int) (|block.gaslimit@16| Int) (|count@17| Int) (|limit@18| Int) (|__balance@19| (Array Int Int)) (|__code_epoch@20| Int) (|n@21| Int) (|g@22| Bool) (|g@23| Bool) (|arith@24| Int)) (=> (and (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)) (not (= |this@1| 0)) (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)) (not (= |msg.sender@2| 0)) (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)) (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)) (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)) (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (= |g@22| (and true (<= |count@17| |limit@18|))) (= |g@23| (and |g@22| (= |msg.value@3| 0))) (= |arith@24| (+ |count@17| |n@21|)) (and |g@23| (not (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) |Reverted|))) +; r1: revert path leaving the entry +(assert (forall ((|this@1| Int) (|msg.sender@2| Int) (|msg.value@3| Int) (|block.timestamp@4| Int) (|block.number@5| Int) (|block.chainid@6| Int) (|tx.origin@7| Int) (|tx.gasprice@8| Int) (|msg.sig@9| Int) (|msg.data@10| Int) (|block.basefee@11| Int) (|block.blobbasefee@12| Int) (|block.coinbase@13| Int) (|block.prevrandao@14| Int) (|block.difficulty@15| Int) (|block.gaslimit@16| Int) (|count@17| Int) (|limit@18| Int) (|__balance@19| (Array Int Int)) (|__code_epoch@20| Int) (|n@21| Int) (|g@22| Bool) (|g@23| Bool) (|arith@24| Int) (|g@25| Bool)) (=> (and (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)) (not (= |this@1| 0)) (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)) (not (= |msg.sender@2| 0)) (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)) (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)) (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)) (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (= |g@22| (and true (<= |count@17| |limit@18|))) (= |g@23| (and |g@22| (= |msg.value@3| 0))) (= |arith@24| (+ |count@17| |n@21|)) (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))) (and |g@25| (not (<= |arith@24| |limit@18|)))) |Reverted|))) +; r2: revert path leaving the body +(assert (forall ((|this@1| Int) (|msg.sender@2| Int) (|msg.value@3| Int) (|block.timestamp@4| Int) (|block.number@5| Int) (|block.chainid@6| Int) (|tx.origin@7| Int) (|tx.gasprice@8| Int) (|msg.sig@9| Int) (|msg.data@10| Int) (|block.basefee@11| Int) (|block.blobbasefee@12| Int) (|block.coinbase@13| Int) (|block.prevrandao@14| Int) (|block.difficulty@15| Int) (|block.gaslimit@16| Int) (|count@17| Int) (|limit@18| Int) (|__balance@19| (Array Int Int)) (|__code_epoch@20| Int) (|n@21| Int) (|g@22| Bool) (|g@23| Bool) (|arith@24| Int) (|g@25| Bool) (|g@26| Bool) (|count@27| Int) (|i@28| Int) (|g@29| Bool) (|g@30| Bool) (|arith@31| Int)) (=> (and (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)) (not (= |this@1| 0)) (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)) (not (= |msg.sender@2| 0)) (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)) (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)) (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)) (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (= |g@22| (and true (<= |count@17| |limit@18|))) (= |g@23| (and |g@22| (= |msg.value@3| 0))) (= |arith@24| (+ |count@17| |n@21|)) (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))) (= |g@26| (and |g@25| (<= |arith@24| |limit@18|))) (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (= |g@29| |g@26|) (|Inv@L0| |count@27| |i@28| |n@21| |count@17|) (= |g@30| (and |g@29| (< |i@28| |n@21|))) (= |arith@31| (+ |count@27| 1)) (and |g@30| (not (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) |Reverted|))) +; r3: revert path leaving the body +(assert (forall ((|this@1| Int) (|msg.sender@2| Int) (|msg.value@3| Int) (|block.timestamp@4| Int) (|block.number@5| Int) (|block.chainid@6| Int) (|tx.origin@7| Int) (|tx.gasprice@8| Int) (|msg.sig@9| Int) (|msg.data@10| Int) (|block.basefee@11| Int) (|block.blobbasefee@12| Int) (|block.coinbase@13| Int) (|block.prevrandao@14| Int) (|block.difficulty@15| Int) (|block.gaslimit@16| Int) (|count@17| Int) (|limit@18| Int) (|__balance@19| (Array Int Int)) (|__code_epoch@20| Int) (|n@21| Int) (|g@22| Bool) (|g@23| Bool) (|arith@24| Int) (|g@25| Bool) (|g@26| Bool) (|count@27| Int) (|i@28| Int) (|g@29| Bool) (|g@30| Bool) (|arith@31| Int) (|g@32| Bool) (|arith@33| Int)) (=> (and (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975)) (not (= |this@1| 0)) (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975)) (not (= |msg.sender@2| 0)) (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975)) (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295)) (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975)) (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (= |g@22| (and true (<= |count@17| |limit@18|))) (= |g@23| (and |g@22| (= |msg.value@3| 0))) (= |arith@24| (+ |count@17| |n@21|)) (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))) (= |g@26| (and |g@25| (<= |arith@24| |limit@18|))) (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935)) (= |g@29| |g@26|) (|Inv@L0| |count@27| |i@28| |n@21| |count@17|) (= |g@30| (and |g@29| (< |i@28| |n@21|))) (= |arith@31| (+ |count@27| 1)) (= |g@32| (and |g@30| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935)))) (= |arith@33| (+ |i@28| 1)) (and |g@32| (not (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) |Reverted|))) +(check-sat) diff --git a/Verify/Infer/loopvc/solar/Counter/bump.lean b/Verify/Infer/loopvc/solar/Counter/bump.lean new file mode 100644 index 00000000..452bb31f --- /dev/null +++ b/Verify/Infer/loopvc/solar/Counter/bump.lean @@ -0,0 +1,142 @@ +-- Generated by solar-verify --emit-lean (format 2); do not edit. +import Verify.Obligation + +set_option maxRecDepth 100000 + +namespace SolarVerifyVc.Counter.bump +open SolarVerify.Smt SolarVerify.Vc + +/-- Script 0 of Counter.bump: the solver's assertion stack. -/ +def script0 : Script where + decls := [ + ⟨"|this@1|", [], .int⟩, + ⟨"|msg.sender@2|", [], .int⟩, + ⟨"|msg.value@3|", [], .int⟩, + ⟨"|block.timestamp@4|", [], .int⟩, + ⟨"|block.number@5|", [], .int⟩, + ⟨"|block.chainid@6|", [], .int⟩, + ⟨"|tx.origin@7|", [], .int⟩, + ⟨"|tx.gasprice@8|", [], .int⟩, + ⟨"|msg.sig@9|", [], .int⟩, + ⟨"|msg.data@10|", [], .int⟩, + ⟨"|block.basefee@11|", [], .int⟩, + ⟨"|block.blobbasefee@12|", [], .int⟩, + ⟨"|block.coinbase@13|", [], .int⟩, + ⟨"|block.prevrandao@14|", [], .int⟩, + ⟨"|block.difficulty@15|", [], .int⟩, + ⟨"|block.gaslimit@16|", [], .int⟩, + ⟨"|count@17|", [], .int⟩, + ⟨"|limit@18|", [], .int⟩, + ⟨"|__balance@19|", [], (.array .int .int)⟩, + ⟨"|__code_epoch@20|", [], .int⟩, + ⟨"|n@21|", [], .int⟩, + ⟨"|g@22|", [], .bool⟩, + ⟨"|g@23|", [], .bool⟩, + ⟨"|arith@24|", [], .int⟩, + ⟨"|g@25|", [], .bool⟩, + ⟨"|g@26|", [], .bool⟩, + ⟨"|count@27|", [], .int⟩, + ⟨"|i@28|", [], .int⟩, + ⟨"|g@29|", [], .bool⟩, + ⟨"|g@30|", [], .bool⟩, + ⟨"|arith@31|", [], .int⟩, + ⟨"|g@32|", [], .bool⟩, + ⟨"|arith@33|", [], .int⟩, + ⟨"|g@34|", [], .bool⟩, + ⟨"|g@35|", [], .bool⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 0 [], .int 0]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 16 []], .app .le [.fn 16 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 19 []], .app .le [.fn 19 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 20 []], .app .le [.fn 20 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 21 [], .app .and [.bool true, .app .le [.fn 16 [], .fn 17 []]]], + .app .eq [.fn 22 [], .app .and [.fn 21 [], .app .eq [.fn 2 [], .int 0]]], + .app .eq [.fn 23 [], .app .add [.fn 16 [], .fn 20 []]], + .app .eq [.fn 24 [], .app .and [.fn 22 [], .app .and [.app .le [.int 0, .fn 23 []], .app .le [.fn 23 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 25 [], .app .and [.fn 24 [], .app .le [.fn 23 [], .fn 17 []]]], + .app .and [.app .le [.int 0, .fn 26 []], .app .le [.fn 26 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 27 []], .app .le [.fn 27 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 28 [], .app .and [.fn 25 [], .app .and [.app .le [.fn 27 [], .fn 20 []], .app .eq [.fn 26 [], .app .add [.fn 16 [], .fn 27 []]]]]], + .app .eq [.fn 29 [], .app .and [.fn 28 [], .app .lt [.fn 27 [], .fn 20 []]]], + .app .eq [.fn 30 [], .app .add [.fn 26 [], .int 1]], + .app .eq [.fn 31 [], .app .and [.fn 29 [], .app .and [.app .le [.int 0, .fn 30 []], .app .le [.fn 30 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 32 [], .app .add [.fn 27 [], .int 1]], + .app .eq [.fn 33 [], .app .and [.fn 31 [], .app .and [.app .le [.int 0, .fn 32 []], .app .le [.fn 32 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 34 [], .app .and [.fn 28 [], .app .not [.app .lt [.fn 27 [], .fn 20 []]]]] + ] + +/-- Counter.bump#0: loop invariant not satisfied on entry: `i <= n` (unsat). -/ +def ob0 : Obligation where + script := script0 + upto := 26 + guard := .fn 25 [] + goal := .app .le [.int 0, .fn 20 []] + +/-- Counter.bump#1: loop invariant not satisfied on entry: `count == old(count) + i` (unsat). -/ +def ob1 : Obligation where + script := script0 + upto := 26 + guard := .fn 25 [] + goal := .app .eq [.fn 16 [], .app .add [.fn 16 [], .int 0]] + +/-- Counter.bump#2: loop invariant not preserved by the loop body: `i <= n` (unsat). -/ +def ob2 : Obligation where + script := script0 + upto := 34 + guard := .fn 33 [] + goal := .app .le [.fn 32 [], .fn 20 []] + +/-- Counter.bump#3: loop invariant not preserved by the loop body: `count == old(count) + i` (unsat). -/ +def ob3 : Obligation where + script := script0 + upto := 34 + guard := .fn 33 [] + goal := .app .eq [.fn 30 [], .app .add [.fn 16 [], .fn 32 []]] + +/-- Counter.bump#4: loop does not terminate: decreases clause not decreased: `n - i` (unsat). -/ +def ob4 : Obligation where + script := script0 + upto := 34 + guard := .fn 33 [] + goal := .app .and [.app .le [.int 0, .app .sub [.fn 20 [], .fn 27 []]], .app .lt [.app .sub [.fn 20 [], .fn 32 []], .app .sub [.fn 20 [], .fn 27 []]]] + +/-- Counter.bump#5: a query only a warning reads (sat). -/ +def ob5 : Obligation where + script := script0 + upto := 35 + guard := .fn 34 [] + goal := .bool false + +/-- Counter.bump#6: postcondition not satisfied: `count == old(count) + n` (unsat). -/ +def ob6 : Obligation where + script := script0 + upto := 35 + guard := .fn 34 [] + goal := .app .eq [.fn 26 [], .app .add [.fn 16 [], .fn 20 []]] + +/-- Counter.bump#7: contract invariant not preserved: `count <= limit` (unsat). -/ +def ob7 : Obligation where + script := script0 + upto := 35 + guard := .fn 34 [] + goal := .app .le [.fn 26 [], .fn 17 []] + +end SolarVerifyVc.Counter.bump diff --git a/Verify/Infer/loopvc/solar/Counter/bump.loopvc.json b/Verify/Infer/loopvc/solar/Counter/bump.loopvc.json new file mode 100644 index 00000000..cdce2e8a --- /dev/null +++ b/Verify/Infer/loopvc/solar/Counter/bump.loopvc.json @@ -0,0 +1,405 @@ +{ + "candidate": { + "conjuncts": [ + { + "origin": "annotation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23 + }, + "term": "(<= |i@28| |n@21|)", + "text": "i <= n" + }, + { + "origin": "annotation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 24 + }, + "term": "(= |count@27| (+ |count@17| |i@28|))", + "text": "count == old(count) + i" + } + ], + "head_assumption": "(assert (= |g@29| (and |g@26| (and (<= |i@28| |n@21|) (= |count@27| (+ |count@17| |i@28|))))))", + "rank": { + "origin": "annotation", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 25 + }, + "term": "(- |n@21| |i@28|)", + "text": "n - i" + } + }, + "cut": { + "head": { + "command": 57, + "guard_after": "|g@29|", + "guard_before": "|g@26|", + "script": 0, + "template": "(assert (= |g@29| (and |g@26| (|Inv@L0| |count@27| |i@28| |n@21| |count@17|))))" + }, + "id": "L0", + "loop": "for", + "params": [ + { + "back": "|arith@31|", + "entry": "|count@17|", + "lean_symbol": 26, + "name": "count", + "role": "loop", + "sort": "Int", + "symbol": "|count@27|" + }, + { + "back": "|arith@33|", + "entry": "0", + "lean_symbol": 27, + "name": "i", + "role": "loop", + "sort": "Int", + "symbol": "|i@28|" + }, + { + "back": "|n@21|", + "entry": "|n@21|", + "lean_symbol": 20, + "name": "n", + "role": "read", + "sort": "Int", + "symbol": "|n@21|" + }, + { + "back": "|count@17|", + "entry": "|count@17|", + "lean_symbol": 16, + "name": "old(count)", + "role": "old", + "sort": "Int", + "symbol": "|count@17|" + } + ], + "predicate": "|Inv@L0|", + "rank": "|Rank@L0|", + "site": { + "column": 9, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 26 + } + }, + "cutpoints": [ + { + "id": "pre", + "kind": "function entry" + }, + { + "id": "L0", + "kind": "loop head", + "site": { + "column": 9, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 26 + } + }, + { + "id": "return", + "kind": "function exit", + "outcome": "normal" + }, + { + "id": "revert", + "kind": "function exit", + "outcome": "revert" + } + ], + "edges": [ + { + "from": "pre", + "id": "entry", + "outcome": null, + "templates": [ + "t0" + ], + "to": "L0" + }, + { + "from": "L0", + "id": "back", + "outcome": null, + "templates": [ + "t1", + "t2" + ], + "to": "L0" + }, + { + "from": "L0", + "id": "exit", + "outcome": "normal", + "templates": [ + "t3", + "t4" + ], + "to": "return" + }, + { + "from": [ + "pre", + "L0" + ], + "id": "revert", + "outcome": "revert", + "paths": [ + "r0", + "r1", + "r2", + "r3" + ], + "to": "revert" + }, + { + "from": "L0", + "id": "call", + "outcome": null, + "templates": [], + "to": "L0" + } + ], + "format": "solar-verify-loopvc", + "horn": { + "file": "Counter/bump.horn.smt2", + "sha256": "88f69aaad5735250f8e4c8f3fd2d6c1dd94603c9cec4c92ff797ef62d8c3fe54" + }, + "lean": { + "library": "LoopVc.lean", + "library_sha256": "8b5f650e16a217b5b843f8ca623a22f6c0dc6c0afc44e07251fac2559d4b2e82", + "module": "Counter/bump_loopvc.lean", + "namespace": "SolarVerifyLoopVc.Counter.bump" + }, + "obligations": { + "module": "Counter/bump.lean", + "namespace": "SolarVerifyVc.Counter.bump" + }, + "reverts": [ + { + "asserts": 24, + "commands": 48, + "from": "entry", + "guard": "(and |g@23| (not (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))", + "id": "r0", + "script": 0 + }, + { + "asserts": 25, + "commands": 50, + "from": "entry", + "guard": "(and |g@25| (not (<= |arith@24| |limit@18|)))", + "id": "r1", + "script": 0 + }, + { + "asserts": 31, + "commands": 62, + "from": "body", + "guard": "(and |g@30| (not (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))", + "id": "r2", + "script": 0 + }, + { + "asserts": 33, + "commands": 66, + "from": "body", + "guard": "(and |g@32| (not (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))", + "id": "r3", + "script": 0 + } + ], + "sha256": { + "candidate": "28f8c82ca4326f6c8bfef6c8ea3e0185ae769bfaf1992ef547ab9c5f6f84720f", + "formulas": "f8b5887986ea82259e3bc90c12abea85773dc969a7d8788af39535ec590e2de2" + }, + "templates": [ + { + "asserts": 26, + "commands": 52, + "edge": "entry", + "goal": "(|Inv@L0| |count@17| 0 |n@21| |count@17|)", + "guard": "|g@26|", + "id": "t0", + "instances": [ + { + "id": "Counter.bump#0", + "kind": "loop invariant not satisfied on entry", + "lean": "SolarVerifyVc.Counter.bump.ob0", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23 + }, + "spec": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23, + "text": "i <= n" + } + }, + { + "id": "Counter.bump#1", + "kind": "loop invariant not satisfied on entry", + "lean": "SolarVerifyVc.Counter.bump.ob1", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 24 + }, + "spec": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 24, + "text": "count == old(count) + i" + } + } + ], + "lean": "SolarVerifyLoopVc.Counter.bump.t0", + "role": "invariant", + "script": 0 + }, + { + "asserts": 34, + "commands": 68, + "edge": "back", + "goal": "(|Inv@L0| |arith@31| |arith@33| |n@21| |count@17|)", + "guard": "|g@34|", + "id": "t1", + "instances": [ + { + "id": "Counter.bump#2", + "kind": "loop invariant not preserved by the loop body", + "lean": "SolarVerifyVc.Counter.bump.ob2", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23 + }, + "spec": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 23, + "text": "i <= n" + } + }, + { + "id": "Counter.bump#3", + "kind": "loop invariant not preserved by the loop body", + "lean": "SolarVerifyVc.Counter.bump.ob3", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 24 + }, + "spec": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 24, + "text": "count == old(count) + i" + } + } + ], + "lean": "SolarVerifyLoopVc.Counter.bump.t1", + "role": "invariant", + "script": 0 + }, + { + "asserts": 34, + "commands": 68, + "edge": "back", + "goal": "(and (<= 0 (|Rank@L0| |count@27| |i@28| |n@21| |count@17|)) (< (|Rank@L0| |arith@31| |arith@33| |n@21| |count@17|) (|Rank@L0| |count@27| |i@28| |n@21| |count@17|)))", + "guard": "|g@34|", + "id": "t2", + "instances": [ + { + "id": "Counter.bump#4", + "kind": "loop does not terminate: decreases clause not decreased", + "lean": "SolarVerifyVc.Counter.bump.ob4", + "site": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 25 + }, + "spec": { + "column": 14, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 25, + "text": "n - i" + } + } + ], + "lean": "SolarVerifyLoopVc.Counter.bump.t2", + "role": "rank", + "script": 0 + }, + { + "asserts": 35, + "commands": 70, + "edge": "exit", + "goal": "(= |count@27| (+ |count@17| |n@21|))", + "guard": "|g@35|", + "id": "t3", + "instances": [ + { + "id": "Counter.bump#6", + "kind": "postcondition not satisfied", + "lean": "SolarVerifyVc.Counter.bump.ob6", + "site": { + "column": 10, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 20 + }, + "spec": { + "column": 10, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 20, + "text": "count == old(count) + n" + } + } + ], + "lean": "SolarVerifyLoopVc.Counter.bump.t3", + "role": "path", + "script": 0 + }, + { + "asserts": 35, + "commands": 70, + "edge": "exit", + "goal": "(<= |count@27| |limit@18|)", + "guard": "|g@35|", + "id": "t4", + "instances": [ + { + "id": "Counter.bump#7", + "kind": "contract invariant not preserved", + "lean": "SolarVerifyVc.Counter.bump.ob7", + "site": { + "column": 5, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 21 + }, + "spec": { + "column": 6, + "file": "Certified/verify_counter/verify_counter.sol", + "line": 4, + "text": "count <= limit" + } + } + ], + "lean": "SolarVerifyLoopVc.Counter.bump.t4", + "role": "path", + "script": 0 + } + ], + "unit": "Counter.bump", + "version": 1 +} diff --git a/Verify/Infer/loopvc/solar/Counter/bump.script0.smt2 b/Verify/Infer/loopvc/solar/Counter/bump.script0.smt2 new file mode 100644 index 00000000..06ebf7de --- /dev/null +++ b/Verify/Infer/loopvc/solar/Counter/bump.script0.smt2 @@ -0,0 +1,70 @@ +(declare-const |this@1| Int) +(assert (and (<= 0 |this@1|) (<= |this@1| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |this@1| 0))) +(declare-const |msg.sender@2| Int) +(assert (and (<= 0 |msg.sender@2|) (<= |msg.sender@2| 1461501637330902918203684832716283019655932542975))) +(assert (not (= |msg.sender@2| 0))) +(declare-const |msg.value@3| Int) +(assert (and (<= 0 |msg.value@3|) (<= |msg.value@3| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.timestamp@4| Int) +(assert (and (<= 0 |block.timestamp@4|) (<= |block.timestamp@4| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.number@5| Int) +(assert (and (<= 0 |block.number@5|) (<= |block.number@5| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.chainid@6| Int) +(assert (and (<= 0 |block.chainid@6|) (<= |block.chainid@6| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |tx.origin@7| Int) +(assert (and (<= 0 |tx.origin@7|) (<= |tx.origin@7| 1461501637330902918203684832716283019655932542975))) +(declare-const |tx.gasprice@8| Int) +(assert (and (<= 0 |tx.gasprice@8|) (<= |tx.gasprice@8| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |msg.sig@9| Int) +(assert (and (<= 0 |msg.sig@9|) (<= |msg.sig@9| 4294967295))) +(declare-const |msg.data@10| Int) +(declare-const |block.basefee@11| Int) +(assert (and (<= 0 |block.basefee@11|) (<= |block.basefee@11| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.blobbasefee@12| Int) +(assert (and (<= 0 |block.blobbasefee@12|) (<= |block.blobbasefee@12| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.coinbase@13| Int) +(assert (and (<= 0 |block.coinbase@13|) (<= |block.coinbase@13| 1461501637330902918203684832716283019655932542975))) +(declare-const |block.prevrandao@14| Int) +(assert (and (<= 0 |block.prevrandao@14|) (<= |block.prevrandao@14| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.difficulty@15| Int) +(assert (and (<= 0 |block.difficulty@15|) (<= |block.difficulty@15| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |block.gaslimit@16| Int) +(assert (and (<= 0 |block.gaslimit@16|) (<= |block.gaslimit@16| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |count@17| Int) +(assert (and (<= 0 |count@17|) (<= |count@17| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |limit@18| Int) +(assert (and (<= 0 |limit@18|) (<= |limit@18| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |__balance@19| (Array Int Int)) +(declare-const |__code_epoch@20| Int) +(assert (and (<= 0 |__code_epoch@20|) (<= |__code_epoch@20| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |n@21| Int) +(assert (and (<= 0 |n@21|) (<= |n@21| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@22| Bool) +(assert (= |g@22| (and true (<= |count@17| |limit@18|)))) +(declare-const |g@23| Bool) +(assert (= |g@23| (and |g@22| (= |msg.value@3| 0)))) +(declare-const |arith@24| Int) +(assert (= |arith@24| (+ |count@17| |n@21|))) +(declare-const |g@25| Bool) +(assert (= |g@25| (and |g@23| (and (<= 0 |arith@24|) (<= |arith@24| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@26| Bool) +(assert (= |g@26| (and |g@25| (<= |arith@24| |limit@18|)))) +(declare-const |count@27| Int) +(assert (and (<= 0 |count@27|) (<= |count@27| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |i@28| Int) +(assert (and (<= 0 |i@28|) (<= |i@28| 115792089237316195423570985008687907853269984665640564039457584007913129639935))) +(declare-const |g@29| Bool) +(assert (= |g@29| (and |g@26| (and (<= |i@28| |n@21|) (= |count@27| (+ |count@17| |i@28|)))))) +(declare-const |g@30| Bool) +(assert (= |g@30| (and |g@29| (< |i@28| |n@21|)))) +(declare-const |arith@31| Int) +(assert (= |arith@31| (+ |count@27| 1))) +(declare-const |g@32| Bool) +(assert (= |g@32| (and |g@30| (and (<= 0 |arith@31|) (<= |arith@31| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |arith@33| Int) +(assert (= |arith@33| (+ |i@28| 1))) +(declare-const |g@34| Bool) +(assert (= |g@34| (and |g@32| (and (<= 0 |arith@33|) (<= |arith@33| 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) +(declare-const |g@35| Bool) +(assert (= |g@35| (and |g@29| (not (< |i@28| |n@21|))))) diff --git a/Verify/Infer/loopvc/solar/Counter/bump_loopvc.lean b/Verify/Infer/loopvc/solar/Counter/bump_loopvc.lean new file mode 100644 index 00000000..c8bd62e8 --- /dev/null +++ b/Verify/Infer/loopvc/solar/Counter/bump_loopvc.lean @@ -0,0 +1,166 @@ +-- Generated by solar-verify --emit-loopvc (format 1); do not edit. +import LoopVc +import Counter.bump + +set_option maxRecDepth 100000 + +namespace SolarVerifyLoopVc.Counter.bump +open SolarVerify.Smt SolarVerify.Vc SolarVerify.LoopVc + +/-- Script 0 of Counter.bump with the cut's candidate abstracted: |Inv@L0| in the head assumption, and the cut's symbols declared last. -/ +def tscript0 : Script where + decls := [ + ⟨"|this@1|", [], .int⟩, + ⟨"|msg.sender@2|", [], .int⟩, + ⟨"|msg.value@3|", [], .int⟩, + ⟨"|block.timestamp@4|", [], .int⟩, + ⟨"|block.number@5|", [], .int⟩, + ⟨"|block.chainid@6|", [], .int⟩, + ⟨"|tx.origin@7|", [], .int⟩, + ⟨"|tx.gasprice@8|", [], .int⟩, + ⟨"|msg.sig@9|", [], .int⟩, + ⟨"|msg.data@10|", [], .int⟩, + ⟨"|block.basefee@11|", [], .int⟩, + ⟨"|block.blobbasefee@12|", [], .int⟩, + ⟨"|block.coinbase@13|", [], .int⟩, + ⟨"|block.prevrandao@14|", [], .int⟩, + ⟨"|block.difficulty@15|", [], .int⟩, + ⟨"|block.gaslimit@16|", [], .int⟩, + ⟨"|count@17|", [], .int⟩, + ⟨"|limit@18|", [], .int⟩, + ⟨"|__balance@19|", [], (.array .int .int)⟩, + ⟨"|__code_epoch@20|", [], .int⟩, + ⟨"|n@21|", [], .int⟩, + ⟨"|g@22|", [], .bool⟩, + ⟨"|g@23|", [], .bool⟩, + ⟨"|arith@24|", [], .int⟩, + ⟨"|g@25|", [], .bool⟩, + ⟨"|g@26|", [], .bool⟩, + ⟨"|count@27|", [], .int⟩, + ⟨"|i@28|", [], .int⟩, + ⟨"|g@29|", [], .bool⟩, + ⟨"|g@30|", [], .bool⟩, + ⟨"|arith@31|", [], .int⟩, + ⟨"|g@32|", [], .bool⟩, + ⟨"|arith@33|", [], .int⟩, + ⟨"|g@34|", [], .bool⟩, + ⟨"|g@35|", [], .bool⟩, + ⟨"|Inv@L0|", [.int, .int, .int, .int], .bool⟩, + ⟨"|Rank@L0|", [.int, .int, .int, .int], .int⟩ + ] + asserts := [ + .app .and [.app .le [.int 0, .fn 0 []], .app .le [.fn 0 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 0 [], .int 0]], + .app .and [.app .le [.int 0, .fn 1 []], .app .le [.fn 1 [], .int 1461501637330902918203684832716283019655932542975]], + .app .not [.app .eq [.fn 1 [], .int 0]], + .app .and [.app .le [.int 0, .fn 2 []], .app .le [.fn 2 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 3 []], .app .le [.fn 3 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 4 []], .app .le [.fn 4 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 5 []], .app .le [.fn 5 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 6 []], .app .le [.fn 6 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 7 []], .app .le [.fn 7 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 8 []], .app .le [.fn 8 [], .int 4294967295]], + .app .and [.app .le [.int 0, .fn 10 []], .app .le [.fn 10 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 11 []], .app .le [.fn 11 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 12 []], .app .le [.fn 12 [], .int 1461501637330902918203684832716283019655932542975]], + .app .and [.app .le [.int 0, .fn 13 []], .app .le [.fn 13 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 14 []], .app .le [.fn 14 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 15 []], .app .le [.fn 15 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 16 []], .app .le [.fn 16 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 17 []], .app .le [.fn 17 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 19 []], .app .le [.fn 19 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 20 []], .app .le [.fn 20 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 21 [], .app .and [.bool true, .app .le [.fn 16 [], .fn 17 []]]], + .app .eq [.fn 22 [], .app .and [.fn 21 [], .app .eq [.fn 2 [], .int 0]]], + .app .eq [.fn 23 [], .app .add [.fn 16 [], .fn 20 []]], + .app .eq [.fn 24 [], .app .and [.fn 22 [], .app .and [.app .le [.int 0, .fn 23 []], .app .le [.fn 23 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 25 [], .app .and [.fn 24 [], .app .le [.fn 23 [], .fn 17 []]]], + .app .and [.app .le [.int 0, .fn 26 []], .app .le [.fn 26 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .and [.app .le [.int 0, .fn 27 []], .app .le [.fn 27 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]], + .app .eq [.fn 28 [], .app .and [.fn 25 [], .fn 35 [.fn 26 [], .fn 27 [], .fn 20 [], .fn 16 []]]], + .app .eq [.fn 29 [], .app .and [.fn 28 [], .app .lt [.fn 27 [], .fn 20 []]]], + .app .eq [.fn 30 [], .app .add [.fn 26 [], .int 1]], + .app .eq [.fn 31 [], .app .and [.fn 29 [], .app .and [.app .le [.int 0, .fn 30 []], .app .le [.fn 30 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 32 [], .app .add [.fn 27 [], .int 1]], + .app .eq [.fn 33 [], .app .and [.fn 31 [], .app .and [.app .le [.int 0, .fn 32 []], .app .le [.fn 32 [], .int 115792089237316195423570985008687907853269984665640564039457584007913129639935]]]], + .app .eq [.fn 34 [], .app .and [.fn 28 [], .app .not [.app .lt [.fn 27 [], .fn 20 []]]]] + ] + +/-- The cut: the constants the candidate ranges over, in the order of |Inv@L0|'s arguments. -/ +def cut : Cut where + params := [26, 27, 20, 16] + +/-- The candidate of the run. -/ +def cand : Cand where + conj := [ + .app .le [.fn 27 [], .fn 20 []], + .app .eq [.fn 26 [], .app .add [.fn 16 [], .fn 27 []]] + ] + rank := some (.app .sub [.fn 20 [], .fn 27 []]) + +/-- Template 0: entry edge, invariant. -/ +def t0 : Template where + script := tscript0 + base := 35 + upto := 26 + guard := .fn 25 [] + goal := .fn 35 [.fn 16 [], .int 0, .fn 20 [], .fn 16 []] + +theorem t0_exact : t0.instances cut cand = [SolarVerifyVc.Counter.bump.ob0, SolarVerifyVc.Counter.bump.ob1] := rfl + +theorem t0_valid : t0.Valid cut cand ↔ ∀ o ∈ [SolarVerifyVc.Counter.bump.ob0, SolarVerifyVc.Counter.bump.ob1], o.Valid := + Template.valid_iff t0_exact + +/-- Template 1: back edge, invariant. -/ +def t1 : Template where + script := tscript0 + base := 35 + upto := 34 + guard := .fn 33 [] + goal := .fn 35 [.fn 30 [], .fn 32 [], .fn 20 [], .fn 16 []] + +theorem t1_exact : t1.instances cut cand = [SolarVerifyVc.Counter.bump.ob2, SolarVerifyVc.Counter.bump.ob3] := rfl + +theorem t1_valid : t1.Valid cut cand ↔ ∀ o ∈ [SolarVerifyVc.Counter.bump.ob2, SolarVerifyVc.Counter.bump.ob3], o.Valid := + Template.valid_iff t1_exact + +/-- Template 2: back edge, rank. -/ +def t2 : Template where + script := tscript0 + base := 35 + upto := 34 + guard := .fn 33 [] + goal := .app .and [.app .le [.int 0, .fn 36 [.fn 26 [], .fn 27 [], .fn 20 [], .fn 16 []]], .app .lt [.fn 36 [.fn 30 [], .fn 32 [], .fn 20 [], .fn 16 []], .fn 36 [.fn 26 [], .fn 27 [], .fn 20 [], .fn 16 []]]] + +theorem t2_exact : t2.instances cut cand = [SolarVerifyVc.Counter.bump.ob4] := rfl + +theorem t2_valid : t2.Valid cut cand ↔ ∀ o ∈ [SolarVerifyVc.Counter.bump.ob4], o.Valid := + Template.valid_iff t2_exact + +/-- Template 3: exit edge, path. -/ +def t3 : Template where + script := tscript0 + base := 35 + upto := 35 + guard := .fn 34 [] + goal := .app .eq [.fn 26 [], .app .add [.fn 16 [], .fn 20 []]] + +theorem t3_exact : t3.instances cut cand = [SolarVerifyVc.Counter.bump.ob6] := rfl + +theorem t3_valid : t3.Valid cut cand ↔ ∀ o ∈ [SolarVerifyVc.Counter.bump.ob6], o.Valid := + Template.valid_iff t3_exact + +/-- Template 4: exit edge, path. -/ +def t4 : Template where + script := tscript0 + base := 35 + upto := 35 + guard := .fn 34 [] + goal := .app .le [.fn 26 [], .fn 17 []] + +theorem t4_exact : t4.instances cut cand = [SolarVerifyVc.Counter.bump.ob7] := rfl + +theorem t4_valid : t4.Valid cut cand ↔ ∀ o ∈ [SolarVerifyVc.Counter.bump.ob7], o.Valid := + Template.valid_iff t4_exact + +end SolarVerifyLoopVc.Counter.bump diff --git a/Verify/Infer/loopvc/solar/LoopVc.lean b/Verify/Infer/loopvc/solar/LoopVc.lean new file mode 100644 index 00000000..aa83b10a --- /dev/null +++ b/Verify/Infer/loopvc/solar/LoopVc.lean @@ -0,0 +1,141 @@ +-- Generated by solar-verify --emit-loopvc (format 1); do not edit. +import Verify.Obligation + +/-! +# Loop cutpoint templates of solar-verify's verification conditions + +`solar-verify --emit-loopvc DIR` cuts a function at the head of its loop and writes every +obligation of the function as a `Template`: the obligation solar-verify sent, with the loop's +candidate invariant and ranking function replaced by two declared symbols, the predicate `Inv` +(symbol `base`) and the ranking function `Rank` (symbol `base + 1`), applied to the cut's +parameters. `Template.instances cut c t` puts a candidate `c` back: every `Inv` application +becomes the conjunction of `c.conj` at its arguments and every `Rank` application `c.rank` at +its arguments; a template whose goal is an `Inv` application gives one obligation per conjunct, +as solar-verify checks each conjunct on its own. The module exported for a function proves, by +`rfl`, that the instances of its templates at the candidate of the run are exactly the +obligations solar-verify emitted for that run (`--emit-lean`). + +A candidate is a list of terms over the cut's parameters: declared constants of the function's +script, numbered as there, that `subst` replaces by an application's arguments. A template never +has an `Inv` or `Rank` application under a binder, and a candidate's terms have no loose bound +variable, so substitution needs no shifting. +-/ + +namespace SolarVerify.LoopVc + +open SolarVerify.Smt SolarVerify.Vc + +/-- A loop cut: the declared constants (by symbol number) a candidate ranges over, in the +order of the arguments of the cut's `Inv` and `Rank` applications. -/ +structure Cut where + params : List Nat + deriving Repr, Inhabited + +/-- A candidate: the invariant's conjuncts and the ranking function, over the cut's +parameters. -/ +structure Cand where + conj : List Term + rank : Option Term + deriving Repr, Inhabited + +/-- The term bound to symbol `f` by `σ`, if any. -/ +def lookup : List (Nat × Term) → Nat → Option Term + | [], _ => none + | (g, t) :: σ, f => match Nat.beq f g with + | true => some t + | false => lookup σ f + +mutual +/-- `t` with every constant `σ` binds replaced by its term. -/ +def subst (σ : List (Nat × Term)) : Term → Term + | .fn f [] => match lookup σ f with + | some u => u + | none => .fn f [] + | .fn f (a :: as) => .fn f (substList σ (a :: as)) + | .app op args => .app op (substList σ args) + | .constArray s v => .constArray s (subst σ v) + | .mk fs => .mk (substList σ fs) + | .proj i t => .proj i (subst σ t) + | .«forall» bs b => .«forall» bs (subst σ b) + | .«exists» bs b => .«exists» bs (subst σ b) + | .bool b => .bool b + | .int i => .int i + | .bv w n => .bv w n + | .var i => .var i +/-- `subst` on each term of a list. -/ +def substList (σ : List (Nat × Term)) : List Term → List Term + | [] => [] + | t :: ts => subst σ t :: substList σ ts +end + +/-- The conjunction of a candidate's conjuncts, as solar-verify assumes it at the loop head: +the term itself for one conjunct, `and` of them for several. -/ +def conjoin : List Term → Term + | [t] => t + | ts => .app .and ts + +mutual +/-- `t` with candidate `c` in place of the cut's `Inv` (symbol `base`) and `Rank` (symbol +`base + 1`). -/ +def inst (cut : Cut) (c : Cand) (base : Nat) : Term → Term + | .fn f args => + let args' := instList cut c base args + match Nat.beq f base with + | true => conjoin (c.conj.map (subst (cut.params.zip args'))) + | false => match Nat.beq f (base + 1), c.rank with + | true, some r => subst (cut.params.zip args') r + | _, _ => .fn f args' + | .app op args => .app op (instList cut c base args) + | .constArray s v => .constArray s (inst cut c base v) + | .mk fs => .mk (instList cut c base fs) + | .proj i t => .proj i (inst cut c base t) + | .«forall» bs b => .«forall» bs (inst cut c base b) + | .«exists» bs b => .«exists» bs (inst cut c base b) + | .bool b => .bool b + | .int i => .int i + | .bv w n => .bv w n + | .var i => .var i +/-- `inst` on each term of a list. -/ +def instList (cut : Cut) (c : Cand) (base : Nat) : List Term → List Term + | [] => [] + | t :: ts => inst cut c base t :: instList cut c base ts +end + +/-- An obligation of the function with the cut's candidate abstracted: the template script +declares the function's `base` symbols, then `Inv` and `Rank`. -/ +structure Template where + script : Script + base : Nat + upto : Nat + guard : Term + goal : Term + deriving Repr, Inhabited + +/-- The template's script with candidate `c`: the function's own declarations, and every +assertion instantiated. -/ +def Template.instScript (t : Template) (cut : Cut) (c : Cand) : Script where + decls := t.script.decls.take t.base + asserts := instList cut c t.base t.script.asserts + +/-- The obligations a template stands for at candidate `c`: one per conjunct when its goal is an +`Inv` application, else one. -/ +def Template.instances (t : Template) (cut : Cut) (c : Cand) : List Obligation := + let script := t.instScript cut c + let guard := inst cut c t.base t.guard + let one (goal : Term) : Obligation := { script, upto := t.upto, guard, goal } + match t.goal with + | .fn f args => match Nat.beq f t.base with + | true => c.conj.map (fun b => one (subst (cut.params.zip (instList cut c t.base args)) b)) + | false => [one (inst cut c t.base t.goal)] + | g => [one (inst cut c t.base g)] + +/-- A template holds at candidate `c`: every obligation it stands for is valid. -/ +def Template.Valid (t : Template) (cut : Cut) (c : Cand) : Prop := + ∀ o ∈ t.instances cut c, o.Valid + +/-- A template whose instances are known obligations holds exactly when they do. -/ +theorem Template.valid_iff {t : Template} {cut : Cut} {c : Cand} {obs : List Obligation} + (h : t.instances cut c = obs) : t.Valid cut c ↔ ∀ o ∈ obs, o.Valid := by + rw [Template.Valid, h] + +end SolarVerify.LoopVc diff --git a/Verify/Infer/loopvc/solar/REV b/Verify/Infer/loopvc/solar/REV new file mode 100644 index 00000000..fa2c2d3e --- /dev/null +++ b/Verify/Infer/loopvc/solar/REV @@ -0,0 +1 @@ +1c38646b38b22196987220f833d207d69fa84771 diff --git a/Verify/Infer/loopvc/spacer/Counter.bump.spacer.out b/Verify/Infer/loopvc/spacer/Counter.bump.spacer.out new file mode 100644 index 00000000..6bfaff8b --- /dev/null +++ b/Verify/Infer/loopvc/spacer/Counter.bump.spacer.out @@ -0,0 +1,361 @@ +sat +( + (define-fun Reverted () Bool + (let ((a!1 (exists ((x!1 Int) + (x!2 Int) + (x!3 Int) + (x!4 Int) + (x!5 Int) + (x!6 Int) + (x!7 Int) + (x!8 Int) + (x!9 Int) + (x!10 Int) + (x!11 Int) + (x!12 Int) + (x!13 Int) + (x!14 Int) + (x!15 Int) + (x!16 Int) + (x!17 Int) + (x!18 Int) + (x!19 Int) + (x!20 Int)) + (! (let ((a!1 (not (<= (+ x!15 (* (- 1) x!19) x!20) (- 1)))) + (a!2 (not (>= (+ x!15 (* (- 1) x!19) x!20) 1))) + (a!3 (not (<= (+ x!15 (* (- 1) x!19) x!18) (- 1))))) + (and a!1 + a!2 + a!3 + (not (= x!2 0)) + (not (= x!1 0)) + (<= 0 x!18) + (<= 0 x!20) + (<= 0 (+ x!15 x!18)) + (<= 0 x!6) + (<= 0 x!15) + (<= 0 x!19) + (<= 0 x!17) + (<= 0 x!16) + (<= 0 x!14) + (<= 0 x!13) + (<= 0 x!12) + (<= 0 x!11) + (<= 0 x!10) + (<= 0 x!9) + (<= 0 x!8) + (<= 0 x!7) + (<= 0 x!5) + (<= 0 x!4) + (<= 0 x!3) + (<= 0 x!2) + (<= 0 x!1) + (<= x!18 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (not (<= x!18 x!20)) + (<= x!20 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= (+ x!15 x!18) + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= (+ x!15 x!18) x!16) + (<= x!6 + 1461501637330902918203684832716283019655932542975) + (<= x!15 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!15 x!16) + (<= x!19 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!17 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!16 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!14 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!13 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!12 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!11 + 1461501637330902918203684832716283019655932542975) + (<= x!10 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!9 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!8 4294967295) + (<= x!7 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!5 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!4 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!3 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!2 + 1461501637330902918203684832716283019655932542975) + (<= x!1 + 1461501637330902918203684832716283019655932542975) + (or (not (<= x!19 + 115792089237316195423570985008687907853269984665640564039457584007913129639934)) + (not (<= (- 1) x!19))))) + :weight 0))) + (a!2 (exists ((x!1 Int) + (x!2 Int) + (x!3 Int) + (x!4 Int) + (x!5 Int) + (x!6 Int) + (x!7 Int) + (x!8 Int) + (x!9 Int) + (x!10 Int) + (x!11 Int) + (x!12 Int) + (x!13 Int) + (x!14 Int) + (x!15 Int) + (x!16 Int) + (x!17 Int) + (x!18 Int) + (x!19 Int) + (x!20 Int)) + (! (let ((a!1 (not (<= (+ x!15 (* (- 1) x!19) x!20) (- 1)))) + (a!2 (not (>= (+ x!15 (* (- 1) x!19) x!20) 1))) + (a!3 (not (<= (+ x!15 (* (- 1) x!19) x!18) (- 1))))) + (and a!1 + a!2 + a!3 + (not (= x!2 0)) + (not (= x!1 0)) + (<= 0 (+ x!15 x!18)) + (<= (- 1) x!19) + (<= 0 x!19) + (<= 0 x!7) + (<= 0 x!16) + (<= 0 x!20) + (<= 0 x!18) + (<= 0 x!17) + (<= 0 x!15) + (<= 0 x!14) + (<= 0 x!13) + (<= 0 x!12) + (<= 0 x!11) + (<= 0 x!10) + (<= 0 x!9) + (<= 0 x!8) + (<= 0 x!6) + (<= 0 x!5) + (<= 0 x!4) + (<= 0 x!3) + (<= 0 x!2) + (<= 0 x!1) + (<= (+ x!15 x!18) + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= (+ x!15 x!18) x!16) + (<= x!19 + 115792089237316195423570985008687907853269984665640564039457584007913129639934) + (<= x!19 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!7 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!16 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!20 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!18 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (not (<= x!18 x!20)) + (<= x!17 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!15 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!15 x!16) + (<= x!14 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!13 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!12 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!11 + 1461501637330902918203684832716283019655932542975) + (<= x!10 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!9 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!8 4294967295) + (<= x!6 + 1461501637330902918203684832716283019655932542975) + (<= x!5 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!4 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!3 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!2 + 1461501637330902918203684832716283019655932542975) + (<= x!1 + 1461501637330902918203684832716283019655932542975) + (or (not (<= (- 1) x!20)) + (not (<= x!20 + 115792089237316195423570985008687907853269984665640564039457584007913129639934))))) + :weight 0))) + (a!3 (exists ((x!1 Int) + (x!2 Int) + (x!3 Int) + (x!4 Int) + (x!5 Int) + (x!6 Int) + (x!7 Int) + (x!8 Int) + (x!9 Int) + (x!10 Int) + (x!11 Int) + (x!12 Int) + (x!13 Int) + (x!14 Int) + (x!15 Int) + (x!16 Int) + (x!17 Int) + (x!18 Int)) + (! (let ((a!1 (or (not (<= 0 (+ x!15 x!18))) + (not (<= (+ x!15 x!18) + 115792089237316195423570985008687907853269984665640564039457584007913129639935))))) + (and (not (= x!2 0)) + (not (= x!1 0)) + (<= 0 x!15) + (<= 0 x!18) + (<= 0 x!16) + (<= 0 x!3) + (<= 0 x!12) + (<= 0 x!17) + (<= 0 x!14) + (<= 0 x!13) + (<= 0 x!11) + (<= 0 x!10) + (<= 0 x!9) + (<= 0 x!8) + (<= 0 x!7) + (<= 0 x!6) + (<= 0 x!5) + (<= 0 x!4) + (<= 0 x!2) + (<= 0 x!1) + (<= x!15 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!15 x!16) + (<= x!18 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!16 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!3 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!12 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!17 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!14 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!13 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!11 + 1461501637330902918203684832716283019655932542975) + (<= x!10 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!9 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!8 4294967295) + (<= x!7 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!6 + 1461501637330902918203684832716283019655932542975) + (<= x!5 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!4 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!2 + 1461501637330902918203684832716283019655932542975) + (<= x!1 + 1461501637330902918203684832716283019655932542975) + a!1)) + :weight 0))) + (a!4 (exists ((x!1 Int) + (x!2 Int) + (x!3 Int) + (x!4 Int) + (x!5 Int) + (x!6 Int) + (x!7 Int) + (x!8 Int) + (x!9 Int) + (x!10 Int) + (x!11 Int) + (x!12 Int) + (x!13 Int) + (x!14 Int) + (x!15 Int) + (x!16 Int) + (x!17 Int) + (x!18 Int)) + (! (and (not (= x!2 0)) + (not (= x!1 0)) + (<= 0 x!15) + (<= 0 (+ x!15 x!18)) + (<= 0 x!18) + (<= 0 x!16) + (<= 0 x!3) + (<= 0 x!12) + (<= 0 x!17) + (<= 0 x!14) + (<= 0 x!13) + (<= 0 x!11) + (<= 0 x!10) + (<= 0 x!9) + (<= 0 x!8) + (<= 0 x!7) + (<= 0 x!6) + (<= 0 x!5) + (<= 0 x!4) + (<= 0 x!2) + (<= 0 x!1) + (<= x!15 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!15 x!16) + (<= (+ x!15 x!18) + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (not (<= (+ x!15 x!18) x!16)) + (<= x!18 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!16 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!3 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!12 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!17 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!14 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!13 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!11 1461501637330902918203684832716283019655932542975) + (<= x!10 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!9 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!8 4294967295) + (<= x!7 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!6 1461501637330902918203684832716283019655932542975) + (<= x!5 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!4 + 115792089237316195423570985008687907853269984665640564039457584007913129639935) + (<= x!2 1461501637330902918203684832716283019655932542975) + (<= x!1 1461501637330902918203684832716283019655932542975)) + :weight 0)))) + (or a!1 a!2 a!3 a!4))) + (define-fun Inv@L0 ((x!0 Int) (x!1 Int) (x!2 Int) (x!3 Int)) Bool + (let ((a!1 (not (<= (+ x!3 (* (- 1) x!0) x!1) (- 1)))) + (a!2 (not (>= (+ x!3 (* (- 1) x!0) x!1) 1))) + (a!3 (not (<= (+ x!3 (* (- 1) x!0) x!2) (- 1))))) + (and a!1 a!2 a!3))) +) diff --git a/Verify/Infer/reconstruct-4.35.axioms.txt b/Verify/Infer/reconstruct-4.35.axioms.txt new file mode 100644 index 00000000..5b420058 --- /dev/null +++ b/Verify/Infer/reconstruct-4.35.axioms.txt @@ -0,0 +1,18 @@ +'FlexEval.counter_int_init' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.counter_int_pres' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.counter_int_use' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.counter_u256_init' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.counter_u256_pres' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.counter_u256_use' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.okwhile_int_init' depends on axioms: [propext, Quot.sound] +'FlexEval.okwhile_int_pres' depends on axioms: [propext, Quot.sound] +'FlexEval.okwhile_int_use' depends on axioms: [propext, Quot.sound] +'FlexEval.okwhile_u256_init' depends on axioms: [propext, Quot.sound] +'FlexEval.okwhile_u256_pres' depends on axioms: [propext, Quot.sound] +'FlexEval.okwhile_u256_use' depends on axioms: [propext, Quot.sound] +'FlexEval.drain_int_init' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.drain_int_pres' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.drain_int_use' depends on axioms: [propext, Quot.sound] +'FlexEval.drain_u256_init' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.drain_u256_pres' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.drain_u256_use' depends on axioms: [propext, Quot.sound] diff --git a/Verify/Infer/smt2lean_inv.py b/Verify/Infer/smt2lean_inv.py new file mode 100644 index 00000000..594d19e7 --- /dev/null +++ b/Verify/Infer/smt2lean_inv.py @@ -0,0 +1,639 @@ +#!/usr/bin/env python3 +"""Mechanical translations from SMT-LIB into Lean. Nothing is simplified or edited. + + smt2lean_inv.py MODEL NAME + A z3 Spacer model (define-fun Inv ...) as a shallow Lean 4 def: each SMT-LIB operator maps + 1:1 to a Lean operator, let stays let. + + smt2lean_inv.py loopvc --interface META.json [--candidate CAND.json | --spacer MODEL] + --root ROOT --out DIR + A loop's exported Horn view (META.json names it; one clause per cutpoint edge) and a + candidate invariant per cutpoint, as the exact obligations of initiation, preservation, + termination, exit and outcome, written as a solar-verify-lean (version 2) export that + Verify/Discharge/discharge.sh checks like any other. See loopvc/README.md. + + smt2lean_inv.py cti DIR + After discharge.sh ran on DIR: for each required obligation it did not prove, asks z3 for a + model of the query and writes DIR/discharge/cti.json (the candidate, the edge, its location + and the cutpoint state before and after the edge) and DIR/discharge/residual/.lean (the + exact goal left open). A model is a counterexample to induction, not a reachable failure. +""" +import hashlib, json, os, re, subprocess, sys + +# ---------------------------------------------------------------------------- s-expressions + +TOKEN = re.compile(r';[^\n]*|\(|\)|\|[^|]*\||"(?:[^"]|"")*"|[^\s()|;"]+') + +def tokenize(s): + return [t for t in TOKEN.findall(s) if not t.startswith(';')] + +def parse(toks, i=0): + if toks[i] == '(': + out = []; i += 1 + while toks[i] != ')': + x, i = parse(toks, i); out.append(x) + return out, i + 1 + return toks[i], i + 1 + +def parse_all(text): + toks = tokenize(text) + out, i = [], 0 + while i < len(toks): + x, i = parse(toks, i); out.append(x) + return out + +def show(e): + if isinstance(e, str): + return e + return '(' + ' '.join(show(x) for x in e) + ')' + +def sha256_bytes(b): + return hashlib.sha256(b).hexdigest() + +def sha256_file(p): + with open(p, 'rb') as f: + return sha256_bytes(f.read()) + +# ---------------------------------------------------------------------- Spacer model -> Lean + +def ident(x): + return x.replace('!', '_') + +def is_bool(v): + return isinstance(v, list) and v[0] in ('not', 'and', 'or', '=>', '<=', '>=', '<', '>', '=') + +def lean(e): + if isinstance(e, str): + if re.fullmatch(r'\d+', e): return '(' + e + ' : Int)' + if e == 'true': return 'True' + if e == 'false': return 'False' + return ident(e) + op, *args = e + if op == 'let': + binds, body = args + s = lean(body) + for name, val in reversed(binds): + ty = 'Prop' if is_bool(val) else 'Int' + s = '(let ' + ident(name) + ' : ' + ty + ' := ' + lean(val) + '; ' + s + ')' + return s + a = [lean(x) for x in args] + if op == 'not': return '(¬ ' + a[0] + ')' + if op == 'and': return '(' + ' ∧ '.join(a) + ')' if a else 'True' + if op == 'or': return '(' + ' ∨ '.join(a) + ')' if a else 'False' + if op == '=>': return '(' + a[0] + ' → ' + a[1] + ')' + if op == '-' and len(a) == 1: return '(-' + a[0] + ')' + if op in ('+', '-', '*'): return '(' + (' ' + op + ' ').join(a) + ')' + if op in ('<=', '>=', '<', '>'): + m = {'<=': '≤', '>=': '≥', '<': '<', '>': '>'}[op] + return '(' + a[0] + ' ' + m + ' ' + a[1] + ')' + if op == '=': return '(' + a[0] + ' = ' + a[1] + ')' + if op == 'ite': return '(if ' + a[0] + ' then ' + a[1] + ' else ' + a[2] + ')' + raise SystemExit('unsupported operator: ' + op) + +def model_main(path, name): + text = open(path).read() + d, _ = parse(tokenize(text[text.index('(define-fun'):])) + _, fname, params, ret, body = d + binders = ' '.join('(' + ident(p) + ' : Int)' for p, _t in params) + print('/-- Verbatim from ' + path + ' (z3 Spacer model for ' + fname + '). -/') + print('def ' + name + ' ' + binders + ' : Prop :=') + print(' ' + lean(body)) + +# ----------------------------------------------- SMT-LIB -> solar-verify's deep embedding +# The translation of solar's crates/verify/src/lean.rs (Scope::term, sort, command), so that an +# obligation written here reads exactly as one solar-verify --emit-lean writes. + +class Unsupported(Exception): + pass + +OPS = { + 'not': 'not', 'and': 'and', 'or': 'or', 'xor': 'xor', '=>': 'implies', '=': 'eq', + 'distinct': 'distinct', 'ite': 'ite', '+': 'add', '-': 'sub', '*': 'mul', 'div': 'div', + 'mod': 'mod', 'abs': 'abs', '<': 'lt', '<=': 'le', '>': 'gt', '>=': 'ge', + 'select': 'select', 'store': 'store', 'bv2nat': 'bv2nat', 'bv2int': 'bv2nat', +} +for _o in ('bvadd bvsub bvmul bvudiv bvurem bvsdiv bvsrem bvsmod bvneg bvand bvor bvxor bvnot ' + 'bvshl bvlshr bvashr bvult bvule bvugt bvuge bvslt bvsle bvsgt bvsge concat').split(): + OPS[_o] = _o + +def sort_lean(s): + if s == 'Bool': return '.bool' + if s == 'Int': return '.int' + if isinstance(s, list) and len(s) == 3 and s[0] == '_' and s[1] == 'BitVec': + return '(.bv %d)' % int(s[2]) + if isinstance(s, list) and len(s) == 3 and s[0] == 'Array': + return '(.array %s %s)' % (sort_lean(s[1]), sort_lean(s[2])) + raise Unsupported("unsupported sort '%s'" % show(s)) + +def lean_string(s): + return '"' + s.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n') + '"' + +class Scope: + def __init__(self): + self.decls = [] # (name, [arg sorts], ret sort) + self.by_name = {} + + def declare(self, name, args, ret): + if name in self.by_name or name in OPS: + raise Unsupported("symbol '%s' declared twice" % name) + self.decls.append((name, args, ret)) + self.by_name[name] = len(self.decls) - 1 + return len(self.decls) - 1 + + def term(self, t, bound): + if isinstance(t, str): + return self.atom(t, bound) + if not t: + raise Unsupported('empty application') + head, args = t[0], t[1:] + if isinstance(head, list): + return self.indexed(head, args, bound, t) + if head == '_': + if len(args) == 2 and args[0].startswith('bv') and args[0][2:].isdigit(): + return '.bv %d %d' % (int(args[1]), int(args[0][2:])) + raise Unsupported("unsupported literal '%s'" % show(t)) + if head == '!': + body, attrs = args[0], args[1:] + if any(k not in (':pattern', ':weight', ':qid', ':skolemid', ':named') for k in attrs[::2]): + raise Unsupported("unsupported attribute in '%s'" % show(t)) + return self.term(body, bound) + if head in ('forall', 'exists'): + vars_, body = args + sorts = [] + n = len(bound) + for v in vars_: + x, s = v + sorts.append(sort_lean(s)) + bound.append(x) + try: + b = self.term(body, bound) + finally: + del bound[n:] + return '.%s [%s] (%s)' % ('«forall»' if head == 'forall' else '«exists»', ', '.join(sorts), b) + if head == 'let': + raise Unsupported("unsupported 'let'") + a = ', '.join(self.term(x, bound) for x in args) + if head in bound: + raise Unsupported("bound variable '%s' applied to arguments" % head) + if head in OPS: + return '.app .%s [%s]' % (OPS[head], a) + if head in self.by_name: + return '.fn %d [%s]' % (self.by_name[head], a) + raise Unsupported("unsupported operator '%s'" % head) + + def atom(self, a, bound): + for i, b in enumerate(reversed(bound)): + if b == a: + return '.var %d' % i + if a in ('true', 'false'): + return '.bool ' + a + if a.isdigit(): + if len(a) > 1 and a.startswith('0'): + raise Unsupported("bad numeral '%s'" % a) + return '.int ' + a + if a.startswith('#x'): + return '.bv %d %d' % (4 * (len(a) - 2), int(a[2:], 16)) + if a.startswith('#b'): + return '.bv %d %d' % (len(a) - 2, int(a[2:], 2)) + if a in self.by_name: + if self.decls[self.by_name[a]][1]: + raise Unsupported("function '%s' used as a constant" % a) + return '.fn %d []' % self.by_name[a] + raise Unsupported("undeclared symbol '%s'" % a) + + def indexed(self, h, args, bound, t): + a = [self.term(x, bound) for x in args] + if len(h) >= 2 and h[0] == '_': + name, rest = h[1], h[2:] + if name == 'int2bv' and len(rest) == 1: o = '(.int2bv %d)' % int(rest[0]) + elif name == 'extract' and len(rest) == 2: o = '(.extract %d %d)' % (int(rest[0]), int(rest[1])) + elif name == 'zero_extend' and len(rest) == 1: o = '(.zeroExtend %d)' % int(rest[0]) + elif name == 'sign_extend' and len(rest) == 1: o = '(.signExtend %d)' % int(rest[0]) + else: raise Unsupported("unsupported operator in '%s'" % show(t)) + return '.app %s [%s]' % (o, ', '.join(a)) + if len(h) == 3 and h[0] == 'as' and h[1] == 'const': + s = h[2] + if not (isinstance(s, list) and s[0] == 'Array'): + raise Unsupported("'as const' of a non-array sort in '%s'" % show(t)) + return '.constArray %s (%s)' % (sort_lean(s[1]), a[0]) + raise Unsupported("unsupported operator in '%s'" % show(t)) + + def command(self, cmd): + """The Lean assertion a command adds, if any (declare-const, declare-fun, define-fun, assert).""" + op = cmd[0] + if op == 'declare-const': + self.declare(cmd[1], [], sort_lean(cmd[2])); return None + if op == 'declare-fun': + self.declare(cmd[1], [sort_lean(s) for s in cmd[2]], sort_lean(cmd[3])); return None + if op == 'define-fun': + names = [p[0] for p in cmd[2]] + sorts = [sort_lean(p[1]) for p in cmd[2]] + body = self.term(cmd[4], list(names)) + f = self.declare(cmd[1], sorts, sort_lean(cmd[3])) + vars_ = ', '.join('.var %d' % i for i in reversed(range(len(names)))) + eq = '.app .eq [.fn %d [%s], %s]' % (f, vars_, body) + return eq if not names else '.«forall» [%s] (%s)' % (', '.join(sorts), eq) + if op == 'assert': + return self.term(cmd[1], []) + raise Unsupported("unsupported command '%s'" % op) + +# ------------------------------------------------------------------------------ loop VCs +# Reads solar-verify's loop-cut interface (--emit-loopvc, format 1: crates/verify's +# docs/loopvc-interface.md) and a candidate, and writes the candidate's obligations. Lean computes +# them: the obligations are what the interface's own Template.instances gives at the candidate, +# printed as terms, and a bridge module proves each template's instances equal to them by rfl. + +def atoms(t): + if isinstance(t, str): + return {t} + out = set() + for x in t: + out |= atoms(x) + return out + +def subst(t, m, bound=()): + """Substitution of free symbols by terms: SMT-LIB's meaning of a define-fun application.""" + if isinstance(t, str): + return m[t] if t in m and t not in bound else t + if t and t[0] in ('forall', 'exists'): + return [t[0], t[1], subst(t[2], m, bound + tuple(v[0] for v in t[1]))] + if t and t[0] == 'let': + raise Unsupported("unsupported 'let'") + return [subst(x, m, bound) for x in t] + +def expand_lets(t, env=None): + """Spacer's lets, replaced by what they name (the meaning SMT-LIB gives let).""" + env = env or {} + if isinstance(t, str): + return env.get(t, t) + if t and t[0] == 'let': + inner = dict(env) + for name, val in t[1]: + inner[name] = expand_lets(val, env) + return expand_lets(t[2], inner) + if t and t[0] in ('forall', 'exists'): + names = {v[0] for v in t[1]} + return [t[0], t[1], expand_lets(t[2], {k: v for k, v in env.items() if k not in names})] + return [expand_lets(x, env) for x in t] + +def conjuncts(t): + if isinstance(t, list) and t and t[0] == 'and': + return [c for x in t[1:] for c in conjuncts(x)] + return [t] + +LITERAL = re.compile(r'-?\d+|#x[0-9a-fA-F]+|#b[01]+|true|false') + +def spacer_candidate(path, iface): + """Spacer's model of the cut's predicate, over the cut's parameters, as a candidate; the + ranking function stays the interface's (a Horn solver gives none).""" + answer = parse_all(open(path).read()) + if not answer or answer[0] != 'sat' or len(answer) < 2: + raise SystemExit('%s is not a sat answer with a model' % path) + cut = iface['cut'] + for d in answer[1]: + if isinstance(d, list) and d and d[0] == 'define-fun' and d[1].strip('|') == cut['predicate'].strip('|'): + params = [p[0] for p in d[2]] + if len(params) != len(cut['params']): + raise SystemExit('the model has %d parameters, the cut %d' % (len(params), len(cut['params']))) + body = subst(expand_lets(d[4]), dict(zip(params, [p['symbol'] for p in cut['params']]))) + return { + 'id': 'spacer-' + sha256_file(path)[:12], + 'conjuncts': [{'term': show(c), 'text': show(c), 'origin': 'spacer', 'site': None} for c in conjuncts(body)], + 'rank': iface['candidate'].get('rank'), + } + raise SystemExit('no model of %s in %s' % (cut['predicate'], path)) + +def rel(path, root): + r = os.path.relpath(os.path.abspath(path), os.path.abspath(root)) + if r.startswith('..'): + raise SystemExit('%s is outside the root %s' % (path, root)) + return r.replace(os.sep, '/') + +def lean_env(here): + """lean and the LEAN_PATH of the discharge library (Verify/Discharge/Reconstruct), which + builds Verify.Obligation.""" + pkg = os.path.normpath(os.path.join(here, '..', 'Discharge', 'Reconstruct')) + lp = subprocess.run(['lake', 'env', 'printenv', 'LEAN_PATH'], cwd=pkg, capture_output=True, text=True, check=True).stdout.strip() + root = os.path.normpath(os.path.join(here, '..', '..')) + r = subprocess.run(['elan', 'which', 'lean'], cwd=root, capture_output=True, text=True) + return (r.stdout.strip() if r.returncode == 0 else 'lean'), lp + +def run_lean(leanbin, lp, args, cwd): + r = subprocess.run([leanbin, '-DmaxHeartbeats=0', '-DmaxRecDepth=100000'] + args, cwd=cwd, + env=dict(os.environ, LEAN_PATH=lp), capture_output=True, text=True) + if r.returncode != 0 or re.search(r'(^|\n)[^\n]*error', r.stdout + r.stderr): + raise SystemExit('lean %s failed:\n%s%s' % (' '.join(args), r.stdout[-4000:], r.stderr[-2000:])) + return r.stdout + +KIND = {('invariant', 'entry'): 'initiation', ('invariant', 'back'): 'preservation', + ('rank', 'back'): 'termination', ('path', 'exit'): 'exit'} + +def loopvc_main(argv): + import argparse, shutil, tempfile + ap = argparse.ArgumentParser(prog='smt2lean_inv.py loopvc') + ap.add_argument('--export', required=True, help='a solar-verify --emit-loopvc directory') + ap.add_argument('--unit', required=True, help='Contract.function') + ap.add_argument('--candidate', help='a candidate as the interface writes one: {conjuncts, rank}') + ap.add_argument('--spacer', help="z3 Spacer's answer for the unit's Horn view") + ap.add_argument('--root', required=True) + ap.add_argument('--out', required=True) + a = ap.parse_args(argv) + a.export, a.out = os.path.abspath(a.export), os.path.abspath(a.out) + here = os.path.dirname(os.path.abspath(__file__)) + lib = os.path.normpath(os.path.join(here, '..', 'Obligation')) + contract, fn = a.unit.split('.', 1) + mod = '%s/%s' % (contract, fn) + jpath = os.path.join(a.export, mod + '.loopvc.json') + iface = json.load(open(jpath)) + if (iface.get('format'), iface.get('version')) != ('solar-verify-loopvc', 1): + raise SystemExit('%s is not solar-verify-loopvc format 1' % jpath) + cut = iface['cut'] + horn = iface['horn']['file'] + horn = os.path.join(a.export, horn if '/' in horn else os.path.join(contract, horn)) + sources = [jpath, horn, os.path.join(a.export, 'LoopVc.lean'), os.path.join(a.export, mod + '.lean'), + os.path.join(a.export, mod + '_loopvc.lean')] + if iface['horn'].get('sha256') and sha256_file(horn) != iface['horn']['sha256']: + raise SystemExit('the Horn view is not the one the interface names') + if iface['lean'].get('library_sha256') and sha256_file(sources[2]) != iface['lean']['library_sha256']: + raise SystemExit('LoopVc.lean is not the one the interface names') + if a.spacer: + cand = spacer_candidate(a.spacer, iface) + sources.append(a.spacer) + elif a.candidate: + cand = dict(json.load(open(a.candidate))) + cand.setdefault('id', os.path.basename(a.candidate).split('.json')[0]) + sources.append(a.candidate) + else: + cand = dict(iface['candidate'], id='annotated') + cid = re.sub(r'\W', '_', cand['id']) + + # The candidate in the embedding, numbered as the unit's script declares its symbols. + script_file = os.path.join(a.export, '%s.script%d.smt2' % (mod, cut['head']['script'])) + sources.append(script_file) + cmds = [l for l in open(script_file).read().split('\n') if l.strip()] + sc = Scope() + for c in cmds: + x = parse_all(c)[0] + if x[0] in ('declare-const', 'declare-fun', 'define-fun'): + sc.command(x) + params = [p['symbol'] for p in cut['params']] + for p in cut['params']: + if sc.by_name.get(p['symbol']) != p['lean_symbol']: + raise SystemExit('parameter %s is not symbol %s of the script' % (p['symbol'], p['lean_symbol'])) + defined = {x[1] for x in (parse_all(c)[0] for c in cmds) if x[0] == 'define-fun'} + def cand_term(t, what): + e = parse_all(t)[0] + free = {x for x in atoms(e) - set(params) - set(OPS) if not LITERAL.fullmatch(x)} - defined + free -= {'forall', 'exists', '_', '!'} | {v[0] for v in _bound(e)} + if free: + raise SystemExit("the candidate's %s '%s' names %s, not only the cut's parameters" % (what, t, sorted(free))) + return e, sc.term(e, []) + conj = [cand_term(c['term'], 'conjunct') for c in cand['conjuncts']] + rank = cand_term(cand['rank']['term'], 'ranking function') if cand.get('rank') else None + if not conj: + raise SystemExit('the candidate has no conjunct') + + # Lean: build the interface's modules, and print every template's instances at the candidate. + leanbin, lp = lean_env(here) + tmp = tempfile.mkdtemp(prefix='loopvc-') + try: + for m in ['LoopVc', mod, mod + '_loopvc']: + os.makedirs(os.path.join(tmp, os.path.dirname(m)), exist_ok=True) + run_lean(leanbin, lp + ':' + tmp, ['-o', os.path.join(tmp, m + '.olean'), os.path.join(a.export, m + '.lean')], a.export) + tns = 'SolarVerifyLoopVc.%s.%s' % (contract, fn) + cand_lean = '{ conj := [%s], rank := %s }' % (', '.join(t for _e, t in conj), 'some (%s)' % rank[1] if rank else 'none') + temps = iface['templates'] + pr = ['import %s' % (mod + '_loopvc').replace('/', '.'), 'open SolarVerify.Smt SolarVerify.Vc SolarVerify.LoopVc', + "def cand' : Cand := %s" % cand_lean] + for t in temps: + k = t['id'][1:] + pr.append('#eval do') + pr.append(" for o in (%s.t%s.instances %s.cut cand') do" % (tns, k, tns)) + for f in ('script', 'upto', 'guard', 'goal'): + pr.append(' IO.println "@@%s %s"' % (t['id'], f)) + pr.append(' IO.println (Std.Format.pretty (repr o.%s) 100000)' % f) + with open(os.path.join(tmp, 'Print.lean'), 'w') as f: + f.write('\n'.join(pr) + '\n') + out = run_lean(leanbin, lp + ':' + tmp, [os.path.join(tmp, 'Print.lean')], tmp) + parts = re.split(r'^@@(t\d+) (script|upto|guard|goal)\n', out, flags=re.M)[1:] + insts = [] + for i in range(0, len(parts), 3): + tid, field, val = parts[i], parts[i + 1], parts[i + 2].strip() + if field == 'script': + insts.append({'template': tid}) + insts[-1][field] = val + scripts = [] + for o in insts: + if o['script'] not in scripts: + scripts.append(o['script']) + + ns = 'SolarVerifyVc.LoopVc.%s.%s_%s' % (contract, fn, cid) + modpath = 'LoopVc/%s/%s_%s' % (contract, fn, cid) + os.makedirs(os.path.join(a.out, os.path.dirname(modpath)), exist_ok=True) + L = ['-- Generated by Verify/Infer/smt2lean_inv.py loopvc; do not edit.', + "-- The instances of %s's loop-cut templates (%s) at candidate %s." % (a.unit, rel(jpath, a.root), cand['id']), + 'import Verify.Obligation', '', 'set_option maxRecDepth 100000', '', + 'namespace %s' % ns, 'open SolarVerify.Smt SolarVerify.Vc', ''] + for s, text_ in enumerate(scripts): + L.append("/-- The function's script with the candidate at the loop head. -/") + L.append('def script%d : Script :=\n %s\n' % (s, text_)) + def inst_smt(e): + """The candidate put back in an SMT-LIB term, as Template.instances does on terms.""" + if isinstance(e, list) and e and e[0] == cut['predicate']: + m = dict(zip(params, [inst_smt(x) for x in e[1:]])) + cs = [subst(c, m) for c, _t in conj] + return cs[0] if len(cs) == 1 else ['and'] + cs + if isinstance(e, list) and e and e[0] == cut['rank'] and rank: + return subst(rank[0], dict(zip(params, [inst_smt(x) for x in e[1:]]))) + if isinstance(e, list): + return [inst_smt(x) for x in e] + return e + rows, k = [], 0 + bridge = ['import Lean', 'import %s' % (mod + '_loopvc').replace('/', '.'), 'import %s' % modpath.replace('/', '.'), '', + 'open SolarVerify.Smt SolarVerify.Vc SolarVerify.LoopVc', '', + 'namespace %s.Bridge' % ns, '', + "/-- The candidate, in the interface's terms. -/", + 'def cand : Cand := %s' % cand_lean, ''] + if not a.candidate and not a.spacer: + bridge += ['/-- It is the candidate of the run. -/', + 'theorem cand_eq : cand = %s.cand := rfl' % tns, ''] + head_cmd = parse_all(cut['head']['template'])[0] + for t in temps: + mine = [o for o in insts if o['template'] == t['id']] + names = [] + for j, o in enumerate(mine): + kind = KIND.get((t['role'], t['edge']), '%s-%s' % (t['edge'], t['role'])) + c = cand['conjuncts'][j] if t['role'] == 'invariant' else None + oid = '%s@%s#%s%s' % (a.unit, cut['id'], t['id'], '.c%d' % j if t['role'] == 'invariant' else '') + L.append('/-- %s: %s of edge %s (template %s, %s)%s, candidate %s. -/' % ( + oid, kind, t['edge'], t['id'], t['role'], + (', conjunct "%s"' % c['text']) if c else '', cand['id'])) + L.append('def ob%d : Obligation where\n script := script%d\n upto := %s\n guard := %s\n goal := %s\n' % ( + k, scripts.index(o['script']), o['upto'], o['guard'], o['goal'])) + names.append('%s.ob%d' % (ns, k)) + cs = [parse_all(x)[0] for x in cmds[:t['commands']]] + hc = cut['head']['command'] + if hc < len(cs): + cs[hc] = head_cmd + goal = parse_all(t['goal'])[0] + post = {} + if t['role'] == 'invariant': + args = [inst_smt(x) for x in goal[1:]] + post = {p['name']: show(x) for p, x in zip(cut['params'], args)} + goal = subst(conj[j][0], dict(zip(params, args))) + else: + goal = inst_smt(goal) + smt = ''.join(show(inst_smt(x)) + '\n' for x in cs) + smt += '(assert %s)\n(assert (not %s))\n(check-sat)\n' % (show(inst_smt(parse_all(t['guard'])[0])), show(goal)) + smt_file = '%s.ob%d.smt2' % (modpath, k) + with open(os.path.join(a.out, smt_file), 'w') as f: + f.write(smt) + pre = {} if t['edge'] == 'entry' else {cut['id']: {p['name']: p['symbol'] for p in cut['params']}} + inst0 = (t.get('instances') or [{}])[0] + rows.append({ + 'id': oid, 'lean': '%s.ob%d' % (ns, k), 'role': 'obligation', 'kind': kind, + 'edge': t['edge'], 'template': t['id'], 'template_role': t['role'], 'cutpoint': cut['id'], + 'site': (c or {}).get('site') or inst0.get('site') or cut.get('site'), 'candidate': cand['id'], + 'spec': ({'text': c['text'], 'span': c.get('site')} if c else + {'text': cand['rank']['text'], 'span': cand['rank'].get('site')} if t['role'] == 'rank' else + {'text': inst0.get('kind', t['role']), 'span': inst0.get('site')}), + 'pre': pre, 'post': post, 'smt': smt_file, 'smt_sha256': sha256_bytes(smt.encode()), + 'answer': 'not-run', 'required': True, + }) + k += 1 + bridge.append('theorem %s_exact : %s.%s.instances %s.cut cand = [%s] := rfl' % ( + t['id'], tns, t['id'], tns, ', '.join(names))) + bridge.append('') + L.append('end %s' % ns) + with open(os.path.join(a.out, modpath + '.lean'), 'w') as f: + f.write('\n'.join(L) + '\n') + bridge += ['end %s.Bridge' % ns, '', 'open Lean Elab Command in', + '#eval show CommandElabM Unit from do', + ' for n in [%s] do' % ', '.join('`%s.Bridge.%s_exact' % (ns, t['id']) for t in temps), + ' let axs ← Lean.collectAxioms n', + ' IO.println s!"AXIOMS {n}: {String.intercalate \" \" (axs.toList.map toString)}"'] + bpath = os.path.join(a.out, 'bridge', modpath + '_bridge.lean') + os.makedirs(os.path.dirname(bpath), exist_ok=True) + with open(bpath, 'w') as f: + f.write('\n'.join(bridge) + '\n') + # The bridge must check now: each template's instances are exactly the obligations written. + os.makedirs(os.path.join(tmp, os.path.dirname(modpath)), exist_ok=True) + run_lean(leanbin, lp + ':' + tmp, ['-o', os.path.join(tmp, modpath + '.olean'), os.path.join(a.out, modpath + '.lean')], a.out) + bout = run_lean(leanbin, lp + ':' + tmp, [bpath], tmp) + checked = [l for l in bout.splitlines() if l.startswith('AXIOMS')] + if len(checked) != len(temps): + raise SystemExit('the bridge reported %d of %d templates' % (len(checked), len(temps))) + for line in checked: + if set(line.split(': ', 1)[1].split()) - {'propext', 'Classical.choice', 'Quot.sound'}: + raise SystemExit('the bridge uses another axiom: ' + line) + finally: + shutil.rmtree(tmp, ignore_errors=True) + + if cut.get('site'): + p = os.path.join(a.root, cut['site']['file']) + if p not in sources: + sources.append(p) + manifest = { + 'format': 'solar-verify-lean', 'version': 2, + 'generator': {'name': 'Verify/Infer/smt2lean_inv.py loopvc', 'interface': { + 'format': iface['format'], 'version': iface['version'], 'formulas_sha256': iface['sha256']['formulas']}}, + 'sources': [{'path': rel(p, a.root), 'sha256': sha256_file(p)} for p in sources], + 'lean': {'toolchain': open(os.path.join(here, '..', '..', 'lean-toolchain')).read().strip(), + 'smt_sha256': sha256_file(os.path.join(lib, 'Smt.lean')), + 'vc_sha256': sha256_file(os.path.join(lib, 'Vc.lean'))}, + 'units': [{ + 'name': '%s %s [%s]' % (a.unit, cut['id'], cand['id']), 'status': 'generated', + 'module': modpath + '.lean', 'namespace': ns, 'bridge': rel(bpath, a.out), + 'candidate': cand, + # A revert path owes nothing without succeeds-if (the interface's contract): listed, no row. + 'reverts': iface.get('reverts', []), + 'obligations': rows, + }], + } + with open(os.path.join(a.out, 'manifest.json'), 'w') as f: + f.write(json.dumps(manifest, indent=2, sort_keys=True) + '\n') + print('loopvc: %d obligations for %s at %s (candidate %s); bridge checked' % ( + len(rows), a.unit, cut['id'], cand['id']), file=sys.stderr) + return 0 + +def _bound(t): + if isinstance(t, str): + return [] + out = [] + if t and t[0] in ('forall', 'exists'): + out += list(t[1]) + for x in t: + out += _bound(x) + return out + +# ----------------------------------------------------------------------- CTIs and residuals + +def z3_version(z3): + try: + return subprocess.run([z3, '--version'], capture_output=True, text=True).stdout.strip() + except OSError: + return None + +def cti_main(argv): + d = argv[0] + z3 = os.environ.get('SOLAR_VERIFY_Z3', 'z3') + manifest = json.load(open(os.path.join(d, 'manifest.json'))) + summary = {} + with open(os.path.join(d, 'discharge', 'summary.tsv')) as f: + next(f) + for line in f: + r = line.rstrip('\n').split('\t') + summary[r[0]] = r[3] + out, n_cti = [], 0 + os.makedirs(os.path.join(d, 'discharge', 'residual'), exist_ok=True) + for u in manifest['units']: + for ob in u['obligations']: + if not ob.get('required') or summary.get(ob['id']) == 'proved': + continue + row = {'id': ob['id'], 'status': summary.get(ob['id'], 'missing'), + 'candidate': ob.get('candidate'), 'edge': ob.get('edge'), 'kind': ob.get('kind'), + 'site': ob.get('site'), 'spec': ob.get('spec')} + if u.get('module') is None: + row.update(verdict='inconclusive', reason=u.get('reason')) + out.append(row); continue + terms = [('pre', p, t) for _c, args in sorted(ob['pre'].items()) for p, t in args.items()] + terms += [('post', p, t) for p, t in ob['post'].items()] + q = open(os.path.join(d, ob['smt'])).read() + if terms: + q += '(get-value (%s))\n' % ' '.join(t for _c, _p, t in terms) + try: + res = subprocess.run([z3, '-in', '-smt2', '-T:60'], input=q, capture_output=True, text=True, timeout=90).stdout + except subprocess.TimeoutExpired: + res = 'timeout' + first = res.split('\n', 1)[0].strip() + if first == 'sat': + vals = parse_all(res.split('\n', 1)[1]) if terms else [] + vals = vals[0] if vals else [] + state = {} + for (c, p, _t), v in zip(terms, vals): + state.setdefault(c, {})[p] = show(v[1]) + row.update(verdict='cti', solver=z3_version(z3), **state) + n_cti += 1 + else: + row.update(verdict='inconclusive', reason='z3: ' + (first or 'no answer')) + out.append(row) + safe = re.sub(r'[^A-Za-z0-9_]', '_', ob['id']) + with open(os.path.join(d, 'discharge', 'residual', safe + '.lean'), 'w') as f: + f.write('-- Open: %s (%s).\n-- The exact goal no backend proved: a proof of it closes the obligation when\n' + '-- discharge.sh accepts it as a certificate (backend cert).%s\n' + 'import Verify.Obligation\nimport %s\n\ntheorem residual : %s.Valid := by\n skip\n' % ( + ob['id'], summary.get(ob['id'], 'missing'), + '\n-- z3 found a counterexample to induction (cti.json): the candidate fails here.' if row['verdict'] == 'cti' else '', + u['module'][:-5].replace('/', '.'), ob['lean'])) + with open(os.path.join(d, 'discharge', 'cti.json'), 'w') as f: + f.write(json.dumps(out, indent=2, sort_keys=True) + '\n') + print('cti: %d open obligations, %d with a counterexample to induction (%s)' % ( + len(out), n_cti, os.path.join(d, 'discharge', 'cti.json')), file=sys.stderr) + return 0 + +if __name__ == '__main__': + if len(sys.argv) > 1 and sys.argv[1] == 'loopvc': + sys.exit(loopvc_main(sys.argv[2:])) + if len(sys.argv) > 1 and sys.argv[1] == 'cti': + sys.exit(cti_main(sys.argv[2:])) + model_main(sys.argv[1], sys.argv[2]) diff --git a/Verify/Infer/spacerpath-4.35.out b/Verify/Infer/spacerpath-4.35.out new file mode 100644 index 00000000..ca95dd61 --- /dev/null +++ b/Verify/Infer/spacerpath-4.35.out @@ -0,0 +1,21 @@ +spacer: instantiated invariants + inv := fun (a a_1 a_2 a_3 a_4 : Int) => + ¬a + a_3 + -1 * a_4 ≤ -1 ∧ ¬1 ≤ a + a_3 + -1 * a_4 ∧ ¬a + a_1 + -1 * a_4 ≤ -1 ∧ ¬1 ≤ a_1 + -1 * a_2 + -1 * a_3 + a_4 +spacer: instantiated invariants + inv := fun (a a_1 a_2 a_3 a_4 : Int) => + ¬a + a_3 + -1 * a_4 ≤ -1 ∧ ¬a + a_1 + -1 * a_4 ≤ -1 ∧ ¬1 ≤ a + a_3 + -1 * a_4 ∧ ¬1 ≤ a_1 + -1 * a_2 + -1 * a_3 + a_4 +spacer: instantiated invariants + inv := fun (a a_1 : Int) => ¬a + -1 * a_1 ≤ -1 +spacer: instantiated invariants + inv := fun (a a_1 : Int) => ¬a + -1 * a_1 ≤ -1 +spacer: instantiated invariants + inv := fun (a a_1 a_2 : Int) => ¬a + -1 * a_1 + -1 * a_2 ≤ -1 ∧ ¬a + -1 * a_2 ≤ -1 ∧ ¬1 ≤ a + -1 * a_1 + -1 * a_2 +spacer: instantiated invariants + inv := fun (a a_1 a_2 : Int) => ¬a + -1 * a_1 + -1 * a_2 ≤ -1 ∧ ¬a + -1 * a_2 ≤ -1 ∧ ¬1 ≤ a + -1 * a_1 + -1 * a_2 +'FlexEval.SpacerPath.counter_int' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.SpacerPath.counter_u256' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.SpacerPath.okwhile_int' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.SpacerPath.okwhile_u256' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.SpacerPath.drain_int' depends on axioms: [propext, Classical.choice, Quot.sound] +'FlexEval.SpacerPath.drain_u256' depends on axioms: [propext, Classical.choice, Quot.sound] +wall=3.52 s maxrss=1950308 KB diff --git a/Verify/LoomAxioms.lean b/Verify/LoomAxioms.lean new file mode 100644 index 00000000..e8e76d60 --- /dev/null +++ b/Verify/LoomAxioms.lean @@ -0,0 +1,39 @@ +import Verify.CounterBump +import Verify.Fuel + +/-! Axioms of the Loom pieces SolidCore's verification builds on, and of Counter's `bump`. Each +shows only `propext`, `Classical.choice` and `Quot.sound`. -/ + +#print axioms MAlgExceptErr +#print axioms MAlgExceptErrProp +#print axioms MAlgExceptErr.lift_eq +#print axioms triple_bounded +#print axioms triple_while +#print axioms bounded_eq_of_variant +#print axioms TotalCorrectness.repeat_inv +#print axioms PartialCorrectness.repeat_inv +#print axioms triple_forIn_list +#print axioms StateT.wp_get +#print axioms StateT.wp_set +#print axioms ExceptT.wp_throw +#print axioms SolidCore.Verify.wp_eq_loom +#print axioms SolidCore.Verify.wp_get +#print axioms SolidCore.Verify.wp_set +#print axioms SolidCore.Verify.wp_throw +#print axioms SolidCore.Verify.triple_whileM +#print axioms SolidCore.Verify.triple_of_wp +#print axioms SolidCore.Verify.Triple.finishes +#print axioms SolidCore.Verify.tripleSome_of_wp +#print axioms SolidCore.Verify.Triple.some +#print axioms SolidCore.Verify.satisfies_of_triple +#print axioms SolidCore.Verify.CounterBump.body_step +#print axioms SolidCore.Verify.CounterBump.bump_spec +#print axioms SolidCore.Verify.runAny_isSome_iff +#print axioms SolidCore.Verify.runAny_spec +#print axioms SolidCore.Verify.runAny_of_run +#print axioms SolidCore.Verify.tripleAny_of_wp +#print axioms SolidCore.Verify.TripleAny.some +#print axioms SolidCore.Verify.implementsAny_of_some +#print axioms SolidCore.Verify.tripleAny_of_some +#print axioms SolidCore.Verify.triple_of_within +#print axioms SolidCore.Verify.Triple.any diff --git a/Verify/LoomImports.lean b/Verify/LoomImports.lean new file mode 100644 index 00000000..a42e32ae --- /dev/null +++ b/Verify/LoomImports.lean @@ -0,0 +1,16 @@ +import Verify.CounterBump +import Verify.Fuel + +/-! The certified Loom path does not reach Loom's SMT layer (lean-auto, z3, cvc5), its +VC tactic layer or `Verify.Finite` (which uses `native_decide`): elaboration fails +if any of these modules is in this file's import closure. -/ + +open Lean Elab Command in +run_cmd do + let forbidden := [`Loom.SMT, `Auto, `Loom.TacticAsync, `Loom.Meta, + `Loom.MonadAlgebras.WP.Tactic, `Verify.Finite, `Verify.Tactic] + let mods := (← getEnv).header.moduleNames + for f in forbidden do + if mods.any (fun m => m == f || f.isPrefixOf m) then + throwError m!"certified Loom path imports {f}" + logInfo m!"import closure: {mods.size} modules, none forbidden" diff --git a/Verify/Obligation.lean b/Verify/Obligation.lean new file mode 100644 index 00000000..a7eaeb99 --- /dev/null +++ b/Verify/Obligation.lean @@ -0,0 +1,7 @@ +import Verify.Obligation.Smt +import Verify.Obligation.Vc +import Verify.Obligation.Model + +/-! The obligations `solar-verify --emit-lean` exports: the SMT-LIB fragment it writes with its +meaning (`Smt`), its scripts and obligations (`Vc`), and models of its answers (`Model`). An +exported module imports this one. -/ diff --git a/Verify/Obligation/Model.lean b/Verify/Obligation/Model.lean new file mode 100644 index 00000000..7289c40d --- /dev/null +++ b/Verify/Obligation/Model.lean @@ -0,0 +1,67 @@ +import Verify.Obligation.Smt +/-! +Interpretations from finite models: a value for each constant, and for each function a table +of argument values with a default. Tests use them to evaluate exported terms in the kernel, and +they can replay a solver's counterexample. Nothing an obligation means depends on this file. +-/ +namespace SolarVerify.Model +open SolarVerify.Smt + +/-- An Int value. -/ +def int (i : Int) : Val := ⟨.int, show Srt.Den .int from i⟩ + +/-- A Bool value. -/ +def bool (b : Bool) : Val := ⟨.bool, show Srt.Den .bool from b⟩ + +/-- A bitvector value of width `w` and value `n mod 2^w`. -/ +def bv (w n : Nat) : Val := ⟨.bv w, show Srt.Den (.bv w) from BitVec.ofNat w n⟩ + +/-- A record value. -/ +def tup (fields : List Val) : Val := ⟨.tup (sortsOf fields), pack fields⟩ + +/-- A value at sort `s`, or the sort's default when it has another sort. -/ +def valAt (s : Srt) (v : Val) : s.Den := (v.as s).getD s.default + +/-- Whether two values are equal (arrays never compare equal here). -/ +def same (a b : Val) : Bool := + match b.as a.1 with + | some x => match a with + | ⟨.array _ _, _⟩ => false + | ⟨s, y⟩ => firstOrderEq s y x + | none => false +where + /-- Equality of first-order values, which the kernel reduces. -/ + firstOrderEq : (s : Srt) → s.Den → s.Den → Bool + | .bool, a, b => @decide _ (Bool.decEq a b) + | .int, a, b => @decide _ (Int.decEq a b) + | .bv w, a, b => @decide _ ((inferInstance : DecidableEq (BitVec w)) a b) + | .array _ _, _, _ => false + | .tup fs, a, b => tupEq fs a b + tupEq : (ss : List Srt) → Srt.DenList ss → Srt.DenList ss → Bool + | [], _, _ => true + | s :: ss, (a, as), (b, bs) => firstOrderEq s a b && tupEq ss as bs + +/-- An array of sort `(Array idx elem)`: `entries` over the default `d`, the first entry for a +key winning. -/ +def array (idx elem : Srt) (d : Val) (entries : List (Val × Val)) : Val := + ⟨.array idx elem, fun k => + match entries.find? (fun e => same e.1 ⟨idx, k⟩) with + | some e => valAt elem e.2 + | none => valAt elem d⟩ + +/-- A function: the value of the first row whose arguments equal the call's, else `d`. -/ +def table (d : Val) (rows : List (List Val × Val)) (args : List Val) : Val := + match rows.find? (fun r => r.1.length == args.length && (r.1.zip args).all (fun p => same p.1 p.2)) with + | some r => r.2 + | none => d + +/-- The interpretation giving symbol `f` the function `fns[f]`, and quotients and remainders by +zero the value 0. -/ +def env (fns : List (List Val → Val)) : Env where + fn f args ret xs := match fns[f]? with + | some g => valAt ret (g (Srt.unpack args xs)) + | none => ret.default + divZero _ := 0 + modZero _ := 0 + +end SolarVerify.Model diff --git a/Verify/Obligation/Smt.lean b/Verify/Obligation/Smt.lean new file mode 100644 index 00000000..d6af72f1 --- /dev/null +++ b/Verify/Obligation/Smt.lean @@ -0,0 +1,470 @@ +/- +The SMT-LIB fragment solar-verify writes, as a deep embedding with its denotation. + +This file is the meaning of every verification condition `solar-verify --emit-lean` exports: +see docs/VERIFY_LEAN.md. Format version 1. + +Sorts are SMT-LIB's `Bool`, `Int`, `(_ BitVec w)` and `(Array I E)`, and records: solar-verify +declares each struct as a datatype with one constructor and no recursion, which the export +writes as the product of its field sorts. Terms are untyped: `Term.eval` infers each sort and +returns `none` on an ill-sorted term. +An environment interprets every declared function symbol (constants are 0-ary symbols) and the +values SMT-LIB leaves unspecified: integer `div` and `mod` by zero. + +Evaluation reduces in the kernel except at quantifiers and equality of arrays, which decide with +classical logic, so `decide` in the kernel evaluates any term free of them. +-/ +namespace SolarVerify.Smt + +/-- A sort. A record is the product of its field sorts. -/ +inductive Srt where + | bool + | int + | bv (w : Nat) + | array (idx elem : Srt) + | tup (fields : List Srt) + deriving Repr, Inhabited + +mutual +/-- Decidable equality of sorts, written out so that the kernel reduces it. -/ +def Srt.decEq : (a b : Srt) → Decidable (a = b) + | .bool, .bool => isTrue rfl + | .int, .int => isTrue rfl + | .bv w, .bv v => + if h : w = v then isTrue (h ▸ rfl) else isFalse (fun e => by injection e; contradiction) + | .array i e, .array j f => + match Srt.decEq i j, Srt.decEq e f with + | isTrue h1, isTrue h2 => isTrue (h1 ▸ h2 ▸ rfl) + | isFalse h, _ => isFalse (fun x => by injection x; contradiction) + | _, isFalse h => isFalse (fun x => by injection x; contradiction) + | .tup fs, .tup gs => + match Srt.decEqList fs gs with + | isTrue h => isTrue (h ▸ rfl) + | isFalse h => isFalse (fun x => by injection x; contradiction) + | .bool, .int | .bool, .bv _ | .bool, .array _ _ | .bool, .tup _ + | .int, .bool | .int, .bv _ | .int, .array _ _ | .int, .tup _ + | .bv _, .bool | .bv _, .int | .bv _, .array _ _ | .bv _, .tup _ + | .array _ _, .bool | .array _ _, .int | .array _ _, .bv _ | .array _ _, .tup _ + | .tup _, .bool | .tup _, .int | .tup _, .bv _ | .tup _, .array _ _ => + isFalse (fun h => by cases h) +def Srt.decEqList : (a b : List Srt) → Decidable (a = b) + | [], [] => isTrue rfl + | x :: xs, y :: ys => + match Srt.decEq x y, Srt.decEqList xs ys with + | isTrue h1, isTrue h2 => isTrue (h1 ▸ h2 ▸ rfl) + | isFalse h, _ => isFalse (fun e => by injection e; contradiction) + | _, isFalse h => isFalse (fun e => by injection e; contradiction) + | [], _ :: _ => isFalse (fun h => by cases h) + | _ :: _, [] => isFalse (fun h => by cases h) +end + +instance : DecidableEq Srt := Srt.decEq + +mutual +/-- The values of a sort. An array is a total function, as in SMT-LIB's theory of arrays. -/ +def Srt.Den : Srt → Type + | .bool => Bool + | .int => Int + | .bv w => BitVec w + | .array i e => Srt.Den i → Srt.Den e + | .tup fs => Srt.DenList fs +/-- The values of a list of sorts, one each. -/ +def Srt.DenList : List Srt → Type + | [] => Unit + | s :: ss => Srt.Den s × Srt.DenList ss +end + +mutual +/-- A value of every sort, for building interpretations. -/ +def Srt.default : (s : Srt) → s.Den + | .bool => (false : Bool) + | .int => (0 : Int) + | .bv w => (0 : BitVec w) + | .array _ e => fun _ => Srt.default e + | .tup fs => Srt.defaultList fs +/-- A value of every list of sorts. -/ +def Srt.defaultList : (ss : List Srt) → Srt.DenList ss + | [] => () + | s :: ss => (Srt.default s, Srt.defaultList ss) +end + +/-- A value with its sort. -/ +abbrev Val := (s : Srt) × s.Den + +mutual +/-- SMT-LIB equality of two values of one sort: structural on records, extensional (classical) +on arrays. -/ +noncomputable def Srt.beq : (s : Srt) → s.Den → s.Den → Bool + | .bool, a, b => @decide _ (Bool.decEq a b) + | .int, a, b => @decide _ (Int.decEq a b) + | .bv w, a, b => @decide _ ((inferInstance : DecidableEq (BitVec w)) a b) + | .array i e, a, b => + @decide (∀ k : Srt.Den i, Srt.beq e (a k) (b k) = true) (Classical.propDecidable _) + | .tup fs, a, b => Srt.beqList fs a b +noncomputable def Srt.beqList : (ss : List Srt) → Srt.DenList ss → Srt.DenList ss → Bool + | [], _, _ => true + | s :: ss, (a, as), (b, bs) => Srt.beq s a b && Srt.beqList ss as bs +end + +/-- A value's view at a sort it may have. -/ +def Val.as (v : Val) (s : Srt) : Option s.Den := + if h : v.1 = s then some (h ▸ v.2) else none + +/-- A list of values as the values of a list of sorts. -/ +def Val.asList : List Val → (ss : List Srt) → Option (Srt.DenList ss) + | [], [] => some () + | v :: vs, s :: ss => do + let x ← v.as s + let xs ← Val.asList vs ss + pure (x, xs) + | _, _ => none + +/-- The values of a record, with their sorts. -/ +def Srt.unpack : (ss : List Srt) → Srt.DenList ss → List Val + | [], () => [] + | s :: ss, (x, xs) => ⟨s, x⟩ :: Srt.unpack ss xs + +/-- Field `i` of a record. -/ +def Srt.field : (ss : List Srt) → Srt.DenList ss → Nat → Option Val + | [], _, _ => none + | s :: _, (x, _), 0 => some ⟨s, x⟩ + | _ :: ss, (_, xs), n + 1 => Srt.field ss xs n + +/-- The bitvector a value holds, with its width. -/ +def Val.bv? : Val → Option ((w : Nat) × BitVec w) + | ⟨.bv w, x⟩ => some ⟨w, x⟩ + | _ => none + +/-- The Bool a value holds. -/ +def boolOf (o : Option Val) : Option Bool := o.bind (fun v => v.as .bool) + +/-- The built-in operators, by their SMT-LIB names. The n-ary and chainable ones take as many +arguments as SMT-LIB allows. -/ +inductive Op where + -- Core. + | not | and | or | xor | implies | eq | distinct | ite + -- Ints. `sub` with one argument is negation, as SMT-LIB's `-`. + | add | sub | mul | div | mod | abs | lt | le | gt | ge + -- Arrays. + | select | store + -- Conversions. + | bv2nat | int2bv (w : Nat) + -- Bitvectors. + | bvadd | bvsub | bvmul | bvudiv | bvurem | bvsdiv | bvsrem | bvsmod | bvneg + | bvand | bvor | bvxor | bvnot | bvshl | bvlshr | bvashr + | bvult | bvule | bvugt | bvuge | bvslt | bvsle | bvsgt | bvsge + | concat | extract (hi lo : Nat) | zeroExtend (n : Nat) | signExtend (n : Nat) + deriving Repr, DecidableEq, Inhabited + +/-- A term. Function symbols are numbered by their declaration in the script; bound variables +are de Bruijn indices, 0 the last binder of the innermost quantifier. -/ +inductive Term where + | bool (b : Bool) + | int (i : Int) + /-- The bitvector literal of width `w` and value `n mod 2^w`. -/ + | bv (w n : Nat) + /-- Declared function symbol `f` applied to its arguments (none for a constant). -/ + | fn (f : Nat) (args : List Term) + /-- Bound variable `i`. -/ + | var (i : Nat) + | app (op : Op) (args : List Term) + /-- `((as const (Array idx E)) v)`. -/ + | constArray (idx : Srt) (v : Term) + /-- The constructor of a record. -/ + | mk (fields : List Term) + /-- Field `i` of a record. -/ + | proj (i : Nat) (t : Term) + | «forall» (binders : List Srt) (body : Term) + | «exists» (binders : List Srt) (body : Term) + deriving Repr, Inhabited + +/-- A declared function symbol: its name (for people), argument sorts and result sort. -/ +structure Decl where + name : String + args : List Srt + ret : Srt + deriving Repr, Inhabited + +/-- An interpretation: a function for every symbol number at every signature (a term uses only +the one its declaration gives), and integer `div` and `mod` by zero, which SMT-LIB leaves +unspecified. -/ +structure Env where + fn : Nat → (args : List Srt) → (ret : Srt) → Srt.DenList args → ret.Den + divZero : Int → Int + modZero : Int → Int + +/-- Bound values, the innermost first. -/ +abbrev Locals := List Val + +section ops + +/-- SMT-LIB `div`: the Euclidean quotient. -/ +def intDiv (env : Env) (a b : Int) : Int := if b = 0 then env.divZero a else a.ediv b + +/-- SMT-LIB `mod`: the Euclidean remainder, in `[0, |b|)`. -/ +def intMod (env : Env) (a b : Int) : Int := if b = 0 then env.modZero a else a.emod b + +/-- A relation over consecutive arguments, as `(< a b c)` means `a < b < c`. -/ +def chain {α} (r : α → α → Bool) : α → List α → Bool + | a, b :: rest => r a b && chain r b rest + | _, [] => true + +/-- A relation over every pair of positions. -/ +def pairwise {α} (r : α → α → Bool) : List α → Bool + | [] => true + | a :: rest => rest.all (r a) && pairwise r rest + +/-- The Ints of a list of values. -/ +def ints : List Val → Option (List Int) + | [] => some [] + | v :: vs => do let x ← v.as .int; let xs ← ints vs; pure (x :: xs) + +/-- The Bools of a list of values. -/ +def bools : List Val → Option (List Bool) + | [] => some [] + | v :: vs => do let x ← v.as .bool; let xs ← bools vs; pure (x :: xs) + +/-- Values of one sort: the first one's. -/ +def sameSort (s : Srt) : List Val → Option (List s.Den) + | [] => some [] + | v :: vs => do let x ← v.as s; let xs ← sameSort s vs; pure (x :: xs) + +/-- Bitvectors of one width, the width of the first. -/ +def bvs : List Val → Option ((w : Nat) × List (BitVec w)) + | [] => none + | v :: vs => do + let ⟨w, x⟩ ← v.bv? + let xs ← sameSort (.bv w) vs + pure ⟨w, x :: xs⟩ + +/-- A left fold over at least two arguments. -/ +def foldl2 {α} (f : α → α → α) : List α → Option α + | a :: b :: rest => some (rest.foldl f (f a b)) + | _ => none + +/-- `=>` over at least two arguments, associating to the right. -/ +def impliesChain (bs : List Bool) : Option Bool := + match bs.reverse with + | last :: init@(_ :: _) => some (init.foldl (fun acc a => !a || acc) last) + | _ => none + +/-- An Int relation, chained over at least two arguments. -/ +def intRel (r : Int → Int → Bool) (args : List Val) : Option Val := do + let xs ← ints args + match xs with + | a :: rest@(_ :: _) => some ⟨.bool, chain r a rest⟩ + | _ => none + +/-- A bitvector relation of two arguments. -/ +def bvRel (r : (w : Nat) → BitVec w → BitVec w → Bool) (args : List Val) : Option Val := do + let ⟨w, xs⟩ ← bvs args + match xs with + | [a, b] => some ⟨.bool, r w a b⟩ + | _ => none + +/-- A left-associative bitvector operation of at least two arguments. -/ +def bvFold (f : (w : Nat) → BitVec w → BitVec w → BitVec w) (args : List Val) : Option Val := do + let ⟨w, xs⟩ ← bvs args + let r ← foldl2 (f w) xs + pure ⟨.bv w, r⟩ + +/-- A bitvector operation of two arguments. -/ +def bvBin (f : (w : Nat) → BitVec w → BitVec w → BitVec w) (args : List Val) : Option Val := do + let ⟨w, xs⟩ ← bvs args + match xs with + | [a, b] => some ⟨.bv w, f w a b⟩ + | _ => none + +/-- A bitvector operation of one argument. -/ +def bvUn (f : (w : Nat) → BitVec w → BitVec w) (args : List Val) : Option Val := do + let ⟨w, xs⟩ ← bvs args + match xs with + | [a] => some ⟨.bv w, f w a⟩ + | _ => none + +/-- The value of an operator on the values of its arguments, or `none` when they do not have +the sorts and number it takes. Bitvector division and remainder by zero are as SMT-LIB 2.6 +defines them. -/ +noncomputable def Op.apply (env : Env) : Op → List Val → Option Val + | .not, args => do + let bs ← bools args + match bs with | [a] => some ⟨.bool, !a⟩ | _ => none + | .and, args => do let bs ← bools args; pure ⟨.bool, bs.all id⟩ + | .or, args => do let bs ← bools args; pure ⟨.bool, bs.any id⟩ + | .xor, args => do let bs ← bools args; let r ← foldl2 Bool.xor bs; pure ⟨.bool, r⟩ + | .implies, args => do let bs ← bools args; let r ← impliesChain bs; pure ⟨.bool, r⟩ + | .eq, args => + match args with + | a :: rest@(_ :: _) => do + let xs ← sameSort a.1 rest + pure ⟨.bool, chain (Srt.beq a.1) a.2 xs⟩ + | _ => none + | .distinct, args => + match args with + | a :: rest@(_ :: _) => do + let xs ← sameSort a.1 rest + pure ⟨.bool, pairwise (fun x y => !Srt.beq a.1 x y) (a.2 :: xs)⟩ + | _ => none + | .ite, args => + match args with + | [c, t, e] => do + let b ← boolOf (some c) + let e' ← e.as t.1 + pure (if b then t else ⟨t.1, e'⟩) + | _ => none + | .add, args => do let xs ← ints args; let r ← foldl2 (· + ·) xs; pure ⟨.int, r⟩ + | .sub, args => do + let xs ← ints args + match xs with + | [a] => some ⟨.int, -a⟩ + | _ => do let r ← foldl2 (· - ·) xs; pure ⟨.int, r⟩ + | .mul, args => do let xs ← ints args; let r ← foldl2 (· * ·) xs; pure ⟨.int, r⟩ + | .div, args => do let xs ← ints args; let r ← foldl2 (intDiv env) xs; pure ⟨.int, r⟩ + | .mod, args => do + let xs ← ints args + match xs with | [a, b] => some ⟨.int, intMod env a b⟩ | _ => none + | .abs, args => do + let xs ← ints args + match xs with | [a] => some ⟨.int, (a.natAbs : Int)⟩ | _ => none + | .lt, args => intRel (fun a b => decide (a < b)) args + | .le, args => intRel (fun a b => decide (a ≤ b)) args + | .gt, args => intRel (fun a b => decide (b < a)) args + | .ge, args => intRel (fun a b => decide (b ≤ a)) args + | .select, args => + match args with + | [⟨.array i e, f⟩, k] => do let k' ← k.as i; pure ⟨e, f k'⟩ + | _ => none + | .store, args => + match args with + | [⟨.array i e, f⟩, k, v] => do + let k' ← k.as i + let v' ← v.as e + pure ⟨.array i e, fun j => if Srt.beq i j k' then v' else f j⟩ + | _ => none + | .bv2nat, args => + match args with + | [⟨.bv _, x⟩] => some ⟨.int, (x.toNat : Int)⟩ + | _ => none + | .int2bv w, args => do + let xs ← ints args + match xs with | [a] => some ⟨.bv w, BitVec.ofInt w a⟩ | _ => none + | .bvadd, args => bvFold (fun _ a b => a + b) args + | .bvsub, args => bvBin (fun _ a b => a - b) args + | .bvmul, args => bvFold (fun _ a b => a * b) args + | .bvudiv, args => bvBin (fun _ a b => BitVec.smtUDiv a b) args + | .bvurem, args => bvBin (fun _ a b => BitVec.umod a b) args + | .bvsdiv, args => bvBin (fun _ a b => BitVec.smtSDiv a b) args + | .bvsrem, args => bvBin (fun _ a b => BitVec.srem a b) args + | .bvsmod, args => bvBin (fun _ a b => BitVec.smod a b) args + | .bvneg, args => bvUn (fun _ a => -a) args + | .bvand, args => bvFold (fun _ a b => a &&& b) args + | .bvor, args => bvFold (fun _ a b => a ||| b) args + | .bvxor, args => bvFold (fun _ a b => a ^^^ b) args + | .bvnot, args => bvUn (fun _ a => ~~~a) args + | .bvshl, args => bvBin (fun _ a b => a <<< b.toNat) args + | .bvlshr, args => bvBin (fun _ a b => a >>> b.toNat) args + | .bvashr, args => bvBin (fun _ a b => a.sshiftRight b.toNat) args + | .bvult, args => bvRel (fun _ a b => BitVec.ult a b) args + | .bvule, args => bvRel (fun _ a b => BitVec.ule a b) args + | .bvugt, args => bvRel (fun _ a b => BitVec.ult b a) args + | .bvuge, args => bvRel (fun _ a b => BitVec.ule b a) args + | .bvslt, args => bvRel (fun _ a b => BitVec.slt a b) args + | .bvsle, args => bvRel (fun _ a b => BitVec.sle a b) args + | .bvsgt, args => bvRel (fun _ a b => BitVec.slt b a) args + | .bvsge, args => bvRel (fun _ a b => BitVec.sle b a) args + | .concat, args => + match args with + | [⟨.bv w, a⟩, ⟨.bv v, b⟩] => some ⟨.bv (w + v), BitVec.append (n := w) (m := v) a b⟩ + | _ => none + | .extract hi lo, args => + match args with + | [⟨.bv w, a⟩] => + if lo ≤ hi ∧ hi < w then some ⟨.bv (hi - lo + 1), a.extractLsb' lo (hi - lo + 1)⟩ + else none + | _ => none + | .zeroExtend n, args => + match args with + | [⟨.bv w, a⟩] => some ⟨.bv (w + n), a.setWidth (w + n)⟩ + | _ => none + | .signExtend n, args => + match args with + | [⟨.bv w, a⟩] => some ⟨.bv (w + n), a.signExtend (w + n)⟩ + | _ => none + +end ops + +/-- The sorts of a list of values. -/ +def sortsOf : List Val → List Srt + | [] => [] + | v :: vs => v.1 :: sortsOf vs + +/-- A record value from its fields. -/ +def pack : (vs : List Val) → Srt.DenList (sortsOf vs) + | [] => () + | v :: vs => (v.2, pack vs) + +/-- Bound values after binding `xs`, of sorts `ss`: the last binder is innermost. -/ +def bindAll (ss : List Srt) (xs : Srt.DenList ss) (locals : Locals) : Locals := + (Srt.unpack ss xs).reverse ++ locals + +mutual +/-- The value of a term under an interpretation of the declared symbols `decls` and values of +its bound variables, or `none` when the term or any part of it is ill-sorted. A quantifier is +`none` unless its body is a formula at every value of its binders. -/ +noncomputable def Term.eval (env : Env) (decls : List Decl) (locals : Locals) : Term → Option Val + | .bool b => some ⟨.bool, b⟩ + | .int i => some ⟨.int, i⟩ + | .bv w n => some ⟨.bv w, BitVec.ofNat w n⟩ + | .fn f args => do + let d ← decls[f]? + let vs ← Term.evalList env decls locals args + let xs ← Val.asList vs d.args + pure ⟨d.ret, env.fn f d.args d.ret xs⟩ + | .var i => locals[i]? + | .app op args => do + let vs ← Term.evalList env decls locals args + op.apply env vs + | .constArray idx v => do + let x ← Term.eval env decls locals v + pure ⟨.array idx x.1, fun _ => x.2⟩ + | .mk fields => do + let vs ← Term.evalList env decls locals fields + pure ⟨.tup (sortsOf vs), pack vs⟩ + | .proj i t => do + let v ← Term.eval env decls locals t + match v with + | ⟨.tup ss, x⟩ => Srt.field ss x i + | _ => none + | .forall ss body => + @ite _ (∀ xs : Srt.DenList ss, (boolOf (Term.eval env decls (bindAll ss xs locals) body)).isSome) + (Classical.propDecidable _) + (some ⟨.bool, @decide (∀ xs : Srt.DenList ss, + boolOf (Term.eval env decls (bindAll ss xs locals) body) = some true) + (Classical.propDecidable _)⟩) + none + | .exists ss body => + @ite _ (∀ xs : Srt.DenList ss, (boolOf (Term.eval env decls (bindAll ss xs locals) body)).isSome) + (Classical.propDecidable _) + (some ⟨.bool, @decide (∃ xs : Srt.DenList ss, + boolOf (Term.eval env decls (bindAll ss xs locals) body) = some true) + (Classical.propDecidable _)⟩) + none +/-- The values of a list of terms. -/ +noncomputable def Term.evalList (env : Env) (decls : List Decl) (locals : Locals) : + List Term → Option (List Val) + | [] => some [] + | t :: ts => do + let v ← Term.eval env decls locals t + let vs ← Term.evalList env decls locals ts + pure (v :: vs) +end + +/-- A closed formula holds: it is well-sorted and evaluates to true. -/ +def Holds (env : Env) (decls : List Decl) (t : Term) : Prop := + boolOf (Term.eval env decls [] t) = some true + +/-- The Bool a closed formula evaluates to, for tests that evaluate in the kernel. -/ +noncomputable def Term.evalBool (env : Env) (decls : List Decl) (t : Term) : Option Bool := + boolOf (Term.eval env decls [] t) + +end SolarVerify.Smt diff --git a/Verify/Obligation/Vc.lean b/Verify/Obligation/Vc.lean new file mode 100644 index 00000000..1af20145 --- /dev/null +++ b/Verify/Obligation/Vc.lean @@ -0,0 +1,38 @@ +import Verify.Obligation.Smt +/-! +Verification conditions as solar-verify exports them: a script of declarations and assertions, +as the solver's assertion stack held them, and obligations that each ask the solver to show a +goal under a guard and the first assertions of the script. See docs/VERIFY_LEAN.md. +-/ +namespace SolarVerify.Vc +open SolarVerify.Smt + +/-- The version of the export format this library reads. -/ +def formatVersion : Nat := 1 + +/-- The declarations and assertions in scope in the solver, in the order solar-verify sent them. +A `define-fun` is a declaration and an assertion that it equals its body at every argument. -/ +structure Script where + decls : List Decl + asserts : List Term + deriving Repr, Inhabited + +/-- One query: the goal follows from the first `upto` assertions of the script and the guard. +solar-verify asks the solver whether `(and asserts guard (not goal))` is unsatisfiable. -/ +structure Obligation where + script : Script + upto : Nat + guard : Term + goal : Term + deriving Repr, Inhabited + +/-- The obligation as one closed formula, `(=> (and a_0 ... a_{upto-1} guard) goal)`. -/ +def Obligation.formula (o : Obligation) : Term := + .app .implies [.app .and (o.script.asserts.take o.upto ++ [o.guard]), o.goal] + +/-- The obligation holds: its formula is well-sorted and true under every interpretation of the +declared symbols. Exactly when the query solar-verify sends is unsatisfiable. -/ +def Obligation.Valid (o : Obligation) : Prop := + ∀ env : Env, Holds env o.script.decls o.formula + +end SolarVerify.Vc diff --git a/Verify/Run.lean b/Verify/Run.lean new file mode 100644 index 00000000..8f2c485a --- /dev/null +++ b/Verify/Run.lean @@ -0,0 +1,132 @@ +import Verify.Abi + +/-! +# Running a call from a given storage + +The wide refinement proofs run SolidCore on calls from empty storage (`Wide.run_eq`). A +specification over a contract whose constructor leaves storage, such as c4's packed +`uint8 w = 7`, runs from that storage instead: on `callAt sel ws s`, the call of selector +`sel` on the free argument words `ws` from the storage `s`, which `Wide.run_eq_at` rewrites +to the ABI dispatcher of the core contract on the deployed state with `s` written over its +storage, for `src_symex` to evaluate. `callAt`, `deployedAt` and `run_eq_at` live in +`SolidCore.Refinement.Wide`, which the refinement proofs from a given storage share. + +`implements_of_run` turns one theorem per function on free words into `Implements` on +`Abi.fullScope`. `vcs_of_fullScope` states the verification conditions on `Abi.fullScope` +call by call, with the argument words and the initial storage known, the form `sc_vcgen` +proves. +-/ + +namespace SolidCore.Verify + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source + +/-- One theorem per function, on free argument words that meet `ok`, gives `Implements` on +the calls of `Abi.fullScope` whose argument words meet `ok`. -/ +theorem implements_of_run {fuel : Nat} {c : TypeCheck.CheckedContract} {fns : List Fn} + {s : List (Nat × Nat)} {n : Nat} {ok : List Nat → Prop} {model : List Nat → SolM (List Nat)} + (hn : ∀ fn ∈ fns, fn.params.length = n) + (h : ∀ fn ∈ fns, ∀ ws : List U256, ws.length = n → ok (ws.map BitVec.toNat) → + Source.run fuel c (callAt fn.sel ws s) = + some (observe (slotValue s) (model (ws.map BitVec.toNat) (slotValue s)))) : + Implements fuel c (fun call => fullScope fns s call ∧ ok (argWords n call)) (argWords n) + model := by + rintro _ ⟨⟨fn, hfn, args, hlen, hargs, rfl⟩, hok⟩ + rw [hn fn hfn] at hlen + have hw : argWords n ({ calldata := Abi.calldata fn.sel args, callvalue := 0, storage := s } : + Call) = args := hlen ▸ argWords_calldata _ args hargs 0 s + have hws := map_ofNat_toNat args hargs + rw [hw] at hok ⊢ + have := h fn hfn (args.map (BitVec.ofNat 256)) (by simpa using hlen) (by rw [hws]; exact hok) + rw [hws, ← callAt_of_args _ _ hargs] at this + exact this + +/-- `implements_of_run` with no condition on the argument words. -/ +theorem implements_of_run' {fuel : Nat} {c : TypeCheck.CheckedContract} {fns : List Fn} + {s : List (Nat × Nat)} {n : Nat} {model : List Nat → SolM (List Nat)} + (hn : ∀ fn ∈ fns, fn.params.length = n) + (h : ∀ fn ∈ fns, ∀ ws : List U256, ws.length = n → + Source.run fuel c (callAt fn.sel ws s) = + some (observe (slotValue s) (model (ws.map BitVec.toNat) (slotValue s)))) : + Implements fuel c (fullScope fns s) (argWords n) model := fun call hs => + implements_of_run (ok := fun _ => True) hn (fun fn hfn ws hl _ => h fn hfn ws hl) call + ⟨hs, trivial⟩ + +/-- `Implements` on a scope holds on every smaller one. -/ +theorem Implements.mono {fuel : Nat} {c : TypeCheck.CheckedContract} {scope scope' : Call → Prop} + {args : Call → List Nat} {model : List Nat → SolM (List Nat)} + (h : Implements fuel c scope args model) (hs : ∀ call, scope' call → scope call) : + Implements fuel c scope' args model := fun call hc => h call (hs call hc) + +/-- The verification conditions on `Abi.fullScope`, call by call: for each function and each +list of argument words, with the call, its argument words and its initial storage known. -/ +theorem vcs_of_fullScope {fns : List Fn} {s : List (Nat × Nat)} {n : Nat} + {model : List Nat → SolM (List Nat)} {pre : Call → Prop} {post : Call → Observable → Prop} + (hn : ∀ fn ∈ fns, fn.params.length = n) + (h : ∀ fn ∈ fns, ∀ call args, + call = ({ calldata := Abi.calldata fn.sel args, callvalue := 0, storage := s } : Call) → + argWords n call = args → args.length = n → (∀ a ∈ args, a < 2 ^ 256) → + initStorage call = slotValue s → pre call → + wp (model args) + (fun out _ s' => post call { success := true, output := out, logs := [], storage := s' }) + (fun e => post call { success := false, output := e, logs := [], storage := slotValue s }) + (slotValue s)) : + ∀ call, fullScope fns s call → pre call → vc model (argWords n) post call := by + rintro _ ⟨fn, hfn, args, hlen, hargs, rfl⟩ hpre + rw [hn fn hfn] at hlen + have hw : argWords n ({ calldata := Abi.calldata fn.sel args, callvalue := 0, storage := s } : + Call) = args := hlen ▸ argWords_calldata _ args hargs 0 s + have := h fn hfn _ args rfl hw hlen hargs rfl hpre + simp only [vc, hw] + exact this + +/-- The verification conditions on a smaller scope follow from those on a larger one. -/ +theorem vcs_mono {scope scope' pre : Call → Prop} {model : List Nat → SolM (List Nat)} + {args : Call → List Nat} {post : Call → Observable → Prop} + (h : ∀ call, scope call → pre call → vc model args post call) + (hs : ∀ call, scope' call → scope call) : + ∀ call, scope' call → pre call → vc model args post call := fun call hc hp => + h call (hs call hc) hp + +/-- A slot of a storage map after the entries `σ` are written over it, as the last write of the +slot or the map's own entry. -/ +theorem getElem?_foldl_insertLoop (σ : List (Nat × Nat)) (m0 : StorageMap) (q : Nat) : + (σ.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) m0)[q]? = + σ.foldl (fun acc kv => if Shared.norm kv.1 = q then some (Shared.norm kv.2) else acc) + m0[q]? := by + induction σ generalizing m0 with + | nil => rfl + | cons kv σ ih => + simp only [List.foldl_cons] + rw [ih] + simp only [StorageMap.insertLoop, Std.HashMap.getElem?_insert, beq_iff_eq] + +/-- The last write of a slot among `σ`, as a word, is `slotValue`'s fold. -/ +theorem getD_foldl (σ : List (Nat × Nat)) (k : Nat) (a : Option Nat) (b : Nat) (h : a.getD 0 = b) : + (σ.foldl (fun acc kv => if Shared.norm kv.1 = k % 2 ^ 256 then some (Shared.norm kv.2) else acc) + a).getD 0 = + σ.foldl (fun acc kv => if kv.1 % 2 ^ 256 = k % 2 ^ 256 then kv.2 % 2 ^ 256 else acc) b := by + induction σ generalizing a b with + | nil => simpa using h + | cons kv σ ih => + simp only [List.foldl_cons] + apply ih + simp only [Shared.norm, Shared.wordModulus, EvmYul.UInt256.size, Nat.reducePow] + split <;> simp_all + +/-- A slot of the storage a call writes over an empty deployed storage reads as `slotValue`. -/ +theorem getD_storage {m0 : StorageMap} (h0 : ∀ q : Nat, m0[q]? = none) (σ : List (Nat × Nat)) + (k : Nat) : + ((σ.foldl (fun acc kv => acc.insertLoop kv.1 kv.2) m0)[k % 2 ^ 256]?).getD 0 = + slotValue σ k := by + rw [getElem?_foldl_insertLoop, h0] + exact getD_foldl σ k none 0 rfl + +/-- A constructor that leaves no storage leaves exactly the empty list of entries. -/ +theorem deployedAt_of_deployed {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + (hd : Deployed fuel c d) : DeployedAt fuel c d [] := + ⟨hd.cons, by + exact List.isEmpty_iff.mp (by rw [Std.HashMap.isEmpty_toList]; exact hd.storage), hd.events⟩ + +end SolidCore.Verify diff --git a/Verify/ShapeBundle.lean b/Verify/ShapeBundle.lean new file mode 100644 index 00000000..e7c4468e --- /dev/null +++ b/Verify/ShapeBundle.lean @@ -0,0 +1,46 @@ +import Verify.Shapes +import Verify.Spec.Contract + +/-! +# A postcondition read off solar-verify's exported spec + +`bundlePost b ctxOf step` is the meaning of an exported spec bundle `b` +(`solar-verify --emit-lean-spec`, `SolidCore.Spec.Bundle`) as a postcondition of one call: for every +function spec of the bundle and every pre-state meeting its precondition on the call +(`SolidCore.Spec.Pre`), the observable meets its postcondition (`SolidCore.Spec.Post`). The certify +driver states a published `Shapes.Certified` with this postcondition over the bundle it exports in +the same run, so the specification the statement speaks of is solar-verify's, bound by the kernel's +type check rather than restated by hand. + +`meets_of_bundle` turns `SolidCore.Spec.Holds` of the source on a scope that covers the valid +calls into `Shapes.Meets` of `bundlePost` (the source is deterministic, so the observable `Holds` +names is the one every run gives). +-/ + +namespace SolidCore.Refinement.Shapes + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Final + +/-- solar-verify's exported spec `b` as a postcondition of one call. -/ +def bundlePost (b : SolidCore.Spec.Bundle) (ctxOf : Call → SolidCore.Spec.Ctx) + (step : SolidCore.Spec.GhostStep) (call : Call) (obs : Observable) : Prop := + ∀ fs ∈ b.spec.specs, ∀ (args : List Int) (pre : SolidCore.Spec.State), + SolidCore.Spec.Pre b fs (ctxOf call) pre call args → + SolidCore.Spec.Post b fs (ctxOf call) pre (step call pre.ghost) obs args + +/-- `Holds` of the exported spec on a scope covering the valid calls is `Meets` of `bundlePost`. -/ +theorem meets_of_bundle {S : Sem} {p : S.Prog} {Valid scope : Call → Prop} + {b : SolidCore.Spec.Bundle} {ctxOf : Call → SolidCore.Spec.Ctx} {step : SolidCore.Spec.GhostStep} + (hv : ∀ call, Valid call → scope call) (h : SolidCore.Spec.Holds S p scope b ctxOf step) : + Meets S p Valid (bundlePost b ctxOf step) := by + intro call hc obs hrun fs hfs args pre hpre + obtain ⟨obs', h1, h2⟩ := h fs hfs call (hv call hc) args pre hpre + rw [hrun] at h1 + cases h1 + exact h2 + +/-- info: 'SolidCore.Refinement.Shapes.meets_of_bundle' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms meets_of_bundle + +end SolidCore.Refinement.Shapes diff --git a/Verify/ShapeCtx.lean b/Verify/ShapeCtx.lean new file mode 100644 index 00000000..a2b59e16 --- /dev/null +++ b/Verify/ShapeCtx.lean @@ -0,0 +1,93 @@ +import Verify.ShapeGeneric +import Verify.Spec.Contract +import SolidCore.Refinement.Solar.AssembleCtxCall + +/-! +# The functional shape of a generic-stage contract through the context checker + +For a contract whose bytecode only the checker with calling contexts and STATICCALL accepts +(`AssembleCtx.checkXB`, the runtime of a token with `ecrecover`, whose internal functions are +called from several places), and on the calls of the functions the generic source stage accepts, +`functional_ctx` composes: + +* the generic source stage (`Generic.check` on the first lowered MIR, under every oracle whose + caller and Keccak-256 are EthLib's), +* solar-tv's backend stages from that MIR to the final EVM IR, under every oracle, on a scope + covering the valid calls, +* the context checker's per-run theorem: at every gas below `2 ^ 256`, each valid call has an + oracle meeting the certificate's `CertOk` under which every result of the exact bytecode is the + final EVM IR's, or a failure that changes nothing, +* a specification of SolidCore's runs on the valid calls (`Meets`), + +into `Shapes.Functional`: equivalence (gas-insensitive), termination (`Generic.definedAt`) and the +specification. It does not give `Resources`: the context checker proves no gas bound, so a +contract certified through this theorem never reaches `Shapes.Certified` from it alone. + +`meets_of_holdsFn` turns a solar-verify function spec proved of SolidCore's contract +(`SolidCore.Spec.HoldsFn`) into the postcondition `holdsPost` of every source result. +-/ + +namespace SolidCore.Refinement.Shapes + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Final SolidCore.Refinement.Abi +open SolidCore.Refinement.Solar SolidCore.Solidity + +/-- An oracle whose caller and Keccak-256 are EthLib's is one every generic source stage takes. -/ +theorem sourceEnvOk_of {o : Machine.Oracle} (h : Assemble.OracleOk o) : Generic.SourceEnvOk o := + ⟨by unfold Generic.CallerOk; rw [h.1]; exact callerAddress_word, + fun a b _ _ => by rw [h.2]; exact Keccak.ethKeccak_twoWords a b⟩ + +/-- **The functional shape through the context checker.** -/ +theorem functional_ctx {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {m : MIR.Lowered.Module} + {fns : List Fn} {env : Generic.EnvFlags} + (hchk : Generic.check fuel mirFuel c.core m fns env = true) + {q : Assemble.Program} {code : ByteArray} {scope : Call → Prop} {base : Assemble.Cert} + (henv : base.env = true) + (inhabited : ∃ call, genericValid0 fns s call) + (backend : ∀ o, Stage (mirSem o) (evmirSem o) m q scope) + (hscope : ∀ call, genericValid0 fns s call → scope call) + (asm : ∀ gas, gas < 2 ^ 256 → ∀ call, genericValid0 fns s call → ∃ o, + RunOracle.CertOk base o ∧ Within (evmirSem o) (ethLibWith gas) q code (· = call)) + {Post : Call → Observable → Prop} (meets : Meets (solidCore fuel) c (genericValid0 fns s) Post) : + Functional (solidCore fuel) c code (genericValid0 fns s) (fun _ _ => True) Post := by + have defined := Generic.definedAt hd hchk + have total : ∀ call, genericValid0 fns s call → ∃ obs, (solidCore fuel).run c call = some obs := + fun call hc => Option.isSome_iff_exists.mp (defined call hc) + refine ⟨inhabited, ?_, fun call hc => ?_, meets⟩ + · exact equiv_of_runs (sem := evmirSem) (q := fun _ => q) (Ok := RunOracle.CertOk base) total + (fun o ho => (Generic.stageAtWith o hd (sourceEnvOk_of (ho.1 henv)).ask hchk).trans + ((backend o).mono hscope)) + asm + · obtain ⟨obs, hs⟩ := total call hc + exact ⟨obs, hs, trivial⟩ + +/-- A solar-verify function spec as a postcondition: on a call of `scope`, every pre-state and +arguments meeting the spec's precondition meet its postcondition with the call's result. -/ +def holdsPost (b : SolidCore.Spec.Bundle) (ctxOf : Call → SolidCore.Spec.Ctx) + (step : SolidCore.Spec.GhostStep) (fs : SolidCore.Spec.FnSpec) (scope : Call → Prop) + (call : Call) (obs : Observable) : Prop := + scope call → ∀ (args : List Int) (pre : SolidCore.Spec.State), + SolidCore.Spec.Pre b fs (ctxOf call) pre call args → + SolidCore.Spec.Post b fs (ctxOf call) pre (step call pre.ghost) obs args + +/-- A function spec proved of the source is `Meets` of its `holdsPost`. -/ +theorem meets_of_holdsFn {S : Sem} {p : S.Prog} {Valid scope : Call → Prop} + {b : SolidCore.Spec.Bundle} {ctxOf : Call → SolidCore.Spec.Ctx} {step : SolidCore.Spec.GhostStep} + {fs : SolidCore.Spec.FnSpec} (h : SolidCore.Spec.HoldsFn S p scope b ctxOf step fs) : + Meets S p Valid (holdsPost b ctxOf step fs scope) := by + intro call _ obs hrun hs args pre hpre + obtain ⟨obs', hrun', hpost⟩ := h call hs args pre hpre + rw [hrun] at hrun' + cases hrun' + exact hpost + +/-- info: 'SolidCore.Refinement.Shapes.functional_ctx' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms functional_ctx + +/-- info: 'SolidCore.Refinement.Shapes.meets_of_holdsFn' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms meets_of_holdsFn + +end SolidCore.Refinement.Shapes diff --git a/Verify/ShapeCtxGas.lean b/Verify/ShapeCtxGas.lean new file mode 100644 index 00000000..c88a835c --- /dev/null +++ b/Verify/ShapeCtxGas.lean @@ -0,0 +1,117 @@ +import Verify.ShapeCtx +import SolidCore.Refinement.Solar.AssembleCtxGas + +/-! +# The certified shape through the checker with contexts and gas + +For contracts whose final EVM IR the loop checker rejects only because of blocks no valid call +reaches (a permit path's STATICCALL and GAS, say), and whose internal functions are called in +several contexts. Inputs, all generated by the certify driver: + +* the source stage and its definedness (from `Generic.check`); +* `backend`: solar-tv's stages from the module to the final EVM IR `q`; +* `ends` / `guard_run`: on each valid call, the run of `guard F q` (each block of `F` replaced by + a jump to itself) ends within `N` blocks and equals `q`'s run at that fuel: so no valid call + enters `F`; +* `asm`: `AssembleCtxGas.checkXL F q code cx`. + +`compiled_ofXL` proves `Compiled` at the one oracle `oracle`, with the gas bound +`gasBoundL cx.base N`. Unlike `functional_ctx` it has no hypothesis on the runner of messages +(no `StaticRunner`, no `CalleesRun`): EthLib's run of the bytes never reaches a STATICCALL or a GAS +on a valid call, which `within_of_checkXL` and `forward_of_checkXL` prove from the same block bound. +-/ + +namespace SolidCore.Refinement.Shapes + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Final SolidCore.Refinement.Abi +open SolidCore.Refinement.Solar SolidCore.Solidity + +theorem evmir_run_of_iterate {o : Machine.Oracle} {q : Assemble.Program} {call : Call} {N : Nat} + {r : Machine.Halt × Machine.State} + (h : EVM.Program.run o q call N = some r) : + (evmirSem o).run q call = some (Machine.observe call r.2 r.1) := by + change (SolarTV.EVM.Program.layer.result o q call).map _ = _ + rw [SolarTV.EVM.Program.layer.result_of_ends ⟨N, h⟩] + rfl + +/-- **The shape from a total source stage, the backend stages and the checker with contexts and +gas.** -/ +theorem compiled_ofXL {S : Sem} {p : S.Prog} {m : MIR.Lowered.moduleLayer.Prog} + {q : Assemble.Program} {code : ByteArray} {Valid scope : Call → Prop} {F : List Nat} + {cx : AssembleCtx.CtxCert} {N : Nat} + (inhabited : ∃ call, Valid call) + (src : Stage S (mirSem oracle) p m Valid) (defined : Defined S p Valid) + (backend : Stage (mirSem oracle) (evmirSem oracle) m q scope) + (hscope : ∀ call, Valid call → scope call) + (ends : ∀ call, Valid call → + (EVM.Program.run oracle (AssembleCtxGas.guard F q) call N).isSome = true) + (guard_run : ∀ call, Valid call → + EVM.Program.run oracle q call N = EVM.Program.run oracle (AssembleCtxGas.guard F q) call N) + (asm : AssembleCtxGas.checkXL F q code cx = true) + (hG : AssembleLoop.gasBoundL cx.base N < 2 ^ 64) : + Compiled S p code Valid (fun _ => AssembleLoop.gasBoundL cx.base N) := by + have total : ∀ call, Valid call → ∃ obs, S.run p call = some obs := fun call hc => + Option.isSome_iff_exists.mp (defined call hc) + have stage : Stage S (evmirSem oracle) p q Valid := + src.trans (backend.mono hscope) + -- On a valid call: the guarded run's result, and the source's result is its observable. + have key : ∀ call, Valid call → ∃ r, + Machine.iterate (EVM.Program.block oracle call (AssembleCtxGas.guard F q)) N + (0, [], Machine.State.initial call) = some r ∧ + S.run p call = some (Machine.observe call r.2 r.1) ∧ + (evmirSem oracle).run q call = some (Machine.observe call r.2 r.1) := by + intro call hc + obtain ⟨r, hr⟩ := Option.isSome_iff_exists.mp (ends call hc) + have hq : (evmirSem oracle).run q call = some (Machine.observe call r.2 r.1) := + evmir_run_of_iterate ((guard_run call hc).trans hr) + obtain ⟨obs0, h0⟩ := total call hc + have := stage call hc obs0 h0 + rw [hq] at this + cases this + exact ⟨r, hr, h0, hq⟩ + have hequiv : Equiv S p code Valid := by + intro gas _ call hc obs hrun + obtain ⟨r, hit, hs, -⟩ := key call hc + rcases AssembleCtxGas.within_of_checkXL asm oracle (fun _ => oracle_ok.1) (fun _ => oracle_ok.2) + call N r hit gas obs hrun with e | e + · exact Or.inl (e ▸ hs) + · exact Or.inr e + have hres : Resources S p code Valid (fun _ => AssembleLoop.gasBoundL cx.base N) := + resources_of_forward (B := evmirSem oracle) (q := q) total stage fun call hc => + ⟨hG, fun _ h1 _ obs hrun => by + obtain ⟨r, hit, -, hq⟩ := key call hc + rw [hq] at hrun + cases hrun + exact AssembleCtxGas.forward_of_checkXL asm oracle (fun _ => oracle_ok.1) + (fun _ => oracle_ok.2) call N r hit h1⟩ + exact ⟨inhabited, equivG_of hequiv hres, fun call hc => by + obtain ⟨obs, hs⟩ := total call hc + exact ⟨obs, hs, trivial⟩, hres⟩ + +/-- **The shape of a generic-stage contract on calls without a value, through the checker with +contexts and gas.** -/ +theorem compiled0XL {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {m : MIR.Lowered.Module} + {fns : List Fn} {env : Generic.EnvFlags} + (hchk : Generic.check fuel mirFuel c.core m fns env = true) + {q : Assemble.Program} {code : ByteArray} {scope : Call → Prop} {F : List Nat} + {cx : AssembleCtx.CtxCert} {N : Nat} + (inhabited : ∃ call, genericValid0 fns s call) + (backend : Stage (mirSem oracle) (evmirSem oracle) m q scope) + (hscope : ∀ call, genericValid0 fns s call → scope call) + (ends : ∀ call, genericValid0 fns s call → + (EVM.Program.run oracle (AssembleCtxGas.guard F q) call N).isSome = true) + (guard_run : ∀ call, genericValid0 fns s call → + EVM.Program.run oracle q call N = EVM.Program.run oracle (AssembleCtxGas.guard F q) call N) + (asm : AssembleCtxGas.checkXL F q code cx = true) + (hG : AssembleLoop.gasBoundL cx.base N < 2 ^ 64) : + Compiled (solidCore fuel) c code (genericValid0 fns s) + (fun _ => AssembleLoop.gasBoundL cx.base N) := + compiled_ofXL inhabited (Generic.stageAtWith oracle hd oracle_sourceEnvOk.ask hchk) + (Generic.definedAt hd hchk) backend hscope ends guard_run asm hG + +/-- info: 'SolidCore.Refinement.Shapes.compiled0XL' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms compiled0XL + +end SolidCore.Refinement.Shapes diff --git a/Verify/ShapeCtxGasFrom.lean b/Verify/ShapeCtxGasFrom.lean new file mode 100644 index 00000000..30fcc778 --- /dev/null +++ b/Verify/ShapeCtxGasFrom.lean @@ -0,0 +1,100 @@ +import Verify.ShapeCtxGas +import SolidCore.Refinement.Solar.AssembleCtxGasFrom + +/-! +# Resources from any caller, through the checker with contexts and gas + +`Shapes.Resources` speaks of `Final.Target.runWith`, one message from the fixed account +`callerAddress`. `ResourcesFrom` asks the same of every caller: for every account `a` below +`2 ^ 160` but the contract's own, every valid call and every gas from the bound `G call` on (below +`2 ^ 256`), EthLib's run of the exact bytecode from `a` (`Final.Target.runWithFrom a`) is the source's +run of the call from `a`. At `callerAddress` it gives `Resources` (`ResourcesFrom.resources`). + +* `gasEdge_ofXL` is the gas edge on its own (E8): from the checker with contexts and gas on the + exact bytecode, and the guard stage (no valid call enters a block the checker leaves unchecked), + for every caller and every oracle whose CALLER is that caller and whose Keccak-256 is EthLib's, + at every gas from `gasBoundL cx.base N` on the bytecode's result is the final EVM IR's result. + Its premises are about programs only (the checker's verdict and two symbolic runs of the EVM + IR); none of them mentions gas or EthLib's result, so the bound is not assumed. +* `resourcesFrom_ofXL` composes it with a source stage per caller (the functional edges E3 and E4, + proved elsewhere and taken here as the named hypothesis `stage`) into `ResourcesFrom`. +-/ + +namespace SolidCore.Refinement.Shapes + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Final SolidCore.Refinement.Solar + +/-- The oracle of a call from the account `a`: `oracle` with CALLER `a`. -/ +def oracleFrom (a : Nat) : Machine.Oracle := { oracle with caller := BitVec.ofNat 160 a } + +theorem oracleFrom_ok {a : Nat} (ha : a < 2 ^ 160) : AssembleLoop.OracleOkAt a (oracleFrom a) := by + refine ⟨?_, oracle_ok.1.2⟩ + apply BitVec.eq_of_toNat_eq + rw [Assemble.address_toNat ha] + show ((BitVec.ofNat 160 a).setWidth 256).toNat = a + rw [BitVec.toNat_setWidth, BitVec.toNat_ofNat, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt (by omega)] + +/-- At `callerAddress` it is `oracle`'s caller. -/ +theorem oracleFrom_callerAddress_ok : AssembleLoop.OracleOkAt callerAddress (oracleFrom callerAddress) := + oracleFrom_ok (by decide) + +/-- **Resources from any caller.** -/ +def ResourcesFrom (run : Nat → Call → Option Observable) (code : ByteArray) (Valid : Call → Prop) + (G : Call → Nat) : Prop := + ∀ a, a < 2 ^ 160 → a ≠ selfAddress → ∀ call, Valid call → G call < 2 ^ 64 ∧ + ∀ gas, G call ≤ gas → gas < 2 ^ 256 → Final.Target.runWithFrom a gas code call = run a call + +/-- At `callerAddress`, `ResourcesFrom` is `Resources`. -/ +theorem ResourcesFrom.resources {S : Sem} {p : S.Prog} {code : ByteArray} {Valid : Call → Prop} + {G : Call → Nat} {run : Nat → Call → Option Observable} (h : ResourcesFrom run code Valid G) + (hrun : run callerAddress = S.run p) : Resources S p code Valid G := fun call hc => by + obtain ⟨hG, hr⟩ := h callerAddress (by decide) (by decide) call hc + refine ⟨hG, fun gas h1 h2 => ?_⟩ + rw [← hrun, ← Final.Target.runWithFrom_callerAddress] + exact hr gas h1 h2 + +/-- **The gas edge from any caller.** -/ +theorem gasEdge_ofXL {q : Assemble.Program} {F : List Nat} {code : ByteArray} + {cx : AssembleCtx.CtxCert} {N : Nat} {Valid : Call → Prop} + (asm : AssembleCtxGas.checkXL F q code cx = true) (hreads : cx.base.reads = false) + (ends : ∀ o call, Valid call → + (EVM.Program.run o (AssembleCtxGas.guard F q) call N).isSome = true) + (guard_run : ∀ o call, Valid call → + EVM.Program.run o q call N = EVM.Program.run o (AssembleCtxGas.guard F q) call N) : + ∀ a, a < 2 ^ 160 → a ≠ selfAddress → ∀ o, AssembleLoop.OracleOkAt a o → ∀ call, Valid call → + ∀ gas, AssembleLoop.gasBoundL cx.base N ≤ gas → + ∃ obs, (evmirSem o).run q call = some obs ∧ Final.Target.runWithFrom a gas code call = some obs := by + intro a ha hne o ho call hc gas hg + obtain ⟨r, hr⟩ := Option.isSome_iff_exists.mp (ends o call hc) + refine ⟨_, evmir_run_of_iterate ((guard_run o call hc).trans hr), ?_⟩ + exact AssembleCtxGas.forward_of_checkXLFrom asm a (Assemble.address_ne_self ha hne) o (fun _ => ho) + (fun h => absurd h (by simp [hreads])) call N r hr hg + +/-- **Resources from any caller, from a source stage per caller and the gas edge.** -/ +theorem resourcesFrom_ofXL {q : Assemble.Program} {F : List Nat} {code : ByteArray} + {cx : AssembleCtx.CtxCert} {N : Nat} {Valid : Call → Prop} {run : Nat → Call → Option Observable} + (total : ∀ a, a < 2 ^ 160 → a ≠ selfAddress → ∀ call, Valid call → ∃ obs, run a call = some obs) + (stage : ∀ a, a < 2 ^ 160 → a ≠ selfAddress → ∀ call, Valid call → ∀ obs, run a call = some obs → + (evmirSem (oracleFrom a)).run q call = some obs) + (asm : AssembleCtxGas.checkXL F q code cx = true) (hreads : cx.base.reads = false) + (ends : ∀ o call, Valid call → + (EVM.Program.run o (AssembleCtxGas.guard F q) call N).isSome = true) + (guard_run : ∀ o call, Valid call → + EVM.Program.run o q call N = EVM.Program.run o (AssembleCtxGas.guard F q) call N) + (hG : AssembleLoop.gasBoundL cx.base N < 2 ^ 64) : + ResourcesFrom run code Valid (fun _ => AssembleLoop.gasBoundL cx.base N) := by + intro a ha hne call hc + refine ⟨hG, fun gas h1 _ => ?_⟩ + obtain ⟨obs, hq, hb⟩ := gasEdge_ofXL asm hreads ends guard_run a ha hne (oracleFrom a) + (oracleFrom_ok ha) call hc gas h1 + obtain ⟨obs0, h0⟩ := total a ha hne call hc + have := stage a ha hne call hc obs0 h0 + rw [hq] at this + cases this + rw [hb, h0] + +/-- info: 'SolidCore.Refinement.Shapes.resourcesFrom_ofXL' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms resourcesFrom_ofXL + +end SolidCore.Refinement.Shapes diff --git a/Verify/ShapeGeneric.lean b/Verify/ShapeGeneric.lean new file mode 100644 index 00000000..533ccf25 --- /dev/null +++ b/Verify/ShapeGeneric.lean @@ -0,0 +1,274 @@ +import Verify.Shapes +import Verify.Basic +import SolidCore.Refinement.Generic.Total +import SolidCore.Refinement.Solar.Totality +import SolidCore.Refinement.Solar.AssembleGasLoop +import SolidCore.Refinement.Solar.RunOracle +import SolidCore.Refinement.Keccak.TwoWords + +/-! +# The certified shape of a loop-free contract, from the generic pieces + +One theorem for every contract whose source stage is the generic check (`Generic.check`, with +`Generic.checkValue` for calls with a value) and whose bytecode the checker of code with loops +accepts (`AssembleLoop.checkL`, on a certificate `tools/certify/asm_cert.py` infers and the kernel's +evaluation re-derives). Its inputs are exactly the evidence the certify driver generates: + +* a source stage and its definedness (from `Generic.check` and `Generic.checkValue`, by + `Generic.stageAtValueWith` and `Generic.definedAtValue`); +* `backend`: solar-tv's stages from that module to the final EVM IR, under every oracle; +* `ends`: the final EVM IR ends within `N` blocks on every call (the last stage's fuel: each stage + file runs both programs within a fuel the kernel's evaluation reaches); +* `asm`: `checkL` accepts the final EVM IR against the exact bytecode. + +From these, at the one oracle `oracle` (EthLib's caller, Keccak-256 and environment, as the +bytecode's own run reads them; `oracle_ok`), `compiled_of` proves `Compiled`: + +* equivalence (`Shapes.Equiv`, sharpened to `EquivG`): at every gas below `2 ^ 256`, every result + of the bytecode on a valid call is SolidCore's, or a failure that changes nothing, and that only + below the gas bound; +* termination: SolidCore ends on every valid call, with any status; +* resources: from `AssembleLoop.gasBoundL cert N` gas on, the bytecode gives exactly SolidCore's + result, a revert with its data included (`AssembleLoop.stage_of_checkL_gas`). + +`Compiled` has no specification: a contract with none never reaches `Shapes.Certified`. +`Compiled.certified` adds a specification proved of the same source semantics (`Allowed`, `Post`). + +One fixed oracle suffices: the checker's fragment (no GAS, no calls, no return data) reads of the +oracle only the caller, the Keccak-256 of memory and the block and transaction words, all of which +are EthLib's in `oracle`; `within_of_checkL` and `forward_of_checkL` are theorems about EthLib's +run of the bytes, at every gas, related to the EVM IR under that oracle. +-/ + +namespace SolidCore.Refinement.Shapes + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Final SolidCore.Refinement.Abi +open SolidCore.Refinement.Solar SolidCore.Solidity + +/-! ## Sharper equivalence and the status without a specification -/ + +/-- **Equivalence with the gas bound**: every result of the bytecode on a valid call, at every gas +below `2 ^ 256`, is the source's, or a failure that changes nothing at a gas below the bound. At +and above the bound it is the source's exactly, its revert data included. -/ +def EquivG (S : Sem) (p : S.Prog) (code : ByteArray) (Valid : Call → Prop) (G : Call → Nat) : + Prop := + ∀ gas, gas < 2 ^ 256 → ∀ call, Valid call → ∀ obs, Final.Target.runWith gas code call = some obs → + S.run p call = some obs ∨ (Inert call obs ∧ gas < G call) + +theorem equivG_of {S : Sem} {p : S.Prog} {code : ByteArray} {Valid : Call → Prop} {G : Call → Nat} + (he : Equiv S p code Valid) (hr : Resources S p code Valid G) : EquivG S p code Valid G := by + intro gas hg call hc obs hrun + by_cases hlt : gas < G call + · rcases he gas hg call hc obs hrun with e | e + · exact Or.inl e + · exact Or.inr ⟨e, hlt⟩ + · left + rw [← (hr call hc).2 gas (Nat.not_lt.mp hlt) hg] + exact hrun + +theorem EquivG.equiv {S : Sem} {p : S.Prog} {code : ByteArray} {Valid : Call → Prop} + {G : Call → Nat} (h : EquivG S p code Valid G) : Equiv S p code Valid := + fun gas hg call hc obs hrun => (h gas hg call hc obs hrun).imp id And.left + +/-- **Translation without a specification**: equivalence with the gas bound, termination with +any status, and resources. Reported with the specification status "none", never as the +strongest status. -/ +structure Compiled (S : Sem) (p : S.Prog) (code : ByteArray) (Valid : Call → Prop) + (G : Call → Nat) : Prop where + inhabited : ∃ call, Valid call + equiv : EquivG S p code Valid G + terminates : Terminates S p Valid (fun _ _ => True) + resources : Resources S p code Valid G + +/-- A specification of the same source semantics (allowed statuses and a postcondition of every +source result) makes a compiled contract certified. -/ +theorem Compiled.certified {S : Sem} {p : S.Prog} {code : ByteArray} {Valid : Call → Prop} + {G : Call → Nat} {Allowed Post : Call → Observable → Prop} (h : Compiled S p code Valid G) + (allowed : ∀ call, Valid call → ∀ obs, S.run p call = some obs → Allowed call obs) + (meets : Meets S p Valid Post) : Certified S p code Valid Allowed Post G where + inhabited := h.inhabited + equiv := h.equiv.equiv + terminates := fun call hc => by + obtain ⟨obs, hs, -⟩ := h.terminates call hc + exact ⟨obs, hs, allowed call hc obs hs⟩ + meets := meets + resources := h.resources + +/-- A larger bound below `2 ^ 64` keeps the shape. -/ +theorem Compiled.mono_gas {S : Sem} {p : S.Prog} {code : ByteArray} {Valid : Call → Prop} + {G G' : Call → Nat} (h : Compiled S p code Valid G) (hle : ∀ call, G call ≤ G' call) + (hlt : ∀ call, G' call < 2 ^ 64) : Compiled S p code Valid G' where + inhabited := h.inhabited + equiv := fun gas hg call hc obs hrun => + (h.equiv gas hg call hc obs hrun).imp id fun ⟨hi, hl⟩ => ⟨hi, Nat.lt_of_lt_of_le hl (hle call)⟩ + terminates := h.terminates + resources := fun call hc => + ⟨hlt call, fun gas h1 h2 => (h.resources call hc).2 gas (Nat.le_trans (hle call) h1) h2⟩ + +/-- The strongest status also gives the sharper equivalence. -/ +theorem Certified.equivG {S : Sem} {p : S.Prog} {code : ByteArray} {Valid : Call → Prop} + {Allowed Post : Call → Observable → Prop} {G : Call → Nat} + (h : Certified S p code Valid Allowed Post G) : EquivG S p code Valid G := + equivG_of h.equiv h.resources + +/-! ## The oracle of the bytecode's own run -/ + +/-- EthLib's caller, Keccak-256 and environment reads; every other answer from the empty table. -/ +def oracle : Machine.Oracle := + RunOracle.tableOracle (Assemble.envOracle (Assemble.ethOracle RunOracle.anyOracle)) {} + +theorem oracle_ok : Assemble.OracleOk oracle ∧ Assemble.EnvOk oracle := + RunOracle.table_ok _ _ + +theorem callerAddress_word : + (SolidCore.Refinement.Target.address SolidCore.Refinement.callerAddress).toU256.toNat = + Generic.callerWord := by + decide +kernel + +/-- It is an oracle every generic source stage takes, whatever its environment flags. -/ +theorem oracle_sourceEnvOk : Generic.SourceEnvOk oracle := + ⟨by unfold Generic.CallerOk; rw [oracle_ok.1.1]; exact callerAddress_word, + fun a b _ _ => by rw [oracle_ok.1.2]; exact Keccak.ethKeccak_twoWords a b⟩ + +/-! ## The composition -/ + +/-- **The shape from a total source stage, the backend stages and the loop checker.** -/ +theorem compiled_of {S : Sem} {p : S.Prog} {m : MIR.Lowered.moduleLayer.Prog} + {q : Assemble.Program} {code : ByteArray} {Valid scope : Call → Prop} {c : Assemble.Cert} + {mx : List Nat} {N : Nat} + (inhabited : ∃ call, Valid call) + (src : Stage S (mirSem oracle) p m Valid) (defined : Defined S p Valid) + (backend : Stage (mirSem oracle) (evmirSem oracle) m q scope) + (hscope : ∀ call, Valid call → scope call) + (ends : ∀ call, (EVM.Program.run oracle q call N).isSome = true) + (asm : AssembleLoop.checkL q code c mx = true) + (hG : AssembleLoop.gasBoundL c N < 2 ^ 64) : + Compiled S p code Valid (fun _ => AssembleLoop.gasBoundL c N) := by + have total : ∀ call, Valid call → ∃ obs, S.run p call = some obs := fun call hc => + Option.isSome_iff_exists.mp (defined call hc) + have stage : Stage S (evmirSem oracle) p q Valid := + src.trans (backend.mono hscope) + have hequiv : Equiv S p code Valid := + equiv_of_runs (sem := evmirSem) (q := fun _ => q) (Ok := fun o => o = oracle) total + (fun o ho => ho ▸ stage) + (fun gas _ call _ => ⟨oracle, rfl, + AssembleLoop.within_of_checkL asm oracle (fun _ => oracle_ok.1) _ gas + (fun _ => oracle_ok.2)⟩) + have hres : Resources S p code Valid (fun _ => AssembleLoop.gasBoundL c N) := + resources_of_forward (B := evmirSem oracle) (q := q) total stage fun call _ => + ⟨hG, fun _ h1 _ obs hrun => + AssembleLoop.stage_of_checkL_gas asm oracle (fun _ => oracle_ok.1) + (fun _ => oracle_ok.2) call N (Option.isSome_iff_exists.mp (ends call)) h1 obs hrun⟩ + exact ⟨inhabited, equivG_of hequiv hres, fun call hc => by + obtain ⟨obs, hs⟩ := total call hc + exact ⟨obs, hs, trivial⟩, hres⟩ + +/-- The valid calls of a generic stage: a function of `fns` on argument words below `2 ^ 256`, any +value below `2 ^ 256`, from a storage that writes every slot the constructor wrote. -/ +def genericValid (fns : List Fn) (s : List (Nat × Nat)) (call : Call) : Prop := + ∃ σ v, Generic.Covers s σ ∧ Generic.fullScopeValue fns σ v call + +/-- **The shape of a generic-stage contract**: the generic check at every value, the backend stages, +the final EVM IR's fuel and the loop checker. -/ +theorem compiled {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {m : MIR.Lowered.Module} + {fns : List Fn} {env : Generic.EnvFlags} + (hchk : Generic.check fuel mirFuel c.core m fns env = true) + (hval : Generic.checkValue mirFuel c.core m fns env = true) + {q : Assemble.Program} {code : ByteArray} {scope : Call → Prop} {cert : Assemble.Cert} + {mx : List Nat} {N : Nat} + (inhabited : ∃ call, genericValid fns s call) + (backend : Stage (mirSem oracle) (evmirSem oracle) m q scope) + (hscope : ∀ call, genericValid fns s call → scope call) + (ends : ∀ call, (EVM.Program.run oracle q call N).isSome = true) + (asm : AssembleLoop.checkL q code cert mx = true) + (hG : AssembleLoop.gasBoundL cert N < 2 ^ 64) : + Compiled (solidCore fuel) c code (genericValid fns s) (fun _ => AssembleLoop.gasBoundL cert N) := + compiled_of inhabited + (Generic.stageAtValueWith oracle hd oracle_sourceEnvOk.ask hchk hval) + (Generic.definedAtValue hd hchk hval) backend hscope ends asm hG + +/-- A call of every generic stage's scope: the first function on zero words, no value, from the +constructor's storage. -/ +theorem genericValid_inhabited (f : Fn) (fns : List Fn) (s : List (Nat × Nat)) : + ∃ call, genericValid (f :: fns) s call := + ⟨_, s, 0, fun kv hkv => ⟨kv, hkv, rfl⟩, by decide, f, List.mem_cons_self, + List.replicate f.params.length 0, List.length_replicate, + fun a ha => by rw [(List.mem_replicate.mp ha).2]; decide, rfl⟩ + +/-- info: 'SolidCore.Refinement.Shapes.compiled' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms compiled + +/-- info: 'SolidCore.Refinement.Shapes.Compiled.certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms Compiled.certified + + +/-! ## Calls without a value, and specifications from triples -/ + +/-- The valid calls of a generic stage without a value: a function of `fns` on argument words below +`2 ^ 256`, no value, from a storage that writes every slot the constructor wrote. -/ +def genericValid0 (fns : List Fn) (s : List (Nat × Nat)) (call : Call) : Prop := + ∃ σ, Generic.Covers s σ ∧ fullScope fns σ call + +/-- **The shape of a generic-stage contract on calls without a value.** -/ +theorem compiled0 {fuel mirFuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {m : MIR.Lowered.Module} + {fns : List Fn} {env : Generic.EnvFlags} + (hchk : Generic.check fuel mirFuel c.core m fns env = true) + {q : Assemble.Program} {code : ByteArray} {scope : Call → Prop} {cert : Assemble.Cert} + {mx : List Nat} {N : Nat} + (inhabited : ∃ call, genericValid0 fns s call) + (backend : Stage (mirSem oracle) (evmirSem oracle) m q scope) + (hscope : ∀ call, genericValid0 fns s call → scope call) + (ends : ∀ call, (EVM.Program.run oracle q call N).isSome = true) + (asm : AssembleLoop.checkL q code cert mx = true) + (hG : AssembleLoop.gasBoundL cert N < 2 ^ 64) : + Compiled (solidCore fuel) c code (genericValid0 fns s) (fun _ => AssembleLoop.gasBoundL cert N) := + compiled_of inhabited (Generic.stageAtWith oracle hd oracle_sourceEnvOk.ask hchk) + (Generic.definedAt hd hchk) backend hscope ends asm hG + +theorem genericValid0_inhabited (f : Fn) (fns : List Fn) (s : List (Nat × Nat)) : + ∃ call, genericValid0 (f :: fns) s call := + ⟨_, s, fun kv hkv => ⟨kv, hkv, rfl⟩, f, List.mem_cons_self, + List.replicate f.params.length 0, List.length_replicate, + fun a ha => by rw [(List.mem_replicate.mp ha).2]; decide, rfl⟩ + +/-- A total-correctness triple of SolidCore on part of the valid calls is the specification +"on those calls, `post`" of every source result. -/ +theorem meets_of_triple {fuel : Nat} {c : TypeCheck.CheckedContract} {Valid scope : Call → Prop} + {post : Call → Observable → Prop} (ht : SolidCore.Verify.Triple fuel c scope (fun _ => True) post) : + Meets (solidCore fuel) c Valid (fun call obs => scope call → post call obs) := + fun call _ obs hrun hs => (ht call hs trivial).2 obs hrun + +theorem Meets.and {S : Sem} {p : S.Prog} {Valid : Call → Prop} {P Q : Call → Observable → Prop} + (h1 : Meets S p Valid P) (h2 : Meets S p Valid Q) : + Meets S p Valid (fun call obs => P call obs ∧ Q call obs) := + fun call hc obs hrun => ⟨h1 call hc obs hrun, h2 call hc obs hrun⟩ + +/-- info: 'SolidCore.Refinement.Shapes.compiled0' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms compiled0 + + +/-! ## Code with loops: a total first lowered MIR, the loop checker's backward theorem -/ + +/-- **Equivalence, termination and the specification of a program that ends on every valid call**, +whose results the bytecode refines at every gas (`AssembleLoop.within_of_checkL` composed with +cut-point stages read backwards), with the specification proved of the same program. Resources are +not part of it: a gas bound needs the final EVM IR's block count. -/ +theorem functional_of {S : Sem} {p : S.Prog} {code : ByteArray} {Valid : Call → Prop} + {Allowed Post : Call → Observable → Prop} (inhabited : ∃ call, Valid call) + (ends : ∀ call, Valid call → (S.run p call).isSome = true) + (allowed : ∀ call, Valid call → ∀ obs, S.run p call = some obs → Allowed call obs) + (within : ∀ gas, Within S (ethLibWith gas) p code Valid) (meets : Meets S p Valid Post) : + Functional S p code Valid Allowed Post where + inhabited := inhabited + equiv := fun gas _ call hc obs hrun => within gas call hc obs hrun + terminates := fun call hc => by + obtain ⟨obs, hs⟩ := Option.isSome_iff_exists.mp (ends call hc) + exact ⟨obs, hs, allowed call hc obs hs⟩ + meets := meets + +end SolidCore.Refinement.Shapes diff --git a/Verify/ShapeOpen.lean b/Verify/ShapeOpen.lean new file mode 100644 index 00000000..8302c9db --- /dev/null +++ b/Verify/ShapeOpen.lean @@ -0,0 +1,173 @@ +import Verify.Shapes +import SolidCore.Refinement.SourceOracle + +/-! +# The shape of a certified compilation in an open world + +`Shapes.Functional` runs the bytecode in EthLib's state with only the contract and its caller +(`Target.preState`), so every external call reaches an account without code. For a contract +whose functions call other contracts (a pair reading its tokens' balances and paying them), that +closed world makes every such function revert, and a specification of their successes holds +vacuously. This file states the same three obligations with the environment quantified, as +requirement E asks: + +* `TargetEnv`: the other accounts of the target's state (address, code, storage, balance), any + list the statement admits (`EnvOk`); `Target.runWithIn env gas code call` is + `Final.Target.runWith` with those accounts added, observing the contract's own logs only. +* `OpenFunctional`: equivalence (every result of the exact bytecode in every admitted environment, + at every gas below `2 ^ 256`, is SolidCore's result in some admitted open world `W`, or an + inert failure, or a result that only a world outside the admitted ones explains: `Unadmitted`, + reported as such), termination with an allowed status in **every** admitted world (never by choosing + a terminating oracle), and the specification of every source result in every admitted world. + The allowed statuses and the specification may read the world (a ghost step that depends on the + answers of the calls). + +`OpenFunctional.bytecode_any` is what it says of the bytes: every result in every admitted +environment is allowed and meets the specification for some admitted world, or changes nothing. +No resources obligation: a gas bound for code whose callees spend gas is not stated here. + +The world the equivalence picks is existential per run: the statement does not say it is the one +the environment's code computes (causal consistency is the stage's business; the specification +holds in every admitted world, so the conclusion does not depend on which). +-/ + +namespace SolidCore.Refinement.Shapes + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Final +open EthLib.Base EthLib.Execution EthLib.Execution.Evm EthLib.Execution.State + +/-- One other account of the target's state. -/ +structure EnvAccount where + addr : Nat + code : ByteArray + storage : List (Nat × Nat) + balance : Nat + nonce : Nat + +/-- The other accounts of the target's state. -/ +abbrev TargetEnv := List EnvAccount + +/-- The environment's accounts are distinct addresses below `2 ^ 160`, neither the contract nor +its caller. -/ +def TargetEnv.WF (env : TargetEnv) : Prop := + (env.map (·.addr)).Nodup ∧ ∀ a ∈ env, a.addr < 2 ^ 160 ∧ a.addr ≠ selfAddress ∧ a.addr ≠ callerAddress + +namespace Target + +/-- `Target.preState` with the environment's accounts, storage and code added. -/ +def preStateIn (env : TargetEnv) (code : ByteArray) (call : Call) : TransactionState := + let hash := EthLib.Cryptography.Hash.Keccak.keccak256 code + let storage : Std.ExtTreeMap Bytes32 U256 := + call.storage.foldl (fun m kv => m.insert (Refinement.Target.storageKey kv.1) (BitVec.ofNat 256 kv.2)) ∅ + let accounts0 : Std.ExtTreeMap Address Account := + ((∅ : Std.ExtTreeMap Address Account).insert (Refinement.Target.address selfAddress) + { nonce := 1, balance := 0, codeHash := hash }).insert (Refinement.Target.address callerAddress) + { nonce := 0, balance := BitVec.ofNat 256 call.callvalue, + codeHash := EthLib.Cryptography.Hash.Keccak.keccak256 .empty } + let storage0 : Std.ExtTreeMap Address (Std.ExtTreeMap Bytes32 U256) := + (∅ : Std.ExtTreeMap Address (Std.ExtTreeMap Bytes32 U256)).insert + (Refinement.Target.address selfAddress) storage + let code0 : Std.ExtTreeMap Hash32 ByteArray := (∅ : Std.ExtTreeMap Hash32 ByteArray).insert hash code + let pre : State := env.foldl (fun (s : State) a => + let h := EthLib.Cryptography.Hash.Keccak.keccak256 a.code + { accounts := s.accounts.insert (Refinement.Target.address a.addr) + { nonce := a.nonce, balance := BitVec.ofNat 256 a.balance, codeHash := h }, + storage := s.storage.insert (Refinement.Target.address a.addr) + (a.storage.foldl (fun m kv => + m.insert (Refinement.Target.storageKey kv.1) (BitVec.ofNat 256 kv.2)) ∅), + code := s.code.insert h a.code }) + { accounts := accounts0, storage := storage0, code := code0 } + TransactionState.ofBlock + { preState := pre, accountWrites := ∅, storageWrites := ∅, codeWrites := ∅, + storageClears := ∅ } + +/-- `Final.Target.runWith` in the environment `env`: the contract's own logs, storage and +output. -/ +def runWithIn (env : TargetEnv) (gas : Nat) (code : ByteArray) (call : Call) : Option Observable := + match processMessage (Meter := Nat) .fusaka (Final.Target.messageWith gas code call) + (preStateIn env code call) Substate.empty with + | .error _ => none + | .ok ⟨evm, _⟩ => + let success := evm.error.isNone + some + { success + output := evm.output.toList.map (·.toNat) + logs := + if success then + (evm.substate.logs.toList.filter fun log => + log.address == Refinement.Target.address selfAddress).map fun log => + (log.topics.map fun topic => bytesToNat topic.toList, + log.data.toList.map (·.toNat)) + else [] + storage := fun slot => + if success then + (evm.state.getStorage (Refinement.Target.address selfAddress) + (Refinement.Target.storageKey slot)).toNat + else slotValue call.storage slot } + +end Target + +/-- A result outside what the admitted worlds explain: some world of the wide class `Wide` gives it, +and no admitted world does (such as a run that only a world changing the contract's storage +during one of its external calls explains). -/ +def Unadmitted (fuel : Nat) (c : SolidCore.Solidity.TypeCheck.CheckedContract) + (Wide Admit : World → Prop) (call : Call) (obs : Observable) : Prop := + (∃ W, Wide W ∧ Source.runIn W fuel c call = some obs) ∧ + ∀ W, Admit W → Source.runIn W fuel c call ≠ some obs + +/-- **Equivalence, termination and the specification in an open world.** `Admit` are the worlds +the specification and termination speak of; a result of the bytes that only a world of the wider +class `Wide` explains is reported as `Unadmitted`, never as meeting the specification. -/ +structure OpenFunctional (fuel : Nat) (c : SolidCore.Solidity.TypeCheck.CheckedContract) + (code : ByteArray) (EnvOk : TargetEnv → Prop) (Wide Admit : World → Prop) (Valid : Call → Prop) + (Allowed Post : World → Call → Observable → Prop) : Prop where + inhabited : ∃ call, Valid call + equiv : ∀ env, EnvOk env → ∀ gas, gas < 2 ^ 256 → ∀ call, Valid call → ∀ obs, + Target.runWithIn env gas code call = some obs → + (∃ W, Admit W ∧ Source.runIn W fuel c call = some obs) ∨ Inert call obs ∨ + Unadmitted fuel c Wide Admit call obs + terminates : ∀ W, Admit W → ∀ call, Valid call → + ∃ obs, Source.runIn W fuel c call = some obs ∧ Allowed W call obs + meets : ∀ W, Admit W → ∀ call, Valid call → ∀ obs, + Source.runIn W fuel c call = some obs → Post W call obs + +/-- **What the bytecode does in every admitted environment**: every result, at any gas below +`2 ^ 256`, is allowed and meets the specification in some admitted world, or changes nothing, or +is explained by no admitted world. -/ +theorem OpenFunctional.bytecode_any {fuel : Nat} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {code : ByteArray} {EnvOk : TargetEnv → Prop} {Wide Admit : World → Prop} {Valid : Call → Prop} + {Allowed Post : World → Call → Observable → Prop} + (h : OpenFunctional fuel c code EnvOk Wide Admit Valid Allowed Post) (env : TargetEnv) + (he : EnvOk env) (gas : Nat) (hg : gas < 2 ^ 256) (call : Call) (hc : Valid call) + (obs : Observable) (hrun : Target.runWithIn env gas code call = some obs) : + (∃ W, Admit W ∧ Allowed W call obs ∧ Post W call obs) ∨ Inert call obs ∨ + Unadmitted fuel c Wide Admit call obs := by + rcases h.equiv env he gas hg call hc obs hrun with ⟨W, hW, hs⟩ | e | e + · obtain ⟨obs', hs', ha⟩ := h.terminates W hW call hc + obtain rfl : obs' = obs := Option.some.inj (hs'.symm.trans hs) + exact Or.inl ⟨W, hW, ha, h.meets W hW call hc obs' hs'⟩ + · exact Or.inr (Or.inl e) + · exact Or.inr (Or.inr e) + +/-- The obligations compose from their parts: a source total in every admitted world, its +specification in every admitted world, and the per-run equivalence of the bytecode. -/ +theorem OpenFunctional.of_parts {fuel : Nat} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {code : ByteArray} {EnvOk : TargetEnv → Prop} {Wide Admit : World → Prop} {Valid : Call → Prop} + {Allowed Post : World → Call → Observable → Prop} + (hin : ∃ call, Valid call) + (heq : ∀ env, EnvOk env → ∀ gas, gas < 2 ^ 256 → ∀ call, Valid call → ∀ obs, + Target.runWithIn env gas code call = some obs → + (∃ W, Admit W ∧ Source.runIn W fuel c call = some obs) ∨ Inert call obs ∨ + Unadmitted fuel c Wide Admit call obs) + (hterm : ∀ W, Admit W → ∀ call, Valid call → + ∃ obs, Source.runIn W fuel c call = some obs ∧ Allowed W call obs) + (hspec : ∀ W, Admit W → Meets (solidCoreIn W fuel) c Valid (Post W)) : + OpenFunctional fuel c code EnvOk Wide Admit Valid Allowed Post := + ⟨hin, heq, hterm, fun W hW => hspec W hW⟩ + +/-- info: 'SolidCore.Refinement.Shapes.OpenFunctional.bytecode_any' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms OpenFunctional.bytecode_any + +end SolidCore.Refinement.Shapes + diff --git a/Verify/ShapeSpecExport.lean b/Verify/ShapeSpecExport.lean new file mode 100644 index 00000000..73a4e713 --- /dev/null +++ b/Verify/ShapeSpecExport.lean @@ -0,0 +1,308 @@ +import Verify.ShapeBundle +import Verify.ShapeGeneric +import Verify.Spec.Tree + +/-! +# Allowed statuses and the whole valid scope from solar-verify's exported spec + +The certify driver's strongest status reads both the postcondition and the allowed statuses off +solar-verify's export of the run's source, never off a Lean restatement: + +* `bundlePost b ctxOf step` (`Verify.ShapeBundle`) is the postcondition; +* `bundleAllowed b ctxOf` is the allowed statuses: a call may revert only when no function spec + whose precondition it meets has its succeeds-if conditions hold. A function spec with + succeeds-if conditions says from which pre-states it must succeed, so a revert from such a + pre-state is not allowed. A function without any makes no claim, as in solar-verify. + +`allowed_of_holds` gives every source result's status from `SolidCore.Spec.Holds`, so the +published `Terminates` with `bundleAllowed` follows from the source's totality and the spec. + +`holds_genericValid0` and `holds_genericValid` assemble `Holds` on the generic stage's valid +calls (`Shapes.genericValid0`, `Shapes.genericValid`) from each function spec's `HoldsFn` on the +stage's calls of the one function of its selector (`stageScope`, what +tools/certify/spec_connect.py proves for each function from its erased tree): a call of another +function has another selector, so no precondition of the spec holds of it; a call with a value of +a non-payable function reverts with empty data (`Generic.source_run_value`), which meets every +postcondition whose succeeds-if conditions require `msg.value == 0` (`valueGuarded`). + +`ctxOfCall` and `idStep` are the call context and the ghost step the statement names: the +interface's one frame (sender `0x2000`, the contract at `0x1000`, block timestamp 1) with the call's +value, and no ghost update. +-/ + +namespace SolidCore.Refinement.Shapes + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Final SolidCore.Refinement.Abi +open SolidCore.Spec (Bundle FnSpec Pre Post HoldsFn Holds) + +/-- The call context of the interface's one frame, with the call's value. -/ +def ctxOfCall (call : Call) : SolidCore.Spec.Ctx := + { sender := 0x2000, value := call.callvalue, timestamp := 1, self := 0x1000 } + +/-- No ghost update. -/ +def idStep : SolidCore.Spec.GhostStep := fun _ g => g + +/-- **The statuses solar-verify's exported spec allows**: success, or a call from which no +function spec with succeeds-if conditions must succeed. -/ +def bundleAllowed (b : Bundle) (ctxOf : Call → SolidCore.Spec.Ctx) (call : Call) + (obs : Observable) : Prop := + obs.success = true ∨ ∀ fs ∈ b.spec.specs, ∀ (args : List Int) (pre : SolidCore.Spec.State), + Pre b fs (ctxOf call) pre call args → fs.succeedsIf ≠ [] → + ¬ b.satAll fs.succeedsIf (SolidCore.Spec.mkEnv (ctxOf call) args [] pre pre) + +/-- Every source result on a call of the spec's scope has an allowed status. -/ +theorem allowed_of_holds {S : Sem} {p : S.Prog} {Valid scope : Call → Prop} {b : Bundle} + {ctxOf : Call → SolidCore.Spec.Ctx} {step : SolidCore.Spec.GhostStep} + (hv : ∀ call, Valid call → scope call) (h : Holds S p scope b ctxOf step) : + ∀ call, Valid call → ∀ obs, S.run p call = some obs → bundleAllowed b ctxOf call obs := by + intro call hc obs hrun + by_cases hs : obs.success = true + · exact Or.inl hs + · refine Or.inr fun fs hfs args pre hpre hne hsat => hs ?_ + obtain ⟨obs', h1, h2⟩ := h fs hfs call (hv call hc) args pre hpre + rw [hrun] at h1 + cases h1 + exact h2.2 hne hsat + +/-- A specified compiled contract is certified with the exported spec's postcondition and allowed +statuses, from the spec's `Holds` of the source on a scope covering the valid calls. -/ +theorem Compiled.certified_of_holds {S : Sem} {p : S.Prog} {code : ByteArray} + {Valid scope : Call → Prop} {G : Call → Nat} {b : Bundle} {ctxOf : Call → SolidCore.Spec.Ctx} + {step : SolidCore.Spec.GhostStep} (h : Compiled S p code Valid G) + (hv : ∀ call, Valid call → scope call) (hh : Holds S p scope b ctxOf step) : + Certified S p code Valid (bundleAllowed b ctxOf) (bundlePost b ctxOf step) G := + h.certified (allowed_of_holds hv hh) (meets_of_bundle hv hh) + +/-! ## The selector of the stage's calls -/ + +theorem selectorOf_calldata {sel : Nat} (hsel : sel < 2 ^ 32) (args : List Nat) (v : Nat) + (σ : List (Nat × Nat)) : + SolidCore.Spec.selectorOf { calldata := calldata sel args, callvalue := v, storage := σ } = sel := by + simp only [SolidCore.Spec.selectorOf] + rw [Dirty.bytes_calldata, List.take_append_of_le_length (by simp [EthLib.Base.natToBytes_length]), + List.take_of_length_le (by simp [EthLib.Base.natToBytes_length]), SolidCore.Spec.bytesWord_map, + EthLib.Base.bytesToNat_natToBytes_of_lt (by simpa using hsel)] + +/-- A function spec's precondition does not hold of a call of another selector. -/ +theorem not_pre_of_sel {b : Bundle} {fs : FnSpec} {ctx : SolidCore.Spec.Ctx} + {pre : SolidCore.Spec.State} {args : List Int} {sel : Nat} (hsel : sel < 2 ^ 32) + (hne : sel ≠ fs.selector) (as : List Nat) (v : Nat) (σ : List (Nat × Nat)) : + ¬ Pre b fs ctx pre { calldata := calldata sel as, callvalue := v, storage := σ } args := by + rintro ⟨⟨-, hs, -⟩, -⟩ + rw [selectorOf_calldata hsel] at hs + exact hne hs + +/-- The stage's scope of a function depends on its selector and its number of parameters. -/ +theorem stageScope_congr {fn fn' : Fn} (hs : fn.sel = fn'.sel) + (hl : fn.params.length = fn'.params.length) (s : List (Nat × Nat)) (call : Call) : + SolidCore.Verify.VC.stageScope fn s call → SolidCore.Verify.VC.stageScope fn' s call := by + rintro ⟨σ, hcov, g, hg, args, hlen, hargs, rfl⟩ + simp only [List.mem_singleton] at hg + subst hg + exact ⟨σ, hcov, fn', List.mem_singleton_self _, args, hlen.trans hl, hargs, by rw [hs]⟩ + +/-- Whether every function of `fns` with the selector `sel` has `n` parameters, and every selector +of `fns` is below `2 ^ 32`: checked by the kernel's evaluation. -/ +def selOk (fns : List Fn) (sel n : Nat) : Bool := + fns.all fun g => decide (g.sel < 2 ^ 32) && (g.sel != sel || g.params.length == n) + +/-- **One function spec on the stage's calls without a value**, from its `HoldsFn` on the stage's +calls of the function of its selector. -/ +theorem holdsFn_genericValid0 {S : Sem} {p : S.Prog} {fns : List Fn} {s : List (Nat × Nat)} + {b : Bundle} {ctxOf : Call → SolidCore.Spec.Ctx} {step : SolidCore.Spec.GhostStep} {fs : FnSpec} + {fn : Fn} (hfn : fn.sel = fs.selector) (hok : selOk fns fn.sel fn.params.length = true) + (h : HoldsFn S p (SolidCore.Verify.VC.stageScope fn s) b ctxOf step fs) : + HoldsFn S p (genericValid0 fns s) b ctxOf step fs := by + rintro _ ⟨σ, hcov, g, hg, args, hlen, hargs, rfl⟩ iargs pre hpre + have hk := List.all_eq_true.mp hok g hg + simp only [Bool.and_eq_true, decide_eq_true_eq, Bool.or_eq_true, bne_iff_ne, ne_eq, + beq_iff_eq] at hk + obtain ⟨hlt, hk⟩ := hk + by_cases he : g.sel = fn.sel + · have hl := hk.resolve_left (not_not.mpr he) + exact h _ (stageScope_congr he hl s _ ⟨σ, hcov, g, List.mem_singleton_self _, args, hlen, hargs, + rfl⟩) iargs pre hpre + · exact absurd hpre (not_pre_of_sel hlt (hfn ▸ he) args 0 σ) + +/-- `Holds` from every function spec, by its index. -/ +theorem holds_of_getElem {S : Sem} {p : S.Prog} {scope : Call → Prop} {b : Bundle} + {ctxOf : Call → SolidCore.Spec.Ctx} {step : SolidCore.Spec.GhostStep} + (h : ∀ i (hi : i < b.spec.specs.length), HoldsFn S p scope b ctxOf step b.spec.specs[i]) : + Holds S p scope b ctxOf step := by + intro fs hfs + obtain ⟨i, hi, rfl⟩ := List.getElem_of_mem hfs + exact h i hi + +/-- info: 'SolidCore.Refinement.Shapes.Compiled.certified_of_holds' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms Compiled.certified_of_holds + +/-- info: 'SolidCore.Refinement.Shapes.holdsFn_genericValid0' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holdsFn_genericValid0 + + +/-! ## Calls with a value -/ + +/-- `msg.value == 0`, as solar-verify exports it. -/ +def valueZero : SolidCore.Spec.Term := .bin .eq (.env .value) (.lit 0) + +/-- The value guard: one of the spec's succeeds-if conditions is `msg.value == 0`, or a conjunction +`msg.value == 0 && e` (one condition, as solar-verify reads each condition on its own). -/ +def valueGuarded (fs : FnSpec) : Prop := + ∃ t ∈ fs.succeedsIf, t = valueZero ∨ ∃ e, t = .bin .and valueZero e + +theorem not_sat_of_value {b : Bundle} {fs : FnSpec} (hg : valueGuarded fs) {e : SolidCore.Spec.Env} + (hv : e.ctx.value ≠ 0) : ¬ b.satAll fs.succeedsIf e := by + intro h + obtain ⟨t, ht, hgt⟩ := hg + have := h t ht + rcases hgt with rfl | ⟨x, rfl⟩ <;> + simp [valueZero, SolidCore.Spec.Bundle.sat, SolidCore.Spec.eval, SolidCore.Spec.BinOp.apply, + SolidCore.Spec.ofProp, hv] at this + +/-- SolidCore rejects a value on every call of a function the generic check and the value check +accept. -/ +theorem run_value {fuel mirFuel : Nat} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {d : SolidCore.Solidity.Source.State} {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) + {m : SolarTV.MIR.Lowered.Module} {fns : List Fn} {env : Generic.EnvFlags} + (hchk : Generic.check fuel mirFuel c.core m fns env = true) + (hval : Generic.checkValue mirFuel c.core m fns env = true) {g : Fn} (hg : g ∈ fns) + (args : List Nat) (hlen : args.length = g.params.length) (hargs : ∀ a ∈ args, a < 2 ^ 256) + {v : Nat} (hv0 : v ≠ 0) (hv : v < 2 ^ 256) (σ : List (Nat × Nat)) : + (solidCore fuel).run c { calldata := calldata g.sel args, callvalue := v, storage := σ } = + some (rejected σ) := by + have hcf := List.all_eq_true.mp hchk g hg + have hcv := List.all_eq_true.mp hval g hg + unfold Generic.checkFn at hcf + unfold Generic.checkValueFn at hcv + cases hfind : c.core.findFunctionBySelector? g.sel with + | none => simp [hfind] at hcf + | some fn => + cases ht1 : Generic.eraseFn (Generic.envOf c.core) fuel fn with + | none => simp [hfind, ht1] at hcf + | some t1 => + simp only [hfind, ht1, Bool.and_eq_true, decide_eq_true_eq] at hcf + obtain ⟨hsel, hpl, -⟩ := hcf + simp only [hfind, Bool.and_eq_true, Bool.not_eq_true'] at hcv + obtain ⟨ws, hw⟩ := Generic.eraseFn_widths ht1 + exact Generic.source_run_value hd hsel hfind hw hcv.1 args (by rw [hlen, hpl]) hargs hv0 hv σ + +/-- **One function spec on the stage's calls at every value**: the calls without a value from +its `HoldsFn` on the stage's calls of the function of its selector; the calls with a value revert +with empty data, which meets the spec when its succeeds-if conditions require `msg.value == 0`. -/ +theorem holdsFn_genericValid {fuel mirFuel : Nat} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {d : SolidCore.Solidity.Source.State} {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) + {m : SolarTV.MIR.Lowered.Module} {fns : List Fn} {env : Generic.EnvFlags} + (hchk : Generic.check fuel mirFuel c.core m fns env = true) + (hval : Generic.checkValue mirFuel c.core m fns env = true) + {b : Bundle} {ctxOf : Call → SolidCore.Spec.Ctx} {step : SolidCore.Spec.GhostStep} {fs : FnSpec} + (hctx : ∀ call, (ctxOf call).value = call.callvalue) + (hguard : fs.succeedsIf = [] ∨ valueGuarded fs) + {fn : Fn} (hfn : fn.sel = fs.selector) (hok : selOk fns fn.sel fn.params.length = true) + (h : HoldsFn (solidCore fuel) c (SolidCore.Verify.VC.stageScope fn s) b ctxOf step fs) : + HoldsFn (solidCore fuel) c (genericValid fns s) b ctxOf step fs := by + rintro _ ⟨σ, v, hcov, hv, g, hg, args, hlen, hargs, rfl⟩ iargs pre hpre + by_cases hv0 : v = 0 + · subst hv0 + exact holdsFn_genericValid0 hfn hok h _ ⟨σ, hcov, g, hg, args, hlen, hargs, rfl⟩ iargs pre hpre + · refine ⟨_, run_value hd hchk hval hg args hlen hargs hv0 hv σ, fun hs => absurd hs (by + simp [rejected]), fun hne hsat => absurd hsat (not_sat_of_value (hguard.resolve_left hne) ?_)⟩ + simp only [SolidCore.Spec.mkEnv, hctx] + exact_mod_cast hv0 + +/-! ## Non-vacuity from a call whose succeeds-if conditions hold -/ + +/-- **Both non-vacuity witnesses from one valid call** from which a function spec with succeeds-if +conditions must succeed: the same call reverting is rejected by the exported postcondition and by +the exported allowed statuses. -/ +theorem nonvacuous_of_succeeds {b : Bundle} {ctxOf : Call → SolidCore.Spec.Ctx} + {step : SolidCore.Spec.GhostStep} {Valid : Call → Prop} {call : Call} (hc : Valid call) + {fs : FnSpec} (hfs : fs ∈ b.spec.specs) {args : List Int} {pre : SolidCore.Spec.State} + (hpre : Pre b fs (ctxOf call) pre call args) (hne : fs.succeedsIf ≠ []) + (hsat : b.satAll fs.succeedsIf (SolidCore.Spec.mkEnv (ctxOf call) args [] pre pre)) : + (∃ (call : Call) (obs : Observable), Valid call ∧ ¬ bundlePost b ctxOf step call obs) ∧ + (∃ (call : Call) (obs : Observable), Valid call ∧ obs.success = false ∧ + ¬ bundleAllowed b ctxOf call obs) := by + let obs : Observable := ⟨false, [], [], slotValue call.storage⟩ + refine ⟨⟨call, obs, hc, fun h => ?_⟩, ⟨call, obs, hc, rfl, fun h => ?_⟩⟩ + · have := (h fs hfs args pre hpre).2 hne hsat + cases this + · rcases h with h | h + · cases h + · exact h fs hfs args pre hpre hne hsat + +/-- A call of the stage's valid calls without a value: the function of `fns` with the selector +`sel` (found by evaluation) on zero words. -/ +theorem valid0_of_find {fns : List Fn} {s σ : List (Nat × Nat)} (hcov : Generic.Covers s σ) + {sel n : Nat} (h : (fns.find? (fun g => g.sel == sel)).map (·.params.length) = some n) : + genericValid0 fns s { calldata := calldata sel (List.replicate n 0), callvalue := 0, storage := σ } := by + cases hf : fns.find? (fun g => g.sel == sel) with + | none => rw [hf] at h; cases h + | some g => + rw [hf] at h + simp only [Option.map_some, Option.some.injEq] at h + have hg := List.mem_of_find?_eq_some hf + have hs := List.find?_some hf + simp only [beq_iff_eq] at hs + subst h hs + exact ⟨σ, hcov, g, hg, List.replicate g.params.length 0, List.length_replicate, + fun a ha => by rw [(List.mem_replicate.mp ha).2]; decide, rfl⟩ + +/-- The same call among the stage's valid calls at every value. -/ +theorem valid_of_find {fns : List Fn} {s σ : List (Nat × Nat)} (hcov : Generic.Covers s σ) + {sel n : Nat} (h : (fns.find? (fun g => g.sel == sel)).map (·.params.length) = some n) : + genericValid fns s { calldata := calldata sel (List.replicate n 0), callvalue := 0, storage := σ } := by + obtain ⟨σ', hc, hs⟩ := valid0_of_find hcov h + exact ⟨σ', 0, hc, (Generic.fullScopeValue_zero _ _ _).2 hs⟩ + +/-- The precondition's decoding of the stage's call data on zero words. -/ +theorem decodes_zero {fs : FnSpec} {sel n : Nat} (hsel : sel < 2 ^ 32) (hfs : fs.selector = sel) + {args : List Int} (hd : SolidCore.Spec.decodeWords fs.params (List.replicate n 0) = some args) + (v : Nat) (σ : List (Nat × Nat)) : + SolidCore.Spec.Decodes fs { calldata := calldata sel (List.replicate n 0), callvalue := v, storage := σ } args := by + refine ⟨?_, by rw [selectorOf_calldata hsel, hfs], ?_⟩ + · show 4 ≤ (calldata sel (List.replicate n 0)).size + have := congrArg List.length (Dirty.bytes_calldata sel (List.replicate n 0)) + simp only [List.length_map, Array.length_toList, List.length_append, EthLib.Base.natToBytes_length] at this + rw [ByteArray.size, this] + omega + · show SolidCore.Spec.decodeWords fs.params (SolidCore.Spec.words + (((calldata sel (List.replicate n 0)).data.toList.map (·.toNat)).drop 4)) = some args + rw [SolidCore.Spec.words_calldata _ (fun a ha => by rw [(List.mem_replicate.mp ha).2]; decide)] + exact hd + +/-- info: 'SolidCore.Refinement.Shapes.holdsFn_genericValid' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holdsFn_genericValid + +/-- info: 'SolidCore.Refinement.Shapes.nonvacuous_of_succeeds' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms nonvacuous_of_succeeds + + +/-! ## A zero storage covering the constructor's slots -/ + +/-- The constructor's slots, each written with 0. -/ +def zeros (s : List (Nat × Nat)) : List (Nat × Nat) := s.map fun kv => (kv.1, 0) + +theorem covers_zeros (s : List (Nat × Nat)) : Generic.Covers s (zeros s) := by + intro kv hkv + exact ⟨(kv.1, 0), List.mem_map.mpr ⟨kv, hkv, rfl⟩, rfl⟩ + +theorem slotValue_zeros (s : List (Nat × Nat)) : slotValue (zeros s) = fun _ => 0 := by + funext k + unfold slotValue zeros + suffices ∀ (l : List (Nat × Nat)) (a : Nat), a = 0 → + (l.map fun kv => (kv.1, 0)).foldl (fun acc kv => if kv.1 % 2^256 = k % 2^256 then kv.2 % 2^256 else acc) a = 0 from + this s 0 rfl + intro l + induction l with + | nil => intro a h; simpa using h + | cons x l ih => + intro a h + simp only [List.map_cons, List.foldl_cons] + apply ih + split <;> simp [h] + +end SolidCore.Refinement.Shapes diff --git a/Verify/Shapes.lean b/Verify/Shapes.lean new file mode 100644 index 00000000..200c4b6e --- /dev/null +++ b/Verify/Shapes.lean @@ -0,0 +1,234 @@ +import Verify.Final + +/-! +# The shape of a certified compilation + +What a published certificate of a contract states, as four separate obligations over SolidCore's +checked source `p` (in a source semantics `S`) and the exact emitted runtime bytecode `code` +(under EthLib at an explicit gas), on a declared valid-call precondition `Valid`: + +* `Equiv` (behavioural equivalence, gas-insensitive): at every gas below `2 ^ 256`, every result + of the bytecode on a valid call is the source's result on that call, or a failure that changes + nothing (`Inert`: running out of gas is one). This is the backward simulation; the forward one is + `Resources`, so together they give equality of observable results (`Certified.agree`). +* `Terminates`: the source halts on every valid call, with a status the specification allows + (`Allowed`: success, or one of the declared reverts; an arbitrary revert is not allowed unless + `Allowed` says so). For a fuel-indexed source (`solidCore fuel`) halting is within the fuel; + for loops, the fuel bound is what a ranking certificate proves. +* `Meets`: the user specification `Post` holds of every source result on a valid call, over the + same source semantics the other obligations use. +* `Resources`: an explicit gas bound `G call` below `2 ^ 64` from which on, at every gas below + `2 ^ 256`, the bytecode gives exactly the source's result: it does not run out of gas. It is + not a premise: `G` is part of the statement and the theorem must prove the run at every gas + above it. + +`Certified` is all four plus a witness that `Valid` is inhabited. Named environment +assumptions are hypotheses of the published statement (`Env → Certified …`), never folded into +`Valid`. A source that diverges or gets stuck on a valid call cannot meet `Terminates`, so it +never reaches the strongest status; stages of such programs keep the bidirectional +`SolarTV.CutPoint.LayerSim` (`ends_iff`, `diverges_iff`, `stuck_iff`), which this file does not +use, since for a source total on `Valid` a forward stage and the backward `Within` suffice +(`equiv_of_runs`, `resources_of_forward`). + +Observables do not tell running out of gas from a revert with the same (empty) data, so +`Resources` asks for the source's exact result rather than "not out of gas". +-/ + +namespace SolidCore.Refinement.Shapes + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Final + +/-- A failure that changes nothing. -/ +def Inert (call : Call) (obs : Observable) : Prop := + obs.success = false ∧ obs.storage = slotValue call.storage ∧ obs.logs = [] + +/-- **(1) Behavioural equivalence, gas-insensitive.** -/ +def Equiv (S : Sem) (p : S.Prog) (code : ByteArray) (Valid : Call → Prop) : Prop := + ∀ gas, gas < 2 ^ 256 → ∀ call, Valid call → ∀ obs, Final.Target.runWith gas code call = some obs → + S.run p call = some obs ∨ Inert call obs + +/-- **(2) Termination** of the source on every valid call, with an allowed status. -/ +def Terminates (S : Sem) (p : S.Prog) (Valid : Call → Prop) + (Allowed : Call → Observable → Prop) : Prop := + ∀ call, Valid call → ∃ obs, S.run p call = some obs ∧ Allowed call obs + +/-- **(3) The specification** of every source result on a valid call. -/ +def Meets (S : Sem) (p : S.Prog) (Valid : Call → Prop) (Post : Call → Observable → Prop) : Prop := + ∀ call, Valid call → ∀ obs, S.run p call = some obs → Post call obs + +/-- **(4) Resources**: from `G call` gas on the bytecode gives the source's result exactly. -/ +def Resources (S : Sem) (p : S.Prog) (code : ByteArray) (Valid : Call → Prop) + (G : Call → Nat) : Prop := + ∀ call, Valid call → G call < 2 ^ 64 ∧ + ∀ gas, G call ≤ gas → gas < 2 ^ 256 → Final.Target.runWith gas code call = S.run p call + +/-- **The strongest status**: all four obligations on an inhabited precondition. -/ +structure Certified (S : Sem) (p : S.Prog) (code : ByteArray) (Valid : Call → Prop) + (Allowed Post : Call → Observable → Prop) (G : Call → Nat) : Prop where + inhabited : ∃ call, Valid call + equiv : Equiv S p code Valid + terminates : Terminates S p Valid Allowed + meets : Meets S p Valid Post + resources : Resources S p code Valid G + +/-- Everything but resources: what a contract whose gas bound is not proved yet can state. Never +reported as the strongest status. -/ +structure Functional (S : Sem) (p : S.Prog) (code : ByteArray) (Valid : Call → Prop) + (Allowed Post : Call → Observable → Prop) : Prop where + inhabited : ∃ call, Valid call + equiv : Equiv S p code Valid + terminates : Terminates S p Valid Allowed + meets : Meets S p Valid Post + +theorem Certified.functional {S : Sem} {p : S.Prog} {code : ByteArray} {Valid : Call → Prop} + {Allowed Post : Call → Observable → Prop} {G : Call → Nat} + (h : Certified S p code Valid Allowed Post G) : Functional S p code Valid Allowed Post := + ⟨h.inhabited, h.equiv, h.terminates, h.meets⟩ + +/-! ## What the bytecode does -/ + +/-- **Total correctness of the bytecode.** At every gas from the bound on, every valid call ends, +with an allowed status, meeting the specification, with the source's observable. -/ +theorem Certified.bytecode_total {S : Sem} {p : S.Prog} {code : ByteArray} {Valid : Call → Prop} + {Allowed Post : Call → Observable → Prop} {G : Call → Nat} + (h : Certified S p code Valid Allowed Post G) (call : Call) (hc : Valid call) : + G call < 2 ^ 64 ∧ ∀ gas, G call ≤ gas → gas < 2 ^ 256 → ∃ obs, + Final.Target.runWith gas code call = some obs ∧ S.run p call = some obs ∧ + Allowed call obs ∧ Post call obs := by + obtain ⟨hG, hrun⟩ := h.resources call hc + refine ⟨hG, fun gas h1 h2 => ?_⟩ + obtain ⟨obs, hs, ha⟩ := h.terminates call hc + exact ⟨obs, (hrun gas h1 h2).trans hs, hs, ha, h.meets call hc obs hs⟩ + +/-- **Partial correctness of the bytecode at every gas.** Every result of the bytecode on a valid +call, at any gas below `2 ^ 256`, is an allowed one meeting the specification, or a failure that +changes nothing. -/ +theorem Functional.bytecode_any {S : Sem} {p : S.Prog} {code : ByteArray} {Valid : Call → Prop} + {Allowed Post : Call → Observable → Prop} + (h : Functional S p code Valid Allowed Post) (gas : Nat) (hg : gas < 2 ^ 256) (call : Call) + (hc : Valid call) (obs : Observable) (hrun : Final.Target.runWith gas code call = some obs) : + (Allowed call obs ∧ Post call obs) ∨ Inert call obs := by + rcases h.equiv gas hg call hc obs hrun with e | e + · obtain ⟨obs', hs, ha⟩ := h.terminates call hc + obtain rfl : obs' = obs := Option.some.inj (hs.symm.trans e) + exact Or.inl ⟨ha, h.meets call hc obs' hs⟩ + · exact Or.inr e + +/-- Equivalence in both directions at enough gas: source and bytecode give the same observable. -/ +theorem Certified.agree {S : Sem} {p : S.Prog} {code : ByteArray} {Valid : Call → Prop} + {Allowed Post : Call → Observable → Prop} {G : Call → Nat} + (h : Certified S p code Valid Allowed Post G) (call : Call) (hc : Valid call) (gas : Nat) + (h1 : G call ≤ gas) (h2 : gas < 2 ^ 256) : + ∃ obs, S.run p call = some obs ∧ Final.Target.runWith gas code call = some obs := by + obtain ⟨-, hr⟩ := h.bytecode_total call hc + obtain ⟨obs, ht, hs, -⟩ := hr gas h1 h2 + exact ⟨obs, hs, ht⟩ + +/-! ## Composition from the existing pieces -/ + +/-- **Equivalence from a total source, forward stages and the per-run assembly theorem.** A +source that ends on every valid call, a stage from it into the EVM IR under every oracle meeting +`Ok`, and the assembly checker's per-run theorem (`AssembleCut.WithinRunLt`, unfolded) give +equivalence with the exact bytecode at every gas. -/ +theorem equiv_of_runs {O : Type} {S : Sem} {p : S.Prog} {sem : O → Sem} {q : ∀ o, (sem o).Prog} + {code : ByteArray} {Valid : Call → Prop} {Ok : O → Prop} + (total : ∀ call, Valid call → ∃ obs, S.run p call = some obs) + (stage : ∀ o, Ok o → Stage S (sem o) p (q o) Valid) + (runs : ∀ gas, gas < 2 ^ 256 → ∀ call, Valid call → ∃ o, Ok o ∧ + Within (sem o) (ethLibWith gas) (q o) code (· = call)) : + Equiv S p code Valid := by + intro gas hg call hc obs hrun + obtain ⟨o, ho, hw⟩ := runs gas hg call hc + rcases hw call rfl obs hrun with e | e + · obtain ⟨obs0, h0⟩ := total call hc + have hq := stage o ho call hc obs0 h0 + obtain rfl : obs0 = obs := Option.some.inj (hq.symm.trans e) + exact Or.inl h0 + · exact Or.inr e + +/-- **Resources from a forward assembly theorem with gas.** -/ +theorem resources_of_forward {S B : Sem} {p : S.Prog} {q : B.Prog} {code : ByteArray} + {Valid : Call → Prop} {G : Call → Nat} + (total : ∀ call, Valid call → ∃ obs, S.run p call = some obs) + (stage : Stage S B p q Valid) + (forward : ∀ call, Valid call → G call < 2 ^ 64 ∧ ∀ gas, G call ≤ gas → gas < 2 ^ 256 → + ∀ obs, B.run q call = some obs → Final.Target.runWith gas code call = some obs) : + Resources S p code Valid G := by + intro call hc + obtain ⟨hG, hf⟩ := forward call hc + refine ⟨hG, fun gas h1 h2 => ?_⟩ + obtain ⟨obs, hs⟩ := total call hc + rw [hs] + exact hf gas h1 h2 obs (stage call hc obs hs) + +/-- Termination from a source that ends with an allowed status. -/ +theorem terminates_of {S : Sem} {p : S.Prog} {Valid : Call → Prop} + {Allowed : Call → Observable → Prop} (f : Call → Observable) + (run : ∀ call, Valid call → S.run p call = some (f call)) + (allowed : ∀ call, Valid call → Allowed call (f call)) : Terminates S p Valid Allowed := + fun call hc => ⟨f call, run call hc, allowed call hc⟩ + +/-- solar-verify's contract specification as a postcondition: a result of a call of a specified +function, on clean argument words, with a value below `2 ^ 256`, from a storage that meets the +invariant and the precondition, meets `ContractSpec.Outcome`. -/ +def specPost {St : Type} (spec : ContractSpec St) (call : Call) (obs : Observable) : Prop := + ∀ f ∈ spec.fns, ∀ args, f.Typed args → ∀ v, v < 2 ^ 256 → ∀ σ, call = f.call args v σ → + spec.invariant (spec.abs (slotValue σ)) → f.requires args (spec.abs (slotValue σ)) → + spec.Outcome f args call obs + +/-- `Holds` of the source is `Meets` of `specPost`. -/ +theorem meets_of_holds {St : Type} {S : Sem} {p : S.Prog} {spec : ContractSpec St} + {Valid : Call → Prop} (h : Holds S p spec) : Meets S p Valid (specPost spec) := by + intro call _ obs hrun f hf args ht v hv σ he hinv hreq + subst he + exact h f hf args ht v hv σ hinv hreq obs hrun + +/-! ## Negative controls: each obligation fails by a concrete mismatch -/ + +theorem not_equiv_of {S : Sem} {p : S.Prog} {code : ByteArray} {Valid : Call → Prop} + {call : Call} {gas : Nat} {obs : Observable} (hc : Valid call) (hg : gas < 2 ^ 256) + (hrun : Final.Target.runWith gas code call = some obs) (hs : S.run p call ≠ some obs) + (hi : ¬Inert call obs) : ¬Equiv S p code Valid := fun h => + (h gas hg call hc obs hrun).elim hs hi + +theorem not_terminates_of_none {S : Sem} {p : S.Prog} {Valid : Call → Prop} + {Allowed : Call → Observable → Prop} {call : Call} (hc : Valid call) + (hn : S.run p call = none) : ¬Terminates S p Valid Allowed := fun h => by + obtain ⟨obs, hs, -⟩ := h call hc + rw [hn] at hs + cases hs + +theorem not_terminates_of_disallowed {S : Sem} {p : S.Prog} {Valid : Call → Prop} + {Allowed : Call → Observable → Prop} {call : Call} {obs : Observable} (hc : Valid call) + (hs : S.run p call = some obs) (hn : ¬Allowed call obs) : ¬Terminates S p Valid Allowed := + fun h => by + obtain ⟨obs', hs', ha⟩ := h call hc + rw [hs] at hs' + cases hs' + exact hn ha + +theorem not_meets_of {S : Sem} {p : S.Prog} {Valid : Call → Prop} + {Post : Call → Observable → Prop} {call : Call} {obs : Observable} (hc : Valid call) + (hs : S.run p call = some obs) (hn : ¬Post call obs) : ¬Meets S p Valid Post := + fun h => hn (h call hc obs hs) + +theorem not_resources_of {S : Sem} {p : S.Prog} {code : ByteArray} {Valid : Call → Prop} + {G : Call → Nat} {call : Call} {gas : Nat} (hc : Valid call) (h1 : G call ≤ gas) + (h2 : gas < 2 ^ 256) (hn : Final.Target.runWith gas code call ≠ S.run p call) : + ¬Resources S p code Valid G := fun h => hn ((h call hc).2 gas h1 h2) + +theorem not_resources_of_bound {S : Sem} {p : S.Prog} {code : ByteArray} {Valid : Call → Prop} + {G : Call → Nat} {call : Call} (hc : Valid call) (hG : 2 ^ 64 ≤ G call) : + ¬Resources S p code Valid G := fun h => absurd (h call hc).1 (Nat.not_lt.mpr hG) + +theorem not_certified_of_empty {S : Sem} {p : S.Prog} {code : ByteArray} {Valid : Call → Prop} + {Allowed Post : Call → Observable → Prop} {G : Call → Nat} (he : ∀ call, ¬Valid call) : + ¬Certified S p code Valid Allowed Post G := fun h => by + obtain ⟨call, hc⟩ := h.inhabited + exact he call hc + +/-- info: 'SolidCore.Refinement.Shapes.Certified.bytecode_total' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms Certified.bytecode_total + +end SolidCore.Refinement.Shapes diff --git a/Verify/SourceOracle.lean b/Verify/SourceOracle.lean new file mode 100644 index 00000000..98853d5b --- /dev/null +++ b/Verify/SourceOracle.lean @@ -0,0 +1,146 @@ +import Verify.Final +import SolidCore.Refinement.SourceOracle +import SolidCore.Refinement.Generic.StageIn +import SolidCore.Refinement.SourceOracleSat +import SolidCore.Refinement.SourceOracleMono + +/-! +# The composition under a call oracle + +`compose_in` is `Final.compose_anyGas` for SolidCore in the world `W` (`solidCoreIn`), with the +oracle hypothesis `CallsAgree o W` that the source stage into `mirSem o` assumes a premise of the +end-to-end theorem: a specification proved of SolidCore under every open world, or under the +worlds a named interface hypothesis admits, holds of the bytecode for every oracle that agrees with +one of them. +-/ + +namespace SolidCore.Refinement + +/-- **The specification holds of the bytecode, in the world `W`**: given the specification of +SolidCore in `W`, its totality there, the source stage into `mirSem o` under the oracle hypothesis +`CallsAgree o W`, the backend stages and the assembly stage at every gas, the bytecode agrees with +SolidCore in `W` and the specification holds of it at every gas. -/ +theorem compose_in {St : Type} {W : World} {fuel : Nat} {o : SolarTV.Machine.Oracle} + {mirSem evmirSem : Sem} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {mir : mirSem.Prog} {evmir : evmirSem.Prog} {code : ByteArray} + {spec : Final.ContractSpec St} + (agree : CallsAgree o W) + (source : Final.Holds (solidCoreIn W fuel) c spec) + (fin : ∀ call, spec.Calls call → (Source.runIn W fuel c call).isSome) + (lowering : CallsAgree o W → Stage (solidCoreIn W fuel) mirSem c mir spec.Calls) + (backend : Stage mirSem evmirSem mir evmir spec.Calls) + (assembly : ∀ gas, Final.Within evmirSem (Final.ethLibWith gas) evmir code spec.Calls) + (gas : Nat) : + Final.Within (solidCoreIn W fuel) (Final.ethLibWith gas) c code spec.Calls ∧ + Final.Holds (Final.ethLibWith gas) code spec := + Final.compose_anyGas source fin (lowering agree) backend assembly gas + +/-- info: 'SolidCore.Refinement.compose_in' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms compose_in + +/-- **The specification holds of the bytecode, run by run**: a call's outcomes in EthLib depend on +the gas and the state of the other accounts, so no single oracle describes every run. Here each run +of the bytecode at each gas has an oracle `o` and an open world `W` that agree (`CallsAgree o W`) +under which the EVM IR gives the bytecode's result or a failure that changes nothing (`assembly`); +the specification, the totality and the stages hold for every open world and every oracle; and then +the specification holds of the bytecode at every gas. -/ +theorem holds_of_runs {St : Type} {fuel : Nat} + {mirSem evmirSem : SolarTV.Machine.Oracle → Sem} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {mir : ∀ o, (mirSem o).Prog} {evmir : ∀ o, (evmirSem o).Prog} {code : ByteArray} + {spec : Final.ContractSpec St} + (source : ∀ W : World, W.Open → Final.Holds (solidCoreIn W fuel) c spec) + (fin : ∀ W : World, W.Open → ∀ call, spec.Calls call → (Source.runIn W fuel c call).isSome) + (lowering : ∀ o W, CallsAgree o W → Stage (solidCoreIn W fuel) (mirSem o) c (mir o) spec.Calls) + (backend : ∀ o, Stage (mirSem o) (evmirSem o) (mir o) (evmir o) spec.Calls) + (assembly : ∀ gas call, spec.Calls call → ∃ o W, W.Open ∧ CallsAgree o W ∧ + Final.Within (evmirSem o) (Final.ethLibWith gas) (evmir o) code (· = call)) + (gas : Nat) : Final.Holds (Final.ethLibWith gas) code spec := by + intro f hf args ht v hv σ hinv hreq obs hrun + have hc : spec.Calls (f.call args v σ) := ⟨f, hf, args, ht, v, hv, σ, rfl⟩ + obtain ⟨o, W, hopen, hagree, hwithin⟩ := assembly gas _ hc + have agree := Final.agree_of_stage ((lowering o W hagree).trans (backend o)) (fin W hopen) + rcases hwithin _ rfl obs hrun with h | ⟨hs, hst, hl⟩ + · obtain ⟨obs', hs', hm⟩ := agree _ hc + rw [h] at hm + cases hm + exact source W hopen f hf args ht v hv σ hinv hreq obs hs' + · exact ⟨fun h'' => absurd (hs.symm.trans h'') (by decide), fun _ => ⟨hst, hl⟩⟩ + +/-- info: 'SolidCore.Refinement.holds_of_runs' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holds_of_runs + +/-- **The specification holds of the bytecode, run by run, for a contract the generic check +accepts**: `holds_of_runs` with its lowering obligation discharged by the generic source stage in +every world (`Generic.stageInDeployed`): the functions `check` accepts make no external call, so the +stage holds for every world and oracle with no hypothesis. -/ +theorem holds_of_runs_generic {St : Type} {fuel mirFuel : Nat} + {evmirSem : SolarTV.Machine.Oracle → Sem} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {d : SolidCore.Solidity.Source.State} {s : List (Nat × Nat)} + {m : SolarTV.MIR.Lowered.Module} {fns : List Abi.Fn} + {evmir : ∀ o, (evmirSem o).Prog} {code : ByteArray} {spec : Final.ContractSpec St} + (hd : Wide.DeployedAt fuel c d s) (hchk : Generic.check fuel mirFuel c.core m fns = true) + (hscope : ∀ call, spec.Calls call → Abi.fullScope fns s call) + (source : ∀ W : World, W.Open → Final.Holds (solidCoreIn W fuel) c spec) + (fin : ∀ W : World, W.Open → ∀ call, spec.Calls call → (Source.runIn W fuel c call).isSome) + (backend : ∀ o, Stage (SolarTV.MIR.Lowered.moduleSem o) (evmirSem o) m (evmir o) spec.Calls) + (assembly : ∀ gas call, spec.Calls call → ∃ o W, W.Open ∧ CallsAgree o W ∧ + Final.Within (evmirSem o) (Final.ethLibWith gas) (evmir o) code (· = call)) + (gas : Nat) : Final.Holds (Final.ethLibWith gas) code spec := + holds_of_runs (mirSem := SolarTV.MIR.Lowered.moduleSem) (mir := fun _ => m) source fin + (fun o W _ => SolarTV.Stage.mono (Generic.stageInDeployed W o hd hchk) hscope) + backend assembly gas + +/-- info: 'SolidCore.Refinement.holds_of_runs_generic' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holds_of_runs_generic + +/-! ## Specifications in every world -/ + +/-- `Triple` with SolidCore in the world `W`. -/ +def TripleIn (W : World) (fuel : Nat) (c : SolidCore.Solidity.TypeCheck.CheckedContract) + (scope : SolarTV.Call → Prop) (pre : SolarTV.Call → Prop) + (post : SolarTV.Call → SolarTV.Observable → Prop) : Prop := + ∀ call, scope call → pre call → + (Source.runIn W fuel c call).isSome ∧ + ∀ obs, Source.runIn W fuel c call = some obs → post call obs + +/-- **A triple of a function the generic check accepts holds in every world**: such a function runs +the same in every world (`Generic.runIn_eq_run`). -/ +theorem tripleIn_of_triple {fuel mirFuel : Nat} {c : SolidCore.Solidity.TypeCheck.CheckedContract} + {d : SolidCore.Solidity.Source.State} {s : List (Nat × Nat)} {m : SolarTV.MIR.Lowered.Module} + {fns : List Abi.Fn} {env : SolidCore.Refinement.Generic.EnvFlags} + (hd : Wide.DeployedAt fuel c d s) (hchk : Generic.check fuel mirFuel c.core m fns env = true) + {scope pre : SolarTV.Call → Prop} {post : SolarTV.Call → SolarTV.Observable → Prop} + (hscope : ∀ call, scope call → ∃ σ, Generic.Covers s σ ∧ Abi.fullScope fns σ call) + (h : SolidCore.Verify.Triple fuel c scope pre post) (W : World) : + TripleIn W fuel c scope pre post := by + intro call hs hp + rw [Generic.runIn_eq_run W hd hchk call (hscope call hs)] + exact h call hs hp + +/-- **A specification of the functions the generic check accepts holds in every world.** -/ +theorem holdsIn_of_holds {St : Type} {fuel mirFuel : Nat} + {c : SolidCore.Solidity.TypeCheck.CheckedContract} {d : SolidCore.Solidity.Source.State} + {s : List (Nat × Nat)} {m : SolarTV.MIR.Lowered.Module} {fns : List Abi.Fn} + {env : SolidCore.Refinement.Generic.EnvFlags} {spec : Final.ContractSpec St} + (hd : Wide.DeployedAt fuel c d s) (hchk : Generic.check fuel mirFuel c.core m fns env = true) + (hscope : ∀ call, spec.Calls call → ∃ σ, Generic.Covers s σ ∧ Abi.fullScope fns σ call) + (h : Final.Holds (solidCore fuel) c spec) (W : World) : + Final.Holds (solidCoreIn W fuel) c spec := by + intro f hf args ht v hv σ hinv hreq obs hrun + have hc : spec.Calls (f.call args v σ) := ⟨f, hf, args, ht, v, hv, σ, rfl⟩ + change Source.runIn W fuel c _ = some obs at hrun + rw [Generic.runIn_eq_run W hd hchk _ (hscope _ hc)] at hrun + exact h f hf args ht v hv σ hinv hreq obs hrun + +/-- info: 'SolidCore.Refinement.tripleIn_of_triple' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms tripleIn_of_triple + +/-- info: 'SolidCore.Refinement.holdsIn_of_holds' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holdsIn_of_holds + +end SolidCore.Refinement diff --git a/Verify/Spec/Contract.lean b/Verify/Spec/Contract.lean new file mode 100644 index 00000000..9eb6515d --- /dev/null +++ b/Verify/Spec/Contract.lean @@ -0,0 +1,186 @@ +import Verify.Spec.Semantics + +/-! +# A function's spec over a call and its observable + +`Pre` and `Post` are a function's spec as predicates over a `SolarTV.Call` and the +`SolarTV.Observable` it finishes with, given the call's environment (`Ctx`), the ghost state before +and after it and `__time` before it. `Holds` says that every function's spec holds of a program in +a semantics. Because SolidCore (`SolidCore.Refinement.solidCore`) and EthLib +(`SolidCore.Refinement.ethLib`) are both `SolarTV.Sem`s over the same calls and observables, the +same `Holds` states the spec of the source and of the bytecode, and a refinement between them +carries one to the other (`Holds.of_stage`). + +The meaning follows solar-verify's (crates/verify/README.md, "Semantics"): + +* the requires and the contract invariants are assumed of the pre-state, with `__time` the time + before the call, at most the block's timestamp; +* a successful call returns ABI-clean words of the return types, and the ensures and the + invariants hold of the post-state, in which `__time` is the block's timestamp; +* a reverted call owes nothing, since it has no effect (the semantics' failure convention); +* from a pre-state meeting the succeeds-if conditions (and the requires), the call succeeds. +-/ + +namespace SolidCore.Spec + +open SolarTV + +/-- The 32-byte big-endian words of a byte list (a short last word is dropped). -/ +def words (bs : List Nat) : List Nat := + (List.range (bs.length / 32)).map fun i => bytesWord ((bs.drop (32 * i)).take 32) + +/-- Decode words as values of the types, or `none` when there are too few or one is not clean. -/ +def decodeWords : List Ty → List Nat → Option (List Int) + | [], _ => some [] + | _ :: _, [] => none + | t :: ts, w :: ws => do + let v ← t.ofWord w + let vs ← decodeWords ts ws + pure (v :: vs) + +/-- The selector of a call: its first four bytes. -/ +def selectorOf (call : Call) : Nat := bytesWord ((call.calldata.data.toList.map (·.toNat)).take 4) + +/-- The call is to `fs`, with arguments `args`: the selector matches and the argument words are +clean for the parameter types. -/ +def Decodes (fs : FnSpec) (call : Call) (args : List Int) : Prop := + 4 ≤ call.calldata.size ∧ selectorOf call = fs.selector ∧ + decodeWords fs.params (words ((call.calldata.data.toList.map (·.toNat)).drop 4)) = some args + +/-- The environment of a spec expression on a call. -/ +def mkEnv (ctx : Ctx) (args rets : List Int) (pre post : State) : Env := + { args, rets, pre, post, ctx, vars := [], inOld := false } + +/-- The spec of a contract's functions, with `fuel` the bound on nested spec function calls. -/ +structure Bundle where + spec : ContractSpec + fuel : Nat + +/-- A formula of the bundle holds in an environment. -/ +def Bundle.sat (b : Bundle) (t : Term) (e : Env) : Prop := eval b.spec.fns b.fuel t e ≠ 0 + +/-- Every formula of a list holds. -/ +def Bundle.satAll (b : Bundle) (ts : List Term) (e : Env) : Prop := ∀ t ∈ ts, b.sat t e + +/-- The precondition of `fs` on `call` from the state `pre`: the arguments decode, `pre` is the +call's storage, `__time` is at most the block's timestamp, and the requires and invariants hold. -/ +def Pre (b : Bundle) (fs : FnSpec) (ctx : Ctx) (pre : State) (call : Call) (args : List Int) : + Prop := + Decodes fs call args ∧ pre.storage = slotValue call.storage ∧ pre.time ≤ ctx.timestamp ∧ + b.satAll fs.requires (mkEnv ctx args [] pre pre) ∧ + b.satAll b.spec.invariants (mkEnv ctx args [] pre pre) + +/-- The postcondition of `fs` on `call` from `pre`, finishing with `obs` and the ghost state +`ghost'`: a success returns clean words meeting the ensures and leaves a state meeting the +invariants; when `fs` has succeeds-if conditions, from a pre-state meeting them the call +succeeds. A function without any makes no claim that it succeeds, as in solar-verify, whose +export then writes `succeedsIf := []`. -/ +def Post (b : Bundle) (fs : FnSpec) (ctx : Ctx) (pre : State) (ghost' : Ghost) (obs : Observable) + (args : List Int) : Prop := + let post : State := { storage := obs.storage, ghost := ghost', time := ctx.timestamp } + (obs.success = true → ∃ rets, decodeWords fs.rets (words obs.output) = some rets ∧ + b.satAll fs.ensures (mkEnv ctx args rets pre post) ∧ + b.satAll b.spec.invariants (mkEnv ctx args rets post post)) ∧ + (fs.succeedsIf ≠ [] → b.satAll fs.succeedsIf (mkEnv ctx args [] pre pre) → obs.success = true) + +/-- The ghost state after a call, from the call and the ghost state before it. -/ +abbrev GhostStep := Call → Ghost → Ghost + +/-- `fs`'s spec holds of `p` in `S` on `scope`: every call of the scope to `fs` from a pre-state +meeting `Pre` finishes, with an observable meeting `Post`. -/ +def HoldsFn (S : Sem) (p : S.Prog) (scope : Call → Prop) (b : Bundle) (ctxOf : Call → Ctx) + (step : GhostStep) (fs : FnSpec) : Prop := + ∀ call, scope call → ∀ (args : List Int) (pre : State), Pre b fs (ctxOf call) pre call args → + ∃ obs, S.run p call = some obs ∧ Post b fs (ctxOf call) pre (step call pre.ghost) obs args + +/-- Every function's spec holds of `p`. -/ +def Holds (S : Sem) (p : S.Prog) (scope : Call → Prop) (b : Bundle) (ctxOf : Call → Ctx) + (step : GhostStep) : Prop := + ∀ fs ∈ b.spec.specs, HoldsFn S p scope b ctxOf step fs + +/-- A refinement carries a spec from source to target: a stage from `S` to `T` preserves every +observable `p` finishes with, and `Post` speaks only of the observable. -/ +theorem HoldsFn.of_stage {S T : Sem} {p : S.Prog} {q : T.Prog} {scope : Call → Prop} + {b : Bundle} {ctxOf : Call → Ctx} {step : GhostStep} {fs : FnSpec} + (h : HoldsFn S p scope b ctxOf step fs) (st : Stage S T p q scope) : + HoldsFn T q scope b ctxOf step fs := by + intro call hs args pre hpre + obtain ⟨obs, hrun, hpost⟩ := h call hs args pre hpre + exact ⟨obs, st call hs obs hrun, hpost⟩ + +theorem Holds.of_stage {S T : Sem} {p : S.Prog} {q : T.Prog} {scope : Call → Prop} + {b : Bundle} {ctxOf : Call → Ctx} {step : GhostStep} + (h : Holds S p scope b ctxOf step) (st : Stage S T p q scope) : + Holds T q scope b ctxOf step := + fun fs hfs => (h fs hfs).of_stage st + +/-- A spec holds on any narrower scope. -/ +theorem HoldsFn.mono {S : Sem} {p : S.Prog} {scope narrower : Call → Prop} {b : Bundle} + {ctxOf : Call → Ctx} {step : GhostStep} {fs : FnSpec} (h : HoldsFn S p scope b ctxOf step fs) + (hn : ∀ call, narrower call → scope call) : HoldsFn S p narrower b ctxOf step fs := + fun call hc => h call (hn call hc) + +/-! ## Checked obligations -/ + +/-- Every spec function call of the bundle resolves and nests within its fuel, and every spec +function's body does too. Computable: the kernel checks it of an exported bundle by `decide`. -/ +def Bundle.WF (b : Bundle) : Bool := + (b.spec.specs.all fun fs => + Term.ClosedList b.spec.fns b.fuel fs.requires && + Term.ClosedList b.spec.fns b.fuel fs.ensures && + Term.ClosedList b.spec.fns b.fuel fs.succeedsIf) && + Term.ClosedList b.spec.fns b.fuel b.spec.invariants + +/-- Every opaque spec function's body takes values in its return type's range, at every depth +up to the fuel and in every environment: the range solar-verify assumes of an opaque +application, so that its proofs, which hold for every function in that range, hold for this one. -/ +def OpaqueInRange (b : Bundle) : Prop := + ∀ f ∈ b.spec.fns, f.isOpaque = true → ∀ k ≤ b.fuel, ∀ e, f.ret.InRange (eval b.spec.fns k f.body e) + +theorem opaqueInRange_of_none {b : Bundle} (h : b.spec.fns.all (fun f => !f.isOpaque) = true) : + OpaqueInRange b := by + intro f hf ho + have := List.all_eq_true.mp h f hf + simp [ho] at this + +/-! ## Ghost-free specs -/ + +mutual +/-- One level of `Term.GhostFree`: `t` reads no ghost variable, and `k` holds of the bodies of the +spec functions it calls. -/ +def Term.ghostFreeWith (fns : List SpecFn) (k : Term → Bool) : Term → Bool + | .ghost _ _ => false + | .load p off _ _ => Place.ghostFreeWith fns k p && Term.ghostFreeWith fns k off + | .len p => Place.ghostFreeWith fns k p + | .old t | .un _ t | .shl t _ | .shr t _ | .all _ _ t | .ex _ _ t => Term.ghostFreeWith fns k t + | .bin _ a b => Term.ghostFreeWith fns k a && Term.ghostFreeWith fns k b + | .ite c a b => Term.ghostFreeWith fns k c && Term.ghostFreeWith fns k a && Term.ghostFreeWith fns k b + | .call f args => + Term.ghostFreeListWith fns k args && + match fns.find? (·.name == f) with + | some sf => k sf.body + | none => true + | .lit _ | .arg _ | .ret _ | .var _ | .env _ => true + +def Term.ghostFreeListWith (fns : List SpecFn) (k : Term → Bool) : List Term → Bool + | [] => true + | t :: ts => Term.ghostFreeWith fns k t && Term.ghostFreeListWith fns k ts + +def Place.ghostFreeWith (fns : List SpecFn) (k : Term → Bool) : Place → Bool + | .slot _ => true + | .offset b i | .entry b i | .elem b i _ | .packedElem b i _ => + Place.ghostFreeWith fns k b && Term.ghostFreeWith fns k i +end + +/-- `t` reads no ghost variable, through spec function calls nested at most `fuel` deep. -/ +def Term.GhostFree (fns : List SpecFn) : Nat → Term → Bool + | 0 => Term.ghostFreeWith fns fun _ => true + | n + 1 => Term.ghostFreeWith fns (Term.GhostFree fns n) + +/-- Two environments that differ only in their ghost states. -/ +def Env.ghostEquiv (e e' : Env) : Prop := + e.args = e'.args ∧ e.rets = e'.rets ∧ e.ctx = e'.ctx ∧ e.vars = e'.vars ∧ e.inOld = e'.inOld ∧ + e.pre.storage = e'.pre.storage ∧ e.pre.time = e'.pre.time ∧ + e.post.storage = e'.post.storage ∧ e.post.time = e'.post.time + +end SolidCore.Spec diff --git a/Verify/Spec/Ghost.lean b/Verify/Spec/Ghost.lean new file mode 100644 index 00000000..7402319f --- /dev/null +++ b/Verify/Spec/Ghost.lean @@ -0,0 +1,635 @@ +/-! +# Ghost erasure + +solar-verify proves a contract together with its ghost code: `@custom:ghost x = e` updates, +`@custom:assert` and `@custom:assume`, and the lemmas `@custom:use` applies. The bytecode runs +without any of it: NatSpec is a comment to the compiler. A proof with ghost code is a proof of the +deployed program only if erasing the ghost code leaves every real execution as it was. +solar-verify checks the discipline of Filliâtre, Gondelman and Paskevich, "The Spirit of Ghost +Code" (CAV 2014), before it verifies anything (crates/verify/src/ghost.rs, README "Ghost code"): + +1. ghost code writes only ghost variables (it may read real ones); +2. ghost code never reverts, and no ghost condition decides a real write; +3. ghost code terminates; +4. real code never reads a ghost variable. + +This module proves that the discipline suffices, for a core statement language with that shape: +assignments, `require`, sequencing, conditionals and loops over real and ghost variables of one +store, ghost updates, `assert` and `assume`. `WF` is rules 1, 2 and 4 as a boolean check on the +syntax, as ghost.rs grades variables; rule 3 is `GhostTotal`, that every piece of ghost code +finishes from every state (solar-verify proves it through `@custom:decreases` variants and its +syntactic rules; `ghostTotal_of_straight` proves it here for ghost code without loops or assumes). + +* `sound`: every instrumented execution that does not fail an assertion is, on the real + variables, an execution of the erased program. +* `complete`: every execution of the erased program is, on the real variables, an instrumented + execution from any ghost state, or one that fails an assertion. +* `spec_of_erased`: a property proved of every instrumented execution, with no failing + assertion, holds of every execution of the erased program, with some ghost state. + +What this module leaves to solar-verify's encoding (crates/verify/src/vc.rs, a named hypothesis of +the final theorem, `SolidCore.Spec.TrustedBase`): that its model of a Solidity function is the +instrumented program of this language whose erasure is the function SolidCore runs. +-/ + +namespace SolidCore.Spec.Ghost + +/-- One store of real and ghost variables. -/ +abbrev Store := String → Int + +/-- Expressions over the store. -/ +inductive Exp where + | lit (v : Int) + | var (x : String) + | un (f : Int → Int) (a : Exp) + | bin (f : Int → Int → Int) (a b : Exp) + +/-- An expression's value. -/ +def Exp.eval (σ : Store) : Exp → Int + | .lit v => v + | .var x => σ x + | .un f a => f (a.eval σ) + | .bin f a b => f (a.eval σ) (b.eval σ) + +/-- The variables an expression reads. -/ +def Exp.vars : Exp → List String + | .lit _ => [] + | .var x => [x] + | .un _ a => a.vars + | .bin _ a b => a.vars ++ b.vars + +/-- Statements: real code (`assign`, `require`), ghost code (`ghost`, `assert`, `assume`), and the +control flow both share. -/ +inductive Stmt where + | skip + | assign (x : String) (e : Exp) + | require (e : Exp) + | seq (s t : Stmt) + | ite (c : Exp) (s t : Stmt) + | loop (c : Exp) (body : Stmt) + /-- `@custom:ghost x = e`. -/ + | ghost (x : String) (e : Exp) + /-- `@custom:assert e`: proved, so a failure is a failed proof. -/ + | assert (e : Exp) + /-- `@custom:assume e` (and a lemma's ensures, or a trusted contract): an execution where it + does not hold does not exist. -/ + | assume (e : Exp) + +/-- What a statement finishes with: normally, by reverting (which undoes everything, so no +store), or by failing an assertion. -/ +inductive Out where + | ok (σ : Store) + | rev + | fail + +/-- Update a variable. -/ +def Store.set (σ : Store) (x : String) (v : Int) : Store := fun y => if y = x then v else σ y + +/-- Big-step semantics. A loop that does not terminate, and an `assume` that does not hold, have +no execution. -/ +inductive Exec : Stmt → Store → Out → Prop where + | skip : Exec .skip σ (.ok σ) + | assign : Exec (.assign x e) σ (.ok (σ.set x (e.eval σ))) + | requireOk : e.eval σ ≠ 0 → Exec (.require e) σ (.ok σ) + | requireRev : e.eval σ = 0 → Exec (.require e) σ .rev + | seqOk : Exec s σ (.ok σ') → Exec t σ' o → Exec (.seq s t) σ o + | seqRev : Exec s σ .rev → Exec (.seq s t) σ .rev + | seqFail : Exec s σ .fail → Exec (.seq s t) σ .fail + | iteT : c.eval σ ≠ 0 → Exec s σ o → Exec (.ite c s t) σ o + | iteF : c.eval σ = 0 → Exec t σ o → Exec (.ite c s t) σ o + | loopDone : c.eval σ = 0 → Exec (.loop c b) σ (.ok σ) + | loopOk : c.eval σ ≠ 0 → Exec b σ (.ok σ') → Exec (.loop c b) σ' o → Exec (.loop c b) σ o + | loopRev : c.eval σ ≠ 0 → Exec b σ .rev → Exec (.loop c b) σ .rev + | loopFail : c.eval σ ≠ 0 → Exec b σ .fail → Exec (.loop c b) σ .fail + | ghost : Exec (.ghost x e) σ (.ok (σ.set x (e.eval σ))) + | assertOk : e.eval σ ≠ 0 → Exec (.assert e) σ (.ok σ) + | assertFail : e.eval σ = 0 → Exec (.assert e) σ .fail + | assume : e.eval σ ≠ 0 → Exec (.assume e) σ (.ok σ) + +section +variable (isGhost : String → Bool) + +/-- The expression reads no ghost variable. -/ +def Exp.real (e : Exp) : Bool := e.vars.all fun x => !isGhost x + +/-- Ghost code: statements made only of ghost updates of ghost variables, assertions and +assumptions, under any control flow. -/ +def Stmt.ghostCode : Stmt → Bool + | .skip | .assert _ | .assume _ => true + | .ghost x _ => isGhost x + | .assign _ _ | .require _ => false + | .seq s t | .ite _ s t => s.ghostCode && t.ghostCode + | .loop _ b => b.ghostCode + +/-- Erase the ghost code. -/ +def Stmt.erase : Stmt → Stmt + | s@(.seq a b) => if s.ghostCode isGhost then .skip else .seq (a.erase) (b.erase) + | s@(.ite c a b) => if s.ghostCode isGhost then .skip else .ite c (a.erase) (b.erase) + | s@(.loop c b) => if s.ghostCode isGhost then .skip else .loop c (b.erase) + | s => if s.ghostCode isGhost then .skip else s + +/-- The discipline, as a check on the syntax: real assignments write real variables from real +values (rules 1 and 4), `require` and every real condition read only real variables (rules 2 +and 4), and ghost updates write ghost variables (rule 1). Ghost code has no `require` and no real +assignment by `ghostCode` (rule 2). -/ +def Stmt.WF : Stmt → Bool + | .skip | .assert _ | .assume _ => true + | .ghost x _ => isGhost x + | .assign x e => !isGhost x && e.real isGhost + | .require e => e.real isGhost + | .seq s t => s.WF && t.WF + | s@(.ite c a b) => s.ghostCode isGhost || (c.real isGhost && a.WF && b.WF) + | s@(.loop c b) => s.ghostCode isGhost || (c.real isGhost && b.WF) + +/-- Two stores agree on the real variables. -/ +def Agree (σ τ : Store) : Prop := ∀ x, isGhost x = false → σ x = τ x + +/-- Two outcomes agree on the real variables. -/ +def OutAgree : Out → Out → Prop + | .ok σ, .ok τ => Agree isGhost σ τ + | .rev, .rev => True + | .fail, .fail => True + | _, _ => False + +/-- Rule 3: every piece of ghost code finishes from every state (perhaps failing an assertion). -/ +def GhostTotal : Stmt → Prop + | s@(.seq a b) | s@(.ite _ a b) => + (s.ghostCode isGhost = true → ∀ σ, ∃ o, Exec s σ o) ∧ GhostTotal a ∧ GhostTotal b + | s@(.loop _ b) => (s.ghostCode isGhost = true → ∀ σ, ∃ o, Exec s σ o) ∧ GhostTotal b + | s => s.ghostCode isGhost = true → ∀ σ, ∃ o, Exec s σ o +end + +/-! ## Lemmas -/ + +variable {isGhost : String → Bool} + +theorem Agree.refl (σ : Store) : Agree isGhost σ σ := fun _ _ => rfl + +theorem Agree.symm {σ τ : Store} (h : Agree isGhost σ τ) : Agree isGhost τ σ := + fun x hx => (h x hx).symm + +theorem Agree.trans {σ τ υ : Store} (h : Agree isGhost σ τ) (h' : Agree isGhost τ υ) : + Agree isGhost σ υ := fun x hx => (h x hx).trans (h' x hx) + +theorem Agree.set {σ τ : Store} (h : Agree isGhost σ τ) (x : String) (v : Int) : + Agree isGhost (σ.set x v) (τ.set x v) := by + intro y hy + simp only [Store.set] + split + · rfl + · exact h y hy + +theorem Agree.set_ghost {σ : Store} {x : String} (hx : isGhost x = true) (v : Int) : + Agree isGhost (σ.set x v) σ := by + intro y hy + simp only [Store.set] + split + · subst_vars; simp_all + · rfl + +theorem Exp.eval_agree {σ τ : Store} (h : Agree isGhost σ τ) : + ∀ e : Exp, e.real isGhost = true → e.eval σ = e.eval τ + | .lit _, _ => rfl + | .var x, he => by + simp [Exp.real, Exp.vars] at he + exact h x he + | .un f a, he => by + simp only [Exp.real, Exp.vars] at he + simp only [Exp.eval, Exp.eval_agree h a he] + | .bin f a b, he => by + simp only [Exp.real, Exp.vars, List.all_append, Bool.and_eq_true] at he + simp only [Exp.eval, Exp.eval_agree h a he.1, Exp.eval_agree h b he.2] + +/-- Ghost code changes no real variable and never reverts. -/ +theorem ghostCode_exec {s : Stmt} {σ : Store} {o : Out} (hx : Exec s σ o) + (hg : s.ghostCode isGhost = true) : + o = .fail ∨ ∃ σ', o = .ok σ' ∧ Agree isGhost σ' σ := by + induction hx with + | skip => exact .inr ⟨_, rfl, Agree.refl _⟩ + | assign => simp [Stmt.ghostCode] at hg + | requireOk => simp [Stmt.ghostCode] at hg + | requireRev => simp [Stmt.ghostCode] at hg + | seqOk _ _ ih1 ih2 => + simp only [Stmt.ghostCode, Bool.and_eq_true] at hg + rcases ih1 hg.1 with h | ⟨σ1, h1, a1⟩ + · cases h + · cases h1 + rcases ih2 hg.2 with h | ⟨σ2, h2, a2⟩ + · exact .inl h + · exact .inr ⟨σ2, h2, a2.trans a1⟩ + | seqRev _ ih => + simp only [Stmt.ghostCode, Bool.and_eq_true] at hg + rcases ih hg.1 with h | ⟨_, h, _⟩ <;> cases h + | seqFail => exact .inl rfl + | iteT _ _ ih => + simp only [Stmt.ghostCode, Bool.and_eq_true] at hg + exact ih hg.1 + | iteF _ _ ih => + simp only [Stmt.ghostCode, Bool.and_eq_true] at hg + exact ih hg.2 + | loopDone => exact .inr ⟨_, rfl, Agree.refl _⟩ + | loopOk _ _ _ ih1 ih2 => + rcases ih1 hg with h | ⟨σ1, h1, a1⟩ + · cases h + · cases h1 + rcases ih2 hg with h | ⟨σ2, h2, a2⟩ + · exact .inl h + · exact .inr ⟨σ2, h2, a2.trans a1⟩ + | loopRev _ _ ih => + rcases ih hg with h | ⟨_, h, _⟩ <;> cases h + | loopFail => exact .inl rfl + | ghost => exact .inr ⟨_, rfl, Agree.set_ghost (by simpa [Stmt.ghostCode] using hg) _⟩ + | assertOk => exact .inr ⟨_, rfl, Agree.refl _⟩ + | assertFail => exact .inl rfl + | assume => exact .inr ⟨_, rfl, Agree.refl _⟩ + +theorem erase_of_ghostCode {s : Stmt} (hg : s.ghostCode isGhost = true) : + s.erase isGhost = .skip := by + cases s <;> simp_all [Stmt.erase] + +theorem erase_of_not_ghostCode {s : Stmt} (hg : s.ghostCode isGhost = false) : + s.erase isGhost = match s with + | .seq a b => .seq (a.erase isGhost) (b.erase isGhost) + | .ite c a b => .ite c (a.erase isGhost) (b.erase isGhost) + | .loop c b => .loop c (b.erase isGhost) + | s => s := by + cases s <;> simp_all [Stmt.erase] + +/-! ## Soundness: instrumented executions are executions of the erased program -/ + +/-- **Soundness of erasure.** An instrumented execution of a well-formed program that does not +fail an assertion is, from any store agreeing on the real variables, an execution of the erased +program agreeing on the real variables. -/ +theorem sound {s : Stmt} {σ : Store} {o : Out} (hx : Exec s σ o) (hwf : s.WF isGhost = true) + (hnf : o ≠ .fail) : ∀ τ, Agree isGhost σ τ → + ∃ o', Exec (s.erase isGhost) τ o' ∧ OutAgree isGhost o o' := by + induction hx with + | skip => intro τ h; exact ⟨.ok τ, by simp [Stmt.erase, Stmt.ghostCode]; exact .skip, h⟩ + | @assign x e σ => + intro τ h + simp only [Stmt.WF, Bool.and_eq_true, Bool.not_eq_true'] at hwf + have he : (Stmt.assign x e).erase isGhost = .assign x e := by simp [Stmt.erase, Stmt.ghostCode] + rw [he] + refine ⟨_, .assign, ?_⟩ + show Agree isGhost _ _ + rw [Exp.eval_agree h e hwf.2] + exact h.set x _ + | @requireOk e σ hc => + intro τ h + simp only [Stmt.WF] at hwf + have he : (Stmt.require e).erase isGhost = .require e := by simp [Stmt.erase, Stmt.ghostCode] + rw [he] + exact ⟨.ok τ, .requireOk (by rwa [← Exp.eval_agree h e hwf]), h⟩ + | @requireRev e σ hc => + intro τ h + simp only [Stmt.WF] at hwf + have he : (Stmt.require e).erase isGhost = .require e := by simp [Stmt.erase, Stmt.ghostCode] + rw [he] + exact ⟨_, .requireRev (by rwa [← Exp.eval_agree h e hwf]), trivial⟩ + | @seqOk a σ σ1 b o h1 h2 ih1 ih2 => + intro τ h + simp only [Stmt.WF, Bool.and_eq_true] at hwf + cases hg : (Stmt.seq a b).ghostCode isGhost + · rw [erase_of_not_ghostCode hg] + obtain ⟨o1, e1, a1⟩ := ih1 hwf.1 (by simp) τ h + cases o1 with + | ok τ1 => + obtain ⟨o2, e2, a2⟩ := ih2 hwf.2 hnf τ1 a1 + exact ⟨o2, .seqOk e1 e2, a2⟩ + | rev => exact absurd a1 (by simp [OutAgree]) + | fail => exact absurd a1 (by simp [OutAgree]) + · rw [erase_of_ghostCode hg] + rcases ghostCode_exec (.seqOk h1 h2) hg with hf | ⟨σ', ho, ha⟩ + · exact absurd hf hnf + · subst ho; exact ⟨.ok τ, .skip, ha.trans h⟩ + | @seqRev a σ b h1 ih => + intro τ h + simp only [Stmt.WF, Bool.and_eq_true] at hwf + cases hg : (Stmt.seq a b).ghostCode isGhost + · rw [erase_of_not_ghostCode hg] + obtain ⟨o1, e1, a1⟩ := ih hwf.1 (by simp) τ h + cases o1 with + | rev => exact ⟨_, .seqRev e1, trivial⟩ + | ok _ => exact absurd a1 (by simp [OutAgree]) + | fail => exact absurd a1 (by simp [OutAgree]) + · rcases ghostCode_exec (.seqRev (t := b) h1) hg with hf | ⟨σ', ho, _⟩ + · cases hf + · cases ho + | seqFail => exact absurd rfl hnf + | @iteT a σ o c b hc h1 ih => + intro τ h + cases hg : (Stmt.ite c a b).ghostCode isGhost + · rw [erase_of_not_ghostCode hg] + simp only [Stmt.WF, hg, Bool.false_or, Bool.and_eq_true] at hwf + obtain ⟨o1, e1, a1⟩ := ih hwf.1.2 hnf τ h + exact ⟨o1, .iteT (by rwa [← Exp.eval_agree h c hwf.1.1]) e1, a1⟩ + · rw [erase_of_ghostCode hg] + rcases ghostCode_exec (.iteT (t := b) hc h1) hg with hf | ⟨σ', ho, ha⟩ + · exact absurd hf hnf + · subst ho; exact ⟨.ok τ, .skip, ha.trans h⟩ + | @iteF b σ o c a hc h1 ih => + intro τ h + cases hg : (Stmt.ite c a b).ghostCode isGhost + · rw [erase_of_not_ghostCode hg] + simp only [Stmt.WF, hg, Bool.false_or, Bool.and_eq_true] at hwf + obtain ⟨o1, e1, a1⟩ := ih hwf.2 hnf τ h + exact ⟨o1, .iteF (by rwa [← Exp.eval_agree h c hwf.1.1]) e1, a1⟩ + · rw [erase_of_ghostCode hg] + rcases ghostCode_exec (.iteF (s := a) hc h1) hg with hf | ⟨σ', ho, ha⟩ + · exact absurd hf hnf + · subst ho; exact ⟨.ok τ, .skip, ha.trans h⟩ + | @loopDone c b σ hc => + intro τ h + cases hg : (Stmt.loop c b).ghostCode isGhost + · rw [erase_of_not_ghostCode hg] + simp only [Stmt.WF, hg, Bool.false_or, Bool.and_eq_true] at hwf + exact ⟨.ok τ, .loopDone (by rwa [← Exp.eval_agree h c hwf.1]), h⟩ + · rw [erase_of_ghostCode hg]; exact ⟨.ok τ, .skip, h⟩ + | @loopOk b σ σ1 c o hc h1 h2 ih1 ih2 => + intro τ h + cases hg : (Stmt.loop c b).ghostCode isGhost + · have hwf' := hwf + rw [erase_of_not_ghostCode hg] at ih2 ⊢ + simp only [Stmt.WF, hg, Bool.false_or, Bool.and_eq_true] at hwf + obtain ⟨o1, e1, a1⟩ := ih1 hwf.2 (by simp) τ h + cases o1 with + | ok τ1 => + obtain ⟨o2, e2, a2⟩ := ih2 hwf' hnf τ1 a1 + exact ⟨o2, .loopOk (by rwa [← Exp.eval_agree h c hwf.1]) e1 e2, a2⟩ + | rev => exact absurd a1 (by simp [OutAgree]) + | fail => exact absurd a1 (by simp [OutAgree]) + · rw [erase_of_ghostCode hg] + rcases ghostCode_exec (.loopOk hc h1 h2) hg with hf | ⟨σ', ho, ha⟩ + · exact absurd hf hnf + · subst ho; exact ⟨.ok τ, .skip, ha.trans h⟩ + | @loopRev b σ c hc h1 ih => + intro τ h + cases hg : (Stmt.loop c b).ghostCode isGhost + · rw [erase_of_not_ghostCode hg] + simp only [Stmt.WF, hg, Bool.false_or, Bool.and_eq_true] at hwf + obtain ⟨o1, e1, a1⟩ := ih hwf.2 (by simp) τ h + cases o1 with + | rev => exact ⟨_, .loopRev (by rwa [← Exp.eval_agree h c hwf.1]) e1, trivial⟩ + | ok _ => exact absurd a1 (by simp [OutAgree]) + | fail => exact absurd a1 (by simp [OutAgree]) + · rcases ghostCode_exec (.loopRev hc h1) hg with hf | ⟨σ', ho, _⟩ + · cases hf + · cases ho + | loopFail => exact absurd rfl hnf + | @ghost x e σ => + intro τ h + simp only [Stmt.WF] at hwf + have hg : (Stmt.ghost x e).ghostCode isGhost = true := by simpa [Stmt.ghostCode] using hwf + rw [erase_of_ghostCode hg] + exact ⟨.ok τ, .skip, (Agree.set_ghost hwf _).trans h⟩ + | assertOk => + intro τ h; exact ⟨.ok τ, by simp [Stmt.erase, Stmt.ghostCode]; exact .skip, h⟩ + | assertFail => exact absurd rfl hnf + | assume => + intro τ h; exact ⟨.ok τ, by simp [Stmt.erase, Stmt.ghostCode]; exact .skip, h⟩ + +/-! ## Completeness: every execution of the erased program is matched -/ + +theorem ghostTotal_here {s : Stmt} (ht : GhostTotal isGhost s) (hg : s.ghostCode isGhost = true) : + ∀ σ, ∃ o, Exec s σ o := by + cases s <;> simp only [GhostTotal] at ht + all_goals first | exact ht hg | exact ht.1 hg + +/-- **Completeness of erasure.** Every execution of the erased program of a well-formed program +whose ghost code terminates is matched, from any store agreeing on the real variables (any ghost +state), by an instrumented execution that agrees with it on the real variables or fails an +assertion. -/ +theorem complete : ∀ {s : Stmt}, s.WF isGhost = true → GhostTotal isGhost s → + ∀ {τ : Store} {o : Out}, Exec (s.erase isGhost) τ o → ∀ σ, Agree isGhost σ τ → + ∃ o', Exec s σ o' ∧ (o' = .fail ∨ OutAgree isGhost o' o) := by + intro s + induction s with + | skip => + intro _ _ τ o hx σ h + simp only [Stmt.erase, Stmt.ghostCode, ite_true] at hx + cases hx + exact ⟨_, .skip, .inr h⟩ + | assign x e => + intro hwf _ τ o hx σ h + simp only [Stmt.WF, Bool.and_eq_true, Bool.not_eq_true'] at hwf + simp only [Stmt.erase, Stmt.ghostCode] at hx + cases hx + refine ⟨_, .assign, .inr ?_⟩ + show Agree isGhost _ _ + rw [Exp.eval_agree h e hwf.2] + exact h.set x _ + | require e => + intro hwf _ τ o hx σ h + simp only [Stmt.WF] at hwf + simp only [Stmt.erase, Stmt.ghostCode] at hx + cases hx with + | requireOk hc => exact ⟨_, .requireOk (by rwa [Exp.eval_agree h e hwf]), .inr h⟩ + | requireRev hc => exact ⟨_, .requireRev (by rwa [Exp.eval_agree h e hwf]), .inr trivial⟩ + | seq a b iha ihb => + intro hwf ht τ o hx σ h + cases hg : (Stmt.seq a b).ghostCode isGhost + · rw [erase_of_not_ghostCode hg] at hx + simp only [Stmt.WF, Bool.and_eq_true] at hwf + simp only [GhostTotal] at ht + cases hx with + | seqOk h1 h2 => + obtain ⟨o1, e1, a1⟩ := iha hwf.1 ht.2.1 h1 σ h + rcases a1 with rfl | a1 + · exact ⟨_, .seqFail e1, .inl rfl⟩ + · cases o1 with + | ok σ1 => + obtain ⟨o2, e2, a2⟩ := ihb hwf.2 ht.2.2 h2 σ1 a1 + exact ⟨o2, .seqOk e1 e2, a2⟩ + | _ => simp [OutAgree] at a1 + | seqRev h1 => + obtain ⟨o1, e1, a1⟩ := iha hwf.1 ht.2.1 h1 σ h + rcases a1 with rfl | a1 + · exact ⟨_, .seqFail e1, .inl rfl⟩ + · cases o1 with + | rev => exact ⟨_, .seqRev e1, .inr trivial⟩ + | _ => simp [OutAgree] at a1 + | seqFail h1 => + obtain ⟨o1, e1, a1⟩ := iha hwf.1 ht.2.1 h1 σ h + rcases a1 with rfl | a1 + · exact ⟨_, .seqFail e1, .inl rfl⟩ + · cases o1 with + | fail => exact ⟨_, .seqFail e1, .inl rfl⟩ + | _ => simp [OutAgree] at a1 + · rw [erase_of_ghostCode hg] at hx + cases hx + obtain ⟨o', e'⟩ := ghostTotal_here ht hg σ + rcases ghostCode_exec e' hg with rfl | ⟨σ', rfl, a'⟩ + · exact ⟨_, e', .inl rfl⟩ + · exact ⟨_, e', .inr (a'.trans h)⟩ + | ite c a b iha ihb => + intro hwf ht τ o hx σ h + cases hg : (Stmt.ite c a b).ghostCode isGhost + · rw [erase_of_not_ghostCode hg] at hx + simp only [Stmt.WF, hg, Bool.false_or, Bool.and_eq_true] at hwf + simp only [GhostTotal] at ht + cases hx with + | iteT hc h1 => + obtain ⟨o1, e1, a1⟩ := iha hwf.1.2 ht.2.1 h1 σ h + exact ⟨o1, .iteT (by rwa [Exp.eval_agree h c hwf.1.1]) e1, a1⟩ + | iteF hc h1 => + obtain ⟨o1, e1, a1⟩ := ihb hwf.2 ht.2.2 h1 σ h + exact ⟨o1, .iteF (by rwa [Exp.eval_agree h c hwf.1.1]) e1, a1⟩ + · rw [erase_of_ghostCode hg] at hx + cases hx + obtain ⟨o', e'⟩ := ghostTotal_here ht hg σ + rcases ghostCode_exec e' hg with rfl | ⟨σ', rfl, a'⟩ + · exact ⟨_, e', .inl rfl⟩ + · exact ⟨_, e', .inr (a'.trans h)⟩ + | loop c b ihb => + intro hwf ht τ o hx σ h + cases hg : (Stmt.loop c b).ghostCode isGhost + · have he : (Stmt.loop c b).erase isGhost = .loop c (b.erase isGhost) := by + simp [Stmt.erase, hg] + rw [he] at hx + simp only [Stmt.WF, hg, Bool.false_or, Bool.and_eq_true] at hwf + simp only [GhostTotal] at ht + generalize hl : Stmt.loop c (b.erase isGhost) = l at hx + induction hx generalizing σ with + | loopDone hc => + cases hl + exact ⟨_, .loopDone (by rwa [Exp.eval_agree h c hwf.1]), .inr h⟩ + | loopOk hc h1 _ _ ih2 => + cases hl + obtain ⟨o1, e1, a1⟩ := ihb hwf.2 ht.2 h1 σ h + rcases a1 with rfl | a1 + · exact ⟨_, .loopFail (by rwa [Exp.eval_agree h c hwf.1]) e1, .inl rfl⟩ + · cases o1 with + | ok σ1 => + obtain ⟨o2, e2, a2⟩ := ih2 σ1 a1 rfl + exact ⟨o2, .loopOk (by rwa [Exp.eval_agree h c hwf.1]) e1 e2, a2⟩ + | _ => simp [OutAgree] at a1 + | loopRev hc h1 => + cases hl + obtain ⟨o1, e1, a1⟩ := ihb hwf.2 ht.2 h1 σ h + rcases a1 with rfl | a1 + · exact ⟨_, .loopFail (by rwa [Exp.eval_agree h c hwf.1]) e1, .inl rfl⟩ + · cases o1 with + | rev => exact ⟨_, .loopRev (by rwa [Exp.eval_agree h c hwf.1]) e1, .inr trivial⟩ + | _ => simp [OutAgree] at a1 + | loopFail hc h1 => + cases hl + obtain ⟨o1, e1, a1⟩ := ihb hwf.2 ht.2 h1 σ h + rcases a1 with rfl | a1 + · exact ⟨_, .loopFail (by rwa [Exp.eval_agree h c hwf.1]) e1, .inl rfl⟩ + · cases o1 with + | fail => exact ⟨_, .loopFail (by rwa [Exp.eval_agree h c hwf.1]) e1, .inl rfl⟩ + | _ => simp [OutAgree] at a1 + | _ => cases hl + · rw [erase_of_ghostCode hg] at hx + cases hx + obtain ⟨o', e'⟩ := ghostTotal_here ht hg σ + rcases ghostCode_exec e' hg with rfl | ⟨σ', rfl, a'⟩ + · exact ⟨_, e', .inl rfl⟩ + · exact ⟨_, e', .inr (a'.trans h)⟩ + | ghost x e => + intro hwf ht τ o hx σ h + have hg : (Stmt.ghost x e).ghostCode isGhost = true := by simpa [Stmt.WF, Stmt.ghostCode] using hwf + rw [erase_of_ghostCode hg] at hx + cases hx + exact ⟨_, .ghost, .inr ((Agree.set_ghost (by simpa [Stmt.WF] using hwf) _).trans h)⟩ + | assert e => + intro _ _ τ o hx σ h + simp only [Stmt.erase, Stmt.ghostCode, ite_true] at hx + cases hx + by_cases hc : e.eval σ = 0 + · exact ⟨_, .assertFail hc, .inl rfl⟩ + · exact ⟨_, .assertOk hc, .inr h⟩ + | assume e => + intro _ ht τ o hx σ h + simp only [Stmt.erase, Stmt.ghostCode, ite_true] at hx + cases hx + obtain ⟨o', e'⟩ := ht (by simp [Stmt.ghostCode]) σ + cases e' + exact ⟨_, .assume ‹_›, .inr h⟩ + +/-! ## A spec proved with ghost code holds of the erased program -/ + +/-- **A spec proved with ghost code holds of the erased program.** If every instrumented +execution of a well-formed program whose ghost code terminates passes its assertions and ends in +an outcome meeting `Q`, then every execution of the erased program, from any store, ends in an +outcome that agrees on the real variables with one meeting `Q`: one started from that store with +any ghost state. When `Q` reads only real variables it holds of the erased outcome itself +(`spec_of_erased_real`). -/ +theorem spec_of_erased {s : Stmt} {Q : Store → Out → Prop} (hwf : s.WF isGhost = true) + (ht : GhostTotal isGhost s) + (hproof : ∀ σ o, Exec s σ o → o ≠ .fail ∧ Q σ o) : + ∀ τ o, Exec (s.erase isGhost) τ o → ∀ σ, Agree isGhost σ τ → + ∃ o', Exec s σ o' ∧ Q σ o' ∧ OutAgree isGhost o' o := by + intro τ o hx σ h + obtain ⟨o', e', a'⟩ := complete hwf ht hx σ h + obtain ⟨hnf, hq⟩ := hproof σ o' e' + rcases a' with rfl | a' + · exact absurd rfl hnf + · exact ⟨o', e', hq, a'⟩ + +/-- `Q` reads only the real variables of the outcome. -/ +def RealOnly (isGhost : String → Bool) (Q : Out → Prop) : Prop := + ∀ o o', OutAgree isGhost o o' → Q o → Q o' + +/-- A real postcondition proved with ghost code holds of every execution of the erased program. -/ +theorem spec_of_erased_real {s : Stmt} {Q : Out → Prop} (hwf : s.WF isGhost = true) + (ht : GhostTotal isGhost s) (hq : RealOnly isGhost Q) + (hproof : ∀ σ o, Exec s σ o → o ≠ .fail ∧ Q o) : + ∀ τ o, Exec (s.erase isGhost) τ o → Q o := by + intro τ o hx + obtain ⟨o', _, hq', a'⟩ := spec_of_erased (Q := fun _ o => Q o) hwf ht hproof τ o hx τ + (Agree.refl τ) + exact hq o' o a' hq' + +/-! ## Ghost code without loops or assumptions terminates -/ + +/-- Ghost code made of ghost updates and assertions, under sequencing and conditionals. -/ +def Stmt.straight : Stmt → Bool + | .skip | .assert _ | .ghost _ _ | .assign _ _ | .require _ => true + | .seq a b | .ite _ a b => a.straight && b.straight + | .loop _ _ | .assume _ => false + +theorem total_of_straight : ∀ {s : Stmt}, s.straight = true → ∀ σ, ∃ o, Exec s σ o + | .skip, _, σ => ⟨_, .skip⟩ + | .assign _ _, _, σ => ⟨_, .assign⟩ + | .ghost _ _, _, σ => ⟨_, .ghost⟩ + | .require e, _, σ => by + by_cases hc : e.eval σ = 0 + · exact ⟨_, .requireRev hc⟩ + · exact ⟨_, .requireOk hc⟩ + | .assert e, _, σ => by + by_cases hc : e.eval σ = 0 + · exact ⟨_, .assertFail hc⟩ + · exact ⟨_, .assertOk hc⟩ + | .seq a b, hs, σ => by + simp only [Stmt.straight, Bool.and_eq_true] at hs + obtain ⟨o1, e1⟩ := total_of_straight hs.1 σ + cases o1 with + | ok σ1 => + obtain ⟨o2, e2⟩ := total_of_straight hs.2 σ1 + exact ⟨_, .seqOk e1 e2⟩ + | rev => exact ⟨_, .seqRev e1⟩ + | fail => exact ⟨_, .seqFail e1⟩ + | .ite c a b, hs, σ => by + simp only [Stmt.straight, Bool.and_eq_true] at hs + by_cases hc : c.eval σ = 0 + · obtain ⟨o, e⟩ := total_of_straight hs.2 σ + exact ⟨_, .iteF hc e⟩ + · obtain ⟨o, e⟩ := total_of_straight hs.1 σ + exact ⟨_, .iteT hc e⟩ + +/-- **Rule 3 for straight-line ghost code**: a program whose statements have no loop and no +assumption meets `GhostTotal`. -/ +theorem ghostTotal_of_straight : ∀ {s : Stmt}, s.straight = true → GhostTotal isGhost s + | .skip, _ | .assert _, _ | .ghost _ _, _ | .assign _ _, _ | .require _, _ => + fun _ => total_of_straight (by simp [Stmt.straight]) + | .seq a b, hs => by + simp only [Stmt.straight, Bool.and_eq_true] at hs + exact ⟨fun _ => total_of_straight (by simp [Stmt.straight, hs]), + ghostTotal_of_straight hs.1, ghostTotal_of_straight hs.2⟩ + | .ite c a b, hs => by + simp only [Stmt.straight, Bool.and_eq_true] at hs + exact ⟨fun _ => total_of_straight (by simp [Stmt.straight, hs]), + ghostTotal_of_straight hs.1, ghostTotal_of_straight hs.2⟩ + +end SolidCore.Spec.Ghost diff --git a/Verify/Spec/GhostFree.lean b/Verify/Spec/GhostFree.lean new file mode 100644 index 00000000..62bdae71 --- /dev/null +++ b/Verify/Spec/GhostFree.lean @@ -0,0 +1,168 @@ +import Verify.Spec.Contract + +/-! +# Ghost-free specs ignore ghosts + +A term that reads no ghost variable, through the spec functions it calls (`Term.GhostFree`), has the +same value in two environments that differ only in their ghost states (`Env.ghostEquiv`). So a +ghost-free spec clause cannot tell a run with ghost code apart from its erasure, which only changes +ghost state (`Ghost.sound`). +-/ + +namespace SolidCore.Spec + +namespace Env.ghostEquiv + +theorem refl (e : Env) : e.ghostEquiv e := by + simp [Env.ghostEquiv] + +theorem symm {e e' : Env} (h : e.ghostEquiv e') : e'.ghostEquiv e := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := h + exact ⟨h1.symm, h2.symm, h3.symm, h4.symm, h5.symm, h6.symm, h7.symm, h8.symm, h9.symm⟩ + +theorem storage {e e' : Env} (h : e.ghostEquiv e') : e.cur.storage = e'.cur.storage := by + obtain ⟨-, -, -, -, h5, h6, -, h8, -⟩ := h + simp only [Env.cur, h5]; split <;> assumption + +theorem time {e e' : Env} (h : e.ghostEquiv e') : e.cur.time = e'.cur.time := by + obtain ⟨-, -, -, -, h5, -, h7, -, h9⟩ := h + simp only [Env.cur, h5]; split <;> assumption + +theorem bind {e e' : Env} (h : e.ghostEquiv e') (x : String) (v : Int) : + (e.bind x v).ghostEquiv (e'.bind x v) := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := h + exact ⟨h1, h2, h3, by simp [Env.bind, h4], h5, h6, h7, h8, h9⟩ + +theorem old {e e' : Env} (h : e.ghostEquiv e') : + ({ e with inOld := true } : Env).ghostEquiv { e' with inOld := true } := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := h + exact ⟨h1, h2, h3, h4, rfl, h6, h7, h8, h9⟩ + +theorem withVars {e e' : Env} (h : e.ghostEquiv e') (vs : List (String × Int)) : + ({ e with vars := vs } : Env).ghostEquiv { e' with vars := vs } := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9⟩ := h + exact ⟨h1, h2, h3, rfl, h5, h6, h7, h8, h9⟩ + +end Env.ghostEquiv + +/-- What `k` promises of the spec function bodies at one fuel level: they ignore ghosts when +evaluated with one less fuel. -/ +def BodiesIgnoreGhosts (fns : List SpecFn) (fuel : Nat) (k : Term → Bool) : Prop := + ∀ body, k body = true → ∀ fuel', fuel = fuel' + 1 → + ∀ e e', e.ghostEquiv e' → eval fns fuel' body e = eval fns fuel' body e' + +mutual +theorem eval_ghostEquiv_with {fns : List SpecFn} {fuel : Nat} {k : Term → Bool} + (hk : BodiesIgnoreGhosts fns fuel k) : + ∀ (t : Term), Term.ghostFreeWith fns k t = true → + ∀ e e', e.ghostEquiv e' → eval fns fuel t e = eval fns fuel t e' + | .lit _, _, e, e', h => by simp only [eval] + | .arg _, _, e, e', h => by simp only [eval, h.1] + | .ret _, _, e, e', h => by simp only [eval, h.2.1] + | .var _, _, e, e', h => by simp only [eval, h.2.2.2.1] + | .env v, _, e, e', h => by + cases v <;> simp only [eval, h.2.2.1, h.time] + | .load p off size ty, hg, e, e', h => by + simp only [Term.ghostFreeWith, Bool.and_eq_true] at hg + simp only [eval, h.storage, slotOf_ghostEquiv_with hk p hg.1 e e' h, + eval_ghostEquiv_with hk off hg.2 e e' h] + | .len p, hg, e, e', h => by + simp only [Term.ghostFreeWith] at hg + simp only [eval, h.storage, slotOf_ghostEquiv_with hk p hg e e' h] + | .ghost _ _, hg, _, _, _ => by simp [Term.ghostFreeWith] at hg + | .old t, hg, e, e', h => by + simp only [Term.ghostFreeWith] at hg + simp only [eval]; exact eval_ghostEquiv_with hk t hg _ _ h.old + | .un op t, hg, e, e', h => by + simp only [Term.ghostFreeWith] at hg + cases op <;> simp only [eval, eval_ghostEquiv_with hk t hg e e' h] + | .bin op a b, hg, e, e', h => by + simp only [Term.ghostFreeWith, Bool.and_eq_true] at hg + simp only [eval, eval_ghostEquiv_with hk a hg.1 e e' h, eval_ghostEquiv_with hk b hg.2 e e' h] + | .shl t _, hg, e, e', h => by + simp only [Term.ghostFreeWith] at hg + simp only [eval, eval_ghostEquiv_with hk t hg e e' h] + | .shr t _, hg, e, e', h => by + simp only [Term.ghostFreeWith] at hg + simp only [eval, eval_ghostEquiv_with hk t hg e e' h] + | .ite c a b, hg, e, e', h => by + simp only [Term.ghostFreeWith, Bool.and_eq_true] at hg + simp only [eval, eval_ghostEquiv_with hk c hg.1.1 e e' h, eval_ghostEquiv_with hk a hg.1.2 e e' h, + eval_ghostEquiv_with hk b hg.2 e e' h] + | .all x _ body, hg, e, e', h => by + simp only [Term.ghostFreeWith] at hg + have hb : ∀ v, eval fns fuel body (e.bind x v) = eval fns fuel body (e'.bind x v) := + fun v => eval_ghostEquiv_with hk body hg _ _ (h.bind x v) + simp only [eval, hb] + | .ex x _ body, hg, e, e', h => by + simp only [Term.ghostFreeWith] at hg + have hb : ∀ v, eval fns fuel body (e.bind x v) = eval fns fuel body (e'.bind x v) := + fun v => eval_ghostEquiv_with hk body hg _ _ (h.bind x v) + simp only [eval, hb] + | .call f args, hg, e, e', h => by + simp only [Term.ghostFreeWith, Bool.and_eq_true] at hg + have ha := evalList_ghostEquiv_with hk args hg.1 e e' h + obtain ⟨-, hb⟩ := hg + cases fuel with + | zero => rw [eval.eq_def, eval.eq_def] + | succ fuel' => + cases hf : fns.find? (·.name == f) with + | none => rw [eval.eq_def, eval.eq_def]; simp only [hf] + | some sf => + rw [hf] at hb + rw [eval.eq_def, eval.eq_def]; simp only [hf, ha] + exact hk sf.body hb fuel' rfl _ _ (h.withVars _) +termination_by t => sizeOf t + +theorem evalList_ghostEquiv_with {fns : List SpecFn} {fuel : Nat} {k : Term → Bool} + (hk : BodiesIgnoreGhosts fns fuel k) : + ∀ (ts : List Term), Term.ghostFreeListWith fns k ts = true → + ∀ e e', e.ghostEquiv e' → evalList fns fuel ts e = evalList fns fuel ts e' + | [], _, e, e', _ => by simp only [evalList] + | t :: ts, hg, e, e', h => by + simp only [Term.ghostFreeListWith, Bool.and_eq_true] at hg + simp only [evalList, eval_ghostEquiv_with hk t hg.1 e e' h, + evalList_ghostEquiv_with hk ts hg.2 e e' h] +termination_by ts => sizeOf ts + +theorem slotOf_ghostEquiv_with {fns : List SpecFn} {fuel : Nat} {k : Term → Bool} + (hk : BodiesIgnoreGhosts fns fuel k) : + ∀ (p : Place), Place.ghostFreeWith fns k p = true → + ∀ e e', e.ghostEquiv e' → slotOf fns fuel p e = slotOf fns fuel p e' + | .slot _, _, e, e', _ => by simp only [slotOf] + | .offset b i, hg, e, e', h => by + simp only [Place.ghostFreeWith, Bool.and_eq_true] at hg + simp only [slotOf, slotOf_ghostEquiv_with hk b hg.1 e e' h, eval_ghostEquiv_with hk i hg.2 e e' h] + | .entry b i, hg, e, e', h => by + simp only [Place.ghostFreeWith, Bool.and_eq_true] at hg + simp only [slotOf, slotOf_ghostEquiv_with hk b hg.1 e e' h, eval_ghostEquiv_with hk i hg.2 e e' h] + | .elem b i _, hg, e, e', h => by + simp only [Place.ghostFreeWith, Bool.and_eq_true] at hg + simp only [slotOf, slotOf_ghostEquiv_with hk b hg.1 e e' h, eval_ghostEquiv_with hk i hg.2 e e' h] + | .packedElem b i _, hg, e, e', h => by + simp only [Place.ghostFreeWith, Bool.and_eq_true] at hg + simp only [slotOf, slotOf_ghostEquiv_with hk b hg.1 e e' h, eval_ghostEquiv_with hk i hg.2 e e' h] +termination_by p => sizeOf p +end + +/-- A ghost-free term has the same value in two environments that differ only in their ghost +states: a spec that reads no ghost cannot tell ghost code apart from its erasure. -/ +theorem eval_ghostEquiv {fns : List SpecFn} : + ∀ (fuel : Nat) {t : Term}, Term.GhostFree fns fuel t = true → + ∀ {e e' : Env}, e.ghostEquiv e' → eval fns fuel t e = eval fns fuel t e' + | 0, t, hg, e, e', h => by + refine eval_ghostEquiv_with ?_ t hg e e' h + intro _ _ fuel' h0; cases h0 + | n + 1, t, hg, e, e', h => by + refine eval_ghostEquiv_with ?_ t hg e e' h + intro body hb fuel' hf _ _ h' + cases hf + exact eval_ghostEquiv n hb h' + +/-- A ghost-free clause holds in one environment exactly when it holds in another that differs only +in its ghost state. -/ +theorem Bundle.sat_ghostEquiv (b : Bundle) {t : Term} (hg : Term.GhostFree b.spec.fns b.fuel t = true) + {e e' : Env} (h : e.ghostEquiv e') : b.sat t e ↔ b.sat t e' := by + simp only [Bundle.sat, eval_ghostEquiv b.fuel hg h] + +end SolidCore.Spec diff --git a/Verify/Spec/Hash.lean b/Verify/Spec/Hash.lean new file mode 100644 index 00000000..0cf26b0f --- /dev/null +++ b/Verify/Spec/Hash.lean @@ -0,0 +1,135 @@ +import Verify.Spec.Semantics +import SolidCore.Refinement.Generic.Source +import Verify.Spec.TrustedBase.Hypotheses + +/-! +# SolidCore's storage hash is the spec's + +SolidCore hashes a mapping slot as `solHash k s` (its interpreter's `keccakWord` of the 64 bytes +of `k` and `s`, through `wordToBytesBE` and `bytesToWordBE`); the spec semantics reads the +same slot as `SolidCore.Spec.keccakWord (wordBytes k ++ wordBytes s)`. Both use EvmYul's +Keccak-256 sponge, whose output is 32 bytes each below 256, so the two are equal +(`solHash_eq`): a spec over mappings reads the slots SolidCore writes, with no hypothesis. +-/ + +namespace SolidCore.Spec + +open EvmYul.SpongeHash.Keccak256 in +theorem squeezeBytes_lt (st : List Nat) : ∀ b ∈ squeezeBytes st, b < 256 := by + intro b hb + unfold squeezeBytes at hb + have := List.mem_of_mem_take hb + simp only [List.mem_flatMap, laneBytesLE, List.mem_map, laneByte] at this + obtain ⟨_, _, _, _, rfl⟩ := this + exact Nat.mod_lt _ (by decide) + +open EvmYul.SpongeHash.Keccak256 in +theorem squeezeBytes_length (st : List Nat) : (squeezeBytes st).length = 32 := by + simp [squeezeBytes, laneBytesLE, List.length_flatMap] + +theorem foldl_bytes_lt : ∀ (l : List Nat) (acc : Nat), (∀ b ∈ l, b < 256) → + l.foldl (fun a b => a * 256 + b) acc < (acc + 1) * 256 ^ l.length + | [], acc, _ => by simp + | b :: l, acc, h => by + have hb := h b (List.mem_cons_self ..) + have ih := foldl_bytes_lt l (acc * 256 + b) fun x hx => h x (List.mem_cons_of_mem _ hx) + simp only [List.foldl_cons, List.length_cons, Nat.pow_succ] + calc _ < (acc * 256 + b + 1) * 256 ^ l.length := ih + _ ≤ (acc + 1) * 256 * 256 ^ l.length := Nat.mul_le_mul_right _ (by omega) + _ = (acc + 1) * (256 ^ l.length * 256) := by rw [Nat.mul_assoc, Nat.mul_comm 256] + +theorem foldl_norm : ∀ (l : List Nat) (acc : Nat), (∀ b ∈ l, b < 256) → + l.foldl (fun a b => a * 256 + SolidCore.Solidity.Source.normByte b) acc = + l.foldl (fun a b => a * 256 + b) acc + | [], _, _ => rfl + | b :: l, acc, h => by + have hb := h b (List.mem_cons_self ..) + simp only [List.foldl_cons] + rw [show SolidCore.Solidity.Source.normByte b = b from Nat.mod_eq_of_lt hb] + exact foldl_norm l _ fun x hx => h x (List.mem_cons_of_mem _ hx) + +theorem keccakWord_eq (l : List Nat) : + SolidCore.Solidity.Source.keccakWord l = keccakWord l := by + unfold SolidCore.Solidity.Source.keccakWord keccakWord SolidCore.Solidity.Source.bytesToWordBE bytesWord + have hk : SolidCore.Solidity.Source.Keccak.keccak256Bytes l = + EvmYul.SpongeHash.Keccak256.keccak256Bytes l := rfl + rw [hk] + unfold EvmYul.SpongeHash.Keccak256.keccak256Bytes + generalize EvmYul.SpongeHash.Keccak256.absorbBlocks _ _ = st + have hlt := squeezeBytes_lt st + rw [foldl_norm _ 0 hlt] + have := foldl_bytes_lt _ 0 hlt + rw [squeezeBytes_length] at this + unfold SolidCore.Solidity.Shared.norm SolidCore.Solidity.Shared.wordModulus + have h2 : EvmYul.UInt256.size = 2 ^ 256 := rfl + rw [h2] + simpa using this + +theorem wordToBytesBE_eq : ∀ (n v : Nat), SolidCore.Solidity.Source.wordToBytesBE n v = + ((List.range n).reverse.map fun i => v / 256 ^ i % 256) + | 0, _ => rfl + | n + 1, v => by + rw [SolidCore.Solidity.Source.wordToBytesBE, wordToBytesBE_eq n, List.range_succ_eq_map, + List.reverse_cons, List.map_append, ← List.map_reverse, List.map_map] + refine congrArg₂ _ ?_ ?_ + · refine List.map_congr_left fun i _ => ?_ + simp only [Function.comp, Nat.pow_succ, Nat.div_div_eq_div_mul, Nat.mul_comm (256 ^ i)] + · simp [SolidCore.Solidity.Source.normByte, SolidCore.Solidity.Shared.Account.byte] + +/-- **SolidCore's mapping slot is the spec's.** -/ +theorem solHash_eq (k s : Nat) : + SolidCore.Refinement.Generic.solHash k s = keccakWord (wordBytes k ++ wordBytes s) := by + unfold SolidCore.Refinement.Generic.solHash SolidCore.Solidity.Source.storageWordBytes + rw [keccakWord_eq, wordToBytesBE_eq, wordToBytesBE_eq] + rfl + +/-! ## Mapping slots keyed by addresses + +`SlotsSeparated m` names the one keccak256 assumption a spec over an address-keyed mapping at +slot `m` needs: keccak256 is separated (injective, every image at least `2 ^ 128`, so never a +small constant slot) on the preimages of `m[a]` for every address `a` +(`TrustedBase.KeccakSeparated`). It is not provable (keccak256 is not injective on all +inputs) and not refutable from the definitions; a theorem that uses it states it as a premise. +From it, SolidCore's slots of two addresses are equal only for equal addresses (`slot_inj`), and +none is a small slot (`slot_ge`). -/ + +theorem bytesWord_append (l : List Nat) (x : Nat) : bytesWord (l ++ [x]) = bytesWord l * 256 + x := by + simp [bytesWord, List.foldl_append] + +theorem bytesWord_wordToBytesBE : ∀ n v, + bytesWord (SolidCore.Solidity.Source.wordToBytesBE n v) = v % 256 ^ n + | 0, v => by simp [bytesWord, SolidCore.Solidity.Source.wordToBytesBE, Nat.mod_one] + | n + 1, v => by + rw [SolidCore.Solidity.Source.wordToBytesBE, bytesWord_append, bytesWord_wordToBytesBE n, + Nat.pow_succ, Nat.mul_comm (256 ^ n) 256, Nat.mod_mul] + simp only [SolidCore.Solidity.Source.normByte, SolidCore.Solidity.Shared.Account.byte] + omega + +theorem bytesWord_wordBytes (v : Nat) : bytesWord (wordBytes v) = v % 2 ^ 256 := by + have : wordBytes v = SolidCore.Solidity.Source.wordToBytesBE 32 v := by + rw [wordToBytesBE_eq]; rfl + rw [this, bytesWord_wordToBytesBE, show (256 : Nat) ^ 32 = 2 ^ 256 from rfl] + +theorem length_wordBytes (v : Nat) : (wordBytes v).length = 32 := by simp [wordBytes] + +/-- keccak256 is separated on the slots of `m[a]`, for every address `a`. -/ +def SlotsSeparated (m : Nat) : Prop := + TrustedBase.KeccakSeparated (fun x => ∃ a < 2 ^ 160, x = TrustedBase.mappingPreimage a m) + +theorem slot_inj {m : Nat} (h : SlotsSeparated m) {a b : Nat} (ha : a < 2 ^ 160) (hb : b < 2 ^ 160) + (he : SolidCore.Refinement.Generic.solHash a m = SolidCore.Refinement.Generic.solHash b m) : + a = b := by + rw [solHash_eq, solHash_eq] at he + have := h.1 _ _ ⟨a, ha, rfl⟩ ⟨b, hb, rfl⟩ he + unfold TrustedBase.mappingPreimage at this + have hw := List.append_inj_left' this (by simp [length_wordBytes]) + have := congrArg bytesWord hw + rw [bytesWord_wordBytes, bytesWord_wordBytes] at this + omega + +theorem slot_ge {m : Nat} (h : SlotsSeparated m) {a : Nat} (ha : a < 2 ^ 160) : + 2 ^ 128 ≤ SolidCore.Refinement.Generic.solHash a m := by + rw [solHash_eq] + exact h.2 _ ⟨a, ha, rfl⟩ + +end SolidCore.Spec diff --git a/Verify/Spec/HashScope.lean b/Verify/Spec/HashScope.lean new file mode 100644 index 00000000..e2f4e5c9 --- /dev/null +++ b/Verify/Spec/HashScope.lean @@ -0,0 +1,355 @@ +import Verify.Spec.TreeSplit +import Mathlib.Data.Fintype.Prod + +/-! +# keccak256 separation scoped to the preimages a call hashes + +A Solidity mapping stores `m[k]` at `keccak256(k . m)`, so a proof about a function that reads and +writes mappings needs to know which of its slots are equal. Keccak-256 is not injective, so this +is assumed, and the assumption must be satisfiable and stated. + +**The global premise is refuted.** `NestedSlotsSeparated ms ns` (TreeMapNested.lean) asks keccak256 +to be injective on the nested slots `n[b][a]` of all pairs of addresses: `2 ^ 320` preimages into +words below `2 ^ 256`. `not_nestedSlotsSeparated` derives `False` from it by counting for any +`ns ≠ []`, so every theorem with it as a premise is vacuous. + +**The scoped premise.** As hevm does (pairwise injectivity of the keccak256 applications that occur +in a query, never a universal axiom), `HashScope L F` speaks of the finite list `L` of preimages a +call hashes: their images are pairwise distinct (`inj`), above the small slots (`reserved`), and +none is the image of another preimage of the frame family `F` (`apart`), the slots a frame clause +such as `forall a :: a != msg.sender && a != to ==> balanceOf[a] == old(balanceOf[a])` quantifies +over. Nothing is asked of two preimages of `F`. A call's premise is `MapScope sender idx ms args`: +`L` the slots `m[k]` for `m ∈ ms` and the keys `k` the call touches (the caller `sender` and the +address arguments at the positions `idx`), `F` every slot `m[a]`. + +For `transfer(to, value)` of a balance mapping at slot `m` this is keccak256 on +`{caller . m, to . m}`: distinct when `caller ≠ to`, at least `2 ^ 128`, and the image of no other +address's balance slot. For a given call the real keccak256 fails this only with probability about +`2 ^ -94` (its two images hitting one of `2 ^ 160` other slots or a small slot); it is a named +computational assumption of the call, in the statement, not provable and not refutable. + +**Using it.** `TreeMeetsFixedOn (fun ρ => MapScope sender idx ms ρ.args)` is a function's spec of +its erased tree on the calls whose premise holds; `tree_meets_scoped` proves it (the scoped +`map_inj` and `map_ge`, `scope_inj` and `scope_ge`, instantiated with each key condition shown by +`simp`), and `holdsFnUnder_of_tree_fixed` lifts it to SolidCore's contract as `HoldsFnUnder`: the +spec on every stage call of the function whose argument words satisfy the premise. +-/ + +namespace SolidCore.Spec + +open SolidCore.Refinement SolidCore.Refinement.Generic TrustedBase + +/-! ## The global nested premise is false -/ + +/-- **`NestedSlotsSeparated ms ns` is false whenever `ns` has a mapping slot**: it makes +`(a, c) ↦ solHash a (solHash c n)` injective on the `2 ^ 320` pairs of addresses, into words below +`2 ^ 256`. -/ +theorem not_nestedSlotsSeparated {ms ns : List Nat} {n : Nat} (hn : n ∈ ns) (hnw : n < 2 ^ 256) : + ¬ NestedSlotsSeparated ms ns := by + intro h + let g : Fin (2 ^ 160) × Fin (2 ^ 160) → Fin (2 ^ 256) := + fun p => ⟨solHash p.1 (solHash p.2 n), solHash_lt _ _⟩ + have hg : Function.Injective g := by + rintro ⟨a, c⟩ ⟨b, d⟩ he + have he' : solHash a (solHash c n) = solHash b (solHash d n) := congrArg Fin.val he + obtain ⟨e1, e2, -⟩ := nmap_inj_nn h n n hn hn hnw hnw a b c d a.isLt b.isLt c.isLt d.isLt he' + exact Prod.ext (Fin.ext e1) (Fin.ext e2) + have := Fintype.card_le_of_injective g hg + simp only [Fintype.card_prod, Fintype.card_fin] at this + exact absurd this (by decide) + +/-- UniswapV2ERC20's earlier premise, `NestedSlotsSeparated [1, 4] [2]`, is false. -/ +theorem not_nestedSlotsSeparated_erc20 : ¬ NestedSlotsSeparated [1, 4] [2] := + not_nestedSlotsSeparated (n := 2) (by decide) (by decide) + +/-! ## The scoped premise -/ + +/-- **keccak256 separated on the preimages `L` a call hashes, apart from the frame family `F`**: +`L`'s images pairwise distinct and at least `2 ^ 128`, and the image of no other preimage of `F`. -/ +structure HashScope (L : List (List Nat)) (F : Preimages) : Prop where + reserved : ∀ x ∈ L, 2 ^ 128 ≤ keccakWord x + inj : ∀ x ∈ L, ∀ y ∈ L, keccakWord x = keccakWord y → x = y + apart : ∀ x ∈ L, ∀ y, F y → keccakWord x = keccakWord y → x = y + +/-- Nothing hashed, nothing assumed. -/ +theorem hashScope_nil (F : Preimages) : HashScope [] F := + ⟨fun _ h => by simp at h, fun _ h => by simp at h, fun _ h => by simp at h⟩ + +/-- Every slot `m[a]` of the mappings at `ms`: the frame family of a single-level map. -/ +def mapFamily (ms : List Nat) : Preimages := + fun x => ∃ a < 2 ^ 160, ∃ m ∈ ms, x = mappingPreimage a m + +/-- The slots `m[k]` for the keys `K` and the mapping slots `ms`. -/ +def mapScope (K ms : List Nat) : List (List Nat) := + K.flatMap fun k => ms.map fun m => mappingPreimage k m + +/-- The keys a call touches: the caller and the address arguments at the positions `idx`. -/ +def callKeys (sender : Nat) (idx args : List Nat) : List Nat := + sender :: idx.map fun i => args.getD i 0 % 2 ^ 160 + +/-- **A call's scoped premise** for single-level mappings at `ms`. -/ +def MapScope (sender : Nat) (idx ms args : List Nat) : Prop := + HashScope (mapScope (callKeys sender idx args) ms) (mapFamily ms) + +theorem mem_mapScope {K ms : List Nat} {k m : Nat} (hk : k ∈ K) (hm : m ∈ ms) : + mappingPreimage k m ∈ mapScope K ms := + List.mem_flatMap.2 ⟨k, hk, List.mem_map.2 ⟨m, hm, rfl⟩⟩ + +/-- Slots of a key in scope and of any address are equal only for the same key and mapping. -/ +theorem scope_inj {K ms : List Nat} (h : HashScope (mapScope K ms) (mapFamily ms)) (m n : Nat) + (hm : m ∈ ms) (hn : n ∈ ms) (hmw : m < 2 ^ 256) (hnw : n < 2 ^ 256) (a b : Nat) + (hK : a ∈ K ∨ b ∈ K) : + a < 2 ^ 160 → b < 2 ^ 160 → solHash a m = solHash b n → a = b ∧ m = n := by + intro ha hb he + rw [solHash_eq, solHash_eq] at he + have hp : mappingPreimage a m = mappingPreimage b n := by + rcases hK with hK | hK + · exact h.apart _ (mem_mapScope hK hm) _ ⟨b, hb, n, hn, rfl⟩ he + · exact (h.apart _ (mem_mapScope hK hn) _ ⟨a, ha, m, hm, rfl⟩ he.symm).symm + exact mappingPreimage_inj (by omega) (by omega) hmw hnw hp + +/-- A slot of a key in scope is at least `2 ^ 128`. -/ +theorem scope_ge {K ms : List Nat} (h : HashScope (mapScope K ms) (mapFamily ms)) (m : Nat) + (hm : m ∈ ms) (a : Nat) (hK : a ∈ K) : 2 ^ 128 ≤ solHash a m := by + rw [solHash_eq] + exact h.reserved _ (mem_mapScope hK hm) + +/-- **A specification that needs a collision is refuted under the premise**: a slot of a key in +scope is no other address's slot. -/ +theorem scope_no_collision {K ms : List Nat} (h : HashScope (mapScope K ms) (mapFamily ms)) + {m : Nat} (hm : m ∈ ms) (hmw : m < 2 ^ 256) {a b : Nat} (hK : a ∈ K) (ha : a < 2 ^ 160) + (hb : b < 2 ^ 160) (hne : a ≠ b) : solHash a m ≠ solHash b m := + fun he => hne (scope_inj h m m hm hm hmw hmw a b (.inl hK) ha hb he).1 + +/-! ## The footprint premise + +`ScopedSep L` is keccak256 separated (injective, images at least `2 ^ 128`) on the finite list `L` of +preimages a call hashes and nothing else: no frame family, no other key. It is +`TrustedBase.KeccakSeparated (· ∈ L)`, the shape slice2-nested's `HashScope.Scoped` uses. For a +concrete call the kernel can check it (`scopedSep_transfer_example`); for every finite list some +hash function satisfies it (`exists_separatedBy`), so it is never `False` in disguise. -/ + +/-- **The scoped premise**: keccak256 injective, with images at least `2 ^ 128`, on the finite +footprint `L`. -/ +def ScopedSep (L : List (List Nat)) : Prop := TrustedBase.KeccakSeparated (· ∈ L) + +/-- The footprint of `transfer(to, value)` of a balance mapping at slot `m`: the slots of the caller +and of `to`. -/ +def transferFootprint (m caller recipient : Nat) : List (List Nat) := + [mappingPreimage caller m, mappingPreimage recipient m] + +/-- The premise for any hash function `h` (a model), of which `ScopedSep` is the case `keccakWord`. -/ +def SeparatedBy (h : List Nat → Nat) (L : List (List Nat)) : Prop := + (∀ x ∈ L, ∀ y ∈ L, h x = h y → x = y) ∧ ∀ x ∈ L, 2 ^ 128 ≤ h x + +theorem scopedSep_iff (L : List (List Nat)) : ScopedSep L ↔ SeparatedBy keccakWord L := + ⟨fun h => ⟨fun x hx y hy => h.1 x y hx hy, h.2⟩, fun h => ⟨fun x y hx hy => h.1 x hx y hy, h.2⟩⟩ + +/-- **Satisfiable for every footprint**: the hash `x ↦ 2 ^ 128 + (position of x in L)` meets it. -/ +theorem exists_separatedBy (L : List (List Nat)) : ∃ h, SeparatedBy h L := by + refine ⟨fun x => 2 ^ 128 + L.idxOf x, fun x hx y hy he => ?_, fun _ _ => Nat.le_add_right _ _⟩ + have he' : L.idxOf x = L.idxOf y := by simpa using he + rw [← List.getElem_idxOf (List.idxOf_lt_length_of_mem hx), + ← List.getElem_idxOf (List.idxOf_lt_length_of_mem hy)] + simp only [he'] + +/-- **The real keccak256 meets a nontrivial transfer footprint**: caller `0x2000` sending to +address 1, `balanceOf` at slot 1 (UniswapV2ERC20's layout), by the kernel's evaluation of the sponge +(`TrustedBase.image4`, `image5`). -/ +theorem scopedSep_transfer_example : ScopedSep (transferFootprint 1 0x2000 1) := by + have e4 := TrustedBase.image4 + have e5 := TrustedBase.image5 + refine ⟨fun x y hx hy he => ?_, fun x hx => ?_⟩ + · simp only [transferFootprint, List.mem_cons, List.not_mem_nil, or_false] at hx hy + rcases hx with rfl | rfl <;> rcases hy with rfl | rfl <;> first | rfl | (rw [e4, e5] at he; exact absurd he (by decide)) | (rw [e5, e4] at he; exact absurd he (by decide)) + · simp only [transferFootprint, List.mem_cons, List.not_mem_nil, or_false] at hx + rcases hx with rfl | rfl + · rw [e5]; decide + · rw [e4]; decide + +/-- Two slots of the footprint are equal only for the same key and mapping. -/ +theorem scoped_inj {L : List (List Nat)} (h : ScopedSep L) {a b m n : Nat} + (ha : a < 2 ^ 256) (hb : b < 2 ^ 256) (hmw : m < 2 ^ 256) (hnw : n < 2 ^ 256) + (hx : mappingPreimage a m ∈ L) (hy : mappingPreimage b n ∈ L) + (he : solHash a m = solHash b n) : a = b ∧ m = n := by + rw [solHash_eq, solHash_eq] at he + exact mappingPreimage_inj ha hb hmw hnw (h.1 _ _ hx hy he) + +/-- A slot of the footprint is at least `2 ^ 128`: no small constant slot. -/ +theorem scoped_ge {L : List (List Nat)} (h : ScopedSep L) {a m : Nat} + (hx : mappingPreimage a m ∈ L) : 2 ^ 128 ≤ solHash a m := by + rw [solHash_eq]; exact h.2 _ hx + +/-- **transfer's key-level fact**: under its footprint premise, the caller's and the recipient's +balance slots are distinct when they are distinct addresses, and neither is a small slot. -/ +theorem transfer_slots {m c t : Nat} (h : ScopedSep (transferFootprint m c t)) (hm : m < 2 ^ 256) + (hc : c < 2 ^ 256) (ht : t < 2 ^ 256) : + (c ≠ t → solHash c m ≠ solHash t m) ∧ 2 ^ 128 ≤ solHash c m ∧ 2 ^ 128 ≤ solHash t m := + ⟨fun hne he => hne (scoped_inj h hc ht hm hm (by simp [transferFootprint]) (by simp [transferFootprint]) he).1, + scoped_ge h (by simp [transferFootprint]), scoped_ge h (by simp [transferFootprint])⟩ + +/-- info: 'SolidCore.Spec.scopedSep_transfer_example' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms scopedSep_transfer_example + +/-! ## Instances in a tactic -/ + +open Lean Meta Elab Tactic in +/-- `hash_facts_scoped H s hinj hge hlt hs`: `hash_facts` for the scoped lemmas. For every slot term +`H x y` of the goal and the hypotheses, `hlt x y` and, when `x` is in scope (shown by `simp`), +`hge y _ x _`; for every pair, `hinj y y' _ _ _ _ x x' _` when one of the keys is in scope. An +instance whose side conditions do not hold is left out. -/ +elab "hash_facts_scoped " H:ident s:ident hinj:ident hge:ident hlt:ident hs:ident : tactic => do + let (ts, ss) ← withMainContext do + let He ← getFVarFromUserName H.getId + let se ← getFVarFromUserName s.getId + let mut es := #[← instantiateMVars (← getMainTarget)] + for d in (← getLCtx) do + if d.isImplementationDetail then continue + es := es.push (← instantiateMVars d.type) + let tr ← IO.mkRef (#[] : Array Expr) + let sr ← IO.mkRef (#[] : Array Expr) + for e in es do + e.forEachWhere (fun t => t.getAppFn == He && t.getAppNumArgs == 2 && !t.hasLooseBVars) + fun t => tr.modify fun a => if a.contains t then a else a.push t + e.forEachWhere (fun t => t.isApp && t.appFn! == se && !t.hasLooseBVars) + fun t => sr.modify fun a => if a.contains t.appArg! then a else a.push t.appArg! + pure (← tr.get, ← sr.get) + for t in ts do + withMainContext do + let x ← Term.exprToSyntax t.appFn!.appArg! + let y ← Term.exprToSyntax t.appArg! + evalTactic (← `(tactic| have := $hlt $x $y)) + evalTactic (← `(tactic| try (have := $hge $y (by decide) $x ?_; rotate_left; simp; done))) + for x in ss do + withMainContext do + let x ← Term.exprToSyntax x + evalTactic (← `(tactic| try have := $hs $x)) + for i in [0:ts.size] do + for j in [i+1:ts.size] do + withMainContext do + let x1 ← Term.exprToSyntax ts[i]!.appFn!.appArg! + let y1 ← Term.exprToSyntax ts[i]!.appArg! + let x2 ← Term.exprToSyntax ts[j]!.appFn!.appArg! + let y2 ← Term.exprToSyntax ts[j]!.appArg! + evalTactic (← `(tactic| try (have := $hinj $y1 $y2 (by decide) (by decide) (by decide) (by decide) $x1 $x2 ?_; rotate_left; simp; done))) + +/-- `tree_meets_scoped [defs]` proves `TreeMeetsFixedOn (fun ρ => MapScope sender idx ms ρ.args) b fs +ctx n T` for a function of at most eight parameters that reads and writes single-level mappings at +the slots `ms`: `tree_meets_map` with the call's scoped premise in place of a global one. It +decodes the argument words, reads the keys the call touches from the premise, takes the scoped +`scope_inj` and `scope_ge`, generalizes `solHash` to a variable `H` (no step evaluates keccak256) +and closes each case by `omega` with `hash_facts_scoped`'s instances. A case it cannot close stays an +error: it never leaves a `sorry`. -/ +macro "tree_meets_scoped" "[" ds:Lean.Parser.Tactic.simpLemma,* "]" : tactic => `(tactic| ( + intro args s iargs pre hl hargs hs hdec hst ht hreq hinv hP + simp only [Nat.reducePow] at hs + rcases args with _ | ⟨a0, _ | ⟨a1, _ | ⟨a2, _ | ⟨a3, _ | ⟨a4, _ | ⟨a5, _ | ⟨a6, _ | ⟨a7, _ | ⟨_, _⟩⟩⟩⟩⟩⟩⟩⟩⟩ <;> + simp only [List.length_cons, List.length_nil] at hl <;> (try omega) <;> + simp only [List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, + IsEmpty.forall_iff, implies_true, and_true, Nat.reducePow] at hargs <;> + simp only [$ds,*, List.head, List.getElem_cons_zero, List.getElem_cons_succ, decodeWords, Ty.ofWord, + bind, pure, Option.bind, Nat.reducePow] at hdec <;> + split_ifs at hdec <;> simp only [Option.some.injEq, reduceCtorEq] at hdec <;> + subst hdec <;> + simp only [MapScope, callKeys, List.map_cons, List.map_nil, List.getD_cons_zero, + List.getD_cons_succ, Nat.reducePow] at hP <;> + simp (disch := omega) only [Nat.mod_eq_of_lt] at hP <;> + have hinj := scope_inj hP <;> have hge := scope_ge hP <;> have hlt := solHash_lt' <;> + have hkec := keccak_solHash <;> + generalize solHash = H at hinj hge hlt hkec ⊢ <;> + refine ⟨fun hsucc => ?_, fun hne => ?_⟩ + all_goals try (simp [$ds,*] at hne; done) + all_goals simp only [$ds,*, Tree.eval, WExpr.eval, BinOp.eval, UnOp.eval, Generic.wordSize, Res.obs, + Writes.store, List.getD_cons_zero, List.getD_cons_succ, Nat.reducePow] at hsucc ⊢ + all_goals simp (disch := simp only [hargs, hs, hlt, Nat.reduceLT]) only [Nat.mod_eq_of_lt, ite_mod_nat, + Nat.reduceMod, Nat.zero_mod, ite10_eq_zero_iff, Decidable.not_not] at hsucc ⊢ + all_goals split_ifs at hsucc ⊢ + all_goals simp only [Bool.false_eq_true, Bool.true_eq_false, imp_false, not_true_eq_false, + IsEmpty.forall_iff] at hsucc + all_goals simp only [$ds,*, OByte.eval, WExpr.eval, Generic.wordSize, words, bytesWord, decodeWords, Ty.ofWord, + List.map_cons, List.map_nil, List.length_cons, List.length_nil, List.range_succ, List.range_zero, + List.nil_append, List.cons_append, List.drop_zero, List.take_succ_cons, List.take_zero, List.foldl_cons, + List.foldl_nil, Nat.reduceDiv, Nat.reducePow, Nat.reduceMod, Nat.reduceSub, Nat.reduceMul, Nat.reduceAdd, + Nat.reduceLT, ite_true, ite_false, List.getElem_cons_succ, List.getElem_cons_zero, Option.some.injEq, + exists_eq_left', bind, pure, Option.bind, Ty.InRange, Nat.cast_ofNat, Nat.zero_add, + Nat.reduceLeDiff] at hsucc ⊢ + all_goals try clear hsucc + all_goals try refine ⟨?_, ?_⟩ + all_goals simp only [Bundle.satAll, Bundle.sat, $ds,*, List.getElem_cons_succ, List.getElem_cons_zero, + List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, eval, evalList, slotOf, mkEnv, + Env.cur, Env.bind, BinOp.apply, Ty.ofBits, toWord, List.getD_cons_zero, List.getD_cons_succ, + List.lookup, hkec, ofProp_ne_zero, ite_true, ite_false, Bool.false_eq_true, Nat.zero_mod, hst, + beq_self_eq_true, Ty.InRange, Option.getD_some, forall_int_range, Nat.cast_ofNat] at hinv ⊢ + all_goals simp only [wordMod, Nat.reducePow] at hinv ⊢ + all_goals simp (disch := first | exact hlt _ _ | exact hs _ | omega) only [Nat.mod_eq_of_lt, + toNat_natCast_emod] at hinv ⊢ + all_goals simp (disch := first | exact hlt _ _ | exact hs _ | omega) only [Nat.cast_ofNat, + Int.reduceMod, Int.reduceToNat, Nat.mod_eq_of_lt, toNat_natCast_emod, toNat_ofNat_emod, + toNat_zero_emod, toNat_one_emod, wordMod, Nat.reducePow, Nat.reduceMul, Nat.reduceMod, Nat.div_one, + Nat.reduceDiv, Int.reducePow] at hinv ⊢ + all_goals (repeat' (first | (apply And.intro) | intro)) + all_goals (hash_facts_scoped H s hinj hge hlt hs; split_ifs <;> omega))) + +/-! ## From the tree to SolidCore's contract, under a per-call premise -/ + +open SolarTV SolidCore.Refinement.Abi SolidCore.Solidity + +/-- The argument words of a call: its call data after the selector. -/ +def callArgs (call : Call) : List Nat := words ((call.calldata.data.toList.map (·.toNat)).drop 4) + +/-- `HoldsFn` on the calls that meet `Q`: the premise is part of the statement, call by call. -/ +def HoldsFnUnder (Q : Call → Prop) (S : Sem) (p : S.Prog) (scope : Call → Prop) (b : Bundle) + (ctxOf : Call → Ctx) (step : GhostStep) (fs : FnSpec) : Prop := + ∀ call, scope call → Q call → ∀ (args : List Int) (pre : State), Pre b fs (ctxOf call) pre call args → + ∃ obs, S.run p call = some obs ∧ Post b fs (ctxOf call) pre (step call pre.ghost) obs args + +/-- With the trivial premise it is `HoldsFn`. -/ +theorem HoldsFnUnder.holdsFn {S : Sem} {p : S.Prog} {scope : Call → Prop} {b : Bundle} + {ctxOf : Call → Ctx} {step : GhostStep} {fs : FnSpec} + (h : HoldsFnUnder (fun _ => True) S p scope b ctxOf step fs) : HoldsFn S p scope b ctxOf step fs := + fun call hs => h call hs trivial + +/-- A refinement carries it from source to target, as `HoldsFn.of_stage`. -/ +theorem HoldsFnUnder.of_stage {S T : Sem} {p : S.Prog} {q : T.Prog} {scope : Call → Prop} + {b : Bundle} {ctxOf : Call → Ctx} {step : GhostStep} {fs : FnSpec} {Q : Call → Prop} + (h : HoldsFnUnder Q S p scope b ctxOf step fs) (st : SolarTV.Stage S T p q scope) : + HoldsFnUnder Q T q scope b ctxOf step fs := by + intro call hs hq args pre hpre + obtain ⟨obs, hrun, hpost⟩ := h call hs hq args pre hpre + exact ⟨obs, st call hs obs hrun, hpost⟩ + +/-- **`holdsFn_of_tree_fixed` under a per-call premise**: the spec of the erased tree on the argument +words meeting `P` is the spec of SolidCore's contract on the stage's calls whose argument words +meet `P`. -/ +theorem holdsFnUnder_of_tree_fixed {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {fn : Fn} {f : Source.FunctionDef} + (hsel : fn.sel < 2 ^ 32) (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) fuel f = some T) {b : Bundle} {fs : FnSpec} + {ctxOf : Call → Ctx} {step : GhostStep} {ctx : Ctx} {P : List Nat → Prop} + (hctx : ∀ call : Call, call.callvalue = 0 → ctxOf call = ctx) + (hstep : ∀ call, SolidCore.Verify.VC.stageScope fn s call → ∀ g, step call g = g) + (hm : TreeMeetsFixedOn (fun ρ => P ρ.args) b fs ctx fn.params.length T) : + HoldsFnUnder (fun call => P (callArgs call)) (solidCore fuel) c + (SolidCore.Verify.VC.stageScope fn s) b ctxOf step fs := by + intro call hcall hq iargs pre hpre + have hg := hstep call hcall pre.ghost + obtain ⟨σ, hcov, fn', hfn', args, hl, hargs, rfl⟩ := hcall + simp only [List.mem_singleton] at hfn' + subst hfn' + have hrun := source_run hd hcov hsel hfind hT args (hl.trans hlen.symm) hargs + obtain ⟨⟨-, -, hdec⟩, hst, ht, hreq, hinv⟩ := hpre + rw [hctx _ rfl] at ht hreq hinv ⊢ + rw [words_calldata _ hargs] at hdec + simp only [callArgs] at hq + rw [words_calldata _ hargs] at hq + rw [hg] + exact ⟨_, hrun, hm args (slotValue σ) iargs pre hl hargs (fun k => Generic.slotValue_lt σ k) + hdec hst ht hreq hinv hq⟩ + +/-- info: 'SolidCore.Spec.not_nestedSlotsSeparated_erc20' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms not_nestedSlotsSeparated_erc20 + +end SolidCore.Spec diff --git a/Verify/Spec/HashScopeCheck.lean b/Verify/Spec/HashScopeCheck.lean new file mode 100644 index 00000000..325ec6ca --- /dev/null +++ b/Verify/Spec/HashScopeCheck.lean @@ -0,0 +1,281 @@ +import Verify.Spec.HashScope + +/-! +# Footprint premises: the kernel check, nested footprints, and what is not claimed + +Verify/Spec/HashScope.lean states the per-call premise `ScopedSep L` (keccak256 injective, images at +least `2 ^ 128`, on the finite list `L` of preimages the call hashes). This file keeps three kinds of +statement apart: + +1. **Abstract model** (`SeparatedBy h L` for a hash function `h` that is not keccak256): every footprint, + including the nested ones whose inner key is the hash's own output, has a word-valued model + (`approve_model`, `transferFrom_model`). This says the premise is consistent; it says nothing about + keccak256. +2. **Real witness** (`ScopedSep L`, the real keccak256): decidable. `scopedSep_iff_check` makes it the + Boolean `sepCheckBy keccakWord L = true`, which the kernel evaluates for any concrete footprint + (`decide +kernel`): `scopedSep_of_check` turns one evaluation into the premise of one call. The + instances below are concrete calls, each a kernel evaluation of the sponge. +3. **Universal claims** (the premise for every pair of addresses): not proved and not assumed. + `universalTransferSep_iff` shows `∀ caller to, ScopedSep (transferFootprint m caller to)` is exactly + keccak256 separation on all `2 ^ 160` balance preimages, a global computational claim; statements + take the premise of their own call instead. + +Nested (allowance) footprints: `allowance[owner][spender]` at mapping slot `a` is stored at +`keccak256(spender . keccak256(owner . a))`, so the footprint lists the outer preimage `owner . a` and the +inner one `spender . keccak256(owner . a)`, the inner key computed by the same hash +(`approveFootprintBy h`, `transferFromFootprintBy h`). Pigeonhole refutes the global nested premise +(`not_nestedSlotsSeparated`), not these: each call names at most four preimages. +-/ + +namespace SolidCore.Spec + +open SolidCore.Refinement SolidCore.Refinement.Generic TrustedBase + +/-! ## The check -/ + +/-- The Boolean form of `SeparatedBy h L`: each image at least `2 ^ 128`, and equal images only for +equal preimages. -/ +def sepCheckBy (h : List Nat → Nat) (L : List (List Nat)) : Bool := + let P := L.map fun x => (x, h x) + P.all (fun p => decide (2 ^ 128 ≤ p.2)) && P.all fun p => P.all fun q => decide (p.2 = q.2 → p.1 = q.1) + +theorem separatedBy_iff_check (h : List Nat → Nat) (L : List (List Nat)) : + SeparatedBy h L ↔ sepCheckBy h L = true := by + simp only [sepCheckBy, SeparatedBy, Bool.and_eq_true, List.all_eq_true, List.mem_map, + decide_eq_true_eq, forall_exists_index, and_imp] + constructor + · rintro ⟨hi, hg⟩ + refine ⟨?_, ?_⟩ + · rintro _ x hx rfl; exact hg x hx + · rintro _ x hx rfl _ y hy rfl he; exact hi x hx y hy he + · rintro ⟨hg, hi⟩ + exact ⟨fun x hx y hy he => hi _ x hx rfl _ y hy rfl he, fun x hx => hg _ x hx rfl⟩ + +/-- **The real premise is the check at keccak256.** -/ +theorem scopedSep_iff_check (L : List (List Nat)) : ScopedSep L ↔ sepCheckBy keccakWord L = true := + (scopedSep_iff L).trans (separatedBy_iff_check _ _) + +instance (L : List (List Nat)) : Decidable (ScopedSep L) := + decidable_of_iff _ (scopedSep_iff_check L).symm + +/-- One kernel evaluation of the check is one call's premise: `scopedSep_of_check (by decide +kernel)`. -/ +theorem scopedSep_of_check {L : List (List Nat)} (h : sepCheckBy keccakWord L = true) : ScopedSep L := + (scopedSep_iff_check L).2 h + +theorem SeparatedBy.mono {h : List Nat → Nat} {L M : List (List Nat)} (hL : SeparatedBy h L) + (hM : ∀ x ∈ M, x ∈ L) : SeparatedBy h M := + ⟨fun x hx y hy he => hL.1 x (hM x hx) y (hM y hy) he, fun x hx => hL.2 x (hM x hx)⟩ + +/-! ## Nested footprints -/ + +/-- The footprint of `approve(spender, value)` of an allowance mapping at slot `a`, for the hash `h`: the +outer preimage `caller . a` and the inner `spender . h(caller . a)`. -/ +def approveFootprintBy (h : List Nat → Nat) (a caller spender : Nat) : List (List Nat) := + [mappingPreimage caller a, mappingPreimage spender (h (mappingPreimage caller a))] + +/-- The footprint of `transferFrom(src, dst, value)` with balances at slot `b` and allowances at slot +`a`: `balanceOf[src]`, `balanceOf[dst]`, and `allowance[src][caller]` (outer and inner preimage). -/ +def transferFromFootprintBy (h : List Nat → Nat) (b a src dst caller : Nat) : List (List Nat) := + [mappingPreimage src b, mappingPreimage dst b, mappingPreimage src a, + mappingPreimage caller (h (mappingPreimage src a))] + +/-- `approve`'s footprint at the real keccak256. -/ +abbrev approveFootprint (a caller spender : Nat) : List (List Nat) := + approveFootprintBy keccakWord a caller spender + +/-- `transferFrom`'s footprint at the real keccak256. -/ +abbrev transferFromFootprint (b a src dst caller : Nat) : List (List Nat) := + transferFromFootprintBy keccakWord b a src dst caller + +/-- The nested slot `m[k1][k2]` as SolidCore computes it is the inner preimage's image. -/ +theorem nested_slot_eq (k1 k2 a : Nat) : + solHash k2 (solHash k1 a) = keccakWord (mappingPreimage k2 (keccakWord (mappingPreimage k1 a))) := by + rw [solHash_eq, solHash_eq]; rfl + +/-- **approve's slot fact**: `allowance[caller][spender]` and its outer slot are at least `2 ^ 128`, so +neither is a small fixed slot. -/ +theorem approve_slots {a c s : Nat} (h : ScopedSep (approveFootprint a c s)) : + 2 ^ 128 ≤ solHash c a ∧ 2 ^ 128 ≤ solHash s (solHash c a) := by + refine ⟨scoped_ge h (by simp [approveFootprintBy]), scoped_ge h ?_⟩ + have e : solHash c a = keccakWord (mappingPreimage c a) := solHash_eq c a + rw [e]; simp [approveFootprintBy] + +/-- **transferFrom's slot facts**: the two balance slots differ when `src ≠ dst`; the allowance slot +`allowance[src][caller]` differs from both balance slots whatever the addresses (its inner key is a +hash, at least `2 ^ 128`, while `b` is a small slot); all three are at least `2 ^ 128`. -/ +theorem transferFrom_slots {b a f t c : Nat} (h : ScopedSep (transferFromFootprint b a f t c)) + (hb : b < 2 ^ 128) (ha : a < 2 ^ 256) (hf : f < 2 ^ 256) (ht : t < 2 ^ 256) (hc : c < 2 ^ 256) : + (f ≠ t → solHash f b ≠ solHash t b) ∧ solHash c (solHash f a) ≠ solHash f b ∧ + solHash c (solHash f a) ≠ solHash t b ∧ 2 ^ 128 ≤ solHash f b ∧ 2 ^ 128 ≤ solHash t b ∧ + 2 ^ 128 ≤ solHash c (solHash f a) := by + have hbw : b < 2 ^ 256 := lt_trans hb (by decide) + have mf : mappingPreimage f b ∈ transferFromFootprint b a f t c := by simp [transferFromFootprintBy] + have mt : mappingPreimage t b ∈ transferFromFootprint b a f t c := by simp [transferFromFootprintBy] + have mo : mappingPreimage f a ∈ transferFromFootprint b a f t c := by simp [transferFromFootprintBy] + have mi : mappingPreimage c (solHash f a) ∈ transferFromFootprint b a f t c := by + have e : solHash f a = keccakWord (mappingPreimage f a) := solHash_eq f a + rw [e]; simp [transferFromFootprintBy] + have hge := scoped_ge h mo + have hlt : solHash f a < 2 ^ 256 := solHash_lt f a + have hne : ∀ x, x < 2 ^ 256 → mappingPreimage x b ∈ transferFromFootprint b a f t c → + solHash c (solHash f a) ≠ solHash x b := fun x hx mx he => by + have := (scoped_inj h hc hx hlt hbw mi mx he).2 + omega + exact ⟨fun hft he => hft (scoped_inj h hf ht hbw hbw mf mt he).1, hne f hf mf, hne t ht mt, + scoped_ge h mf, scoped_ge h mt, scoped_ge h mi⟩ + +/-! ## 1. Abstract model: every footprint is consistent -/ + +/-- The position hash `x ↦ 2 ^ 128 + (position of x in L)` separates `L`. -/ +theorem separatedBy_idxOf (L : List (List Nat)) : SeparatedBy (fun x => 2 ^ 128 + L.idxOf x) L := by + refine ⟨fun x hx y hy he => ?_, fun _ _ => Nat.le_add_right _ _⟩ + have he' : L.idxOf x = L.idxOf y := by simpa using he + rw [← List.getElem_idxOf (List.idxOf_lt_length_of_mem hx), + ← List.getElem_idxOf (List.idxOf_lt_length_of_mem hy)] + simp only [he'] + +/-- **approve's footprint has a word-valued model**, its inner key computed by the model itself. -/ +theorem approve_model (a c s : Nat) : + ∃ h : List Nat → Nat, (∀ x, h x < 2 ^ 256) ∧ SeparatedBy h (approveFootprintBy h a c s) := by + let L := [mappingPreimage c a, mappingPreimage s (2 ^ 128)] + refine ⟨fun x => 2 ^ 128 + L.idxOf x, fun x => ?_, ?_⟩ + · show 2 ^ 128 + L.idxOf x < 2 ^ 256 + exact Nat.lt_of_le_of_lt (Nat.add_le_add_left List.idxOf_le_length _) (by simp [L]) + · refine (separatedBy_idxOf L).mono fun x hx => ?_ + simp [approveFootprintBy, L] at hx ⊢ + rcases hx with rfl | rfl <;> simp + +/-- **transferFrom's footprint has a word-valued model**, its inner key computed by the model. -/ +theorem transferFrom_model (b a f t c : Nat) : + ∃ h : List Nat → Nat, (∀ x, h x < 2 ^ 256) ∧ SeparatedBy h (transferFromFootprintBy h b a f t c) := by + let L := [mappingPreimage f a, mappingPreimage c (2 ^ 128), mappingPreimage f b, mappingPreimage t b] + refine ⟨fun x => 2 ^ 128 + L.idxOf x, fun x => ?_, ?_⟩ + · show 2 ^ 128 + L.idxOf x < 2 ^ 256 + exact Nat.lt_of_le_of_lt (Nat.add_le_add_left List.idxOf_le_length _) (by simp [L]) + · refine (separatedBy_idxOf L).mono fun x hx => ?_ + simp [transferFromFootprintBy, L] at hx ⊢ + rcases hx with rfl | rfl | rfl | rfl <;> simp + +/-! ## 2. Real witnesses: kernel evaluations of the check on concrete calls + +Addresses are arbitrary 160-bit values. UniswapV2ERC20's layout: `balanceOf` at slot 1, `allowance` +at slot 2. -/ + +/-- A caller. -/ +abbrev addrA : Nat := 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4 +/-- A recipient or spender. -/ +abbrev addrB : Nat := 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2 +/-- A third address. -/ +abbrev addrC : Nat := 0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db + +set_option maxRecDepth 100000 in +theorem real_transfer_AB : ScopedSep (transferFootprint 1 addrA addrB) := + scopedSep_of_check (by decide +kernel) + +set_option maxRecDepth 100000 in +/-- Self-transfer: the footprint names one preimage twice; the check holds. -/ +theorem real_transfer_AA : ScopedSep (transferFootprint 1 addrA addrA) := + scopedSep_of_check (by decide +kernel) + +set_option maxRecDepth 100000 in +theorem real_approve_AB : ScopedSep (approveFootprint 2 addrA addrB) := + scopedSep_of_check (by decide +kernel) + +set_option maxRecDepth 100000 in +theorem real_transferFrom_ABC : ScopedSep (transferFromFootprint 1 2 addrA addrB addrC) := + scopedSep_of_check (by decide +kernel) + +/-! Negative controls, by evaluation: the check refuses hashes that collide on the footprint or map +into the small slots. -/ + +theorem check_refuses_constant : + sepCheckBy (fun _ => 2 ^ 128) (transferFootprint 1 addrA addrB) = false := by decide +kernel + +set_option maxRecDepth 100000 in +theorem check_refuses_truncated : + sepCheckBy (fun x => keccakWord x % 2 ^ 128) (transferFootprint 1 addrA addrB) = false := by + decide +kernel + +theorem check_refuses_length_hash : + sepCheckBy (fun x => 2 ^ 128 + x.length) + (transferFromFootprintBy (fun _ => 0) 1 2 addrA addrB addrC) = false := by + decide +kernel + +/-! ## 3. Universal claims: named, not proved, not assumed -/ + +/-- The transfer premise for every pair of addresses. **Not proved**; no statement assumes it. -/ +def UniversalTransferSep (m : Nat) : Prop := + ∀ c t, c < 2 ^ 160 → t < 2 ^ 160 → ScopedSep (transferFootprint m c t) + +/-- It is exactly keccak256 separation on all `2 ^ 160` balance preimages: a global claim about the +hash, which is why statements take the premise of their own call instead. -/ +theorem universalTransferSep_iff (m : Nat) : + UniversalTransferSep m ↔ KeccakSeparated (fun x => ∃ k < 2 ^ 160, x = mappingPreimage k m) := by + constructor + · intro hu + refine ⟨fun x y ⟨k, hk, hx⟩ ⟨k', hk', hy⟩ he => ?_, fun x ⟨k, hk, hx⟩ => ?_⟩ + · subst hx hy + exact (hu k k' hk hk').1 _ _ (by simp [transferFootprint]) (by simp [transferFootprint]) he + · subst hx; exact (hu k k hk hk).2 _ (by simp [transferFootprint]) + · intro hs c t hc ht + refine hs.mono fun x hx => ?_ + simp only [transferFootprint, List.mem_cons, List.not_mem_nil, or_false] at hx + rcases hx with rfl | rfl + · exact ⟨c, hc, rfl⟩ + · exact ⟨t, ht, rfl⟩ + +/-! ## Axiom checks -/ + +/-- info: 'SolidCore.Spec.scopedSep_iff_check' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms scopedSep_iff_check + +/-- info: 'SolidCore.Spec.approve_slots' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms approve_slots + +/-- info: 'SolidCore.Spec.transferFrom_slots' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms transferFrom_slots + +/-- info: 'SolidCore.Spec.approve_model' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms approve_model + +/-- info: 'SolidCore.Spec.transferFrom_model' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms transferFrom_model + +/-- info: 'SolidCore.Spec.real_transfer_AB' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms real_transfer_AB + +/-- info: 'SolidCore.Spec.real_transfer_AA' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms real_transfer_AA + +/-- info: 'SolidCore.Spec.real_approve_AB' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms real_approve_AB + +/-- info: 'SolidCore.Spec.real_transferFrom_ABC' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms real_transferFrom_ABC + +/-- info: 'SolidCore.Spec.check_refuses_constant' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms check_refuses_constant + +/-- info: 'SolidCore.Spec.check_refuses_truncated' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms check_refuses_truncated + +/-- info: 'SolidCore.Spec.check_refuses_length_hash' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms check_refuses_length_hash + +/-- info: 'SolidCore.Spec.universalTransferSep_iff' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms universalTransferSep_iff + +end SolidCore.Spec diff --git a/Verify/Spec/HashScopeNested.lean b/Verify/Spec/HashScopeNested.lean new file mode 100644 index 00000000..9bd5209f --- /dev/null +++ b/Verify/Spec/HashScopeNested.lean @@ -0,0 +1,159 @@ +import Verify.Spec.HashScope +import Verify.Spec.TrustedBase.Hypotheses + +/-! +# keccak256 separation scoped to a call's footprint, for mappings of mappings + +`NestedSlotsSeparated ms ns` (TreeMapNested.lean) asks keccak256 to be injective on the slots +`n[b][a]` for **all** addresses `a`, `b`: `2 ^ 320` preimages into `2 ^ 256` words, so it is false of +keccak256 and every theorem assuming it is vacuous for the real EVM. This module states the +separation a call needs instead: keccak256 separated (`TrustedBase.KeccakSeparated`: injective, +every image at least `2 ^ 128`) on the **finite list** of preimages the call hashes, its +footprint, as hevm does (pairwise injectivity over the hash applications that occur). + +* `Scoped L`: the premise, for a footprint `L` (a list, so finite by construction). +* `nestedFootprint n o s`: the two preimages of `n[o][s]`'s slot, the inner `o . n` and the outer + `s . keccak(o . n)`; `approveFootprint` and `transferFromFootprint` are UniswapV2ERC20's (allowance + at slot 2, balanceOf at slot 1). +* The slot facts a spec needs, each from `Scoped L` and membership in `L` only: two slots of + the footprint are equal only for equal keys and mapping slots (`slot_ne`), a nested slot is no + first-level slot of a small mapping slot (`nested_ne_flat`) and no small constant slot (`slot_ge`). +* `transferFrom_scoped_witness`: the premise holds of a concrete nontrivial footprint (three + distinct keys, four preimages), by the kernel's evaluation of keccak256 on each, so it is + satisfiable, unlike `NestedSlotsSeparated`. + +`Scoped` is hash-scope's `ScopedSep` (Verify/Spec/HashScope.lean), the one footprint premise for +single-level and nested mappings alike: this module adds only the nested footprints and their slot +facts. +-/ + +namespace SolidCore.Spec.HashScopeNested + +open SolidCore.Refinement SolidCore.Refinement.Generic + +/-- **keccak256 separated on a call's footprint** `L`: injective on the finitely many preimages in +`L`, and every image at least `2 ^ 128` (so no small constant slot). -/ +abbrev Scoped (L : List (List Nat)) : Prop := ScopedSep L + +/-- The preimage of the slot of `m[a]` for a mapping at slot `m`. -/ +abbrev pre (a m : Nat) : List Nat := TrustedBase.mappingPreimage a m + +/-- The footprint of `n[o][s]`: the inner preimage `o . n` and the outer `s . keccak(o . n)`. -/ +def nestedFootprint (n o s : Nat) : List (List Nat) := [pre o n, pre s (solHash o n)] + +/-- `approve(spender, value)` from `caller` writes `allowance[caller][spender]` (allowance at slot 2). -/ +def approveFootprint (caller spender : Nat) : List (List Nat) := nestedFootprint 2 caller spender + +/-- `transferFrom(frm, to, value)` from `caller` reads and writes `allowance[frm][caller]`, +`balanceOf[frm]` and `balanceOf[to]` (balanceOf at slot 1). -/ +def transferFromFootprint (caller frm dst : Nat) : List (List Nat) := + nestedFootprint 2 frm caller ++ [pre frm 1, pre dst 1] + +theorem Scoped.mono {L L' : List (List Nat)} (h : Scoped L') (hs : ∀ x ∈ L, x ∈ L') : Scoped L := + TrustedBase.KeccakSeparated.mono h hs + +/-- A footprint slot is no small constant slot. -/ +theorem slot_ge {L : List (List Nat)} (h : Scoped L) {a m : Nat} (hx : pre a m ∈ L) : + 2 ^ 128 ≤ solHash a m := by + rw [solHash_eq] + exact h.2 _ hx + +/-- Two footprint slots are equal only for equal keys and mapping slots. -/ +theorem slot_ne {L : List (List Nat)} (h : Scoped L) {a b m n : Nat} (h1 : pre a m ∈ L) + (h2 : pre b n ∈ L) (ha : a < 2 ^ 256) (hb : b < 2 ^ 256) (hm : m < 2 ^ 256) (hn : n < 2 ^ 256) + (hne : ¬(a = b ∧ m = n)) : solHash a m ≠ solHash b n := by + intro he + rw [solHash_eq, solHash_eq] at he + exact hne (mappingPreimage_inj ha hb hm hn (h.1 _ _ h1 h2 he)) + +/-- A nested footprint slot `n[o][s]` is no first-level slot `m[b]` of a small mapping slot. -/ +theorem nested_ne_flat {L : List (List Nat)} (h : Scoped L) {o s n b m : Nat} + (hi : pre o n ∈ L) (ho : pre s (solHash o n) ∈ L) (hf : pre b m ∈ L) + (hs : s < 2 ^ 256) (hb : b < 2 ^ 256) (hm : m < 2 ^ 128) : + solHash s (solHash o n) ≠ solHash b m := by + have hge := slot_ge h hi + have hlt := solHash_lt o n + unfold Generic.wordSize at hlt + exact slot_ne h ho hf hs hb hlt (by omega) (fun ⟨_, e⟩ => by omega) + +/-- **transferFrom's slots are apart on its footprint**: `allowance[frm][caller]` is neither balance +slot, the two balance slots differ for different keys, and none is a small constant slot. -/ +theorem transferFrom_slots {caller frm dst : Nat} (h : Scoped (transferFromFootprint caller frm dst)) + (hc : caller < 2 ^ 256) (hf : frm < 2 ^ 256) (ht : dst < 2 ^ 256) : + solHash caller (solHash frm 2) ≠ solHash frm 1 ∧ solHash caller (solHash frm 2) ≠ solHash dst 1 ∧ + (frm ≠ dst → solHash frm 1 ≠ solHash dst 1) ∧ 2 ^ 128 ≤ solHash caller (solHash frm 2) ∧ + 2 ^ 128 ≤ solHash frm 1 ∧ 2 ^ 128 ≤ solHash dst 1 := by + simp only [transferFromFootprint, nestedFootprint] at h + have m0 : pre frm 2 ∈ [pre frm 2, pre caller (solHash frm 2)] ++ [pre frm 1, pre dst 1] := by simp + have m1 : pre caller (solHash frm 2) ∈ [pre frm 2, pre caller (solHash frm 2)] ++ [pre frm 1, pre dst 1] := by simp + have m2 : pre frm 1 ∈ [pre frm 2, pre caller (solHash frm 2)] ++ [pre frm 1, pre dst 1] := by simp + have m3 : pre dst 1 ∈ [pre frm 2, pre caller (solHash frm 2)] ++ [pre frm 1, pre dst 1] := by simp + exact ⟨nested_ne_flat h m0 m1 m2 hc hf (by norm_num), nested_ne_flat h m0 m1 m3 hc ht (by norm_num), + fun hne => slot_ne h m2 m3 hf ht (by norm_num) (by norm_num) (fun ⟨e, _⟩ => hne e), + slot_ge h m1, slot_ge h m2, slot_ge h m3⟩ + +/-- **approve's slot is no small constant slot** on its footprint. -/ +theorem approve_slot {caller spender : Nat} (h : Scoped (approveFootprint caller spender)) : + 2 ^ 128 ≤ solHash spender (solHash caller 2) := + slot_ge h (by simp [approveFootprint, nestedFootprint]) + +end SolidCore.Spec.HashScopeNested + +namespace SolidCore.Spec.HashScopeNested + +open SolidCore.Refinement SolidCore.Refinement.Generic + +/-! ## The premise is satisfiable and not trivial + +`transferFrom_scoped_witness`: on the footprint of `transferFrom(1, 2, _)` from `0x2000` (the stage's +caller) the premise holds, from the four images by the kernel's evaluation of keccak256 (one per +declaration). `not_scoped_collision`: it is not `True` either, since a footprint with two byte lists +of one image (`[0]` and `[256]`, the same bytes) refutes it. -/ + +/-- keccak256 of `1 . 2` (the slot of `allowance[1]`'s inner mapping). -/ +abbrev kInner : Nat := 0xe90b7bceb6e7df5418fb78d8ee546e97c83a08bbccc01a0644d599ccd2a7c2e0 + +set_option maxRecDepth 100000 in +theorem image_inner : keccakWord (TrustedBase.mappingPreimage 1 2) = kInner := by decide +kernel + +set_option maxRecDepth 100000 in +theorem image_outer : keccakWord (TrustedBase.mappingPreimage 0x2000 kInner) = + 0x2e4aafeb9f8b1b374b0f80165f823ef45fa5ed8d99f592ae99f791121a39e502 := by decide +kernel + +set_option maxRecDepth 100000 in +theorem image_from : keccakWord (TrustedBase.mappingPreimage 1 1) = + 0xcc69885fda6bcc1a4ace058b4a62bf5e179ea78fd58a1ccd71c22cc9b688792f := by decide +kernel + +set_option maxRecDepth 100000 in +theorem image_to : keccakWord (TrustedBase.mappingPreimage 2 1) = + 0xd9d16d34ffb15ba3a3d852f0d403e2ce1d691fb54de27ac87cd2f993f3ec330f := by decide +kernel + +/-- **The scoped premise holds of a concrete nontrivial footprint**: `transferFrom(1, 2, _)` from +`0x2000`, four preimages over three distinct keys and both mapping levels. -/ +theorem transferFrom_scoped_witness : Scoped (transferFromFootprint 0x2000 1 2) := by + have hi : solHash 1 2 = kInner := by rw [solHash_eq]; exact image_inner + unfold Scoped transferFromFootprint nestedFootprint pre + rw [hi] + exact TrustedBase.keccakSeparated_of_images (H := [kInner, + 0x2e4aafeb9f8b1b374b0f80165f823ef45fa5ed8d99f592ae99f791121a39e502, + 0xcc69885fda6bcc1a4ace058b4a62bf5e179ea78fd58a1ccd71c22cc9b688792f, + 0xd9d16d34ffb15ba3a3d852f0d403e2ce1d691fb54de27ac87cd2f993f3ec330f]) + (by simp only [List.cons_append, List.nil_append, List.map_cons, List.map_nil, image_inner, + image_outer, image_from, image_to]) (by decide) (by decide) + +set_option maxRecDepth 100000 in +/-- **The scoped premise is not trivial**: it fails on a footprint with a collision. -/ +theorem not_scoped_collision : ¬ Scoped [[0], [256]] := by + intro h + have := h.1 [0] [256] (by simp) (by simp) (by decide +kernel) + simp at this + +/-- info: 'SolidCore.Spec.HashScopeNested.transferFrom_scoped_witness' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms transferFrom_scoped_witness + +/-- info: 'SolidCore.Spec.HashScopeNested.transferFrom_slots' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms transferFrom_slots + +end SolidCore.Spec.HashScopeNested diff --git a/Verify/Spec/README.md b/Verify/Spec/README.md new file mode 100644 index 00000000..684b13db --- /dev/null +++ b/Verify/Spec/README.md @@ -0,0 +1,91 @@ +# The meaning of solar-verify's specs + +This directory gives the annotations `solar-verify` checks a meaning in Lean, over the calls and +observables SolidCore and EthLib share (`SolarTV.Sem`), so a spec `solar-verify` accepts becomes a +Lean proposition about the contract and, through the certified translation, about solar's bytecode. + +## Files + +- `Syntax.lean`: the spec language after `solar-verify`'s front end. Terms are integers (math-int + semantics: no wrapping until a value is stored), with arguments, named returns, storage loads at + a slot, byte offset and width with their type, `old(..)`, ghosts, `msg.sender`, `msg.value`, + `block.timestamp` (`__time`), `==>` and `<==>`, bounded `forall` and `exists`, and calls of spec + functions, opaque (`@custom:opaque`) or inlined by unfolding. A `Manifest` binds a spec to its + source's sha256, the compiler and the runtime bytecode's sha256. +- `Semantics.lean`: `eval`, total on fuel; mapping and array slots by keccak. +- `Contract.lean`: `Pre` and `Post` of a function spec at a call (selector, ABI decoding, + requires, and the contract and struct invariants) and `Holds S p scope b ctxOf`: every call in + scope that meets its function's `Pre` ends in an observable meeting its `Post` (a revert is + allowed only where the spec does not say the call succeeds). `Holds.of_stage` moves it along a + refinement stage, so a spec proved of SolidCore holds of the bytecode. +- `Ghost.lean`: ghost erasure. For a core language with assignments, requires, branches, loops, + ghost statements, asserts and assumes, erasing well-formed ghost code changes no real state and + no outcome when the ghost code terminates (`sound`, `complete`), so a spec over real state + proved of the program with ghosts holds of the erased program (`spec_of_erased_real`). + Straight-line ghost code always terminates (`ghostTotal_of_straight`). +- `GhostFree.lean`: a ghost-free term has the same value in environments that differ only in + their ghost states (`eval_ghostEquiv`, `Bundle.sat_ghostEquiv`). +- `TrustedBase.lean`: each item of the "Trusted base" in solar-verify's README as a named + hypothesis, never an axiom, and `spec_of_verdict`, which takes the verdict itself as one. +- `TrustedBase/Hypotheses.lean`: each of those hypotheses stated precisely (`Hyps`, + `Hyps.toAssumptions`, `spec_of_verdict_hyps`), with a witness that it is satisfiable, where cheap one + that it is not trivially true, and its discharge for code without the feature (table below). + `TrustedBase/Instances.lean`: c4's and Counter's discharged. `TrustedBase/Axioms.lean`: their + `#print axioms`. +- `Export/`: specs generated by `solar-verify --emit-lean-spec` from `scripts/refinement/spec`. +- `Solar/C4.lean`: the c4 spec proved of SolidCore (`holds_source`), of solar's bytecode for the + deployed storage (`holds_bytecode`) and for any storage given the solar-tv stage + (`holds_bytecode_at`), bound to the manifest (`certified`); the wrong spec fails on a concrete + call (`wrong_fails`). +- `Axioms.lean`: `#print axioms` for the theorems above: `propext`, `Classical.choice` and + `Quot.sound` only. + +## Trusted base as hypotheses + +| README item | Lean | +| --- | --- | +| 1. Parser, VC encoding and solvers | `Verdict`, the hypothesis of `spec_of_verdict` | +| 2. `@custom:assume`, `@custom:trusted`, interface ensures | `Assumptions.assumptionsHold` | +| 3. No `delegatecall` into the contract | `Assumptions.noDelegatecall` | +| 4. keccak256 injective, images in `[2^128, 2^256)` | `Assumptions.keccakSeparated`, per call: injectivity cannot hold of all inputs | +| 5. Assembly slots disjoint, assembly memory-safe | `Assumptions.asmSlotsDisjoint`, `Assumptions.asmMemorySafe` | +| 6. `Math.mulDiv` summarized as OpenZeppelin's | `Assumptions.mulDiv` | +| 7. View and pure calls answer as functions of what they read | `Assumptions.viewCalls` | +| Opaque spec functions return values of their type | `OpaqueInRange` | + +Stated precisely in `TrustedBase/Hypotheses.lean`: + +| Item | Statement | Satisfiable / not trivial | Discharged | +| --- | --- | --- | --- | +| 2. `@custom:assume` | `Core.AssumesHold s σ`: no assume cuts off an execution of the core program from `σ` | `assumesHold_assumeX` / `not_assumesHold_assumeX` | no assume: `assumesHold_of_noAssume` | +| 2. `@custom:trusted`, internal | `Core.MeetsContract s req ens` | `meetsContract_assign` / `not_meetsContract_assign` | no trusted function | +| 2. `@custom:trusted`, external | `TrustedHold`: `Holds` of the trusted functions' specs | | `trustedHold_nil`, `trustedHold_of_holds` | +| 2. Interface ensures | `InterfaceEnsures ens tr` over a transcript's call exchanges; `ens := ifaceEnsOf iface ctx st` builds it from an exported interface spec (`Interface.lean`) | `interfaceEnsures_one` / `not_interfaceEnsures_zero` | no call returns: `interfaceEnsures_of_default` | +| 3. No `delegatecall` into the contract | `NoForeignWrites` within a call; `Reach` from deployment across calls | `Reach.refl` | `noForeignWrites_of_default` | +| 4. keccak256 | `KeccakSeparated S` of the call's preimages | `keccakSeparated_mapping` (six real mapping slots, kernel-evaluated) / `not_keccakSeparated_univ` | nothing hashed: `keccakSeparated_empty` | +| 5. Assembly | `AsmFree u`, stronger: SolidCore rejects assembly | `asmFree_example` / `not_asmFree_example` | by `decide`: `asmFree_c4`, `asmFree_counter` | +| 6. `Math.mulDiv` | `MulDivSummary impl`: agrees with `ozMulDiv` (`ozMulDiv_spec`: floor of the exact quotient) | `mulDivSummary_oz` / `not_mulDivSummary_unchecked` | no `Math.mulDiv` | +| 7. View calls | `ViewDeterministic self tr`: same target and calldata, from worlds agreeing on balances, code and the caller's storage, answer alike whatever the gas | `viewDeterministic_twice` / `not_viewDeterministic` | `viewDeterministic_of_default` | + +`Hyps.satisfiable`: the whole structure holds on every call of some instance. Open: a call's keccak256 +preimages and its transcript are supplied with `Hyps`, not yet derived from SolidCore's run +(`transcriptWith` computes a transcript from an interaction tree, but `Source.run` folds its tree +without exposing it, and SolidCore hashes inside its interpreter); `MulDivSummary` is not yet +instantiated with SolidCore's internal-call semantics. + +c4 needs none of them: `Assumptions.none_on`, and its spec has no opaque functions. + +## Checking the exports + +`scripts/refinement/spec/check.sh` regenerates the exports with `solar-verify` and fails if they +differ, checks that the annotated source is the corpus source with comments, and that the +manifest's bytecode sha256 is the runtime bytecode's. + +## Not done yet + +- Loop invariants have syntax but no meaning yet; they wait on Loom's loop rules in + `vendor/loom`. Ghost erasure is proved for the core language, not yet tied to SolidCore + statements. +- A spec holds per call; invariants are not yet chained along a sequence of calls. +- `holds_bytecode_at` takes the solar-tv c4 stage as a hypothesis, because the pinned solar-tv + c4 milestone proofs do not build here. diff --git a/Verify/Spec/Semantics.lean b/Verify/Spec/Semantics.lean new file mode 100644 index 00000000..928ef038 --- /dev/null +++ b/Verify/Spec/Semantics.lean @@ -0,0 +1,263 @@ +import Verify.Spec.Syntax + +/-! +# solar-verify's spec language: meaning + +The meaning of a spec over a call and what it observes (`SolarTV.Call`, `SolarTV.Observable`), +the interface SolidCore, solar's IRs and EthLib share, so that the same predicate holds of the +source and of the bytecode a refinement relates it to. + +* `eval`: a spec expression's value, an `Int`, from the call's arguments and return values, the + pre- and post-state (storage, ghost state, `__time`) and the call's environment. Arithmetic is + on mathematical integers; division and remainder truncate toward zero; `&`, `|`, `^` work on the + 256-bit two's complement words of their operands; `<<` by a literal wraps modulo `2 ^ 256`. These + are solar-verify's own spec encodings (`src/vc.rs`, `arith` in spec mode). Where solar-verify + leaves a value unconstrained (division by zero, a negative exponent), any value here is sound + for its proofs, and this one picks Lean's. +* Quantifiers range over the binder's type, as solar-verify's `quant` does. They make `eval` + noncomputable: a formula's meaning is a proposition. +* A spec function call evaluates the function's body with its parameters bound to the + arguments' values. Calls nest at most `fuel` deep: `Term.Closed` checks that the exported fuel + suffices, so the out-of-fuel case (`0`) is never reached in an exported spec. An opaque + function means its body too; solar-verify proves facts about it for every interpretation in its + return type's range, which includes this one exactly when `OpaqueInRange` holds. +* `Pre` and `Post` state a function's spec: the call selects the function and its arguments + decode (ABI-clean words of their types), and from a pre-state meeting the requires and the + contract invariants, a successful call returns clean words meeting the ensures and leaves a + state meeting the invariants, and one meeting the succeeds-if conditions succeeds. +* `Holds S p scope cs ctxOf step`: every function's spec holds of program `p` in semantics `S` on + `scope`, with ghost state updated by `step`. A ghost-free spec does not depend on `step` + (`Holds.ghostFree`). +-/ + +namespace SolidCore.Spec + +open SolarTV + +/-- Storage: slot to word. -/ +abbrev Storage := Nat → Nat + +/-- Ghost state: each ghost variable, as a function of its mapping keys (none for a scalar). -/ +abbrev Ghost := String → List Int → Int + +/-- The ghost state at deployment: every ghost zero. -/ +def Ghost.zero : Ghost := fun _ _ => 0 + +/-- `2 ^ 256`. -/ +abbrev wordMod : Nat := 2 ^ 256 + +/-- The 256-bit word of an integer (two's complement for negative ones). -/ +def toWord (v : Int) : Nat := (v % (wordMod : Int)).toNat + +/-- The 32 big-endian bytes of a word. -/ +def wordBytes (v : Nat) : List Nat := (List.range 32).reverse.map fun i => v / 256 ^ i % 256 + +/-- The big-endian word of a byte list. -/ +def bytesWord (bs : List Nat) : Nat := bs.foldl (fun acc b => acc * 256 + b) 0 + +/-- Keccak-256 of a byte list, as a word: the definition SolidCore and EthLib both use. -/ +def keccakWord (bs : List Nat) : Nat := bytesWord (EvmYul.SpongeHash.Keccak256.keccak256Bytes bs) + +/-! ## Types -/ + +/-- The values of a type. -/ +def Ty.InRange : Ty → Int → Prop + | .uint b, v => 0 ≤ v ∧ v < 2 ^ b + | .int b, v => -(2 ^ (b - 1)) ≤ v ∧ v < 2 ^ (b - 1) + | .bool, v => v = 0 ∨ v = 1 + | .address, v => 0 ≤ v ∧ v < 2 ^ 160 + | .fixedBytes n, v => 0 ≤ v ∧ v < 2 ^ (8 * n) + | .enum c, v => 0 ≤ v ∧ v < c + | .math, _ => True + +instance (t : Ty) (v : Int) : Decidable (t.InRange v) := by + cases t <;> unfold Ty.InRange <;> infer_instance + +/-- A value of type `t` from the `8 * bits` low bits of a storage word, as Solidity reads it. -/ +def Ty.ofBits : Ty → Nat → Int + | .int b, raw => if 2 ^ (b - 1) ≤ raw then (raw : Int) - 2 ^ b else raw + | .bool, raw => if raw = 0 then 0 else 1 + | _, raw => raw + +/-- A value of type `t` from an ABI word, or `none` when the word is not clean for `t` (Solidity's +decoder reverts on it). `bytesN` is left-aligned. -/ +def Ty.ofWord : Ty → Nat → Option Int + | .uint b, w => if w < 2 ^ b then some w else none + | .int b, w => + if w < 2 ^ (b - 1) then some w + else if wordMod - 2 ^ (b - 1) ≤ w ∧ w < wordMod then some ((w : Int) - wordMod) + else none + | .bool, w => if w ≤ 1 then some w else none + | .address, w => if w < 2 ^ 160 then some w else none + | .fixedBytes n, w => + if w < wordMod ∧ w % 2 ^ (8 * (32 - n)) = 0 then some (w / 2 ^ (8 * (32 - n)) : Nat) else none + | .enum c, w => if w < c then some w else none + | .math, _ => none + +/-! ## States and environments -/ + +/-- What a spec reads of a state: storage, ghost state and `__time`. -/ +structure State where + storage : Storage + ghost : Ghost + time : Int + +/-- The call's environment. -/ +structure Ctx where + sender : Int + value : Int + timestamp : Int + self : Int + +/-- Everything a spec expression reads. `inOld` is set inside `old(..)`. -/ +structure Env where + args : List Int + rets : List Int + pre : State + post : State + ctx : Ctx + vars : List (String × Int) + inOld : Bool + +/-- The state a read sees. -/ +def Env.cur (e : Env) : State := if e.inOld then e.pre else e.post + +/-- Bind a variable. -/ +def Env.bind (e : Env) (x : String) (v : Int) : Env := { e with vars := (x, v) :: e.vars } + +/-- A truth value as `0` or `1`. -/ +noncomputable def ofProp (p : Prop) : Int := by + classical exact if p then 1 else 0 + +/-- Binary operators on values. -/ +noncomputable def BinOp.apply : BinOp → Int → Int → Int + | .add, a, b => a + b + | .sub, a, b => a - b + | .mul, a, b => a * b + | .div, a, b => a.tdiv b + | .mod, a, b => a.tmod b + | .pow, a, b => a ^ b.toNat + | .band, a, b => (toWord a &&& toWord b : Nat) + | .bor, a, b => (toWord a ||| toWord b : Nat) + | .bxor, a, b => (toWord a ^^^ toWord b : Nat) + | .eq, a, b => ofProp (a = b) + | .ne, a, b => ofProp (a ≠ b) + | .lt, a, b => ofProp (a < b) + | .le, a, b => ofProp (a ≤ b) + | .gt, a, b => ofProp (a > b) + | .ge, a, b => ofProp (a ≥ b) + | .and, a, b => ofProp (a ≠ 0 ∧ b ≠ 0) + | .or, a, b => ofProp (a ≠ 0 ∨ b ≠ 0) + | .implies, a, b => ofProp (a ≠ 0 → b ≠ 0) + +/-! ## Evaluation -/ + +mutual +/-- The value of a spec expression, with spec function calls nested at most `fuel` deep. -/ +noncomputable def eval (fns : List SpecFn) (fuel : Nat) : Term → Env → Int + | .lit v, _ => v + | .arg i, e => e.args.getD i 0 + | .ret i, e => e.rets.getD i 0 + | .var x, e => (e.vars.lookup x).getD 0 + | .env .sender, e => e.ctx.sender + | .env .value, e => e.ctx.value + | .env .timestamp, e => e.ctx.timestamp + | .env .self, e => e.ctx.self + | .env .time, e => e.cur.time + | .load p off size ty, e => + ty.ofBits (e.cur.storage (slotOf fns fuel p e) / 2 ^ (8 * toWord (eval fns fuel off e)) % + 2 ^ (8 * size)) + | .len p, e => e.cur.storage (slotOf fns fuel p e) + | .ghost x ks, e => e.cur.ghost x (evalList fns fuel ks e) + | .old t, e => eval fns fuel t { e with inOld := true } + | .un .neg t, e => -eval fns fuel t e + | .un .not t, e => ofProp (eval fns fuel t e = 0) + | .bin op a b, e => op.apply (eval fns fuel a e) (eval fns fuel b e) + | .shl t k, e => (eval fns fuel t e * 2 ^ k) % (wordMod : Int) + | .shr t k, e => eval fns fuel t e / 2 ^ k + | .ite c a b, e => if eval fns fuel c e ≠ 0 then eval fns fuel a e else eval fns fuel b e + | .all x ty body, e => ofProp (∀ v, ty.InRange v → eval fns fuel body (e.bind x v) ≠ 0) + | .ex x ty body, e => ofProp (∃ v, ty.InRange v ∧ eval fns fuel body (e.bind x v) ≠ 0) + | .call f args, e => + match fuel, fns.find? (·.name == f) with + | fuel' + 1, some sf => + eval fns fuel' sf.body { e with vars := (sf.params.map Prod.fst).zip (evalList fns (fuel' + 1) args e) } + | _, _ => 0 +termination_by t => (fuel, sizeOf t) + +/-- The values of a list of spec expressions. -/ +noncomputable def evalList (fns : List SpecFn) (fuel : Nat) : List Term → Env → List Int + | [], _ => [] + | t :: ts, e => eval fns fuel t e :: evalList fns fuel ts e +termination_by ts => (fuel, sizeOf ts) + +/-- The slot of a place. -/ +noncomputable def slotOf (fns : List SpecFn) (fuel : Nat) : Place → Env → Nat + | .slot n, _ => n % wordMod + | .offset b k, e => (slotOf fns fuel b e + toWord (eval fns fuel k e)) % wordMod + | .entry b k, e => keccakWord (wordBytes (toWord (eval fns fuel k e)) ++ wordBytes (slotOf fns fuel b e)) + | .elem b i n, e => + (keccakWord (wordBytes (slotOf fns fuel b e)) + toWord (eval fns fuel i e) * n) % wordMod + | .packedElem b i n, e => + (keccakWord (wordBytes (slotOf fns fuel b e)) + toWord (eval fns fuel i e) / n) % wordMod +termination_by p => (fuel, sizeOf p) +end + +/-- A formula holds: its value is nonzero. -/ +def Holds' (fns : List SpecFn) (fuel : Nat) (t : Term) (e : Env) : Prop := eval fns fuel t e ≠ 0 + + +/-! ## Evaluation lemmas -/ + +@[simp] theorem ofProp_ne_zero (p : Prop) : ofProp p ≠ 0 ↔ p := by + unfold ofProp; split <;> simp_all + +@[simp] theorem ofProp_eq_zero (p : Prop) : ofProp p = 0 ↔ ¬p := by + unfold ofProp; split <;> simp_all + +@[simp] theorem toWord_natCast {n : Nat} (h : n < 2 ^ 256) : toWord (n : Int) = n := by + have h' : (n : Int) < ((wordMod : Nat) : Int) := by exact_mod_cast h + unfold toWord + rw [Int.emod_eq_of_lt (by omega) h'] + simp + +/-! ## Well-formedness, checked by the kernel on every exported spec -/ + +mutual +/-- One level of `Term.Closed`: every call in `t` names a function of `fns` with as many arguments +as it has parameters, and `k` holds of the body it unfolds. Structural, so the kernel evaluates it. -/ +def Term.closedWith (fns : List SpecFn) (k : Term → Bool) : Term → Bool + | .load p off _ _ => Place.closedWith fns k p && Term.closedWith fns k off + | .len p => Place.closedWith fns k p + | .ghost _ ks => Term.closedListWith fns k ks + | .old t | .un _ t | .shl t _ | .shr t _ | .all _ _ t | .ex _ _ t => Term.closedWith fns k t + | .bin _ a b => Term.closedWith fns k a && Term.closedWith fns k b + | .ite c a b => Term.closedWith fns k c && Term.closedWith fns k a && Term.closedWith fns k b + | .call f args => + Term.closedListWith fns k args && + match fns.find? (·.name == f) with + | some sf => sf.params.length == args.length && k sf.body + | none => false + | .lit _ | .arg _ | .ret _ | .var _ | .env _ => true + +def Term.closedListWith (fns : List SpecFn) (k : Term → Bool) : List Term → Bool + | [] => true + | t :: ts => Term.closedWith fns k t && Term.closedListWith fns k ts + +def Place.closedWith (fns : List SpecFn) (k : Term → Bool) : Place → Bool + | .slot _ => true + | .offset b i | .entry b i | .elem b i _ | .packedElem b i _ => + Place.closedWith fns k b && Term.closedWith fns k i +end + +/-- Every spec function call in `t` resolves, with as many arguments as parameters, and calls nest +at most `fuel` deep, counting the bodies they unfold: `eval fns fuel t` never runs out of fuel. -/ +def Term.Closed (fns : List SpecFn) : Nat → Term → Bool + | 0 => Term.closedWith fns fun _ => false + | n + 1 => Term.closedWith fns (Term.Closed fns n) + +/-- `Term.Closed` of every term of a list. -/ +def Term.ClosedList (fns : List SpecFn) (fuel : Nat) (ts : List Term) : Bool := + ts.all (Term.Closed fns fuel) + +end SolidCore.Spec diff --git a/Verify/Spec/Syntax.lean b/Verify/Spec/Syntax.lean new file mode 100644 index 00000000..94974e99 --- /dev/null +++ b/Verify/Spec/Syntax.lean @@ -0,0 +1,162 @@ +import SolarTV.Sem +import EvmYul.SpongeHash.Keccak256 + +/-! +# solar-verify's spec language: syntax + +solar-verify (paradigmxyz/solar, crates/verify) reads specs from NatSpec tags: +`@custom:requires`, `@custom:ensures`, `@custom:succeeds-if`, `@custom:invariant` on a contract +or a struct, `@custom:ghost` declarations and updates, and spec functions, plain or +`@custom:opaque`. Its exporter (`solar-verify --emit-lean`) writes each contract's specs in the +syntax below, and `SolidCore.Spec.Semantics` gives them their meaning over the calls and +observables of SolidCore and EthLib (`SolarTV.Call`, `SolarTV.Observable`). + +Spec expressions are Solidity expressions over mathematical integers, as solar-verify encodes them +(`src/vc.rs`, `arith` with `spec` set): one sort, `Int`, with booleans as `0` and `1`. A spec +reads the contract's storage through `Place`s the exporter resolves from the storage layout +(state variables, mapping entries, array elements, struct fields), so its meaning is over the raw +slots the bytecode reads and writes, not over solar-verify's per-variable model of them. + +Every form the exporter does not translate is an export error, never a dropped spec. +-/ + +namespace SolidCore.Spec + +/-- The value types a spec reads, binds and returns. -/ +inductive Ty where + /-- `uintN`, `bits` a multiple of 8 up to 256. -/ + | uint (bits : Nat) + /-- `intN`, two's complement. -/ + | int (bits : Nat) + | bool + | address + /-- `bytesN`, read as the unsigned integer of its `n` bytes. -/ + | fixedBytes (n : Nat) + /-- An enum with `count` members, read as its index. -/ + | enum (count : Nat) + /-- A mathematical integer: the type of a `mathint` or `integer` quantifier binder. -/ + | math + deriving Repr, DecidableEq, Inhabited + +/-- Environment values of a call. `time` is solar-verify's `__time`, the latest +`block.timestamp` the contract has seen. -/ +inductive EnvVar where + | sender | value | timestamp | self | time + deriving Repr, DecidableEq, Inhabited + +/-- Unary operators. -/ +inductive UnOp where + | neg | not + deriving Repr, DecidableEq, Inhabited + +/-- Binary operators. The logical operators take and give `0` and `1`. -/ +inductive BinOp where + | add | sub | mul | div | mod | pow + | band | bor | bxor + | eq | ne | lt | le | gt | ge + | and | or | implies + deriving Repr, DecidableEq, Inhabited + +mutual +/-- A spec expression. -/ +inductive Term where + | lit (v : Int) + /-- The `i`th parameter of the function, as the call passed it. -/ + | arg (i : Nat) + /-- The `i`th return value (`result` is `ret 0`; named returns are their index). -/ + | ret (i : Nat) + /-- A variable bound by a quantifier or a spec function's parameter. -/ + | var (name : String) + | env (v : EnvVar) + /-- The value of type `ty` stored at `place`, `size` bytes from byte `offset` of its slot + (counted from the least significant byte; computed for packed array elements). -/ + | load (place : Place) (offset : Term) (size : Nat) (ty : Ty) + /-- The length of the dynamic storage array at `place`: the word in its slot. -/ + | len (place : Place) + /-- A ghost variable; `keys` index a ghost mapping. Ghost state starts at zero. -/ + | ghost (name : String) (keys : List Term) + /-- `old(e)`: `e` in the pre-state (storage, ghost state and `__time` of the call's start). -/ + | old (e : Term) + | un (op : UnOp) (e : Term) + | bin (op : BinOp) (a b : Term) + /-- `e << k` by a literal `k`: wraps modulo `2 ^ 256`, as solar-verify's specs do. -/ + | shl (e : Term) (k : Nat) + /-- `e >> k` by a literal `k`: the floor of `e / 2 ^ k`. Shifts by a computed amount are export + errors, since solar-verify encodes them through a table that differs from `2 ^ k` past 255. -/ + | shr (e : Term) (k : Nat) + /-- `c ? a : b`. -/ + | ite (c a b : Term) + /-- `forall T x :: body` (one binder; the exporter nests several). -/ + | all (x : String) (ty : Ty) (body : Term) + /-- `exists T x :: body`. -/ + | ex (x : String) (ty : Ty) (body : Term) + /-- A call of the spec function `fn`. -/ + | call (fn : String) (args : List Term) + deriving Repr, Inhabited + +/-- A storage location, resolved from the storage layout. -/ +inductive Place where + /-- A slot fixed by the layout. -/ + | slot (n : Nat) + /-- `k` slots after `base`: a struct field, or an element of a fixed-size array. -/ + | offset (base : Place) (k : Term) + /-- The entry of the mapping at `base` for the value-typed key `key`: + `keccak256(key ++ slot(base))`, both as 32-byte words. -/ + | entry (base : Place) (key : Term) + /-- Element `index` of the dynamic array at `base`, whose elements take `slots` slots each: + `keccak256(slot(base)) + index * slots`. -/ + | elem (base : Place) (index : Term) (slots : Nat) + /-- The slot holding packed element `index` of the dynamic array at `base`, `perSlot` elements to + a slot: `keccak256(slot(base)) + index / perSlot`. Its byte offset is the reader's. -/ + | packedElem (base : Place) (index : Term) (perSlot : Nat) + deriving Repr, Inhabited +end + +/-- A spec function: a single-`return` pure or view function solar-verify unfolds in specs. +An `isOpaque` one is uninterpreted in solar-verify's proofs except where revealed; its meaning +here is its body, and `ret` is the range solar-verify assumes of its result +(`Semantics.OpaqueInRange`). -/ +structure SpecFn where + name : String + params : List (String × Ty) + ret : Ty + body : Term + isOpaque : Bool + deriving Repr, Inhabited + +/-- One function's spec. -/ +structure FnSpec where + /-- `Contract.name`. -/ + name : String + /-- The 4-byte ABI selector. -/ + selector : Nat + params : List Ty + rets : List Ty + payable : Bool + requires : List Term + ensures : List Term + succeedsIf : List Term + deriving Repr, Inhabited + +/-- A contract's specs. `invariants` are the contract's `@custom:invariant`s and, expanded +by the exporter over every stored value of the struct, its structs' invariants. -/ +structure ContractSpec where + name : String + fns : List SpecFn + invariants : List Term + ghosts : List String + specs : List FnSpec + deriving Repr, Inhabited + +/-- What a spec was exported from: the source and its sha256, the compiler that built the +bytecode, its options, and the runtime bytecode's sha256. `solar-verify --emit-lean` writes it; +a theorem about the spec is about these bytes only. -/ +structure Manifest where + source : String + sourceSha256 : String + compiler : String + options : List String + bytecodeSha256 : String + deriving Repr, Inhabited, DecidableEq + +end SolidCore.Spec diff --git a/Verify/Spec/Tree.lean b/Verify/Spec/Tree.lean new file mode 100644 index 00000000..d1e9e7a2 --- /dev/null +++ b/Verify/Spec/Tree.lean @@ -0,0 +1,187 @@ +import Verify.VC.Model +import Verify.Spec.Contract + +/-! +# A spec from the erased tree, for every function of the generic source stage + +The generic source stage runs every call of a function of its fragment as the function's erased +tree (`Generic.source_run`). So a function's spec holds of SolidCore's checked contract on the +stage's calls as soon as it holds of the tree: `TreeMeets b fs ctx n T` says that from any `n` +argument words decoding to the spec's arguments, any storage of words and any pre-state on that +storage meeting the requires and the invariants, the tree's observable meets `Post` (for every +ghost state after the call, so a ghost-free spec). It speaks of the tree and the spec alone: no +SolidCore run, no ABI, no fuel. `holdsFn_of_tree` turns it into the spec's `HoldsFn` against +SolidCore on `stageScope`, which a refinement then carries to the bytecode +(`HoldsFn.of_stage`). + +No solver verdict and no encoding of solar-verify's enters: the statement is solar-verify's exported +spec (`--emit-lean-spec`) read with `Spec.eval`, and the tree is the generic stage's. +-/ + +namespace SolidCore.Spec + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Generic +open SolidCore.Solidity + +theorem bytesWord_map (l : List UInt8) : + bytesWord (l.map (·.toNat)) = EthLib.Base.bytesToNat l := by + simp [bytesWord, EthLib.Base.bytesToNat, List.foldl_map] + +theorem bytesWord_natToBytes {v : Nat} (h : v < 2 ^ 256) : + bytesWord ((EthLib.Base.natToBytes 32 v).map (·.toNat)) = v := by + rw [bytesWord_map, EthLib.Base.bytesToNat_natToBytes_of_lt] + simpa using h + +/-- A 32-byte word in front: its word, then the words of the rest. -/ +theorem words_append32 {x : List Nat} (hx : x.length = 32) (r : List Nat) : + words (x ++ r) = bytesWord x :: words r := by + unfold words + rw [List.length_append, hx, show (32 + r.length) / 32 = r.length / 32 + 1 by omega, + List.range_succ_eq_map] + simp only [List.map_cons, List.map_map, Nat.mul_zero, List.drop_zero] + refine congrArg₂ _ ?_ ?_ + · rw [List.take_append_of_le_length (by omega), List.take_of_length_le (by omega)] + · refine List.map_congr_left fun i _ => ?_ + simp only [Function.comp] + have hd : List.drop (32 + 32 * i) (x ++ r) = List.drop (32 * i) r := by + rw [← List.drop_drop, List.drop_left' hx] + rw [show 32 * (i + 1) = 32 + 32 * i by omega, hd] + +theorem words_argBytes : ∀ (args : List Nat), (∀ a ∈ args, a < 2 ^ 256) → + words (Dirty.argBytes args) = args + | [], _ => by simp [Dirty.argBytes, words] + | a :: as, h => by + have ha := h a (List.mem_cons_self ..) + have hs : Dirty.argBytes (a :: as) = (EthLib.Base.natToBytes 32 a).map (·.toNat) ++ + Dirty.argBytes as := by simp [Dirty.argBytes] + rw [hs, words_append32 (by simp [EthLib.Base.natToBytes_length]), bytesWord_natToBytes ha, + words_argBytes as fun x hx => h x (List.mem_cons_of_mem _ hx)] + +/-- The words after the selector of the stage's call data are the arguments. -/ +theorem words_calldata (sel : Nat) {args : List Nat} (h : ∀ a ∈ args, a < 2 ^ 256) : + words (((calldata sel args).data.toList.map (·.toNat)).drop 4) = args := by + rw [Dirty.bytes_calldata, Wide.drop_selector, words_argBytes args h] + +/-- What a function's spec asks of its erased tree: see the module comment. -/ +def TreeMeets (b : Bundle) (fs : FnSpec) (ctx : Ctx) (n : Nat) (T : Tree) : Prop := + ∀ (args : List Nat) (s : Storage) (iargs : List Int) (pre : State) (ghost' : Ghost), + args.length = n → (∀ a ∈ args, a < 2 ^ 256) → (∀ k, s k < 2 ^ 256) → + decodeWords fs.params args = some iargs → pre.storage = s → pre.time ≤ ctx.timestamp → + b.satAll fs.requires (mkEnv ctx iargs [] pre pre) → + b.satAll b.spec.invariants (mkEnv ctx iargs [] pre pre) → + Post b fs ctx pre ghost' (T.eval ⟨args, s, solHash, SolidCore.Refinement.Generic.callerWord⟩).obs iargs + +/-- **A function's spec holds of SolidCore's contract when it holds of the erased tree**, on +the stage's calls of the function (any argument words, no value, any storage covering the +deployed one), for a call context fixed on those calls. -/ +theorem holdsFn_of_tree {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {fn : Fn} {f : Source.FunctionDef} + (hsel : fn.sel < 2 ^ 32) (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) fuel f = some T) {b : Bundle} {fs : FnSpec} + {ctxOf : Call → Ctx} {step : GhostStep} {ctx : Ctx} + (hctx : ∀ call : Call, call.callvalue = 0 → ctxOf call = ctx) + (hm : TreeMeets b fs ctx fn.params.length T) : + HoldsFn (solidCore fuel) c (SolidCore.Verify.VC.stageScope fn s) b ctxOf step fs := by + rintro _ ⟨σ, hcov, fn', hfn', args, hl, hargs, rfl⟩ iargs pre hpre + simp only [List.mem_singleton] at hfn' + subst hfn' + have hrun := source_run hd hcov hsel hfind hT args (hl.trans hlen.symm) hargs + obtain ⟨⟨-, -, hdec⟩, hst, ht, hreq, hinv⟩ := hpre + rw [hctx _ rfl] at ht hreq hinv ⊢ + rw [words_calldata _ hargs] at hdec + exact ⟨_, hrun, hm args (slotValue σ) iargs pre _ hl hargs (fun k => Generic.slotValue_lt σ k) + hdec hst ht hreq hinv⟩ + +/-! ## Functions that leave the ghost state alone -/ + +/-- `TreeMeets` for a function whose calls leave the ghost state as it was: the post-state's +ghost state is the pre-state's. -/ +def TreeMeetsFixed (b : Bundle) (fs : FnSpec) (ctx : Ctx) (n : Nat) (T : Tree) : Prop := + ∀ (args : List Nat) (s : Storage) (iargs : List Int) (pre : State), + args.length = n → (∀ a ∈ args, a < 2 ^ 256) → (∀ k, s k < 2 ^ 256) → + decodeWords fs.params args = some iargs → pre.storage = s → pre.time ≤ ctx.timestamp → + b.satAll fs.requires (mkEnv ctx iargs [] pre pre) → + b.satAll b.spec.invariants (mkEnv ctx iargs [] pre pre) → + Post b fs ctx pre pre.ghost (T.eval ⟨args, s, solHash, SolidCore.Refinement.Generic.callerWord⟩).obs iargs + +/-- **`holdsFn_of_tree` for a function that leaves the ghost state alone**: the ghost step is the +identity on the stage's calls of the function. -/ +theorem holdsFn_of_tree_fixed {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {fn : Fn} {f : Source.FunctionDef} + (hsel : fn.sel < 2 ^ 32) (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) fuel f = some T) {b : Bundle} {fs : FnSpec} + {ctxOf : Call → Ctx} {step : GhostStep} {ctx : Ctx} + (hctx : ∀ call : Call, call.callvalue = 0 → ctxOf call = ctx) + (hstep : ∀ call, SolidCore.Verify.VC.stageScope fn s call → ∀ g, step call g = g) + (hm : TreeMeetsFixed b fs ctx fn.params.length T) : + HoldsFn (solidCore fuel) c (SolidCore.Verify.VC.stageScope fn s) b ctxOf step fs := by + intro call hcall iargs pre hpre + have hg := hstep call hcall pre.ghost + obtain ⟨σ, hcov, fn', hfn', args, hl, hargs, rfl⟩ := hcall + simp only [List.mem_singleton] at hfn' + subst hfn' + have hrun := source_run hd hcov hsel hfind hT args (hl.trans hlen.symm) hargs + obtain ⟨⟨-, -, hdec⟩, hst, ht, hreq, hinv⟩ := hpre + rw [hctx _ rfl] at ht hreq hinv ⊢ + rw [words_calldata _ hargs] at hdec + rw [hg] + exact ⟨_, hrun, hm args (slotValue σ) iargs pre hl hargs (fun k => Generic.slotValue_lt σ k) + hdec hst ht hreq hinv⟩ + +/-! ## Proving `TreeMeets` + +`tree_meets [defs]` proves `TreeMeets b fs ctx n T` for a function of at most eight parameters +and no succeeds-if conditions, unfolding `defs` (the tree, the spec bundle and the function's +spec): it names the argument words, decodes them, splits the tree's branches, evaluates the spec's +terms and the tree's words, and closes each case with `omega`. A goal it cannot close stays an +error: it never leaves a `sorry`. -/ + +macro "tree_meets" "[" ds:Lean.Parser.Tactic.simpLemma,* "]" : tactic => `(tactic| ( + intro args s iargs pre g hl hargs hs hdec hst ht hreq hinv + have hsm : ∀ k, s k % 2 ^ 256 = s k := fun k => Nat.mod_eq_of_lt (hs k) + rcases args with _ | ⟨a0, _ | ⟨a1, _ | ⟨a2, _ | ⟨a3, _ | ⟨a4, _ | ⟨a5, _ | ⟨a6, _ | ⟨a7, _ | ⟨_, _⟩⟩⟩⟩⟩⟩⟩⟩⟩ <;> + simp only [List.length_cons, List.length_nil] at hl <;> (try omega) <;> + simp only [List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, + IsEmpty.forall_iff, implies_true, and_true] at hargs <;> + simp only [$ds,*, List.head, List.getElem_cons_zero, List.getElem_cons_succ, decodeWords, Ty.ofWord, + hargs, ite_true, bind, pure, Option.bind, + Option.some.injEq] at hdec <;> + subst hdec <;> + refine ⟨fun hsucc => ?_, fun hne => ?_⟩ <;> + first + | (simp [$ds,*] at hne; done) + | (simp only [$ds,*, Tree.eval, WExpr.eval, BinOp.eval, Generic.wordSize, hsm, + List.getD_cons_zero, List.getD_cons_succ] at hsucc ⊢ + split_ifs at hsucc ⊢ <;> + simp_all [$ds,*, Res.obs, Writes.store, WExpr.eval, BinOp.eval, Bundle.satAll, Bundle.sat, + eval, slotOf, mkEnv, Env.cur, BinOp.apply, Ty.ofBits, toWord, decodeWords, words, + Generic.wordSize] <;> + omega))) + +/-- `tree_meets` for `TreeMeetsFixed`: the same steps, with the post-state's ghost state the +pre-state's. -/ +macro "tree_meets_fixed" "[" ds:Lean.Parser.Tactic.simpLemma,* "]" : tactic => `(tactic| ( + intro args s iargs pre hl hargs hs hdec hst ht hreq hinv + have hsm : ∀ k, s k % 2 ^ 256 = s k := fun k => Nat.mod_eq_of_lt (hs k) + rcases args with _ | ⟨a0, _ | ⟨a1, _ | ⟨a2, _ | ⟨a3, _ | ⟨a4, _ | ⟨a5, _ | ⟨a6, _ | ⟨a7, _ | ⟨_, _⟩⟩⟩⟩⟩⟩⟩⟩⟩ <;> + simp only [List.length_cons, List.length_nil] at hl <;> (try omega) <;> + simp only [List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, + IsEmpty.forall_iff, implies_true, and_true] at hargs <;> + simp only [$ds,*, List.head, List.getElem_cons_zero, List.getElem_cons_succ, decodeWords, Ty.ofWord, + hargs, ite_true, bind, pure, Option.bind, + Option.some.injEq] at hdec <;> + subst hdec <;> + refine ⟨fun hsucc => ?_, fun hne => ?_⟩ <;> + first + | (simp [$ds,*] at hne; done) + | (simp only [$ds,*, Tree.eval, WExpr.eval, BinOp.eval, Generic.wordSize, hsm, + List.getD_cons_zero, List.getD_cons_succ] at hsucc ⊢ + split_ifs at hsucc ⊢ <;> + simp_all [$ds,*, Res.obs, Writes.store, WExpr.eval, BinOp.eval, Bundle.satAll, Bundle.sat, + eval, slotOf, mkEnv, Env.cur, BinOp.apply, Ty.ofBits, toWord, decodeWords, words, + Generic.wordSize] <;> + omega))) + +end SolidCore.Spec diff --git a/Verify/Spec/TreeIn.lean b/Verify/Spec/TreeIn.lean new file mode 100644 index 00000000..bb2f86cc --- /dev/null +++ b/Verify/Spec/TreeIn.lean @@ -0,0 +1,76 @@ +import Verify.Spec.Tree +import SolidCore.Refinement.Generic.StageIn + +/-! +# Tree specs in every world + +`TreeMeets` speaks of a function's erased tree alone, so it says nothing about the world a call +runs in. SolidCore runs a call of a function of the generic stage's fragment as its tree in every +world `W` (`Generic.source_runIn`): a call-free function asks the world nothing. So a spec proved +of the tree (`tree_meets`, `tree_meets_map`) holds of SolidCore in every world, open or not +(`holdsFn_of_tree_in`, `holdsFn_of_tree_fixed_in`), which is what `compose_in` and +`holds_of_runs` (Verify/SourceOracle.lean) take for the source side. The closed world is +`holdsFn_of_tree` again (`solidCoreIn_closed`). +-/ + +namespace SolidCore.Spec + +open SolarTV SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Generic +open SolidCore.Solidity + +/-- **A function's spec holds of SolidCore's contract in every world when it holds of the erased +tree**, on the stage's calls of the function. -/ +theorem holdsFn_of_tree_in (W : World) {fuel : Nat} {c : TypeCheck.CheckedContract} + {d : Source.State} {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {fn : Fn} + {f : Source.FunctionDef} (hsel : fn.sel < 2 ^ 32) + (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) fuel f = some T) {b : Bundle} {fs : FnSpec} + {ctxOf : Call → Ctx} {step : GhostStep} {ctx : Ctx} + (hctx : ∀ call : Call, call.callvalue = 0 → ctxOf call = ctx) + (hm : TreeMeets b fs ctx fn.params.length T) : + HoldsFn (solidCoreIn W fuel) c (SolidCore.Verify.VC.stageScope fn s) b ctxOf step fs := by + rintro _ ⟨σ, hcov, fn', hfn', args, hl, hargs, rfl⟩ iargs pre hpre + simp only [List.mem_singleton] at hfn' + subst hfn' + have hrun := source_runIn W hd hcov hsel hfind hT args (hl.trans hlen.symm) hargs + obtain ⟨⟨-, -, hdec⟩, hst, ht, hreq, hinv⟩ := hpre + rw [hctx _ rfl] at ht hreq hinv ⊢ + rw [words_calldata _ hargs] at hdec + exact ⟨_, hrun, hm args (slotValue σ) iargs pre _ hl hargs (fun k => Generic.slotValue_lt σ k) + hdec hst ht hreq hinv⟩ + +/-- `holdsFn_of_tree_in` for a function that leaves the ghost state alone. -/ +theorem holdsFn_of_tree_fixed_in (W : World) {fuel : Nat} {c : TypeCheck.CheckedContract} + {d : Source.State} {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {fn : Fn} + {f : Source.FunctionDef} (hsel : fn.sel < 2 ^ 32) + (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) fuel f = some T) {b : Bundle} {fs : FnSpec} + {ctxOf : Call → Ctx} {step : GhostStep} {ctx : Ctx} + (hctx : ∀ call : Call, call.callvalue = 0 → ctxOf call = ctx) + (hstep : ∀ call, SolidCore.Verify.VC.stageScope fn s call → ∀ g, step call g = g) + (hm : TreeMeetsFixed b fs ctx fn.params.length T) : + HoldsFn (solidCoreIn W fuel) c (SolidCore.Verify.VC.stageScope fn s) b ctxOf step fs := by + intro call hcall iargs pre hpre + have hg := hstep call hcall pre.ghost + obtain ⟨σ, hcov, fn', hfn', args, hl, hargs, rfl⟩ := hcall + simp only [List.mem_singleton] at hfn' + subst hfn' + have hrun := source_runIn W hd hcov hsel hfind hT args (hl.trans hlen.symm) hargs + obtain ⟨⟨-, -, hdec⟩, hst, ht, hreq, hinv⟩ := hpre + rw [hctx _ rfl] at ht hreq hinv ⊢ + rw [words_calldata _ hargs] at hdec + rw [hg] + exact ⟨_, hrun, hm args (slotValue σ) iargs pre hl hargs (fun k => Generic.slotValue_lt σ k) + hdec hst ht hreq hinv⟩ + +/-- info: 'SolidCore.Spec.holdsFn_of_tree_in' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holdsFn_of_tree_in + +/-- info: 'SolidCore.Spec.holdsFn_of_tree_fixed_in' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs (whitespace := lax) in +#print axioms holdsFn_of_tree_fixed_in + +end SolidCore.Spec diff --git a/Verify/Spec/TreeMap.lean b/Verify/Spec/TreeMap.lean new file mode 100644 index 00000000..5cd3f67c --- /dev/null +++ b/Verify/Spec/TreeMap.lean @@ -0,0 +1,203 @@ +import Verify.Spec.Tree +import Verify.Spec.Hash + +/-! +# Mapping slots in tree specs + +`tree_meets` closes a function's cases by `omega` over words; a function that reads or writes a +mapping also needs to know which of its slots are equal. Those slots are SolidCore's +`solHash key slot`, which is the spec semantics' slot by `solHash_eq`. `MapSlotsSeparated ms` is +the one hypothesis: keccak256 is injective on the preimages of `m[a]` for the mapping slots +`m ∈ ms` and every address `a`, with images at least `2 ^ 128` (so apart from the scalar slots). +`map_inj` and `map_ge` give `omega` what it needs, and `hash_facts` adds their instances for +every slot term of the goal and the hypotheses. `tree_meets_map` is `tree_meets_fixed` for such +functions: it proves `TreeMeetsFixed` from `MapSlotsSeparated ms` with no other input. +-/ + +namespace SolidCore.Spec + +open SolidCore.Refinement SolidCore.Refinement.Generic + +/-- keccak256 is separated on the slots of `m[a]`, for every mapping slot `m ∈ ms` and every +address `a`. -/ +def MapSlotsSeparated (ms : List Nat) : Prop := + TrustedBase.KeccakSeparated + (fun x => ∃ a < 2 ^ 160, ∃ m ∈ ms, x = TrustedBase.mappingPreimage a m) + +theorem MapSlotsSeparated.slots {ms : List Nat} (h : MapSlotsSeparated ms) {m : Nat} + (hm : m ∈ ms) : SlotsSeparated m := + h.mono fun _ ⟨a, ha, hx⟩ => ⟨a, ha, m, hm, hx⟩ + +/-- One mapping's separation is `SlotsSeparated`. -/ +theorem mapSlotsSeparated_singleton (m : Nat) : MapSlotsSeparated [m] ↔ SlotsSeparated m := by + unfold MapSlotsSeparated SlotsSeparated + constructor + · intro h; exact h.mono fun _ ⟨a, ha, hx⟩ => ⟨a, ha, m, List.mem_singleton_self m, hx⟩ + · intro h + refine h.mono fun x ⟨a, ha, n, hn, hx⟩ => ⟨a, ha, ?_⟩ + rw [List.mem_singleton] at hn + exact hn ▸ hx + +/-- Two slots of separated mappings are equal only for the same key and mapping. -/ +theorem map_inj {ms : List Nat} (h : MapSlotsSeparated ms) {m n : Nat} (hm : m ∈ ms) (hn : n ∈ ms) + (hmw : m < 2 ^ 256) (hnw : n < 2 ^ 256) (a b : Nat) : + a < 2 ^ 160 → b < 2 ^ 160 → solHash a m = solHash b n → a = b ∧ m = n := by + intro ha hb he + rw [solHash_eq, solHash_eq] at he + have := h.1 _ _ ⟨a, ha, m, hm, rfl⟩ ⟨b, hb, n, hn, rfl⟩ he + unfold TrustedBase.mappingPreimage at this + obtain ⟨h1, h2⟩ := List.append_inj this (by simp [length_wordBytes]) + have e1 := congrArg bytesWord h1 + have e2 := congrArg bytesWord h2 + rw [bytesWord_wordBytes, bytesWord_wordBytes] at e1 e2 + omega + +/-- A slot of a separated mapping is at least `2 ^ 128`. -/ +theorem map_ge {ms : List Nat} (h : MapSlotsSeparated ms) {m : Nat} (hm : m ∈ ms) (a : Nat) : + a < 2 ^ 160 → 2 ^ 128 ≤ solHash a m := by + intro ha + rw [solHash_eq] + exact h.2 _ ⟨a, ha, m, hm, rfl⟩ + +theorem solHash_lt' (a b : Nat) : + solHash a b < 115792089237316195423570985008687907853269984665640564039457584007913129639936 := + solHash_lt a b + +theorem keccak_solHash (k s : Nat) : keccakWord (wordBytes k ++ wordBytes s) = solHash k s := + (solHash_eq k s).symm + +theorem toNat_natCast_emod {a n : Nat} (h : a < n) : ((a : Int) % (n : Int)).toNat = a := by + rw [← Int.natCast_emod, Int.toNat_natCast, Nat.mod_eq_of_lt h] + +theorem toNat_ofNat_emod (a n : Nat) [a.AtLeastTwo] : + ((OfNat.ofNat a : Int) % (n : Int)).toNat = a % n := by + rw [show (OfNat.ofNat a : Int) = ((a : Nat) : Int) from rfl, ← Int.natCast_emod, Int.toNat_natCast] + +theorem toNat_zero_emod (n : Nat) : ((0 : Int) % (n : Int)).toNat = 0 := by simp +theorem toNat_one_emod (n : Nat) : ((1 : Int) % (n : Int)).toNat = 1 % n := by + rw [show (1 : Int) = ((1 : Nat) : Int) from rfl, ← Int.natCast_emod, Int.toNat_natCast] + +theorem ite_mod_nat {P : Prop} [Decidable P] (a b n : Nat) : + (if P then a else b) % n = if P then a % n else b % n := by split <;> rfl + +theorem ite10_eq_zero_iff {P : Prop} [Decidable P] : ((if P then 1 else 0) : Nat) = 0 ↔ ¬ P := by + split <;> simp_all + +/-- An address-ranged quantifier over integers is one over naturals. -/ +theorem forall_int_range {P : Int → Prop} (b : Nat) : + (∀ v : Int, 0 ≤ v ∧ v < 2 ^ b → P v) ↔ ∀ n : Nat, n < 2 ^ b → P n := by + constructor + · intro h n hn; exact h n ⟨Int.natCast_nonneg n, by exact_mod_cast hn⟩ + · intro h v hv + obtain ⟨n, rfl⟩ := Int.eq_ofNat_of_zero_le hv.1 + exact h n (by exact_mod_cast hv.2) + +/-- `map_inj` for any two of the mappings, as `hash_facts` instantiates it. -/ +theorem map_inj' {ms : List Nat} (h : MapSlotsSeparated ms) (m n : Nat) (hm : m ∈ ms) (hn : n ∈ ms) + (hmw : m < 2 ^ 256) (hnw : n < 2 ^ 256) (a b : Nat) : + a < 2 ^ 160 → b < 2 ^ 160 → solHash a m = solHash b n → a = b ∧ m = n := + map_inj h hm hn hmw hnw a b + +theorem map_ge' {ms : List Nat} (h : MapSlotsSeparated ms) (m : Nat) (hm : m ∈ ms) (a : Nat) : + a < 2 ^ 160 → 2 ^ 128 ≤ solHash a m := + map_ge h hm a + +open Lean Meta Elab Tactic in +/-- `hash_facts H s hinj hge hlt hs`, with `H` the slot hash (generalized from `solHash`) and `s` +the storage: for every term `H x y` of the goal and the hypotheses, `hlt x y : H x y < 2 ^ 256` +and, when `decide` shows `y` is one of the separated mappings, `hge y _ x : x < 2 ^ 160 → +2 ^ 128 ≤ H x y` and, with every other such `H x' y'`, `hinj y y' _ _ _ _ x x' : x < 2 ^ 160 → +x' < 2 ^ 160 → H x y = H x' y' → x = x' ∧ y = y'`; and `hs x : s x < 2 ^ 256` for every +term `s x`. Each is an instance of a hypothesis; one whose side conditions `decide` does not show +is left out. -/ +elab "hash_facts " H:ident s:ident hinj:ident hge:ident hlt:ident hs:ident : tactic => do + let (ts, ss) ← withMainContext do + let He ← getFVarFromUserName H.getId + let se ← getFVarFromUserName s.getId + let mut es := #[← instantiateMVars (← getMainTarget)] + for d in (← getLCtx) do + if d.isImplementationDetail then continue + es := es.push (← instantiateMVars d.type) + let tr ← IO.mkRef (#[] : Array Expr) + let sr ← IO.mkRef (#[] : Array Expr) + for e in es do + e.forEachWhere (fun t => t.getAppFn == He && t.getAppNumArgs == 2 && !t.hasLooseBVars) + fun t => tr.modify fun a => if a.contains t then a else a.push t + e.forEachWhere (fun t => t.isApp && t.appFn! == se && !t.hasLooseBVars) + fun t => sr.modify fun a => if a.contains t.appArg! then a else a.push t.appArg! + pure (← tr.get, ← sr.get) + for t in ts do + withMainContext do + let x ← Term.exprToSyntax t.appFn!.appArg! + let y ← Term.exprToSyntax t.appArg! + evalTactic (← `(tactic| have := $hlt $x $y)) + evalTactic (← `(tactic| try have := $hge $y (by decide) $x)) + for x in ss do + withMainContext do + let x ← Term.exprToSyntax x + evalTactic (← `(tactic| try have := $hs $x)) + for i in [0:ts.size] do + for j in [i+1:ts.size] do + withMainContext do + let x1 ← Term.exprToSyntax ts[i]!.appFn!.appArg! + let y1 ← Term.exprToSyntax ts[i]!.appArg! + let x2 ← Term.exprToSyntax ts[j]!.appFn!.appArg! + let y2 ← Term.exprToSyntax ts[j]!.appArg! + evalTactic (← `(tactic| try have := $hinj $y1 $y2 (by decide) (by decide) (by decide) (by decide) $x1 $x2)) + + +/-- \`tree_meets_map [defs] hsep\` proves \`TreeMeetsFixed b fs ctx n T\` for a function of at most eight +parameters that reads and writes mappings keyed by addresses at the slots \`ms\`, from +\`hsep : MapSlotsSeparated ms\`, unfolding \`defs\` (the tree, the spec bundle, the function's spec and +the call context). It decodes the argument words, generalizes the slot hash \`solHash\` to a +variable \`H\` (so no step evaluates keccak256), evaluates the tree and the spec's terms, splits +every branch, and closes each case by \`omega\` with \`hash_facts\`'s instances of \`map_inj\`, +\`map_ge\` and the word bounds. A case it cannot close stays an error: it never leaves a \`sorry\`. -/ +macro "tree_meets_map" "[" ds:Lean.Parser.Tactic.simpLemma,* "]" hsep:term:max : tactic => `(tactic| ( + intro args s iargs pre hl hargs hs hdec hst ht hreq hinv + simp only [Nat.reducePow] at hs + rcases args with _ | ⟨a0, _ | ⟨a1, _ | ⟨a2, _ | ⟨a3, _ | ⟨a4, _ | ⟨a5, _ | ⟨a6, _ | ⟨a7, _ | ⟨_, _⟩⟩⟩⟩⟩⟩⟩⟩⟩ <;> + simp only [List.length_cons, List.length_nil] at hl <;> (try omega) <;> + simp only [List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, + IsEmpty.forall_iff, implies_true, and_true, Nat.reducePow] at hargs <;> + simp only [$ds,*, List.head, List.getElem_cons_zero, List.getElem_cons_succ, decodeWords, Ty.ofWord, + bind, pure, Option.bind, Nat.reducePow] at hdec <;> + split_ifs at hdec <;> simp only [Option.some.injEq, reduceCtorEq] at hdec <;> + subst hdec <;> + have hinj := map_inj' $hsep <;> have hge := map_ge' $hsep <;> have hlt := solHash_lt' <;> + have hkec := keccak_solHash <;> + generalize solHash = H at hinj hge hlt hkec ⊢ <;> + refine ⟨fun hsucc => ?_, fun hne => ?_⟩ + all_goals try (simp [$ds,*] at hne; done) + all_goals simp only [$ds,*, Tree.eval, WExpr.eval, BinOp.eval, UnOp.eval, Generic.wordSize, Res.obs, + Writes.store, List.getD_cons_zero, List.getD_cons_succ, Nat.reducePow] at hsucc ⊢ + all_goals simp (disch := simp only [hargs, hs, hlt, Nat.reduceLT]) only [Nat.mod_eq_of_lt, ite_mod_nat, + Nat.reduceMod, Nat.zero_mod, ite10_eq_zero_iff, Decidable.not_not] at hsucc ⊢ + all_goals split_ifs at hsucc ⊢ + all_goals simp only [Bool.false_eq_true, Bool.true_eq_false, imp_false, not_true_eq_false, + IsEmpty.forall_iff] at hsucc + all_goals simp only [$ds,*, OByte.eval, WExpr.eval, Generic.wordSize, words, bytesWord, decodeWords, Ty.ofWord, + List.map_cons, List.map_nil, List.length_cons, List.length_nil, List.range_succ, List.range_zero, + List.nil_append, List.cons_append, List.drop_zero, List.take_succ_cons, List.take_zero, List.foldl_cons, + List.foldl_nil, Nat.reduceDiv, Nat.reducePow, Nat.reduceMod, Nat.reduceSub, Nat.reduceMul, Nat.reduceAdd, + Nat.reduceLT, ite_true, ite_false, List.getElem_cons_succ, List.getElem_cons_zero, Option.some.injEq, + exists_eq_left', bind, pure, Option.bind, Ty.InRange, Nat.cast_ofNat, Nat.zero_add, + Nat.reduceLeDiff] at hsucc ⊢ + all_goals try clear hsucc + all_goals try refine ⟨?_, ?_⟩ + all_goals simp only [Bundle.satAll, Bundle.sat, $ds,*, List.getElem_cons_succ, List.getElem_cons_zero, + List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, eval, evalList, slotOf, mkEnv, + Env.cur, Env.bind, BinOp.apply, Ty.ofBits, toWord, List.getD_cons_zero, List.getD_cons_succ, + List.lookup, hkec, ofProp_ne_zero, ite_true, ite_false, Bool.false_eq_true, Nat.zero_mod, hst, + beq_self_eq_true, Ty.InRange, Option.getD_some, forall_int_range, Nat.cast_ofNat] at hinv ⊢ + all_goals simp only [wordMod, Nat.reducePow] at hinv ⊢ + all_goals simp (disch := first | exact hlt _ _ | exact hs _ | omega) only [Nat.mod_eq_of_lt, + toNat_natCast_emod] at hinv ⊢ + all_goals simp (disch := first | exact hlt _ _ | exact hs _ | omega) only [Nat.cast_ofNat, + Int.reduceMod, Int.reduceToNat, Nat.mod_eq_of_lt, toNat_natCast_emod, toNat_ofNat_emod, + toNat_zero_emod, toNat_one_emod, wordMod, Nat.reducePow, Nat.reduceMul, Nat.reduceMod, Nat.div_one, + Nat.reduceDiv, Int.reducePow] at hinv ⊢ + all_goals (repeat' (first | (apply And.intro) | intro)) + all_goals (hash_facts H s hinj hge hlt hs; split_ifs <;> omega))) + +end SolidCore.Spec diff --git a/Verify/Spec/TreeMapNested.lean b/Verify/Spec/TreeMapNested.lean new file mode 100644 index 00000000..2474f7d4 --- /dev/null +++ b/Verify/Spec/TreeMapNested.lean @@ -0,0 +1,327 @@ +import Verify.Spec.TreeMap + +/-! +# Nested mapping slots in tree specs + +`tree_meets_map` (TreeMap.lean) knows the slots `m[a]` of mappings at literal slots. A mapping of +mappings at slot `n`, such as an ERC20 allowance `allowance[o][s]`, stores at +`solHash s (solHash o n)`, whose mapping slot is itself a hash. `NestedSlotsSeparated ms ns` is +the one hypothesis for both kinds: keccak256 is separated (injective, every image at least +`2 ^ 128`) on the preimages of `m[a]` for `m ∈ ms ++ ns` and of `n[b][a]` for `n ∈ ns`, for all +addresses `a` and `b`. It is `MapSlotsSeparated (ms ++ ns)` with the second level added and, like +it, a premise of the theorems that use it, never an axiom. + +`nmap_inj_ln`, `nmap_inj_nn` and `nmap_ge_n` say when second-level slots are equal to others; +`hash_facts_nested` instantiates them for every pair of slot terms of the goal and the +hypotheses, beside `hash_facts`'s first-level instances. `tree_meets_map2` is `tree_meets_map` with +both: it proves `TreeMeetsFixed` from `NestedSlotsSeparated ms ns` with no other input, or fails. +-/ + +namespace SolidCore.Spec + +open SolidCore.Refinement SolidCore.Refinement.Generic + +/-- keccak256 is separated on the slots of `m[a]` for `m ∈ ms ++ ns` and of `n[b][a]` for `n ∈ ns`, +for all addresses `a` and `b`. -/ +def NestedSlotsSeparated (ms ns : List Nat) : Prop := + TrustedBase.KeccakSeparated (fun x => ∃ a < 2 ^ 160, + (∃ m ∈ ms ++ ns, x = TrustedBase.mappingPreimage a m) ∨ + ∃ b < 2 ^ 160, ∃ n ∈ ns, x = TrustedBase.mappingPreimage a (solHash b n)) + +/-- Equal preimages of two mapping slots have equal keys and equal mapping slots. -/ +theorem mappingPreimage_inj {a b m n : Nat} (ha : a < 2 ^ 256) (hb : b < 2 ^ 256) + (hm : m < 2 ^ 256) (hn : n < 2 ^ 256) + (h : TrustedBase.mappingPreimage a m = TrustedBase.mappingPreimage b n) : a = b ∧ m = n := by + unfold TrustedBase.mappingPreimage at h + obtain ⟨h1, h2⟩ := List.append_inj h (by simp [length_wordBytes]) + have e1 := congrArg bytesWord h1 + have e2 := congrArg bytesWord h2 + rw [bytesWord_wordBytes, bytesWord_wordBytes] at e1 e2 + omega + +/-- The first level of the nested hypothesis. -/ +theorem NestedSlotsSeparated.flat {ms ns : List Nat} (h : NestedSlotsSeparated ms ns) : + MapSlotsSeparated (ms ++ ns) := + h.mono fun _ ⟨a, ha, m, hm, hx⟩ => ⟨a, ha, .inl ⟨m, hm, hx⟩⟩ + +/-- A second-level slot is at least `2 ^ 128`. -/ +theorem nmap_ge_n {ms ns : List Nat} (h : NestedSlotsSeparated ms ns) (n : Nat) (hn : n ∈ ns) + (a c : Nat) : a < 2 ^ 160 → c < 2 ^ 160 → 2 ^ 128 ≤ solHash a (solHash c n) := by + intro ha hc + rw [solHash_eq a] + exact h.2 _ ⟨a, ha, .inr ⟨c, hc, n, hn, rfl⟩⟩ + +/-- A first-level slot of a small mapping slot is no second-level slot. -/ +theorem nmap_inj_ln {ms ns : List Nat} (h : NestedSlotsSeparated ms ns) (m n : Nat) + (hm : m ∈ ms ++ ns) (hn : n ∈ ns) (hmw : m < 2 ^ 128) (a b c : Nat) : + a < 2 ^ 160 → b < 2 ^ 160 → c < 2 ^ 160 → solHash a m = solHash b (solHash c n) → False := by + intro ha hb hc he + rw [solHash_eq a, solHash_eq b] at he + have := h.1 _ _ ⟨a, ha, .inl ⟨m, hm, rfl⟩⟩ ⟨b, hb, .inr ⟨c, hc, n, hn, rfl⟩⟩ he + obtain ⟨-, e⟩ := mappingPreimage_inj (by omega) (by omega) (by omega) (solHash_lt _ _) this + have hge := map_ge' h.flat n (List.mem_append_right ms hn) c hc + omega + +/-- Two second-level slots are equal only for the same keys and mapping. -/ +theorem nmap_inj_nn {ms ns : List Nat} (h : NestedSlotsSeparated ms ns) (n n' : Nat) (hn : n ∈ ns) + (hn' : n' ∈ ns) (hnw : n < 2 ^ 256) (hnw' : n' < 2 ^ 256) (a b c d : Nat) : + a < 2 ^ 160 → b < 2 ^ 160 → c < 2 ^ 160 → d < 2 ^ 160 → + solHash a (solHash c n) = solHash b (solHash d n') → a = b ∧ c = d ∧ n = n' := by + intro ha hb hc hd he + rw [solHash_eq a, solHash_eq b] at he + have := h.1 _ _ ⟨a, ha, .inr ⟨c, hc, n, hn, rfl⟩⟩ ⟨b, hb, .inr ⟨d, hd, n', hn', rfl⟩⟩ he + obtain ⟨e1, e2⟩ := mappingPreimage_inj (by omega) (by omega) (solHash_lt _ _) (solHash_lt _ _) this + obtain ⟨e3, e4⟩ := map_inj' h.flat n n' (List.mem_append_right ms hn) (List.mem_append_right ms hn') + hnw hnw' c d hc hd e2 + exact ⟨e1, e3, e4⟩ + +/-- A natural number's cast modulo an integer literal, back in the naturals. -/ +theorem toNat_natCast_emod_ofNat (a N : Nat) [N.AtLeastTwo] : + ((a : Int) % (OfNat.ofNat N : Int)).toNat = a % N := by + rw [show (OfNat.ofNat N : Int) = ((N : Nat) : Int) from rfl, ← Int.natCast_emod, Int.toNat_natCast] + +/-- A word's cast modulo `2 ^ 256`, back in the naturals. -/ +theorem toNat_natCast_emod_word {a : Nat} (h : a < 2 ^ 256) : + ((a : Int) % 115792089237316195423570985008687907853269984665640564039457584007913129639936).toNat = a := by + omega + +open Lean Meta Elab Tactic in +/-- `hash_facts_nested H hgn hln hnn`, with `H` the slot hash: for every second-level term +`H x (H c n)` of the goal and the hypotheses, `hgn n _ x c`; with every first-level term `H x' m`, +`hln m n _ _ _ x' x c`; with every other second-level term `H x' (H c' n')`, +`hnn n n' _ _ _ _ x x' c c'`. Each is an instance of a hypothesis; one whose side conditions +`decide` does not show is left out. -/ +elab "hash_facts_nested " H:ident hgn:ident hln:ident hnn:ident : tactic => do + let ts ← withMainContext do + let He ← getFVarFromUserName H.getId + let mut es := #[← instantiateMVars (← getMainTarget)] + for d in (← getLCtx) do + if d.isImplementationDetail then continue + es := es.push (← instantiateMVars d.type) + let tr ← IO.mkRef (#[] : Array Expr) + for e in es do + e.forEachWhere (fun t => t.getAppFn == He && t.getAppNumArgs == 2 && !t.hasLooseBVars) + fun t => tr.modify fun a => if a.contains t then a else a.push t + pure (← tr.get, He) + let (ts, He) := ts + let isNested (t : Expr) : Bool := + let y := t.appArg! + y.getAppFn == He && y.getAppNumArgs == 2 + for i in [0:ts.size] do + let t := ts[i]! + if !isNested t then continue + withMainContext do + let x ← Term.exprToSyntax t.appFn!.appArg! + let c ← Term.exprToSyntax t.appArg!.appFn!.appArg! + let n ← Term.exprToSyntax t.appArg!.appArg! + evalTactic (← `(tactic| try have := $hgn $n (by decide) $x $c)) + for j in [0:ts.size] do + if i == j then continue + let u := ts[j]! + withMainContext do + let x ← Term.exprToSyntax t.appFn!.appArg! + let c ← Term.exprToSyntax t.appArg!.appFn!.appArg! + let n ← Term.exprToSyntax t.appArg!.appArg! + let x2 ← Term.exprToSyntax u.appFn!.appArg! + if isNested u then + if i < j then + let c2 ← Term.exprToSyntax u.appArg!.appFn!.appArg! + let n2 ← Term.exprToSyntax u.appArg!.appArg! + evalTactic (← `(tactic| try have := $hnn $n $n2 (by decide) (by decide) (by decide) (by decide) $x $x2 $c $c2)) + else + let m ← Term.exprToSyntax u.appArg! + evalTactic (← `(tactic| try have := $hln $m $n (by decide) (by decide) (by decide) $x2 $x $c)) + + +open Lean Meta Elab Tactic in +/-- `inst_foralls`: split every conjunction among the hypotheses, then instantiate every hypothesis +`∀ x : Nat, x < b → P x` (a quantified clause of an invariant, such as `allowance[address(0)][s] == 0` +for every address `s`) at every natural-number variable of the context, its bound discharged by +`omega`. Each instance is a consequence of a hypothesis; one whose bound `omega` does not show is +left out. -/ +elab "inst_foralls" : tactic => do + -- Split every conjunction once (its parts too), keeping the original. + let done ← IO.mkRef (#[] : Array FVarId) + for _ in [0:64] do + let next ← withMainContext do + let seen ← done.get + let mut r := none + for d in (← getLCtx) do + if d.isImplementationDetail || seen.contains d.fvarId then continue + if (← instantiateMVars d.type).isAppOfArity `And 2 then + r := some d.fvarId + break + pure r + let some h := next | break + done.modify (·.push h) + withMainContext do + let hs ← Term.exprToSyntax (mkFVar h) + evalTactic (← `(tactic| have := ($hs).1)) + evalTactic (← `(tactic| have := ($hs).2)) + let (fs, vs) ← withMainContext do + let mut fs := #[] + let mut vs := #[] + for d in (← getLCtx) do + if d.isImplementationDetail then continue + let ty ← whnfR (← instantiateMVars d.type) + if ty.isForall && ty.bindingDomain!.isConstOf `Nat && ty.bindingBody!.hasLooseBVars && + ty.bindingBody!.isForall && (ty.bindingBody!.bindingDomain!.isAppOfArity `LT.lt 4 || + ty.bindingBody!.bindingDomain!.isAppOfArity `LE.le 4) then + fs := fs.push d.fvarId + else if (← instantiateMVars d.type).isConstOf `Nat then + vs := vs.push d.fvarId + pure (fs, vs) + for f in fs do + for v in vs do + withMainContext do + let fe ← Term.exprToSyntax (mkFVar f) + let ve ← Term.exprToSyntax (mkFVar v) + evalTactic (← `(tactic| first | have := $fe $ve (by omega) | skip)) + + +open Lean Meta Elab Tactic in +/-- `hash_bounds H s hlt hs`: for every slot term `H x y` of the goal and the hypotheses, +`hlt x y : H x y < 2 ^ 256`, and for every storage read `s x`, `hs x : s x < 2 ^ 256`: word bounds only, no +implication, so `omega` stays linear in them. -/ +elab "hash_bounds " H:ident s:ident hlt:ident hs:ident : tactic => do + let (ts, ss) ← withMainContext do + let He ← getFVarFromUserName H.getId + let se ← getFVarFromUserName s.getId + let mut es := #[← instantiateMVars (← getMainTarget)] + for d in (← getLCtx) do + if d.isImplementationDetail then continue + es := es.push (← instantiateMVars d.type) + let tr ← IO.mkRef (#[] : Array Expr) + let sr ← IO.mkRef (#[] : Array Expr) + for e in es do + e.forEachWhere (fun t => t.getAppFn == He && t.getAppNumArgs == 2 && !t.hasLooseBVars) + fun t => tr.modify fun a => if a.contains t then a else a.push t + e.forEachWhere (fun t => t.isApp && t.appFn! == se && !t.hasLooseBVars) + fun t => sr.modify fun a => if a.contains t.appArg! then a else a.push t.appArg! + pure (← tr.get, ← sr.get) + for t in ts do + withMainContext do + let x ← Term.exprToSyntax t.appFn!.appArg! + let y ← Term.exprToSyntax t.appArg! + evalTactic (← `(tactic| have := $hlt $x $y)) + for x in ss do + withMainContext do + let x ← Term.exprToSyntax x + evalTactic (← `(tactic| try have := $hs $x)) + +open Lean Meta Elab Tactic in +/-- `hash_eqs H hinj hge hgn hln hnn`: for every hypothesis that equates a slot term `H x y` with +another one (a branch of the tree or of the spec where two slots coincide), the consequence the +separation gives: the keys and mapping slots are equal (`hinj`, `hnn`) or there is no such branch +(`hln`); and for one equating a slot term with anything else, that the slot is at least `2 ^ 128` +(`hge`, `hgn`). Address bounds are discharged by `omega`, membership by `decide`; an instance +whose side conditions do not hold is left out. Only equalities present in the context are used, so +the facts grow with the branch, not with the square of the slot terms. -/ +elab "hash_eqs " H:ident hinj:ident hge:ident hgn:ident hln:ident hnn:ident : tactic => do + let eqs ← withMainContext do + let He ← getFVarFromUserName H.getId + let isH (t : Expr) : Bool := t.getAppFn == He && t.getAppNumArgs == 2 + let mut acc := #[] + for d in (← getLCtx) do + if d.isImplementationDetail then continue + let ty ← instantiateMVars d.type + if let some (_, l, r) := ty.eq? then + if (isH l || isH r) && !ty.hasLooseBVars then acc := acc.push (d.fvarId, l, r) + pure (acc, He) + let (eqs, He) := eqs + let isH (t : Expr) : Bool := t.getAppFn == He && t.getAppNumArgs == 2 + let isN (t : Expr) : Bool := isH t && isH t.appArg! + for (h, l, r) in eqs do + withMainContext do + let hs ← Term.exprToSyntax (mkFVar h) + let k (t : Expr) := Term.exprToSyntax t.appFn!.appArg! + let m (t : Expr) := Term.exprToSyntax t.appArg! + let c (t : Expr) := Term.exprToSyntax t.appArg!.appFn!.appArg! + let n (t : Expr) := Term.exprToSyntax t.appArg!.appArg! + if isH l && isH r then + if !isN l && !isN r then + let (x, y, x2, y2) := (← k l, ← m l, ← k r, ← m r) + evalTactic (← `(tactic| try (have e := $hinj $y $y2 (by decide) (by decide) (by decide) (by decide) $x $x2 (by omega) (by omega) $hs; have := e.1; have := e.2; clear e))) + else if !isN l && isN r then + let (x, y, x2, c2, n2) := (← k l, ← m l, ← k r, ← c r, ← n r) + evalTactic (← `(tactic| try have := $hln $y $n2 (by decide) (by decide) (by decide) $x $x2 $c2 (by omega) (by omega) (by omega) $hs)) + else if isN l && !isN r then + let (x, c1, n1, x2, y2) := (← k l, ← c l, ← n l, ← k r, ← m r) + evalTactic (← `(tactic| try have := $hln $y2 $n1 (by decide) (by decide) (by decide) $x2 $x $c1 (by omega) (by omega) (by omega) ($hs).symm)) + else + let (x, c1, n1, x2, c2, n2) := (← k l, ← c l, ← n l, ← k r, ← c r, ← n r) + evalTactic (← `(tactic| try (have e := $hnn $n1 $n2 (by decide) (by decide) (by decide) (by decide) $x $x2 $c1 $c2 (by omega) (by omega) (by omega) (by omega) $hs; have := e.1; have := e.2.1; have := e.2.2; clear e))) + for t in [l, r] do + if isN t then + let (x, c1, n1) := (← k t, ← c t, ← n t) + evalTactic (← `(tactic| try have := $hgn $n1 (by decide) $x $c1 (by omega) (by omega))) + else if isH t then + let (x, y) := (← k t, ← m t) + evalTactic (← `(tactic| try have := $hge $y (by decide) $x (by omega))) + +/-- `tree_meets_map2 [defs] hsep` is `tree_meets_map` for functions that also read and write +mappings of mappings keyed by addresses at the slots `ns`, from `hsep : NestedSlotsSeparated ms ns`: +`hash_facts` instantiates the first level (`map_inj`, `map_ge` of `ms ++ ns`) and +`hash_facts_nested` the second. A case it cannot close stays an error: it never leaves a `sorry`. -/ +macro "tree_meets_map2" "[" ds:Lean.Parser.Tactic.simpLemma,* "]" hsep:term:max : tactic => `(tactic| ( + intro args s iargs pre hl hargs hs hdec hst ht hreq hinv + simp only [Nat.reducePow] at hs + rcases args with _ | ⟨a0, _ | ⟨a1, _ | ⟨a2, _ | ⟨a3, _ | ⟨a4, _ | ⟨a5, _ | ⟨a6, _ | ⟨a7, _ | ⟨_, _⟩⟩⟩⟩⟩⟩⟩⟩⟩ <;> + simp only [List.length_cons, List.length_nil] at hl <;> (try omega) <;> + simp only [List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, + IsEmpty.forall_iff, implies_true, and_true, Nat.reducePow] at hargs <;> + simp only [$ds,*, List.head, List.getElem_cons_zero, List.getElem_cons_succ, decodeWords, Ty.ofWord, + bind, pure, Option.bind, Nat.reducePow] at hdec <;> + split_ifs at hdec <;> simp only [Option.some.injEq, reduceCtorEq] at hdec <;> + subst hdec <;> + have hinj := map_inj' (NestedSlotsSeparated.flat $hsep) <;> + have hge := map_ge' (NestedSlotsSeparated.flat $hsep) <;> + have hgn := nmap_ge_n $hsep <;> have hln := nmap_inj_ln $hsep <;> have hnn := nmap_inj_nn $hsep <;> + have hlt := solHash_lt' <;> + have hkec := keccak_solHash <;> + generalize solHash = H at hinj hge hgn hln hnn hlt hkec ⊢ <;> + refine ⟨fun hsucc => ?_, fun hne => ?_⟩ + all_goals try (simp [$ds,*] at hne; done) + all_goals simp only [$ds,*, Tree.eval, WExpr.eval, BinOp.eval, UnOp.eval, Generic.wordSize, Res.obs, + Writes.store, List.getD_cons_zero, List.getD_cons_succ, Nat.reducePow] at hsucc ⊢ + all_goals simp (disch := simp only [hargs, hs, hlt, Nat.reduceLT]) only [Nat.mod_eq_of_lt, ite_mod_nat, + Nat.reduceMod, Nat.zero_mod, ite10_eq_zero_iff, Decidable.not_not] at hsucc ⊢ + all_goals split_ifs at hsucc ⊢ + all_goals simp only [Bool.false_eq_true, Bool.true_eq_false, imp_false, not_true_eq_false, + IsEmpty.forall_iff] at hsucc + all_goals simp only [$ds,*, OByte.eval, WExpr.eval, Generic.wordSize, words, bytesWord, decodeWords, Ty.ofWord, + List.map_cons, List.map_nil, List.length_cons, List.length_nil, List.range_succ, List.range_zero, + List.nil_append, List.cons_append, List.drop_zero, List.take_succ_cons, List.take_zero, List.foldl_cons, + List.foldl_nil, Nat.reduceDiv, Nat.reducePow, Nat.reduceMod, Nat.reduceSub, Nat.reduceMul, Nat.reduceAdd, + Nat.reduceLT, ite_true, ite_false, List.getElem_cons_succ, List.getElem_cons_zero, Option.some.injEq, + exists_eq_left', bind, pure, Option.bind, Ty.InRange, Nat.cast_ofNat, Nat.zero_add, + Nat.reduceLeDiff] at hsucc ⊢ + all_goals try clear hsucc + all_goals try refine ⟨?_, ?_⟩ + all_goals simp only [Bundle.satAll, Bundle.sat, $ds,*, List.getElem_cons_succ, List.getElem_cons_zero, + List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, eval, evalList, slotOf, mkEnv, + Env.cur, Env.bind, BinOp.apply, Ty.ofBits, toWord, List.getD_cons_zero, List.getD_cons_succ, + List.lookup, hkec, ofProp_ne_zero, ite_true, ite_false, Bool.false_eq_true, Nat.zero_mod, hst, + beq_self_eq_true, Ty.InRange, Option.getD_some, forall_int_range, Nat.cast_ofNat, + String.reduceBEq, Bool.false_eq_true] at hinv ⊢ + all_goals simp only [wordMod, Nat.reducePow] at hinv ⊢ + all_goals simp (disch := first | exact hlt _ _ | exact hs _ | omega) only [Nat.mod_eq_of_lt, + toNat_natCast_emod] at hinv ⊢ + all_goals simp (disch := first | exact hlt _ _ | exact hs _ | omega) only [Nat.cast_ofNat, + Int.reduceMod, Int.reduceToNat, Nat.mod_eq_of_lt, toNat_natCast_emod, toNat_ofNat_emod, + toNat_zero_emod, toNat_one_emod, wordMod, Nat.reducePow, Nat.reduceMul, Nat.reduceMod, Nat.div_one, + Nat.reduceDiv, Int.reducePow] at hinv ⊢ + all_goals (repeat' (first | (apply And.intro) | intro)) + all_goals (try simp only [toNat_natCast_emod_ofNat] at hinv ⊢) + all_goals (try simp (disch := first | exact hlt _ _ | exact hs _ | omega) only [Nat.mod_eq_of_lt, + toNat_natCast_emod_word, toNat_natCast_emod, Int.toNat_natCast, Nat.cast_inj, Nat.cast_le, Nat.cast_lt] at hinv ⊢) + all_goals inst_foralls + all_goals (try simp (disch := omega) only [toNat_natCast_emod_word, Int.toNat_natCast, Nat.cast_inj] at *) + all_goals hash_bounds H s hlt hs + all_goals ((try split_ifs) <;> (try simp only [Nat.cast_inj] at *) <;> (hash_eqs H hinj hge hgn hln hnn; (try subst_vars); first | contradiction | omega)))) + +/-- info: 'SolidCore.Spec.nmap_inj_nn' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms nmap_inj_nn + +end SolidCore.Spec diff --git a/Verify/Spec/TreeSplit.lean b/Verify/Spec/TreeSplit.lean new file mode 100644 index 00000000..7a1585ac --- /dev/null +++ b/Verify/Spec/TreeSplit.lean @@ -0,0 +1,148 @@ +import Verify.Spec.TreeMapNested + +/-! +# Tree specs by cases on a tree's tests + +`TreeMeetsFixedOn P` is `TreeMeetsFixed` on the evaluations that meet `P`. `TreeMeetsFixedOn.ite` +splits a tree's test into its two branches, each with the test's outcome added to `P`, so a spec of a +tree with many paths is proved as several smaller theorems, one per branch, each its own kernel +check. `tree_meets_map2_on` is `tree_meets_map2` for one branch: it reads the branch's tests from +`P` beside the other hypotheses. Nothing here is trusted: a case it cannot close is an error. +-/ + +namespace SolidCore.Spec + +open SolidCore.Refinement SolidCore.Refinement.Generic + +/-- `TreeMeetsFixed` on the evaluations that meet `P`. -/ +def TreeMeetsFixedOn (P : Val → Prop) (b : Bundle) (fs : FnSpec) (ctx : Ctx) (n : Nat) (T : Tree) : + Prop := + ∀ (args : List Nat) (s : Storage) (iargs : List Int) (pre : State), + args.length = n → (∀ a ∈ args, a < 2 ^ 256) → (∀ k, s k < 2 ^ 256) → + decodeWords fs.params args = some iargs → pre.storage = s → pre.time ≤ ctx.timestamp → + b.satAll fs.requires (mkEnv ctx iargs [] pre pre) → + b.satAll b.spec.invariants (mkEnv ctx iargs [] pre pre) → + P ⟨args, s, solHash, SolidCore.Refinement.Generic.callerWord⟩ → + Post b fs ctx pre pre.ghost (T.eval ⟨args, s, solHash, SolidCore.Refinement.Generic.callerWord⟩).obs iargs + +theorem TreeMeetsFixedOn.fixed {b : Bundle} {fs : FnSpec} {ctx : Ctx} {n : Nat} {T : Tree} + (h : TreeMeetsFixedOn (fun _ => True) b fs ctx n T) : TreeMeetsFixed b fs ctx n T := + fun args s iargs pre hl hargs hs hdec hst ht hreq hinv => + h args s iargs pre hl hargs hs hdec hst ht hreq hinv trivial + +/-- **A test splits a tree spec into its branches.** -/ +theorem TreeMeetsFixedOn.ite {P : Val → Prop} {b : Bundle} {fs : FnSpec} {ctx : Ctx} {n : Nat} + {c : WExpr} {t e : Tree} + (h1 : TreeMeetsFixedOn (fun ρ => P ρ ∧ c.eval ρ ≠ 0) b fs ctx n t) + (h2 : TreeMeetsFixedOn (fun ρ => P ρ ∧ c.eval ρ = 0) b fs ctx n e) : + TreeMeetsFixedOn P b fs ctx n (.ite c t e) := by + intro args s iargs pre hl hargs hs hdec hst ht hreq hinv hP + simp only [Tree.eval] + split + · exact h2 args s iargs pre hl hargs hs hdec hst ht hreq hinv ⟨hP, by assumption⟩ + · exact h1 args s iargs pre hl hargs hs hdec hst ht hreq hinv ⟨hP, by assumption⟩ + +/-- info: 'SolidCore.Spec.TreeMeetsFixedOn.ite' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms TreeMeetsFixedOn.ite + +open Lean Meta Elab Tactic in +/-- `inst_forall_lits`: `inst_foralls` at the numerals of the context. It instantiates every hypothesis +`∀ x : Nat, x < b → P x` (a quantified clause of an invariant, such as `allowance[address(0)][s] == 0` +for every address `s`) at every numeral that is an argument of a two-argument application of a local +function (a slot hash `H k s`, such as the one of the caller's address), its bound discharged by +`omega`. Each instance is a consequence of a hypothesis; one whose bound `omega` does not show is +left out. -/ +elab "inst_forall_lits" : tactic => do + let lits ← IO.mkRef (#[] : Array Nat) + let fs ← withMainContext do + let mut fs := #[] + let mut tys := #[← instantiateMVars (← getMainTarget)] + for d in (← getLCtx) do + if d.isImplementationDetail then continue + let t ← instantiateMVars d.type + tys := tys.push t + let ty ← whnfR t + if ty.isForall && ty.bindingDomain!.isConstOf `Nat && ty.bindingBody!.hasLooseBVars && + ty.bindingBody!.isForall && (ty.bindingBody!.bindingDomain!.isAppOfArity `LT.lt 4 || + ty.bindingBody!.bindingDomain!.isAppOfArity `LE.le 4) then + fs := fs.push d.fvarId + for t in tys do + t.forEach fun e => do + if let .app (.app (.fvar _) a) b := e then + for x in [a, b] do + if let some n := x.nat? then + lits.modify fun acc => if acc.contains n then acc else acc.push n + pure fs + for f in fs do + for n in (← lits.get) do + withMainContext do + let fe ← Term.exprToSyntax (mkFVar f) + let ne := Syntax.mkNumLit (toString n) + evalTactic (← `(tactic| first | have := $fe ($ne : Nat) (by omega) | skip)) + +/-- `tree_meets_map2` for one branch of a split tree (`TreeMeetsFixedOn`): `P`'s tests join the +hypotheses. -/ +macro "tree_meets_map2_on" "[" ds:Lean.Parser.Tactic.simpLemma,* "]" hsep:term:max : tactic => `(tactic| ( + intro args s iargs pre hl hargs hs hdec hst ht hreq hinv hP + simp only [Nat.reducePow] at hs + rcases args with _ | ⟨a0, _ | ⟨a1, _ | ⟨a2, _ | ⟨a3, _ | ⟨a4, _ | ⟨a5, _ | ⟨a6, _ | ⟨a7, _ | ⟨_, _⟩⟩⟩⟩⟩⟩⟩⟩⟩ <;> + simp only [List.length_cons, List.length_nil] at hl <;> (try omega) <;> + simp only [List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, + IsEmpty.forall_iff, implies_true, and_true, Nat.reducePow] at hargs <;> + simp only [$ds,*, List.head, List.getElem_cons_zero, List.getElem_cons_succ, decodeWords, Ty.ofWord, + bind, pure, Option.bind, Nat.reducePow] at hdec <;> + split_ifs at hdec <;> simp only [Option.some.injEq, reduceCtorEq] at hdec <;> + subst hdec <;> + have hinj := map_inj' (NestedSlotsSeparated.flat $hsep) <;> + have hge := map_ge' (NestedSlotsSeparated.flat $hsep) <;> + have hgn := nmap_ge_n $hsep <;> have hln := nmap_inj_ln $hsep <;> have hnn := nmap_inj_nn $hsep <;> + have hlt := solHash_lt' <;> + have hkec := keccak_solHash <;> + generalize solHash = H at hinj hge hgn hln hnn hlt hkec hP ⊢ <;> + simp only [true_and, WExpr.eval, BinOp.eval, UnOp.eval, Generic.wordSize, List.getD_cons_zero, + List.getD_cons_succ, Nat.reducePow] at hP <;> + refine ⟨fun hsucc => ?_, fun hne => ?_⟩ + all_goals try (simp [$ds,*] at hne; done) + all_goals try (simp only [$ds,*, Tree.eval, WExpr.eval, BinOp.eval, UnOp.eval, Generic.wordSize, Res.obs, + Writes.store, List.getD_cons_zero, List.getD_cons_succ, Nat.reducePow] at hsucc ⊢) + all_goals try simp (disch := simp only [hargs, hs, hlt, Nat.reduceLT]) only [Nat.mod_eq_of_lt, ite_mod_nat, + Nat.reduceMod, Nat.zero_mod, ite10_eq_zero_iff, Decidable.not_not, ne_eq] at hP + all_goals try (simp (disch := simp only [hargs, hs, hlt, Nat.reduceLT]) only [Nat.mod_eq_of_lt, ite_mod_nat, + Nat.reduceMod, Nat.zero_mod, ite10_eq_zero_iff, Decidable.not_not] at hsucc ⊢) + all_goals try (first | split_ifs at hP hsucc ⊢ | split_ifs at hP ⊢ | split_ifs at hsucc ⊢) + all_goals try (simp only [Bool.false_eq_true, Bool.true_eq_false, imp_false, not_true_eq_false, + IsEmpty.forall_iff] at hsucc) + all_goals try (simp only [$ds,*, OByte.eval, WExpr.eval, Generic.wordSize, words, bytesWord, decodeWords, Ty.ofWord, + List.map_cons, List.map_nil, List.length_cons, List.length_nil, List.range_succ, List.range_zero, + List.nil_append, List.cons_append, List.drop_zero, List.take_succ_cons, List.take_zero, List.foldl_cons, + List.foldl_nil, Nat.reduceDiv, Nat.reducePow, Nat.reduceMod, Nat.reduceSub, Nat.reduceMul, Nat.reduceAdd, + Nat.reduceLT, ite_true, ite_false, List.getElem_cons_succ, List.getElem_cons_zero, Option.some.injEq, + exists_eq_left', bind, pure, Option.bind, Ty.InRange, Nat.cast_ofNat, Nat.zero_add, + Nat.reduceLeDiff] at hsucc ⊢) + all_goals try clear hsucc + all_goals try refine ⟨?_, ?_⟩ + all_goals try (simp only [Bundle.satAll, Bundle.sat, $ds,*, List.getElem_cons_succ, List.getElem_cons_zero, + List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, eval, evalList, slotOf, mkEnv, + Env.cur, Env.bind, BinOp.apply, Ty.ofBits, toWord, List.getD_cons_zero, List.getD_cons_succ, + List.lookup, hkec, ofProp_ne_zero, ite_true, ite_false, Bool.false_eq_true, Nat.zero_mod, hst, + beq_self_eq_true, Ty.InRange, Option.getD_some, forall_int_range, Nat.cast_ofNat, + String.reduceBEq, Bool.false_eq_true] at hinv ⊢) + all_goals try (simp only [wordMod, Nat.reducePow] at hinv ⊢) + all_goals try (simp (disch := first | exact hlt _ _ | exact hs _ | omega) only [Nat.mod_eq_of_lt, + toNat_natCast_emod] at hinv ⊢) + all_goals try (simp (disch := first | exact hlt _ _ | exact hs _ | omega) only [Nat.cast_ofNat, + Int.reduceMod, Int.reduceToNat, Nat.mod_eq_of_lt, toNat_natCast_emod, toNat_ofNat_emod, + toNat_zero_emod, toNat_one_emod, wordMod, Nat.reducePow, Nat.reduceMul, Nat.reduceMod, Nat.div_one, + Nat.reduceDiv, Int.reducePow] at hinv ⊢) + all_goals try ((repeat' (first | (apply And.intro) | intro))) + all_goals try ((try simp only [toNat_natCast_emod_ofNat] at hinv ⊢)) + all_goals try ((try simp (disch := first | exact hlt _ _ | exact hs _ | omega) only [Nat.mod_eq_of_lt, + toNat_natCast_emod_word, toNat_natCast_emod, Int.toNat_natCast, Nat.cast_inj, Nat.cast_le, Nat.cast_lt] at hinv ⊢)) + all_goals try (inst_foralls) + all_goals try (inst_forall_lits) + all_goals try ((try simp (disch := omega) only [toNat_natCast_emod_word, Int.toNat_natCast, Nat.cast_inj] at *)) + all_goals try (hash_bounds H s hlt hs) + all_goals ((try split_ifs) <;> (try simp only [Nat.cast_inj] at *) <;> (hash_eqs H hinj hge hgn hln hnn; (try subst_vars); first | contradiction | omega)))) + +end SolidCore.Spec diff --git a/Verify/Spec/TreeSucceeds.lean b/Verify/Spec/TreeSucceeds.lean new file mode 100644 index 00000000..10552920 --- /dev/null +++ b/Verify/Spec/TreeSucceeds.lean @@ -0,0 +1,168 @@ +import Verify.Spec.TreeMap + +/-! +# Succeeds-if conditions of the erased tree + +\`TreeMeets\` (\`Verify.Spec.Tree\`) asks the tree's observable to meet a function spec's \`Post\`, whose +second part is the spec's succeeds-if conditions: from a pre-state meeting them, the call succeeds. +\`tree_meets\` proves the first part (the ensures and the invariants on success); this file proves +the second apart, as \`TreeSucceeds\`, so that a spec with succeeds-if conditions is proved of its +tree by two steps the kernel checks: + +* \`TreeMeets b fs.noSucc ctx n T\` (the spec without its succeeds-if conditions, by \`tree_meets\`, + or \`TreeMeetsFixed\` by \`tree_meets_fixed\` and \`tree_meets_map\`); +* \`TreeSucceeds b fs ctx n T\` (by \`tree_succeeds\` or, for a function reading mappings, by + \`tree_succeeds_map\` from \`MapSlotsSeparated\`); + +and \`treeMeets_of_succeeds\` (\`treeMeetsFixed_of_succeeds\`) puts them together. +-/ + +namespace SolidCore.Spec + +open SolidCore.Refinement SolidCore.Refinement.Generic + +/-- What a function's succeeds-if conditions ask of its erased tree: from every pre-state meeting +the precondition, the invariants and the succeeds-if conditions, the tree succeeds. -/ +def TreeSucceeds (b : Bundle) (fs : FnSpec) (ctx : Ctx) (n : Nat) (T : Tree) : Prop := + ∀ (args : List Nat) (s : Storage) (iargs : List Int) (pre : State), + args.length = n → (∀ a ∈ args, a < 2 ^ 256) → (∀ k, s k < 2 ^ 256) → + decodeWords fs.params args = some iargs → pre.storage = s → pre.time ≤ ctx.timestamp → + b.satAll fs.requires (mkEnv ctx iargs [] pre pre) → + b.satAll b.spec.invariants (mkEnv ctx iargs [] pre pre) → + b.satAll fs.succeedsIf (mkEnv ctx iargs [] pre pre) → + (T.eval ⟨args, s, solHash, SolidCore.Refinement.Generic.callerWord⟩).obs.success = true + +/-- No mapping slots: nothing to separate. -/ +theorem mapSlotsSeparated_nil : MapSlotsSeparated [] := + TrustedBase.keccakSeparated_empty.mono fun _ ⟨_, _, _, hm, _⟩ => by simp at hm + +/-- The function spec without its succeeds-if conditions. -/ +def FnSpec.noSucc (fs : FnSpec) : FnSpec := { fs with succeedsIf := [] } + +theorem treeMeets_of_succeeds {b : Bundle} {fs : FnSpec} {ctx : Ctx} {n : Nat} {T : Tree} + (h : TreeMeets b fs.noSucc ctx n T) (hs : TreeSucceeds b fs ctx n T) : TreeMeets b fs ctx n T := by + intro args s iargs pre g' hl ha hs' hd hst ht hr hi + exact ⟨(h args s iargs pre g' hl ha hs' hd hst ht hr hi).1, + fun _ hsat => hs args s iargs pre hl ha hs' hd hst ht hr hi hsat⟩ + +theorem treeMeetsFixed_of_succeeds {b : Bundle} {fs : FnSpec} {ctx : Ctx} {n : Nat} {T : Tree} + (h : TreeMeetsFixed b fs.noSucc ctx n T) (hs : TreeSucceeds b fs ctx n T) : + TreeMeetsFixed b fs ctx n T := by + intro args s iargs pre hl ha hs' hd hst ht hr hi + exact ⟨(h args s iargs pre hl ha hs' hd hst ht hr hi).1, + fun _ hsat => hs args s iargs pre hl ha hs' hd hst ht hr hi hsat⟩ + +/-- \`tree_succeeds [defs]\` proves \`TreeSucceeds b fs ctx n T\` for a function of at most eight +parameters that reads no mapping: it decodes the argument words, evaluates the tree and the +succeeds-if terms, splits every branch and closes each by \`omega\`. -/ +macro "tree_succeeds" "[" ds:Lean.Parser.Tactic.simpLemma,* "]" : tactic => `(tactic| ( + intro args s iargs pre hl hargs hs hdec hst ht hreq hinv hsi + simp only [Nat.reducePow] at hs + rcases args with _ | ⟨a0, _ | ⟨a1, _ | ⟨a2, _ | ⟨a3, _ | ⟨a4, _ | ⟨a5, _ | ⟨a6, _ | ⟨a7, _ | ⟨_, _⟩⟩⟩⟩⟩⟩⟩⟩⟩ <;> + simp only [List.length_cons, List.length_nil] at hl <;> (try omega) <;> + simp only [List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, + IsEmpty.forall_iff, implies_true, and_true, Nat.reducePow] at hargs <;> + simp only [$ds,*, List.head, List.getElem_cons_zero, List.getElem_cons_succ, decodeWords, Ty.ofWord, + bind, pure, Option.bind, Nat.reducePow] at hdec <;> + split_ifs at hdec <;> simp only [Option.some.injEq, reduceCtorEq] at hdec <;> + subst hdec + all_goals simp only [$ds,*, Tree.eval, WExpr.eval, BinOp.eval, UnOp.eval, Generic.wordSize, Res.obs, + Writes.store, List.getD_cons_zero, List.getD_cons_succ, Nat.reducePow] + all_goals simp (disch := simp only [hargs, hs, Nat.reduceLT]) only [Nat.mod_eq_of_lt, ite_mod_nat, + Nat.reduceMod, Nat.zero_mod, ite10_eq_zero_iff, Decidable.not_not] + all_goals simp only [Bundle.satAll, Bundle.sat, $ds,*, List.getElem_cons_succ, List.getElem_cons_zero, + List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, eval, evalList, slotOf, mkEnv, + Env.cur, Env.bind, BinOp.apply, Ty.ofBits, toWord, List.getD_cons_zero, List.getD_cons_succ, + List.lookup, ofProp_ne_zero, ite_true, ite_false, Bool.false_eq_true, Nat.zero_mod, hst, + beq_self_eq_true, Ty.InRange, Option.getD_some, forall_int_range, Nat.cast_ofNat, Int.reducePow] at hsi + all_goals simp only [wordMod, Nat.reducePow] at hsi + all_goals simp (disch := first | exact hs _ | omega) only [Nat.cast_ofNat, + Int.reduceMod, Int.reduceToNat, Nat.mod_eq_of_lt, toNat_natCast_emod, toNat_ofNat_emod, + toNat_zero_emod, toNat_one_emod, wordMod, Nat.reducePow, Nat.reduceMul, Nat.reduceMod, Nat.div_one, + Nat.reduceDiv, Int.reducePow] at hsi + all_goals ((try split_ifs) <;> (try rfl) <;> first | omega | (simp_all; done) | (simp_all; omega)))) + +/-- \`tree_succeeds_map [defs] hsep\`: \`tree_succeeds\` for a function that reads mappings keyed by +addresses at the slots \`ms\`, from \`hsep : MapSlotsSeparated ms\`, as \`tree_meets_map\` does. -/ +macro "tree_succeeds_map" "[" ds:Lean.Parser.Tactic.simpLemma,* "]" hsep:term:max : tactic => `(tactic| ( + intro args s iargs pre hl hargs hs hdec hst ht hreq hinv hsi + simp only [Nat.reducePow] at hs + rcases args with _ | ⟨a0, _ | ⟨a1, _ | ⟨a2, _ | ⟨a3, _ | ⟨a4, _ | ⟨a5, _ | ⟨a6, _ | ⟨a7, _ | ⟨_, _⟩⟩⟩⟩⟩⟩⟩⟩⟩ <;> + simp only [List.length_cons, List.length_nil] at hl <;> (try omega) <;> + simp only [List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, + IsEmpty.forall_iff, implies_true, and_true, Nat.reducePow] at hargs <;> + simp only [$ds,*, List.head, List.getElem_cons_zero, List.getElem_cons_succ, decodeWords, Ty.ofWord, + bind, pure, Option.bind, Nat.reducePow] at hdec <;> + split_ifs at hdec <;> simp only [Option.some.injEq, reduceCtorEq] at hdec <;> + subst hdec <;> + have hinj := map_inj' $hsep <;> have hge := map_ge' $hsep <;> have hlt := solHash_lt' <;> + have hkec := keccak_solHash <;> + generalize solHash = H at hinj hge hlt hkec ⊢ + all_goals simp only [$ds,*, Tree.eval, WExpr.eval, BinOp.eval, UnOp.eval, Generic.wordSize, Res.obs, + Writes.store, List.getD_cons_zero, List.getD_cons_succ, Nat.reducePow] + all_goals simp (disch := simp only [hargs, hs, hlt, Nat.reduceLT]) only [Nat.mod_eq_of_lt, ite_mod_nat, + Nat.reduceMod, Nat.zero_mod, ite10_eq_zero_iff, Decidable.not_not] + all_goals simp only [Bundle.satAll, Bundle.sat, $ds,*, List.getElem_cons_succ, List.getElem_cons_zero, + List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, eval, evalList, slotOf, mkEnv, + Env.cur, Env.bind, BinOp.apply, Ty.ofBits, toWord, List.getD_cons_zero, List.getD_cons_succ, + List.lookup, hkec, ofProp_ne_zero, ite_true, ite_false, Bool.false_eq_true, Nat.zero_mod, hst, + beq_self_eq_true, Ty.InRange, Option.getD_some, forall_int_range, Nat.cast_ofNat, Int.reducePow] at hsi + all_goals simp only [wordMod, Nat.reducePow] at hsi + all_goals simp (disch := first | exact hlt _ _ | exact hs _ | omega) only [Nat.cast_ofNat, + Int.reduceMod, Int.reduceToNat, Nat.mod_eq_of_lt, toNat_natCast_emod, toNat_ofNat_emod, + toNat_zero_emod, toNat_one_emod, wordMod, Nat.reducePow, Nat.reduceMul, Nat.reduceMod, Nat.div_one, + Nat.reduceDiv, Int.reducePow] at hsi + all_goals ((try split_ifs) <;> (try rfl) <;> first | (hash_facts H s hinj hge hlt hs; omega) | + (hash_facts H s hinj hge hlt hs; simp_all; done) | (hash_facts H s hinj hge hlt hs; simp_all; omega)))) + +/-- \`tree_meets_map' [defs] hsep\`: \`tree_meets_map\`, with each simplification step allowed to make +no progress (a spec with no invariants, or a goal a step leaves alone), as \`spec_connect\` uses it for +a spec whose succeeds-if conditions \`tree_succeeds_map\` proves apart. -/ +macro "tree_meets_map'" "[" ds:Lean.Parser.Tactic.simpLemma,* "]" hsep:term:max : tactic => `(tactic| ( + intro args s iargs pre hl hargs hs hdec hst ht hreq hinv + simp only [Nat.reducePow] at hs + rcases args with _ | ⟨a0, _ | ⟨a1, _ | ⟨a2, _ | ⟨a3, _ | ⟨a4, _ | ⟨a5, _ | ⟨a6, _ | ⟨a7, _ | ⟨_, _⟩⟩⟩⟩⟩⟩⟩⟩⟩ <;> + simp only [List.length_cons, List.length_nil] at hl <;> (try omega) <;> + simp only [List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, + IsEmpty.forall_iff, implies_true, and_true, Nat.reducePow] at hargs <;> + simp only [$ds,*, List.head, List.getElem_cons_zero, List.getElem_cons_succ, decodeWords, Ty.ofWord, + bind, pure, Option.bind, Nat.reducePow] at hdec <;> + split_ifs at hdec <;> simp only [Option.some.injEq, reduceCtorEq] at hdec <;> + subst hdec <;> + have hinj := map_inj' $hsep <;> have hge := map_ge' $hsep <;> have hlt := solHash_lt' <;> + have hkec := keccak_solHash <;> + generalize solHash = H at hinj hge hlt hkec ⊢ <;> + refine ⟨fun hsucc => ?_, fun hne => ?_⟩ + all_goals try (simp [$ds,*] at hne; done) + all_goals try (simp only [$ds,*, Tree.eval, WExpr.eval, BinOp.eval, UnOp.eval, Generic.wordSize, Res.obs, + Writes.store, List.getD_cons_zero, List.getD_cons_succ, Nat.reducePow] at hsucc ⊢) + all_goals try (simp (disch := simp only [hargs, hs, hlt, Nat.reduceLT]) only [Nat.mod_eq_of_lt, ite_mod_nat, + Nat.reduceMod, Nat.zero_mod, ite10_eq_zero_iff, Decidable.not_not] at hsucc ⊢) + all_goals try (split_ifs at hsucc ⊢) + all_goals try (simp only [Bool.false_eq_true, Bool.true_eq_false, imp_false, not_true_eq_false, + IsEmpty.forall_iff] at hsucc) + all_goals try (simp only [$ds,*, OByte.eval, WExpr.eval, Generic.wordSize, words, bytesWord, decodeWords, Ty.ofWord, + List.map_cons, List.map_nil, List.length_cons, List.length_nil, List.range_succ, List.range_zero, + List.nil_append, List.cons_append, List.drop_zero, List.take_succ_cons, List.take_zero, List.foldl_cons, + List.foldl_nil, Nat.reduceDiv, Nat.reducePow, Nat.reduceMod, Nat.reduceSub, Nat.reduceMul, Nat.reduceAdd, + Nat.reduceLT, ite_true, ite_false, List.getElem_cons_succ, List.getElem_cons_zero, Option.some.injEq, + exists_eq_left', bind, pure, Option.bind, Ty.InRange, Nat.cast_ofNat, Nat.zero_add, + Nat.reduceLeDiff] at hsucc ⊢) + all_goals try clear hsucc + all_goals try refine ⟨?_, ?_⟩ + all_goals try (simp only [Bundle.satAll, Bundle.sat, $ds,*, List.getElem_cons_succ, List.getElem_cons_zero, + List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, forall_eq, eval, evalList, slotOf, mkEnv, + Env.cur, Env.bind, BinOp.apply, Ty.ofBits, toWord, List.getD_cons_zero, List.getD_cons_succ, + List.lookup, hkec, ofProp_ne_zero, ite_true, ite_false, Bool.false_eq_true, Nat.zero_mod, hst, + beq_self_eq_true, Ty.InRange, Option.getD_some, forall_int_range, Nat.cast_ofNat] at hinv ⊢) + all_goals try (simp only [wordMod, Nat.reducePow] at hinv ⊢) + all_goals try (simp (disch := first | exact hlt _ _ | exact hs _ | omega) only [Nat.mod_eq_of_lt, + toNat_natCast_emod] at hinv ⊢) + all_goals try (simp (disch := first | exact hlt _ _ | exact hs _ | omega) only [Nat.cast_ofNat, + Int.reduceMod, Int.reduceToNat, Nat.mod_eq_of_lt, toNat_natCast_emod, toNat_ofNat_emod, + toNat_zero_emod, toNat_one_emod, wordMod, Nat.reducePow, Nat.reduceMul, Nat.reduceMod, Nat.div_one, + Nat.reduceDiv, Int.reducePow] at hinv ⊢) + all_goals (repeat' (first | (apply And.intro) | intro)) + all_goals (hash_facts H s hinj hge hlt hs; (try split_ifs) <;> first | omega | (simp_all; done) | (simp_all; omega)))) + +end SolidCore.Spec diff --git a/Verify/Spec/TrustedBase.lean b/Verify/Spec/TrustedBase.lean new file mode 100644 index 00000000..b268b771 --- /dev/null +++ b/Verify/Spec/TrustedBase.lean @@ -0,0 +1,103 @@ +import Verify.Spec.Contract +import Verify.Spec.Ghost + +/-! +# solar-verify's trusted base, as named hypotheses + +solar-verify's ✔ is a claim of its own (crates/verify/README.md, "Trusted base"), checked by +Rust code and SMT solvers rather than by Lean's kernel. This module states that claim as one +proposition about the spec's meaning (`Verdict`), with every assumption of its model a separate, +named field of `Assumptions`, so that a theorem that rests on it says so in its statement and +never through an axiom. `spec_of_verdict` is the final theorem: the verdict on the source +semantics, and a kernel-checked refinement from the source to the bytecode, give the spec of the +bytecode on the calls where the assumptions hold. A spec proved of SolidCore in Lean instead +(`SolidCore.Spec.Solar.C4`) needs none of this. + +The items, in the README's order, and where each one is in the statement: + +1. "The parser, the encoding in `src/vc.rs` and `src/vc/yul.rs`, and the solvers": `Verdict` + itself. This includes that solar-verify's model of a function with its ghost code is a program + whose erasure is the function SolidCore runs; erasure itself is proved, not trusted + (`SolidCore.Spec.Ghost.spec_of_erased`), on a core language with solar-verify's discipline. +2. "`@custom:assume`, `@custom:trusted` and interface ensures": `Assumptions.assumptionsHold`. +3. "No `delegatecall` into the contract": `Assumptions.noDelegatecall`. It matters across calls: + the storage a call starts from is the one the previous call left. +4. "`keccak256` is injective and its results lie in `[2^128, 2^256)`": `Assumptions.keccakSeparated`, + per call. Stated for all inputs it is false (keccak256 maps unboundedly many inputs to 2^256 + words, and some 64-byte input almost surely hashes below 2^128), and a false hypothesis would + make every theorem that takes it vacuous; per call it says only that the hashes this call + computes are separated, which is what the encoding uses. +5. "Raw storage slots that assembly reaches are disjoint from the declared state variables, and + assembly is memory-safe": `Assumptions.asmSlotsDisjoint`, `Assumptions.asmMemorySafe`. +6. "A library named `Math` with a `mulDiv` ... is summarized as OpenZeppelin's": `Assumptions.mulDiv`. +7. "A high-level call to a view or pure function answers as a function of its target, its + arguments and the state it can read": `Assumptions.viewCalls`. + +Two more obligations come from giving specs a meaning, and are checked rather than trusted: every +spec function call resolves and nests within the exported fuel (`Bundle.WF`, by the kernel's +evaluation), and an opaque spec function's body stays in its return type's range, the range +solar-verify assumes of it (`OpaqueInRange`, proved per contract). +-/ + +namespace SolidCore.Spec + +open SolarTV + +/-- The per-call and global assumptions of solar-verify's model (items 2 to 7 above). Each is a +proposition supplied by whoever states the theorem; `Assumptions.none` assumes nothing. -/ +structure Assumptions where + /-- Item 2: on this call, every `@custom:assume` holds where it is assumed, every + `@custom:trusted` function meets its contract, and every external callee meets its interface's + ensures. -/ + assumptionsHold : Call → Prop + /-- Item 3: no account changes the contract's storage except through its own functions. -/ + noDelegatecall : Prop + /-- Item 4, per call: the keccak256 images this call computes are distinct for distinct + preimages and at least `2 ^ 128`. -/ + keccakSeparated : Call → Prop + /-- Item 5: on this call, the raw slots inline assembly reaches are none of the declared + variables' slots. -/ + asmSlotsDisjoint : Call → Prop + /-- Item 5: on this call, inline assembly is memory-safe. -/ + asmMemorySafe : Call → Prop + /-- Item 6: a library `Math.mulDiv` without specs computes OpenZeppelin's `Math.mulDiv`. -/ + mulDiv : Prop + /-- Item 7: view and pure calls answer as a function of their target, arguments and the state + they can read. -/ + viewCalls : Prop + +/-- Every assumption, on one call. -/ +def Assumptions.On (A : Assumptions) (call : Call) : Prop := + A.assumptionsHold call ∧ A.noDelegatecall ∧ A.keccakSeparated call ∧ A.asmSlotsDisjoint call ∧ + A.asmMemorySafe call ∧ A.mulDiv ∧ A.viewCalls + +/-- No assumption at all: the case of a contract without assumes, trusted functions, external +calls, mappings, assembly or `Math.mulDiv`, or of a spec proved in Lean. -/ +def Assumptions.none : Assumptions := + ⟨fun _ => True, True, fun _ => True, fun _ => True, fun _ => True, True, True⟩ + +theorem Assumptions.none_on (call : Call) : Assumptions.none.On call := by + simp [Assumptions.On, Assumptions.none] + +/-- Item 1, **solar-verify's verdict**: its ✔ on every function of the bundle means the spec +holds of the source program `p` in `S` on the calls of the scope where the assumptions hold. This +is the trusted claim; nothing in Lean proves it. -/ +def Verdict (S : Sem) (p : S.Prog) (scope : Call → Prop) (b : Bundle) (ctxOf : Call → Ctx) + (step : GhostStep) (A : Assumptions) : Prop := + Holds S p (fun call => scope call ∧ A.On call) b ctxOf step + +/-! ## The final theorem -/ + +/-- **The spec of the bytecode, from solar-verify's verdict.** A kernel-checked stage from the +source semantics `S` to the target `T` (for SolidCore and EthLib, a certified translation of the +contract to its bytecode), and solar-verify's verdict on the source (trusted, item 1), give the +spec of the target on every call of the scope where the assumptions (items 2 to 7) hold. The +bundle's well-formedness and the opaque functions' ranges are hypotheses checked per contract. -/ +theorem spec_of_verdict {S T : Sem} {p : S.Prog} {q : T.Prog} {scope : Call → Prop} {b : Bundle} + {ctxOf : Call → Ctx} {step : GhostStep} {A : Assumptions} + (_wf : b.WF = true) (_opaque : OpaqueInRange b) + (verdict : Verdict S p scope b ctxOf step A) (stage : Stage S T p q scope) : + Holds T q (fun call => scope call ∧ A.On call) b ctxOf step := + verdict.of_stage (Stage.mono stage fun _ h => h.1) + +end SolidCore.Spec diff --git a/Verify/Spec/TrustedBase/Axioms.lean b/Verify/Spec/TrustedBase/Axioms.lean new file mode 100644 index 00000000..19979aac --- /dev/null +++ b/Verify/Spec/TrustedBase/Axioms.lean @@ -0,0 +1,45 @@ +import Verify.Spec.TrustedBase.Instances +import Verify.Spec.TrustedBase.Interface + +/-! The axioms of the trusted base's theorems: `propext`, `Classical.choice` and `Quot.sound` at most, +and no `sorry`, `native_decide` (`Lean.ofReduceBool`) or `bv_decide`. -/ + +open SolidCore.Spec.TrustedBase in +section +#print axioms keccakSeparated_empty +#print axioms keccakSeparated_mapping +#print axioms not_keccakSeparated_univ +#print axioms Core.exec_dropAssumes +#print axioms Core.assumesHold_of_noAssume +#print axioms Core.spec_of_assumes +#print axioms Core.assumesHold_assumeX +#print axioms Core.not_assumesHold_assumeX +#print axioms Core.meetsContract_assign +#print axioms Core.not_meetsContract_assign +#print axioms trustedHold_nil +#print axioms trustedHold_of_holds +#print axioms follows_transcriptWith +#print axioms defaultCalls_transcriptWith +#print axioms interfaceEnsures_of_default +#print axioms interfaceEnsures_of_default' +#print axioms interfaceEnsures_one +#print axioms not_interfaceEnsures_zero +#print axioms viewDeterministic_of_default +#print axioms noForeignWrites_of_default +#print axioms viewDeterministic_twice +#print axioms not_viewDeterministic +#print axioms Reach.trans +#print axioms asmFree_example +#print axioms not_asmFree_example +#print axioms mulDivSummary_oz +#print axioms not_mulDivSummary_unchecked +#print axioms ozMulDiv_spec +#print axioms Hyps.plain_on +#print axioms Hyps.satisfiable +#print axioms spec_of_verdict_hyps +#print axioms Instances.asmFree_c4 +#print axioms Instances.asmFree_counter +#print axioms Instances.c4_on +#print axioms Instances.counter_on +#print axioms Instances.counter_spec_of_verdict +end diff --git a/Verify/Spec/TrustedBase/Hypotheses.lean b/Verify/Spec/TrustedBase/Hypotheses.lean new file mode 100644 index 00000000..5a558e88 --- /dev/null +++ b/Verify/Spec/TrustedBase/Hypotheses.lean @@ -0,0 +1,658 @@ +import Verify.Spec.TrustedBase +import EvmInteraction.Simulation.Interaction +import SolidCore.Solidity.Ast + +/-! +# solar-verify's trusted base, item by item, as precise hypotheses + +`SolidCore.Spec.TrustedBase.Assumptions` names each item of solar-verify's trusted base +(crates/verify/README.md, "Trusted base") as a field, but leaves each field an arbitrary +proposition. This module gives each item a precise statement over the objects the composition +already has: `SolarTV.Call`/`Observable` and a `Sem`, the transcripts of query/answer exchanges +SolidCore's interaction trees make with the outside world (`EvmCompiler.Simulation.Interaction`), +the core language of ghost code (`SolidCore.Spec.Ghost`) and the Solidity AST. `Hyps` collects +them, `Hyps.toAssumptions` instantiates `Assumptions` with them, and `spec_of_verdict_hyps` is +`spec_of_verdict` with the precise hypotheses. + +For each item: the statement, a witness that it is satisfiable (not `False` in disguise), where +it is cheap a witness that it is not trivially `True` either, and the discharge for code that does +not use the feature. + +| README item | Here | Discharged when | +|---|---|---| +| keccak256 injective, results in `[2^128, 2^256)` | `KeccakSeparated` of the call's preimages | no preimages (`keccakSeparated_empty`); checked by the kernel on concrete ones (`keccakSeparated_mapping`) | +| `@custom:assume` | `AssumesHold` | the body has no assume (`assumesHold_of_noAssume`) | +| `@custom:trusted` (internal) | `MeetsContract` | no trusted function | +| `@custom:trusted` (external) | `TrustedHold` | no trusted function (`trustedHold_nil`), or the spec proved (`trustedHold_of_holds`) | +| interface ensures | `InterfaceEnsures` | every external call fails, e.g. SolidCore's fail-open answers (`DefaultCalls`) | +| no delegatecall into the contract | `NoForeignWrites` within a call, `Reach` across calls | `DefaultCalls` | +| assembly slots disjoint, memory-safe | `AsmFree` (stronger) | the source has no assembly (`AsmFree` by `decide`) | +| `Math.mulDiv` summary | `MulDivSummary` | no `Math.mulDiv` | +| view calls deterministic | `ViewDeterministic` | `DefaultCalls` | + +Two items are stated against data the theorem's user supplies rather than derived from SolidCore's +run, and the gap is named where they are: the keccak256 preimages a call hashes +(`Hyps.keccakInputs`) and the transcript of a call (`Hyps.transcript`; `transcriptWith` computes it +from an interaction tree and an answerer, but `Source.run` does not yet expose its tree). Item 1 +(the parser, the VC encoding and the solvers) stays `Verdict` itself. +-/ + +namespace SolidCore.Spec.TrustedBase + +open SolarTV SolidCore.Spec + +/-! ## keccak256 -/ + +/-- A set of keccak256 preimages (byte lists), as a predicate. -/ +abbrev Preimages := List Nat → Prop + +/-- **keccak256 is separated on `S`**: injective on `S`, and every image at least `2 ^ 128`, so +no image is a small constant slot. Stated for every input it is false (`not_keccakSeparated_univ`); +solar-verify's encoding uses it only on the preimages a call hashes. -/ +def KeccakSeparated (S : Preimages) : Prop := + (∀ x y, S x → S y → keccakWord x = keccakWord y → x = y) ∧ ∀ x, S x → 2 ^ 128 ≤ keccakWord x + +theorem KeccakSeparated.mono {S T : Preimages} (h : KeccakSeparated T) (hST : ∀ x, S x → T x) : + KeccakSeparated S := + ⟨fun x y hx hy he => h.1 x y (hST x hx) (hST y hy) he, fun x hx => h.2 x (hST x hx)⟩ + +/-- A call that hashes nothing needs nothing of keccak256. -/ +theorem keccakSeparated_empty : KeccakSeparated (fun _ => False) := + ⟨fun _ _ h => h.elim, fun _ h => h.elim⟩ + +/-- Injectivity on a list from distinct images. -/ +theorem inj_of_nodup_map {α β : Type} {f : α → β} : + ∀ {l : List α}, (l.map f).Nodup → ∀ x ∈ l, ∀ y ∈ l, f x = f y → x = y + | [], _, _, hx, _, _, _ => by simp at hx + | a :: l, h, x, hx, y, hy, he => by + simp only [List.map_cons, List.nodup_cons, List.mem_map] at h + simp only [List.mem_cons] at hx hy + rcases hx with rfl | hx <;> rcases hy with rfl | hy + · rfl + · exact absurd ⟨y, hy, he.symm⟩ h.1 + · exact absurd ⟨x, hx, he⟩ h.1 + · exact inj_of_nodup_map h.2 x hx y hy he + +/-- Separation on a list, from its images: distinct and each at least `2 ^ 128`. -/ +theorem keccakSeparated_of_images {L : List (List Nat)} {H : List Nat} + (hH : L.map keccakWord = H) (hnd : H.Nodup) (hge : ∀ v ∈ H, 2 ^ 128 ≤ v) : + KeccakSeparated (· ∈ L) := + ⟨fun x y hx hy he => inj_of_nodup_map (hH ▸ hnd) x hx y hy he, + fun _ hx => hge _ (hH ▸ List.mem_map_of_mem hx)⟩ + +/-- The preimage of the slot of `m[k]` for a mapping `m` at slot `s`: `k` then `s`, as words. -/ +def mappingPreimage (k s : Nat) : List Nat := wordBytes k ++ wordBytes s + +/-- The slots of `m[0]`, `m[1]` and `m[0x2000]` (`msg.sender` for `callerAddress`) for mappings at slots 0 +and 1. -/ +def mappingPreimages : List (List Nat) := + [mappingPreimage 0 0, mappingPreimage 1 0, mappingPreimage 0x2000 0, mappingPreimage 0 1, + mappingPreimage 1 1, mappingPreimage 0x2000 1] + +/-! Their keccak256 images, each by the kernel's evaluation of the sponge (one per declaration, +so that the kernel's caches stay small). -/ + +set_option maxRecDepth 100000 in +theorem image0 : keccakWord (mappingPreimage 0 0) = + 0xad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5 := by + decide +kernel + +set_option maxRecDepth 100000 in +theorem image1 : keccakWord (mappingPreimage 1 0) = + 0xada5013122d395ba3c54772283fb069b10426056ef8ca54750cb9bb552a59e7d := by + decide +kernel + +set_option maxRecDepth 100000 in +theorem image2 : keccakWord (mappingPreimage 0x2000 0) = + 0x7a590e257d634ba5db8688524231d50b5351ea3cd1a840d196ed0e2098593fd8 := by + decide +kernel + +set_option maxRecDepth 100000 in +theorem image3 : keccakWord (mappingPreimage 0 1) = + 0xa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb49 := by + decide +kernel + +set_option maxRecDepth 100000 in +theorem image4 : keccakWord (mappingPreimage 1 1) = + 0xcc69885fda6bcc1a4ace058b4a62bf5e179ea78fd58a1ccd71c22cc9b688792f := by + decide +kernel + +set_option maxRecDepth 100000 in +theorem image5 : keccakWord (mappingPreimage 0x2000 1) = + 0x38da9dc9759c46bd12ce677a753bb966a85f8995667f5aade8c3f5d0f1de587a := by + decide +kernel + +theorem mappingPreimages_images : + mappingPreimages.map keccakWord = + [0xad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5, + 0xada5013122d395ba3c54772283fb069b10426056ef8ca54750cb9bb552a59e7d, + 0x7a590e257d634ba5db8688524231d50b5351ea3cd1a840d196ed0e2098593fd8, + 0xa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb49, + 0xcc69885fda6bcc1a4ace058b4a62bf5e179ea78fd58a1ccd71c22cc9b688792f, + 0x38da9dc9759c46bd12ce677a753bb966a85f8995667f5aade8c3f5d0f1de587a] := by + simp only [mappingPreimages, List.map_cons, List.map_nil, image0, image1, image2, image3, image4, + image5] + +/-- **Satisfiable on real preimages**: keccak256 is separated on `mappingPreimages`. -/ +theorem keccakSeparated_mapping : KeccakSeparated (· ∈ mappingPreimages) := + keccakSeparated_of_images mappingPreimages_images (by decide) (by decide) + +set_option maxRecDepth 100000 in +theorem not_keccakSeparated_univ : ¬ KeccakSeparated (fun _ => True) := by + intro h + have := h.1 [0] [256] trivial trivial (by decide +kernel) + simp at this + +/-! ## `@custom:assume` and `@custom:trusted`, on the core language of ghost code -/ + +namespace Core +open SolidCore.Spec.Ghost + +/-- The program with every `assume` replaced by `skip`. -/ +def dropAssumes : Ghost.Stmt → Ghost.Stmt + | .assume _ => .skip + | .seq s t => .seq (dropAssumes s) (dropAssumes t) + | .ite c s t => .ite c (dropAssumes s) (dropAssumes t) + | .loop c b => .loop c (dropAssumes b) + | s => s + +/-- The program has no `assume`. -/ +def noAssume : Ghost.Stmt → Bool + | .assume _ => false + | .seq s t => noAssume s && noAssume t + | .ite _ s t => noAssume s && noAssume t + | .loop _ b => noAssume b + | _ => true + +/-- **Every `@custom:assume` holds where it is reached** from `σ`: every execution of the program +without its assumes is one of the program, so no assume cuts an execution off. -/ +def AssumesHold (s : Ghost.Stmt) (σ : Store) : Prop := + ∀ o, Exec (dropAssumes s) σ o → Exec s σ o + +/-- Dropping assumes only adds executions. -/ +theorem exec_dropAssumes {s : Ghost.Stmt} {σ : Store} {o : Out} (h : Exec s σ o) : + Exec (dropAssumes s) σ o := by + induction h with + | skip => exact .skip + | assign => exact .assign + | requireOk h => exact .requireOk h + | requireRev h => exact .requireRev h + | seqOk _ _ ih1 ih2 => exact .seqOk ih1 ih2 + | seqRev _ ih => exact .seqRev ih + | seqFail _ ih => exact .seqFail ih + | iteT hc _ ih => exact .iteT hc ih + | iteF hc _ ih => exact .iteF hc ih + | loopDone hc => exact .loopDone hc + | loopOk hc _ _ ih1 ih2 => exact .loopOk hc ih1 ih2 + | loopRev hc _ ih => exact .loopRev hc ih + | loopFail hc _ ih => exact .loopFail hc ih + | ghost => exact .ghost + | assertOk h => exact .assertOk h + | assertFail h => exact .assertFail h + | assume _ => exact .skip + +theorem dropAssumes_of_noAssume : ∀ {s : Ghost.Stmt}, noAssume s = true → dropAssumes s = s + | .skip, _ | .assign _ _, _ | .require _, _ | .ghost _ _, _ | .assert _, _ => rfl + | .assume _, h => by simp [noAssume] at h + | .seq s t, h => by + simp only [noAssume, Bool.and_eq_true] at h + simp [dropAssumes, dropAssumes_of_noAssume h.1, dropAssumes_of_noAssume h.2] + | .ite c s t, h => by + simp only [noAssume, Bool.and_eq_true] at h + simp [dropAssumes, dropAssumes_of_noAssume h.1, dropAssumes_of_noAssume h.2] + | .loop c b, h => by + simp only [noAssume] at h + simp [dropAssumes, dropAssumes_of_noAssume h] + +/-- **Discharged without assumes.** -/ +theorem assumesHold_of_noAssume {s : Ghost.Stmt} (h : noAssume s = true) (σ : Store) : + AssumesHold s σ := by + intro o ho + rwa [dropAssumes_of_noAssume h] at ho + +/-- What a proof of `s` gives the program without its assumes, where they hold. -/ +theorem spec_of_assumes {s : Ghost.Stmt} {σ : Store} {Q : Out → Prop} + (hs : ∀ o, Exec s σ o → Q o) (ha : AssumesHold s σ) : ∀ o, Exec (dropAssumes s) σ o → Q o := + fun o ho => hs o (ha o ho) + +/-- `@custom:assume x`. -/ +def assumeX : Ghost.Stmt := .assume (.var "x") + +/-- **Satisfiable**: `assume x` holds from a store where `x = 1`. -/ +theorem assumesHold_assumeX : AssumesHold assumeX (fun _ => 1) := by + intro o ho + cases ho + exact .assume (by simp [Exp.eval]) + +/-- **Not trivial**: it fails from a store where `x = 0`. -/ +theorem not_assumesHold_assumeX : ¬ AssumesHold assumeX (fun _ => 0) := by + intro h + have := h _ (Exec.skip (σ := fun _ => 0)) + cases this with + | assume hx => exact hx (by simp [Exp.eval]) + +/-- **A `@custom:trusted` internal function meets its contract**: from every store meeting `req`, +every execution of its body `s` meets `ens`. -/ +def MeetsContract (s : Ghost.Stmt) (req : Store → Prop) (ens : Store → Out → Prop) : Prop := + ∀ σ, req σ → ∀ o, Exec s σ o → ens σ o + +/-- **Satisfiable**: `r = 1` ensures `r == 1`. -/ +theorem meetsContract_assign : + MeetsContract (.assign "r" (.lit 1)) (fun _ => True) + (fun _ o => ∃ σ', o = .ok σ' ∧ σ' "r" = 1) := by + intro σ _ o ho + cases ho + exact ⟨_, rfl, by simp [Store.set, Exp.eval]⟩ + +/-- **Not trivial**: `r = 0` does not. -/ +theorem not_meetsContract_assign : + ¬ MeetsContract (.assign "r" (.lit 0)) (fun _ => True) + (fun _ o => ∃ σ', o = .ok σ' ∧ σ' "r" = 1) := by + intro h + obtain ⟨σ', h1, h2⟩ := h (fun _ => 0) trivial _ .assign + cases h1 + simp [Store.set, Exp.eval] at h2 + +end Core + +/-! ## `@custom:trusted` external and public functions, on calls -/ + +/-- The bundle restricted to the functions named. -/ +def Bundle.only (b : Bundle) (names : List String) : Bundle := + { b with spec := { b.spec with specs := b.spec.specs.filter (fun fs => names.contains fs.name) } } + +/-- **The `@custom:trusted` external functions `names` meet their specs** on `p` in `S`: their +bodies are not verified, so their specs are assumed. -/ +def TrustedHold (S : Sem) (p : S.Prog) (scope : Call → Prop) (b : Bundle) (ctxOf : Call → Ctx) + (step : GhostStep) (names : List String) : Prop := + Holds S p scope (Bundle.only b names) ctxOf step + +/-- **Discharged without trusted functions.** -/ +theorem trustedHold_nil {S : Sem} {p : S.Prog} {scope : Call → Prop} {b : Bundle} + {ctxOf : Call → Ctx} {step : GhostStep} : TrustedHold S p scope b ctxOf step [] := by + intro fs hfs + simp [Bundle.only] at hfs + +/-- **Discharged by a proof**: a spec proved of every function, in Lean or otherwise, holds of the +trusted ones. -/ +theorem trustedHold_of_holds {S : Sem} {p : S.Prog} {scope : Call → Prop} {b : Bundle} + {ctxOf : Call → Ctx} {step : GhostStep} (names : List String) + (h : Holds S p scope b ctxOf step) : TrustedHold S p scope b ctxOf step names := by + intro fs hfs + simp only [Bundle.only, List.mem_filter] at hfs + exact h fs hfs.1 + +/-! ## External calls: interface ensures, view calls and writes by others + +SolidCore runs a function as an interaction tree whose external calls are `Query.external` nodes, +answered by an answerer; a run's transcript is the list of its exchanges. These items are +properties of a transcript's call exchanges: the world the call was made in, the request and the +response (whose `postWorld` the caller adopts). +-/ + +open EvmCompiler.Simulation + +/-- The call exchanges of a transcript: world, request, response. -/ +def callsOf : Interaction.Transcript → List (OpenWorld × CallRequest × CallResponse) + | [] => [] + | ⟨.external w (.call r), a⟩ :: tr => (w, r, a) :: callsOf tr + | _ :: tr => callsOf tr + +/-- The transcript of an interaction tree answered by `ans`. -/ +def transcriptWith {ε α : Type} (ans : (q : Query) → Answer q) : + Interaction ε α → Interaction.Transcript + | .done _ => [] + | .request q k => ⟨q, ans q⟩ :: transcriptWith ans (k (ans q)) + +/-- The transcript is a branch of the tree. -/ +theorem follows_transcriptWith {ε α : Type} (ans : (q : Query) → Answer q) : + ∀ t : Interaction ε α, Interaction.Follows t (transcriptWith ans t) + | .done _ => .nil _ + | .request q k => .request (follows_transcriptWith ans (k (ans q))) + +/-- **Interface ensures**: every external call that returns meets `ens`, the interface's ensures +on the request (target and calldata) and the returned data. -/ +def InterfaceEnsures (ens : CallRequest → CallResponse → Prop) (tr : Interaction.Transcript) : + Prop := + ∀ c ∈ callsOf tr, c.2.2.success = true → ens c.2.1 c.2.2 + +/-- What a view call may read, as solar-verify's README puts it: the balance and code of every +account, and the storage of the calling contract `self`. -/ +def ReadAgree (self : InteractionAddress) (w w' : OpenWorld) : Prop := + (∀ a, (w.accounts.find? a).map (fun acc => (acc.balance, acc.codeBytes)) = + (w'.accounts.find? a).map (fun acc => (acc.balance, acc.codeBytes))) ∧ + ∀ k, (w.accounts.find? self).map (fun acc => acc.storage.find? k) = + (w'.accounts.find? self).map (fun acc => acc.storage.find? k) + +/-- **View calls are deterministic**: two static calls to the same target with the same calldata, +from worlds that agree on what a view call may read, answer alike, whatever gas each carried. -/ +def ViewDeterministic (self : InteractionAddress) (tr : Interaction.Transcript) : Prop := + ∀ c₁ ∈ callsOf tr, ∀ c₂ ∈ callsOf tr, c₁.2.1.kind = .staticcall → c₂.2.1.kind = .staticcall → + c₁.2.1.recipient = c₂.2.1.recipient → c₁.2.1.calldata = c₂.2.1.calldata → + ReadAgree self c₁.1 c₂.1 → + c₁.2.2.success = c₂.2.2.success ∧ c₁.2.2.returnData = c₂.2.2.returnData + +/-- `self`'s storage in a world, as a slot function (absent slots and accounts read zero). -/ +def selfSlots (self : InteractionAddress) (w : OpenWorld) : Nat → Nat := fun k => + (((w.accounts.find? self).bind fun acc => acc.storage.find? (EvmYul.UInt256.ofNat k)).map + EvmYul.UInt256.toNat).getD 0 + +/-- Storage `σ'` is reachable from `σ` through the contract's own functions: by successful calls of +`p` in `S`, each from the storage the previous one left. -/ +inductive Reach (S : Sem) (p : S.Prog) : (Nat → Nat) → (Nat → Nat) → Prop + | refl (σ : Nat → Nat) : Reach S p σ σ + | step {σ σ' : Nat → Nat} (call : Call) (obs : Observable) : + slotValue call.storage = σ → S.run p call = some obs → obs.success = true → + Reach S p obs.storage σ' → Reach S p σ σ' + +theorem Reach.trans {S : Sem} {p : S.Prog} {σ σ' σ'' : Nat → Nat} (h : Reach S p σ σ') + (h' : Reach S p σ' σ'') : Reach S p σ σ'' := by + induction h with + | refl => exact h' + | step call obs hs hr hok _ ih => exact .step call obs hs hr hok (ih h') + +/-- **No delegatecall into the contract**, within a call: across each external call, `self`'s +storage changes only by reentrant calls of its own functions. Across transactions the same +relation, `Reach S p deployed (slotValue call.storage)`, restricts the calls a theorem covers to +those from a storage the contract's functions reach from deployment (`Hyps.reachable`). -/ +def NoForeignWrites (S : Sem) (p : S.Prog) (self : InteractionAddress) + (tr : Interaction.Transcript) : Prop := + ∀ c ∈ callsOf tr, Reach S p (selfSlots self c.1) (selfSlots self c.2.2.postWorld) + +/-- The default, fail-open response to a call from `w`: failure, no data, the world unchanged. -/ +def defaultResponse (w : OpenWorld) : CallResponse := + CallResponse.mk false default w (EvmYul.UInt256.ofNat 0) + +/-- Every external call of the transcript got the default, fail-open answer: failure, no data, +the world unchanged. SolidCore's `contextAnswer` gives it to every call that is not a precompile's. -/ +def DefaultCalls (tr : Interaction.Transcript) : Prop := + ∀ c ∈ callsOf tr, c.2.2 = defaultResponse c.1 + +/-- An answerer that gives every external call the default answer. -/ +def DefaultOnCalls (ans : (q : Query) → Answer q) : Prop := + ∀ w r, ans (.external w (.call r)) = Query.defaultAnswer (.external w (.call r)) + +theorem defaultCalls_cons_call {w : OpenWorld} {r : CallRequest} {a : CallResponse} + {tr : Interaction.Transcript} + (ha : a = defaultResponse w) (h : DefaultCalls tr) : + DefaultCalls (⟨.external w (.call r), a⟩ :: tr) := by + intro c hc + simp only [callsOf, List.mem_cons] at hc + rcases hc with rfl | hc + · exact ha + · exact h c hc + +/-- An answerer defaulting on calls yields a transcript with default calls, on every tree. -/ +theorem defaultCalls_transcriptWith {ε α : Type} {ans : (q : Query) → Answer q} + (hans : DefaultOnCalls ans) : ∀ t : Interaction ε α, DefaultCalls (transcriptWith ans t) + | .done _ => fun _ h => by simp [transcriptWith, callsOf] at h + | .request q k => by + have ih := defaultCalls_transcriptWith hans (k (ans q)) + match q with + | .external w (.call r) => + exact defaultCalls_cons_call ((hans w r).trans rfl) ih + | .external w (.create r) => + intro c hc + exact ih c (by simpa [transcriptWith, callsOf] using hc) + | .resource r => + intro c hc + exact ih c (by simpa [transcriptWith, callsOf] using hc) + +/-- **Interface ensures, discharged** where no external call returns. -/ +theorem interfaceEnsures_of_default {ens : CallRequest → CallResponse → Prop} + {tr : Interaction.Transcript} (h : DefaultCalls tr) : InterfaceEnsures ens tr := by + intro c hc hs + rw [h c hc] at hs + cases hs + +/-- **View calls, discharged** where every call gets the default answer. -/ +theorem viewDeterministic_of_default {self : InteractionAddress} {tr : Interaction.Transcript} + (h : DefaultCalls tr) : ViewDeterministic self tr := by + intro c₁ h₁ c₂ h₂ _ _ _ _ _ + rw [h c₁ h₁, h c₂ h₂] + exact ⟨rfl, rfl⟩ + +/-- **Writes by others, discharged** where every call gets the default answer. -/ +theorem noForeignWrites_of_default {S : Sem} {p : S.Prog} {self : InteractionAddress} + {tr : Interaction.Transcript} (h : DefaultCalls tr) : NoForeignWrites S p self tr := by + intro c hc + rw [h c hc] + exact .refl _ + +/-- A static call to target 1 with empty calldata, from the default world. -/ +def staticReq : CallRequest := + { kind := .staticcall, requestedGas := EvmYul.UInt256.ofNat 0, caller := default, + recipient := default, codeAddress := default, transferValue := EvmYul.UInt256.ofNat 0, + apparentValue := EvmYul.UInt256.ofNat 0, calldata := .empty, permission := false } + +/-- The same static call, answered with `ok` and the data `d`. -/ +def staticEx (ok : Bool) (d : ByteArray) : Interaction.Exchange := + ⟨.external default (.call staticReq), + (CallResponse.mk ok d default (EvmYul.UInt256.ofNat 0) : CallResponse)⟩ + +/-- **Satisfiable with calls that return**: the same view call twice, answered alike. -/ +theorem viewDeterministic_twice (self : InteractionAddress) (d : ByteArray) : + ViewDeterministic self [staticEx true d, staticEx true d] := by + intro c₁ h₁ c₂ h₂ _ _ _ _ _ + simp only [callsOf, staticEx, List.mem_cons, List.not_mem_nil, or_false] at h₁ h₂ + rcases h₁ with rfl | rfl <;> rcases h₂ with rfl | rfl <;> exact ⟨rfl, rfl⟩ + +theorem readAgree_refl (self : InteractionAddress) (w : OpenWorld) : ReadAgree self w w := + ⟨fun _ => rfl, fun _ => rfl⟩ + +/-- **Not trivial**: the same view call answered once with success and once without breaks it. -/ +theorem not_viewDeterministic (self : InteractionAddress) : + ¬ ViewDeterministic self [staticEx true .empty, staticEx false .empty] := by + intro h + have := h (default, staticReq, CallResponse.mk true .empty default (EvmYul.UInt256.ofNat 0)) + (by simp [callsOf, staticEx]) (default, staticReq, CallResponse.mk false .empty default + (EvmYul.UInt256.ofNat 0)) (by simp [callsOf, staticEx]) rfl rfl rfl rfl (readAgree_refl _ _) + simp at this + +/-! ## Inline assembly -/ + +open SolidCore.Solidity in +mutual +/-- The statement contains inline assembly. -/ +def stmtHasAsm : Solidity.Stmt → Bool + | .inlineAssembly _ => true + | .assemblyCreate2 _ _ _ _ => true + | .block ss => stmtsHaveAsm ss + | .ifElse _ s none => stmtHasAsm s + | .ifElse _ s (some t) => stmtHasAsm s || stmtHasAsm t + | .whileLoop _ s => stmtHasAsm s + | .doWhile s _ => stmtHasAsm s + | .forLoop none _ _ s => stmtHasAsm s + | .forLoop (some i) _ _ s => stmtHasAsm i || stmtHasAsm s + | .tryCatch _ cs => clausesHaveAsm cs + | .tryCatchReturns _ _ s cs => stmtHasAsm s || clausesHaveAsm cs + | .unchecked s => stmtHasAsm s + | .empty | .varDecl _ _ | .expr _ | .emitEvent _ | .revertCall _ | .returnValues _ | .break + | .continue | .modifierPlaceholder => false + +def stmtsHaveAsm : List Solidity.Stmt → Bool + | [] => false + | s :: ss => stmtHasAsm s || stmtsHaveAsm ss + +def clausesHaveAsm : List Solidity.CatchClause → Bool + | [] => false + | .clause _ _ s :: cs => stmtHasAsm s || clausesHaveAsm cs +end + +/-- A body that may be absent contains inline assembly. -/ +def bodyHasAsm : Option Solidity.Stmt → Bool + | none => false + | some s => stmtHasAsm s + +/-- A contract item contains inline assembly. -/ +def itemHasAsm : Solidity.ContractItem → Bool + | .function f => bodyHasAsm f.body + | .modifierDecl m => bodyHasAsm m.body + | _ => false + +/-- A source item contains inline assembly. -/ +def sourceItemHasAsm : Solidity.SourceItem → Bool + | .contract c => c.items.any itemHasAsm + | .freeFunction f => bodyHasAsm f.body + | _ => false + +/-- **No inline assembly** anywhere in the source unit. SolidCore's type checker rejects inline +assembly, and its AST keeps a block as an unparsed string, so the composition can rely only on +this, which is stronger than README item 5 (raw slots that assembly reaches are disjoint from the +declared variables, and assembly is memory-safe) and implies it: with no assembly there is no +raw slot and no assembly memory access. Contracts with assembly fail closed, at type checking. -/ +def AsmFree (u : Solidity.SourceUnit) : Prop := u.items.any sourceItemHasAsm = false + +instance (u : Solidity.SourceUnit) : Decidable (AsmFree u) := by unfold AsmFree; infer_instance + +/-- A source unit with one contract and one function with body `body`. -/ +def exampleFn (body : Solidity.Stmt) : Solidity.SourceUnit := + Solidity.SourceUnit.mk [.contract (Solidity.ContractDecl.mk .contract "C" false none [] + [.function { body := some body }])] + +/-- **Satisfiable**: a contract with one empty function. -/ +theorem asmFree_example : AsmFree (exampleFn .empty) := by decide + +/-- **Not trivial**: a function whose body is an assembly block. -/ +theorem not_asmFree_example : + ¬ AsmFree (exampleFn (.block [.inlineAssembly "sstore(0, 1)"])) := by + decide + +/-! ## `Math.mulDiv` -/ + +/-- OpenZeppelin's `Math.mulDiv(x, y, d)` on words: `⌊x * y / d⌋`, or a revert (`none`) when `d` is +zero or the quotient does not fit a word. -/ +def ozMulDiv (x y d : Nat) : Option Nat := + if d = 0 ∨ 2 ^ 256 ≤ x * y / d then none else some (x * y / d) + +/-- **`Math.mulDiv` is OpenZeppelin's**: the library function, as a function of its word arguments +to its result or a revert (`impl`), agrees with `ozMulDiv` on every word. -/ +def MulDivSummary (impl : Nat → Nat → Nat → Option Nat) : Prop := + ∀ x y d, x < 2 ^ 256 → y < 2 ^ 256 → d < 2 ^ 256 → impl x y d = ozMulDiv x y d + +/-- **Satisfiable**: by the summary itself. -/ +theorem mulDivSummary_oz : MulDivSummary ozMulDiv := fun _ _ _ _ _ _ => rfl + +/-- **Not trivial**: plain `x * y / d` without the overflow check is not the summary +(`2^255 * 4 / 2` overflows a word). -/ +theorem not_mulDivSummary_unchecked : + ¬ MulDivSummary (fun x y d => if d = 0 then none else some (x * y / d)) := by + intro h + have := h (2 ^ 255) 4 2 (by decide) (by decide) (by decide) + simp [ozMulDiv] at this + +/-- The summary's full-precision meaning: what it returns is the floor of the exact quotient. -/ +theorem ozMulDiv_spec {x y d r : Nat} (h : ozMulDiv x y d = some r) : + 0 < d ∧ r * d ≤ x * y ∧ x * y < (r + 1) * d ∧ r < 2 ^ 256 := by + unfold ozMulDiv at h + split at h + · cases h + · rename_i hn + cases h + have hd : 0 < d := Nat.pos_of_ne_zero (fun h0 => hn (Or.inl h0)) + refine ⟨hd, Nat.div_mul_le_self _ _, ?_, Nat.lt_of_not_le (fun h' => hn (Or.inr h'))⟩ + rw [Nat.mul_comm _ d] + exact Nat.lt_mul_div_succ _ hd + +/-! ## All of it -/ + +/-- The data the precise trusted base is stated over, for a source program `p` in `S`: + +* `keccakInputs call`: the keccak256 preimages the call hashes. Supplied, not derived: SolidCore + hashes inside its interpreter, not through a query, so its runs do not yet expose them. +* `transcript call`: the call's exchanges with the outside world. Supplied: `transcriptWith` + computes it from an interaction tree and an answerer, but `Source.run` does not expose its tree. +* `self`: the contract's address in those worlds; `deployed`: its storage after deployment. +* `ifaceEns`: the external interfaces' ensures, on a request and its response. +* `assumeSites call`: each body with `@custom:assume`s the call runs, with the store it starts + from; `trustedBodies`: each `@custom:trusted` internal function's body, requires and ensures; + `trustedNames`: the `@custom:trusted` external functions. +* `source`: the Solidity source unit SolidCore checked; `mulDiv`: the contract's `Math.mulDiv`, + if it has one. -/ +structure Hyps (S : Sem) (p : S.Prog) where + keccakInputs : Call → Preimages + transcript : Call → Interaction.Transcript + self : InteractionAddress + deployed : Nat → Nat + ifaceEns : CallRequest → CallResponse → Prop + assumeSites : Call → List (Ghost.Stmt × Ghost.Store) + trustedBodies : List (Ghost.Stmt × (Ghost.Store → Prop) × (Ghost.Store → Ghost.Out → Prop)) + trustedNames : List String + source : Solidity.SourceUnit + mulDiv : Option (Nat → Nat → Nat → Option Nat) + +namespace Hyps + +variable {S : Sem} {p : S.Prog} (H : Hyps S p) + +/-- The contract's `Math.mulDiv` is OpenZeppelin's, if it has one. -/ +def MulDivOk : Prop := ∀ f, H.mulDiv = some f → MulDivSummary f + +/-- **The trusted base, precisely**, as `Assumptions` for `spec_of_verdict`: item 2 is +`AssumesHold` at every assume site, `MeetsContract` of every trusted internal body, `TrustedHold` +of the trusted external functions and `InterfaceEnsures`; item 3 `NoForeignWrites` of every call; +item 4 `KeccakSeparated` of the call's preimages; item 5 `AsmFree`; item 6 `MulDivSummary`; item 7 +`ViewDeterministic` of every call. -/ +def toAssumptions (scope : Call → Prop) (b : Bundle) (ctxOf : Call → Ctx) (step : GhostStep) : + Assumptions where + assumptionsHold call := + (∀ x ∈ H.assumeSites call, Core.AssumesHold x.1 x.2) ∧ + (∀ t ∈ H.trustedBodies, Core.MeetsContract t.1 t.2.1 t.2.2) ∧ + TrustedHold S p scope b ctxOf step H.trustedNames ∧ + InterfaceEnsures H.ifaceEns (H.transcript call) + noDelegatecall := ∀ call, NoForeignWrites S p H.self (H.transcript call) + keccakSeparated call := KeccakSeparated (H.keccakInputs call) + asmSlotsDisjoint _ := AsmFree H.source + asmMemorySafe _ := AsmFree H.source + mulDiv := H.MulDivOk + viewCalls := ∀ call, ViewDeterministic H.self (H.transcript call) + +/-- The calls from a storage the contract's own functions reach from deployment: item 3 across +transactions. -/ +def reachable (call : Call) : Prop := Reach S p H.deployed (slotValue call.storage) + +/-- The plain instance: nothing hashed, every external call answered by default, no assumes, no +trusted functions, an assembly-free source `u`, no `Math.mulDiv`. -/ +def plain (S : Sem) (p : S.Prog) (u : Solidity.SourceUnit) (deployed : Nat → Nat) + (transcript : Call → Interaction.Transcript) : Hyps S p := + { keccakInputs := fun _ _ => False, transcript, self := default, deployed, + ifaceEns := fun _ _ => False, assumeSites := fun _ => [], trustedBodies := [], + trustedNames := [], source := u, mulDiv := none } + +/-- **Discharged for a contract with no hashing, no external call that returns, no assume, no +trusted function, no assembly and no `Math.mulDiv`**: every hypothesis holds on every call. The +interface ensures are `False` here, so this holds only because no call returns. -/ +theorem plain_on {S : Sem} {p : S.Prog} {u : Solidity.SourceUnit} {deployed : Nat → Nat} + {transcript : Call → Interaction.Transcript} (hu : AsmFree u) + (ht : ∀ call, DefaultCalls (transcript call)) (scope : Call → Prop) (b : Bundle) + (ctxOf : Call → Ctx) (step : GhostStep) (call : Call) : + ((plain S p u deployed transcript).toAssumptions scope b ctxOf step).On call := by + refine ⟨⟨fun _ h => by simp [plain] at h, fun _ h => by simp [plain] at h, trustedHold_nil, + interfaceEnsures_of_default (ht call)⟩, fun c => noForeignWrites_of_default (ht c), + keccakSeparated_empty, hu, hu, fun _ h => by simp [plain] at h, + fun c => viewDeterministic_of_default (ht c)⟩ + +/-- The empty transcript, of a call that makes no query. -/ +theorem defaultCalls_nil : DefaultCalls [] := fun _ h => by simp [callsOf] at h + +/-- **The whole structure is satisfiable**: on every call, in every semantics. -/ +theorem satisfiable (S : Sem) (p : S.Prog) (scope : Call → Prop) (b : Bundle) + (ctxOf : Call → Ctx) (step : GhostStep) : + ∃ H : Hyps S p, ∀ call, (H.toAssumptions scope b ctxOf step).On call := + ⟨plain S p {} (fun _ => 0) (fun _ => []), + plain_on (by decide) (fun _ => defaultCalls_nil) scope b ctxOf step⟩ + +end Hyps + +/-- **The spec of the bytecode from solar-verify's verdict, under the precise trusted base**: as +`spec_of_verdict`, on the calls of the scope where every hypothesis of `H` holds. -/ +theorem spec_of_verdict_hyps {S T : Sem} {p : S.Prog} {q : T.Prog} {scope : Call → Prop} + {b : Bundle} {ctxOf : Call → Ctx} {step : GhostStep} (H : Hyps S p) + (hwf : b.WF = true) (hopaque : OpaqueInRange b) + (verdict : Verdict S p scope b ctxOf step (H.toAssumptions scope b ctxOf step)) + (stage : Stage S T p q scope) : + Holds T q (fun call => scope call ∧ (H.toAssumptions scope b ctxOf step).On call) b ctxOf + step := + spec_of_verdict hwf hopaque verdict stage + +end SolidCore.Spec.TrustedBase diff --git a/Verify/Spec/TrustedBase/Instances.lean b/Verify/Spec/TrustedBase/Instances.lean new file mode 100644 index 00000000..9b40d92e --- /dev/null +++ b/Verify/Spec/TrustedBase/Instances.lean @@ -0,0 +1,60 @@ +import Verify.Spec.TrustedBase.Hypotheses +import SolidCore.Refinement.Source.C4 +import SolidCore.Refinement.Solar.Counter.Source + +/-! +# The trusted base for c4 and Counter + +c4 (`scripts/refinement/corpus/c4.sol`, the source of the spec corpus's `c4.sol`) and Counter +(`scripts/refinement/counter/counter.sol`) have no inline assembly, no `@custom:assume`, no +`@custom:trusted` function and no `Math.mulDiv`, hash nothing and call nothing. Their trusted base: + +* inline assembly: `AsmFree` of the source units SolidCore checks, by the kernel (`asmFree_c4`, + `asmFree_counter`); +* assume, trusted, `Math.mulDiv`: none to assume (`Hyps.plain`); +* keccak256 and external calls: given that a call hashes nothing and makes no external call, every + hypothesis holds (`c4_on`, `counter_on`). That premise is not yet proved of SolidCore's run: + its interpreter hashes internally and `Source.run` folds its interaction tree without exposing + the transcript. For c4 the spec is in any case proved in Lean of SolidCore and of the bytecode + (`SolidCore.Spec.Solar.C4.holds_bytecode`), without the trusted base. +-/ + +namespace SolidCore.Spec.TrustedBase.Instances + +open SolarTV SolidCore.Spec SolidCore.Spec.TrustedBase + +/-- c4's source has no inline assembly. -/ +theorem asmFree_c4 : AsmFree SolidCore.Refinement.Source.C4.importedSourceUnit := by decide + +/-- Counter's source has no inline assembly. -/ +theorem asmFree_counter : AsmFree SolidCore.Refinement.Source.Counter.importedSourceUnit := by + decide + +/-- **c4's trusted base, discharged** on every call, for any source semantics and program: no +hashing, no external call (the empty transcript), its assembly-free source. -/ +theorem c4_on (S : Sem) (p : S.Prog) (deployed : Nat → Nat) (scope : Call → Prop) (b : Bundle) + (ctxOf : Call → Ctx) (step : GhostStep) (call : Call) : + ((Hyps.plain S p SolidCore.Refinement.Source.C4.importedSourceUnit deployed + (fun _ => [])).toAssumptions scope b ctxOf step).On call := + Hyps.plain_on asmFree_c4 (fun _ => Hyps.defaultCalls_nil) scope b ctxOf step call + +/-- **Counter's trusted base, discharged**, as c4's. -/ +theorem counter_on (S : Sem) (p : S.Prog) (deployed : Nat → Nat) (scope : Call → Prop) + (b : Bundle) (ctxOf : Call → Ctx) (step : GhostStep) (call : Call) : + ((Hyps.plain S p SolidCore.Refinement.Source.Counter.importedSourceUnit deployed + (fun _ => [])).toAssumptions scope b ctxOf step).On call := + Hyps.plain_on asmFree_counter (fun _ => Hyps.defaultCalls_nil) scope b ctxOf step call + +/-- **The spec of the bytecode from solar-verify's verdict on Counter, with the trusted base +discharged**: the verdict and a stage give the spec on the whole scope. -/ +theorem counter_spec_of_verdict {S T : Sem} {p : S.Prog} {q : T.Prog} {scope : Call → Prop} + {b : Bundle} {ctxOf : Call → Ctx} {step : GhostStep} (deployed : Nat → Nat) + (hwf : b.WF = true) (hopaque : OpaqueInRange b) + (verdict : Verdict S p scope b ctxOf step + ((Hyps.plain S p SolidCore.Refinement.Source.Counter.importedSourceUnit deployed + (fun _ => [])).toAssumptions scope b ctxOf step)) + (stage : Stage S T p q scope) : Holds T q scope b ctxOf step := + fun fs hfs => (spec_of_verdict_hyps _ hwf hopaque verdict stage fs hfs).mono fun call h => + ⟨h, counter_on S p deployed scope b ctxOf step call⟩ + +end SolidCore.Spec.TrustedBase.Instances diff --git a/Verify/Spec/TrustedBase/Interface.lean b/Verify/Spec/TrustedBase/Interface.lean new file mode 100644 index 00000000..b94fa88e --- /dev/null +++ b/Verify/Spec/TrustedBase/Interface.lean @@ -0,0 +1,98 @@ +import Verify.Spec.TrustedBase.Hypotheses + +/-! +# Interface ensures from an exported interface spec + +`InterfaceEnsures ens tr` (`Hypotheses.lean`) takes the interfaces' ensures as a predicate on a +request and its response. `ifaceEnsOf` builds that predicate from an interface's exported spec (a +`Bundle` whose `FnSpec`s are the interface's functions), with the meaning `Post` gives a function's +ensures: when the calldata selects a function of the interface (its selector, then clean argument +words of its parameter types) and the call returns clean words of its return types, its ensures +hold of those arguments and results. solar-verify trusts exactly this of every interface call that +returns; `--spec-check` samples it where the implementation is in the file. + +`ctx` is the callee's environment and `st` the state its storage and ghost reads see: an interface's +ensures speak of its arguments and results, which these do not affect. +-/ + +namespace SolidCore.Spec.TrustedBase + +open SolarTV SolidCore.Spec EvmCompiler.Simulation + +/-- A byte array's bytes, as numbers. -/ +def bytesOf (b : ByteArray) : List Nat := b.data.toList.map (·.toNat) + +/-- **The ensures of interface `iface` on one call** (see the module doc). -/ +def ifaceEnsOf (iface : Bundle) (ctx : Ctx) (st : State) (r : CallRequest) (a : CallResponse) : + Prop := + ∀ fs ∈ iface.spec.specs, ∀ args rets, + 4 ≤ (bytesOf r.calldata).length → + bytesWord ((bytesOf r.calldata).take 4) = fs.selector → + decodeWords fs.params (words ((bytesOf r.calldata).drop 4)) = some args → + decodeWords fs.rets (words (bytesOf a.returnData)) = some rets → + iface.satAll fs.ensures (mkEnv ctx args rets st st) + +/-- A call that fails owes no ensures, so `InterfaceEnsures` constrains only returning calls. -/ +theorem interfaceEnsures_of_default' {iface : Bundle} {ctx : Ctx} {st : State} + {tr : Interaction.Transcript} (h : DefaultCalls tr) : + InterfaceEnsures (ifaceEnsOf iface ctx st) tr := + interfaceEnsures_of_default h + +/-! ## Witnesses: an interface `one() returns (uint256)` that ensures `result == 1` -/ + +/-- `function one() external returns (uint256)`, selector `0x12345678`, ensuring `result == 1`. -/ +def oneFn : FnSpec := + { name := "one", selector := 0x12345678, params := [], rets := [.uint 256], payable := false, + requires := [], ensures := [.bin .eq (.ret 0) (.lit 1)], succeedsIf := [] } + +/-- The interface with `one`. -/ +def oneIface : Bundle := + { spec := { name := "IOne", fns := [], invariants := [], ghosts := [], specs := [oneFn] }, + fuel := 1 } + +/-- The calldata of `one()`. -/ +def oneCalldata : ByteArray := ⟨#[0x12, 0x34, 0x56, 0x78]⟩ + +/-- The 32-byte big-endian word `v < 256`. -/ +def smallWord (v : UInt8) : ByteArray := ⟨(List.replicate 31 (0 : UInt8) ++ [v]).toArray⟩ + +/-- A call of `one()` that returns the word `v`. -/ +def oneEx (v : UInt8) : Interaction.Exchange := + ⟨.external default (.call { staticReq with calldata := oneCalldata }), + (CallResponse.mk true (smallWord v) default (EvmYul.UInt256.ofNat 0) : CallResponse)⟩ + +theorem oneCalldata_facts : + 4 ≤ (bytesOf oneCalldata).length ∧ + bytesWord ((bytesOf oneCalldata).take 4) = 0x12345678 ∧ + decodeWords [] (words ((bytesOf oneCalldata).drop 4)) = some [] := by + decide + +theorem decode_smallWord1 : decodeWords [.uint 256] (words (bytesOf (smallWord 1))) = some [1] := by + decide + +theorem decode_smallWord0 : decodeWords [.uint 256] (words (bytesOf (smallWord 0))) = some [0] := by + decide + +/-- **Satisfiable with a call that returns**: `one()` returning 1 meets the interface's ensures. -/ +theorem interfaceEnsures_one (ctx : Ctx) (st : State) : + InterfaceEnsures (ifaceEnsOf oneIface ctx st) [oneEx 1] := by + intro c hc _ fs hfs args rets _ _ hargs hrets + simp only [callsOf, oneEx, List.mem_cons, List.not_mem_nil, or_false] at hc + subst hc + simp only [oneIface, List.mem_cons, List.not_mem_nil, or_false] at hfs + subst hfs + rw [show (oneFn.rets) = [.uint 256] from rfl, decode_smallWord1] at hrets + cases hrets + simp [Bundle.satAll, Bundle.sat, oneFn, eval, mkEnv, BinOp.apply, ofProp] + +/-- **Not trivial**: `one()` returning 0 breaks it. -/ +theorem not_interfaceEnsures_zero (ctx : Ctx) (st : State) : + ¬ InterfaceEnsures (ifaceEnsOf oneIface ctx st) [oneEx 0] := by + intro h + obtain ⟨h4, hsel, hargs⟩ := oneCalldata_facts + have := h (default, { staticReq with calldata := oneCalldata }, + CallResponse.mk true (smallWord 0) default (EvmYul.UInt256.ofNat 0)) (by simp [callsOf, oneEx]) + rfl oneFn (by simp [oneIface]) [] [0] h4 hsel hargs decode_smallWord0 + simp [Bundle.satAll, Bundle.sat, oneFn, eval, mkEnv, BinOp.apply, ofProp] at this + +end SolidCore.Spec.TrustedBase diff --git a/Verify/Tactic.lean b/Verify/Tactic.lean new file mode 100644 index 00000000..b55c491f --- /dev/null +++ b/Verify/Tactic.lean @@ -0,0 +1,110 @@ +import Verify.Run +import Verify.Finite + +/-! +# One tactic for the verification conditions + +`sc_vcgen [defs]` proves the verification conditions of a model on `Abi.fullScope`, the goal +`∀ call, scope call → pre call → vc model (argWords n) post call`, where `defs` are the +definitions to unfold: the scope, the function list, the model, the postcondition and +whatever they mention. It + +1. reduces the scope to `Abi.fullScope` (`vcs_of_fullScope`), one goal per function and + list of argument words, with the call's argument words and initial storage known; +2. introduces the argument words (up to four) and their bounds; +3. computes Loom's weakest precondition of the model with `wp_bind`, `wp_pure` and the + rules of `Verify.Basic` and `Verify.Finite` (`wp_sload`, `wp_sstore`, `wp_revert`, + `wp_ite`, `wp_ofPure`); +4. closes what is left, a goal on words, with a fixed cascade (`sc_close`): split the + `if`s, the conjunctions and the quantifiers, then `simp_all`, `omega`, `bv_omega` and + `decide`. It never calls `bv_decide` or `native_decide`, so its proofs rest on the + kernel alone. + +A scope that is a subset of `Abi.fullScope`, such as the finite `· ∈ Abi.calls fns [s]`, +goes through `vcs_mono` first. +-/ + +namespace SolidCore.Verify + +open Lean Elab Tactic + +/-- The bitwise `&&&`, `|||` and `^^^` terms on `Nat` in `e` that mention no bound variable. -/ +partial def bitTerms (e : Expr) (acc : Array Expr := #[]) : Array Expr := + let acc := + if (e.isAppOfArity ``HXor.hXor 6 || e.isAppOfArity ``HOr.hOr 6 || e.isAppOfArity ``HAnd.hAnd 6) && + !e.hasLooseBVars && e.appFn!.appFn!.appFn!.appFn!.appFn!.appArg! == mkConst ``Nat && + !acc.contains e then acc.push e + else acc + match e with + | .app f a => bitTerms a (bitTerms f acc) + | .lam _ t b _ | .forallE _ t b _ => bitTerms b (bitTerms t acc) + | .letE _ t v b _ => bitTerms b (bitTerms v (bitTerms t acc)) + | .mdata _ b | .proj _ _ b => bitTerms b acc + | _ => acc + +/-- For each bitwise term on `Nat` in the goal, adds the bound `t < 2 ^ n` at the least byte +width `n` its operands fit, as `omega` shows, so that `omega`, which treats the term as an +atom, knows it. -/ +elab "sc_bounds" : tactic => do + let ty ← instantiateMVars (← (← getMainGoal).getType) + for e in bitTerms ty do + let stx ← (← getMainGoal).withContext do Term.exprToSyntax e + for n in (List.range 32).map (8 * · + 8) do + let ok ← try + evalTactic (← `(tactic| have : $stx < 2 ^ $(quote n) := by + first + | exact Nat.xor_lt_two_pow (by omega) (by omega) + | exact Nat.or_lt_two_pow (by omega) (by omega) + | exact Nat.lt_of_le_of_lt Nat.and_le_left (by omega))) + pure true + catch _ => pure false + if ok then break + +/-- The closing cascade on a goal on words. -/ +macro "sc_arith" : tactic => `(tactic| first + | done + | trivial + | rfl + | (simp_all; done) + | omega + | (sc_bounds; omega) + | (congr 1 <;> (sc_bounds; omega)) + | (simp only [Nat.reducePow] at *; sc_bounds; omega) + | bv_omega + | decide + | (simp_all <;> (sc_bounds; omega))) + +/-- Splits a goal on words into its cases and closes each with `sc_arith`. -/ +macro "sc_close" : tactic => `(tactic| ( + try split_ifs + all_goals try dsimp only + all_goals repeat' (first | apply And.intro | intro) + all_goals try split_ifs + all_goals repeat' (first | apply And.intro | intro) + all_goals sc_arith)) + +/-- The verification conditions of a model on `Abi.fullScope` (see the module docs). -/ +syntax "sc_vcgen" (" [" term,* "]")? : tactic + +macro_rules + | `(tactic| sc_vcgen) => `(tactic| sc_vcgen []) + | `(tactic| sc_vcgen [$ts,*]) => do + let ts : Array (TSyntax `Lean.Parser.Tactic.simpLemma) ← + ts.getElems.mapM fun t => `(Lean.Parser.Tactic.simpLemma| $t:term) + `(tactic| set_option linter.unusedSimpArgs false in ( + try simp only [$ts,*] + refine vcs_of_fullScope (by simp [$ts,*]) ?_ + intro fn hfn call args hcall hw hlen hargs hinit hpre + simp only [$ts,*, List.mem_cons, List.not_mem_nil, or_false] at hfn + try casesm* _ ∨ _ + all_goals subst fn + all_goals rcases args with _ | ⟨a1, _ | ⟨a2, _ | ⟨a3, _ | ⟨a4, _⟩⟩⟩⟩ + all_goals try (simp at hlen; done) + all_goals try simp only [List.mem_cons, List.not_mem_nil, or_false, forall_eq_or_imp, + forall_eq, imp_false, not_false_eq_true, implies_true, and_true, IsEmpty.forall_iff] at hargs + all_goals simp only [$ts,*, hw, wp_bind, wp_pure, wp_sload, wp_sstore, wp_revert, wp_ite, + wp_ofPure, List.getD_cons_zero, List.getD_cons_succ, ite_apply, dite_apply, SolidCore.Refinement.slotValue, + List.foldl_cons, List.foldl_nil] + all_goals sc_close)) + +end SolidCore.Verify diff --git a/Verify/VC.lean b/Verify/VC.lean new file mode 100644 index 00000000..2f57ef46 --- /dev/null +++ b/Verify/VC.lean @@ -0,0 +1,68 @@ +import Verify.VC.Term +import Verify.VC.Check +import Verify.VC.Model +import Verify.VC.Obligations +import Verify.VC.Discharge +import Verify.VC.ScriptBinds +import Verify.VC.EndToEnd + +/-! +# solar-verify's verification conditions, checked in Lean + +solar-verify (paradigmxyz/solar, `crates/verify`) proves a Solidity function by sending SMT-LIB to a +solver; its README lists the encoding in `src/vc.rs` as part of its trusted base. This library takes +that encoding out of it, one step at a time: + +* `Term`: the SMT-LIB fragment solar-verify emits, its meaning, and `Valid`, what a verdict of + solar-verify claims of a script (every obligation has no model). +* `Check`: `checkScript`, decided by the kernel, and `checkScript_sound`: a script's obligations, + normalized (definitions inlined, names renamed, conjunctions flattened, range facts derived), give + the obligations of the Lean side. +* `Model`: the generic source stage's tree of a function as a model in `SolM`, the monad of the + Loom generator `SolidCore.Verify` (`Basic`), and `implements_tree`, proved once from `source_run`, + so that Loom's weakest precondition of the model gives a `Triple` against SolidCore's + `Source.run` through `triple_of_wp`. +* `Obligations`: `triple_of_binds` and `triple_of_checked`, the generic theorem from a function the + stage erases to its obligations: valid Lean obligations (or solar-verify's verdict and + `checkScript`) and a binding of the erased tree to them (`Binds`, about the tree alone) give the + function's triple against SolidCore on the stage's scope. `Contracts.Counter.VC.Generic` derives + the counter milestone's `inc_triple` from it. +* `Discharge`: `dischargeScript`, a decision procedure the kernel runs over a whole script (definitions + substituted, read over write, a tableau over the connectives, integer `ite`s and negated + quantifiers, and Fourier-Motzkin over linear constraints), and `dischargeScript_sound`: when it + answers `true`, `Valid` holds, with no solver. It fails closed; `dischargeAt` checks one obligation + (`dischargeScript_of_each`), and `vacuousAt` reports obligations whose hypotheses alone have no model. + `Contracts/{Counter,Token}/VC/Discharged` (scripts/verify/gen-discharged.py) discharge their scripts. +* `ScriptBinds`: a script bound to a program's spec (`holds_of_valid_script`, `holds_of_discharged`). +* `EndToEnd`: `bytecode_of_discharged`, one theorem from a discharged script, its checked obligations + and a function's binding, through a stage, to EthLib's run of the exact bytecode. +* `Contracts/*/VC/Export`: solar-verify's transcripts of `scripts/verify/Counter.sol`, `CounterMilestone.sol` + and `Token.sol` (`solar-verify --dry-run --dump-lean`), and `Contracts/*/VC/Bind`, which checks that each + script prints back to its transcript byte for byte. +* `Contracts.Token.VC.Burn` (its own root, since it imports this one): `Token`'s `burn` end to end. The kernel computes + that `Token` deploys with only `owner` in storage and that the stage erases `burn` to `burnTree`; + `burn_triple` is its ensures clause as a `Triple` against SolidCore, and `burn_obligation` is + solar-verify's obligation for it, normalized by `checkScript` and instantiated at the assignment a + successful call gives. `KernelIdx` makes `Std.HashMap`, the storage of SolidCore's state, reduce in + the kernel (`mkIdx_eq`), which the constructor run needs. +* `Contracts.Token.VC.Transfer`: `Token.transfer`'s three ensures clauses on distinct addresses as a `Triple` + against SolidCore (`transfer_triple`), each read off solar-verify's checked obligation through the + binding `trStore_eval`: SolidCore's storage after the call, read through `balanceOf`'s layout, is + solar-verify's array term at the assignment the call binds. Injectivity of the mapping slot on + address keys (`HashInj`) is a hypothesis of the theorem. `Contracts.Token.VC.Mutants`: for a one-line source + mutant and a one-line spec mutant of `Token.sol`, exported by the same solar-verify, `checkScript` + rejects the obligations `transfer`'s clauses need. +* `Contracts.Counter.VC.Inc`: the certified counter milestone's `inc` (`scripts/refinement/counter/counter.sol`, + annotated in `scripts/verify/CounterMilestone.sol`). `inc_triple`: on the stage's scope `inc` + succeeds exactly when `x + d < 2 ^ 256`, then slot 0 holds `x + d` and every other slot is unchanged. + solar-verify's obligation for its clause is valid by its own encoding (`x + d = x + d` once its + definition is inlined), so the theorem takes no verdict: `inc_check` ties solar-verify's script to the + Lean obligation and `inc_binding` ties solar-verify's encoded effect and guard to what SolidCore runs. + `Contracts.Counter.VC.Mutants`: `checkScript` rejects a one-line source mutant and a one-line spec + mutant. + +Nothing here uses `native_decide`, `bv_decide` or `ofReduceBool`, or imports +`SolidCore.Verify.Finite`. `Bind`'s check runs Lean's evaluator (`#guard`), not the kernel: it +checks that the generated module is the transcript, as `scripts/verify/check.sh` checks that the +transcript is solar-verify's. +-/ diff --git a/Verify/VC/Cert.lean b/Verify/VC/Cert.lean new file mode 100644 index 00000000..53161bab --- /dev/null +++ b/Verify/VC/Cert.lean @@ -0,0 +1,455 @@ +import Verify.VC.Discharge + +/-! +# Certificate-checked discharge + +The search of `refuteOb` (Verify/VC/Discharge.lean) is cheap compiled and expensive in the kernel: +every case split first runs Fourier-Motzkin to exhaustion, and each elimination picks its term by +counting every candidate. Here the search runs compiled (`certOb`, not trusted) and records what it +found as a `Cert`: which case splits it took, and, where a branch closes, the nonnegative +multipliers of the branch's constraints `l ≤ 0` whose sum is a positive constant (a Farkas +combination, read off Fourier-Motzkin's eliminations). The kernel then only replays the tableau +along the certificate and adds up the multiplied constraints (`refuteC`, `farkas`); +`refuteObC_sound` shows that an accepted certificate refutes the obligation, whatever produced +it. A wrong certificate makes the check answer `false`: it fails closed. +-/ + +namespace SolidCore.Verify.VC + +/-- How one branch of the tableau closes: `leaf w` at its next case split (or when its facts run +out) by the constraints multiplied by `w`, `br hs` by taking that split, one certificate per case. -/ +inductive Cert where + | leaf (w : List Nat) + | br (hs : List Cert) + /-- At a case split: move its fact to the end of the list, so that the facts after it are read + first. -/ + | later (c : Cert) + /-- At the top only: read only the facts the mask keeps (a missing entry keeps the fact). -/ + | keep (m : List Bool) (c : Cert) + deriving Repr, Inhabited + +/-- The certificate under a later step, if it is one. -/ +def Cert.later? : Cert → Option Cert + | .later c => some c + | _ => none + +/-- `Σ w_i * l_i`, skipping zero multipliers. -/ +def farkasSum : List Nat → List Lin → Lin + | w :: ws, l :: ls => if w = 0 then farkasSum ws ls else (l.scale w).add (farkasSum ws ls) + | _, _ => ⟨0, []⟩ + +/-- The constraints `l ≤ 0`, multiplied by `w` and added up, give a positive constant. -/ +def farkas (w : List Nat) (cs : List Lin) : Bool := + let l := (farkasSum w cs).norm + l.cs.isEmpty && decide (0 < l.k) + +/-- A linear form with the equations substituted in its terms, merged again. -/ +def Lin.substE (eqs : List (Tm × Tm)) (l : Lin) : Lin := + (Lin.mk l.k (l.cs.map fun p => (substN eqs substFuel p.1, p.2))).norm + +/-- The facts a mask keeps; a missing entry keeps the fact. -/ +def keepMask : List Bool → List Tm → List Tm + | b :: bs, t :: ts => if b then t :: keepMask bs ts else keepMask bs ts + | [], ts => ts + | _ :: _, [] => [] + +theorem mem_keepMask : ∀ (m : List Bool) (ts : List Tm) {t : Tm}, t ∈ keepMask m ts → t ∈ ts + | b :: bs, u :: us, t, h => by + simp only [keepMask] at h + split at h + · rcases List.mem_cons.mp h with rfl | h + · simp + · exact List.mem_cons_of_mem _ (mem_keepMask bs us h) + · exact List.mem_cons_of_mem _ (mem_keepMask bs us h) + | [], _, _, h => by simpa [keepMask] using h + | _ :: _, [], _, h => by simp [keepMask] at h + +/-- The tableau of `refute`, along a certificate: no search, and Fourier-Motzkin replaced by the +check of a Farkas combination. -/ +def refuteC (ks : List String) : Nat → List Tm → List Lin → Cert → Bool + | 0, _, _, _ => false + | _ + 1, [], cs, c => match c with + | .leaf w => farkas w cs + | _ => false + | n + 1, t :: rest, cs, c => + match step ks t with + | .drop => refuteC ks n rest cs c + | .closed => true + | .facts ts => refuteC ks n (ts ++ rest) cs c + | .cons ls => refuteC ks n rest (ls ++ cs) c + | .split bs => match c with + | .leaf w => farkas w cs + | .later c' => refuteC ks n (rest ++ [t]) cs c' + | .keep _ _ => false + | .br hs => bs.length == hs.length && (bs.zip hs).all fun p => refuteC ks n (p.1 ++ rest) cs p.2 + | .ite c' t1 t2 => match c with + | .leaf w => farkas w cs + | .br [h1, h2] => + refuteC ks n (c' :: ((t1 :: rest).map (resolve c' true resolveFuel)).map + (substN (iteEqs c') substFuel)) (cs.map (Lin.substE (iteEqs c'))) h1 && + refuteC ks n (neg c' :: (t2 :: rest).map (resolve c' false resolveFuel)) cs h2 + | .later c'' => refuteC ks n (rest ++ [t]) cs c'' + | _ => false + | .skolem x t => + if fresh x rest cs then refuteC ks n (t :: rest) cs c + else if fresh (x ++ "'") (t :: rest) cs then + refuteC ks n (t.subst .int x (.ivar (x ++ "'")) :: rest) cs c + else refuteC ks n rest cs c + +/-- `refuteOb` along a certificate; `d` adds the facts of `mod` and `div`. -/ +def refuteObC (fs : List Tm) (d : Bool) (c : Cert) : Bool := + let eqs := fs.filterMap eqOf? + let gs := (fs.filter fun t => (eqOf? t).isNone).map fun t => rowN rowFuel (substN eqs substFuel t) + let rs := relevant gs + let ts := if d then goalFirst rs ++ divFacts rs else goalFirst rs + match c with + | .keep m c' => refuteC (goalBinders rs) stepFuel (keepMask m ts) [] c' + | c => refuteC (goalBinders rs) stepFuel ts [] c + +/-- `dischargeAt` along a certificate. -/ +def dischargeAtC (cs : List Cmd) (i : Nat) (d : Bool) (c : Cert) : Bool := + let fs := (obligations cs).getD i [] + isProbe fs || refuteObC fs d c + +/-! ## Producing certificates (compiled, not trusted) -/ + +/-- `w * a` plus `v * b`, pointwise. -/ +def combW (v : Nat) (a : List Nat) (w : Nat) (b : List Nat) : List Nat := + List.zipWith (fun x y => v * x + w * y) a b + +/-- `elim`, each constraint carrying its multipliers of the input constraints. -/ +def elimW (x : Tm) (cs : List (Lin × List Nat)) : List (Lin × List Nat) := + let pos := cs.filter fun l => decide (0 < coeff l.1 x) + let neg := cs.filter fun l => decide (coeff l.1 x < 0) + cs.filter (fun l => decide (coeff l.1 x = 0)) ++ + pos.flatMap fun p => neg.map fun q => + (((p.1.scale (-(coeff q.1 x))).add (q.1.scale (coeff p.1 x))).norm, + combW (-(coeff q.1 x)).toNat p.2 (coeff p.1 x).toNat q.2) + +/-- `fm`, returning the multipliers of a contradiction. -/ +def fmW : Nat → List (Lin × List Nat) → Option (List Nat) + | 0, _ => none + | n + 1, cs => + let cs := cs.filter fun l => !(l.1.cs.isEmpty && decide (l.1.k ≤ 0)) + match cs.find? (fun l => l.1.cs.isEmpty && decide (0 < l.1.k)) with + | some l => some l.2 + | none => + let ls := cs.map (·.1) + match pickVar ls with + | none => none + | some x => if elimCost ls x ≤ 256 ∧ cs.length ≤ 512 then fmW n (elimW x cs) else none + +/-- Fourier-Motzkin on `cs`, as a certificate (multipliers tracked only once `fm` succeeds). -/ +def fmCert (F : Nat) (cs : List Lin) : Option Cert := + if !fm F cs then none else + let m := cs.length + let unit := fun i => (List.range m).map fun j => if i = j then 1 else 0 + (fmW F (cs.zipIdx.map fun (l, i) => (l, unit i))).map .leaf + +/-- `refute`, returning the certificate of what it found. -/ +def refuteG (F : Nat) (ks : List String) : Nat → Nat → List Tm → List Lin → Option Cert + | 0, _, _, _ => none + | _ + 1, _, [], cs => fmCert F cs + | n + 1, b, t :: rest, cs => + match step ks t with + | .drop => refuteG F ks n b rest cs + | .closed => some (.leaf []) + | .facts ts => refuteG F ks n b (ts ++ rest) cs + | .cons ls => refuteG F ks n b rest (ls ++ cs) + | .split bs => match fmCert F cs with + | some c => some c + | none => if b = 0 then none else + (bs.mapM fun ts => refuteG F ks n (b - 1) (ts ++ rest) cs).map .br + | .ite c t1 t2 => match fmCert F cs with + | some w => some w + | none => if b = 0 then none else do + let h1 ← refuteG F ks n (b - 1) + (c :: ((t1 :: rest).map (resolve c true resolveFuel)).map (substN (iteEqs c) substFuel)) + (cs.map (Lin.substE (iteEqs c))) + let h2 ← refuteG F ks n (b - 1) (neg c :: (t2 :: rest).map (resolve c false resolveFuel)) cs + some (.br [h1, h2]) + | .skolem x t => + if fresh x rest cs then refuteG F ks n b (t :: rest) cs + else if fresh (x ++ "'") (t :: rest) cs then + refuteG F ks n b (t.subst .int x (.ivar (x ++ "'")) :: rest) cs + else refuteG F ks n b rest cs + +/-- `refuteOb`, returning which fact list it used and its certificate. -/ +def certOb (fs : List Tm) : Option (Bool × Cert) := + let eqs := fs.filterMap eqOf? + let gs := (fs.filter fun t => (eqOf? t).isNone).map fun t => rowN rowFuel (substN eqs substFuel t) + let rs := relevant gs + if refute fmFuel (goalBinders rs) stepFuel splitFuel (goalFirst rs) [] then + (refuteG fmFuel (goalBinders rs) stepFuel splitFuel (goalFirst rs) []).map fun c => (false, c) + else (refuteG fmFuel (goalBinders rs) stepFuel splitFuel (goalFirst rs ++ divFacts rs) []).map + fun c => (true, c) + +/-- The certificate of obligation `i`, checked compiled before it is printed. -/ +def certAt (cs : List Cmd) (i : Nat) : Option (Bool × Cert) := + let fs := (obligations cs).getD i [] + if isProbe fs then some (false, .leaf []) else + match certOb fs with + | some (d, c) => if refuteObC fs d c then some (d, c) else none + | none => none + +/-! ## Soundness -/ + +section Sound + +variable (σ : Env) + +theorem farkasSum_le : ∀ (w : List Nat) (cs : List Lin), (∀ l ∈ cs, l.eval σ ≤ 0) → + (farkasSum w cs).eval σ ≤ 0 + | w :: ws, l :: ls, h => by + have hl := h l (by simp) + have ih := farkasSum_le ws ls (fun l' hl' => h l' (by simp [hl'])) + simp only [farkasSum] + split + · exact ih + · rw [Lin.eval_add, Lin.eval_scale] + have : (0 : Int) ≤ (w : Int) := Int.natCast_nonneg w + nlinarith + | [], _, _ => by simp [farkasSum, Lin.eval, sumCs] + | _ :: _, [], _ => by simp [farkasSum, Lin.eval, sumCs] + +theorem farkas_sound {w : List Nat} {cs : List Lin} (h : farkas w cs = true) + (hc : ∀ l ∈ cs, l.eval σ ≤ 0) : False := by + have hle := farkasSum_le σ w cs hc + rw [← Lin.eval_norm] at hle + simp only [farkas, Bool.and_eq_true, List.isEmpty_iff, decide_eq_true_eq] at h + generalize (farkasSum w cs).norm = l at h hle + simp only [Lin.eval, h.1, sumCs] at hle + omega + +theorem sumCs_substN {eqs : List (Tm × Tm)} (he : ∀ e ∈ eqs, e.1.eval σ = e.2.eval σ) : + ∀ l : List (Tm × Int), sumCs σ (l.map fun p => (substN eqs substFuel p.1, p.2)) = sumCs σ l + | [] => rfl + | p :: ps => by + simp only [List.map_cons, sumCs, substN_eval _ _ σ he, sumCs_substN he ps] + +theorem Lin.eval_substE {eqs : List (Tm × Tm)} (he : ∀ e ∈ eqs, e.1.eval σ = e.2.eval σ) (l : Lin) : + (l.substE eqs).eval σ = l.eval σ := by + simp only [Lin.substE, Lin.eval_norm] + simp only [Lin.eval, sumCs_substN σ he] + +theorem mem_zip_of_mem {α β : Type} {as : List α} {bs : List β} (hl : as.length = bs.length) {a : α} + (ha : a ∈ as) : ∃ b, (a, b) ∈ as.zip bs := by + obtain ⟨i, hi, rfl⟩ := List.getElem_of_mem ha + exact ⟨bs[i]'(hl ▸ hi), by + have : (as.zip bs)[i]'(by simp [hl] at hi ⊢; omega) = (as[i], bs[i]'(hl ▸ hi)) := by simp + rw [← this]; exact List.getElem_mem _⟩ + +theorem refuteC_sound (ks : List String) : ∀ (n : Nat) (σ : Env) (ts : List Tm) (cs : List Lin) (k : Cert), + refuteC ks n ts cs k = true → (∀ t ∈ ts, t.Holds σ) → (∀ l ∈ cs, l.eval σ ≤ 0) → False + | 0, _, _, _, _, h, _, _ => by simp [refuteC] at h + | n + 1, σ, [], cs, k, h, _, hc => by + cases k with + | leaf w => exact farkas_sound σ (by simpa [refuteC] using h) hc + | br _ => simp [refuteC] at h + | later _ => simp [refuteC] at h + | keep _ _ => simp [refuteC] at h + | n + 1, σ, t :: rest, cs, k, h, ht, hc => by + have hlater : ∀ k', refuteC ks n (rest ++ [t]) cs k' = true → False := fun k' h' => by + refine refuteC_sound ks n σ _ cs k' h' ?_ hc + intro u hu + rcases List.mem_append.mp hu with hu | hu + · exact ht u (List.mem_cons_of_mem _ hu) + · exact ht u (by simp at hu; simp [hu]) + simp only [refuteC] at h + have hst := step_sound σ ks t (ht t (by simp)) + have hr : ∀ u ∈ rest, u.Holds σ := fun u hu => ht u (by simp [hu]) + generalize step ks t = s at h hst + cases s with + | drop => exact refuteC_sound ks n σ rest cs k h hr hc + | closed => exact hst + | facts us => + refine refuteC_sound ks n σ _ cs k h ?_ hc + intro u hu + rcases List.mem_append.mp hu with hu | hu + · exact hst u hu + · exact hr u hu + | cons ls => + refine refuteC_sound ks n σ rest _ k h hr ?_ + intro l hl + rcases List.mem_append.mp hl with hl | hl + · exact hst l hl + · exact hc l hl + | split bs => + cases k with + | leaf w => exact farkas_sound σ h hc + | later k' => exact hlater k' h + | keep _ _ => simp at h + | br hs => + simp only [Bool.and_eq_true, beq_iff_eq, List.all_eq_true] at h + obtain ⟨us, hus, hall⟩ := hst + obtain ⟨hh, hmem⟩ := mem_zip_of_mem h.1 hus + refine refuteC_sound ks n σ _ cs hh (h.2 _ hmem) ?_ hc + intro u hu + rcases List.mem_append.mp hu with hu | hu + · exact hall u hu + · exact hr u hu + | ite c t1 t2 => + cases k with + | leaf w => exact farkas_sound σ h hc + | later k' => exact hlater k' h + | keep _ _ => simp at h + | br hs => + match hs, h with + | [h1, h2], h => + rw [Bool.and_eq_true] at h + have hres : ∀ (b : Bool), (if b then c.Holds σ else ¬ c.Holds σ) → ∀ u ∈ rest, + (resolve c b resolveFuel u).Holds σ := by + intro b hb u hu + simp only [Tm.Holds] + rw [resolve_eval σ c b hb] + exact hr u hu + rcases hst with ⟨hc1, ht1⟩ | ⟨hc2, ht2⟩ + · have he := iteEqs_sound σ c hc1 + refine refuteC_sound ks n σ _ _ h1 h.1 ?_ ?_ + rotate_left + · intro l hl + obtain ⟨l', hl', rfl⟩ := List.mem_map.mp hl + rw [Lin.eval_substE σ he] + exact hc l' hl' + intro u hu + rcases List.mem_cons.mp hu with rfl | hu + · exact hc1 + obtain ⟨v, hv, rfl⟩ := List.mem_map.mp hu + obtain ⟨w, hw, rfl⟩ := List.mem_map.mp hv + simp only [Tm.Holds] + rw [substN_eval _ _ σ he] + rcases List.mem_cons.mp hw with rfl | hw + · rw [resolve_eval σ c true (by simpa using hc1)] + exact ht1 + · exact hres true (by simpa using hc1) w hw + · refine refuteC_sound ks n σ _ cs h2 h.2 ?_ hc + intro u hu + simp only [List.mem_cons, List.map_cons, List.mem_map] at hu + rcases hu with rfl | rfl | ⟨u', hu', rfl⟩ + · exact (holds_neg σ c).mpr hc2 + · simp only [Tm.Holds] + rw [resolve_eval σ c false (by simpa using hc2)] + exact ht2 + · exact hres false (by simpa using hc2) u' hu' + | [], h => simp at h + | [_], h => simp at h + | _ :: _ :: _ :: _, h => simp at h + | skolem x u => + have h' : (if fresh x rest cs then refuteC ks n (u :: rest) cs k + else if fresh (x ++ "'") (u :: rest) cs then + refuteC ks n (u.subst .int x (.ivar (x ++ "'")) :: rest) cs k + else refuteC ks n rest cs k) = true := h + by_cases hf : fresh x rest cs + · simp only [hf, ↓reduceIte] at h' + obtain ⟨m, hm⟩ := hst + simp only [fresh, Bool.and_eq_true, List.all_eq_true] at hf + obtain ⟨hf1, hf2⟩ := hf + have hx1 : ∀ v ∈ rest, x ∉ v.vars := fun v hv hxv => by + have := hf1 v hv + simp [hxv] at this + have hx2 : ∀ l ∈ cs, ∀ p ∈ l.cs, x ∉ p.1.vars := fun l hl p hp hxp => by + have := hf2 l hl p hp + simp [hxp] at this + refine refuteC_sound ks n (σ.setI x m) _ cs k h' ?_ ?_ + · intro v hv + rcases List.mem_cons.mp hv with rfl | hv + · exact hm + · have := hr v hv + simp only [Tm.Holds] at this ⊢ + rwa [Tm.eval_congr v (σ := σ.setI x m) (τ := σ) rfl (fun y hy => agree_setI_ne (x := x) m (fun e => hx1 v hv (e ▸ hy)))] + · intro l hl + have := hc l hl + simp only [Lin.eval] at this ⊢ + rwa [sumCs_congr (τ := σ.setI x m) (ρ := σ) rfl l.cs (fun p hp y hy => agree_setI_ne (x := x) m (fun e => hx2 l hl p hp (e ▸ hy)))] + · simp only [hf, Bool.false_eq_true, ↓reduceIte] at h' + by_cases hf' : fresh (x ++ "'") (u :: rest) cs + · simp only [hf', ↓reduceIte] at h' + obtain ⟨m, hm⟩ := hst + simp only [fresh, Bool.and_eq_true, List.all_eq_true] at hf' + obtain ⟨hf1, hf2⟩ := hf' + have hx1 : ∀ v ∈ u :: rest, x ++ "'" ∉ v.vars := fun v hv hxv => by + have := hf1 v hv + simp [hxv] at this + have hx2 : ∀ l ∈ cs, ∀ p ∈ l.cs, x ++ "'" ∉ p.1.vars := fun l hl p hp hxp => by + have := hf2 l hl p hp + simp [hxp] at this + refine refuteC_sound ks n (σ.setI (x ++ "'") m) _ cs k h' ?_ ?_ + · intro v hv + rcases List.mem_cons.mp hv with hvu | hv + · subst hvu + simp only [Tm.Holds] at hm ⊢ + rw [Tm.eval_subst .int x (.ivar (x ++ "'")) rfl u _ (fun y hy hyx => by + simp only [Tm.vars, List.mem_cons, List.not_mem_nil, or_false] at hyx + subst hyx + exact hx1 u (by simp) (Tm.mem_vars_of_binders u hy))] + have e1 : (Tm.ivar (x ++ "'")).eval (σ.setI (x ++ "'") m) = .int m := by + simp [Tm.eval, Env.setI] + rw [e1] + have e2 : u.eval ((σ.setI (x ++ "'") m).set .int x (.int m)) = u.eval (σ.setI x m) := + Tm.eval_congr u (σ := (σ.setI (x ++ "'") m).set .int x (.int m)) (τ := σ.setI x m) rfl + (fun y hy => by + have hy' : y ≠ x ++ "'" := fun e => hx1 u (by simp) (e ▸ hy) + refine ⟨?_, rfl, rfl, rfl⟩ + simp only [Env.set, Env.setI, Value.toInt] + by_cases hyx : y = x <;> simp [hyx, hy']) + rw [e2] + exact hm + · have := hr v hv + simp only [Tm.Holds] at this ⊢ + rwa [Tm.eval_congr v (σ := σ.setI (x ++ "'") m) (τ := σ) rfl + (fun y hy => agree_setI_ne (x := x ++ "'") m + (fun e => hx1 v (List.mem_cons_of_mem _ hv) (e ▸ hy)))] + · intro l hl + have := hc l hl + simp only [Lin.eval] at this ⊢ + rwa [sumCs_congr (τ := σ.setI (x ++ "'") m) (ρ := σ) rfl l.cs + (fun p hp y hy => agree_setI_ne (x := x ++ "'") m (fun e => hx2 l hl p hp (e ▸ hy)))] + · simp only [hf', Bool.false_eq_true, ↓reduceIte] at h' + exact refuteC_sound ks n σ rest cs k h' hr hc + +theorem refuteObC_sound {fs : List Tm} {d : Bool} {c : Cert} (h : refuteObC fs d c = true) : + ∀ σ : Env, ¬ ∀ t ∈ fs, t.Holds σ := by + intro σ hσ + have he : ∀ e ∈ fs.filterMap eqOf?, e.1.eval σ = e.2.eval σ := by + intro e hm + obtain ⟨t, ht, hte⟩ := List.mem_filterMap.mp hm + exact eqOf_sound σ hte (hσ t ht) + have hg : ∀ t ∈ relevant ((fs.filter fun t => (eqOf? t).isNone).map + fun t => rowN rowFuel (substN (fs.filterMap eqOf?) substFuel t)), t.Holds σ := by + intro t ht + simp only [relevant, List.mem_filter] at ht + obtain ⟨t', ht', rfl⟩ := List.mem_map.mp ht.1 + simp only [Tm.Holds] + rw [rowN_eval _ σ, substN_eval _ _ σ he] + exact hσ t' (List.mem_filter.mp ht').1 + simp only [refuteObC] at h + have hall : ∀ t ∈ (if d then goalFirst (relevant ((fs.filter fun t => (eqOf? t).isNone).map + fun t => rowN rowFuel (substN (fs.filterMap eqOf?) substFuel t))) ++ + divFacts (relevant ((fs.filter fun t => (eqOf? t).isNone).map + fun t => rowN rowFuel (substN (fs.filterMap eqOf?) substFuel t))) + else goalFirst (relevant ((fs.filter fun t => (eqOf? t).isNone).map + fun t => rowN rowFuel (substN (fs.filterMap eqOf?) substFuel t)))), t.Holds σ := by + intro t ht + cases d with + | false => exact hg t (mem_goalFirst ht) + | true => + rcases List.mem_append.mp ht with ht | ht + · exact hg t (mem_goalFirst ht) + · exact divFacts_holds σ _ t ht + split at h + · exact refuteC_sound _ _ σ _ [] _ h (fun t ht => hall t (mem_keepMask _ _ ht)) (by simp) + · exact refuteC_sound _ _ σ _ [] _ h hall (by simp) + +end Sound + +/-- **The discharge along certificates, one obligation at a time.** -/ +theorem dischargeScript_of_certs (cs : List Cmd) + (h : ∀ i < (obligations cs).length, ∃ d c, dischargeAtC cs i d c = true) : Valid cs := by + intro fs hfs hp σ + obtain ⟨i, hi, rfl⟩ := List.getElem_of_mem hfs + obtain ⟨d, c, hc⟩ := h i hi + simp only [dischargeAtC, List.getD_eq_getElem?_getD, List.getElem?_eq_getElem hi, + Option.getD_some, hp, Bool.false_or] at hc + exact refuteObC_sound hc σ + +end SolidCore.Verify.VC diff --git a/Verify/VC/Check.lean b/Verify/VC/Check.lean new file mode 100644 index 00000000..cbd0472b --- /dev/null +++ b/Verify/VC/Check.lean @@ -0,0 +1,877 @@ +import Verify.VC.Term + +/-! +# Checking solar-verify's obligations against the Lean generator's + +`checkOb e (hs, φ)` decides, by evaluation, that an obligation `e` solar-verify sent the solver (the +facts one `check-sat` reads) implies the obligation `hs ⟹ φ` the Lean generator computes: +`checkOb_sound` shows that if `e` has no model then every assignment that makes `hs` hold makes `φ` +hold. The check normalizes `e` and compares it with the Lean obligation by syntax: + +1. `inline`: a fact `(= x t)`, where `x` is a constant that `t` does not mention, of `t`'s sort, is a + definition (solar-verify names its intermediate terms so): `x` is replaced by `t` in the other + facts and the fact dropped. An obligation without a model keeps none (`inline_sound`). +2. `rename`: solar-verify's constants are `name@N` and its bound variables `name!N`; each is + renamed to `name` (`strip`), provided no renaming makes a bound variable meet another name in its + scope (`renameOk`). +3. The last fact must be `(not φ')` with `φ'` equal to `φ`. Every other fact, its conjunctions + flattened, must be one of `hs`, a range fact `0 ≤ t` or `t ≤ M` that `hs` imply (`inRange`: + through `select`, `store` and `ite`), or a range fact `0 ≤ x` or `x ≤ M` (`0 ≤ M`) of a constant the + Lean obligation does not mention, which 0 satisfies. + +Each step is proved once, so the check is sound whatever the terms are; a step that does not +apply leaves the obligation unmatched, and the check fails. +-/ + +namespace SolidCore.Verify.VC + +/-! ## Variables -/ + +mutual +/-- Every name a term mentions, free or bound, of any sort. -/ +def Tm.vars : Tm → List String + | .num _ | .tt | .ff => [] + | .ivar x | .bvar x | .avar x | .a2var x => [x] + | .app _ args => Tm.varsList args + | .all x body => x :: Tm.vars body +def Tm.varsList : List Tm → List String + | [] => [] + | t :: ts => Tm.vars t ++ Tm.varsList ts +end + +/-- Two assignments agree on a name, in every sort. -/ +def Env.Agree (σ τ : Env) (x : String) : Prop := + σ.i x = τ.i x ∧ σ.b x = τ.b x ∧ σ.a x = τ.a x ∧ σ.a2 x = τ.a2 x + +theorem Env.Agree.setI {σ τ : Env} {x : String} (h : σ.Agree τ x) (y : String) (n : Int) : + (σ.setI y n).Agree (τ.setI y n) x := by + obtain ⟨h1, h2, h3, h4⟩ := h + refine ⟨?_, h2, h3, h4⟩ + by_cases hx : x = y <;> simp [Env.setI, hx, h1] + +mutual +theorem Tm.eval_congr : ∀ (t : Tm) {σ τ : Env}, σ.u = τ.u → (∀ x ∈ t.vars, σ.Agree τ x) → + t.eval σ = t.eval τ + | .num _, _, _, _, _ => rfl + | .tt, _, _, _, _ => rfl + | .ff, _, _, _, _ => rfl + | .ivar x, _, _, _, h => by simp [Tm.eval, (h x (by simp [Tm.vars])).1] + | .bvar x, _, _, _, h => by simp [Tm.eval, (h x (by simp [Tm.vars])).2.1] + | .avar x, _, _, _, h => by simp [Tm.eval, (h x (by simp [Tm.vars])).2.2.1] + | .a2var x, _, _, _, h => by simp [Tm.eval, (h x (by simp [Tm.vars])).2.2.2] + | .app f args, σ, τ, hu, h => by + simp only [Tm.eval] + rw [Tm.evalList_congr args hu (by simpa [Tm.vars] using h), hu] + | .all x body, σ, τ, hu, h => by + simp only [Tm.eval] + have : ∀ n : Int, Tm.eval (σ.setI x n) body = Tm.eval (τ.setI x n) body := fun n => + Tm.eval_congr body hu fun y hy => Env.Agree.setI (h y (by simp [Tm.vars, hy])) x n + simp only [this] +theorem Tm.evalList_congr : ∀ (ts : List Tm) {σ τ : Env}, σ.u = τ.u → + (∀ x ∈ Tm.varsList ts, σ.Agree τ x) → Tm.evalList σ ts = Tm.evalList τ ts + | [], _, _, _, _ => rfl + | t :: ts, σ, τ, hu, h => by + simp only [Tm.evalList] + rw [Tm.eval_congr t hu (fun x hx => h x (by simp [Tm.varsList, hx])), + Tm.evalList_congr ts hu (fun x hx => h x (by simp [Tm.varsList, hx]))] +end + +/-! ## Sorts of values -/ + +/-- The sort of a value. -/ +def Value.sortOf : Value → Srt + | .int _ => .int + | .prop _ => .bool + | .arr _ => .arr + | .arr2 _ => .arr2 + +/-- Values whose sorts are the ones the list gives, where it gives one. -/ +def SortsAgree : List (Option Srt) → List Value → Prop + | [], [] => True + | o :: os, v :: vs => (∀ s, o = some s → v.sortOf = s) ∧ SortsAgree os vs + | _, _ => False + +/-- An uninterpreted function's application is an integer. -/ +theorem applyOp_not_op (u : String → List Int → Int) {f : String} (hf : isOpName f = false) + (vs : List Value) : applyOp u f vs = .int (u f (vs.map Value.toInt)) := by + unfold applyOp + split <;> simp_all [isOpName, isOpName.constName, isOpName.const2Name] + +theorem sortOp_not_op {f : String} (hf : isOpName f = false) (os : List (Option Srt)) : + sortOp f os = if isOpName f = false ∧ os ≠ [] then some .int else none := by + unfold sortOp + split <;> simp_all [isOpName, isOpName.constName, isOpName.const2Name] + +theorem applyOp_sortOf (u : String → List Int → Int) (f : String) : + ∀ (os : List (Option Srt)) (vs : List Value), + SortsAgree os vs → ∀ {s : Srt}, sortOp f os = some s → (applyOp u f vs).sortOf = s := by + intro os vs h s hs + by_cases hf : isOpName f = false + · rw [sortOp_not_op hf] at hs + rw [applyOp_not_op u hf] + split at hs <;> simp_all [Value.sortOf] + unfold sortOp at hs + split at hs + all_goals first + | (simp at hs; done) + | (simp [hf] at hs; done) + | (rcases vs with _ | ⟨v1, _ | ⟨v2, _ | ⟨v3, _ | ⟨v4, vs⟩⟩⟩⟩ <;> + simp_all [SortsAgree, applyOp, Value.sortOf] <;> done) + | (simp only [Option.some.injEq] at hs; subst hs + rcases vs with _ | ⟨v1, _ | ⟨v2, _ | ⟨v3, _ | ⟨v4, vs⟩⟩⟩⟩ <;> (try cases v1) <;> + simp_all [SortsAgree, applyOp, Value.sortOf, Value.store, Value.select] <;> done) + | skip + all_goals + split at hs <;> simp at hs + subst_vars + rcases vs with _ | ⟨c, _ | ⟨v1, _ | ⟨v2, _ | ⟨v3, vs⟩⟩⟩⟩ <;> simp [SortsAgree] at h + obtain ⟨-, h1, h2⟩ := h + cases v1 <;> cases v2 <;> simp [Value.sortOf, applyOp] at h1 h2 ⊢ <;> (try subst h1) <;> simp_all + +mutual +theorem Tm.eval_sortOf : ∀ (t : Tm) (σ : Env) {s : Srt}, t.sort? = some s → (t.eval σ).sortOf = s + | .num _, _, s, h => by simp_all [Tm.sort?, Tm.eval, Value.sortOf] + | .tt, _, s, h => by simp_all [Tm.sort?, Tm.eval, Value.sortOf] + | .ff, _, s, h => by simp_all [Tm.sort?, Tm.eval, Value.sortOf] + | .ivar _, _, s, h => by simp_all [Tm.sort?, Tm.eval, Value.sortOf] + | .bvar _, _, s, h => by simp_all [Tm.sort?, Tm.eval, Value.sortOf] + | .avar _, _, s, h => by simp_all [Tm.sort?, Tm.eval, Value.sortOf] + | .a2var _, _, s, h => by simp_all [Tm.sort?, Tm.eval, Value.sortOf] + | .all _ _, _, s, h => by + simp only [Tm.sort?] at h + split at h <;> simp at h + subst h; simp [Tm.eval, Value.sortOf] + | .app f args, σ, s, h => by + simp only [Tm.sort?] at h + simp only [Tm.eval] + exact applyOp_sortOf σ.u f _ _ (Tm.evalList_sortOf args σ) h +theorem Tm.evalList_sortOf : ∀ (ts : List Tm) (σ : Env), SortsAgree (Tm.sortList ts) (Tm.evalList σ ts) + | [], _ => trivial + | t :: ts, σ => ⟨fun _ h => Tm.eval_sortOf t σ h, Tm.evalList_sortOf ts σ⟩ +end + +/-! ## Substitution -/ + +mutual +/-- The names a term binds. -/ +def Tm.binders : Tm → List String + | .app _ args => Tm.bindersList args + | .all x body => x :: Tm.binders body + | _ => [] +def Tm.bindersList : List Tm → List String + | [] => [] + | t :: ts => Tm.binders t ++ Tm.bindersList ts +end + +/-- Whether `t` is the constant of sort `s` named `x`. -/ +def Tm.isVar : Tm → Srt → String → Bool + | .ivar y, .int, x => y == x + | .bvar y, .bool, x => y == x + | .avar y, .arr, x => y == x + | .a2var y, .arr2, x => y == x + | _, _, _ => false + +mutual +/-- Replace the constant of sort \`s\` named \`x\` by \`u\`. A bound variable of the same name shadows +it. -/ +def Tm.subst : Tm → Srt → String → Tm → Tm + | .num n, _, _, _ => .num n + | .tt, _, _, _ => .tt + | .ff, _, _, _ => .ff + | .ivar y, s, x, u => if (Tm.ivar y).isVar s x then u else .ivar y + | .bvar y, s, x, u => if (Tm.bvar y).isVar s x then u else .bvar y + | .avar y, s, x, u => if (Tm.avar y).isVar s x then u else .avar y + | .a2var y, s, x, u => if (Tm.a2var y).isVar s x then u else .a2var y + | .app f args, s, x, u => .app f (Tm.substList args s x u) + | .all y body, s, x, u => if s = .int ∧ y = x then .all y body else .all y (Tm.subst body s x u) +def Tm.substList : List Tm → Srt → String → Tm → List Tm + | [], _, _, _ => [] + | t :: ts, s, x, u => Tm.subst t s x u :: Tm.substList ts s x u +end + +/-- The assignment with the constant of sort `s` named `x` set to the value `v`. -/ +def Env.set (σ : Env) : Srt → String → Value → Env + | .int, x, v => σ.setI x v.toInt + | .bool, x, v => σ.setB x v.toProp + | .arr, x, v => σ.setA x v.toArr + | .arr2, x, v => σ.setA2 x v.toArr2 + +theorem Env.set_u (σ : Env) (s : Srt) (x : String) (v : Value) : (σ.set s x v).u = σ.u := by + cases s <;> rfl + +theorem Env.setI_setI (σ : Env) (x : String) (m n : Int) : (σ.setI x m).setI x n = σ.setI x n := by + cases σ; simp only [Env.setI, Env.mk.injEq, and_true]; funext y; split <;> rfl + +theorem Env.set_setI_comm (σ : Env) (s : Srt) (x y : String) (v : Value) (n : Int) + (h : ¬ (s = .int ∧ y = x)) : (σ.setI y n).set s x v = (σ.set s x v).setI y n := by + cases σ + cases s <;> simp only [Env.set, Env.setI, Env.setB, Env.setA, Env.setA2, Env.mk.injEq, and_true] + funext z + have : y ≠ x := fun e => h ⟨rfl, e⟩ + by_cases hz : z = x + · subst hz; simp [this.symm] + · simp [hz] + +theorem Value.eq_refl : ∀ v : Value, v.eq v + | .int _ => rfl + | .prop _ => Iff.rfl + | .arr _ => rfl + | .arr2 _ => rfl + +theorem Value.sortOf_int {v : Value} (h : v.sortOf = .int) : v = .int v.toInt := by + cases v <;> simp_all [Value.sortOf, Value.toInt] +theorem Value.sortOf_bool {v : Value} (h : v.sortOf = .bool) : v = .prop v.toProp := by + cases v <;> simp_all [Value.sortOf, Value.toProp] +theorem Value.sortOf_arr {v : Value} (h : v.sortOf = .arr) : v = .arr v.toArr := by + cases v <;> simp_all [Value.sortOf, Value.toArr] +theorem Value.sortOf_arr2 {v : Value} (h : v.sortOf = .arr2) : v = .arr2 v.toArr2 := by + cases v <;> simp_all [Value.sortOf, Value.toArr2] + +/-- The constant of sort `s` named `x` reads the value of sort `s` set at it. -/ +theorem Env.set_var (σ : Env) (s : Srt) (x : String) (v : Value) (hv : v.sortOf = s) (y : Tm) + (hy : y.isVar s x = true) : y.eval (σ.set s x v) = v := by + cases y <;> cases s <;> simp [Tm.isVar] at hy <;> subst hy <;> + simp [Tm.eval, Env.set, Env.setI, Env.setB, Env.setA, Env.setA2] + · exact (Value.sortOf_int hv).symm + · exact (Value.sortOf_bool hv).symm + · exact (Value.sortOf_arr hv).symm + · exact (Value.sortOf_arr2 hv).symm + +theorem Env.set_other (σ : Env) (s : Srt) (x : String) (v : Value) : + ∀ y : Tm, (y matches .ivar _ | .bvar _ | .avar _ | .a2var _) → y.isVar s x = false → + y.eval (σ.set s x v) = y.eval σ := by + intro y hy hn + cases y <;> simp at hy <;> cases s <;> + simp_all [Tm.isVar, Tm.eval, Env.set, Env.setI, Env.setB, Env.setA, Env.setA2] + +mutual +theorem Tm.eval_subst (s : Srt) (x : String) (u : Tm) (hu : u.sort? = some s) : + ∀ (A : Tm) (σ : Env), (∀ y ∈ A.binders, y ∉ u.vars) → + (A.subst s x u).eval σ = A.eval (σ.set s x (u.eval σ)) + | .num _, σ, _ => rfl + | .tt, σ, _ => rfl + | .ff, σ, _ => rfl + | .ivar y, σ, _ => by + simp only [Tm.subst] + split + · rename_i h; exact (Env.set_var σ s x _ (Tm.eval_sortOf u σ hu) _ h).symm + · rename_i h; exact (Env.set_other σ s x _ _ rfl (by simpa using h)).symm + | .bvar y, σ, _ => by + simp only [Tm.subst] + split + · rename_i h; exact (Env.set_var σ s x _ (Tm.eval_sortOf u σ hu) _ h).symm + · rename_i h; exact (Env.set_other σ s x _ _ rfl (by simpa using h)).symm + | .avar y, σ, _ => by + simp only [Tm.subst] + split + · rename_i h; exact (Env.set_var σ s x _ (Tm.eval_sortOf u σ hu) _ h).symm + · rename_i h; exact (Env.set_other σ s x _ _ rfl (by simpa using h)).symm + | .a2var y, σ, _ => by + simp only [Tm.subst] + split + · rename_i h; exact (Env.set_var σ s x _ (Tm.eval_sortOf u σ hu) _ h).symm + · rename_i h; exact (Env.set_other σ s x _ _ rfl (by simpa using h)).symm + | .app f args, σ, hb => by + simp only [Tm.subst, Tm.eval] + rw [Tm.evalList_subst s x u hu args σ (by simpa [Tm.binders] using hb), Env.set_u] + | .all y body, σ, hb => by + simp only [Tm.subst] + split + · rename_i h + obtain ⟨rfl, rfl⟩ := h + simp only [Tm.eval, Env.set, Env.setI_setI] + · rename_i h + simp only [Tm.eval] + have hy : y ∉ u.vars := hb y (by simp [Tm.binders]) + have key : ∀ n : Int, (body.subst s x u).eval (σ.setI y n) = + body.eval ((σ.set s x (u.eval σ)).setI y n) := by + intro n + rw [Tm.eval_subst s x u hu body (σ.setI y n) (fun z hz => hb z (by simp [Tm.binders, hz]))] + have : u.eval (σ.setI y n) = u.eval σ := Tm.eval_congr u rfl fun z hz => by + have : z ≠ y := fun e => hy (e ▸ hz) + exact ⟨by simp [Env.setI, this], rfl, rfl, rfl⟩ + rw [this, Env.set_setI_comm σ s x y _ n h] + simp only [key] +theorem Tm.evalList_subst (s : Srt) (x : String) (u : Tm) (hu : u.sort? = some s) : + ∀ (ts : List Tm) (σ : Env), (∀ y ∈ Tm.bindersList ts, y ∉ u.vars) → + Tm.evalList σ (Tm.substList ts s x u) = Tm.evalList (σ.set s x (u.eval σ)) ts + | [], _, _ => rfl + | t :: ts, σ, hb => by + simp only [Tm.substList, Tm.evalList] + rw [Tm.eval_subst s x u hu t σ (fun y hy => hb y (by simp [Tm.bindersList, hy])), + Tm.evalList_subst s x u hu ts σ (fun y hy => hb y (by simp [Tm.bindersList, hy]))] +end + +/-! ## Inlining definitions -/ + +/-- A definition `(= x u)`: a constant `x` that `u` does not mention, of `u`'s sort. -/ +def defOf? : Tm → Option (Srt × String × Tm) + | .app "=" [.ivar x, u] => if u.sort? = some .int ∧ x ∉ u.vars then some (.int, x, u) else none + | .app "=" [.bvar x, u] => if u.sort? = some .bool ∧ x ∉ u.vars then some (.bool, x, u) else none + | .app "=" [.avar x, u] => if u.sort? = some .arr ∧ x ∉ u.vars then some (.arr, x, u) else none + | .app "=" [.a2var x, u] => if u.sort? = some .arr2 ∧ x ∉ u.vars then some (.arr2, x, u) else none + | _ => none + +/-- The definition's variable, as a term. -/ +def varOf : Srt → String → Tm + | .int, x => .ivar x + | .bool, x => .bvar x + | .arr, x => .avar x + | .arr2, x => .a2var x + +theorem defOf?_spec {t : Tm} {s : Srt} {x : String} {u : Tm} (h : defOf? t = some (s, x, u)) : + u.sort? = some s ∧ x ∉ u.vars ∧ ∀ σ, t.eval σ = .prop (((varOf s x).eval σ).eq (u.eval σ)) := by + unfold defOf? at h + split at h <;> (try simp at h) + all_goals + obtain ⟨⟨hs1, hs2⟩, rfl, rfl, rfl⟩ := h + exact ⟨hs1, hs2, fun σ => by simp [Tm.eval, applyOp, Tm.evalList, varOf]⟩ + +theorem varOf_isVar (s : Srt) (x : String) : (varOf s x).isVar s x = true := by + cases s <;> simp [varOf, Tm.isVar] + +/-- Whether the facts have a model. -/ +def Sat (σ : Env) (fs : List Tm) : Prop := ∀ t ∈ fs, t.Holds σ + +/-- A definition holds where its variable is set to its term's value. -/ +theorem def_holds {t : Tm} {s : Srt} {x : String} {u : Tm} (h : defOf? t = some (s, x, u)) + (σ : Env) : t.Holds (σ.set s x (u.eval σ)) := by + obtain ⟨hu, hx, he⟩ := defOf?_spec h + have hv : u.eval (σ.set s x (u.eval σ)) = u.eval σ := Tm.eval_congr u (Env.set_u σ s x _) fun z hz => by + have : z ≠ x := fun e => hx (e ▸ hz) + cases s <;> refine ⟨?_, ?_, ?_, ?_⟩ <;> simp [Env.set, Env.setI, Env.setB, Env.setA, Env.setA2, this] + have hvar : (varOf s x).eval (σ.set s x (u.eval σ)) = u.eval σ := + Env.set_var σ s x (u.eval σ) (Tm.eval_sortOf u σ hu) (varOf s x) (varOf_isVar s x) + simp only [Tm.Holds, he, hvar, hv, Value.toProp] + exact Value.eq_refl _ + +/-- Inline the definitions among `rest`, with `done` the facts already seen (newest first), with +`fuel` steps. -/ +def inlineFuel : Nat → List Tm → List Tm → List Tm + | 0, done, rest => done.reverse ++ rest + | _ + 1, done, [] => done.reverse + | n + 1, done, f :: rest => + match defOf? f with + | some (s, x, u) => + if (done ++ rest).all (fun t => t.binders.all (fun y => !u.vars.contains y)) then + inlineFuel n (done.map (·.subst s x u)) (rest.map (·.subst s x u)) + else inlineFuel n (f :: done) rest + | none => inlineFuel n (f :: done) rest + +def inline (fs : List Tm) : List Tm := inlineFuel fs.length [] fs + +theorem shift {t f : Tm} {done rest : List Tm} (ht : t ∈ done ∨ t ∈ f :: rest) : + t ∈ f :: done ∨ t ∈ rest := by + rcases ht with ht | ht + · exact Or.inl (List.mem_cons_of_mem _ ht) + · rcases List.mem_cons.mp ht with h | h + · exact Or.inl (List.mem_cons.mpr (Or.inl h)) + · exact Or.inr h + +theorem inlineFuel_sound : ∀ (n : Nat) (done rest : List Tm), + (∀ σ, ¬ ∀ t, t ∈ done ∨ t ∈ rest → t.Holds σ) → ∀ σ, ¬ Sat σ (inlineFuel n done rest) + | 0, done, rest, h, σ, hs => h σ fun t ht => hs t (by + simp only [inlineFuel, List.mem_append, List.mem_reverse]; exact ht) + | _ + 1, done, [], h, σ, hs => h σ fun t ht => hs t (by simp [inlineFuel]; simpa using ht) + | n + 1, done, f :: rest, h, σ, hs => by + simp only [inlineFuel] at hs + split at hs + · rename_i s x u hd + split at hs + · rename_i hcap + refine inlineFuel_sound n _ _ ?_ σ hs + intro τ hτ + have hu := (defOf?_spec hd).1 + have hcap' : ∀ t ∈ done ++ rest, ∀ y ∈ t.binders, y ∉ u.vars := by + intro t ht y hy hyu + have := List.all_eq_true.mp hcap t ht + have := List.all_eq_true.mp this y hy + simp [hyu] at this + apply h (τ.set s x (u.eval τ)) + intro t ht + rcases ht with ht | ht + · have := hτ (t.subst s x u) (Or.inl (List.mem_map.mpr ⟨t, ht, rfl⟩)) + simp only [Tm.Holds] at this ⊢ + rwa [Tm.eval_subst s x u hu t τ (hcap' t (by simp [ht]))] at this + · rcases List.mem_cons.mp ht with rfl | ht + · exact def_holds hd τ + · have := hτ (t.subst s x u) (Or.inr (List.mem_map.mpr ⟨t, ht, rfl⟩)) + simp only [Tm.Holds] at this ⊢ + rwa [Tm.eval_subst s x u hu t τ (hcap' t (by simp [ht]))] at this + · exact inlineFuel_sound n (f :: done) rest + (fun τ hτ => h τ fun t ht => hτ t (shift ht)) σ hs + · exact inlineFuel_sound n (f :: done) rest + (fun τ hτ => h τ fun t ht => hτ t (shift ht)) σ hs + +theorem inline_sound {fs : List Tm} (h : ∀ σ, ¬ Sat σ fs) : ∀ σ, ¬ Sat σ (inline fs) := + inlineFuel_sound _ [] fs (fun σ hσ => h σ fun t ht => hσ t (Or.inr ht)) + +/-! ## Renaming solar-verify's names -/ + +/-- `name@N` and `name!N` to `name`. -/ +def strip (x : String) : String := String.ofList (x.toList.takeWhile fun c => c ≠ '@' ∧ c ≠ '!') + +mutual +def Tm.rename : Tm → Tm + | .num n => .num n + | .tt => .tt + | .ff => .ff + | .ivar x => .ivar (strip x) + | .bvar x => .bvar (strip x) + | .avar x => .avar (strip x) + | .a2var x => .a2var (strip x) + | .app f args => .app f (Tm.renameList args) + | .all x body => .all (strip x) (Tm.rename body) +def Tm.renameList : List Tm → List Tm + | [] => [] + | t :: ts => Tm.rename t :: Tm.renameList ts +end + +mutual +/-- No renaming makes a bound variable meet another name in its scope. -/ +def Tm.renameOk : Tm → Bool + | .app _ args => Tm.renameOkList args + | .all x body => body.vars.all (fun y => y == x || strip y != strip x) && Tm.renameOk body + | _ => true +def Tm.renameOkList : List Tm → Bool + | [] => true + | t :: ts => Tm.renameOk t && Tm.renameOkList ts +end + +/-- `σ` reads each name as `τ` reads its renaming. -/ +def Env.Renamed (σ τ : Env) (y : String) : Prop := + σ.i y = τ.i (strip y) ∧ σ.b y = τ.b (strip y) ∧ σ.a y = τ.a (strip y) ∧ σ.a2 y = τ.a2 (strip y) + +mutual +theorem Tm.eval_rename : ∀ (t : Tm) {σ τ : Env}, σ.u = τ.u → t.renameOk = true → + (∀ y ∈ t.vars, σ.Renamed τ y) → t.eval σ = t.rename.eval τ + | .num _, _, _, _, _, _ => rfl + | .tt, _, _, _, _, _ => rfl + | .ff, _, _, _, _, _ => rfl + | .ivar x, _, _, _, _, h => by simp [Tm.rename, Tm.eval, (h x (by simp [Tm.vars])).1] + | .bvar x, _, _, _, _, h => by simp [Tm.rename, Tm.eval, (h x (by simp [Tm.vars])).2.1] + | .avar x, _, _, _, _, h => by simp [Tm.rename, Tm.eval, (h x (by simp [Tm.vars])).2.2.1] + | .a2var x, _, _, _, _, h => by simp [Tm.rename, Tm.eval, (h x (by simp [Tm.vars])).2.2.2] + | .app f args, σ, τ, hu, ho, h => by + simp only [Tm.rename, Tm.eval] + rw [Tm.evalList_rename args hu (by simpa [Tm.renameOk] using ho) (by simpa [Tm.vars] using h), hu] + | .all x body, σ, τ, hu, ho, h => by + simp only [Tm.renameOk, Bool.and_eq_true, List.all_eq_true] at ho + simp only [Tm.rename, Tm.eval] + have key : ∀ n : Int, body.eval (σ.setI x n) = body.rename.eval (τ.setI (strip x) n) := by + intro n + apply Tm.eval_rename body (σ := σ.setI x n) (τ := τ.setI (strip x) n) hu ho.2 + intro y hy + obtain ⟨h1, h2, h3, h4⟩ := h y (by simp [Tm.vars, hy]) + refine ⟨?_, h2, h3, h4⟩ + by_cases hyx : y = x + · subst hyx; simp [Env.setI] + · have := ho.1 y hy + have hs : strip y ≠ strip x := by simpa [hyx] using this + simp [Env.setI, hyx, hs, h1] + simp only [key] +theorem Tm.evalList_rename : ∀ (ts : List Tm) {σ τ : Env}, σ.u = τ.u → Tm.renameOkList ts = true → + (∀ y ∈ Tm.varsList ts, σ.Renamed τ y) → Tm.evalList σ ts = Tm.evalList τ (Tm.renameList ts) + | [], _, _, _, _, _ => rfl + | t :: ts, σ, τ, hu, ho, h => by + simp only [Tm.renameOkList, Bool.and_eq_true] at ho + simp only [Tm.renameList, Tm.evalList] + rw [Tm.eval_rename t hu ho.1 (fun y hy => h y (by simp [Tm.varsList, hy])), + Tm.evalList_rename ts hu ho.2 (fun y hy => h y (by simp [Tm.varsList, hy]))] +end + +theorem rename_sound {fs : List Tm} (hok : fs.all Tm.renameOk = true) (h : ∀ σ, ¬ Sat σ fs) : + ∀ τ, ¬ Sat τ (fs.map Tm.rename) := by + intro τ hτ + let σ : Env := ⟨fun y => τ.i (strip y), fun y => τ.b (strip y), fun y => τ.a (strip y), + fun y => τ.a2 (strip y), τ.u⟩ + apply h σ + intro t ht + have := hτ t.rename (List.mem_map.mpr ⟨t, ht, rfl⟩) + simp only [Tm.Holds] at this ⊢ + rwa [Tm.eval_rename t (σ := σ) (τ := τ) rfl (List.all_eq_true.mp hok t ht) + (fun y _ => ⟨rfl, rfl, rfl, rfl⟩)] + +/-! ## Flattening conjunctions -/ + +mutual +def flatten : Tm → List Tm + | .tt => [] + | .app "and" args => flattenList args + | t => [t] +def flattenList : List Tm → List Tm + | [] => [] + | t :: ts => flatten t ++ flattenList ts +end + +mutual +theorem flatten_holds : ∀ (t : Tm) (σ : Env), (∀ c ∈ flatten t, c.Holds σ) → t.Holds σ + | .tt, _, _ => by simp [Tm.Holds, Tm.eval, Value.toProp] + | .app f args, σ, h => by + by_cases hf : f = "and" + · subst hf + simp only [flatten] at h + have := flattenList_holds args σ h + simp only [Tm.Holds, Tm.eval, applyOp, Value.toProp, Tm.evalList_eq] + intro v hv + obtain ⟨t, ht, rfl⟩ := List.mem_map.mp hv + exact this t ht + · have : flatten (.app f args) = [.app f args] := by + unfold flatten; split <;> simp_all + exact h _ (by simp [this]) + | .num n, _, h => h _ (by simp [flatten]) + | .ff, _, h => h _ (by simp [flatten]) + | .ivar x, _, h => h _ (by simp [flatten]) + | .bvar x, _, h => h _ (by simp [flatten]) + | .avar x, _, h => h _ (by simp [flatten]) + | .a2var x, _, h => h _ (by simp [flatten]) + | .all x b, _, h => h _ (by simp [flatten]) +theorem flattenList_holds : ∀ (ts : List Tm) (σ : Env), (∀ c ∈ flattenList ts, c.Holds σ) → + ∀ t ∈ ts, t.Holds σ + | [], _, _ => by simp + | t :: ts, σ, h => by + simp only [flattenList, List.mem_append] at h + intro u hu + cases hu with + | head => exact flatten_holds t σ fun c hc => h c (Or.inl hc) + | tail _ hu => exact flattenList_holds ts σ (fun c hc => h c (Or.inr hc)) u hu +end + +theorem mem_flattenList {t c : Tm} : ∀ {ts : List Tm}, t ∈ ts → c ∈ flatten t → c ∈ flattenList ts + | _ :: _, .head _, hc => by simp only [flattenList, List.mem_append]; exact Or.inl hc + | _ :: _, .tail _ ht, hc => by + simp only [flattenList, List.mem_append]; exact Or.inr (mem_flattenList ht hc) + +/-! ## Range facts -/ + +/-- The fact that the elements of the array `m` lie in `[0, M]`, as the Lean generator states it of +the arrays of its storage: `(forall ((k Int)) (and (<= 0 (select m k)) (<= (select m k) M)))`. -/ +def arrFact (k m : String) (M : Nat) : Tm := + .all k (.app "and" [.app "<=" [.num 0, .app "select" [.avar m, .ivar k]], + .app "<=" [.app "select" [.avar m, .ivar k], .num M]]) + +/-- An array fact of `m` among `hs` bounds its elements by at most `M`. -/ +def arrBound (hs : List Tm) (m : String) (M : Nat) : Bool := + hs.any fun h => match h with + | .all k (.app "and" [.app "<=" [.num 0, .app "select" [.avar m', .ivar k']], + .app "<=" [.app "select" [.avar m'', .ivar k''], .num M']]) => + m' == m && m'' == m && k' == k && k'' == k && decide (M' ≤ M) + | _ => false + +theorem arrBound_sound {hs : List Tm} {m : String} {M : Nat} (h : arrBound hs m M = true) + {σ : Env} (hh : ∀ x ∈ hs, x.Holds σ) (n : Int) : 0 ≤ σ.a m n ∧ σ.a m n ≤ M := by + obtain ⟨f, hf, hm⟩ := List.any_eq_true.mp h + split at hm + · rename_i k m' k' m'' k'' M' + simp only [Bool.and_eq_true, beq_iff_eq, decide_eq_true_eq] at hm + obtain ⟨⟨⟨⟨rfl, rfl⟩, rfl⟩, rfl⟩, hM⟩ := hm + have := hh _ hf + simp only [Tm.Holds, Tm.eval, Value.toProp] at this + have := this n + simp [Tm.eval, Tm.evalList, applyOp, Value.toProp, Value.toInt, Value.toArr, Env.setI] at this + exact ⟨this.1, Int.le_trans this.2 (by exact_mod_cast hM)⟩ + · simp at hm + +/-- `hs` imply `0 ≤ t`, with `fuel` steps: a fact of `hs`, or through an `ite`, a `select` of a +`store` and a `select` of an array whose elements `hs` bound. -/ +def lowerOk (hs : List Tm) : Nat → Tm → Bool + | 0, t => hs.any (·.beq (.app "<=" [.num 0, t])) + | n + 1, t => hs.any (·.beq (.app "<=" [.num 0, t])) || match t with + | .app "ite" [_, a, b] => lowerOk hs n a && lowerOk hs n b + | .app "select" [.app "store" [a, _, v], j] => lowerOk hs n v && lowerOk hs n (.app "select" [a, j]) + | .app "select" [.avar m, _] => hs.any fun h => match h with + | .all k (.app "and" [.app "<=" [.num 0, .app "select" [.avar m', .ivar k']], _]) => + m' == m && k' == k + | _ => false + | _ => false + +/-- `hs` imply `t ≤ M`, as `lowerOk` does `0 ≤ t`. -/ +def upperOk (hs : List Tm) (M : Nat) : Nat → Tm → Bool + | 0, t => hs.any fun h => match h with + | .app "<=" [t', .num M'] => t'.beq t && decide (M' ≤ M) + | _ => false + | n + 1, t => (hs.any fun h => match h with + | .app "<=" [t', .num M'] => t'.beq t && decide (M' ≤ M) + | _ => false) || match t with + | .app "ite" [_, a, b] => upperOk hs M n a && upperOk hs M n b + | .app "select" [.app "store" [a, _, v], j] => + upperOk hs M n v && upperOk hs M n (.app "select" [a, j]) + | .app "select" [.avar m, _] => arrBound hs m M + | _ => false + +theorem holds_le (σ : Env) (a b : Tm) : + (Tm.app "<=" [a, b]).Holds σ ↔ (a.eval σ).toInt ≤ (b.eval σ).toInt := by + simp [Tm.Holds, Tm.eval, Tm.evalList, applyOp, Value.toProp] + +theorem eval_select (σ : Env) (a j : Tm) : + ((Tm.app "select" [a, j]).eval σ).toInt = (a.eval σ).toArr (j.eval σ).toInt := by + simp only [Tm.eval, Tm.evalList, applyOp] + cases a.eval σ <;> rfl + +/-- Read over write, of the integer a term takes: the case of a mapping of mappings (an array +value) takes none. -/ +theorem eval_store_select (σ : Env) (a i v j : Tm) : + ((Tm.app "select" [.app "store" [a, i, v], j]).eval σ).toInt = + (if (j.eval σ).toInt = (i.eval σ).toInt then (v.eval σ).toInt + else ((Tm.app "select" [a, j]).eval σ).toInt) ∨ + ((Tm.app "select" [.app "store" [a, i, v], j]).eval σ).toInt = 0 := by + simp only [Tm.eval, Tm.evalList, applyOp] + cases a.eval σ with + | arr2 f => exact Or.inr rfl + | arr f => left; simp only [Value.store, Value.select, Value.toInt]; first | rfl | (by_cases hc : (Tm.eval σ j).toInt = (Tm.eval σ i).toInt <;> simp_all [Value.toInt]) + | int n => left; simp only [Value.store, Value.select, Value.toInt]; first | rfl | (by_cases hc : (Tm.eval σ j).toInt = (Tm.eval σ i).toInt <;> simp_all [Value.toInt]) + | prop p => left; simp only [Value.store, Value.select, Value.toInt]; first | rfl | (by_cases hc : (Tm.eval σ j).toInt = (Tm.eval σ i).toInt <;> simp_all [Value.toInt]) + +open Classical in +theorem eval_ite_int (σ : Env) (c a b : Tm) : + ((Tm.app "ite" [c, a, b]).eval σ).toInt = ((Tm.app "ite" [c, a, b]).eval σ).toInt := rfl + +/-- The integer an `ite` takes is one of its branches', whatever their sorts. -/ +theorem ite_toInt (σ : Env) (c a b : Tm) : + ((Tm.app "ite" [c, a, b]).eval σ).toInt = (a.eval σ).toInt ∨ + ((Tm.app "ite" [c, a, b]).eval σ).toInt = (b.eval σ).toInt ∨ + ((Tm.app "ite" [c, a, b]).eval σ).toInt = 0 := by + simp only [Tm.eval, Tm.evalList] + cases a.eval σ <;> cases b.eval σ + all_goals first + | (simp [applyOp, Value.toInt]; done) + | (right; right; rfl) + | (simp only [applyOp, Value.toInt]; split <;> simp; done) + +theorem lowerOk_sound (hs : List Tm) {σ : Env} (hh : ∀ x ∈ hs, x.Holds σ) : + ∀ n t, lowerOk hs n t = true → 0 ≤ (t.eval σ).toInt := by + have mem : ∀ t, (hs.any (·.beq (.app "<=" [.num 0, t]))) = true → 0 ≤ (t.eval σ).toInt := by + intro t h + obtain ⟨f, hf, he⟩ := List.any_eq_true.mp h + have := hh f hf + rw [Tm.eq_of_beq he, holds_le] at this + simpa [Tm.eval, Value.toInt] using this + intro n + induction n with + | zero => exact fun t h => mem t h + | succ n ih => + intro t h + simp only [lowerOk, Bool.or_eq_true] at h + rcases h with h | h + · exact mem t h + · split at h + · rename_i c a b + simp only [Bool.and_eq_true] at h + rcases ite_toInt σ c a b with e | e | e <;> rw [e] + · exact ih a h.1 + · exact ih b h.2 + · exact Int.le_refl 0 + · rename_i a i v j + simp only [Bool.and_eq_true] at h + rcases eval_store_select σ a i v j with e | e <;> rw [e] + · split + · exact ih v h.1 + · exact ih _ h.2 + · exact Int.le_refl 0 + · rename_i m j + obtain ⟨f, hf, hm⟩ := List.any_eq_true.mp h + split at hm + · rename_i k m' k' rest + simp only [Bool.and_eq_true, beq_iff_eq] at hm + obtain ⟨rfl, rfl⟩ := hm + have := hh _ hf + simp only [Tm.Holds, Tm.eval, Value.toProp] at this + have := this (j.eval σ).toInt + simp [Tm.eval, Tm.evalList, applyOp, Value.toProp, Value.toInt, Value.select, Env.setI] at this + rw [eval_select] + simpa [Value.toInt, Tm.eval, Value.toArr] using this.1 + · simp at hm + · simp at h + +theorem upperOk_sound (hs : List Tm) (M : Nat) {σ : Env} (hh : ∀ x ∈ hs, x.Holds σ) : + ∀ n t, upperOk hs M n t = true → (t.eval σ).toInt ≤ M := by + have mem : ∀ t, (hs.any fun h => match h with + | .app "<=" [t', .num M'] => t'.beq t && decide (M' ≤ M) + | _ => false) = true → (t.eval σ).toInt ≤ M := by + intro t h + obtain ⟨f, hf, he⟩ := List.any_eq_true.mp h + split at he + · rename_i t' M' + simp only [Bool.and_eq_true, decide_eq_true_eq] at he + have := hh _ hf + rw [Tm.eq_of_beq he.1, holds_le] at this + simp only [Tm.eval, Value.toInt] at this + exact Int.le_trans this (by exact_mod_cast he.2) + · simp at he + intro n + induction n with + | zero => exact fun t h => mem t h + | succ n ih => + intro t h + simp only [upperOk, Bool.or_eq_true] at h + rcases h with h | h + · exact mem t h + · split at h + · rename_i c a b + simp only [Bool.and_eq_true] at h + rcases ite_toInt σ c a b with e | e | e <;> rw [e] + · exact ih a h.1 + · exact ih b h.2 + · exact Int.natCast_nonneg M + · rename_i a i v j + simp only [Bool.and_eq_true] at h + rcases eval_store_select σ a i v j with e | e <;> rw [e] + · split + · exact ih v h.1 + · exact ih _ h.2 + · exact Int.natCast_nonneg M + · rename_i m j + rw [eval_select] + exact (arrBound_sound h hh _).2 + · simp at h + +/-! ## The check of one obligation -/ + +/-- A range fact of a constant the Lean obligation does not mention, which 0 satisfies. -/ +def defaultOk (V : List String) : Tm → Bool + | .app "<=" [.num 0, .ivar x] => !V.contains x + | .app "<=" [.ivar x, .num _] => !V.contains x + | _ => false + +/-- A fact of solar-verify's obligation that the Lean obligation's facts `hs` give. -/ +def hypOk (hs : List Tm) (V : List String) (h : Tm) : Bool := + hs.any (·.beq h) || defaultOk V h || match h with + | .app "<=" [.num 0, t] => lowerOk hs 64 t + | .app "<=" [t, .num M] => upperOk hs M 64 t + | _ => false + +/-- The names the Lean obligation mentions. -/ +def leanVars (hs : List Tm) (φ : Tm) : List String := Tm.varsList hs ++ φ.vars + +/-- solar-verify's obligation `e` gives the Lean obligation `hs ⟹ φ`. -/ +def checkOb (e hs : List Tm) (φ : Tm) : Bool := + let e1 := inline e + e1.all Tm.renameOk && + match (e1.map Tm.rename).reverse with + | .app "not" [φ'] :: rhyps => φ'.beq φ && (flattenList rhyps).all (hypOk hs (leanVars hs φ)) + | _ => false + +/-- The assignment that reads as `σ` the names of `V`, and every other name as 0. -/ +def Env.restrict (σ : Env) (V : List String) : Env := + ⟨fun x => if x ∈ V then σ.i x else 0, fun x => if x ∈ V then σ.b x else False, + fun x => if x ∈ V then σ.a x else fun _ => 0, fun x => if x ∈ V then σ.a2 x else fun _ _ => 0, + σ.u⟩ + +theorem Env.restrict_agree (σ : Env) {V : List String} {x : String} (h : x ∈ V) : + (σ.restrict V).Agree σ x := by + simp [Env.restrict, Env.Agree, h] + +theorem mem_varsList {t : Tm} : ∀ {ts : List Tm}, t ∈ ts → ∀ x ∈ t.vars, x ∈ Tm.varsList ts + | _ :: _, .head _, x, hx => by simp only [Tm.varsList, List.mem_append]; exact Or.inl hx + | _ :: _, .tail _ ht, x, hx => by + simp only [Tm.varsList, List.mem_append]; exact Or.inr (mem_varsList ht x hx) + +theorem holds_restrict {σ : Env} {V : List String} {t : Tm} (h : ∀ x ∈ t.vars, x ∈ V) : + t.Holds (σ.restrict V) ↔ t.Holds σ := by + simp only [Tm.Holds] + rw [Tm.eval_congr t (σ := σ.restrict V) (τ := σ) rfl fun x hx => Env.restrict_agree σ (h x hx)] + +theorem hypOk_sound {hs : List Tm} {φ : Tm} {σ : Env} (hh : ∀ x ∈ hs, x.Holds σ) {h : Tm} + (ok : hypOk hs (leanVars hs φ) h = true) : h.Holds (σ.restrict (leanVars hs φ)) := by + have hV : ∀ x ∈ hs, ∀ y ∈ x.vars, y ∈ leanVars hs φ := fun x hx y hy => by + simp only [leanVars, List.mem_append]; exact Or.inl (mem_varsList hx y hy) + have hh' : ∀ x ∈ hs, x.Holds (σ.restrict (leanVars hs φ)) := fun x hx => + (holds_restrict (hV x hx)).mpr (hh x hx) + simp only [hypOk, Bool.or_eq_true] at ok + rcases ok with (ok | ok) | ok + · obtain ⟨f, hf, he⟩ := List.any_eq_true.mp ok + rw [← Tm.eq_of_beq he]; exact hh' f hf + · unfold defaultOk at ok + split at ok + · rename_i x + simp only [Bool.not_eq_true', List.contains_eq_mem, decide_eq_false_iff_not] at ok + rw [holds_le]; simp [Tm.eval, Env.restrict, ok, Value.toInt] + · rename_i x M + simp only [Bool.not_eq_true', List.contains_eq_mem, decide_eq_false_iff_not] at ok + rw [holds_le]; simp [Tm.eval, Env.restrict, ok, Value.toInt] + · simp at ok + · split at ok + · rename_i t + rw [holds_le] + simpa [Tm.eval, Value.toInt] using lowerOk_sound hs hh' 64 t ok + · rename_i t M _ + rw [holds_le] + simpa [Tm.eval, Value.toInt] using upperOk_sound hs M hh' 64 t ok + · simp at ok + +theorem checkOb_sound {e hs : List Tm} {φ : Tm} (h : checkOb e hs φ = true) + (hv : ∀ σ, ¬ Sat σ e) (σ : Env) (hh : ∀ x ∈ hs, x.Holds σ) : φ.Holds σ := by + simp only [checkOb, Bool.and_eq_true] at h + obtain ⟨hok, h⟩ := h + have h2 := rename_sound hok (inline_sound hv) + split at h + · rename_i φ' rhyps hr + simp only [Bool.and_eq_true, List.all_eq_true] at h + obtain ⟨hφ, hyps⟩ := h + have he := Tm.eq_of_beq hφ + subst he + have hφV : ∀ x ∈ φ'.vars, x ∈ leanVars hs φ' := fun x hx => by + simp only [leanVars, List.mem_append]; exact Or.inr hx + apply Classical.byContradiction + intro hn + apply h2 (σ.restrict (leanVars hs φ')) + intro t ht + have ht' : t ∈ (Tm.app "not" [φ'] :: rhyps).reverse := by + rw [← hr, List.reverse_reverse]; exact ht + rw [List.mem_reverse] at ht' + rcases List.mem_cons.mp ht' with rfl | ht' + · simp only [Tm.Holds, Tm.eval, Tm.evalList, applyOp, Value.toProp] + intro hp + exact hn ((holds_restrict hφV).mp hp) + · exact flatten_holds t _ fun c hc => + hypOk_sound hh (hyps c (mem_flattenList ht' hc)) + · simp at h + +/-! ## The check of a script -/ + +/-- Every Lean obligation `(hs, φ)` is given by one of the script's obligations. -/ +def checkScript (cs : List Cmd) (obs : List (List Tm × Tm)) : Bool := + let es := (obligations cs).filter (fun e => !isProbe e) + obs.all fun o => es.any fun e => checkOb e o.1 o.2 + +/-- What the Lean obligations claim: each one's facts imply its goal. -/ +def ObsValid (obs : List (List Tm × Tm)) : Prop := + ∀ o ∈ obs, ∀ σ : Env, (∀ x ∈ o.1, x.Holds σ) → o.2.Holds σ + +theorem checkScript_sound {cs : List Cmd} {obs : List (List Tm × Tm)} + (h : checkScript cs obs = true) (hv : Valid cs) : ObsValid obs := by + intro o ho σ hh + have := List.all_eq_true.mp h o ho + obtain ⟨e, he, hc⟩ := List.any_eq_true.mp this + rw [List.mem_filter] at he + have hp : isProbe e = false := by simpa using he.2 + exact checkOb_sound hc (fun τ hτ => hv e he.1 hp τ hτ) σ hh + +/-! ## One function's obligations -/ + +/-- The commands of the function `name` (`Contract.fn`): those after its `; ===== name` line, up to +the next function's. -/ +def fnSlice (cs : List Cmd) (name : String) : List Cmd := + let isMark : Cmd → String → Bool := fun c n => match c with + | .raw l => l == "; ===== " ++ n + | _ => false + let isAny : Cmd → Bool := fun c => match c with + | .raw l => l.startsWith "; ===== " + | _ => false + ((cs.dropWhile (fun c => !isMark c name)).drop 1).takeWhile (fun c => !isAny c) + +/-- An obligation of solar-verify's, normalized as `checkOb` normalizes it: its facts, flattened, +and its goal. -/ +def normOb (e : List Tm) : Option (List Tm × Tm) := + let e1 := inline e + if e1.all Tm.renameOk then + match (e1.map Tm.rename).reverse with + | .app "not" [φ] :: rhyps => some (flattenList rhyps, φ) + | _ => none + else none + +/-- The obligations of the function `name`, normalized, without the probe. -/ +def fnObs (cs : List Cmd) (name : String) : List (List Tm × Tm) := + ((obligations (fnSlice cs name)).filter (fun e => !isProbe e)).filterMap normOb + +end SolidCore.Verify.VC diff --git a/Verify/VC/Discharge.lean b/Verify/VC/Discharge.lean new file mode 100644 index 00000000..d0cfeb44 --- /dev/null +++ b/Verify/VC/Discharge.lean @@ -0,0 +1,1364 @@ +import Verify.VC.Check +import Mathlib.Tactic.Ring +import Mathlib.Tactic.Linarith + +/-! +# A verified decision procedure for solar-verify's scripts + +`dischargeScript cs` decides, by evaluation in the kernel, that every obligation of the script +`cs` (the facts one `check-sat` reads, `obligations`) has no model, leaving out the probes +(`isProbe`); `dischargeScript_sound` shows that `dischargeScript cs = true` gives `Valid cs`, +the claim of solar-verify's verdict, with no solver and no certificate. The procedure is +incomplete and fails closed: an obligation it cannot refute makes it answer `false`. + +For one obligation (`refuteOb`): + +1. Definitions: every fact `(= x u)` with `x` a constant is an equation; each constant with + one is replaced by its term, to a bounded depth, outside quantifiers (`substN`). Every model + of the facts satisfies the equations, so it satisfies the rewritten facts (`substN_eval`). +2. A tableau (`refute`): conjunctions are split into facts, disjunctions, implications and negated + conjunctions into branches (each of which must close), and an `ite` of integers that is an + argument of a comparison into its two cases (`splitIte`). A comparison of linear terms + (`lin`: numerals, `+`, `-`, multiplication by a numeral, and any other integer term as + an atom compared by syntax) becomes constraints `l ≤ 0` (`cmpCons`, `x < y` read as + `x - y + 1 ≤ 0` over the integers); a disequality of integers is split in two. Every other + fact is dropped, which is sound. +3. Fourier-Motzkin (`fm`): a branch closes when eliminating its constants one at a time, by + nonnegative combinations of pairs of constraints, reaches a constraint `k ≤ 0` with `0 < k`. + +Each step is proved sound once (`step_sound`, `elim_sound`, `fm_sound`), whatever the terms +are; fuel bounds every recursion, so the kernel evaluates the procedure by structural recursion. +-/ + +namespace SolidCore.Verify.VC + +/-! ## Linear forms -/ + +/-- `k + Σ c * t`, over integer terms `t`. -/ +structure Lin where + k : Int + cs : List (Tm × Int) + +noncomputable def sumCs (σ : Env) : List (Tm × Int) → Int + | [] => 0 + | p :: ps => p.2 * (p.1.eval σ).toInt + sumCs σ ps + +noncomputable def Lin.eval (σ : Env) (l : Lin) : Int := l.k + sumCs σ l.cs + +def Lin.add (a b : Lin) : Lin := ⟨a.k + b.k, a.cs ++ b.cs⟩ +def Lin.scale (c : Int) (a : Lin) : Lin := ⟨c * a.k, a.cs.map fun p => (p.1, c * p.2)⟩ +def Lin.sub (a b : Lin) : Lin := a.add (b.scale (-1)) +def Lin.inc (a : Lin) : Lin := ⟨a.k + 1, a.cs⟩ + +/-- Add one monomial to a list, merging it with one of the same term. -/ +def insertC (p : Tm × Int) : List (Tm × Int) → List (Tm × Int) + | [] => [p] + | q :: qs => if Tm.beq q.1 p.1 then (q.1, q.2 + p.2) :: qs else q :: insertC p qs + +/-- Merge the monomials of one term and drop those with coefficient 0. -/ +def Lin.norm (a : Lin) : Lin := ⟨a.k, (a.cs.foldr insertC []).filter fun p => p.2 != 0⟩ + +/-- The coefficient of a term in a merged form. -/ +def coeff (a : Lin) (x : Tm) : Int := + match a.cs.find? (fun p => Tm.beq p.1 x) with + | some p => p.2 + | none => 0 + +/-! ## Fourier-Motzkin -/ + +/-- Eliminate `x` from constraints `l ≤ 0`: keep those without it and add, for each pair with +coefficients of opposite signs, their combination in which it cancels. -/ +def elim (x : Tm) (cs : List Lin) : List Lin := + let pos := cs.filter fun l => decide (0 < coeff l x) + let neg := cs.filter fun l => decide (coeff l x < 0) + cs.filter (fun l => decide (coeff l x = 0)) ++ + pos.flatMap fun p => neg.map fun q => ((p.scale (-(coeff q x))).add (q.scale (coeff p x))).norm + +/-- How many constraints eliminating `x` adds: pairs of opposite signs. -/ +def elimCost (cs : List Lin) (x : Tm) : Nat := + (cs.filter fun l => decide (0 < coeff l x)).length * (cs.filter fun l => decide (coeff l x < 0)).length + +/-- The term of the constraints whose elimination adds the fewest. -/ +def pickVar (cs : List Lin) : Option Tm := + (cs.flatMap fun l => l.cs.map (·.1)).foldl (fun best x => match best with + | none => some x + | some y => if elimCost cs x < elimCost cs y then some x else some y) none + +/-- Whether the constraints `l ≤ 0` have no integer solution, by Fourier-Motzkin with `fuel` +eliminations. -/ +def fm : Nat → List Lin → Bool + | 0, _ => false + | n + 1, cs => + let cs := cs.filter fun l => !(l.cs.isEmpty && decide (l.k ≤ 0)) + if cs.any (fun l => l.cs.isEmpty && decide (0 < l.k)) then true + else match pickVar cs with + | none => false + | some x => if elimCost cs x ≤ 256 ∧ cs.length ≤ 512 then fm n (elim x cs) else false + +/-! ## Linear terms -/ + +def Tm.isIntAtom (t : Tm) : Bool := t.sort? == some .int + +/-- An integer term as an atom of a linear form. -/ +def linAtom (t : Tm) : Option Lin := if t.isIntAtom then some ⟨0, [(t, 1)]⟩ else none + +/-- The linear form of an integer term, with `fuel` levels. -/ +def lin : Nat → Tm → Option Lin + | 0, _ => none + | n + 1, t => + match t with + | .num m => some ⟨m, []⟩ + | .app f args => + if f = "+" then + match args with + | [a, b] => match lin n a, lin n b with + | some la, some lb => some (la.add lb) + | _, _ => none + | _ => none + else if f = "-" then + match args with + | [a] => (lin n a).map (Lin.scale (-1)) + | [a, b] => match lin n a, lin n b with + | some la, some lb => some (la.sub lb) + | _, _ => none + | _ => none + else if f = "*" then + match args with + | [.num c, a] => (lin n a).map (Lin.scale c) + | [a, .num c] => (lin n a).map (Lin.scale c) + | _ => linAtom t + else linAtom t + | _ => linAtom t + +/-- The constraints `l ≤ 0` a comparison `f` of `a` and `b` (negated when `pos` is false) gives. -/ +def cmpCons (f : String) (pos : Bool) (a b : Lin) : List Lin := + if f = "<=" then (if pos then [a.sub b] else [(b.sub a).inc]) + else if f = "<" then (if pos then [(a.sub b).inc] else [b.sub a]) + else if f = ">=" then (if pos then [b.sub a] else [(a.sub b).inc]) + else if f = ">" then (if pos then [(b.sub a).inc] else [a.sub b]) + else if f = "=" then (if pos then [a.sub b, b.sub a] else []) + else [] + +/-! ## Definitions -/ + +def Tm.isConst : Tm → Bool + | .ivar _ | .bvar _ | .avar _ | .a2var _ => true + | _ => false + +/-- `(= x u)` with `x` a constant. -/ +def eqOf? : Tm → Option (Tm × Tm) + | .app f [v, u] => if f = "=" ∧ v.isConst = true then some (v, u) else none + | _ => none + +def lookupEq : List (Tm × Tm) → Tm → Option Tm + | [], _ => none + | e :: es, v => if Tm.beq e.1 v then some e.2 else lookupEq es v + +/-- Replace each constant with an equation by its term, `n` levels deep, outside quantifiers. -/ +def substN : List (Tm × Tm) → Nat → Tm → Tm + | _, 0, t => t + | eqs, n + 1, t => + match t with + | .app f args => .app f (args.map (substN eqs n)) + | .all x body => + .all x (substN (eqs.filter fun e => !(e.1.vars.contains x || e.2.vars.contains x)) n body) + | t => if t.isConst then (match lookupEq eqs t with | some u => substN eqs n u | none => t) else t + +/-! ## The tableau -/ + +def neg (t : Tm) : Tm := .app "not" [t] +def wrap (pos : Bool) (t : Tm) : Tm := if pos then t else neg t + +/-- `(ite c p q)` with `p` and `q` integers. -/ +def isIte : Tm → Option (Tm × Tm × Tm) + | .app g [c, p, q] => if g = "ite" ∧ p.isIntAtom = true ∧ q.isIntAtom = true then some (c, p, q) else none + | _ => none + +/-- The first of `args` in which `g` finds an `ite`, with the two cases of the list. -/ +def liftArgs (g : Tm → Option (Tm × Tm × Tm)) : List Tm → Option (Tm × List Tm × List Tm) + | [] => none + | a :: as => + match g a with + | some (c, a1, a2) => some (c, a1 :: as, a2 :: as) + | none => (liftArgs g as).map fun r => (r.1, a :: r.2.1, a :: r.2.2) + +/-- The leftmost integer `ite` of a term, outside quantifiers, as its condition and the term with +the `ite` replaced by each of its cases. -/ +def liftIte : Nat → Tm → Option (Tm × Tm × Tm) + | 0, _ => none + | n + 1, t => + match t with + | .app f args => + match isIte t with + | some r => some r + | none => (liftArgs (liftIte n) args).map fun r => (r.1, .app f r.2.1, .app f r.2.2) + | _ => none + +/-- What one fact gives the tableau. -/ +inductive Step where + | drop + | closed + | facts (ts : List Tm) + | cons (ls : List Lin) + | split (bs : List (List Tm)) + /-- `c` and `t1`, or the negation of `c` and `t2`: the cases of an `ite` on `c`. -/ + | ite (c t1 t2 : Tm) + /-- `t`, at some value of the constant `x`: a negated quantifier, opened at a witness. -/ + | skolem (x : String) (t : Tm) + +def linFuel : Nat := 64 + +def isCmp (f : String) : Bool := f == "<=" || f == "<" || f == ">=" || f == ">" || f == "=" + +/-- A comparison `f a b`, asserted (`pos`) or negated. -/ +def atomStep (pos : Bool) (f : String) (a b : Tm) : Step := + match liftIte linFuel (.app f [a, b]) with + | some (c, t1, t2) => .ite c (wrap pos t1) (wrap pos t2) + | none => + match lin linFuel a, lin linFuel b with + | some la, some lb => + if f = "=" ∧ pos = false then .split [[.app "<" [a, b]], [.app "<" [b, a]]] + else .cons ((cmpCons f pos la lb).map Lin.norm) + | _, _ => .drop + +def stepNot (x : Tm) : Step := + match x with + | .tt => .closed + | .ff => .drop + | .app f args => + if f = "not" then (match args with | [a] => .facts [a] | _ => .drop) + else if f = "and" then .split (args.map fun a => [neg a]) + else if f = "or" then .facts (args.map neg) + else if f = "=>" then (match args with | [a, b] => .facts [a, neg b] | _ => .drop) + else if isCmp f then (match args with | [a, b] => atomStep false f a b | _ => .drop) + else .drop + | .all x body => .skolem x (neg body) + | _ => .drop + +/-- The instances of `(forall ((x Int)) body)` at the integer constants `ks` (the goal's +quantified variables, opened as constants by `skolem`), leaving out a constant `body` binds. -/ +def instances (ks : List String) (x : String) (body : Tm) : List Tm := + ks.filterMap fun k => if body.binders.contains k then none else some (body.subst .int x (.ivar k)) + +def step (ks : List String) (t : Tm) : Step := + match t with + | .tt => .drop + | .ff => .closed + | .app f args => + if f = "and" then .facts args + else if f = "or" then .split (args.map fun a => [a]) + else if f = "=>" then (match args with | [a, b] => .split [[neg a], [b]] | _ => .drop) + else if f = "not" then (match args with | [x] => stepNot x | _ => .drop) + else if isCmp f then (match args with | [a, b] => atomStep true f a b | _ => .drop) + else .drop + | .all x body => .facts (instances ks x body) + | _ => .drop + +/-- The constant `x` occurs in none of the facts `rest` and the constraints `cs`. -/ +def fresh (x : String) (rest : List Tm) (cs : List Lin) : Bool := + rest.all (fun u => !u.vars.contains x) && cs.all (fun l => l.cs.all fun p => !p.1.vars.contains x) + +/-- Replace every integer `ite` on the condition `c` by its case `b`, `n` levels deep, outside +quantifiers. -/ +def resolve (c : Tm) (b : Bool) : Nat → Tm → Tm + | 0, t => t + | n + 1, t => + match t with + | .app f args => + let t' := Tm.app f (args.map (resolve c b n)) + match isIte t' with + | some (c', p, q) => if Tm.beq c' c then (if b then p else q) else t' + | none => t' + | t => t + +def resolveFuel : Nat := 64 + +def substFuel : Nat := 128 + +/-- The equation a case `c` of an `ite` gives, when it is `(= a b)` of integers with `a` (or `b`) a +constant: in the case where `c` holds, the constant is replaced by the other side. -/ +def iteEqs (c : Tm) : List (Tm × Tm) := + match c with + | .app f [a, b] => + if f = "=" ∧ a.isIntAtom = true ∧ b.isIntAtom = true then + (if a.isConst then [(a, b)] else if b.isConst then [(b, a)] else []) + else [] + | _ => [] + +/-- Whether the facts `ts` and the constraints `cs` have no common model, with `n` steps on each +branch, at most `b` nested case splits, and `F` eliminations at the end of each branch. -/ +def refute (F : Nat) (ks : List String) : Nat → Nat → List Tm → List Lin → Bool + | 0, _, _, _ => false + | _ + 1, _, [], cs => fm F cs + | n + 1, b, t :: rest, cs => + match step ks t with + | .drop => refute F ks n b rest cs + | .closed => true + | .facts ts => refute F ks n b (ts ++ rest) cs + | .cons ls => refute F ks n b rest (ls ++ cs) + | .split bs => fm F cs || (b != 0 && bs.all fun ts => refute F ks n (b - 1) (ts ++ rest) cs) + | .ite c t1 t2 => + fm F cs || b != 0 && (refute F ks n (b - 1) + (c :: ((t1 :: rest).map (resolve c true resolveFuel)).map (substN (iteEqs c) substFuel)) cs && + refute F ks n (b - 1) (neg c :: (t2 :: rest).map (resolve c false resolveFuel)) cs) + | .skolem x t => + if fresh x rest cs then refute F ks n b (t :: rest) cs + else if fresh (x ++ "'") (t :: rest) cs then + refute F ks n b (t.subst .int x (.ivar (x ++ "'")) :: rest) cs + else refute F ks n b rest cs + +/-! ## Arrays -/ + +/-- `(store a i v)` of an array of integers or of a mapping of mappings. -/ +def rowSorts (a v : Tm) : Bool := + (a.sort? == some .arr && v.isIntAtom) || (a.sort? == some .arr2 && v.sort? == some .arr) + +/-- Two arrays of one sort. -/ +def arrPair (p q : Tm) : Bool := + (p.sort? == some .arr && q.sort? == some .arr) || (p.sort? == some .arr2 && q.sort? == some .arr2) + +/-- One step at `(select x j)`, `x` and `j` rewritten: read over write (`v` itself when `j` and `i` +are one term), a read of an `ite` of arrays as the `ite` of its reads, and a read of a constant +array. `r` rewrites the new reads. -/ +def rowSel (r : Tm → Tm) (x j : Tm) : Tm := + match x with + | .app g [a, i, v] => + if g = "store" ∧ i.isIntAtom = true ∧ j.isIntAtom = true ∧ rowSorts a v = true then + (if Tm.beq j i then v else .app "ite" [.app "=" [j, i], v, r (.app "select" [a, j])]) + else if g = "ite" ∧ arrPair i v = true then + .app "ite" [a, r (.app "select" [i, j]), r (.app "select" [v, j])] + else .app "select" [x, j] + | .app g [v] => + if (g = isOpName.constName ∧ v.isIntAtom = true) ∨ (g = isOpName.const2Name ∧ v.sort? = some .arr) + then v else .app "select" [x, j] + | _ => .app "select" [x, j] + +/-- Read over write, inside out, `n` levels deep, outside quantifiers (`rowSel`). -/ +def rowN : Nat → Tm → Tm + | 0, t => t + | n + 1, t => + match t with + | .app f args => + let args' := args.map (rowN n) + if f = "select" then + match args' with + | [x, j] => rowSel (rowN n) x j + | _ => .app f args' + else .app f args' + | .all x body => .all x (rowN n body) + | t => t + +def rowFuel : Nat := 64 + +/-! ## The procedure -/ + +def stepFuel : Nat := 4096 +def splitFuel : Nat := 48 +def fmFuel : Nat := 256 + +/-- The constants reachable from `xs` through facts that share one, in `n` rounds. -/ +def reach (fs : List Tm) : Nat → List String → List String + | 0, xs => xs + | n + 1, xs => reach fs n ((fs.filter fun t => t.vars.any xs.contains).flatMap Tm.vars ++ xs) + +/-- Keep the facts that mention a constant reachable from the last fact's (the negated goal's), +and those that mention none. Dropping facts is sound: a model of all of them is one of these. -/ +def relevant (fs : List Tm) : List Tm := + let xs := reach fs 3 ((fs.getLast?.map Tm.vars).getD []) + fs.filter fun t => t.vars.isEmpty || t.vars.any xs.contains + +mutual +/-- The terms `(mod t M)` and `(div t M)` with `M` a positive numeral, outside quantifiers, as +`(t, M)`. -/ +def Tm.mods : Tm → List (Tm × Nat) + | .app f args => + (match f, args with + | "mod", [t, .num m] => if 0 < m then [(t, m)] else [] + | "div", [t, .num m] => if 0 < m then [(t, m)] else [] + | _, _ => []) ++ Tm.modsList args + | _ => [] +def Tm.modsList : List Tm → List (Tm × Nat) + | [] => [] + | t :: ts => Tm.mods t ++ Tm.modsList ts +end + +/-- What every model gives `(mod t M)` and `(div t M)`, for `0 < M`: `t = M * (div t M) + (mod t M)` +and `0 ≤ (mod t M) ≤ M - 1`, and the integer `(div t M)` is at most -1, 0 or at least 1 (the +cases that let Fourier-Motzkin, over the rationals, see that it is an integer). -/ +def modFacts (t : Tm) (m : Nat) : List Tm := + let r := Tm.app "mod" [t, .num m] + let q := Tm.app "div" [t, .num m] + [.app "=" [t, .app "+" [.app "*" [.num m, q], r]], .app "<=" [.num 0, r], .app "<=" [r, .num (m - 1)], + .app "or" [.app "<=" [.app "+" [q, .num 1], .num 0], .app "=" [q, .num 0], .app "<=" [.num 1, q]]] + +/-- The facts of every `mod` and `div` by a positive numeral in `fs`. -/ +def divFacts (fs : List Tm) : List Tm := + ((Tm.modsList fs).foldl (fun acc p => if acc.any (fun q => q.2 == p.2 && Tm.beq q.1 p.1) then acc + else acc ++ [p]) []).flatMap fun p => + if p.1.isIntAtom = true ∧ 0 < p.2 then modFacts p.1 p.2 else [] + +/-- The last fact (the negated goal) first, so that its quantifiers are opened before the facts that +are instantiated at them. -/ +def goalFirst (fs : List Tm) : List Tm := fs.getLast?.toList ++ fs.dropLast + +mutual +/-- The integer constants a term reads or writes an array at, outside quantifiers. -/ +def Tm.selIdx : Tm → List String + | .app f args => + (match f, args with + | "select", [_, .ivar x] => [x] + | "store", [_, .ivar x, _] => [x] + | _, _ => []) ++ Tm.selIdxList args + | _ => [] +def Tm.selIdxList : List Tm → List String + | [] => [] + | t :: ts => Tm.selIdx t ++ Tm.selIdxList ts +end + +/-- The constants the facts' quantifiers are instantiated at: the variables the goal quantifies +(opened as constants first, or under a primed name when the plain one is taken) and the integer +constants the facts index arrays at. -/ +def goalBinders (fs : List Tm) : List String := + let bs := (fs.getLast?.map Tm.binders).getD [] + (bs ++ bs.map (· ++ "'") ++ Tm.selIdxList fs).foldl + (fun acc x => if acc.contains x then acc else acc ++ [x]) [] + +/-- Whether one obligation's facts have no model: its equations are substituted, and dropped, the +facts the goal does not reach are left out, and the goal comes first. -/ +def refuteOb (fs : List Tm) : Bool := + let eqs := fs.filterMap eqOf? + let gs := (fs.filter fun t => (eqOf? t).isNone).map fun t => rowN rowFuel (substN eqs substFuel t) + let rs := relevant gs + refute fmFuel (goalBinders rs) stepFuel splitFuel (goalFirst rs) [] || + refute fmFuel (goalBinders rs) stepFuel splitFuel (goalFirst rs ++ divFacts rs) [] + +/-- Whether every obligation of a script but the probes has no model. -/ +def dischargeScript (cs : List Cmd) : Bool := + (obligations cs).all fun fs => isProbe fs || refuteOb fs + +/-- Whether the obligation at index `i` of a script is a probe or has no model: one kernel check +per obligation keeps each evaluation small (`dischargeScript_of_each`). -/ +def dischargeAt (cs : List Cmd) (i : Nat) : Bool := + let fs := (obligations cs).getD i [] + isProbe fs || refuteOb fs + +end SolidCore.Verify.VC + +/-! ## Soundness -/ + +namespace SolidCore.Verify.VC + +section Sound + +variable (σ : Env) + +theorem sumCs_append (l m : List (Tm × Int)) : sumCs σ (l ++ m) = sumCs σ l + sumCs σ m := by + induction l with + | nil => simp [sumCs] + | cons p ps ih => simp only [List.cons_append, sumCs, ih]; ring + +theorem sumCs_scale (c : Int) (l : List (Tm × Int)) : + sumCs σ (l.map fun p => (p.1, c * p.2)) = c * sumCs σ l := by + induction l with + | nil => simp [sumCs] + | cons p ps ih => simp only [List.map_cons, sumCs, ih]; ring + +theorem Lin.eval_add (a b : Lin) : (a.add b).eval σ = a.eval σ + b.eval σ := by + simp only [Lin.add, Lin.eval, sumCs_append]; ring + +theorem Lin.eval_scale (c : Int) (a : Lin) : (a.scale c).eval σ = c * a.eval σ := by + simp only [Lin.scale, Lin.eval, sumCs_scale]; ring + +theorem Lin.eval_sub (a b : Lin) : (a.sub b).eval σ = a.eval σ - b.eval σ := by + simp only [Lin.sub, Lin.eval_add, Lin.eval_scale]; ring + +theorem Lin.eval_inc (a : Lin) : a.inc.eval σ = a.eval σ + 1 := by + simp only [Lin.inc, Lin.eval]; ring + +theorem sumCs_insertC (p : Tm × Int) (qs : List (Tm × Int)) : + sumCs σ (insertC p qs) = p.2 * (p.1.eval σ).toInt + sumCs σ qs := by + induction qs with + | nil => simp [insertC, sumCs] + | cons q qs ih => + simp only [insertC] + split + · rename_i h + have := Tm.eq_of_beq h + simp only [sumCs, this]; ring + · simp only [sumCs, ih]; ring + +theorem sumCs_foldr (l : List (Tm × Int)) : sumCs σ (l.foldr insertC []) = sumCs σ l := by + induction l with + | nil => simp [sumCs] + | cons p ps ih => simp only [List.foldr_cons, sumCs_insertC, ih, sumCs] + +theorem sumCs_filter (l : List (Tm × Int)) : + sumCs σ (l.filter fun p => p.2 != 0) = sumCs σ l := by + induction l with + | nil => simp [sumCs] + | cons p ps ih => + by_cases h : p.2 = 0 + · simp [h, sumCs, ih] + · simp [h, sumCs, ih] + +theorem Lin.eval_norm (a : Lin) : a.norm.eval σ = a.eval σ := by + simp only [Lin.norm, Lin.eval, sumCs_filter, sumCs_foldr] + +/-! ### Fourier-Motzkin -/ + +theorem elim_sound (x : Tm) (cs : List Lin) (h : ∀ l ∈ cs, l.eval σ ≤ 0) : + ∀ l ∈ elim x cs, l.eval σ ≤ 0 := by + intro l hl + simp only [elim, List.mem_append, List.mem_filter, List.mem_flatMap, List.mem_map] at hl + rcases hl with ⟨hl, _⟩ | ⟨p, ⟨hp, hpx⟩, q, ⟨hq, hqx⟩, rfl⟩ + · exact h l hl + · rw [Lin.eval_norm, Lin.eval_add, Lin.eval_scale, Lin.eval_scale] + have h1 := h p hp + have h2 := h q hq + simp only [decide_eq_true_eq] at hpx hqx + nlinarith + +theorem fm_sound : ∀ (n : Nat) (cs : List Lin), fm n cs = true → (∀ l ∈ cs, l.eval σ ≤ 0) → False + | 0, _, h, _ => by simp [fm] at h + | n + 1, cs, h, hc => by + have hc' : ∀ l ∈ cs.filter (fun l => !(l.cs.isEmpty && decide (l.k ≤ 0))), l.eval σ ≤ 0 := + fun l hl => hc l (List.mem_filter.mp hl).1 + simp only [fm] at h + generalize cs.filter (fun l => !(l.cs.isEmpty && decide (l.k ≤ 0))) = ds at h hc' + split at h + · rename_i hany + obtain ⟨l, hl, hk⟩ := List.any_eq_true.mp hany + simp only [Bool.and_eq_true, List.isEmpty_iff, decide_eq_true_eq] at hk + have := hc' l hl + simp only [Lin.eval, hk.1, sumCs] at this + omega + · split at h + · simp at h + · split at h + · exact fm_sound n _ h (elim_sound σ _ _ hc') + · simp at h + +/-! ### Terms -/ + +theorem eval_app (f : String) (args : List Tm) : + (Tm.app f args).eval σ = applyOp σ.u f (args.map (Tm.eval σ)) := by + simp [Tm.eval, Tm.evalList_eq] + +theorem holds_app (f : String) (args : List Tm) : + (Tm.app f args).Holds σ = (applyOp σ.u f (args.map (Tm.eval σ))).toProp := by + simp [Tm.Holds, eval_app] + +theorem eval_num (n : Nat) : (Tm.num n).eval σ = .int n := by simp [Tm.eval] + +theorem holds_neg (t : Tm) : (neg t).Holds σ ↔ ¬ t.Holds σ := by + rw [neg, holds_app]; simp [applyOp, Value.toProp, Tm.Holds] + +theorem holds_and (args : List Tm) : (Tm.app "and" args).Holds σ ↔ ∀ a ∈ args, a.Holds σ := by + rw [holds_app]; simp [applyOp, Value.toProp, Tm.Holds] + +theorem holds_or (args : List Tm) : (Tm.app "or" args).Holds σ ↔ ∃ a ∈ args, a.Holds σ := by + rw [holds_app]; simp [applyOp, Value.toProp, Tm.Holds] + +theorem holds_imp (a b : Tm) : (Tm.app "=>" [a, b]).Holds σ ↔ (a.Holds σ → b.Holds σ) := by + rw [holds_app]; simp [applyOp, Value.toProp, Tm.Holds] + +theorem int_atom {t : Tm} (h : t.isIntAtom = true) : t.eval σ = .int (t.eval σ).toInt := by + simp only [Tm.isIntAtom, beq_iff_eq] at h + exact Value.sortOf_int (Tm.eval_sortOf t σ h) + +theorem linAtom_sound {t : Tm} {l : Lin} (h : linAtom t = some l) : t.eval σ = .int (l.eval σ) := by + unfold linAtom at h + split_ifs at h with ha + simp only [Option.some.injEq] at h + subst h + rw [int_atom σ ha] + simp [Lin.eval, sumCs] + +theorem lin_sound : ∀ (n : Nat) (t : Tm) (l : Lin), lin n t = some l → t.eval σ = .int (l.eval σ) + | 0, _, _, h => by simp [lin] at h + | n + 1, t, l, h => by + unfold lin at h + split at h + · simp only [Option.some.injEq] at h + subst h + simp [eval_num, Lin.eval, sumCs] + · rename_i f args + split_ifs at h with h1 h2 h3 + · subst h1 + split at h + · rename_i a b + split at h + · rename_i la lb ha hb + simp only [Option.some.injEq] at h + subst h + simp [eval_app, applyOp, lin_sound n a la ha, lin_sound n b lb hb, Value.toInt, + Lin.eval_add] + · simp at h + · simp at h + · subst h2 + split at h + · rename_i a + cases ha : lin n a with + | none => simp [ha] at h + | some la => + simp only [ha, Option.map_some, Option.some.injEq] at h + subst h + simp [eval_app, applyOp, lin_sound n a la ha, Value.toInt, Lin.eval_scale] + · rename_i a b + split at h + · rename_i la lb ha hb + simp only [Option.some.injEq] at h + subst h + simp [eval_app, applyOp, lin_sound n a la ha, lin_sound n b lb hb, Value.toInt, + Lin.eval_sub] + · simp at h + · simp at h + · subst h3 + split at h + · rename_i c a + cases ha : lin n a with + | none => simp [ha] at h + | some la => + simp only [ha, Option.map_some, Option.some.injEq] at h + subst h + simp [eval_app, applyOp, lin_sound n a la ha, Value.toInt, Lin.eval_scale, eval_num] + · rename_i a c _ + cases ha : lin n a with + | none => simp [ha] at h + | some la => + simp only [ha, Option.map_some, Option.some.injEq] at h + subst h + simp [eval_app, applyOp, lin_sound n a la ha, Value.toInt, Lin.eval_scale, eval_num] + ring + · exact linAtom_sound σ h + · exact linAtom_sound σ h + · exact linAtom_sound σ h + +theorem holds_wrap_congr {pos : Bool} {X Y : Tm} (he : X.eval σ = Y.eval σ) + (h : (wrap pos X).Holds σ) : (wrap pos Y).Holds σ := by + cases pos + · simp only [wrap, holds_neg, Bool.false_eq_true, ↓reduceIte] at h ⊢ + simpa [Tm.Holds, he] using h + · simp only [wrap, ↓reduceIte] at h ⊢ + simpa [Tm.Holds, he] using h + +theorem isIte_sound {t c p q : Tm} (h : isIte t = some (c, p, q)) : + (c.Holds σ → t.eval σ = p.eval σ) ∧ (¬ c.Holds σ → t.eval σ = q.eval σ) := by + unfold isIte at h + split at h + · rename_i g c' p' q' + split_ifs at h with hg + obtain ⟨rfl, hp, hq⟩ := hg + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl, rfl⟩ := h + obtain ⟨x, hx⟩ : ∃ x, p'.eval σ = .int x := ⟨_, int_atom σ hp⟩ + obtain ⟨y, hy⟩ : ∃ y, q'.eval σ = .int y := ⟨_, int_atom σ hq⟩ + refine ⟨fun hc => ?_, fun hc => ?_⟩ <;> + simp only [Tm.Holds] at hc <;> simp [eval_app, hx, hy, applyOp, hc] + · simp at h + +theorem liftArgs_sound {g : Tm → Option (Tm × Tm × Tm)} + (hg : ∀ t c t1 t2, g t = some (c, t1, t2) → + (c.Holds σ → t.eval σ = t1.eval σ) ∧ (¬ c.Holds σ → t.eval σ = t2.eval σ)) : + ∀ (args : List Tm) {c : Tm} {l1 l2 : List Tm}, liftArgs g args = some (c, l1, l2) → + (c.Holds σ → args.map (Tm.eval σ) = l1.map (Tm.eval σ)) ∧ + (¬ c.Holds σ → args.map (Tm.eval σ) = l2.map (Tm.eval σ)) + | [], _, _, _, h => by simp [liftArgs] at h + | a :: as, c, l1, l2, h => by + simp only [liftArgs] at h + split at h + · rename_i c' a1 a2 ha + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl, rfl⟩ := h + obtain ⟨h1, h2⟩ := hg a _ _ _ ha + exact ⟨fun hc => by simp [h1 hc], fun hc => by simp [h2 hc]⟩ + · cases hr : liftArgs g as with + | none => simp [hr] at h + | some r => + simp only [hr, Option.map_some, Option.some.injEq] at h + obtain ⟨c', r1, r2⟩ := r + simp only [Prod.mk.injEq] at h + obtain ⟨rfl, rfl, rfl⟩ := h + obtain ⟨h1, h2⟩ := liftArgs_sound hg as hr + exact ⟨fun hc => by simp [h1 hc], fun hc => by simp [h2 hc]⟩ + +theorem liftIte_sound : ∀ (n : Nat) (t c t1 t2 : Tm), liftIte n t = some (c, t1, t2) → + (c.Holds σ → t.eval σ = t1.eval σ) ∧ (¬ c.Holds σ → t.eval σ = t2.eval σ) + | 0, _, _, _, _, h => by simp [liftIte] at h + | n + 1, t, c, t1, t2, h => by + unfold liftIte at h + split at h + · rename_i f args + split at h + · rename_i r hi + simp only [Option.some.injEq] at h + subst h + exact isIte_sound σ hi + · cases hr : liftArgs (liftIte n) args with + | none => simp [hr] at h + | some r => + simp only [hr, Option.map_some, Option.some.injEq] at h + obtain ⟨c', r1, r2⟩ := r + simp only [Prod.mk.injEq] at h + obtain ⟨rfl, rfl, rfl⟩ := h + obtain ⟨h1, h2⟩ := liftArgs_sound σ (liftIte_sound n) args hr + exact ⟨fun hc => by simp only [eval_app, h1 hc], fun hc => by simp only [eval_app, h2 hc]⟩ + · simp at h + +theorem cmpCons_sound (f : String) (pos : Bool) {a b : Tm} {la lb : Lin} + (ha : a.eval σ = .int (la.eval σ)) (hb : b.eval σ = .int (lb.eval σ)) + (h : (wrap pos (.app f [a, b])).Holds σ) : ∀ l ∈ cmpCons f pos la lb, l.eval σ ≤ 0 := by + intro l hl + have hx : (Tm.app f [a, b]).Holds σ = + (applyOp σ.u f [.int (la.eval σ), .int (lb.eval σ)]).toProp := by + rw [holds_app]; simp [ha, hb] + have hw : (wrap pos (.app f [a, b])).Holds σ ↔ + (if pos then (applyOp σ.u f [.int (la.eval σ), .int (lb.eval σ)]).toProp + else ¬ (applyOp σ.u f [.int (la.eval σ), .int (lb.eval σ)]).toProp) := by + cases pos <;> simp [wrap, holds_neg, hx] + rw [hw] at h + unfold cmpCons at hl + by_cases h1 : f = "<=" + · subst h1 + cases pos <;> simp [applyOp, Value.toProp, Value.toInt] at h hl <;> subst hl <;> + simp only [Lin.eval_sub, Lin.eval_inc] <;> omega + by_cases h2 : f = "<" + · subst h2 + cases pos <;> simp [applyOp, Value.toProp, Value.toInt] at h hl <;> subst hl <;> + simp only [Lin.eval_sub, Lin.eval_inc] <;> omega + by_cases h3 : f = ">=" + · subst h3 + cases pos <;> simp [applyOp, Value.toProp, Value.toInt] at h hl <;> subst hl <;> + simp only [Lin.eval_sub, Lin.eval_inc] <;> omega + by_cases h4 : f = ">" + · subst h4 + cases pos <;> simp [applyOp, Value.toProp, Value.toInt] at h hl <;> subst hl <;> + simp only [Lin.eval_sub, Lin.eval_inc] <;> omega + by_cases h5 : f = "=" + · subst h5 + cases pos + · simp at hl + · simp [applyOp, Value.toProp, Value.eq] at h hl + rcases hl with rfl | rfl <;> simp only [Lin.eval_sub] <;> omega + simp [h1, h2, h3, h4, h5] at hl + +/-- What a step of the tableau may assume of one fact's model. -/ +def StepOK : Step → Prop + | .drop => True + | .closed => False + | .facts ts => ∀ u ∈ ts, u.Holds σ + | .cons ls => ∀ l ∈ ls, l.eval σ ≤ 0 + | .split bs => ∃ ts ∈ bs, ∀ u ∈ ts, u.Holds σ + | .ite c t1 t2 => (c.Holds σ ∧ t1.Holds σ) ∨ (¬ c.Holds σ ∧ t2.Holds σ) + | .skolem x t => ∃ m : Int, t.Holds (σ.setI x m) + +theorem atomStep_sound (pos : Bool) (f : String) (a b : Tm) + (h : (wrap pos (.app f [a, b])).Holds σ) : StepOK σ (atomStep pos f a b) := by + unfold atomStep + split + · rename_i c t1 t2 hs + obtain ⟨h1, h2⟩ := liftIte_sound σ _ _ _ _ _ hs + by_cases hc : c.Holds σ + · exact Or.inl ⟨hc, holds_wrap_congr σ (h1 hc) h⟩ + · exact Or.inr ⟨hc, holds_wrap_congr σ (h2 hc) h⟩ + · split + · rename_i la lb hla hlb + have ha := lin_sound σ _ _ _ hla + have hb := lin_sound σ _ _ _ hlb + split_ifs with he + · obtain ⟨rfl, rfl⟩ := he + simp only [wrap, holds_neg, holds_app, List.map_cons, List.map_nil, ha, hb, + Bool.false_eq_true, ↓reduceIte] at h + simp only [applyOp, Value.toProp, Value.eq] at h + rcases lt_or_gt_of_ne h with h | h + · exact ⟨[.app "<" [a, b]], by simp, by + simp [holds_app, ha, hb, applyOp, Value.toProp, Value.toInt, h]⟩ + · exact ⟨[.app "<" [b, a]], by simp, by + simp [holds_app, ha, hb, applyOp, Value.toProp, Value.toInt, h]⟩ + · intro l hl + simp only [List.mem_map] at hl + obtain ⟨l', hl', rfl⟩ := hl + rw [Lin.eval_norm] + exact cmpCons_sound σ f pos ha hb h l' hl' + · trivial + +theorem stepNot_sound (x : Tm) (h : ¬ x.Holds σ) : StepOK σ (stepNot x) := by + unfold stepNot + split + · exact h (by simp [Tm.Holds, Tm.eval, Value.toProp]) + · trivial + · rename_i f args + split_ifs with h1 h2 h3 h4 h5 + · subst h1 + split + · rename_i a + have : ¬ (neg a).Holds σ := h + rw [holds_neg] at this + intro u hu + simp only [List.mem_cons, List.mem_nil_iff, or_false] at hu + subst hu + exact Classical.not_not.mp this + · trivial + · subst h2 + rw [holds_and] at h + push Not at h + obtain ⟨a, ha, hna⟩ := h + exact ⟨[neg a], List.mem_map.mpr ⟨a, ha, rfl⟩, by simp [holds_neg, hna]⟩ + · subst h3 + rw [holds_or] at h + push Not at h + intro u hu + obtain ⟨a, ha, rfl⟩ := List.mem_map.mp hu + exact (holds_neg σ a).mpr (h a ha) + · subst h4 + split + · rename_i a b + rw [holds_imp] at h + push Not at h + intro u hu + simp only [List.mem_cons, List.mem_nil_iff, or_false] at hu + rcases hu with rfl | rfl + · exact h.1 + · exact (holds_neg σ b).mpr h.2 + · trivial + · split + · rename_i a b + exact atomStep_sound σ false f a b (by simpa [wrap, holds_neg] using h) + · trivial + · trivial + · rename_i x body + have h' : ¬ ∀ m : Int, body.Holds (σ.setI x m) := h + push Not at h' + obtain ⟨m, hm⟩ := h' + exact ⟨m, (holds_neg _ body).mpr hm⟩ + · trivial + +theorem step_sound (ks : List String) (t : Tm) (h : t.Holds σ) : StepOK σ (step ks t) := by + unfold step + split + · trivial + · exact h + · rename_i f args + split_ifs with h1 h2 h3 h4 h5 + · subst h1 + exact (holds_and σ args).mp h + · subst h2 + obtain ⟨a, ha, hh⟩ := (holds_or σ args).mp h + exact ⟨[a], List.mem_map.mpr ⟨a, ha, rfl⟩, by simp [hh]⟩ + · subst h3 + split + · rename_i a b + have := (holds_imp σ a b).mp h + by_cases ha : a.Holds σ + · exact ⟨[b], by simp, by simp [this ha]⟩ + · exact ⟨[neg a], by simp, by simp [holds_neg, ha]⟩ + · trivial + · subst h4 + split + · rename_i x + exact stepNot_sound σ x ((holds_neg σ x).mp h) + · trivial + · split + · rename_i a b + exact atomStep_sound σ true f a b (by simpa [wrap] using h) + · trivial + · trivial + · rename_i x body + intro u hu + simp only [instances, List.mem_filterMap] at hu + obtain ⟨k, -, hk⟩ := hu + split at hk + · simp at hk + · rename_i hb + simp only [Option.some.injEq] at hk + subst hk + have hall : ∀ m : Int, body.Holds (σ.setI x m) := h + have := hall (σ.i k) + simp only [Tm.Holds] at this ⊢ + rw [Tm.eval_subst .int x (.ivar k) rfl body σ (fun y hy hyk => by + simp only [Tm.vars, List.mem_cons, List.not_mem_nil, or_false] at hyk + subst hyk; simp_all)] + exact this + · trivial + +theorem resolve_eval (c : Tm) (b : Bool) (hc : if b then c.Holds σ else ¬ c.Holds σ) : + ∀ (n : Nat) (t : Tm), (resolve c b n t).eval σ = t.eval σ + | 0, _ => rfl + | n + 1, t => by + cases t with + | app f args => + have hargs : (Tm.app f (args.map (resolve c b n))).eval σ = (Tm.app f args).eval σ := by + rw [eval_app, eval_app, List.map_map] + congr 1 + apply List.map_congr_left + intro a _ + exact resolve_eval c b hc n a + simp only [resolve] + split + · rename_i c' p q hi + obtain ⟨h1, h2⟩ := isIte_sound σ hi + split_ifs with hb hbb + · have := Tm.eq_of_beq hb + subst this + rw [← hargs, h1 (by simpa [hbb] using hc)] + · have := Tm.eq_of_beq hb + subst this + rw [← hargs, h2 (by simpa [hbb] using hc)] + · exact hargs + · exact hargs + | _ => rfl + +mutual +theorem Tm.mem_vars_of_binders : ∀ (t : Tm) {y : String}, y ∈ t.binders → y ∈ t.vars + | .app _ args, y, h => by + simp only [Tm.binders] at h + simpa [Tm.vars] using Tm.mem_varsList_of_bindersList args h + | .all x body, y, h => by + simp only [Tm.binders, List.mem_cons] at h + simp only [Tm.vars, List.mem_cons] + rcases h with h | h + · exact Or.inl h + · exact Or.inr (Tm.mem_vars_of_binders body h) + | .num _, _, h | .tt, _, h | .ff, _, h | .ivar _, _, h | .bvar _, _, h | .avar _, _, h + | .a2var _, _, h => by simp [Tm.binders] at h +theorem Tm.mem_varsList_of_bindersList : ∀ (ts : List Tm) {y : String}, y ∈ Tm.bindersList ts → + y ∈ Tm.varsList ts + | [], _, h => by simp [Tm.bindersList] at h + | t :: ts, y, h => by + simp only [Tm.bindersList, List.mem_append] at h + simp only [Tm.varsList, List.mem_append] + rcases h with h | h + · exact Or.inl (Tm.mem_vars_of_binders t h) + · exact Or.inr (Tm.mem_varsList_of_bindersList ts h) +end + +theorem agree_setI_ne {τ : Env} {x y : String} (m : Int) (h : y ≠ x) : (τ.setI x m).Agree τ y := + ⟨by simp [Env.setI, h], rfl, rfl, rfl⟩ + +theorem sumCs_congr {τ ρ : Env} (hu : τ.u = ρ.u) : ∀ (l : List (Tm × Int)), (∀ p ∈ l, ∀ y ∈ p.1.vars, τ.Agree ρ y) → + sumCs τ l = sumCs ρ l + | [], _ => rfl + | p :: ps, h => by + simp only [sumCs] + rw [Tm.eval_congr p.1 hu (h p (by simp)), sumCs_congr hu ps (fun q hq => h q (by simp [hq]))] + +/-! ### Definitions -/ + +theorem eqOf_sound {t v u : Tm} (h : eqOf? t = some (v, u)) (ht : t.Holds σ) : + v.eval σ = u.eval σ := by + unfold eqOf? at h + split at h + · rename_i f v' u' + split_ifs at h with hc + obtain ⟨rfl, hv⟩ := hc + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + simp only [holds_app, List.map_cons, List.map_nil, applyOp, Value.toProp] at ht + cases v' <;> simp [Tm.isConst] at hv <;> simp only [Tm.eval] at ht ⊢ <;> + cases hu : u'.eval σ <;> simp [hu, Value.eq] at ht ⊢ + all_goals exact ht + · simp at h + +theorem lookupEq_mem : ∀ {eqs : List (Tm × Tm)} {v u : Tm}, lookupEq eqs v = some u → + ∃ e ∈ eqs, e.1 = v ∧ e.2 = u + | [], _, _, h => by simp [lookupEq] at h + | e :: es, v, u, h => by + simp only [lookupEq] at h + split at h + · rename_i hb + simp only [Option.some.injEq] at h + exact ⟨e, by simp, Tm.eq_of_beq hb, h⟩ + · obtain ⟨e', he', h1, h2⟩ := lookupEq_mem h + exact ⟨e', by simp [he'], h1, h2⟩ + +theorem substN_eval : ∀ (n : Nat) (eqs : List (Tm × Tm)) (σ : Env), + (∀ e ∈ eqs, e.1.eval σ = e.2.eval σ) → ∀ t : Tm, (substN eqs n t).eval σ = t.eval σ + | 0, _, _, _, _ => rfl + | n + 1, eqs, σ, he, t => by + cases t with + | app f args => + simp only [substN, eval_app, List.map_map] + congr 1 + apply List.map_congr_left + intro a _ + exact substN_eval n eqs σ he a + | all x body => + have hb : ∀ m : Int, (substN (eqs.filter fun e => !(e.1.vars.contains x || e.2.vars.contains x)) + n body).eval (σ.setI x m) = body.eval (σ.setI x m) := by + intro m + refine substN_eval n _ _ ?_ body + intro e hm + obtain ⟨hm, hx⟩ := List.mem_filter.mp hm + have h1 : x ∉ e.1.vars := fun hm' => by simp [hm'] at hx + have h2 : x ∉ e.2.vars := fun hm' => by simp [hm'] at hx + rw [Tm.eval_congr e.1 (σ := σ.setI x m) (τ := σ) rfl + (fun y hy => agree_setI_ne (x := x) m (fun h => h1 (h ▸ hy))), + Tm.eval_congr e.2 (σ := σ.setI x m) (τ := σ) rfl + (fun y hy => agree_setI_ne (x := x) m (fun h => h2 (h ▸ hy)))] + exact he e hm + simp only [substN, Tm.eval, hb] + | _ => + simp only [substN] + split_ifs + · split + · rename_i u hl + obtain ⟨e, hm, h1, h2⟩ := lookupEq_mem hl + rw [substN_eval n eqs σ he u, ← h2, ← he e hm, h1] + · rfl + · rfl + +theorem iteEqs_sound (c : Tm) (hc : c.Holds σ) : ∀ e ∈ iteEqs c, e.1.eval σ = e.2.eval σ := by + intro e he + unfold iteEqs at he + split at he + · rename_i f a b + by_cases h1 : f = "=" ∧ a.isIntAtom = true ∧ b.isIntAtom = true + · rw [if_pos h1] at he + obtain ⟨rfl, ha, hb⟩ := h1 + have ea := int_atom σ ha + have eb := int_atom σ hb + have hc' : (a.eval σ).toInt = (b.eval σ).toInt := by + simp only [holds_app, List.map_cons, List.map_nil, applyOp, Value.toProp] at hc + rw [ea, eb] at hc + simpa [Value.eq] using hc + have hab : a.eval σ = b.eval σ := by rw [ea, eb, hc'] + split at he + · simp only [List.mem_singleton] at he; subst he; exact hab + · split at he + · simp only [List.mem_singleton] at he; subst he; exact hab.symm + · simp at he + · rw [if_neg h1] at he; simp at he + · simp at he + +theorem refute_sound (F : Nat) (ks : List String) : ∀ (n b : Nat) (σ : Env) (ts : List Tm) (cs : List Lin), + refute F ks n b ts cs = true → (∀ t ∈ ts, t.Holds σ) → (∀ l ∈ cs, l.eval σ ≤ 0) → False + | 0, _, _, _, _, h, _, _ => by simp [refute] at h + | n + 1, _, σ, [], cs, h, _, hc => fm_sound σ F cs (by simpa [refute] using h) hc + | n + 1, b, σ, t :: rest, cs, h, ht, hc => by + have hst := step_sound σ ks t (ht t (by simp)) + have hr : ∀ u ∈ rest, u.Holds σ := fun u hu => ht u (by simp [hu]) + simp only [refute] at h + generalize step ks t = s at h hst + cases s with + | drop => exact refute_sound F ks n b σ rest cs h hr hc + | closed => exact hst + | facts us => + refine refute_sound F ks n b σ _ cs h ?_ hc + intro u hu + rcases List.mem_append.mp hu with hu | hu + · exact hst u hu + · exact hr u hu + | cons ls => + refine refute_sound F ks n b σ rest _ h hr ?_ + intro l hl + rcases List.mem_append.mp hl with hl | hl + · exact hst l hl + · exact hc l hl + | split bs => + rcases Bool.or_eq_true _ _ |>.mp h with h | h + · exact fm_sound σ F cs h hc + obtain ⟨us, hus, hall⟩ := hst + refine refute_sound F ks n (b - 1) σ _ cs + (List.all_eq_true.mp (Bool.and_eq_true _ _ |>.mp h).2 us hus) ?_ hc + intro u hu + rcases List.mem_append.mp hu with hu | hu + · exact hall u hu + · exact hr u hu + | ite c t1 t2 => + rcases Bool.or_eq_true _ _ |>.mp h with h | h + · exact fm_sound σ F cs h hc + rw [Bool.and_eq_true, Bool.and_eq_true] at h + replace h := h.2 + have hres : ∀ (b : Bool), (if b then c.Holds σ else ¬ c.Holds σ) → ∀ u ∈ rest, + (resolve c b resolveFuel u).Holds σ := by + intro b hb u hu + simp only [Tm.Holds] + rw [resolve_eval σ c b hb] + exact hr u hu + rcases hst with ⟨hc1, ht1⟩ | ⟨hc2, ht2⟩ + · refine refute_sound F ks n (b - 1) σ _ cs h.1 ?_ hc + have he := iteEqs_sound σ c hc1 + intro u hu + rcases List.mem_cons.mp hu with rfl | hu + · exact hc1 + obtain ⟨v, hv, rfl⟩ := List.mem_map.mp hu + obtain ⟨w, hw, rfl⟩ := List.mem_map.mp hv + simp only [Tm.Holds] + rw [substN_eval _ _ σ he] + rcases List.mem_cons.mp hw with rfl | hw + · rw [resolve_eval σ c true (by simpa using hc1)] + exact ht1 + · exact hres true (by simpa using hc1) w hw + · refine refute_sound F ks n (b - 1) σ _ cs h.2 ?_ hc + intro u hu + simp only [List.mem_cons, List.map_cons, List.mem_map] at hu + rcases hu with rfl | rfl | ⟨u', hu', rfl⟩ + · exact (holds_neg σ c).mpr hc2 + · simp only [Tm.Holds] + rw [resolve_eval σ c false (by simpa using hc2)] + exact ht2 + · exact hres false (by simpa using hc2) u' hu' + | skolem x u => + have h' : (if fresh x rest cs then refute F ks n b (u :: rest) cs + else if fresh (x ++ "'") (u :: rest) cs then + refute F ks n b (u.subst .int x (.ivar (x ++ "'")) :: rest) cs + else refute F ks n b rest cs) = true := h + by_cases hf : fresh x rest cs + · simp only [hf, ↓reduceIte] at h' + obtain ⟨m, hm⟩ := hst + simp only [fresh, Bool.and_eq_true, List.all_eq_true] at hf + obtain ⟨hf1, hf2⟩ := hf + have hx1 : ∀ v ∈ rest, x ∉ v.vars := fun v hv hxv => by + have := hf1 v hv + simp [hxv] at this + have hx2 : ∀ l ∈ cs, ∀ p ∈ l.cs, x ∉ p.1.vars := fun l hl p hp hxp => by + have := hf2 l hl p hp + simp [hxp] at this + refine refute_sound F ks n b (σ.setI x m) _ cs h' ?_ ?_ + · intro v hv + rcases List.mem_cons.mp hv with rfl | hv + · exact hm + · have := hr v hv + simp only [Tm.Holds] at this ⊢ + rwa [Tm.eval_congr v (σ := σ.setI x m) (τ := σ) rfl (fun y hy => agree_setI_ne (x := x) m (fun e => hx1 v hv (e ▸ hy)))] + · intro l hl + have := hc l hl + simp only [Lin.eval] at this ⊢ + rwa [sumCs_congr (τ := σ.setI x m) (ρ := σ) rfl l.cs (fun p hp y hy => agree_setI_ne (x := x) m (fun e => hx2 l hl p hp (e ▸ hy)))] + · simp only [hf, Bool.false_eq_true, ↓reduceIte] at h' + by_cases hf' : fresh (x ++ "'") (u :: rest) cs + · simp only [hf', ↓reduceIte] at h' + obtain ⟨m, hm⟩ := hst + simp only [fresh, Bool.and_eq_true, List.all_eq_true] at hf' + obtain ⟨hf1, hf2⟩ := hf' + have hx1 : ∀ v ∈ u :: rest, x ++ "'" ∉ v.vars := fun v hv hxv => by + have := hf1 v hv + simp [hxv] at this + have hx2 : ∀ l ∈ cs, ∀ p ∈ l.cs, x ++ "'" ∉ p.1.vars := fun l hl p hp hxp => by + have := hf2 l hl p hp + simp [hxp] at this + refine refute_sound F ks n b (σ.setI (x ++ "'") m) _ cs h' ?_ ?_ + · intro v hv + rcases List.mem_cons.mp hv with hvu | hv + · subst hvu + simp only [Tm.Holds] at hm ⊢ + rw [Tm.eval_subst .int x (.ivar (x ++ "'")) rfl u _ (fun y hy hyx => by + simp only [Tm.vars, List.mem_cons, List.not_mem_nil, or_false] at hyx + subst hyx + exact hx1 u (by simp) (Tm.mem_vars_of_binders u hy))] + have e1 : (Tm.ivar (x ++ "'")).eval (σ.setI (x ++ "'") m) = .int m := by + simp [Tm.eval, Env.setI] + rw [e1] + have e2 : u.eval ((σ.setI (x ++ "'") m).set .int x (.int m)) = u.eval (σ.setI x m) := + Tm.eval_congr u (σ := (σ.setI (x ++ "'") m).set .int x (.int m)) (τ := σ.setI x m) rfl + (fun y hy => by + have hy' : y ≠ x ++ "'" := fun e => hx1 u (by simp) (e ▸ hy) + refine ⟨?_, rfl, rfl, rfl⟩ + simp only [Env.set, Env.setI, Value.toInt] + by_cases hyx : y = x <;> simp [hyx, hy']) + rw [e2] + exact hm + · have := hr v hv + simp only [Tm.Holds] at this ⊢ + rwa [Tm.eval_congr v (σ := σ.setI (x ++ "'") m) (τ := σ) rfl + (fun y hy => agree_setI_ne (x := x ++ "'") m + (fun e => hx1 v (List.mem_cons_of_mem _ hv) (e ▸ hy)))] + · intro l hl + have := hc l hl + simp only [Lin.eval] at this ⊢ + rwa [sumCs_congr (τ := σ.setI (x ++ "'") m) (ρ := σ) rfl l.cs + (fun p hp y hy => agree_setI_ne (x := x ++ "'") m (fun e => hx2 l hl p hp (e ▸ hy)))] + · simp only [hf', Bool.false_eq_true, ↓reduceIte] at h' + exact refute_sound F ks n b σ rest cs h' hr hc + +theorem rowSel_eval {r : Tm → Tm} (hr : ∀ t, (r t).eval σ = t.eval σ) (x j : Tm) : + (rowSel r x j).eval σ = (Tm.app "select" [x, j]).eval σ := by + unfold rowSel + split + · rename_i g a i v + by_cases h1 : g = "store" ∧ i.isIntAtom = true ∧ j.isIntAtom = true ∧ rowSorts a v = true + · rw [if_pos h1] + obtain ⟨rfl, hi, hj, hs⟩ := h1 + obtain ⟨I, eI⟩ : ∃ I, i.eval σ = .int I := ⟨_, int_atom σ hi⟩ + obtain ⟨J, eJ⟩ : ∃ J, j.eval σ = .int J := ⟨_, int_atom σ hj⟩ + simp only [rowSorts, Bool.or_eq_true, Bool.and_eq_true, beq_iff_eq] at hs + rcases hs with ⟨ha, hv⟩ | ⟨ha, hv⟩ + · obtain ⟨V, eV⟩ : ∃ V, v.eval σ = .int V := ⟨_, int_atom σ hv⟩ + obtain ⟨eA', eA⟩ : ∃ X, a.eval σ = .arr X := ⟨_, Value.sortOf_arr (Tm.eval_sortOf a σ ha)⟩ + by_cases hb : Tm.beq j i = true + · rw [if_pos hb] + have := Tm.eq_of_beq hb + subst this + simp only [Tm.eval, Tm.evalList, applyOp, eA, eV, eI, Value.store, Value.select, Value.toInt] + simp + · rw [if_neg hb] + simp only [Tm.eval, Tm.evalList, applyOp, hr, eA, eV, eI, eJ, Value.store, Value.select, + Value.toInt, Value.toProp, Value.eq] + by_cases hJI : J = I <;> simp [hJI] + · obtain ⟨eV', eV⟩ : ∃ X, v.eval σ = .arr X := ⟨_, Value.sortOf_arr (Tm.eval_sortOf v σ hv)⟩ + obtain ⟨eA', eA⟩ : ∃ X, a.eval σ = .arr2 X := ⟨_, Value.sortOf_arr2 (Tm.eval_sortOf a σ ha)⟩ + by_cases hb : Tm.beq j i = true + · rw [if_pos hb] + have := Tm.eq_of_beq hb + subst this + simp only [Tm.eval, Tm.evalList, applyOp, eA, eV, eI, Value.store, Value.select, Value.toInt, + Value.toArr] + simp + · rw [if_neg hb] + simp only [Tm.eval, Tm.evalList, applyOp, hr, eA, eV, eI, eJ, Value.store, Value.select, + Value.toInt, Value.toProp, Value.eq, Value.toArr] + by_cases hJI : J = I <;> simp [hJI] + · rw [if_neg h1] + by_cases h2 : g = "ite" ∧ arrPair i v = true + · rw [if_pos h2] + obtain ⟨rfl, hp⟩ := h2 + simp only [arrPair, Bool.or_eq_true, Bool.and_eq_true, beq_iff_eq] at hp + rcases hp with ⟨hi, hv⟩ | ⟨hi, hv⟩ + · obtain ⟨eI', eI⟩ : ∃ X, i.eval σ = .arr X := ⟨_, Value.sortOf_arr (Tm.eval_sortOf i σ hi)⟩ + obtain ⟨eV', eV⟩ : ∃ X, v.eval σ = .arr X := ⟨_, Value.sortOf_arr (Tm.eval_sortOf v σ hv)⟩ + simp only [Tm.eval, Tm.evalList, applyOp, hr] + rw [eI, eV] + simp only [applyOp, Value.select, Value.toInt] + by_cases hc : (a.eval σ).toProp <;> simp [hc] + · obtain ⟨eI', eI⟩ : ∃ X, i.eval σ = .arr2 X := ⟨_, Value.sortOf_arr2 (Tm.eval_sortOf i σ hi)⟩ + obtain ⟨eV', eV⟩ : ∃ X, v.eval σ = .arr2 X := ⟨_, Value.sortOf_arr2 (Tm.eval_sortOf v σ hv)⟩ + simp only [Tm.eval, Tm.evalList, applyOp, hr] + rw [eI, eV] + simp only [applyOp, Value.select] + by_cases hc : (a.eval σ).toProp <;> simp [hc] + · rw [if_neg h2] + · rename_i g v + by_cases hc : (g = isOpName.constName ∧ v.isIntAtom = true) ∨ + (g = isOpName.const2Name ∧ v.sort? = some .arr) + · rw [if_pos hc] + rcases hc with ⟨rfl, hv⟩ | ⟨rfl, hv⟩ + · obtain ⟨V, eV⟩ : ∃ V, v.eval σ = .int V := ⟨_, int_atom σ hv⟩ + simp only [Tm.eval, Tm.evalList, isOpName.constName, applyOp, eV, Value.select, Value.toInt] + · obtain ⟨eV', eV⟩ : ∃ X, v.eval σ = .arr X := ⟨_, Value.sortOf_arr (Tm.eval_sortOf v σ hv)⟩ + simp only [Tm.eval, Tm.evalList, isOpName.const2Name, applyOp, eV, Value.select, Value.toArr] + · rw [if_neg hc] + · rfl + +theorem rowN_eval : ∀ (n : Nat) (σ : Env) (t : Tm), (rowN n t).eval σ = t.eval σ + | 0, _, _ => rfl + | n + 1, σ, t => by + cases t with + | all x body => + have hb : ∀ m : Int, (rowN n body).eval (σ.setI x m) = body.eval (σ.setI x m) := + fun m => rowN_eval n _ body + simp only [rowN, Tm.eval, hb] + | app f args => + have hargs : (args.map (rowN n)).map (Tm.eval σ) = args.map (Tm.eval σ) := by + rw [List.map_map] + apply List.map_congr_left + intro a _ + exact rowN_eval n σ a + simp only [rowN] + split_ifs with hf + · subst hf + split + · rename_i x j heq + rw [rowSel_eval σ (rowN_eval n σ) x j] + have hsel := congrArg (List.map (Tm.eval σ)) heq + rw [hargs] at hsel + rw [eval_app σ "select" [x, j], eval_app σ "select" args, hsel] + · simp only [eval_app, hargs] + · simp only [eval_app, hargs] + | _ => rfl + +theorem modFacts_holds {t : Tm} {m : Nat} (ht : t.isIntAtom = true) (hm : 0 < m) : + ∀ u ∈ modFacts t m, u.Holds σ := by + obtain ⟨T, eT⟩ : ∃ T, t.eval σ = .int T := ⟨_, int_atom σ ht⟩ + have hm' : (m : Int) ≠ 0 := by exact_mod_cast hm.ne' + have h1 := Int.mul_ediv_add_emod T m + have h2 := Int.emod_nonneg T hm' + have h3 := Int.emod_lt_of_pos T (by exact_mod_cast hm : (0 : Int) < m) + have h4 : ((m - 1 : Nat) : Int) = m - 1 := by omega + intro u hu + simp only [modFacts, List.mem_cons, List.not_mem_nil, or_false] at hu + rcases hu with rfl | rfl | rfl | rfl <;> + simp [Tm.Holds, Tm.eval, Tm.evalList, applyOp, eT, Value.toInt, Value.toProp, Value.eq, hm', h4] + · omega + · omega + · omega + · omega + +theorem divFacts_holds (fs : List Tm) : ∀ u ∈ divFacts fs, u.Holds σ := by + intro u hu + simp only [divFacts, List.mem_flatMap] at hu + obtain ⟨p, -, hu⟩ := hu + split at hu + · rename_i h + exact modFacts_holds σ h.1 h.2 u hu + · simp at hu + +theorem mem_goalFirst {fs : List Tm} {t : Tm} (h : t ∈ goalFirst fs) : t ∈ fs := by + simp only [goalFirst, List.mem_append] at h + rcases h with h | h + · exact List.mem_of_getLast? (by simpa using h) + · exact List.dropLast_subset fs h + +theorem refuteOb_sound {fs : List Tm} (h : refuteOb fs = true) : ∀ σ : Env, ¬ ∀ t ∈ fs, t.Holds σ := by + intro σ hσ + have he : ∀ e ∈ fs.filterMap eqOf?, e.1.eval σ = e.2.eval σ := by + intro e hm + obtain ⟨t, ht, hte⟩ := List.mem_filterMap.mp hm + exact eqOf_sound σ hte (hσ t ht) + have hg : ∀ t ∈ relevant ((fs.filter fun t => (eqOf? t).isNone).map + fun t => rowN rowFuel (substN (fs.filterMap eqOf?) substFuel t)), t.Holds σ := by + intro t ht + simp only [relevant, List.mem_filter] at ht + obtain ⟨t', ht', rfl⟩ := List.mem_map.mp ht.1 + simp only [Tm.Holds] + rw [rowN_eval _ σ, substN_eval _ _ σ he] + exact hσ t' (List.mem_filter.mp ht').1 + simp only [refuteOb, Bool.or_eq_true] at h + rcases h with h | h + · exact refute_sound fmFuel _ stepFuel splitFuel σ _ [] h (fun t ht => hg t (mem_goalFirst ht)) + (by simp) + · refine refute_sound fmFuel _ stepFuel splitFuel σ _ [] h ?_ (by simp) + intro t ht + rcases List.mem_append.mp ht with ht | ht + · exact hg t (mem_goalFirst ht) + · exact divFacts_holds σ _ t ht + +end Sound + +/-- **The discharge is sound**: a script `dischargeScript` accepts is valid, every obligation of +it but the probes having no model. -/ +theorem dischargeScript_sound (cs : List Cmd) (h : dischargeScript cs = true) : Valid cs := by + intro fs hfs hp σ + have := List.all_eq_true.mp h fs hfs + simp only [hp, Bool.false_or] at this + exact refuteOb_sound this σ + +/-- **The discharge, one obligation at a time.** -/ +theorem dischargeScript_of_each (cs : List Cmd) + (h : ∀ i < (obligations cs).length, dischargeAt cs i = true) : Valid cs := by + intro fs hfs hp σ + obtain ⟨i, hi, rfl⟩ := List.getElem_of_mem hfs + have := h i hi + simp only [dischargeAt, List.getD_eq_getElem?_getD, List.getElem?_eq_getElem hi, + Option.getD_some, hp, Bool.false_or] at this + exact refuteOb_sound this σ + +/-- An obligation the discharge rejects makes it reject the script. -/ +theorem dischargeScript_false_of {cs : List Cmd} {i : Nat} (hi : i < (obligations cs).length) + (h : dischargeAt cs i = false) : dischargeScript cs = false := by + simp only [dischargeAt, List.getD_eq_getElem?_getD, List.getElem?_eq_getElem hi, + Option.getD_some] at h + simp only [dischargeScript, List.all_eq_false] + exact ⟨_, List.getElem_mem hi, by simp [h]⟩ + +/-- Whether the obligation at index `i` is vacuous: its hypotheses, without the negated goal, already +have no model, so it holds only because the path it covers is unreachable. A report, never a +verdict: `false` means only that the discharge found no contradiction among the hypotheses. -/ +def vacuousAt (cs : List Cmd) (i : Nat) : Bool := + refuteOb ((obligations cs).getD i []).dropLast + +/-- A vacuous obligation's hypotheses have no model. -/ +theorem vacuousAt_sound {cs : List Cmd} {i : Nat} (h : vacuousAt cs i = true) : + ∀ σ : Env, ¬ ∀ t ∈ ((obligations cs).getD i []).dropLast, t.Holds σ := + refuteOb_sound h + +end SolidCore.Verify.VC diff --git a/Verify/VC/EndToEnd.lean b/Verify/VC/EndToEnd.lean new file mode 100644 index 00000000..d13ac180 --- /dev/null +++ b/Verify/VC/EndToEnd.lean @@ -0,0 +1,69 @@ +import Verify.VC.Obligations +import Verify.VC.Discharge +import SolidCore.Refinement.Compose + +/-! +# From solar-verify's script to the bytecode, in one theorem + +\`bytecode_of_discharged\` composes, for one function the generic source stage erases: + +1. the kernel's discharge of solar-verify's whole script (\`dischargeScript cs = true\`, decided by + \`decide +kernel\`; \`dischargeScript_sound\` gives \`Valid cs\` with no solver verdict); +2. the kernel's check that the script's obligations are the Lean obligations \`obs\` + (\`checkScript cs obs = true\`); +3. the binding of the function's erased tree to \`obs\` (\`Binds\`), which gives SolidCore's triple + (\`triple_of_checked\`); +4. a stage from SolidCore's checked contract to the bytecode on the function's scope + (\`SolarTV.Stage\`, as the certify driver's stages and assembly compose it); + +into the run of the exact bytecode under EthLib: every call of the scope runs to an observable +meeting the function's postcondition. Its hypotheses are exactly those four facts (and the deployment +shape \`DeployedAt\`), each a theorem a contract's certificate proves; none is a verdict. +-/ + +namespace SolidCore.Verify.VC + +open SolidCore.Verify SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Generic +open SolidCore.Solidity + +/-- A total-correctness triple of SolidCore's contract carries to the bytecode through a stage. -/ +theorem bytecode_of_triple {fuel : Nat} {c : TypeCheck.CheckedContract} {code : ByteArray} + {scope : Call → Prop} {post : Call → Observable → Prop} + (stage : SolarTV.Stage (solidCore fuel) ethLib c code scope) + (ht : Triple fuel c scope (fun _ => True) post) : + ∀ call, scope call → ∃ obs, Target.run code call = some obs ∧ post call obs := by + intro call hs + obtain ⟨hsome, hpost⟩ := ht call hs trivial + obtain ⟨obs, hobs⟩ := Option.isSome_iff_exists.mp hsome + exact ⟨obs, stage call hs obs hobs, hpost obs hobs⟩ + +/-- **solar-verify's script, discharged by the kernel, holds of the bytecode.** -/ +theorem bytecode_of_discharged {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {fn : Fn} {f : Source.FunctionDef} + (hsel : fn.sel < 2 ^ 32) (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) fuel f = some T) {cs : List Cmd} {obs : List (List Tm × Tm)} + {env : List Nat → Storage → Env} {P : List Nat → Storage → Observable → Prop} + (hdis : dischargeScript cs = true) (hcheck : checkScript cs obs = true) + (hbind : Binds fn T obs env P) {code : ByteArray} + (stage : SolarTV.Stage (solidCore fuel) ethLib c code (stageScope fn s)) : + ∀ call, stageScope fn s call → ∃ o, Target.run code call = some o ∧ treePost fn P call o := + bytecode_of_triple stage + (triple_of_checked hd hsel hfind hlen hT hcheck (dischargeScript_sound cs hdis) hbind) + +/-- **solar-verify's verdict on a script, its obligations checked, holds of the bytecode.** The +verdict may be any proof of `Valid cs`, such as a generated `Discharged.script_valid`. -/ +theorem bytecode_of_checked {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {fn : Fn} {f : Source.FunctionDef} + (hsel : fn.sel < 2 ^ 32) (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) fuel f = some T) {cs : List Cmd} {obs : List (List Tm × Tm)} + {env : List Nat → Storage → Env} {P : List Nat → Storage → Observable → Prop} + (hv : Valid cs) (hcheck : checkScript cs obs = true) + (hbind : Binds fn T obs env P) {code : ByteArray} + (stage : SolarTV.Stage (solidCore fuel) ethLib c code (stageScope fn s)) : + ∀ call, stageScope fn s call → ∃ o, Target.run code call = some o ∧ treePost fn P call o := + bytecode_of_triple stage (triple_of_checked hd hsel hfind hlen hT hcheck hv hbind) + +end SolidCore.Verify.VC + diff --git a/Verify/VC/KernelIdx.lean b/Verify/VC/KernelIdx.lean new file mode 100644 index 00000000..6dc459db --- /dev/null +++ b/Verify/VC/KernelIdx.lean @@ -0,0 +1,59 @@ +import Std + +/-! +# Hash map buckets the kernel can compute + +`Std.HashMap` picks a key's bucket with `mkIdx`, a `USize` computation. The width of `USize` is +`System.Platform.numBits`, which the kernel cannot reduce, so no lookup or insert, and nothing that +runs the constructor of a contract that writes storage, reduces by conversion alone. `mkIdxK` +computes the same index on `Nat` for every table below `2 ^ 32` buckets, where the mask fits either +platform's word, and falls back to `mkIdx` otherwise. `mkIdx_eq` proves the two equal, so +`kernel_rfl … using mkIdx_eq` evaluates hash maps in the kernel without assuming a platform. +-/ + +namespace SolidCore.Verify.VC + +open Std.DHashMap.Internal + +/-- Either platform's `USize` holds every `Nat` below `2 ^ 32`. -/ +theorem usize_size_ge : 2 ^ 32 ≤ USize.size := by + rcases USize.size_eq with h | h <;> rw [h] <;> decide + +/-- `mkIdx` on `Nat` below `2 ^ 32` buckets, where its mask does not depend on the word width. -/ +def mkIdxK (sz : Nat) (h : 0 < sz) (hash : UInt64) : { u : USize // u.toNat < sz } := + if hs : sz < 2 ^ 32 then + ⟨USize.ofNatLT ((scrambleHash hash).toNat &&& (sz - 1)) + (Nat.lt_of_le_of_lt Nat.and_le_right (by have := usize_size_ge; omega)), + by + show (scrambleHash hash).toNat &&& (sz - 1) < sz + exact Nat.lt_of_le_of_lt Nat.and_le_right (by omega)⟩ + else mkIdx sz h hash + +/-- `mkIdxK` is `mkIdx`, whatever `System.Platform.numBits` is. -/ +theorem mkIdx_eq : @mkIdx = @mkIdxK := by + funext sz h hash + unfold mkIdxK + split + · next hs => + apply Subtype.ext + apply USize.toNat_inj.mp + have hsz := usize_size_ge + unfold mkIdx + simp only [USize.toNat_and, USize.toNat_ofNatLT, UInt64.toNat_toUSize] + rw [USize.toNat_sub_of_le, USize.toNat_ofNat_of_lt' (by omega)] + · simp only [USize.toNat_one] + have hm : sz - 1 < 2 ^ System.Platform.numBits := by + have : USize.size = 2 ^ System.Platform.numBits := rfl + omega + apply Nat.eq_of_testBit_eq + intro i + simp only [Nat.testBit_and, Nat.testBit_mod_two_pow] + by_cases hi : i < System.Platform.numBits + · simp [hi] + · have : sz - 1 < 2 ^ i := + Nat.lt_of_lt_of_le hm (Nat.pow_le_pow_right (by decide) (by omega)) + simp [hi, Nat.testBit_lt_two_pow this] + · simp [USize.le_iff_toNat_le, USize.toNat_ofNat_of_lt' (show sz < USize.size by omega)]; omega + · rfl + +end SolidCore.Verify.VC diff --git a/Verify/VC/Model.lean b/Verify/VC/Model.lean new file mode 100644 index 00000000..68ff2719 --- /dev/null +++ b/Verify/VC/Model.lean @@ -0,0 +1,127 @@ +import Verify.Abi +import SolidCore.Refinement.Generic.SourceRun + +/-! +# The generic source stage's trees as Loom models + +The generic source stage (`SolidCore.Refinement.Generic`) erases a SolidCore function of its +fragment to a `Tree` (`eraseFn`) and proves that SolidCore runs every call of it as the tree +(`source_run`). `treeModel T` reads the tree as a model in `SolM`, the monad of +`SolidCore.Verify`'s Loom generator: it reads the storage, branches where the tree branches, and +ends as the tree's leaf does, writing the leaf's storage and returning its output, or reverting +with it. `implements_tree` is `Implements` for every function the stage erases, proved once from +`source_run`: so Loom's weakest precondition of `treeModel T` (`vc`, computed by `wp_bind`, `wp_ite` +and the rules below) gives a `Triple` against `Source.run` through `triple_of_wp`, with no proof +per contract of how SolidCore runs it. + +The scope is the stage's: every call of the function on any argument words below `2 ^ 256`, with +no value, from any storage that writes every slot the constructor wrote (`Covers`). A model emits +no logs (`observe`), so the tree must have none (`noLogs`). +-/ + +namespace SolidCore.Verify.VC + +open SolidCore.Verify SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Generic +open SolidCore.Solidity + +/-- Read the whole storage. -/ +def getStore : SolM Storage := fun s => .ok (s, s) + +/-- Replace the whole storage. -/ +def setStore (s' : Storage) : SolM Unit := fun _ => .ok ((), s') + +@[simp] theorem wp_getStore (post : Storage → Assn) : + wp getStore post = fun herr s => post s herr s := by + rw [wp_eq]; rfl + +@[simp] theorem wp_setStore (s' : Storage) (post : Unit → Assn) : + wp (setStore s') post = fun herr _ => post () herr s' := by + rw [wp_eq]; rfl + +/-- The words of a call on the argument words `args` from the storage `s`, with SolidCore's slot +hash. -/ +def valOf (args : List Nat) (s : Storage) : Val := ⟨args, s, solHash, SolidCore.Refinement.Generic.callerWord⟩ + +/-- A tree that emits no log. -/ +def noLogs : Tree → Bool + | .halt _ _ _ ls => ls.isEmpty + | .ite _ t e => noLogs t && noLogs e + +/-- The tree as a model: branch on the words of the call, end as the leaf does. -/ +def treeModel : Tree → List Nat → SolM (List Nat) + | .halt ok out ws _, args => do + let s ← getStore + if ok then do + setStore (Writes.store (valOf args s) ws) + pure (out.map (OByte.eval (valOf args s))) + else revert (out.map (OByte.eval (valOf args s))) + | .ite c t e, args => do + let s ← getStore + if c.eval (valOf args s) = 0 then treeModel e args else treeModel t args + +/-- What a tree's result is as a model's outcome. -/ +def resOutcome (R : Res) : Except Revert (List Nat × Storage) := + if R.success then .ok (R.output, R.store) else .error R.output + +theorem treeModel_run (args : List Nat) (s : Storage) : + ∀ T : Tree, treeModel T args s = resOutcome (T.eval (valOf args s)) + | .halt ok out ws ls => by + cases ok <;> rfl + | .ite c t e => by + show (if c.eval (valOf args s) = 0 then treeModel e args else treeModel t args) s = _ + simp only [Tree.eval] + split + · exact treeModel_run args s e + · exact treeModel_run args s t + +theorem eval_logs (ρ : Val) : ∀ T : Tree, noLogs T = true → (T.eval ρ).logs = [] + | .halt ok out ws ls, h => by + simp only [noLogs, List.isEmpty_iff] at h + subst h; cases ok <;> rfl + | .ite c t e, h => by + simp only [noLogs, Bool.and_eq_true] at h + simp only [Tree.eval] + split + · exact eval_logs ρ e h.2 + · exact eval_logs ρ t h.1 + +theorem observe_resOutcome (s : Storage) (R : Res) (hs : R.success = false → R.store = s) + (hl : R.logs = []) : observe s (resOutcome R) = R.obs := by + unfold resOutcome observe Res.obs + cases h : R.success + · simp [hs h, hl] + · simp [hl] + +theorem eval_store_fail (ρ : Val) : ∀ T : Tree, (T.eval ρ).success = false → + (T.eval ρ).store = ρ.store + | .halt ok out ws ls, h => by cases ok <;> simp_all [Tree.eval] + | .ite c t e, h => by + simp only [Tree.eval] at h ⊢ + split at h <;> rename_i hc <;> simp only [hc, ite_true, ite_false] <;> + first | exact eval_store_fail ρ e h | exact eval_store_fail ρ t h + +/-- The stage's scope of one function: every call of it on argument words below `2 ^ 256`, with no +value, from any storage that writes every slot the constructor wrote. -/ +def stageScope (fn : Fn) (s : List (Nat × Nat)) (call : Call) : Prop := + ∃ σ, Covers s σ ∧ fullScope [fn] σ call + +/-- Every function the generic source stage erases is implemented by its tree's model. -/ +theorem implements_tree {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {fn : Fn} {f : Source.FunctionDef} + (hsel : fn.sel < 2 ^ 32) (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) fuel f = some T) (hlogs : noLogs T = true) : + Implements fuel c (stageScope fn s) (argWords fn.params.length) (treeModel T) := by + rintro _ ⟨σ, hcov, fn', hfn', args, hl, hargs, rfl⟩ + simp only [List.mem_singleton] at hfn' + subst hfn' + have hw : argWords fn'.params.length + ({ calldata := Abi.calldata fn'.sel args, callvalue := 0, storage := σ } : Call) = args := + hl ▸ argWords_calldata _ args hargs 0 σ + rw [hw, source_run hd hcov hsel hfind hT args (hl.trans hlen.symm) hargs] + simp only [initStorage] + rw [treeModel_run] + exact congrArg some (observe_resOutcome _ _ (eval_store_fail _ T) + (eval_logs _ T hlogs)).symm + +end SolidCore.Verify.VC diff --git a/Verify/VC/Obligations.lean b/Verify/VC/Obligations.lean new file mode 100644 index 00000000..333416d4 --- /dev/null +++ b/Verify/VC/Obligations.lean @@ -0,0 +1,92 @@ +import Verify.VC.Model +import Verify.VC.Check + +/-! +# From an erased function to solar-verify's obligations, once for every function + +The generic source stage erases a function of its fragment to a `Tree` (`eraseFn`), and +`source_run` proves that SolidCore runs every call of it as the tree. solar-verify's verdict on a +script is `Valid`, and `checkScript` ties the script's obligations to Lean obligations +(`checkScript_sound`). What is left per function is the binding: the Lean obligations, at the +assignment of solar-verify's names a call binds, say what the tree's result is. + +* `ObsAt obs σ`: every Lean obligation of `obs` holds at the assignment `σ`. +* `Binds fn T obs env P`: on every call's argument words `args` (as many as `fn` takes, each + below `2 ^ 256`) and every storage `s` of words, the obligations at `env args s` give `P args s` + of the tree's observable. This is the one proof a function needs, and it is about the tree and + the obligations alone: no SolidCore run, no fuel, no ABI. +* `triple_of_binds`: for every function the stage erases, its obligations' validity and the + binding give the triple `{True} c {treePost fn P}` against SolidCore on the stage's scope + (`stageScope`). Unlike `implements_tree`, the tree may emit logs: the observable is the tree's, + logs included. +* `triple_of_checked`: the same from solar-verify's script, its verdict `Valid cs` and the + kernel's `checkScript cs obs = true`. + +A verdict is a hypothesis (`Valid cs`): solar-verify's solver is not trusted, so the theorem says +what holds if its verdict is right, and `checkScript` makes sure the verdict is about the +obligations the binding uses. An obligation that is valid by solar-verify's own encoding needs no +verdict: `triple_of_binds` takes `ObsValid obs` proved in Lean. +-/ + +namespace SolidCore.Verify.VC + +open SolidCore.Verify SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Generic +open SolidCore.Solidity + +/-- Every Lean obligation of `obs` holds at the assignment `σ`. -/ +def ObsAt (obs : List (List Tm × Tm)) (σ : Env) : Prop := + ∀ o ∈ obs, (∀ x ∈ o.1, x.Holds σ) → o.2.Holds σ + +theorem ObsValid.at {obs : List (List Tm × Tm)} (h : ObsValid obs) (σ : Env) : ObsAt obs σ := + fun o ho hh => h o ho σ hh + +/-- The binding of a function's tree to Lean obligations: on every call's argument words and +storage of words, the obligations at the assignment `env args s` give `P` of the tree's +observable. -/ +def Binds (fn : Fn) (T : Tree) (obs : List (List Tm × Tm)) (env : List Nat → Storage → Env) + (P : List Nat → Storage → Observable → Prop) : Prop := + ∀ (args : List Nat) (s : Storage), args.length = fn.params.length → (∀ a ∈ args, a < 2 ^ 256) → + (∀ k, s k < 2 ^ 256) → ObsAt obs (env args s) → P args s (T.eval (valOf args s)).obs + +/-- `P` of a call: of its argument words, its initial storage and its observable. -/ +def treePost (fn : Fn) (P : List Nat → Storage → Observable → Prop) (call : Call) + (o : Observable) : Prop := + P (argWords fn.params.length call) (initStorage call) o + +/-- **Every function the generic source stage erases meets the triple its binding gives**, from +valid Lean obligations. -/ +theorem triple_of_binds {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {fn : Fn} {f : Source.FunctionDef} + (hsel : fn.sel < 2 ^ 32) (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) fuel f = some T) {obs : List (List Tm × Tm)} + {env : List Nat → Storage → Env} {P : List Nat → Storage → Observable → Prop} + (hobs : ObsValid obs) (hbind : Binds fn T obs env P) : + Triple fuel c (stageScope fn s) (fun _ => True) (treePost fn P) := by + rintro _ ⟨σ, hcov, fn', hfn', args, hl, hargs, rfl⟩ - + simp only [List.mem_singleton] at hfn' + subst hfn' + have hrun := source_run hd hcov hsel hfind hT args (hl.trans hlen.symm) hargs + refine ⟨by simp [hrun], fun o ho => ?_⟩ + rw [hrun] at ho + cases ho + have hw : argWords fn'.params.length + ({ calldata := Abi.calldata fn'.sel args, callvalue := 0, storage := σ } : Call) = args := + hl ▸ argWords_calldata _ args hargs 0 σ + unfold treePost + rw [hw] + exact hbind args (slotValue σ) hl hargs (fun k => Generic.slotValue_lt σ k) (hobs.at _) + +/-- **The same from solar-verify's script**: its verdict and the kernel's check that its +obligations are the Lean ones. -/ +theorem triple_of_checked {fuel : Nat} {c : TypeCheck.CheckedContract} {d : Source.State} + {s : List (Nat × Nat)} (hd : Wide.DeployedAt fuel c d s) {fn : Fn} {f : Source.FunctionDef} + (hsel : fn.sel < 2 ^ 32) (hfind : c.core.findFunctionBySelector? fn.sel = some f) + (hlen : f.params.length = fn.params.length) {T : Tree} + (hT : eraseFn (envOf c.core) fuel f = some T) {cs : List Cmd} {obs : List (List Tm × Tm)} + {env : List Nat → Storage → Env} {P : List Nat → Storage → Observable → Prop} + (hcheck : checkScript cs obs = true) (hv : Valid cs) (hbind : Binds fn T obs env P) : + Triple fuel c (stageScope fn s) (fun _ => True) (treePost fn P) := + triple_of_binds hd hsel hfind hlen hT (checkScript_sound hcheck hv) hbind + +end SolidCore.Verify.VC diff --git a/Verify/VC/ScriptBinds.lean b/Verify/VC/ScriptBinds.lean new file mode 100644 index 00000000..c3a9f5a4 --- /dev/null +++ b/Verify/VC/ScriptBinds.lean @@ -0,0 +1,45 @@ +import Verify.VC.Discharge +import Verify.Spec.Contract + +/-! +# Binding solar-verify's script to a stage's semantics + +\`ScriptBinds script S p scope b ctxOf step\`: the kernel's check \`checkScript\` finds, among the +obligations of solar-verify's script \`script\`, Lean obligations \`obs\` whose validity gives the +spec \`b\` of the program \`p\` in the semantics \`S\` on \`scope\` (\`SolidCore.Spec.Holds\`). The +implication is where a contract's binding lives: per function, \`triple_of_binds\` +(Verify/VC/Obligations.lean) turns a function's erased tree and its obligations into SolidCore's +triple, and the stages carry it to the bytecode (\`Holds.of_stage\`). + +* \`holds_of_valid_script\`: a binding and solar-verify's verdict \`Valid script\` give the spec. +* \`holds_of_discharged\`: a binding and the kernel's \`dischargeScript script = true\` give the spec + with no verdict (\`dischargeScript_sound\`, Verify/VC/Discharge.lean). +-/ + +namespace SolidCore.Verify.VC + +open SolidCore.Spec + +/-- solar-verify's script \`script\` binds the spec \`b\` of \`p\` in \`S\`: some Lean obligations the +kernel finds in the script give it when they are valid. -/ +def ScriptBinds (script : List Cmd) (S : SolarTV.Sem) (p : S.Prog) (scope : SolarTV.Call → Prop) + (b : Bundle) (ctxOf : SolarTV.Call → Ctx) (step : GhostStep) : Prop := + ∃ obs : List (List Tm × Tm), checkScript script obs = true ∧ + (ObsValid obs → Holds S p scope b ctxOf step) + +/-- **A bound script's verdict gives the spec.** -/ +theorem holds_of_valid_script {S : SolarTV.Sem} {p : S.Prog} {scope : SolarTV.Call → Prop} + {b : Bundle} {ctxOf : SolarTV.Call → Ctx} {step : GhostStep} + (script : List Cmd) (bind : ScriptBinds script S p scope b ctxOf step) + (valid : Valid script) : Holds S p scope b ctxOf step := by + obtain ⟨obs, hcheck, himp⟩ := bind + exact himp (checkScript_sound hcheck valid) + +/-- **A bound script the kernel discharges gives the spec**, with no solver verdict. -/ +theorem holds_of_discharged {S : SolarTV.Sem} {p : S.Prog} {scope : SolarTV.Call → Prop} + {b : Bundle} {ctxOf : SolarTV.Call → Ctx} {step : GhostStep} + (script : List Cmd) (bind : ScriptBinds script S p scope b ctxOf step) + (h : dischargeScript script = true) : Holds S p scope b ctxOf step := + holds_of_valid_script script bind (dischargeScript_sound script h) + +end SolidCore.Verify.VC diff --git a/Verify/VC/Term.lean b/Verify/VC/Term.lean new file mode 100644 index 00000000..5941d22e --- /dev/null +++ b/Verify/VC/Term.lean @@ -0,0 +1,386 @@ +/-! +# SMT-LIB terms of solar-verify's verification conditions + +solar-verify proves a function by sending SMT-LIB to a solver: constants with their sorts, the +facts it assumes, and for each obligation a `check-sat` of the guard of the paths that return +normally and the negation of what they must show. `Tm` is the fragment of SMT-LIB terms it emits +over integers, booleans and arrays from integers to integers, and `Cmd` its commands. Every +constant carries its sort (`Tm.ivar`, `Tm.bvar`, `Tm.avar`), as its `declare-const` gives it, +so an assignment of the constants (`Env`) is well sorted by construction. + +`Tm.eval` is the meaning SMT-LIB gives the theory of integers with arrays, with one model of what +SMT-LIB leaves open: `div` and `mod` by zero are 0. An obligation that holds in every model holds in +this one. A term the fragment does not cover (a wrong arity or sort) means the default value of its +sort: the checks of `Check` compare terms by their syntax, so such a term can +only make a check fail. + +`Tm.print` prints a term as solar-verify does, so that a script's print can be compared with the +bytes solar-verify sent the solver. +-/ + +namespace SolidCore.Verify.VC + +/-- The sorts of the fragment. -/ +inductive Srt where + | int | bool | arr + /-- `(Array Int (Array Int Int))`. -/ + | arr2 + deriving DecidableEq, Repr + +/-- A term. Numerals are naturals; a negative integer is `(- n)`. -/ +inductive Tm where + | num (n : Nat) + | tt + | ff + | ivar (x : String) + | bvar (x : String) + | avar (x : String) + /-- A constant of sort `(Array Int (Array Int Int))`. -/ + | a2var (x : String) + | app (f : String) (args : List Tm) + /-- `(forall ((x Int)) body)`. -/ + | all (x : String) (body : Tm) + deriving Repr, Inhabited + +/-! ## Equality of terms, by structural recursion (the kernel evaluates it) -/ + +mutual +def Tm.beq : Tm → Tm → Bool + | .num a, .num b => a == b + | .tt, .tt => true + | .ff, .ff => true + | .ivar a, .ivar b => a == b + | .bvar a, .bvar b => a == b + | .avar a, .avar b => a == b + | .a2var a, .a2var b => a == b + | .app f as, .app g bs => f == g && Tm.beqList as bs + | .all x a, .all y b => x == y && Tm.beq a b + | _, _ => false +def Tm.beqList : List Tm → List Tm → Bool + | [], [] => true + | a :: as, b :: bs => Tm.beq a b && Tm.beqList as bs + | _, _ => false +end + +mutual +theorem Tm.eq_of_beq : ∀ {a b : Tm}, Tm.beq a b = true → a = b + | .num a, .num b, h => by simp [Tm.beq] at h; rw [h] + | .tt, .tt, _ => rfl + | .ff, .ff, _ => rfl + | .ivar a, .ivar b, h => by simp [Tm.beq] at h; rw [h] + | .bvar a, .bvar b, h => by simp [Tm.beq] at h; rw [h] + | .avar a, .avar b, h => by simp [Tm.beq] at h; rw [h] + | .a2var a, .a2var b, h => by simp [Tm.beq] at h; rw [h] + | .app f as, .app g bs, h => by + simp only [Tm.beq, Bool.and_eq_true, beq_iff_eq] at h + rw [h.1, Tm.eq_of_beqList h.2] + | .all x a, .all y b, h => by + simp only [Tm.beq, Bool.and_eq_true, beq_iff_eq] at h + rw [h.1, Tm.eq_of_beq h.2] + | .num _, .tt, h | .num _, .ff, h | .num _, .ivar _, h | .num _, .bvar _, h | .num _, .avar _, h | .num _, .a2var _, h | .num _, .app _ _, h | .num _, .all _ _, h => by simp [Tm.beq] at h + | .tt, .num _, h | .tt, .ff, h | .tt, .ivar _, h | .tt, .bvar _, h | .tt, .avar _, h | .tt, .a2var _, h | .tt, .app _ _, h | .tt, .all _ _, h => by simp [Tm.beq] at h + | .ff, .num _, h | .ff, .tt, h | .ff, .ivar _, h | .ff, .bvar _, h | .ff, .avar _, h | .ff, .a2var _, h | .ff, .app _ _, h | .ff, .all _ _, h => by simp [Tm.beq] at h + | .ivar _, .num _, h | .ivar _, .tt, h | .ivar _, .ff, h | .ivar _, .bvar _, h | .ivar _, .avar _, h | .ivar _, .a2var _, h | .ivar _, .app _ _, h | .ivar _, .all _ _, h => by simp [Tm.beq] at h + | .bvar _, .num _, h | .bvar _, .tt, h | .bvar _, .ff, h | .bvar _, .ivar _, h | .bvar _, .avar _, h | .bvar _, .a2var _, h | .bvar _, .app _ _, h | .bvar _, .all _ _, h => by simp [Tm.beq] at h + | .avar _, .num _, h | .avar _, .tt, h | .avar _, .ff, h | .avar _, .ivar _, h | .avar _, .bvar _, h | .avar _, .a2var _, h | .avar _, .app _ _, h | .avar _, .all _ _, h => by simp [Tm.beq] at h + | .a2var _, .num _, h | .a2var _, .tt, h | .a2var _, .ff, h | .a2var _, .ivar _, h | .a2var _, .bvar _, h | .a2var _, .avar _, h | .a2var _, .app _ _, h | .a2var _, .all _ _, h => by simp [Tm.beq] at h + | .app _ _, .num _, h | .app _ _, .tt, h | .app _ _, .ff, h | .app _ _, .ivar _, h | .app _ _, .bvar _, h | .app _ _, .avar _, h | .app _ _, .a2var _, h | .app _ _, .all _ _, h => by simp [Tm.beq] at h + | .all _ _, .num _, h | .all _ _, .tt, h | .all _ _, .ff, h | .all _ _, .ivar _, h | .all _ _, .bvar _, h | .all _ _, .avar _, h | .all _ _, .a2var _, h | .all _ _, .app _ _, h => by simp [Tm.beq] at h +theorem Tm.eq_of_beqList : ∀ {as bs : List Tm}, Tm.beqList as bs = true → as = bs + | [], [], _ => rfl + | a :: as, b :: bs, h => by + simp only [Tm.beqList, Bool.and_eq_true] at h + rw [Tm.eq_of_beq h.1, Tm.eq_of_beqList h.2] + | [], _ :: _, h | _ :: _, [], h => by simp [Tm.beqList] at h +end + +instance : BEq Tm := ⟨Tm.beq⟩ + +/-! ## Values and assignments -/ + +/-- A value of one of the sorts. A boolean is a proposition: a quantifier's value need not be +decidable. -/ +inductive Value where + | int (n : Int) + | prop (p : Prop) + | arr (f : Int → Int) + | arr2 (f : Int → Int → Int) + +def Value.toInt : Value → Int + | .int n => n + | _ => 0 + +def Value.toProp : Value → Prop + | .prop p => p + | _ => False + +def Value.toArr : Value → (Int → Int) + | .arr f => f + | _ => fun _ => 0 + +def Value.toArr2 : Value → (Int → Int → Int) + | .arr2 f => f + | _ => fun _ _ => 0 + +/-- `(select a i)`: an integer of an array, or an array of a mapping of mappings. -/ +def Value.select : Value → Int → Value + | .arr2 f, i => .arr (f i) + | .arr f, i => .int (f i) + | .int _, _ => .int 0 + | .prop _, _ => .int 0 + +/-- `(store a i v)`. -/ +def Value.store : Value → Int → Value → Value + | .arr2 f, i, v => .arr2 (fun j => if j = i then v.toArr else f j) + | .arr f, i, v => .arr (fun j => if j = i then v.toInt else f j) + | .int _, i, v => .arr (fun j => if j = i then v.toInt else 0) + | .prop _, i, v => .arr (fun j => if j = i then v.toInt else 0) + +/-- The integer a `select` reads is the array's entry, for every value: a mapping of mappings and a +non-array read as 0 on both sides. -/ +theorem Value.toInt_select (v : Value) (i : Int) : (v.select i).toInt = v.toArr i := by + cases v <;> rfl + +/-- Whether a value has a sort. -/ +def Value.Sorted : Value → Srt → Prop + | .int _, .int => True + | .prop _, .bool => True + | .arr _, .arr => True + | .arr2 _, .arr2 => True + | _, _ => False + +/-- An assignment of the constants and bound variables, one function per sort, and of the +uninterpreted functions (`u`), from the integers of their arguments. -/ +structure Env where + i : String → Int + b : String → Prop + a : String → (Int → Int) + a2 : String → (Int → Int → Int) := fun _ _ _ => 0 + u : String → List Int → Int := fun _ _ => 0 + +def Env.setI (σ : Env) (x : String) (n : Int) : Env := + { σ with i := fun y => if y = x then n else σ.i y } +def Env.setB (σ : Env) (x : String) (p : Prop) : Env := + { σ with b := fun y => if y = x then p else σ.b y } +def Env.setA (σ : Env) (x : String) (f : Int → Int) : Env := + { σ with a := fun y => if y = x then f else σ.a y } +def Env.setA2 (σ : Env) (x : String) (f : Int → Int → Int) : Env := + { σ with a2 := fun y => if y = x then f else σ.a2 y } + +open Classical in +/-- Equality of two values of one sort. -/ +noncomputable def Value.eq : Value → Value → Prop + | .int a, .int b => a = b + | .prop a, .prop b => (a ↔ b) + | .arr a, .arr b => a = b + | .arr2 a, .arr2 b => a = b + | _, _ => False + +/-- The operators of the fragment; every other name applied is an uninterpreted function. -/ +def isOpName (f : String) : Bool := + f == "+" || f == "-" || f == "*" || f == "div" || f == "mod" || f == "<=" || f == "<" || + f == ">=" || f == ">" || f == "=" || f == "not" || f == "=>" || f == "and" || f == "or" || + f == "ite" || f == "select" || f == "store" || f == constName || f == const2Name +where + constName := "(as const (Array Int Int))" + const2Name := "(as const (Array Int (Array Int Int)))" + +open Classical in +/-- The meaning of an operator applied to the values of its arguments; `u` interprets the +uninterpreted functions. -/ +noncomputable def applyOp (u : String → List Int → Int) : String → List Value → Value + | "+", [a, b] => .int (a.toInt + b.toInt) + | "+", as => .int (as.map Value.toInt).sum + | "-", [a] => .int (-a.toInt) + | "-", [a, b] => .int (a.toInt - b.toInt) + | "*", [a, b] => .int (a.toInt * b.toInt) + | "div", [a, b] => .int (if b.toInt = 0 then 0 else a.toInt / b.toInt) + | "mod", [a, b] => .int (if b.toInt = 0 then 0 else a.toInt % b.toInt) + | "<=", [a, b] => .prop (a.toInt ≤ b.toInt) + | "<", [a, b] => .prop (a.toInt < b.toInt) + | ">=", [a, b] => .prop (a.toInt ≥ b.toInt) + | ">", [a, b] => .prop (a.toInt > b.toInt) + | "=", [a, b] => .prop (a.eq b) + | "not", [a] => .prop (¬ a.toProp) + | "=>", [a, b] => .prop (a.toProp → b.toProp) + | "and", as => .prop (∀ v ∈ as, v.toProp) + | "or", as => .prop (∃ v ∈ as, v.toProp) + | "ite", [c, .int a, .int b] => .int (if c.toProp then a else b) + | "ite", [c, .prop a, .prop b] => .prop (if c.toProp then a else b) + | "ite", [c, .arr a, .arr b] => .arr (if c.toProp then a else b) + | "ite", [c, .arr2 a, .arr2 b] => .arr2 (if c.toProp then a else b) + | "select", [a, i] => a.select i.toInt + | "store", [a, i, v] => a.store i.toInt v + | "(as const (Array Int Int))", [v] => .arr (fun _ => v.toInt) + | "(as const (Array Int (Array Int Int)))", [v] => .arr2 (fun _ => v.toArr) + | f, vs => .int (if isOpName f then 0 else u f (vs.map Value.toInt)) + +mutual +noncomputable def Tm.eval (σ : Env) : Tm → Value + | .num n => .int n + | .tt => .prop True + | .ff => .prop False + | .ivar x => .int (σ.i x) + | .bvar x => .prop (σ.b x) + | .avar x => .arr (σ.a x) + | .a2var x => .arr2 (σ.a2 x) + | .app f args => applyOp σ.u f (Tm.evalList σ args) + | .all x body => .prop (∀ n : Int, (Tm.eval (σ.setI x n) body).toProp) +noncomputable def Tm.evalList (σ : Env) : List Tm → List Value + | [] => [] + | t :: ts => Tm.eval σ t :: Tm.evalList σ ts +end + +theorem Tm.evalList_eq (σ : Env) : ∀ ts : List Tm, Tm.evalList σ ts = ts.map (Tm.eval σ) + | [] => rfl + | t :: ts => by rw [Tm.evalList, Tm.evalList_eq σ ts]; rfl + +/-- A term holds. -/ +def Tm.Holds (σ : Env) (t : Tm) : Prop := (t.eval σ).toProp + +/-! ## Sorts of terms -/ + +/-- The sort of a term, when the fragment gives it one. -/ +def sortOp : String → List (Option Srt) → Option Srt + | "+", [some .int, some .int] => some .int + | "-", [some .int] => some .int + | "-", [some .int, some .int] => some .int + | "*", [some .int, some .int] => some .int + | "div", [some .int, some .int] => some .int + | "mod", [some .int, some .int] => some .int + | "<=", [some .int, some .int] => some .bool + | "<", [some .int, some .int] => some .bool + | ">=", [some .int, some .int] => some .bool + | ">", [some .int, some .int] => some .bool + | "=", [some a, some b] => if a = b then some .bool else none + | "not", [some .bool] => some .bool + | "=>", [some .bool, some .bool] => some .bool + | "and", ss => if ss.all (· == some .bool) then some .bool else none + | "or", ss => if ss.all (· == some .bool) then some .bool else none + | "ite", [some .bool, some a, some b] => if a = b then some a else none + | "select", [some .arr, some .int] => some .int + | "store", [some .arr, some .int, some .int] => some .arr + | "select", [some .arr2, some .int] => some .arr + | "store", [some .arr2, some .int, some .arr] => some .arr2 + | "(as const (Array Int Int))", [some .int] => some .arr + | "(as const (Array Int (Array Int Int)))", [some .arr] => some .arr2 + | f, ss => if isOpName f = false ∧ ss ≠ [] then some .int else none + +mutual +def Tm.sort? : Tm → Option Srt + | .num _ => some .int + | .tt => some .bool + | .ff => some .bool + | .ivar _ => some .int + | .bvar _ => some .bool + | .avar _ => some .arr + | .a2var _ => some .arr2 + | .app f args => sortOp f (Tm.sortList args) + | .all _ body => if Tm.sort? body = some .bool then some .bool else none +def Tm.sortList : List Tm → List (Option Srt) + | [] => [] + | t :: ts => Tm.sort? t :: Tm.sortList ts +end + +/-! ## Printing, as solar-verify prints SMT-LIB -/ + +mutual +def Tm.print : Tm → String + | .num n => toString n + | .tt => "true" + | .ff => "false" + | .ivar x => "|" ++ x ++ "|" + | .bvar x => "|" ++ x ++ "|" + | .avar x => "|" ++ x ++ "|" + | .a2var x => "|" ++ x ++ "|" + | .app f args => "(" ++ f ++ Tm.printArgs args ++ ")" + | .all x body => "(forall ((|" ++ x ++ "| Int)" ++ Tm.printBody body +def Tm.printArgs : List Tm → String + | [] => "" + | t :: ts => " " ++ Tm.print t ++ Tm.printArgs ts +/-- The rest of a quantifier's print: directly nested quantifiers print as one with several +binders, as solar-verify writes `(forall ((x Int) (y Int)) body)`. -/ +def Tm.printBody : Tm → String + | .all y body => " (|" ++ y ++ "| Int)" ++ Tm.printBody body + | .app f args => ") (" ++ f ++ Tm.printArgs args ++ "))" + | t => ") " ++ Tm.printLeaf t ++ ")" +/-- A term without subterms. -/ +def Tm.printLeaf : Tm → String + | .num n => toString n + | .tt => "true" + | .ff => "false" + | .ivar x | .bvar x | .avar x | .a2var x => "|" ++ x ++ "|" + | _ => "" +end + +def Srt.print : Srt → String + | .int => "Int" + | .bool => "Bool" + | .arr => "(Array Int Int)" + | .arr2 => "(Array Int (Array Int Int))" + +/-! ## Scripts -/ + +/-- A command of a script. `raw` is a line the checks do not read (a comment, `(push 1)` around a +function); `elem x lo hi` is solar-verify's `;@elem` hint that the elements of the array `x` lie +in `[lo, hi]`, which the checks do not take as a fact. -/ +inductive Cmd where + | decl (x : String) (s : Srt) + | assert (t : Tm) + | push + | pop + | checkSat + | elem (x : String) (lo hi : Nat) + /-- `(declare-fun f (Int … Int) Int)`, with `n` arguments. -/ + | declFun (f : String) (n : Nat) + | raw (line : String) + deriving Repr, Inhabited + +def Cmd.print : Cmd → String + | .decl x s => "(declare-const |" ++ x ++ "| " ++ s.print ++ ")" + | .assert t => "(assert " ++ t.print ++ ")" + | .push => "(push 1)" + | .pop => "(pop 1)" + | .checkSat => "(check-sat)" + | .elem x lo hi => ";@elem |" ++ x ++ "| " ++ toString lo ++ " " ++ toString hi + | .declFun f n => "(declare-fun " ++ f ++ " (" ++ " ".intercalate (List.replicate n "Int") ++ ") Int)" + | .raw l => l + +/-- A script's print: one command per line, each line ending in a newline. -/ +def printScript (cs : List Cmd) : String := + String.join (cs.map fun c => c.print ++ "\n") + +/-! ## Obligations + +At each `check-sat` the solver is asked whether the facts asserted so far, in every open `push`, +have a model. solar-verify asks it of the obligations it owes, which hold when there is none, and +of one probe per function, `(assert (not false))` after the guard, which asks whether some path +returns at all and owes nothing. -/ + +/-- The facts asserted when the commands `cs` have run from the stack `stk` (innermost frame +first), and at each `check-sat` the facts it reads, in order. -/ +def obligationsFrom : List (List Tm) → List Cmd → List (List Tm) + | _, [] => [] + | stk, .assert t :: cs => + match stk with + | [] => obligationsFrom [[t]] cs + | f :: rest => obligationsFrom ((t :: f) :: rest) cs + | stk, .push :: cs => obligationsFrom ([] :: stk) cs + | stk, .pop :: cs => obligationsFrom (stk.drop 1) cs + | stk, .checkSat :: cs => stk.flatten.reverse :: obligationsFrom stk cs + | stk, _ :: cs => obligationsFrom stk cs + +/-- The facts each `check-sat` of a script reads, oldest first. -/ +def obligations (cs : List Cmd) : List (List Tm) := obligationsFrom [[]] cs + +/-- A `check-sat` that only probes whether a path returns: its last fact is `(not false)`. -/ +def isProbe (fs : List Tm) : Bool := + match fs.getLast? with + | some (.app "not" [.ff]) => true + | _ => false + +/-- What solar-verify's verdict claims of a script: every obligation's facts have no model. -/ +def Valid (cs : List Cmd) : Prop := + ∀ fs ∈ obligations cs, isProbe fs = false → ∀ σ : Env, ¬ ∀ t ∈ fs, t.Holds σ + +end SolidCore.Verify.VC diff --git a/Verify/W1.lean b/Verify/W1.lean new file mode 100644 index 00000000..e9a27566 --- /dev/null +++ b/Verify/W1.lean @@ -0,0 +1,98 @@ +import Verify.Tactic +import SolidCore.Refinement.Corpus.W1 + +/-! +# w1: `f(uint256 x)` returns `x + 1`, or panics on overflow + +The specification of `Main.f` in `scripts/refinement/corpus/w1.sol`, proved against SolidCore +with the Loom VC generator of `Verify.Basic`: on every call of `f` with any argument word +`x < 2 ^ 256`, from the deployed (empty) storage, the call returns the word `x + 1` when it +fits in 256 bits and otherwise reverts with `Panic(0x11)`; storage stays empty. + +`model` is the function as a `SolM` program; `implements` ties it to SolidCore by symbolic +evaluation of the interpreter (`wide_symex`), and `spec` follows from Loom's weakest +precondition of the model, which `simp` computes and `omega` discharges. +-/ + +namespace SolidCore.Verify.W1 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement.Corpus.W1 + +/-- `f` as a Loom program over the storage. -/ +def model (ws : List Nat) : SolM (List Nat) := + if ws.getD 0 0 + 1 < 2 ^ 256 then pure (word (ws.getD 0 0 + 1)) else revert (panic 0x11) + +/-- The calls of the specification: `f` on any word, from the deployed storage. -/ +def scope : Call → Prop := fullScope fns [] + +/-- No precondition beyond the scope. -/ +def pre : Call → Prop := fun _ => True + +/-- `f(x)` returns `x + 1` when it fits, else reverts with `Panic(0x11)`, and leaves +storage empty. -/ +def post (call : Call) (obs : Observable) : Prop := + let x := (argWords 1 call).getD 0 0 + (if x + 1 < 2 ^ 256 then obs.success = true ∧ obs.output = word (x + 1) + else obs.success = false ∧ obs.output = panic 0x11) ∧ + obs.logs = [] ∧ ∀ slot, obs.storage slot = 0 + +end SolidCore.Verify.W1 + + +namespace SolidCore.Verify.W1 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement.Corpus.W1 + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs `f` on any argument word as `model` does. -/ +theorem run_f {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) (w : U256) : + Source.run fuel c (callOf Bytecode.W1.Main.fSelector [w]) = + some (Verify.observe (fun _ => 0) (model [w.toNat] (fun _ => 0))) := by + rw [run_eq hd] + have hs := hd.storage + have hev := hd.events + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.W1.Main.fSelector] + all_goals + have hw := w.isLt + simp only [model, List.getD_cons_zero] + split + all_goals try omega + all_goals + try rw [Nat.mod_eq_of_lt (by omega)] + simp [Source.observe, Verify.observe, revert, pure, StateT.pure, Except.pure, panic, word, + State.logEntries, State.loadSlot, StorageMap.lookup?, getElem?_of_isEmpty hs, + slotValue, callOf] + +/-- `model` implements SolidCore's `Main` on every call of the scope. -/ +theorem implements {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) : Implements fuel c scope (argWords 1) model := + implements_of_run' (by simp [fns]) fun fn hfn ws hl => by + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w, _ | _⟩ <;> simp at hl + exact run_f hcore hd w + +/-- The verification conditions of `f`, by Loom's weakest preconditions. -/ +theorem vcs : ∀ call, scope call → pre call → vc model (argWords 1) post call := by + sc_vcgen [scope, fns, model, post] + +/-- **The specification of `w1`'s `f`**, as a triple against SolidCore. -/ +theorem spec : ∃ c, contract? = .ok c ∧ Triple fuel c scope pre post := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + exact ⟨c, hc, triple_of_wp (implements hk hd) vcs⟩ + +/-- The specification of `w1`'s `f` as `Satisfies` on SolidCore. -/ +theorem satisfies : ∃ c, contract? = .ok c ∧ Satisfies (solidCore fuel) c scope pre post := by + obtain ⟨c, hc, h⟩ := spec + exact ⟨c, hc, satisfies_of_triple h⟩ + +end SolidCore.Verify.W1 diff --git a/Verify/W4.lean b/Verify/W4.lean new file mode 100644 index 00000000..e35de352 --- /dev/null +++ b/Verify/W4.lean @@ -0,0 +1,173 @@ +import Verify.Tactic +import SolidCore.Refinement.Corpus.W4 + +/-! +# w4: `set(uint256 v)` stores `v` in slot 0 + +The specification of `Main.set` in `scripts/refinement/corpus/w4.sol`, proved against +SolidCore with the Loom VC generator of `Verify.Basic`: on every call of `set` with any +argument word `v < 2 ^ 256`, from the deployed (empty) storage, the call succeeds with empty +output and no logs, and afterwards slot 0 holds `v` and every other slot 0. + +`model` is the function as a `SolM` program (one `sstore`); `implements` ties it to +SolidCore by symbolic evaluation of the interpreter (`wide_symex`), and `spec` follows +from Loom's weakest precondition of the model. + +`specAt` widens it to any initial storage: on every call of `set` with no value from any +storage `σ` (`scopeAt`), slot 0 ends holding `v` and every other slot of `σ` is kept +(`postAt`). +-/ + +namespace SolidCore.Verify.W4 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement.Corpus.W4 + +/-- `set` as a Loom program over the storage. -/ +def model (ws : List Nat) : SolM (List Nat) := do + sstore 0 (ws.getD 0 0) + pure [] + +/-- The calls of the specification: `set` on any word, from the deployed storage. -/ +def scope : Call → Prop := fullScope fns [] + +/-- No precondition beyond the scope. -/ +def pre : Call → Prop := fun _ => True + +/-- `set(v)` succeeds with no output and no logs, and leaves `v` in slot 0 and 0 elsewhere. -/ +def post (call : Call) (obs : Observable) : Prop := + let v := (argWords 1 call).getD 0 0 + obs.success = true ∧ obs.output = [] ∧ obs.logs = [] ∧ + ∀ slot, obs.storage slot = if slot % 2 ^ 256 = 0 then v else 0 + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs `set` on any argument word as `model` does. -/ +theorem run_set {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) (w : U256) : + Source.run fuel c (callOf Bytecode.W4.Main.setSelector [w]) = + some (Verify.observe (fun _ => 0) (model [w.toNat] (fun _ => 0))) := by + rw [run_eq hd] + have hs := hd.storage + have hev := hd.events + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.W4.Main.setSelector] + have hw := w.isLt + simp only [Source.observe, Verify.observe, model, sstore, bind, StateT.bind, pure, StateT.pure, + Except.bind, Except.pure, Observable.mk.injEq] + refine ⟨trivial, trivial, by simp [State.logEntries], ?_⟩ + funext slot + simp only [ite_true, State.loadSlot, StorageMap.lookup?, Std.HashMap.get?_eq_getElem?, + Std.HashMap.getElem?_insert, getElem?_of_isEmpty hs, Shared.norm, Shared.wordModulus] + rw [show EvmYul.UInt256.size = 2 ^ 256 from rfl] + generalize slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = k + by_cases h : k = 0 + · subst h; simp; exact (Nat.mod_eq_of_lt hw).symm + · have h' : ¬0 = k := fun e => h e.symm + simp [h, h'] + +/-- `model` implements SolidCore's `Main` on every call of the scope. -/ +theorem implements {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) : Implements fuel c scope (argWords 1) model := + implements_of_run' (by simp [fns]) fun fn hfn ws hl => by + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w, _ | _⟩ <;> simp at hl + exact run_set hcore hd w + +/-- The verification conditions of `set`, by Loom's weakest preconditions. -/ +theorem vcs : ∀ call, scope call → pre call → vc model (argWords 1) post call := by + sc_vcgen [scope, fns, model, post] + +/-- **The specification of `w4`'s `set`**, as a triple against SolidCore. -/ +theorem spec : ∃ c, contract? = .ok c ∧ Triple fuel c scope pre post := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + exact ⟨c, hc, triple_of_wp (implements hk hd) vcs⟩ + +/-- The specification of `w4`'s `set` as `Satisfies` on SolidCore. -/ +theorem satisfies : ∃ c, contract? = .ok c ∧ Satisfies (solidCore fuel) c scope pre post := by + obtain ⟨c, hc, h⟩ := spec + exact ⟨c, hc, satisfies_of_triple h⟩ + + +/-! ## From any storage + +`specAt` states the same on `scopeAt`, every call of `set` with no value from any storage `σ`, +whose postcondition `postAt` keeps every slot of `σ` but slot 0: `run_set_at` runs SolidCore +from `σ` written over the deployed storage (`run_eq_at`), and `vcsAt` is `sc_vcgen` for each +`σ`. -/ + +/-- The calls of `set` on any word, with no value, from any storage. -/ +def scopeAt : Call → Prop := fun call => ∃ σ, fullScope fns σ call + +/-- `set(v)` succeeds with no output and no logs, and leaves `v` in slot 0 and every other +slot of the call's storage as it was. -/ +def postAt (call : Call) (obs : Observable) : Prop := + let v := (argWords 1 call).getD 0 0 + obs.success = true ∧ obs.output = [] ∧ obs.logs = [] ∧ + ∀ slot, obs.storage slot = if slot % 2 ^ 256 = 0 then v else slotValue call.storage slot + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs `set` on any argument word from any storage `σ` as `model` does. -/ +theorem run_set_at {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d []) (w : U256) (σ : List (Nat × Nat)) : + Source.run fuel c (callAt Bytecode.W4.Main.setSelector [w] σ) = + some (Verify.observe (slotValue σ) (model [w.toNat] (slotValue σ))) := by + rw [run_eq_at hd] + have hev := hd.events + have h0 : ∀ q : Nat, d.storage[q]? = none := fun q => hd.getElem?_eq_none (by simp) + have hget := getD_storage h0 σ + generalize σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage = m at hget + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.W4.Main.setSelector] + have hw := w.isLt + simp only [Source.observe, Verify.observe, model, sstore, bind, StateT.bind, pure, StateT.pure, + Except.bind, Except.pure, Observable.mk.injEq] + refine ⟨trivial, trivial, by simp [State.logEntries], ?_⟩ + funext slot + have hs := hget slot + simp only [Nat.reducePow] at hs + simp only [ite_true, State.loadSlot, StorageMap.lookup?, Std.HashMap.get?_eq_getElem?, + Std.HashMap.getElem?_insert, Shared.norm, Shared.wordModulus, EvmYul.UInt256.size, + List.getD_cons_zero, Nat.zero_mod, beq_iff_eq] + generalize slot % 115792089237316195423570985008687907853269984665640564039457584007913129639936 = k at hs ⊢ + by_cases h : k = 0 + · subst h; simp [Nat.mod_eq_of_lt hw] + · have h' : ¬0 = k := fun e => h e.symm + simp only [h, h', ↓reduceIte, ← hs] + cases m[k]? <;> rfl + +/-- `model` implements SolidCore's `Main` on every call of `scopeAt`. -/ +theorem implementsAt {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d []) : Implements fuel c scopeAt (argWords 1) model := by + rintro call ⟨σ, hs⟩ + refine implements_of_run' (s := σ) (by simp [fns]) (fun fn hfn ws hl => ?_) call hs + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w, _ | _⟩ <;> simp at hl + exact run_set_at hcore hd w σ + +/-- The verification conditions of `set` from any storage, by Loom's weakest preconditions. -/ +theorem vcsAt : ∀ call, scopeAt call → pre call → vc model (argWords 1) postAt call := by + rintro call ⟨σ, hs⟩ hp + have h : ∀ call, fullScope fns σ call → pre call → vc model (argWords 1) postAt call := by + sc_vcgen [fns, model, postAt] + exact h call hs hp + +/-- **The specification of `w4`'s `set` from any storage**, as a triple against SolidCore. -/ +theorem specAt : ∃ c, contract? = .ok c ∧ Triple fuel c scopeAt pre postAt := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + exact ⟨c, hc, triple_of_wp (implementsAt hk (deployedAt_of_deployed hd)) vcsAt⟩ + +/-- The specification from any storage as `Satisfies` on SolidCore. -/ +theorem satisfiesAt : ∃ c, contract? = .ok c ∧ Satisfies (solidCore fuel) c scopeAt pre postAt := by + obtain ⟨c, hc, h⟩ := specAt + exact ⟨c, hc, satisfies_of_triple h⟩ + +end SolidCore.Verify.W4 diff --git a/Verify/W5.lean b/Verify/W5.lean new file mode 100644 index 00000000..8a065c5f --- /dev/null +++ b/Verify/W5.lean @@ -0,0 +1,173 @@ +import Verify.Tactic +import SolidCore.Refinement.Corpus.W5 + +/-! +# w5: `f(uint256 a, uint256 b)` returns `a + b`, or panics on overflow + +The specification of `Main.f` in `scripts/refinement/corpus/w5.sol` (compiled by solar with +`-Ogas`), proved against SolidCore with the Loom VC generator of `Verify.Basic`: on every call +of `f` with any argument words `a b < 2 ^ 256`, from the deployed (empty) storage, the call +returns the word `a + b` when it fits in 256 bits and otherwise reverts with `Panic(0x11)`; +it emits no logs and storage stays empty. + +`model` is the function as a `SolM` program; `implements` ties it to SolidCore by symbolic +evaluation of the interpreter (`wide_symex`), and `vcs` follows from Loom's weakest +precondition of the model by `sc_vcgen`. Nothing here, nor in `Corpus.W5`, uses +`native_decide` or `bv_decide`: the kernel checks `Corpus.W5.shape_eq` by evaluation. +-/ + +namespace SolidCore.Verify.W5 + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source +open SolidCore.Refinement.Corpus.W5 + +/-- `f` as a Loom program over the storage. -/ +def model (ws : List Nat) : SolM (List Nat) := + if ws.getD 0 0 + ws.getD 1 0 < 2 ^ 256 then pure (word (ws.getD 0 0 + ws.getD 1 0)) + else revert (panic 0x11) + +/-- The calls of the specification: `f` on any two words, from the deployed storage. -/ +def scope : Call → Prop := fullScope fns [] + +/-- No precondition beyond the scope. -/ +def pre : Call → Prop := fun _ => True + +/-- `f(a, b)` returns `a + b` when it fits, else reverts with `Panic(0x11)`; it emits no +logs and leaves storage empty. -/ +def post (call : Call) (obs : Observable) : Prop := + let a := (argWords 2 call).getD 0 0 + let b := (argWords 2 call).getD 1 0 + (if a + b < 2 ^ 256 then obs.success = true ∧ obs.output = word (a + b) + else obs.success = false ∧ obs.output = panic 0x11) ∧ + obs.logs = [] ∧ ∀ slot, obs.storage slot = 0 + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs `f` on any argument words as `model` does. -/ +theorem run_f {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) (w1 w2 : U256) : + Source.run fuel c (callOf Bytecode.W5.Main.fSelector [w1, w2]) = + some (Verify.observe (fun _ => 0) (model [w1.toNat, w2.toNat] (fun _ => 0))) := by + rw [run_eq hd] + have hs := hd.storage + have hev := hd.events + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.W5.Main.fSelector] + all_goals + have hw1 := w1.isLt + have hw2 := w2.isLt + simp only [model, List.getD_cons_zero, List.getD_cons_succ] + split + all_goals try omega + all_goals + try rw [Nat.mod_eq_of_lt (by omega)] + simp [Source.observe, Verify.observe, revert, pure, StateT.pure, Except.pure, panic, word, + State.logEntries, State.loadSlot, StorageMap.lookup?, getElem?_of_isEmpty hs, + slotValue, callOf] + +/-- `model` implements SolidCore's `Main` on every call of the scope. -/ +theorem implements {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : Deployed fuel c d) : Implements fuel c scope (argWords 2) model := + implements_of_run' (by simp [fns]) fun fn hfn ws hl => by + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w1, _ | ⟨w2, _ | _⟩⟩ <;> simp at hl + exact run_f hcore hd w1 w2 + +/-- The verification conditions of `f`, by Loom's weakest preconditions. -/ +theorem vcs : ∀ call, scope call → pre call → vc model (argWords 2) post call := by + sc_vcgen [scope, fns, model, post] + +/-- **The specification of `w5`'s `f`**, as a triple against SolidCore. -/ +theorem spec : ∃ c, contract? = .ok c ∧ Triple fuel c scope pre post := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + exact ⟨c, hc, triple_of_wp (implements hk hd) vcs⟩ + +/-- The specification of `w5`'s `f` as `Satisfies` on SolidCore. -/ +theorem satisfies : ∃ c, contract? = .ok c ∧ Satisfies (solidCore fuel) c scope pre post := by + obtain ⟨c, hc, h⟩ := spec + exact ⟨c, hc, satisfies_of_triple h⟩ + + +/-! ## From any storage + +`specAt` states the same on `scopeAt`, every call of `f` with no value from any storage `σ`, +whose postcondition `postAt` keeps `σ`: `run_f_at` runs SolidCore from `σ` written over the +deployed storage (`run_eq_at`), and `vcsAt` is `sc_vcgen` for each `σ`. -/ + +/-- The calls of `f` on any two words, with no value, from any storage. -/ +def scopeAt : Call → Prop := fun call => ∃ σ, fullScope fns σ call + +/-- `f(a, b)` returns `a + b` when it fits, else reverts with `Panic(0x11)`; it emits no +logs and leaves the call's storage as it was. -/ +def postAt (call : Call) (obs : Observable) : Prop := + let a := (argWords 2 call).getD 0 0 + let b := (argWords 2 call).getD 1 0 + (if a + b < 2 ^ 256 then obs.success = true ∧ obs.output = word (a + b) + else obs.success = false ∧ obs.output = panic 0x11) ∧ + obs.logs = [] ∧ ∀ slot, obs.storage slot = slotValue call.storage slot + +set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore runs `f` on any argument words from any storage `σ` as `model` does. -/ +theorem run_f_at {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d []) (w1 w2 : U256) (σ : List (Nat × Nat)) : + Source.run fuel c (callAt Bytecode.W5.Main.fSelector [w1, w2] σ) = + some (Verify.observe (slotValue σ) (model [w1.toNat, w2.toNat] (slotValue σ))) := by + rw [run_eq_at hd] + have hev := hd.events + have h0 : ∀ q : Nat, d.storage[q]? = none := fun q => hd.getElem?_eq_none (by simp) + have hget := getD_storage h0 σ + generalize σ.foldl (fun acc kv => StorageMap.insertLoop acc kv.1 kv.2) d.storage = m at hget + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, Bytecode.W5.Main.fSelector] + all_goals + have hw1 := w1.isLt + have hw2 := w2.isLt + simp only [model, List.getD_cons_zero, List.getD_cons_succ] + split + all_goals try omega + all_goals + try rw [Nat.mod_eq_of_lt (by omega)] + simp [Source.observe, Verify.observe, revert, pure, StateT.pure, Except.pure, panic, word, + State.logEntries, State.loadSlot, StorageMap.lookup?, callAt] + funext slot + have hs := hget slot + simp only [Nat.reducePow] at hs + simp only [Shared.norm, Shared.wordModulus, EvmYul.UInt256.size] + rw [← hs] + split <;> (rename_i h; simp [h]) + +/-- `model` implements SolidCore's `Main` on every call of `scopeAt`. -/ +theorem implementsAt {c : TypeCheck.CheckedContract} (hcore : c.core = coreLit) {d : Source.State} + (hd : DeployedAt fuel c d []) : Implements fuel c scopeAt (argWords 2) model := by + rintro call ⟨σ, hs⟩ + refine implements_of_run' (s := σ) (by simp [fns]) (fun fn hfn ws hl => ?_) call hs + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + subst hfn + rcases ws with _ | ⟨w1, _ | ⟨w2, _ | _⟩⟩ <;> simp at hl + exact run_f_at hcore hd w1 w2 σ + +/-- The verification conditions of `f` from any storage, by Loom's weakest preconditions. -/ +theorem vcsAt : ∀ call, scopeAt call → pre call → vc model (argWords 2) postAt call := by + rintro call ⟨σ, hs⟩ hp + have h : ∀ call, fullScope fns σ call → pre call → vc model (argWords 2) postAt call := by + sc_vcgen [fns, model, postAt] + exact h call hs hp + +/-- **The specification of `w5`'s `f` from any storage**, as a triple against SolidCore. -/ +theorem specAt : ∃ c, contract? = .ok c ∧ Triple fuel c scopeAt pre postAt := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hk, _, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + exact ⟨c, hc, triple_of_wp (implementsAt hk (deployedAt_of_deployed hd)) vcsAt⟩ + +/-- The specification from any storage as `Satisfies` on SolidCore. -/ +theorem satisfiesAt : ∃ c, contract? = .ok c ∧ Satisfies (solidCore fuel) c scopeAt pre postAt := by + obtain ⟨c, hc, h⟩ := specAt + exact ⟨c, hc, satisfies_of_triple h⟩ + +end SolidCore.Verify.W5 diff --git a/docs/CERTIFICATION_TARGET.md b/docs/CERTIFICATION_TARGET.md new file mode 100644 index 00000000..47b7531e --- /dev/null +++ b/docs/CERTIFICATION_TARGET.md @@ -0,0 +1,62 @@ +# Certification target: final theorem and interfaces (v1, 2026-11-14) + +## The one statement we publish per contract slice +For a pinned input triple (source file + sha256, solar-verify spec annotations, compile options `-Ogas --evm-version osaka`) +and the runtime bytes `code` that the solar binary built in the same run emits (byte-equal, fresh, never a reference artifact): + + Certified EthLib code Valid Allowed Post G -- Verify/Shapes.lean + inhabited : ∃ call, Valid call + equiv : Equiv -- every Valid call: EVM run of code ≈ SolidCore run of src (storage, return data, revert data, logs) + terminates: Terminates -- every Valid call: the source run terminates (ranking certificates, no fuel-as-proof) + meets : Meets -- every Valid call: Post holds of the source result (success or an Allowed revert) + resources : Resources -- every Valid call with gas ≥ G runs out of gas never; G is a proved bound + +with every premise printed in the statement and the transitive axioms only propext, Classical.choice, Quot.sound. +The driver states this type, checks the proof term against it, replays the closure in the kernel and binds `code`. + +## The chain, edge by edge (what is proved vs trusted) +| Edge | From -> To | Status rule | +|---|---|---| +| E0 port | upstream v2-core (0.5.16) -> pinned 0.8 port (port.py text edits) | TRUSTED boundary, stated. Not an equivalence proof for upstream. | +| E1 frontend | port .sol -> solc AST -> Source.lean (uniswap_v2_sources.py, solc_ast_to_lean_source.py) | TRUSTED frontend (TCB). uniswap_v2_core.py checks the AST import/typing only. Regenerating or hashing Source.lean does not prove it denotes the source. | +| E2 semantics | Source.lean -> SolidCore run | definition: the meaning of the source | +| E3 source -> MIR | SolidCore run -> MIR stage0 run | PROVED per contract by the generic source checker (contract_ok / checkC*) | +| E4 MIR -> EVM IR | stage0 -> sched -> evm1..n | PROVED per stage (stage certificates) | +| E5 EVM IR -> bytes | evm_n -> executed exact runtime bytes (Assemble.check, AssembleCallSeg) | PROVED; its runner premises (StaticRunner, CalleesRun) must be discharged, not assumed | +| E6 binding | statement's `code` = fresh solar output | driver byte equality + leanchecker replay | +| E7 spec | solar-verify spec -> VC over SolidCore runs -> discharged -> transferred to bytes via E3..E5 | PROVED; spec non-vacuous (NonVacuous), mutants refused by execution | +| E8 resources | gas bound on EthLib run of code | PROVED bound G, separate from functional equivalence | + +Strongest status (CERTIFIED) requires E3..E8 proved for the named scope. Any missing edge blocks it and is reported by name. +Handwritten specs, ghost state, abstraction functions, loop invariants and proof scripts are proof aids and are fine. +A hand-maintained functional model of the contract is NOT a substitute for E1..E5: without a checked correspondence it is a lemma. + +## Hash premises +Global separation over all 160-bit keys of a nested mapping is unsatisfiable: `NestedSlotsSeparated` (Verify/Spec/TreeMapNested.lean) +makes `(a, c) ↦ keccak(a . keccak(c . n))` injective on 2^320 pairs into 2^256 words, so any theorem assuming it is vacuous for real EVM. +Replacement: separation scoped to the finite set of preimages a call touches (its keys and the slots its frame states), as hevm does +(pairwise injectivity over the hash applications that occur, not a universal axiom). Single-level maps over 160-bit keys have no such +cardinality obstruction but are still a named computational assumption, printed in the statement. + +## First slice: UniswapV2ERC20.transfer (scope named; never advertised as Uniswap) +Valid: selector transfer(address,uint256), well-formed calldata, callvalue 0, ANY caller, any to and value, any storage. +Post, as sequential storage updates in source order (debit the caller, then credit the recipient reading the debited state): +- caller != to: success iff balanceOf[caller] >= value and balanceOf[to] + value < 2^256; then balanceOf[caller] -= value, + balanceOf[to] += value. +- caller == to: success iff balanceOf[caller] >= value (the credit reads the debited slot, so it cannot overflow); + balanceOf is unchanged. No recipient-overflow condition applies. +- on success: Transfer(caller, to, value) logged, returns true, every slot outside the call's footprint unchanged; + otherwise revert with the source's revert data and no state change. +Required concrete cases: balance = 2^256-1, value = 1, caller == to succeeds with balance unchanged and Transfer emitted; +self-transfer with balance < value reverts. +Premise: balanceOf slot separation scoped to the call's footprint {caller, to}: the exact premise is printed in the statement, +with a satisfiable instance exhibited in Lean. The frame is stated over the footprint and the slots the source writes; it must +not quantify over "all other slots" in a way that reintroduces collision-freedom for every key. No external calls: +StaticRunner/CalleesRun discharged. +Negative controls by execution: altered bytecode/jump, missing debit, wrong post, mismatched environment. + +## Reclassified (kept as lemmas until connected) +- Contracts/UniswapV2/PairSpec/Published.lean published_of_stages: composition interface taking every stage as a hypothesis. Not a Pair proof. +- PairSpec Negative.lean: formula checks on example states, not mutated program executions. +- Factory/Create2 lemmas and CreateNode (eval_create2Bytes, EvmCreate2): createPair is translated since the frontend covers its one assembly block (Stmt.assemblyCreate2, CREATE2 of the init code's bytes as an open-world request), and the whole Factory passes contract_ok. Lemmas until createPair's E3 (source -> MIR with a creation node) is proved. +- ERC20 EndToEndAll.published: vacuous (NestedSlotsSeparated), StaticRunner/CalleesRun assumed, its generated stage modules are not in the CI build. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 4e142541..b44403c5 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -5,6 +5,22 @@ The run is fully autonomous; where the phases and implementation notes leave a choice open, the most conservative behavior-preserving option was taken and recorded here. +## 2026-11-14 — Inline assembly create2 as an open-world creation of the init code's bytes + +The frontend translates exactly one inline assembly block, +`target := create2(value, add(code, 32), mload(code), salt)` over Solidity locals (an +address target, a `bytes memory` init code, a literal or `uint256` value, a literal, +`uint256` or `bytes32` salt), to `Stmt.assemblyCreate2`; every other block stays rejected. +`add(code, 32)` and `mload(code)` are the first byte and the length of `code`'s bytes, so the +statement means CREATE2 of exactly those bytes. It lowers to the core `Expr.create2Bytes`, +which emits one `Query.external` creation whose init code is the bytes themselves (not the +name encoding `creationInitCode` that `new C{salt: s}()` uses), and returns the answered +address, 0 on failure, with no revert of the caller, as the EVM's CREATE2. The salt, the code +and the value evaluate right to left as Yul's builtin arguments; they are literals or locals, +so the order has no other effect. `type(C).creationCode` stays the context's +`contractCreationCodes` entry, which a certificate binds to the compiler's bytes. This puts +`UniswapV2Factory.createPair` in the fragment (Contracts/UniswapV2/Factory/Create2Run.lean). + ## 2026-07-09 — NEW-OOM investigation: scaled `finalize_allocation` guard is via-IR-ONLY (NON-divergence under legacy ground truth) Investigated a proposed "MISSING-PANIC" gap: inline `new T[](n)` for `n` in the diff --git a/docs/refinement-statements.md b/docs/refinement-statements.md new file mode 100644 index 00000000..a537aeb7 --- /dev/null +++ b/docs/refinement-statements.md @@ -0,0 +1,170 @@ +# Refinement statements, end to end + +What the theorems from SolidCore to solar's bytecode state, in which direction, how fuel and +gas enter, why none of them holds vacuously, and what is still open. Lean names are relative to +`SolidCore.Refinement` unless they start with `SolarTV`. + +## The objects + +* `Call` (`SolarTV.Call`): call data, call value, and the callee's storage before the call as + (slot, value) pairs, a later pair winning. One frame, caller `0x2000`, callee `0x1000`. +* `Observable` (`SolarTV.Observable`): `success`, `output` (return data on success, revert data on + failure), `logs` (topics and data, in order) and `storage : Nat → Nat` (the callee's whole storage + after the call). A failed call has no logs and its initial storage (`Sem.FailureConvention`, + proved for `ethLib` and `solidCore` in `Behaviours.lean`). +* `Sem`: a type of programs and `run : Prog → Call → Option Observable`, a function, so a program has + at most one observable per call. `none` means no observable: the run did not finish, or used + something its semantics leaves undefined. + * `solidCore fuel`: `Source.run fuel`, SolidCore with a fixed statement fuel. Running out of statement + fuel is `none`. + * `SolarTV.mirSem o`, `SolarTV.evmirSem o`: solar's lowered MIR and EVM IR under an oracle `o` (caller, + Keccak, the results of calls out). `run` is the end some fuel reaches (`Layer.result`), which is unique + because each layer is deterministic and fuel-monotone (`Layer.mono`), so there is no fuel cut-off: + `none` means no fuel reaches an end. + * `ethLib`: `Target.run`, one `processMessage` at Fusaka with `gasLimit = 10_000_000` gas. Running out of + gas, `INVALID` and every exceptional halt are failures (`success = false`), never `none`; `none` only when + `processMessage` raises. + +## The relations + +All four are stated per call, for every call in a scope `scope : Call → Prop`. + +| name | statement | direction | +|---|---|---| +| `Stage A B p q scope` | `A.run p call = some obs → B.run q call = some obs` | forward, partial | +| `Backward A B p q scope` | `B.run q call = some obs → A.run p call = some obs` | target ⊆ source | +| `Total A B p q scope` | `∃ obs, A.run p call = some obs ∧ B.run q call = some obs` | both finish, equal | +| `Satisfies S p scope pre post` | `pre call → ∃ obs, S.run p call = some obs ∧ post call obs` | total correctness | + +`Refines fuel c code scope` is `Total (solidCore fuel) ethLib c code scope` (`refines_iff_total`, by `Iff.rfl`). +solar-tv's `Certified A B o p q scope` (every end of `p` some fuel reaches, `q` reaches an end that +`Agree`s with it) gives a `Stage` (`stage_of_certified`); `Agree` is finer than equal observables (it +tells `invalid` from `revert []` and compares transient storage and the world on success). + +### How they relate (`Behaviours.lean`, all proved) + +* `total_iff_stage`: `Total ↔ Stage ∧ Defined A p scope`. +* `total_iff_backward`: `Total ↔ Backward ∧ Defined B q scope`. +* `Total.backward`, `Refines.backward`: every observable of the bytecode on a call of the scope is + SolidCore's observable of that call: the same success, the same return or revert data, the same + logs and the same final storage. +* `Stage.backward_of_defined`: a stage whose source finishes on the scope is backward. +* `Backward.failure`: a backward simulation from a semantics whose failures roll back gives a target + whose failures roll back. + +### Composition + +* `Stage.trans` (solar-tv), `Total.trans`, `Backward.trans`: each relation composes with itself on a common + scope. +* `Total.trans_stage`: a total first stage followed by plain stages is total. A chain is as total as + its first source, so the only totality to prove is SolidCore's. +* `Satisfies.of_stage` carries a specification forward through a stage, `Satisfies.of_backward` + through a backward simulation onto a defined target, and `Satisfies.total_of_stage` turns a + specification and a stage into a total refinement on `scope ∧ pre`. +* `bytecode_total_of_stages`: from SolidCore's specification and the three stages (lowering, backend, + assembly), both `Refines fuel c code (scope ∧ pre)` and `Satisfies ethLib code scope pre post`. + +## Vacuity + +A bare `Stage` (and solar-tv's `Certified`) says nothing on a call its source does not finish: +`Stage.of_never` proves a stage from a never-finishing source to any target, and `never_stage_total` +exhibits one that is a stage but not total. Every end-to-end theorem must therefore rest on the +source's totality, and these are the places it comes from: + +* the headline theorems (`Headline.c1`, `w1`, `w4`, `c4`, `w5`, `w1_staged`) and counter's + `certified*`: from `Satisfies (solidCore fuel)`, which requires SolidCore to finish every specified + call, or from `Refines` directly; +* the generic source stage: its proof runs SolidCore to an observable on every call of its scope + (`Generic.source_run`), now exposed as `Generic.definedAt` / `Generic.defined` and the total forms + `Generic.totalAtWith`, `totalAt`, `totalAtEnv`, `totalAtCaller` (`Generic/Total.lean`); +* bank and events, whose `certified` theorems are bare stages under an oracle hypothesis + (`Assemble.OracleOk`): `Solar.Bank.defined` and `Solar.Events.defined` (`Solar/Total.lean`) give SolidCore's + totality on their whole scope (every function, any argument words, any storage, no value), so + `Bank.refines_of_stage` / `Events.refines_of_stage` turn their stages into `Refines`; + `Solar.ethOracle_sourceEnvOk` shows the source stage's oracle hypothesis is met by EthLib's caller and + Keccak (the oracle `Assemble.ethOracle_ok` already shows meets `OracleOk`). The one-line composition + `Bank.refines_of_stage hc (Bank.certified (Assemble.ethOracle o) (Assemble.ethOracle_ok o) + Bank.ethKeccakAgree hc)` is not checked yet: `Bank.certified` does not build at this branch's solar-tv pin + (below). + +The relations tell observables apart: on `Fixed` (programs are their own observables) a stage +between two observables holds iff they are equal (`Fixed.stage_iff`, `total_iff`, `backward_iff`), and +`stage_rejects_success`, `_output`, `_logs`, `_storage` each refute a stage between observables differing +in one field. + +### Concrete calls (`NonVacuity.lean`) + +For each headline, a call where both sides finish and the relation is checked, read off the +theorems alone (no evaluation of either semantics outside them): + +| headline | call | bytecode and SolidCore both give | +|---|---|---| +| w5 | `f(1, 2)` | success, `word 3`, no logs, storage 0 | +| w5 | `f(2^256-1, 1)` | failure, `Panic(0x11)`, no logs, storage 0 | +| w1 | `f(41)`, `f(2^256-1)` | `word 42`; `Panic(0x11)` | +| w4 | `set(9)` | success, no output, slot 0 holds 9 | +| c1 | `f(2)`, `f(85)` | `word 7`; `Panic(0x11)` | +| c4 | `add(3)` from the deployed storage | `word 3`, slot 0 holds `3 + (7 xor 3) * 256` | +| c4 | `add(256)` (dirty `uint8`) | failure, empty data, deployed storage kept | + +Each `*_rejects` theorem refutes a neighbouring observable (a wrong word, success instead of a +revert, a wrong slot). With a relation that related everything none of these would be provable. + +## Fuel and gas + +* SolidCore: a run that runs out of statement fuel is `none`, which refutes `Total`, `Refines` and + `Satisfies`; it never satisfies them. `Solidity/FuelExtension.lean` proves this holds along every path, + not only for trees with no `outOfFuel` anywhere: each statement evaluator at fuel `n` is extended + (`SolI.Ext`: some `outOfFuel` leaves replaced) by itself at any `m ≥ n` (`Stmt.eval_fuel_ext`), a + fold that does not end in `outOfFuel` ends the same way on an extension (`SolI.Ext.runWith`), so + `FunctionDef.call?` and the ABI dispatcher (`ABI.Contract.callCalldataAtFromWithContext?_fuel_mono`) are + fuel-monotone. `Refinement/Fuel.lean` lifts it to `Source.run_fuel_mono`, `Refines.fuel_mono` and + `Satisfies.fuel_mono`, under one hypothesis, `CtorStable n m`: the constructor gives the same result at + both fuels. **Open**: discharging `CtorStable`. The constructor runs under a self-dispatch hook whose + depth is the fuel (`CheckedContract.constructWithContext?`), so its context differs between fuels; the hook + is never reached during construction (a statement-level self-call reverts, a low-level one fails + closed), but proving that needs an induction over the expression evaluator too. + Expression and ABI-decoding fuel are structural (computed from the expression or type) and their + exhaustion is a revert; the design argues it is unreachable, which is not proved. +* Self-dispatch: where the hook is installed and reached (`Contract.callWithSelfDispatch` and its + transaction twin, not `Source.run`), a hook that returns `none`, which includes a nested call that ran + out of fuel or depth, is a *failed call* (`success = false`), not `outOfFuel` (`selfDispatchCall`). That + result depends on the fuel, so those entry points are not fuel-monotone; mapping `none` to `outOfFuel` + there would fail closed instead. `Source.run`'s dispatch context installs no hook, so self-calls fail + closed and the theorems above are unaffected. +* solar's MIR and EVM IR: no fuel cut-off (`Layer.result`). +* EthLib: one fixed gas, `gasLimit`. `Total` at it forces the bytecode not to run out of gas on any call of + the scope where SolidCore finishes (it would give `success = false` where SolidCore succeeds). + **Open**: every other gas. The intended statement, with `Target.runGas g` the same message with `g` + gas and `oog call = ⟨false, [], [], slotValue call.storage⟩`: + + `∀ g, ∀ call, scope call → ∀ obs, Target.runGas g code call = some obs → Source.run fuel c call = some obs ∨ obs = oog call` + + together with `Refines` at `gasLimit`, which keeps it from relating an always-failing bytecode. It + needs EthLib's gas monotonicity for the frame; the composition work has started on this + (`Within`, `compose_anyGas`). Note that `oog call` is also the observable of `revert(0, 0)`: the + observable does not tell the two apart (nor `INVALID`), only gas consumption does. + +## Build state at this pin (solar-tv 2144dccb) + +* `SolidCore/Refinement/Solar/Assemble.lean` fails: solar-tv's `dup`/`swap` now take `Fin 256` and the + assembly proofs expect `Fin 16`. Everything that imports it (every assembly stage, `Bank.certified`, + `Events.certified`, the counter milestone) does not build here. +* solar-tv's own bank and events milestone run proofs (`milestone/bank/Proofs/Runs/Sched.lean`, `Evm1` to + `Evm11`, and the events ones) fail in `sym_exec`, so `SolarTV.Milestone.Bank.evm*_run` depend on + `sorryAx` at this pin. A newer solar-tv is expected to fix both. +* Built and checked here: `Behaviours.lean`, `Generic/Total.lean`, `NonVacuity.lean` (on the headline + theorems, which do not import the assembly stage) and `Solar/Total.lean`. + +## Assumptions every theorem keeps + +From `Statement.lean`: one frame and a fixed environment (no block or account reads, no calls out: +solar-tv's `FrameLocal` rejects `CALL`, `CREATE`, balance, environment and `GAS` opcodes); the bytecode +starts from runtime code with the call's storage while SolidCore runs its constructor first; transient +storage is not observed; one gas amount (above). The oracle hypotheses of the staged theorems are +satisfiable (`Solar.ethOracle_sourceEnvOk`, `Assemble.ethOracle_ok`). + +## Checked + +`#print axioms` for the new theorems is pinned with `#guard_msgs` in each file: `propext`, +`Classical.choice` and `Quot.sound` only. No `sorry`, `native_decide` or `bv_decide`. diff --git a/lake-manifest.json b/lake-manifest.json index 085d68a3..5c50c94a 100644 --- a/lake-manifest.json +++ b/lake-manifest.json @@ -1,140 +1,197 @@ { - "version": "1.1.0", - "packagesDir": ".lake/packages", - "packages": [ - { - "url": "https://github.com/danrobinson/evm-interaction.git", - "type": "git", - "subDir": null, - "scope": "", - "rev": "c939817c55f966dab97e1ba8df05ceca1fdfbdb2", - "name": "\u00abevm-interaction\u00bb", - "manifestFile": "lake-manifest.json", - "inputRev": "c939817c55f966dab97e1ba8df05ceca1fdfbdb2", - "inherited": false, - "configFile": "lakefile.lean" - }, - { - "url": "https://github.com/danrobinson/EVMYulLean.git", - "type": "git", - "subDir": null, - "scope": "", - "rev": "b08573c65e33feb5331abe2b7c1d76be89bb8eff", - "name": "evmyul", - "manifestFile": "lake-manifest.json", - "inputRev": "b08573c65e33feb5331abe2b7c1d76be89bb8eff", - "inherited": false, - "configFile": "lakefile.lean" - }, - { - "url": "https://github.com/leanprover-community/mathlib4.git", - "type": "git", - "subDir": null, - "scope": "", - "rev": "8f9d9cff6bd728b17a24e163c9402775d9e6a365", - "name": "mathlib", - "manifestFile": "lake-manifest.json", - "inputRev": "v4.28.0", - "inherited": true, - "configFile": "lakefile.lean" - }, - { - "url": "https://github.com/leanprover-community/plausible", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "55c8532eb21ec9f6d565d51d96b8ca50bd1fbef3", - "name": "plausible", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/LeanSearchClient", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "c5d5b8fe6e5158def25cd28eb94e4141ad97c843", - "name": "LeanSearchClient", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/import-graph", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "85b59af46828c029a9168f2f9c35119bd0721e6e", - "name": "importGraph", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/ProofWidgets4", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "be3b2e63b1bbf496c478cef98b86972a37c1417d", - "name": "proofwidgets", - "manifestFile": "lake-manifest.json", - "inputRev": "v0.0.87", - "inherited": true, - "configFile": "lakefile.lean" - }, - { - "url": "https://github.com/leanprover-community/aesop", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "f642a64c76df8ba9cb53dba3b919425a0c2aeaf1", - "name": "aesop", - "manifestFile": "lake-manifest.json", - "inputRev": "master", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/quote4", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "b8f98e9087e02c8553945a2c5abf07cec8e798c3", - "name": "Qq", - "manifestFile": "lake-manifest.json", - "inputRev": "master", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover-community/batteries", - "type": "git", - "subDir": null, - "scope": "leanprover-community", - "rev": "495c008c3e3f4fb4256ff5582ddb3abf3198026f", - "name": "batteries", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.toml" - }, - { - "url": "https://github.com/leanprover/lean4-cli", - "type": "git", - "subDir": null, - "scope": "leanprover", - "rev": "4f10f47646cb7d5748d6f423f4a07f98f7bbcc9e", - "name": "Cli", - "manifestFile": "lake-manifest.json", - "inputRev": "v4.28.0", - "inherited": true, - "configFile": "lakefile.toml" - } - ], - "name": "\u00absolidity-lean\u00bb", - "lakeDir": ".lake" -} \ No newline at end of file + "version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "56a005855ea17e0b0958f73ec801ae140b0a1679", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.35.0", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "type": "path", + "scope": "", + "name": "\u00abevm-interaction\u00bb", + "manifestFile": "lake-manifest.json", + "inherited": false, + "dir": "vendor/evm-interaction", + "copy": false, + "configFile": "lakefile.lean" + }, + { + "type": "path", + "scope": "", + "name": "evmyul", + "manifestFile": "lake-manifest.json", + "inherited": false, + "dir": "vendor/evmyul", + "copy": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/ethereum/EthLib.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "2cd5d14a6a2f6fd22ef6b68423e45cfa3a21001a", + "name": "EthLib", + "manifestFile": "lake-manifest.json", + "inputRev": "2cd5d14a6a2f6fd22ef6b68423e45cfa3a21001a", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "dfa4f38190d07c37e315953e08b90fe2d95b3c24", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "d6b4c7be5be75ec4917c873ac50c756dc1436372", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "a41f0e9a4dea23188ea9cc1c41ac9f8bbafe0b93", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "df72b022e558978a1c50264cfc4d7fec86fa8e04", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "4a174c490d8707121c4a9290800489f105d85e07", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "dce0ad79c486cb1fb504af04f953c3466b0c6db8", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "66e469188fe07963e5cf666c7d4433f45b8131c5", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/Verified-zkEVM/VCVio.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "bbf05eeeedf84c5f98baaf5ab846f2d2479cc8ab", + "name": "VCVio", + "manifestFile": "lake-manifest.json", + "inputRev": "bbf05eeeedf84c5f98baaf5ab846f2d2479cc8ab", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "c24fe6078c630e89b489bffe59b3e20ac30d12c8", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.35.0", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/lean-crypto-foundations/QuantumFoundations", + "type": "git", + "subDir": null, + "scope": "", + "rev": "901aaab7967ceecd2240d0b38bbde7cf3e2c14ac", + "name": "QuantumFoundations", + "manifestFile": "lake-manifest.json", + "inputRev": "901aaab7967ceecd2240d0b38bbde7cf3e2c14ac", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/Verified-zkEVM/PolyFun", + "type": "git", + "subDir": null, + "scope": "", + "rev": "4181c82238142d9b73403fbf4c4b13e1a801e400", + "name": "PolyFun", + "manifestFile": "lake-manifest.json", + "inputRev": "4181c82238142d9b73403fbf4c4b13e1a801e400", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/cslib", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "5b56df99362532c46e1175381fbbdd755bd56030", + "name": "cslib", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.35.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "\u00absolidity-lean\u00bb", + "lakeDir": ".lake", + "fixedToolchain": false +} diff --git a/lakefile.lean b/lakefile.lean index 5b4ab383..ed3bd02c 100644 --- a/lakefile.lean +++ b/lakefile.lean @@ -1,26 +1,44 @@ import Lake open Lake DSL -require evmyul from git - "https://github.com/danrobinson/EVMYulLean.git" @ "b08573c65e33feb5331abe2b7c1d76be89bb8eff" +-- The EVM semantics the refinement theorems run solar's bytecode on. +require EthLib from git + "https://github.com/ethereum/EthLib.git" @ "2cd5d14a6a2f6fd22ef6b68423e45cfa3a21001a" + +-- evmyul and evm-interaction are vendored with the changes Lean 4.35 needs; see +-- vendor/README.md. +require evmyul from "vendor" / "evmyul" -- The shared "language of composition": the interaction monad, Query/Answer, --- OpenWorld, and ForwardRel, extracted verbatim from evm-compiler. Consumed as a --- Lake path dependency (a sibling git repo); promote to a git URL later. A --- hash-check (scripts/check_shared_interaction_hashes.py) guarantees its --- Simulation sources stay byte-identical to evm-compiler's. -require «evm-interaction» from git - "https://github.com/danrobinson/evm-interaction.git" @ "c939817c55f966dab97e1ba8df05ceca1fdfbdb2" +-- OpenWorld, and ForwardRel, extracted verbatim from evm-compiler. +require «evm-interaction» from "vendor" / "evm-interaction" + +-- Mathlib at the release EthLib builds against. Listed last, so its pins of +-- Batteries, Aesop and the rest win over older ones further up. +require "leanprover-community" / "mathlib" @ git "v4.35.0" package «solidity-lean» where + -- `lake build -KleanMemory=4500` caps each Lean process's memory in MB, without changing + -- the build's traces. + weakLeanArgs := match get_config? leanMemory with + | some mb => #["-M", mb] + | none => #[] leanOptions := #[ - ⟨`maxHeartbeats, 1000000⟩ + ⟨`maxHeartbeats, 1000000⟩, + -- Lean 4.35's new `do` elaborator drops the `match` hypotheses that the + -- automatic termination proofs of the checker and interpreter rely on. + ⟨`backward.do.legacy, true⟩ ] -- The default root retains every proof and witness in the full build. @[default_target] lean_lib SolidCore where +-- c1's hand-written refinement evaluates SolidCore with `native_decide`, which trusts Lean's +-- compiler, so it stays out of the default library: `lake build SolidCoreNative`. +lean_lib SolidCoreNative where + roots := #[`SolidCore.Refinement.C1.Spec] + -- The giant statement-lowering mutual block takes much longer to optimize in -- C than to execute once per prepared fixture. Keep its development build cheap; -- opt into -O3 with `lake -KspecHuntLoweringO3=true build` for throughput profiling. @@ -28,6 +46,26 @@ lean_lib SolidCoreStatementLowering where roots := #[`SolidCore.Solidity.Interface.Statements] moreLeancArgs := if get_config? specHuntLoweringO3 == some "true" then #[] else #["-O0"] +-- w4's stages against solar's own (solar-tv/milestone/w4), outside the default root: w4's +-- exported stages share their names (SolarTV.Export.Main) with w1's, which the root imports. +lean_lib SolidCoreSolarW4 where + roots := #[`SolidCore.Refinement.Solar.W4.Milestone] + +-- c4's source stage against solar's first lowered MIR (solar-tv/milestone/c4's export), composed +-- with solar-tv's backend stages and the assembly stage into one theorem from SolidCore to the +-- bytecode (Solar/C4/Certified.lean), outside the default root for the same reason. +lean_lib SolidCoreSolarC4 where + roots := #[`SolidCore.Refinement.Solar.C4.Lowering, `SolidCore.Refinement.Solar.C4.LoweringGeneric, + `SolidCore.Refinement.Solar.C4.Assembly, `SolidCore.Refinement.Solar.C4.Certified] + +-- The generic source stage against solar's first lowered MIR of a narrow-mul test contract +-- (scripts/refinement/mulx/mul.sol; solar-tv/milestone/mulx, solar's export at a8179dfc), +-- composed with solar-tv's backend stages and the assembly stage into one theorem from +-- SolidCore to the bytecode (Solar/MulX/Certified.lean), outside the default root for the same +-- reason. Lowering.lean and Certified.lean need -KleanMemory=6000 (peaks of 5.4 and 4.3 GB). +lean_lib SolidCoreSolarMulX where + roots := #[`SolidCore.Refinement.Solar.MulX.Lowering, `SolidCore.Refinement.Solar.MulX.Certified] + /-- Compile precisely the observable helper's semantic import closure. Using individual module objects avoids building every library root in evmyul/Mathlib (the pinned evmyul package has no Conform.lean root). -/ @@ -42,9 +80,12 @@ target specHuntNative pkg : Dynlib := do if seen.contains mod.pkg.keyName then return (seen, jobs) let libs ← mod.pkg.externLibs.mapM (·.static.fetch) return (seen.insert mod.pkg.keyName, jobs ++ libs) + -- Mathlib's import closure reaches ImportGraph, which links Lake, so the + -- plugin needs the toolchain's shared libraries at load time. + let rpath := s!"-Wl,-rpath,{(← getLeanLibDir)}" buildLeanSharedLib "specHuntNative" (pkg.sharedLibDir / nameToSharedLib "specHuntNative") - (objects ++ libraries) #[] #[] #[] (plugin := true) + (objects ++ libraries) #[] #[rpath] #[] (plugin := true) -- Only witnesses load the native semantic plugin. Proofs and the semantic -- modules still elaborate normally; this introduces no alternative evaluator. @@ -73,3 +114,501 @@ lean_exe precompileParity where lean_exe specHuntRunner where root := `SpecHuntRunner supportInterpreter := true + +/-- Loom's monad algebras and weakest preconditions, ported to Lean 4.35 (Loom/README.md). Only +the ported modules are kept; every one builds. -/ +lean_lib Loom where + roots := #[`Loom] + globs := #[.andSubmodules `Loom] + +/-- Verification on top of SolidCore: the Loom-based VC generator and the specs it proves +(Verify/*.lean), solar-verify's spec language with ghost erasure and its trusted base +(Verify/Spec), solar-verify's VCs checked against Loom models (Verify/VC) and the composition +of a source triple with the refinement to bytecode (Verify/Final.lean). `lake build Verify` +builds the root's closure; the libraries below hold the heavier, generated-input parts. -/ +lean_lib Verify where + roots := #[`Verify] + +-- bank's and events' assembly stages against solar's exports (solar-tv/milestone/bank and +-- solar-tv/milestone/events at 0a455fda): the generic assembler check with mapping hashes, +-- CALLER, LOG2 and LOG3 and internal calls through pushed return labels, under an oracle whose +-- caller and hash are EthLib's, and bank's composition from its first lowered MIR. Outside the +-- default root: the exports share solar-tv's milestone libraries. Each module fits in +-- -KleanMemory=3000 (peaks of 2.6 GB, 2.3 GB of them the imports' mapped oleans): the kernel +-- evaluates the check's one-pass form (Solar/AssembleFast.lean). +lean_lib SolidCoreSolarBank where + roots := #[`SolidCore.Refinement.Solar.Bank.Assembly, `SolidCore.Refinement.Solar.Bank.Mutants, + `SolidCore.Refinement.Solar.Events.Assembly] + +-- The generic source stages of bank and events (SolidCore to solar's first lowered MIR) and +-- their composition with solar-tv's backend stages and the assembly stage, outside the default +-- root for the same reason. Bank/Lowering.lean needs -KleanMemory=3500 (a peak of 3.4 GB); the rest +-- fit in 3000, and Bank/Certified.lean and Events/Certified.lean bind the theorems to the exports' +-- manifests (Solar/Hex.lean decodes the manifest's hex). +lean_lib SolidCoreSolarBankSource where + roots := #[`SolidCore.Refinement.Solar.Bank.Lowering, `SolidCore.Refinement.Solar.Events.Lowering, + `SolidCore.Refinement.Solar.Bank.Certified, `SolidCore.Refinement.Solar.Events.Certified, + `SolidCore.Refinement.Solar.Total] + +-- SolidCore ends on bank's, events' and mulx's certified scopes (within fuel 4096), so their +-- certified stages are total refinements (Solar/Totality.lean). Outside the default root: it +-- imports the three certified theorems. Fits in -KleanMemory=3000. +lean_lib SolidCoreSolarTotality where + roots := #[`SolidCore.Refinement.Solar.Totality] + +-- The assembly checker for code with loops on reads of the block and the transaction, ADDRESS +-- and SLT: an accepted program and its kernel-checked execution theorem, and a mutant of an +-- environment read that the checker rejects by evaluation (Solar/AssembleLoopEnv.lean). +lean_lib SolidCoreSolarAssemblyEnv where + roots := #[`SolidCore.Refinement.Solar.AssembleLoopEnv] + +-- The assembly theorem in its per-run oracle form (Solar/RunOracle.lean), and what GAS, +-- RETURNDATASIZE, RETURNDATACOPY, CALLDATACOPY and STATICCALL do in SolarTV and EthLib, one +-- instruction at a time, under the oracle of a run (Solar/AssembleEffects.lean), and the +-- refinement at the gas a run has from a block simulation under the runner of messages +-- (Solar/AssembleRun.lean), met by every program the loop checker accepts +-- (Solar/AssembleRunLoop.lean), and by every program the checker with contexts accepts, which +-- types an internal function once per call site (Solar/AssembleCtx.lean). +lean_lib SolidCoreSolarRunOracle where + roots := #[`SolidCore.Refinement.Solar.RunOracle, `SolidCore.Refinement.Solar.AssembleEffects, + `SolidCore.Refinement.Solar.AssembleRun, `SolidCore.Refinement.Solar.AssembleRunLoop, + `SolidCore.Refinement.Solar.RunOracleSource, + `SolidCore.Refinement.Solar.AssembleCut, `SolidCore.Refinement.Solar.AssembleDyn, + `SolidCore.Refinement.Solar.AssembleMem, `SolidCore.Refinement.Solar.AssembleDynCopy, + `SolidCore.Refinement.Solar.AssembleDynExample, `SolidCore.Refinement.Solar.AssembleCall, + `SolidCore.Refinement.Solar.AssembleCallWorld, `SolidCore.Refinement.Solar.AssembleCallCut, + `SolidCore.Refinement.Solar.AssembleCallSeg, `SolidCore.Refinement.Solar.AssembleCallExample, + `SolidCore.Refinement.Solar.AssembleCallPre, `SolidCore.Refinement.Solar.AssembleCallStatic, + `SolidCore.Refinement.Solar.AssembleCallStaticRunner, `SolidCore.Refinement.Solar.AssembleCtxTrack, + `SolidCore.Refinement.Solar.AssembleCtx, `SolidCore.Refinement.Solar.AssembleCtxExample, + `SolidCore.Refinement.Solar.AssembleCtxCall, + `SolidCore.Refinement.Solar.AssembleNoCall, `SolidCore.Refinement.Solar.AssembleNoCallExample, + `SolidCore.Refinement.Solar.AssembleCtxGas, `SolidCore.Refinement.Solar.AssembleCtxGasFrom] + +-- Runs that revert: no step of EthLib throws a revert and only REVERT ends a frame with it +-- (Solar/EthLibErr.lean), so a run with less gas that reverts follows the run with more +-- (Solar/EthLibErrLow.lean), and the loop checker's theorem relates revert data +-- (Solar/AssembleRevert.lean), and so does the checker with GAS and memory at any offset +-- (Solar/AssembleRevertCut.lean), each with an example and mutants (Solar/AssembleRevert*Example.lean). +lean_lib SolidCoreSolarRevert where + roots := #[`SolidCore.Refinement.Solar.EthLibErr, `SolidCore.Refinement.Solar.EthLibErrLow, + `SolidCore.Refinement.Solar.AssembleRevert, `SolidCore.Refinement.Solar.AssembleRevertExample, + `SolidCore.Refinement.Solar.AssembleRevertCut, `SolidCore.Refinement.Solar.AssembleRevertCutExample, + `SolidCore.Refinement.Solar.AssembleRevertCall] + +-- CODECOPY, CALL with value and CREATE2 at the frame's own gas, from a run that succeeds, and what +-- they do in SolarTV (Solar/AssembleCodeCopy.lean, Solar/AssembleCallValue.lean, +-- Solar/AssembleCreate.lean). +lean_lib SolidCoreSolarCreate where + roots := #[`SolidCore.Refinement.Solar.AssembleCodeCopy, `SolidCore.Refinement.Solar.AssembleCreate, + `SolidCore.Refinement.Solar.AssembleCallValue, `SolidCore.Refinement.Solar.AssembleCreateBack, + `SolidCore.Refinement.Solar.AssembleCallValueEffect, `SolidCore.Refinement.Solar.AssembleCallValueZero, + `SolidCore.Refinement.Solar.AssembleCreateSeg, `SolidCore.Refinement.Solar.AssembleCallValueSeg, + `SolidCore.Refinement.Solar.AssembleCallValueZeroSeg, + `SolidCore.Refinement.Solar.AssembleCreateSegOracle, `SolidCore.Refinement.Solar.AssembleCreateExample, + `SolidCore.Refinement.Solar.AssembleCreateCut, + `SolidCore.Refinement.Solar.AssembleCreateRun, `SolidCore.Refinement.Solar.AssembleCreateCutQ, + `SolidCore.Refinement.Solar.AssembleCreateSegF, `SolidCore.Refinement.Solar.AssembleCreateRunF] + +/-! solar's translation validation (formerly solar's `solar-tv` Lean package, moved here so that +every Lean source of the certified translation lives in this repository; solar keeps only the +stage exporter and the drivers that generate Lean against a pinned commit of this repository). +These libraries keep Lean's default options (as their own package had), not the ones above. -/ + +/-- The option defaults of solar's former `solar_tv` package. -/ +def solarTVOptions : Array LeanOption := #[ + ⟨`maxHeartbeats, (200000 : Nat)⟩, + ⟨`backward.do.legacy, false⟩ +] + +/-- solar's word semantics and rewrite-rule lemmas (`EvmRules`), vendored from solar's +scripts/evm-rules/lean at the commit vendor/evm-rules/README.md names. -/ +lean_lib EvmRules where + srcDir := "vendor/evm-rules" + globs := #[.andSubmodules `EvmRules] + leanOptions := solarTVOptions + +/-- MIR and EVM IR semantics, the stages and their refinement, assembly walk, cut points and +symbolic memory laws. -/ +lean_lib SolarTV where + srcDir := "tv" + globs := #[.andSubmodules `SolarTV] + leanOptions := solarTVOptions + +/-- The symbolic-execution procedures and assembly items that the generated per-contract proofs +use, and w1's own stage proofs. Symbolic execution is heavy: fail on running out of memory rather +than exhaust the machine. -/ +lean_lib W1Proofs where + srcDir := "tv" + globs := #[.andSubmodules `W1Proofs] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +/-! Generated per-contract stages and proofs that the headline theorems import, as solar's +exporter and certify driver write them (Certified//gen and Certified//Proofs, module +names without a `Certified` prefix). Regenerate with solar's certify driver; see +Certified/README.md. -/ + +/-- w1's exported stages and their checks. -/ +lean_lib W1 where + srcDir := "Certified/w1" + roots := #[`W1] + globs := #[.andSubmodules `W1, .submodules `gen] + leanOptions := solarTVOptions + +lean_lib counter where + srcDir := "Certified" + roots := #[`counter.Proofs] + globs := #[.submodules `counter] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +lean_lib w4 where + srcDir := "Certified" + roots := #[`w4.Proofs] + globs := #[.submodules `w4] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +lean_lib masks where + srcDir := "Certified" + roots := #[`masks.Proofs] + globs := #[.submodules `masks] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +lean_lib bank where + srcDir := "Certified" + roots := #[`bank.Proofs] + globs := #[.submodules `bank] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +lean_lib c4 where + srcDir := "Certified" + roots := #[`c4.Proofs] + globs := #[.submodules `c4] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +lean_lib mulx where + srcDir := "Certified" + roots := #[`mulx.Proofs] + globs := #[.submodules `mulx] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +lean_lib events where + srcDir := "Certified" + roots := #[`events.Proofs] + globs := #[.submodules `events] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +lean_lib reader where + srcDir := "Certified" + roots := #[`reader.Proofs] + globs := #[.submodules `reader] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +/-- solar-verify's Token (Contracts/Token/VC's source): its exported stages and backend proofs. -/ +lean_lib verify_token where + srcDir := "Certified" + roots := #[`verify_token.Proofs] + globs := #[.submodules `verify_token] + leanOptions := solarTVOptions + -- Shape.lean peaks at 2.9 GB with LEAN_NUM_THREADS=2 (CI's setting), above a 3000 MB cap. + moreLeanArgs := #["-M", "4500"] + +-- solar-verify's spec language: its meaning over SolidCore's and EthLib's calls and observables, +-- ghost erasure, the trusted base as named hypotheses, and the specs solar-verify exports +-- (Verify/Spec, scripts/refinement/spec/check.sh). +lean_lib VerifySpec where + roots := #[`Verify.Spec.Syntax, `Verify.Spec.Semantics, `Verify.Spec.Contract, + `Verify.Spec.Ghost, `Verify.Spec.GhostFree, `Verify.Spec.TrustedBase, + `Verify.Spec.TrustedBase.Hypotheses, `Verify.Spec.TrustedBase.Interface, + `Verify.Spec.TreeMapNested, `Verify.Spec.HashScopeCheck] + +-- The trusted base discharged for c4 and Counter on their checked-in source ASTs, and its axiom +-- audit. Separate from VerifySpec because the ASTs import the type checker. +lean_lib VerifySpecTrustedBase where + roots := #[`Verify.Spec.TrustedBase.Instances, `Verify.Spec.TrustedBase.Axioms] + +-- c4's exported spec (solar-verify --emit-lean-spec, scripts/refinement/spec/check.sh) proved of +-- SolidCore and of solar's bytecode, and the axiom audit. Needs the generated corpus +-- (scripts/refinement/gen.sh), so it is outside the default root. +lean_lib ContractsC4Spec where + roots := #[`Contracts.C4.Spec.Export, `Contracts.C4.Spec.ExportWrong, `Contracts.C4.Spec.Bytecode, + `Contracts.C4.Spec.Axioms] + +-- solar-verify's verification conditions checked against SolidCore through the Loom generator +-- (Verify/VC.lean), the generic theorem from an erased function to its obligations +-- (Verify/VC/Obligations.lean) and its fuel uniformity (Verify/FuelStable.lean), outside the default +-- root: it builds on the generic source stage. +lean_lib VerifyVC where + roots := #[`Verify.VC, `Verify.FuelStable, `Verify.Spec.Tree, `Verify.Spec.Hash, `Verify.Spec.TreeMap, + `Verify.Spec.TreeIn, `Verify.Spec.TreeSplit] + +-- solar-verify's transcripts of scripts/verify/{Counter,Token}.sol (scripts/verify/check.sh) bound +-- to their scripts, Token.burn and Token.transfer proved from the checked VCs, and the mutants. +lean_lib ContractsVC where + roots := #[`Contracts.Counter.VC.Bind, `Contracts.Token.VC.Bind, `Contracts.Token.VC.Burn, + `Contracts.Token.VC.Transfer, `Contracts.Token.VC.Mutants, `Contracts.Counter.VC.Inc, `Contracts.Counter.VC.Get, + `Contracts.Counter.VC.Mutants, `Contracts.Counter.VC.Generic, `Contracts.Counter.VC.Discharged, + `Contracts.Token.VC.Discharged, `Contracts.Token.VC.FromScript, + `Contracts.Counter.VC.MilestoneDischarged, `Contracts.Counter.VC.ScriptEndToEnd] + -- The exports, sources and mutants the roots import are under the same directories. + globs := #[.submodules `Contracts.Counter.VC, .submodules `Contracts.Token.VC] + +-- SolidCore's checked Uniswap V2 port: Contracts/UniswapV2//{Source,Core}.lean, which +-- scripts/verify/uniswap_v2_gen.sh generates before the build (they are not committed: v2-core is +-- GPL-3.0), so run it first: scripts/verify/uniswap_v2_gen.sh && lake build ContractsUniswapV2. +-- Each Core is the kernel's type check and translation of its contract (contract_ok). +lean_lib ContractsUniswapV2 where + roots := #[`Contracts.UniswapV2.ERC20.Core] + -- The generated sources the roots import belong to this library too, or Lake looks for their + -- object files elsewhere instead of building them. + globs := #[.one `Contracts.UniswapV2.ERC20.Source, .one `Contracts.UniswapV2.ERC20.Core] + +-- UniswapV2Factory's translation, createPair included, is checked in stages as the Pair's is (one +-- module each, each within 6 GB; checked in one declaration it peaks at the 6 GB cap), with the +-- CREATE2 address lemmas (Create2) and createPair's execution tests (Create2Run). +lean_lib ContractsUniswapV2Factory where + roots := #[`Contracts.UniswapV2.Factory.Contract, `Contracts.UniswapV2.Factory.Create2, + `Contracts.UniswapV2.Factory.Create2Run] + globs := #[.submodules `Contracts.UniswapV2.Factory] + +-- Inline assembly create2 (Stmt.assemblyCreate2): Contracts/Create2/Deployer.sol's translation +-- (scripts/verify/create2_sources.py) and its execution tests, with the view negative control, +-- and the create node of the source semantics (SolidCore/Refinement/Generic/CreateNode.lean). +lean_lib ContractsCreate2 where + roots := #[`Contracts.Create2.Run, `SolidCore.Refinement.Generic.CreateNode] + globs := #[.submodules `Contracts.Create2, .one `SolidCore.Refinement.Generic.CreateNode] + +-- solar-verify's ERC20 specs connected to SolidCore's checked UniswapV2ERC20 (Meets: approve and +-- transfer meet their exported specs and the mutated spec is refused; SpecTree: the specs hold in +-- every world). scripts/verify/uniswap_v2_spec.sh generates Spec, SpecMut and Connect (derived from +-- the GPL-3.0 port, so not committed) after scripts/verify/uniswap_v2_gen.sh. +lean_lib ContractsUniswapV2ERC20Spec where + roots := #[`Contracts.UniswapV2.ERC20.Meets, `Contracts.UniswapV2.ERC20.SpecTree] + globs := #[.one `Contracts.UniswapV2.ERC20.Spec, .one `Contracts.UniswapV2.ERC20.SpecMut, + .one `Contracts.UniswapV2.ERC20.Connect, .one `Contracts.UniswapV2.ERC20.SpecTreeKeccak, + .one `Contracts.UniswapV2.ERC20.Meets, .one `Contracts.UniswapV2.ERC20.SpecTree] + +-- UniswapV2ERC20's approve and transferFrom (Contracts/UniswapV2/ERC20/Nested): the generic source +-- stage's trees and check against solar's stage0, slot-level sequential posts, and key-level +-- corollaries under keccak256 separation scoped to each call's footprint +-- (Verify/Spec/HashScopeNested.lean). Generated first, not committed (GPL-3.0 port): stage0 by +-- scripts/verify/uniswap_v2_erc20_stages.sh (lib uv2_erc20), its mutants by +-- scripts/verify/uniswap_v2_stage0_mutants.py, then, after +-- lake build Contracts.UniswapV2.ERC20.Core Contracts.UniswapV2.ERC20.SpecTreeKeccak, the trees by +-- scripts/verify/uniswap_v2_trees.py. Every module is checked within 6 GB. +lean_lib ContractsUniswapV2ERC20Nested where + roots := #[`Contracts.UniswapV2.ERC20.Nested.All] + globs := #[.submodules `Contracts.UniswapV2.ERC20.Nested, .one `Verify.Spec.HashScopeNested] + +-- UniswapV2ERC20.transfer's certified slice, E7 (docs/CERTIFICATION_TARGET.md): solar-verify's +-- transfer-slice.spec exported, its VC discharged over SolidCore's runs with no global hash premise, +-- the observable's postcondition, non-vacuity, the required concrete runs, the source mutants refused +-- by execution and the transfer of Meets to the bytes through Equiv (Contracts/UniswapV2/ERC20/Slice). +-- scripts/verify/uniswap_v2_transfer_slice.sh generates Slice/Gen (derived from the GPL-3.0 port, so +-- not committed) after scripts/verify/uniswap_v2_gen.sh. +lean_lib ContractsUniswapV2TransferSlice where + roots := #[`Contracts.UniswapV2.ERC20.Slice.All] + globs := #[.submodules `Contracts.UniswapV2.ERC20.Slice, .one `Contracts.UniswapV2.ERC20.SpecTreeKeccak] + +-- UniswapV2ERC20's exact runtime bytes against AssembleNoCall's call-free check (NoCall*: refused at +-- the counters NoCallAt lists; NoCallControl: the bytes with those instructions scrubbed pass; NoCallNeg: +-- scrubbing all but the STATICCALL fails). One kernel evaluation per module, each under 6 GB: build the +-- modules one at a time (each needs up to 5.8 GB). scripts/verify/uniswap_v2_runtime.sh writes +-- Runtime.lean from solar's output (derived from the GPL-3.0 port, so not committed) before the build. +lean_lib ContractsUniswapV2ERC20NoCall where + roots := #[`Contracts.UniswapV2.ERC20.NoCallFa, `Contracts.UniswapV2.ERC20.NoCallDecode, `Contracts.UniswapV2.ERC20.NoCallOnly, `Contracts.UniswapV2.ERC20.NoCallAt, `Contracts.UniswapV2.ERC20.NoCallControl, `Contracts.UniswapV2.ERC20.NoCallNeg] + globs := #[.one `Contracts.UniswapV2.ERC20.Runtime, .one `Contracts.UniswapV2.ERC20.NoCall, .one `Contracts.UniswapV2.ERC20.NoCallFa, .one `Contracts.UniswapV2.ERC20.NoCallDecode, .one `Contracts.UniswapV2.ERC20.NoCallOnly, .one `Contracts.UniswapV2.ERC20.NoCallAt, .one `Contracts.UniswapV2.ERC20.NoCallControl, .one `Contracts.UniswapV2.ERC20.NoCallNeg] + +-- UniswapV2Pair's translation is checked in stages, one module each, each within 6 GB: +-- Pair/Contract.lean composes contract_ok from Check, Ctx, Clones, one Fn module per run of +-- functions (mint and swap in three each: Fn/_pre, Fn/_lower, Fn/), Groups and Asm. +-- Not in CI yet: 22 modules, the largest (swap's lowering) at 5.98 GB under -M 6000. +lean_lib ContractsUniswapV2Pair where + roots := #[`Contracts.UniswapV2.Pair.Contract] + globs := #[.submodules `Contracts.UniswapV2.Pair] + +-- Loom's axiom audit and the check that the certified Loom path stays off Loom's unported +-- layers (Verify/LoomAxioms.lean, Verify/LoomImports.lean). +lean_lib VerifyLoom where + roots := #[`Verify.LoomAxioms, `Verify.LoomImports] + +-- Counter end to end: its source triple carried through the refinement to solar's bytecode +-- (Verify.Final) and solar-verify's verdict as named hypotheses; the headline +-- (Contracts/Counter/Headline.lean) discharges the verdict for solar-verify's exported spec of +-- scripts/verify/CounterMilestone.sol and states it of solar's bytecode. +lean_lib ContractsCounter where + roots := #[`Contracts.Counter.Final, `Contracts.Counter.Verdict, `Contracts.Counter.EndToEnd, + `Contracts.Counter.Headline, `Contracts.Counter.SpecTree, `Contracts.Counter.Exports] + -- The roots themselves (explicit globs replace the default of one glob per root), and the + -- spec exports, deploy proof and source binding they import. + globs := #[.one `Contracts.Counter.Final, .one `Contracts.Counter.Verdict, + .one `Contracts.Counter.EndToEnd, .one `Contracts.Counter.Headline, + .one `Contracts.Counter.Verify, .one `Contracts.Counter.Deploy, + .one `Contracts.Counter.SpecTree, .one `Contracts.Counter.Exports, .one `SolidCore.Refinement.Deploy, + .submodules `Contracts.Counter.Spec] + +-- The published shape of a certificate (Verify/Shapes.lean: equivalence, termination, spec and +-- resources, apart), the forward assembly stage from a gas bound on (AssembleGas, and +-- AssembleGasLoop for code with loops) and Counter's +-- instance: its bytecode run by the checker with GAS +-- (Contracts/Counter/Execution.lean), the statement's inputs (ShapeSpec), the proof (Shape) and the +-- negative controls (ShapeNeg). Certified/counter/Final.lean, which solar's certify driver writes, +-- states the published theorem over them. Verify/ShapeCtx.lean: the same shape, without resources, +-- through the context checker (AssembleCtxCall). +lean_lib ContractsShapes where + roots := #[`Verify.Shapes, `Verify.ShapeGeneric, `SolidCore.Refinement.Solar.AssembleGas, + `SolidCore.Refinement.Solar.AssembleGasLoop, `Contracts.Counter.Execution, `Contracts.Counter.ShapeSpec, + `Contracts.Counter.Shape, `Contracts.Counter.ShapeNeg, `Verify.ShapeBundle, + `Contracts.Counter.ShapeExport, `Verify.ShapeCtx, `Verify.ShapeCtxGas] + globs := #[.one `Verify.Shapes, .one `Verify.ShapeGeneric, .one `SolidCore.Refinement.Solar.AssembleGas, + .one `SolidCore.Refinement.Solar.AssembleGasLoop, + .one `Contracts.Counter.Execution, .one `Contracts.Counter.ShapeSpec, + .one `Contracts.Counter.Shape, .one `Contracts.Counter.ShapeNeg, .one `Verify.ShapeBundle, + .one `Contracts.Counter.ShapeExport, .one `Verify.ShapeCtx, .one `Verify.ShapeCtxGas] + +-- solar-verify's Token end to end: the generic source stage from SolidCore's checked Token to +-- Certified/verify_token's stage0, the assembly stage of its evm12, and solar-verify's Token +-- triples carried to solar's bytecode. +lean_lib ContractsToken where + roots := #[`Contracts.Token.Lowering, `Contracts.Token.Assembly, `Contracts.Token.Discharge, + `Contracts.Token.EndToEnd, `Contracts.Token.Exports, `Contracts.Token.LoweringIn, + `Contracts.Token.TransferMeets, `Contracts.Token.SpecTree, `Contracts.Token.WorldSpec, + `Contracts.Token.HashScope] + globs := #[.one `Contracts.Token.Lowering, .one `Contracts.Token.LoweringIn, .one `Contracts.Token.WorldSpec, .one `Contracts.Token.Assembly, + .one `Contracts.Token.Discharge, .one `Contracts.Token.EndToEnd, + .one `Contracts.Token.Exports, .one `Contracts.Token.TransferMeets, .one `Contracts.Token.SpecTree, + .one `Contracts.Token.HashScope, + .submodules `Contracts.Token.Spec] + +/-! solar-verify's verification conditions and their kernel-checked discharge (formerly solar's +crates/verify/lean). An exported VC module imports `Verify.Obligation`; `Verify.Discharge` holds the +certificate checkers a VC is accepted by (Verify/Discharge/README.md). Lean's default options, as +solar's `solar_verify` package had. -/ +lean_lib VerifyDischarge where + roots := #[`Verify.Obligation, `Verify.Discharge] + leanOptions := #[⟨`maxHeartbeats, (200000 : Nat)⟩, ⟨`backward.do.legacy, false⟩] + +-- ArrayMax and Vault: solar-verify's exported VCs of their specs (Contracts/{ArrayMax,Vault}/Vc), +-- every required obligation proved in the kernel (Proofs/), Vault's vacuous obligations shown +-- vacuous (Contracts/Vault/Proofs/Vacuous.lean), and the axiom audits. +lean_lib ContractsArrayMaxVault where + roots := #[`Contracts.ArrayMax.Audit, `Contracts.Vault.Audit] + globs := #[.submodules `Contracts.ArrayMax, .submodules `Contracts.Vault] + leanOptions := #[⟨`maxHeartbeats, (200000 : Nat)⟩, ⟨`backward.do.legacy, false⟩] + +-- verify_counter: the stages of solar's crates/verify/examples/Counter.sol (the counter with +-- bump's loop) that solar-tv/milestone/verify_counter exports; for now its first lowered MIR. +lean_lib verify_counter where + srcDir := "Certified" + roots := #[`verify_counter.Proofs] + globs := #[.submodules `verify_counter] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +-- solar-verify's spec of that Counter (Contracts/Counter/Verify.lean) on solar's first lowered +-- MIR, every function and every call, bump's loop through cut points (Bump.lean), and carried +-- along any backend proved back to it (Holds.lean). +lean_lib ContractsVerifyCounter where + roots := #[`Contracts.VerifyCounter.Holds] + globs := #[.submodules `Contracts.VerifyCounter] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +-- Math.sqrt's Newton loop inside CallSqrt's internal call: its generated ranking certificate +-- (Contracts/CallSqrt/Inferred.lean), sqrt's total contract under any caller, every call ending on +-- the first lowered MIR and the final EVM IR, and the exact bytecode (Final.lean). +lean_lib ContractsCallSqrt where + roots := #[`Contracts.CallSqrt.Final] + globs := #[.submodules `Contracts.CallSqrt] + leanOptions := solarTVOptions + moreLeanArgs := #["-M", "3000"] + +-- callsqrt: the stages of Certified/callsqrt/callsqrt.sol's CallSqrt and their kernel proofs, which +-- solar's scripts/certify writes. +lean_lib «callsqrt» where + srcDir := "Certified" + roots := #[`callsqrt.Proofs] + globs := #[.submodules `callsqrt] + +-- Non-vacuity of the source semantics under a call oracle (SolidCore/Refinement/SourceOracle.lean): +-- one contract per external-call family of a constant-product pair (Contracts/CallFamilies/Calls.sol), +-- each function kernel-evaluated to a normal return in an open world and to no normal return in the +-- closed world of Source.run. The kernel_rfl selector table needs more than 3000 MB. +lean_lib ContractsCallFamilies where + roots := #[`Contracts.CallFamilies.NonVacuity] + globs := #[.submodules `Contracts.CallFamilies] + moreLeanArgs := #["-M", "6000"] + +-- arraymax: the stages of Certified/arraymax/arraymax.sol's ArrayMaxEntry, which solar's +-- scripts/certify writes, and the kernel proofs of its EVM IR stages (evm1 to evm15). The MIR stages +-- (Runs.Mir1-3, Runs.Sched) and the composition (Proofs.Stages) do not check yet: the first fails +-- sym_seg on the ABI decoder's checks; they are left out of the library until they do. +lean_lib «arraymax» where + srcDir := "Certified" + roots := #[`arraymax.Proofs.Runs.Evm1, `arraymax.Proofs.Runs.Evm2, `arraymax.Proofs.Runs.Evm3, `arraymax.Proofs.Runs.Evm4, `arraymax.Proofs.Runs.Evm5, `arraymax.Proofs.Runs.Evm6, `arraymax.Proofs.Runs.Evm7, `arraymax.Proofs.Runs.Evm8, `arraymax.Proofs.Runs.Evm9, `arraymax.Proofs.Runs.Evm10, `arraymax.Proofs.Runs.Evm11, `arraymax.Proofs.Runs.Evm12, `arraymax.Proofs.Runs.Evm13, `arraymax.Proofs.Runs.Evm14, `arraymax.Proofs.Runs.Evm15] + globs := #[.submodules `arraymax.gen] + +-- UniswapV2Pair's published statement of swap, skim and sync (Contracts/UniswapV2/PairSpec): the +-- statement over an open world (Verify/ShapeOpen.lean), the stage theorems it composes as named +-- Props, the composition wrapper and the negative controls. scripts/verify/uniswap_v2_pair_spec.sh +-- generates its inputs (Spec, SpecWrongK, Bytecode, Runtime; derived from the GPL-3.0 port, so not +-- committed) after scripts/verify/uniswap_v2_gen.sh. +lean_lib ContractsUniswapV2PairSpec where + roots := #[`Contracts.UniswapV2.PairSpec.Published, `Contracts.UniswapV2.PairSpec.Negative, `Contracts.UniswapV2.PairSpec.Axioms] + globs := #[.submodules `Contracts.UniswapV2.PairSpec] + +-- uv2_erc20: UniswapV2ERC20's exported stages (Certified/uv2_erc20/gen, solar -Zemit-lean-stages of the +-- port, with the stage0 mutants of uniswap_v2_erc20_mutants.py; scripts/verify/uniswap_v2_erc20_stages.sh, +-- after scripts/verify/uniswap_v2_gen.sh), the certificate of the checker with contexts and gas +-- (CtxGas.lean, scripts/verify/uniswap_v2_gas.sh with solar's tools/certify/gen_ctxgas.py) and the +-- transfer slice's gas bound (Gas.lean, GasGuard.lean), and the backend stages' proofs for transfer's +-- calls (ProofsT/) with the bytes certificates (Ctx.lean, CtxNeg.lean), all written by +-- scripts/verify/uniswap_v2_stages.sh. The generated files come from the GPL-3.0 v2-core port, so +-- none is committed. Every module is checked within 6 GB. +lean_lib «uv2_erc20» where + srcDir := "Certified" + roots := #[`uv2_erc20.Gas, `uv2_erc20.AnyCaller, `uv2_erc20.gen.UniswapV2ERC20.Stage0, `uv2_erc20.ProofsT.Stages, + `uv2_erc20.ProofsT.Assembly, `uv2_erc20.Ctx, `uv2_erc20.CtxNeg] + globs := #[.submodules `uv2_erc20] + leanOptions := solarTVOptions + +-- E3 of docs/CERTIFICATION_TARGET.md's first slice: the generic source stage of UniswapV2ERC20.transfer +-- against the exported stage0 (Contracts/UniswapV2/ERC20/SourceMir.lean) and its refused mutants. +lean_lib ContractsUniswapV2ERC20SourceMir where + roots := #[`Contracts.UniswapV2.ERC20.SourceMir, `Contracts.UniswapV2.ERC20.SourceMirNeg, + `Contracts.UniswapV2.ERC20.SourceMirFrom, `Contracts.UniswapV2.ERC20.SourceMirFromNeg, `Contracts.UniswapV2.ERC20.SourceMirPinned] + globs := #[.one `Contracts.UniswapV2.ERC20.SourceMirDefs, .one `Contracts.UniswapV2.ERC20.SourceMirCheck, + .one `Contracts.UniswapV2.ERC20.SourceMirDeploy, .one `Contracts.UniswapV2.ERC20.SourceMir, + .one `Contracts.UniswapV2.ERC20.SourceMirNeg, + .one `Contracts.UniswapV2.ERC20.SourceMirFromDefs, .one `Contracts.UniswapV2.ERC20.SourceMirFromCheck, + .one `Contracts.UniswapV2.ERC20.SourceMirFrom, .one `Contracts.UniswapV2.ERC20.SourceMirFromNeg, + .one `Contracts.UniswapV2.ERC20.SourceMirPinned] + +-- event_words: the stages of Certified/event_words/event_words.sol's EventWords and their kernel proofs, which +-- solar's scripts/certify writes. +lean_lib «event_words» where + srcDir := "Certified" + roots := #[`event_words.Proofs] + globs := #[.submodules `event_words] + +-- abi_hash: the stages of Certified/abi_hash/abi_hash.sol's AbiHash and their kernel proofs, which +-- solar's scripts/certify writes. +lean_lib «abi_hash» where + srcDir := "Certified" + roots := #[`abi_hash.Proofs] + globs := #[.submodules `abi_hash] + +-- UniswapV2ERC20.transfer certified at the caller 0x2000 (Contracts/UniswapV2/ERC20/Certified): E3, E4, +-- E5 + E8 and E7 composed into one Shapes.Certified statement, with the two self-transfer cases on the +-- exact bytes. Needs the generated modules of uv2_erc20, ContractsUniswapV2ERC20SourceMir and +-- ContractsUniswapV2TransferSlice (scripts/verify/uniswap_v2_stages.sh, uniswap_v2_transfer_slice.sh). +lean_lib ContractsUniswapV2ERC20Certified where + roots := #[`Contracts.UniswapV2.ERC20.Certified.Transfer] diff --git a/lean-toolchain b/lean-toolchain index 4c685fa0..a6aff065 100644 --- a/lean-toolchain +++ b/lean-toolchain @@ -1 +1 @@ -leanprover/lean4:v4.28.0 +leanprover/lean4:v4.35.0 diff --git a/scripts/check-evm-rules-vendor.sh b/scripts/check-evm-rules-vendor.sh new file mode 100755 index 00000000..b2f46017 --- /dev/null +++ b/scripts/check-evm-rules-vendor.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Compare the vendored EvmRules library with a solar checkout's scripts/evm-rules/lean. +# Usage: scripts/check-evm-rules-vendor.sh SOLAR_DIR +set -euo pipefail +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +solar="${1:?usage: check-evm-rules-vendor.sh SOLAR_DIR}" +diff -r "$solar/scripts/evm-rules/lean/EvmRules.lean" "$root/vendor/evm-rules/EvmRules.lean" +diff -r "$solar/scripts/evm-rules/lean/EvmRules" "$root/vendor/evm-rules/EvmRules" +echo "vendor/evm-rules matches $solar" diff --git a/scripts/refinement/FACTS.md b/scripts/refinement/FACTS.md new file mode 100644 index 00000000..90c4f9c4 --- /dev/null +++ b/scripts/refinement/FACTS.md @@ -0,0 +1,58 @@ +# solar's analysis facts in Lean + +`scripts/refinement/facts.sh` checks, in Lean, the dataflow facts solar's optimizer relied on +when it compiled each contract of `scripts/refinement/corpus`. It builds solar and +`tools/prove-analyses` at the commit in `scripts/refinement/prove-rev`, compiles every corpus +contract at `-O gas` with `-Zprove-analyses`, has Z3 prove each recorded fact, and has +`crates/smt/src/certify/lean.rs` translate each proved query into a Lean theorem that +`bv_decide` proves. It writes one module per contract to `SolidCore/Refinement/Facts/`, with +`SolidCore/Refinement/Facts.lean` importing them; `lake build SolidCore.Refinement.Facts` +checks every theorem. `facts.sh --check` regenerates the modules and fails when they differ from +the checked-in ones. `PROVE_TARGET` names a directory holding prebuilt `solar` and +`solar-prove-analyses` binaries of the pinned commit, and `Z3` a Z3 binary. + +## What a theorem says + +A fact is a claim `lhs pred rhs` (`pred` one of `eq`, `ne`, `ult`, `ule`) about two MIR values +at the end of one MIR block, recorded by the pass whose rewrite relied on it: + +- `sccp`: a constant SCCP substituted for a value; +- `check_elim`: a branch, check, overflow test or equality that check elimination decided; +- `cse`: a memory, storage or transient read CSE forwarded from an earlier value; +- `load_pre`: a read load PRE forwarded; +- `indvar_simplify`: the entry bound induction variable simplification relied on. + +The corpus has `check_elim` and `cse` facts only. Each theorem's comment names the contract, +the function, the block, the claim and the query it came from. Its hypotheses are the query's +assertions: the definitions of the values in the blocks that dominate the fact's block, with +EVM word semantics, the branch conditions into them, the facts checked before it (Regehr's +induction: in the first execution that violates a fact, every earlier fact held), and the +fact's negation; its conclusion is `False`. Memory, storage, calls and hashes are +unconstrained functions, and a theorem whose comment names `heap-floor` also assumes the +backend's placement of deferred allocations. A theorem certified in the abstract tier proves a +weaker query, with non-constant multiplication, division and remainder replaced by functions +obeying their laws, which implies the exact one. A fact Z3 or Lean did not prove has a comment +with the reason in place of a theorem. + +The theorems trust `bv_decide`'s LRAT checker as Lean's compiler evaluates it: each theorem +that reaches `bv_decide` depends on its own `._native.bv_decide.ax_*` axiom besides +`propext`, `Classical.choice` and `Quot.sound`. They also trust that the translator renders +the query faithfully and that the query encodes the MIR faithfully. + +## What they do not yet connect to + +The facts are about solar's MIR at `lower-assumes`, in a compile that records them, not about +the runtime bytecode the refinement theorems in `SolidCore/Refinement` are about. Recording +keeps the values a fact is about alive, so a recording compile can optimize slightly +differently from a plain one, and `prove-rev` may name a different commit from `solar-rev`. +Composing the facts with a bytecode refinement needs, at least, a semantics of solar's MIR in +Lean, a proof that each query's assertions hold of every MIR execution reaching the fact's +block (so the theorem gives the fact there), a proof that the optimized MIR, rewritten under +those facts, refines the MIR before the rewrite, and a proof or validation that the backend +compiles that MIR to the bytecode `gen.sh` checks in, from the same commit and without +recording. + +## Commits + +`prove-rev` and `solar-rev` name the same solar commit, so the facts and the bytecode +proofs describe one compile of each contract. Keep them equal when moving either. diff --git a/scripts/refinement/axiom-audit.sh b/scripts/refinement/axiom-audit.sh new file mode 100755 index 00000000..0f35b6a1 --- /dev/null +++ b/scripts/refinement/axiom-audit.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# The axiom pass: elaborates the nine SolidCore/Refinement/Axioms files (one environment can hold +# only one of the w1, w4, c4 and mulx exports, which all declare SolarTV.Export.Main), then +# checks every #print axioms line and greps the files' import closure. Build the libraries first: +# lake -KleanMemory=6000 build SolidCore SolidCoreSolarC4 SolidCoreSolarMulX SolidCoreSolarW4 \ +# SolidCoreSolarBankSource SolidCore.Refinement.Axioms.Audit \ +# ContractsCounter ContractsVC VerifyLoom VerifySpecTrustedBase +set -uo pipefail +cd "$(dirname "$0")/../.." +logs=() closures=() +for part in Main C4 MulX W4 CounterGeneric Contracts Token VerifyCounter Lanes; do + log=.lake/axiom-$part.log + lake env lean -M "${AXIOM_MEMORY:-6000}" "SolidCore/Refinement/Axioms/$part.lean" > "$log" 2>&1 + echo "$part: lean exit $?" + logs+=("$log") + part_lc=$(echo "$part" | tr '[:upper:]' '[:lower:]') + closures+=(".lake/axiom-closure-$part_lc.txt") +done +python3 scripts/refinement/axiom-closure.py "${logs[@]}" -- "${closures[@]}" diff --git a/scripts/refinement/axiom-closure.py b/scripts/refinement/axiom-closure.py new file mode 100755 index 00000000..3d357f43 --- /dev/null +++ b/scripts/refinement/axiom-closure.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""Checks the axiom pass's output and greps its import closure. + +Usage: axiom-closure.py LOG... -- CLOSURE... + +Each LOG is the output of one SolidCore/Refinement/Axioms file; every "depends on axioms" line +must name only propext, Classical.choice and Quot.sound, and no line may report an error or an +axiom violation. Each CLOSURE lists the modules of one file's environment with their sources; the +script strips comments from every source outside the toolchain and Mathlib's ecosystem and greps +it for sorry, native_decide, bv_decide and ofReduceBool, and checks that no SolidCore.Witness +module and no Corpus/C4/SeqPart module is in any closure. + +A grep hit fails the pass unless it is one of KNOWN's, each a vendored or tactic-fallback line +that no audited declaration reaches. That is sound because the grep is a second line of defence: +native_decide closes a goal through an axiom of its own (Lean 4.35 names it +._native.native_decide.ax_*; older Lean used Lean.ofReduceBool) and bv_decide through +Lean.ofReduceBool, and #print axioms and the sweep report every axiom other than propext, +Classical.choice and Quot.sound that a declaration's proof reaches, failing the pass on it. A +known line that is gone also fails the pass, so the list cannot go stale. +""" +import re, sys + +args = sys.argv[1:] +cut = args.index('--') +logs, closures = args[:cut], args[cut + 1:] +ok = True +allowed = {'propext', 'Classical.choice', 'Quot.sound'} +printed = 0 +for log in logs: + text = open(log).read() + for m in re.finditer(r"^'(.+)' depends on axioms: \[([^\]]*)\]", text, re.M): + printed += 1 + axs = {a.strip() for a in m.group(2).split(',') if a.strip()} + if not axs <= allowed: + ok = False + print(f'VIOLATION {log}: {m.group(1)} {sorted(axs)}') + for m in re.finditer(r"^'(.+)' does not depend on any axioms", text, re.M): + printed += 1 + for line in text.splitlines(): + if 'error' in line or 'AXIOM-VIOLATION' in line: + ok = False + print(f'{log}: {line}') + for line in text.splitlines(): + if 'axiom sweep:' in line: + print(f'{log}: {line.split("info: ")[-1]}') +print(f'#print axioms lines: {printed}') + +skip = re.compile(r'/(toolchains|packages/(mathlib|batteries|aesop|Qq|plausible|importGraph|LeanSearchClient|proofwidgets|Cli))/', re.I) +pat = re.compile(r'\bsorry\b|\bnative_decide\b|\bbv_decide\b|\bofReduceBool\b|decide\s*\+\s*native|Lean\.trustCompiler|^\s*axiom\s') + +def strip(src): + out, i, depth, n = [], 0, 0, len(src) + while i < n: + if src.startswith('/-', i): + depth += 1; i += 2; continue + if depth and src.startswith('-/', i): + depth -= 1; i += 2; continue + if depth: + if src[i] == '\n': out.append('\n') + i += 1; continue + if src.startswith('--', i): + j = src.find('\n', i) + i = n if j < 0 else j + continue + if src[i] == '"': + j = i + 1 + while j < n and src[j] != '"': + j += 2 if src[j] == '\\' else 1 + out.append(src[i:j + 1]); i = j + 1; continue + out.append(src[i]); i += 1 + return ''.join(out) + +files = {} +for c in closures: + for line in open(c): + mod, path = line.split() + files.setdefault(path, set()).add(c) + if mod.startswith('SolidCore.Witness') or re.match(r'SolidCore\.Refinement\.Corpus\.C4\.SeqPart', mod): + ok = False + print(f'FORBIDDEN MODULE in {c}: {mod}') + if path == '?': + print(f'note: no source for {mod} in {c}') +# Grep hits allowed by path suffix and stripped line; see the module docstring. +KNOWN = { + # Symex's symex_bv tries the kernel-checked symex_omega first and falls back on bv_decide; + # a proof that took the fallback would depend on Lean.ofReduceBool, which the axiom checks + # above report. + ('SolidCore/Refinement/Evm/Symex.lean', '| bv_decide (config := { enums := false })))'), + # Vendored evmyul: the private lemmas fromBytes'_cons_mod and fromBytes'_cons_div, behind + # EvmYul.zeroPadBytes_toBytes'_fromBytes'_eq_of_length_eq_32 and the zeroPadBytes theorems + # after it, which depend on their EvmYul.fromBytes'_cons_*._native.native_decide.ax_* axioms; + # no audited declaration reaches them (the sweep reports none outside the three axioms). + ('vendor/evmyul/EvmYul/UInt256.lean', 'rw [show 2 ^ 8 = UInt8.size by native_decide]'), +} +seen = set() +scanned = 0 +for path in sorted(files): + if path == '?' or skip.search(path): + continue + scanned += 1 + src = strip(open(path).read()) + for k, line in enumerate(src.splitlines(), 1): + if pat.search(line): + known = next((e for e in KNOWN if path.endswith('/' + e[0]) and line.strip() == e[1]), None) + if known: + seen.add(known) + print(f'known {path}:{k}: {line.strip()[:160]}') + continue + ok = False + print(f'HIT {path}:{k}: {line.strip()[:160]}') +for e in sorted(KNOWN - seen): + ok = False + print(f'STALE known hit, not found: {e[0]}: {e[1]}') +print(f'closure: {len(files)} source files, {scanned} scanned outside the toolchain and Mathlib') +print('AXIOM PASS OK' if ok else 'AXIOM PASS FAILED') +sys.exit(0 if ok else 1) diff --git a/scripts/refinement/bank/bank.sol b/scripts/refinement/bank/bank.sol new file mode 100644 index 00000000..be8994d3 --- /dev/null +++ b/scripts/refinement/bank/bank.sol @@ -0,0 +1,26 @@ +contract Bank { + mapping(address => uint256) balances; + uint256 total; + + event Deposit(address indexed who, uint256 amount); + + function credit(address who, uint256 amount) internal returns (uint256) { + balances[who] += amount; + total += amount; + return balances[who]; + } + + function deposit(uint256 amount) external returns (uint256) { + uint256 b = credit(msg.sender, amount); + emit Deposit(msg.sender, amount); + return b; + } + + function depositFor(address who, uint256 amount) external returns (uint256) { + return credit(who, amount); + } + + function balanceOf(address who) external view returns (uint256) { + return balances[who]; + } +} diff --git a/scripts/refinement/c4/c4.sol b/scripts/refinement/c4/c4.sol new file mode 100644 index 00000000..44d5fc4f --- /dev/null +++ b/scripts/refinement/c4/c4.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { uint8 v; uint8 w = 7; function add(uint8 x) external returns (uint8) { v += x; w ^= x; return v; } } diff --git a/scripts/refinement/certified b/scripts/refinement/certified new file mode 100644 index 00000000..7ca8b558 --- /dev/null +++ b/scripts/refinement/certified @@ -0,0 +1,6 @@ +# Corpus contracts whose generated refinement proofs certified libraries import +# (SolidCore.Refinement.Solar.{C4,W4,Lowering}): gen.sh requires each to be checked by the +# kernel alone. +c4 +w4 +w5 diff --git a/scripts/refinement/check-solar-w1.sh b/scripts/refinement/check-solar-w1.sh new file mode 100755 index 00000000..b88e6fa1 --- /dev/null +++ b/scripts/refinement/check-solar-w1.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Check that the runtime bytecode literal of SolidCore/Refinement/Solar/W1.lean is what solar +# emits for the milestone contract w1, by sha256, and that the recorded sha256 is the literal's. +# +# scripts/refinement/check-solar-w1.sh [path/to/solar] [path/to/w1.sol] +# +# solar must be built at the commit the Lean file names (c7ac11c0); the script prints the +# compiler's version line and fails on any mismatch. +set -euo pipefail +cd "$(dirname "$0")/../.." + +solar=${1:?usage: check-solar-w1.sh SOLAR W1_SOL} +source=${2:?usage: check-solar-w1.sh SOLAR W1_SOL} +lean=SolidCore/Refinement/Solar/W1.lean + +literal=$(sed -n '/^def runtimeHex/{n;s/.*"\([0-9a-f]*\)".*/\1/p}' "$lean") +recorded=$(sed -n 's/^def runtimeSha256 : String := "\([0-9a-f]*\)"/\1/p' "$lean") +"$solar" --version | head -1 +emitted=$("$solar" "$source" -Ogas --evm-version osaka --emit=bin-runtime 2>/dev/null | + python3 -c 'import json,sys; c=json.load(sys.stdin)["contracts"]; print(next(v["bin-runtime"] for k,v in c.items() if k.endswith(":Main")))') + +sha() { python3 -c 'import hashlib,sys; print(hashlib.sha256(bytes.fromhex(sys.argv[1])).hexdigest())' "$1"; } +lit_sha=$(sha "$literal") +out_sha=$(sha "$emitted") +echo "literal sha256 $lit_sha" +echo "recorded sha256 $recorded" +echo "solar sha256 $out_sha" +[[ "$lit_sha" == "$recorded" ]] || { echo "recorded sha256 is not the literal's" >&2; exit 1; } +[[ "$lit_sha" == "$out_sha" ]] || { echo "the literal is not solar's output" >&2; exit 1; } +nat=$(sed -n '/^def runtimeNat/{n;s/^ *0x\([0-9a-f]*\)$/\1/p}' "$lean") +[[ "$nat" == "$literal" ]] || { echo "runtimeNat is not runtimeHex" >&2; exit 1; } +echo "ok: the Lean literal is solar's runtime bytecode for w1" diff --git a/scripts/refinement/check.sh b/scripts/refinement/check.sh new file mode 100755 index 00000000..42a190cd --- /dev/null +++ b/scripts/refinement/check.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Check the refinement of solar's bytecode against SolidCore. +# +# Builds solar at the commit in scripts/refinement/solar-rev, regenerates the +# corpus's bytecode and source files and fails if any differs from the checked-in +# copy, then does the same for solar's analysis facts on the corpus with +# scripts/refinement/facts.sh (solar at scripts/refinement/prove-rev). Finally it +# builds SolidCore.Refinement, which checks every refinement proof, and +# SolidCore.Refinement.Facts, which checks every fact's Lean theorem. +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../.." + +scripts/refinement/gen.sh --check +scripts/refinement/facts.sh --check +lake exe cache get +lake build SolidCore.Refinement +lake build SolidCore.Refinement.Facts diff --git a/scripts/refinement/corpus/b1.sol b/scripts/refinement/corpus/b1.sol new file mode 100644 index 00000000..8fc98ed1 --- /dev/null +++ b/scripts/refinement/corpus/b1.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + uint8 s; + function word() internal view returns (bytes2) { return bytes2(uint16(s)); } + function pick() internal returns (uint256) { s = 7; return 1; } + function f(uint8 x) external returns (bytes1) { s = x; return word()[pick()]; } +} diff --git a/scripts/refinement/corpus/b2.sol b/scripts/refinement/corpus/b2.sol new file mode 100644 index 00000000..1c265979 --- /dev/null +++ b/scripts/refinement/corpus/b2.sol @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + uint8 x; + modifier m(uint8 k) { + if (k == 2) return; + _; + x = k; + } + function f(bool b) external m(b ? 1 : 3) m(2) {} +} diff --git a/scripts/refinement/corpus/b3.sol b/scripts/refinement/corpus/b3.sol new file mode 100644 index 00000000..8ea3c2ed --- /dev/null +++ b/scripts/refinement/corpus/b3.sol @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + bytes1 constant X = bytes1(uint8(255) + uint8(1)); + function f(bool b) external pure returns (uint256) { + if (b) return X.length; + return 3; + } +} diff --git a/scripts/refinement/corpus/b4.sol b/scripts/refinement/corpus/b4.sol new file mode 100644 index 00000000..89c79450 --- /dev/null +++ b/scripts/refinement/corpus/b4.sol @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + struct S { uint8 x; } + function make(uint8 a) internal pure returns (S memory) { return S(a + 1); } + function f(uint8 a) external pure returns (uint8) { + unchecked { return make(a).x; } + } +} diff --git a/scripts/refinement/corpus/b5.sol b/scripts/refinement/corpus/b5.sol new file mode 100644 index 00000000..21553016 --- /dev/null +++ b/scripts/refinement/corpus/b5.sol @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + uint8[] v; + function push() internal returns (uint8) { v.push(7); return 1; } + function f(bool b) external returns (uint256) { + delete v; + if (b) { + (uint8[] memory c, uint8 m) = (v, push()); + return c.length + m; + } + return v.length; + } +} diff --git a/scripts/refinement/corpus/b6.sol b/scripts/refinement/corpus/b6.sol new file mode 100644 index 00000000..12189e3b --- /dev/null +++ b/scripts/refinement/corpus/b6.sol @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + struct S { uint8[] a; uint8 m; } + uint8[] v; + function push() internal returns (uint8) { v.push(7); return 1; } + function f(bool b) external returns (uint256) { + delete v; + if (b) { + S memory s = S(v, push()); + return s.a.length + s.m; + } + return v.length; + } +} diff --git a/scripts/refinement/corpus/b7.sol b/scripts/refinement/corpus/b7.sol new file mode 100644 index 00000000..6a874dd5 --- /dev/null +++ b/scripts/refinement/corpus/b7.sol @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + uint8[] v; + function push() internal returns (uint8) { v.push(7); return 1; } + function pair() internal returns (uint8[] memory, uint8) { return (v, push()); } + function f(bool b) external returns (uint256) { + delete v; + if (b) { + (uint8[] memory c, uint8 m) = pair(); + return c.length + m; + } + return v.length; + } +} diff --git a/scripts/refinement/corpus/c1.sol b/scripts/refinement/corpus/c1.sol new file mode 100644 index 00000000..f3b97af5 --- /dev/null +++ b/scripts/refinement/corpus/c1.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +// refinement: shape=kernel +contract Main { + function f(uint8 x) external pure returns (uint8) { + return x * 3 + 1; + } +} diff --git a/scripts/refinement/corpus/c10.sol b/scripts/refinement/corpus/c10.sol new file mode 100644 index 00000000..94908b4e --- /dev/null +++ b/scripts/refinement/corpus/c10.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { function f(uint8 c) external pure returns (bytes32) { return bytes32(bytes2(0x1234) >> c); } } diff --git a/scripts/refinement/corpus/c11.sol b/scripts/refinement/corpus/c11.sol new file mode 100644 index 00000000..f5372167 --- /dev/null +++ b/scripts/refinement/corpus/c11.sol @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +type U is int8; +contract Main { function f(uint8 x) external pure returns (U) { return U.wrap(int8(x)); } } diff --git a/scripts/refinement/corpus/c2.sol b/scripts/refinement/corpus/c2.sol new file mode 100644 index 00000000..46676995 --- /dev/null +++ b/scripts/refinement/corpus/c2.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { function f(int8 a, int8 b) external pure returns (int8, int8) { return (a / b, a % b); } } diff --git a/scripts/refinement/corpus/c3.sol b/scripts/refinement/corpus/c3.sol new file mode 100644 index 00000000..5d6e6db5 --- /dev/null +++ b/scripts/refinement/corpus/c3.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { function f(uint8 x, uint8 s) external pure returns (uint8, uint8, uint8, int8) { unchecked { return (x << s, x >> s, x * x, int8(x) >> (s % 9)); } } } diff --git a/scripts/refinement/corpus/c4.sol b/scripts/refinement/corpus/c4.sol new file mode 100644 index 00000000..cf51d370 --- /dev/null +++ b/scripts/refinement/corpus/c4.sol @@ -0,0 +1,4 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +// refinement: route=symbolic shape=kernel +contract Main { uint8 v; uint8 w = 7; function add(uint8 x) external returns (uint8) { v += x; w ^= x; return v; } } diff --git a/scripts/refinement/corpus/c5.sol b/scripts/refinement/corpus/c5.sol new file mode 100644 index 00000000..eb5b857e --- /dev/null +++ b/scripts/refinement/corpus/c5.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { mapping(uint8 => uint16) m; function inc(uint8 k) external returns (uint16) { m[k] += 300; m[k ^ 1] = k; return m[k]; } } diff --git a/scripts/refinement/corpus/c6.sol b/scripts/refinement/corpus/c6.sol new file mode 100644 index 00000000..ed0836f2 --- /dev/null +++ b/scripts/refinement/corpus/c6.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { function sum(uint8 n) external pure returns (uint256 s, uint256 c) { for (uint256 i = 0; i < n; i++) { if (i % 7 == 3) continue; s += i * i; c++; if (s > 100000) break; } } } diff --git a/scripts/refinement/corpus/c7.sol b/scripts/refinement/corpus/c7.sol new file mode 100644 index 00000000..4866d2de --- /dev/null +++ b/scripts/refinement/corpus/c7.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { enum E { A, B, C } function f(E e, bool b) external pure returns (uint8, bool) { return (uint8(e) * 2, b != (e == E.B)); } } diff --git a/scripts/refinement/corpus/c8.sol b/scripts/refinement/corpus/c8.sol new file mode 100644 index 00000000..734e4ecf --- /dev/null +++ b/scripts/refinement/corpus/c8.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { function fib(uint8 n) internal pure returns (uint256) { return n < 2 ? n : fib(n - 1) + fib(n - 2); } modifier m(uint8 x) { require(x < 25, "big"); _; } function f(uint8 x) external pure m(x) returns (uint256) { return fib(x % 13); } } diff --git a/scripts/refinement/corpus/c9.sol b/scripts/refinement/corpus/c9.sol new file mode 100644 index 00000000..866a0526 --- /dev/null +++ b/scripts/refinement/corpus/c9.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { uint256[] a; function g() internal returns (uint256) { a.push(5); return 1; } function f(uint8 x) external returns (uint256, uint256) { a.push(x); uint256[] memory m = new uint256[](3); m[g()] = x; return (a.length, m[1]); } } diff --git a/scripts/refinement/corpus/d1.sol b/scripts/refinement/corpus/d1.sol new file mode 100644 index 00000000..49214aec --- /dev/null +++ b/scripts/refinement/corpus/d1.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { function f(bytes calldata b) external pure returns (uint256) { return b.length; } } diff --git a/scripts/refinement/corpus/d2.sol b/scripts/refinement/corpus/d2.sol new file mode 100644 index 00000000..07ad1065 --- /dev/null +++ b/scripts/refinement/corpus/d2.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { function f(uint8[] calldata a) external pure returns (uint256) { return a.length == 0 ? 0 : a[0]; } } diff --git a/scripts/refinement/corpus/d3.sol b/scripts/refinement/corpus/d3.sol new file mode 100644 index 00000000..4e12bf45 --- /dev/null +++ b/scripts/refinement/corpus/d3.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { struct S { uint8 x; bool y; } function f(S calldata s) external pure returns (uint256) { return s.y ? s.x : 3; } } diff --git a/scripts/refinement/corpus/d4.sol b/scripts/refinement/corpus/d4.sol new file mode 100644 index 00000000..e0ce5432 --- /dev/null +++ b/scripts/refinement/corpus/d4.sol @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { struct S { uint8 x; bool y; } function f(S calldata s) external pure returns (S calldata) { return s; } } diff --git a/scripts/refinement/corpus/w1.sol b/scripts/refinement/corpus/w1.sol new file mode 100644 index 00000000..cd337362 --- /dev/null +++ b/scripts/refinement/corpus/w1.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +// refinement: shape=kernel +contract Main { + function f(uint256 x) external pure returns (uint256) { + return x + 1; + } +} diff --git a/scripts/refinement/corpus/w2.sol b/scripts/refinement/corpus/w2.sol new file mode 100644 index 00000000..d443bae4 --- /dev/null +++ b/scripts/refinement/corpus/w2.sol @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + function f(uint256 a, uint256 b) external pure returns (uint256) { + return a > b ? a - b : b - a; + } +} diff --git a/scripts/refinement/corpus/w3.sol b/scripts/refinement/corpus/w3.sol new file mode 100644 index 00000000..a81b574b --- /dev/null +++ b/scripts/refinement/corpus/w3.sol @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + function f(address a) external pure returns (uint160) { + return uint160(a) ^ 1; + } +} diff --git a/scripts/refinement/corpus/w4.sol b/scripts/refinement/corpus/w4.sol new file mode 100644 index 00000000..bfaa9548 --- /dev/null +++ b/scripts/refinement/corpus/w4.sol @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +// refinement: shape=kernel +contract Main { + uint256 x; + function set(uint256 v) external { + x = v; + } +} diff --git a/scripts/refinement/corpus/w5.sol b/scripts/refinement/corpus/w5.sol new file mode 100644 index 00000000..0e8f6833 --- /dev/null +++ b/scripts/refinement/corpus/w5.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +// refinement: solar-flags=-Ogas shape=kernel +contract Main { + function f(uint256 a, uint256 b) external pure returns (uint256) { + return a + b; + } +} diff --git a/scripts/refinement/counter/counter.sol b/scripts/refinement/counter/counter.sol new file mode 100644 index 00000000..0159f465 --- /dev/null +++ b/scripts/refinement/counter/counter.sol @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Counter { + uint256 x; + function inc(uint256 d) external { x += d; } + function get() external view returns (uint256) { return x; } +} diff --git a/scripts/refinement/events/events.sol b/scripts/refinement/events/events.sol new file mode 100644 index 00000000..cb5412f7 --- /dev/null +++ b/scripts/refinement/events/events.sol @@ -0,0 +1,7 @@ +contract Events { + event Transfer(address indexed from, uint256 indexed id, uint256 value); + + function transfer(uint256 id, uint256 value) external { + emit Transfer(msg.sender, id, value); + } +} diff --git a/scripts/refinement/facts.sh b/scripts/refinement/facts.sh new file mode 100755 index 00000000..aebc5992 --- /dev/null +++ b/scripts/refinement/facts.sh @@ -0,0 +1,254 @@ +#!/usr/bin/env bash +# Check solar's dataflow facts on the refinement corpus in Lean. +# +# scripts/refinement/facts.sh rewrite SolidCore/Refinement/Facts/*.lean +# scripts/refinement/facts.sh --check the same, then fail if any generated file changed +# +# solar records, with -Zprove-analyses, every fact an optimization relied on (an +# SCCP constant, a check that check elimination dropped, a read that CSE or load +# PRE forwarded, an induction variable bound) at the end of a MIR block, and +# writes each as an SMT-LIB query whose assertions are contradictory exactly when +# the fact holds on every execution the query encodes. tools/prove-analyses runs +# Z3 on the queries and, with --certify-lean, translates each proved one with +# crates/smt/src/certify/lean.rs into a Lean theorem that the query's assertions +# imply False, proved by bv_decide, and checks it with Lean. +# +# This script builds solar and tools/prove-analyses at the commit in +# scripts/refinement/prove-rev into PROVE_DIR (default .cache/solar-prove), or +# takes both binaries from the directory PROVE_TARGET, runs them over every +# scripts/refinement/corpus/*.sol at -O gas (solar's default, which gen.sh +# compiles with), and collects the translator's theorems, unchanged but for +# their names and the preamble they share, into +# SolidCore/Refinement/Facts/NAME.lean one module per corpus contract +# SolidCore/Refinement/Facts/Prelude.lean the translator's store function +# SolidCore/Refinement/Facts.lean the root importing them +# A fact Z3 or Lean did not prove gets a comment with the reason instead of a +# theorem. Z3 comes from its pinned release, checked against its SHA-256, unless +# Z3 names a binary; Lean is the repository's toolchain. +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../.." + +check=0 +[[ "${1-}" == "--check" ]] && check=1 + +rev="$(tr -d '[:space:]' < scripts/refinement/prove-rev)" +prove_dir="${PROVE_DIR:-.cache/solar-prove}" + +if [[ -z "${PROVE_TARGET-}" ]]; then + if [[ ! -d "$prove_dir/.git" ]]; then + git init -q "$prove_dir" + git -C "$prove_dir" remote add origin https://github.com/paradigmxyz/solar.git + fi + git -C "$prove_dir" fetch -q --depth 1 origin "$rev" + git -C "$prove_dir" checkout -q --detach "$rev" + cargo build --release --locked --manifest-path "$prove_dir/Cargo.toml" \ + -p solar-compiler --bin solar + cargo build --release --locked --manifest-path "$prove_dir/Cargo.toml" \ + -p solar-prove-analyses + PROVE_TARGET="$prove_dir/target/release" +fi +solar="$PROVE_TARGET/solar" +prover="$PROVE_TARGET/solar-prove-analyses" + +version="$("$solar" --version | head -n 1)" +if [[ "$version" != *"${rev:0:8}"* ]]; then + echo "error: $solar reports '$version', not commit $rev" >&2 + exit 1 +fi + +z3_version=4.15.4 +z3_sha256=a41b690e89c343931471506cdc6d957b6044a200fd2d240cc017432afdff7d3e +if [[ -z "${Z3-}" ]]; then + Z3=".cache/z3-$z3_version-x64-glibc-2.39/bin/z3" + if [[ ! -x "$Z3" ]]; then + mkdir -p .cache + curl -fsSL -o .cache/z3.zip.tmp \ + "https://github.com/Z3Prover/z3/releases/download/z3-$z3_version/z3-$z3_version-x64-glibc-2.39.zip" + echo "$z3_sha256 .cache/z3.zip.tmp" | sha256sum -c --quiet + (cd .cache && unzip -q -o z3.zip.tmp && rm z3.zip.tmp) + fi +fi + +# Z3's limits are resource counts, so its verdicts do not depend on machine load. +# The limit and memory for a query proved alone are above the tool's defaults, +# which c6's loop needs. +# The compiler runs in each source's directory, so the paths it gets are absolute. +run="$(realpath -m "${FACTS_RUN_DIR:-.cache/facts-run}")" +rm -rf "$run" +"$prover" --solar "$solar" --z3 "$Z3" --levels gas \ + --rlimit 400000000 --memory 8000 --timeout 300 --jobs "${FACTS_JOBS:-2}" \ + --certify-lean --lean "$(command -v lean)" --lean-project "$PWD" --certify-timeout 600 \ + --out "$run" scripts/refinement/corpus >&2 + +out=SolidCore/Refinement/Facts +rm -rf "$out" +mkdir -p "$out" +python3 - "$run/results.jsonl" "$out" "$rev" "$version" <<'EOF' +import json, os, re, sys, textwrap + +results, out, rev, version = sys.argv[1:] +# What the translator writes before each theorem. +STORE = """def store {a b : Nat} (m : BitVec a → BitVec b) (i : BitVec a) (v : BitVec b) : + BitVec a → BitVec b := + fun j => if j = i then v else m j +""" +OPTIONS = """set_option maxHeartbeats 0 +set_option maxRecDepth 100000 +set_option linter.unusedVariables false +""" +PREAMBLE = "import Std.Tactic.BVDecide\n\n" + STORE + "\n" + OPTIONS + "\n" +KINDS = { + "sccp": "a constant SCCP substituted for a value", + "check_elim": "a branch, check, overflow test or equality that check elimination decided", + "cse": "a memory, storage or transient read CSE forwarded from an earlier value", + "load_pre": "a read load PRE forwarded from the values reaching it", + "indvar_simplify": "the entry bound induction variable simplification relied on", +} +QUERY = re.compile( + r"^(?P.+)-f(?P\d+)-bb(?P\d+)-(?P[^-]+)-(?P[a-z_]+)-(?P\d+)\.smt2$" +) + +records = [json.loads(line) for line in open(results)] +if not records: + sys.exit("error: the prover recorded no facts; did the compiles fail?") +corpus = sorted( + (f for f in os.listdir("scripts/refinement/corpus") if f.endswith(".sol")), + key=lambda f: (len(f), f), +) +by_source = {name: [] for name in corpus} +for r in records: + by_source[os.path.basename(r["source"])].append(r) + + +def parts(r): + return QUERY.match(os.path.basename(r["query"])) + + +def comment(text, prefix): + text = text.replace("-/", "- /").replace("/-", "/ -") + return textwrap.fill(prefix + text, width=100, break_long_words=False, break_on_hyphens=False) + + +modules = [] +for name in corpus: + module = name[0].upper() + name[1:-4] + modules.append(module) + facts = sorted(by_source[name], key=lambda r: (int(parts(r)["fid"]), int(parts(r)["index"]))) + proved = [r for r in facts if r["result"] == "unsat"] + checked = [r for r in facts if r.get("certificate") == "checked-lean"] + kinds = sorted({parts(r)["kind"] for r in facts}) + lines = [ + "-- Generated by scripts/refinement/facts.sh. Do not edit.", + f"-- Source: scripts/refinement/corpus/{name}", + f"-- solar: {version}", + f"-- solar commit: {rev}", + "", + "import SolidCore.Refinement.Facts.Prelude", + "", + "/-!", + f"# solar's analysis facts for `{name}`", + "", + "Each theorem is the Lean translation, by solar's `crates/smt/src/certify/lean.rs`, of the", + "query `-Zprove-analyses` writes for one fact an optimization relied on in contract", + "`Main`, compiled at `-O gas`: the definitions of the values in the blocks that", + "dominate the fact's program point, with EVM word semantics, the branch conditions into", + "them and the facts checked before it, together with the fact's negation, imply `False`.", + "They are facts about solar's MIR at `lower-assumes`, not about the runtime bytecode.", + "", + f"Facts recorded: {len(facts)}. Proved by Z3: {len(proved)}. Checked in Lean by the prover and", + f"emitted here: {len(checked)}.", + "", + "Fact kinds in this module:", + ] + for kind in kinds: + lines.append(f"- `{kind}`: {KINDS.get(kind, kind)}.") + if not kinds: + lines.append("- none: no optimization of this contract relied on a recorded fact.") + lines += ["-/", "", OPTIONS, f"namespace SolidCore.Refinement.Facts.{module}", ""] + for r in facts: + q = os.path.basename(r["query"]) + m = parts(r) + function = r.get("function", "") + fname = re.sub(r"[^A-Za-z0-9_]", "_", function.split(" ", 1)[-1]) + ident = f"f{m['fid']}_{fname}_bb{m['bb']}_{m['lhs']}_{m['kind']}_{m['index']}" + about = [ + f"Contract `Main`, function `{function}`, fact {m['index']}:", + f"`{r.get('claim', '')}`, its left operand defined by `{r.get('definition', '')}`.", + f"Query `{q}`.", + ] + if r.get("axioms"): + about.append(f"The query assumes the backend axioms `{r['axioms']}`.") + if r.get("opaque"): + about.append(f"Its goal depends on the unconstrained values `{r['opaque']}`.") + if r.get("certificate") != "checked-lean": + reason = r["result"] + if r.get("counterexample"): + reason += f", Z3 model {r['counterexample']}" + for field in ("certificate", "lean_certificate"): + if r.get(field): + reason += f", {r[field]}" + about.append(f"Not proved: {reason}.") + lines.append(comment(" ".join(about), f"/- Not emitted: {ident}. ") + " -/") + lines.append("") + continue + tier = r.get("certified_tier", "exact") + if tier == "abstract": + about.append( + "Certified in the query's abstract tier, which replaces non-constant " + "multiplication, division and remainder by functions obeying their laws, " + "so it implies the exact query." + ) + stem = r["query"][: -len(".smt2")] + lean = open(stem + (".abstract" if tier == "abstract" else "") + ".lean").read() + if not lean.startswith(PREAMBLE): + sys.exit(f"error: {stem}.lean: unexpected preamble from the translator") + body, _, tail = lean[len(PREAMBLE):].partition("\n#print axioms query\n") + if tail.strip() or not body.startswith("theorem query "): + sys.exit(f"error: {stem}.lean: unexpected theorem from the translator") + lines.append(comment(" ".join(about), "/-- ") + " -/") + lines.append("theorem " + ident + body[len("theorem query"):].rstrip("\n")) + lines.append("") + lines += [f"end SolidCore.Refinement.Facts.{module}", ""] + with open(f"{out}/{module}.lean", "w") as f: + f.write("\n".join(lines)) + print( + f"scripts/refinement/corpus/{name}: {len(facts)} facts, {len(proved)} proved, " + f"{len(checked)} emitted -> {out}/{module}.lean" + ) + +with open(f"{out}/Prelude.lean", "w") as f: + f.write( + "-- Generated by scripts/refinement/facts.sh. Do not edit.\n\n" + "import Std.Tactic.BVDecide\n\n" + "/-! The definitions shared by the theorems solar's Lean translator writes. -/\n\n" + "namespace SolidCore.Refinement.Facts\n\n" + "/-- An SMT-LIB array `store`: `m` with index `i` mapped to `v`. -/\n" + + STORE + + "\nend SolidCore.Refinement.Facts\n" + ) +root = ["-- Generated by scripts/refinement/facts.sh. Do not edit.", ""] +root += [f"import SolidCore.Refinement.Facts.{m}" for m in modules] +root += [ + "", + "/-!", + "# solar's analysis facts on the refinement corpus", + "", + "One module per `scripts/refinement/corpus` contract, each theorem one recorded MIR fact;", + "see `scripts/refinement/FACTS.md` for what they mean.", + "-/", + "", +] +with open(f"{out}.lean", "w") as f: + f.write("\n".join(root)) +EOF + +if (( check )); then + if ! git diff --exit-code -- "$out" "$out.lean"; then + echo "error: generated facts differ from the checked-in files; run scripts/refinement/facts.sh" >&2 + exit 1 + fi + if [[ -n "$(git ls-files --others --exclude-standard -- "$out" "$out.lean")" ]]; then + echo "error: untracked generated files in $out" >&2 + exit 1 + fi +fi diff --git a/scripts/refinement/gen.sh b/scripts/refinement/gen.sh new file mode 100755 index 00000000..f3e1e1f1 --- /dev/null +++ b/scripts/refinement/gen.sh @@ -0,0 +1,197 @@ +#!/usr/bin/env bash +# Regenerate the refinement corpus bytecode from solar at a pinned commit. +# +# scripts/refinement/gen.sh rewrite SolidCore/Refinement/{Bytecode,Source}/*.lean +# scripts/refinement/gen.sh --check the same, then fail if any generated file changed +# +# Each scripts/refinement/corpus/NAME.sol holds one contract named Main. For +# each, the script writes +# SolidCore/Refinement/Bytecode/NAME.lean solar's runtime bytecode and selectors +# SolidCore/Refinement/Source/NAME.lean the SolidCore source AST, through +# scripts/solc_ast_to_lean_source.py +# SolidCore/Refinement/Corpus/NAME*.lean the refinement proof of each name in +# scripts/refinement/kept, through +# scripts/refinement/gen_proof.py +# and SolidCore/Refinement/Corpus.lean imports every proof. A line +# "// refinement: solar-flags=F1,F2" in a source passes F1 and F2 to solar; the +# bytecode file then records the flags and the runtime's SHA-256. +# +# The names in scripts/refinement/certified (the corpus contracts that certified libraries +# import) must get a proof the kernel checks alone, without native_decide or bv_decide: +# gen_proof.py refuses their fallbacks and scripts/refinement/kernel_only.py checks the +# written modules. +# +# scripts/refinement/solar-rev names the paradigmxyz/solar commit, built here +# with cargo into SOLAR_DIR (default .cache/solar). SOLAR_BIN skips the build and +# uses that binary instead, which must report the pinned commit. The source AST +# comes from solc 0.8.35, downloaded and checked against its SHA-256 unless SOLC +# names a binary. +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../.." + +check=0 +[[ "${1-}" == "--check" ]] && check=1 + +rev="$(tr -d '[:space:]' < scripts/refinement/solar-rev)" +solar_dir="${SOLAR_DIR:-.cache/solar}" + +if [[ -z "${SOLAR_BIN-}" ]]; then + if [[ ! -d "$solar_dir/.git" ]]; then + git init -q "$solar_dir" + git -C "$solar_dir" remote add origin https://github.com/paradigmxyz/solar.git + fi + git -C "$solar_dir" fetch -q --depth 1 origin "$rev" + git -C "$solar_dir" checkout -q --detach "$rev" + cargo build --release --locked --manifest-path "$solar_dir/Cargo.toml" --bin solar + SOLAR_BIN="$solar_dir/target/release/solar" +fi + +version="$("$SOLAR_BIN" --version | head -n 1)" +if [[ "$version" != *"${rev:0:7}"* ]]; then + echo "error: $SOLAR_BIN reports '$version', not commit $rev" >&2 + exit 1 +fi + +solc_version=0.8.35 +solc_sha256=fa8ac9a32d301ad023a36ee5a29f8e291fe3200c60244e43c142539e82a617f4 +if [[ -z "${SOLC-}" ]]; then + SOLC=".cache/solc-$solc_version" + if [[ ! -x "$SOLC" ]]; then + mkdir -p .cache + curl -fsSL -o "$SOLC.tmp" \ + "https://github.com/argotorg/solidity/releases/download/v$solc_version/solc-static-linux" + echo "$solc_sha256 $SOLC.tmp" | sha256sum -c --quiet + chmod +x "$SOLC.tmp" + mv "$SOLC.tmp" "$SOLC" + fi +fi + +out=SolidCore/Refinement/Bytecode +src_out=SolidCore/Refinement/Source +proof_out=SolidCore/Refinement/Corpus +rm -rf "$proof_out" +mkdir -p "$out" "$src_out" "$proof_out" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +proved=() +for sol in scripts/refinement/corpus/*.sol; do + name="$(basename "$sol" .sol)" + module="$(echo "${name:0:1}" | tr '[:lower:]' '[:upper:]')${name:1}" + # A line "// refinement: solar-flags=F1,F2" passes F1 and F2 to solar. + solar_flags=() + flags_line="$(sed -n 's|^//[[:space:]]*refinement:.*solar-flags=\([^[:space:]]*\).*$|\1|p' "$sol" | head -n 1)" + if [[ -n "$flags_line" ]]; then + IFS=, read -r -a solar_flags <<< "$flags_line" + fi + json="$("$SOLAR_BIN" ${solar_flags[@]+"${solar_flags[@]}"} --emit bin-runtime,hashes --no-warnings "$sol")" + python3 - "$json" "$name" "$module" "$rev" "$version" "$sol" "${solar_flags[*]-}" > "$out/$module.lean" <<'EOF' +import hashlib, json, sys +blob, name, module, rev, version, sol, flags = sys.argv[1:] +contracts = json.loads(blob)["contracts"] +lines = [ + "-- Generated by scripts/refinement/gen.sh. Do not edit.", + f"-- Source: {sol}", + f"-- solar: {version}", + f"-- solar commit: {rev}", +] +if flags: + lines += [f"-- solar flags: {flags}"] +lines += [ + "", + f"namespace SolidCore.Refinement.Bytecode.{module}", + "", + f'def solarRev : String := "{rev}"', +] +for key in sorted(contracts): + c = contracts[key] + cname = key.rsplit(":", 1)[1] + code = c["bin-runtime"] + lines += [ + "", + f"/-- Runtime bytecode of `{cname}` as solar emits it, read big-endian. -/", + f"def {cname}.runtimeNat : Nat :=", + f" 0x{code}", + "", + f"/-- Length of `{cname}`'s runtime bytecode in bytes. -/", + f"def {cname}.runtimeSize : Nat := {len(code) // 2}", + ] + if flags: + digest = hashlib.sha256(bytes.fromhex(code)).hexdigest() + lines += [ + "", + f"/-- SHA-256 of `{cname}`'s runtime bytecode, from solar with `{flags}`. -/", + f'def {cname}.runtimeSha256 : String := "{digest}"', + ] + for sig, sel in sorted((c.get("hashes") or {}).items()): + ident = sig.split("(")[0] + lines += [ + "", + f"/-- Selector of `{sig}`. -/", + f"def {cname}.{ident}Selector : Nat := 0x{sel}", + ] +lines += ["", f"end SolidCore.Refinement.Bytecode.{module}", ""] +sys.stdout.write("\n".join(lines)) +EOF + { + echo "-- Generated by scripts/refinement/gen.sh from $sol with solc $solc_version. Do not edit." + echo + echo "import SolidCore.Solidity.Checked" + echo + echo "open SolidCore.Solidity" + echo + python3 scripts/solc_ast_to_lean_source.py "$sol" --contract Main --solc "$SOLC" \ + --namespace "SolidCore.Refinement.Source.$module" --body-only \ + | sed "s|^def importedSourceName : String := .*$|def importedSourceName : String := \"$sol\"|" + } > "$src_out/$module.lean" + echo "$sol -> $out/$module.lean, $src_out/$module.lean" + # Only the names in scripts/refinement/kept get a committed proof; the rest stop at bytecode + # and source. + if ! grep -qx "$name" scripts/refinement/kept; then + if grep -qx "$name" scripts/refinement/certified; then + echo "error: $sol is certified but not in scripts/refinement/kept" >&2 + exit 1 + fi + continue + fi + "$SOLAR_BIN" ${solar_flags[@]+"${solar_flags[@]}"} --emit abi,hashes --no-warnings "$sol" > "$tmp/solar.json" + "$SOLC" --combined-json ast "$sol" > "$tmp/ast.json" + # A name in scripts/refinement/certified must get a proof the kernel checks alone. + certified=0 + grep -qx "$name" scripts/refinement/certified && certified=1 + status=0 + REFINEMENT_CERTIFIED=$certified python3 scripts/refinement/gen_proof.py "$name" "$module" \ + "$tmp/solar.json" "$tmp/ast.json" "$sol" || status=$? + if (( status == 0 )); then + proved+=("$module") + if (( certified )); then + python3 scripts/refinement/kernel_only.py "SolidCore.Refinement.Corpus.$module" + fi + elif (( status != 3 )); then + exit "$status" + elif (( certified )); then + echo "error: $sol is certified but gets no proof" >&2 + exit 1 + fi +done + +{ + echo "-- Generated by scripts/refinement/gen.sh. Do not edit." + echo + for module in "${proved[@]}"; do + echo "import SolidCore.Refinement.Corpus.$module" + done + echo + echo "/-! The refinement proofs of every contract in scripts/refinement/corpus/. -/" +} > "$proof_out.lean" + +if (( check )); then + if ! git diff --exit-code -- "$out" "$src_out" "$proof_out" "$proof_out.lean"; then + echo "error: generated bytecode differs from the checked-in files; run scripts/refinement/gen.sh" >&2 + exit 1 + fi + if [[ -n "$(git ls-files --others --exclude-standard -- "$out" "$src_out" "$proof_out")" ]]; then + echo "error: untracked generated files in $out, $src_out or $proof_out" >&2 + exit 1 + fi +fi + diff --git a/scripts/refinement/gen_proof.py b/scripts/refinement/gen_proof.py new file mode 100755 index 00000000..afc3175d --- /dev/null +++ b/scripts/refinement/gen_proof.py @@ -0,0 +1,1305 @@ +#!/usr/bin/env python3 +"""Write the refinement proof modules of one corpus contract. + + gen_proof.py NAME MODULE SOLAR_JSON SOLC_AST_JSON SOURCE + +SOLAR_JSON is solar's --emit abi,hashes output for the contract and +SOLC_AST_JSON solc's --combined-json ast output, which names the members of +each enum. The script writes, under SolidCore/Refinement/Corpus/: + + MODULE/Defs.lean the code, the checked contract, its functions, the scope + MODULE/PartI.lean one native_decide check of every PARTS-th call + MODULE/Dirty.lean EthLib rejects every dirty argument word (symbolic, dirty_symex) + MODULE.lean the refinement theorems: on clean words, then on every word + MODULE/SeqStates.lean the storages clean calls reach, found by Seq.explore + MODULE/SeqDefs.lean the sequence certificate and its dirty-call check + MODULE/SeqPartI.lean one native_decide check of every PARTS-th certificate call + MODULE/Seq.lean the refinement on sequences of calls + +and SolidCore/Refinement/Seq/Corpus.lean, which imports every MODULE/Seq.lean. +For a contract with a function that is neither pure nor view, the sequence +certificate comes from running SolidCore.Refinement.Seq.explore through lake, +so MODULE/Defs.lean must build. + +Every parameter must have a small ABI type (uintN or intN with N <= 16, bool or +an enum): the scope is every call with clean argument words, so it must be +finite and small. A contract with a wide parameter (uintN or intN with N > 16, +address or bytesN) instead gets a symbolic proof, written by gen_wide below into +MODULE.lean alone: SolidCore's interpreter and solar's bytecode both run on free +argument words (SolidCore.Refinement.Wide). It needs the contract's constructor to +leave no storage and no logs, and a function that is not pure or view to write at +most one slot on each path. It builds SolidCore.Refinement.Source.MODULE with lake +and prints SolidCore's core contract through Lean, which the proof checks against +SolidCore's own in the kernel (kernel_rfl, below). A contract with any other parameter gets no +proof, and the script says so and exits 3. + +A contract with a dynamic or struct parameter (bytes, an array of a small type, a +struct of small types) gets a proof on SolidCore.Refinement.Dyn.dynScope, written by +gen_dyn: MODULE/Defs.lean and MODULE/PartI.lean check every canonical encoding within +the bounds by native_decide, MODULE/Malformed.lean proves EthLib rejects malformed call +data by dyn_symex, and MODULE.lean states refines_full. A line +"// refinement: bytes=N array=M" sets the bounds on the length of a bytes argument and +of an array (default 2 each). + +A line "// refinement: fuel=N" in the source sets SolidCore's fuel (default 4096). +Every symbolic proof learns that SolidCore's checked core is the printed literal coreLit +by one kernel conversion check (kernel_rfl shape_eq, SolidCore.Refinement.KernelRfl), on +copies of the type checker that read each function's selector from a table +(selectorTable): selector_eq, from one kernel_rfl check of each selector by Keccak-256 +against the bytecode file's, which solc's AST functionSelector confirms. No Bool +recognizer of coreLit is generated: its match on the whole literal and split cost +gigabytes. "// refinement: shape=kernel" also proves a small symbolic contract's dirty +shapeOk in the kernel; without it, that check is native_decide. +gen.sh reads "// refinement: solar-flags=F1,F2" and passes the flags to solar. +""" +import json +import math +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +CALLS_PER_PART = 4096 +MAX_CALLS = 1 << 17 + +name, module, solar_json, ast_json, source = sys.argv[1:] +contracts = json.loads(Path(solar_json).read_text())["contracts"] +main = next(c for k, c in contracts.items() if k.rsplit(":", 1)[1] == "Main") +abi = main["abi"] +if isinstance(abi, str): + abi = json.loads(abi) + +enums = {} +for unit in json.loads(Path(ast_json).read_text())["sources"].values(): + stack = [unit["AST"]] + while stack: + node = stack.pop() + if isinstance(node, dict): + if node.get("nodeType") == "EnumDefinition": + enums[node["canonicalName"]] = len(node["members"]) + stack.extend(node.values()) + elif isinstance(node, list): + stack.extend(node) + +fuel = 4096 +m = re.search(r"//\s*refinement:\s*fuel=(\d+)", Path(source).read_text()) +if m: + fuel = int(m.group(1)) + +# "// refinement: shape=kernel" has the kernel check a small symbolic contract's dirty shapeOk +# (kernel_rfl) instead of native_decide. Every contract's core shape is the kernel's. +kernel_shape = re.search(r"//\s*refinement:.*\bshape=kernel\b", Path(source).read_text()) is not None +# A certified contract (REFINEMENT_CERTIFIED=1, which gen.sh sets for the names in +# scripts/refinement/certified) must be proved by the kernel alone: no native_decide or +# bv_decide fallback, so it needs "// refinement: shape=kernel". gen.sh then checks the +# written modules with scripts/refinement/kernel_only.py. +if os.environ.get("REFINEMENT_CERTIFIED") == "1" and not kernel_shape: + sys.exit(f"{source}: a certified contract needs '// refinement: shape=kernel'; without it " + "the shape check falls back to native_decide") + + +# Each function's selector as solc's AST gives it (functionSelector), by name, for the +# contract Main: the check of solar's signatures in selector_block. +solc_selectors = {} +for unit in json.loads(Path(ast_json).read_text())["sources"].values(): + for node in unit["AST"].get("nodes", []): + if node.get("nodeType") == "ContractDefinition" and node.get("name") == "Main": + for member in node.get("nodes", []): + if "functionSelector" in member: + solc_selectors[member["name"]] = member["functionSelector"] + + +def param(p): + internal = p.get("internalType", "") + if internal.startswith("enum "): + n = enums[internal[len("enum "):]] + return f"(.enum {n})", n + t = p["type"] + if t == "bool": + return ".bool", 2 + m = re.fullmatch(r"(u?)int(\d+)", t) + if m and int(m.group(2)) <= 16: + bits = int(m.group(2)) + return f"(.{'uint' if m.group(1) else 'int'} {bits})", 2 ** bits + return None, None + + +def wide_param(p): + """The Abi.Param a wide parameter is counted as, or None. Abi.fullScope only counts + a function's parameters, so a wide one stands for every word below 2 ^ 256.""" + t = p["type"] + m = re.fullmatch(r"(u?)int(\d+)", t) + if m and int(m.group(2)) > 16: + return f"(.{'uint' if m.group(1) else 'int'} {int(m.group(2))})" + if t == "address": + return "(.uint 160)" + if re.fullmatch(r"bytes\d+", t): + return "(.uint 256)" + return None + + +def core_repr(module): + """SolidCore's checked core contract of Source.MODULE, printed as a Lean term.""" + subprocess.run(["lake", "build", f"SolidCore.Refinement.Source.{module}"], check=True, + stdout=subprocess.DEVNULL) + with tempfile.NamedTemporaryFile("w", suffix=".lean", delete=False) as f: + f.write(f"""import SolidCore.Refinement.Source.{module} +open SolidCore.Solidity +#eval match TypeCheck.CheckedInput.contract + SolidCore.Refinement.Source.{module}.importedSourceUnit "Main" with + | .ok c => IO.println (repr c.core).pretty + | .error _ => IO.println "error" +""") + out = subprocess.run(["lake", "env", "lean", f.name], check=True, capture_output=True, + text=True).stdout.rstrip("\n") + Path(f.name).unlink() + if out == "error" or not out.startswith("{"): + print(f"{source}: no proof: SolidCore rejects the contract") + sys.exit(3) + return out + + +def deployed_storage(module): + """The storage SolidCore's constructor of Source.MODULE leaves with the proof's fuel, as + Abi.deployedStorage lists it (slot, word) by slot, printed as a Lean term.""" + subprocess.run(["lake", "build", "SolidCore.Refinement.Abi", f"SolidCore.Refinement.Source.{module}"], + check=True, stdout=subprocess.DEVNULL) + with tempfile.NamedTemporaryFile("w", suffix=".lean", delete=False) as f: + f.write(f"""import SolidCore.Refinement.Abi +import SolidCore.Refinement.Source.{module} +open SolidCore.Solidity SolidCore.Refinement.Abi +#eval match TypeCheck.CheckedInput.contract + SolidCore.Refinement.Source.{module}.importedSourceUnit "Main" with + | .ok c => + match deployedStorage {fuel} c with + | some s => IO.println (" ".intercalate ("storage" :: s.map fun (kv : Nat × Nat) => s!"{{kv.1}}:{{kv.2}}")) + | none => IO.println "error" + | .error _ => IO.println "error" +""") + out = subprocess.run(["lake", "env", "lean", f.name], check=True, capture_output=True, + text=True).stdout.split() + Path(f.name).unlink() + if not out or out[0] != "storage": + print(f"{source}: no proof: SolidCore's constructor fails") + sys.exit(3) + entries = [tuple(int(x) for x in kv.split(":")) for kv in out[1:]] + return "[" + ", ".join(f"({k}, {v})" for k, v in entries) + "]", [k for k, _ in entries] + + +def selector_block(fns): + """The selector table of the functions fns (tuples whose first item is the name): one + kernel_rfl check of each selector by Keccak-256 of its signature against the bytecode + file's, the table selectorTable, and selector_eq : ABI.selectorFromSignature = + selectorTable, which kernel_rfl's using passes to the shape checks. The signatures are + solar's (hashes), each checked against solc's AST functionSelector.""" + hashes = main.get("hashes") or {} + sigs = [] + for f in fns: + n = f[0] + sig = [g for g in hashes if g.split("(")[0] == n] + if len(sig) != 1: + sys.exit(f"{source}: no unique signature of {n} in solar's hashes") + sel = hashes[sig[0]] + if solc_selectors.get(n) != sel: + sys.exit(f"{source}: solar's selector {sel} of {sig[0]} is not solc's {solc_selectors.get(n)}") + sigs.append((n, sig[0])) + word = "SolidCore.Solidity.Shared.Word" + sfs = "SolidCore.Solidity.Source.ABI.selectorFromSignature" + parts = ["""/-! ## The selectors + +The type checker computes each external function's selector by Keccak-256 of its +signature, which costs the kernel about 400 MB a hash. Each is checked once, alone, against +the bytecode file's, and the shape checks below run on copies that read them from +`selectorTable` (`selector_eq`). -/ +"""] + for n, sig in sigs: + cap = n[0].upper() + n[1:] + parts.append(f"""/-- `{n}`'s selector, by Keccak-256 of its signature. -/ +def sel{cap} : {word} := + {sfs} "{sig}" + +kernel_rfl sel{cap}_eq sel{cap} Bytecode.{module}.Main.{n}Selector +""") + table = "\n else ".join(f'if s = "{sig}" then Bytecode.{module}.Main.{n}Selector' for n, sig in sigs) + cases = [] + for i, (n, sig) in enumerate(sigs): + cap = n[0].upper() + n[1:] + cases.append(f""" by_cases h{i} : s = "{sig}" + · rw [ite_eq_left h{i}, h{i}] + exact sel{cap}_eq + rw [ite_eq_right h{i}]""") + parts.append(f"""/-- `ABI.selectorFromSignature`, with `Main`'s signatures by table. -/ +def selectorTable (s : String) : {word} := + {table} + else {sfs} s + +theorem selector_eq : {sfs} = selectorTable := by + funext s + unfold selectorTable +{chr(10).join(cases)} +""") + return "\n".join(parts) + + +def shape_block(storage_lit, deployed_fn, deployed_doc): + """shape?, its kernel check shape_eq, and shape_of and contract_ok, for a constructor that + leaves the storage storage_lit (a Lean list), checked by the Bool deployed_fn on c.""" + return f"""/-- SolidCore's checked core of `Main`, the storage its constructor leaves and whether +it leaves {deployed_doc} and no logs, when `Main` type checks. -/ +def shape? : Option (Contract × Option (List (Nat × Nat)) × Bool) := + match contract? with + | .ok c => some (c.core, deployedStorage fuel c, {deployed_fn}) + | .error _ => none + +-- `shape_eq : shape? = some (coreLit, some {storage_lit}, true)`: `Main` type checks, its +-- core is `coreLit` and its constructor leaves {deployed_doc} and no logs, by the kernel's +-- conversion check on the copy of `shape?` that reads the selectors from `selectorTable` +-- (`selector_eq`): one check evaluates the type checker once and hashes nothing, where a +-- `Bool` test of the core would need a decision procedure for equality of cores. +kernel_rfl shape_eq shape? (some (coreLit, some {storage_lit}, true)) using selector_eq + +/-- The checked contract has the core `coreLit`, and its constructor leaves {deployed_doc} +and no logs. -/ +theorem shape_of {{c : TypeCheck.CheckedContract}} (hc : contract? = .ok c) : + c.core = coreLit ∧ deployedStorage fuel c = some {storage_lit} ∧ {deployed_fn} = true := by + have h := shape_eq + unfold shape? at h + rw [hc] at h + obtain ⟨hk, h⟩ := Prod.mk.inj (Option.some.inj h) + obtain ⟨hs, he⟩ := Prod.mk.inj h + exact ⟨hk, hs, he⟩ + +/-- `Main` type checks. -/ +theorem contract_ok : ∃ c, contract? = .ok c := by + have h := shape_eq + unfold shape? at h + cases hc : contract? with + | ok c => exact ⟨c, rfl⟩ + | error _ => rw [hc] at h; simp at h +""" + + +def wide_parts(fns, storage=None): + """The pieces of a symbolic proof: the printed core contract as a term, and one call_* + theorem per function. With storage, the Lean list of the deployed storage + and its slots from deployed_storage, every call starts from that storage.""" + lit = core_repr(module) + term = "\n".join(" " + line for line in lit.split("\n")) + ns = f"SolidCore.Refinement.Corpus.{module}" + header = f"-- Generated by scripts/refinement/gen.sh from {source}. Do not edit.\n" + fn_list = ",\n ".join( + f"⟨Bytecode.{module}.Main.{n}Selector, [{', '.join(ps)}]⟩" for n, ps, _ in fns + ) + selectors = ", ".join(f"Bytecode.{module}.Main.{n}Selector" for n, _, _ in fns) + rules = f"code, Bytecode.{module}.Main.runtimeNat, Bytecode.{module}.Main.runtimeSize, {selectors}" + theorems = [] + for n, ps, writes in fns: + k = len(ps) + ws = [f"w{i + 1}" for i in range(k)] + if writes: + # A function that may write storage: the bytecode's state is checked slot by slot. + target = f""" all_goals + refine run_of_postS code _ [{', '.join(ws)}] _ (by simp [Source.observe, State.logEntries, hev]) + (fun hX slot => by simp_all [Source.observe, slotValue, callOf]) ?_ + all_goals wide_tgt_s [{rules}] +""" + else: + target = f""" all_goals + refine run_of_post code _ [{', '.join(ws)}] _ (by simp [Source.observe, State.logEntries, hev]) + (fun slot => by + simp [Source.observe, State.loadSlot, StorageMap.lookup?, getElem?_of_isEmpty hs, + slotValue, callOf]) ?_ + all_goals wide_tgt [{rules}] +""" + pattern = "_" + for w in reversed(ws): + pattern = f"_ | ⟨{w}, {pattern}⟩" + if storage is not None: + # A call from the deployed storage: SLOAD reads it and the bytecode's state is checked + # slot by slot, for every function. + lit, keys = storage + conds = "".join(f"k ≠ {key} → " for key in keys) + names = " ".join(f"h{i}" for i in range(len(keys))) + theorems.append(f"""set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore and solar's bytecode agree on every call of `{n}` on any argument words, from the +deployed storage. -/ +theorem call_{n} {{c : TypeCheck.CheckedContract}} (hcore : c.core = coreLit) {{d : Source.State}} + (hd : DeployedAt fuel c d {lit}) (ws : List U256) (hl : ws.length = {k}) : + ∃ obs, Source.run fuel c (callAt Bytecode.{module}.Main.{n}Selector ws {lit}) = some obs ∧ + Target.run code (callAt Bytecode.{module}.Main.{n}Selector ws {lit}) = some obs := by + rcases ws with {pattern} <;> simp at hl + rw [run_eq_at hd] + have hev := hd.events + have hnone : ∀ k, {conds}d.storage[k]? = none := fun k {names} => + hd.getElem?_eq_none fun v hv => by simp at hv; omega + simp only [hcore, List.map_cons, List.map_nil, List.foldl_cons, List.foldl_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, {selectors}, get?_insert] + all_goals + refine run_of_postS_at code _ [{', '.join(ws)}] _ _ (by simp [Source.observe, State.logEntries, hev]) + (fun hX slot => by simp_all [Source.observe, callAt]) ?_ + all_goals wide_tgt_at [{rules}] +""") + continue + theorems.append(f"""set_option maxHeartbeats 0 in +set_option maxRecDepth 100000 in +/-- SolidCore and solar's bytecode agree on every call of `{n}` on any argument words. -/ +theorem call_{n} {{c : TypeCheck.CheckedContract}} (hcore : c.core = coreLit) {{d : Source.State}} + (hd : Deployed fuel c d) (ws : List U256) (hl : ws.length = {k}) : + ∃ obs, Source.run fuel c (callOf Bytecode.{module}.Main.{n}Selector ws) = some obs ∧ + Target.run code (callOf Bytecode.{module}.Main.{n}Selector ws) = some obs := by + rcases ws with {pattern} <;> simp at hl + rw [run_eq hd] + have hs := hd.storage + have hev := hd.events + simp only [hcore, List.map_cons, List.map_nil] + wide_symex [coreLit, fuel, ctxOf, hcore, {selectors}] +{target}""") + return term, theorems + + +def gen_wide(fns): + """Write MODULE.lean, the symbolic refinement of a contract with wide parameters.""" + term, theorems = wide_parts(fns) + ns = f"SolidCore.Refinement.Corpus.{module}" + header = f"-- Generated by scripts/refinement/gen.sh from {source}. Do not edit.\n" + fn_list = ",\n ".join( + f"⟨Bytecode.{module}.Main.{n}Selector, [{', '.join(ps)}]⟩" for n, ps, _ in fns + ) + cases = " | ".join(["rfl"] * len(fns)) + dispatch = "\n".join(f" · exact call_{n} hcore hd ws hl" for n, _, _ in fns) + extra_import = "import SolidCore.Refinement.KernelCopies\nimport SolidCore.Refinement.KernelRfl\n" + shape_doc = """The kernel checks `shape_eq` (`kernel_rfl`, `SolidCore.Refinement.KernelRfl`): that +SolidCore's checked contract has the core `coreLit`, the generator's print of it, and that +its constructor leaves no storage and no logs, by one conversion check that evaluates copies +of the type checker and the interpreter, which read each function's selector from +`selectorTable` (`selector_eq`, each selector checked by Keccak-256 on its own).""" + if kernel_shape: + shape_doc += """ +`wide_tgt` decides branches by evaluation and `bv_omega`.""" + else: + shape_doc += """ +`wide_tgt` decides branches by evaluation and `bv_omega`, and by `bv_decide` (which +trusts Lean's compiler) only where those fail.""" + selectors = selector_block(fns) + shape = shape_block("[]", "deployedEmpty fuel c", "no storage") + (out / f"{module}.lean").write_text(f"""{header} +import SolidCore.Refinement.Wide.Refines +import SolidCore.Refinement.Bytecode.{module} +import SolidCore.Refinement.Source.{module} +{extra_import} +/-! +# {name}: solar's bytecode refines SolidCore's `Main` on wide arguments + +`refines_full` proves `Refines fuel contract code (fullScope fns s)` for `Main` in +`{source}`, where `code` is solar's runtime bytecode at the pinned commit and `s` the +storage SolidCore's constructor leaves (none): every call of every function on any +argument words below `2 ^ 256`, with no value. Each `call_*` theorem runs one function +symbolically in both semantics (`SolidCore.Refinement.Wide`): SolidCore's interpreter by +`wide_symex`, solar's bytecode on EthLib by `wide_tgt`, path by path. + +{shape_doc} +-/ + +namespace {ns} + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source + +/-- The interpreter fuel the refinement uses. -/ +def fuel : Nat := {fuel} + +/-- solar's runtime bytecode of `Main`, from the generated file. -/ +def code : ByteArray := + EthLib.Execution.Evm.Logic.NatCode.ofNat Bytecode.{module}.Main.runtimeNat + Bytecode.{module}.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.{module}.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. A wide parameter counts as the +`Param` of its width; `fullScope` only counts them. -/ +def fns : List Fn := + [{fn_list}] + +/-- SolidCore's core contract of `Main`, as the generator printed it. -/ +def coreLit : Contract := +{term} + +{selectors} +{shape} +{chr(10).join(theorems)} +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on every call of every +function with any argument words below `2 ^ 256`, from the deployed storage. -/ +theorem refines_full : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + Refines fuel c code (fullScope fns s) := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hcore, hdep, hemp⟩ := shape_of hc + obtain ⟨d, hd⟩ := deployed_of hemp + refine ⟨c, [], hc, hdep, refines_of_calls fun fn hfn ws hl => ?_⟩ + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + rcases hfn with {cases} +{dispatch} + +end {ns} +""") + print(f"{source} -> {out}/{module}.lean (wide, {len(fns)} function(s), symbolic)") + + + +ROUTES = Path("scripts/refinement/routes") + + +def select_route(): + """The proof route of a contract whose parameters are all small: "symbolic" (both + semantics run on free argument words, as for a wide contract) or "enum" (every clean + call by native_decide, every dirty one by dirty_symex). A line + "// refinement: route=symbolic" or "route=enum" in the source picks it; otherwise + scripts/refinement/routes, which lists the contracts whose symbolic proof builds in + reasonable time, does; otherwise "enum", which always applies.""" + m = re.search(r"//\s*refinement:.*\broute=(symbolic|enum)\b", Path(source).read_text()) + if m: + return m.group(1) + if ROUTES.exists(): + for line in ROUTES.read_text().splitlines(): + words = line.split("#", 1)[0].split() + if len(words) == 2 and words[0] == name and words[1] in ("symbolic", "enum"): + return words[1] + return "enum" + + +def gen_small_symbolic(): + """Write MODULE.lean, the symbolic refinement of a contract whose parameters are all + small, next to MODULE/Defs.lean and MODULE/Dirty.lean, which the sequence proof uses. + When the constructor leaves storage, every call starts from it: the call_* theorems are + stated on Evm.Wide.callAt of the deployed storage and proved by wide_tgt_at.""" + mut = {i["name"]: i.get("stateMutability") for i in abi if i.get("type") == "function"} + wfns = [(n, ps, mut[n] not in ("pure", "view")) for n, ps in fns] + # A constructor that leaves storage: every call starts from it (Wide.refines_of_calls_at). + lit, keys = deployed_storage(module) + term, theorems = wide_parts(wfns, (lit, keys) if keys else None) + if keys: + leaves = f"the storage `{lit}`" + leaves_note = f"(`{lit}`)" + tgt = "wide_tgt_at" + tgt_doc = """ `wide_tgt_at` decides branches by evaluation and +`bv_omega`, and compares the words left by evaluating them on every value of a small argument +word in the kernel (`word_decide`).""" + shape = shape_block(lit, f"deployedAt fuel c {lit}", f"the storage `{lit}`") + deployed_of = "obtain ⟨d, hd⟩ := deployedAt_of hemp" + refines_of = f"refine ⟨c, {lit}, hc, hdep, refines_of_calls_at fun fn hfn ws hl => ?_⟩" + else: + leaves = "no storage" + leaves_note = "(none)" + tgt = "wide_tgt" + tgt_doc = """ `wide_tgt` decides branches by evaluation and `bv_omega`.""" + shape = shape_block("[]", "deployedEmpty fuel c", "no storage") + deployed_of = "obtain ⟨d, hd⟩ := deployed_of hemp" + refines_of = "refine ⟨c, [], hc, hdep, refines_of_calls fun fn hfn ws hl => ?_⟩" + cases = " | ".join(["rfl"] * len(fns)) + dispatch = "\n".join(f" · exact call_{n} hcore hd ws hl" for n, _, _ in wfns) + kernel_import = "import SolidCore.Refinement.KernelCopies\nimport SolidCore.Refinement.KernelRfl\n" + selectors = selector_block(wfns) + core_doc = f"""The kernel checks `shape_eq` (`kernel_rfl`, `SolidCore.Refinement.KernelRfl`): that +SolidCore's checked contract has the core `coreLit`, the generator's print of it, and that +its constructor leaves {leaves} and no logs, by one conversion check that evaluates copies +of the type checker and the interpreter, which read each function's selector from +`selectorTable` (`selector_eq`, each selector checked by Keccak-256 on its own).""" + if kernel_shape: + core_doc += tgt_doc + shape_proof = "kernel_rfl shapeOk_eq_true shapeOk true using selector_eq" + else: + core_doc += f""" +`{tgt}` decides branches by evaluation and `bv_omega`, and by `bv_decide` (which +trusts Lean's compiler) only where those fail.""" + shape_proof = "theorem shapeOk_eq_true : shapeOk = true := by native_decide" + (out / f"{module}.lean").write_text(f"""{header} +import SolidCore.Refinement.Wide.Refines +import SolidCore.Refinement.Wide.Clean +import {ns}.Defs +import {ns}.Dirty +{kernel_import} +/-! +# {name}: solar's bytecode refines SolidCore's `Main`, symbolically + +`refines_full` proves `Refines fuel contract code (fullScope fns s)` for `Main` in +`{source}`, where `code` is solar's runtime bytecode at the pinned commit and `s` the +storage SolidCore's constructor leaves {leaves_note}: every call of every function on any +argument words below `2 ^ 256`, clean or dirty, with no value. Each `call_*` theorem runs +one function symbolically in both semantics (`SolidCore.Refinement.Wide`): SolidCore's +interpreter by `wide_symex`, solar's bytecode on EthLib by `{tgt}`, path by path, so no +call is run by `native_decide`. `refines`, on the clean calls of `scope s`, follows. + +{core_doc} +`shapeOk` and `Dirty.lean` serve the sequence proof (`Seq.lean`), not these theorems. +-/ + +namespace {ns} + +open EthLib.Base SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Wide +open SolidCore.Refinement.Evm.Wide SolidCore.Solidity SolidCore.Solidity.Source + +/-- SolidCore's core contract of `Main`, as the generator printed it. -/ +def coreLit : Contract := +{term} + +{selectors} +{shape} +{chr(10).join(theorems)} +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on every call of every +function with any argument words below `2 ^ 256`, from the deployed storage. -/ +theorem refines_full : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + Refines fuel c code (fullScope fns s) := by + obtain ⟨c, hc⟩ := contract_ok + obtain ⟨hcore, hdep, hemp⟩ := shape_of hc + {deployed_of} + {refines_of} + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + rcases hfn with {cases} +{dispatch} + +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on every call of +the scope: every clean call. -/ +theorem refines : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + Refines fuel c code (· ∈ scope s) := by + obtain ⟨c, s, hc, hs, h⟩ := refines_full + exact ⟨c, s, hc, hs, refines_of_full (by decide) h⟩ + +/-- Whether every function of `fns` has the shape `Dirty.run_dirty` covers, in +SolidCore's checked `Main`. -/ +def shapeOk : Bool := + match contract? with + | .ok c => fns.all (Dirty.fnShapeOk c) + | .error _ => false + +{shape_proof} + +end {ns} +""") + print(f"{source} -> {out}/{module}.lean ({total} calls, symbolic)") + + +def dyn_param(p): + """The Dyn.DParam of a parameter and its number of encodings within the bounds, or + (None, None). A dynamic parameter is bytes, an array of a small type or a struct of + small types; a small one is a word.""" + t = p["type"] + if t == "bytes": + n = DYN_BYTES + return f"(.bytes {n})", sum(256 ** k for k in range(n + 1)) + if t.endswith("[]"): + ep, count = param({**p, "type": t[:-2], "internalType": p.get("internalType", "")[:-2]}) + if ep is None: + return None, None + n = DYN_ARRAY + return f"(.array {ep} {n})", sum(count ** k for k in range(n + 1)) + if t == "tuple": + comps = [param(c) for c in p["components"]] + if not comps or any(c[0] is None for c in comps): + return None, None + return f"(.struct [{', '.join(c[0] for c in comps)}])", math.prod(c[1] for c in comps) + w, count = param(p) + if w is None: + return None, None + return f"(.word {w})", count + + +DYN_BYTES = 2 +DYN_ARRAY = 2 +m = re.search(r"//\s*refinement:.*\bbytes=(\d+)", Path(source).read_text()) +if m: + DYN_BYTES = int(m.group(1)) +m = re.search(r"//\s*refinement:.*\barray=(\d+)", Path(source).read_text()) +if m: + DYN_ARRAY = int(m.group(1)) + + +def gen_dyn(items): + """Write the refinement of a contract with dynamic or struct parameters: the canonical + encodings within the bounds by evaluation, malformed call data symbolically.""" + fns = [] + total = 0 + for item in items: + ps = [dyn_param(p) for p in item["inputs"]] + if any(p[0] is None for p in ps): + bad = ", ".join(p["type"] for p in item["inputs"]) + print(f"{source}: no proof: {item['name']}({bad}) has a parameter outside the scope") + sys.exit(3) + fns.append((item["name"], [p[0] for p in ps])) + total += math.prod(p[1] for p in ps) + if total > MAX_CALLS: + print(f"{source}: no proof: {total} encodings is outside the finite scope") + sys.exit(3) + parts = max(1, math.ceil(total / CALLS_PER_PART)) + ns = f"SolidCore.Refinement.Corpus.{module}" + out = Path("SolidCore/Refinement/Corpus") + (out / module).mkdir(parents=True, exist_ok=True) + header = f"-- Generated by scripts/refinement/gen.sh from {source}. Do not edit.\n" + fn_list = ",\n ".join( + f"⟨Bytecode.{module}.Main.{n}Selector, [{', '.join(ps)}]⟩" for n, ps in fns + ) + (out / module / "Defs.lean").write_text(f"""{header} +import SolidCore.Refinement.Dyn.Abi +import SolidCore.Refinement.Check +import SolidCore.Refinement.Bytecode.{module} +import SolidCore.Refinement.Source.{module} + +/-! +# The scope of {name}'s refinement + +{total} calls: every function of `Main` in `{source}` on the canonical ABI encoding of +every argument tuple within the bounds (`Dyn.encodings`), with no value, from the storage +SolidCore's constructor leaves. The check runs in {parts} part(s), each in its own module. +-/ + +namespace {ns} + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Dyn SolidCore.Solidity + +/-- The interpreter fuel the refinement uses. -/ +def fuel : Nat := {fuel} + +/-- solar's runtime bytecode of `Main`, from the generated file. -/ +def code : ByteArray := + EthLib.Execution.Evm.Logic.NatCode.ofNat Bytecode.{module}.Main.runtimeNat + Bytecode.{module}.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.{module}.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters, with the bounds of their encodings. -/ +def fns : List DFn := + [{fn_list}] + +/-- The number of parts the check runs in. -/ +def parts : Nat := {parts} + +/-- The calls the evaluation covers, from the deployed storage `s`. -/ +def scope (s : List (Nat × Nat)) : List Call := encodings fns [s] + +/-- Whether both semantics agree on every `parts`-th call of the scope, from the `i`-th. -/ +def partOk (i : Nat) : Bool := + match contract? with + | .ok c => + match deployedStorage fuel c with + | some s => checkPart (agree fuel c code) (scope s).toArray parts i + | none => false + | .error _ => false + +end {ns} +""") + for i in range(parts): + (out / module / f"Part{i}.lean").write_text(f"""{header} +import {ns}.Defs + +namespace {ns} + +theorem part{i} : partOk {i} = true := by native_decide + +end {ns} +""") + rules = ", ".join( + [f"Bytecode.{module}.Main.runtimeNat", f"Bytecode.{module}.Main.runtimeSize"] + + [f"Bytecode.{module}.Main.{n}Selector" for n, _ in fns] + ) + fn_cases = "\n".join( + f" · exact malformed_of_frame code Bytecode.{module}.Main.{n}Selector [{', '.join(ps)}]\n" + f" (by dyn_symex [code, {rules}])" + for n, ps in fns + ) + pattern = " | ".join(["rfl"] * len(fns)) + (out / module / "Malformed.lean").write_text(f"""{header} +import SolidCore.Refinement.Dyn.Refines +import {ns}.Defs + +/-! +# {name}: EthLib rejects malformed call data + +For every function of `Main` in `{source}`, every call whose call data after the +selector is malformed (`Dyn.Malformed`: shorter than the heads, or a dynamic argument +pointing past the end), of any length below `2 ^ 32` and with any bytes, reverts with +empty output in EthLib, from any storage. Each case is one `dyn_symex` run over solar's +bytecode, symbolic in the call data's size and bytes. +-/ + +namespace {ns} + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Dyn + +set_option maxHeartbeats 4000000 in +set_option maxRecDepth 8192 in +/-- EthLib rejects every malformed call of every function of `Main`. -/ +theorem target_malformed : TargetMalformed code fns := by + intro fn hfn + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + rcases hfn with {pattern} +{fn_cases} + +end {ns} +""") + imports = "\n".join(f"import {ns}.Part{i}" for i in range(parts)) + imports += f"\nimport {ns}.Malformed" + cases = "\n".join(f" | {i}, _ => part{i}" for i in range(parts)) + (out / f"{module}.lean").write_text(f"""{header} +{imports} + +/-! +# {name}: solar's bytecode refines SolidCore's `Main` on dynamic parameters + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in `{source}`, +where `code` is solar's runtime bytecode at the pinned commit and `s` the storage +SolidCore's constructor leaves. The scope is every call of every function on the +canonical encoding of an argument tuple within the bounds, {total} calls, each run in both +semantics by `native_decide` (which trusts Lean's compiler). + +`refines_full` extends it to `Dyn.dynScope`: also every call on malformed call data, +which both sides reject with empty output, by `Dyn.run_malformed` for SolidCore (once +`native_decide` checks each function's shape) and by `target_malformed` for EthLib. +-/ + +namespace {ns} + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Dyn + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with +{cases} + | n + {parts}, h => absurd h (by simp only [parts]; omega) + +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on every canonical +encoding within the bounds. -/ +theorem refines : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + Refines fuel c code (· ∈ scope s) := by + have h0 := parts_ok 0 (by decide) + match hc : contract?, h0 with + | .ok c, h0 => + match hs : deployedStorage fuel c with + | some s => + refine ⟨c, s, rfl, hs, refines_of_all (all_of_parts (parts := parts) (by decide) fun i hi => ?_)⟩ + have := parts_ok i hi + simpa only [partOk, hc, hs] using this + | none => simp [partOk, hc, hs] at h0 + | .error _, h0 => simp [partOk, hc] at h0 + +/-- Whether every function of `fns` has the shape `Dyn.run_malformed` covers, in +SolidCore's checked `Main`. -/ +def shapeOk : Bool := + match contract? with + | .ok c => fns.all (dfnShapeOk c) + | .error _ => false + +theorem shapeOk_eq_true : shapeOk = true := by native_decide + +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on every call of every +function on a canonical encoding within the bounds or on malformed call data shorter than +`2 ^ 32`, from the deployed storage. -/ +theorem refines_full : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + Refines fuel c code (dynScope fns s) := by + obtain ⟨c, s, hc, hs, h⟩ := refines + have hsh := shapeOk_eq_true + simp only [shapeOk, hc] at hsh + exact ⟨c, s, hc, hs, refines_dyn hs h hsh target_malformed⟩ + +end {ns} +""") + print(f"{source} -> {out}/{module}.lean (dynamic, {total} encodings, {parts} part(s), malformed symbolic)") + + +dyn_items = sorted((i for i in abi if i.get("type") == "function"), key=lambda i: i["name"]) +if any(p["type"] in ("bytes", "tuple") or p["type"].endswith("[]") + for i in dyn_items for p in i["inputs"]): + gen_dyn(dyn_items) + sys.exit(0) + +wide = False +for item in sorted((i for i in abi if i.get("type") == "function"), key=lambda i: i["name"]): + if any(param(p)[0] is None and wide_param(p) is not None for p in item["inputs"]): + wide = True +fns_wide = [] +if wide: + for item in sorted((i for i in abi if i.get("type") == "function"), key=lambda i: i["name"]): + ps = [param(p)[0] or wide_param(p) for p in item["inputs"]] + if any(p is None for p in ps): + bad = ", ".join(p["type"] for p in item["inputs"]) + print(f"{source}: no proof: {item['name']}({bad}) has a parameter outside the scope") + sys.exit(3) + writes = item.get("stateMutability") not in ("pure", "view") + fns_wide.append((item["name"], ps, writes)) + out = Path("SolidCore/Refinement/Corpus") + out.mkdir(parents=True, exist_ok=True) + gen_wide(fns_wide) + sys.exit(0) + +fns = [] +total = 0 +for item in sorted((i for i in abi if i.get("type") == "function"), key=lambda i: i["name"]): + params = [param(p) for p in item["inputs"]] + if any(p[0] is None for p in params): + bad = ", ".join(p["type"] for p in item["inputs"]) + print(f"{source}: no proof: {item['name']}({bad}) has a parameter outside the finite scope") + sys.exit(3) + fns.append((item["name"], [p[0] for p in params])) + total += math.prod(p[1] for p in params) +if not fns or total > MAX_CALLS: + print(f"{source}: no proof: {total} calls is outside the finite scope") + sys.exit(3) + +parts = max(1, math.ceil(total / CALLS_PER_PART)) +route = select_route() +ns = f"SolidCore.Refinement.Corpus.{module}" +out = Path("SolidCore/Refinement/Corpus") +(out / module).mkdir(parents=True, exist_ok=True) +header = f"-- Generated by scripts/refinement/gen.sh from {source}. Do not edit.\n" +fn_list = ",\n ".join( + f"⟨Bytecode.{module}.Main.{n}Selector, [{', '.join(ps)}]⟩" for n, ps in fns +) + +(out / module / "Defs.lean").write_text(f"""{header} +import SolidCore.Refinement.Abi +import SolidCore.Refinement.Bytecode.{module} +import SolidCore.Refinement.Source.{module} + +/-! +# The scope of {name}'s refinement + +{total} calls: every function of `Main` in `{source}` on every list of clean +argument words, with no value, from the storage SolidCore's constructor leaves. +The check runs in {parts} part(s), each in its own module. +-/ + +namespace {ns} + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity + +/-- The interpreter fuel the refinement uses. -/ +def fuel : Nat := {fuel} + +/-- solar's runtime bytecode of `Main`, from the generated file. -/ +def code : ByteArray := + EthLib.Execution.Evm.Logic.NatCode.ofNat Bytecode.{module}.Main.runtimeNat + Bytecode.{module}.Main.runtimeSize + +/-- SolidCore's checked `Main`. -/ +def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract := + TypeCheck.CheckedInput.contract Source.{module}.importedSourceUnit "Main" + +/-- The functions of `Main` and their parameters. -/ +def fns : List Fn := + [{fn_list}] + +/-- The number of parts the check runs in. -/ +def parts : Nat := {parts} + +/-- The calls the theorem covers, from the deployed storage `s`. -/ +def scope (s : List (Nat × Nat)) : List Call := calls fns [s] + +/-- Whether both semantics agree on every `parts`-th call of the scope, from the `i`-th. -/ +def partOk (i : Nat) : Bool := + match contract? with + | .ok c => + match deployedStorage fuel c with + | some s => checkPart (agree fuel c code) (scope s).toArray parts i + | none => false + | .error _ => false + +end {ns} +""") + +if route == "enum": + for i in range(parts): + (out / module / f"Part{i}.lean").write_text(f"""{header} +import {ns}.Defs + +namespace {ns} + +theorem part{i} : partOk {i} = true := by native_decide + +end {ns} +""") + +rules = ", ".join( + [f"Bytecode.{module}.Main.runtimeNat", f"Bytecode.{module}.Main.runtimeSize"] + + [f"Bytecode.{module}.Main.{n}Selector" for n, _ in fns] +) +fn_cases = "\n".join( + f" · exact dirty_of_frame code Bytecode.{module}.Main.{n}Selector [{', '.join(ps)}]\n" + f" (by dirty_symex [code, {rules}])" + for n, ps in fns +) +pattern = " | ".join(["rfl"] * len(fns)) +(out / module / "Dirty.lean").write_text(f"""{header} +import SolidCore.Refinement.Evm.Symex +import SolidCore.Refinement.Dirty.Source +import {ns}.Defs + +/-! +# {name}: EthLib rejects every dirty argument word + +For every function of `Main` in `{source}`, every call whose argument words are +below `2 ^ 256` but not all clean reverts with empty output in EthLib, from any +storage. Each case is one `dirty_symex` run over solar's bytecode, symbolic in +the argument words; `bv_omega` decides its branch conditions, a kernel-checked +proof (`symex_bv` falls back to `bv_decide` only where it fails). +-/ + +namespace {ns} + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Refinement.Evm.Symex + +set_option maxHeartbeats 4000000 in +set_option maxRecDepth 8192 in +/-- EthLib rejects every dirty call of every function of `Main`. -/ +theorem target_dirty : Dirty.TargetDirty code fns := by + intro fn hfn + simp only [fns, List.mem_cons, List.not_mem_nil, or_false] at hfn + rcases hfn with {pattern} +{fn_cases} + +end {ns} +""") + +if route == "enum": + imports = "\n".join(f"import {ns}.Part{i}" for i in range(parts)) + imports += f"\nimport {ns}.Dirty" + cases = "\n".join(f" | {i}, _ => part{i}" for i in range(parts)) + (out / f"{module}.lean").write_text(f"""{header} +{imports} + +/-! +# {name}: solar's bytecode refines SolidCore's `Main` + +`refines` proves `Refines fuel contract code (· ∈ scope s)` for `Main` in +`{source}`, where `code` is solar's runtime bytecode at the pinned commit and `s` +the storage SolidCore's constructor leaves. The scope is every call of every +function on clean argument words with no value, {total} calls, each run in +both semantics by `native_decide` (which trusts Lean's compiler). + +`refines_full` extends it to every argument word below `2 ^ 256`: a dirty word +makes both sides revert with empty output and keep the storage, by +`Dirty.run_dirty` for SolidCore (once `native_decide` checks each function's +shape) and by `target_dirty` for EthLib. +-/ + +namespace {ns} + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem parts_ok : ∀ i < parts, partOk i = true := fun i hi => + match i, hi with +{cases} + | n + {parts}, h => absurd h (by simp only [parts]; omega) + +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on every call of +the scope: every clean call. -/ +theorem refines : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + Refines fuel c code (· ∈ scope s) := by + have h0 := parts_ok 0 (by decide) + match hc : contract?, h0 with + | .ok c, h0 => + match hs : deployedStorage fuel c with + | some s => + refine ⟨c, s, rfl, hs, refines_of_all (all_of_parts (parts := parts) (by decide) fun i hi => ?_)⟩ + have := parts_ok i hi + simpa only [partOk, hc, hs] using this + | none => simp [partOk, hc, hs] at h0 + | .error _, h0 => simp [partOk, hc] at h0 + +/-- Whether every function of `fns` has the shape `Dirty.run_dirty` covers, in +SolidCore's checked `Main`. -/ +def shapeOk : Bool := + match contract? with + | .ok c => fns.all (Dirty.fnShapeOk c) + | .error _ => false + +theorem shapeOk_eq_true : shapeOk = true := by native_decide + +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on every call of every +function with any argument words below `2 ^ 256`, clean or dirty, from the deployed +storage: the clean calls by `refines`, the dirty ones by `Dirty.run_dirty` on the +SolidCore side and `target_dirty` on the EthLib side. -/ +theorem refines_full : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + Refines fuel c code (fullScope fns s) := by + obtain ⟨c, s, hc, hs, h⟩ := refines + have hsh := shapeOk_eq_true + simp only [shapeOk, hc] at hsh + exact ⟨c, s, hc, hs, Dirty.refines_full hs h hsh target_dirty⟩ + +end {ns} +""") + print(f"{source} -> {out}/{module}.lean ({total} calls, {parts} part(s))") +else: + gen_small_symbolic() + + + + +# Sequences of calls. Everything below only adds files: MODULE/SeqStates.lean, +# MODULE/SeqDefs.lean, MODULE/SeqPartI.lean and MODULE/Seq.lean, and the +# aggregate SolidCore/Refinement/Seq/Corpus.lean. +# +# The certificate is the set of storages clean calls reach from the deployed +# one, by level. A contract whose functions are all pure or view cannot write +# storage, so its certificate is the deployed storage alone, closed. Otherwise +# SolidCore.Refinement.Seq.explore computes it with SolidCore, run here through +# lake: it stops at the closure (closed: every sequence of any length) or before +# the levels would hold more than SEQ_MAX_STATES storages or need more than +# SEQ_BUDGET calls to check (open: every sequence of at most as many calls as +# there are levels). Lean re-checks the certificate on both semantics, so the +# exploration is not trusted. A failed exploration skips the sequence proof. +import os +import subprocess +import tempfile + +SEQ_MAX_STATES = 1 << 12 +SEQ_BUDGET = 1 << 17 +SEQ_ROUNDS = 64 +seq_pure = all(i.get("stateMutability") in ("pure", "view") for i in abi if i.get("type") == "function") + + +def seq_plan(): + if seq_pure: + return True, total, [], [] + lake = os.environ.get("LAKE", "lake") + build = subprocess.run([lake, "build", f"{ns}.Defs", "SolidCore.Refinement.Seq.Explore"], + capture_output=True, text=True) + if build.returncode != 0: + raise RuntimeError(build.stdout[-2000:] + build.stderr[-2000:]) + probe = f"""import SolidCore.Refinement.Seq.Explore +import {ns}.Defs +open SolidCore.Refinement SolidCore.Refinement.Abi {ns} +#eval show IO Unit from do + match contract? with + | .ok c => + match deployedStorage fuel c with + | some s => IO.println (Seq.explore fuel c fns s {SEQ_MAX_STATES} {SEQ_BUDGET} {SEQ_ROUNDS}).render + | none => IO.println "error" + | .error _ => IO.println "error" +""" + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "Probe.lean" + path.write_text(probe) + res = subprocess.run([lake, "env", "lean", str(path)], capture_output=True, text=True) + lines = res.stdout.splitlines() + starts = [i for i, l in enumerate(lines) if l in ("closed", "open")] + if res.returncode != 0 or not starts: + raise RuntimeError(res.stdout[-2000:] + res.stderr[-2000:]) + lines = lines[starts[0]:] + closed = lines[0] == "closed" + per = int(lines[1]) + keys = [int(k) for k in lines[2].split()] + levels = [] + for line in lines[3:]: + if not line.startswith("L "): + break + level = [] + for st in line[2:].split(";"): + level.append([tuple(int(x) for x in kv.split(":")) for kv in st.split(",") if kv]) + levels.append(level) + return closed, per, keys, levels + + +try: + seq_closed, seq_per, seq_keys, seq_levels = seq_plan() +except RuntimeError as e: + print(f"{source}: no sequence proof: exploration failed\n{e}", file=sys.stderr) + seq_closed = None + +if seq_closed is not None: + seq_states = 1 + sum(len(l) for l in seq_levels) + seq_calls = seq_per * seq_states + seq_depth = 1 + len(seq_levels) + seq_parts = max(1, math.ceil(seq_calls / CALLS_PER_PART)) + + def lean_state(st): + return "[" + ", ".join(f"({k}, {v})" for k, v in st) + "]" + + if seq_levels: + level_txt = ",\n ".join( + "[" + ",\n ".join(lean_state(st) for st in level) + "]" for level in seq_levels + ) + levels_lit = f"[\n {level_txt}]" + else: + levels_lit = "[]" + keys_lit = "[" + ", ".join(str(k) for k in seq_keys) + "]" + if seq_closed: + how = ("every function is pure or view, so the deployed storage alone is closed" + if seq_pure else "`Seq.explore` found the closure") + variant = (f"closed: {seq_states} storage(s) in {seq_depth} level(s); {how}. The\n" + "theorem covers every sequence of calls of any length") + else: + variant = (f"open: the closure did not fit {SEQ_MAX_STATES} storages and {SEQ_BUDGET} calls,\n" + f"so the certificate keeps the first {seq_depth} level(s), {seq_states} storage(s). The\n" + f"theorem covers every sequence of at most {seq_depth} calls") + + (out / module / "SeqStates.lean").write_text(f"""{header} +/-! +# The storages {name}'s clean calls reach + +The certificate of the sequence refinement of `Main` in `{source}`, as +`SolidCore.Refinement.Seq.explore` found it: the slots any reached storage holds +(`seqKeys`) and the storages of every level after the deployed one (`seqLevels`), +each as its nonzero or constructor-written slots, sorted. Nothing here is +trusted: `SeqDefs.lean` checks it against both semantics. +-/ + +namespace {ns} + +/-- The slots a reached storage holds a word for. -/ +def seqKeys : List Nat := {keys_lit} + +/-- The reached storages, by level, from level 1. -/ +def seqLevels : List (List (List (Nat × Nat))) := {levels_lit} + +end {ns} +""") + + (out / module / "SeqDefs.lean").write_text(f"""{header} +import SolidCore.Refinement.Seq.Check +import {ns}.Defs +import {ns}.SeqStates + +/-! +# The certificate of {name}'s sequence refinement + +The storages of `SeqStates.lean`, with the deployed storage `s` as level 0, are +{variant}. +`seqNext s` turns a call's observable into the next call's storage list: every +slot of `seqKeys` or of the deployed storage whose final value is nonzero or that +the constructor wrote. The check runs every clean call from every storage of the +certificate, {seq_calls} calls, in {seq_parts} part(s), and every dirty call once +per storage. +-/ + +namespace {ns} + +open SolidCore.Refinement SolidCore.Refinement.Abi SolidCore.Solidity + +/-- The storage list the next call starts from. -/ +def seqNext (s : List (Nat × Nat)) : Observable → List (Nat × Nat) := + Seq.canon (Seq.normKeys (seqKeys ++ s.map (·.1))) (s.map (·.1)) + +/-- The certificate's levels, the deployed storage `s` alone at level 0. -/ +def seqLevelsOf (s : List (Nat × Nat)) : List (List (List (Nat × Nat))) := [s] :: seqLevels + +/-- Whether the certificate is closed under every call. -/ +def seqClosed : Bool := {"true" if seq_closed else "false"} + +/-- The number of parts the check runs in. -/ +def seqParts : Nat := {seq_parts} + +/-- Whether every `seqParts`-th clean call of the certificate, from the `i`-th, checks. -/ +def seqPartOk (i : Nat) : Bool := + match contract? with + | .ok c => + match deployedStorage fuel c with + | some s => + checkPart (Seq.itemOk fuel c code (seqNext s) (seqLevelsOf s) seqClosed) + (Seq.items fns (seqLevelsOf s)).toArray seqParts i + | none => false + | .error _ => false + +/-- Whether the dirty calls from every storage of the certificate check. -/ +def seqDirtyOk : Bool := + match contract? with + | .ok c => + match deployedStorage fuel c with + | some s => (Seq.states (seqLevelsOf s)).all (Seq.dirtyOk (seqNext s) (seqLevelsOf s) seqClosed) + | none => false + | .error _ => false + +theorem seqDirtyOk_eq_true : seqDirtyOk = true := by native_decide + +end {ns} +""") + + for i in range(seq_parts): + (out / module / f"SeqPart{i}.lean").write_text(f"""{header} +import {ns}.SeqDefs + +namespace {ns} + +theorem seqPart{i} : seqPartOk {i} = true := by native_decide + +end {ns} +""") + + seq_imports = "\n".join([f"import {ns}", f"import {ns}.SeqDefs"] + + [f"import {ns}.SeqPart{i}" for i in range(seq_parts)]) + seq_cases = "\n".join(f" | {i}, _ => seqPart{i}" for i in range(seq_parts)) + if seq_closed: + seq_stmt = "RefinesSeq fuel c code (seqNext s) s (Seq.fullMsg fns)" + seq_apply = "Seq.refinesSeq_of_cert (levels := seqLevelsOf s) (next := seqNext s) hs ⟨[s], List.mem_cons_self, List.mem_singleton_self s⟩" + seq_doc = "every finite sequence of calls" + seq_tail = " exact h" + else: + seq_stmt = f"RefinesSeqUpTo fuel c code (seqNext s) s (Seq.fullMsg fns) {seq_depth}" + seq_apply = "Seq.refinesSeqUpTo_of_cert (levels := seqLevelsOf s) (next := seqNext s) hs (List.mem_singleton_self s)" + seq_doc = f"every sequence of at most {seq_depth} calls" + seq_tail = (f" have hl : (seqLevelsOf s).length = {seq_depth} := rfl\n" + " rw [hl] at h\n exact h") + (out / module / "Seq.lean").write_text(f"""{header} +{seq_imports} + +/-! +# {name}: solar's bytecode refines SolidCore's `Main` on sequences of calls + +`refines_seq` proves that on {seq_doc} from the deployed storage, each +call of any function of `Main` in `{source}` on any argument words below +`2 ^ 256` with no value, and each starting from the storage the previous call +left, SolidCore and solar's bytecode on EthLib finish every call with the same +observables (`SolidCore.Refinement.RefinesSeq`). + +The certificate of reached storages is {variant}. +Its clean calls run in both semantics by `native_decide` (which trusts Lean's +compiler), in `SeqPartI.lean`; its dirty calls reuse `Dirty.run_dirty` and +`target_dirty`, which hold from every storage, with one `native_decide` check of +the storages they keep (`seqDirtyOk_eq_true`). +-/ + +namespace {ns} + +open SolidCore.Refinement SolidCore.Refinement.Abi + +theorem seq_parts_ok : ∀ i < seqParts, seqPartOk i = true := fun i hi => + match i, hi with +{seq_cases} + | n + {seq_parts}, h => absurd h (by simp only [seqParts]; omega) + +/-- solar's runtime bytecode of `Main` refines SolidCore's `Main` on {seq_doc} +of every function on any argument words from the deployed storage. -/ +theorem refines_seq : ∃ c s, contract? = .ok c ∧ deployedStorage fuel c = some s ∧ + {seq_stmt} := by + have h0 := seq_parts_ok 0 (by decide) + have hd := seqDirtyOk_eq_true + match hc : contract?, h0, hd with + | .ok c, h0, hd => + match hs : deployedStorage fuel c with + | some s => + have hsh := shapeOk_eq_true + simp only [shapeOk, hc] at hsh + refine ⟨c, s, rfl, hs, ?_⟩ + have h := {seq_apply} + (all_of_parts (parts := seqParts) (by decide) fun i hi => by + simpa only [seqPartOk, seqClosed, hc, hs] using seq_parts_ok i hi) + (by simpa only [seqDirtyOk, seqClosed, hc, hs] using hd) hsh target_dirty +{seq_tail} + | none => simp [seqPartOk, hc, hs] at h0 + | .error _, h0, _ => simp [seqPartOk, hc] at h0 + +end {ns} +""") + print(f"{source} -> {out}/{module}/Seq.lean ({'closed' if seq_closed else f'depth {seq_depth}'}, " + f"{seq_states} storage(s), {seq_calls} calls, {seq_parts} part(s))") + +seq_mods = sorted(p.parent.name for p in out.glob("*/Seq.lean")) +Path("SolidCore/Refinement/Seq").mkdir(parents=True, exist_ok=True) +Path("SolidCore/Refinement/Seq/Corpus.lean").write_text( + "-- Generated by scripts/refinement/gen_proof.py. Do not edit.\n\n" + "import SolidCore.Refinement.Sequence\n" + + "".join(f"import SolidCore.Refinement.Corpus.{m}.Seq\n" for m in seq_mods) + + "\n/-! The sequence refinement proofs of every contract in scripts/refinement/corpus/\n" + "that has one: `Corpus//Seq.lean`. -/\n") diff --git a/scripts/refinement/kept b/scripts/refinement/kept new file mode 100644 index 00000000..eb478993 --- /dev/null +++ b/scripts/refinement/kept @@ -0,0 +1,8 @@ +# Corpus contracts whose generated refinement proofs are committed: the ones +# SolidCore.Refinement.Headline imports. gen.sh writes Bytecode and Source for every corpus +# contract but a proof only for these. Every name in scripts/refinement/certified is here. +c1 +c4 +w1 +w4 +w5 diff --git a/scripts/refinement/kernel_only.py b/scripts/refinement/kernel_only.py new file mode 100755 index 00000000..3a425642 --- /dev/null +++ b/scripts/refinement/kernel_only.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Fail unless a generated refinement proof is checked by the kernel alone. + + kernel_only.py MODULE... + +Follows the imports of each MODULE (such as SolidCore.Refinement.Corpus.C4) through the +generated corpus modules (SolidCore/Refinement/{Corpus,Bytecode,Source}) and fails, naming +the file and line, on any use outside comments of native_decide, decide +native, bv_decide, +ofReduceBool, ofReduceNat, implemented_by, extern or sorry: each trusts Lean's compiler or +proves nothing. The hand-written libraries these modules import are audited by their own +axioms (#print axioms), not here. +""" +import re +import sys +from pathlib import Path + +GENERATED = ("SolidCore.Refinement.Corpus.", "SolidCore.Refinement.Bytecode.", + "SolidCore.Refinement.Source.") +BANNED = re.compile(r"\bnative_decide\b|\bdecide\s*\+\s*native\b|\bbv_decide\b|\bofReduce(Bool|Nat)\b" + r"|\bimplemented_by\b|@\[extern\b|\bsorry\b") + + +def code_lines(text): + """The lines of TEXT with comments blanked, numbered from 1.""" + text = re.sub(r"/-.*?-/", lambda m: re.sub(r"[^\n]", " ", m.group(0)), text, flags=re.S) + for number, line in enumerate(text.split("\n"), 1): + yield number, line.split("--", 1)[0] + + +def main(modules): + seen, todo, bad = set(), list(modules), [] + while todo: + module = todo.pop() + if module in seen: + continue + seen.add(module) + path = Path(*module.split(".")).with_suffix(".lean") + if not path.is_file(): + sys.exit(f"kernel_only: no file {path} for {module}") + for number, line in code_lines(path.read_text()): + if m := re.match(r"\s*import\s+(\S+)", line): + if m.group(1).startswith(GENERATED): + todo.append(m.group(1)) + elif m := BANNED.search(line): + bad.append(f"{path}:{number}: {m.group(0)}") + if bad: + print("\n".join(bad), file=sys.stderr) + sys.exit(f"kernel_only: {len(bad)} use(s) outside the kernel in {', '.join(modules)}") + print(f"kernel_only: {len(seen)} generated module(s) of {', '.join(modules)} use the kernel alone") + + +if __name__ == "__main__": + if len(sys.argv) < 2: + sys.exit(__doc__) + main(sys.argv[1:]) diff --git a/scripts/refinement/mem/abi_encode.sol b/scripts/refinement/mem/abi_encode.sol new file mode 100644 index 00000000..6ee59138 --- /dev/null +++ b/scripts/refinement/mem/abi_encode.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +contract AbiEncode { + function hashPair(uint256 a, uint256 b) external pure returns (bytes32) { + return keccak256(abi.encode(a, b)); + } +} diff --git a/scripts/refinement/mem/abi_hash.sol b/scripts/refinement/mem/abi_hash.sol new file mode 100644 index 00000000..f8d44f88 --- /dev/null +++ b/scripts/refinement/mem/abi_hash.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +contract AbiHash { + function hashPair(uint256 a, uint256 b) external pure returns (uint256) { + return uint256(keccak256(abi.encode(a, b))); + } +} diff --git a/scripts/refinement/mem/array_sum.sol b/scripts/refinement/mem/array_sum.sol new file mode 100644 index 00000000..966bbc0f --- /dev/null +++ b/scripts/refinement/mem/array_sum.sol @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +contract ArraySum { + function sum(uint256[] calldata xs) external pure returns (uint256 s) { + for (uint256 i = 0; i < xs.length; i++) { + s += xs[i]; + } + } +} diff --git a/scripts/refinement/mem/event_dyn.sol b/scripts/refinement/mem/event_dyn.sol new file mode 100644 index 00000000..71caf708 --- /dev/null +++ b/scripts/refinement/mem/event_dyn.sol @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +contract EventDyn { + event Note(address indexed who, bytes data); + + function note(bytes calldata data) external { + emit Note(msg.sender, data); + } +} diff --git a/scripts/refinement/mem/event_words.sol b/scripts/refinement/mem/event_words.sol new file mode 100644 index 00000000..6d401dd3 --- /dev/null +++ b/scripts/refinement/mem/event_words.sol @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +contract EventWords { + event Swap(address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to); + + function swap(uint256 a0, uint256 a1, uint256 b0, uint256 b1, address to) external { + emit Swap(msg.sender, a0, a1, b0, b1, to); + } +} diff --git a/scripts/refinement/mem/keccak_mem.sol b/scripts/refinement/mem/keccak_mem.sol new file mode 100644 index 00000000..79ed253e --- /dev/null +++ b/scripts/refinement/mem/keccak_mem.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +contract KeccakMem { + function salt(address token0, address token1) external pure returns (bytes32) { + return keccak256(abi.encodePacked(token0, token1)); + } +} diff --git a/scripts/refinement/mem/mem_fmp.sol b/scripts/refinement/mem/mem_fmp.sol new file mode 100644 index 00000000..ee6bf45e --- /dev/null +++ b/scripts/refinement/mem/mem_fmp.sol @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +contract MemFmp { + function pair(uint256 a, uint256 b) external pure returns (uint256) { + uint256[2] memory x; + x[0] = a; + x[1] = b; + return x[0] ^ x[1]; + } +} diff --git a/scripts/refinement/mem/ret_decode.sol b/scripts/refinement/mem/ret_decode.sol new file mode 100644 index 00000000..397e5140 --- /dev/null +++ b/scripts/refinement/mem/ret_decode.sol @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +interface IToken { + function balanceOf(address owner) external view returns (uint256); +} + +contract RetDecode { + function held(IToken token) external view returns (uint256) { + return token.balanceOf(address(this)); + } +} diff --git a/scripts/refinement/mem/safe_transfer.sol b/scripts/refinement/mem/safe_transfer.sol new file mode 100644 index 00000000..96eeda62 --- /dev/null +++ b/scripts/refinement/mem/safe_transfer.sol @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +contract SafeTransfer { + bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)"))); + + function pay(address token, address to, uint256 value) external { + (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); + require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FAILED"); + } +} diff --git a/scripts/refinement/mem/try_catch.sol b/scripts/refinement/mem/try_catch.sol new file mode 100644 index 00000000..b4b9c699 --- /dev/null +++ b/scripts/refinement/mem/try_catch.sol @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +interface IPrice { + function price() external view returns (uint256); +} + +contract TryCatch { + function priceOr(IPrice o, uint256 dflt) external view returns (uint256) { + try o.price() returns (uint256 p) { + return p; + } catch { + return dflt; + } + } +} diff --git a/scripts/refinement/mulx/mul.sol b/scripts/refinement/mulx/mul.sol new file mode 100644 index 00000000..efd1c806 --- /dev/null +++ b/scripts/refinement/mulx/mul.sol @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + uint8 x8; + uint16 y16 = 3; + uint256 z; + function m(uint8 a, uint16 b) external { x8 *= a; y16 *= b; } + function n(uint8 a, uint16 b, uint256 c) external returns (uint256) { z = uint256(a) * b * c; return z; } +} diff --git a/scripts/refinement/prove-rev b/scripts/refinement/prove-rev new file mode 100644 index 00000000..56735643 --- /dev/null +++ b/scripts/refinement/prove-rev @@ -0,0 +1 @@ +9688f21581717743806cb7bf3afae2ac3c156a08 diff --git a/scripts/refinement/routes b/scripts/refinement/routes new file mode 100644 index 00000000..c9038912 --- /dev/null +++ b/scripts/refinement/routes @@ -0,0 +1,3 @@ +# Proof route of each corpus contract whose parameters are all small, read by +# gen_proof.py: symbolic where the symbolic proof builds in reasonable time. +c1 symbolic diff --git a/scripts/refinement/solar-rev b/scripts/refinement/solar-rev new file mode 100644 index 00000000..56735643 --- /dev/null +++ b/scripts/refinement/solar-rev @@ -0,0 +1 @@ +9688f21581717743806cb7bf3afae2ac3c156a08 diff --git a/scripts/refinement/spec/c4.sol b/scripts/refinement/spec/c4.sol new file mode 100644 index 00000000..f45337b6 --- /dev/null +++ b/scripts/refinement/spec/c4.sol @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + uint8 v; + uint8 w = 7; + /// @custom:ensures result == old(v) + x + /// @custom:ensures v == old(v) + x + /// @custom:ensures w == (old(w) ^ x) + /// @custom:succeeds-if v + x < 256 + function add(uint8 x) external returns (uint8) { v += x; w ^= x; return v; } +} diff --git a/scripts/refinement/spec/c4_wrong.sol b/scripts/refinement/spec/c4_wrong.sol new file mode 100644 index 00000000..4a7c7294 --- /dev/null +++ b/scripts/refinement/spec/c4_wrong.sol @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Main { + uint8 v; + uint8 w = 7; + /// @custom:ensures result == old(v) + x + 1 + /// @custom:ensures v == old(v) + x + /// @custom:ensures w == (old(w) ^ x) + /// @custom:succeeds-if v + x < 256 + function add(uint8 x) external returns (uint8) { v += x; w ^= x; return v; } +} diff --git a/scripts/refinement/spec/check.sh b/scripts/refinement/spec/check.sh new file mode 100755 index 00000000..01b435e7 --- /dev/null +++ b/scripts/refinement/spec/check.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# Check the specs solar-verify exported for the spec corpus (scripts/refinement/spec). +# +# SOLAR_VERIFY=path/to/solar-verify scripts/refinement/spec/check.sh +# +# For each annotated source NAME.sol it +# 1. regenerates Contracts/C4/Spec/.lean with solar-verify --emit-lean-spec and fails if it +# differs from the checked-in file; +# 2. checks that the annotated source is the corpus source it annotates +# (scripts/refinement/corpus/c4.sol) with comments and whitespace removed, so the compiler +# sees the same program; +# 3. checks that the manifest's bytecode sha256 is the sha256 of the runtime bytecode the corpus +# refinement is about (SolidCore/Refinement/Bytecode/C4.lean). +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../../.." + +sv="${SOLAR_VERIFY:?set SOLAR_VERIFY to a solar-verify binary with --emit-lean-spec}" +compiler="solar 0.3.0-dev+commit.9688f215" +sha="8a21bc207d9dd8be48d921a717eda3ecb7e5bfcb5397850bc3d64a29037fac47" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT + +for pair in c4:C4:Export c4_wrong:C4Wrong:ExportWrong; do + name="${pair%%:*}" + rest="${pair#*:}"; mod="${rest%%:*}"; file="${rest#*:}" + "$sv" "scripts/refinement/spec/$name.sol" --emit-lean-spec "$tmp/$mod.lean" \ + --lean-spec-module "SolidCore.Spec.Export.$mod" --lean-spec-compiler "$compiler" \ + --lean-spec-bytecode-sha256 "$sha" + diff -u "Contracts/C4/Spec/$file.lean" "$tmp/$mod.lean" +done + +strip() { sed -e 's|//.*$||' "$1" | tr -d ' \t\n'; } +[[ "$(strip scripts/refinement/spec/c4.sol)" == "$(strip scripts/refinement/corpus/c4.sol)" ]] || { + echo "spec/c4.sol is not corpus/c4.sol with comments" >&2 + exit 1 +} + +python3 - "$sha" <<'PY' +import hashlib, re, sys +s = open("SolidCore/Refinement/Bytecode/C4.lean").read() +h = re.search(r"def Main.runtimeNat : Nat :=\s*0x([0-9a-f]+)", s).group(1) +n = int(re.search(r"runtimeSize : Nat := (\d+)", s).group(1)) +got = hashlib.sha256(bytes.fromhex(h.rjust(2 * n, "0"))).hexdigest() +if got != sys.argv[1]: + sys.exit(f"bytecode sha256 {got} is not the manifest's {sys.argv[1]}") +PY +echo "spec exports, sources and bytecode hash check out" diff --git a/scripts/solc_ast_to_lean_source.py b/scripts/solc_ast_to_lean_source.py index 5de6c1eb..83c3215d 100755 --- a/scripts/solc_ast_to_lean_source.py +++ b/scripts/solc_ast_to_lean_source.py @@ -47,7 +47,9 @@ SOURCE_CHILD_FIELDS: set[tuple[str, str]] = {('ArrayTypeName', 'baseType'), ('Ar METADATA_CHILD_FIELDS: set[tuple[str, str]] = {('ContractDefinition', 'documentation'), ('EnumDefinition', 'documentation'), ('ErrorDefinition', 'documentation'), ('EventDefinition', 'documentation'), ('FunctionDefinition', 'documentation'), ('ModifierDefinition', 'documentation'), ('StructDefinition', 'documentation'), ('VariableDeclaration', 'documentation')} SOURCE_SCALAR_FIELDS: set[tuple[str, str]] = {('Assignment', 'operator'), ('BinaryOperation', 'operator'), ('ContractDefinition', 'abstract'), ('ContractDefinition', 'contractKind'), ('ContractDefinition', 'name'), ('ElementaryTypeName', 'name'), ('ElementaryTypeName', 'stateMutability'), ('EnumDefinition', 'name'), ('EnumValue', 'name'), ('ErrorDefinition', 'name'), ('EventDefinition', 'anonymous'), ('EventDefinition', 'name'), ('FunctionCall', 'names'), ('FunctionCallOptions', 'names'), ('FunctionDefinition', 'kind'), ('FunctionDefinition', 'name'), ('FunctionDefinition', 'stateMutability'), ('FunctionDefinition', 'virtual'), ('FunctionDefinition', 'visibility'), ('FunctionTypeName', 'stateMutability'), ('FunctionTypeName', 'visibility'), ('Identifier', 'name'), ('IdentifierPath', 'name'), ('Literal', 'hexValue'), ('Literal', 'kind'), ('Literal', 'subdenomination'), ('Literal', 'value'), ('MemberAccess', 'memberName'), ('ModifierDefinition', 'name'), ('ModifierDefinition', 'virtual'), ('PragmaDirective', 'literals'), ('StructDefinition', 'name'), ('TryCatchClause', 'errorName'), ('TupleExpression', 'components'), ('TupleExpression', 'isInlineArray'), ('UnaryOperation', 'operator'), ('UnaryOperation', 'prefix'), ('UserDefinedValueTypeDefinition', 'name'), ('UsingForDirective', 'functionList.operator'), ('UsingForDirective', 'global'), ('VariableDeclaration', 'constant'), ('VariableDeclaration', 'indexed'), ('VariableDeclaration', 'mutability'), ('VariableDeclaration', 'name'), ('VariableDeclaration', 'stateVariable'), ('VariableDeclaration', 'storageLocation'), ('VariableDeclaration', 'visibility'), ('VariableDeclarationStatement', 'declarations')} ANALYSIS_SCALAR_FIELDS: set[tuple[str, str]] = {('ArrayTypeName', 'typeDescriptions.typeIdentifier'), ('ArrayTypeName', 'typeDescriptions.typeString'), ('Assignment', 'isConstant'), ('Assignment', 'isLValue'), ('Assignment', 'isPure'), ('Assignment', 'lValueRequested'), ('Assignment', 'typeDescriptions.typeIdentifier'), ('Assignment', 'typeDescriptions.typeString'), ('BinaryOperation', 'commonType.typeIdentifier'), ('BinaryOperation', 'commonType.typeString'), ('BinaryOperation', 'isConstant'), ('BinaryOperation', 'isLValue'), ('BinaryOperation', 'isPure'), ('BinaryOperation', 'lValueRequested'), ('BinaryOperation', 'function'), ('BinaryOperation', 'typeDescriptions.typeIdentifier'), ('BinaryOperation', 'typeDescriptions.typeString'), ('Conditional', 'isConstant'), ('Conditional', 'isLValue'), ('Conditional', 'isPure'), ('Conditional', 'lValueRequested'), ('Conditional', 'typeDescriptions.typeIdentifier'), ('Conditional', 'typeDescriptions.typeString'), ('ContractDefinition', 'fullyImplemented'), ('ElementaryTypeName', 'typeDescriptions.typeIdentifier'), ('ElementaryTypeName', 'typeDescriptions.typeString'), ('ElementaryTypeNameExpression', 'argumentTypes.typeIdentifier'), ('ElementaryTypeNameExpression', 'argumentTypes.typeString'), ('ElementaryTypeNameExpression', 'isConstant'), ('ElementaryTypeNameExpression', 'isLValue'), ('ElementaryTypeNameExpression', 'isPure'), ('ElementaryTypeNameExpression', 'lValueRequested'), ('ElementaryTypeNameExpression', 'typeDescriptions.typeIdentifier'), ('ElementaryTypeNameExpression', 'typeDescriptions.typeString'), ('ForStatement', 'isSimpleCounterLoop'), ('FunctionCall', 'argumentTypes.typeIdentifier'), ('FunctionCall', 'argumentTypes.typeString'), ('FunctionCall', 'isConstant'), ('FunctionCall', 'isLValue'), ('FunctionCall', 'isPure'), ('FunctionCall', 'kind'), ('FunctionCall', 'lValueRequested'), ('FunctionCall', 'tryCall'), ('FunctionCall', 'typeDescriptions.typeIdentifier'), ('FunctionCall', 'typeDescriptions.typeString'), ('FunctionCallOptions', 'argumentTypes.typeIdentifier'), ('FunctionCallOptions', 'argumentTypes.typeString'), ('FunctionCallOptions', 'isConstant'), ('FunctionCallOptions', 'isLValue'), ('FunctionCallOptions', 'isPure'), ('FunctionCallOptions', 'lValueRequested'), ('FunctionCallOptions', 'typeDescriptions.typeIdentifier'), ('FunctionCallOptions', 'typeDescriptions.typeString'), ('FunctionDefinition', 'implemented'), ('FunctionTypeName', 'typeDescriptions.typeIdentifier'), ('FunctionTypeName', 'typeDescriptions.typeString'), ('Identifier', 'argumentTypes.typeIdentifier'), ('Identifier', 'argumentTypes.typeString'), ('Identifier', 'typeDescriptions.typeIdentifier'), ('Identifier', 'typeDescriptions.typeString'), ('IndexAccess', 'argumentTypes.typeIdentifier'), ('IndexAccess', 'argumentTypes.typeString'), ('IndexAccess', 'isConstant'), ('IndexAccess', 'isLValue'), ('IndexAccess', 'isPure'), ('IndexAccess', 'lValueRequested'), ('IndexAccess', 'typeDescriptions.typeIdentifier'), ('IndexAccess', 'typeDescriptions.typeString'), ('IndexRangeAccess', 'isConstant'), ('IndexRangeAccess', 'isLValue'), ('IndexRangeAccess', 'isPure'), ('IndexRangeAccess', 'lValueRequested'), ('IndexRangeAccess', 'typeDescriptions.typeIdentifier'), ('IndexRangeAccess', 'typeDescriptions.typeString'), ('Literal', 'isConstant'), ('Literal', 'isLValue'), ('Literal', 'isPure'), ('Literal', 'lValueRequested'), ('Literal', 'typeDescriptions.typeIdentifier'), ('Literal', 'typeDescriptions.typeString'), ('Mapping', 'typeDescriptions.typeIdentifier'), ('Mapping', 'typeDescriptions.typeString'), ('MemberAccess', 'argumentTypes.typeIdentifier'), ('MemberAccess', 'argumentTypes.typeString'), ('MemberAccess', 'isConstant'), ('MemberAccess', 'isLValue'), ('MemberAccess', 'isPure'), ('MemberAccess', 'lValueRequested'), ('MemberAccess', 'typeDescriptions.typeIdentifier'), ('MemberAccess', 'typeDescriptions.typeString'), ('ModifierInvocation', 'kind'), ('NewExpression', 'argumentTypes.typeIdentifier'), ('NewExpression', 'argumentTypes.typeString'), ('NewExpression', 'isConstant'), ('NewExpression', 'isLValue'), ('NewExpression', 'isPure'), ('NewExpression', 'lValueRequested'), ('NewExpression', 'typeDescriptions.typeIdentifier'), ('NewExpression', 'typeDescriptions.typeString'), ('TupleExpression', 'argumentTypes.typeIdentifier'), ('TupleExpression', 'argumentTypes.typeString'), ('TupleExpression', 'isConstant'), ('TupleExpression', 'isLValue'), ('TupleExpression', 'isPure'), ('TupleExpression', 'lValueRequested'), ('TupleExpression', 'typeDescriptions.typeIdentifier'), ('TupleExpression', 'typeDescriptions.typeString'), ('UnaryOperation', 'function'), ('UnaryOperation', 'isConstant'), ('UnaryOperation', 'isLValue'), ('UnaryOperation', 'isPure'), ('UnaryOperation', 'lValueRequested'), ('UnaryOperation', 'typeDescriptions.typeIdentifier'), ('UnaryOperation', 'typeDescriptions.typeString'), ('UserDefinedTypeName', 'typeDescriptions.typeIdentifier'), ('UserDefinedTypeName', 'typeDescriptions.typeString'), ('VariableDeclaration', 'typeDescriptions.typeIdentifier'), ('VariableDeclaration', 'typeDescriptions.typeString')} -METADATA_SCALAR_FIELDS: set[tuple[str, str]] = {('Mapping', 'keyName'), ('Mapping', 'keyNameLocation'), ('Mapping', 'valueName'), ('Mapping', 'valueNameLocation'), ('ModifierDefinition', 'baseModifiers'), ('ModifierDefinition', 'visibility'), ('SourceUnit', 'absolutePath'), ('SourceUnit', 'license'), ('StructDefinition', 'visibility'), ('StructuredDocumentation', 'text'), ('VariableDeclarationStatement', 'assignments')} +# Statement-level NatSpec (solar-verify's @custom: specs) is a comment: it does not change +# the program, so it is metadata like declaration-level documentation. +METADATA_SCALAR_FIELDS: set[tuple[str, str]] = {('Block', 'documentation'), ('Break', 'documentation'), ('Continue', 'documentation'), ('DoWhileStatement', 'documentation'), ('EmitStatement', 'documentation'), ('ExpressionStatement', 'documentation'), ('ForStatement', 'documentation'), ('IfStatement', 'documentation'), ('PlaceholderStatement', 'documentation'), ('Return', 'documentation'), ('RevertStatement', 'documentation'), ('TryStatement', 'documentation'), ('UncheckedBlock', 'documentation'), ('VariableDeclarationStatement', 'documentation'), ('WhileStatement', 'documentation'), ('Mapping', 'keyName'), ('Mapping', 'keyNameLocation'), ('Mapping', 'valueName'), ('Mapping', 'valueNameLocation'), ('ModifierDefinition', 'baseModifiers'), ('ModifierDefinition', 'visibility'), ('SourceUnit', 'absolutePath'), ('SourceUnit', 'license'), ('StructDefinition', 'visibility'), ('StructuredDocumentation', 'text'), ('VariableDeclarationStatement', 'assignments')} METADATA_SCALAR_FIELD_SUFFIXES: set[str] = {'baseFunctions', 'canonicalName', 'contractDependencies', 'errorSelector', 'eventSelector', 'functionReturnParameters', 'functionSelector', 'id', 'linearizedBaseContracts', 'memberLocation', 'nameLocation', 'nameLocations', 'overloadedDeclarations', 'referencedDeclaration', 'scope', 'src', 'usedErrors', 'usedEvents'} SOURCE_SCALAR_VALUE_DOMAINS: dict[tuple[str, str], set[Any]] = { ('Assignment', 'operator'): {'=', '+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '<<=', '>>='}, @@ -1386,6 +1388,158 @@ def expr_from_node(node: dict[str, Any]) -> str: fail(f"unsupported expression node {node_type!r}") + +# Inline assembly is out of SolidCore's fragment except for one exact block (solc's AST of +# the source text: one Yul assignment, no Yul locals, every identifier a Solidity local): +# +# target := create2(value, add(code, 32), mload(code), salt) +# +# with target an address local, code a bytes memory local, and value, salt each a Yul number +# literal or a uint256 (salt also bytes32) local. It is CREATE2 of exactly the bytes of code +# (add(code, 32) is their first byte and mload(code) their length), so it translates to +# Stmt.assemblyCreate2, whose semantics is that opcode's: the new account's address, or 0. +DECLARATION_BY_ID: dict[int, dict[str, Any]] = {} + + +def collect_declarations_by_id(ast: dict[str, Any]) -> dict[int, dict[str, Any]]: + found: dict[int, dict[str, Any]] = {} + + def visit(node: Any) -> None: + if isinstance(node, dict): + node_id = node.get("id") + if node.get("nodeType") == "VariableDeclaration" and isinstance(node_id, int): + found[node_id] = node + for value in node.values(): + visit(value) + elif isinstance(node, list): + for value in node: + visit(value) + + visit(ast) + return found + + +def yul_create2_assignment(node: dict[str, Any]) -> tuple[str, str, str, str] | None: + """The Lean expressions (target, value, code, salt) of an inline assembly block of the one + create2 shape the fragment covers, or None for any other block.""" + if node.get("nodeType") != "InlineAssembly": + return None + if set(node) - {"AST", "evmVersion", "externalReferences", "id", "nodeType", "src", "flags", "documentation"}: + return None + if node.get("flags"): + return None + block = node.get("AST") + if not isinstance(block, dict) or block.get("nodeType") != "YulBlock": + return None + statements = block.get("statements") + if not isinstance(statements, list) or len(statements) != 1: + return None + assignment = statements[0] + if not isinstance(assignment, dict) or assignment.get("nodeType") != "YulAssignment": + return None + targets = assignment.get("variableNames") + if not isinstance(targets, list) or len(targets) != 1: + return None + references = node.get("externalReferences") + if not isinstance(references, list): + return None + by_src: dict[str, dict[str, Any]] = {} + for reference in references: + if not isinstance(reference, dict) or set(reference) - {"declaration", "isOffset", "isSlot", "src", "valueSize", "suffix"}: + return None + if reference.get("isOffset") or reference.get("isSlot") or reference.get("suffix") or reference.get("valueSize") != 1: + return None + by_src[reference.get("src")] = reference + + def call(item: Any, name: str, arity: int) -> list[Any] | None: + if not isinstance(item, dict) or item.get("nodeType") != "YulFunctionCall": + return None + function_name = item.get("functionName") + if not isinstance(function_name, dict) or function_name.get("name") != name: + return None + arguments = item.get("arguments") + if not isinstance(arguments, list) or len(arguments) != arity: + return None + return arguments + + def local(item: Any, types: set[str]) -> str | None: + # A Yul identifier naming a Solidity local (not a state, constant or storage variable) + # of one of the given types (solc type identifiers). + if not isinstance(item, dict) or item.get("nodeType") != "YulIdentifier": + return None + name = item.get("name") + reference = by_src.get(item.get("src")) + if not isinstance(name, str) or reference is None: + return None + declaration = DECLARATION_BY_ID.get(reference.get("declaration")) + if declaration is None or declaration.get("name") != name: + return None + if declaration.get("stateVariable") or declaration.get("constant"): + return None + type_identifier = (declaration.get("typeDescriptions") or {}).get("typeIdentifier") + if type_identifier not in types: + return None + return name + + def number(item: Any) -> str | None: + if not isinstance(item, dict) or item.get("nodeType") != "YulLiteral" or item.get("kind") != "number": + return None + if item.get("type", "") != "": + return None + value = item.get("value") + if not isinstance(value, str): + return None + try: + int(value, 0) + except ValueError: + return None + return value + + def word(item: Any, types: set[str]) -> str | None: + name = local(item, types) + if name is not None: + return f"Expr.ident {lean_string(name)}" + value = number(item) + if value is not None: + return f"Expr.literal (Literal.number {lean_string(str(int(value, 0)))})" + return None + + target = local(targets[0], {"t_address", "t_address_payable"}) + arguments = call(assignment.get("value"), "create2", 4) + if target is None or arguments is None: + return None + value = word(arguments[0], {"t_uint256"}) + start = call(arguments[1], "add", 2) + length = call(arguments[2], "mload", 1) + salt = word(arguments[3], {"t_uint256", "t_bytes32"}) + if value is None or start is None or length is None or salt is None: + return None + code = local(start[0], {"t_bytes_memory_ptr"}) + if code is None or number(start[1]) is None or int(number(start[1]), 0) != 32: + return None + if local(length[0], {"t_bytes_memory_ptr"}) != code: + return None + # Every external reference is one of the identifiers read above. + used = {targets[0].get("src"), arguments[1]["arguments"][0].get("src"), arguments[2]["arguments"][0].get("src")} + for item in (arguments[0], arguments[3]): + if item.get("nodeType") == "YulIdentifier": + used.add(item.get("src")) + if set(by_src) != used or len(by_src) != len(references): + return None + return (f"Expr.ident {lean_string(target)}", value, f"Expr.ident {lean_string(code)}", salt) + + +def without_create2_assembly(value: Any) -> Any: + """The AST with every inline assembly block of the covered create2 shape left out, so the + node guard rejects every other block.""" + if isinstance(value, dict): + return {key: without_create2_assembly(child) for key, child in value.items()} + if isinstance(value, list): + return [without_create2_assembly(child) for child in value + if not (isinstance(child, dict) and yul_create2_assignment(child) is not None)] + return value + + def stmt_from_node(node: dict[str, Any]) -> str: node_type = node.get("nodeType") if node_type == "Block": @@ -1529,6 +1683,11 @@ def stmt_from_node(node: dict[str, Any]) -> str: return "Stmt.continue" if node_type == "PlaceholderStatement": return "Stmt.modifierPlaceholder" + if node_type == "InlineAssembly": + create2 = yul_create2_assignment(node) + if create2 is None: + fail("inline assembly other than one create2 assignment is out of scope") + return "Stmt.assemblyCreate2 " + " ".join(f"({part})" for part in create2) fail(f"unsupported statement node {node_type!r}") @@ -2153,7 +2312,9 @@ def render_module(ast: dict[str, Any], source_name: str, contract_name: str, nam global FUNCTION_NAME_BY_ID FUNCTION_PARAM_COUNT_BY_ID = collect_function_param_counts(ast) FUNCTION_NAME_BY_ID = collect_function_names_by_id(ast) - guard_no_unsupported_nodes(ast) + DECLARATION_BY_ID.clear() + DECLARATION_BY_ID.update(collect_declarations_by_id(ast)) + guard_no_unsupported_nodes(without_create2_assembly(ast)) contract = find_contract(ast, contract_name) contracts = contract_definitions(ast) segments = namespace_segments(namespace) @@ -2211,6 +2372,29 @@ def render_module(ast: dict[str, Any], source_name: str, contract_name: str, nam return "\n".join(lines) +def omit_functions(ast: dict[str, Any], names: Sequence[str]) -> dict[str, Any]: + """The AST with each named function definition removed; each name must match at least once.""" + wanted: dict[tuple[str, str], int] = {} + for name in names: + contract, sep, function = name.partition(".") + if not sep or not contract or not function: + fail(f"--omit-function {name!r} is not CONTRACT.FUNCTION") + wanted[(contract, function)] = 0 + for node in contract_definitions(ast): + kept = [] + for item in node.get("nodes", []): + key = (node.get("name"), item.get("name")) + if item.get("nodeType") == "FunctionDefinition" and key in wanted: + wanted[key] += 1 + else: + kept.append(item) + node["nodes"] = kept + missing = [f"{c}.{f}" for (c, f), n in wanted.items() if n == 0] + if missing: + fail("--omit-function matched no function: " + ", ".join(missing)) + return ast + + def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("source", type=Path) @@ -2221,6 +2405,14 @@ def build_parser() -> argparse.ArgumentParser: default="SolidCore.Solidity.SolcAstImport.Generated", ) parser.add_argument("--body-only", action="store_true") + parser.add_argument( + "--omit-function", + action="append", + default=[], + metavar="CONTRACT.FUNCTION", + help="leave the named function out of the translation (every overload of it); the result " + "is a contract without it, so nothing proved of the result covers that function", + ) parser.add_argument( "--audit-coverage", action="store_true", @@ -2244,6 +2436,8 @@ def main(argv: Sequence[str] | None = None) -> int: solc = resolve_executable(args.solc) source = args.source.resolve() source_name, ast = run_solc_ast(solc, source) + if args.omit_function: + ast = omit_functions(ast, args.omit_function) if args.audit_coverage: print(json.dumps(frontend_coverage(ast), indent=2, sort_keys=True)) return 0 diff --git a/scripts/verify/Counter.sol b/scripts/verify/Counter.sol new file mode 100644 index 00000000..c27e1c20 --- /dev/null +++ b/scripts/verify/Counter.sol @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +/// @custom:invariant count <= limit +contract Counter { + uint256 public count; + uint256 public limit; + + /// @custom:ensures limit == _limit && count == 0 + constructor(uint256 _limit) { + limit = _limit; + } + + /// @custom:requires count < limit + /// @custom:ensures count == old(count) + 1 + function increment() external { + count += 1; + } + + /// @custom:ensures count == old(count) + n + function bump(uint256 n) external { + require(count + n <= limit, "over"); + /// @custom:invariant i <= n + /// @custom:invariant count == old(count) + i + /// @custom:decreases n - i + for (uint256 i = 0; i < n; i++) { + count++; + } + } + + /// @custom:ensures result == (a >= b ? a : b) + /// @custom:ensures result >= a && result >= b + function max(uint256 a, uint256 b) public pure returns (uint256) { + if (a >= b) return a; + return b; + } +} diff --git a/scripts/verify/CounterMilestone.sol b/scripts/verify/CounterMilestone.sol new file mode 100644 index 00000000..5a7a17e3 --- /dev/null +++ b/scripts/verify/CounterMilestone.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Counter { + uint256 x; + /// @custom:ensures x == old(x) + d + function inc(uint256 d) external { x += d; } + function get() external view returns (uint256) { return x; } +} diff --git a/scripts/verify/MANIFEST b/scripts/verify/MANIFEST new file mode 100644 index 00000000..cd74918a --- /dev/null +++ b/scripts/verify/MANIFEST @@ -0,0 +1,9 @@ +# SHA-256 of the sources and of solar-verify's transcripts (--dry-run --dump-smt). +# solar-verify: paradigmxyz/solar alpharush/verify at 4c1c187 with --dump-lean; solc 0.8.35 for the source AST. +f1c87a334b8db31fc8f80541febeaf8617318d20b685634f44e26c74146ad326 Counter.sol +45b62aa1152c4ec09e76735ac7257a06bf3e4be0f435fdacdc174f41e8c8e75c Token.sol +6db0750ba689e6aff86103e846e76739d732822f9a436efe2bc2ec69b935cb8e Counter.smt2 +59ba90cc3e7c018685d759fb6c566d82bddd147db3cc7581f835154a95b52b90 Token.smt2 +# CounterMilestone and the Counter mutants: solar-verify from paradigmxyz/solar alpharush/verify-dump-lean with the raw-section exporter change (same output for Counter and Token). +6ed83fe1a6c41fb109c6a880ed372b37ca1d895b9bde4bb5f202461289706da9 CounterMilestone.sol +1c38d99ffd21a587329c1c5ad39b97a144809a4c751d5adfb6636f665022c5e1 CounterMilestone.smt2 diff --git a/scripts/verify/Token.sol b/scripts/verify/Token.sol new file mode 100644 index 00000000..70d2f281 --- /dev/null +++ b/scripts/verify/Token.sol @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +/// A minimal token. The invariant ties the ghost sum of balances to totalSupply, with +/// Certora-style ghost updates written next to every balance write. +/// @custom:ghost uint256 sumBalances +/// @custom:invariant totalSupply == sumBalances +contract Token { + mapping(address => uint256) public balanceOf; + uint256 public totalSupply; + address public owner; + + modifier onlyOwner() { + require(msg.sender == owner, "not owner"); + _; + } + + /// @custom:ensures owner == msg.sender + constructor() { + owner = msg.sender; + } + + /// @custom:ensures balanceOf[to] == old(balanceOf[to]) + amount + /// @custom:ensures totalSupply == old(totalSupply) + amount + /// @custom:ensures forall address a :: a != to ==> balanceOf[a] == old(balanceOf[a]) + function mint(address to, uint256 amount) external onlyOwner { + totalSupply += amount; + /// @custom:ghost sumBalances = sumBalances + amount + balanceOf[to] += amount; + } + + /// @custom:ensures msg.sender != to ==> balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount + /// @custom:ensures msg.sender != to ==> balanceOf[to] == old(balanceOf[to]) + amount + /// @custom:ensures forall address a :: a != msg.sender && a != to ==> balanceOf[a] == old(balanceOf[a]) + /// @custom:ensures totalSupply == old(totalSupply) + function transfer(address to, uint256 amount) external returns (bool) { + uint256 bal = balanceOf[msg.sender]; + require(bal >= amount, "insufficient"); + balanceOf[msg.sender] = bal - amount; + balanceOf[to] += amount; + return true; + } + + /// @custom:ensures balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount + function burn(uint256 amount) external { + balanceOf[msg.sender] -= amount; + /// @custom:ghost sumBalances = sumBalances - amount + totalSupply -= amount; + } +} diff --git a/scripts/verify/cert-search.lean.in b/scripts/verify/cert-search.lean.in new file mode 100644 index 00000000..75ff81e1 --- /dev/null +++ b/scripts/verify/cert-search.lean.in @@ -0,0 +1,221 @@ +/- +Certificate search for Verify/VC/Cert.lean (not trusted: the kernel checks what it finds). +Instantiated by scripts/verify/cert-search.sh, which substitutes the export module and script. +For each obligation in OBS it tries fact masks (tight, then by shared atoms at depth 1, 2, 3, +then all facts; or MASK), runs the tableau with case splits deferred behind the other facts, +and closes each branch by Fourier-Motzkin on growing subsets of its constraints, tracking the +multipliers; it writes OUT/certs/ob.txt (" ") once refuteObC accepts it. +-/ +import @IMPORT@ +import Verify.VC.Cert +open SolidCore.Verify.VC +def scr := @SCRIPT@ +def trimZ (w : List Nat) : List Nat := (w.reverse.dropWhile (· == 0)).reverse +partial def SolidCore.Verify.VC.Cert.toLean : Cert → String + | .leaf w => s!"(.leaf {trimZ w})" + | .later c => s!"(.later {c.toLean})" + | .keep m c => s!"(.keep {m} {c.toLean})" + | .br hs => "(.br [" ++ ", ".intercalate (hs.map Cert.toLean) ++ "])" + +def fmW2 (cap : Nat) : Nat → List (Lin × List Nat) → Option (List Nat) + | 0, _ => none + | n + 1, cs => + let cs := cs.filter fun l => !(l.1.cs.isEmpty && decide (l.1.k ≤ 0)) + match cs.find? (fun l => l.1.cs.isEmpty && decide (0 < l.1.k)) with + | some l => some l.2 + | none => + let ls := cs.map (·.1) + match pickVar ls with + | none => none + | some x => if elimCost ls x ≤ cap ∧ cs.length ≤ 4 * cap then fmW2 cap n (elimW x cs) else none + +def atomsOf (l : Lin) : List Tm := l.cs.map (·.1) +def memT (x : Tm) (xs : List Tm) : Bool := xs.any fun y => Tm.beq x y + +def grow (ics : List (Lin × Nat)) (seed : List Tm) : Nat → List Tm + | 0 => seed + | n + 1 => + let s := ics.filter fun (l, _) => (atomsOf l).any fun a => memT a seed + grow ics (seed ++ (s.flatMap fun (l, _) => (atomsOf l).filter fun a => !memT a seed)) n + +def fmSub (cap : Nat) (m : Nat) (sub : List (Lin × Nat)) : Option (List Nat) := + if (fmW2 cap 1000 (sub.map fun (l, _) => (l, []))).isNone then none else + fmW2 cap 1000 (sub.map fun (l, i) => (l, (List.range m).map fun j => if i = j then 1 else 0)) + +def linBeq (a b : Lin) : Bool := + a.k == b.k && a.cs.length == b.cs.length && (a.cs.zip b.cs).all fun (p, q) => p.2 == q.2 && Tm.beq p.1 q.1 + +def fmCert2 (cap : Nat) (cs : List Lin) : Option Cert := Id.run do + let m := cs.length + let mut acc : Array (Lin × Nat) := #[] + for (l, i) in cs.zipIdx do + if !(l.cs.isEmpty && decide (l.k ≤ 0)) && !(acc.any fun (l', _) => linBeq l l') then + acc := acc.push (l, i) + let ics := acc.toList + if let some w := fmSub cap m ics then return some (.leaf w) + for (l0, _) in ics do + for d in [0, 1, 2] do + let seed := grow ics (atomsOf l0) d + let sub := ics.filter fun (l, _) => (atomsOf l).all fun a => memT a seed + if let some w := fmSub cap m sub then return some (.leaf w) + match fmSub cap m ics with + | some w => return some (.leaf w) + | none => return none + +def isBranch : Step → Bool + | .split _ => true + | .ite _ _ _ => true + | _ => false + +def deferrable : Step → Bool + | .split _ => true + | .ite c _ _ => (iteEqs c).isEmpty + | _ => false + +def refuteG3 (cap : Nat) (ks : List String) : Nat → List Tm → List Lin → StateM (Nat × List (List Lin)) (Option Cert) + | 0, _, _ => pure none + | _ + 1, [], cs => do + let b := (← get).1 + if b = 0 then return none + modify fun s => (b - 1, s.2) + let r := fmCert2 cap cs + if r.isNone then modify fun s => (s.1, cs :: s.2) + return r + | n + 1, t :: rest, cs => do + let st := step ks t + if deferrable st && rest.any (fun u => !isBranch (step ks u)) then + return (← refuteG3 cap ks n (rest ++ [t]) cs).map .later + match st with + | .drop => refuteG3 cap ks n rest cs + | .closed => return some (.leaf []) + | .facts ts => refuteG3 cap ks n (ts ++ rest) cs + | .cons ls => refuteG3 cap ks n rest (ls ++ cs) + | .split bs => + let b := (← get).1 + if b = 0 then return none + modify fun s => (b - 1, s.2) + match fmCert2 cap cs with + | some c => return some c + | none => + let mut hs := #[] + for ts in bs do + match ← refuteG3 cap ks n (ts ++ rest) cs with + | some h => hs := hs.push h + | none => return none + return some (.br hs.toList) + | .ite c t1 t2 => + let b := (← get).1 + if b = 0 then return none + modify fun s => (b - 1, s.2) + match fmCert2 cap cs with + | some w => return some w + | none => + let some h1 ← refuteG3 cap ks n + (c :: ((t1 :: rest).map (resolve c true resolveFuel)).map (substN (iteEqs c) substFuel)) (cs.map (Lin.substE (iteEqs c))) | return none + let some h2 ← refuteG3 cap ks n (neg c :: (t2 :: rest).map (resolve c false resolveFuel)) cs | return none + return some (.br [h1, h2]) + | .skolem x t => + if fresh x rest cs then refuteG3 cap ks n (t :: rest) cs + else if fresh (x ++ "'") (t :: rest) cs then + refuteG3 cap ks n (t.subst .int x (.ivar (x ++ "'")) :: rest) cs + else refuteG3 cap ks n rest cs + +partial def atomsT : Tm → List Tm + | t@(.app f args) => + if f = "select" then [t] + else if f = "mod" || f = "div" then t :: args.flatMap atomsT + else args.flatMap atomsT + | .all _ b => atomsT b + | _ => [] + +partial def hasIte : Tm → Bool + | .app f args => f = "ite" || args.any hasIte + | .all _ b => hasIte b + | _ => false + +def selAtoms (t : Tm) : List Tm := (atomsT t).filter fun a => match a with + | .app "select" _ => true + | _ => false + +def maskTight (ts : List Tm) (guard : Nat) : List Bool := + let g := selAtoms (ts.headD .tt) + ts.zipIdx.map fun (t, i) => i == 0 || i == guard || + ((i > guard || !hasIte t) && (selAtoms t).all (fun a => memT a g)) && !(isBranch (step [] t) && (atomsT t).isEmpty) + +/-- Every fact but the range facts of terms with an ite before the path guard, and the scalar +facts that split. -/ +def maskNoIte (ts : List Tm) (guard : Nat) : List Bool := + ts.zipIdx.map fun (t, i) => i == 0 || i >= guard || + (!hasIte t && !(isBranch (step [] t) && (atomsT t).isEmpty)) + +def maskFor (ts : List Tm) (d : Nat) : List Bool := Id.run do + let as := ts.map atomsT + let mut front : List Tm := as.headD [] + let mut keep : Array Bool := (List.replicate ts.length false).toArray + keep := keep.set! 0 true + for _ in List.range d do + let mut add : List Tm := [] + for (a, i) in as.zipIdx do + if !keep[i]! && a.any (fun x => memT x front) then + keep := keep.set! i true + add := add ++ a + front := front ++ add + return (keep.toList.zip ts).map fun (b, t) => b || (atomsT t).isEmpty + +def prepOb (fs : List Tm) (d : Bool) : List String × List Tm := + let eqs := fs.filterMap eqOf? + let gs := (fs.filter fun t => (eqOf? t).isNone).map fun t => rowN rowFuel (substN eqs substFuel t) + let rs := relevant gs + (goalBinders rs, if d then goalFirst rs ++ divFacts rs else goalFirst rs) + +#eval show IO Unit from do + let args := (← IO.getEnv "OBS").getD "" + let cap := ((← IO.getEnv "CAP").getD "256").toNat! + let budget := ((← IO.getEnv "BUDGET").getD "3000").toNat! + let obs := (args.splitOn ",").filterMap String.toNat? + let err ← IO.getStderr + let outDir := (← IO.getEnv "OUT").getD "." + for i in obs do + let fs := (obligations scr).getD i [] + let (ks, ts) := prepOb fs true + let mut found := false + if (← IO.getEnv "OLDFIRST").isSome then + if (obligations scr).getD i [] |> isProbe then + IO.FS.writeFile s!"{outDir}/certs/ob{i}.txt" "false (.leaf [])" + found := true + else if let some (d, c) := certAt scr i then + IO.FS.writeFile s!"{outDir}/certs/ob{i}.txt" s!"{d} {c.toLean}" + found := true + let maskEnv := (← IO.getEnv "MASK").map fun e => ((e.splitOn ",").filterMap String.toNat?) + let nfs := (let eqs := fs.filterMap eqOf? + let gs := (fs.filter fun t => (eqOf? t).isNone).map fun t => rowN rowFuel (substN eqs substFuel t) + (relevant gs).length) + for d in (if found then [] else if maskEnv.isSome then [0] else [7, 8, 1, 2, 3, 100]) do + if found then break + let m := match maskEnv with + | some ix => (List.range ts.length).map fun j => ix.contains j + | none => if d = 7 then maskTight ts (nfs - 1) else if d = 8 then maskNoIte ts (nfs - 1) else maskFor ts d + let t0 ← IO.monoMsNow + let (r, (left, fails)) := (refuteG3 cap ks stepFuel (keepMask m ts) []).run (budget, []) + if let some cs := fails.getLast? then + IO.FS.writeFile s!"{outDir}/leaf{i}-{d}.txt" (String.intercalate "\n" (cs.map fun l => s!"{l.k} + {repr l.cs}")) + match r with + | some c => + let direct := refuteC ks stepFuel (keepMask m ts) [] c + let c := Cert.keep m c + let ok := refuteObC fs true c + err.putStrLn s!"direct={direct}" + IO.FS.writeFile s!"{outDir}/dbg{i}.txt" s!"direct={direct} ok={ok} cert={c.toLean}" + + err.putStrLn s!"OB {i} d={d} kept={(m.filter id).length}/{m.length} FOUND ok={ok} left={left} {(← IO.monoMsNow) - t0}ms" + if ok then + found := true + IO.FS.writeFile s!"{outDir}/certs/ob{i}.txt" s!"true {c.toLean}" + | none => err.putStrLn s!"OB {i} d={d} kept={(m.filter id).length}/{m.length} NONE left={left} {(← IO.monoMsNow) - t0}ms" + IO.FS.writeFile s!"{outDir}/g3-{i}-{d}.log" s!"{r.isSome} left={left} fails={fails.length}" + if !found then + if (obligations scr).getD i [] |> isProbe then + IO.FS.writeFile s!"{outDir}/certs/ob{i}.txt" "false (.leaf [])" + else match certAt scr i with + | some (d, c) => IO.FS.writeFile s!"{outDir}/certs/ob{i}.txt" s!"{d} {c.toLean}" + | none => err.putStrLn s!"OB {i} NONE" diff --git a/scripts/verify/cert-search.sh b/scripts/verify/cert-search.sh new file mode 100755 index 00000000..35d8ac65 --- /dev/null +++ b/scripts/verify/cert-search.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# Usage: cert-search.sh IMPORT SCRIPT OUT OBS [MASK] +# Writes OUT/certs/ob.txt for each obligation index in OBS (comma-separated) that the search +# certifies; scripts/verify/gen-certified.py turns OUT/certs into kernel-checked modules. +set -eu +imp="$1"; script="$2"; out="$3"; obs="$4"; mask="${5-}" +mkdir -p "$out/certs" +f=$(mktemp --suffix=.lean -p "$out") +sed -e "s|@IMPORT@|$imp|" -e "s|@SCRIPT@|$script|" "$(dirname "$0")/cert-search.lean.in" > "$f" +if [ -n "$mask" ]; then export MASK="$mask"; fi +OUT="$out" OBS="$obs" lake env lean "$f" +rm -f "$f" diff --git a/scripts/verify/check.sh b/scripts/verify/check.sh new file mode 100755 index 00000000..c569155a --- /dev/null +++ b/scripts/verify/check.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash +# Regenerate solar-verify's exports and fail if any changed. +# +# SOLAR_VERIFY=/path/to/solar-verify scripts/verify/check.sh +# +# For each scripts/verify/NAME.sol (a copy of solar's crates/verify/examples/NAME.sol, or an +# annotated copy of a source the refinement certifies) and each mutant in scripts/verify/mutant, +# runs solar-verify --dry-run with --dump-smt and --dump-lean, compares the Lean module with its +# file under Contracts/ (out_of), and the source's and transcript's SHA-256 with the MANIFEST. +# lake build ContractsVC then checks (Contracts/NAME/VC/Bind.lean) that each script prints back to +# its transcript. It also compares solar-verify's spec exports (--emit-lean-spec) with +# Contracts/Counter/Spec/{Export,ExportWrong}.lean (spec_of). +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../.." +: "${SOLAR_VERIFY:?set SOLAR_VERIFY to a solar-verify binary built with --dump-lean and --emit-lean-spec}" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +status=0 +# Annotated copies of sources the refinement certifies: stripping the NatSpec lines must give +# the certified source back byte for byte. +if ! grep -v '^ *///' scripts/verify/CounterMilestone.sol | cmp -s - scripts/refinement/counter/counter.sol; then + echo "error: scripts/verify/CounterMilestone.sol is not scripts/refinement/counter/counter.sol plus NatSpec" >&2 + status=1 +fi +# Token's certified backend (Certified/verify_token) compiles this Token: the same bytes, and the +# source hash its stage manifest records is the one MANIFEST pins. +if ! cmp -s scripts/verify/Token.sol Certified/verify_token/verify_token.sol; then + echo "error: Certified/verify_token/verify_token.sol is not scripts/verify/Token.sol" >&2 + status=1 +fi +token_sha="$(grep ' Token.sol$' scripts/verify/MANIFEST | cut -d' ' -f1)" +if ! grep -qF "\"$token_sha\")]" Certified/verify_token/gen/Token/Manifest.lean; then + echo "error: Certified/verify_token's stage manifest records no source with sha256 $token_sha" >&2 + status=1 +fi +# The Lean module of each transcript. +out_of() { + case "$1" in + CounterMilestone) echo Contracts/Counter/VC/ExportMilestone.lean ;; + CounterSrcMut) echo Contracts/Counter/VC/Mutant/SrcMut.lean ;; + CounterSpecMut) echo Contracts/Counter/VC/Mutant/SpecMut.lean ;; + TokenSrcMut) echo Contracts/Token/VC/Mutant/SrcMut.lean ;; + TokenSpecMut) echo Contracts/Token/VC/Mutant/SpecMut.lean ;; + *) echo "Contracts/$1/VC/Export.lean" ;; + esac +} +check() { # check DIR NAMESPACE_PREFIX + local dir="$1" ns="$2" sol name rc f want got out + for sol in "$dir"/*.sol; do + name="$(basename "$sol" .sol)" + out="$(out_of "$name")" + # A dry run proves nothing, so solar-verify exits 1; 2 is an error. + rc=0 + "$SOLAR_VERIFY" --dry-run --dump-smt "$tmp/$name.smt2" --dump-lean "$tmp/$name.lean" \ + --lean-namespace "$ns.$name" "$sol" > /dev/null 2> "$tmp/$name.err" || rc=$? + if [[ $rc -gt 1 ]]; then cat "$tmp/$name.err" >&2; exit "$rc"; fi + # The export imports the library by its module path in this repository. + sed -i 's/^import SolidCore\.Verify\.VC\.Term$/import Verify.VC.Term/' "$tmp/$name.lean" + if ! cmp -s "$tmp/$name.lean" "$out"; then + echo "error: $out differs from solar-verify's export" >&2 + status=1 + fi + # A function outside the Lean fragment is left raw: refused, never checked. + grep '^-- Left raw' "$tmp/$name.lean" | sed "s|^-- Left raw, outside the Lean fragment: |refused ($name): |" >&2 || true + for f in "$sol" "$tmp/$name.smt2"; do + want="$(grep " $(basename "$f")\$" "$dir/MANIFEST" | cut -d' ' -f1)" + got="$(sha256sum "$f" | cut -d' ' -f1)" + if [[ "$want" != "$got" ]]; then + echo "error: $(basename "$f"): sha256 $got, $dir/MANIFEST says ${want:-nothing}" >&2 + status=1 + fi + done + done +} +check scripts/verify SolidCore.Verify.VC.Export +check scripts/verify/mutant SolidCore.Verify.VC.Export.Mutant +# solar-verify's spec exports, bound to the counter milestone's compiler and bytecode +# (solar-tv/milestone/counter's manifest). +counter_compiler="0.8.38+commit.1134e61f.solar.0.3.0-dev" +counter_bytecode="daed21b0c790bb2c08bcf999c9ebc6fea950c213ea0a799418552aa14c18f6ec" +spec_of() { # spec_of SOURCE MODULE OUT + rm -f "$tmp/spec.lean" + "$SOLAR_VERIFY" --dry-run --emit-lean-spec "$tmp/spec.lean" --lean-spec-module "$2" \ + --lean-spec-compiler "$counter_compiler" --lean-spec-bytecode-sha256 "$counter_bytecode" \ + "$1" > /dev/null 2> "$tmp/spec.err" || true + if [[ ! -s "$tmp/spec.lean" ]]; then + cat "$tmp/spec.err" >&2 + echo "error: solar-verify wrote no spec export for $1" >&2 + status=1 + return + fi + sed -i 's/^import SolidCore\.Spec\.Contract$/import Verify.Spec.Contract/' "$tmp/spec.lean" + if ! cmp -s "$tmp/spec.lean" "$3"; then + echo "error: $3 differs from solar-verify's spec export" >&2 + diff "$tmp/spec.lean" "$3" >&2 || true + status=1 + fi +} +spec_of scripts/verify/CounterMilestone.sol SolidCore.Spec.Export.Counter Contracts/Counter/Spec/Export.lean +spec_of scripts/verify/mutant/CounterSpecMut.sol SolidCore.Spec.Export.CounterSpecMut \ + Contracts/Counter/Spec/ExportWrong.lean +exit "$status" diff --git a/scripts/verify/create2_sources.py b/scripts/verify/create2_sources.py new file mode 100755 index 00000000..e54cb628 --- /dev/null +++ b/scripts/verify/create2_sources.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +"""Writes and tests the frontend's translation of inline assembly create2 (Contracts/Create2). + + scripts/verify/create2_sources.py [--solc SOLC] [--check] + +Writes Contracts/Create2/Source.lean, the frontend's translation of Contracts/Create2/Deployer.sol, +and Contracts/Create2/SourceView.lean, the same with `deploy` declared `view` (which solc rejects +before it writes an AST, so the mutation is made on the translation): SolidCore's checker must +reject it (Contracts/Create2/Run.lean). Then checks that the frontend rejects every other inline +assembly block of the negative cases below. With --check, compares instead of writing and exits 1 +on a difference or on a case the frontend does not decide as expected. +""" + +import argparse +import pathlib +import subprocess +import sys +import tempfile + +ROOT = pathlib.Path(__file__).resolve().parent.parent.parent +FRONTEND = ROOT / "scripts" / "solc_ast_to_lean_source.py" +DIR = ROOT / "Contracts" / "Create2" +NAMESPACE = "SolidCore.Verify.Create2.Source" +VIEW_NAMESPACE = "SolidCore.Verify.Create2.SourceView" + +# (name, function body): each block is outside the one create2 shape, so the frontend fails. +NEGATIVE = [ + ("offset 64", "assembly { a := create2(0, add(code, 64), mload(code), salt) }"), + ("create", "assembly { a := create(0, add(code, 32), mload(code)) }"), + ("length of another local", "bytes memory other = code; assembly { a := create2(0, add(code, 32), mload(other), salt) }"), + ("two statements", "assembly { a := create2(0, add(code, 32), mload(code), salt) a := 0 }"), + ("Yul local", "assembly { let s := salt a := create2(0, add(code, 32), mload(code), s) }"), + ("bytes16 salt", "bytes16 s = bytes16(salt); assembly { a := create2(0, add(code, 32), mload(code), s) }"), + ("uint8 value", "uint8 v = 0; assembly { a := create2(v, add(code, 32), mload(code), salt) }"), + ("value expression", "assembly { a := create2(callvalue(), add(code, 32), mload(code), salt) }"), + ("memory target", "bytes memory b; assembly { b := create2(0, add(code, 32), mload(code), salt) }"), + ("uint256 target", "uint256 w; assembly { w := create2(0, add(code, 32), mload(code), salt) }"), +] +NEGATIVE_SOURCE = """// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +contract Negative { + function f(bytes32 salt) external returns (address a) { + bytes memory code = hex"00"; + BODY + } +} +""" + + +HEAD = "import SolidCore.Solidity.Checked\nimport SolidCore.Witness.Checked\n" + + +def translate(solc: str, sol: pathlib.Path, contract: str, namespace: str) -> subprocess.CompletedProcess: + out = subprocess.run( + [sys.executable, str(FRONTEND), "--solc", solc, "--contract", contract, "--namespace", namespace, + str(sol)], cwd=ROOT, capture_output=True, text=True) + if out.returncode == 0: + # As scripts/verify/uniswap_v2_sources.py: the checker's import only, the frontend's + # opens, and the source's path relative to the repository. + if not out.stdout.startswith(HEAD): + sys.exit("error: unexpected frontend header") + out.stdout = ("import SolidCore.Solidity.Checked\n\nopen SolidCore.Solidity\n" + + out.stdout[len(HEAD):].replace(str(ROOT) + "/", "")) + return out + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--solc", default="solc") + ap.add_argument("--check", action="store_true") + a = ap.parse_args() + status = 0 + sol = (DIR / "Deployer.sol").relative_to(ROOT) + out = translate(a.solc, sol, "Deployer", NAMESPACE) + if out.returncode != 0: + print(out.stderr, file=sys.stderr) + return 1 + source = out.stdout + out = translate(a.solc, sol, "Deployer", VIEW_NAMESPACE) + if out.returncode != 0: + print(out.stderr, file=sys.stderr) + return 1 + view = out.stdout + deploy = 'name := some "deploy",' + old, new = "mutability := StateMutability.nonpayable", "mutability := StateMutability.view" + if view.count(deploy) != 1: + sys.exit("error: expected one deploy function") + j = view.index(old, view.index(deploy)) + view = view[:j] + new + view[j + len(old):] + header = ("-- Generated from Contracts/Create2/Deployer.sol with solc 0.8.35 by " + "scripts/verify/create2_sources.py. Do not edit.\n\n") + for name, text in (("Source.lean", header + source), ("SourceView.lean", header + view)): + path = DIR / name + if a.check: + if not path.exists() or path.read_text() != text: + print(f"error: {path.relative_to(ROOT)} is out of date", file=sys.stderr) + status = 1 + else: + path.write_text(text) + with tempfile.TemporaryDirectory() as tmp: + for name, body in NEGATIVE: + neg = pathlib.Path(tmp) / "Negative.sol" + neg.write_text(NEGATIVE_SOURCE.replace("BODY", body)) + compiled = subprocess.run([a.solc, "--ast-compact-json", str(neg)], capture_output=True, text=True) + if compiled.returncode != 0: + print(f"error: negative case {name!r} does not compile:\n{compiled.stderr}", file=sys.stderr) + status = 1 + continue + res = translate(a.solc, neg, "Negative", "X") + if res.returncode == 0 or "assembly" not in res.stderr.lower(): + print(f"error: the frontend accepted negative case {name!r}", file=sys.stderr) + status = 1 + else: + print(f"rejected {name}: {res.stderr.strip().splitlines()[-1]}") + return status + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/verify/gen-certified.py b/scripts/verify/gen-certified.py new file mode 100755 index 00000000..cbe97703 --- /dev/null +++ b/scripts/verify/gen-certified.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Write Lean modules that discharge a solar-verify --dump-lean script in the kernel along +certificates (Verify/VC/Cert.lean). + +Usage: gen-certified.py MODULE NAMESPACE IMPORT SCRIPT COUNT CERTDIR [--chunk K] + [--reject IMPORT SCRIPT INDEX]... + +CERTDIR holds ob.txt, " " as scripts/verify/certs.lean writes them (the +compiled search, not trusted). Writes MODULE.Part, one theorem per obligation +(dischargeAtC SCRIPT i d cert = true, by decide +kernel), and MODULE: the count of obligations and +script_valid : Valid SCRIPT from dischargeScript_of_certs. Without a certificate for every +obligation, MODULE proves only the obligations it has and lists the rest; no script_valid. +Each --reject names a mutant script and an obligation the plain discharge rejects there. +""" +import os +import sys + +HEADER = "set_option maxRecDepth 100000" + + +def write(module, lines): + path = module.replace(".", "/") + ".lean" + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w") as f: + f.write("\n".join(lines)) + + +def main(argv): + module, ns, imp, script, count, certdir = argv[:6] + count = int(count) + chunk = 2 + rejects = [] + rest = argv[6:] + while rest: + if rest[0] == "--chunk": + chunk = int(rest[1]); rest = rest[2:] + elif rest[0] == "--reject": + rejects.append((rest[1], rest[2], int(rest[3]))); rest = rest[4:] + else: + sys.exit(f"unknown argument {rest[0]}") + certs = {} + for i in range(count): + p = os.path.join(certdir, f"ob{i}.txt") + if os.path.exists(p): + d, c = open(p).read().strip().split(" ", 1) + certs[i] = (d, c) + have = sorted(certs) + missing = [i for i in range(count) if i not in certs] + parts = [] + for k, lo in enumerate(range(0, len(have), chunk)): + part = f"{module}.Part{k}" + parts.append(part) + idx = have[lo:lo + chunk] + L = ["import Verify.VC.Cert", f"import {imp}", "", + f"/-! Obligations {', '.join(map(str, idx))} of `{script}`, each checked by the kernel along", + "its certificate (generated by scripts/verify/gen-certified.py). -/", "", + f"namespace {ns}", "", "open SolidCore.Verify.VC", "", HEADER, ""] + for i in idx: + d, c = certs[i] + L += [f"def cert_{i} : Cert := {c}", "", + f"theorem ob_{i} : dischargeAtC {script} {i} {d} cert_{i} = true := by decide +kernel", ""] + L += [f"end {ns}", ""] + write(part, L) + seen = [] + for i in parts + [r[0] for r in rejects]: + if i not in seen: + seen.append(i) + L = ["import Verify.VC.Discharge"] + [f"import {i}" for i in seen] + L += ["", "/-!", f"# `{script}`, discharged by the kernel along certificates", "", + "Generated by scripts/verify/gen-certified.py: one kernel check of `dischargeAtC` per", + "obligation (the Part modules), and the script's verdict `Valid` from them, with no solver.", + "-/", "", f"namespace {ns}", "", "open SolidCore.Verify.VC", "", HEADER, "", + f"theorem obligation_count : (obligations {script}).length = {count} := by decide +kernel", ""] + if not missing: + L += ["/-- Every obligation of the script has no model. -/", + f"theorem script_valid : Valid {script} :=", + " dischargeScript_of_certs _ fun i hi =>", + " match i, obligation_count \u25b8 hi with"] + L += [f" | {i}, _ => \u27e8_, _, ob_{i}\u27e9" for i in range(count)] + L += [f" | _ + {count}, h => absurd h (by omega)", ""] + else: + L += [f"/-- The obligations checked so far; {', '.join(map(str, missing))} have no certificate. -/", + "theorem checked : " + " \u2227 ".join(f"(\u2203 d c, dischargeAtC {script} {i} d c = true)" for i in have) + " :=", + " \u27e8" + ", ".join(f"\u27e8_, _, ob_{i}\u27e9" for i in have) + "\u27e9", ""] + for k, (_, m, idx) in enumerate(rejects): + L += [f"/-- The mutant script is rejected at obligation {idx}. -/", + f"theorem reject_{k} : dischargeScript {m} = false :=", + f" dischargeScript_false_of (i := {idx}) (by decide +kernel) (by decide +kernel)", ""] + if not missing: + L += [f"/-- info: '{ns}.script_valid' depends on axioms: [propext, Classical.choice, Quot.sound] -/", + "#guard_msgs (whitespace := lax) in", "#print axioms script_valid", ""] + L += [f"end {ns}", ""] + write(module, L) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/scripts/verify/gen-discharged.py b/scripts/verify/gen-discharged.py new file mode 100755 index 00000000..aea68a9c --- /dev/null +++ b/scripts/verify/gen-discharged.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Write Lean modules that discharge a solar-verify --dump-lean script in the kernel. + +Usage: gen-discharged.py MODULE NAMESPACE IMPORT SCRIPT COUNT [--chunk K] + [--reject IMPORT SCRIPT INDEX]... + +Run from the repository root. Writes MODULE (its path from its name) and, for every K obligations, +MODULE.Part: one theorem per obligation (dischargeAt SCRIPT i = true, by decide +kernel), so each +kernel evaluation stays small and each Lean process holds few of them; then MODULE proves the +count of obligations and script_valid : Valid SCRIPT from dischargeScript_of_each. Each --reject +names a mutant script and an obligation index the discharge rejects there, so that +dischargeScript MUTANT = false (dischargeScript_false_of): a mismatch, not a timeout. +""" +import os +import sys + +HEADER = "set_option maxRecDepth 100000" + + +def write(module, lines): + path = module.replace(".", "/") + ".lean" + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w") as f: + f.write("\n".join(lines)) + + +def main(argv): + module, ns, imp, script, count = argv[:5] + count = int(count) + chunk = 4 + rejects = [] + rest = argv[5:] + while rest: + if rest[0] == "--chunk": + chunk = int(rest[1]) + rest = rest[2:] + elif rest[0] == "--reject": + rejects.append((rest[1], rest[2], int(rest[3]))) + rest = rest[4:] + else: + sys.exit(f"unknown argument {rest[0]}") + parts = [] + for k, lo in enumerate(range(0, count, chunk)): + part = f"{module}.Part{k}" + parts.append(part) + L = ["import Verify.VC.Discharge", f"import {imp}", "", + f"/-! Obligations {lo} to {min(count, lo + chunk) - 1} of `{script}`, each discharged by the", + "kernel (generated by scripts/verify/gen-discharged.py). -/", "", + f"namespace {ns}", "", "open SolidCore.Verify.VC", "", HEADER, ""] + for i in range(lo, min(count, lo + chunk)): + L += [f"theorem ob_{i} : dischargeAt {script} {i} = true := by decide +kernel", ""] + L += [f"end {ns}", ""] + write(part, L) + imports = parts + [r[0] for r in rejects] + seen = [] + for i in imports: + if i not in seen: + seen.append(i) + L = [f"import {i}" for i in seen] + L += ["", "/-!", f"# `{script}`, discharged by the kernel", "", + "Generated by scripts/verify/gen-discharged.py: one kernel evaluation of `dischargeAt` per", + "obligation (the Part modules, Verify/VC/Discharge.lean), and the script's verdict `Valid` from", + "them, with no solver. Each rejected mutant script fails by a mismatch at the obligation named.", + "-/", "", f"namespace {ns}", "", "open SolidCore.Verify.VC", "", HEADER, "", + f"theorem obligation_count : (obligations {script}).length = {count} := by decide +kernel", "", + "/-- Every obligation of the script has no model. -/", + f"theorem script_valid : Valid {script} :=", + " dischargeScript_of_each _ fun i hi =>", + " match i, obligation_count \u25b8 hi with"] + L += [f" | {i}, _ => ob_{i}" for i in range(count)] + L += [f" | _ + {count}, h => absurd h (by omega)", ""] + for k, (_, m, idx) in enumerate(rejects): + L += [f"/-- The mutant script is rejected at obligation {idx}. -/", + f"theorem reject_{k} : dischargeScript {m} = false :=", + f" dischargeScript_false_of (i := {idx}) (by decide +kernel) (by decide +kernel)", ""] + L += [f"/-- info: '{ns}.script_valid' depends on axioms: [propext, Classical.choice, Quot.sound] -/", + "#guard_msgs (whitespace := lax) in", "#print axioms script_valid", "", f"end {ns}", ""] + write(module, L) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/scripts/verify/keccak/TokenSpecCollide.sol b/scripts/verify/keccak/TokenSpecCollide.sol new file mode 100644 index 00000000..1c5dc6a9 --- /dev/null +++ b/scripts/verify/keccak/TokenSpecCollide.sol @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +/// A minimal token. The invariant ties the ghost sum of balances to totalSupply, with +/// Certora-style ghost updates written next to every balance write. +/// @custom:ghost uint256 sumBalances +/// @custom:invariant totalSupply == sumBalances +contract Token { + mapping(address => uint256) public balanceOf; + uint256 public totalSupply; + address public owner; + + modifier onlyOwner() { + require(msg.sender == owner, "not owner"); + _; + } + + /// @custom:ensures owner == msg.sender + constructor() { + owner = msg.sender; + } + + /// @custom:ensures balanceOf[to] == old(balanceOf[to]) + amount + /// @custom:ensures totalSupply == old(totalSupply) + amount + /// @custom:ensures forall address a :: a != to ==> balanceOf[a] == old(balanceOf[a]) + function mint(address to, uint256 amount) external onlyOwner { + totalSupply += amount; + /// @custom:ghost sumBalances = sumBalances + amount + balanceOf[to] += amount; + } + + /// @custom:ensures msg.sender != to ==> balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount + /// @custom:ensures msg.sender != to ==> balanceOf[to] == old(balanceOf[msg.sender]) + amount + /// @custom:ensures forall address a :: a != msg.sender && a != to ==> balanceOf[a] == old(balanceOf[a]) + /// @custom:ensures totalSupply == old(totalSupply) + function transfer(address to, uint256 amount) external returns (bool) { + uint256 bal = balanceOf[msg.sender]; + require(bal >= amount, "insufficient"); + balanceOf[msg.sender] = bal - amount; + balanceOf[to] += amount; + return true; + } + + /// @custom:ensures balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount + function burn(uint256 amount) external { + balanceOf[msg.sender] -= amount; + /// @custom:ghost sumBalances = sumBalances - amount + totalSupply -= amount; + } +} diff --git a/scripts/verify/keccak/footprint_check.sh b/scripts/verify/keccak/footprint_check.sh new file mode 100755 index 00000000..0519329d --- /dev/null +++ b/scripts/verify/keccak/footprint_check.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# Kernel check of one call's footprint premise for the real keccak256. +# +# footprint_check.sh transfer +# footprint_check.sh approve +# footprint_check.sh transferFrom +# +# Slots are below 2^128, addresses below 2^160 (decimal or 0x hex). Writes a one-theorem Lean file, +# proves ScopedSep of the call's footprint by 'scopedSep_of_check (by decide +kernel)' +# (Verify/Spec/HashScopeCheck.lean), and checks its axioms. Prints the premise and exits 0 when the +# kernel accepts it; exits 1 when the check or the axiom audit fails, 2 on malformed input. Run from +# the repository root after 'lake build Verify.Spec.HashScopeCheck'. +set -euo pipefail + +die() { echo "REFUSED $*" >&2; exit 2; } + +num() { # num : canonical decimal of a value below 2^bits, or refuse. + python3 - "$1" "$2" <<'EOF' || exit 2 +import sys +s, bits = sys.argv[1], int(sys.argv[2]) +try: + v = int(s, 16) if s.lower().startswith("0x") else int(s, 10) +except ValueError: + sys.stderr.write(f"REFUSED not a number: {s}\n"); sys.exit(2) +if not (0 <= v < 2 ** bits): + sys.stderr.write(f"REFUSED out of range (2^{bits}): {s}\n"); sys.exit(2) +print(v) +EOF +} + +kind="${1:-}"; shift || true +case "$kind" in + transfer) + [ $# -eq 3 ] || die "transfer takes " + a=$(num "$1" 128); b=$(num "$2" 160); c=$(num "$3" 160) + fp="transferFootprint $a $b $c" ;; + approve) + [ $# -eq 3 ] || die "approve takes " + a=$(num "$1" 128); b=$(num "$2" 160); c=$(num "$3" 160) + fp="approveFootprint $a $b $c" ;; + transferFrom) + [ $# -eq 5 ] || die "transferFrom takes " + a=$(num "$1" 128); b=$(num "$2" 128); c=$(num "$3" 160); d=$(num "$4" 160); e=$(num "$5" 160) + fp="transferFromFootprint $a $b $c $d $e" ;; + *) die "unknown call kind: '$kind'" ;; +esac + +dir=$(mktemp -d); trap 'rm -rf "$dir"' EXIT +cat > "$dir/Check.lean" <&1); then + echo "$out" >&2; echo "CHECK failed"; exit 1 +fi +echo "$out" +ax=$(echo "$out" | sed -n "s/.*depends on axioms: \[\(.*\)\]/\1/p") +[ -n "$ax" ] || { echo "CHECK no axiom report"; exit 1; } +for x in $(echo "$ax" | tr ',' ' '); do + case "$x" in propext|Classical.choice|Quot.sound) ;; *) echo "CHECK axiom refused: $x"; exit 1 ;; esac +done +echo "CHECK kernel accepted" diff --git a/scripts/verify/mutant/CounterSpecMut.sol b/scripts/verify/mutant/CounterSpecMut.sol new file mode 100644 index 00000000..0e6d8d4b --- /dev/null +++ b/scripts/verify/mutant/CounterSpecMut.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Counter { + uint256 x; + /// @custom:ensures x == old(x) + d + 1 + function inc(uint256 d) external { x += d; } + function get() external view returns (uint256) { return x; } +} diff --git a/scripts/verify/mutant/CounterSrcMut.sol b/scripts/verify/mutant/CounterSrcMut.sol new file mode 100644 index 00000000..4888a009 --- /dev/null +++ b/scripts/verify/mutant/CounterSrcMut.sol @@ -0,0 +1,8 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.28; +contract Counter { + uint256 x; + /// @custom:ensures x == old(x) + d + function inc(uint256 d) external { x += d + 1; } + function get() external view returns (uint256) { return x; } +} diff --git a/scripts/verify/mutant/MANIFEST b/scripts/verify/mutant/MANIFEST new file mode 100644 index 00000000..e7d7f041 --- /dev/null +++ b/scripts/verify/mutant/MANIFEST @@ -0,0 +1,12 @@ +# SHA-256 of the mutants of ../Token.sol and of solar-verify's transcripts of them (--dry-run --dump-smt). +# Exported with the same solar-verify as ../MANIFEST into Contracts/Token/VC/Mutant (--lean-namespace SolidCore.Verify.VC.Export.Mutant.NAME). +# TokenSrcMut: line 40, transfer credits amount + 1. TokenSpecMut: line 33, the recipient clause claims old + amount + 1. +7d9e63fce842edd61266528e84206a5a9815f1399f7756c0a0ea34799cacf3d2 TokenSpecMut.sol +70fe01828715a428790c073162f481941d2758d80562eaeb5a48d6d2b8e1cfe8 TokenSrcMut.sol +796fd3eda4a952cf78c8aa3cc6bb7494f0ea5d81094943b1d0299d80e495e772 TokenSpecMut.smt2 +7616295111ee5a10d43c4ee695e098a31e0c7ae8ad3ac16d3adf63b778d4744e TokenSrcMut.smt2 +# CounterSrcMut: inc adds d + 1. CounterSpecMut: inc's clause claims old(x) + d + 1. +50106ede6130f1751bb61a2412d7358bdef842f29ea02bfc8083a2c2cb054013 CounterSrcMut.sol +afaec6975bea758e12835d06dafce1c218409d260471a7a039df235b1e91b224 CounterSpecMut.sol +809c14522fe1a0babe2fe61cf046edf5d24591aef580279d5bcf21449a356bc6 CounterSrcMut.smt2 +bc69abfa93b0a5b831dbc347d55ae8fc121a7b05dddf165d94e5e3f0a86bb003 CounterSpecMut.smt2 diff --git a/scripts/verify/mutant/TokenSpecMut.sol b/scripts/verify/mutant/TokenSpecMut.sol new file mode 100644 index 00000000..91c03e71 --- /dev/null +++ b/scripts/verify/mutant/TokenSpecMut.sol @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +/// A minimal token. The invariant ties the ghost sum of balances to totalSupply, with +/// Certora-style ghost updates written next to every balance write. +/// @custom:ghost uint256 sumBalances +/// @custom:invariant totalSupply == sumBalances +contract Token { + mapping(address => uint256) public balanceOf; + uint256 public totalSupply; + address public owner; + + modifier onlyOwner() { + require(msg.sender == owner, "not owner"); + _; + } + + /// @custom:ensures owner == msg.sender + constructor() { + owner = msg.sender; + } + + /// @custom:ensures balanceOf[to] == old(balanceOf[to]) + amount + /// @custom:ensures totalSupply == old(totalSupply) + amount + /// @custom:ensures forall address a :: a != to ==> balanceOf[a] == old(balanceOf[a]) + function mint(address to, uint256 amount) external onlyOwner { + totalSupply += amount; + /// @custom:ghost sumBalances = sumBalances + amount + balanceOf[to] += amount; + } + + /// @custom:ensures msg.sender != to ==> balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount + /// @custom:ensures msg.sender != to ==> balanceOf[to] == old(balanceOf[to]) + amount + 1 + /// @custom:ensures forall address a :: a != msg.sender && a != to ==> balanceOf[a] == old(balanceOf[a]) + /// @custom:ensures totalSupply == old(totalSupply) + function transfer(address to, uint256 amount) external returns (bool) { + uint256 bal = balanceOf[msg.sender]; + require(bal >= amount, "insufficient"); + balanceOf[msg.sender] = bal - amount; + balanceOf[to] += amount; + return true; + } + + /// @custom:ensures balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount + function burn(uint256 amount) external { + balanceOf[msg.sender] -= amount; + /// @custom:ghost sumBalances = sumBalances - amount + totalSupply -= amount; + } +} diff --git a/scripts/verify/mutant/TokenSrcMut.sol b/scripts/verify/mutant/TokenSrcMut.sol new file mode 100644 index 00000000..22df88f4 --- /dev/null +++ b/scripts/verify/mutant/TokenSrcMut.sol @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; + +/// A minimal token. The invariant ties the ghost sum of balances to totalSupply, with +/// Certora-style ghost updates written next to every balance write. +/// @custom:ghost uint256 sumBalances +/// @custom:invariant totalSupply == sumBalances +contract Token { + mapping(address => uint256) public balanceOf; + uint256 public totalSupply; + address public owner; + + modifier onlyOwner() { + require(msg.sender == owner, "not owner"); + _; + } + + /// @custom:ensures owner == msg.sender + constructor() { + owner = msg.sender; + } + + /// @custom:ensures balanceOf[to] == old(balanceOf[to]) + amount + /// @custom:ensures totalSupply == old(totalSupply) + amount + /// @custom:ensures forall address a :: a != to ==> balanceOf[a] == old(balanceOf[a]) + function mint(address to, uint256 amount) external onlyOwner { + totalSupply += amount; + /// @custom:ghost sumBalances = sumBalances + amount + balanceOf[to] += amount; + } + + /// @custom:ensures msg.sender != to ==> balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount + /// @custom:ensures msg.sender != to ==> balanceOf[to] == old(balanceOf[to]) + amount + /// @custom:ensures forall address a :: a != msg.sender && a != to ==> balanceOf[a] == old(balanceOf[a]) + /// @custom:ensures totalSupply == old(totalSupply) + function transfer(address to, uint256 amount) external returns (bool) { + uint256 bal = balanceOf[msg.sender]; + require(bal >= amount, "insufficient"); + balanceOf[msg.sender] = bal - amount; + balanceOf[to] += amount + 1; + return true; + } + + /// @custom:ensures balanceOf[msg.sender] == old(balanceOf[msg.sender]) - amount + function burn(uint256 amount) external { + balanceOf[msg.sender] -= amount; + /// @custom:ghost sumBalances = sumBalances - amount + totalSupply -= amount; + } +} diff --git a/scripts/verify/uniswap-v2/.gitignore b/scripts/verify/uniswap-v2/.gitignore new file mode 100644 index 00000000..99c5cbd3 --- /dev/null +++ b/scripts/verify/uniswap-v2/.gitignore @@ -0,0 +1,2 @@ +# Generated by scripts/verify/uniswap_v2_sources.py from the GPL-3.0 v2-core port; not committed. +*.sol diff --git a/scripts/verify/uniswap-v2/solar-rev b/scripts/verify/uniswap-v2/solar-rev new file mode 100644 index 00000000..e3638e20 --- /dev/null +++ b/scripts/verify/uniswap-v2/solar-rev @@ -0,0 +1 @@ +67946d7d204862c9d28ed18b83604aa00546f5f6 diff --git a/scripts/verify/uniswap-v2/transfer-mutants.txt b/scripts/verify/uniswap-v2/transfer-mutants.txt new file mode 100644 index 00000000..4fd1178d --- /dev/null +++ b/scripts/verify/uniswap-v2/transfer-mutants.txt @@ -0,0 +1,8 @@ +# UniswapV2ERC20.transfer's source mutants (scripts/verify/uniswap_v2_transfer_slice.sh): a name, the +# port's text and its replacement, tab-separated, with \n for a line break. Each edit must apply once +# and keep transfer inside the generic source stage (a bare expression statement such as +# balanceOf[from].sub(value); is outside it): Debit undoes the debit, Log swaps the log's +# addresses, Ret returns false. +Debit balanceOf[from] = balanceOf[from].sub(value);\n balanceOf[to] = balanceOf[to].add(value); balanceOf[from] = balanceOf[from].sub(value).add(value);\n balanceOf[to] = balanceOf[to].add(value); +Log emit Transfer(from, to, value); emit Transfer(to, from, value); +Ret _transfer(msg.sender, to, value);\n return true; _transfer(msg.sender, to, value);\n return false; diff --git a/scripts/verify/uniswap_v2_core.py b/scripts/verify/uniswap_v2_core.py new file mode 100755 index 00000000..a3492acc --- /dev/null +++ b/scripts/verify/uniswap_v2_core.py @@ -0,0 +1,433 @@ +#!/usr/bin/env python3 +"""Writes Contracts/UniswapV2/C/Core.lean: SolidCore's checked Uniswap V2 contract C, with +its selectors by table. + + scripts/verify/uniswap_v2_core.py [--solc SOLC] [--check] + +Reads the generated scripts/verify/uniswap-v2/NAME.sol (scripts/verify/uniswap_v2_sources.py) for +the signatures solc hashes, of every contract and interface in the file, since SolidCore's checker +hashes the interfaces' signatures too. Each selector is proved once by Keccak-256 in the kernel +(`kernel_rfl`) and `selector_eq` replaces `ABI.selectorFromSignature` by the table, as +Contracts/Token/VC/Burn.lean does for Token; `digest_eq` replaces `Keccak.digestWord` by the +table of event topics likewise. `contract_ok` is the kernel's type check of the contract and its +translation, checked as two conversions (`checkedSource_eq`, `translated_eq`). The module holds no v2-core code, only its ABI signatures. +""" + +import argparse +import json +import pathlib +import re +import subprocess +import sys + +ROOT = pathlib.Path(__file__).resolve().parent.parent.parent +CONTRACTS = [("UniswapV2ERC20", "ERC20"), ("UniswapV2Pair", "Pair"), ("UniswapV2Factory", "Factory")] + + +def signatures(solc: str, sol: pathlib.Path) -> tuple[list[tuple[str, int]], list[tuple[str, int]]]: + """The function selectors and the event topics solc hashes, of every contract in the file.""" + out = subprocess.run([solc, "--hashes", str(sol)], check=True, capture_output=True, + text=True).stdout + sels: dict[str, int] = {} + topics: dict[str, int] = {} + for m in re.finditer(r"^([0-9a-f]{8}|[0-9a-f]{64}): (\S+)$", out, re.M): + (sels if len(m.group(1)) == 8 else topics).setdefault(m.group(2), int(m.group(1), 16)) + return sorted(sels.items()), sorted(topics.items()) + + +def ident(sig: str) -> str: + name = sig.split("(")[0] + return name[0].upper() + name[1:] + + +B = chr(96) + + +def render(contract: str, d: str, sigs: list[tuple[str, int]], topics: list[tuple[str, int]], + staged: bool = False) -> str: + # Overloads would share a name; v2-core has none. + names = [ident(s) for s, _ in sigs] + assert len(set(names)) == len(names), names + L = [f"-- Generated by scripts/verify/uniswap_v2_core.py. Do not edit.", "", + f"import Contracts.UniswapV2.{d}.Source", + "import SolidCore.Refinement.KernelRfl", "import Verify.VC.KernelIdx", "", + "/-!", f"# SolidCore's checked `{contract}`", "", + f"The kernel's type check of the Uniswap V2 port's `{contract}` (`contract_ok`), with the checker's", + "selectors from a table each of whose entries the kernel checks against Keccak-256 once", + "(`selector_eq`), and its event topics likewise (`digest_eq`).", "-/", "", + f"namespace SolidCore.Verify.VC.{contract}", "", + "open SolidCore.Solidity SolidCore.Solidity.Source", "", + "/-- The interpreter fuel of SolidCore's runs. -/", "def fuel : Nat := 4096", "", + f"/-- SolidCore's checked `{contract}`. -/", + "def contract? : Except TypeCheck.TypeError TypeCheck.CheckedContract :=", + f" TypeCheck.CheckedInput.contract SolidCore.Verify.VC.Source.{contract}.importedSourceUnit \"{contract}\"", ""] + for (s, v), n in zip(sigs, names): + L += [f"/-- The selector of `{s}`. -/", f"abbrev {n[0].lower()+n[1:]}Sel : Nat := {v}", "", + f"/-- The selector of `{s}`, by Keccak-256 of its signature. -/", + f"def sel{n} : SolidCore.Solidity.Shared.Word :=", + f" SolidCore.Solidity.Source.ABI.selectorFromSignature \"{s}\"", "", + f"kernel_rfl sel{n}_eq sel{n} {n[0].lower()+n[1:]}Sel", ""] + L += [f"/-- `ABI.selectorFromSignature`, with `{contract}`'s selectors by table. -/", + "def selectorTable (s : String) : SolidCore.Solidity.Shared.Word :="] + for i, ((s, _), n) in enumerate(zip(sigs, names)): + L.append(f" {'if' if i == 0 else 'else if'} s = \"{s}\" then {n[0].lower()+n[1:]}Sel") + L += [" else SolidCore.Solidity.Source.ABI.selectorFromSignature s", "", + "theorem selector_eq : SolidCore.Solidity.Source.ABI.selectorFromSignature = selectorTable := by", + " funext s", " unfold selectorTable"] + for i, ((s, _), n) in enumerate(zip(sigs, names)): + L += [f" by_cases h{i} : s = \"{s}\"", f" · rw [ite_eq_left h{i}, h{i}]", + f" exact sel{n}_eq", f" rw [ite_eq_right h{i}]"] + L += ["", "/-! ## Event topics, by table -/", ""] + for s, v in topics: + n = ident(s) + L += [f"/-- The topic of {B}{s}{B}. -/", f"abbrev topic{n}Word : Nat := {v:#066x}", "", + f"/-- The topic of `{s}`, by Keccak-256 of its signature. -/", + f"def topic{n} : Nat := SolidCore.Solidity.Source.Keccak.digestWord \"{s}\"", "", + f"kernel_rfl topic{n}_eq topic{n} topic{n}Word", ""] + L += ["/-- `Keccak.digestWord`, with the contract's event signatures by table. -/", + "def digestTable (s : String) : Nat :="] + for i, (s, v) in enumerate(topics): + L.append(f" {'if' if i == 0 else 'else if'} s = \"{s}\" then topic{ident(s)}Word") + L += [" else SolidCore.Solidity.Source.Keccak.digestWord s", "", + "theorem digest_eq : SolidCore.Solidity.Source.Keccak.digestWord = digestTable := by", + " funext s", " unfold digestTable"] + # As SolidCore/Refinement/Solar/Events/Lowering.lean: rewriting the signature into + # digestWord makes the kernel evaluate Keccak-256 again, subst does not. + L.append(" split") + for i, (s, _) in enumerate(topics): + ind = " " * (i + 1) + L.append(f"{ind}· next h => subst h; exact topic{ident(s)}_eq") + L.append(f"{ind}· split" if i + 1 < len(topics) else f"{ind}· rfl") + src = f"SolidCore.Verify.VC.Source.{contract}.importedSourceUnit" + # The type check and the translation are separate kernel checks: each alone fits the + # kernel's memory, the two in one conversion do not. + S = ["", "/-- The source unit SolidCore's type checker returns: the source itself. -/", + "def checkedSource : Except TypeCheck.TypeError Solidity.SourceUnit :=", + f" (TypeCheck.TypecheckedInput.checkedSourceUnit {src}).map (·.source)", "", + f"kernel_rfl checkedSource_eq checkedSource (Except.ok {src})", + " using selector_eq digest_eq SolidCore.Verify.VC.mkIdx_eq", "", + ] + T = ["/-- Whether SolidCore translates the type-checked source's contract. -/", + "def translated : Bool :=", " match (do", + f" let p ← TypeCheck.CheckedProgram.fromChecked {{ source := {src} }}", + f" TypeCheck.CheckedProgram.contract p \"{contract}\") with", + " | .ok _ => true", " | .error _ => false", "", + "kernel_rfl translated_eq translated true", + " using selector_eq digest_eq SolidCore.Verify.VC.mkIdx_eq", "", + ] + C = ["theorem checkedSourceUnit_eq :", + f" TypeCheck.TypecheckedInput.checkedSourceUnit {src} = .ok {{ source := {src} }} := by", + " have h := checkedSource_eq", " unfold checkedSource at h", " revert h", + f" cases TypeCheck.TypecheckedInput.checkedSourceUnit {src} with", + " | error e => intro h; cases h", " | ok ck => intro h; cases ck; cases h; rfl", ""] + K = [ + f"/-- SolidCore type checks and translates the Uniswap V2 port's `{contract}`. -/", + "theorem contract_ok : ∃ c, contract? = .ok c := by", + " have ht := translated_eq", " unfold translated at ht", " split at ht", + " · next c hc =>", " refine ⟨c, ?_⟩", " show (do", " let p ← (do", + f" let checked ← TypeCheck.TypecheckedInput.checkedSourceUnit {src}", + " TypeCheck.CheckedProgram.fromChecked checked)", + f" TypeCheck.CheckedProgram.contract p \"{contract}\") = _", + " rw [checkedSourceUnit_eq]", " exact hc", " · cases ht", "", + f"/-- info: 'SolidCore.Verify.VC.{contract}.contract_ok' depends on axioms: [propext, Classical.choice, Quot.sound] -/", + "#guard_msgs (whitespace := lax) in", "#print axioms contract_ok", ""] + # A staged contract's translation and contract_ok are its Ctx/Fn/Groups/Asm/Contract modules. + if staged: + # The type check is its own module (Check.lean), so the stages need only the tables. Its + # namespace keeps its kernel_rfl copies apart from Ctx's, so Contract can import both. + L += [f"end SolidCore.Verify.VC.{contract}", ""] + P = ["-- Generated by scripts/verify/uniswap_v2_core.py. Do not edit.", "", + f"import Contracts.UniswapV2.{d}.Core", "", "/-!", + f"# SolidCore's type check of `{contract}`", "-/", "", + f"namespace SolidCore.Verify.VC.{contract}.Check", "", + "open SolidCore.Solidity SolidCore.Solidity.Source"] + return "\n".join(L), "\n".join(P + S + C + [f"end SolidCore.Verify.VC.{contract}.Check", ""]) + L += S + T + C + K + L += [f"end SolidCore.Verify.VC.{contract}", ""] + return "\n".join(L) + + +# --- Staged translation check ------------------------------------------------------------- +# +# A contract whose translation does not kernel-check in one declaration within 6 GB +# (UniswapV2Pair, and UniswapV2Factory with createPair) is +# checked in stages, each module its own process: Ctx.lean (the translation context, field by +# field), Fn/_.lean (one function's translation each), Groups.lean (the +# function groups from them), Asm.lean (the assembly) and Contract.lean (contract_ok from all). +# Every stage's value is printed by kernel_some from a fresh evaluation and checked by the kernel; +# the generator only decides how to split, so a wrong split fails a kernel check. + +STAGED = {"UniswapV2Pair", "UniswapV2Factory"} +USING = "selector_eq digest_eq SolidCore.Verify.VC.mkIdx_eq" +FAST = (" Executable.TypeEnv.shadowedStateNames_eq_K Executable.stringDecEq_eq_K" + " Executable.toByteArray_eq_K") +CTX_FIELDS = ("allContracts sourceUsingDecls sourceFunctions dispatchOrder structEnv stateVars " + "constants storageStateVars transientStateVars storageNames layoutBaseSlot " + "externalCallKindEnv externalCallKindTypeEnv stateEnv sharedConstantTail modifiers " + "libraryHelpers baseHelpers superHelpers availableFunctions internalFnIds " + "contractEvents visibleSourceEvents contractErrors visibleSourceErrors eventArgEnv " + "eventIndexedEnv errorArgEnv").split() + + +def layout(solc: str, sol: pathlib.Path, contract: str) -> list[tuple[str, list[tuple[str, int]]]]: + """The contract's linearized bases with their implemented functions, in solc's order: the + translation's dispatch order and the functions it translates (checked by the kernel).""" + out = subprocess.run([solc, "--ast-compact-json", str(sol)], check=True, capture_output=True, + text=True).stdout + ast = json.loads(out[out.index("{"):]) + defs = {n["id"]: n for n in ast["nodes"] if n.get("nodeType") == "ContractDefinition"} + top = next(n for n in defs.values() if n["name"] == contract) + res = [] + for cid in top["linearizedBaseContracts"]: + c = defs[cid] + fns = [(f["name"], int(f["src"].split(":")[1])) for f in c["nodes"] + if f.get("nodeType") == "FunctionDefinition" and f.get("kind") == "function" + and f.get("implemented")] + res.append((c["name"], fns)) + return res + + +# Consecutive functions share a module up to this much source text (bytes): one module per +# process, so the split only bounds each check's memory; any split checks the same theorem. +FN_CHUNK = 1500 + + +# Functions whose translation the kernel cannot check in one module within 6 GB: each is checked +# in three (`FromOrdersCtx.pairF_of_stages`): the passes before the lowering with the ANF +# preprocessing of the body, the lowering of the body, and the rest. +STAGED_FNS = {("UniswapV2Pair", "mint"), ("UniswapV2Pair", "swap"), ("UniswapV2Pair", "burn"), + ("UniswapV2Pair", "_mintFee")} + + +def chunks(fns: list[tuple[str, int]], staged: set[int] = set()) -> list[list[int]]: + """Consecutive function indices grouped up to FN_CHUNK bytes of source, each staged one alone.""" + out: list[list[int]] = [] + size = 0 + for j, (_, n) in enumerate(fns): + if out and size + n <= FN_CHUNK and j not in staged and out[-1][-1] not in staged: + out[-1].append(j) + size += n + else: + out.append([j]) + size = n + return out + + +def staged_files(contract: str, d: str, lay0: list[tuple[str, list[tuple[str, int]]]]) -> dict[str, str]: + lay = [(c, [f for f, _ in fns]) for c, fns in lay0] + ns = f"SolidCore.Verify.VC.{contract}" + src = f"SolidCore.Verify.VC.Source.{contract}.importedSourceUnit" + head = ["-- Generated by scripts/verify/uniswap_v2_core.py. Do not edit.", ""] + opens = ["open SolidCore.Solidity SolidCore.Solidity.Source", ""] + files = {} + # Ctx.lean + L = head + [f"import Contracts.UniswapV2.{d}.Core", "import SolidCore.Refinement.KernelValue", + "import SolidCore.Solidity.StagedK", "", "/-!", + f"# The translation context of `{contract}`", "", + "The raw declaration, its storage and dispatch orders and the translation context, each", + "printed from a fresh evaluation and checked by the kernel (the context field by field);", + "the dispatch order's contracts and the functions the translation translates likewise.", + "-/", "", f"namespace {ns}", ""] + opens + [ + f"abbrev src := {src}", "", + "/-- The type-resolved program finds the contract. -/", + "def found : Bool :=", + " match (TypeCheck.CheckedProgram.fromChecked? { source := src }).bind", + f" (fun p => TypeCheck.CheckedProgram.findSourceContract? p \"{contract}\") with", + f" | some d => d.name == \"{contract}\"", " | none => false", "", + f"kernel_rfl found_eq found true using {USING}", "", + f"def rawDecl? := Executable.SourceUnit.findContract? src \"{contract}\"", + f"kernel_some rawDecl rawDecl? using {USING}", "", + "def storageOrder? := Executable.ContractDecl.storageOrder? (Executable.SourceUnit.contracts src) rawDecl", + f"kernel_some storageOrder storageOrder? using {USING}", "", + "def dispatchOrder? := Executable.ContractDecl.dispatchOrder? (Executable.SourceUnit.contracts src) rawDecl", + f"kernel_some dispatchOrder dispatchOrder? using {USING}", "", + "/-- The translation context. -/", + "def ctx? : Option Executable.FromOrdersCtx :=", + " Executable.ContractDecl.fromOrdersCtx? (Executable.SourceUnit.contracts src)", + " (Executable.SourceUnit.usingDecls src) (Executable.SourceUnit.freeFunctions src)", + " (Executable.SourceUnit.freeEvents src) (Executable.SourceUnit.freeErrors src)", + " (Executable.SourceUnit.freeConstants src) (Executable.SourceUnit.freeUserValueTypes src)", + " (Executable.SourceUnit.freeEnums src) (Executable.SourceUnit.freeStructs src)", + " storageOrder dispatchOrder", ""] + for f in CTX_FIELDS: + L += [f"def ctx_{f}? := Option.map Executable.FromOrdersCtx.{f} ctx?", f"kernel_some ctx_{f} ctx_{f}? using {USING}", ""] + L += ["/-- The translation context, from its fields. -/", "def ctx : Executable.FromOrdersCtx :="] + L += [" { " + ",\n ".join(f"{f} := ctx_{f}" for f in CTX_FIELDS) + " }", ""] + L += ["theorem ctx_eq : ctx? = some ctx :=", + " Executable.FromOrdersCtx.some_eq_of_fields " + " ".join(f"ctx_{f}_eq" for f in CTX_FIELDS), ""] + for i, (cname, fns) in enumerate(lay): + L += [f"/-- `{cname}`, the dispatch order's contract {i}. -/", + f"def d{i}? := ctx.dispatchOrder[{i}]?", f"kernel_some d{i} d{i}? using {USING}", ""] + for j, fn in enumerate(fns): + L += [f"/-- `{cname}.{fn}`. -/", + f"def f{i}_{j}? := (Executable.FromOrdersCtx.fnsOf d{i})[{j}]?", + f"kernel_some f{i}_{j} f{i}_{j}? using {USING}", ""] + L += [f"def fns{i} := Executable.FromOrdersCtx.fnsOf d{i}", + f"kernel_rfl fns{i}_eq fns{i} [" + + ", ".join(f"f{i}_{j}" for j in range(len(fns))) + f"] using {USING}", "", + f"def getters{i}? := ctx.getters? d{i}", f"kernel_some getters{i} getters{i}? using {USING}", ""] + L += ["/-- The dispatch order, contract by contract. -/", + "def dispatchOrderL := ctx.dispatchOrder", "", + f"kernel_rfl dispatchOrderL_eq dispatchOrderL [" + ", ".join(f"d{i}" for i in range(len(lay))) + + f"] using {USING}", "", f"end {ns}", ""] + files[f"Contracts/UniswapV2/{d}/Ctx.lean"] = "\n".join(L) + # Clones.lean: the translation's copies under the equal forms, made once and shared by the Fn + # modules (each would otherwise add the same copies, which two imports could not both hold). + L = head + [f"import Contracts.UniswapV2.{d}.Ctx", "", "/-!", + f"# The translation's copies for the function checks of `{contract}`", "", + "`kernel_rfl … using` copies every definition that reaches a replaced constant; this", + "module makes the copies of `FromOrdersCtx.pairF`'s definitions once, under the namespace the", + "Fn modules check in, so they reuse them.", "-/", "", + f"namespace {ns}.Fn", ""] + opens + [f"open {ns}", "", + "/-- Mentions its argument and is `true`. -/", + "def mention {α : Sort _} (_ : α) : Bool := true", "", + "def warm : Bool := mention @Executable.FromOrdersCtx.pairF", + f"kernel_rfl warm_eq warm true using {USING}{FAST}", "", f"end {ns}.Fn", ""] + files[f"Contracts/UniswapV2/{d}/Clones.lean"] = "\n".join(L) + # ClonesStaged.lean: the same for the staged functions' checks. + L = head + [f"import Contracts.UniswapV2.{d}.Clones", "import SolidCore.Solidity.StagedL", "", "/-!", + f"# The translation's copies for the staged function checks of \u0060{contract}\u0060", "", + "The copies of \u0060FromOrdersCtx.preF\u0060's, \u0060anfF\u0060's, \u0060lowF\u0060's and \u0060restF\u0060's", + "definitions, made once for the staged functions' modules.", "-/", "", + f"namespace {ns}.Fn", ""] + opens + [f"open {ns}", "", + "def warmStaged : Bool := mention @Executable.FromOrdersCtx.preF && mention @Executable.FromOrdersCtx.anfF &&", + " mention @Executable.FromOrdersCtx.lowF && mention @Executable.FromOrdersCtx.restF", + f"kernel_rfl warmStaged_eq warmStaged true using {USING}{FAST}", "", f"end {ns}.Fn", ""] + files[f"Contracts/UniswapV2/{d}/ClonesStaged.lean"] = "\n".join(L) + # Fn modules, one per chunk of consecutive functions + mods = [] + for i, (cname, fns0) in enumerate(lay0): + fns = [f for f, _ in fns0] + staged = {j for j, f in enumerate(fns) if (cname, f) in STAGED_FNS} + for js in chunks(fns0, staged): + m = f"{cname}_{fns[js[0]]}" + mods.append(m) + names = ", ".join(f"`{cname}.{fns[j]}`" for j in js) + if js[0] in staged: + j = js[0] + k = f"{i}_{j}" + fn_open = [f"namespace {ns}.Fn", ""] + opens + [f"open {ns}", ""] + L = head + [f"import Contracts.UniswapV2.{d}.ClonesStaged", "", "/-!", + f"# The translation of {names} in `{contract}`: before the lowering", "", + "The passes before the lowering of the body and its ANF preprocessing, printed from a", + "fresh evaluation and checked by the kernel.", "-/", ""] + fn_open + [ + f"def pre{k}? := ctx.preF d{i} f{k}", + f"kernel_some pre{k} pre{k}? using {USING}{FAST}", "", + f"def anf{k}? : Option Solidity.Stmt := some (ctx.anfF pre{k})", + f"kernel_some anf{k} anf{k}? using {USING}{FAST}", "", f"end {ns}.Fn", ""] + files[f"Contracts/UniswapV2/{d}/Fn/{m}_pre.lean"] = "\n".join(L) + L = head + [f"import Contracts.UniswapV2.{d}.Fn.{m}_pre", "", "/-!", + f"# The translation of {names} in `{contract}`: the lowering", "", + "The lowering of the preprocessed body, printed from a fresh evaluation and checked", + "by the kernel.", "-/", ""] + fn_open + [ + f"def low{k}? := ctx.lowF pre{k} anf{k}", + f"kernel_some low{k} low{k}? using {USING}{FAST}", "", f"end {ns}.Fn", ""] + files[f"Contracts/UniswapV2/{d}/Fn/{m}_lower.lean"] = "\n".join(L) + L = head + [f"import Contracts.UniswapV2.{d}.Fn.{m}_lower", "", "/-!", + f"# The translation of {names} in `{contract}`", "", + "The rest of the translation after the lowering, printed from a fresh evaluation and", + "checked by the kernel, and the translation from its stages", + "(`FromOrdersCtx.pairF_of_stages`).", "-/", ""] + fn_open + [ + f"def p{k}? := ctx.pairF d{i} f{k}", "", + f"def rest{k}? := ctx.restF d{i} f{k} pre{k} (some low{k})", + f"kernel_some r{k} rest{k}? using {USING}{FAST}", "", + f"/-- The translation of `{cname}.{fns[j]}`. -/", + f"def p{k} := r{k}", "", + f"theorem p{k}_eq : p{k}? = some p{k} :=", + f" Executable.FromOrdersCtx.pairF_of_stages pre{k}_eq anf{k}_eq low{k}_eq r{k}_eq", "", + f"end {ns}.Fn", ""] + files[f"Contracts/UniswapV2/{d}/Fn/{m}.lean"] = "\n".join(L) + continue + L = head + [f"import Contracts.UniswapV2.{d}.Clones", "", "/-!", + f"# The translation of {names} in `{contract}`", "", + "Each function's translation, printed from a fresh evaluation and checked by the", + "kernel, with names compared by key (`TypeEnv.shadowedStateNames_eq_K`).", "-/", "", + f"namespace {ns}.Fn", ""] + opens + [f"open {ns}", ""] + for j in js: + L += [f"def p{i}_{j}? := ctx.pairF d{i} f{i}_{j}", + f"kernel_some p{i}_{j} p{i}_{j}? using {USING}{FAST}", ""] + L += [f"end {ns}.Fn", ""] + files[f"Contracts/UniswapV2/{d}/Fn/{m}.lean"] = "\n".join(L) + # Groups.lean + L = head + [f"import Contracts.UniswapV2.{d}.Fn.{m}" for m in mods] + ["", "/-!", + f"# The function groups of `{contract}`", "", + "Each contract's group of the dispatch order from its getters and its functions'", + "translations (`FromOrdersCtx.group?_of_pairs`).", "-/", "", f"namespace {ns}", ""] + opens + [ + f"open {ns}.Fn Executable", ""] + for i, (cname, fns) in enumerate(lay): + chain = "mapOption_nil' _" + for j in reversed(range(len(fns))): + chain = f"mapOption_cons' (f := ctx.pairF d{i}) (x := f{i}_{j}) p{i}_{j}_eq ({chain})" + L += [f"theorem group{i}_eq : ctx.group? d{i} = some (groupOfPairs getters{i} [" + + ", ".join(f"p{i}_{j}" for j in range(len(fns))) + "]) :=", + f" FromOrdersCtx.group?_of_pairs getters{i}_eq (by", + f" rw [show FromOrdersCtx.fnsOf d{i} = [" + ", ".join(f"f{i}_{j}" for j in range(len(fns))) + + f"] from fns{i}_eq]", f" exact {chain})", ""] + gl = ", ".join(f"groupOfPairs getters{i} [" + ", ".join(f"p{i}_{j}" for j in range(len(fns))) + "]" + for i, (_, fns) in enumerate(lay)) + chain = "mapOption_nil' _" + for i in reversed(range(len(lay))): + chain = f"mapOption_cons' (f := ctx.group?) (x := d{i}) group{i}_eq ({chain})" + L += ["/-- The function groups. -/", f"def groups : List (List CoreFunctionDef) := [{gl}]", "", + "theorem groups_eq : mapOption ctx.group? ctx.dispatchOrder = some groups := by", + " rw [show ctx.dispatchOrder = [" + ", ".join(f"d{i}" for i in range(len(lay))) + + "] from dispatchOrderL_eq]", f" exact {chain}", "", + f"end {ns}", ""] + files[f"Contracts/UniswapV2/{d}/Groups.lean"] = "\n".join(L) + # Asm.lean + L = head + [f"import Contracts.UniswapV2.{d}.Groups", "", "/-!", f"# The assembly of `{contract}`", + "-/", "", f"namespace {ns}", ""] + opens + [ + "def core? := ctx.assemble? groups", + f"kernel_some core core? using {USING}{FAST}", "", f"end {ns}", ""] + files[f"Contracts/UniswapV2/{d}/Asm.lean"] = "\n".join(L) + # Contract.lean + L = head + [f"import Contracts.UniswapV2.{d}.Asm", f"import Contracts.UniswapV2.{d}.Check", "", "/-!", + f"# SolidCore type checks and translates `{contract}`", "", + "`contract_ok` from the type check (`Check.checkedSourceUnit_eq`), the context (`ctx_eq`), the", + "function groups (`groups_eq`) and the assembly (`core_eq`), each its own module.", "-/", "", + f"namespace {ns}", ""] + opens + [ + f"/-- SolidCore type checks and translates the Uniswap V2 port's `{contract}`. -/", + "theorem contract_ok : ∃ c, contract? = .ok c :=", + f" TypeCheck.CheckedInput.contract_ok_of_stages src \"{contract}\" rawDecl storageOrder dispatchOrder", + " Check.checkedSourceUnit_eq found_eq rawDecl_eq storageOrder_eq dispatchOrder_eq", + " ⟨core, Executable.ContractDecl.toCoreFromOrders?_of_stages ctx_eq groups_eq core_eq⟩", "", + f"/-- info: '{ns}.contract_ok' depends on axioms: [propext, Classical.choice, Quot.sound] -/", + "#guard_msgs (whitespace := lax) in", "#print axioms contract_ok", "", f"end {ns}", ""] + files[f"Contracts/UniswapV2/{d}/Contract.lean"] = "\n".join(L) + return files + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--solc", default="solc") + ap.add_argument("--check", action="store_true") + ap.add_argument("contracts", nargs="*") + a = ap.parse_args() + status = 0 + for contract, d in CONTRACTS: + if a.contracts and d not in a.contracts: + continue + sol = ROOT / "scripts" / "verify" / "uniswap-v2" / f"{contract}.sol" + staged = contract in STAGED + if staged: + core, check = render(contract, d, *signatures(a.solc, sol), staged=True) + files = {f"Contracts/UniswapV2/{d}/Core.lean": core, + f"Contracts/UniswapV2/{d}/Check.lean": check} + files.update(staged_files(contract, d, layout(a.solc, sol, contract))) + else: + files = {f"Contracts/UniswapV2/{d}/Core.lean": render(contract, d, *signatures(a.solc, sol))} + for rel, text in files.items(): + out = ROOT / rel + if a.check: + if not out.exists() or out.read_text() != text: + print(f"error: {rel} is out of date", file=sys.stderr) + status = 1 + else: + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(text) + return status + + +if __name__ == "__main__": + sys.exit(main()) + diff --git a/scripts/verify/uniswap_v2_erc20_mutants.py b/scripts/verify/uniswap_v2_erc20_mutants.py new file mode 100755 index 00000000..f4d1d7ec --- /dev/null +++ b/scripts/verify/uniswap_v2_erc20_mutants.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Write mutants of solar's exported stage0 of UniswapV2ERC20 for the negative controls of +Contracts/UniswapV2/ERC20/SourceMirNeg.lean: each edits one instruction of transfer, _transfer or +SafeMath's sub and must change the file (else this fails), under its own namespace +SolarTV.Export.UniswapV2ERC20Mut.. Derived from the GPL-3.0 port, so not committed. + + python3 scripts/verify/uniswap_v2_erc20_mutants.py Certified/uv2_erc20/gen +""" +import re, sys, pathlib + +gen = pathlib.Path(sys.argv[1]) +src = (gen / "UniswapV2ERC20" / "Stage0.lean").read_text() + +def block(text, name): + """The span of function @name's entry in the exported module.""" + start = text.index(f" -- @{name}\n") + nxt = text.find(" -- @", start + 1) + return start, (nxt if nxt != -1 else len(text)) + +def edit(fn, old, new, count=1): + def f(text): + a, b = block(text, fn) + body = text[a:b] + if body.count(old) < count: + raise SystemExit(f"mutant: {old!r} not found {count}x in @{fn}") + return text[:a] + body.replace(old, new, count) + text[b:] + return f + +# name -> (edit, what it breaks) +MUTANTS = { + "NoDebit": (edit("_transfer", ".effect none .sstore [.value 36, .value 7],\n", ""), + "the debit of balanceOf[from] dropped"), + "WrongSlot": (edit("_transfer", ".effect none .mstore [.const 32, .const 1],", ".effect none .mstore [.const 32, .const 2],"), + "balanceOf's slot 1 read as slot 2"), + "NoOverflowCheck": (edit("_transfer", ".pure 26 .lt [.value 25, .value 14]", ".pure 26 .gt [.value 25, .value 14]"), + "the add overflow test reversed"), + "NoUnderflowCheck": (edit("sub", ".pure 3 .lt [.value 0, .value 2]", ".pure 3 .gt [.value 0, .value 2]"), + "SafeMath sub's underflow test reversed"), + "WrongTopic": (edit("_transfer", "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ee"), + "the Transfer topic changed"), + "WrongReturn": (edit("transfer", ".effect none .mstore [.const 0, .const 1]", ".effect none .mstore [.const 0, .const 0]"), + "returns false"), + "WrongRevertData": (edit("_transfer", "0x64732d6d6174682d6164642d6f766572666c6f77", "0x64732d6d6174682d6164642d6f766572666c6f78"), + "the add overflow revert reason changed"), + "SwappedLogArgs": (edit("_transfer", ".value 0, .value 1]]", ".value 1, .value 0]]"), + "from and to swapped in the Transfer topics"), + "PinnedCaller": (edit("transfer", ".effect (some 2) .caller [],", ".pure 2 .add [.const 0x2000, .const 0],"), + "CALLER replaced by the constant 0x2000: right only for that caller"), +} + +out = gen / "UniswapV2ERC20Mut" +out.mkdir(parents=True, exist_ok=True) +for name, (f, _) in MUTANTS.items(): + text = f(src) + if text == src: + raise SystemExit(f"mutant {name} did not change stage0") + text = text.replace("namespace SolarTV.Export.UniswapV2ERC20\n", f"namespace SolarTV.Export.UniswapV2ERC20Mut.{name}\n", 1) + text = text.replace("end SolarTV.Export.UniswapV2ERC20\n", f"end SolarTV.Export.UniswapV2ERC20Mut.{name}\n", 1) + if f"namespace SolarTV.Export.UniswapV2ERC20Mut.{name}" not in text or f"end SolarTV.Export.UniswapV2ERC20Mut.{name}" not in text: + raise SystemExit(f"mutant {name}: namespace not rewritten") + (out / f"{name}.lean").write_text(text) +print(" ".join(MUTANTS)) + diff --git a/scripts/verify/uniswap_v2_erc20_stages.sh b/scripts/verify/uniswap_v2_erc20_stages.sh new file mode 100755 index 00000000..c39be202 --- /dev/null +++ b/scripts/verify/uniswap_v2_erc20_stages.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Export solar's stages of the Uniswap V2 port's UniswapV2ERC20 into Certified/uv2_erc20/gen, before +# the build of the uv2_erc20 library (Contracts/UniswapV2/ERC20/SourceMir.lean imports its Stage0). +# They are not committed: they are compiled from the GPL-3.0 v2-core port, as Source.lean is. +# +# SOLAR=path/to/solar scripts/verify/uniswap_v2_erc20_stages.sh +# +# Needs scripts/verify/uniswap_v2_gen.sh's port (.cache/uniswap-v2/src). SOLAR is a solar binary +# built from the solar commit under test (default: solar on PATH). Compiles with the slice's options +# (Certified/uv2_erc20/options: -Ogas --evm-version osaka) and -Zemit-lean-stages, checks that the +# flag does not change the runtime bytecode, and fails if Stage0.lean is missing afterwards. +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../.." +SOLAR="${SOLAR:-solar}" +src=.cache/uniswap-v2/src +[[ -s $src/UniswapV2ERC20.sol ]] || { echo "error: $src/UniswapV2ERC20.sol missing; run scripts/verify/uniswap_v2_gen.sh" >&2; exit 1; } +mapfile -t opts < Certified/uv2_erc20/options +out="$(pwd)/Certified/uv2_erc20/gen" +tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT +rm -rf "$out" +(cd "$src" && "$SOLAR" "${opts[@]}" --emit bin-runtime UniswapV2ERC20.sol) > "$tmp/plain.json" +(cd "$src" && "$SOLAR" "${opts[@]}" -Zemit-lean-stages="$tmp/stages" --emit bin-runtime UniswapV2ERC20.sol) > "$tmp/staged.json" +cmp -s "$tmp/plain.json" "$tmp/staged.json" \ + || { echo "error: -Zemit-lean-stages changed the runtime bytecode" >&2; exit 1; } +mkdir -p "$out" +cp -r "$tmp/stages/UniswapV2ERC20" "$out/" +[[ -s $out/UniswapV2ERC20/Stage0.lean ]] || { echo "error: no Stage0.lean exported" >&2; exit 1; } +python3 scripts/verify/uniswap_v2_erc20_mutants.py "$out" >/dev/null +echo "wrote $out/UniswapV2ERC20 ($("$SOLAR" --version | sed -n 's/^Commit SHA: //p'))" diff --git a/scripts/verify/uniswap_v2_gas.sh b/scripts/verify/uniswap_v2_gas.sh new file mode 100755 index 00000000..aa43ba85 --- /dev/null +++ b/scripts/verify/uniswap_v2_gas.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Generate UniswapV2ERC20's exported stages and the transfer slice's gas certificate before the +# build of the uv2_erc20 library (Certified/uv2_erc20/Gas.lean). Nothing generated is committed: +# it is derived from the GPL-3.0 v2-core port. +# +# SOLAR_DIR=... SOLAR=... scripts/verify/uniswap_v2_gas.sh +# +# Needs scripts/verify/uniswap_v2_gen.sh's scripts/verify/uniswap-v2/UniswapV2ERC20.sol, and: +# SOLAR_DIR a solar checkout with tools/certify/{asm_cert,asm_ctxl,gen_ctxgas}.py; +# SOLAR its solar binary (default $SOLAR_DIR/target/release/solar). +# Writes, under Certified/uv2_erc20/ (ignored by git): +# uv2_erc20.sol the flattened port, for reference; +# gen/ scripts/verify/uniswap_v2_erc20_stages.sh's export of the port +# (solar -Ogas --evm-version osaka -Zemit-lean-stages); +# CtxGas.lean gen_ctxgas.py's certificate: the checker with contexts and gas on +# the exact bytes against the final EVM IR, every block outside +# transfer's slice (the dispatcher's jump on 0xa9059cbb) unchecked. +# Fails if any step fails, if the export changes the bytecode, or if the final stage is not evm11. +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../.." +: "${SOLAR_DIR:?set SOLAR_DIR to a solar checkout}" +SOLAR_DIR="$(realpath "$SOLAR_DIR")" +SOLAR="$(realpath "${SOLAR:-$SOLAR_DIR/target/release/solar}")" +src=scripts/verify/uniswap-v2/UniswapV2ERC20.sol +[[ -s $src ]] || { echo "error: $src missing; run scripts/verify/uniswap_v2_gen.sh" >&2; exit 1; } +out=Certified/uv2_erc20 +mkdir -p "$out" +outabs="$(realpath "$out")" +cp "$src" "$out/uv2_erc20.sol" +# The stages: scripts/verify/uniswap_v2_erc20_stages.sh exports them from the port with the same +# solar (and checks that the export does not change the bytecode). +SOLAR="$SOLAR" scripts/verify/uniswap_v2_erc20_stages.sh +gen="$out/gen/UniswapV2ERC20" +final=$(python3 -c 'import json,sys; s=json.load(open(sys.argv[1]))["stages"]; print([x["definition"] for x in s if x["kind"]=="evm"][-1])' "$gen/manifest.json") +[[ "$final" == evm11 ]] || { echo "error: the final EVM IR is $final, the proofs name evm11" >&2; exit 1; } +python3 "$SOLAR_DIR/tools/certify/gen_ctxgas.py" "$gen" --module-prefix uv2_erc20.gen.UniswapV2ERC20 \ + --contract UniswapV2ERC20 --final "$final" --selector 0xa9059cbb --out "$out/CtxGas.lean" +echo "wrote $out/gen $out/CtxGas.lean" diff --git a/scripts/verify/uniswap_v2_gen.sh b/scripts/verify/uniswap_v2_gen.sh new file mode 100755 index 00000000..efa7cc4c --- /dev/null +++ b/scripts/verify/uniswap_v2_gen.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Generate SolidCore's Uniswap V2 sources before the build (they are not committed: v2-core is +# GPL-3.0, so this repository keeps the recipe, as solar keeps solar-tv/uniswap-v2/port.py). +# +# scripts/verify/uniswap_v2_gen.sh +# +# Fetches paradigmxyz/solar at the commit in scripts/verify/uniswap-v2/solar-rev (only its +# sources: nothing is built; the refinement's scripts/refinement/solar-rev predates port.py), +# runs its solar-tv/uniswap-v2/port.py, which clones Uniswap/v2-core at the pinned commit and +# writes the ^0.8 port, then scripts/verify/uniswap_v2_sources.py and +# scripts/verify/uniswap_v2_core.py with solc 0.8.35 (downloaded and checked against its SHA-256 +# unless SOLC names a binary). Fails if any generated module is missing afterwards, so a build +# never runs on stale or absent sources. SOLAR_DIR (default .cache/solar-uniswap-v2) is the checkout. +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../.." + +rev="$(tr -d '[:space:]' < scripts/verify/uniswap-v2/solar-rev)" +solar_dir="${SOLAR_DIR:-.cache/solar-uniswap-v2}" +if [[ ! -d "$solar_dir/.git" ]]; then + git init -q "$solar_dir" + git -C "$solar_dir" remote add origin https://github.com/paradigmxyz/solar.git +fi +if [[ "$(git -C "$solar_dir" rev-parse -q --verify HEAD 2>/dev/null || true)" != "$rev" ]]; then + git -C "$solar_dir" fetch -q --depth 1 origin "$rev" + git -C "$solar_dir" checkout -q --detach "$rev" +fi + +solc_version=0.8.35 +solc_sha256=fa8ac9a32d301ad023a36ee5a29f8e291fe3200c60244e43c142539e82a617f4 +if [[ -z "${SOLC-}" ]]; then + SOLC=".cache/solc-$solc_version" + if [[ ! -x "$SOLC" ]]; then + mkdir -p .cache + curl -fsSL -o "$SOLC.tmp" \ + "https://github.com/argotorg/solidity/releases/download/v$solc_version/solc-static-linux" + echo "$solc_sha256 $SOLC.tmp" | sha256sum -c --quiet + chmod +x "$SOLC.tmp" + mv "$SOLC.tmp" "$SOLC" + fi +fi + +port=".cache/uniswap-v2/src" +python3 "$solar_dir/solar-tv/uniswap-v2/port.py" --out "$port" --v2-core .cache/uniswap-v2/v2-core +python3 scripts/verify/uniswap_v2_sources.py --port "$port" --solc "$SOLC" +python3 scripts/verify/uniswap_v2_core.py --solc "$SOLC" + +status=0 +for d in ERC20 Pair Factory; do + for f in Source Core; do + if [[ ! -s "Contracts/UniswapV2/$d/$f.lean" ]]; then + echo "error: Contracts/UniswapV2/$d/$f.lean was not generated" >&2 + status=1 + fi + done +done +for d in Pair Factory; do + if [[ ! -s "Contracts/UniswapV2/$d/Contract.lean" ]]; then + echo "error: Contracts/UniswapV2/$d/Contract.lean was not generated" >&2 + status=1 + fi +done +exit "$status" diff --git a/scripts/verify/uniswap_v2_mutant.py b/scripts/verify/uniswap_v2_mutant.py new file mode 100755 index 00000000..837c301e --- /dev/null +++ b/scripts/verify/uniswap_v2_mutant.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Writes SolidCore's source and checked contract of one source mutant of UniswapV2ERC20. + + scripts/verify/uniswap_v2_mutant.py --solc SOLC --sol MUTANT.sol --name M --out DIR + +MUTANT.sol is the flattened port (scripts/verify/uniswap-v2/UniswapV2ERC20.sol) with one edit +(scripts/verify/uniswap_v2_transfer_slice.sh applies it). Writes DIR/Source.lean, the frontend's +translation (namespace SolidCore.Verify.VC.Source.UniswapV2ERC20Mut), and DIR/Core.lean, +scripts/verify/uniswap_v2_core.py's checked contract of it (namespace +SolidCore.Verify.VC.UniswapV2ERC20Mut: contract_ok, fuel, the selector and topic tables). +Nothing here is trusted: both are checked by the kernel when they build. Derived from the GPL-3.0 +port, so not committed. +""" + +import argparse +import pathlib +import subprocess +import sys + +ROOT = pathlib.Path(__file__).resolve().parent.parent.parent +sys.path.insert(0, str(ROOT / "scripts" / "verify")) +import uniswap_v2_core as core # noqa: E402 +import uniswap_v2_sources as sources # noqa: E402 + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--solc", required=True) + ap.add_argument("--sol", type=pathlib.Path, required=True) + ap.add_argument("--name", required=True) + ap.add_argument("--out", type=pathlib.Path, required=True) + a = ap.parse_args() + c = "UniswapV2ERC20" + m = f"{c}Mut{a.name}" + sol = a.sol.resolve() + out = a.out.resolve() + mod = ".".join(out.relative_to(ROOT).parts) + src = sources.lean_of(a.solc, sol, c, []) + # The frontend opens the namespace one component a line: rename the innermost one. + for old, new in [(f"namespace {c}\n", f"namespace {m}\n"), (f"end {c}\n", f"end {m}\n")]: + if src.count(old) != 1: + sys.exit(f"error: {old!r} is not in the frontend's output exactly once") + src = src.replace(old, new) + text = core.render(c, "ERC20", *core.signatures(a.solc, sol)) + for old, new in [ + ("import Contracts.UniswapV2.ERC20.Source", f"import {mod}.Source"), + (f"SolidCore.Verify.VC.Source.{c}.", f"SolidCore.Verify.VC.Source.{m}."), + (f"SolidCore.Verify.VC.{c}", f"SolidCore.Verify.VC.{m}"), + ]: + if old not in text: + sys.exit(f"error: {old!r} not in the rendered Core") + text = text.replace(old, new) + out.mkdir(parents=True, exist_ok=True) + (out / "Source.lean").write_text(src) + (out / "Core.lean").write_text(text) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/verify/uniswap_v2_pair_spec.sh b/scripts/verify/uniswap_v2_pair_spec.sh new file mode 100755 index 00000000..a2d83641 --- /dev/null +++ b/scripts/verify/uniswap_v2_pair_spec.sh @@ -0,0 +1,158 @@ +#!/usr/bin/env bash +# Generate the inputs of UniswapV2Pair's published statement (Contracts/UniswapV2/PairSpec), before +# its build. None is committed: each is derived from the GPL-3.0 v2-core port. +# +# scripts/verify/uniswap_v2_pair_spec.sh +# +# Needs scripts/verify/uniswap_v2_gen.sh's outputs (scripts/verify/uniswap-v2/UniswapV2Pair.sol and +# Contracts/UniswapV2/Pair/{Source,Core}.lean), and: +# SOLAR_DIR a solar checkout with crates/verify/uniswap-v2/{apply_specs.py,uniswap-v2.spec}; +# SOLAR its solar binary (the bytecode and its stage export); +# SOLAR_VERIFY its solar-verify binary (--emit-lean-spec, with dynamic parameters exported as +# their head word: solar's spec_lean.rs with the pair-spec lane's patch). +# Writes, under Contracts/UniswapV2/PairSpec/: +# Spec.lean solar-verify's --emit-lean-spec export of the ERC20 and Pair sections of +# uniswap-v2.spec, applied to the flattened UniswapV2Pair.sol; +# SpecWrongK.lean the same with swap's fee-adjusted constant-product clause mutated (fee 4/1000 +# instead of 3/1000, stronger than the code meets): a negative control; +# Bytecode.lean solar -Zemit-lean-stages's Bytecode.lean for UniswapV2Pair (the export); +# Runtime.lean the runtime bytecode of solar's plain compile (--emit=bin-runtime), as numbers, +# the bytes the statement binds the export to; +# SourceNoUpdate.lean, RuntimeNoUpdate.lean, SourceSkimUpdate.lean, RuntimeSkimUpdate.lean +# swap without its _update and skim that updates the reserves (negative controls +# Negative.lean runs): SolidCore's translation and solar's compile of the mutant +# (scripts/verify/uniswap-v2/UniswapV2PairNoUpdate.sol, UniswapV2PairSkimUpdate.sol). +# Fails (exit 1) if any step fails; nothing is written as passing that does not check. +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../.." +: "${SOLAR_DIR:?set SOLAR_DIR to a solar checkout}" +: "${SOLAR:?set SOLAR to a solar binary}" +: "${SOLAR_VERIFY:?set SOLAR_VERIFY to a solar-verify binary}" +sol=scripts/verify/uniswap-v2/UniswapV2Pair.sol +out=Contracts/UniswapV2/PairSpec +[[ -s $sol ]] || { echo "error: $sol missing; run scripts/verify/uniswap_v2_gen.sh" >&2; exit 1; } +opts=(-Ogas --evm-version osaka) +tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT +mkdir -p "$tmp/src"; cp "$sol" "$tmp/src/" +# The ERC20 and Pair sections (the flattened file holds both contracts; Math and Factory are not in it). +awk '/^# -+ Factory/ {exit} /^# -+ Math/ {skip=1} /^# -+ Pair/ {skip=0} !skip' \ + "$SOLAR_DIR/crates/verify/uniswap-v2/uniswap-v2.spec" > "$tmp/pair.spec" +grep -q '^== contract UniswapV2Pair' "$tmp/pair.spec" +grep -q '^== function UniswapV2Pair.swap' "$tmp/pair.spec" +# The wrong-K mutant: swap's fee-adjusted clause with 4 instead of 3 (stronger than the code meets). +sed 's/^\(@custom:ensures (reserve0 \* 1000 - IN(reserve0, amount0Out) \* \)3\() \* (reserve1 \* 1000 - IN(reserve1, amount1Out) \* \)3/\14\24/' \ + "$tmp/pair.spec" > "$tmp/pair-wrongk.spec" +! cmp -s "$tmp/pair.spec" "$tmp/pair-wrongk.spec" || { echo "error: the wrong-K mutation did not apply" >&2; exit 1; } +for v in plain wrongk; do + s="$tmp/pair.spec"; [[ $v == wrongk ]] && s="$tmp/pair-wrongk.spec" + python3 "$SOLAR_DIR/crates/verify/uniswap-v2/apply_specs.py" --src "$tmp/src" --out "$tmp/$v" --spec "$s" >/dev/null +done +(cd "$tmp/plain" && "$SOLAR_VERIFY" UniswapV2Pair.sol --emit-lean-spec "$tmp/Spec.lean" \ + --lean-spec-module SolidCore.Spec.Export.UniswapV2Pair) +(cd "$tmp/wrongk" && "$SOLAR_VERIFY" UniswapV2Pair.sol --emit-lean-spec "$tmp/SpecWrongK.lean" \ + --lean-spec-module SolidCore.Spec.Export.UniswapV2PairWrongK) +for m in Spec SpecWrongK; do + { echo "-- Generated by scripts/verify/uniswap_v2_pair_spec.sh. Do not edit."; cat "$tmp/$m.lean"; } > "$out/$m.lean" +done +# The bytecode: the stage export and the plain compile, from the same solar. +(cd "$tmp/src" && "$SOLAR" UniswapV2Pair.sol "${opts[@]}" --emit=bin-runtime -Zemit-lean-stages="$tmp/gen" >/dev/null 2>"$tmp/gen.log") \ + || { cat "$tmp/gen.log" >&2; exit 1; } +[[ -s "$tmp/gen/UniswapV2Pair/Bytecode.lean" ]] || { echo "error: no Bytecode.lean in the export" >&2; exit 1; } +{ echo "-- Generated by scripts/verify/uniswap_v2_pair_spec.sh from solar -Zemit-lean-stages. Do not edit." + cat "$tmp/gen/UniswapV2Pair/Bytecode.lean"; } > "$out/Bytecode.lean" +hex=$(cd "$tmp/src" && "$SOLAR" UniswapV2Pair.sol "${opts[@]}" --emit=bin-runtime 2>/dev/null \ + | python3 -c 'import json,sys; print(json.load(sys.stdin)["contracts"]["UniswapV2Pair.sol:UniswapV2Pair"]["bin-runtime"])') +[[ $hex =~ ^[0-9a-f]+$ ]] || { echo "error: no runtime bytecode for UniswapV2Pair" >&2; exit 1; } +python3 - "$hex" > "$out/Runtime.lean" <<'PY' +import sys +b = bytes.fromhex(sys.argv[1]) +rows = [", ".join(hex(x) for x in b[i:i + 16]) for i in range(0, len(b), 16)] +print("-- Generated by scripts/verify/uniswap_v2_pair_spec.sh from solar --emit=bin-runtime. Do not edit.") +print() +print("namespace SolidCore.Spec.UniswapV2.PairSpec") +print() +print("/-- The runtime bytecode of UniswapV2Pair, from solar's plain compile, as numbers. -/") +print("def runtimeBytes : List Nat :=") +print(" [" + ",\n ".join(rows) + "]") +print() +print("end SolidCore.Spec.UniswapV2.PairSpec") +PY +echo "wrote $out/Spec.lean $out/SpecWrongK.lean $out/Bytecode.lean $out/Runtime.lean (${#hex} hex digits)" + + +# Negative controls by execution: swap without its reserve update (the mutant source, its SolidCore +# translation and solar's compile of it). +python3 - "$sol" "$tmp/src/UniswapV2PairNoUpdate.sol" <<'PY' +import sys +src = open(sys.argv[1]).read() +at = src.index("external lock {", src.index("function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock")) +line = " _update(balance0, balance1, _reserve0, _reserve1);\n" +i = src.index(line, at) +nxt = src.find("function ", at + 1) +assert nxt == -1 or i < nxt, "swap's _update not found in swap" +open(sys.argv[2], "w").write(src[:i] + src[i + len(line):]) +PY +mut=scripts/verify/uniswap-v2/UniswapV2PairNoUpdate.sol +cp "$tmp/src/UniswapV2PairNoUpdate.sol" "$mut" +solc="${SOLC:-.cache/solc-0.8.35}" +{ echo "-- Generated by scripts/verify/uniswap_v2_pair_spec.sh: swap without its _update. Do not edit." + echo; echo "import SolidCore.Solidity.Checked"; echo; echo "open SolidCore.Solidity" + python3 scripts/solc_ast_to_lean_source.py --solc "$solc" --contract UniswapV2Pair \ + --namespace SolidCore.Verify.VC.Source.UniswapV2PairNoUpdate "$mut" \ + | tail -n +3; } > "$out/SourceNoUpdate.lean" +grep -q 'importedSourceUnit' "$out/SourceNoUpdate.lean" || { echo "error: no mutant source" >&2; exit 1; } +hexmut=$(cd "$tmp/src" && "$SOLAR" UniswapV2PairNoUpdate.sol "${opts[@]}" --emit=bin-runtime 2>/dev/null \ + | python3 -c 'import json,sys; print(json.load(sys.stdin)["contracts"]["UniswapV2PairNoUpdate.sol:UniswapV2Pair"]["bin-runtime"])') +[[ $hexmut =~ ^[0-9a-f]+$ && $hexmut != "$hex" ]] || { echo "error: no distinct mutant bytecode" >&2; exit 1; } +python3 - "$hexmut" > "$out/RuntimeNoUpdate.lean" <<'PY' +import sys +b = bytes.fromhex(sys.argv[1]) +rows = [", ".join(hex(x) for x in b[i:i + 16]) for i in range(0, len(b), 16)] +print("-- Generated by scripts/verify/uniswap_v2_pair_spec.sh: solar's compile of swap without its _update. Do not edit.") +print() +print("namespace SolidCore.Spec.UniswapV2.PairSpec") +print() +print("/-- The runtime bytecode of the mutant (swap without its reserve update), as numbers. -/") +print("def runtimeNoUpdate : List Nat :=") +print(" [" + ",\n ".join(rows) + "]") +print() +print("end SolidCore.Spec.UniswapV2.PairSpec") +PY +echo "wrote $out/SourceNoUpdate.lean $out/RuntimeNoUpdate.lean (${#hexmut} hex digits)" + +# Second mutant: skim that first forces the reserves to the balances (sync's _update at its start). +python3 - "$sol" "$tmp/src/UniswapV2PairSkimUpdate.sol" <<'PY' +import sys +src = open(sys.argv[1]).read() +head = "function skim(address to) external lock {\n" +i = src.index(head) + len(head) +assert src.count(head) == 1, "skim's body not found once" +upd = " _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);\n" +open(sys.argv[2], "w").write(src[:i] + upd + src[i:]) +PY +mut2=scripts/verify/uniswap-v2/UniswapV2PairSkimUpdate.sol +cp "$tmp/src/UniswapV2PairSkimUpdate.sol" "$mut2" +{ echo "-- Generated by scripts/verify/uniswap_v2_pair_spec.sh: skim that updates the reserves. Do not edit." + echo; echo "import SolidCore.Solidity.Checked"; echo; echo "open SolidCore.Solidity" + python3 scripts/solc_ast_to_lean_source.py --solc "$solc" --contract UniswapV2Pair \ + --namespace SolidCore.Verify.VC.Source.UniswapV2PairSkimUpdate "$mut2" \ + | tail -n +3; } > "$out/SourceSkimUpdate.lean" +grep -q 'importedSourceUnit' "$out/SourceSkimUpdate.lean" || { echo "error: no skim mutant source" >&2; exit 1; } +hexmut2=$(cd "$tmp/src" && "$SOLAR" UniswapV2PairSkimUpdate.sol "${opts[@]}" --emit=bin-runtime 2>/dev/null \ + | python3 -c 'import json,sys; print(json.load(sys.stdin)["contracts"]["UniswapV2PairSkimUpdate.sol:UniswapV2Pair"]["bin-runtime"])') +[[ $hexmut2 =~ ^[0-9a-f]+$ && $hexmut2 != "$hex" ]] || { echo "error: no distinct skim mutant bytecode" >&2; exit 1; } +python3 - "$hexmut2" > "$out/RuntimeSkimUpdate.lean" <<'PY' +import sys +b = bytes.fromhex(sys.argv[1]) +rows = [", ".join(hex(x) for x in b[i:i + 16]) for i in range(0, len(b), 16)] +print("-- Generated by scripts/verify/uniswap_v2_pair_spec.sh: solar's compile of skim that updates the reserves. Do not edit.") +print() +print("namespace SolidCore.Spec.UniswapV2.PairSpec") +print() +print("/-- The runtime bytecode of the mutant (skim forcing the reserves to the balances), as numbers. -/") +print("def runtimeSkimUpdate : List Nat :=") +print(" [" + ",\n ".join(rows) + "]") +print() +print("end SolidCore.Spec.UniswapV2.PairSpec") +PY +echo "wrote $out/SourceSkimUpdate.lean $out/RuntimeSkimUpdate.lean (${#hexmut2} hex digits)" diff --git a/scripts/verify/uniswap_v2_runtime.sh b/scripts/verify/uniswap_v2_runtime.sh new file mode 100755 index 00000000..fe7ecfe7 --- /dev/null +++ b/scripts/verify/uniswap_v2_runtime.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Write Contracts/UniswapV2/ERC20/Runtime.lean: UniswapV2ERC20's runtime bytecode as solar emits it +# for the certification target's options (-Ogas --evm-version osaka), from the ^0.8 port. +# Generated at build time and not committed (the port and its bytecode derive from GPL-3.0 v2-core). +# +# SOLAR=/path/to/solar scripts/verify/uniswap_v2_runtime.sh [PORT_DIR] +# +# PORT_DIR defaults to .cache/uniswap-v2/src (scripts/verify/uniswap_v2_gen.sh writes it). +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../.." + +: "${SOLAR:?set SOLAR to the solar binary whose output is certified}" +port="${1:-.cache/uniswap-v2/src}" +src="$port/UniswapV2ERC20.sol" +[[ -s "$src" ]] || { echo "error: $src missing (run scripts/verify/uniswap_v2_gen.sh)" >&2; exit 1; } + +version="$("$SOLAR" --version)" || { echo "error: $SOLAR --version failed" >&2; exit 1; } +version="$(head -n1 <<<"$version") ($(grep -m1 "Commit SHA" <<<"$version" || echo "no commit"))" +json="$(cd "$port" && "$SOLAR" -Ogas --evm-version osaka --emit bin-runtime UniswapV2ERC20.sol 2>/dev/null)" \ + || { echo "error: solar failed on $src" >&2; exit 1; } +hex="$(jq -er '.contracts["UniswapV2ERC20.sol:UniswapV2ERC20"]["bin-runtime"]' <<<"$json")" \ + || { echo "error: no runtime bytecode for UniswapV2ERC20" >&2; exit 1; } +[[ "$hex" =~ ^([0-9a-f]{2})+$ ]] || { echo "error: runtime bytecode is not even-length hex" >&2; exit 1; } +digest="$(printf '%s' "$hex" | sha256sum | cut -d' ' -f1)" +srcdigest="$(sha256sum "$src" | cut -d' ' -f1)" + +out=Contracts/UniswapV2/ERC20/Runtime.lean +{ + echo "-- Generated by scripts/verify/uniswap_v2_runtime.sh; do not edit, do not commit." + echo "-- solar: $version" + echo "-- options: -Ogas --evm-version osaka --emit bin-runtime" + echo "-- source sha256: $srcdigest" + echo "-- runtime hex sha256: $digest ($(( ${#hex} / 2 )) bytes)" + echo + echo "namespace SolidCore.Spec.UniswapV2.ERC20.Runtime" + echo + echo "/-- UniswapV2ERC20's runtime bytecode, as the solar above emits it. -/" + printf 'def code : ByteArray := ⟨#[' + sed -E 's/(..)/0x\1, /g; s/, $//' <<<"$hex" + echo "]⟩" + echo + echo "end SolidCore.Spec.UniswapV2.ERC20.Runtime" +} > "$out.tmp" +mv "$out.tmp" "$out" +echo "wrote $out: $(( ${#hex} / 2 )) bytes, sha256 $digest" diff --git a/scripts/verify/uniswap_v2_sources.py b/scripts/verify/uniswap_v2_sources.py new file mode 100755 index 00000000..8b2eb506 --- /dev/null +++ b/scripts/verify/uniswap_v2_sources.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Writes SolidCore's sources of the Uniswap V2 port (solar's solar-tv/uniswap-v2/port.py). + + scripts/verify/uniswap_v2_sources.py --port DIR [--solc SOLC] [--check] + +SolidCore's frontend (scripts/solc_ast_to_lean_source.py) reads one file with no imports and no +inline assembly but one create2 assignment, so for each certified contract this writes one file +(scripts/verify/uniswap-v2/NAME.sol): the contract's file and every file it imports, in import +order, each without its `import` and `pragma solidity` lines, under one +`pragma solidity ^0.8.0;`. One edit changes +code: `UniswapV2ERC20`'s constructor reads the chain ID as `block.chainid` instead of with +inline assembly `chainid()`, the same value (solc documents `block.chainid` as the `CHAINID` +opcode). Every edit must apply exactly once. solar's certified backend compiles the same file. +Then solc 0.8.35's AST of it goes through the frontend into Contracts/UniswapV2/C/Source.lean. +With --check, compares instead of writing and exits 1 on a difference. + +v2-core is GPL-3.0, so, as in solar, this repository keeps the recipe and not the code: the +`.sol` and `Source.lean` files are ignored by git and generated before the build, from the +output of solar's solar-tv/uniswap-v2/port.py (v2-core 6a9e7c9). +""" + +import argparse +import pathlib +import re +import subprocess +import sys + +ROOT = pathlib.Path(__file__).resolve().parent.parent.parent +OUT_SOL = ROOT / "scripts" / "verify" / "uniswap-v2" +FRONTEND = ROOT / "scripts" / "solc_ast_to_lean_source.py" +# (contract, its file in the port, the Lean directory under Contracts/UniswapV2, the functions +# the translation leaves out). `UniswapV2Factory.createPair` deploys the pair with inline +# assembly `pair := create2(0, add(bytecode, 32), mload(bytecode), salt)` of +# `type(UniswapV2Pair).creationCode`, the one assembly block the frontend translates +# (`Stmt.assemblyCreate2`), so every function is translated. +CONTRACTS = [ + ("UniswapV2ERC20", "UniswapV2ERC20.sol", "ERC20", []), + ("UniswapV2Pair", "UniswapV2Pair.sol", "Pair", []), + ("UniswapV2Factory", "UniswapV2Factory.sol", "Factory", []), +] +CHAINID_OLD = """ assembly { + chainId := chainid() + }""" +CHAINID_NEW = " chainId = block.chainid;" +IMPORT = re.compile(r"^import\s+['\"]([^'\"]+)['\"];\n", re.M) + + +def flatten(port: pathlib.Path, main: str) -> str: + order: list[pathlib.Path] = [] + + def visit(p: pathlib.Path) -> None: + p = p.resolve() + if p in order: + return + for m in IMPORT.finditer(p.read_text()): + visit(p.parent / m.group(1)) + order.append(p) + + visit(port / main) + parts = [] + for p in order: + text = p.read_text() + text = IMPORT.sub("", text) + text = re.sub(r"^pragma solidity [^;]+;\n", "", text, flags=re.M) + text = re.sub(r"^// SPDX-License-Identifier:[^\n]*\n", "", text, flags=re.M) + parts.append(f"// {p.relative_to(port.resolve())}\n{text.strip()}\n") + flat = "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.0;\n\n" + "\n".join(parts) + if flat.count(CHAINID_OLD) != 1: + sys.exit("error: the chain ID assembly occurs more than once") + return flat.replace(CHAINID_OLD, CHAINID_NEW) + + +def lean_of(solc: str, sol: pathlib.Path, contract: str, omit: list[str]) -> str: + rel = sol.relative_to(ROOT) + out = subprocess.run( + [sys.executable, str(FRONTEND), "--solc", solc, "--contract", contract, + "--namespace", f"SolidCore.Verify.VC.Source.{contract}", str(rel)] + + [f"--omit-function={f}" for f in omit], + cwd=ROOT, check=True, capture_output=True, text=True).stdout + head = "import SolidCore.Solidity.Checked\nimport SolidCore.Witness.Checked\n" + if not out.startswith(head): + sys.exit("error: unexpected frontend header") + left_out = f", without {', '.join(omit)}" if omit else "" + return (f"-- Generated from {rel} (the Uniswap V2 port's {contract}, flattened{left_out}) with " + "solc 0.8.35 by scripts/verify/uniswap_v2_sources.py. Do not edit.\n\n" + "import SolidCore.Solidity.Checked\n\nopen SolidCore.Solidity\n" + out[len(head):]) + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--port", type=pathlib.Path, required=True) + ap.add_argument("--solc", default="solc") + ap.add_argument("--check", action="store_true") + a = ap.parse_args() + status = 0 + OUT_SOL.mkdir(parents=True, exist_ok=True) + + def put(path: pathlib.Path, text: str) -> None: + nonlocal status + if a.check: + if not path.exists() or path.read_text() != text: + print(f"error: {path.relative_to(ROOT)} is out of date", file=sys.stderr) + status = 1 + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + + for contract, main_file, d, omit in CONTRACTS: + sol = OUT_SOL / f"{contract}.sol" + put(sol, flatten(a.port, main_file)) + if not a.check: + put(ROOT / "Contracts" / "UniswapV2" / d / "Source.lean", lean_of(a.solc, sol, contract, omit)) + return status + + +if __name__ == "__main__": + sys.exit(main()) + diff --git a/scripts/verify/uniswap_v2_spec-solar-rev b/scripts/verify/uniswap_v2_spec-solar-rev new file mode 100644 index 00000000..cc81ac07 --- /dev/null +++ b/scripts/verify/uniswap_v2_spec-solar-rev @@ -0,0 +1 @@ +91fc248452e2936dcec6a5628ef9c7e8a07634c1 diff --git a/scripts/verify/uniswap_v2_spec.sh b/scripts/verify/uniswap_v2_spec.sh new file mode 100755 index 00000000..389a2d0e --- /dev/null +++ b/scripts/verify/uniswap_v2_spec.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# Generate the Lean modules that connect solar-verify's Uniswap V2 ERC20 specs to SolidCore's +# checked UniswapV2ERC20, before their build. They are not committed: they are derived from the +# GPL-3.0 v2-core port (the erased trees of its functions), as Source.lean and Core.lean are. +# +# scripts/verify/uniswap_v2_spec.sh +# +# Needs scripts/verify/uniswap_v2_gen.sh's outputs (scripts/verify/uniswap-v2/UniswapV2ERC20.sol, +# Contracts/UniswapV2/ERC20/{Source,Core}.lean) and Core's build, and: +# SOLAR_DIR a solar checkout with crates/verify/uniswap-v2/{apply_specs.py,uniswap-v2.spec} +# and tools/certify/spec_connect.py (nested mapping slots, *_holds_in); +# SOLAR_VERIFY its solar-verify binary (--emit-lean-spec); +# LEAN the command that runs Lean on one file of this checkout (default: lake env lean). +# Writes, under Contracts/UniswapV2/ERC20/: +# Spec.lean solar-verify's --emit-lean-spec export of the ERC20 section of uniswap-v2.spec; +# SpecMut.lean the same with transfer's credit clause mutated (old(balanceOf[to]) + value + 1); +# Connect.lean spec_connect.py's module: per function the erased tree (kernel_rfl against +# SolidCore's checked contract), the spec of the tree (tree_meets_map or +# tree_meets_map2) and of SolidCore's contract in every world (_holds_in). +# Fails (exit 1) if any step fails or spec_connect refuses a function: nothing is written as +# passing that does not check. +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../.." +: "${SOLAR_DIR:?set SOLAR_DIR to a solar checkout}" +: "${SOLAR_VERIFY:?set SOLAR_VERIFY to a solar-verify binary}" +# Absolute paths: the steps below run solar-verify from temporary directories. +SOLAR_DIR="$(realpath "$SOLAR_DIR")" +SOLAR_VERIFY="$(realpath "$SOLAR_VERIFY")" +LEAN="${LEAN:-lake env lean}" +FUNCTIONS="${UV2_ERC20_FUNCTIONS:-UniswapV2ERC20.approve,UniswapV2ERC20.transfer}" +sol=scripts/verify/uniswap-v2/UniswapV2ERC20.sol +out=Contracts/UniswapV2/ERC20 +for f in "$sol" "$out/Source.lean" "$out/Core.lean"; do + [[ -s $f ]] || { echo "error: $f missing; run scripts/verify/uniswap_v2_gen.sh" >&2; exit 1; } +done +tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT +mkdir -p "$tmp/src"; cp "$sol" "$tmp/src/" +# The ERC20 section of the spec file: everything before the Math section. +spec="$SOLAR_DIR/crates/verify/uniswap-v2/uniswap-v2.spec" +awk '/^# -+ Math/ {exit} {print}' "$spec" > "$tmp/erc20.spec" +grep -q '^== contract UniswapV2ERC20' "$tmp/erc20.spec" +# The mutant: transfer credits one more than the amount. +sed 's/^\(@custom:ensures msg.sender != to ==> balanceOf\[to\] == old(balanceOf\[to\]) + value\)$/\1 + 1/' \ + "$tmp/erc20.spec" > "$tmp/erc20-mut.spec" +! cmp -s "$tmp/erc20.spec" "$tmp/erc20-mut.spec" || { echo "error: the mutation did not apply" >&2; exit 1; } +for v in plain mut; do + s="$tmp/erc20.spec"; [[ $v == mut ]] && s="$tmp/erc20-mut.spec" + python3 "$SOLAR_DIR/crates/verify/uniswap-v2/apply_specs.py" --src "$tmp/src" --out "$tmp/$v" --spec "$s" >/dev/null +done +(cd "$tmp/plain" && "$SOLAR_VERIFY" UniswapV2ERC20.sol --emit-lean-spec "$tmp/Spec.lean" \ + --lean-spec-module SolidCore.Spec.Export.UniswapV2ERC20) +(cd "$tmp/mut" && "$SOLAR_VERIFY" UniswapV2ERC20.sol --emit-lean-spec "$tmp/SpecMut.lean" \ + --lean-spec-module SolidCore.Spec.Export.UniswapV2ERC20SpecMut) +{ echo "-- Generated by scripts/verify/uniswap_v2_spec.sh. Do not edit."; cat "$tmp/Spec.lean"; } > "$out/Spec.lean" +{ echo "-- Generated by scripts/verify/uniswap_v2_spec.sh. Do not edit."; cat "$tmp/SpecMut.lean"; } > "$out/SpecMut.lean" +# spec_connect.py checks each function against the built Spec and SpecTreeKeccak modules. +lake build ${LAKE_BUILD_FLAGS:--KleanMemory=6000} Contracts.UniswapV2.ERC20.Spec \ + Contracts.UniswapV2.ERC20.SpecTreeKeccak +python3 "$SOLAR_DIR/tools/certify/spec_connect.py" --core-module Contracts.UniswapV2.ERC20.Core \ + --namespace SolidCore.Verify.VC.UniswapV2ERC20 --spec-module Contracts.UniswapV2.ERC20.Spec \ + --bundle SolidCore.Spec.Export.UniswapV2ERC20.UniswapV2ERC20 \ + --module-name SolidCore.Spec.UniswapV2.ERC20 --out "$out/Connect.lean" --lean "$LEAN" \ + --ghost-fixed --only "$FUNCTIONS" \ + --using SolidCore.Verify.VC.UniswapV2ERC20.digest_eq \ + --using SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq \ + --import Contracts.UniswapV2.ERC20.SpecTreeKeccak +echo "wrote $out/Spec.lean $out/SpecMut.lean $out/Connect.lean" diff --git a/scripts/verify/uniswap_v2_stage0_mutants.py b/scripts/verify/uniswap_v2_stage0_mutants.py new file mode 100755 index 00000000..e902fc48 --- /dev/null +++ b/scripts/verify/uniswap_v2_stage0_mutants.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""Writes three mutants of the exported stage0 of UniswapV2ERC20 for the negative controls of +Contracts/UniswapV2/ERC20/Nested/NegE3.lean (generated, not committed, as Stage0.lean is): + + Mut1 _approve's SSTORE of allowance[owner][spender] dropped; + Mut2 _approve hashes the owner into mapping slot 3 instead of 2 (allowance's slot); + Mut3 transferFrom's SSTORE of the spent allowance dropped. + +Each edit must apply exactly once inside its function, else exit 1. + + scripts/verify/uniswap_v2_stage0_mutants.py +""" +import pathlib, sys + +d = pathlib.Path("Certified/uv2_erc20/gen/UniswapV2ERC20") +src = (d / "Stage0.lean").read_text() + + +def fn_span(text, name): + i = text.index(f" -- @{name}\n") + j = text.index(" -- @", i + 1) + return i, j + + +def mutate(text, fn, old, new): + i, j = fn_span(text, fn) + body = text[i:j] + if body.count(old) != 1: + sys.exit(f"mutant: {old!r} occurs {body.count(old)} times in @{fn}") + return text[:i] + body.replace(old, new) + text[j:] + + +muts = { + "Mut1": ("_approve", " .effect none .sstore [.value 23, .value 2],\n", ""), + "Mut2": ("_approve", ".effect none .mstore [.const 32, .const 2],", ".effect none .mstore [.const 32, .const 3],"), + "Mut3": ("transferFrom", ",\n .effect none .sstore [.value 75, .value 20]]", "]"), +} +for name, (fn, old, new) in muts.items(): + t = mutate(src, fn, old, new) + t = t.replace("namespace SolarTV.Export.UniswapV2ERC20\n", f"namespace SolarTV.Export.UniswapV2ERC20{name}\n") + t = t.replace("end SolarTV.Export.UniswapV2ERC20\n", f"end SolarTV.Export.UniswapV2ERC20{name}\n") + if f"namespace SolarTV.Export.UniswapV2ERC20{name}" not in t: + sys.exit("mutant: namespace not found") + (d / f"Stage0{name}.lean").write_text(t) + print(f"wrote {d}/Stage0{name}.lean") diff --git a/scripts/verify/uniswap_v2_stages-solar-rev b/scripts/verify/uniswap_v2_stages-solar-rev new file mode 100644 index 00000000..33d017a5 --- /dev/null +++ b/scripts/verify/uniswap_v2_stages-solar-rev @@ -0,0 +1 @@ +697fc6864620d2fdb0b9b3ff66882ae4ad56b41e diff --git a/scripts/verify/uniswap_v2_stages.sh b/scripts/verify/uniswap_v2_stages.sh new file mode 100755 index 00000000..2f2324ec --- /dev/null +++ b/scripts/verify/uniswap_v2_stages.sh @@ -0,0 +1,91 @@ +#!/usr/bin/env bash +# Generate UniswapV2ERC20.transfer's slice before the build of the uv2_erc20 library: the exported +# stages, the backend stages' proofs, the bytes certificates and the gas certificate. None is +# committed: each is compiled from the GPL-3.0 v2-core port. +# +# scripts/verify/uniswap_v2_gen.sh # first: the port under .cache/uniswap-v2/src +# scripts/verify/uniswap_v2_stages.sh +# lake build -KleanMemory=6000 uv2_erc20 ContractsUniswapV2ERC20SourceMir +# +# Needs a solar checkout at the commit in scripts/verify/uniswap_v2_stages-solar-rev (SOLAR_DIR, +# default .cache/solar-stages) and its solar binary (SOLAR, default +# $SOLAR_DIR/target/release/solar, built here when missing). Writes, under Certified/uv2_erc20/: +# gen/UniswapV2ERC20/ solar -Zemit-lean-stages of the port (scripts/verify/uniswap_v2_erc20_stages.sh, +# with its stage0 mutants in gen/UniswapV2ERC20Mut); +# CtxGas.lean the checker with contexts and gas on the exact bytes against the final EVM +# IR, transfer's slice only (scripts/verify/uniswap_v2_gas.sh); +# ProofsT/ tools/certify/certify.py: each stage's refinement for the calls of +# transfer(address,uint256) (every other selector excluded), cut block by +# block so each module stays within 6 GB, and their composition +# (ProofsT/Stages.lean); +# Ctx.lean tools/certify/asm_ctx.py: the checker with contexts and STATICCALL +# (checkXB) accepts the exact runtime bytecode against the final EVM IR. Its +# bytes theorem is stated only for call-free bytes (AssembleNoCall); this +# contract's bytes make calls (permit's ecrecover STATICCALL), so Ctx states +# not_call_free and no bytes theorem (the gas certificate's guard route +# gives the bytes for transfer's calls); +# CtxNeg.lean the checker refuses the bytes with one byte changed (negative controls). +# Fails if any step fails or any module is missing afterwards. +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../.." + +rev="$(tr -d '[:space:]' < scripts/verify/uniswap_v2_stages-solar-rev)" +SOLAR_DIR="${SOLAR_DIR:-.cache/solar-stages}" +if ! git -C "$SOLAR_DIR" rev-parse --git-dir >/dev/null 2>&1; then + git init -q "$SOLAR_DIR" + git -C "$SOLAR_DIR" remote add origin https://github.com/paradigmxyz/solar.git +fi +if [[ "$(git -C "$SOLAR_DIR" rev-parse -q --verify HEAD 2>/dev/null || true)" != "$rev" ]]; then + git -C "$SOLAR_DIR" fetch -q --depth 1 origin "$rev" + git -C "$SOLAR_DIR" checkout -q --detach "$rev" +fi +SOLAR_DIR="$(realpath "$SOLAR_DIR")" +SOLAR="${SOLAR:-$SOLAR_DIR/target/release/solar}" +if [[ ! -x "$SOLAR" || "$(cat "$SOLAR_DIR/target/.stages-rev" 2>/dev/null)" != "$rev" ]]; then + cargo build --release --locked --manifest-path "$SOLAR_DIR/Cargo.toml" --bin solar + echo "$rev" > "$SOLAR_DIR/target/.stages-rev" +fi +SOLAR="$(realpath "$SOLAR")" +for f in tools/certify/certify.py tools/certify/asm_ctx.py tools/certify/gen_ctxgas.py; do + [[ -s "$SOLAR_DIR/$f" ]] || { echo "error: solar $rev has no $f" >&2; exit 1; } +done + +out=Certified/uv2_erc20 +gen="$out/gen/UniswapV2ERC20" +# The stages and the gas certificate (the gas script exports the stages first). +SOLAR_DIR="$SOLAR_DIR" SOLAR="$SOLAR" scripts/verify/uniswap_v2_gas.sh + +# The scope: calls of transfer(address,uint256); every other external function is excluded. +excluded=( + '06fdde03=name()' + '95d89b41=symbol()' + '313ce567=decimals()' + '18160ddd=totalSupply()' + '70a08231=balanceOf(address)' + 'dd62ed3e=allowance(address,address)' + '3644e515=DOMAIN_SEPARATOR()' + '30adf81f=PERMIT_TYPEHASH()' + '7ecebe00=nonces(address)' + 'd505accf=permit(address,address,uint256,uint256,uint8,bytes32,bytes32)' + '095ea7b3=approve(address,uint256)' + '23b872dd=transferFrom(address,address,uint256)' +) +args=() +for e in "${excluded[@]}"; do args+=(--exclude "$e"); done +rm -rf "$out/ProofsT" "$out/ProofsT.lean" "$out/Ctx.lean" "$out/CtxNeg.lean" +python3 "$SOLAR_DIR/tools/certify/certify.py" "$gen" --gen-module uv2_erc20.gen.UniswapV2ERC20 \ + --proof-dir "$out/ProofsT" --proof-module uv2_erc20.ProofsT \ + --namespace SolarTV.Milestone.Uv2Erc20T --label uv2_erc20_transfer \ + --cut --joins --no-mir-joins --segment 8 "${args[@]}" +python3 "$SOLAR_DIR/tools/certify/asm_ctx.py" "$gen" --gen-module uv2_erc20.gen.UniswapV2ERC20 \ + --out "$out/Ctx.lean" --neg-out "$out/CtxNeg.lean" --module uv2_erc20.Ctx + +# The last EVM IR stage is the one before assemble; how many passes change the code depends on +# the compiler, so it is read from the manifest. +last=$(python3 -c 'import json,sys; s=[x for x in json.load(open(sys.argv[1]))["stages"] if x["pass"]!="assemble"]; print(s[-1]["file"])' "$gen/manifest.json") +status=0 +for f in "$gen/Stage0.lean" "$gen/Sched.lean" "$gen/$last" "$gen/Bytecode.lean" "$out/CtxGas.lean" \ + "$out/ProofsT/Stages.lean" "$out/ProofsT/Assembly.lean" "$out/Ctx.lean" "$out/CtxNeg.lean"; do + [[ -s $f ]] || { echo "error: $f was not generated" >&2; status=1; } +done +exit "$status" diff --git a/scripts/verify/uniswap_v2_transfer_slice.sh b/scripts/verify/uniswap_v2_transfer_slice.sh new file mode 100755 index 00000000..2769c113 --- /dev/null +++ b/scripts/verify/uniswap_v2_transfer_slice.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# Generate the Lean modules of UniswapV2ERC20.transfer's certified slice that depend on the +# GPL-3.0 v2-core port, before their build (not committed, like Source.lean and Core.lean): +# +# scripts/verify/uniswap_v2_transfer_slice.sh +# +# Needs scripts/verify/uniswap_v2_gen.sh's outputs (scripts/verify/uniswap-v2/UniswapV2ERC20.sol, +# Contracts/UniswapV2/ERC20/{Source,Core}.lean) and: +# SOLAR_DIR a solar checkout with crates/verify/uniswap-v2/{apply_specs.py,transfer-slice.spec} +# and tools/certify/spec_connect.py with --tree-only; +# SOLAR_VERIFY its solar-verify binary (--emit-lean-spec); +# SOLC solc 0.8.35 (default .cache/solc-0.8.35, which uniswap_v2_gen.sh downloads); +# LEAN the command that runs Lean on one file of this checkout (default: lake env lean). +# Writes, under Contracts/UniswapV2/ERC20/Slice/Gen/: +# Spec.lean solar-verify's --emit-lean-spec export of transfer-slice.spec; +# Tree.lean spec_connect.py --tree-only: transfer's erased tree, checked against +# SolidCore's contract by kernel_rfl (transfer_erase_eq, deploy_eq); +# Mut/Source.lean, Mut/Core.lean, Mut/Tree.lean +# the frontend's source and the checked contract of each source mutant of the +# port (scripts/verify/uniswap-v2/transfer-mutants.txt): one text edit of +# the port, which must apply exactly once; Tree.lean is the mutant's transfer +# erased by the same stage (spec_connect.py --tree-only). +# Fails (exit 1) if any step fails: nothing is written as passing that does not check. +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../.." +: "${SOLAR_DIR:?set SOLAR_DIR to a solar checkout}" +: "${SOLAR_VERIFY:?set SOLAR_VERIFY to a solar-verify binary}" +SOLAR_DIR="$(realpath "$SOLAR_DIR")" +SOLAR_VERIFY="$(realpath "$SOLAR_VERIFY")" +SOLC="${SOLC:-.cache/solc-0.8.35}" +LEAN="${LEAN:-lake env lean}" +sol=scripts/verify/uniswap-v2/UniswapV2ERC20.sol +out=Contracts/UniswapV2/ERC20/Slice/Gen +for f in "$sol" Contracts/UniswapV2/ERC20/Source.lean Contracts/UniswapV2/ERC20/Core.lean; do + [[ -s $f ]] || { echo "error: $f missing; run scripts/verify/uniswap_v2_gen.sh" >&2; exit 1; } +done +mkdir -p "$out" +tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT +mkdir -p "$tmp/src"; cp "$sol" "$tmp/src/" +spec="$SOLAR_DIR/crates/verify/uniswap-v2/transfer-slice.spec" +python3 "$SOLAR_DIR/crates/verify/uniswap-v2/apply_specs.py" --src "$tmp/src" --out "$tmp/plain" --spec "$spec" >/dev/null +(cd "$tmp/plain" && "$SOLAR_VERIFY" UniswapV2ERC20.sol --emit-lean-spec "$tmp/Spec.lean" \ + --lean-spec-module SolidCore.Spec.Export.UniswapV2ERC20Slice) +{ echo "-- Generated by scripts/verify/uniswap_v2_transfer_slice.sh. Do not edit."; cat "$tmp/Spec.lean"; } > "$out/Spec.lean" + +# The source mutants: NAME, then the exact text of the port and its replacement, tab-separated. +while IFS=$'\t' read -r name old new; do + [[ -z $name || $name == \#* ]] && continue + old="${old//\\n/$'\n'}"; new="${new//\\n/$'\n'}" + msol="scripts/verify/uniswap-v2/UniswapV2ERC20Mut$name.sol" + python3 - "$sol" "$msol" "$old" "$new" <<'PY' +import sys +src, dst, old, new = sys.argv[1:] +text = open(src).read() +if text.count(old) != 1: + sys.exit(f"error: mutant edit applies {text.count(old)} times, not once: {old!r}") +open(dst, "w").write(text.replace(old, new)) +PY + d="$out/Mut$name"; mkdir -p "$d" + python3 scripts/verify/uniswap_v2_mutant.py --solc "$SOLC" --sol "$msol" --name "$name" --out "$d" +done < scripts/verify/uniswap-v2/transfer-mutants.txt + +lake build ${LAKE_BUILD_FLAGS:--KleanMemory=6000} Contracts.UniswapV2.ERC20.Slice.Gen.Spec \ + Contracts.UniswapV2.ERC20.SpecTreeKeccak Verify.VC.Model Verify.Spec.Tree Verify.Spec.TreeMap \ + Verify.Spec.TreeMapNested Verify.Spec.TreeIn Verify.VC.KernelIdx +python3 "$SOLAR_DIR/tools/certify/spec_connect.py" --core-module Contracts.UniswapV2.ERC20.Core \ + --namespace SolidCore.Verify.VC.UniswapV2ERC20 --spec-module Contracts.UniswapV2.ERC20.Slice.Gen.Spec \ + --bundle SolidCore.Spec.Export.UniswapV2ERC20Slice.UniswapV2ERC20 \ + --module-name SolidCore.Spec.UniswapV2.ERC20.Slice.Gen --out "$out/Tree.lean" --lean "$LEAN" \ + --tree-only --only UniswapV2ERC20.transfer \ + --using SolidCore.Verify.VC.UniswapV2ERC20.digest_eq \ + --using SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq \ + --import Contracts.UniswapV2.ERC20.SpecTreeKeccak + +# Each mutant's transfer, erased by the same stage and checked against its own contract. +while IFS=$'\t' read -r name _ _; do + [[ -z $name || $name == \#* ]] && continue + lake build ${LAKE_BUILD_FLAGS:--KleanMemory=6000} Contracts.UniswapV2.ERC20.Slice.Gen.Mut$name.Core + python3 "$SOLAR_DIR/tools/certify/spec_connect.py" --core-module Contracts.UniswapV2.ERC20.Slice.Gen.Mut$name.Core \ + --namespace SolidCore.Verify.VC.UniswapV2ERC20Mut$name --spec-module Contracts.UniswapV2.ERC20.Slice.Gen.Spec \ + --bundle SolidCore.Spec.Export.UniswapV2ERC20Slice.UniswapV2ERC20 \ + --module-name SolidCore.Spec.UniswapV2.ERC20.Slice.Gen.Mut$name --out "$out/Mut$name/Tree.lean" --lean "$LEAN" \ + --tree-only --only UniswapV2ERC20.transfer \ + --using SolidCore.Verify.VC.UniswapV2ERC20Mut$name.digest_eq \ + --using SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq \ + --import Contracts.UniswapV2.ERC20.SpecTreeKeccak +done < scripts/verify/uniswap-v2/transfer-mutants.txt +echo "wrote $out" diff --git a/scripts/verify/uniswap_v2_trees.py b/scripts/verify/uniswap_v2_trees.py new file mode 100755 index 00000000..0b8d249f --- /dev/null +++ b/scripts/verify/uniswap_v2_trees.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Writes Contracts/UniswapV2/ERC20/Nested/Trees.lean: the generic source stage's erased trees of +UniswapV2ERC20's approve and transferFrom, checked by the kernel against SolidCore's checked contract. + + scripts/verify/uniswap_v2_trees.py [--lean 'lake env lean'] + +Needs scripts/verify/uniswap_v2_gen.sh's outputs and the build of Contracts.UniswapV2.ERC20.Core and +Contracts.UniswapV2.ERC20.SpecTreeKeccak. The module is not committed (the trees are derived from the +GPL-3.0 v2-core port, as Source.lean and Core.lean are). Lean prints each tree by evaluation; the +module then states it by kernel_rfl, so nothing printed here is trusted: a wrong tree fails the build. +Exit 1 when the probe fails or a function is outside the generic source stage. +""" + +import argparse +import pathlib +import shlex +import subprocess +import sys +import tempfile + +NS = "SolidCore.Verify.VC.UniswapV2ERC20" +FNS = [("approve", 157198259), ("transferFrom", 599290589)] +USINGS = " ".join([ + f"{NS}.selector_eq", "SolidCore.Verify.VC.mkIdx_eq", f"{NS}.digest_eq", + "SolidCore.Spec.UniswapV2.ERC20.Keccak.keccakWord_eq", +]) +BT = chr(96) + +PROBE = """import Contracts.UniswapV2.ERC20.Core +import Verify.VC.Model + +open SolidCore.Refinement SolidCore.Refinement.Generic SolidCore.Solidity + +#eval show IO Unit from do + match {ns}.contract? with + | .error _ => IO.println "TREES error the contract does not type check" + | .ok c => + let dep := match TypeCheck.CheckedContract.constructWithContext? {ns}.fuel c (Wide.ctxOf c) + Source.State.empty SolidCore.Refinement.selfAddress 0 [] with + | some (Source.CallResult.returned d _) => + if d.events.isEmpty then some d.storage.toList else none + | _ => none + IO.println s!"TREES deployed {{repr dep}}" + for sel in {sels} do + match (c.core.findFunctionBySelector? sel).map fun f => (f.params.length, eraseFn (envOf c.core) {ns}.fuel f) with + | none => IO.println s!"TREES fn {{sel}} none" + | some (n, none) => IO.println s!"TREES fn {{sel}} {{n}} noerase" + | some (n, some t) => IO.println s!"TREES fn {{sel}} {{n}} TREE {{(repr t).pretty 100000}}" +""" + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--lean", default="lake env lean") + ap.add_argument("--out", type=pathlib.Path, default=pathlib.Path("Contracts/UniswapV2/ERC20/Nested/Trees.lean")) + args = ap.parse_args() + probe = PROBE.format(ns=NS, sels="[" + ", ".join(str(s) for _, s in FNS) + "]") + with tempfile.NamedTemporaryFile("w", suffix=".lean", dir=".", delete=False) as f: + f.write(probe) + path = pathlib.Path(f.name) + try: + res = subprocess.run(shlex.split(args.lean) + [str(path)], capture_output=True, text=True, check=False) + finally: + path.unlink() + lines = [l[len("TREES "):] for l in res.stdout.splitlines() if l.startswith("TREES ")] + if res.returncode != 0 or not lines or lines[0].startswith("error"): + sys.exit(f"uniswap_v2_trees: the probe failed:\n{res.stdout}\n{res.stderr}") + if not lines[0].startswith("deployed some "): + sys.exit(f"uniswap_v2_trees: the constructor does not deploy without logs: {lines[0]}") + deployed = lines[0][len("deployed some "):] + out = [ + "-- Generated by scripts/verify/uniswap_v2_trees.py. Do not edit.", + "import Contracts.UniswapV2.ERC20.Core", + "import Contracts.UniswapV2.ERC20.SpecTreeKeccak", + "import Verify.VC.Model", + "import Verify.VC.KernelIdx", + "import SolidCore.Refinement.KernelRfl", + "", + "/-!", + "# UniswapV2ERC20's approve and transferFrom as the generic source stage erases them", + "", + f"{BT}deploy_eq{BT}: the constructor deploys with {BT}deployed{BT} and no logs. {BT}F_erase_eq{BT}: SolidCore's", + f"checked contract dispatches F's selector to a function the generic source stage erases to {BT}F_tree{BT}.", + f"Both by {BT}kernel_rfl{BT} from the source text up.", + "-/", + "", + "namespace SolidCore.Spec.UniswapV2.ERC20.Nested", + "", + "open SolidCore.Refinement SolidCore.Refinement.Generic", + "", + f"def deployed : List (Nat × Nat) := {deployed}", + "", + "def deploy? : Bool :=", + f" match {NS}.contract? with", + f" | .ok c => Wide.deployedAt {NS}.fuel c deployed", + " | .error _ => false", + "", + f"kernel_rfl deploy_eq deploy? true using {USINGS}", + "", + ] + for (name, sel), line in zip(FNS, lines[1:]): + parts = line.split(" ", 4) + if parts[1] != str(sel) or parts[2] == "none" or parts[3] == "noerase": + sys.exit(f"uniswap_v2_trees: {name} is not erased: {line[:200]}") + n, tree = int(parts[2]), parts[4].removeprefix("TREE ") + out += [ + f"/-- {BT}{name}{BT} as the stage's ABI sees it. -/", + f"def fn_{name} : SolidCore.Refinement.Abi.Fn := ⟨{sel}, List.replicate {n} (.uint 256)⟩", + "", + f"def {name}_tree : Tree :=", + f" {tree}", + "", + f"def {name}_erase? : Option (Nat × Option Tree) :=", + f" match {NS}.contract? with", + f" | .ok c => (c.core.findFunctionBySelector? {sel}).map fun f => (f.params.length, eraseFn (envOf c.core) {NS}.fuel f)", + " | .error _ => none", + "", + f"kernel_rfl {name}_erase_eq {name}_erase? (some ({n}, some {name}_tree)) using {USINGS}", + "", + ] + out += ["end SolidCore.Spec.UniswapV2.ERC20.Nested", ""] + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text("\n".join(out)) + print(f"wrote {args.out}") + + +if __name__ == "__main__": + main() diff --git a/tv/SolarTV.lean b/tv/SolarTV.lean new file mode 100644 index 00000000..5ebe119d --- /dev/null +++ b/tv/SolarTV.lean @@ -0,0 +1,255 @@ +import SolarTV.MIR.Transforms.DCE +import SolarTV.MIR.Transforms.Casts +import SolarTV.MIR.Transforms.CheckElim +import SolarTV.MIR.Transforms.TrimSwitchDefaults +import SolarTV.MIR.Transforms.RenamePhiPredecessors +import SolarTV.EVMIR.Transforms.EqIszeroJumpi +import SolarTV.EVMIR.Transforms.StackPeephole +import SolarTV.EVMIR.StackSafety +import SolarTV.EVMIR.Memory +import SolarTV.MIR.Transforms.DeadStore +import SolarTV.MemorySafety +import SolarTV.MemorySymbolic +import SolarTV.MemorySymbolicSafety +import SolarTV.EVMIR.GasSafety +import SolarTV.EVMIR.Transforms.GasSwapAdd +import SolarTV.Stages.Assembly +import SolarTV.Stages.Link +import SolarTV.Stages.Entries + +import SolarTV.Agreement.Encoder +import SolarTV.Composition +import SolarTV.CutPoint +import SolarTV.CutPointExamples +import SolarTV.MIR.Validation.AddZero + +import SolarTV.State.StorageSafety +import SolarTV.State.Calls +import SolarTV.KeccakSafety +import SolarTV.WordSafety + +import SolarTV.EVMIR.State.Normalize +import SolarTV.EVMIR.State.Observe +import SolarTV.EVMIR.State.Safety +import SolarTV.EVMIR.Precompiles.Observe +import SolarTV.EVMIR.Precompiles.Safety +import SolarTV.MIR.State.Observe +import SolarTV.MIR.State.Safety +import SolarTV.MIR.State.Normalize + +-- Keep the transitive axiom sets visible on the pinned toolchain. An admitted +-- proof introduces sorryAx and fails the build even if it lives in an import. +/-- info: 'SolarTV.CutPoint.Sim.ends' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.CutPoint.Sim.ends + +/-- info: 'SolarTV.CutPoint.Sim.diverges_iff' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.CutPoint.Sim.diverges_iff + +/-- info: 'SolarTV.CutPoint.LayerSim.certified' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.CutPoint.LayerSim.certified + +/-- info: 'SolarTV.CutPoint.LayerSim.certified_back' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.CutPoint.LayerSim.certified_back + +/-- info: 'SolarTV.CutPoint.seg_ne_fuel' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.CutPoint.seg_ne_fuel + +/-- info: 'SolarTV.MIR.simplify_switch' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms SolarTV.MIR.simplify_switch + +/-- info: 'SolarTV.EVM.eq_iszero_jumpi' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.EVM.eq_iszero_jumpi + +/-- info: 'SolarTV.MIR.erase_unused' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.MIR.erase_unused + +/-- info: 'SolarTV.MIR.rename_phi_predecessors' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms SolarTV.MIR.rename_phi_predecessors + +/-- info: 'SolarTV.MIR.truncate_extended_address' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.MIR.truncate_extended_address + +/-- info: 'SolarTV.MIR.increment_below_bound' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.MIR.increment_below_bound + +/-- info: 'SolarTV.MIR.cannot_drop_overflow' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.MIR.cannot_drop_overflow + +/-- info: 'SolarTV.EVM.swap_add' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.EVM.swap_add + +/-- info: 'SolarTV.EVM.dropping_full_push_pop_changes_outcome' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.EVM.dropping_full_push_pop_changes_outcome + +/-- info: 'SolarTV.MIR.dead_store' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.MIR.dead_store + +/-- info: 'SolarTV.EVM.Gas.swap_add_refines' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.EVM.Gas.swap_add_refines + +/-- info: 'SolarTV.Assembly.stage' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Assembly.stage + +/-- info: 'SolarTV.Assembly.example_fault' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Assembly.example_fault + +/-- info: 'SolarTV.Entries.to_bytecode' does not depend on any axioms -/ +#guard_msgs in +#print axioms SolarTV.Entries.to_bytecode + +-- The agreement theorems that the pass validation encoder's terms are the Lean semantics. +-- They are kernel proofs: none bit-blasts, so none depends on a natively evaluated check. +/-- info: 'SolarTV.Agreement.step_sdiv' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Agreement.step_sdiv + +/-- info: 'SolarTV.Agreement.abstract_mulmod' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Agreement.abstract_mulmod + +/-- +info: 'SolarTV.Agreement.word_signextend' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.Agreement.word_signextend + +/-- +info: 'SolarTV.Agreement.mir_add_i160' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.Agreement.mir_add_i160 +/-- +info: 'SolarTV.Agreement.word_byte' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.Agreement.word_byte + +/-- +info: 'SolarTV.Agreement.mir_shl_i160' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.Agreement.mir_shl_i160 + +/-- +info: 'SolarTV.Agreement.mir_lt_i1' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.Agreement.mir_lt_i1 + +/-- +info: 'SolarTV.Agreement.mir_sext_i160_i256' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.Agreement.mir_sext_i160_i256 +-- Contract semantics and the composition of stages. +/-- info: 'SolarTV.mir_to_evmir_certified' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.mir_to_evmir_certified + +/-- info: 'SolarTV.mir_to_bytecode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.mir_to_bytecode + +/-- +info: 'SolarTV.MIR.Lowered.failureConvention' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.MIR.Lowered.failureConvention + +/-- +info: 'SolarTV.MIR.Lowered.moduleFailureConvention' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.MIR.Lowered.moduleFailureConvention + +/-- +info: 'SolarTV.EVM.Program.failureConvention' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.EVM.Program.failureConvention + +/-- +info: 'SolarTV.EVM.Program.stepOp_project' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.EVM.Program.stepOp_project +-- One pass validation query lifted to a stage. +/-- +info: 'SolarTV.MIR.Validation.AddZero.stage' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in +#print axioms SolarTV.MIR.Validation.AddZero.stage + +/-- info: 'SolarTV.Word.power_eq_pow' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Word.power_eq_pow + +/-- info: 'SolarTV.Keccak.empty' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Keccak.empty + +/-- info: 'SolarTV.Storage.overwrite' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Storage.overwrite + +/-- info: 'SolarTV.Storage.sentry_rejects' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Storage.sentry_rejects + +/-- info: 'SolarTV.Calls.reverted_restores_journal' does not depend on any axioms -/ +#guard_msgs in +#print axioms SolarTV.Calls.reverted_restores_journal + +/-- info: 'SolarTV.MIR.State.simultaneous_phis' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.MIR.State.simultaneous_phis + +/-- info: 'SolarTV.MIR.State.work_limit_is_not_equivalence' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms SolarTV.MIR.State.work_limit_is_not_equivalence + +/-- info: 'SolarTV.Execution.slotsWrite_overwrite' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Execution.slotsWrite_overwrite + +/-- info: 'SolarTV.Execution.flatten_wordBytes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Execution.flatten_wordBytes + +/-- info: 'SolarTV.Execution.readWord_writeWord' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.Execution.readWord_writeWord + +/-- info: 'SolarTV.MIR.State.run_next' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms SolarTV.MIR.State.run_next + +/-- info: 'SolarTV.MIR.State.live_return_data_is_observable' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms SolarTV.MIR.State.live_return_data_is_observable + +/-- info: 'SolarTV.MIR.State.project_inserted_field' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms SolarTV.MIR.State.project_inserted_field + +/-- info: 'SolarTV.MIR.State.uninitialized_neighbor' depends on axioms: [propext] -/ +#guard_msgs in +#print axioms SolarTV.MIR.State.uninitialized_neighbor diff --git a/tv/SolarTV/Agreement/Encoder.lean b/tv/SolarTV/Agreement/Encoder.lean new file mode 100644 index 00000000..fe45194a --- /dev/null +++ b/tv/SolarTV/Agreement/Encoder.lean @@ -0,0 +1,768 @@ +import SolarTV.Agreement.Tactic + +/-! Agreement of the pass validation encoder with the Lean semantics. + +Generated by the `lean_agreement` test in +`crates/codegen/src/mir/transform/validate_passes.rs`: do not edit by hand. Each term is +the one the encoder (`Encoder::pure`, `low_bits`, `sign_extend`, `not_equal` and +`select`) gives an operation on symbolic operands, translated to Lean by the certifier's +`word_term`, so a mistranslation of either fails these proofs. + +- `word_X` and `step_X`: the term of each pure opcode the encoder models exactly is its + `EvmRules.Evm` definition, and so the result `SolarTV.EVM.step` pushes. +- `exp_X`: the constant shapes of `EXP` the encoder computes exactly. +- `abstract_X`: the abstract tier's laws hold of the exact operation, so replacing it + with an uninterpreted function constrained by them only allows more models. +- `mir_X_iN`: the term of each MIR operation on `iN` operands, which the encoder keeps + as zero-extended words and masks to their width, is the zero-extended result of its + `SolarTV.MIR` definition. Signed operations read the sign bit of a word, so the + encoder rejects them on narrow integers and they appear at `i256` only. +-/ + +namespace SolarTV.Agreement + +open EvmRules + +set_option linter.unusedSimpArgs false + +theorem word_add («$a» «$b» : Word) : + («$a» + «$b») = + Evm.add «$a» «$b» := by + agree_word + +theorem step_add (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .add («$a» :: «$b» :: rest) = + some ((«$a» + «$b») :: rest) := by + rw [word_add]; rfl + +theorem word_mul («$a» «$b» : Word) : + («$a» * «$b») = + Evm.mul «$a» «$b» := by + agree_word + +theorem step_mul (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .mul («$a» :: «$b» :: rest) = + some ((«$a» * «$b») :: rest) := by + rw [word_mul]; rfl + +theorem word_sub («$a» «$b» : Word) : + («$a» - «$b») = + Evm.sub «$a» «$b» := by + agree_word + +theorem step_sub (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .sub («$a» :: «$b» :: rest) = + some ((«$a» - «$b») :: rest) := by + rw [word_sub]; rfl + +theorem word_div («$a» «$b» : Word) : + (if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtUDiv «$a» «$b»)) = + Evm.div «$a» «$b» := by + agree_word + +theorem step_div (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .div («$a» :: «$b» :: rest) = + some ((if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtUDiv «$a» «$b»)) :: rest) := by + rw [word_div]; rfl + +theorem word_sdiv («$a» «$b» : Word) : + (if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtSDiv «$a» «$b»)) = + Evm.sdiv «$a» «$b» := by + agree_word + +theorem step_sdiv (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .sdiv («$a» :: «$b» :: rest) = + some ((if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtSDiv «$a» «$b»)) :: rest) := by + rw [word_sdiv]; rfl + +theorem word_mod («$a» «$b» : Word) : + (if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$a» «$b»)) = + Evm.mod «$a» «$b» := by + agree_word + +theorem step_mod (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .mod («$a» :: «$b» :: rest) = + some ((if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$a» «$b»)) :: rest) := by + rw [word_mod]; rfl + +theorem word_smod («$a» «$b» : Word) : + (if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.srem «$a» «$b»)) = + Evm.smod «$a» «$b» := by + agree_word + +theorem step_smod (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .smod («$a» :: «$b» :: rest) = + some ((if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.srem «$a» «$b»)) :: rest) := by + rw [word_smod]; rfl + +theorem word_addmod («$a» «$b» «$c» : Word) : + (if («$c» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.extractLsb' 0 256 (BitVec.umod ((BitVec.setWidth 257 «$a») + (BitVec.setWidth 257 «$b»)) (BitVec.setWidth 257 «$c»)))) = + Evm.addmod «$a» «$b» «$c» := by + agree_word + +theorem step_addmod (ctx : EVM.Context) («$a» «$b» «$c» : Word) (rest : EVM.Stack) : + EVM.step ctx .addmod («$a» :: «$b» :: «$c» :: rest) = + some ((if («$c» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.extractLsb' 0 256 (BitVec.umod ((BitVec.setWidth 257 «$a») + (BitVec.setWidth 257 «$b»)) (BitVec.setWidth 257 «$c»)))) :: rest) := by + rw [word_addmod]; rfl + +theorem word_mulmod («$a» «$b» «$c» : Word) : + (if («$c» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.extractLsb' 0 256 (BitVec.umod ((BitVec.setWidth 512 «$a») * (BitVec.setWidth 512 «$b»)) (BitVec.setWidth 512 «$c»)))) = + Evm.mulmod «$a» «$b» «$c» := by + agree_word + +theorem step_mulmod (ctx : EVM.Context) («$a» «$b» «$c» : Word) (rest : EVM.Stack) : + EVM.step ctx .mulmod («$a» :: «$b» :: «$c» :: rest) = + some ((if («$c» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.extractLsb' 0 256 (BitVec.umod ((BitVec.setWidth 512 «$a») * (BitVec.setWidth 512 «$b»)) (BitVec.setWidth 512 «$c»)))) :: rest) := by + rw [word_mulmod]; rfl + +theorem word_signextend («$a» «$b» : Word) : + (if («$a» ≥ (0x000000000000000000000000000000000000000000000000000000000000001f#256)) then «$b» else (BitVec.sshiftRight' («$b» <<< ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * «$a»))) ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * «$a»)))) = + Evm.signextend «$a» «$b» := by + agree_word + +theorem step_signextend (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .signextend («$a» :: «$b» :: rest) = + some ((if («$a» ≥ (0x000000000000000000000000000000000000000000000000000000000000001f#256)) then «$b» else (BitVec.sshiftRight' («$b» <<< ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * «$a»))) ((0x00000000000000000000000000000000000000000000000000000000000000f8#256) - ((0x0000000000000000000000000000000000000000000000000000000000000008#256) * «$a»)))) :: rest) := by + rw [word_signextend]; rfl + +theorem word_lt («$a» «$b» : Word) : + (if («$a» < «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = + Evm.lt «$a» «$b» := by + agree_word + +theorem step_lt (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .lt («$a» :: «$b» :: rest) = + some ((if («$a» < «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) :: rest) := by + rw [word_lt]; rfl + +theorem word_gt («$a» «$b» : Word) : + (if («$a» > «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = + Evm.gt «$a» «$b» := by + agree_word + +theorem step_gt (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .gt («$a» :: «$b» :: rest) = + some ((if («$a» > «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) :: rest) := by + rw [word_gt]; rfl + +theorem word_slt («$a» «$b» : Word) : + (if ((BitVec.slt «$a» «$b») = true) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = + Evm.slt «$a» «$b» := by + agree_word + +theorem step_slt (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .slt («$a» :: «$b» :: rest) = + some ((if ((BitVec.slt «$a» «$b») = true) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) :: rest) := by + rw [word_slt]; rfl + +theorem word_sgt («$a» «$b» : Word) : + (if ((BitVec.slt «$b» «$a») = true) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = + Evm.sgt «$a» «$b» := by + agree_word + +theorem step_sgt (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .sgt («$a» :: «$b» :: rest) = + some ((if ((BitVec.slt «$b» «$a») = true) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) :: rest) := by + rw [word_sgt]; rfl + +theorem word_eq («$a» «$b» : Word) : + (if («$a» = «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = + Evm.eq «$a» «$b» := by + agree_word + +theorem step_eq (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .eq («$a» :: «$b» :: rest) = + some ((if («$a» = «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) :: rest) := by + rw [word_eq]; rfl + +theorem word_iszero («$a» : Word) : + (if («$a» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = + Evm.iszero «$a» := by + agree_word + +theorem step_iszero (ctx : EVM.Context) («$a» : Word) (rest : EVM.Stack) : + EVM.step ctx .iszero («$a» :: rest) = + some ((if («$a» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) :: rest) := by + rw [word_iszero]; rfl + +theorem word_and («$a» «$b» : Word) : + («$a» &&& «$b») = + Evm.and «$a» «$b» := by + agree_word + +theorem step_and (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .and («$a» :: «$b» :: rest) = + some ((«$a» &&& «$b») :: rest) := by + rw [word_and]; rfl + +theorem word_or («$a» «$b» : Word) : + («$a» ||| «$b») = + Evm.or «$a» «$b» := by + agree_word + +theorem step_or (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .or («$a» :: «$b» :: rest) = + some ((«$a» ||| «$b») :: rest) := by + rw [word_or]; rfl + +theorem word_xor («$a» «$b» : Word) : + («$a» ^^^ «$b») = + Evm.xor «$a» «$b» := by + agree_word + +theorem step_xor (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .xor («$a» :: «$b» :: rest) = + some ((«$a» ^^^ «$b») :: rest) := by + rw [word_xor]; rfl + +theorem word_not («$a» : Word) : + (~~~«$a») = + Evm.not «$a» := by + agree_word + +theorem step_not (ctx : EVM.Context) («$a» : Word) (rest : EVM.Stack) : + EVM.step ctx .not («$a» :: rest) = + some ((~~~«$a») :: rest) := by + rw [word_not]; rfl + +theorem word_byte («$a» «$b» : Word) : + (if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((«$b» >>> (((0x000000000000000000000000000000000000000000000000000000000000001f#256) - «$a») * (0x0000000000000000000000000000000000000000000000000000000000000008#256))) &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256))) = + Evm.byte «$a» «$b» := by + agree_word + +theorem step_byte (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .byte («$a» :: «$b» :: rest) = + some ((if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((«$b» >>> (((0x000000000000000000000000000000000000000000000000000000000000001f#256) - «$a») * (0x0000000000000000000000000000000000000000000000000000000000000008#256))) &&& (0x00000000000000000000000000000000000000000000000000000000000000ff#256))) :: rest) := by + rw [word_byte]; rfl + +theorem word_shl («$a» «$b» : Word) : + (if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» <<< «$a»)) = + Evm.shl «$a» «$b» := by + agree_word + +theorem step_shl (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .shl («$a» :: «$b» :: rest) = + some ((if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» <<< «$a»)) :: rest) := by + rw [word_shl]; rfl + +theorem word_shr («$a» «$b» : Word) : + (if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» >>> «$a»)) = + Evm.shr «$a» «$b» := by + agree_word + +theorem step_shr (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .shr («$a» :: «$b» :: rest) = + some ((if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» >>> «$a»)) :: rest) := by + rw [word_shr]; rfl + +theorem word_sar («$a» «$b» : Word) : + (if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (BitVec.sshiftRight' «$b» (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) else (BitVec.sshiftRight' «$b» «$a»)) = + Evm.sar «$a» «$b» := by + agree_word + +theorem step_sar (ctx : EVM.Context) («$a» «$b» : Word) (rest : EVM.Stack) : + EVM.step ctx .sar («$a» :: «$b» :: rest) = + some ((if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (BitVec.sshiftRight' «$b» (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) else (BitVec.sshiftRight' «$b» «$a»)) :: rest) := by + rw [word_sar]; rfl + +theorem exp_base_0 («$e» : Word) : + (if («$e» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) = + Evm.exp 0#256 «$e» := by + agree_exp + +theorem exp_base_1 («$e» : Word) : + (0x0000000000000000000000000000000000000000000000000000000000000001#256) = + Evm.exp 1#256 «$e» := by + agree_exp + +theorem exp_base_2 («$e» : Word) : + (if («$e» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((0x0000000000000000000000000000000000000000000000000000000000000001#256) <<< («$e» * (0x0000000000000000000000000000000000000000000000000000000000000001#256)))) = + Evm.exp 2#256 «$e» := by + agree_exp + +theorem exp_base_16 («$e» : Word) : + (if («$e» ≥ (0x0000000000000000000000000000000000000000000000000000000000000040#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((0x0000000000000000000000000000000000000000000000000000000000000001#256) <<< («$e» * (0x0000000000000000000000000000000000000000000000000000000000000004#256)))) = + Evm.exp 16#256 «$e» := by + agree_exp + +theorem exp_base_256 («$e» : Word) : + (if («$e» ≥ (0x0000000000000000000000000000000000000000000000000000000000000020#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((0x0000000000000000000000000000000000000000000000000000000000000001#256) <<< («$e» * (0x0000000000000000000000000000000000000000000000000000000000000008#256)))) = + Evm.exp 256#256 «$e» := by + agree_exp + +theorem exp_power_0 («$a» : Word) : + (0x0000000000000000000000000000000000000000000000000000000000000001#256) = + Evm.exp «$a» 0#256 := by + agree_exp + +theorem exp_power_1 («$a» : Word) : + ((0x0000000000000000000000000000000000000000000000000000000000000001#256) * «$a») = + Evm.exp «$a» 1#256 := by + agree_exp + +theorem exp_power_2 («$a» : Word) : + (((0x0000000000000000000000000000000000000000000000000000000000000001#256) * «$a») * «$a») = + Evm.exp «$a» 2#256 := by + agree_exp + +theorem exp_power_8 («$a» : Word) : + (((((((((0x0000000000000000000000000000000000000000000000000000000000000001#256) * «$a») * «$a») * «$a») * «$a») * «$a») * «$a») * «$a») * «$a») = + Evm.exp «$a» 8#256 := by + agree_exp + +theorem abstract_mul («$a» «$b» «$t» : Word) («$umul» : Word → Word → Word) + (hf : ∀ p q, «$umul» p q = Evm.mul p q) + (ht : «$t» = Evm.mul «$a» «$b») : + ((«$t» = («$umul» «$a» «$b»)) ∧ ((((«$a» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) ∨ («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) → («$t» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ (((«$a» = (0x0000000000000000000000000000000000000000000000000000000000000001#256)) → («$t» = «$b»)) ∧ (((«$b» = (0x0000000000000000000000000000000000000000000000000000000000000001#256)) → («$t» = «$a»)) ∧ («$t» = («$umul» «$b» «$a»)))))) := by + agree_abstract + +theorem abstract_div («$a» «$b» «$t» : Word) («$udiv» : Word → Word → Word) + (hf : ∀ p q, «$udiv» p q = Evm.div p q) + (ht : «$t» = Evm.div «$a» «$b») : + ((«$t» = («$udiv» «$a» «$b»)) ∧ (((«$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) → («$t» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((«$t» ≤ «$a») ∧ ((«$b» = (0x0000000000000000000000000000000000000000000000000000000000000001#256)) → («$t» = «$a»))))) := by + agree_abstract + +theorem abstract_mod («$a» «$b» «$t» : Word) («$umod» : Word → Word → Word) + (hf : ∀ p q, «$umod» p q = Evm.mod p q) + (ht : «$t» = Evm.mod «$a» «$b») : + ((«$t» = («$umod» «$a» «$b»)) ∧ (((«$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) → («$t» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ (((¬(«$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) → («$t» < «$b»)) ∧ ((«$t» ≤ «$a») ∧ ((«$a» < «$b») → («$t» = «$a»)))))) := by + agree_abstract + +theorem abstract_addmod («$a» «$b» «$c» «$t» : Word) («$addmod3» : Word → Word → Word → Word) + (hf : ∀ p q r, «$addmod3» p q r = Evm.addmod p q r) + (ht : «$t» = Evm.addmod «$a» «$b» «$c») : + ((«$t» = («$addmod3» «$a» «$b» «$c»)) ∧ (((«$c» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) → («$t» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((¬(«$c» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) → («$t» < «$c»)))) := by + agree_abstract + +theorem abstract_mulmod («$a» «$b» «$c» «$t» : Word) («$mulmod3» : Word → Word → Word → Word) + (hf : ∀ p q r, «$mulmod3» p q r = Evm.mulmod p q r) + (ht : «$t» = Evm.mulmod «$a» «$b» «$c») : + ((«$t» = («$mulmod3» «$a» «$b» «$c»)) ∧ (((«$c» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) → («$t» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) ∧ ((¬(«$c» = (0x0000000000000000000000000000000000000000000000000000000000000000#256))) → («$t» < «$c»)))) := by + agree_abstract + +theorem mir_add_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» + «$b») &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .add x y).setWidth 256 := by + agree_mir + +theorem mir_sub_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» - «$b») &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .sub x y).setWidth 256 := by + agree_mir + +theorem mir_mul_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» * «$b») &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .mul x y).setWidth 256 := by + agree_mir + +theorem mir_and_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» &&& «$b») &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .and x y).setWidth 256 := by + agree_mir + +theorem mir_or_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» ||| «$b») &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .or x y).setWidth 256 := by + agree_mir + +theorem mir_xor_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» ^^^ «$b») &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .xor x y).setWidth 256 := by + agree_mir + +theorem mir_div_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtUDiv «$a» «$b»)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .div x y).setWidth 256 := by + agree_mir + +theorem mir_mod_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$a» «$b»)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .mod x y).setWidth 256 := by + agree_mir + +theorem mir_shl_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» <<< «$a»)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .shl x y).setWidth 256 := by + agree_mir + +theorem mir_shr_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» >>> «$a»)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.eval .shr x y).setWidth 256 := by + agree_mir + +theorem mir_not_i1 (x : BitVec 1) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + ((~~~«$a») &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.not x).setWidth 256 := by + agree_mir + +theorem mir_lt_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» < «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .lt x y).setWidth 256 := by + agree_mir + +theorem mir_gt_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» > «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .gt x y).setWidth 256 := by + agree_mir + +theorem mir_eq_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» = «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .eq x y).setWidth 256 := by + agree_mir + +theorem mir_ne_i1 (x : BitVec 1) (y : BitVec 1) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$a» = «$b») then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .ne x y).setWidth 256 := by + agree_mir + +theorem mir_select_i1 (x : BitVec 1) (y : BitVec 1) (z : BitVec 1) («$a» «$b» «$c» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) + (hc : «$c» = z.setWidth 256) : + (if («$a» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then «$c» else «$b») = + (MIR.select x y z).setWidth 256 := by + agree_mir + +theorem mir_add_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» + «$b») &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .add x y).setWidth 256 := by + agree_mir + +theorem mir_sub_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» - «$b») &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .sub x y).setWidth 256 := by + agree_mir + +theorem mir_mul_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» * «$b») &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .mul x y).setWidth 256 := by + agree_mir + +theorem mir_and_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» &&& «$b») &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .and x y).setWidth 256 := by + agree_mir + +theorem mir_or_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» ||| «$b») &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .or x y).setWidth 256 := by + agree_mir + +theorem mir_xor_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((«$a» ^^^ «$b») &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .xor x y).setWidth 256 := by + agree_mir + +theorem mir_div_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtUDiv «$a» «$b»)) &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .div x y).setWidth 256 := by + agree_mir + +theorem mir_mod_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$a» «$b»)) &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .mod x y).setWidth 256 := by + agree_mir + +theorem mir_shl_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» <<< «$a»)) &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .shl x y).setWidth 256 := by + agree_mir + +theorem mir_shr_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» >>> «$a»)) &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.eval .shr x y).setWidth 256 := by + agree_mir + +theorem mir_not_i160 (x : BitVec 160) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + ((~~~«$a») &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.not x).setWidth 256 := by + agree_mir + +theorem mir_lt_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» < «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .lt x y).setWidth 256 := by + agree_mir + +theorem mir_gt_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» > «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .gt x y).setWidth 256 := by + agree_mir + +theorem mir_eq_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» = «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .eq x y).setWidth 256 := by + agree_mir + +theorem mir_ne_i160 (x : BitVec 160) (y : BitVec 160) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$a» = «$b») then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .ne x y).setWidth 256 := by + agree_mir + +theorem mir_select_i160 (x : BitVec 1) (y : BitVec 160) (z : BitVec 160) («$a» «$b» «$c» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) + (hc : «$c» = z.setWidth 256) : + (if («$a» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then «$c» else «$b») = + (MIR.select x y z).setWidth 256 := by + agree_mir + +theorem mir_add_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + («$a» + «$b») = + (MIR.eval .add x y).setWidth 256 := by + agree_mir + +theorem mir_sub_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + («$a» - «$b») = + (MIR.eval .sub x y).setWidth 256 := by + agree_mir + +theorem mir_mul_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + («$a» * «$b») = + (MIR.eval .mul x y).setWidth 256 := by + agree_mir + +theorem mir_and_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + («$a» &&& «$b») = + (MIR.eval .and x y).setWidth 256 := by + agree_mir + +theorem mir_or_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + («$a» ||| «$b») = + (MIR.eval .or x y).setWidth 256 := by + agree_mir + +theorem mir_xor_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + («$a» ^^^ «$b») = + (MIR.eval .xor x y).setWidth 256 := by + agree_mir + +theorem mir_div_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtUDiv «$a» «$b»)) = + (MIR.eval .div x y).setWidth 256 := by + agree_mir + +theorem mir_mod_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.umod «$a» «$b»)) = + (MIR.eval .mod x y).setWidth 256 := by + agree_mir + +theorem mir_sdiv_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.smtSDiv «$a» «$b»)) = + (MIR.eval .sdiv x y).setWidth 256 := by + agree_mir + +theorem mir_smod_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$b» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (BitVec.srem «$a» «$b»)) = + (MIR.eval .smod x y).setWidth 256 := by + agree_mir + +theorem mir_shl_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» <<< «$a»)) = + (MIR.eval .shl x y).setWidth 256 := by + agree_mir + +theorem mir_shr_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else («$b» >>> «$a»)) = + (MIR.eval .shr x y).setWidth 256 := by + agree_mir + +theorem mir_sar_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$a» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (BitVec.sshiftRight' «$b» (0x00000000000000000000000000000000000000000000000000000000000000ff#256)) else (BitVec.sshiftRight' «$b» «$a»)) = + (MIR.eval .sar x y).setWidth 256 := by + agree_mir + +theorem mir_not_i256 (x : BitVec 256) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + (~~~«$a») = + (MIR.not x).setWidth 256 := by + agree_mir + +theorem mir_lt_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» < «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .lt x y).setWidth 256 := by + agree_mir + +theorem mir_gt_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» > «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .gt x y).setWidth 256 := by + agree_mir + +theorem mir_slt_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if ((BitVec.slt «$a» «$b») = true) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .slt x y).setWidth 256 := by + agree_mir + +theorem mir_sgt_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if ((BitVec.slt «$b» «$a») = true) then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .sgt x y).setWidth 256 := by + agree_mir + +theorem mir_eq_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + ((if («$a» = «$b») then (0x0000000000000000000000000000000000000000000000000000000000000001#256) else (0x0000000000000000000000000000000000000000000000000000000000000000#256)) &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .eq x y).setWidth 256 := by + agree_mir + +theorem mir_ne_i256 (x : BitVec 256) (y : BitVec 256) («$a» «$b» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) : + (if («$a» = «$b») then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.compare .ne x y).setWidth 256 := by + agree_mir + +theorem mir_select_i256 (x : BitVec 1) (y : BitVec 256) (z : BitVec 256) («$a» «$b» «$c» : Word) + (ha : «$a» = x.setWidth 256) + (hb : «$b» = y.setWidth 256) + (hc : «$c» = z.setWidth 256) : + (if («$a» = (0x0000000000000000000000000000000000000000000000000000000000000000#256)) then «$c» else «$b») = + (MIR.select x y z).setWidth 256 := by + agree_mir + +theorem mir_zext_i1_i160 (x : BitVec 1) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + «$a» = + (MIR.cast .zext 160 x).setWidth 256 := by + agree_mir + +theorem mir_sext_i1_i160 (x : BitVec 1) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + ((BitVec.signExtend 256 (BitVec.extractLsb' 0 1 «$a»)) &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.cast .sext 160 x).setWidth 256 := by + agree_mir + +theorem mir_zext_i1_i256 (x : BitVec 1) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + «$a» = + (MIR.cast .zext 256 x).setWidth 256 := by + agree_mir + +theorem mir_sext_i1_i256 (x : BitVec 1) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + ((BitVec.signExtend 256 (BitVec.extractLsb' 0 1 «$a»)) &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.cast .sext 256 x).setWidth 256 := by + agree_mir + +theorem mir_trunc_i160_i1 (x : BitVec 160) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + («$a» &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.cast .trunc 1 x).setWidth 256 := by + agree_mir + +theorem mir_zext_i160_i256 (x : BitVec 160) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + «$a» = + (MIR.cast .zext 256 x).setWidth 256 := by + agree_mir + +theorem mir_sext_i160_i256 (x : BitVec 160) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + ((BitVec.signExtend 256 (BitVec.extractLsb' 0 160 «$a»)) &&& (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.cast .sext 256 x).setWidth 256 := by + agree_mir + +theorem mir_trunc_i256_i1 (x : BitVec 256) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + («$a» &&& (0x0000000000000000000000000000000000000000000000000000000000000001#256)) = + (MIR.cast .trunc 1 x).setWidth 256 := by + agree_mir + +theorem mir_trunc_i256_i160 (x : BitVec 256) («$a» : Word) + (ha : «$a» = x.setWidth 256) : + («$a» &&& (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256)) = + (MIR.cast .trunc 160 x).setWidth 256 := by + agree_mir + +end SolarTV.Agreement diff --git a/tv/SolarTV/Agreement/Tactic.lean b/tv/SolarTV/Agreement/Tactic.lean new file mode 100644 index 00000000..356ec5c9 --- /dev/null +++ b/tv/SolarTV/Agreement/Tactic.lean @@ -0,0 +1,552 @@ +import SolarTV.MIR.Ops +import SolarTV.EVMIR.Ops +import EvmRules.Tactic +import EvmRules.Reference + +/-! Tactics for the generated agreement theorems of `Encoder.lean`. + +Every theorem is proved by rewriting with the lemmas below and checked by the kernel alone: +no SAT solver, and `decide +kernel` only on closed terms. The EVM opcodes go through the +second transcription of `EvmRules.Reference`, the MIR operations through lemmas about +zero-extended operands, and divisions, remainders, products and the powers of `EXP` through +`BitVec.toNat`, as do the abstract tier's laws. -/ + +namespace SolarTV.Agreement + +open EvmRules + +/-- SMT-LIB's unsigned division by zero gives all ones; the guard the encoder puts +around it gives zero, as `DIV` does. -/ +theorem guarded_div (a b : Word) : + (if b = 0#256 then 0#256 else BitVec.smtUDiv a b) = Evm.div a b := by + by_cases h : b = 0#256 <;> simp [h, BitVec.smtUDiv, Evm.div] + +theorem guarded_sdiv (a b : Word) : + (if b = 0#256 then 0#256 else BitVec.smtSDiv a b) = Evm.sdiv a b := by + by_cases h : b = 0#256 + · simp [h, Evm.sdiv] + · have h' : -b ≠ 0#256 := by simpa using h + simp only [h, ite_false, BitVec.smtSDiv, BitVec.sdiv, BitVec.smtUDiv, Evm.sdiv] + split <;> simp_all + +theorem guarded_mod (a b : Word) : + (if b = 0#256 then 0#256 else BitVec.umod a b) = Evm.mod a b := by + by_cases h : b = 0#256 <;> simp [h, Evm.mod, BitVec.umod_eq] + +theorem guarded_smod (a b : Word) : + (if b = 0#256 then 0#256 else BitVec.srem a b) = Evm.smod a b := by + by_cases h : b = 0#256 <;> simp [h, Evm.smod] + +set_option exponentiation.threshold 512 in +theorem guarded_addmod (a b n : Word) : + (if n = 0#256 then 0#256 else BitVec.extractLsb' 0 256 + (BitVec.umod (BitVec.setWidth 257 a + BitVec.setWidth 257 b) (BitVec.setWidth 257 n))) = + Evm.addmod a b n := by + rw [← BitVec.setWidth_eq_extractLsb' (by decide)] + by_cases h : n = 0#256 + · simp [h, Evm.addmod] + · have h0 : ¬n = 0 := h + simp only [h, h0, ite_false, Evm.addmod, beq_iff_eq, Bool.cond_eq_ite, BitVec.umod_eq] + apply BitVec.eq_of_toNat_eq + have ha := a.isLt + have hb := b.isLt + have hn := n.isLt + have h1 : (2:Nat) ^ 257 = 2 * 2 ^ 256 := by rw [Nat.pow_succ, Nat.mul_comm] + have h2 : (2:Nat) ^ 512 = 2 ^ 256 * 2 ^ 256 := by rw [← Nat.pow_add] + have h3 : 2 ≤ (2:Nat) ^ 256 := Nat.le_self_pow (by decide) 2 + have h4 : 2 * 2 ^ 256 ≤ (2:Nat) ^ 256 * 2 ^ 256 := Nat.mul_le_mul_right _ h3 + simp only [BitVec.toNat_setWidth, BitVec.toNat_umod, BitVec.toNat_add, + Nat.mod_eq_of_lt (show a.toNat < 2 ^ 512 by omega), + Nat.mod_eq_of_lt (show b.toNat < 2 ^ 512 by omega), + Nat.mod_eq_of_lt (show n.toNat < 2 ^ 512 by omega), + Nat.mod_eq_of_lt (show a.toNat < 2 ^ 257 by omega), + Nat.mod_eq_of_lt (show b.toNat < 2 ^ 257 by omega), + Nat.mod_eq_of_lt (show n.toNat < 2 ^ 257 by omega), + Nat.mod_eq_of_lt (show a.toNat + b.toNat < 2 ^ 512 by omega), + Nat.mod_eq_of_lt (show a.toNat + b.toNat < 2 ^ 257 by omega)] + +theorem guarded_mulmod (a b n : Word) : + (if n = 0#256 then 0#256 else BitVec.extractLsb' 0 256 + (BitVec.umod (BitVec.setWidth 512 a * BitVec.setWidth 512 b) (BitVec.setWidth 512 n))) = + Evm.mulmod a b n := by + rw [← BitVec.setWidth_eq_extractLsb' (by decide)] + by_cases h : n = 0#256 + · simp [h, Evm.mulmod] + · simp [h, Evm.mulmod, BitVec.umod_eq] + +/-- The value of a power, which `BitVec` defines by repeated multiplication. -/ +theorem toNat_pow {w : Nat} (x : BitVec w) (n : Nat) : (x ^ n).toNat = x.toNat ^ n % 2 ^ w := by + induction n with + | zero => simp [BitVec.pow_zero, BitVec.toNat_ofNat] + | succ n ih => rw [BitVec.pow_succ, BitVec.toNat_mul, ih, Nat.pow_succ, Nat.mod_mul_mod] + +/-- A base `2^k` raised to `e` is `1 <<< (e k)`, zero once `e k` reaches the width: the +encoder's limit `L` is the least exponent with `L k ≥ 256`, below which `e k` cannot wrap. -/ +theorem exp_power_of_two (k L : Nat) (e : Word) (hk : k < 256) (hL : 256 ≤ L * k) + (hL' : (L - 1) * k < 256) (hL256 : L ≤ 256) : + (if e ≥ BitVec.ofNat 256 L then 0#256 else 1#256 <<< (e * BitVec.ofNat 256 k)) = + Evm.exp (BitVec.ofNat 256 (2 ^ k)) e := by + apply BitVec.eq_of_toNat_eq + have h256 : 256 < 2 ^ 256 := Nat.lt_two_pow_self + have hpow : 2 ^ k < 2 ^ 256 := Nat.pow_lt_pow_right (by decide) hk + have hL2 : L < 2 ^ 256 := by omega + have hk2 : k < 2 ^ 256 := by omega + simp only [Evm.exp, toNat_pow, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hpow, ← Nat.pow_mul] + simp only [GE.ge, BitVec.le_def, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hL2] + by_cases he : L ≤ e.toNat + · simp only [he, ↓reduceIte] + have : L * k ≤ e.toNat * k := Nat.mul_le_mul_right k he + obtain ⟨d, hd⟩ : ∃ d, k * e.toNat = 256 + d := ⟨k * e.toNat - 256, by + rw [Nat.mul_comm k]; omega⟩ + rw [hd, Nat.pow_add, Nat.mul_mod_right] + rfl + · simp only [he, ↓reduceIte] + have : e.toNat ≤ L - 1 := by omega + have hsmall : e.toNat * k < 256 := Nat.lt_of_le_of_lt (Nat.mul_le_mul_right k this) hL' + rw [BitVec.shiftLeft_eq', BitVec.toNat_shiftLeft, BitVec.toNat_mul, BitVec.toNat_ofNat, + BitVec.toNat_ofNat, Nat.mod_eq_of_lt hk2, Nat.mod_eq_of_lt (by omega : e.toNat * k < 2 ^ 256), + Nat.shiftLeft_eq, Nat.mul_comm (e.toNat) k] + simp + +theorem exp_zero_base (e : Word) : + (if e = 0#256 then 1#256 else 0#256) = Evm.exp 0#256 e := by + apply BitVec.eq_of_toNat_eq + by_cases hz : e = 0#256 + · simp [hz, Evm.exp] + · have : e.toNat ≠ 0 := fun hn => hz (BitVec.eq_of_toNat_eq (by simp [hn])) + simp [hz, Evm.exp, toNat_pow, Nat.zero_pow (Nat.pos_of_ne_zero this)] + +theorem exp_one_base (e : Word) : 1#256 = Evm.exp 1#256 e := by + apply BitVec.eq_of_toNat_eq + simp [Evm.exp, toNat_pow] + +/-- Low bits as the mask the encoder applies, for the narrow widths. -/ +theorem mask_160 (t : Word) : + t &&& 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256 = + (t.setWidth 160).setWidth 256 := by + apply BitVec.eq_of_toNat_eq + rw [BitVec.toNat_and, BitVec.toNat_setWidth, BitVec.toNat_setWidth, + show (0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff#256).toNat = + 2 ^ 160 - 1 from rfl, + Nat.and_two_pow_sub_one_eq_mod, Nat.mod_eq_of_lt (a := t.toNat % 2 ^ 160)] + exact Nat.lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (Nat.pow_le_pow_right (by decide) (by decide)) + +theorem mask_1 (t : Word) : + t &&& 0x0000000000000000000000000000000000000000000000000000000000000001#256 = + (t.setWidth 1).setWidth 256 := by + apply BitVec.eq_of_toNat_eq + rw [BitVec.toNat_and, BitVec.toNat_setWidth, BitVec.toNat_setWidth, + show (0x0000000000000000000000000000000000000000000000000000000000000001#256).toNat = + 2 ^ 1 - 1 from rfl, + Nat.and_two_pow_sub_one_eq_mod, Nat.mod_eq_of_lt (a := t.toNat % 2 ^ 1)] + exact Nat.lt_of_lt_of_le (Nat.mod_lt _ (by decide)) (Nat.pow_le_pow_right (by decide) (by decide)) + +theorem setWidth_div {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + x.setWidth 256 / y.setWidth 256 = (x / y).setWidth 256 := by + apply BitVec.eq_of_toNat_eq + have hx := x.isLt + have hy := y.isLt + have : 2 ^ w ≤ 2 ^ 256 := Nat.pow_le_pow_right (by omega) h + have hq : x.toNat / y.toNat < 2 ^ w := Nat.lt_of_le_of_lt (Nat.div_le_self _ _) hx + simp only [BitVec.toNat_udiv, BitVec.toNat_setWidth, + Nat.mod_eq_of_lt (show x.toNat < 2 ^ 256 by omega), + Nat.mod_eq_of_lt (show y.toNat < 2 ^ 256 by omega), + Nat.mod_eq_of_lt (show x.toNat / y.toNat < 2 ^ 256 by omega)] + +theorem setWidth_mod {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + x.setWidth 256 % y.setWidth 256 = (x % y).setWidth 256 := by + apply BitVec.eq_of_toNat_eq + have hx := x.isLt + have hy := y.isLt + have : 2 ^ w ≤ 2 ^ 256 := Nat.pow_le_pow_right (by omega) h + have hr : x.toNat % y.toNat < 2 ^ w := Nat.lt_of_le_of_lt (Nat.mod_le _ _) hx + simp only [BitVec.toNat_umod, BitVec.toNat_setWidth, + Nat.mod_eq_of_lt (show x.toNat < 2 ^ 256 by omega), + Nat.mod_eq_of_lt (show y.toNat < 2 ^ 256 by omega), + Nat.mod_eq_of_lt (show x.toNat % y.toNat < 2 ^ 256 by omega)] + +theorem setWidth_mul {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + ((x.setWidth 256 * y.setWidth 256).setWidth w).setWidth 256 = (x * y).setWidth 256 := by + rw [BitVec.setWidth_mul _ _ h, BitVec.setWidth_setWidth_of_le _ h, + BitVec.setWidth_setWidth_of_le _ h, BitVec.setWidth_eq, BitVec.setWidth_eq] + +/-- `SIGNEXTEND`'s shift is eight times the byte index; as a shift it bit-blasts cheaply. -/ +theorem mul_eight (a : Word) : + 0x0000000000000000000000000000000000000000000000000000000000000008#256 * a = a <<< 3 := by + apply BitVec.eq_of_toNat_eq + rw [BitVec.toNat_mul, BitVec.toNat_shiftLeft, Nat.shiftLeft_eq] + simp only [BitVec.toNat_ofNat] + rw [Nat.mul_comm] + +theorem beq_zero {a : Word} (h : ¬a = 0#256) : (a == 0) = false := by + simpa using h + +theorem toNat_ne_zero {a : Word} (h : ¬a = 0#256) : a.toNat ≠ 0 := + fun hn => h (BitVec.eq_of_toNat_eq (by simp [hn])) + +theorem mul_comm (a b : Word) : Evm.mul a b = Evm.mul b a := BitVec.mul_comm _ _ + +theorem div_le (a b : Word) : Evm.div a b ≤ a := by + simp only [Evm.div, BitVec.le_def, BitVec.toNat_udiv] + exact Nat.div_le_self _ _ + +theorem mod_lt (a b : Word) : ¬b = 0#256 → Evm.mod a b < b := by + intro h + simp only [Evm.mod, beq_zero h, Bool.cond_false, BitVec.lt_def, BitVec.toNat_umod] + exact Nat.mod_lt _ (Nat.pos_of_ne_zero (toNat_ne_zero h)) + +theorem mod_le (a b : Word) : Evm.mod a b ≤ a := by + by_cases h : b = 0#256 + · subst h; simp [Evm.mod, BitVec.le_def] + · simp only [Evm.mod, beq_zero h, Bool.cond_false, BitVec.le_def, BitVec.toNat_umod] + exact Nat.mod_le _ _ + +theorem mod_of_lt (a b : Word) : a < b → Evm.mod a b = a := by + intro h + have hb : ¬b = 0#256 := by + intro hb; subst hb; simp [BitVec.lt_def] at h + simp only [Evm.mod, beq_zero hb, Bool.cond_false] + apply BitVec.eq_of_toNat_eq + simp only [BitVec.toNat_umod] + exact Nat.mod_eq_of_lt (BitVec.lt_def.mp h) + +set_option exponentiation.threshold 512 in +theorem setWidth_umod_lt (x n : BitVec 512) (h : n.toNat ≠ 0) : + (BitVec.setWidth 256 (x % n)).toNat < n.toNat := by + simp only [BitVec.toNat_setWidth, BitVec.toNat_umod] + exact Nat.lt_of_le_of_lt (Nat.mod_le _ _) (Nat.mod_lt _ (Nat.pos_of_ne_zero h)) + +set_option exponentiation.threshold 512 in +theorem addmod_lt (a b n : Word) : ¬n = 0#256 → Evm.addmod a b n < n := by + intro h + have : (2:Nat) ^ 256 ≤ 2 ^ 512 := Nat.pow_le_pow_right (by decide) (by decide) + have hn : (n.setWidth 512).toNat = n.toNat := by + simp only [BitVec.toNat_setWidth]; exact Nat.mod_eq_of_lt (by have := n.isLt; omega) + simp only [Evm.addmod, beq_zero h, Bool.cond_false, BitVec.lt_def] + have := setWidth_umod_lt (BitVec.setWidth 512 a + BitVec.setWidth 512 b) (n.setWidth 512) + (by rw [hn]; exact toNat_ne_zero h) + rwa [hn] at this + +set_option exponentiation.threshold 512 in +theorem mulmod_lt (a b n : Word) : ¬n = 0#256 → Evm.mulmod a b n < n := by + intro h + have : (2:Nat) ^ 256 ≤ 2 ^ 512 := Nat.pow_le_pow_right (by decide) (by decide) + have hn : (n.setWidth 512).toNat = n.toNat := by + simp only [BitVec.toNat_setWidth]; exact Nat.mod_eq_of_lt (by have := n.isLt; omega) + simp only [Evm.mulmod, beq_zero h, Bool.cond_false, BitVec.lt_def] + have := setWidth_umod_lt (BitVec.setWidth 512 a * BitVec.setWidth 512 b) (n.setWidth 512) + (by rw [hn]; exact toNat_ne_zero h) + rwa [hn] at this + +theorem addmod_zero (a b n : Word) : n = 0#256 → Evm.addmod a b n = 0#256 := by + intro h; subst h; rfl + +theorem mulmod_zero (a b n : Word) : n = 0#256 → Evm.mulmod a b n = 0#256 := by + intro h; subst h; rfl + +/-! Kernel proofs of the remaining terms, without a SAT solver: the EVM opcodes through the +second transcription of `EvmRules.Reference`, and the MIR operations at the operand width +through the zero-extension lemmas below. An `i1` operand takes two values, so those +theorems split on them and the kernel evaluates each closed case. -/ + +theorem bv1_cases (x : BitVec 1) : x = 0#1 ∨ x = 1#1 := by + have h := x.isLt + have : x.toNat = 0 ∨ x.toNat = 1 := by omega + rcases this with h | h + · exact Or.inl (BitVec.eq_of_toNat_eq (by simp [h])) + · exact Or.inr (BitVec.eq_of_toNat_eq (by simp [h])) + +theorem enc_lt (a b : Word) : + (if a < b then 1#256 else 0#256) = Evm.lt a b := by + rw [lt_agrees]; rfl + +theorem enc_gt (a b : Word) : + (if a > b then 1#256 else 0#256) = Evm.gt a b := by + rw [gt_agrees]; rfl + +theorem enc_slt (a b : Word) : + (if (BitVec.slt a b = true) then 1#256 else 0#256) = Evm.slt a b := by + rw [slt_agrees]; rfl + +theorem enc_sgt (a b : Word) : + (if (BitVec.slt b a = true) then 1#256 else 0#256) = Evm.sgt a b := by + rw [sgt_agrees]; rfl + +theorem enc_eq (a b : Word) : + (if a = b then 1#256 else 0#256) = Evm.eq a b := by + rw [eq_agrees]; rfl + +theorem enc_iszero (a : Word) : + (if a = 0#256 then 1#256 else 0#256) = Evm.iszero a := by + rw [iszero_agrees]; rfl + +theorem enc_shl (a b : Word) : + (if a ≥ 256#256 then 0#256 else b <<< a) = Evm.shl a b := by + rw [shl_agrees] + unfold Reference.shl + by_cases h : a ≥ 256#256 + · rw [ite_eq_left h, ite_eq_right (by simpa [BitVec.le_def, BitVec.lt_def] using h)] + · rw [ite_eq_right h, ite_eq_left (by simpa [BitVec.le_def, BitVec.lt_def] using h), BitVec.shiftLeft_eq'] + +theorem enc_shr (a b : Word) : + (if a ≥ 256#256 then 0#256 else b >>> a) = Evm.shr a b := by + rw [shr_agrees] + unfold Reference.shr + by_cases h : a ≥ 256#256 + · rw [ite_eq_left h, ite_eq_right (by simpa [BitVec.le_def, BitVec.lt_def] using h)] + · rw [ite_eq_right h, ite_eq_left (by simpa [BitVec.le_def, BitVec.lt_def] using h), BitVec.ushiftRight_eq'] + +/-- Shifting by 255 already copies the sign bit into every bit. -/ +theorem sshiftRight_255 (b : Word) : b.sshiftRight 255 = b.sshiftRight 256 := by + apply BitVec.eq_of_getLsbD_eq + intro i hi + simp only [BitVec.getLsbD_sshiftRight, BitVec.msb_eq_getLsbD_last] + by_cases h0 : i = 0 + · subst h0; simp + · simp [show ¬255 + i < 256 by omega, show ¬256 + i < 256 by omega] + +theorem enc_sar (a b : Word) : + (if a ≥ 256#256 then BitVec.sshiftRight' b 255#256 else BitVec.sshiftRight' b a) = + Evm.sar a b := by + rw [sar_agrees] + unfold Reference.sar + by_cases h : a ≥ 256#256 + · rw [ite_eq_left h, ite_eq_right (by simpa [BitVec.le_def, BitVec.lt_def] using h), + BitVec.sshiftRight_eq'] + exact sshiftRight_255 b + · rw [ite_eq_right h, ite_eq_left (by simpa [BitVec.le_def, BitVec.lt_def] using h), + BitVec.sshiftRight_eq'] + +theorem enc_byte (a b : Word) : + (if a ≥ 32#256 then 0#256 else (b >>> ((31#256 - a) * 8#256)) &&& 255#256) = + Evm.byte a b := by + rw [byte_agrees] + unfold Reference.byte + by_cases h : a ≥ 32#256 + · rw [ite_eq_left h, ite_eq_right (by simpa [BitVec.le_def, BitVec.lt_def] using h)] + · have hc : ((31#256 - a) * 8#256).toNat < 256 := by + simp only [GE.ge, BitVec.le_def, BitVec.toNat_ofNat] at h + bv_omega + rw [ite_eq_right h, ite_eq_left (by simpa [BitVec.le_def, BitVec.lt_def] using h), Reference.shr, + ite_eq_left (by simpa [BitVec.lt_def] using hc), BitVec.ushiftRight_eq'] + +theorem enc_signextend (a b : Word) : + (if a ≥ 31#256 then b else + BitVec.sshiftRight' (b <<< (248#256 - 8#256 * a)) (248#256 - 8#256 * a)) = + Evm.signextend a b := by + rw [signextend_agrees] + unfold Reference.signextend + by_cases h : a ≥ 31#256 + · rw [ite_eq_left h, ite_eq_right (by simpa [BitVec.le_def, BitVec.lt_def] using h)] + · have hc : (248#256 - a * 8#256).toNat < 256 := by + simp only [GE.ge, BitVec.le_def, BitVec.toNat_ofNat] at h + bv_omega + rw [ite_eq_right h, ite_eq_left (by simpa [BitVec.le_def, BitVec.lt_def] using h), Reference.sar, + Reference.shl, ite_eq_left (by simpa [BitVec.lt_def] using hc), + ite_eq_left (by simpa [BitVec.lt_def] using hc), BitVec.mul_comm 8#256 a, + BitVec.sshiftRight_eq', BitVec.shiftLeft_eq'] + +theorem toNat_setWidth_256 {w : Nat} (x : BitVec w) (h : w ≤ 256) : + (x.setWidth 256).toNat = x.toNat := by + rw [BitVec.toNat_setWidth, + Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le x.isLt (Nat.pow_le_pow_right (by decide) h))] + +theorem setWidth_256_inj {w : Nat} {x y : BitVec w} (h : w ≤ 256) : + x.setWidth 256 = y.setWidth 256 ↔ x = y := by + constructor + · intro e + apply BitVec.eq_of_toNat_eq + have := congrArg BitVec.toNat e + rwa [toNat_setWidth_256 _ h, toNat_setWidth_256 _ h] at this + · intro e; rw [e] + +theorem setWidth_256_lt {w : Nat} {x y : BitVec w} (h : w ≤ 256) : + x.setWidth 256 < y.setWidth 256 ↔ x < y := by + simp only [BitVec.lt_def, toNat_setWidth_256 _ h] + +theorem setWidth_256_ge {w : Nat} {x : BitVec w} (h : w ≤ 256) : + x.setWidth 256 ≥ 256#256 ↔ 256 ≤ x.toNat := by + simp only [GE.ge, BitVec.le_def, toNat_setWidth_256 _ h, BitVec.toNat_ofNat] + +theorem low_ext {w : Nat} (x : BitVec w) (h : w ≤ 256) : (x.setWidth 256).setWidth w = x := by + rw [BitVec.setWidth_setWidth_of_le _ h, BitVec.setWidth_eq] + +theorem low_add {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + (x.setWidth 256 + y.setWidth 256).setWidth w = x + y := by + rw [BitVec.setWidth_add _ _ h, low_ext _ h, low_ext _ h] + +theorem low_sub {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + (x.setWidth 256 - y.setWidth 256).setWidth w = x - y := by + rw [BitVec.sub_eq_add_neg, BitVec.setWidth_add _ _ h, BitVec.setWidth_neg_of_le h, + low_ext _ h, low_ext _ h, ← BitVec.sub_eq_add_neg] + +theorem low_and {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + (x.setWidth 256 &&& y.setWidth 256).setWidth w = x &&& y := by + rw [BitVec.setWidth_and, low_ext _ h, low_ext _ h] + +theorem low_or {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + (x.setWidth 256 ||| y.setWidth 256).setWidth w = x ||| y := by + rw [BitVec.setWidth_or, low_ext _ h, low_ext _ h] + +theorem low_xor {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + (x.setWidth 256 ^^^ y.setWidth 256).setWidth w = x ^^^ y := by + rw [BitVec.setWidth_xor, low_ext _ h, low_ext _ h] + +theorem low_not {w : Nat} (x : BitVec w) (h : w ≤ 256) : + (~~~x.setWidth 256).setWidth w = ~~~x := by + rw [BitVec.setWidth_not h, low_ext _ h] + +theorem low_mod {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + (bif y.setWidth 256 == 0 then 0 else (x % y).setWidth 256).setWidth w = + if y = 0 then 0 else x % y := by + by_cases hy : y = 0 + · subst hy; simp + · have : (y.setWidth 256 == 0) = false := by + rw [beq_eq_false_iff_ne, ne_eq] + intro e + exact hy ((setWidth_256_inj h).mp (e.trans (BitVec.setWidth_zero 256 w).symm)) + rw [this, Bool.cond_false, ite_eq_right hy, low_ext _ h] + +theorem low_shl {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + (if x.setWidth 256 ≥ 256#256 then 0#256 else y.setWidth 256 <<< x.setWidth 256).setWidth w = + y <<< x.toNat := by + rw [BitVec.shiftLeft_eq', toNat_setWidth_256 _ h] + by_cases hx : x.setWidth 256 ≥ 256#256 + · rw [ite_eq_left hx, BitVec.shiftLeft_eq_zero (by have := (setWidth_256_ge h).mp hx; omega)] + simp + · rw [ite_eq_right hx, BitVec.setWidth_shiftLeft_of_le h, low_ext _ h] + +theorem low_shr {w : Nat} (x y : BitVec w) (h : w ≤ 256) : + (if x.setWidth 256 ≥ 256#256 then 0#256 else y.setWidth 256 >>> x.setWidth 256).setWidth w = + y >>> x.toNat := by + rw [BitVec.ushiftRight_eq', toNat_setWidth_256 _ h] + by_cases hx : x.setWidth 256 ≥ 256#256 + · rw [ite_eq_left hx, BitVec.ushiftRight_eq_zero (by have := (setWidth_256_ge h).mp hx; omega)] + simp + · rw [ite_eq_right hx, ← BitVec.setWidth_ushiftRight h, low_ext _ h] + +theorem word_mod_guard (x y : Word) : + (bif y == 0 then 0 else x % y) = if y = 0 then 0 else x % y := by + by_cases hy : y = 0 <;> simp [hy] + +theorem word_smod_guard (x y : Word) : + (bif y == 0 then 0 else x.srem y) = if y = 0 then 0 else x.srem y := by + by_cases hy : y = 0 <;> simp [hy] + +theorem word_shl_guard (x y : Word) : + (if x ≥ 256#256 then 0#256 else y <<< x) = y <<< x.toNat := by + rw [enc_shl, shl_agrees]; unfold Reference.shl + by_cases hx : x < 256#256 + · rw [ite_eq_left hx] + · rw [ite_eq_right hx, BitVec.shiftLeft_eq_zero (by simp [BitVec.lt_def] at hx; omega)] + +theorem word_shr_guard (x y : Word) : + (if x ≥ 256#256 then 0#256 else y >>> x) = y >>> x.toNat := by + rw [enc_shr, shr_agrees]; unfold Reference.shr + by_cases hx : x < 256#256 + · rw [ite_eq_left hx] + · rw [ite_eq_right hx, BitVec.ushiftRight_eq_zero (by simp [BitVec.lt_def] at hx; omega)] + +theorem word_sar_guard (x y : Word) : + (if x ≥ 256#256 then y.sshiftRight' 255#256 else y.sshiftRight' x) = + y.sshiftRight x.toNat := by + rw [enc_sar, sar_agrees]; unfold Reference.sar + by_cases hx : x < 256#256 + · rw [ite_eq_left hx] + · rw [ite_eq_right hx] + exact BitVec.sshiftRight_eq_sshiftRight_of_le (by decide) + (by simp [BitVec.lt_def] at hx; omega) + +theorem sext_160_256 (x : BitVec 160) : + BitVec.signExtend 256 (BitVec.extractLsb' 0 160 (BitVec.setWidth 256 x)) &&& + 115792089237316195423570985008687907853269984665640564039457584007913129639935#256 = + BitVec.signExtend 256 x := by + rw [← BitVec.setWidth_eq_extractLsb' (by decide), low_ext _ (by decide), + show (115792089237316195423570985008687907853269984665640564039457584007913129639935#256) = + BitVec.allOnes 256 from by decide +kernel, BitVec.and_allOnes] + +/-- The abstract tier's laws of the exact operation: the uninterpreted function is the +operation, so the first law holds by definition and each other one by a lemma above. -/ +macro "agree_abstract" : tactic => + `(tactic| ( + subst_vars + simp only [*, true_and] + repeat' apply And.intro + all_goals first + | with_reducible exact mul_comm _ _ + | with_reducible exact div_le _ _ + | with_reducible exact mod_le _ _ + | with_reducible exact mod_lt _ _ + | with_reducible exact mod_of_lt _ _ + | with_reducible exact addmod_lt _ _ _ + | with_reducible exact mulmod_lt _ _ _ + | with_reducible exact addmod_zero _ _ _ + | with_reducible exact mulmod_zero _ _ _ + | (rintro (h | h) <;> simp [h, Evm.mul]) + | (intro h; subst h; simp [Evm.mul, Evm.div, Evm.mod, Evm.addmod, Evm.mulmod]))) + +/-- The term of a pure opcode is its EVM definition: by definition, through the division +guards, or through the opcode's lemma above. -/ +macro "agree_word" : tactic => + `(tactic| first + | rfl + | simp only [guarded_div, guarded_sdiv, guarded_mod, guarded_smod, guarded_addmod, + guarded_mulmod]; done + | exact enc_lt _ _ + | exact enc_gt _ _ + | exact enc_slt _ _ + | exact enc_sgt _ _ + | exact enc_eq _ _ + | exact enc_iszero _ + | exact enc_byte _ _ + | exact enc_shl _ _ + | exact enc_shr _ _ + | exact enc_sar _ _ + | exact enc_signextend _ _) + +/-- The constant shapes of `EXP`. -/ +macro "agree_exp" : tactic => + `(tactic| first + | exact exp_zero_base _ + | exact exp_one_base _ + | (apply exp_power_of_two <;> decide) + | (simp only [Evm.exp, BitVec.toNat_ofNat, BitVec.pow_succ, BitVec.pow_zero]; done) + | (simp [Evm.exp, BitVec.pow_succ, BitVec.pow_zero]; done)) + +set_option hygiene false in +/-- A MIR operation's term: substitute the zero-extended operands, rewrite masks as low +bits and divisions, remainders and products at the operand width, then each operation at the +operand width by its lemma above. Comparisons split on their condition. An `i1` operand +(`x`, `y` or `z`, the generated theorems' names, hence the unhygienic macro) is split into +its two values, and the kernel evaluates what is then closed. -/ +macro "agree_mir" : tactic => + `(tactic| ( + subst_vars + try simp only [guarded_div, guarded_sdiv, guarded_mod, guarded_smod, mask_160, mask_1, + Evm.div, Evm.mod, Evm.sdiv, Evm.smod, MIR.eval, Word.binary, MIR.not, MIR.select, + MIR.compare, + MIR.cast, BitVec.setWidth_eq, setWidth_div _ _ (by decide : 160 ≤ 256), + setWidth_div _ _ (by decide : 1 ≤ 256), setWidth_mod _ _ (by decide : 160 ≤ 256), + setWidth_mod _ _ (by decide : 1 ≤ 256), setWidth_mul _ _ (by decide : 160 ≤ 256), + setWidth_mul _ _ (by decide : 1 ≤ 256)] + all_goals first + | rfl + | (simp only [low_add _ _ (by decide : 160 ≤ 256), low_sub _ _ (by decide : 160 ≤ 256), + low_and _ _ (by decide : 160 ≤ 256), low_or _ _ (by decide : 160 ≤ 256), + low_xor _ _ (by decide : 160 ≤ 256), low_not _ (by decide : 160 ≤ 256), + low_ext _ (by decide : 160 ≤ 256), low_mod _ _ (by decide : 160 ≤ 256), + low_shl _ _ (by decide : 160 ≤ 256), low_shr _ _ (by decide : 160 ≤ 256), + word_mod_guard, word_smod_guard, word_shl_guard, word_shr_guard, word_sar_guard, + sext_160_256]; done) + | rw [low_shl _ _ (by decide : 160 ≤ 256)] + | rw [low_shr _ _ (by decide : 160 ≤ 256)] + | (rcases bv1_cases x with rfl | rfl <;> + (try rcases bv1_cases y with rfl | rfl) <;> + (try rcases bv1_cases z with rfl | rfl) <;> + first | decide +kernel | simp) + | (try simp only [gt_iff_lt, setWidth_256_lt (by decide : 160 ≤ 256), + setWidth_256_inj (by decide : 160 ≤ 256), BitVec.ult_eq_decide_lt, decide_eq_true_eq, + beq_iff_eq, bne_iff_ne, ne_eq] + split <;> (try split) <;> first | decide +kernel | (exfalso; simp_all)))) + +end SolarTV.Agreement diff --git a/tv/SolarTV/Composition.lean b/tv/SolarTV/Composition.lean new file mode 100644 index 00000000..c042fe89 --- /dev/null +++ b/tv/SolarTV/Composition.lean @@ -0,0 +1,112 @@ +import SolarTV.MIR.Program +import SolarTV.EVMIR.Program + +/-! Composing the stages of the backend into one stage from lowered MIR to EVM IR. + +A compilation is the lowered MIR module, the output of each MIR pass after it, the +scheduled EVM IR program and the output of each EVM IR pass. Each MIR pass and each EVM IR +pass is a stage of its layer's semantics, which `-Zvalidate-passes` and +`-Zvalidate-evm-ir-passes` check pass by pass, and scheduling is a stage between the two +layers, which `-Zvalidate-backend` checks. Chaining them gives a stage from the MIR the +pipeline starts with to the EVM IR it ends with (`mir_to_evmir`), or from certificates +(`mir_to_evmir_certified`). The MIR semantics is at the lowered phase, so `lower-abi` and +`lower-dispatch` are outside these stages. `AssemblyStage` is the stage from EVM IR to +bytecode, which solidity-lean's bytecode semantics states, and `mir_to_bytecode` composes +it. -/ + +namespace SolarTV + +open Machine + +noncomputable def mirSem (o : Oracle) : Sem := MIR.Lowered.moduleSem o + +noncomputable def evmirSem (o : Oracle) : Sem := EVM.Program.sem o + +/-- Each program is a stage of the one before it. -/ +def Steps (S : Sem) (scope : Call → Prop) : List S.Prog → Prop + | [] | [_] => True + | p :: q :: rest => Stage S S p q scope ∧ Steps S scope (q :: rest) + +/-- Each program is certified against the one before it. -/ +def CertifiedSteps (L : Layer) (o : Oracle) (scope : Call → Prop) : List L.Prog → Prop + | [] | [_] => True + | p :: q :: rest => Certified L L o p q scope ∧ CertifiedSteps L o scope (q :: rest) + +theorem Steps.stage {S : Sem} {scope : Call → Prop} : + ∀ (p : S.Prog) (ps : List S.Prog), Steps S scope (p :: ps) → + Stage S S p ((p :: ps).getLast (List.cons_ne_nil p ps)) scope + | p, [], _ => Stage.refl S p scope + | p, q :: rest, ⟨first, steps⟩ => by + rw [List.getLast_cons_cons] + exact first.trans (Steps.stage q rest steps) + +theorem CertifiedSteps.certified {L : Layer} {o : Oracle} {scope : Call → Prop} : + ∀ (p : L.Prog) (ps : List L.Prog), CertifiedSteps L o scope (p :: ps) → + Certified L L o p ((p :: ps).getLast (List.cons_ne_nil p ps)) scope + | p, [], _ => Certified.refl L o p scope + | p, q :: rest, ⟨first, steps⟩ => by + rw [List.getLast_cons_cons] + exact first.trans (CertifiedSteps.certified q rest steps) + +theorem CertifiedSteps.steps {L : Layer} {o : Oracle} {scope : Call → Prop} : + ∀ (ps : List L.Prog), CertifiedSteps L o scope ps → Steps (L.sem o) scope ps + | [], _ | [_], _ => trivial + | _ :: q :: rest, ⟨first, steps⟩ => + ⟨stage_of_certified first, CertifiedSteps.steps (q :: rest) steps⟩ + +structure Compilation where + mir : MIR.Lowered.Module + mirPasses : List MIR.Lowered.Module + scheduled : EVM.Program.Program + evmirPasses : List EVM.Program.Program + +/-- The MIR the backend schedules: the output of the last MIR pass. -/ +def Compilation.scheduledFrom (p : Compilation) : MIR.Lowered.Module := + (p.mir :: p.mirPasses).getLast (List.cons_ne_nil _ _) + +/-- The EVM IR the pipeline ends with: the output of the last EVM IR pass. -/ +def Compilation.evmir (p : Compilation) : EVM.Program.Program := + (p.scheduled :: p.evmirPasses).getLast (List.cons_ne_nil _ _) + +theorem mir_to_evmir (o : Oracle) (scope : Call → Prop) (p : Compilation) + (mirPasses : Steps (mirSem o) scope (p.mir :: p.mirPasses)) + (scheduling : Stage (mirSem o) (evmirSem o) p.scheduledFrom p.scheduled scope) + (evmirPasses : Steps (evmirSem o) scope (p.scheduled :: p.evmirPasses)) : + Stage (mirSem o) (evmirSem o) p.mir p.evmir scope := + ((Steps.stage _ _ mirPasses).trans scheduling).trans (Steps.stage _ _ evmirPasses) + +theorem mir_to_evmir_certified (o : Oracle) (scope : Call → Prop) (p : Compilation) + (mirPasses : CertifiedSteps MIR.Lowered.moduleLayer o scope (p.mir :: p.mirPasses)) + (scheduling : Certified MIR.Lowered.moduleLayer EVM.Program.layer o p.scheduledFrom p.scheduled + scope) + (evmirPasses : CertifiedSteps EVM.Program.layer o scope (p.scheduled :: p.evmirPasses)) : + Stage (mirSem o) (evmirSem o) p.mir p.evmir scope := + mir_to_evmir o scope p (CertifiedSteps.steps _ mirPasses) (stage_of_certified scheduling) + (CertifiedSteps.steps _ evmirPasses) + +/-- The stage from scheduled EVM IR to bytecode under a bytecode semantics, which this +library takes as a hypothesis. -/ +def AssemblyStage (bytecode : Sem) (o : Oracle) (q : EVM.Program.Program) + (code : bytecode.Prog) (scope : Call → Prop) : Prop := + Stage (evmirSem o) bytecode q code scope + +theorem mir_to_bytecode (o : Oracle) (scope : Call → Prop) (p : Compilation) + (bytecode : Sem) (code : bytecode.Prog) + (mirPasses : CertifiedSteps MIR.Lowered.moduleLayer o scope (p.mir :: p.mirPasses)) + (scheduling : Certified MIR.Lowered.moduleLayer EVM.Program.layer o p.scheduledFrom p.scheduled + scope) + (evmirPasses : CertifiedSteps EVM.Program.layer o scope (p.scheduled :: p.evmirPasses)) + (assembly : AssemblyStage bytecode o p.evmir code scope) : + Stage (mirSem o) bytecode p.mir code scope := + (mir_to_evmir_certified o scope p mirPasses scheduling evmirPasses).trans assembly + +/-- One MIR pass, the backend and one EVM IR pass, each certified. -/ +theorem pipeline {o : Oracle} {scope : Call → Prop} {f g : MIR.Lowered.Module} + {q r : EVM.Program.Program} + (mirPass : Certified MIR.Lowered.moduleLayer MIR.Lowered.moduleLayer o f g scope) + (scheduling : Certified MIR.Lowered.moduleLayer EVM.Program.layer o g q scope) + (evmirPass : Certified EVM.Program.layer EVM.Program.layer o q r scope) : + Stage (mirSem o) (evmirSem o) f r scope := + stage_of_certified ((mirPass.trans scheduling).trans evmirPass) + +end SolarTV diff --git a/tv/SolarTV/CutPoint.lean b/tv/SolarTV/CutPoint.lean new file mode 100644 index 00000000..ecfeb17b --- /dev/null +++ b/tv/SolarTV/CutPoint.lean @@ -0,0 +1,533 @@ +import SolarTV.Machine + +/-! Whole runs from loop-free segments between cut points. + +A stage whose programs loop cannot be proved by running both on a call to their ends, as the +loop-free stages are: a loop runs as many times as its data says. Instead, each program gets +cut points, configurations such as the headers of its loops, so that every cycle of its control +flow passes through one, and the two programs get a relation between their configurations at +cut points. A segment runs a program from a configuration for at least one step and on until it +reaches a cut point, ends, or is stuck (\`seg\`); it is loop-free, so symbolic execution runs it +to the end with fuel the number of blocks (\`seg_ne_fuel\` shows such fuel suffices when every +cycle passes through a cut point). \`Sim\` asks that from every related pair of configurations, +both segments end alike: in results that agree, at cut points that are related again, or both +stuck. Running out of a segment's fuel matches nothing, so a segment that does not end where the +procedure expects fails the proof, by mismatch. + +From that alone, whole runs are related for any number of loop iterations (\`Sim.ends\`, +\`Sim.ends_back\`): every end of one program at some fuel is matched by an agreeing end of the +other at some fuel, in both directions, so one program ends exactly when the other does +(\`Sim.ends_iff\`); one is stuck exactly when the other is (\`Sim.stuck_iff\`); and one runs forever +exactly when the other does (\`Sim.diverges_iff\`). None of these holds vacuously: the segment +obligation has no case for running out of fuel, and each segment takes at least one step, so +an infinite run of one program is matched step for step by an infinite run of the other. + +Nothing here depends on what a configuration is, so the same theorem serves every stage whose +programs run as a step function with fuel (\`Machine.iterate\`): MIR to MIR, MIR to EVM IR and EVM +IR to EVM IR, and EVM IR to any bytecode semantics given as a step function. The relation is the +exporter's: it derives it from what the compiler records at each cut point (the values that +correspond, the phis, the stack layout of a loop header); this file proves no invariant of its +own. \`certified\` and \`certified_back\` state the result for layers. -/ + +namespace SolarTV.CutPoint + +universe u v u' v' + +/-- A machine of configurations \`σ\` and results \`R\`: one step ends in a result, continues from +a new configuration, or is stuck (\`none\`). -/ +abbrev Step (σ : Type u) (R : Type v) := σ → Option (R ⊕ σ) + +variable {σ : Type u} {R : Type v} {τ : Type u'} {R' : Type v'} + +/-- A run with fuel, one unit per step, as \`Machine.iterate\` runs: the result, or \`none\` when the +fuel runs out or the machine is stuck. -/ +def run (step : Step σ R) : Nat → σ → Option R + | 0, _ => none + | n + 1, x => + match step x with + | some (.inl r) => some r + | some (.inr y) => run step n y + | none => none + +/-- \`k\` steps from a configuration: the result reached on the way, the configuration after +them, or \`none\` when the machine is stuck on the way. -/ +def steps (step : Step σ R) : Nat → σ → Option (R ⊕ σ) + | 0, x => some (.inr x) + | k + 1, x => + match step x with + | some (.inl r) => some (.inl r) + | some (.inr y) => steps step k y + | none => none + +/-- A configuration from which the machine runs forever. -/ +def Diverges (step : Step σ R) (x : σ) : Prop := ∀ k, ∃ y, steps step k x = some (.inr y) + +/-- A configuration from which the machine gets stuck. -/ +def Stuck (step : Step σ R) (x : σ) : Prop := ∃ k, steps step k x = none + +/-- How a segment ends: in a result, at a cut point, stuck, or out of its fuel. -/ +inductive Seg (R : Type v) (σ : Type u) where + | done (r : R) + | cut (y : σ) + | stuck + | fuel + +/-- A segment from \`x\`: one step, then on until a cut point, an end or a stuck step, for at most +\`k\` steps in all. -/ +def seg (step : Step σ R) (cut : σ → Bool) : Nat → σ → Seg R σ + | 0, _ => .fuel + | k + 1, x => + match step x with + | none => .stuck + | some (.inl r) => .done r + | some (.inr y) => if cut y then .cut y else seg step cut k y + +/-- Two segments that end alike: in agreeing results, at related cut points, or both stuck. +Running out of fuel matches nothing. -/ +def SegRel (Ag : R → R' → Prop) (Rel : σ → τ → Prop) : Seg R σ → Seg R' τ → Prop + | .done r, .done r' => Ag r r' + | .cut y, .cut y' => Rel y y' + | .stuck, .stuck => True + | _, _ => False + +theorem SegRel.flip {Ag : R → R' → Prop} {Rel : σ → τ → Prop} : + ∀ {a : Seg R σ} {b : Seg R' τ}, SegRel Ag Rel a b → + SegRel (fun r' r => Ag r r') (fun y' y => Rel y y') b a + | .done _, .done _, h | .cut _, .cut _, h | .stuck, .stuck, h => h + | .done _, .cut _, h | .done _, .stuck, h | .done _, .fuel, h + | .cut _, .done _, h | .cut _, .stuck, h | .cut _, .fuel, h + | .stuck, .done _, h | .stuck, .cut _, h | .stuck, .fuel, h + | .fuel, _, h => h.elim + +/-! Runs and steps. -/ + +section Runs + +variable {step : Step σ R} + +theorem run_eq_steps : ∀ (n : Nat) (x : σ), + run step n x = match steps step n x with | some (.inl r) => some r | _ => none + | 0, _ => rfl + | n + 1, x => by + simp only [run, steps] + cases step x with + | none => rfl + | some v => + cases v with + | inl r => rfl + | inr y => exact run_eq_steps n y + +theorem run_of_steps {n : Nat} {x : σ} {r : R} (h : steps step n x = some (.inl r)) : + run step n x = some r := by + rw [run_eq_steps, h] + +theorem steps_of_run {n : Nat} {x : σ} {r : R} (h : run step n x = some r) : + steps step n x = some (.inl r) := by + rw [run_eq_steps] at h + split at h + · rename_i e; cases h; exact e + · cases h + +/-- Past an end or a stuck step, more steps change nothing. -/ +theorem steps_succ : ∀ {k : Nat} {x : σ}, (∀ y, steps step k x ≠ some (.inr y)) → + steps step (k + 1) x = steps step k x + | 0, x, h => absurd rfl (h x) + | k + 1, x, h => by + simp only [steps] at h ⊢ + cases e : step x with + | none => rfl + | some v => + cases v with + | inl r => rfl + | inr y => + rw [e] at h + exact steps_succ h + +theorem steps_le {k k' : Nat} {x : σ} (le : k ≤ k') (h : ∀ y, steps step k x ≠ some (.inr y)) : + steps step k' x = steps step k x := by + induction le with + | refl => rfl + | step _ ih => + rw [steps_succ (by rw [ih]; exact h), ih] + +theorem run_mono {n m : Nat} {x : σ} {r : R} (le : n ≤ m) (h : run step n x = some r) : + run step m x = some r := by + apply run_of_steps + rw [steps_le le (by rw [steps_of_run h]; intro y e; cases e)] + exact steps_of_run h + +/-- A run ends in at most one result, whatever its fuel. -/ +theorem run_unique {n m : Nat} {x : σ} {a b : R} (ha : run step n x = some a) + (hb : run step m x = some b) : a = b := by + have := run_mono (Nat.le_max_left n m) ha + rw [run_mono (Nat.le_max_right n m) hb] at this + exact (Option.some.inj this).symm + +theorem not_stuck_of_diverges {x : σ} (d : Diverges step x) : ¬Stuck step x := by + intro ⟨k, h⟩ + obtain ⟨y, e⟩ := d k + rw [h] at e + cases e + +theorem not_run_of_diverges {x : σ} (d : Diverges step x) (n : Nat) (r : R) : + run step n x ≠ some r := by + intro h + obtain ⟨y, e⟩ := d n + rw [steps_of_run h] at e + cases e + +/-- A run that neither ends nor gets stuck runs forever. -/ +theorem diverges_of {x : σ} (noEnd : ∀ n r, run step n x ≠ some r) (noStuck : ¬Stuck step x) : + Diverges step x := by + intro k + cases e : steps step k x with + | none => exact absurd ⟨k, e⟩ noStuck + | some v => + cases v with + | inl r => exact absurd (run_of_steps e) (noEnd k r) + | inr y => exact ⟨y, rfl⟩ + +theorem iterate_eq {ς : Type} (step : Step ς (Machine.Halt × Machine.State)) : + ∀ (n : Nat) (x : ς), Machine.iterate step n x = run step n x + | 0, _ => rfl + | n + 1, x => by + simp only [Machine.iterate, run] + cases step x with + | none => rfl + | some v => + cases v with + | inl r => rfl + | inr y => exact iterate_eq step n y + +end Runs + +/-! What a segment says about whole runs. -/ + +section Segments + +variable {step : Step σ R} {cut : σ → Bool} + +/-- A segment that reaches a cut point ran \`j ≥ 1\` steps to it. -/ +theorem seg_cut : ∀ {k : Nat} {x y : σ}, seg step cut k x = .cut y → + ∃ j, 1 ≤ j ∧ ∀ n, run step (n + j) x = run step n y ∧ steps step (n + j) x = steps step n y + | 0, _, _, h => by cases h + | k + 1, x, y, h => by + simp only [seg] at h + cases e : step x with + | none => rw [e] at h; cases h + | some v => + cases v with + | inl r => rw [e] at h; cases h + | inr z => + rw [e] at h + simp only at h + by_cases c : cut z = true + · simp only [c, ↓reduceIte] at h + cases h + refine ⟨1, Nat.le_refl 1, fun n => ⟨?_, ?_⟩⟩ <;> simp only [run, steps, e] + · simp only [c] at h + obtain ⟨j, pos, runs⟩ := seg_cut h + refine ⟨j + 1, by omega, fun n => ?_⟩ + rw [← Nat.add_assoc] + simp only [run, steps, e] + exact runs n + +/-- A segment that ends ran \`j ≥ 1\` steps to its result. -/ +theorem seg_done : ∀ {k : Nat} {x : σ} {r : R}, seg step cut k x = .done r → + ∃ j, 1 ≤ j ∧ ∀ n, run step (n + j) x = some r + | 0, _, _, h => by cases h + | k + 1, x, r, h => by + simp only [seg] at h + cases e : step x with + | none => rw [e] at h; cases h + | some v => + cases v with + | inl r' => + rw [e] at h + cases h + exact ⟨1, Nat.le_refl 1, fun n => by simp only [run, e]⟩ + | inr z => + rw [e] at h + simp only at h + by_cases c : cut z = true + · simp only [c, ↓reduceIte] at h; cases h + · simp only [c] at h + obtain ⟨j, pos, runs⟩ := seg_done h + refine ⟨j + 1, by omega, fun n => ?_⟩ + rw [← Nat.add_assoc] + simp only [run, e] + exact runs n + +/-- A segment that gets stuck never ends, and is stuck after \`j\` steps. -/ +theorem seg_stuck : ∀ {k : Nat} {x : σ}, seg step cut k x = .stuck → + (∀ n, run step n x = none) ∧ ∃ j, steps step j x = none + | 0, _, h => by cases h + | k + 1, x, h => by + simp only [seg] at h + cases e : step x with + | none => + refine ⟨fun n => ?_, 1, by simp only [steps, e]⟩ + cases n <;> simp only [run, e] + | some v => + cases v with + | inl r => rw [e] at h; cases h + | inr z => + rw [e] at h + simp only at h + by_cases c : cut z = true + · simp only [c, ↓reduceIte] at h; cases h + · simp only [c] at h + obtain ⟨runs, j, stuck⟩ := seg_stuck h + refine ⟨fun n => ?_, j + 1, by simp only [steps, e]; exact stuck⟩ + cases n with + | zero => rfl + | succ n => simp only [run, e]; exact runs n + +/-- Cut points that cover every cycle bound every segment: when every step to a configuration +that is no cut point climbs a rank bounded by \`N\` (a topological order of the control flow with +the edges into cut points removed, which is acyclic exactly when every cycle passes through a cut +point), a segment with more than \`N\` steps of fuel never runs out of it. -/ +theorem seg_ne_fuel (rank : σ → Nat) (N : Nat) (bound : ∀ x, rank x ≤ N) + (climbs : ∀ x y, step x = some (.inr y) → cut y = false → rank x < rank y) : + ∀ (k : Nat) (x : σ), N - rank x < k → seg step cut k x ≠ .fuel + | 0, _, h => absurd h (Nat.not_lt_zero _) + | k + 1, x, h => by + simp only [seg] + cases e : step x with + | none => simp + | some v => + cases v with + | inl r => simp + | inr y => + simp only + cases c : cut y with + | true => simp + | false => + simp only [Bool.false_eq_true, ↓reduceIte] + have := climbs x y e c + have := bound y + exact seg_ne_fuel rank N bound climbs k y (by omega) + +end Segments + +/-! The simulation. -/ + +/-- From every pair of related configurations, the two segments end alike. This is what symbolic +execution proves, segment by segment, at each pair of cut points; the relation holds of the two +programs' first configurations too, which need not be cut points. -/ +structure Sim (step : Step σ R) (cut : σ → Bool) (step' : Step τ R') (cut' : τ → Bool) + (Ag : R → R' → Prop) (Rel : σ → τ → Prop) : Prop where + segment : ∀ x x', Rel x x' → ∃ k k', SegRel Ag Rel (seg step cut k x) (seg step' cut' k' x') + +namespace Sim + +variable {step : Step σ R} {cut : σ → Bool} {step' : Step τ R'} {cut' : τ → Bool} + {Ag : R → R' → Prop} {Rel : σ → τ → Prop} + +/-- The simulation read backwards. -/ +theorem flip (S : Sim step cut step' cut' Ag Rel) : + Sim step' cut' step cut (fun r' r => Ag r r') (fun y' y => Rel y y') where + segment x' x rel := by + obtain ⟨k, k', h⟩ := S.segment x x' rel + exact ⟨k', k, h.flip⟩ + +/-- Every end of the first program, at any fuel, is matched by an agreeing end of the second. -/ +theorem ends (S : Sim step cut step' cut' Ag Rel) : + ∀ (n : Nat) (x : σ) (x' : τ) (r : R), Rel x x' → run step n x = some r → + ∃ m r', run step' m x' = some r' ∧ Ag r r' := by + intro n + induction n using Nat.strongRecOn with + | ind n ih => + intro x x' r rel ran + obtain ⟨k, k', h⟩ := S.segment x x' rel + cases hs : seg step cut k x with + | fuel => rw [hs] at h; exact h.elim + | stuck => + rw [(seg_stuck hs).1 n] at ran + cases ran + | done a => + cases hs' : seg step' cut' k' x' with + | done a' => + rw [hs, hs'] at h + obtain ⟨j, _, runs⟩ := seg_done hs + obtain ⟨j', _, runs'⟩ := seg_done hs' + have e : r = a := run_unique ran (runs 0) + subst e + exact ⟨0 + j', a', runs' 0, h⟩ + | cut _ | stuck | fuel => rw [hs, hs'] at h; exact h.elim + | cut y => + cases hs' : seg step' cut' k' x' with + | cut y' => + rw [hs, hs'] at h + obtain ⟨j, pos, runs⟩ := seg_cut hs + obtain ⟨j', _, runs'⟩ := seg_cut hs' + by_cases le : j ≤ n + · have e : n = (n - j) + j := by omega + rw [e, (runs (n - j)).1] at ran + obtain ⟨m, r', ran', ag⟩ := ih (n - j) (by omega) y y' r h ran + exact ⟨m + j', r', by rw [(runs' m).1]; exact ran', ag⟩ + · have := run_mono (Nat.le_of_lt (Nat.lt_of_not_le le)) ran + rw [show j = 0 + j from (Nat.zero_add j).symm, (runs 0).1] at this + cases this + | done _ | stuck | fuel => rw [hs, hs'] at h; exact h.elim + +/-- Every end of the second program is matched by an agreeing end of the first. -/ +theorem ends_back (S : Sim step cut step' cut' Ag Rel) (m : Nat) (x : σ) (x' : τ) (r' : R') + (rel : Rel x x') (ran : run step' m x' = some r') : + ∃ n r, run step n x = some r ∧ Ag r r' := + S.flip.ends m x' x r' rel ran + +/-- One program ends at some fuel exactly when the other does. -/ +theorem ends_iff (S : Sim step cut step' cut' Ag Rel) {x : σ} {x' : τ} (rel : Rel x x') : + (∃ n r, run step n x = some r) ↔ (∃ m r', run step' m x' = some r') := by + constructor + · intro ⟨n, r, ran⟩ + obtain ⟨m, r', ran', _⟩ := S.ends n x x' r rel ran + exact ⟨m, r', ran'⟩ + · intro ⟨m, r', ran'⟩ + obtain ⟨n, r, ran, _⟩ := S.ends_back m x x' r' rel ran' + exact ⟨n, r, ran⟩ + +/-- A stuck first program has a stuck second program. -/ +theorem stuck (S : Sim step cut step' cut' Ag Rel) : + ∀ (k : Nat) (x : σ) (x' : τ), Rel x x' → steps step k x = none → Stuck step' x' := by + intro k + induction k using Nat.strongRecOn with + | ind k ih => + intro x x' rel stuckAt + obtain ⟨k₁, k₁', h⟩ := S.segment x x' rel + cases hs : seg step cut k₁ x with + | fuel => rw [hs] at h; exact h.elim + | stuck => + cases hs' : seg step' cut' k₁' x' with + | stuck => exact (seg_stuck hs').2 + | done _ | cut _ | fuel => rw [hs, hs'] at h; exact h.elim + | done a => + obtain ⟨j, _, runs⟩ := seg_done hs + have ended := steps_of_run (runs 0) + have := steps_le (step := step) (x := x) (Nat.le_max_left (0 + j) k) + (by rw [ended]; intro y e; cases e) + rw [ended, steps_le (Nat.le_max_right (0 + j) k) (by rw [stuckAt]; intro y e; cases e), + stuckAt] at this + cases this + | cut y => + cases hs' : seg step' cut' k₁' x' with + | cut y' => + rw [hs, hs'] at h + obtain ⟨j, pos, runs⟩ := seg_cut hs + obtain ⟨j', _, runs'⟩ := seg_cut hs' + by_cases le : j ≤ k + · have e : k = (k - j) + j := by omega + rw [e, (runs (k - j)).2] at stuckAt + obtain ⟨i, si⟩ := ih (k - j) (by omega) y y' h stuckAt + exact ⟨i + j', by rw [(runs' i).2]; exact si⟩ + · -- Stuck before reaching the cut point, which it reaches: impossible. + have := steps_le (step := step) (x := x) (Nat.le_of_lt (Nat.lt_of_not_le le)) + (by rw [stuckAt]; intro y e; cases e) + rw [show j = 0 + j from (Nat.zero_add j).symm, (runs 0).2, stuckAt] at this + cases this + | done _ | stuck | fuel => rw [hs, hs'] at h; exact h.elim + +theorem stuck_iff (S : Sim step cut step' cut' Ag Rel) {x : σ} {x' : τ} (rel : Rel x x') : + Stuck step x ↔ Stuck step' x' := + ⟨fun ⟨k, h⟩ => S.stuck k x x' rel h, fun ⟨k, h⟩ => S.flip.stuck k x' x rel h⟩ + +/-- One program runs forever exactly when the other does: an infinite run is matched by an +infinite run, never by an end or a stuck step. -/ +theorem diverges_iff (S : Sim step cut step' cut' Ag Rel) {x : σ} {x' : τ} (rel : Rel x x') : + Diverges step x ↔ Diverges step' x' := by + constructor + · intro d + apply diverges_of + · intro m r' ran' + obtain ⟨n, r, ran, _⟩ := S.ends_back m x x' r' rel ran' + exact not_run_of_diverges d n r ran + · intro st + exact not_stuck_of_diverges d ((S.stuck_iff rel).2 st) + · intro d + apply diverges_of + · intro n r ran + obtain ⟨m, r', ran', _⟩ := S.ends n x x' r rel ran + exact not_run_of_diverges d m r' ran' + · intro st + exact not_stuck_of_diverges d ((S.stuck_iff rel).1 st) + +/-- A simulation from one obligation per pair of cut points: the relation is that one of the +pairs' relations holds, and each segment from a pair ends at a pair. -/ +theorem of_each {rels : List (σ → τ → Prop)} + (each : ∀ P ∈ rels, ∀ x x', P x x' → ∃ k k', + SegRel Ag (fun y y' => ∃ Q ∈ rels, Q y y') (seg step cut k x) (seg step' cut' k' x')) : + Sim step cut step' cut' Ag (fun x x' => ∃ P ∈ rels, P x x') where + segment x x' := fun ⟨P, mem, holds⟩ => each P mem x x' holds + +end Sim + +/-! Layers. -/ + +open Machine + +theorem Agree.symm {a b : Halt × State} (h : Agree a b) : Agree b a := by + obtain ⟨ha, sa⟩ := a + obtain ⟨hb, sb⟩ := b + cases ha <;> cases hb <;> simp_all [Agree] <;> (try exact h.symm) <;> (try omega) + all_goals (obtain ⟨k, st, tr, w⟩ := h; exact ⟨k.symm, st.symm, tr.symm, w.symm⟩) + +/-- Two programs of layers that run as step functions from each call's first configuration, +simulated through cut points on every call in scope. -/ +structure LayerSim (A B : Layer) (o : Oracle) (p : A.Prog) (q : B.Prog) (scope : Call → Prop) + where + σ : Type + τ : Type + step : Call → Step σ (Halt × State) + step' : Call → Step τ (Halt × State) + init : Call → σ + init' : Call → τ + runs : ∀ call n, A.run o p call n = Machine.iterate (step call) n (init call) + runs' : ∀ call n, B.run o q call n = Machine.iterate (step' call) n (init' call) + cut : σ → Bool + cut' : τ → Bool + Rel : Call → σ → τ → Prop + start : ∀ call, scope call → Rel call (init call) (init' call) + sim : ∀ call, scope call → Sim (step call) cut (step' call) cut' Agree (Rel call) + +namespace LayerSim + +variable {A B : Layer} {o : Oracle} {p : A.Prog} {q : B.Prog} {scope : Call → Prop} + +/-- Every end of \`p\` is matched by an agreeing end of \`q\`: a stage. -/ +theorem certified (S : LayerSim A B o p q scope) : Certified A B o p q scope := by + intro call inScope r ⟨n, ran⟩ + rw [S.runs, iterate_eq] at ran + obtain ⟨m, r', ran', ag⟩ := (S.sim call inScope).ends n _ _ r (S.start call inScope) ran + exact ⟨r', ⟨m, by rw [S.runs', iterate_eq]; exact ran'⟩, ag⟩ + +/-- Every end of \`q\` is matched by an agreeing end of \`p\`: the stage backwards, so \`q\` ends on a +call exactly when \`p\` does, and diverges exactly when \`p\` does. -/ +theorem certified_back (S : LayerSim A B o p q scope) : Certified B A o q p scope := by + intro call inScope r' ⟨m, ran'⟩ + rw [S.runs', iterate_eq] at ran' + obtain ⟨n, r, ran, ag⟩ := + (S.sim call inScope).ends_back m _ _ r' (S.start call inScope) ran' + exact ⟨r, ⟨n, by rw [S.runs, iterate_eq]; exact ran⟩, Agree.symm ag⟩ + +theorem ends_iff (S : LayerSim A B o p q scope) (call : Call) (inScope : scope call) : + (∃ r, A.Ends o p call r) ↔ (∃ r', B.Ends o q call r') := by + constructor + · intro ⟨r, e⟩ + obtain ⟨r', e', _⟩ := S.certified call inScope r e + exact ⟨r', e'⟩ + · intro ⟨r', e'⟩ + obtain ⟨r, e, _⟩ := S.certified_back call inScope r' e' + exact ⟨r, e⟩ + +theorem diverges_iff (S : LayerSim A B o p q scope) (call : Call) (inScope : scope call) : + Diverges (S.step call) (S.init call) ↔ Diverges (S.step' call) (S.init' call) := + (S.sim call inScope).diverges_iff (S.start call inScope) + +theorem stuck_iff (S : LayerSim A B o p q scope) (call : Call) (inScope : scope call) : + Stuck (S.step call) (S.init call) ↔ Stuck (S.step' call) (S.init' call) := + (S.sim call inScope).stuck_iff (S.start call inScope) + +end LayerSim + +end SolarTV.CutPoint diff --git a/tv/SolarTV/CutPointExamples.lean b/tv/SolarTV/CutPointExamples.lean new file mode 100644 index 00000000..9f021556 --- /dev/null +++ b/tv/SolarTV/CutPointExamples.lean @@ -0,0 +1,190 @@ +import SolarTV.CutPoint +import SolarTV.EVMIR.Program + +/-! The cut-point theorem on a loop whose trip count is the calldata's first word. + +\`countdown\` reads a word and subtracts one until it is zero; \`countdownAdd\` spells the +decrement as adding the all-ones word, as a peephole pass might. Their one cut point is the loop +header, block 1, and the relation there is that both configurations are the same, which is what +the exporter derives for a pass that leaves the header's stack layout alone. Each segment (the +entry, and one trip round the loop or out of it) is run symbolically, and \`LayerSim\` lifts them +to a stage in both directions for every call, however many times the loop runs, and to "one +diverges exactly when the other does". + +The negatives change the loop's body or its exit test; their segments from the header end at +configurations that differ, so the obligation is false, a mismatch at the cut point rather than a +proof that runs out of fuel. -/ + +namespace SolarTV.CutPoint.Examples + +open EvmRules Machine EVM.Program + +/-- Reads calldata word 0, then counts it down to zero. -/ +def countdown : Program := { blocks := [ + [.op (.stack (.push 0)), .effect .calldataload 1, .jump 1], + [.op (.stack (.dup 0)), .op (.stack .iszero), .jumpi 2, + .op (.stack (.push 1)), .op (.stack (.swap 0)), .op (.stack .sub), .jump 1], + [.op (.stack .pop), .stop]] } + +/-- The same loop, decrementing by adding the all-ones word. -/ +def countdownAdd : Program := { blocks := [ + [.op (.stack (.push 0)), .effect .calldataload 1, .jump 1], + [.op (.stack (.dup 0)), .op (.stack .iszero), .jumpi 2, + .op (.stack (.push (BitVec.allOnes 256))), .op (.stack .add), .jump 1], + [.op (.stack .pop), .stop]] } + +/-- The loop header. -/ +def header : Nat × EVM.Stack × State → Bool := fun x => x.1 == 1 + +/-- The first configuration of a call, and the loop header with its counter, each the same in +both programs. -/ +def rels (call : Call) : List (Nat × EVM.Stack × State → Nat × EVM.Stack × State → Prop) := + [fun x x' => x = (0, [], State.initial call) ∧ x' = x, + fun x x' => ∃ (w : BitVec 256) (s : State), x = (1, [w], s) ∧ x' = x] + + +/-- Adding the all-ones word subtracts one. -/ +theorem add_allOnes (w : BitVec 256) : + Evm.add 115792089237316195423570985008687907853269984665640564039457584007913129639935#256 w = + Evm.sub w 1#256 := by + unfold Evm.add Evm.sub + bv_omega + +theorem segments (o : Oracle) (call : Call) : + ∀ P ∈ rels call, ∀ x x', P x x' → ∃ k k', + SegRel Agree (fun y y' => ∃ Q ∈ rels call, Q y y') + (seg (block o call countdown) header k x) (seg (block o call countdownAdd) header k' x') := by + intro P mem x x' holds + simp only [rels, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl + · obtain ⟨rfl, rfl⟩ := holds + refine ⟨1, 1, ?_⟩ + simp [seg, block, countdown, countdownAdd, exec, stepOp, EVM.stepChecked, EVM.step, Except.map, header, + Effect.apply, SegRel, rels] + · obtain ⟨w, s, rfl, rfl⟩ := holds + refine ⟨2, 2, ?_⟩ + by_cases hw : w = 0 + · simp [seg, block, countdown, countdownAdd, exec, stepOp, EVM.stepChecked, EVM.step, Except.map, header, + SegRel, hw, Evm.iszero] + exact Agree.refl _ + · have hw' : (w = 0#256) = False := propext ⟨hw, False.elim⟩ + simp [seg, block, countdown, countdownAdd, exec, stepOp, EVM.stepChecked, EVM.step, Except.map, header, + SegRel, rels, hw', Evm.iszero, add_allOnes] + +/-- The two loops, simulated through their header on every call. -/ +def sim (o : Oracle) : + LayerSim EVM.Program.layer EVM.Program.layer o countdown countdownAdd (fun _ => True) where + σ := Nat × EVM.Stack × State + τ := Nat × EVM.Stack × State + step call := block o call countdown + step' call := block o call countdownAdd + init call := (0, [], State.initial call) + init' call := (0, [], State.initial call) + runs _ _ := rfl + runs' _ _ := rfl + cut := header + cut' := header + Rel call := fun x x' => ∃ P ∈ rels call, P x x' + start _ _ := ⟨_, List.mem_cons_self, rfl, rfl⟩ + sim call _ := Sim.of_each (segments o call) + +/-- Every end of \`countdown\` is an end of \`countdownAdd\`, however many times the loop runs. -/ +theorem stage (o : Oracle) : + Stage (EVM.Program.sem o) (EVM.Program.sem o) countdown countdownAdd (fun _ => True) := + stage_of_certified (sim o).certified + +/-- And backwards. -/ +theorem stage_back (o : Oracle) : + Stage (EVM.Program.sem o) (EVM.Program.sem o) countdownAdd countdown (fun _ => True) := + stage_of_certified (sim o).certified_back + +/-- One runs forever on a call exactly when the other does. -/ +theorem diverges_iff (o : Oracle) (call : Call) : + Diverges (block o call countdown) (0, [], State.initial call) ↔ + Diverges (block o call countdownAdd) (0, [], State.initial call) := + (sim o).diverges_iff call trivial + +/-- The stage is not about runs that never end: on calldata whose first word is two, \`countdown\` +goes round its loop twice and stops. -/ +def two : Call := ⟨⟨(List.replicate 31 (0 : UInt8) ++ [2]).toArray⟩, 0, []⟩ + +theorem two_word : calldataWord two 0#256 = 2#256 := by decide +kernel + +theorem ends_on_two (o : Oracle) : (EVM.Program.run o countdown two 6).isSome = true := by + simp [EVM.Program.run, iterate, block, countdown, exec, stepOp, EVM.stepChecked, EVM.step, + Except.map, Effect.apply, two_word, Evm.iszero, Evm.sub] + +/-! Negatives: each mutation makes a segment from the header end differently, so no proof of the +obligation exists. -/ + +/-- The body subtracts two. -/ +def countdownBody : Program := { blocks := [ + [.op (.stack (.push 0)), .effect .calldataload 1, .jump 1], + [.op (.stack (.dup 0)), .op (.stack .iszero), .jumpi 2, + .op (.stack (.push 2)), .op (.stack (.swap 0)), .op (.stack .sub), .jump 1], + [.op (.stack .pop), .stop]] } + +/-- The exit test is inverted: the loop leaves while the counter is nonzero. -/ +def countdownExit : Program := { blocks := [ + [.op (.stack (.push 0)), .effect .calldataload 1, .jump 1], + [.op (.stack (.dup 0)), .jumpi 2, + .op (.stack (.push 1)), .op (.stack (.swap 0)), .op (.stack .sub), .jump 1], + [.op (.stack .pop), .stop]] } + +/-- From a counter of one, \`countdown\` comes back to the header with zero and \`countdownBody\` +with the all-ones word: the configurations at the cut point differ. -/ +theorem body_mismatch (o : Oracle) (call : Call) (s : State) : + ¬∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ rels call, Q y y') + (seg (block o call countdown) header k (1, [1#256], s)) + (seg (block o call countdownBody) header k' (1, [1#256], s)) := by + rintro ⟨k, k', h⟩ + cases k with + | zero => simp [seg, SegRel] at h + | succ k => + cases k' with + | zero => simp [seg, SegRel] at h + | succ k' => + simp [seg, block, countdown, countdownBody, exec, stepOp, EVM.stepChecked, EVM.step, + Except.map, header, SegRel, rels, Evm.iszero, Evm.sub] at h + +/-- From a counter of one, \`countdown\` comes back to the header and \`countdownExit\` stops. -/ +theorem exit_mismatch (o : Oracle) (call : Call) (s : State) : + ¬∃ k k', SegRel Agree (fun y y' => ∃ Q ∈ rels call, Q y y') + (seg (block o call countdown) header k (1, [1#256], s)) + (seg (block o call countdownExit) header k' (1, [1#256], s)) := by + rintro ⟨k, k', h⟩ + cases k with + | zero => simp [seg, SegRel] at h + | succ k => + cases k' with + | zero => simp [seg, SegRel] at h + | succ k' => + cases k' with + | zero => + simp [seg, block, countdown, countdownExit, exec, stepOp, EVM.stepChecked, EVM.step, + Except.map, header, SegRel, Evm.iszero, Evm.sub] at h + | succ k' => + simp [seg, block, countdown, countdownExit, exec, stepOp, EVM.stepChecked, EVM.step, + Except.map, header, SegRel, Evm.iszero, Evm.sub] at h + +/-- info: 'SolarTV.CutPoint.Examples.stage' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage + +/-- info: 'SolarTV.CutPoint.Examples.diverges_iff' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms diverges_iff + +/-- info: 'SolarTV.CutPoint.Examples.body_mismatch' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms body_mismatch + +/-- info: 'SolarTV.CutPoint.Examples.exit_mismatch' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms exit_mismatch + +/-- info: 'SolarTV.CutPoint.Examples.ends_on_two' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms ends_on_two + +end SolarTV.CutPoint.Examples diff --git a/tv/SolarTV/CutPointHoare.lean b/tv/SolarTV/CutPointHoare.lean new file mode 100644 index 00000000..0e1b91bb --- /dev/null +++ b/tv/SolarTV/CutPointHoare.lean @@ -0,0 +1,145 @@ +import SolarTV.CutPoint + +/-! # Partial correctness through cut points + +`SolarTV.CutPoint.Sim` relates two machines segment by segment. This is its one-machine +counterpart: an invariant `Inv` on cut-point configurations and a postcondition `Post` on +results. When every segment from a configuration meeting `Inv` (and from the first +configuration) ends in a result meeting `Post`, at a cut point meeting `Inv`, or stuck, every +result the machine reaches, at any fuel, meets `Post`, whatever number of times its loops run. +Running out of a segment's fuel proves nothing (`SegOk` of `.fuel` is `False`), so a proof +that leaves a segment unfinished fails. -/ + +namespace SolarTV.CutPoint + +universe u v + +variable {σ : Type u} {R : Type v} + +/-- A segment that ends as the invariant and the postcondition ask: in a result meeting `Post`, +at a cut point meeting `Inv`, or stuck. -/ +def SegOk (Inv : σ → Prop) (Post : R → Prop) : Seg R σ → Prop + | .done r => Post r + | .cut y => Inv y + | .stuck => True + | .fuel => False + +/-- A weaker invariant at the cut points. -/ +theorem SegOk.mono {Inv Inv' : σ → Prop} {Post : R → Prop} (h : ∀ y, Inv y → Inv' y) : + ∀ {s : Seg R σ}, SegOk Inv Post s → SegOk Inv' Post s + | .done _, p | .stuck, p => p + | .cut y, p => h y p + | .fuel, p => p.elim + +/-- **Partial correctness through cut points.** If every segment from a configuration meeting +`Inv` ends as `SegOk` asks, every result of a run from such a configuration meets `Post`. -/ +theorem post_of_segments {step : Step σ R} {cut : σ → Bool} {Inv : σ → Prop} {Post : R → Prop} + (segment : ∀ x, Inv x → ∃ k, SegOk Inv Post (seg step cut k x)) : + ∀ (n : Nat) (x : σ) (r : R), Inv x → run step n x = some r → Post r := by + intro n + induction n using Nat.strongRecOn with + | ind n ih => + intro x r inv ran + obtain ⟨k, h⟩ := segment x inv + cases hs : seg step cut k x with + | fuel => rw [hs] at h; exact h.elim + | stuck => + rw [(seg_stuck hs).1 n] at ran + cases ran + | done a => + rw [hs] at h + obtain ⟨j, _, runs⟩ := seg_done hs + have e : r = a := run_unique ran (runs 0) + subst e + exact h + | cut y => + rw [hs] at h + obtain ⟨j, pos, runs⟩ := seg_cut hs + by_cases le : j ≤ n + · have e : n = (n - j) + j := by omega + rw [e, (runs (n - j)).1] at ran + exact ih (n - j) (by omega) y r h ran + · have := run_mono (Nat.le_of_lt (Nat.lt_of_not_le le)) ran + rw [show j = 0 + j from (Nat.zero_add j).symm, (runs 0).1] at this + cases this + +/-- The same from a first configuration that need not be a cut point: its segment ends as +`SegOk` asks too. -/ +theorem post_of_start {step : Step σ R} {cut : σ → Bool} {Inv : σ → Prop} {Post : R → Prop} + {x₀ : σ} (start : ∃ k, SegOk Inv Post (seg step cut k x₀)) + (segment : ∀ x, Inv x → ∃ k, SegOk Inv Post (seg step cut k x)) : + ∀ (n : Nat) (r : R), run step n x₀ = some r → Post r := + fun n r ran => + post_of_segments (step := step) (cut := cut) (Inv := fun x => x = x₀ ∨ Inv x) + (fun x h => by + rcases h with rfl | h + · obtain ⟨k, hk⟩ := start + exact ⟨k, SegOk.mono (fun _ h => Or.inr h) hk⟩ + · obtain ⟨k, hk⟩ := segment x h + exact ⟨k, SegOk.mono (fun _ h => Or.inr h) hk⟩) + n x₀ r (Or.inl rfl) ran + +/-- info: 'SolarTV.CutPoint.post_of_start' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms post_of_start + +/-! ## Total correctness + +With a rank that every segment from a cut point lowers on its way to the next one, and no +segment stuck, every run from a configuration meeting the invariant ends, in a result meeting the +postcondition. -/ + +/-- A segment that ends, as the invariant and the postcondition ask, in a result meeting `Post` +or at a cut point meeting `Inv` and `below` (the rank fell): not stuck, nor out of fuel. -/ +def SegEnds (Inv : σ → Prop) (Post : R → Prop) (below : σ → Prop) : Seg R σ → Prop + | .done r => Post r + | .cut y => Inv y ∧ below y + | .stuck => False + | .fuel => False + +/-- **Total correctness through cut points.** -/ +theorem ends_of_segments {step : Step σ R} {cut : σ → Bool} {Inv : σ → Prop} {Post : R → Prop} + (rank : σ → Nat) + (segment : ∀ x, Inv x → ∃ k, SegEnds Inv Post (fun y => rank y < rank x) (seg step cut k x)) : + ∀ x, Inv x → ∃ n r, run step n x = some r ∧ Post r := by + intro x + induction h : rank x using Nat.strongRecOn generalizing x with + | ind m ih => + intro inv + obtain ⟨k, hk⟩ := segment x inv + cases hs : seg step cut k x with + | fuel | stuck => rw [hs] at hk; exact hk.elim + | done a => + rw [hs] at hk + obtain ⟨j, _, runs⟩ := seg_done hs + exact ⟨0 + j, a, runs 0, hk⟩ + | cut y => + rw [hs] at hk + obtain ⟨iy, lt⟩ := hk + obtain ⟨j, _, runs⟩ := seg_cut hs + obtain ⟨n, r, ran, post⟩ := ih (rank y) (h ▸ lt) y rfl iy + exact ⟨n + j, r, by rw [(runs n).1]; exact ran, post⟩ + +/-- The same from a first configuration that need not be a cut point. -/ +theorem ends_of_start {step : Step σ R} {cut : σ → Bool} {Inv : σ → Prop} {Post : R → Prop} + (rank : σ → Nat) {x₀ : σ} (start : ∃ k, SegEnds Inv Post (fun _ => True) (seg step cut k x₀)) + (segment : ∀ x, Inv x → ∃ k, SegEnds Inv Post (fun y => rank y < rank x) (seg step cut k x)) : + ∃ n r, run step n x₀ = some r ∧ Post r := by + obtain ⟨k, hk⟩ := start + cases hs : seg step cut k x₀ with + | fuel | stuck => rw [hs] at hk; exact hk.elim + | done a => + rw [hs] at hk + obtain ⟨j, _, runs⟩ := seg_done hs + exact ⟨0 + j, a, runs 0, hk⟩ + | cut y => + rw [hs] at hk + obtain ⟨j, _, runs⟩ := seg_cut hs + obtain ⟨n, r, ran, post⟩ := ends_of_segments rank segment y hk.1 + exact ⟨n + j, r, by rw [(runs n).1]; exact ran, post⟩ + +/-- info: 'SolarTV.CutPoint.ends_of_start' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms ends_of_start + +end SolarTV.CutPoint diff --git a/tv/SolarTV/EVMIR/Gas.lean b/tv/SolarTV/EVMIR/Gas.lean new file mode 100644 index 00000000..a064c405 --- /dev/null +++ b/tv/SolarTV/EVMIR/Gas.lean @@ -0,0 +1,143 @@ +import SolarTV.EVMIR.Memory +import SolarTV.State.Fork + +/-! Gas-aware execution of scheduled EVM IR windows. +The modeled costs follow EVMYulLean 047f630, EVM/Gas.lean:18-60, 87-90, +272-297 and GasConstants.lean:7-12, 40. They are unchanged for our opcode +subset from Cancun through Osaka. Memory charges use natural arithmetic. +Each instruction pays before executing; GAS returns the budget after its own +charge. Exceptions consume the remaining gas, whereas REVERT preserves it. + +The window starts after any entry JUMPDEST. Static terminals include the label +PUSH and JUMP/JUMPI, but not execution of the outgoing successor. Exact equality +is compositional for this projection. Resource refinement permits extra gas and +success where the original runs out; it requires a gas-insensitive continuation. +Calls, storage, refunds and transaction intrinsic gas are outside this fragment. -/ + +namespace SolarTV.EVM.Gas +open EvmRules + +inductive Op where + | instruction (op : Memory.Op) + | gas + +inductive Observation where + | execution (result : Memory.Execution) + | outOfGas + deriving DecidableEq + +structure Result where + observation : Observation + remaining : Nat + deriving DecidableEq + +def halted (result : Memory.Execution) (remaining : Nat) : Result := + match result with + | .failed _ => ⟨.execution result, 0⟩ + | _ => ⟨.execution result, remaining⟩ + +def exhausted : Result := ⟨.outOfGas, 0⟩ + +def memoryCost (words : Nat) : Nat := 3 * words + words * words / 512 + +def expansionCost (before after : SolarTV.Memory.State) : Nat := + memoryCost after.words.toNat - memoryCost before.words.toNat + +def pureCost (op : EVM.Op) (fork : Fork := .cancun) : Nat := + match op with + | .mul | .div | .sdiv | .mod | .smod | .signextend | .clz => 5 + | .addmod | .mulmod => 8 + | .exp => 10 + | .exchange _ _ => if fork.atLeast .amsterdam then 3 else 9 + | .pop | .calldatasize | .returndatasize => 2 + | .push value => if value = 0 && fork.atLeast .shanghai then 2 else 3 + | .eq | .sub | .add | .and | .or | .xor | .iszero | .not | .dup _ | .swap _ + | .lt | .gt | .slt | .sgt | .byte | .shl | .shr | .sar => 3 + +def baseCost (op : Memory.Op) (fork : Fork := .cancun) : Nat := + match op with + | .stack op => pureCost op fork + | .size => 2 + | .load | .store | .storeByte | .copy => 3 + | .hash => 30 + +def touched (op : Memory.Op) (stack : Stack) (memory : SolarTV.Memory.State) : + SolarTV.Memory.State := + match op, stack with + | .load, offset :: _ | .store, offset :: _ => SolarTV.Memory.expand memory offset.toNat 32 + | .storeByte, offset :: _ => SolarTV.Memory.expand memory offset.toNat 1 + | .copy, destination :: source :: count :: _ => + SolarTV.Memory.expand (SolarTV.Memory.expand memory source.toNat count.toNat) + destination.toNat count.toNat + | .hash, offset :: count :: _ => SolarTV.Memory.expand memory offset.toNat count.toNat + | _, _ => memory + +def cost (op : Memory.Op) (stack : Stack) (memory : SolarTV.Memory.State) + (fork : Fork := .cancun) : Nat := + let dynamic := match op, stack with + | .stack .exp, _ :: exponent :: _ => + (if fork.atLeast .spuriousDragon then 50 else 10) * ((256 - exponent.clz.toNat + 7) / 8) + | .copy, _ :: _ :: count :: _ => 3 * ((count.toNat + 31) / 32) + | .hash, _ :: count :: _ => 6 * ((count.toNat + 31) / 32) + | _, _ => 0 + baseCost op fork + dynamic + expansionCost memory (touched op stack memory) + +def finish (terminal : Memory.Terminal) (stack : Stack) (memory : SolarTV.Memory.State) + (gas : Nat) : Result := + match terminal with + | .control (.jump _) | .control (.branch _ _) | .control (.branchStop _) => + -- The label PUSH costs 3 and can fail before the transfer executes. + if gas < 3 then exhausted + else if stack.length + 1 > 1024 then halted (.failed .overflow) (gas - 3) + else + let transfer := match terminal with | .control (.jump _) => 8 | _ => 10 + if gas - 3 < transfer then exhausted + else halted (Memory.finish terminal stack memory) (gas - 3 - transfer) + | .output _ => + let expanded := match stack with + | offset :: size :: _ => SolarTV.Memory.expand memory offset.toNat size.toNat + | _ => memory + let charge := expansionCost memory expanded + if gas < charge then exhausted + else halted (Memory.finish terminal stack memory) (gas - charge) + | .control .stop | .control .invalid | .control .returnEmpty | .control .revertEmpty => + halted (Memory.finish terminal stack memory) gas + +def execute (ctx : Context) (ops : List Op) (terminal : Memory.Terminal) (stack : Stack) + (memory : SolarTV.Memory.State) (gas : Nat) (fork : Fork := .cancun) : Result := + match ops with + | [] => finish terminal stack memory gas + | .gas :: ops => + if gas < 2 then exhausted + else if stack.length + 1 > 1024 then halted (.failed .overflow) (gas - 2) + else execute ctx ops terminal (BitVec.ofNat 256 (gas - 2) :: stack) memory (gas - 2) fork + | .instruction op :: ops => + let charge := cost op stack memory fork + if gas < charge then exhausted + else match Memory.step ctx op stack memory with + | .error reason => halted (.failed reason) (gas - charge) + | .ok (stack, memory) => execute ctx ops terminal stack memory (gas - charge) fork +termination_by structural ops + +/-- This resource policy is deliberately weaker than exact EVM equivalence. +Only original out-of-gas is unconstrained; reverts and other failures stay defined. +An outgoing continuation must not distinguish extra remaining gas. -/ +def refines (original candidate : Result) : Prop := + original.observation = .outOfGas ∨ + (original.observation = candidate.observation ∧ original.remaining ≤ candidate.remaining) + +instance (original candidate : Result) : Decidable (refines original candidate) := + inferInstanceAs (Decidable (_ ∨ (_ ∧ _))) + +def code (result : Result) : List Word := + BitVec.ofNat 256 result.remaining :: (match result.observation with + | .outOfGas => [6] + | .execution result => Memory.code result) + +def describe (result : Result) : String := + let outcome := match result.observation with + | .outOfGas => "out-of-gas" + | .execution result => Memory.describe result + s!"{outcome}, gas={result.remaining}" + +end SolarTV.EVM.Gas diff --git a/tv/SolarTV/EVMIR/GasSafety.lean b/tv/SolarTV/EVMIR/GasSafety.lean new file mode 100644 index 00000000..a921554f --- /dev/null +++ b/tv/SolarTV/EVMIR/GasSafety.lean @@ -0,0 +1,42 @@ +import SolarTV.EVMIR.Gas + +/-! Kernel checks for opcode prices, debit order, expansion and exhaustion. +The quadratic boundary at 23 words pins the complete formula even though the +current importer admits accesses only within its 256-byte memory projection. -/ + +namespace SolarTV.EVM.Gas +open EvmRules +set_option maxRecDepth 4096 + +example : memoryCost 22 = 66 := by decide +example : memoryCost 23 = 70 := by decide +example : pureCost (.push 0) = 2 ∧ pureCost (.push 1) = 3 := by decide + +example : execute ⟨0, 0⟩ [.gas] (.control (.jump 1)) [] (SolarTV.Memory.initial [] 0) 13 = + ⟨.execution (.edge 1 [11] (SolarTV.Memory.initial [] 0)), 0⟩ := by decide + +example : execute ⟨0, 0⟩ [.gas] (.control .stop) [] (SolarTV.Memory.initial [] 0) 1 = + exhausted := by decide + +example : execute ⟨0, 0⟩ [.gas] (.control .stop) [] (SolarTV.Memory.initial [] 0) 2 = + ⟨.execution (.success []), 0⟩ := by decide + +example : finish (.control .invalid) [] (SolarTV.Memory.initial [] 0) 100 = + ⟨.execution (.failed .invalid), 0⟩ := by decide + +example : finish (.output true) [0, 32] (SolarTV.Memory.initial [] 0) 2 = exhausted := by decide +example : (finish (.output true) [0, 32] (SolarTV.Memory.initial [] 0) 10).remaining = 7 := by decide + +example : expansionCost (SolarTV.Memory.initial [] 22) + (SolarTV.Memory.expand (SolarTV.Memory.initial [] 22) 704 32) = 4 := by decide + +example : refines exhausted ⟨.execution (.success []), 10⟩ := by decide +example : ¬ refines ⟨.execution (.reverted []), 0⟩ ⟨.execution (.success []), 10⟩ := by decide + +example : execute ⟨0, 0⟩ + [.instruction (.stack (.push 0)), .instruction .load, .instruction (.stack .pop), + .instruction (.stack (.push 0)), .instruction .load, .instruction (.stack .pop)] + (.control .stop) [] (SolarTV.Memory.initial [] 0) 17 = + ⟨.execution (.success []), 0⟩ := by decide + +end SolarTV.EVM.Gas diff --git a/tv/SolarTV/EVMIR/Memory.lean b/tv/SolarTV/EVMIR/Memory.lean new file mode 100644 index 00000000..f58930f0 --- /dev/null +++ b/tv/SolarTV/EVMIR/Memory.lean @@ -0,0 +1,87 @@ +import SolarTV.Memory +import SolarTV.EVMIR.Ops + +/-! Scheduled EVM memory instructions and memory-backed terminal output. +The stack operand order is offset then value for stores, and offset then size +for RETURN/REVERT. All accesses expand active memory, including MLOAD. Terminal +halts discard private memory; outgoing edges retain the projected bytes and size. +Pure operations keep the existing stack-limit and first-exception semantics. -/ + +namespace SolarTV.EVM.Memory +open EvmRules + +inductive Op where + | stack (op : EVM.Op) + | load | store | storeByte | size | copy | hash + +inductive Terminal where + | control (terminal : EVM.Terminal) + | output (reverted : Bool) + +inductive Execution where + | edge (destination : Word) (stack : Stack) (memory : SolarTV.Memory.State) + | success (data : List SolarTV.Memory.Byte) + | reverted (data : List SolarTV.Memory.Byte) + | failed (reason : Failure) + deriving DecidableEq + +def step (ctx : Context) (op : Op) (stack : Stack) (memory : SolarTV.Memory.State) : + Except Failure (Stack × SolarTV.Memory.State) := + if stack.length > 1024 then .error .overflow + else match op, stack with + | .stack op, stack => (stepChecked ctx op stack).map (fun next => (next, memory)) + | .load, offset :: rest => .ok + (SolarTV.Memory.load memory offset.toNat :: rest, SolarTV.Memory.expand memory offset.toNat 32) + | .store, offset :: value :: rest => .ok (rest, SolarTV.Memory.store memory offset.toNat value) + | .storeByte, offset :: value :: rest => .ok (rest, SolarTV.Memory.storeByte memory offset.toNat value) + | .copy, destination :: source :: count :: rest => .ok + (rest, SolarTV.Memory.copy memory destination.toNat source.toNat count.toNat) + | .hash, offset :: count :: rest => .ok + (SolarTV.Memory.hash memory offset.toNat count.toNat :: rest, + SolarTV.Memory.expand memory offset.toNat count.toNat) + | .size, stack => + if stack.length + 1 > 1024 then .error .overflow + else .ok (SolarTV.Memory.msize memory :: stack, memory) + | _, _ => .error .underflow + +def finish (terminal : Terminal) (stack : Stack) (memory : SolarTV.Memory.State) : Execution := + if stack.length > 1024 then .failed .overflow + else match terminal with + | .control terminal => match EVM.finish terminal stack with + | .edge destination stack => .edge destination stack memory + | .success => .success [] + | .reverted => .reverted [] + | .failed reason => .failed reason + | .output reverted => match stack with + | offset :: size :: _ => + let memory := SolarTV.Memory.expand memory offset.toNat size.toNat + let data := SolarTV.Memory.read memory offset.toNat size.toNat + if reverted then .reverted data else .success data + | _ => .failed .underflow + +def execute (ctx : Context) : List Op → Terminal → Stack → SolarTV.Memory.State → Execution + | [], terminal, stack, memory => finish terminal stack memory + | op :: ops, terminal, stack, memory => match step ctx op stack memory with + | .error reason => .failed reason + | .ok (stack, memory) => execute ctx ops terminal stack memory + +def code : Execution → List Word + | .edge destination stack memory => + 0 :: destination :: BitVec.ofNat 256 stack.length :: stack ++ SolarTV.Memory.snapshot memory + | .success data => 1 :: data.map (fun b => b.setWidth 256) + | .reverted data => 2 :: data.map (fun b => b.setWidth 256) + | .failed .underflow => [3] + | .failed .overflow => [4] + | .failed .invalid => [5] + +def describe : Execution → String + | .edge destination stack memory => + let edge := if destination = 0 then "fallthrough" else s!"bb{destination.toNat}" + s!"{edge}, stack={stack.map BitVec.toNat}, {SolarTV.Memory.describe memory}" + | .success data => if data.isEmpty then "success(empty)" else s!"success(data={data.map BitVec.toNat})" + | .reverted data => if data.isEmpty then "revert(empty)" else s!"revert(data={data.map BitVec.toNat})" + | .failed .underflow => "exception(stack-underflow)" + | .failed .overflow => "exception(stack-overflow)" + | .failed .invalid => "exception(invalid-instruction)" + +end SolarTV.EVM.Memory diff --git a/tv/SolarTV/EVMIR/Ops.lean b/tv/SolarTV/EVMIR/Ops.lean new file mode 100644 index 00000000..c70cf136 --- /dev/null +++ b/tv/SolarTV/EVMIR/Ops.lean @@ -0,0 +1,159 @@ +import EvmRules.Word +import SolarTV.Word + +/-! Scheduled EVM IR word operations, bounded stacks and terminal outcomes. +Stack top is the head. The pure `step` gives operand semantics; `execute` adds +stack checks and preserves the first exception. Static transfers expose the +outgoing edge and live stack before the successor executes. Block references +stand for valid resolved destinations, independent of physical byte offsets. -/ + +namespace SolarTV.EVM + +open EvmRules + +inductive Op where + | eq | sub | add | mul | and | or | xor | iszero | not + | div | sdiv | mod | smod | exp | addmod | mulmod | signextend + | lt | gt | slt | sgt | byte | shl | shr | sar | clz + | calldatasize | returndatasize | push (value : Word) + | pop | dup (index : Fin 256) | swap (index : Fin 256) + | exchange (first second : Fin 32) + +structure Context where + calldataSize : Word + returndataSize : Word + +abbrev Stack := List Word + +def step (ctx : Context) : Op → Stack → Option Stack + | .add, a :: b :: rest => some (Evm.add a b :: rest) + | .mul, a :: b :: rest => some (Evm.mul a b :: rest) + | .and, a :: b :: rest => some (Evm.and a b :: rest) + | .or, a :: b :: rest => some (Evm.or a b :: rest) + | .xor, a :: b :: rest => some (Evm.xor a b :: rest) + | .not, a :: rest => some (Evm.not a :: rest) + | .div, a :: b :: rest => some (Evm.div a b :: rest) + | .sdiv, a :: b :: rest => some (Evm.sdiv a b :: rest) + | .mod, a :: b :: rest => some (Evm.mod a b :: rest) + | .smod, a :: b :: rest => some (Evm.smod a b :: rest) + | .exp, a :: b :: rest => some (Word.power a b.toNat :: rest) + | .addmod, a :: b :: n :: rest => some (Evm.addmod a b n :: rest) + | .mulmod, a :: b :: n :: rest => some (Evm.mulmod a b n :: rest) + | .signextend, a :: b :: rest => some (Evm.signextend a b :: rest) + | .byte, a :: b :: rest => some (Evm.byte a b :: rest) + | .shl, a :: b :: rest => some (Evm.shl a b :: rest) + | .shr, a :: b :: rest => some (Evm.shr a b :: rest) + | .sar, a :: b :: rest => some (Evm.sar a b :: rest) + | .lt, a :: b :: rest => some (Evm.lt a b :: rest) + | .gt, a :: b :: rest => some (Evm.gt a b :: rest) + | .slt, a :: b :: rest => some (Evm.slt a b :: rest) + | .sgt, a :: b :: rest => some (Evm.sgt a b :: rest) + | .clz, a :: rest => some (Evm.clz a :: rest) + | .exchange first second, stack => do + let a ← stack[first.val]? + let b ← stack[second.val]? + pure ((stack.set first.val b).set second.val a) + | .pop, _ :: rest => some rest + | .dup index, stack => (stack[index.val]?).map (fun value => value :: stack) + | .swap index, a :: rest => (rest[index.val]?).map (fun value => value :: rest.set index.val a) + | .eq, a :: b :: rest => some (Evm.eq a b :: rest) + | .sub, a :: b :: rest => some (Evm.sub a b :: rest) + | .iszero, a :: rest => some (Evm.iszero a :: rest) + | .calldatasize, rest => some (ctx.calldataSize :: rest) + | .returndatasize, rest => some (ctx.returndataSize :: rest) + | .push value, rest => some (value :: rest) + | _, _ => none + +/-! The bounded machine follows EVMYulLean 047f630, Data/Stack.lean and +EVM/Semantics.lean:450-471. The stack head is the next operand, underflow is +checked before executing an opcode, and the resulting height cannot exceed 1024. +Gas and memory expansion remain outside this fragment. Return/revert terminals +are admitted only when the importer proves the output length is zero. -/ + +inductive Failure where + | underflow | overflow | invalid + deriving DecidableEq + +inductive Execution where + | edge (destination : Word) (stack : Stack) + | success | reverted + | failed (reason : Failure) + deriving DecidableEq + +inductive Terminal where + | jump (destination : Word) + | branch (destination fallthrough : Word) + | branchStop (destination : Word) + | stop | returnEmpty | revertEmpty | invalid + +/-- Internal DUP/SWAP indices are zero-based; the importer accepts DUP1..16/SWAP1..16. -/ +def stepChecked (ctx : Context) (op : Op) (stack : Stack) : Except Failure Stack := + if stack.length > 1024 then .error .overflow + else match step ctx op stack with + | none => .error .underflow + | some next => if next.length > 1024 then .error .overflow else .ok next + +/-- Static transfers include the label PUSH and its peak height. Labels are valid, +resolved references supplied by the parser. A conditional transfer consumes its +condition only after the label push succeeds. -/ +def finish (terminal : Terminal) (stack : Stack) : Execution := + if stack.length > 1024 then .failed .overflow + else match terminal with + | .stop => .success + | .invalid => .failed .invalid + | .returnEmpty => match stack with + | _ :: _ :: _ => .success + | _ => .failed .underflow + | .revertEmpty => match stack with + | _ :: _ :: _ => .reverted + | _ => .failed .underflow + | .jump destination => + if stack.length + 1 > 1024 then .failed .overflow else .edge destination stack + | .branch destination fallthrough => + if stack.length + 1 > 1024 then .failed .overflow + else match stack with + | condition :: rest => .edge (if condition = 0 then fallthrough else destination) rest + | _ => .failed .underflow + | .branchStop destination => + if stack.length + 1 > 1024 then .failed .overflow + else match stack with + | condition :: rest => if condition = 0 then .success else .edge destination rest + | _ => .failed .underflow + +/-- Execute one block window, preserving the first exception. Stack values are +observable at an outgoing edge; terminal halts discard the remaining stack. -/ +def execute (ctx : Context) : List Op → Terminal → Stack → Execution + | [], terminal, stack => finish terminal stack + | op :: ops, terminal, stack => match stepChecked ctx op stack with + | .error reason => .failed reason + | .ok next => execute ctx ops terminal next + +/-- Used only for solver witness discovery. Exact execution equality is replayed +in the kernel before a counterexample is reported. -/ +def code : Execution → List Word + | .edge destination stack => 0 :: destination :: stack + | .success => [1] + | .reverted => [3] + | .failed .underflow => [4] + | .failed .overflow => [5] + | .failed .invalid => [6] + +@[simp] theorem code_ite (condition : Prop) [Decidable condition] (yes no : Execution) : + code (if condition then yes else no) = if condition then code yes else code no := by + split <;> rfl + +@[simp] theorem code_cond (condition : Bool) (yes no : Execution) : + code (bif condition then yes else no) = bif condition then code yes else code no := by + cases condition <;> rfl + +def describe : Execution → String + | .edge destination stack => + let edge := if destination = 0 then "fallthrough" else s!"bb{destination.toNat}" + s!"{edge}, stack={stack.map BitVec.toNat}" + | .success => "success(empty)" + | .reverted => "revert(empty)" + | .failed .underflow => "exception(stack-underflow)" + | .failed .overflow => "exception(stack-overflow)" + | .failed .invalid => "exception(invalid-instruction)" + +end SolarTV.EVM diff --git a/tv/SolarTV/EVMIR/Precompiles/BLS12381.lean b/tv/SolarTV/EVMIR/Precompiles/BLS12381.lean new file mode 100644 index 00000000..32e25e3a --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/BLS12381.lean @@ -0,0 +1,89 @@ +import SolarTV.EVMIR.Precompiles.Pairing + +/-! Canonical encodings and arithmetic for EIP-2537. ADD checks curve membership +but intentionally does not require the prime-order subgroup; MSM and pairing do. +Fp elements occupy 64 bytes, scalars 32, and Fp2 coefficients are (real,imaginary). +Empty MSM/pairing inputs are invalid. Scalar multiplication accepts all 256 bits. +https://eips.ethereum.org/EIPS/eip-2537 -/ + +namespace SolarTV.Precompiles.BLS12381 +open EVM.State + +def p : Nat := 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab +def order : Nat := 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001 +def f := fp p +def f2 := fp2 p +def generator1 : Point Nat := affine f + 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 + 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 +def generator2 : Point F2 := affine f2 + (352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160, + 3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758) + (1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905, + 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582) +def decode1 (input : List Byte) (offset : Nat) (subgroup : Bool) : Option (Point Nat) := + let x := readBE input offset 64; let y := readBE input (offset+64) 64 + if x ≥ p || y ≥ p then none + else if x = 0 && y = 0 then some (infinity f) + else let point := affine f x y + if onCurve f 0 4 point && (!subgroup || isInfinity f (multiply f 0 point order)) then some point else none +def decode2 (input : List Byte) (offset : Nat) (subgroup : Bool) : Option (Point F2) := + let xr := readBE input offset 64; let xi := readBE input (offset+64) 64 + let yr := readBE input (offset+128) 64; let yi := readBE input (offset+192) 64 + if xi ≥ p || xr ≥ p || yi ≥ p || yr ≥ p then none + else if xi = 0 && xr = 0 && yi = 0 && yr = 0 then some (infinity f2) + else let point := affine f2 (xr,xi) (yr,yi) + if onCurve f2 f2.zero (4,4) point && + (!subgroup || isInfinity f2 (multiply f2 f2.zero point order)) then some point else none +def encode1 (point : Point Nat) : List Byte := + match normalize f point with + | none => List.replicate 128 0 + | some (x,y) => be 64 x ++ be 64 y +def encode2 (point : Point F2) : List Byte := + match normalize f2 point with + | none => List.replicate 256 0 + | some (x,y) => be 64 x.1 ++ be 64 x.2 ++ be 64 y.1 ++ be 64 y.2 +def addition1 (input : List Byte) : Option (List Byte) := do + if input.length != 256 then none else + let a ← decode1 input 0 false; let b ← decode1 input 128 false + return encode1 (add f 0 a b) +def addition2 (input : List Byte) : Option (List Byte) := do + if input.length != 512 then none else + let a ← decode2 input 0 false; let b ← decode2 input 256 false + return encode2 (add f2 f2.zero a b) +def msm1 (input : List Byte) : Option (List Byte) := do + if input.isEmpty || input.length%160 != 0 then none else + let result ← (List.range (input.length/160)).foldlM (fun acc i => do + let point ← decode1 input (160*i) true + return add f 0 acc (multiply f 0 point (readBE input (160*i+128) 32))) (infinity f) + return encode1 result +def msm2 (input : List Byte) : Option (List Byte) := do + if input.isEmpty || input.length%288 != 0 then none else + let result ← (List.range (input.length/288)).foldlM (fun acc i => do + let point ← decode2 input (288*i) true + return add f2 f2.zero acc (multiply f2 f2.zero point (readBE input (288*i+256) 32))) (infinity f2) + return encode2 result +def pairing (input : List Byte) : Option (List Byte) := do + if input.isEmpty || input.length%384 != 0 then none else + let pairs ← (List.range (input.length/384)).mapM fun i => do + let a ← decode1 input (384*i) true + let b ← decode2 input (384*i+128) true + return (a,b) + return be 32 (if Pairing.check p order true pairs then 1 else 0) + +def sqrt2 (n : F2) : Option F2 := do + if n.2 = 0 then + match sqrt p n.1 with + | some x => return (x,0) + | none => let y ← sqrt p (f.neg n.1); return (0,y) + else + let norm ← sqrt p (f.add (f.square n.1) (f.square n.2)) + let half := (p+1)/2 + let x ← match sqrt p (f.mul (f.add n.1 norm) half) with + | some x => some x + | none => sqrt p (f.mul (f.sub n.1 norm) half) + if x = 0 then none else + let candidate := (x, f.div n.2 (f.mul 2 x)) + if f2.eq (f2.square candidate) n then some candidate else none + +end SolarTV.Precompiles.BLS12381 diff --git a/tv/SolarTV/EVMIR/Precompiles/BN254.lean b/tv/SolarTV/EVMIR/Precompiles/BN254.lean new file mode 100644 index 00000000..c2fdd300 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/BN254.lean @@ -0,0 +1,51 @@ +import SolarTV.EVMIR.Precompiles.Pairing + +/-! EIP-196/197 BN254 interfaces. ADD/MUL right-pad short inputs and ignore excess +bytes. Pairing requires an exact multiple of 192 bytes and validates G2 subgroup +membership. Wire encoding puts the imaginary Fp2 coefficient first, unlike the +internal (real,imaginary) representation. Infinity is encoded as all-zero bytes. +https://eips.ethereum.org/EIPS/eip-196 +https://eips.ethereum.org/EIPS/eip-197 -/ + +namespace SolarTV.Precompiles.BN254 +open EVM.State + +def p : Nat := 21888242871839275222246405745257275088696311157297823662689037894645226208583 +def order : Nat := 21888242871839275222246405745257275088548364400416034343698204186575808495617 +def f := fp p +def f2 := fp2 p +def decode1 (input : List Byte) (offset : Nat) : Option (Point Nat) := + let x := readBE input offset 32; let y := readBE input (offset+32) 32 + if x ≥ p || y ≥ p then none + else if x = 0 && y = 0 then some (infinity f) + else let point := affine f x y + if onCurve f 0 3 point then some point else none +def decode2 (input : List Byte) (offset : Nat) : Option (Point F2) := + let xi := readBE input offset 32; let xr := readBE input (offset+32) 32 + let yi := readBE input (offset+64) 32; let yr := readBE input (offset+96) 32 + if xi ≥ p || xr ≥ p || yi ≥ p || yr ≥ p then none + else if xi = 0 && xr = 0 && yi = 0 && yr = 0 then some (infinity f2) + else + let point := affine f2 (xr,xi) (yr,yi) + if onCurve f2 f2.zero (f2.div (3,0) (9,1)) point && + isInfinity f2 (multiply f2 f2.zero point order) then some point else none +def encode (point : Point Nat) : List Byte := + match normalize f point with + | none => List.replicate 64 0 + | some (x,y) => be 32 x ++ be 32 y +def addition (input : List Byte) : Option (List Byte) := do + let a ← decode1 input 0 + let b ← decode1 input 64 + return encode (add f 0 a b) +def multiplication (input : List Byte) : Option (List Byte) := do + let a ← decode1 input 0 + return encode (multiply f 0 a (readBE input 64 32)) +def pairing (input : List Byte) : Option (List Byte) := do + if input.length%192 != 0 then none else + let pairs ← (List.range (input.length/192)).mapM fun i => do + let a ← decode1 input (192*i) + let b ← decode2 input (192*i+64) + return (a,b) + return be 32 (if Pairing.check p order false pairs then 1 else 0) + +end SolarTV.Precompiles.BN254 diff --git a/tv/SolarTV/EVMIR/Precompiles/Blake2F.lean b/tv/SolarTV/EVMIR/Precompiles/Blake2F.lean new file mode 100644 index 00000000..6b3f1f7e --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Blake2F.lean @@ -0,0 +1,51 @@ +import SolarTV.EVMIR.Precompiles.Bytes + +/-! The BLAKE2b compression function F from RFC 7693, section 3.2. This is the +compression precompile, not a padded BLAKE2 hash. Rounds are decoded big-endian; +state, message, counters and output are little-endian 64-bit words. +https://www.rfc-editor.org/rfc/rfc7693#section-3.2 +https://eips.ethereum.org/EIPS/eip-152 -/ + +namespace SolarTV.Precompiles.Blake2F +open EVM.State +abbrev W := BitVec 64 +def iv : List W := [0x6a09e667f3bcc908,0xbb67ae8584caa73b,0x3c6ef372fe94f82b,0xa54ff53a5f1d36f1, + 0x510e527fade682d1,0x9b05688c2b3e6c1f,0x1f83d9abfb41bd6b,0x5be0cd19137e2179] +def sigma : List (List Nat) := [ + [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15], + [14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3], + [11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4], + [7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8], + [9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13], + [2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9], + [12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11], + [13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10], + [6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5], + [10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]] +def mix (v : List W) (a b c d : Nat) (x y : W) : List W := + let va := v[a]?.getD 0 + v[b]?.getD 0 + x + let vd := (v[d]?.getD 0 ^^^ va).rotateRight 32 + let vc := v[c]?.getD 0 + vd + let vb := (v[b]?.getD 0 ^^^ vc).rotateRight 24 + let va := va + vb + y + let vd := (vd ^^^ va).rotateRight 16 + let vc := vc + vd + let vb := (vb ^^^ vc).rotateRight 63 + (((v.set a va).set b vb).set c vc).set d vd +def compress (input : List Byte) : List Byte := Id.run do + let rounds := readBE input 0 4 + let h := (List.range 8).map (fun i => BitVec.ofNat 64 (readLE input (4+8*i) 8)) + let m := (List.range 16).map (fun i => BitVec.ofNat 64 (readLE input (68+8*i) 8)) + let mut v := h ++ iv + v := v.set 12 (v[12]?.getD 0 ^^^ BitVec.ofNat 64 (readLE input 196 8)) + v := v.set 13 (v[13]?.getD 0 ^^^ BitVec.ofNat 64 (readLE input 204 8)) + if input[212]?.getD 0 == 1 then v := v.set 14 (~~~(v[14]?.getD 0)) + for round in List.range rounds do + let s := sigma[round % 10]?.getD [] + let indices := [(0,4,8,12),(1,5,9,13),(2,6,10,14),(3,7,11,15), + (0,5,10,15),(1,6,11,12),(2,7,8,13),(3,4,9,14)] + for (j,(a,b,c,d)) in indices.zipIdx.map (fun (v,i) => (i,v)) do + v := mix v a b c d (m[s[2*j]?.getD 0]?.getD 0) (m[s[2*j+1]?.getD 0]?.getD 0) + return (List.range 8).flatMap (fun i => le 8 (h[i]?.getD 0 ^^^ v[i]?.getD 0 ^^^ v[i+8]?.getD 0).toNat) + +end SolarTV.Precompiles.Blake2F diff --git a/tv/SolarTV/EVMIR/Precompiles/Bytes.lean b/tv/SolarTV/EVMIR/Precompiles/Bytes.lean new file mode 100644 index 00000000..ec64fae1 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Bytes.lean @@ -0,0 +1,31 @@ +import SolarTV.EVMIR.State.Types + +/-! Byte encodings and bounded binary exponentiation shared by the precompiles. +Reads pad on the right, as the EVM precompile interfaces require; outputs have +an exact caller-specified width and preserve leading zero bytes. -/ + +namespace SolarTV.Precompiles +open EVM.State + +def readBE (bytes : List Byte) (offset count : Nat) : Nat := + (readBytes bytes offset count).foldl (fun n b => n * 256 + b.toNat) 0 + +def readLE (bytes : List Byte) (offset count : Nat) : Nat := + (readBytes bytes offset count).reverse.foldl (fun n b => n * 256 + b.toNat) 0 + +def be (width n : Nat) : List Byte := + (List.range width).map (fun i => BitVec.ofNat 8 (n >>> (8 * (width - 1 - i)))) + +def le (width n : Nat) : List Byte := (be width n).reverse + +def powLoop (modulus : Nat) : Nat → Nat → Nat → Nat → Nat + | 0, _, _, acc => acc + | fuel + 1, base, exponent, acc => + if exponent = 0 then acc else + powLoop modulus fuel (base * base % modulus) (exponent / 2) + (if exponent % 2 = 1 then acc * base % modulus else acc) + +def powMod (base exponent modulus : Nat) : Nat := + if modulus = 0 then 0 else powLoop modulus (exponent.log2 + 1) (base % modulus) exponent (1 % modulus) + +end SolarTV.Precompiles diff --git a/tv/SolarTV/EVMIR/Precompiles/Curve.lean b/tv/SolarTV/EVMIR/Precompiles/Curve.lean new file mode 100644 index 00000000..e0d6e304 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Curve.lean @@ -0,0 +1,66 @@ +import SolarTV.EVMIR.Precompiles.Field + +/-! Short-Weierstrass arithmetic in homogeneous coordinates (x/z,y/z). Scalar +multiplication uses doubling and addition without intermediate inversions. The +point at infinity has z=0. Interface modules separately enforce canonical field +encodings, curve membership and the required subgroup checks. -/ + +namespace SolarTV.Precompiles + +structure Point (K : Type) where + x : K + y : K + z : K + +def infinity (f : Arithmetic K) : Point K := ⟨f.one,f.one,f.zero⟩ +def affine (f : Arithmetic K) (x y : K) : Point K := ⟨x,y,f.one⟩ +def isInfinity (f : Arithmetic K) (p : Point K) : Bool := f.eq p.z f.zero +def negate (f : Arithmetic K) (p : Point K) : Point K := {p with y := f.neg p.y} +def normalize (f : Arithmetic K) (p : Point K) : Option (K × K) := + if isInfinity f p then none else + let inverse := f.inv p.z + some (f.mul p.x inverse, f.mul p.y inverse) +def onCurve (f : Arithmetic K) (a b : K) (p : Point K) : Bool := + isInfinity f p || f.eq (f.mul (f.square p.y) p.z) + (f.add (f.add (f.mul (f.square p.x) p.x) (f.mul a (f.mul p.x (f.square p.z)))) + (f.mul b (f.mul (f.square p.z) p.z))) + +def double (f : Arithmetic K) (a : K) (p : Point K) : Point K := + if isInfinity f p || f.eq p.y f.zero then infinity f else + let w := f.add (f.mul (f.nat 3) (f.square p.x)) (f.mul a (f.square p.z)) + let s := f.mul p.y p.z + let b := f.mul (f.mul p.x p.y) s + let h := f.sub (f.square w) (f.mul (f.nat 8) b) + ⟨f.mul (f.nat 2) (f.mul h s), + f.sub (f.mul w (f.sub (f.mul (f.nat 4) b) h)) + (f.mul (f.nat 8) (f.mul (f.square p.y) (f.square s))), + f.mul (f.nat 8) (f.mul s (f.square s))⟩ + +def add (f : Arithmetic K) (a : K) (p q : Point K) : Point K := + if isInfinity f p then q else if isInfinity f q then p else + let u1 := f.mul q.y p.z; let u2 := f.mul p.y q.z + let v1 := f.mul q.x p.z; let v2 := f.mul p.x q.z + if f.eq v1 v2 then + if f.eq u1 u2 then double f a p else infinity f + else + let u := f.sub u1 u2; let v := f.sub v1 v2 + let v2v2 := f.mul (f.square v) v2 + let v3 := f.mul (f.square v) v + let z := f.mul p.z q.z + let h := f.sub (f.sub (f.mul (f.square u) z) v3) (f.mul (f.nat 2) v2v2) + ⟨f.mul v h, f.sub (f.mul u (f.sub v2v2 h)) (f.mul v3 u2), f.mul v3 z⟩ + +def multiplyLoop (f : Arithmetic K) (a : K) : Nat → Nat → Point K → Point K → Point K + | 0, _, _, result => result + | fuel + 1, scalar, point, result => + if scalar = 0 then result else + multiplyLoop f a fuel (scalar/2) (double f a point) + (if scalar%2 = 1 then add f a result point else result) +def multiply (f : Arithmetic K) (a : K) (point : Point K) (scalar : Nat) : Point K := + multiplyLoop f a (scalar.log2+1) scalar point (infinity f) + +def sqrt (p n : Nat) : Option Nat := + let root := powMod n ((p+1)/4) p + if root*root%p = n%p then some root else none + +end SolarTV.Precompiles diff --git a/tv/SolarTV/EVMIR/Precompiles/Execute.lean b/tv/SolarTV/EVMIR/Precompiles/Execute.lean new file mode 100644 index 00000000..b8dfe974 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Execute.lean @@ -0,0 +1,81 @@ +import SolarTV.EVMIR.Precompiles.SHA256 +import SolarTV.EVMIR.Precompiles.RIPEMD160 +import SolarTV.EVMIR.Precompiles.Blake2F +import SolarTV.EVMIR.Precompiles.Signatures +import SolarTV.EVMIR.Precompiles.BN254 +import SolarTV.EVMIR.Precompiles.Maps +import SolarTV.EVMIR.Precompiles.KZG +import SolarTV.EVMIR.Precompiles.Gas +import SolarTV.EVMIR.State.Decode + +/-! Complete precompile dispatch for the world's admitted Istanbul–Osaka forks. +Activation is shared with the bytecode evaluator; inactive addresses execute +ordinary account code. Invalid encodings/proofs burn the child budget, whereas +invalid ECDSA signatures return successful empty output. Gas is charged before +expensive crypto. Explicit model work limits are errors, never EVM failures. +Every cryptographic result is computed in Lean from executable arithmetic. +https://eips.ethereum.org/EIPS/eip-7823 -/ + +namespace SolarTV.Precompiles +open EVM.State + +def modexp (input : List Byte) : Except String (List Byte) := do + let base := readBE input 0 32 + let exponent := readBE input 32 32 + let modulus := readBE input 64 32 + if base = 0 && modulus = 0 then return [] + if base > 65536 || exponent > 65536 || modulus > 65536 then + .error "ModExp model byte limit of 64 KiB" + else + let value := powMod (readBE input 96 base) (readBE input (96+base) exponent) + (readBE input (96+base+exponent) modulus) + return be modulus value + +def compute (address : Nat) (input : List Byte) : Except String (Option (List Byte)) := + match address with + | 1 => .ok (some (Signatures.recover input)) + | 2 => .ok (some (SHA256.hash input)) + | 3 => .ok (some (List.replicate 12 0 ++ RIPEMD160.hash input)) + | 4 => .ok (some input) + | 5 => some <$> modexp input + | 6 => .ok (BN254.addition input) + | 7 => .ok (BN254.multiplication input) + | 8 => .ok (BN254.pairing input) + | 9 => + if input.length != 213 || input[212]?.getD 0 > 1 then .ok none + else if readBE input 0 4 > 4096 then .error "BLAKE2F model limit of 4096 rounds" + else .ok (some (Blake2F.compress input)) + | 10 => .ok (KZG.evaluate input) + | 11 => .ok (BLS12381.addition1 input) + | 12 => .ok (BLS12381.msm1 input) + | 13 => .ok (BLS12381.addition2 input) + | 14 => .ok (BLS12381.msm2 input) + | 15 => .ok (BLS12381.pairing input) + | 16 => .ok (BLS12381.map1 input) + | 17 => .ok (BLS12381.map2 input) + | 256 => .ok (some (Signatures.verify input)) + | _ => .error "unrecognized active precompile" + +def execute (fork : Fork) (address : Address) (input : List Byte) (gas : Nat) : + Except String (Stop × List Byte × Nat) := do + if fork = .amsterdam then .error "Amsterdam precompile pricing is not modeled" else + if !precompile fork address then .error "inactive precompile must execute account code" else + -- EIP-152 validates the compression input length before reading rounds. + if address = 9 && input.length != 213 then return (.exception,[],0) + -- MSM/pairing validate their repeated-record layout before charging gas. + if (address = 12 && (input.isEmpty || input.length%160 != 0)) || + (address = 14 && (input.isEmpty || input.length%288 != 0)) || + (address = 15 && (input.isEmpty || input.length%384 != 0)) then + return (.exception,[],0) + if address = 5 && fork.atLeast .osaka && gas < 500 then return (.outOfGas,[],0) + let cost := price fork address.toNat input + if address = 5 && fork.atLeast .osaka && + (readBE input 0 32 > 1024 || readBE input 32 32 > 1024 || readBE input 64 32 > 1024) then + return (.exception,[],0) + if gas < cost then return (.outOfGas,[],0) + let output ← compute address.toNat input + match output with + | none => return (.exception,[],0) + | some bytes => return (.success,bytes,gas-cost) + +end SolarTV.Precompiles diff --git a/tv/SolarTV/EVMIR/Precompiles/Field.lean b/tv/SolarTV/EVMIR/Precompiles/Field.lean new file mode 100644 index 00000000..4c06eccf --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Field.lean @@ -0,0 +1,79 @@ +import SolarTV.EVMIR.Precompiles.Bytes + +/-! Executable finite-field arithmetic for the curve precompiles. Prime fields +use canonical natural residues; quadratic extensions use i² = -1. The degree-12 +extension is a polynomial quotient, with coefficients in ascending order. Its +modulus is x¹² - c*x⁶ + d (BN254: c=18,d=82; BLS12-381: c=2,d=2). +All loops have explicit structural bounds. Inversion at zero is zero; callers +must check the nonzero/curve conditions required by their interface. -/ + +namespace SolarTV.Precompiles + +structure Arithmetic (K : Type) where + zero : K + one : K + nat : Nat → K + add : K → K → K + neg : K → K + mul : K → K → K + inv : K → K + eq : K → K → Bool + +def Arithmetic.sub (f : Arithmetic K) (a b : K) : K := f.add a (f.neg b) +def Arithmetic.square (f : Arithmetic K) (a : K) : K := f.mul a a +def Arithmetic.div (f : Arithmetic K) (a b : K) : K := f.mul a (f.inv b) + +def powerLoop (mul : K → K → K) : Nat → K → Nat → K → K + | 0, _, _, acc => acc + | fuel + 1, base, exponent, acc => + if exponent = 0 then acc else + powerLoop mul fuel (mul base base) (exponent / 2) + (if exponent % 2 = 1 then mul acc base else acc) + +def Arithmetic.pow (f : Arithmetic K) (a : K) (n : Nat) : K := + powerLoop f.mul (n.log2 + 1) a n f.one + +def fp (p : Nat) : Arithmetic Nat := + ⟨0, 1, (· % p), (fun a b => (a+b)%p), (fun a => (p-a%p)%p), + (fun a b => a*b%p), (fun a => powMod a (p-2) p), (· == ·)⟩ + +abbrev F2 := Nat × Nat + +def fp2 (p : Nat) : Arithmetic F2 := + let f := fp p + ⟨(0,0), (1,0), (fun n => (n%p,0)), + (fun a b => (f.add a.1 b.1, f.add a.2 b.2)), + (fun a => (f.neg a.1, f.neg a.2)), + (fun a b => (f.sub (f.mul a.1 b.1) (f.mul a.2 b.2), + f.add (f.mul a.1 b.2) (f.mul a.2 b.1))), + (fun a => let d := f.inv (f.add (f.square a.1) (f.square a.2)) + (f.mul a.1 d, f.neg (f.mul a.2 d))), (· == ·)⟩ + +abbrev F12 := List Nat + +def polynomial (index value : Nat) : F12 := + (List.range 12).map (fun i => if i = index then value else 0) + +def mul12 (p c d : Nat) (a b : F12) : F12 := Id.run do + let mut v := (List.range 23).map (fun k => + ((List.range 12).foldl (fun sum i => + if i ≤ k && k-i < 12 then sum + a[i]?.getD 0 * b[k-i]?.getD 0 else sum) 0) % p) + for j in List.range 11 do + let i := 22-j + let high := v[i]?.getD 0 + v := v.set (i-6) ((v[i-6]?.getD 0 + c*high)%p) + v := v.set (i-12) ((v[i-12]?.getD 0 + p - (d*high)%p)%p) + return v.take 12 + +def fp12 (p c d : Nat) : Arithmetic F12 := + let mul := mul12 p c d + let one := polynomial 0 1 + ⟨polynomial 0 0, one, (fun n => polynomial 0 (n%p)), + (fun a b => (List.range 12).map (fun i => (a[i]?.getD 0 + b[i]?.getD 0)%p)), + (fun a => a.map (fun x => (p-x%p)%p)), mul, + (fun a => powerLoop mul ((p^12-2).log2+1) a (p^12-2) one), (· == ·)⟩ + +def lift2 (p c : Nat) (a : F2) : F12 := + (polynomial 0 ((a.1 + p - (c*a.2)%p)%p)).set 6 a.2 + +end SolarTV.Precompiles diff --git a/tv/SolarTV/EVMIR/Precompiles/Gas.lean b/tv/SolarTV/EVMIR/Precompiles/Gas.lean new file mode 100644 index 00000000..56195414 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Gas.lean @@ -0,0 +1,74 @@ +import SolarTV.EVMIR.Precompiles.Bytes + +/-! Precompile gas schedules and MSM discount tables. ModExp follows EIP-198, +Berlin EIP-2565 and Osaka EIP-7883; the Osaka size restriction is checked before +evaluation by the dispatcher. BN254 repricing starts at Istanbul. BLS discounts +are EIP-2537's exact integer tables, saturated at the final entry. +https://eips.ethereum.org/EIPS/eip-198 +https://eips.ethereum.org/EIPS/eip-2565 +https://eips.ethereum.org/EIPS/eip-7883 +https://eips.ethereum.org/EIPS/eip-2537#gas-schedule -/ + +namespace SolarTV.Precompiles +open EVM.State + +def discount1 : List Nat := [ + 1000,949,848,797,764,750,738,728,719,712,705,698,692,687,682,677,673,669,665, + 661,658,654,651,648,645,642,640,637,635,632,630,627,625,623,621,619,617,615, + 613,611,609,608,606,604,603,601,599,598,596,595,593,592,591,589,588,586,585, + 584,582,581,580,579,577,576,575,574,573,572,570,569,568,567,566,565,564,563, + 562,561,560,559,558,557,556,555,554,553,552,551,550,549,548,547,547,546,545, + 544,543,542,541,540,540,539,538,537,536,536,535,534,533,532,532,531,530,529, + 528,528,527,526,525,525,524,523,522,522,521,520,520,519] +def discount2 : List Nat := [ + 1000,1000,923,884,855,832,812,796,782,770,759,749,740,732,724,717,711,704, + 699,693,688,683,679,674,670,666,663,659,655,652,649,646,643,640,637,634,632, + 629,627,624,622,620,618,615,613,611,609,607,606,604,602,600,598,597,595,593, + 592,590,589,587,586,584,583,582,580,579,578,576,575,574,573,571,570,569,568, + 567,566,565,563,562,561,560,559,558,557,556,555,554,553,552,552,551,550,549, + 548,547,546,545,545,544,543,542,541,541,540,539,538,537,537,536,535,535,534, + 533,532,532,531,530,530,529,528,528,527,526,526,525,524,524] + +def modexpPrice (fork : Fork) (input : List Byte) : Nat := + let base := readBE input 0 32 + let exponent := readBE input 32 32 + let modulus := readBE input 64 32 + let head := readBE input (96+base) (min exponent 32) + let length := max base modulus + let iterations := max 1 ((if fork.atLeast .osaka then 16 else 8)*(exponent-32) + head.log2) + if fork.atLeast .osaka then + max 500 ((if length ≤ 32 then 16 else 2*((length+7)/8)^2)*iterations) + else if fork.atLeast .berlin then max 200 (((length+7)/8)^2 * iterations / 3) + else + let complexity := if length ≤ 64 then length^2 + else if length ≤ 1024 then length^2/4 + 96*length - 3072 + else length^2/16 + 480*length - 199680 + complexity * iterations / 20 + +def price (fork : Fork) (address : Nat) (input : List Byte) : Nat := + let words := (input.length+31)/32 + match address with + | 1 => 3000 + | 2 => 60 + 12*words + | 3 => 600 + 120*words + | 4 => 15 + 3*words + | 5 => modexpPrice fork input + | 6 => if fork.atLeast .istanbul then 150 else 500 + | 7 => if fork.atLeast .istanbul then 6000 else 40000 + | 8 => if fork.atLeast .istanbul then 45000 + 34000*(input.length/192) + else 100000 + 80000*(input.length/192) + | 9 => readBE input 0 4 + | 10 => 50000 + | 11 => 375 + | 12 => let k := input.length/160 + 12000*k*(discount1[min (k-1) 127]?.getD 519)/1000 + | 13 => 600 + | 14 => let k := input.length/288 + 22500*k*(discount2[min (k-1) 127]?.getD 524)/1000 + | 15 => 37700 + 32600*(input.length/384) + | 16 => 5500 + | 17 => 23800 + | 256 => 6900 + | _ => 0 + +end SolarTV.Precompiles diff --git a/tv/SolarTV/EVMIR/Precompiles/KZG.lean b/tv/SolarTV/EVMIR/Precompiles/KZG.lean new file mode 100644 index 00000000..70e14b86 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/KZG.lean @@ -0,0 +1,63 @@ +import SolarTV.EVMIR.Precompiles.BLS12381 +import SolarTV.EVMIR.Precompiles.SHA256 + +/-! EIP-4844 point evaluation against Ethereum's fixed KZG ceremony G2 point. +Compressed points are decoded canonically and checked for subgroup membership; +infinity is permitted. Scalars are canonical Fr values. Verification evaluates +the actual pairing product e(C-yG1,-G2) * e(proof,tauG2-zG2) = 1. +The trusted setup is public protocol data, not a result oracle or pairing axiom. +https://eips.ethereum.org/EIPS/eip-4844#point-evaluation-precompile +https://github.com/ethereum/consensus-specs/blob/dev/specs/deneb/polynomial-commitments.md -/ + +namespace SolarTV.Precompiles.KZG +open EVM.State BLS12381 + +def compressed1 (input : List Byte) : Option (Point Nat) := do + if input.length != 48 then none else + let flags := input[0]?.getD 0 |>.toNat + let x := readBE input 0 48 % 2^381 + if flags/128 != 1 || x ≥ p then none + else if flags/64%2 = 1 then + if x = 0 && flags/32%2 = 0 then some (infinity f) else none + else + let y ← sqrt p (f.add (f.mul (f.square x) x) 4) + let y := if (y > p/2) == (flags/32%2 = 1) then y else f.neg y + let point := affine f x y + if isInfinity f (multiply f 0 point order) then some point else none + +def compressed2 (input : List Byte) : Option (Point F2) := do + if input.length != 96 then none else + let flags := input[0]?.getD 0 |>.toNat + let xi := readBE input 0 48 % 2^381 + let xr := readBE input 48 48 + if flags/128 != 1 || xi ≥ p || xr ≥ p then none + else if flags/64%2 = 1 then + if xi = 0 && xr = 0 && flags/32%2 = 0 then some (infinity f2) else none + else + let x := (xr,xi) + let y ← sqrt2 (f2.add (f2.mul (f2.square x) x) (4,4)) + let sign := y.2 > p/2 || (y.2 = 0 && y.1 > p/2) + let y := if sign == (flags/32%2 = 1) then y else f2.neg y + let point := affine f2 x y + if isInfinity f2 (multiply f2 f2.zero point order) then some point else none + +def tau : Option (Point F2) := compressed2 (be 96 + 0xb5bfd7dd8cdeb128843bc287230af38926187075cbfbefa81009a2ce615ac53d2914e5870cb452d2afaaab24f3499f72185cbfee53492714734429b7b38608e23926c911cceceac9a36851477ba4c60b087041de621000edc98edada20c1def2) + +def evaluate (input : List Byte) : Option (List Byte) := do + if input.length != 192 then none else + let commitment := (input.drop 96).take 48 + let expected := [1] ++ (SHA256.hash commitment).drop 1 + if input.take 32 != expected then none else + let z := readBE input 32 32; let y := readBE input 64 32 + if z ≥ order || y ≥ order then none else + let c ← compressed1 commitment + let proof ← compressed1 (input.drop 144) + let tau ← tau + let left := add f 0 c (negate f (multiply f 0 generator1 y)) + let right := add f2 f2.zero tau (negate f2 (multiply f2 f2.zero generator2 z)) + if Pairing.check p order true [(left,negate f2 generator2),(proof,right)] then + some (be 32 4096 ++ be 32 order) + else none + +end SolarTV.Precompiles.KZG diff --git a/tv/SolarTV/EVMIR/Precompiles/MapConstants.lean b/tv/SolarTV/EVMIR/Precompiles/MapConstants.lean new file mode 100644 index 00000000..41718831 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/MapConstants.lean @@ -0,0 +1,98 @@ +import SolarTV.EVMIR.Precompiles.Field + +/-! EIP-2537 isogeny constants, in ascending polynomial order. Generated +by tools/gen_bls_tables.py from ark-bls12-381 0.6.0; only mathematical +constants are copied, with negative values reduced to canonical residues. +https://eips.ethereum.org/assets/eip-2537/field_to_curve -/ + +namespace SolarTV.Precompiles.BLS12381.MapConstants + +-- Source SHA-256: 1e8090ef8a4774391d7f20c9599c61cdb9476532051b3d0645cf7743bf1421dd. +def g1XNumerator : List Nat := [ + 2712959285290305970661081772124144179193819192423276218370281158706191519995889425075952244140278856085036081760695, + 3564859427549639835253027846704205725951033235539816243131874237388832081954622352624080767121604606753339903542203, + 2051387046688339481714726479723076305756384619135044672831882917686431912682625619320120082313093891743187631791280, + 3612713941521031012780325893181011392520079402153354595775735142359240110423346445050803899623018402874731133626465, + 2247053637822768981792833880270996398470828564809439728372634811976089874056583714987807553397615562273407692740057, + 3415427104483187489859740871640064348492611444552862448295571438270821994900526625562705192993481400731539293415811, + 2067521456483432583860405634125513059912765526223015704616050604591207046392807563217109432457129564962571408764292, + 3650721292069012982822225637849018828271936405382082649291891245623305084633066170122780668657208923883092359301262, + 1239271775787030039269460763652455868148971086016832054354147730155061349388626624328773377658494412538595239256855, + 3479374185711034293956731583912244564891370843071137483962415222733470401948838363051960066766720884717833231600798, + 2492756312273161536685660027440158956721981129429869601638362407515627529461742974364729223659746272460004902959995, + 1058488477413994682556770863004536636444795456512795473806825292198091015005841418695586811009326456605062948114985] + +def g1XDenominator : List Nat := [ + 1353092447850172218905095041059784486169131709710991428415161466575141675351394082965234118340787683181925558786844, + 2822220997908397120956501031591772354860004534930174057793539372552395729721474912921980407622851861692773516917759, + 1717937747208385987946072944131378949849282930538642983149296304709633281382731764122371874602115081850953846504985, + 501624051089734157816582944025690868317536915684467868346388760435016044027032505306995281054569109955275640941784, + 3025903087998593826923738290305187197829899948335370692927241015584233559365859980023579293766193297662657497834014, + 2224140216975189437834161136818943039444741035168992629437640302964164227138031844090123490881551522278632040105125, + 1146414465848284837484508420047674663876992808692209238763293935905506532411661921697047880549716175045414621825594, + 3179090966864399634396993677377903383656908036827452986467581478509513058347781039562481806409014718357094150199902, + 1549317016540628014674302140786462938410429359529923207442151939696344988707002602944342203885692366490121021806145, + 1442797143427491432630626390066422021593505165588630398337491100088557278058060064930663878153124164818522816175370, + 1] + +def g1YNumerator : List Nat := [ + 1393399195776646641963150658816615410692049723305861307490980409834842911816308830479576739332720113414154429643571, + 2968610969752762946134106091152102846225411740689724909058016729455736597929366401532929068084731548131227395540630, + 122933100683284845219599644396874530871261396084070222155796123161881094323788483360414289333111221370374027338230, + 303251954782077855462083823228569901064301365507057490567314302006681283228886645653148231378803311079384246777035, + 1353972356724735644398279028378555627591260676383150667237975415318226973994509601413730187583692624416197017403099, + 3443977503653895028417260979421240655844034880950251104724609885224259484262346958661845148165419691583810082940400, + 718493410301850496156792713845282235942975872282052335612908458061560958159410402177452633054233549648465863759602, + 1466864076415884313141727877156167508644960317046160398342634861648153052436926062434809922037623519108138661903145, + 1536886493137106337339531461344158973554574987550750910027365237255347020572858445054025958480906372033954157667719, + 2171468288973248519912068884667133903101171670397991979582205855298465414047741472281361964966463442016062407908400, + 3915937073730221072189646057898966011292434045388986394373682715266664498392389619761133407846638689998746172899634, + 3802409194827407598156407709510350851173404795262202653149767739163117554648574333789388883640862266596657730112910, + 1707589313757812493102695021134258021969283151093981498394095062397393499601961942449581422761005023512037430861560, + 349697005987545415860583335313370109325490073856352967581197273584891698473628451945217286148025358795756956811571, + 885704436476567581377743161796735879083481447641210566405057346859953524538988296201011389016649354976986251207243, + 3370924952219000111210625390420697640496067348723987858345031683392215988129398381698161406651860675722373763741188] + +def g1YDenominator : List Nat := [ + 3396434800020507717552209507749485772788165484415495716688989613875369612529138640646200921379825018840894888371137, + 3907278185868397906991868466757978732688957419873771881240086730384895060595583602347317992689443299391009456758845, + 854914566454823955479427412036002165304466268547334760894270240966182605542146252771872707010378658178126128834546, + 3496628876382137961119423566187258795236027183112131017519536056628828830323846696121917502443333849318934945158166, + 1828256966233331991927609917644344011503610008134915752990581590799656305331275863706710232159635159092657073225757, + 1362317127649143894542621413133849052553333099883364300946623208643344298804722863920546222860227051989127113848748, + 3443845896188810583748698342858554856823966611538932245284665132724280883115455093457486044009395063504744802318172, + 3484671274283470572728732863557945897902920439975203610275006103818288159899345245633896492713412187296754791689945, + 3755735109429418587065437067067640634211015783636675372165599470771975919172394156249639331555277748466603540045130, + 3459661102222301807083870307127272890283709299202626530836335779816726101522661683404130556379097384249447658110805, + 742483168411032072323733249644347333168432665415341249073150659015707795549260947228694495111018381111866512337576, + 1662231279858095762833829698537304807741442669992646287950513237989158777254081548205552083108208170765474149568658, + 1668238650112823419388205992952852912407572045257706138925379268508860023191233729074751042562151098884528280913356, + 369162719928976119195087327055926326601627748362769544198813069133429557026740823593067700396825489145575282378487, + 2164195715141237148945939585099633032390257748382945597506236650132835917087090097395995817229686247227784224263055, + 1] + +-- Source SHA-256: 6edfd3d72eea73164ce6ed78dabd4e4772389987e8c084340f628f4981464cc7. +def g2XNumerator : List F2 := [ + (889424345604814976315064405719089812568196182208668418962679585805340366775741747653930584250892369786198727235542, 889424345604814976315064405719089812568196182208668418962679585805340366775741747653930584250892369786198727235542), + (0, 2668273036814444928945193217157269437704588546626005256888038757416021100327225242961791752752677109358596181706522), + (2668273036814444928945193217157269437704588546626005256888038757416021100327225242961791752752677109358596181706526, 1334136518407222464472596608578634718852294273313002628444019378708010550163612621480895876376338554679298090853261), + (3557697382419259905260257622876359250272784728834673675850718343221361467102966990615722337003569479144794908942033, 0)] + +def g2XDenominator : List F2 := [ + (0, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559715), + (12, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559775), + (1, 0)] + +def g2YNumerator : List F2 := [ + (3261222600550988246488569487636662646083386001431784202863158481286248011511053074731078808919938689216061999863558, 3261222600550988246488569487636662646083386001431784202863158481286248011511053074731078808919938689216061999863558), + (0, 889424345604814976315064405719089812568196182208668418962679585805340366775741747653930584250892369786198727235518), + (2668273036814444928945193217157269437704588546626005256888038757416021100327225242961791752752677109358596181706524, 1334136518407222464472596608578634718852294273313002628444019378708010550163612621480895876376338554679298090853263), + (2816510427748580758331037284777117739799287910327449993381818688383577828123182200904113516794492504322962636245776, 0)] + +def g2YDenominator : List F2 := [ + (4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559355, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559355), + (0, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559571), + (18, 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559769), + (1, 0)] + +end SolarTV.Precompiles.BLS12381.MapConstants diff --git a/tv/SolarTV/EVMIR/Precompiles/Maps.lean b/tv/SolarTV/EVMIR/Precompiles/Maps.lean new file mode 100644 index 00000000..9ee1832b --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Maps.lean @@ -0,0 +1,58 @@ +import SolarTV.EVMIR.Precompiles.BLS12381 +import SolarTV.EVMIR.Precompiles.MapConstants + +/-! EIP-2537's simplified SWU maps, rational isogenies and effective-cofactor +clearing. Exceptional SWU inputs use B/(Z*A); zero isogeny denominators map to +infinity. The output sign follows sgn0 (parity of the first nonzero coefficient), +not the lexicographic sign used by compressed KZG point encodings. +https://eips.ethereum.org/assets/eip-2537/field_to_curve -/ + +namespace SolarTV.Precompiles.BLS12381 +open EVM.State MapConstants + +def polynomialValue (f : Arithmetic K) (coefficients : List K) (x : K) : K := + coefficients.reverse.foldl (fun acc c => f.add (f.mul acc x) c) f.zero + +def swu (f : Arithmetic K) (a b z : K) (root : K → Option K) + (sign : K → Bool) (u : K) : Option (Point K) := do + let zu2 := f.mul z (f.square u) + let inverse := f.inv (f.add (f.square zu2) zu2) + let x1 := if f.eq inverse f.zero then f.div b (f.mul z a) + else f.mul (f.div (f.neg b) a) (f.add f.one inverse) + let equation := fun x => f.add (f.add (f.mul (f.square x) x) (f.mul a x)) b + let (x,y) ← match root (equation x1) with + | some y => some (x1,y) + | none => let x2 := f.mul zu2 x1; (fun y => (x2,y)) <$> root (equation x2) + return affine f x (if sign u == sign y then y else f.neg y) + +def isogeny (f : Arithmetic K) (xn xd yn yd : List K) (point : Point K) : Point K := + match normalize f point with + | none => infinity f + | some (x,y) => + let dx := polynomialValue f xd x; let dy := polynomialValue f yd x + if f.eq dx f.zero || f.eq dy f.zero then infinity f else + affine f (f.div (polynomialValue f xn x) dx) + (f.div (f.mul y (polynomialValue f yn x)) dy) + +def map1 (input : List Byte) : Option (List Byte) := do + if input.length != 64 then none else + let u := readBE input 0 64 + if u ≥ p then none else + let point ← swu f + 0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d + 0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0 + 11 (sqrt p) (fun n => n%2 == 1) u + let mapped := isogeny f g1XNumerator g1XDenominator g1YNumerator g1YDenominator point + return encode1 (multiply f 0 mapped 0xd201000000010001) + +def map2 (input : List Byte) : Option (List Byte) := do + if input.length != 128 then none else + let a := readBE input 0 64; let b := readBE input 64 64 + if a ≥ p || b ≥ p then none else + let point ← swu f2 (0,240) (1012,1012) (p-2,p-1) sqrt2 + (fun n => n.1%2 == 1 || (n.1 == 0 && n.2%2 == 1)) (a,b) + let mapped := isogeny f2 g2XNumerator g2XDenominator g2YNumerator g2YDenominator point + let cofactor := 0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551 + return encode2 (multiply f2 f2.zero mapped cofactor) + +end SolarTV.Precompiles.BLS12381 diff --git a/tv/SolarTV/EVMIR/Precompiles/Observe.lean b/tv/SolarTV/EVMIR/Precompiles/Observe.lean new file mode 100644 index 00000000..f64914c7 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Observe.lean @@ -0,0 +1,24 @@ +import SolarTV.EVMIR.Precompiles.Execute +import Lean.Data.Json + +/-! Direct precompile observations for boundary tests and independent replay. +These observations do not bypass the kernel proof required for a world-entry +verification. An inactive address is identified separately: its account code, +not a precompile, must be executed by the caller's world evaluator. -/ + +namespace SolarTV.Precompiles +open EVM.State + +def describe (fork : Fork) (address : Address) (input : List Byte) (gas : Nat) : String := + let result := if precompile fork address then execute fork address input gas + else .ok (.success,[],gas) + match result with + | .error reason => (Lean.Json.mkObj [("unsupported",.str reason)]).compress + | .ok (stop,data,remaining) => + let name := if !precompile fork address then "inactive" else match stop with + | .success => "success" | .exception => "exception" + | .outOfGas => "out-of-gas" | .reverted => "revert" + (Lean.Json.arr #[.str name, + .arr (data.map (fun b => Lean.toJson b.toNat)).toArray, Lean.toJson remaining]).compress + +end SolarTV.Precompiles diff --git a/tv/SolarTV/EVMIR/Precompiles/Pairing.lean b/tv/SolarTV/EVMIR/Precompiles/Pairing.lean new file mode 100644 index 00000000..25fc58ec --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Pairing.lean @@ -0,0 +1,81 @@ +import SolarTV.EVMIR.Precompiles.Curve + +/-! Optimal-Ate pairing products over explicit degree-12 polynomial fields. +Miller lines retain numerator/denominator pairs, avoiding an inversion per line. +Final exponentiation compares their powers, not an unchecked foreign result. +BN254 includes its two Frobenius correction lines. BLS12-381 uses the absolute +loop parameter: inversion of the whole product for the negative parameter does +not change the product-equals-one predicate exposed by either precompile. + +The homogeneous line and group formulas follow EVMYulLean's alt_bn128 reference +and the pairing definitions in EIP-197 and EIP-2537. Infinity pairs contribute +one. Decoders must enforce curve and subgroup membership before calling here. +https://eips.ethereum.org/EIPS/eip-197 +https://eips.ethereum.org/EIPS/eip-2537 -/ + +namespace SolarTV.Precompiles.Pairing + +def line (f : Arithmetic F12) (p q t : Point F12) : F12 × F12 := + let numerator := f.sub (f.mul q.y p.z) (f.mul p.y q.z) + let denominator := f.sub (f.mul q.x p.z) (f.mul p.x q.z) + let dx := f.sub (f.mul t.x p.z) (f.mul p.x t.z) + let dy := f.sub (f.mul t.y p.z) (f.mul p.y t.z) + if !f.eq denominator f.zero then + (f.sub (f.mul numerator dx) (f.mul denominator dy), f.mul denominator (f.mul t.z p.z)) + else if f.eq numerator f.zero then + let numerator := f.mul (f.nat 3) (f.square p.x) + let denominator := f.mul (f.nat 2) (f.mul p.y p.z) + (f.sub (f.mul numerator dx) (f.mul denominator dy), f.mul denominator (f.mul t.z p.z)) + else (dx, f.mul p.z t.z) + +def cast (f : Arithmetic F12) (p : Point Nat) : Point F12 := + ⟨f.nat p.x, f.nat p.y, f.nat p.z⟩ + +def twist (p : Nat) (bls : Bool) (q : Point F2) : Point F12 := + let f := fp12 p (if bls then 2 else 18) (if bls then 2 else 82) + let w := polynomial 1 1 + let x := lift2 p (if bls then 1 else 9) q.x + let y := lift2 p (if bls then 1 else 9) q.y + let z := lift2 p (if bls then 1 else 9) q.z + if bls then ⟨f.mul x w, y, f.mul z (f.pow w 3)⟩ + else ⟨f.mul x (f.pow w 2), f.mul y (f.pow w 3), z⟩ + +def miller (p : Nat) (bls : Bool) (g1 : Point Nat) (g2 : Point F2) : F12 × F12 := Id.run do + let f := fp12 p (if bls then 2 else 18) (if bls then 2 else 82) + if isInfinity (fp p) g1 || isInfinity (fp2 p) g2 then return (f.one,f.one) + let q := twist p bls g2 + let t := cast f g1 + let count := if bls then 0xd201000000010000 else 29793968203157093288 + let mut r := q + let mut numerator := f.one + let mut denominator := f.one + for j in List.range count.log2 do + let bit := count.log2-1-j + let l := line f r r t + numerator := f.mul (f.square numerator) l.1 + denominator := f.mul (f.square denominator) l.2 + r := double f f.zero r + if (count >>> bit)%2 = 1 then + let l := line f r q t + numerator := f.mul numerator l.1 + denominator := f.mul denominator l.2 + r := add f f.zero r q + if !bls then + let q1 := Point.mk (f.pow q.x p) (f.pow q.y p) (f.pow q.z p) + let q2 := Point.mk (f.pow q1.x p) (f.neg (f.pow q1.y p)) (f.pow q1.z p) + let l := line f r q1 t + numerator := f.mul numerator l.1; denominator := f.mul denominator l.2 + r := add f f.zero r q1 + let l := line f r q2 t + numerator := f.mul numerator l.1; denominator := f.mul denominator l.2 + return (numerator,denominator) + +def check (p order : Nat) (bls : Bool) (pairs : List (Point Nat × Point F2)) : Bool := + let f := fp12 p (if bls then 2 else 18) (if bls then 2 else 82) + let product := pairs.foldl (fun acc pair => + let (n,d) := miller p bls pair.1 pair.2 + (f.mul acc.1 n, f.mul acc.2 d)) (f.one,f.one) + !f.eq product.2 f.zero && + (f.eq product.1 product.2 || f.eq (f.pow product.1 ((p^12-1)/order)) (f.pow product.2 ((p^12-1)/order))) + +end SolarTV.Precompiles.Pairing diff --git a/tv/SolarTV/EVMIR/Precompiles/RIPEMD160.lean b/tv/SolarTV/EVMIR/Precompiles/RIPEMD160.lean new file mode 100644 index 00000000..7b31fd98 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/RIPEMD160.lean @@ -0,0 +1,72 @@ +import SolarTV.EVMIR.Precompiles.Bytes + +/-! RIPEMD-160's two parallel 80-round compression lanes, with little-endian +words, length padding and digest encoding. The precompile adds its twelve zero +output bytes separately. Constants follow the designers' reference specification. +https://homes.esat.kuleuven.be/~bosselae/ripemd160.html -/ + +namespace SolarTV.Precompiles.RIPEMD160 +open EVM.State +abbrev W := BitVec 32 + +def leftIndex : List Nat := [ + 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, + 7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8, + 3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12, + 1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2, + 4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13] +def rightIndex : List Nat := [ + 5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12, + 6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2, + 15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13, + 8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14, + 12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11] +def leftShift : List Nat := [ + 11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8, + 7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12, + 11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5, + 11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12, + 9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6] +def rightShift : List Nat := [ + 8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6, + 9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11, + 9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5, + 15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8, + 8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11] +def constant (right : Bool) (round : Nat) : W := + (if right then [0x50a28be6,0x5c4dd124,0x6d703ef3,0x7a6d76e9,0] + else [0,0x5a827999,0x6ed9eba1,0x8f1bbcdc,0xa953fd4e])[round]?.getD 0 +def boolean (round : Nat) (x y z : W) : W := + match round with + | 0 => x ^^^ y ^^^ z + | 1 => (x &&& y) ||| (~~~x &&& z) + | 2 => (x ||| ~~~y) ^^^ z + | 3 => (x &&& z) ||| (y &&& ~~~z) + | _ => x ^^^ (y ||| ~~~z) +def lane (right : Bool) (words state : List W) : List W := + (List.range 80).foldl (fun s j => + let a := s[0]?.getD 0; let b := s[1]?.getD 0; let c := s[2]?.getD 0 + let d := s[3]?.getD 0; let e := s[4]?.getD 0 + let index := (if right then rightIndex else leftIndex)[j]?.getD 0 + let shift := (if right then rightShift else leftShift)[j]?.getD 0 + let f := boolean (if right then 4-j/16 else j/16) b c d + let t := (a + f + words[index]?.getD 0 + constant right (j/16)).rotateLeft shift + e + [e,t,b,c.rotateLeft 10,d]) state +def initial : List W := [0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0] +def compress (s : List W) (block : List Byte) : List W := + let words := (List.range 16).map (fun i => BitVec.ofNat 32 (readLE block (4*i) 4)) + let a := lane false words s + let b := lane true words s + [s[1]?.getD 0 + a[2]?.getD 0 + b[3]?.getD 0, + s[2]?.getD 0 + a[3]?.getD 0 + b[4]?.getD 0, + s[3]?.getD 0 + a[4]?.getD 0 + b[0]?.getD 0, + s[4]?.getD 0 + a[0]?.getD 0 + b[1]?.getD 0, + s[0]?.getD 0 + a[1]?.getD 0 + b[2]?.getD 0] +def hash (input : List Byte) : List Byte := + let pad := (64 - ((input.length + 9) % 64)) % 64 + let padded := input ++ [128] ++ List.replicate pad 0 ++ le 8 (input.length * 8) + let state := (List.range (padded.length / 64)).foldl + (fun s i => compress s ((padded.drop (i*64)).take 64)) initial + state.flatMap (fun w => le 4 w.toNat) + +end SolarTV.Precompiles.RIPEMD160 diff --git a/tv/SolarTV/EVMIR/Precompiles/SHA256.lean b/tv/SolarTV/EVMIR/Precompiles/SHA256.lean new file mode 100644 index 00000000..44793f06 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/SHA256.lean @@ -0,0 +1,52 @@ +import SolarTV.EVMIR.Precompiles.Bytes + +/-! Executable SHA-256, following FIPS 180-4, sections 5 and 6.2. The compression +state and schedule use 32-bit words; padding and output lengths are byte-exact. +No foreign function or uninterpreted hash is used by the Lean evaluator. +https://doi.org/10.6028/NIST.FIPS.180-4 -/ + +namespace SolarTV.Precompiles.SHA256 +open EVM.State +abbrev W := BitVec 32 + +def constants : List W := [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2] + +def initial : List W := [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19] + +def compress (state : List W) (block : List Byte) : List W := Id.run do + let mut schedule := (List.range 16).map (fun i => BitVec.ofNat 32 (readBE block (4*i) 4)) + for i in List.range 48 do + let x := schedule[i+1]?.getD 0 + let y := schedule[i+14]?.getD 0 + let s0 := x.rotateRight 7 ^^^ x.rotateRight 18 ^^^ (x >>> 3) + let s1 := y.rotateRight 17 ^^^ y.rotateRight 19 ^^^ (y >>> 10) + schedule := schedule ++ [schedule[i]?.getD 0 + s0 + schedule[i+9]?.getD 0 + s1] + let mut s := state + for i in List.range 64 do + let a := s[0]?.getD 0; let b := s[1]?.getD 0; let c := s[2]?.getD 0; let d := s[3]?.getD 0 + let e := s[4]?.getD 0; let f := s[5]?.getD 0; let g := s[6]?.getD 0; let h := s[7]?.getD 0 + let big1 := e.rotateRight 6 ^^^ e.rotateRight 11 ^^^ e.rotateRight 25 + let choose := (e &&& f) ^^^ (~~~e &&& g) + let t1 := h + big1 + choose + constants[i]?.getD 0 + schedule[i]?.getD 0 + let big0 := a.rotateRight 2 ^^^ a.rotateRight 13 ^^^ a.rotateRight 22 + let majority := (a &&& b) ^^^ (a &&& c) ^^^ (b &&& c) + s := [t1 + big0 + majority, a, b, c, d + t1, e, f, g] + return (state.zip s).map (fun (a,b) => a+b) + +def hash (input : List Byte) : List Byte := + let pad := (64 - ((input.length + 9) % 64)) % 64 + let padded := input ++ [128] ++ List.replicate pad 0 ++ be 8 (input.length * 8) + let state := (List.range (padded.length / 64)).foldl + (fun s i => compress s ((padded.drop (i*64)).take 64)) initial + state.flatMap (fun w => be 4 w.toNat) + +end SolarTV.Precompiles.SHA256 diff --git a/tv/SolarTV/EVMIR/Precompiles/Safety.lean b/tv/SolarTV/EVMIR/Precompiles/Safety.lean new file mode 100644 index 00000000..7a503baf --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Safety.lean @@ -0,0 +1,22 @@ +import SolarTV.EVMIR.Precompiles.Observe + +/-! Kernel-checked digest vectors and failure boundaries. Differential tests +cover every active precompile against the native engine; these checks additionally +pin the pure hashing definitions and distinctions between malformed input, +out-of-gas, and successful empty signature output without foreign computation. -/ + +namespace SolarTV.Precompiles +open EVM.State +set_option maxRecDepth 16384 + +example : SHA256.hash [] = be 32 0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 := by + decide +kernel +example : RIPEMD160.hash [97,98,99] = be 20 0x8eb208f7e05d987a9b044a8e98c6b087f15a0bfc := by + decide +kernel +example : execute .cancun 1 [] 3000 = .ok (.success,[],0) := by rfl +example : execute .osaka 256 [] 6899 = .ok (.outOfGas,[],0) := by rfl +example : execute .prague 12 [] 0 = .ok (.exception,[],0) := by rfl +example : execute .osaka 5 (be 32 1025 ++ be 32 0 ++ be 32 0) 499 = + .ok (.outOfGas,[],0) := by rfl + +end SolarTV.Precompiles diff --git a/tv/SolarTV/EVMIR/Precompiles/Signatures.lean b/tv/SolarTV/EVMIR/Precompiles/Signatures.lean new file mode 100644 index 00000000..eba6c579 --- /dev/null +++ b/tv/SolarTV/EVMIR/Precompiles/Signatures.lean @@ -0,0 +1,56 @@ +import SolarTV.EVMIR.Precompiles.Curve + +/-! ECRECOVER and EIP-7951 P256VERIFY. Both validate their scalar and point +encodings before curve arithmetic. ECRECOVER accepts high s and right-pads its +128-byte input; invalid recovery succeeds with empty output. P256VERIFY requires +exactly 160 bytes and also returns empty output for an invalid signature. +https://eips.ethereum.org/EIPS/eip-7951 -/ + +namespace SolarTV.Precompiles.Signatures +open EVM.State + +def k1p : Nat := 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f +def k1n : Nat := 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 +def k1g : Point Nat := affine (fp k1p) + 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798 + 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8 + +def recover (input : List Byte) : List Byte := Id.run do + let hash := readBE input 0 32 + let v := readBE input 32 32 + let r := readBE input 64 32 + let s := readBE input 96 32 + if (v != 27 && v != 28) || r = 0 || r ≥ k1n || s = 0 || s ≥ k1n then return [] + let f := fp k1p + let some y := sqrt k1p (f.add (f.mul (f.square r) r) 7) | return [] + let y := if y%2 = v-27 then y else k1p-y + let point := affine f r y + let combined := add f 0 (multiply f 0 point s) (multiply f 0 k1g (k1n - hash%k1n)) + let some (x,y) := normalize f (multiply f 0 combined (powMod r (k1n-2) k1n)) | return [] + let digest := Keccak.hash (be 32 x ++ be 32 y) + return be 32 ((digest.setWidth 160).toNat) + +def p256p : Nat := 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff +def p256n : Nat := 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551 +def p256a : Nat := p256p-3 +def p256b : Nat := 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b +def p256g : Point Nat := affine (fp p256p) + 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296 + 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5 + +def verify (input : List Byte) : List Byte := Id.run do + if input.length != 160 then return [] + let hash := readBE input 0 32 + let r := readBE input 32 32; let s := readBE input 64 32 + let x := readBE input 96 32; let y := readBE input 128 32 + if r = 0 || s = 0 || r ≥ p256n || s ≥ p256n || x ≥ p256p || y ≥ p256p then return [] + let f := fp p256p + let q := affine f x y + if !onCurve f p256a p256b q then return [] + let inverse := powMod s (p256n-2) p256n + let point := add f p256a (multiply f p256a p256g (hash*inverse%p256n)) + (multiply f p256a q (r*inverse%p256n)) + let some (x,_) := normalize f point | return [] + return if x%p256n = r then be 32 1 else [] + +end SolarTV.Precompiles.Signatures diff --git a/tv/SolarTV/EVMIR/Program.lean b/tv/SolarTV/EVMIR/Program.lean new file mode 100644 index 00000000..a9c827bb --- /dev/null +++ b/tv/SolarTV/EVMIR/Program.lean @@ -0,0 +1,196 @@ +import SolarTV.Machine +import SolarTV.EVMIR.Memory + +/-! Scheduled EVM IR programs as a layer. + +A program is a list of blocks of instructions over one stack, run with the checked stack +operations and memory instructions of [Memory.lean](Memory.lean) (`SolarTV.EVM.Memory.Op`) +through `stepOp`, which runs them on `Machine.Mem`; `stepOp_project` shows it is +`SolarTV.EVM.Memory.step` on the projection. Effects pop their operands, top first, and +push their result. Static transfers are fused with their label push: `jump b` and +`jumpi b` (the condition on top) need room for the label. A `jumpi` not taken goes on +with the rest of its block, as EVM IR's `push bbN; jumpi` does in the middle of a block, +and at the end of a block falls through to the next one. Running off the end of a block +enters the next one, and past the last block the program stops, as the EVM does past its +code. Block numbers are EVM IR's `BlockId`s, its layout order, as `-Zemit-lean-stages` +writes them. An internal call pushes the label of the block it returns to as a value +(`pushLabel`), and the callee returns with a dynamic `jump` (`jumpDyn`) to the label on top +of the stack. A conditional jump whose label is not pushed right before it (`jumpiDyn`), as +when blocks that share their tail jump to labels their predecessors pushed, takes the label on +top of the stack and the condition below it. A jump table (`jumpTable`) jumps to the block its +index, on top of the stack, numbers; EVM IR requires the index to be in range, and here an index +past the table halts. The label of a block is its number here, where the bytecode has its offset; no +observable shows a label. A dynamic jump to a word that numbers no block is an exceptional +halt, as a jump to a byte that is no `JUMPDEST`. A stack failure is an exceptional +halt, which observes as `invalid`. Each block costs one unit of fuel. -/ + +namespace SolarTV.EVM.Program + +open EvmRules Machine + +inductive Instr where + | op (op : EVM.Memory.Op) + | effect (effect : Effect) (arity : Nat) + | jump (target : Nat) + | jumpi (target : Nat) + /-- The label of a block as a value. -/ + | pushLabel (target : Nat) + /-- A jump to the label on top of the stack. -/ + | jumpDyn + /-- A jump to the label on top of the stack when the word below it is nonzero. -/ + | jumpiDyn + /-- A jump to the block the index on top of the stack numbers in the table (`indexed_jump`); + an index past the table is an exceptional halt. -/ + | jumpTable (targets : List Nat) + | stop | ret | revert | invalid + +structure Program where + blocks : List (List Instr) + +/-- `SolarTV.EVM.Memory.step` on memory of every byte. -/ +def stepOp (ctx : Context) (op : EVM.Memory.Op) (stack : Stack) (m : Mem) : + Except Failure (Stack × Mem) := + if stack.length > 1024 then .error .overflow + else match op, stack with + | .stack op, stack => (stepChecked ctx op stack).map (fun next => (next, m)) + | .load, offset :: rest => .ok (m.load offset.toNat :: rest, m.expand offset.toNat 32) + | .store, offset :: value :: rest => .ok (rest, m.store offset.toNat value) + | .storeByte, offset :: value :: rest => .ok (rest, m.storeByte offset.toNat value) + | .size, stack => + if stack.length + 1 > 1024 then .error .overflow else .ok (m.msize :: stack, m) + | _, _ => .error .underflow + +/-- A load reads inside the 256-byte projection. `stepOp` does not run copies or hashes +on `Machine.Mem`, so the projection covers neither. -/ +def InBounds : EVM.Memory.Op → Stack → Prop + | .load, offset :: _ => offset.toNat + 32 ≤ 256 + | .copy, _ | .hash, _ => False + | _, _ => True + +theorem stepOp_project (ctx : Context) (op : EVM.Memory.Op) (stack : Stack) (m : Mem) + (bounded : InBounds op stack) : + (stepOp ctx op stack m).map (fun next => (next.1, next.2.project)) = + EVM.Memory.step ctx op stack m.project := by + unfold stepOp EVM.Memory.step + split + · rfl + · cases op with + | stack op => + show Except.map _ (Except.map _ (stepChecked ctx op stack)) = + Except.map _ (stepChecked ctx op stack) + cases stepChecked ctx op stack <;> rfl + | load => + cases stack with + | nil => rfl + | cons offset rest => + simp only [InBounds] at bounded + simp only [Except.map, Mem.project_load m _ bounded, Mem.project_expand] + | store => + match stack with + | [] | [_] => rfl + | offset :: value :: rest => simp only [Except.map, Mem.project_store] + | storeByte => + match stack with + | [] | [_] => rfl + | offset :: value :: rest => simp only [Except.map, Mem.project_storeByte] + | size => + by_cases h : stack.length + 1 > 1024 <;> simp [h, Except.map, Mem.project_msize] + | copy => exact absurd bounded (by cases stack <;> simp [InBounds]) + | hash => exact absurd bounded (by cases stack <;> simp [InBounds]) + +def context (o : Oracle) (call : Call) (s : State) : Context := + ⟨BitVec.ofNat 256 call.calldata.size, o.env "returndatasize" s.world []⟩ + +def output (s : State) (stack : Stack) (reverted : Bool) : Halt × State := + match stack with + | offset :: size :: _ => + let memory := s.memory.expand offset.toNat size.toNat + let data := memory.read offset.toNat size.toNat + ((if reverted then .revert data else .ret data), { s with memory }) + | _ => (.invalid, s) + +/-- A block's instructions from block `b`: its end, or the next block and its stack. -/ +def exec (o : Oracle) (call : Call) (b : Nat) : + List Instr → Stack → State → (Halt × State) ⊕ (Nat × Stack × State) + | [], stack, s => .inr (b + 1, stack, s) + | .op op :: rest, stack, s => + match stepOp (context o call s) op stack s.memory with + | .error _ => .inl (.invalid, s) + | .ok (stack, memory) => exec o call b rest stack { s with memory } + | .effect effect arity :: rest, stack, s => + if stack.length < arity then .inl (.invalid, s) + else match effect.apply o call (stack.take arity) s with + | none => .inl (.invalid, s) + | some (result, s) => + let stack := match result with + | some value => value :: stack.drop arity + | none => stack.drop arity + if stack.length > 1024 then .inl (.invalid, s) else exec o call b rest stack s + | .jump target :: _, stack, s => + if stack.length + 1 > 1024 then .inl (.invalid, s) else .inr (target, stack, s) + | .jumpi target :: rest, stack, s => + if stack.length + 1 > 1024 then .inl (.invalid, s) + else match stack with + | condition :: stack => + if condition = 0 then exec o call b rest stack s else .inr (target, stack, s) + | [] => .inl (.invalid, s) + | .pushLabel target :: rest, stack, s => + if stack.length + 1 > 1024 then .inl (.invalid, s) + else exec o call b rest (BitVec.ofNat 256 target :: stack) s + | .jumpDyn :: _, stack, s => + match stack with + | target :: stack => .inr (target.toNat, stack, s) + | [] => .inl (.invalid, s) + | .jumpiDyn :: rest, stack, s => + match stack with + | target :: condition :: stack => + if condition = 0 then exec o call b rest stack s else .inr (target.toNat, stack, s) + | _ => .inl (.invalid, s) + | .jumpTable targets :: _, stack, s => + match stack with + | index :: stack => + match targets[index.toNat]? with + | some target => .inr (target, stack, s) + | none => .inl (.invalid, s) + | [] => .inl (.invalid, s) + | .stop :: _, _, s => .inl (.stop, s) + | .ret :: _, stack, s => .inl (output s stack false) + | .revert :: _, stack, s => .inl (output s stack true) + | .invalid :: _, _, s => .inl (.invalid, s) + +def block (o : Oracle) (call : Call) (p : Program) : + Nat × Stack × State → Option ((Halt × State) ⊕ (Nat × Stack × State)) + | (b, stack, s) => + match p.blocks[b]? with + -- NOTE: running off the last block reaches the number past it, where the program stops; + -- a dynamic jump to that number stops too, where the bytecode's jump to its end fails. + -- Labels only name blocks, so no exported program jumps there. + | none => some (.inl (if b = p.blocks.length then .stop else .invalid, s)) + | some instrs => some (exec o call b instrs stack s) + +def run (o : Oracle) (p : Program) (call : Call) (fuel : Nat) : Option (Halt × State) := + iterate (block o call p) fuel (0, [], State.initial call) + +def layer : Layer where + Prog := Program + run := run + mono _ _ _ n r := iterate_mono _ n _ r + +/-- The fuel-free semantics of scheduled EVM IR under an oracle. -/ +noncomputable def sem (o : Oracle) : Sem := layer.sem o + +theorem sem_failure (o : Oracle) (p : Program) (call : Call) (obs : Observable) + (ran : (sem o).run p call = some obs) (failed : obs.success = false) : + obs.logs = [] ∧ obs.storage = slotValue call.storage := by + obtain ⟨_, _, logs, storage, _⟩ := layer.sem_failure o p call obs ran failed + exact ⟨logs, storage⟩ + +theorem failureConvention (o : Oracle) : (sem o).FailureConvention := layer.failureConvention o + +/-- A program of one block that halts runs it at fuel one. -/ +theorem run_straight (o : Oracle) (call : Call) (instrs : List Instr) (n : Nat) + (result : Halt × State) (halts : exec o call 0 instrs [] (State.initial call) = .inl result) : + run o ⟨[instrs]⟩ call (n + 1) = some result := by + simp only [run, iterate, block, List.getElem?_cons_zero, halts] + +end SolarTV.EVM.Program diff --git a/tv/SolarTV/EVMIR/StackSafety.lean b/tv/SolarTV/EVMIR/StackSafety.lean new file mode 100644 index 00000000..fb784469 --- /dev/null +++ b/tv/SolarTV/EVMIR/StackSafety.lean @@ -0,0 +1,75 @@ +import SolarTV.EVMIR.Ops + +/-! Exceptional stack behavior of the bounded EVM window machine. +These lemmas use symbolic tails at the full 1024-word boundary, following +EVMYulLean EVM/Semantics.lean:450-471. Terminal halts ignore leftover words; +an earlier underflow or overflow still terminates execution immediately. -/ + +namespace SolarTV.EVM +open EvmRules + +theorem pop_underflows (ctx : Context) : stepChecked ctx .pop [] = .error .underflow := rfl + +theorem dup_underflows (ctx : Context) (value : Word) : + stepChecked ctx (.dup 1) [value] = .error .underflow := rfl + +theorem swap_underflows (ctx : Context) (value : Word) : + stepChecked ctx (.swap 0) [value] = .error .underflow := rfl + +theorem push_at_limit (ctx : Context) (stack : Stack) (value : Word) + (full : stack.length = 1024) : + stepChecked ctx (.push value) stack = .error .overflow := by + simp [stepChecked, step, full] + +theorem dup_at_limit (ctx : Context) (value : Word) (rest : Stack) + (full : rest.length = 1023) : + stepChecked ctx (.dup 0) (value :: rest) = .error .overflow := by + simp [stepChecked, step, full] + +theorem swap_at_limit (ctx : Context) (a b : Word) (rest : Stack) + (full : rest.length = 1022) : + stepChecked ctx (.swap 0) (a :: b :: rest) = .ok (b :: a :: rest) := by + simp [stepChecked, step, full] + +theorem push_pop_cannot_recover (ctx : Context) (stack : Stack) (value : Word) + (full : stack.length = 1024) : + execute ctx [.push value, .pop] .stop stack = .failed .overflow := by + simp [execute, push_at_limit ctx stack value full] + +theorem dropping_full_push_pop_changes_outcome (ctx : Context) (stack : Stack) (value : Word) + (full : stack.length = 1024) : + execute ctx [.push value, .pop] .stop stack ≠ execute ctx [] .stop stack := by + rw [push_pop_cannot_recover ctx stack value full] + simp [execute, finish, full] + +theorem full_stack_can_halt (stack : Stack) (full : stack.length = 1024) : + finish .stop stack = .success := by simp [finish, full] + +theorem label_push_can_overflow (stack : Stack) (full : stack.length = 1024) : + finish (.jump 1) stack = .failed .overflow := by simp [finish, full] + +theorem empty_return_needs_two_words (value : Word) : + finish .returnEmpty [value] = .failed .underflow := rfl + +theorem empty_return_discards_stack (offset : Word) (rest : Stack) + (legal : rest.length ≤ 1022) : + finish .returnEmpty (offset :: 0 :: rest) = .success := by + simp [finish] + omega + +theorem untaken_branch_executes_stop (destination : Word) (rest : Stack) + (legal : rest.length ≤ 1022) : + finish (.branchStop destination) (0 :: rest) = .success := by + have h1 : ¬ (rest.length + 1 > 1024) := by omega + have h2 : ¬ (rest.length + 1 + 1 > 1024) := by omega + simp [finish, h1, h2] + +theorem taken_branch_leaves_the_block (destination condition : Word) (rest : Stack) + (nonzero : condition ≠ 0) (legal : rest.length ≤ 1022) : + finish (.branchStop destination) (condition :: rest) = .edge destination rest := by + have h1 : ¬ (rest.length + 1 > 1024) := by omega + have h2 : ¬ (rest.length + 1 + 1 > 1024) := by omega + simp [finish, h1, h2] + exact nonzero + +end SolarTV.EVM diff --git a/tv/SolarTV/EVMIR/State/Create.lean b/tv/SolarTV/EVMIR/State/Create.lean new file mode 100644 index 00000000..d576d078 --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Create.lean @@ -0,0 +1,42 @@ +import SolarTV.EVMIR.State.Types + +/-! CREATE and CREATE2 address derivation, collision and deployment rules. +RLP is encoded directly for the creator's twenty-byte address and a 64-bit nonce. +Initcode is executed by the same nested evaluator as ordinary calls. A creation +checkpoint is taken after the creator's nonce bump and destination warming, so +constructor rollback does not undo either caller-side effect. +https://eips.ethereum.org/EIPS/eip-684 +https://eips.ethereum.org/EIPS/eip-1014 +https://eips.ethereum.org/EIPS/eip-2681 +https://eips.ethereum.org/EIPS/eip-3860 -/ + +namespace SolarTV.EVM.State +open EvmRules + +def addressBytes (address : Address) : List Byte := (wordBytes (address.setWidth 256)).drop 12 + +def nonceBytes (nonce : Nat) : List Byte := + ((wordBytes (BitVec.ofNat 256 nonce)).dropWhile (fun b => b == 0)) + +def encodedNonce (nonce : Nat) : List Byte := + if nonce = 0 then [0x80] + else if nonce < 128 then [BitVec.ofNat 8 nonce] + else let bytes := nonceBytes nonce + BitVec.ofNat 8 (128 + bytes.length) :: bytes + +def createAddress (creator : Address) (nonce : Nat) : Address := + let payload := [0x94] ++ addressBytes creator ++ encodedNonce nonce + (Keccak.hash (BitVec.ofNat 8 (192 + payload.length) :: payload)).setWidth 160 + +def create2Address (creator : Address) (salt : Word) (initcode : List Byte) : Address := + (Keccak.hash ([0xff] ++ addressBytes creator ++ wordBytes salt ++ wordBytes (Keccak.hash initcode))).setWidth 160 + +def collision (world : Journal) (address : Address) : Bool := + let old := account world address + old.nonce != 0 || !old.code.isEmpty + +def validDeployedCode (fork : Fork) (code : List Byte) : Bool := + (!fork.atLeast .spuriousDragon || code.length ≤ 24576) && + (!fork.atLeast .london || code[0]?.getD 0 != 0xef) + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Decode.lean b/tv/SolarTV/EVMIR/State/Decode.lean new file mode 100644 index 00000000..a0cb484f --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Decode.lean @@ -0,0 +1,52 @@ +import SolarTV.EVMIR.State.Create + +/-! Bytecode decoding for explicit-world execution. PUSH payload bytes are not +instructions or jump destinations. Availability and static prices are supplied +from the compiler's reflected opcode schema and bound into the proof input. +Pure instruction values use the separately tested word model. -/ + +namespace SolarTV.EVM.State +open EvmRules + +def pureOp : Nat → Option EVM.Op + | 0x01 => some .add | 0x02 => some .mul | 0x03 => some .sub + | 0x04 => some .div | 0x05 => some .sdiv | 0x06 => some .mod | 0x07 => some .smod + | 0x08 => some .addmod | 0x09 => some .mulmod | 0x0a => some .exp + | 0x0b => some .signextend | 0x10 => some .lt | 0x11 => some .gt + | 0x12 => some .slt | 0x13 => some .sgt | 0x14 => some .eq + | 0x15 => some .iszero | 0x16 => some .and | 0x17 => some .or | 0x18 => some .xor + | 0x19 => some .not | 0x1a => some .byte | 0x1b => some .shl | 0x1c => some .shr + | 0x1d => some .sar | 0x1e => some .clz + | _ => none + +def jumpDestinations (fuel : Nat) (code : List Byte) (pc : Nat := 0) : List Nat := + match fuel with + | 0 => [] + | fuel + 1 => + if pc ≥ code.length then [] else + let byte := code[pc]?.getD 0 |>.toNat + let next := pc + 1 + if 0x60 ≤ byte ∧ byte ≤ 0x7f then byte - 0x5f else 0 + let rest := jumpDestinations fuel code next + if byte = 0x5b then pc :: rest else rest + +def validJump (code : List Byte) (target : Word) : Bool := + (jumpDestinations code.length code).contains target.toNat + +def pushValue (code : List Byte) (pc count : Nat) : Word := + (readBytes code (pc + 1) count).foldl (fun value byte => (value <<< 8) ||| byte.setWidth 256) 0 + +/-- Fork-specific precompile activation, shared by decoding and execution. -/ +def precompile (fork : Fork) (address : Address) : Bool := + let n := address.toNat + (1 ≤ n && n ≤ 4) || + (fork.atLeast .byzantium && 5 ≤ n && n ≤ 8) || + (fork.atLeast .istanbul && n = 9) || + (fork.atLeast .cancun && n = 10) || + (fork.atLeast .prague && 11 ≤ n && n ≤ 17) || + (fork.atLeast .osaka && n = 256) + +def dead (world : Journal) (address : Address) : Bool := + let a := account world address + a.nonce == 0 && a.balance == 0 && a.code.isEmpty + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Delegation.lean b/tv/SolarTV/EVMIR/State/Delegation.lean new file mode 100644 index 00000000..9f5602ab --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Delegation.lean @@ -0,0 +1,36 @@ +import SolarTV.EVMIR.State.Decode + +/-! EIP-7702 execution after authorization processing. Exactly 23-byte designators +resolve once from Prague onward. The resolved target access costs 100/2600 gas, +after warming the authority and before the EIP-150 gas split, even if a call is +later rejected for balance/depth. Resolution warmth survives child revert. +Code introspection reads the original account bytes; execution uses the resolved +image. Delegation to a precompile does not invoke it. A second designator is +executed as ordinary (invalid) bytecode, not recursively resolved. +Authorization signatures, transaction intrinsic gas and authorization refunds +precede this entry model; the fixture supplies their resulting account state. +https://eips.ethereum.org/EIPS/eip-7702#delegation-indicator -/ + +namespace SolarTV.EVM.State + +structure ExecutionCode where + address : Address + bytes : List Byte + delegated : Bool + +def delegationTarget (fork : Fork) (code : List Byte) : Option Address := + if fork.atLeast .prague && code.length = 23 && code.take 3 == [0xef,0x01,0x00] then + some ((readWord (List.replicate 12 0 ++ code.drop 3) 0).setWidth 160) + else none + +def executionCode (fork : Fork) (world : Journal) (destination : Address) : + ExecutionCode × Nat × Journal := + let code := (account world destination).code + let world := warmAddress world destination + match delegationTarget fork code with + | none => (⟨destination,code,false⟩,0,world) + | some target => + let price := if world.warmAddresses.contains target then 100 else 2600 + (⟨target,(account world target).code,true⟩,price,warmAddress world target) + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Environment.lean b/tv/SolarTV/EVMIR/State/Environment.lean new file mode 100644 index 00000000..a4ea820e --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Environment.lean @@ -0,0 +1,22 @@ +import SolarTV.EVMIR.State.Decode + +/-! Explicit environment reads for complete-entry execution. BLOCKHASH accepts +only the previous 256 blocks, excluding the current block, without word-wrap. +The Paris transition selects randomness instead of difficulty; opcode activation +is checked by the reflected fork table before reading context. Blob indices are +full words, so enormous indices return zero rather than truncating to a host index. +SLOTNUM widens the consensus uint64 value. History and blobs are fixture inputs, +not hash oracles inferred from the IR being validated. +https://eips.ethereum.org/EIPS/eip-4399 +https://eips.ethereum.org/EIPS/eip-4844 +https://eips.ethereum.org/EIPS/eip-7843 -/ + +namespace SolarTV.EVM.State +open EvmRules + +export SolarTV.Execution (blockHash) + +def environmentValue (cfg : Config) (opcode : Nat) (argument : Word) : Word := + SolarTV.Execution.environmentValue cfg.fork cfg.block opcode argument + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Interpreter.lean b/tv/SolarTV/EVMIR/State/Interpreter.lean new file mode 100644 index 00000000..1c16a6fb --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Interpreter.lean @@ -0,0 +1,314 @@ +import SolarTV.EVMIR.State.Selfdestruct +import SolarTV.EVMIR.Precompiles.Execute +import SolarTV.EVMIR.State.Environment +import SolarTV.EVMIR.State.Delegation +import SolarTV.EVMIR.State.Messages + +/-! Gas-charged bytecode execution with real nested frames and constructors. +Every frame owns its stack, memory and return-data buffer. Accounts, original +storage and access sets are transaction-wide and journaled at call boundaries. +Unsupported opcodes and finite evaluator limits are model errors; +they never become EVM exceptions and cannot prove a pair correct. + +The explicit-world mode starts after transaction validation, with zero root +value and explicit transaction/block context. The CLI admits Istanbul through +Osaka, plus Amsterdam's environment/scalar/memory fragment. Its two-resource +state/account/call gas remains unsupported. +Calls follow EIP-150/214/2929; creation follows EIP-161/170/684/1014/2681/3541/3860. +https://eips.ethereum.org/EIPS/eip-150 +https://eips.ethereum.org/EIPS/eip-2929 -/ + +namespace SolarTV.EVM.State +open EvmRules + +inductive Step where + | next (world : Journal) (frame : Frame) + | done (result : Result) + | call (message : Calls.Message) (outOffset outSize requested : Nat) + (code : ExecutionCode) (world : Journal) (frame : Frame) + | create (salt : Option Word) (value : Word) (initcode : List Byte) + (world : Journal) (frame : Frame) + +abbrev Action := Except String Step + +def stepFailed (world : Journal) : Action := .ok (.done ⟨.exception, [], world, 0, 0⟩) + +def stepExhausted (world : Journal) : Action := .ok (.done ⟨.outOfGas, [], world, 0, 0⟩) + +def next (world : Journal) (frame : Frame) (stack : List Word) : Action := + .ok (.next world {frame with pc := frame.pc + 1, stack}) + +def available (cfg : Config) (opcode : Nat) : Opcode := + cfg.opcodes[opcode]?.getD ⟨false, 0, 0, 0, 0⟩ + +/-- Charge expansion before allocating host memory. Natural address sums do not wrap. -/ +def withMemory (world : Journal) (frame : Frame) (charge offset count : Nat) + (continuation : Frame → Action) : Action := + let total := charge + memoryCharge frame.memory offset count + if frame.gas < total then stepExhausted world else do + let memory ← expand frame.memory offset count + continuation {frame with memory, gas := frame.gas - total} + +def instruction (cfg : Config) (world : Journal) (frame : Frame) : Action := + if frame.pc ≥ frame.code.length then .ok (.done ⟨.success, [], world, frame.gas, 0⟩) else + let opcode := frame.code[frame.pc]?.getD 0 |>.toNat + let info := available cfg opcode + if !info.available then stepFailed world + -- Amsterdam's environment/memory fragment is admitted independently of the + -- two-resource gas model. Account, storage and call operations remain errors. + else if cfg.fork.atLeast .amsterdam && + ([0x31,0x3b,0x3c,0x3f,0x47,0x54,0x55,0x5c,0x5d,0xf0,0xf1,0xf2,0xf4,0xf5,0xfa,0xff].contains opcode || + (0xa0 ≤ opcode && opcode ≤ 0xa4)) then + .error "Amsterdam state/account/call gas is not modeled" + else if frame.stack.length < info.inputs || frame.stack.length - info.inputs + info.outputs > 1024 then + stepFailed world + else if let some op := pureOp opcode then + let dynamic := if opcode = 0x0a then + info.dynamic * ((256 - (frame.stack[1]?.getD 0).clz.toNat + 7) / 8) else 0 + if frame.gas < info.base + dynamic then stepExhausted world else + match EVM.step ⟨BitVec.ofNat 256 frame.environment.input.length, + BitVec.ofNat 256 frame.returnData.length⟩ op frame.stack with + | none => stepFailed world + | some stack => next world {frame with gas := frame.gas - info.base - dynamic} stack + else if 0x60 ≤ opcode ∧ opcode ≤ 0x7f then + if frame.gas < info.base then stepExhausted world else + .ok (.next world {frame with + pc := frame.pc + 1 + (opcode - 0x5f) + stack := pushValue frame.code frame.pc (opcode - 0x5f) :: frame.stack + gas := frame.gas - info.base}) + else if 0x80 ≤ opcode ∧ opcode ≤ 0x9f then + let op := if opcode < 0x90 then EVM.Op.dup ⟨opcode - 0x80, by omega⟩ + else EVM.Op.swap ⟨opcode - 0x90, by omega⟩ + if frame.gas < info.base then stepExhausted world else + match EVM.step ⟨0, 0⟩ op frame.stack with + | none => stepFailed world + | some stack => next world {frame with gas := frame.gas - info.base} stack + else + let values := frame.stack.take info.inputs + let rest := frame.stack.drop info.inputs + let a := values[0]?.getD 0 + let b := values[1]?.getD 0 + let c := values[2]?.getD 0 + match opcode with + | 0x00 => .ok (.done ⟨.success, [], world, frame.gas, 0⟩) + | 0xfe => stepFailed world + | 0x40 | 0x41 | 0x42 | 0x43 | 0x44 | 0x45 | 0x46 | 0x48 | 0x49 | 0x4a | 0x4b => + if frame.gas < info.base then stepExhausted world + else next world {frame with gas := frame.gas - info.base} + (environmentValue cfg opcode a :: rest) + | 0x20 => withMemory world frame (info.base + info.dynamic * ((b.toNat + 31) / 32)) a.toNat b.toNat fun frame => + next world frame (Keccak.hash (readBytes frame.memory a.toNat b.toNat) :: rest) + | 0x30 | 0x32 | 0x33 | 0x34 | 0x36 | 0x38 | 0x3a | 0x3d | 0x47 | 0x58 | 0x59 | 0x5a | 0x5f => + if frame.gas < info.base then stepExhausted world else + let value := match opcode with + | 0x30 => frame.environment.address.setWidth 256 + | 0x32 => frame.environment.origin.setWidth 256 + | 0x33 => frame.environment.caller.setWidth 256 + | 0x34 => frame.environment.value + | 0x36 => BitVec.ofNat 256 frame.environment.input.length + | 0x38 => BitVec.ofNat 256 frame.code.length + | 0x3a => frame.environment.gasPrice + | 0x3d => BitVec.ofNat 256 frame.returnData.length + | 0x47 => (account world frame.environment.address).balance + | 0x58 => BitVec.ofNat 256 frame.pc + | 0x59 => BitVec.ofNat 256 frame.memory.length + | 0x5a => BitVec.ofNat 256 (frame.gas - info.base) + | _ => 0 + next world {frame with gas := frame.gas - info.base} (value :: rest) + | 0x31 | 0x3b | 0x3f => + let address := a.setWidth 160 + if opcode != 0x31 && cfg.unknownCode == some address then + .error "MIR root runtime code is unknown" else + let charge := if cfg.fork.atLeast .berlin && world.warmAddresses.contains address then 100 else info.base + if frame.gas < charge then stepExhausted world else + let value := if opcode = 0x31 then (account world address).balance + else if opcode = 0x3b then BitVec.ofNat 256 (account world address).code.length + else if world.accounts.any (fun a => a.address == address) then Keccak.hash (account world address).code else 0 + next (warmAddress world address) {frame with gas := frame.gas - charge} (value :: rest) + | 0x35 => + if frame.gas < info.base then stepExhausted world + else next world {frame with gas := frame.gas - info.base} + (readWord frame.environment.input a.toNat :: rest) + | 0x3c => + let owner := a.setWidth 160 + if cfg.unknownCode == some owner then .error "MIR root runtime code is unknown" else + let count := (values[3]?.getD 0).toNat + let base := if cfg.fork.atLeast .berlin && world.warmAddresses.contains owner then 100 else info.base + -- The EXTCODE gas class reflects account access; copying also pays the + -- same per-word price as CALLDATACOPY (Yellow Paper W_copy). + let copyWord := (available cfg 0x37).dynamic + withMemory world frame (base + copyWord * ((count+31)/32)) b.toNat count fun frame => + let bytes := readBytes (account world owner).code c.toNat count + next (warmAddress world owner) {frame with memory := writeBytes frame.memory b.toNat bytes} rest + | 0x37 | 0x39 | 0x3e => + if opcode = 0x3e && b.toNat + c.toNat > frame.returnData.length then stepFailed world + else withMemory world frame (info.base + info.dynamic * ((c.toNat + 31) / 32)) a.toNat c.toNat fun frame => + let source := if opcode = 0x37 then frame.environment.input + else if opcode = 0x39 then frame.code else frame.returnData + let memory := writeBytes frame.memory a.toNat (readBytes source b.toNat c.toNat) + next world {frame with memory} rest + | 0x50 => + if frame.gas < info.base then stepExhausted world + else next world {frame with gas := frame.gas - info.base} rest + | 0x51 | 0x52 | 0x53 => withMemory world frame info.base a.toNat (if opcode = 0x53 then 1 else 32) fun frame => + if opcode = 0x51 then next world frame (readWord frame.memory a.toNat :: rest) + else + let bytes := if opcode = 0x53 then [b.setWidth 8] else wordBytes b + next world {frame with memory := writeBytes frame.memory a.toNat bytes} rest + | 0x54 | 0x55 | 0x5c | 0x5d => + let owner := frame.environment.address + let old := account world owner + let transient := opcode = 0x5c || opcode = 0x5d + let store := opcode = 0x55 || opcode = 0x5d + let current := slotsRead (if transient then old.transient else old.storage) a + let original := slotsRead ((world.original.find? (fun x => x.address == owner)).getD {address := owner}).storage a + let price := if transient then Storage.Price.mk 100 0 + else if store then Storage.writePrice cfg.fork (world.warmSlots.contains (owner, a)) original current b + else Storage.Price.mk (Storage.readPrice cfg.fork (world.warmSlots.contains (owner, a))) 0 + if store && frame.environment.isStatic then stepFailed world + else if opcode = 0x55 && cfg.fork.atLeast .istanbul && frame.gas ≤ 2300 then stepExhausted world + else if frame.gas < price.gas then stepExhausted world else + let world := if transient then world else warmSlot world owner a + let world := if !store then world else + putAccount {world with refund := world.refund + price.refund} + (if transient then {old with transient := slotsWrite old.transient a b} + else {old with storage := slotsWrite old.storage a b}) + next world {frame with gas := frame.gas - price.gas} (if store then rest else current :: rest) + | 0x56 | 0x57 => + if frame.gas < info.base then stepExhausted world + else if opcode = 0x57 && b == 0 then next world {frame with gas := frame.gas - info.base} rest + else if !validJump frame.code a then stepFailed world + else .ok (.next world {frame with stack := rest, pc := a.toNat, gas := frame.gas - info.base}) + | 0x5b => + if frame.gas < info.base then stepExhausted world + else next world {frame with gas := frame.gas - info.base} rest + | 0x5e => + let charge := info.base + info.dynamic * ((c.toNat + 31) / 32) + let sourceGrowth := memoryCost (max (requiredWords frame.memory b.toNat c.toNat) + (requiredWords frame.memory a.toNat c.toNat)) - memoryCost (requiredWords frame.memory a.toNat c.toNat) + withMemory world frame (charge + sourceGrowth) a.toNat c.toNat fun frame => do + let memory ← expand frame.memory b.toNat c.toNat + let bytes := readBytes memory b.toNat c.toNat + next world {frame with memory := writeBytes memory a.toNat bytes} rest + | 0xf3 | 0xfd => withMemory world frame info.base a.toNat b.toNat fun frame => + .ok (.done ⟨if opcode = 0xfd then .reverted else .success, + readBytes frame.memory a.toNat b.toNat, world, frame.gas, 0⟩) + | 0xf1 | 0xf2 | 0xf4 | 0xfa => + let kind := if opcode = 0xf1 then Calls.Kind.call else if opcode = 0xf2 then .callcode + else if opcode = 0xf4 then .delegatecall else .staticcall + let explicitValue := opcode = 0xf1 || opcode = 0xf2 + let value := if explicitValue then c else 0 + let inputOffset := (values[if explicitValue then 3 else 2]?.getD 0).toNat + let inputSize := (values[if explicitValue then 4 else 3]?.getD 0).toNat + let outOffset := (values[if explicitValue then 5 else 4]?.getD 0).toNat + let outSize := (values[if explicitValue then 6 else 5]?.getD 0).toNat + let destination := b.setWidth 160 + let base := if cfg.fork.atLeast .berlin && world.warmAddresses.contains destination then 100 else info.base + let valueCharge := if explicitValue && value != 0 then 9000 else 0 + let newAccount := if kind == .call && dead world destination && + (!cfg.fork.atLeast .spuriousDragon || value != 0) then 25000 else 0 + let (code, resolution, entered) := executionCode cfg.fork world destination + if cfg.unknownCode == some code.address then .error "MIR root runtime code is unknown" else + if frame.environment.isStatic && kind == .call && value != 0 then stepFailed world else + withMemory world frame (base + valueCharge + newAccount + resolution) inputOffset inputSize fun frame => + withMemory world frame 0 outOffset outSize fun frame => + .ok (.call ⟨kind, destination, value, readBytes frame.memory inputOffset inputSize⟩ + outOffset outSize a.toNat code entered {frame with stack := rest, pc := frame.pc + 1}) + | 0xf0 | 0xf5 => + let size := c.toNat + if frame.environment.isStatic then stepFailed world + else if cfg.fork.atLeast .shanghai && size > 49152 then stepExhausted world + else + let perWord := (if cfg.fork.atLeast .shanghai then 2 else 0) + if opcode = 0xf5 then 6 else 0 + withMemory world frame (info.base + perWord * ((size + 31) / 32)) b.toNat size fun frame => + .ok (.create (if opcode = 0xf5 then some (values[3]?.getD 0) else none) a + (readBytes frame.memory b.toNat size) world {frame with stack := rest, pc := frame.pc + 1}) + | 0xff => + let beneficiary := a.setWidth 160 + let charge := destructionPrice cfg.fork world frame.environment.address beneficiary + if frame.environment.isStatic then stepFailed world + else if frame.gas < charge then stepExhausted world + else .ok (.done ⟨.success, [], destroy cfg.fork world frame.environment.address beneficiary, + frame.gas - charge, 0⟩) + | opcode => + if 0xa0 ≤ opcode ∧ opcode ≤ 0xa4 then + if frame.environment.isStatic then stepFailed world else + withMemory world frame (info.base + info.dynamic * b.toNat) a.toNat b.toNat fun frame => + let log := World.Log.mk frame.environment.address (values.drop 2) (readBytes frame.memory a.toNat b.toNat) + next {world with logs := world.logs ++ [log]} frame rest + else .error s!"unmodeled world opcode {opcode}" + +/-- Work fuel bounds the evaluator, not the EVM. Exhaustion is unsupported. -/ +def run (fuel : Nat) (cfg : Config) (world : Journal) (frame : Frame) : Run := + match fuel with + | 0 => .error "world instruction/depth evaluation limit" + | fuel + 1 => do + let result ← match ← instruction cfg world frame with + | .done result => pure result + | .next world frame => run fuel cfg world frame + | .call message outOffset outSize requested code world frame => + let checkpoint := warmAddress world message.destination + if frame.environment.depth ≥ 1024 || + ((message.kind == .call || message.kind == .callcode) && + (account world frame.environment.address).balance.ult message.value) then + -- A rejected value-bearing call returns its unspent stipend too. + run fuel cfg checkpoint {frame with + stack := 0 :: frame.stack + returnData := [] + gas := frame.gas + if Calls.hasValue message then 2300 else 0} + else + match Calls.forwardGas cfg.fork frame.gas requested (Calls.hasValue message) with + | none => exhausted checkpoint + | some budget => + let child ← executeCall (run fuel cfg) cfg checkpoint frame.environment message code budget.supplied + let committed := child.world + let data := child.data + let returned := child.gas + let copied := data.take outSize + let resumed ← run (fuel - child.work) cfg committed {frame with + stack := child.value :: frame.stack + memory := writeBytes frame.memory outOffset copied + returnData := data + gas := frame.gas - budget.charged + returned} + pure {resumed with work := resumed.work + child.work} + | .create salt value initcode world frame => + let creator := account world frame.environment.address + if frame.environment.depth ≥ 1024 || creator.balance.ult value || creator.nonce ≥ 2^64 - 1 then + run fuel cfg world {frame with stack := 0 :: frame.stack, returnData := []} + else + let forwarded := if cfg.fork.atLeast .tangerineWhistle then frame.gas - frame.gas / 64 else frame.gas + let child ← executeCreation (run fuel cfg) cfg world frame.environment salt value initcode forwarded + let resumed ← run (fuel - child.work) cfg child.world {frame with + stack := child.value :: frame.stack + returnData := child.data + gas := frame.gas - forwarded + child.gas} + pure {resumed with work := resumed.work + child.work} + return {result with work := result.work + 1} +termination_by fuel +decreasing_by all_goals omega + +/-- Single-step equations keep symbolic execution from unfolding unknown continuations. -/ +theorem run_next (fuel : Nat) {cfg world frame nextWorld nextFrame} + (h : instruction cfg world frame = .ok (.next nextWorld nextFrame)) : + run (fuel + 1) cfg world frame = (do + let result ← run fuel cfg nextWorld nextFrame + return {result with work := result.work + 1}) := by + simp only [run, h, Except.bind, Bind.bind, Except.pure, Pure.pure] + +theorem run_done (fuel : Nat) {cfg world frame result} + (h : instruction cfg world frame = .ok (.done result)) : + run (fuel + 1) cfg world frame = .ok {result with work := result.work + 1} := by + simp only [run, h, Except.bind, Bind.bind, Except.pure, Pure.pure] + +theorem run_error (fuel : Nat) {cfg world frame reason} + (h : instruction cfg world frame = .error reason) : + run (fuel + 1) cfg world frame = .error reason := by + simp only [run, h, Except.bind, Bind.bind] + +/-- Frame rollback keeps parent-side warming/nonce changes in the checkpoint. -/ +def execute (fuel : Nat) (cfg : Config) (world : Journal) (frame : Frame) : Run := do + let result ← run fuel cfg world frame + return if result.stop = .success then {result with world := finalize result.world} else + {result with world, gas := if result.stop = .exception || result.stop = .outOfGas then 0 else result.gas} + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Messages.lean b/tv/SolarTV/EVMIR/State/Messages.lean new file mode 100644 index 00000000..d7720c87 --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Messages.lean @@ -0,0 +1,87 @@ +import SolarTV.EVMIR.State.Selfdestruct +import SolarTV.EVMIR.State.Delegation +import SolarTV.EVMIR.Precompiles.Execute + +/-! Shared execution of prepared call and creation messages. The caller owns +memory access and parent gas pricing/forwarding; this module owns child entry, +state checkpoints and completion. A child is executed by the supplied evaluator, +never an unconstrained result. MIR can use the bytecode evaluator for fixture +accounts without lowering its own program to bytecode. -/ + +namespace SolarTV.EVM.State +open EvmRules + +structure MessageOutcome where + value : Word + data : List Byte + world : Journal + gas : Nat + work : Nat + +abbrev ChildExecutor := Journal → Frame → Run + +def executeCall (execute : ChildExecutor) (cfg : Config) (checkpoint : Journal) + (parent : World.Environment) (message : Calls.Message) (code : ExecutionCode) + (supplied : Nat) : Except String MessageOutcome := do + if cfg.unknownCode == some code.address then .error "MIR root runtime code is unknown" else + if parent.depth ≥ 1024 || + ((message.kind == .call || message.kind == .callcode) && + (account checkpoint parent.address).balance.ult message.value) then + return ⟨0,[],checkpoint,supplied,0⟩ + else + let entered := if message.kind == .call then + (transfer checkpoint parent.address message.destination message.value).getD checkpoint + else checkpoint + let child ← if !code.delegated && precompile cfg.fork message.destination then do + let (stop,data,gas) ← Precompiles.execute cfg.fork message.destination message.input supplied + pure ⟨stop,data,entered,gas,0⟩ + else execute entered { + environment := {Calls.childEnvironment parent message with codeAddress := code.address} + code := code.bytes + gas := supplied} + let failed := child.stop = .exception || child.stop = .outOfGas + return ⟨if child.stop = .success then 1 else 0, + if failed then [] else child.data, + if child.stop = .success then child.world else checkpoint, + if failed then 0 else child.gas,child.work⟩ + +def executeCreation (execute : ChildExecutor) (cfg : Config) (world : Journal) + (parent : World.Environment) (salt : Option Word) (value : Word) + (initcode : List Byte) (supplied : Nat) : Except String MessageOutcome := do + let creator := account world parent.address + if parent.depth ≥ 1024 || creator.balance.ult value || creator.nonce ≥ 2^64 - 1 then + return ⟨0,[],world,supplied,0⟩ + else + let target := match salt with + | none => createAddress creator.address creator.nonce + | some salt => create2Address creator.address salt initcode + let checkpoint := warmAddress (putAccount world {creator with nonce := creator.nonce + 1}) target + if collision checkpoint target then return ⟨0,[],checkpoint,0,0⟩ else + let old := account checkpoint target + let fresh := {old with + nonce := if cfg.fork.atLeast .spuriousDragon then 1 else 0 + code := [] + storage := [] + transient := [] + created := true + destroyed := false} + let entered := putAccount checkpoint fresh + let entered := {entered with original := fresh :: entered.original.filter (fun a => a.address != target)} + let entered := (transfer entered creator.address target value).getD entered + let child ← execute entered { + environment := {parent with + address := target + codeAddress := target + caller := creator.address + value + input := [] + depth := parent.depth + 1} + code := initcode,gas := supplied} + let deposit := 200 * child.data.length + let success := child.stop == .success && validDeployedCode cfg.fork child.data && deposit ≤ child.gas + return ⟨if success then target.setWidth 256 else 0, + if child.stop = .reverted then child.data else [], + if success then putAccount child.world {(account child.world target) with code := child.data} else checkpoint, + if success then child.gas - deposit else if child.stop = .reverted then child.gas else 0,child.work⟩ + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Normalize.lean b/tv/SolarTV/EVMIR/State/Normalize.lean new file mode 100644 index 00000000..37ca6a58 --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Normalize.lean @@ -0,0 +1,35 @@ +import SolarTV.EVMIR.State.Interpreter +import Lean + +/-! Proof-producing execution at a known bytecode position. Symbolic data must not +cause the simplifier to unfold every remaining unit of global work fuel. Reduce +one known instruction and use its proved equation, leaving unknown control flow +opaque. This produces kernel-checkable terms, not native evaluation evidence. -/ + +namespace SolarTV.EVM.State +open Lean Meta Simp + +simproc_decl reduceRun (run _ _ _ _) := fun expression => do + let args := expression.getAppArgs + let some fuel ← getNatValue? args[0]! | return .continue + if fuel = 0 then return .done {expr := ← whnf expression} + let frame ← whnf args[3]! + unless frame.isAppOf ``Frame.mk do return .continue + let step ← mkAppM ``instruction #[args[1]!,args[2]!,args[3]!] + let reduction ← simp step + let reduced ← whnf reduction.expr + let proof ← reduction.getProof + let parameters := #[toExpr (fuel - 1),args[1]!,args[2]!,args[3]!] + let equation ← if reduced.isAppOf ``Except.error then + pure (mkAppN (mkConst ``run_error) (parameters ++ #[reduced.appArg!,proof])) + else if reduced.isAppOf ``Except.ok then + let signal ← whnf reduced.appArg! + if signal.isAppOf ``Step.next then + pure (mkAppN (mkConst ``run_next) (parameters ++ signal.getAppArgs ++ #[proof])) + else if signal.isAppOf ``Step.done then + pure (mkAppN (mkConst ``run_done) (parameters ++ #[signal.appArg!,proof])) + else return .continue + else return .continue + return .visit {expr := (← inferType equation).appArg!,proof? := some equation} + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Observe.lean b/tv/SolarTV/EVMIR/State/Observe.lean new file mode 100644 index 00000000..4e5e806c --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Observe.lean @@ -0,0 +1,81 @@ +import SolarTV.EVMIR.State.Interpreter +import Lean.Data.Json + +/-! Observable transaction effects for explicit-world entry checks. Private memory, +transient storage and access warmth die with the root frame. Persistent accounts, +nonces, balances, deployed code and logs remain visible. The running root's code +is compared through execution, not as an output byte-string, so ordinary code +rewrites do not count as state changes. CODECOPY/EXTCODEHASH still read the actual +before/after root image during execution. + +Model errors are excluded on both sides of a positive proof. Their textual +observations let the host reject a proposed witness before claiming a compiler +counterexample. Gas/refund observations are optional, but execution always pays +gas from the explicit fixture budget. -/ + +namespace SolarTV.EVM.State +open EvmRules + +structure Observation where + stop : Stop + data : List Byte + gas : Nat + refund : Int + accounts : List Account + logs : List World.Log + deriving DecidableEq + +inductive Policy where + | effects | exact | refine + deriving DecidableEq + +export SolarTV.Execution (orderedInsert ordered normalizedSlots) + +def observe (cfg : Config) (policy : Policy) (result : Result) : Observation := + let accounts := result.world.accounts.map (fun a => {a with + code := if a.address == cfg.root then [] else a.code + storage := normalizedSlots a.storage + transient := [] + created := false + destroyed := false}) + ⟨result.stop, result.data, if policy = .effects then 0 else result.gas, + if policy = .effects then 0 else result.world.refund, + ordered (fun a b => a.address.ule b.address) accounts, result.world.logs⟩ + +def equivalent (cfgBefore cfgAfter : Config) (policy : Policy) (before after : Run) : Prop := + match before, after with + | .ok a, .ok b => + if policy = .refine then + (a.stop = .outOfGas ∨ + (observe cfgBefore .effects a = observe cfgAfter .effects b ∧ + a.world.refund = b.world.refund ∧ a.gas ≤ b.gas)) + else observe cfgBefore policy a = observe cfgAfter policy b + | _, _ => False + +instance (a b : Config) (policy : Policy) (before after : Run) : + Decidable (equivalent a b policy before after) := by + unfold equivalent + split <;> infer_instance + +private def wordJson (value : Word) : Lean.Json := .str (toString value.toNat) +private def byteJson (value : Byte) : Lean.Json := Lean.toJson value.toNat + +def describe (cfg : Config) (policy : Policy) (result : Run) : String := + match result with + | .error reason => "unsupported: " ++ reason + | .ok result => + let result := observe cfg policy result + let accounts := result.accounts.map fun a => Lean.Json.arr #[ + .str (toString a.address.toNat), .str (toString a.nonce), wordJson a.balance, + .arr (a.code.map byteJson).toArray, + .arr (a.storage.map (fun entry => Lean.Json.arr #[wordJson entry.1, wordJson entry.2])).toArray] + let logs := result.logs.map fun log => Lean.Json.arr #[ + .str (toString log.address.toNat), .arr (log.topics.map wordJson).toArray, + .arr (log.data.map byteJson).toArray] + let stop := match result.stop with + | .success => "success" | .reverted => "revert" + | .exception => "exception" | .outOfGas => "out-of-gas" + (Lean.Json.arr #[.str stop, .arr (result.data.map byteJson).toArray, + Lean.toJson result.gas, Lean.toJson result.refund, .arr accounts.toArray, .arr logs.toArray]).compress + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Safety.lean b/tv/SolarTV/EVMIR/State/Safety.lean new file mode 100644 index 00000000..469e652b --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Safety.lean @@ -0,0 +1,60 @@ +import SolarTV.EVMIR.State.Observe + +/-! Kernel checks for the entry evaluator's proof boundary and creation rules. +Unsupported execution cannot establish equivalence, and reverted frames restore +their original journal. Address derivation is pinned to EIP-1014's published +vector, independently of the native replay engine. -/ + +namespace SolarTV.EVM.State + +theorem unsupported_not_equivalent (a b : Config) (policy : Policy) + (reason : String) (other : Run) : + ¬ equivalent a b policy (.error reason) other := by + cases other <;> simp [equivalent] + +theorem reverted_entry_restores_world (fuel : Nat) (cfg : Config) + (world changed : Journal) (frame : Frame) (data : List Byte) (gas : Nat) + (work : Nat) + (execution : run fuel cfg world frame = .ok ⟨.reverted, data, changed, gas, work⟩) : + execute fuel cfg world frame = .ok ⟨.reverted, data, world, gas, work⟩ := by + simp only [execute, execution] + rfl + +theorem exception_cannot_refine_to_success (cfg : Config) (world : Journal) : + ¬ equivalent cfg cfg .refine (.ok ⟨.exception, [], world, 0, 0⟩) + (.ok ⟨.success, [], world, 0, 0⟩) := by + simp [equivalent, observe] + +-- EIP-1014, example 0: https://eips.ethereum.org/EIPS/eip-1014#examples +example : create2Address 0 0 [0] = 0x4d1a2e2bb4f88f0250f26ffff098b0b30b26bf38 := by + decide +kernel + +example : validDeployedCode .berlin [0xef] = true := by decide +example : validDeployedCode .london [0xef] = false := by decide +example (code : List Byte) (size : code.length > 24576) : + validDeployedCode .cancun code = false := by + simp [validDeployedCode, Fork.atLeast, Fork.ordinal, show ¬ code.length ≤ 24576 by omega] + +example : validJump [0x60, 0x5b, 0x00] 1 = false := by decide +example : validJump [0x60, 0x01, 0x5b] 2 = true := by decide + +private def destructionFixture (created : Bool) : Journal := + {accounts := [{address := 1, nonce := 1, balance := 100, code := [0], storage := [(0,7)], created}] + original := [] + warmAddresses := [1] + warmSlots := []} + +example : (finalize (destroy .shanghai (destructionFixture false) 1 1)).accounts = [] := by decide +kernel +example : (account (destroy .cancun (destructionFixture false) 1 1) 1).balance = 100 := by decide +kernel +example : (finalize (destroy .cancun (destructionFixture true) 1 1)).accounts = [] := by decide +kernel +example : (account (destroy .shanghai (destructionFixture false) 1 1) 1).code = [0] := by decide +kernel +example : (destroy .berlin (destroy .berlin (destructionFixture false) 1 1) 1 1).refund = 24000 := by decide +kernel + +example : blockHash {number := 300, hashes := [(43,1),(44,2),(299,3),(300,4)]} 43 = 0 := by decide +kernel +example : blockHash {number := 300, hashes := [(44,2)]} 44 = 2 := by decide +kernel +example : blockHash {number := 300, hashes := [(300,4)]} 300 = 0 := by decide +kernel +example : delegationTarget .cancun ([0xef,0x01,0x00] ++ List.replicate 20 0) = none := by decide +kernel +example : delegationTarget .prague ([0xef,0x01,0x00] ++ List.replicate 19 0 ++ [42]) = some 42 := by decide +kernel +example : delegationTarget .prague ([0xef,0x01,0x00] ++ List.replicate 21 0) = none := by decide +kernel + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Selfdestruct.lean b/tv/SolarTV/EVMIR/State/Selfdestruct.lean new file mode 100644 index 00000000..e980d8fe --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Selfdestruct.lean @@ -0,0 +1,35 @@ +import SolarTV.EVMIR.State.Decode + +/-! SELFDESTRUCT's immediate balance effects and deferred account deletion. +Code and storage survive until transaction finalization, allowing another call +to the same account before the root returns. Cancun preserves existing accounts +under EIP-6780; accounts created in this transaction retain the legacy deletion +and self-beneficiary balance-burning rules. The flags are journaled with accounts, +so reverting any parent also reverts deletion, creation and refund eligibility. +https://eips.ethereum.org/EIPS/eip-6780 +https://eips.ethereum.org/EIPS/eip-3529 +https://eips.ethereum.org/EIPS/eip-2929 -/ + +namespace SolarTV.EVM.State + +def destructionPrice (fork : Fork) (world : Journal) (owner beneficiary : Address) : Nat := + 5000 + (if fork.atLeast .berlin && !world.warmAddresses.contains beneficiary then 2600 else 0) + + if (account world owner).balance != 0 && dead world beneficiary then 25000 else 0 + +def destroy (fork : Fork) (world : Journal) (owner beneficiary : Address) : Journal := + let old := account world owner + let deletes := !fork.atLeast .cancun || old.created + let world := warmAddress world beneficiary + let world := if owner = beneficiary then world else + (transfer world owner beneficiary old.balance).getD world + let current := account world owner + let refund := if !fork.atLeast .london && !old.destroyed then 24000 else 0 + putAccount {world with refund := world.refund + refund} + {current with + balance := if deletes then 0 else current.balance + destroyed := old.destroyed || deletes} + +def finalize (world : Journal) : Journal := + {world with accounts := world.accounts.filter (fun a => !a.destroyed)} + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/State/Types.lean b/tv/SolarTV/EVMIR/State/Types.lean new file mode 100644 index 00000000..d3afa6ef --- /dev/null +++ b/tv/SolarTV/EVMIR/State/Types.lean @@ -0,0 +1,70 @@ +import SolarTV.State.Calls +import SolarTV.State.ByteMemory +import SolarTV.State.Context +import SolarTV.Keccak +import SolarTV.EVMIR.Ops + +/-! Executable, journaled account state for explicit-world validation. Lists are +finite representations of total maps with an absent/zero default. Updates replace +keys rather than appending histories, and observations sort/erase zero slots. +The world fixture is an explicit assumption, never an arbitrary-account proof. +The evaluator reports unsupported behavior and work/memory limits separately +from EVM exceptional halts; neither may certify equivalence. -/ + +namespace SolarTV.EVM.State +open EvmRules +export SolarTV.Execution (Byte Address Slots Account Journal Block slotsRead slotsWrite account putAccount + warmAddress warmSlot transfer memoryWords requiredWords expand readBytes writeBytes wordBytes readWord) + +structure Frame where + environment : World.Environment + code : List Byte + pc : Nat := 0 + stack : List Word := [] + memory : List Byte := [] + returnData : List Byte := [] + gas : Nat + +inductive Stop where + | success | reverted | exception | outOfGas + deriving DecidableEq + +structure Result where + stop : Stop + data : List Byte + world : Journal + gas : Nat + work : Nat := 0 + deriving DecidableEq + +/-- Model errors are not execution outcomes and cannot be equated by the prover. -/ +abbrev Run := Except String Result + +def memoryCost (words : Nat) : Nat := 3 * words + words * words / 512 + +def memoryCharge (memory : List Byte) (offset count : Nat) : Nat := + memoryCost (requiredWords memory offset count) - memoryCost (memoryWords memory) + +def failed (world : Journal) : Run := .ok ⟨.exception, [], world, 0, 0⟩ + +def exhausted (world : Journal) : Run := .ok ⟨.outOfGas, [], world, 0, 0⟩ + +def finished (world : Journal) (frame : Frame) (reverted : Bool) (data : List Byte := []) : Run := + .ok ⟨if reverted then .reverted else .success, data, world, frame.gas, 0⟩ + +structure Opcode where + available : Bool + base : Nat + dynamic : Nat + inputs : Nat + outputs : Nat + deriving DecidableEq + +structure Config where + fork : Fork + opcodes : List Opcode + root : Address + block : Block := {} + unknownCode : Option Address := none + +end SolarTV.EVM.State diff --git a/tv/SolarTV/EVMIR/Transforms/EqIszeroJumpi.lean b/tv/SolarTV/EVMIR/Transforms/EqIszeroJumpi.lean new file mode 100644 index 00000000..8b06cbef --- /dev/null +++ b/tv/SolarTV/EVMIR/Transforms/EqIszeroJumpi.lean @@ -0,0 +1,21 @@ +import SolarTV.EVMIR.Ops + +/-! EVM IR peephole: replace EQ followed by ISZERO with SUB before a conditional jump. -/ + +namespace SolarTV.EVM +open EvmRules + +/-- After EQ (or SUB), the window has room for its single PUSH on any legal +entry stack. No memory, storage or return data is touched by these opcodes. -/ +theorem eq_iszero_jumpi (ctx : Context) (stack : Stack) (dst fallthrough : Word) + (legal : stack.length ≤ 1024) : + execute ctx [.eq, .iszero] (.branch dst fallthrough) stack = + execute ctx [.sub] (.branch dst fallthrough) stack := by + rcases stack with _ | ⟨a, _ | ⟨b, rest⟩⟩ <;> try rfl + have h : ¬ 1024 < rest.length + 1 + 1 := by simpa using legal + have h' : ¬ 1024 < rest.length + 1 := by omega + have zero (x y : Word) : Evm.sub x y = 0#256 ↔ x = y := by + simp [Evm.sub, BitVec.sub_eq_iff_eq_add] + by_cases same : a = b <;> simp [execute, stepChecked, step, finish, Evm.eq, Evm.iszero, zero, same, h, h'] + +end SolarTV.EVM diff --git a/tv/SolarTV/EVMIR/Transforms/GasSwapAdd.lean b/tv/SolarTV/EVMIR/Transforms/GasSwapAdd.lean new file mode 100644 index 00000000..52cc7ec6 --- /dev/null +++ b/tv/SolarTV/EVMIR/Transforms/GasSwapAdd.lean @@ -0,0 +1,25 @@ +import SolarTV.EVMIR.Gas + +/-! Resource refinement for the real commutative-swap peephole. +Dropping SWAP1 before ADD preserves the outgoing stack and memory while saving +three gas. For every budget at which the original completes, the candidate +completes with the same observation and at least as much remaining gas. Original +out-of-gas is unconstrained by this policy; exact gas equality would reject it. -/ + +namespace SolarTV.EVM.Gas +open EvmRules + +theorem swap_add_refines (ctx : Context) (a b destination : Word) + (memory : SolarTV.Memory.State) (gas : Nat) : + refines + (execute ctx [.instruction (.stack (.swap 0)), .instruction (.stack .add)] + (.control (.jump destination)) [a, b] memory gas) + (execute ctx [.instruction (.stack .add)] + (.control (.jump destination)) [a, b] memory gas) := by + simp [refines, execute, finish, cost, baseCost, pureCost, touched, expansionCost, + halted, exhausted, Memory.step, Memory.finish, EVM.stepChecked, EVM.step, + EVM.finish, Except.map, Evm.add, BitVec.add_comm] + repeat' (first | omega | (split <;> simp_all)) + all_goals omega + +end SolarTV.EVM.Gas diff --git a/tv/SolarTV/EVMIR/Transforms/StackPeephole.lean b/tv/SolarTV/EVMIR/Transforms/StackPeephole.lean new file mode 100644 index 00000000..6783e411 --- /dev/null +++ b/tv/SolarTV/EVMIR/Transforms/StackPeephole.lean @@ -0,0 +1,19 @@ +import SolarTV.EVMIR.Ops + +/-! The commutative-swap peephole removes SWAP1 before ADD. +Both versions use the same live-in stack. At a valid entry height the swap +preserves the height, ADD removes one word, and the outgoing label push fits. +The proof observes the entire resulting stack at the outgoing edge. -/ + +namespace SolarTV.EVM +open EvmRules + +theorem swap_add (ctx : Context) (a b destination : Word) (rest : Stack) + (legal : rest.length ≤ 1022) : + execute ctx [.swap 0, .add] (.jump destination) (a :: b :: rest) = + execute ctx [.add] (.jump destination) (a :: b :: rest) := by + have h : ¬ 1024 < rest.length + 1 + 1 := by omega + have h' : ¬ 1024 < rest.length + 1 := by omega + simp [execute, stepChecked, step, finish, h, h', Evm.add, BitVec.add_comm] + +end SolarTV.EVM diff --git a/tv/SolarTV/Keccak.lean b/tv/SolarTV/Keccak.lean new file mode 100644 index 00000000..15ac1e94 --- /dev/null +++ b/tv/SolarTV/Keccak.lean @@ -0,0 +1,70 @@ +import EvmRules.Word + +/-! Keccak-256 with the EVM's original Keccak padding (0x01, not SHA3's 0x06). +The state is 25 little-endian 64-bit lanes, indexed x + 5*y. Each of the 24 +Keccak-f rounds performs theta, rho/pi, chi and iota; the rate is 136 bytes. +There is no hash oracle or collision-freedom axiom. Symbolic hashes may exceed +the prover's limits, which must remain inconclusive rather than uninterpreted. +Reference: https://keccak.team/files/Keccak-reference-3.0.pdf, Algorithms 1-6. -/ + +namespace SolarTV.Keccak + +abbrev Byte := BitVec 8 +abbrev Lane := BitVec 64 +abbrev State := List Lane + +def constants : List Lane := [ + 0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000, + 0x000000000000808B, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, + 0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A, + 0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003, + 0x8000000000008002, 0x8000000000000080, 0x000000000000800A, 0x800000008000000A, + 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008] + +def rotations : List Nat := [ + 0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, + 41, 45, 15, 21, 8, 18, 2, 61, 56, 14] + +def lane (state : State) (x y : Nat) : Lane := state[x % 5 + 5 * (y % 5)]?.getD 0 + +def rotate (value : Lane) (amount : Nat) : Lane := + (value <<< (amount % 64)) ||| (value >>> ((64 - amount % 64) % 64)) + +def round (state : State) (constant : Lane) : State := + let parity := (List.range 5).map (fun x => + (List.range 5).foldl (fun acc y => acc ^^^ lane state x y) 0) + let theta := (List.range 25).map (fun i => + state[i]?.getD 0 ^^^ parity[(i % 5 + 4) % 5]?.getD 0 ^^^ + rotate (parity[(i % 5 + 1) % 5]?.getD 0) 1) + let rhoPi := (List.range 25).foldl (fun result i => + let x := i % 5 + let y := i / 5 + result.set (y + 5 * ((2 * x + 3 * y) % 5)) + (rotate (theta[i]?.getD 0) (rotations[i]?.getD 0))) (List.replicate 25 0) + let chi := (List.range 25).map (fun i => + lane rhoPi (i % 5) (i / 5) ^^^ + ((~~~lane rhoPi (i % 5 + 1) (i / 5)) &&& lane rhoPi (i % 5 + 2) (i / 5))) + chi.set 0 (chi[0]?.getD 0 ^^^ constant) + +def permutation (state : State) : State := constants.foldl round state + +def pad (data : List Byte) : List Byte := + if data.length % 136 = 135 then data ++ [0x81] + else data ++ [1] ++ List.replicate (134 - data.length % 136) 0 ++ [0x80] + +def littleWord (data : List Byte) (offset : Nat) : Lane := + (List.range 8).foldl (fun acc i => + acc ||| ((data[offset + i]?.getD 0).setWidth 64 <<< (8 * i))) 0 + +def absorb (state : State) (block : List Byte) : State := + permutation ((List.range 25).map (fun i => + state[i]?.getD 0 ^^^ if i < 17 then littleWord block (8 * i) else 0)) + +def hash (data : List Byte) : EvmRules.Word := + let padded := pad data + let state := (List.range (padded.length / 136)).foldl (fun state i => + absorb state ((padded.drop (136 * i)).take 136)) (List.replicate 25 0) + (List.range 32).foldl (fun acc i => (acc <<< 8) ||| + (((state[i / 8]?.getD 0) >>> (8 * (i % 8))).setWidth 8).setWidth 256) 0 + +end SolarTV.Keccak diff --git a/tv/SolarTV/KeccakSafety.lean b/tv/SolarTV/KeccakSafety.lean new file mode 100644 index 00000000..a028a594 --- /dev/null +++ b/tv/SolarTV/KeccakSafety.lean @@ -0,0 +1,33 @@ +import SolarTV.Keccak + +/-! Kernel-evaluated Keccak vectors cover empty input, byte/lane ordering, +the one-byte pad boundary and multi-block absorption. Positive checks never +use native_decide, an external hash function or a cryptographic axiom. -/ + +set_option maxRecDepth 8192 +set_option maxHeartbeats 2000000 + +namespace SolarTV.Keccak + +@[simp] theorem empty : hash [] = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 := by + decide +kernel + +example : hash [97, 98, 99] = + 0x4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45 := by + decide +kernel + +example : (pad (List.replicate 135 0)).length = 136 := by decide +example : (pad (List.replicate 136 0)).length = 272 := by decide + +-- These boundary values are also checked by the Rust interpreter tests. +example : hash (List.replicate 135 0) = + 18946676226192871058387231643792898752776336720096239710285640021474136472638 := by + decide +kernel +example : hash (List.replicate 136 0) = + 26391523361189685675012273911989963211388955111946558690139574972697269708281 := by + decide +kernel +example : hash (List.replicate 137 0) = + 86349320094517957708823086655008166321692264600573236910167712870522516913448 := by + decide +kernel + +end SolarTV.Keccak diff --git a/tv/SolarTV/MIR/Ops.lean b/tv/SolarTV/MIR/Ops.lean new file mode 100644 index 00000000..5d345842 --- /dev/null +++ b/tv/SolarTV/MIR/Ops.lean @@ -0,0 +1,149 @@ +import EvmRules.Word +import SolarTV.Outcome +import SolarTV.Word + +/-! Pure typed MIR operations and ordered switch dispatch. +A case stores an SSA value ID. Reading from an arbitrary total environment models +defined MIR operands, including nonconstant cases. The interpreter tests them in +source order and enters the first matching successor from the current block. -/ + +namespace SolarTV.MIR + +open EvmRules + +inductive Op where + | add | sub | mul | div | sdiv | mod | smod | exp | and | or | xor + | shl | shr | sar + +/-- Semantic arithmetic wraps at the operand width, as in lower-integers. Division and +remainder by zero give zero, as the EVM opcodes do. Shifts take the amount first, in EVM +pop order, and shift out every bit once it reaches the width; an arithmetic shift then +fills with the sign bit. The signed operations read the sign bit at the operand width. -/ +def eval {width : Nat} : Op → BitVec width → BitVec width → BitVec width + | .add => fun a b => a + b + | .sub => fun a b => a - b + | .mul => fun a b => a * b + | .div => Word.binary .div + | .sdiv => Word.binary .sdiv + | .mod => Word.binary .mod + | .smod => Word.binary .smod + | .exp => Word.binary .exp + | .and => fun a b => a &&& b + | .or => fun a b => a ||| b + | .xor => fun a b => a ^^^ b + | .shl => fun shift value => value <<< shift.toNat + | .shr => fun shift value => value >>> shift.toNat + | .sar => fun shift value => value.sshiftRight shift.toNat + +/-- Bitwise complement at the operand width. -/ +def not {width : Nat} (a : BitVec width) : BitVec width := ~~~a + +abbrev unary := @Word.unary +abbrev shift := @Word.shift + +/-- MIR `select` takes a normalized i1: the first arm when it is 1. -/ +def select {width : Nat} (condition : BitVec 1) (yes no : BitVec width) : BitVec width := + if condition = 0 then no else yes + +inductive WordBinary where + | byte | signextend + +def wordBinary : WordBinary → EvmRules.Word → EvmRules.Word → EvmRules.Word + | .byte => Evm.byte + | .signextend => Evm.signextend + +inductive Ternary where + | addmod | mulmod + +def ternary : Ternary → EvmRules.Word → EvmRules.Word → EvmRules.Word → EvmRules.Word + | .addmod => Evm.addmod + | .mulmod => Evm.mulmod + +/-- Ordered switch selection, also used when compiling a pair obligation. -/ +abbrev choose {width : Nat} (key test : BitVec width) (yes no : α) := if test = key then yes else no + +abbrev Case := Nat × Nat -- (SSA value ID, destination block) + +def dispatch (read : Nat → EvmRules.Word) (key : EvmRules.Word) (fallback : Nat) : + List Case → Nat + | [] => fallback + | (id, dst) :: rest => choose key (read id) dst (dispatch read key fallback rest) + +/-- Phi operands are read in the incoming environment and selected by predecessor. +An absent predecessor is undefined; the importer requires exactly one match. -/ +def phi {width : Nat} (predecessor : Nat) : List (Nat × BitVec width) → Option (BitVec width) + | [] => none + | (block, value) :: rest => + if predecessor = block then some value else phi predecessor rest + +inductive Cast where + | trunc | zext | sext + +/-- Cast widths are checked by the compiler verifier before import. +Truncation keeps the low bits, including for i1. Extension preserves either the +unsigned value or the source width's sign bit. Neither cast tests for nonzero. -/ +def cast {sourceWidth : Nat} (kind : Cast) (to : Nat) (value : BitVec sourceWidth) : BitVec to := + match kind with + | .trunc | .zext => value.setWidth to + | .sext => value.signExtend to + +inductive Comparison where + | eq | ne | lt | gt | slt | sgt + +/-- Comparisons produce exactly 0 or 1. Signed comparisons use the operand +width's sign bit, matching the sign extensions materialized by lower-integers. -/ +def compare {width : Nat} (kind : Comparison) (a b : BitVec width) : BitVec 1 := + let condition := match kind with + | .eq => a == b + | .ne => a != b + | .lt => a.ult b + | .gt => b.ult a + | .slt => a.slt b + | .sgt => b.slt a + if condition then 1 else 0 + +/-- jumpi takes a normalized i1, so its only possible inputs are 0 and 1. -/ +abbrev branch (condition : BitVec 1) (yes no : α) := if condition = 1 then yes else no + +inductive CheckedOp where + | add | sub | mul | div | wrappingDiv | rem + +/-- Lean's overflow predicates check the unbounded result against the declared +unsigned or two's-complement range. A failure is the Panic(0x11) emitted by +lower-arithmetic; successful results retain the declared width. -/ +def checked {width : Nat} (op : CheckedOp) (signed : Bool) + (a b : BitVec width) : Outcome (BitVec width) := + match op with + | .add => if (if signed then a.saddOverflow b else a.uaddOverflow b) then + .reverted (.panic 0x11) else .returned (a + b) + | .sub => if (if signed then a.ssubOverflow b else a.usubOverflow b) then + .reverted (.panic 0x11) else .returned (a - b) + | .mul => if (if signed then a.smulOverflow b else a.umulOverflow b) then + .reverted (.panic 0x11) else .returned (a * b) + | .div => + if b == 0 then .reverted (.panic 0x12) + else if signed && a == BitVec.intMin width && b == -1 then .reverted (.panic 0x11) + else .returned (if signed then a.sdiv b else a / b) + | .wrappingDiv => + if b == 0 then .reverted (.panic 0x12) + else .returned (if signed then a.sdiv b else a / b) + | .rem => + if b == 0 then .reverted (.panic 0x12) + else .returned (if signed then Word.binary .smod a b else Word.binary .mod a b) + +def checkedPower {width : Nat} (signed : Bool) (base : BitVec width) + (exponent : Nat) : Outcome (BitVec width) := + if _h : exponent = 0 then .returned 1 + else if exponent = 1 then .returned base + else + Outcome.bind (checked .mul signed base base) fun square => + Outcome.bind (checkedPower signed square (exponent / 2)) fun half => + if exponent % 2 = 0 then .returned half else checked .mul signed half base +termination_by exponent +decreasing_by exact Nat.div_lt_self (Nat.pos_of_ne_zero _h) (by decide) + +/-- Semantic checks fail synchronously before any later instruction runs. -/ +def guard (fails : Bool) (failure : RevertData) (next : Outcome α) : Outcome α := + if fails then .reverted failure else next + +end SolarTV.MIR diff --git a/tv/SolarTV/MIR/Program.lean b/tv/SolarTV/MIR/Program.lean new file mode 100644 index 00000000..de885403 --- /dev/null +++ b/tv/SolarTV/MIR/Program.lean @@ -0,0 +1,434 @@ +import SolarTV.Machine +import SolarTV.EVMIR.Ops + +/-! Lowered MIR functions and modules as layers. + +This is MIR at the `lowered` phase, the input of `-Zvalidate-passes`: word SSA values, +phis, branches, switches, the pure EVM operations, `ne`, effects, facts (`assume`), tail +calls and the halts of a contract entry. `lower-abi` and `lower-dispatch` run before it, so the semantic-phase +pipeline that builds the dispatcher is outside this semantics. A function runs block by +block with one unit of fuel per block, from block 0 with every value zero. A phi reads the +incoming environment and selects by predecessor. Pure operations are the word semantics of +`EVM.step`, the same `EvmRules.Evm` definitions the agreement theorems relate to the +encoder, and `ne` is `Evm.ne`. A switch enters the first case whose operand equals its key, +else its default. Malformed code (an unknown block, a phi without the predecessor, an +effect of the wrong arity) has no end, so it has no observable result, and neither has a +run that reaches a fact that does not hold. Casts and `select` have the semantics the +operation schema declares (`crates/mir/src/semantics.rs`): a zero extension or a pointer cast +leaves the word as it is, since every `iN` value keeps the bits above N zero, a truncation +keeps the low bits (`lowBits`), and a select picks by a nonzero condition. + +Two words of memory layout are the backend's, which MIR does not show and the MIR interpreter +reads from the backend memory records: the free memory pointer a runtime entry stores in the +pointer's slot `0x40` when it starts (`Function.entryHeap`, stored on entering the function, +`Function.start`), and the heap floor every `heap_floor` of a function reads, the initial +pointer of the entries that run it (`Inst.heapFloor`). `-Zemit-lean-stages` writes the words +codegen placed, so a stage holds for that placement. So are the allocations (`alloc`) codegen +placed: at a fixed address, or by bumping the free memory pointer by a size, which loads the +pointer and stores it raised as codegen's `mload 0x40; dup1; push size; add; push 0x40; mstore` +does. + +A module is the functions of a contract and the one its runtime code enters +(`Module.run`). A `tail_call` enters the callee's block 0 with a fresh environment that +binds its parameters to the arguments, and keeps the machine state; control never comes +back. An internal call (`icall`) does the same but first pushes a `Return`: the rest of its +block and the caller's values. The callee's `ret` (`leave` here) pops it, binds the call's +result to the returned value and runs the rest of the caller's block, for one more unit of +fuel. A `leave` with no caller, or whose values do not match the call's result, has no end. +A function that returns several words leaves all of them, as stack scheduling returns them on +the stack, and the call binds each to the value that reads it (`bindResults`), where MIR reads +the further ones from the multi-return buffer; those reads are not in the exported block. When +codegen also publishes them to the buffer, the call stores them there (`publishResults`). Block, value and function numbers are the compiler's indices (`BlockId`, `ValueId`, +`FunctionId`), as `-Zemit-lean-stages` writes them. The single-function layer (`layer`) +has no calls: a tail call, an internal call or a `leave` has no end there. -/ + +namespace SolarTV.MIR.Lowered + +open EvmRules Machine + +inductive Operand where + | value (id : Nat) + | const (word : Word) + +/-- Where codegen placed an allocation. -/ +inductive Placement where + /-- At a fixed address, below the heap. -/ + | static (address : Word) + /-- At the free memory pointer, which it raises by `size`. -/ + | dynamic (size : Word) + +inductive Inst where + | pure (dst : Nat) (op : EVM.Op) (args : List Operand) + | effect (dst : Option Nat) (effect : Effect) (args : List Operand) + /-- One when the operands differ, zero otherwise. -/ + | ne (dst : Nat) (a b : Operand) + /-- A fact a pass relied on (`assume`): `op` leaves a nonzero word on the operands, or zero + when `negated`. Where it fails the run has no end, so the fact is checked, never trusted. -/ + | assume (negated : Bool) (op : EVM.Op) (args : List Operand) + /-- The operand's word, unchanged: `zext`, `inttoptr` and `ptrtoint` to 256 bits, whose + operands already keep every bit above their width zero. -/ + | word (dst : Nat) (arg : Operand) + /-- An internal call of a function of the module, binding its result, if any. A callee that + returns several words leaves them all, as stack scheduling does: the call binds the first to + `dst` and each further one to its value in `extras`, if any, and when `publish` names + the callee's return buffer, stores them there too (`publishResults`). -/ + | call (dst : Option Nat) (callee : Nat) (args : List Operand) + (extras : List (Option Nat) := []) (publish : Option Word := none) + /-- The operand's low `bits` bits, zero above them: `trunc` and a narrower `ptrtoint`. -/ + | low (dst : Nat) (bits : Nat) (arg : Operand) + /-- The second operand when the first is nonzero, else the third: `select`. -/ + | select (dst : Nat) (condition yes no : Operand) + /-- The heap floor codegen placed for the function (`heap_floor`). -/ + | heapFloor (dst : Nat) (floor : Word) + /-- An allocation where codegen placed it (`alloc`), binding its address. -/ + | alloc (dst : Nat) (placement : Placement) + +inductive Terminator where + | jump (target : Nat) + | branch (condition : Operand) (yes no : Nat) + | ret (offset size : Operand) + | revert (offset size : Operand) + | stop + | invalid + /-- The first case whose operand equals the key, else the default. -/ + | switch (key : Operand) (default : Nat) (cases : List (Operand × Nat)) + /-- Control moves to the callee's entry for good, binding its parameters to the arguments. -/ + | tailCall (callee : Nat) (args : List Operand) + /-- An internal function's return with its values, to the instruction after the call. -/ + | leave (values : List Operand) + +structure Block where + phis : List (Nat × List (Nat × Operand)) + insts : List Inst + term : Terminator + +structure Function where + blocks : List Block + /-- The value numbers a call binds to its arguments, in order. -/ + params : List Nat := [] + /-- The free memory pointer codegen stores at `0x40` when the function starts as a runtime + entry, if any. -/ + entryHeap : Option Word := none + +/-- The state a function starts in: its entry heap stored in the free memory pointer's slot. -/ +def Function.start (f : Function) (s : State) : State := + match f.entryHeap with + | none => s + | some heap => { s with memory := s.memory.store 64 heap } + +abbrev Env := Nat → Word + +def Env.set (env : Env) (id : Nat) (value : Word) : Env := fun j => if j = id then value else env j + +def Operand.eval (env : Env) : Operand → Word + | .value id => env id + | .const word => word + +/-- The low `bits` bits of a word, zero above them, as the mask a narrow integer keeps. -/ +def lowBits (bits : Nat) (w : Word) : Word := Evm.and w (BitVec.ofNat 256 (2 ^ bits - 1)) + +/-- The second word when the first is nonzero, else the third. -/ +def selectWord (condition yes no : Word) : Word := if condition = 0 then no else yes + +/-- A pure operation on its operands in pop order: the single word `EVM.step` leaves. -/ +def evalPure (op : EVM.Op) (args : List Word) : Option Word := + match EVM.step ⟨0, 0⟩ op args with + | some [value] => some value + | _ => none + +def execInsts (o : Oracle) (call : Call) : List Inst → Env → State → Option (Env × State) + | [], env, s => some (env, s) + | .pure dst op args :: rest, env, s => + match evalPure op (args.map (Operand.eval env)) with + | some value => execInsts o call rest (env.set dst value) s + | none => none + | .effect dst effect args :: rest, env, s => + match effect.apply o call (args.map (Operand.eval env)) s with + | some (result, s) => + let env := match dst, result with + | some dst, some value => env.set dst value + | _, _ => env + execInsts o call rest env s + | none => none + | .ne dst a b :: rest, env, s => execInsts o call rest (env.set dst (Evm.ne (a.eval env) (b.eval env))) s + | .assume negated op args :: rest, env, s => + match evalPure op (args.map (Operand.eval env)) with + | some value => + if value = 0 then (if negated then execInsts o call rest env s else none) + else (if negated then none else execInsts o call rest env s) + | none => none + | .word dst a :: rest, env, s => execInsts o call rest (env.set dst (a.eval env)) s + | .low dst bits a :: rest, env, s => execInsts o call rest (env.set dst (lowBits bits (a.eval env))) s + | .select dst c yes no :: rest, env, s => + execInsts o call rest (env.set dst (selectWord (c.eval env) (yes.eval env) (no.eval env))) s + | .heapFloor dst floor :: rest, env, s => execInsts o call rest (env.set dst floor) s + | .alloc dst (.static address) :: rest, env, s => execInsts o call rest (env.set dst address) s + | .alloc dst (.dynamic size) :: rest, env, s => + let pointer := s.memory.load 64 + let memory := (s.memory.expand 64 32).store 64 (Evm.add size pointer) + execInsts o call rest (env.set dst pointer) { s with memory } + | .call .. :: _, _, _ => none + +/-- Result `k` of a call, from `k`, stored at `buffer + 32 * k`. -/ +def publishWords (memory : Mem) (buffer : Nat) : + Nat → List Word → Mem + | _, [] => memory + | k, value :: rest => publishWords (memory.store (buffer + 32 * k) value) buffer (k + 1) rest + +/-- The further results of a call returning several words, published where codegen publishes +them: result `k` at `buffer + 32 * k` for `k ≥ 1`, then `buffer` at the multi-return buffer +pointer's slot `0x20`, as its `swap1; push buffer+32k; mstore` and +`push buffer; push 0x20; mstore` do. -/ +def publishResults (s : State) : Option Word → List Word → State + | none, _ => s + | some _, [] => s + | some buffer, _ :: rest => + { s with memory := (publishWords s.memory buffer.toNat 1 rest).store 32 buffer } + +/-- The target of a switch on `key`: the first case whose operand equals it, else `default`. -/ +def switchTarget (env : Env) (key : Word) (default : Nat) : List (Operand × Nat) → Nat + | [] => default + | (case, target) :: rest => if case.eval env = key then target else switchTarget env key default rest + +/-- Every phi reads the incoming environment, then all are bound. -/ +def bindPhis (incoming : Env) (predecessor : Nat) : + List (Nat × List (Nat × Operand)) → Env → Option Env + | [], env => some env + | (dst, arms) :: rest, env => + match arms.find? (fun arm => arm.1 == predecessor) with + | some (_, operand) => bindPhis incoming predecessor rest (env.set dst (operand.eval incoming)) + | none => none + +def halt (s : State) (offset size : Word) (reverted : Bool) : Halt × State := + let memory := s.memory.expand offset.toNat size.toNat + let data := memory.read offset.toNat size.toNat + ((if reverted then .revert data else .ret data), { s with memory }) + +/-- One block from a predecessor: its end, or the next block with the state there. -/ +def block (o : Oracle) (call : Call) (f : Function) : + Nat × Nat × Env × State → Option ((Halt × State) ⊕ (Nat × Nat × Env × State)) + | (predecessor, b, env, s) => + match f.blocks[b]? with + | none => none + | some blk => + match bindPhis env predecessor blk.phis env with + | none => none + | some env => + match execInsts o call blk.insts env s with + | none => none + | some (env, s) => + match blk.term with + | .jump target => some (.inr (b, target, env, s)) + | .branch condition yes no => + some (.inr (b, if condition.eval env = 0 then no else yes, env, s)) + | .ret offset size => some (.inl (halt s (offset.eval env) (size.eval env) false)) + | .revert offset size => some (.inl (halt s (offset.eval env) (size.eval env) true)) + | .stop => some (.inl (.stop, s)) + | .invalid => some (.inl (.invalid, s)) + | .switch key default cases => + some (.inr (b, switchTarget env (key.eval env) default cases, env, s)) + | .tailCall _ _ => none + | .leave _ => none + +def run (o : Oracle) (f : Function) (call : Call) (fuel : Nat) : Option (Halt × State) := + iterate (block o call f) fuel (0, 0, fun _ => 0, f.start (State.initial call)) + +def layer : Layer where + Prog := Function + run := run + mono _ _ _ n r := iterate_mono _ n _ r + +/-- The fuel-free semantics of lowered MIR under an oracle. -/ +noncomputable def sem (o : Oracle) : Sem := layer.sem o + +theorem sem_failure (o : Oracle) (f : Function) (call : Call) (obs : Observable) + (ran : (sem o).run f call = some obs) (failed : obs.success = false) : + obs.logs = [] ∧ obs.storage = slotValue call.storage := by + obtain ⟨_, _, logs, storage, _⟩ := layer.sem_failure o f call obs ran failed + exact ⟨logs, storage⟩ + +theorem failureConvention (o : Oracle) : (sem o).FailureConvention := layer.failureConvention o + +/-- A function of one block without phis runs it at fuel one. -/ +theorem run_straight (o : Oracle) (call : Call) (insts : List Inst) (term : Terminator) + (n : Nat) : + run o ⟨[⟨[], insts, term⟩], [], none⟩ call (n + 1) = + match execInsts o call insts (fun _ => 0) (State.initial call) with + | none => none + | some (env, s) => + match term with + | .jump target => iterate (block o call ⟨[⟨[], insts, term⟩], [], none⟩) n (0, target, env, s) + | .branch condition yes no => + iterate (block o call ⟨[⟨[], insts, term⟩], [], none⟩) n + (0, if condition.eval env = 0 then no else yes, env, s) + | .ret offset size => some (halt s (offset.eval env) (size.eval env) false) + | .revert offset size => some (halt s (offset.eval env) (size.eval env) true) + | .stop => some (.stop, s) + | .invalid => some (.invalid, s) + | .switch key default cases => + iterate (block o call ⟨[⟨[], insts, term⟩], [], none⟩) n + (0, switchTarget env (key.eval env) default cases, env, s) + | .tailCall _ _ => none + | .leave _ => none := by + simp only [run, iterate, block, List.getElem?_cons_zero, bindPhis, Function.start] + cases execInsts o call insts (fun _ => 0) (State.initial call) with + | none => rfl + | some r => cases term <;> rfl + +/-! Modules. -/ + +structure Module where + functions : List Function + /-- The function the runtime code enters. -/ + entry : Nat + +/-- The environment a call enters with: each parameter bound to its argument, every other +value zero; `none` when their numbers differ. -/ +def bindParams : List Nat → List Word → Env → Option Env + | [], [], env => some env + | param :: params, arg :: args, env => bindParams params args (env.set param arg) + | _, _, _ => none + +/-- Where an internal call returns: the caller's function and block, the value its result +binds, the instructions after the call, the block's terminator and the caller's values. -/ +structure Return where + fn : Nat + block : Nat + dst : Option Nat + rest : List Inst + term : Terminator + env : Env + /-- The values the further results bind, for a callee that returns several words. -/ + extras : List (Option Nat) := [] + /-- The return buffer the further results are published to, if any. -/ + publish : Option Word := none + +/-- Where a module goes on: into a block of a function from a predecessor, or on with the +rest of a block after an internal call returned. -/ +inductive Pos where + | enter (fn predecessor block : Nat) + | resume (fn block : Nat) (insts : List Inst) (term : Terminator) + +/-- A configuration of a module: the returns of the calls in progress, innermost first, where +it goes on, its values and the machine state. -/ +abbrev Frame := List Return × Pos × Env × State + +/-- The instructions before the first internal call, and that call with the instructions +after it. -/ +def splitCall : List Inst → + List Inst × Option (Option Nat × Nat × List Operand × List (Option Nat) × Option Word × List Inst) + | [] => ([], none) + | .call dst callee args extras publish :: rest => ([], some (dst, callee, args, extras, publish, rest)) + | inst :: rest => + match splitCall rest with + | (before, next) => (inst :: before, next) + +/-- The caller's values after a return: the call's result bound to the returned value. -/ +def bindResult (env : Env) : Option Nat → List Word → Option Env + | none, [] => some env + | some dst, [value] => some (env.set dst value) + | _, _ => none + +/-- The values the further results of a call bind, in order: none for a result no value reads. -/ +def bindExtras (env : Env) : List (Option Nat) → List Word → Option Env + | [], [] => some env + | none :: extras, _ :: values => bindExtras env extras values + | some dst :: extras, value :: values => bindExtras (env.set dst value) extras values + | _, _ => none + +/-- The caller's values after a return: the call's result bound to the first returned value, +and the further ones to the values that read them when the callee returns several words. -/ +def bindResults (env : Env) (dst : Option Nat) : List (Option Nat) → List Word → Option Env + | [], values => bindResult env dst values + | extras, value :: values => + bindExtras (match dst with | some dst => env.set dst value | none => env) extras values + | _ :: _, [] => none + +/-- The rest of a block from its instructions: its end, or the next frame. -/ +def segment (o : Oracle) (call : Call) (m : Module) (stack : List Return) (fn b : Nat) + (insts : List Inst) (term : Terminator) (env : Env) (s : State) : + Option ((Halt × State) ⊕ Frame) := + match splitCall insts with + | (before, some (dst, callee, args, extras, publish, rest)) => + match execInsts o call before env s with + | none => none + | some (env, s) => + match m.functions[callee]? with + | none => none + | some g => + match bindParams g.params (args.map (Operand.eval env)) (fun _ => 0) with + | none => none + | some inner => + some (.inr (⟨fn, b, dst, rest, term, env, extras, publish⟩ :: stack, .enter callee 0 0, + inner, g.start s)) + | (before, none) => + match execInsts o call before env s with + | none => none + | some (env, s) => + match term with + | .jump target => some (.inr (stack, .enter fn b target, env, s)) + | .branch condition yes no => + some (.inr (stack, .enter fn b (if condition.eval env = 0 then no else yes), env, s)) + | .switch key default cases => + some (.inr (stack, .enter fn b (switchTarget env (key.eval env) default cases), env, s)) + | .tailCall callee args => + match m.functions[callee]? with + | none => none + | some g => + match bindParams g.params (args.map (Operand.eval env)) (fun _ => 0) with + | none => none + | some env => some (.inr (stack, .enter callee 0 0, env, g.start s)) + | .leave values => + match stack with + | [] => none + | ret :: stack => + let values := values.map (Operand.eval env) + match bindResults ret.env ret.dst ret.extras values with + | none => none + | some env => + some (.inr (stack, .resume ret.fn ret.block ret.rest ret.term, env, + publishResults s ret.publish values)) + | .ret offset size => some (.inl (halt s (offset.eval env) (size.eval env) false)) + | .revert offset size => some (.inl (halt s (offset.eval env) (size.eval env) true)) + | .stop => some (.inl (.stop, s)) + | .invalid => some (.inl (.invalid, s)) + +/-- One step of a module: a block entered, or the rest of a block after a return; its end, or +the next frame. -/ +def moduleBlock (o : Oracle) (call : Call) (m : Module) : Frame → Option ((Halt × State) ⊕ Frame) + | (stack, .enter fn predecessor b, env, s) => + match m.functions[fn]? with + | none => none + | some f => + match f.blocks[b]? with + | none => none + | some blk => + match bindPhis env predecessor blk.phis env with + | none => none + | some env => segment o call m stack fn b blk.insts blk.term env s + | (stack, .resume fn b insts term, env, s) => segment o call m stack fn b insts term env s + +/-- The state the module's entry function starts in. -/ +def Module.startState (m : Module) (s : State) : State := + match m.functions[m.entry]? with + | some f => f.start s + | none => s + +/-- A module run from its entry function's block 0, with every value zero and no call in +progress. -/ +def Module.run (o : Oracle) (m : Module) (call : Call) (fuel : Nat) : Option (Halt × State) := + iterate (moduleBlock o call m) fuel + ([], .enter m.entry 0 0, fun _ => 0, m.startState (State.initial call)) + +def moduleLayer : Layer where + Prog := Module + run := Module.run + mono _ _ _ n r := iterate_mono _ n _ r + +/-- The fuel-free semantics of lowered MIR modules under an oracle. -/ +noncomputable def moduleSem (o : Oracle) : Sem := moduleLayer.sem o + +theorem moduleFailureConvention (o : Oracle) : (moduleSem o).FailureConvention := + moduleLayer.failureConvention o + +end SolarTV.MIR.Lowered diff --git a/tv/SolarTV/MIR/State/Aggregates.lean b/tv/SolarTV/MIR/State/Aggregates.lean new file mode 100644 index 00000000..3597c765 --- /dev/null +++ b/tv/SolarTV/MIR/State/Aggregates.lean @@ -0,0 +1,54 @@ +import SolarTV.MIR.State.IR + +/-! Functional product updates and projections. Construction has no memory effect. +An undefined product provides undefined components, rather than zero-filled words; +a projection reads only its selected component. Location-tagged slices use the +same product algebra, with exactly a pointer and a word length. -/ + +namespace SolarTV.MIR.State + +def insertField (ty : ValueType) (aggregate : Value) (index : Nat) (value : Value) : Except String Value := do + let types ← required ty.fields "MIR insertion needs a product" + let _ ← required types[index]? "MIR aggregate index" + let fields ← match aggregate with + | .undefined => pure (List.replicate types.length Value.undefined) + | .aggregate fields => pure fields + | _ => .error "MIR insertion needs a product" + if fields.length != types.length then .error "MIR aggregate arity mismatch" else + return .aggregate (fields.set index value) + +def extractField (ty : ValueType) (aggregate : Value) (index : Nat) : Except String Value := do + let types ← required ty.fields "MIR projection needs a product" + let _ ← required types[index]? "MIR aggregate index" + match aggregate with + | .undefined => pure Value.undefined + | .aggregate fields => required fields[index]? "MIR aggregate index" + | _ => .error "MIR projection needs a product" + +@[simp↓] theorem insertField_ite (ty : ValueType) (index : Nat) (value : Value) + (p : Prop) [Decidable p] (a b : Value) : + insertField ty (if p then a else b) index value = + (if p then insertField ty a index value else insertField ty b index value) := by + split <;> rfl + +@[simp↓] theorem extractField_ite (ty : ValueType) (index : Nat) + (p : Prop) [Decidable p] (a b : Value) : + extractField ty (if p then a else b) index = + (if p then extractField ty a index else extractField ty b index) := by + split <;> rfl + +/-- Reading an initialized field does not consult the still-undefined neighbor. -/ +theorem project_inserted_field (word : EvmRules.Word) : + (do let value ← insertField (.product [.word 256,.word 1]) .undefined 0 + (.scalar (Scalar.ofWord 256 word)) + extractField (.product [.word 256,.word 1]) value 0) = + .ok (.scalar (Scalar.ofWord 256 word)) := by rfl + +/-- The uninitialized neighbor has not acquired an arbitrary value. -/ +theorem uninitialized_neighbor : + (do let value ← insertField (.product [.word 256,.word 1]) .undefined 0 + (.scalar (Scalar.ofWord 256 7)) + let field ← extractField (.product [.word 256,.word 1]) value 1 + field.word) = .error "undefined MIR scalar operand" := by rfl + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/Allocation.lean b/tv/SolarTV/MIR/State/Allocation.lean new file mode 100644 index 00000000..b708efff --- /dev/null +++ b/tv/SolarTV/MIR/State/Allocation.lean @@ -0,0 +1,34 @@ +import SolarTV.MIR.State.IR +import SolarTV.State.MemoryLaws + +/-! Direct allocation semantics, with the FMP supplied in explicit byte memory. +Reservation reads word 0x40 and writes the new end without touching the reserved +range. Zero initialization follows the FMP write and touches exactly that range. +The caller includes any alignment/padding in the requested size. Checked bumps +panic with 0x41 on wrapping or exceeding uint64; an invalid infallible bump is +outside its producer's validity contract and remains unsupported. No placement, +heap floor, synthetic pointer or implicit entry initialization is inferred. -/ + +namespace SolarTV.MIR.State +open EvmRules SolarTV.Execution + +def freePointer (frame : Frame) : Step := do + let memory ← expand frame.memory 64 32 + return .returned (some (readWord memory 64),{frame with memory}) + +def allocate (frame : Frame) (size : Word) (zeroed checked : Bool) : Step := do + let memory ← expand frame.memory 64 32 + let pointer := readWord memory 64 + let next := pointer + size + if next.toNat < pointer.toNat || next.toNat > 2^64 - 1 then + if checked then return .reverted (.panic 0x41) + else .error "infallible allocation validity precondition" + else + let memory := writeBytes memory 64 (wordBytes next) + let memory ← if zeroed then do + let memory ← expand memory pointer.toNat size.toNat + pure (writeBytes memory pointer.toNat (List.replicate size.toNat 0)) + else pure memory + return .returned (some pointer,{frame with memory}) + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/IR.lean b/tv/SolarTV/MIR/State/IR.lean new file mode 100644 index 00000000..db831011 --- /dev/null +++ b/tv/SolarTV/MIR/State/IR.lean @@ -0,0 +1,192 @@ +import SolarTV.MIR.State.Values +import SolarTV.EVMIR.State.Types +import Init.Data.List.Monadic +import SolarTV.State.ByteMemory +import SolarTV.State.Context + +/-! Structured typed SSA for direct MIR execution, including immutable products. The compiler's parser and +operation schema supply IDs, types and operation identities; the importer does +not lower MIR or synthesize backend addresses. Phis remain edge-selected and +simultaneous, and blocks retain their CFG, including cycles. -/ + +namespace SolarTV.MIR.State +open EvmRules SolarTV.Execution + +inductive Atom where + | constant (value : Scalar) + | argument (index : Nat) + | local (id : Nat) + | undefined + +structure Operand where + atom : Atom + ty : ValueType + +inductive MemoryOp where + | load | store | storeByte | copy | hash | size | zero + | calldataLoad | calldataSize | calldataCopy | returnDataSize | returnDataCopy + +/-- The predicate of a fact a pass relied on (`assume`), on the operands' words: `ult` and `ule` +compare them unsigned. -/ +inductive Fact where + | eq | ne | ult | ule + +def Fact.holds : Fact → Word → Word → Bool + | .eq, a, b => a == b + | .ne, a, b => a != b + | .ult, a, b => a.ult b + | .ule, a, b => a.ule b + +inductive Operation where + | binary (op : MIR.Op) (width : Nat) + | comparison (op : MIR.Comparison) (width : Nat) + | unary (op : Word.Unary) (width : Nat) + | shift (op : Word.Shift) (width : Nat) + | wordBinary (op : MIR.WordBinary) + | ternary (op : MIR.Ternary) + | word | pointerAdd | lowBits (width : Nat) | signExtend (source target : Nat) + | notEqual | select + | checked (op : MIR.CheckedOp) (width : Nat) (signed : Bool) + | checkedPower (width : Nat) (signed : Bool) + | check (zero : Bool) (panic : Option Word) + | memory (op : MemoryOp) + | storage (transient write : Bool) + | environment (opcode : Nat) + | log (topics : Nat) + | call (callee : Nat) + | freePointer + | allocate (zeroed checked : Bool) + | external (opcode : Nat) + | insertValue (ty : ValueType) (index : Nat) + | extractValue (ty : ValueType) (index : Nat) + | makeSlice (location : Nat) + /-- A fact a pass relied on. Where it fails the program is undefined, as for LLVM's `assume`: + a source run that reaches it has no outcome a target must keep, and a target run that + reaches it where the source is defined does not refine the source. -/ + | assume (fact : Fact) + +structure Instruction where + result : Option Nat + ty : ValueType + opcode : Option Nat + operation : Operation + operands : List Operand + +structure Phi where + result : Nat + ty : ValueType + incoming : List (Nat × Operand) + +inductive Terminator where + | jump (target : Nat) + | branch (condition : Operand) (yes no : Nat) + | switch (value : Operand) (fallback : Nat) (cases : List (Operand × Nat)) + | returned (values : List Operand) + | returndata (offset size : Operand) + | reverted (offset size : Operand) + | tailCall (callee : Nat) (args : List Operand) + | stop | invalid + +structure Block where + phis : List Phi + instructions : List Instruction + terminator : Terminator + +/-- Typed bodies retain their own SSA namespaces; calls share only execution state. -/ +structure Function where + params : List ValueType + returns : List ValueType + blocks : List Block + +abbrev Functions := List (Nat × Function) + +/-- An explicit control position, independent of physical EVM stack or frame placement. -/ +structure Cursor where + function : Nat + block : Nat := 0 + next : Nat := 0 + entered : Bool := false + predecessor : Option Nat := none + +structure Config where + fork : Fork + environment : World.Environment + context : Execution.Block + available : List Nat + entry : Bool + callDepth : Nat := 128 + externalConfig : Option EVM.State.Config := none + creationGas : List Nat := [] + +structure Frame where + world : Journal + memory : List Byte + arguments : List Value + locals : List (Nat × Value) := [] + returnData : List Byte := [] + creationIndex : Nat := 0 + +/-- A caller continuation owns its SSA snapshot, not a private copy of execution memory. -/ +structure Continuation where + cursor : Cursor + frame : Frame + result : Option Nat + ty : ValueType + +inductive Completion where + | returned (values : List Word) + | success (data : List Byte) + | reverted (data : List Byte) + | invalid + /-- A failed `assume`: undefined behaviour, not a program outcome. -/ + | undefined + deriving DecidableEq + +structure Result where + completion : Completion + world : Journal + memory : List Byte + returnData : List Byte := [] + creationIndex : Nat := 0 + +abbrev Run := Except String Result +abbrev Step := Except String (Outcome (Option Word × Frame)) + +def narrow (width : Nat) (value : Word) : Word := + if width = 256 then value else (value.setWidth width).setWidth 256 + +@[simp] theorem narrow_full (value : Word) : narrow 256 value = value := by + simp [narrow] + +def required (value : Option α) (reason : String) : Except String α := + match value with | some value => .ok value | none => .error reason + +def readValue (frame : Frame) (operand : Operand) : Except String Value := do + let value ← match operand.atom with + | .constant value => .ok (.scalar value) + | .argument index => required frame.arguments[index]? "missing MIR argument" + | .local id => required ((frame.locals.find? (·.1 == id)).map Prod.snd) "undefined MIR local" + | .undefined => .ok .undefined + if !value.fits 34 operand.ty then .error "MIR operand type mismatch" else return value + +def read (frame : Frame) (operand : Operand) : Except String Word := do + (← readValue frame operand).word + +def put (locals : List (Nat × α)) (id : Nat) (value : α) : List (Nat × α) := + (id,value) :: locals.filter (·.1 != id) + +def enter (predecessor : Option Nat) (phis : List Phi) (frame : Frame) : Except String Frame := do + -- Read every incoming value from the old environment before assigning any phi. + let values ← phis.mapM fun phi => do + let some predecessor := predecessor | .error "phi at MIR entry" + let incoming := phi.incoming.filter (·.1 == predecessor) + let [(_,operand)] := incoming | .error "ambiguous or missing MIR phi edge" + let value ← readValue frame operand + if !(phi.ty.same operand.ty) then .error "MIR phi type mismatch" else return (phi.result,value) + return {frame with locals := values.foldl (fun locals (id,value) => put locals id value) frame.locals} + +def failureData : RevertData → List Byte + | .empty => [] + | .panic code => [0x4e,0x48,0x7b,0x71] ++ wordBytes code + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/Interpreter.lean b/tv/SolarTV/MIR/State/Interpreter.lean new file mode 100644 index 00000000..e412660d --- /dev/null +++ b/tv/SolarTV/MIR/State/Interpreter.lean @@ -0,0 +1,199 @@ +import SolarTV.MIR.State.Messages + +/-! A direct SSA abstract machine with explicit caller continuations. Each body +has its own arguments/locals; internal calls share byte memory and the journal. +Returning restores only the caller's SSA context, while STOP, raw RETURN, revert +and exception terminate the whole frame. Tail calls replace the activation. +Phis read their incoming values simultaneously. One global work budget covers +all calls and CFG edges; call depth has a separate model bound. Exhaustion is +unsupported, never program failure or a reason to accept equal executions. +No stack scheduling, backend return protocol or frame initialization is used. -/ + +namespace SolarTV.MIR.State +open EvmRules SolarTV.Execution + +def finish (completion : Completion) (frame : Frame) : Result := + ⟨completion,frame.world,frame.memory,frame.returnData,frame.creationIndex⟩ + +def function (functions : Functions) (id : Nat) : Except String Function := + required ((functions.find? (·.1 == id)).map Prod.snd) "unknown MIR function" + +def typedWords (types : List ValueType) (values : List Value) : Except String Unit := + if types.length != values.length then .error "MIR call arity mismatch" + else if (types.zip values).all (fun (ty,value) => value.fits 34 ty) then .ok () + else .error "unmodeled or mismatched MIR call type" + +def choose (frame : Frame) (key : Word) (fallback : Nat) : List (Operand × Nat) → Except String Nat + | [] => .ok fallback + | (operand,target) :: rest => do + let test ← read frame operand + if test = key then return target else choose frame key fallback rest + +def branch (cursor : Cursor) (target : Nat) : Cursor := + {function := cursor.function,block := target,predecessor := some cursor.block} + +def advance (cursor : Cursor) : Cursor := {cursor with next := cursor.next + 1} + +def start (functions : Functions) (callee : Nat) (args : List Value) (frame : Frame) : Except String Frame := do + let body ← function functions callee + typedWords body.params args + return {frame with arguments := args,locals := []} + +def callSignature (callee : Function) (result : Option Nat) (ty : ValueType) : Except String Unit := + if callee.returns.length > 1 then .error "physical multi-return protocol is not modeled" + else if result.isNone || sameTypes callee.returns [ty] then .ok () + else .error "MIR call result signature mismatch" + + +structure Machine where + cursor : Cursor + stack : List Continuation + frame : Frame + +inductive Transition where + | next (extraWork : Nat) (machine : Machine) + | finished (result : Result) + +def next (cursor : Cursor) (stack : List Continuation) (frame : Frame) : Except String Transition := + .ok (.next 0 ⟨cursor,stack,frame⟩) + +def stop (completion : Completion) (frame : Frame) : Except String Transition := + .ok (.finished (finish completion frame)) + +/-- One MIR transition. Internal calls use continuations; external children spend the shared fuel. -/ +def transition (fuel : Nat) (cfg : Config) (functions : Functions) (machine : Machine) : Except String Transition := do + let ⟨cursor,stack,frame⟩ := machine + let body ← function functions cursor.function + let block ← required body.blocks[cursor.block]? "unknown MIR block" + if !cursor.entered then + let frame ← enter cursor.predecessor block.phis frame + return .next block.phis.length ⟨{cursor with entered := true},stack,frame⟩ + else if cursor.next < block.instructions.length then + let inst ← required block.instructions[cursor.next]? "unknown MIR instruction" + match inst.operation with + | .external opcode => + if inst.opcode.any (fun opcode => !cfg.available.contains opcode) then stop .invalid frame else + let args ← inst.operands.mapM (read frame) + let (effect,work) ← external fuel cfg frame opcode args + match effect with + | .returned (value,parent) => + match ← assign parent inst.result inst.ty value with + | .returned (_,parent) => return .next work ⟨advance cursor,stack,parent⟩ + | _ => .error "MIR message result assignment failed" + | .reverted data => stop (.reverted (failureData data)) frame + | .invalid => stop .invalid frame + | .assume fact => + let [lhs,rhs] := inst.operands | .error "MIR assume operand count" + let lhs ← read frame lhs + let rhs ← read frame rhs + if fact.holds lhs rhs then next (advance cursor) stack frame else stop .undefined frame + | .call callee => + let args ← inst.operands.mapM (readValue frame) + let target ← function functions callee + callSignature target inst.result inst.ty + if stack.length + 1 ≥ cfg.callDepth then .error "MIR internal call depth limit" else + let child ← start functions callee args frame + let caller := ⟨advance cursor,frame,inst.result,inst.ty⟩ + next {function := callee} (caller :: stack) child + | _ => + match ← instruction cfg frame inst with + | .returned (_,frame) => next (advance cursor) stack frame + | .reverted data => stop (.reverted (failureData data)) frame + | .invalid => stop .invalid frame + else + match block.terminator with + | .jump target => next (branch cursor target) stack frame + | .branch condition yes no => + let condition ← read frame condition + if condition = 1 then next (branch cursor yes) stack frame + else next (branch cursor no) stack frame + | .switch value fallback cases => + let key ← read frame value + let target ← choose frame key fallback cases + next (branch cursor target) stack frame + | .tailCall callee operands => + let args ← operands.mapM (readValue frame) + let target ← function functions callee + if !(sameTypes target.returns body.returns) then .error "MIR tail call result mismatch" else + let child ← start functions callee args frame + next {function := callee} stack child + | .returned operands => + let values ← operands.mapM (readValue frame) + typedWords body.returns values + match stack with + | [] => + let words ← (body.returns.zip values).mapM (fun (ty,value) => value.flatten 34 ty) + stop (.returned words.flatten) frame + | caller :: rest => + let parent := {caller.frame with + world := frame.world + memory := frame.memory + returnData := frame.returnData + creationIndex := frame.creationIndex} + if caller.result.isNone then next caller.cursor rest parent else + let [value] := values | .error "physical multi-return protocol is not modeled" + match ← assignValue parent caller.result caller.ty value with + | .returned (_,parent) => next caller.cursor rest parent + | _ => .error "MIR call return assignment failed" + | .stop => stop (.success []) frame + | .invalid => stop .invalid frame + | .returndata offset size | .reverted offset size => + let offset ← read frame offset + let size ← read frame size + let memory ← expand frame.memory offset.toNat size.toNat + let data := readBytes memory offset.toNat size.toNat + let reverted := match block.terminator with | .reverted .. => true | _ => false + stop (if reverted then .reverted data else .success data) {frame with memory} + +def run (fuel : Nat) (cfg : Config) (functions : Functions) (machine : Machine) : Run := do + match fuel with + | 0 => .error "MIR evaluation work limit" + | fuel + 1 => + match ← transition fuel cfg functions machine with + | .finished result => return result + | .next extra machine => + if extra > fuel then .error "MIR evaluation work limit" + else run (fuel - extra) cfg functions machine +termination_by fuel +decreasing_by all_goals omega + +theorem run_one (fuel : Nat) (cfg : Config) (functions : Functions) (machine : Machine) : + run (fuel + 1) cfg functions machine = (do + match ← transition fuel cfg functions machine with + | .finished result => return result + | .next extra nextMachine => + if extra > fuel then .error "MIR evaluation work limit" + else run (fuel - extra) cfg functions nextMachine) := by + rw [run] + +theorem run_next (fuel : Nat) {cfg functions machine extra nextMachine} + (h : transition fuel cfg functions machine = .ok (.next extra nextMachine)) : + run (fuel + 1) cfg functions machine = + if extra > fuel then .error "MIR evaluation work limit" + else run (fuel - extra) cfg functions nextMachine := by + simp only [run, h, Except.bind, Bind.bind] + +theorem run_finished (fuel : Nat) {cfg functions machine result} + (h : transition fuel cfg functions machine = .ok (.finished result)) : + run (fuel + 1) cfg functions machine = .ok result := by + simp only [run, h, Except.bind, Bind.bind, Pure.pure, Except.pure] + +theorem run_error (fuel : Nat) {cfg functions machine reason} + (h : transition fuel cfg functions machine = .error reason) : + run (fuel + 1) cfg functions machine = .error reason := by + simp only [run, h, Except.bind, Bind.bind] + +def execute (fuel : Nat) (cfg : Config) (functions : Functions) (entry : Nat) (frame : Frame) : Run := do + if cfg.callDepth = 0 then .error "MIR internal call depth limit" else + let initial ← start functions entry frame.arguments frame + let result ← run fuel cfg functions ⟨{function := entry},[],initial⟩ + match result.completion with + | .reverted _ | .invalid | .undefined => return {result with world := frame.world} + | .returned values => + if cfg.entry then + if values.isEmpty then return {result with completion := .success [],world := EVM.State.finalize result.world} + else .error "MIR entry returned word values" + else return result + | .success _ => return {result with world := EVM.State.finalize result.world} + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/Messages.lean b/tv/SolarTV/MIR/State/Messages.lean new file mode 100644 index 00000000..5c7955d5 --- /dev/null +++ b/tv/SolarTV/MIR/State/Messages.lean @@ -0,0 +1,64 @@ +import SolarTV.MIR.State.Ops +import SolarTV.EVMIR.State.Interpreter + +/-! Direct MIR message boundaries. Explicit CALL gas is forwarded without a +caller-side cap under the sufficient-caller-gas assumption. CREATE's child gas +is an explicit boundary input; it is not invented from an unpriced MIR body. +Children execute real fixture bytecode with fork-specific gas, precompiles and +journaling. The current MIR runtime's code is unknown, so inspecting or executing +it from a child remains unsupported instead of compiling it through the backend. +Missing creation budgets make a scenario unsupported; an unused suffix is allowed. -/ + +namespace SolarTV.MIR.State +open EvmRules SolarTV.Execution + +abbrev MessageStep := Except String (Outcome (Option Word × Frame) × Nat) + +def external (fuel : Nat) (cfg : Config) (frame : Frame) (opcode : Nat) + (args : List Word) : MessageStep := do + let externalConfig ← required cfg.externalConfig "missing MIR external execution configuration" + if cfg.fork.atLeast .amsterdam then .error "Amsterdam MIR message gas is not modeled" else + match opcode,args with + | 0xf1,_ | 0xf2,_ | 0xf4,_ | 0xfa,_ => + let explicitValue := opcode = 0xf1 || opcode = 0xf2 + if args.length != (if explicitValue then 7 else 6) then + .error "MIR call operand count" else + let gas := args[0]?.getD 0 + let destination := args[1]?.getD 0 + let start := if explicitValue then 3 else 2 + let inputOffset := args[start]?.getD 0 + let inputSize := args[start + 1]?.getD 0 + let outputOffset := args[start + 2]?.getD 0 + let outputSize := args[start + 3]?.getD 0 + let amount := if opcode = 0xf1 || opcode = 0xf2 then args[2]?.getD 0 else 0 + let kind := if opcode = 0xf1 then Calls.Kind.call else if opcode = 0xf2 then .callcode + else if opcode = 0xf4 then .delegatecall else .staticcall + if cfg.environment.isStatic && kind == .call && amount != 0 then return (.invalid,0) else + if gas.toNat > 30000000 then .error "MIR requested child gas exceeds 30000000" else + let memory ← expand frame.memory inputOffset.toNat inputSize.toNat + let memory ← expand memory outputOffset.toNat outputSize.toNat + let (code,_,world) := EVM.State.executionCode cfg.fork frame.world (destination.setWidth 160) + let message := ⟨kind,destination.setWidth 160,amount,readBytes memory inputOffset.toNat inputSize.toNat⟩ + let child ← EVM.State.executeCall (EVM.State.run fuel externalConfig) externalConfig world + cfg.environment message code (gas.toNat + if Calls.hasValue message then 2300 else 0) + let next := {frame with + world := child.world + memory := writeBytes memory outputOffset.toNat (child.data.take outputSize.toNat) + returnData := child.data} + return (.returned (some child.value,next),child.work) + | 0xf0,[amount,offset,size] | 0xf5,[amount,offset,size,_] => + if cfg.environment.isStatic then return (.invalid,0) else + if cfg.fork.atLeast .shanghai && size.toNat > 49152 then return (.invalid,0) else + let supplied ← required cfg.creationGas[frame.creationIndex]? "missing MIR creation gas budget" + let memory ← expand frame.memory offset.toNat size.toNat + let salt := if opcode = 0xf5 then args[3]? else none + let child ← EVM.State.executeCreation (EVM.State.run fuel externalConfig) externalConfig frame.world + cfg.environment salt amount (readBytes memory offset.toNat size.toNat) supplied + return (.returned (some child.value,{frame with + world := child.world + memory + returnData := child.data + creationIndex := frame.creationIndex + 1}),child.work) + | _,_ => .error "unmodeled MIR external message or operand count" + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/Normalize.lean b/tv/SolarTV/MIR/State/Normalize.lean new file mode 100644 index 00000000..41c93167 --- /dev/null +++ b/tv/SolarTV/MIR/State/Normalize.lean @@ -0,0 +1,42 @@ +import SolarTV.MIR.State.Interpreter +import Lean + +/-! Proof-producing execution of one known MIR control position at a time. +The simplifier must not unfold recursive execution under an unknown continuation: +that expands the work budget rather than the program's actual path. Each rewrite +uses a proved transition equation and kernel-checkable reduction of that finite +step. Symbolic branches expose one layer; unknown control positions stay opaque. +No VM/native evaluation, rewrite-name recognition or accepted-result axiom is used. -/ + +namespace SolarTV.MIR.State +open Lean Meta Simp + +simproc_decl reduceRun (run _ _ _ _) := fun expression => do + let args := expression.getAppArgs + let some fuel ← getNatValue? args[0]! | return .continue + if fuel = 0 then return .done {expr := ← whnf expression} + let machine ← whnf args[3]! + unless machine.isAppOf ``Machine.mk do return .continue + let cursor ← whnf machine.getAppArgs[0]! + unless cursor.isAppOf ``Cursor.mk do return .continue + for index in [0,1,2] do + unless (← getNatValue? (← withTransparency .default (whnf cursor.getAppArgs[index]!))).isSome do return .continue + let step ← mkAppM ``transition #[toExpr (fuel - 1),args[1]!,args[2]!,args[3]!] + let reduction ← simp step + let reduced ← whnf reduction.expr + let proof ← reduction.getProof + let parameters := #[toExpr (fuel - 1),args[1]!,args[2]!,args[3]!] + let equation ← if reduced.isAppOf ``Except.error then + pure (mkAppN (mkConst ``run_error) (parameters ++ #[reduced.appArg!,proof])) + else if reduced.isAppOf ``Except.ok then + let signal ← whnf reduced.appArg! + if signal.isAppOf ``Transition.next then + pure (mkAppN (mkConst ``run_next) (parameters ++ signal.getAppArgs ++ #[proof])) + else if signal.isAppOf ``Transition.finished then + pure (mkAppN (mkConst ``run_finished) (parameters ++ #[signal.appArg!,proof])) + else mkAppM ``run_one parameters + else mkAppM ``run_one parameters + let rhs := (← inferType equation).appArg! + return .visit {expr := rhs,proof? := some equation} + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/Observe.lean b/tv/SolarTV/MIR/State/Observe.lean new file mode 100644 index 00000000..8a1fdcff --- /dev/null +++ b/tv/SolarTV/MIR/State/Observe.lean @@ -0,0 +1,80 @@ +import SolarTV.MIR.State.Interpreter +import Lean.Data.Json + +/-! Observable direct MIR effects at the selected boundary. A normal internal +return exposes all live memory and transient storage to its caller. STOP/raw +RETURN end the transaction, so private memory and transient storage disappear. +Revert/exception roll back state and expose no memory. No gas placeholders or +backend image hashes are part of this observation. Model errors on either side +exclude a proof, including identical nontermination or resource exhaustion. A source +run that fails an `assume` is undefined and constrains no completed target run. -/ + +namespace SolarTV.MIR.State +open EvmRules SolarTV.Execution + +structure Observation where + status : String + values : List Word + data : List Byte + memory : Option (List Byte) + accounts : List Account + logs : List World.Log + returnData : List Byte + warmAddresses : List Address + warmSlots : List (Address × Word) + deriving DecidableEq + +def observe (result : Result) : Observation := + let (status,values,data,memory,keepTransient) := match result.completion with + | .returned values => ("return",values,[],some result.memory,true) + | .success data => ("success",[],data,none,false) + | .reverted data => ("revert",[],data,none,false) + | .invalid => ("exception",[],[],none,false) + | .undefined => ("undefined",[],[],none,false) + let accounts := result.world.accounts.map fun a => {a with + storage := normalizedSlots a.storage + transient := if keepTransient then normalizedSlots a.transient else [] + created := keepTransient && a.created + destroyed := keepTransient && a.destroyed} + ⟨status,values,data,memory,ordered (fun a b => a.address.ule b.address) accounts,result.world.logs, + if keepTransient then result.returnData else [], + if keepTransient then ordered (fun a b => a.ule b) result.world.warmAddresses.eraseDups else [], + if keepTransient then ordered (fun a b => if a.1 == b.1 then a.2.ule b.2 else a.1.ule b.1) result.world.warmSlots.eraseDups else []⟩ + +/-- The target refines the source: equal observations, unless the source run is undefined (a +failed `assume`), which any target run that completes refines. An undefined target run observes +as `undefined`, which no defined source run observes, so it never refines one. -/ +def equivalent (before after : Run) : Prop := + match before,after with + | .ok a,.ok b => a.completion = .undefined ∨ observe a = observe b + | _,_ => False + +instance (a b : Run) : Decidable (equivalent a b) := by + unfold equivalent + split <;> infer_instance + +private def wordJson (v : Word) : Lean.Json := .str (toString v.toNat) +private def bytesJson (bytes : List Byte) : Lean.Json := + .arr (bytes.map (fun b => Lean.toJson b.toNat)).toArray +private def slotsJson (slots : Slots) : Lean.Json := + .arr (slots.map (fun (k,v) => Lean.Json.arr #[wordJson k,wordJson v])).toArray + +def describe (result : Run) : String := + match result with + | .error reason => "unsupported: " ++ reason + | .ok result => + let o := observe result + (Lean.Json.mkObj [ + ("returndata",bytesJson o.returnData), + ("warm_addresses",.arr (o.warmAddresses.map (fun a => .str (toString a.toNat))).toArray), + ("warm_slots",.arr (o.warmSlots.map (fun (a,k) => Lean.Json.arr #[.str (toString a.toNat),wordJson k])).toArray), + ("outcome",.str o.status), ("values",.arr (o.values.map wordJson).toArray), + ("data",bytesJson o.data), ("memory",o.memory.map bytesJson |>.getD .null), + ("accounts",.arr (o.accounts.map (fun a => Lean.Json.arr #[ + .str (toString a.address.toNat),.str (toString a.nonce),wordJson a.balance, + bytesJson a.code,slotsJson a.storage,slotsJson a.transient,Lean.toJson a.created,Lean.toJson a.destroyed])).toArray), + ("logs",.arr (o.logs.map (fun l => Lean.Json.arr #[ + .str (toString l.address.toNat),.arr (l.topics.map wordJson).toArray,bytesJson l.data])).toArray) + ]).compress + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/Ops.lean b/tv/SolarTV/MIR/State/Ops.lean new file mode 100644 index 00000000..2db95d91 --- /dev/null +++ b/tv/SolarTV/MIR/State/Ops.lean @@ -0,0 +1,162 @@ +import SolarTV.MIR.State.Allocation +import SolarTV.MIR.State.Aggregates +import SolarTV.Keccak + +/-! Direct MIR scalar and state-operation semantics. Typed arithmetic reuses MIR's +width-polymorphic definitions. Memory is byte-addressed and storage is qualified +by its owner in the shared journal. Static violations are exceptional halts. +This layer assigns no physical stack, frame placement, implicit FMP setup or EVM +gas cost. Memory/work bounds are model errors, not program outcomes. -/ + +namespace SolarTV.MIR.State +open EvmRules SolarTV.Execution + +def value (frame : Frame) (word : Word) : Step := .ok (.returned (some word,frame)) +def effect (frame : Frame) : Step := .ok (.returned (none,frame)) + +private def checkedResult (frame : Frame) (result : Outcome (BitVec width)) : Step := + .ok (match result with + | .returned v => .returned (some (v.setWidth 256),frame) + | .reverted data => .reverted data + | .invalid => .invalid) + +def memoryOperation (cfg : Config) (frame : Frame) (op : MemoryOp) (args : List Word) : Step := do + match op,args with + | .size,[] => value frame (BitVec.ofNat 256 frame.memory.length) + | .returnDataSize,[] => value frame (BitVec.ofNat 256 frame.returnData.length) + | .returnDataCopy,[destination,source,count] => + if source.toNat + count.toNat > frame.returnData.length then return .invalid + else + let memory ← expand frame.memory destination.toNat count.toNat + effect {frame with memory := writeBytes memory destination.toNat (readBytes frame.returnData source.toNat count.toNat)} + | .calldataSize,[] => value frame (BitVec.ofNat 256 cfg.environment.input.length) + | .calldataLoad,[offset] => value frame (readWord cfg.environment.input offset.toNat) + | .load,[offset] => + let memory ← expand frame.memory offset.toNat 32 + value {frame with memory} (readWord memory offset.toNat) + | .store,[offset,word] | .storeByte,[offset,word] => + let bytes := match op with | .storeByte => [word.setWidth 8] | _ => wordBytes word + let memory ← expand frame.memory offset.toNat bytes.length + effect {frame with memory := writeBytes memory offset.toNat bytes} + | .copy,[destination,source,size] | .calldataCopy,[destination,source,size] => + let memory ← expand frame.memory destination.toNat size.toNat + let memory ← match op with | .copy => expand memory source.toNat size.toNat | _ => pure memory + let sourceBytes := match op with | .copy => memory | _ => cfg.environment.input + effect {frame with memory := writeBytes memory destination.toNat (readBytes sourceBytes source.toNat size.toNat)} + | .zero,[offset,size] => + let memory ← expand frame.memory offset.toNat size.toNat + effect {frame with memory := writeBytes memory offset.toNat (List.replicate size.toNat 0)} + | .hash,[offset,size] => + let memory ← expand frame.memory offset.toNat size.toNat + value {frame with memory} (Keccak.hash (readBytes memory offset.toNat size.toNat)) + | _,_ => .error "MIR memory operand count" + +def storageOperation (cfg : Config) (frame : Frame) (transient write : Bool) (args : List Word) : Step := do + let owner := cfg.environment.address + let old := account frame.world owner + let slots := if transient then old.transient else old.storage + match write,args with + | false,[key] => value (if transient then frame else + {frame with world := warmSlot frame.world owner key}) (slotsRead slots key) + | true,[key,word] => + if cfg.environment.isStatic then return .invalid + let updated := slotsWrite slots key word + let world := putAccount (if transient then frame.world else warmSlot frame.world owner key) + (if transient then {old with transient := updated} else {old with storage := updated}) + effect {frame with world} + | _,_ => .error "MIR storage operand count" + +def contextOperation (cfg : Config) (frame : Frame) (opcode : Nat) (args : List Word) : Step := + match opcode,args with + | 0x30,[] => value frame (cfg.environment.address.setWidth 256) + | 0x32,[] => value frame (cfg.environment.origin.setWidth 256) + | 0x33,[] => value frame (cfg.environment.caller.setWidth 256) + | 0x34,[] => value frame cfg.environment.value + | 0x3a,[] => value frame cfg.environment.gasPrice + | 0x47,[] => value frame (account frame.world cfg.environment.address).balance + | 0x40,[argument] | 0x49,[argument] => value frame (Execution.environmentValue cfg.fork cfg.context opcode argument) + | 0x41,[] | 0x42,[] | 0x43,[] | 0x44,[] | 0x45,[] | 0x46,[] | 0x48,[] | 0x4a,[] | 0x4b,[] => + value frame (Execution.environmentValue cfg.fork cfg.context opcode 0) + | _,_ => .error "unmodeled MIR context read" + +def operation (cfg : Config) (frame : Frame) (op : Operation) (args : List Word) : Step := do + match op,args with + | .binary op width,[a,b] => value frame (widenBits (MIR.eval op (wordBits width a) (wordBits width b))) + | .comparison op width,[a,b] => value frame (widenBits (MIR.compare op (wordBits width a) (wordBits width b))) + | .unary op width,[a] => value frame (widenBits (MIR.unary op (wordBits width a))) + | .shift op width,[amount,v] => value frame (widenBits (MIR.shift op (wordBits width v) (wordBits width amount))) + | .wordBinary op,[a,b] => value frame (MIR.wordBinary op a b) + | .ternary op,[a,b,c] => value frame (MIR.ternary op a b c) + | .word,[a] => value frame a + | .freePointer,[] => freePointer frame + | .allocate zeroed checked,[size] => allocate frame size zeroed checked + | .insertValue ..,_ | .extractValue ..,_ | .makeSlice ..,_ => .error "aggregate operation needs typed operands" + | .external _,_ => .error "external instruction requires MIR machine context" + | .call _,_ => .error "internal call requires MIR machine context" + | .pointerAdd,[pointer,offset] => value frame (pointer + offset) + | .lowBits width,[a] => value frame (narrow width a) + | .signExtend source target,[a] => value frame (((a.setWidth source).signExtend target).setWidth 256) + | .notEqual,[a,b] => value frame (if a = b then 0 else 1) + | .select,[c,a,b] => value frame (if c = 0 then b else a) + | .checked op width signed,[a,b] => checkedResult frame (MIR.checked op signed (wordBits width a) (wordBits width b)) + | .checkedPower width signed,[a,b] => checkedResult frame (MIR.checkedPower signed (wordBits width a) b.toNat) + | .check zero panic,[condition] => + if (condition == 0) == zero then + return .reverted (match panic with | none => .empty | some code => .panic code) + else effect frame + | .memory op,args => memoryOperation cfg frame op args + | .storage transient write,args => storageOperation cfg frame transient write args + | .environment opcode,args => contextOperation cfg frame opcode args + | .log count,offset :: size :: topics => + if count != topics.length then .error "MIR log topic count" else + if cfg.environment.isStatic then return .invalid else + let memory ← expand frame.memory offset.toNat size.toNat + effect {frame with memory, world := {frame.world with logs := frame.world.logs ++ + [⟨cfg.environment.address,topics,readBytes memory offset.toNat size.toNat⟩]}} + | _,_ => .error "MIR operation operand count" + +def assignValue (next : Frame) (result : Option Nat) (ty : ValueType) (value : Value) : Step := do + let some id := result | .error "MIR result arity mismatch" + if !value.fits 34 ty then .error "MIR result type mismatch" else + effect {next with locals := put next.locals id value} + +def assign (next : Frame) (result : Option Nat) (ty : ValueType) (word : Option Word) : Step := do + match result,word with + | none,none => effect next + | some _,some word => + if ty.width = 0 || ty.width > 256 then .error "unmodeled MIR result type" else + assignValue next result ty (.scalar (Scalar.ofWord ty.width word)) + | _,_ => .error "MIR result arity mismatch" + +def instruction (cfg : Config) (frame : Frame) (inst : Instruction) : Step := do + if inst.opcode.any (fun opcode => !cfg.available.contains opcode) then return .invalid + match inst.operation,inst.operands with + | .insertValue ty index,[aggregate,field] => + let aggregate ← readValue frame aggregate + let value ← readValue frame field + let updated ← insertField ty aggregate index value + assignValue frame inst.result inst.ty updated + | .extractValue ty index,[aggregate] => + let aggregate ← readValue frame aggregate + let value ← extractField ty aggregate index + assignValue frame inst.result inst.ty value + | .makeSlice location,[pointer,length] => + let pointer ← read frame pointer + let length ← read frame length + if !(inst.ty.same (.slice location)) then .error "MIR slice location mismatch" else + assignValue frame inst.result inst.ty (.aggregate [ + .scalar (Scalar.ofWord 256 pointer),.scalar (Scalar.ofWord 256 length)]) + | .select,[condition,yes,no] => + let condition ← read frame condition + let yes ← readValue frame yes + let no ← readValue frame no + assignValue frame inst.result inst.ty (if condition = 0 then no else yes) + | _,_ => + let args ← inst.operands.mapM (read frame) + let result ← operation cfg frame inst.operation args + match result with + | .returned (word,next) => assign next inst.result inst.ty word + | .reverted data => return .reverted data + | .invalid => return .invalid + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/Safety.lean b/tv/SolarTV/MIR/State/Safety.lean new file mode 100644 index 00000000..ae38af84 --- /dev/null +++ b/tv/SolarTV/MIR/State/Safety.lean @@ -0,0 +1,59 @@ +import SolarTV.MIR.State.Observe + +/-! Executable semantic invariants for the direct MIR interpreter. Phi operands +are simultaneous even on cyclic edges; work limits cannot establish equivalence. +Normal returns expose memory and transient cells, unlike transaction termination. +A failed `assume` is undefined: it admits any completed target but is never one. +These checks do not invoke the backend or its physical frame conventions. -/ + +namespace SolarTV.MIR.State +open EvmRules SolarTV.Execution + +theorem work_limit_is_not_equivalence (reason : String) (other : Run) : + ¬ equivalent (.error reason) other := by + simp [equivalent] + +theorem simultaneous_phis : + ((enter (some 1) + [⟨0,.word 256,[(1,⟨.local 1,.word 256⟩)]⟩,⟨1,.word 256,[(1,⟨.local 0,.word 256⟩)]⟩] + ⟨⟨[],[],[],[],[],0⟩,[],[],[(0,.scalar ⟨256,7⟩),(1,.scalar ⟨256,9⟩)],[],0⟩).map (·.locals)) = + .ok [(1,.scalar ⟨256,7⟩),(0,.scalar ⟨256,9⟩)] := by with_unfolding_all rfl + +theorem live_memory_is_observable : + ¬ equivalent + (.ok ⟨.returned [],⟨[],[],[],[],[],0⟩,[],[],0⟩) + (.ok ⟨.returned [],⟨[],[],[],[],[],0⟩,[1],[],0⟩) := by decide +kernel + +theorem live_transient_is_observable : + ¬ equivalent + (.ok ⟨.returned [],⟨[{address:=1}],[],[],[],[],0⟩,[],[],0⟩) + (.ok ⟨.returned [],⟨[{address:=1,transient:=[(0,7)]}],[],[],[],[],0⟩,[],[],0⟩) := by decide +kernel + +theorem live_return_data_is_observable : + ¬ equivalent + (.ok ⟨.returned [],⟨[],[],[],[],[],0⟩,[],[1],0⟩) + (.ok ⟨.returned [],⟨[],[],[],[],[],0⟩,[],[2],0⟩) := by decide +kernel + +theorem undefined_target_is_not_equivalence : + ¬ equivalent + (.ok ⟨.returned [],⟨[],[],[],[],[],0⟩,[],[],0⟩) + (.ok ⟨.undefined,⟨[],[],[],[],[],0⟩,[],[],0⟩) := by decide +kernel + +theorem undefined_source_admits_any_completion : + equivalent + (.ok ⟨.undefined,⟨[],[],[],[],[],0⟩,[],[],0⟩) + (.ok ⟨.returned [7],⟨[],[],[],[],[],0⟩,[],[],0⟩) := by decide +kernel + +theorem undefined_source_does_not_admit_model_errors (reason : String) : + ¬ equivalent (.ok ⟨.undefined,⟨[],[],[],[],[],0⟩,[],[],0⟩) (.error reason) := by + simp [equivalent] + +theorem failed_assume_is_undefined (cfg : Config) : + (transition 1 cfg + [(0,⟨[],[],[⟨[],[⟨none,.word 256,none,.assume .eq, + [⟨.constant (.ofWord 256 1),.word 256⟩,⟨.constant (.ofWord 256 2),.word 256⟩]⟩],.stop⟩]⟩)] + ⟨{function := 0,entered := true},[],⟨⟨[],[],[],[],[],0⟩,[],[],[],[],0⟩⟩).map + (fun | .finished r => some r.completion | .next .. => none) = .ok (some .undefined) := by + with_unfolding_all rfl + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/State/Values.lean b/tv/SolarTV/MIR/State/Values.lean new file mode 100644 index 00000000..b9037308 --- /dev/null +++ b/tv/SolarTV/MIR/State/Values.lean @@ -0,0 +1,121 @@ +import SolarTV.MIR.Ops + +/-! Logical typed SSA values. Products and slices are immutable trees, not memory +objects or backend word layouts. Undefined fields stay undefined until replaced; +projecting another field does not read them. An undefined scalar cannot determine +control flow, an effect or a returned observable. At the selected function boundary +only, products are flattened in declaration order to compare type-lowering passes. +Type depth/node limits are importer resource limits, never execution assumptions. -/ + +namespace SolarTV.MIR.State +open EvmRules + +structure Scalar where + width : Nat + bits : BitVec width + +def wordBits (width : Nat) (value : Word) : BitVec width := + if h : width = 256 then value.cast h.symm else value.setWidth width + +def widenBits {width : Nat} (value : BitVec width) : Word := + if h : width = 256 then value.cast h else value.setWidth 256 + +def Scalar.word (value : Scalar) : Word := widenBits value.bits + +def Scalar.ofWord (width : Nat) (value : Word) : Scalar := ⟨width,wordBits width value⟩ + +/-- Full-width boxing is identity, including before dependent casts are unfolded. -/ +@[simp↓] theorem scalar_word_full (word : Word) : + (Scalar.mk 256 word).word = word := by rfl + +@[simp↓] theorem wordBits_full (word : Word) : wordBits 256 word = word := by rfl + +@[simp↓] theorem widenBits_full (word : Word) : widenBits word = word := by rfl + +inductive ValueType where + | word (width : Nat) + | pointer (location : Nat) + | product (fields : List ValueType) + | slice (location : Nat) + +mutual + def ValueType.same (a b : ValueType) : Bool := + match a,b with + | .word a,.word b | .pointer a,.pointer b | .slice a,.slice b => a == b + | .product a,.product b => sameTypes a b + | _,_ => false + termination_by sizeOf a + + def sameTypes (a b : List ValueType) : Bool := + match a,b with + | [],[] => true + | a :: rest,b :: tail => a.same b && sameTypes rest tail + | _,_ => false + termination_by sizeOf a +end + + +def ValueType.width : ValueType → Nat + | .word width => width + | .pointer _ => 256 + | _ => 0 + +def ValueType.fields : ValueType → Option (List ValueType) + | .product fields => some fields + | .slice location => some [.pointer location,.word 256] + | _ => none + +inductive Value where + | scalar (value : Scalar) + | aggregate (fields : List Value) + | undefined + +/-- Undefined components may be copied, but never silently materialized as zero. -/ +def Value.fits : Nat → ValueType → Value → Bool + | 0,_,_ => false + | _ + 1,_,.undefined => true + | _ + 1,ty,.scalar value => ty.width > 0 && ty.width ≤ 256 && ty.width == value.width + | fuel + 1,ty,.aggregate values => + match ty.fields with + | none => false + | some types => types.length == values.length && + (types.zip values).all (fun (ty,value) => value.fits fuel ty) + +/-- Scalars alone may feed word operations. Pointer bits carry no validity proof. -/ +def Value.word : Value → Except String Word + | .scalar value => .ok value.word + | .undefined => .error "undefined MIR scalar operand" + | _ => .error "aggregate MIR operand used as a scalar" + +/-- Only complete, defined logical leaves are exposed at the function boundary. -/ +def Value.flatten : Nat → ValueType → Value → Except String (List Word) + | 0,_,_ => .error "MIR aggregate type depth limit" + | fuel + 1,ty,value => do + match ty.fields with + | none => return [← value.word] + | some types => + let values ← match value with + | .undefined => pure (List.replicate types.length Value.undefined) + | .aggregate values => pure values + | _ => .error "MIR aggregate return shape mismatch" + if types.length != values.length then .error "MIR aggregate return arity" else + return (← (types.zip values).mapM (fun (ty,value) => value.flatten fuel ty)).flatten + +/-- Normalize value conditionals without distributing the whole execution state. -/ +@[simp↓] theorem fits_ite (fuel : Nat) (ty : ValueType) (p : Prop) [Decidable p] (a b : Value) : + (if p then a else b).fits fuel ty = (if p then a.fits fuel ty else b.fits fuel ty) := by + split <;> rfl + +@[simp↓] theorem word_ite (p : Prop) [Decidable p] (a b : Value) : + (if p then a else b).word = (if p then a.word else b.word) := by + split <;> rfl + +@[simp↓] theorem flatten_ite (fuel : Nat) (ty : ValueType) (p : Prop) [Decidable p] (a b : Value) : + (if p then a else b).flatten fuel ty = (if p then a.flatten fuel ty else b.flatten fuel ty) := by + split <;> rfl + +@[simp↓] theorem except_ok_ite (p : Prop) [Decidable p] (a b : α) : + (if p then Except.ok a else Except.ok b : Except ε α) = .ok (if p then a else b) := by + split <;> rfl + +end SolarTV.MIR.State diff --git a/tv/SolarTV/MIR/Transforms/Casts.lean b/tv/SolarTV/MIR/Transforms/Casts.lean new file mode 100644 index 00000000..c94c45b0 --- /dev/null +++ b/tv/SolarTV/MIR/Transforms/Casts.lean @@ -0,0 +1,42 @@ +import SolarTV.MIR.Ops +import SolarTV.MIR.Program + +/-! Integer cleanup can remove a truncation after a lossless zero extension. +The concrete i160/i256 theorem also checks the native bit-vector width model. +The i1 examples pin the difference between truncation and boolean normalization, +and between sign and zero extension. The last two relate the lowered MIR semantics' casts +to these. -/ + +namespace SolarTV.MIR + +theorem truncate_extended_address (value : BitVec 160) : + cast .trunc 160 (cast .zext 256 value) = value := by + simp [cast] + +theorem truncate_even_word : cast .trunc 1 (2#256) = 0#1 := by decide + +theorem extend_true_sign : cast .sext 256 (1#1) = -1#256 := by decide + +theorem extend_true_zero : cast .zext 256 (1#1) = 1#256 := by decide + +/-- The lowered semantics' truncation, `low`, is the typed one extended back to a word. -/ +theorem lowBits_eq_trunc (bits : Nat) (le : bits ≤ 256) (w : BitVec 256) : + Lowered.lowBits bits w = cast .zext 256 (cast .trunc bits w) := by + apply BitVec.eq_of_toNat_eq + have hp : 2 ^ bits ≤ 2 ^ 256 := Nat.pow_le_pow_right (by decide) le + have hpos : 0 < 2 ^ bits := Nat.two_pow_pos _ + simp only [Lowered.lowBits, EvmRules.Evm.and, cast, BitVec.toNat_and, BitVec.toNat_setWidth, + BitVec.toNat_ofNat] + rw [Nat.mod_eq_of_lt (show 2 ^ bits - 1 < 2 ^ 256 by omega), Nat.and_two_pow_sub_one_eq_mod] + rw [Nat.mod_eq_of_lt (show w.toNat % 2 ^ bits < 2 ^ 256 by + exact Nat.lt_of_lt_of_le (Nat.mod_lt _ hpos) hp)] + +/-- The lowered semantics leaves a zero extension's word as it is (`word`), which is the typed +extension on every word whose bits above the source width are zero, as every MIR value's are. -/ +theorem word_eq_zext (bits : Nat) (w : BitVec 256) (clean : w.toNat < 2 ^ bits) : + w = cast .zext 256 (cast .trunc bits w) := by + apply BitVec.eq_of_toNat_eq + simp only [cast, BitVec.toNat_setWidth] + rw [Nat.mod_eq_of_lt clean, Nat.mod_eq_of_lt w.isLt] + +end SolarTV.MIR diff --git a/tv/SolarTV/MIR/Transforms/CheckElim.lean b/tv/SolarTV/MIR/Transforms/CheckElim.lean new file mode 100644 index 00000000..94021788 --- /dev/null +++ b/tv/SolarTV/MIR/Transforms/CheckElim.lean @@ -0,0 +1,19 @@ +import SolarTV.MIR.Ops + +/-! A dominating bound makes the unsigned increment's overflow check redundant. +The operation otherwise retains its defined Panic(0x11) outcome; it is never +modeled as undefined behavior merely because a check fails. -/ + +namespace SolarTV.MIR + +theorem increment_below_bound (value : BitVec 256) (bound : value.ult 100 = true) : + checked .add false value 1 = Outcome.returned (value + 1) := by + have h : value.toNat < 100 := by simpa [BitVec.ult_iff_toNat_lt] using bound + simp [checked, BitVec.uaddOverflow] <;> omega + +/-- Replacing a defined failure by success fails refinement in either direction. -/ +theorem cannot_drop_overflow : + ¬ refines (checked .add false (-1#256) 1) (Outcome.returned (0#256)) := by + simp [checked, BitVec.uaddOverflow] + +end SolarTV.MIR diff --git a/tv/SolarTV/MIR/Transforms/DCE.lean b/tv/SolarTV/MIR/Transforms/DCE.lean new file mode 100644 index 00000000..f293f98f --- /dev/null +++ b/tv/SolarTV/MIR/Transforms/DCE.lean @@ -0,0 +1,18 @@ +import SolarTV.MIR.Ops + +/-! MIR dead-code elimination: removing an unused pure SSA definition. -/ + +namespace SolarTV.MIR + +abbrev Env := Nat → EvmRules.Word + +/-- Removing a pure SSA definition preserves any continuation whose live-ins +exclude the defined ID. Both operands already have defined word values. -/ +theorem erase_unused (op : Op) (dst lhs rhs : Nat) (env : Env) (k : Env → α) + (unused : ∀ x y : Env, (∀ i, i ≠ dst → x i = y i) → k x = k y) : + k (fun i => if i = dst then eval op (env lhs) (env rhs) else env i) = k env := by + apply unused + intro i h + simp [h] + +end SolarTV.MIR diff --git a/tv/SolarTV/MIR/Transforms/DeadStore.lean b/tv/SolarTV/MIR/Transforms/DeadStore.lean new file mode 100644 index 00000000..b45dff41 --- /dev/null +++ b/tv/SolarTV/MIR/Transforms/DeadStore.lean @@ -0,0 +1,18 @@ +import SolarTV.Memory + +/-! MIR memory-dse removes a word store overwritten before any read. +The final store has the same range, so it also subsumes the first expansion. +Both the live return and all projected memory bytes remain observable. The +theorem is independent of the incoming bytes, active size and stored values. -/ + +namespace SolarTV.MIR +open EvmRules + +theorem dead_store (memory : Memory.State) (offset : Nat) (a b : Word) + (result : BitVec width) : + refines (Outcome.returned (⟨result, Memory.store (Memory.store memory offset a) offset b⟩ : + Memory.Returned width)) + (Outcome.returned ⟨result, Memory.store memory offset b⟩) := by + simp [refines_iff_eq, Memory.store, Memory.expand] + +end SolarTV.MIR diff --git a/tv/SolarTV/MIR/Transforms/RenamePhiPredecessors.lean b/tv/SolarTV/MIR/Transforms/RenamePhiPredecessors.lean new file mode 100644 index 00000000..1867cf61 --- /dev/null +++ b/tv/SolarTV/MIR/Transforms/RenamePhiPredecessors.lean @@ -0,0 +1,22 @@ +import SolarTV.MIR.Ops + +/-! Phi selection is preserved when CFG labels are renamed injectively. +Actual cfg-simplify pairs can also remove forwarders; the pair checker expands +those paths and checks the resulting phi values against the original graph. -/ + +namespace SolarTV.MIR + +theorem rename_phi_predecessors (rename : Nat → Nat) (injective : Function.Injective rename) + (predecessor : Nat) (incoming : List (Nat × EvmRules.Word)) : + phi (rename predecessor) (incoming.map (fun (block, value) => (rename block, value))) = + phi predecessor incoming := by + induction incoming with + | nil => rfl + | cons entry rest ih => + obtain ⟨block, value⟩ := entry + have same : rename predecessor = rename block ↔ predecessor = block := + ⟨fun h => injective h, congrArg rename⟩ + simp only [List.map_cons, phi, same] + split <;> simp_all + +end SolarTV.MIR diff --git a/tv/SolarTV/MIR/Transforms/TrimSwitchDefaults.lean b/tv/SolarTV/MIR/Transforms/TrimSwitchDefaults.lean new file mode 100644 index 00000000..c54f6108 --- /dev/null +++ b/tv/SolarTV/MIR/Transforms/TrimSwitchDefaults.lean @@ -0,0 +1,47 @@ +import SolarTV.MIR.Ops + +/-! MIR cfg-simplify: trim trailing switch cases that jump to the default target. -/ + +namespace SolarTV.MIR + +/-- One past the last non-default destination, or zero if there is none. +This is the prefix length computed by Rust's `rposition(...).map_or(0, |i| i + 1)`. -/ +def keepLength (fallback : Nat) : List Case → Nat + | [] => 0 + | (_, dst) :: rest => + match keepLength fallback rest with + | 0 => if dst = fallback then 0 else 1 + | n + 1 => n + 2 + +theorem trim_preserves_dispatch (read : Nat → EvmRules.Word) (key : EvmRules.Word) + (fallback : Nat) (cases : List Case) : + dispatch read key fallback (cases.take (keepLength fallback cases)) = + dispatch read key fallback cases := by + induction cases with + | nil => rfl + | cons c rest ih => + obtain ⟨id, dst⟩ := c + cases h : keepLength fallback rest with + | zero => + simp [h, dispatch] at ih + by_cases hd : dst = fallback <;> simp [keepLength, h, hd, dispatch, choose, ← ih] + | succ n => + simp only [keepLength, h, List.take_succ_cons, dispatch] + rw [h] at ih + rw [ih] + +/-- At prefix length zero the pass emits a jump. Both forms carry the same predecessor +and register environment into the successor (in particular for phi selection). -/ +theorem simplify_switch (enter : Nat → Nat → (Nat → EvmRules.Word) → α) + (pred fallback : Nat) (read : Nat → EvmRules.Word) (key : EvmRules.Word) (cases : List Case) : + enter pred (if keepLength fallback cases = 0 then fallback + else dispatch read key fallback (cases.take (keepLength fallback cases))) read = + enter pred (dispatch read key fallback cases) read := by + have h := trim_preserves_dispatch read key fallback cases + split + · next hz => + simp [hz, dispatch] at h + exact congrArg (fun dst => enter pred dst read) h + · rw [h] + +end SolarTV.MIR diff --git a/tv/SolarTV/MIR/Validation/AddZero.lean b/tv/SolarTV/MIR/Validation/AddZero.lean new file mode 100644 index 00000000..bf4b040f --- /dev/null +++ b/tv/SolarTV/MIR/Validation/AddZero.lean @@ -0,0 +1,107 @@ +import SolarTV.Composition +import SolarTV.Agreement.Encoder + +/-! Lifting one pass validation query to a stage. + +`tests/ui/codegen/mir/validate-passes/lift_egraph.mir` runs `egraph` on a dispatcher that +reads a calldata word, adds zero to it, shifts one left by it and stores the result: +`egraph` drops the addition. `Query` is the query `-Zvalidate-passes` writes for that +rewrite, stated as the certifier translates it (`crates/smt/src/certify/lean.rs`), and +`query_unsat` proves it. `certified_of_query` then proves, using the query only as a +hypothesis, that the function after the pass is certified against the one before: it runs +both, rewrites their words with the agreement theorems `step_add` and `step_shl` into the +query's terms, and instantiates the query's uninterpreted calldata read, memory, storage +and transient storage with the call's calldata and the initial state. `stage` is the +resulting stage of the lowered MIR semantics. This is one instance, not a general +theorem that every `unsat` query gives a certificate. -/ + +namespace SolarTV.MIR.Validation.AddZero + +open EvmRules Machine MIR.Lowered + +/-- `bb0: v0 = calldataload 0; v1 = add v0, 0; v2 = shl 1, v1; sstore 0, v2; stop`, with +operands in pop order. -/ +def before : Function where + blocks := [⟨[], [.effect (some 0) .calldataload [.const 0], .pure 1 .add [.value 0, .const 0], + .pure 2 .shl [.value 1, .const 1], .effect none .sstore [.const 0, .value 2]], .stop⟩] + +/-- `bb0: v0 = calldataload 0; v2 = shl 1, v0; sstore 0, v2; stop`. -/ +def after : Function where + blocks := [⟨[], [.effect (some 0) .calldataload [.const 0], + .pure 2 .shl [.value 0, .const 1], .effect none .sstore [.const 0, .value 2]], .stop⟩] + +/-- An SMT-LIB array store, as the certifier defines it. -/ +def store {a b : Nat} (m : BitVec a → BitVec b) (i : BitVec a) (v : BitVec b) : + BitVec a → BitVec b := + fun j => if j = i then v else m j + +-- The certifier also turns off the unused-variable linter. +set_option linter.unusedVariables false in +/-- The `egraph` query for `@entry`, as the certifier states it: its assertions are +contradictory. -/ +def Query : Prop := + ∀ («$input_calldataload_1» : BitVec 256 → BitVec 256) («$mem0» : (BitVec 256 → BitVec 8)) + («$sto0» : (BitVec 256 → BitVec 256)) («$tra0» : (BitVec 256 → BitVec 256)) + («$t0» : BitVec 256) («$t1» : BitVec 256) («$t2» : BitVec 256) + («$s3» : (BitVec 256 → BitVec 256)) («$t4» : BitVec 256) («$s5» : (BitVec 256 → BitVec 256)) + (h0 : («$t0» = («$input_calldataload_1» (0x0000000000000000000000000000000000000000000000000000000000000000#256)))) + (h1 : («$t1» = ((0x0000000000000000000000000000000000000000000000000000000000000000#256) + «$t0»))) + (h2 : («$t2» = (if («$t1» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((0x0000000000000000000000000000000000000000000000000000000000000001#256) <<< «$t1»)))) + (h3 : («$s3» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$t2»))) + (h4 : («$t4» = (if («$t0» ≥ (0x0000000000000000000000000000000000000000000000000000000000000100#256)) then (0x0000000000000000000000000000000000000000000000000000000000000000#256) else ((0x0000000000000000000000000000000000000000000000000000000000000001#256) <<< «$t0»)))) + (h5 : («$s5» = (store «$sto0» (0x0000000000000000000000000000000000000000000000000000000000000000#256) «$t4»))) + (h6 : (¬(«$s3» = «$s5»))), + False + +/-- The certifier's `bv_decide` proof does not reach a top-level array disequality, so the +query is proved by hand: adding zero changes nothing. -/ +theorem query_unsat : Query := by + intro _ _ sto0 _ t0 t1 t2 s3 t4 s5 _ h1 h2 h3 h4 h5 h6 + apply h6 + rw [h3, h5, h2, h4, h1, BitVec.zero_add] + +/-- The state the function ends in, writing `value` to slot zero. -/ +def ended (call : Call) (value : Word) : Halt × State := + (.stop, { State.initial call with storage := update (State.initial call).storage 0 value }) + +theorem run_before (o : Oracle) (call : Call) (n : Nat) : + run o before call (n + 1) = some (ended call + (if calldataWord call 0 + 0 ≥ 256#256 then 0#256 else 1#256 <<< (calldataWord call 0 + 0))) := by + rw [before, run_straight] + simp only [execInsts, Operand.eval, List.map, Effect.apply, evalPure, Agreement.step_add, + Agreement.step_shl, Env.set, ↓reduceIte] + rfl + +theorem run_after (o : Oracle) (call : Call) (n : Nat) : + run o after call (n + 1) = some (ended call + (if calldataWord call 0 ≥ 256#256 then 0#256 else 1#256 <<< calldataWord call 0)) := by + rw [after, run_straight] + simp only [execInsts, Operand.eval, List.map, Effect.apply, evalPure, Agreement.step_shl, + Env.set, ↓reduceIte] + rfl + +theorem certified_of_query (query : Query) (o : Oracle) (scope : Call → Prop) : + Certified layer layer o before after scope := by + apply Certified.of_fuel + intro call _ n r ran + cases n with + | zero => simp [layer, run, iterate] at ran + | succ n => + simp only [layer, run_before] at ran + cases ran + refine ⟨1, _, run_after o call 0, ?_⟩ + simp only [ended, Agree, true_and, and_true] + -- The query's array disequality, at the call's calldata and initial storage. + refine Classical.byContradiction fun differ => query (calldataWord call) (fun _ => 0) + (State.initial call).storage (State.initial call).transient (calldataWord call 0) + (0 + calldataWord call 0) _ _ _ _ rfl rfl rfl rfl rfl rfl ?_ + intro same + apply differ + simp only [BitVec.add_comm (calldataWord call 0) 0] + exact same + +theorem stage (o : Oracle) (scope : Call → Prop) : + Stage (sem o) (sem o) before after scope := + stage_of_certified (certified_of_query query_unsat o scope) + +end SolarTV.MIR.Validation.AddZero diff --git a/tv/SolarTV/Machine.lean b/tv/SolarTV/Machine.lean new file mode 100644 index 00000000..be3cf020 --- /dev/null +++ b/tv/SolarTV/Machine.lean @@ -0,0 +1,716 @@ +import SolarTV.Sem +import SolarTV.Memory + +/-! The machine state MIR and EVM IR programs share, and the semantics of a layer. + +Memory is the model of [Memory.lean](Memory.lean) on every byte: its active-word count, +expansion through `Memory.grow` with natural-number offsets, its `MSIZE` formula and +`Memory.byte` order. `Mem.project` is its 256-byte `Memory.State`, and the `project_` +lemmas show that every operation agrees with it there. Storage and transient storage +are total maps. The world is the history of the logs and calls the frame made, and of its +`GAS` reads. `CALLDATACOPY` and `MCOPY` write memory as `Mem.write`, after the expansion +of every range they touch, with calldata zero past its end. + +What the frame cannot see is an `Oracle`: environment reads, and the result and the state +after a call, are functions of the world, as the pass validation encoder takes them to be +uninterpreted functions of its world. An external call (`CALL`, `CALLCODE`, `DELEGATECALL`, +`STATICCALL`) records what its callee sees: the gas, address and value words and the input +bytes, with the storage and transient storage it may reenter. Its success flag (0 or 1), the +size and bytes of the return data, and for every call but `STATICCALL` the storage and +transient storage after it are the oracle's, as functions of the world with the call; the +callee cannot touch the caller's memory, so memory only takes the return data at the output +range, at most as many bytes as the return data has, after the expansion of both ranges. +`RETURNDATACOPY` reads the same return data, and copying past its end is an exceptional halt. `KECCAK256` is the oracle's `keccak`, a function of the +hashed bytes alone that every layer shares, so the same bytes hash to the same word. A layer +runs a program on a call with fuel; its `Sem` is fuel-free, the end some fuel reaches. One +frame, no gas: `GAS` is an environment read, but one the world records, so that each read is +a function of a history no other read has and two reads need not agree. A stage then holds for +every gas the frame may have left at each read, as passes may change the gas the code uses; +it needs both programs to read gas in the same order among their logs and calls. An immutable +is a value fixed at deployment: the oracle's environment read `immutable` of its number in the +empty world, the same wherever and whenever the frame reads it. The deployment code writes it +over each of its placeholders, a `PUSH` of zeros in the runtime code, which then pushes the +low `N` bytes of that word (`immutableWord`); a load decodes them as the compiler does +(`ImmutableRead`). The frame's code is such a read too, byte by byte (`code`), which `CODECOPY` +copies like calldata, zero past its end; it holds the program data, +such as the creation code of a contract the frame creates, at the offsets the stages take from +the assembled code. `CREATE` and `CREATE2` record their value, salt, code and state in the world +as a call does, and the new address and the storage after them are the oracle's. -/ + +namespace SolarTV.Machine + +open EvmRules + +/-- Memory on every byte, with the active-word count of `Memory.State`. -/ +structure Mem where + bytes : Nat → Memory.Byte + words : BitVec 251 + +namespace Mem + +def initial : Mem := ⟨fun _ => 0, 0⟩ + +/-- The first 256 bytes and the active size, as the importers model memory. -/ +def project (m : Mem) : Memory.State := ⟨(List.range 256).map m.bytes, m.words⟩ + +def expand (m : Mem) (offset size : Nat) : Mem := + if size = 0 then m + else { m with words := Memory.grow m.words (BitVec.ofNat 251 ((offset + size + 31) / 32)) } + +def msize (m : Mem) : Word := m.words.setWidth 256 <<< 5 + +def read (m : Mem) (offset size : Nat) : List Memory.Byte := + (List.range size).map (fun i => m.bytes (offset + i)) + +def load (m : Mem) (offset : Nat) : Word := + (m.read offset 32).foldl (fun acc b => (acc <<< 8) ||| b.setWidth 256) 0 + +def store (m : Mem) (offset : Nat) (value : Word) : Mem := + expand { m with bytes := fun i => + if offset ≤ i ∧ i < offset + 32 then Memory.byte value (i - offset) else m.bytes i } offset 32 + +def storeByte (m : Mem) (offset : Nat) (value : Word) : Mem := + expand { m with bytes := fun i => if i = offset then value.setWidth 8 else m.bytes i } offset 1 + +/-- `size` bytes of `source` written from `offset`, as a copy writes them. -/ +def write (m : Mem) (offset size : Nat) (source : Nat → Memory.Byte) : Mem := + expand { m with bytes := fun i => + if offset ≤ i ∧ i < offset + size then source (i - offset) else m.bytes i } offset size + +/-- A load reads bytes, which expansion leaves as they are. -/ +theorem load_expand (m : Mem) (offset size address : Nat) : + (m.expand offset size).load address = m.load address := by + unfold expand + split <;> rfl + +/-- Expanding memory again over the same range changes nothing. -/ +theorem expand_expand (m : Mem) (offset size : Nat) : + (m.expand offset size).expand offset size = m.expand offset size := by + unfold expand + split <;> simp only [Memory.grow_idempotent] + +/-- A store already expanded memory over its word, as a load of that word would. -/ +theorem expand_store (m : Mem) (offset : Nat) (value : Word) : + (m.store offset value).expand offset 32 = m.store offset value := by + unfold store + exact expand_expand _ _ _ + +/-- A load reads none of the bytes a write outside its word writes. -/ +theorem load_write_of_disjoint (m : Mem) (offset size address : Nat) (source : Nat → Memory.Byte) + (disjoint : address + 32 ≤ offset ∨ offset + size ≤ address) : + (m.write offset size source).load address = m.load address := by + unfold write + rw [load_expand] + unfold load read + congr 1 + apply List.map_congr_left + intro i mem + simp only [List.mem_range] at mem + have : ¬(offset ≤ address + i ∧ address + i < offset + size) := by omega + simp only [this, if_false] + +/-- A store is a write of the value's bytes. -/ +theorem store_eq_write (m : Mem) (offset : Nat) (value : Word) : + m.store offset value = m.write offset 32 (Memory.byte value) := rfl + +/-- A load reads none of the bytes a store outside its word writes. -/ +theorem load_store_of_disjoint (m : Mem) (offset address : Nat) (value : Word) + (disjoint : address + 32 ≤ offset ∨ offset + 32 ≤ address) : + (m.store offset value).load address = m.load address := by + rw [store_eq_write] + exact load_write_of_disjoint m offset 32 address _ disjoint + +/-- Memory a call starts with reads as zero everywhere. -/ +theorem load_initial (address : Nat) : initial.load address = 0 := by + unfold load read initial + generalize List.range 32 = l + suffices h : ∀ acc : Word, acc = 0 → + (l.map (fun _ => (0 : Memory.Byte))).foldl + (fun (acc : Word) (b : Memory.Byte) => (acc <<< 8) ||| b.setWidth 256) acc = 0 from + h 0 rfl + induction l with + | nil => intro acc h; exact h + | cons _ l ih => + intro acc h + subst h + exact ih _ (by simp) + +/-- One more byte of a word, from the top: the word shifted right by one byte less. -/ +private theorem step_bytes (v : BitVec 256) (n : Nat) (h : n < 32) : + ((v >>> (8 * (32 - n))) <<< 8) ||| (SolarTV.Memory.byte v n).setWidth 256 = + v >>> (8 * (32 - (n + 1))) := by + apply BitVec.eq_of_getLsbD_eq + intro j hj + simp only [SolarTV.Memory.byte, BitVec.getLsbD_or, BitVec.getLsbD_shiftLeft, + BitVec.getLsbD_ushiftRight, BitVec.getLsbD_setWidth] + by_cases hj8 : j < 8 + · simp only [hj8, decide_true, Bool.true_and, Bool.not_true, Bool.false_and, Bool.false_or, hj] + have : 8 * (31 - n) + j = 8 * (32 - (n + 1)) + j := by omega + rw [this] + · have h1 : ¬ (j < 8) := hj8 + simp only [h1, decide_false, Bool.false_and, Bool.not_false] + simp only [hj, decide_true, Bool.true_and, Bool.or_false] + have : 8 * (32 - n) + (j - 8) = 8 * (32 - (n + 1)) + j := by omega + rw [this] + +/-- A word's first `n` bytes, big-endian, as a load folds them: its top `n` bytes. -/ +private theorem fold_bytes (v : BitVec 256) (n : Nat) (h : n ≤ 32) : + ((List.range n).map (SolarTV.Memory.byte v)).foldl + (fun (acc : BitVec 256) (b : SolarTV.Memory.Byte) => (acc <<< 8) ||| b.setWidth 256) + (0 : BitVec 256) = v >>> (8 * (32 - n)) := by + induction n with + | zero => + simp only [List.range_zero, List.map_nil, List.foldl_nil] + apply BitVec.eq_of_getLsbD_eq + intro j hj + simp only [BitVec.getLsbD_ushiftRight, BitVec.getLsbD_zero] + rw [BitVec.getLsbD_of_ge v _ (by omega)] + simp + | succ n ih => + rw [List.range_succ, List.map_append, List.foldl_append, ih (by omega)] + simp only [List.map_cons, List.map_nil, List.foldl_cons, List.foldl_nil] + exact step_bytes v n (by omega) + +/-- A load of the word a store wrote reads it back. -/ +theorem load_store_same (m : Mem) (offset : Nat) (value : Word) : + (m.store offset value).load offset = value := by + unfold store + rw [load_expand] + unfold load read + have : (List.range 32).map (fun i => + (if offset ≤ offset + i ∧ offset + i < offset + 32 then + SolarTV.Memory.byte value (offset + i - offset) else m.bytes (offset + i))) = + (List.range 32).map (SolarTV.Memory.byte value) := by + apply List.map_congr_left + intro i mem + simp only [List.mem_range] at mem + have c : offset ≤ offset + i ∧ offset + i < offset + 32 := by omega + simp only [c, and_self, ite_true, Nat.add_sub_cancel_left] + simp only [this] + rw [fold_bytes value 32 (by omega)] + simp + +theorem grow_comm (w a b : BitVec 251) : + Memory.grow (Memory.grow w a) b = Memory.grow (Memory.grow w b) a := by + unfold Memory.grow + simp only [BitVec.ult_iff_toNat_lt] + repeat' split + all_goals first | rfl | (apply BitVec.eq_of_toNat_eq; omega) | omega + +/-- A store as the bytes it writes and the words it grows memory to. -/ +theorem store_eq (m : Mem) (a : Nat) (v : Word) : + m.store a v = ⟨fun i => if a ≤ i ∧ i < a + 32 then Memory.byte v (i - a) else m.bytes i, + Memory.grow m.words (BitVec.ofNat 251 ((a + 32 + 31) / 32))⟩ := rfl + +/-- Expansions commute: each grows memory to the larger of its size and the current one. -/ +theorem expand_comm (m : Mem) (o s o' s' : Nat) : + (m.expand o s).expand o' s' = (m.expand o' s').expand o s := by + unfold expand + by_cases h : s = 0 <;> by_cases h' : s' = 0 <;> simp only [h, h', ite_true, ite_false] + rw [grow_comm] + +/-- A store after an expansion is the store, then the expansion. -/ +theorem store_expand_comm (m : Mem) (o s a : Nat) (v : Word) : + (m.expand o s).store a v = (m.store a v).expand o s := by + unfold expand + by_cases h : s = 0 + · simp only [h, ite_true] + · simp only [h, ite_false, store_eq] + rw [grow_comm] + +/-- A store over a word a store wrote leaves only the later value. -/ +theorem store_store_same (m : Mem) (a : Nat) (v w : Word) : + (m.store a v).store a w = m.store a w := by + simp only [store_eq, Memory.grow_idempotent, Mem.mk.injEq, and_true] + funext i + split <;> simp_all + +/-- Stores to disjoint words commute. -/ +theorem store_store_comm (m : Mem) (a b : Nat) (v w : Word) (h : a + 32 ≤ b) : + (m.store b w).store a v = (m.store a v).store b w := by + simp only [store_eq, Mem.mk.injEq] + refine ⟨?_, grow_comm _ _ _⟩ + funext i + by_cases h1 : a ≤ i ∧ i < a + 32 <;> by_cases h2 : b ≤ i ∧ i < b + 32 <;> + simp only [h1, h2, ite_false] <;> omega + +theorem project_initial : initial.project = Memory.initial [] 0 := by + unfold project initial Memory.initial + congr 1 + +theorem project_expand (m : Mem) (offset size : Nat) : + (m.expand offset size).project = Memory.expand m.project offset size := by + unfold expand Memory.expand project + split <;> rfl + +theorem project_msize (m : Mem) : m.msize = Memory.msize m.project := rfl + +theorem project_read (m : Mem) (offset size : Nat) (bounded : offset + size ≤ 256) : + m.read offset size = Memory.read m.project offset size := by + unfold read Memory.read project + apply List.map_congr_left + intro i mem + have : offset + i < 256 := by simp at mem; omega + simp [this] + +theorem project_load (m : Mem) (offset : Nat) (bounded : offset + 32 ≤ 256) : + m.load offset = Memory.load m.project offset := by + unfold load Memory.load + rw [project_read m offset 32 bounded] + +theorem project_store (m : Mem) (offset : Nat) (value : Word) : + (m.store offset value).project = Memory.store m.project offset value := by + unfold store Memory.store + rw [project_expand] + apply congrArg (Memory.expand · offset 32) + simp only [project, Memory.writeWord] + rw [Memory.State.mk.injEq] + refine ⟨?_, rfl⟩ + apply List.ext_getElem (by simp only [List.length_map, List.length_mapIdx]) + intro i h _ + simp only [List.getElem_map, List.getElem_range, List.getElem_mapIdx] + +theorem project_storeByte (m : Mem) (offset : Nat) (value : Word) : + (m.storeByte offset value).project = Memory.storeByte m.project offset value := by + unfold storeByte Memory.storeByte + rw [project_expand] + apply congrArg (Memory.expand · offset 1) + simp only [project] + rw [Memory.State.mk.injEq] + refine ⟨?_, rfl⟩ + apply List.ext_getElem (by simp only [List.length_map, List.length_set]) + intro i h _ + simp only [List.getElem_map, List.getElem_range, List.getElem_set] + by_cases e : i = offset + · subst e; simp + · have e' : ¬offset = i := fun h => e h.symm + simp only [e, e', ↓reduceIte] + +end Mem + +/-- The external calls. -/ +inductive CallKind where + | call | callcode | delegatecall | staticcall + deriving DecidableEq + +/-- An event of the frame: a log, a call with its operands and the state it sees, or a read +of a word that changes as the frame runs, such as `GAS`. -/ +inductive Event where + | log (topics : List Word) (data : List Memory.Byte) + | call (kind : CallKind) (operands : List Word) (input : List Memory.Byte) + (storage transient : Word → Word) + | read (name : String) + /-- A contract creation: its value (and `CREATE2`'s salt), the creation code and the state the + new contract may reenter. -/ + | create (operands : List Word) (code : List Memory.Byte) (storage transient : Word → Word) + +structure State where + memory : Mem + storage : Word → Word + transient : Word → Word + world : List Event + +/-- The state a call starts in: zeroed memory, the call's storage, no events. -/ +def State.initial (call : Call) : State := + ⟨Mem.initial, fun slot => BitVec.ofNat 256 (slotValue call.storage slot.toNat), fun _ => 0, []⟩ + +theorem State.initial_memory (call : Call) : (State.initial call).memory = Mem.initial := rfl + +/-- What the frame cannot see, as functions of the world (`Encoder`'s `env_`, `result` +and the state after a call event). The size of the return data is the environment read +`returndatasize` and its byte `i` the low byte of the read `returndata` of `i`. -/ +structure Oracle where + env : String → List Event → List Word → Word + result : List Event → Word + storageAfter : List Event → Word → Word + transientAfter : List Event → Word → Word + /-- The hash of a byte string. Uninterpreted, but a function, so hashing is deterministic. -/ + keccak : List Memory.Byte → Word + /-- The address that made the call (`CALLER`): any address, so that what holds for every + oracle holds for every caller. -/ + caller : BitVec 160 + +/-- The big-endian word of calldata at an offset, zero past its end. -/ +def calldataWord (call : Call) (offset : Word) : Word := + (List.range 32).foldl + (fun acc i => (acc <<< 8) ||| BitVec.ofNat 256 (call.calldata.data.getD (offset.toNat + i) 0).toNat) 0 + +/-- The calldata byte at an offset, zero past its end. -/ +def calldataByte (call : Call) (offset : Nat) : Memory.Byte := + BitVec.ofNat 8 (call.calldata.data.getD offset 0).toNat + +/-- `store m k v` as the certifier translates an SMT-LIB array store. -/ +def update (m : Word → Word) (key value : Word) : Word → Word := + fun j => if j = key then value else m j + +/-- How a load of an immutable decodes the word its placeholder pushes, as the code after the +push does: as it is (a full word, or a value zero-extended from the placeholder's bytes), +sign-extended from byte `byte` (`SIGNEXTEND`, a signed integer), or shifted left by `bits` +(`SHL`, fixed bytes the placeholder holds right-aligned). -/ +inductive ImmutableRead where + | word + | signExtend (byte : Word) + | shiftLeft (bits : Word) + +def ImmutableRead.apply : ImmutableRead → Word → Word + | .word, x => x + | .signExtend byte, x => Evm.signextend byte x + | .shiftLeft bits, x => Evm.shl bits x + +/-- The value fixed at deployment for immutable `id`. -/ +def immutableValue (o : Oracle) (id : Nat) : Word := o.env "immutable" [] [BitVec.ofNat 256 id] + +/-- The word a `PUSH` placeholder of immutable `id` pushes: the low `bytes` bytes of the +value, which the deployment code writes there. -/ +def immutableWord (o : Oracle) (id bytes : Nat) : Word := + if bytes < 32 then BitVec.ofNat 256 ((immutableValue o id).toNat % 2 ^ (8 * bytes)) + else immutableValue o id + +/-- The word a placeholder of width `bytes` pushes in the stages is the value a deployment +links there: the immutable's value modulo `256 ^ bytes`. -/ +theorem immutableWord_toNat (o : Oracle) (id bytes : Nat) (b1 : 1 ≤ bytes) (b32 : bytes ≤ 32) : + (immutableWord o id bytes).toNat = (immutableValue o id).toNat % 256 ^ bytes := by + have pow : 2 ^ (8 * bytes) = 256 ^ bytes := by + rw [Nat.pow_mul] + unfold immutableWord + split + · rw [BitVec.toNat_ofNat, pow] + apply Nat.mod_eq_of_lt + have : 256 ^ bytes ≤ 2 ^ 256 := by + rw [← pow]; exact Nat.pow_le_pow_right (by decide) (by omega) + have := Nat.mod_lt (immutableValue o id).toNat (Nat.pow_pos (n := bytes) (by decide : 0 < 256)) + omega + · have : bytes = 32 := by omega + subst this + rw [Nat.mod_eq_of_lt] + exact (immutableValue o id).isLt + +inductive Effect where + | mload | mstore | mstore8 | msize | sload | sstore | tload | tstore + | calldataload | calldatasize | callvalue | caller | address | returndatasize + | log (topics : Nat) + | keccak256 + | env (name : String) + | call (kind : CallKind) + | calldatacopy | mcopy | returndatacopy + | gas + /-- Immutable `id` from its `PUSH` placeholder, decoded by `read` (`loadimmutable`; + the placeholder push itself reads `.word`). -/ + | immutable (id bytes : Nat) (read : ImmutableRead) + | codecopy | create | create2 + +/-- The size of the return data the world's last call left. -/ +abbrev returndataSize (o : Oracle) (world : List Event) : Word := o.env "returndatasize" world [] + +/-- Byte `i` of the return data the world's last call left. -/ +def returndataByte (o : Oracle) (world : List Event) (i : Nat) : Memory.Byte := + (o.env "returndata" world [BitVec.ofNat 256 i]).setWidth 8 + +/-- A call's operands in pop order: the words its callee sees (gas, address and, for `CALL` +and `CALLCODE`, value), and its input and output offsets and sizes. -/ +def CallKind.shape : CallKind → List Word → Option (List Word × Word × Word × Word × Word) + | .call, [gas, address, value, inOffset, inSize, outOffset, outSize] + | .callcode, [gas, address, value, inOffset, inSize, outOffset, outSize] => + some ([gas, address, value], inOffset, inSize, outOffset, outSize) + | .delegatecall, [gas, address, inOffset, inSize, outOffset, outSize] + | .staticcall, [gas, address, inOffset, inSize, outOffset, outSize] => + some ([gas, address], inOffset, inSize, outOffset, outSize) + | _, _ => none + +/-- The state after an external call whose world, with the call, is `world`. -/ +def called (o : Oracle) (kind : CallKind) (s : State) (memory : Mem) (outOffset outSize : Word) + (world : List Event) : State := + let copied := min outSize.toNat (returndataSize o world).toNat + let memory := memory.write outOffset.toNat copied (returndataByte o world) + match kind with + | .staticcall => { s with memory, world } + | _ => ⟨memory, o.storageAfter world, o.transientAfter world, world⟩ + +/-- Byte `i` of the frame's code, the oracle's environment read `code` of `i` in the empty world. -/ +def codeByte (o : Oracle) (i : Nat) : Memory.Byte := + (o.env "code" [] [BitVec.ofNat 256 i]).setWidth 8 + +/-- A contract creation with the operands its new contract sees (value, and `CREATE2`'s salt) +and its creation code at `offset`: the new address (the low 160 bits of the oracle's result, +zero for a failed creation), and the storage after it, as after a call; memory only expands. -/ +def created (o : Oracle) (s : State) (seen : List Word) (offset size : Word) : + Option Word × State := + let memory := s.memory.expand offset.toNat size.toNat + let world := s.world ++ [.create seen (memory.read offset.toNat size.toNat) s.storage s.transient] + (some (BitVec.ofNat 256 ((o.result world).toNat % 2 ^ 160)), + ⟨memory, o.storageAfter world, o.transientAfter world, world⟩) + +/-- A call's success flag. -/ +def callFlag (o : Oracle) (world : List Event) : Word := if o.result world = 0 then 0 else 1 + +/-- An effect on its operands, in pop order: its result, if any, and the state after it; +`none` for operands of the wrong arity. -/ +def Effect.apply (o : Oracle) (call : Call) : Effect → List Word → State → Option (Option Word × State) + | .mload, [offset], s => + some (some (s.memory.load offset.toNat), { s with memory := s.memory.expand offset.toNat 32 }) + | .mstore, [offset, value], s => some (none, { s with memory := s.memory.store offset.toNat value }) + | .mstore8, [offset, value], s => + some (none, { s with memory := s.memory.storeByte offset.toNat value }) + | .msize, [], s => some (some s.memory.msize, s) + | .sload, [key], s => some (some (s.storage key), s) + | .sstore, [key, value], s => some (none, { s with storage := update s.storage key value }) + | .tload, [key], s => some (some (s.transient key), s) + | .tstore, [key, value], s => some (none, { s with transient := update s.transient key value }) + | .calldataload, [offset], s => some (some (calldataWord call offset), s) + | .calldatasize, [], s => some (some (BitVec.ofNat 256 call.calldata.size), s) + | .callvalue, [], s => some (some (BitVec.ofNat 256 call.callvalue), s) + | .caller, [], s => some (some (o.caller.setWidth 256), s) + | .address, [], s => some (some (BitVec.ofNat 256 environment.callee), s) + | .returndatasize, [], s => some (some (o.env "returndatasize" s.world []), s) + | .log n, offset :: size :: topics, s => + if topics.length = n then + let memory := s.memory.expand offset.toNat size.toNat + some (none, { s with + memory, world := s.world ++ [.log topics (memory.read offset.toNat size.toNat)] }) + else none + | .keccak256, [offset, size], s => + let memory := s.memory.expand offset.toNat size.toNat + some (some (o.keccak (memory.read offset.toNat size.toNat)), { s with memory }) + | .env name, operands, s => some (some (o.env name s.world operands), s) + | .calldatacopy, [dest, offset, size], s => + let memory := s.memory.write dest.toNat size.toNat (fun i => calldataByte call (offset.toNat + i)) + some (none, { s with memory }) + | .mcopy, [dest, source, size], s => + let read := s.memory.expand source.toNat size.toNat + let memory := read.write dest.toNat size.toNat (fun i => read.bytes (source.toNat + i)) + some (none, { s with memory }) + | .immutable id bytes read, [], s => some (some (read.apply (immutableWord o id bytes)), s) + | .codecopy, [dest, offset, size], s => + let memory := s.memory.write dest.toNat size.toNat (fun i => codeByte o (offset.toNat + i)) + some (none, { s with memory }) + | .create, [value, offset, size], s => some (created o s [value] offset size) + | .create2, [value, offset, size, salt], s => some (created o s [value, salt] offset size) + | .gas, [], s => + let world := s.world ++ [.read "gas"] + some (some (o.env "gas" world []), { s with world }) + | .returndatacopy, [dest, offset, size], s => + if (returndataSize o s.world).toNat < offset.toNat + size.toNat then none + else + let memory := s.memory.write dest.toNat size.toNat + (fun i => returndataByte o s.world (offset.toNat + i)) + some (none, { s with memory }) + | .call kind, operands, s => + match kind.shape operands with + | none => none + | some (seen, inOffset, inSize, outOffset, outSize) => + let memory := (s.memory.expand inOffset.toNat inSize.toNat).expand outOffset.toNat + outSize.toNat + let world := s.world ++ + [.call kind seen (memory.read inOffset.toNat inSize.toNat) s.storage s.transient] + some (some (callFlag o world), called o kind s memory outOffset outSize world) + | _, _, _ => none + +/-- How a frame ends. `invalid` also stands for every exceptional halt. -/ +inductive Halt where + | stop + | ret (data : List Memory.Byte) + | revert (data : List Memory.Byte) + | invalid + +def logs (s : State) : List (List Nat × List Nat) := + s.world.filterMap fun + | .log topics data => some (topics.map BitVec.toNat, data.map BitVec.toNat) + | .call .. | .read _ | .create .. => none + +def storageOf (s : State) : Nat → Nat := fun slot => (s.storage (BitVec.ofNat 256 slot)).toNat + +def revertData : Halt → List Nat + | .revert data => data.map BitVec.toNat + | _ => [] + +/-- A successful end commits its storage and logs; a failed one rolls them back. -/ +def observe (call : Call) (s : State) : Halt → Observable + | .stop => ⟨true, [], logs s, storageOf s⟩ + | .ret data => ⟨true, data.map BitVec.toNat, logs s, storageOf s⟩ + | .revert data => ⟨false, data.map BitVec.toNat, [], slotValue call.storage⟩ + | .invalid => ⟨false, [], [], slotValue call.storage⟩ + +theorem observe_failure (call : Call) (s : State) (halt : Halt) + (failed : (observe call s halt).success = false) : + (observe call s halt).logs = [] ∧ (observe call s halt).storage = slotValue call.storage ∧ + (observe call s halt).output = revertData halt := by + cases halt <;> simp_all [observe, revertData] + +/-- Two ends no observer tells apart, as `Encoder::differ` compares them: the kind, the +returned bytes (`stop` returns none), and on success storage, transient storage and the +world; a revert compares its data alone. -/ +def Agree : Halt × State → Halt × State → Prop + | (.revert d, _), (.revert e, _) => d = e + | (.invalid, _), (.invalid, _) => True + | (a, s), (b, t) => + (match a, b with + | .stop, .stop => True + | .stop, .ret e => e = [] + | .ret d, .stop => d = [] + | .ret d, .ret e => d = e + | _, _ => False) ∧ + s.storage = t.storage ∧ s.transient = t.transient ∧ s.world = t.world + +theorem Agree.refl (r : Halt × State) : Agree r r := by + obtain ⟨h, s⟩ := r + cases h <;> simp [Agree] + +theorem Agree.trans {a b c : Halt × State} (ab : Agree a b) (bc : Agree b c) : Agree a c := by + obtain ⟨ha, sa⟩ := a + obtain ⟨hb, sb⟩ := b + obtain ⟨hc, sc⟩ := c + cases ha <;> cases hb <;> cases hc <;> simp_all [Agree] + +theorem storageOf_congr {s t : State} (h : s.storage = t.storage) : storageOf s = storageOf t := by + unfold storageOf + rw [h] + +theorem logs_congr {s t : State} (h : s.world = t.world) : logs s = logs t := by + unfold logs + rw [h] + +theorem observe_of_agree (call : Call) {a b : Halt × State} (agree : Agree a b) : + observe call a.2 a.1 = observe call b.2 b.1 := by + obtain ⟨ha, sa⟩ := a + obtain ⟨hb, sb⟩ := b + cases ha <;> cases hb <;> simp only [Agree] at agree <;> simp only [observe] + all_goals first + | exact agree.1.elim + | (obtain ⟨kind, storage, _, world⟩ := agree + rw [storageOf_congr storage, logs_congr world] + try first | rfl | (subst kind; rfl) | (rw [kind]; rfl)) + | (subst agree; rfl) + | rfl + | exact agree.elim + +/-- An iteration that either ends or continues from a new configuration, with fuel. -/ +def iterate {σ : Type} (step : σ → Option ((Halt × State) ⊕ σ)) : Nat → σ → Option (Halt × State) + | 0, _ => none + | n + 1, x => + match step x with + | some (.inl result) => some result + | some (.inr next) => iterate step n next + | none => none + +theorem iterate_mono {σ : Type} (step : σ → Option ((Halt × State) ⊕ σ)) (n : Nat) (x : σ) + (result : Halt × State) (ran : iterate step n x = some result) : + iterate step (n + 1) x = some result := by + induction n generalizing x with + | zero => simp [iterate] at ran + | succ n ih => + unfold iterate at ran ⊢ + cases hs : step x with + | none => simp [hs] at ran + | some v => + cases v with + | inl r => simp_all + | inr y => + simp only [hs] at ran ⊢ + exact ih y ran + +/-- A language whose programs run on a call with fuel, deterministically: more fuel never +changes an end. -/ +structure Layer where + Prog : Type + run : Oracle → Prog → Call → Nat → Option (Halt × State) + mono : ∀ o p call n result, run o p call n = some result → run o p call (n + 1) = some result + +namespace Layer + +variable (L : Layer) + +/-- Some fuel reaches this end. -/ +def Ends (o : Oracle) (p : L.Prog) (call : Call) (result : Halt × State) : Prop := + ∃ n, L.run o p call n = some result + +theorem mono_le {o : Oracle} {p : L.Prog} {call : Call} {result : Halt × State} {n m : Nat} + (le : n ≤ m) (ran : L.run o p call n = some result) : L.run o p call m = some result := by + induction le with + | refl => exact ran + | step _ ih => exact L.mono _ _ _ _ _ ih + +theorem ends_unique {o : Oracle} {p : L.Prog} {call : Call} {a b : Halt × State} + (ea : L.Ends o p call a) (eb : L.Ends o p call b) : a = b := by + obtain ⟨n, hn⟩ := ea + obtain ⟨m, hm⟩ := eb + have := L.mono_le (Nat.le_max_left n m) hn + rw [L.mono_le (Nat.le_max_right n m) hm] at this + exact (Option.some.inj this).symm + +open Classical in +/-- The end of a call, which some fuel reaches, or `none` when no fuel does. -/ +noncomputable def result (o : Oracle) (p : L.Prog) (call : Call) : Option (Halt × State) := + if h : ∃ r, L.Ends o p call r then some h.choose else none + +theorem result_of_ends {o : Oracle} {p : L.Prog} {call : Call} {r : Halt × State} + (ends : L.Ends o p call r) : L.result o p call = some r := by + have h : ∃ r, L.Ends o p call r := ⟨r, ends⟩ + simp only [result, h, dite_true] + exact congrArg some (L.ends_unique h.choose_spec ends) + +theorem ends_of_result {o : Oracle} {p : L.Prog} {call : Call} {r : Halt × State} + (res : L.result o p call = some r) : L.Ends o p call r := by + unfold result at res + split at res + · rename_i h + cases res + exact h.choose_spec + · cases res + +/-- The fuel-free semantics of a layer under an oracle. -/ +noncomputable def sem (o : Oracle) : Sem := + ⟨L.Prog, fun p call => (L.result o p call).map fun r => observe call r.2 r.1⟩ + +theorem sem_failure (o : Oracle) (p : L.Prog) (call : Call) (obs : Observable) + (ran : (L.sem o).run p call = some obs) (failed : obs.success = false) : + ∃ r, L.Ends o p call r ∧ obs.logs = [] ∧ obs.storage = slotValue call.storage ∧ + obs.output = revertData r.1 := by + simp only [sem, Option.map_eq_some_iff] at ran + obtain ⟨r, res, rfl⟩ := ran + exact ⟨r, L.ends_of_result res, observe_failure call r.2 r.1 failed⟩ + +theorem failureConvention (o : Oracle) : (L.sem o).FailureConvention := by + intro p call obs ran failed + obtain ⟨_, _, logs, storage, _⟩ := L.sem_failure o p call obs ran failed + exact ⟨logs, storage⟩ + +end Layer + +/-- Every end `p` reaches on a call in scope, `q` reaches an end that agrees with. This is +what an `unsat` pass validation query states, and it gives a stage. -/ +def Certified (A B : Layer) (o : Oracle) (p : A.Prog) (q : B.Prog) (scope : Call → Prop) : Prop := + ∀ call, scope call → ∀ r, A.Ends o p call r → ∃ r', B.Ends o q call r' ∧ Agree r r' + +theorem stage_of_certified {A B : Layer} {o : Oracle} {p : A.Prog} {q : B.Prog} + {scope : Call → Prop} (certified : Certified A B o p q scope) : + Stage (A.sem o) (B.sem o) p q scope := by + intro call inScope obs ran + simp only [Layer.sem, Option.map_eq_some_iff] at ran ⊢ + obtain ⟨r, res, rfl⟩ := ran + obtain ⟨r', ends, agree⟩ := certified call inScope r (A.ends_of_result res) + exact ⟨r', B.result_of_ends ends, (observe_of_agree call agree).symm⟩ + +theorem Certified.refl (A : Layer) (o : Oracle) (p : A.Prog) (scope : Call → Prop) : + Certified A A o p p scope := + fun _ _ r ends => ⟨r, ends, Agree.refl r⟩ + +theorem Certified.trans {A B C : Layer} {o : Oracle} {p : A.Prog} {q : B.Prog} {r : C.Prog} + {scope : Call → Prop} (first : Certified A B o p q scope) + (second : Certified B C o q r scope) : Certified A C o p r scope := by + intro call inScope x ends + obtain ⟨y, ey, xy⟩ := first call inScope x ends + obtain ⟨z, ez, yz⟩ := second call inScope y ey + exact ⟨z, ez, xy.trans yz⟩ + +/-- A certificate from runs at given fuel: for every fuel at which `p` ends, `q` ends at +some fuel in an agreeing end. -/ +theorem Certified.of_fuel {A B : Layer} {o : Oracle} {p : A.Prog} {q : B.Prog} + {scope : Call → Prop} + (runs : ∀ call, scope call → ∀ n r, A.run o p call n = some r → + ∃ m r', B.run o q call m = some r' ∧ Agree r r') : + Certified A B o p q scope := by + intro call inScope r ⟨n, hn⟩ + obtain ⟨m, r', hm, agree⟩ := runs call inScope n r hn + exact ⟨r', ⟨m, hm⟩, agree⟩ + +end SolarTV.Machine diff --git a/tv/SolarTV/Memory.lean b/tv/SolarTV/Memory.lean new file mode 100644 index 00000000..cd1bff71 --- /dev/null +++ b/tv/SolarTV/Memory.lean @@ -0,0 +1,116 @@ +import SolarTV.Outcome +import EvmRules.Word +import SolarTV.Keccak + +/-! Byte-addressed memory shared by the MIR and EVM IR importers. +The current projection retains the first 256 bytes and the complete active-word +count. Importers admit only constant accesses inside that prefix. Incoming bytes +are arbitrary in active words and zero outside them; bytes beyond the projection +are unchanged by every admitted operation. This is a projected-state model, not +a bounded-address assumption on a symbolic pointer. + +Expansion follows EVMYulLean 047f630, MachineStateOps.lean:24-33: zero-length +accesses do not expand, and offset + length is natural arithmetic, not wrapping +word arithmetic. Byte order and the low byte of MSTORE8 follow lines 35-68. +Gas remains outside this fragment. -/ + +namespace SolarTV.Memory +open EvmRules + +abbrev Byte := BitVec 8 + +structure State where + bytes : List Byte + words : BitVec 251 + deriving DecidableEq + +/-- Big-endian byte i of a word. -/ +def byte (value : Word) (i : Nat) : Byte := + (value >>> (8 * (31 - i))).setWidth 8 + +/-- The count covers all representable, word-aligned MSIZE values. +The importer limits accesses to eight words, so expansion cannot overflow it. -/ +def initial (values : List Word) (words : BitVec 251) : State := + ⟨(List.range 256).map (fun i => + if (BitVec.ofNat 251 (i / 32)).ult words then byte (values[i / 32]?.getD 0) (i % 32) + else 0), words⟩ + +def grow (words required : BitVec 251) : BitVec 251 := + if words.ult required then required else words + +@[simp] theorem grow_idempotent (words required : BitVec 251) : + grow (grow words required) required = grow words required := by + unfold grow + split <;> simp_all [BitVec.ult_iff_toNat_lt] + +def expand (memory : State) (offset size : Nat) : State := + if size = 0 then memory + else + let required := BitVec.ofNat 251 ((offset + size + 31) / 32) + { memory with words := grow memory.words required } + +def msize (memory : State) : Word := memory.words.setWidth 256 <<< 5 + +def read (memory : State) (offset size : Nat) : List Byte := + (List.range size).map (fun i => memory.bytes[offset + i]?.getD 0) + +def load (memory : State) (offset : Nat) : Word := + (read memory offset 32).foldl (fun acc b => (acc <<< 8) ||| b.setWidth 256) 0 + +def writeWord (bytes : List Byte) (offset : Nat) (value : Word) : List Byte := + bytes.mapIdx (fun i old => if offset ≤ i ∧ i < offset + 32 then byte value (i - offset) else old) + +@[simp] theorem writeWord_overwrite (bytes : List Byte) (offset : Nat) (a b : Word) : + writeWord (writeWord bytes offset a) offset b = writeWord bytes offset b := by + simp only [writeWord, List.mapIdx_mapIdx] + congr 1 + funext i old + split <;> simp_all + +def store (memory : State) (offset : Nat) (value : Word) : State := + let bytes := writeWord memory.bytes offset value + expand { memory with bytes } offset 32 + +def storeByte (memory : State) (offset : Nat) (value : Word) : State := + expand { memory with bytes := memory.bytes.set offset (value.setWidth 8) } offset 1 + +/-- Snapshot the source before writing, including overlapping MCOPY ranges. -/ +def copy (memory : State) (destination source count : Nat) : State := + if count = 0 then memory else + let bytes := memory.bytes.mapIdx (fun i old => + if destination ≤ i ∧ i < destination + count then + memory.bytes[source + i - destination]?.getD 0 else old) + expand (expand {memory with bytes} source count) destination count + +def hash (memory : State) (offset count : Nat) : Word := + Keccak.hash (read memory offset count) + +/-- Only witness discovery uses this projection. Concrete witnesses are replayed +against equality of the actual modeled executions in Lean's kernel. -/ +def snapshot (memory : State) : List Word := + msize memory :: memory.bytes.map (fun b => b.setWidth 256) + +def describe (memory : State) : String := + let values := (List.range 8).map (fun i => (load memory (i * 32)).toNat) + s!"msize={msize memory |>.toNat}, memory={values}" + +structure Returned (width : Nat) where + value : BitVec width + memory : State + deriving DecidableEq + +def code (result : Outcome (Returned width)) : List Word := + match result with + | .returned result => 0 :: result.value.setWidth 256 :: snapshot result.memory + | .reverted .empty => [1] + | .reverted (.panic value) => [2, value] + | .invalid => [3] + +def describeReturn (result : Outcome (Returned width)) : String := + match result with + | .returned result => s!"return={result.value.toNat}, {describe result.memory}" + | .reverted .empty => "revert(empty)" + | .reverted (.panic value) => s!"revert Panic({value.toNat})" + | .invalid => "invalid" + +end SolarTV.Memory diff --git a/tv/SolarTV/MemorySafety.lean b/tv/SolarTV/MemorySafety.lean new file mode 100644 index 00000000..42672776 --- /dev/null +++ b/tv/SolarTV/MemorySafety.lean @@ -0,0 +1,19 @@ +import SolarTV.Memory + +/-! Executable checks of byte order, overlapping writes and exact expansion. +Gas is deliberately not priced yet. These kernel proofs pin the memory rules +used by both IR models, including zero-sized accesses at maximal offsets. -/ + +namespace SolarTV.Memory + +set_option maxRecDepth 4096 + +example : (expand (initial [] 0) (2^256 - 1) 0).words = 0 := by decide +example : msize (expand (initial [] 0) 1 32) = 64 := by decide +example : load (initial [0xffff] 0) 0 = 0 := by decide +example : load (initial [0x1234] 1) 0 = 0x1234 := by decide +example : load (store (initial [] 0) 1 0x1234) 1 = 0x1234 := by decide +example : load (storeByte (store (initial [] 0) 0 0x1234) 31 0x1ff) 0 = 0x12ff := by decide +example : load (storeByte (initial [] 0) 0 0xff) 0 = (0xff : EvmRules.Word) <<< 248 := by decide + +end SolarTV.Memory diff --git a/tv/SolarTV/MemorySymbolic.lean b/tv/SolarTV/MemorySymbolic.lean new file mode 100644 index 00000000..87e7af02 --- /dev/null +++ b/tv/SolarTV/MemorySymbolic.lean @@ -0,0 +1,264 @@ +import SolarTV.Machine + +/-! Read-over-write laws of `Machine.Mem` at symbolic addresses. + +`Mem` is a total byte map with an active-word count, so a computed offset is just a +natural number: nothing here bounds an address or assumes two pointers are distinct. +Every law that moves a read past a write takes the disjointness, containment or exact +match of the two ranges as a hypothesis over natural numbers, for `omega` (or a caller's +`omega`-based discharger over word `toNat`s) to prove from the path's cases. When it +cannot, the law does not fire and the read stays over the write: overlapping or unproved +ranges fail closed. `read_store` and `bytes_store` give the byte-exact fallback for an +overlap. Expansion stays exact: `words_store` and `words_write` are the active-word +count the semantics defines, with no rounding or bound. -/ + +namespace SolarTV.Machine.Mem +open EvmRules + +/-- The 32 big-endian bytes `store` writes. -/ +def wordBytes (value : Word) : List Memory.Byte := (List.range 32).map (Memory.byte value) + +@[simp] theorem wordBytes_length (value : Word) : (wordBytes value).length = 32 := by + simp [wordBytes] + +@[simp] theorem read_length (m : Mem) (offset size : Nat) : (m.read offset size).length = size := by + simp [read] + +@[simp] theorem read_zero (m : Mem) (offset : Nat) : m.read offset 0 = [] := rfl + +/-! Bytes and active size after each operation. -/ + +@[simp] theorem bytes_expand (m : Mem) (offset size : Nat) : (m.expand offset size).bytes = m.bytes := by + unfold expand; split <;> rfl + +theorem words_expand (m : Mem) (offset size : Nat) : (m.expand offset size).words = + if size = 0 then m.words else Memory.grow m.words (BitVec.ofNat 251 ((offset + size + 31) / 32)) := by + unfold expand; split <;> rfl + +theorem bytes_store (m : Mem) (offset : Nat) (value : Word) (i : Nat) : + (m.store offset value).bytes i = + if offset ≤ i ∧ i < offset + 32 then Memory.byte value (i - offset) else m.bytes i := by + simp [store] + +theorem words_store (m : Mem) (offset : Nat) (value : Word) : + (m.store offset value).words = Memory.grow m.words (BitVec.ofNat 251 ((offset + 32 + 31) / 32)) := by + simp [store, words_expand] + +theorem bytes_storeByte (m : Mem) (offset : Nat) (value : Word) (i : Nat) : + (m.storeByte offset value).bytes i = if i = offset then value.setWidth 8 else m.bytes i := by + simp [storeByte] + +theorem words_storeByte (m : Mem) (offset : Nat) (value : Word) : + (m.storeByte offset value).words = Memory.grow m.words (BitVec.ofNat 251 ((offset + 1 + 31) / 32)) := by + simp [storeByte, words_expand] + +theorem bytes_write (m : Mem) (offset size : Nat) (source : Nat → Memory.Byte) (i : Nat) : + (m.write offset size source).bytes i = + if offset ≤ i ∧ i < offset + size then source (i - offset) else m.bytes i := by + simp [write] + +theorem words_write (m : Mem) (offset size : Nat) (source : Nat → Memory.Byte) : + (m.write offset size source).words = (m.expand offset size).words := by + simp [write, words_expand] + +/-- Growth to a size memory already has changes nothing. -/ +theorem grow_of_le (words required : BitVec 251) (h : required.toNat ≤ words.toNat) : + Memory.grow words required = words := by + unfold Memory.grow + simp only [BitVec.ult_iff_toNat_lt] + split <;> first | rfl | omega + +/-- Growth past the active size is exactly the required size. -/ +theorem grow_of_lt (words required : BitVec 251) (h : words.toNat < required.toNat) : + Memory.grow words required = required := by + unfold Memory.grow + simp only [BitVec.ult_iff_toNat_lt] + split <;> first | rfl | omega + +/-! Reads. -/ + +@[simp] theorem read_expand (m : Mem) (offset size address count : Nat) : + (m.expand offset size).read address count = m.read address count := by + simp [read] + +/-- Reading two adjacent ranges is reading their union. -/ +theorem read_append (m : Mem) (address k l : Nat) : + m.read address (k + l) = m.read address k ++ m.read (address + k) l := by + unfold read + rw [List.range_add, List.map_append, List.map_map] + congr 1 + apply List.map_congr_left + intro i _ + simp [Function.comp, Nat.add_assoc] + +/-- A range longer than a word as its first word and the rest, for word-by-word reads of +`abi.encode` output. The lower bound keeps the rewrite from unfolding a word into itself; the +upper bound (32 words) keeps it to the short encodings a hash reads, so a long or symbolic +range is never unfolded byte-word by byte-word. -/ +theorem read_split (m : Mem) (address count : Nat) (h : 32 < count) (bounded : count ≤ 1024) : + m.read address count = m.read address 32 ++ m.read (address + 32) (count - 32) := by + have := read_append m address 32 (count - 32) + rwa [Nat.add_sub_cancel' (by omega)] at this + +/-- A read is unchanged by a store outside it. -/ +theorem read_store_disjoint (m : Mem) (offset : Nat) (value : Word) (address count : Nat) + (h : address + count ≤ offset ∨ offset + 32 ≤ address) : + (m.store offset value).read address count = m.read address count := by + unfold read + apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [bytes_store] + have : ¬(offset ≤ address + i ∧ address + i < offset + 32) := by omega + simp only [this, ite_false] + +/-- A load is unchanged by a store whose word it does not overlap. -/ +theorem load_store_disjoint (m : Mem) (offset : Nat) (value : Word) (address : Nat) + (h : address + 32 ≤ offset ∨ offset + 32 ≤ address) : + (m.store offset value).load address = m.load address := by + unfold load + rw [read_store_disjoint m offset value address 32 h] + +/-- A read is unchanged by a byte store outside it. -/ +theorem read_storeByte_disjoint (m : Mem) (offset : Nat) (value : Word) (address count : Nat) + (h : address + count ≤ offset ∨ offset < address) : + (m.storeByte offset value).read address count = m.read address count := by + unfold read + apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [bytes_storeByte] + have : ¬(address + i = offset) := by omega + simp only [this, ite_false] + +theorem load_storeByte_disjoint (m : Mem) (offset : Nat) (value : Word) (address : Nat) + (h : address + 32 ≤ offset ∨ offset < address) : + (m.storeByte offset value).load address = m.load address := by + unfold load + rw [read_storeByte_disjoint m offset value address 32 h] + +/-- A read is unchanged by a copy, calldata or return data write outside it. -/ +theorem read_write_disjoint (m : Mem) (offset size : Nat) (source : Nat → Memory.Byte) + (address count : Nat) (h : address + count ≤ offset ∨ offset + size ≤ address) : + (m.write offset size source).read address count = m.read address count := by + unfold read + apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [bytes_write] + have : ¬(offset ≤ address + i ∧ address + i < offset + size) := by omega + simp only [this, ite_false] + +/-- The word a store wrote, read back as bytes, as `KECCAK256` over it reads them. -/ +theorem read_store_same (m : Mem) (offset : Nat) (value : Word) : + (m.store offset value).read offset 32 = wordBytes value := by + unfold read wordBytes + apply List.map_congr_left + intro i hi + simp only [List.mem_range] at hi + rw [bytes_store] + have : offset ≤ offset + i ∧ offset + i < offset + 32 := by omega + simp only [this, and_self, ite_true, Nat.add_sub_cancel_left] + +/-- A word stored at an offset equal to the read's, as `omega` proves it (such as +`(p + 32).toNat` and `p.toNat + 32` when the sum does not wrap). -/ +theorem read_store_at (m : Mem) (offset : Nat) (value : Word) (address count : Nat) + (h : address = offset) (hc : count = 32) : + (m.store offset value).read address count = wordBytes value := by + subst h hc; exact read_store_same m address value + +theorem load_store_at (m : Mem) (offset : Nat) (value : Word) (address : Nat) (h : address = offset) : + (m.store offset value).load address = value := by + subst h; exact load_store_same m address value + +/-- A read inside the range a write wrote reads the source at the same distance. -/ +theorem read_write_inside (m : Mem) (offset size : Nat) (source : Nat → Memory.Byte) + (address count : Nat) (lo : offset ≤ address) (hi : address + count ≤ offset + size) : + (m.write offset size source).read address count = + (List.range count).map (fun i => source (address - offset + i)) := by + unfold read + apply List.map_congr_left + intro i hi' + simp only [List.mem_range] at hi' + rw [bytes_write] + have c : offset ≤ address + i ∧ address + i < offset + size := by omega + have e : address + i - offset = address - offset + i := by omega + simp only [c, and_self, ite_true, e] + +/-- The whole range a write wrote reads its source, at any symbolic length. -/ +theorem read_write_same (m : Mem) (offset size : Nat) (source : Nat → Memory.Byte) : + (m.write offset size source).read offset size = (List.range size).map source := by + rw [read_write_inside m offset size source offset size (Nat.le_refl _) (Nat.le_refl _)] + simp + +/-- An `MCOPY` read back inside its destination: the source memory's bytes, at the source +offset moved by the same distance. `from` is the memory the copy read, which `apply_mcopy` +expands first; `read_expand` then removes that expansion. -/ +theorem read_copy_inside (m src : Mem) (offset size source address count : Nat) + (lo : offset ≤ address) (hi : address + count ≤ offset + size) : + (m.write offset size (fun i => src.bytes (source + i))).read address count = + src.read (source + (address - offset)) count := by + rw [read_write_inside m offset size _ address count lo hi] + unfold read + apply List.map_congr_left + intro i _ + simp [Nat.add_assoc] + +/-- A store's word followed by bytes it does not touch. -/ +theorem read_store_head (m : Mem) (offset : Nat) (value : Word) (count : Nat) : + (m.store offset value).read offset (32 + count) = wordBytes value ++ m.read (offset + 32) count := by + rw [read_append, read_store_same, + read_store_disjoint m offset value (offset + 32) count (Or.inr (Nat.le_refl _))] + +/-- Byte-exact reading over any store, overlapping or not: the fallback when neither +disjointness nor containment holds. -/ +theorem read_store (m : Mem) (offset : Nat) (value : Word) (address count : Nat) : + (m.store offset value).read address count = (List.range count).map (fun i => + if offset ≤ address + i ∧ address + i < offset + 32 then + Memory.byte value (address + i - offset) else m.bytes (address + i)) := by + unfold read + apply List.map_congr_left + intro i _ + rw [bytes_store] + +/-- A range of length zero, as `omega` proves it. -/ +theorem read_of_eq_zero (m : Mem) (address count : Nat) (h : count = 0) : m.read address count = [] := by + subst h; rfl + +/-- The whole range a write wrote, at offsets and lengths `omega` proves equal. -/ +theorem read_write_at (m : Mem) (offset size : Nat) (source : Nat → Memory.Byte) (address count : Nat) + (h : address = offset) (hc : count = size) : + (m.write offset size source).read address count = (List.range size).map source := by + subst h hc; exact read_write_same m address count source + +/-- A range that contains a stored word: the bytes before it, the word, the bytes after it. +This is how a hash over a region built word by word at computed offsets meets its words. -/ +theorem read_store_within (m : Mem) (offset : Nat) (value : Word) (address count : Nat) + (lo : address ≤ offset) (hi : offset + 32 ≤ address + count) : + (m.store offset value).read address count = + m.read address (offset - address) ++ wordBytes value ++ + m.read (offset + 32) (address + count - (offset + 32)) := by + have hk : count = (offset - address) + (32 + (address + count - (offset + 32))) := by omega + have ho : address + (offset - address) = offset := by omega + conv => lhs; rw [hk, read_append, read_append, ho] + rw [read_store_disjoint m offset value address (offset - address) (Or.inl (by omega)), + read_store_same, + read_store_disjoint m offset value (offset + 32) _ (Or.inr (Nat.le_refl _)), + List.append_assoc] + +/-- A range that contains a copy's destination: the bytes before it, the copied bytes at any +symbolic length, the bytes after it, as a hash over a header and a copied array reads them. -/ +theorem read_write_within (m : Mem) (offset size : Nat) (source : Nat → Memory.Byte) + (address count : Nat) (lo : address ≤ offset) (hi : offset + size ≤ address + count) : + (m.write offset size source).read address count = + m.read address (offset - address) ++ (List.range size).map source ++ + m.read (offset + size) (address + count - (offset + size)) := by + have hk : count = (offset - address) + (size + (address + count - (offset + size))) := by omega + have ho : address + (offset - address) = offset := by omega + conv => lhs; rw [hk, read_append, read_append, ho] + rw [read_write_disjoint m offset size source address (offset - address) (Or.inl (by omega)), + read_write_same, + read_write_disjoint m offset size source (offset + size) _ (Or.inr (Nat.le_refl _)), + List.append_assoc] + +end SolarTV.Machine.Mem diff --git a/tv/SolarTV/MemorySymbolicSafety.lean b/tv/SolarTV/MemorySymbolicSafety.lean new file mode 100644 index 00000000..1aabb6ce --- /dev/null +++ b/tv/SolarTV/MemorySymbolicSafety.lean @@ -0,0 +1,183 @@ +import SolarTV.MemorySymbolic + +/-! Kernel-checked uses and negatives of the symbolic memory laws, in the shapes ABI +encoding and order hashing take: words stored at a computed free pointer and hashed as one +range, a calldata copy of variable length hashed in place, the free pointer advanced past +it, and an `MCOPY` read back. The negatives show that a wrong offset, a wrong length or an +overlapping write changes the bytes, and that `mem_simp` refuses to move a read past a write +it cannot prove disjoint. -/ + +namespace SolarTV.Machine.Mem +open EvmRules + +/-- Read-over-write by the laws, each side condition by `omega`. -/ +macro "mem_simp" : tactic => `(tactic| repeat (first + | simp (disch := omega) only [read_expand, read_store_at, read_store_disjoint, load_store_at, + load_store_disjoint, read_storeByte_disjoint, load_storeByte_disjoint, read_write_disjoint, + load_write_of_disjoint, read_write_same, read_write_inside, read_copy_inside, load_expand, + read_store_within, read_write_within, read_of_eq_zero, read_write_at, List.append_nil, List.nil_append, + List.append_assoc] + | simp only [read_split, Nat.reduceLT, Nat.reduceLeDiff, Nat.reduceSub, Nat.reduceAdd])) + +/-- `abi.encode(typehash, a, b)` at a free pointer `p` above the scratch and pointer words, +hashed over its 96 bytes: the hash input is the three words, and the pointer word is intact. -/ +theorem encode3_read (m : Mem) (p : Nat) (h : 0x60 ≤ p) (t a b : Word) : + (((m.store p t).store (p + 32) a).store (p + 64) b).read p 96 = + wordBytes t ++ wordBytes a ++ wordBytes b ∧ + (((m.store p t).store (p + 32) a).store (p + 64) b).load 0x40 = m.load 0x40 := by + constructor <;> mem_simp + +/-- A calldata copy of symbolic length `n` at `p`, the next word stored at `p + n` (the +pointer advanced by the copy), then the copy hashed: the hash reads exactly the copied bytes. -/ +theorem copy_then_store_read (m : Mem) (p n : Nat) (src : Nat → Memory.Byte) (w : Word) : + ((m.write p n src).store (p + n) w).read p n = (List.range n).map src := by + mem_simp + +/-- An order hash over `p .. p+n` followed by an encoding at the advanced pointer: the +encoding's word reads back, the copy is untouched. -/ +theorem copy_encode (m : Mem) (p n : Nat) (src : Nat → Memory.Byte) (t w : Word) : + (((m.write p n src).store (p + n) t).store (p + n + 32) w).read (p + n) 64 = + wordBytes t ++ wordBytes w ∧ + (((m.write p n src).store (p + n) t).store (p + n + 32) w).read p n = (List.range n).map src := by + constructor <;> mem_simp + +/-- `MCOPY` of `n` bytes from `s` to `d`, read back at a computed offset inside. -/ +theorem mcopy_read (m : Mem) (d s n k : Nat) (hk : k + 32 ≤ n) : + let src := m.expand s n + (src.write d n (fun i => src.bytes (s + i))).read (d + k) 32 = m.read (s + k) 32 := by + intro src + rw [read_copy_inside _ _ _ _ _ _ _ (by omega) (by omega)] + simp [src, Nat.add_sub_cancel_left] + +/-! Negatives: concrete memories where the wrong claim is false, checked by the kernel. -/ + +set_option maxRecDepth 8192 in +/-- Wrong offset: the encoding read one byte late is not the encoded words. -/ +theorem wrong_offset : ¬ ∀ (m : Mem) (p : Nat) (t a : Word), + ((m.store p t).store (p + 32) a).read (p + 1) 64 = wordBytes t ++ wordBytes a := by + intro h + have := congrArg (·[31]?) (h initial 0 1 0) + revert this + decide + +/-- Wrong length: 64 bytes are not three words. -/ +theorem wrong_length : ¬ ∀ (m : Mem) (p : Nat) (t a b : Word), + (((m.store p t).store (p + 32) a).store (p + 64) b).read p 64 = + wordBytes t ++ wordBytes a ++ wordBytes b := by + intro h + have := congrArg List.length (h initial 0 0 0 0) + simp at this + +set_option maxRecDepth 8192 in +/-- Overlapping write: a store sixteen bytes into a word replaces its low half. -/ +theorem overlapping_write : ¬ ∀ (m : Mem) (p : Nat) (a b : Word), + ((m.store p a).store (p + 16) b).read p 32 = wordBytes a := by + intro h + have := congrArg (·[31]?) (h initial 0 1 0) + revert this + decide + +/-- The procedure fails closed on the overlap: it cannot move the read past the second store. -/ +example (m : Mem) (p : Nat) (a b : Word) : True := by + fail_if_success + have : ((m.store p a).store (p + 16) b).read p 32 = wordBytes a := by mem_simp + trivial + +/-- ... and on a store it cannot place: an unrelated pointer `q` may alias `p`. -/ +example (m : Mem) (p q : Nat) (a b : Word) : True := by + fail_if_success + have : ((m.store p a).store q b).read p 32 = wordBytes a := by mem_simp + trivial + +/-- With the path's bound on `q`, the same read moves. -/ +example (m : Mem) (p q : Nat) (a b : Word) (h : p + 32 ≤ q) : + ((m.store p a).store q b).read p 32 = wordBytes a := by mem_simp + +/-! Exact expansion at symbolic offsets. -/ + +example (m : Mem) (p : Nat) (v : Word) (h : (BitVec.ofNat 251 ((p + 63) / 32)).toNat ≤ m.words.toNat) : + (m.store p v).words = m.words := by + rw [words_store]; exact grow_of_le _ _ (by simpa using h) + +/-! Containment: a hash range that holds stores and copies at computed offsets. -/ + +/-- An order-hash shape: a type hash at `p`, a copied array of symbolic length `n` after it, +hashed as one range of `32 + n` bytes. -/ +theorem typehash_array_read (m : Mem) (p n : Nat) (t : Word) (src : Nat → Memory.Byte) : + ((m.store p t).write (p + 32) n src).read p (32 + n) = wordBytes t ++ (List.range n).map src := by + mem_simp + +/-- A word stored at a computed offset `q` inside a hashed range of symbolic length. -/ +theorem store_within_read (m : Mem) (p q k : Nat) (v : Word) (lo : p ≤ q) (hi : q + 32 ≤ p + k) : + (m.store q v).read p k = m.read p (q - p) ++ wordBytes v ++ m.read (q + 32) (p + k - (q + 32)) := by + mem_simp + +/-- Wrong split: a word that starts inside the range but ends past it is not inside it. -/ +theorem straddling_store : ¬ ∀ (m : Mem) (p : Nat) (v : Word), + (m.store (p + 16) v).read p 32 = m.read p 16 ++ wordBytes v ++ m.read (p + 48) 0 := by + intro h + have := congrArg List.length (h initial 0 0) + simp at this + +/-- The procedure refuses the straddling store. -/ +example (m : Mem) (p : Nat) (v : Word) : True := by + fail_if_success + have : (m.store (p + 16) v).read p 32 = m.read p 16 ++ wordBytes v := by mem_simp + trivial + +end SolarTV.Machine.Mem + +/-- info: 'SolarTV.Machine.Mem.encode3_read' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.encode3_read +/-- info: 'SolarTV.Machine.Mem.copy_then_store_read' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.copy_then_store_read +/-- info: 'SolarTV.Machine.Mem.copy_encode' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.copy_encode +/-- info: 'SolarTV.Machine.Mem.mcopy_read' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.mcopy_read +/-- info: 'SolarTV.Machine.Mem.wrong_offset' depends on axioms: [propext] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.wrong_offset +/-- info: 'SolarTV.Machine.Mem.wrong_length' depends on axioms: [propext] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.wrong_length +/-- info: 'SolarTV.Machine.Mem.overlapping_write' depends on axioms: [propext] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.overlapping_write +/-- info: 'SolarTV.Machine.Mem.read_store_disjoint' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_store_disjoint +/-- info: 'SolarTV.Machine.Mem.load_store_disjoint' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.load_store_disjoint +/-- info: 'SolarTV.Machine.Mem.read_storeByte_disjoint' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_storeByte_disjoint +/-- info: 'SolarTV.Machine.Mem.read_write_disjoint' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_write_disjoint +/-- info: 'SolarTV.Machine.Mem.read_store_same' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_store_same +/-- info: 'SolarTV.Machine.Mem.read_write_inside' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_write_inside +/-- info: 'SolarTV.Machine.Mem.read_write_same' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_write_same +/-- info: 'SolarTV.Machine.Mem.read_copy_inside' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_copy_inside +/-- info: 'SolarTV.Machine.Mem.read_store_head' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_store_head +/-- info: 'SolarTV.Machine.Mem.read_split' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_split +/-- info: 'SolarTV.Machine.Mem.read_append' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_append +/-- info: 'SolarTV.Machine.Mem.grow_of_le' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.grow_of_le +/-- info: 'SolarTV.Machine.Mem.grow_of_lt' depends on axioms: [propext] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.grow_of_lt +/-- info: 'SolarTV.Machine.Mem.words_store' depends on axioms: [propext] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.words_store +/-- info: 'SolarTV.Machine.Mem.read_store' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_store +/-- info: 'SolarTV.Machine.Mem.typehash_array_read' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.typehash_array_read +/-- info: 'SolarTV.Machine.Mem.store_within_read' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.store_within_read +/-- info: 'SolarTV.Machine.Mem.straddling_store' depends on axioms: [propext] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.straddling_store +/-- info: 'SolarTV.Machine.Mem.read_store_within' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_store_within +/-- info: 'SolarTV.Machine.Mem.read_write_within' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in #print axioms SolarTV.Machine.Mem.read_write_within diff --git a/tv/SolarTV/Outcome.lean b/tv/SolarTV/Outcome.lean new file mode 100644 index 00000000..f84eecba --- /dev/null +++ b/tv/SolarTV/Outcome.lean @@ -0,0 +1,116 @@ +/-! Observable termination and refinement for the supported, gas-independent fragment. +A semantic Panic(uint256) has a fixed four-byte selector and one ABI word, so its +code identifies the complete payload and cannot alias the empty revert payload. +`invalid` is an exceptional halt, distinct from both forms of revert. Unsupported +IR and checker limits are host-side failures, never execution outcomes. +-/ + +namespace SolarTV + +inductive RevertData where + | empty + | panic (code : BitVec 256) + deriving DecidableEq + +inductive Outcome (α : Type) where + | returned (value : α) + | reverted (data : RevertData) + | invalid + deriving DecidableEq + +/-- Continue only after successful execution. Later failures cannot overwrite the first one. -/ +def Outcome.bind (result : Outcome α) (next : α → Outcome β) : Outcome β := + match result with + | .returned value => next value + | .reverted data => .reverted data + | .invalid => .invalid + +@[simp] theorem Outcome.bind_return (result : Outcome α) : + result.bind Outcome.returned = result := by + cases result <;> rfl + +@[simp] theorem Outcome.bind_returned (value : α) (next : α → Outcome β) : + (Outcome.returned value).bind next = next value := rfl + +@[simp] theorem Outcome.bind_reverted (data : RevertData) (next : α → Outcome β) : + (Outcome.reverted data).bind next = Outcome.reverted data := rfl + +@[simp] theorem Outcome.bind_invalid (next : α → Outcome β) : + Outcome.invalid.bind next = Outcome.invalid := rfl + +@[simp] theorem Outcome.bind_ite (condition : Prop) [Decidable condition] + (yes no : Outcome α) (next : α → Outcome β) : + (if condition then yes else no).bind next = + if condition then yes.bind next else no.bind next := by + split <;> rfl + +/-- A behavior records the outcomes a program permits at a fixed input. +This allows future nondeterministic semantics without equating failure with undefinedness. -/ +abbrev Behavior (α : Type) := Outcome α → Prop + +def Behavior.exact (result : Outcome α) : Behavior α := fun observed => observed = result + +/-- A candidate may produce only outcomes permitted by the original program. -/ +def Behavior.refines (original candidate : Behavior α) : Prop := + ∀ observed, candidate observed → original observed + +/-- The current importer emits deterministic, defined executions. -/ +def refines (original candidate : Outcome α) : Prop := + Behavior.refines (Behavior.exact original) (Behavior.exact candidate) + +@[simp] theorem refines_iff_eq (original candidate : Outcome α) : + refines original candidate ↔ original = candidate := by + constructor + · intro h + exact (h candidate rfl).symm + · intro h + subst candidate + exact fun _ observed => observed + +theorem refinement_transitive (a b c : Behavior α) + (ab : Behavior.refines a b) (bc : Behavior.refines b c) : Behavior.refines a c := + fun result hc => ab result (bc result hc) + +/-- A bit-vector projection used only to ask the solver for candidate witnesses. +The importer bounds return widths by 256. Every proposed input is then checked +against the actual refinement proposition, independently of this projection. -/ +def Outcome.code (result : Outcome (BitVec width)) : BitVec 258 := + match result with + | .returned value => value.setWidth 258 + | .reverted .empty => 1#258 <<< 256 + | .reverted (.panic code) => (2#258 <<< 256) ||| code.setWidth 258 + | .invalid => 3#258 <<< 256 + +@[simp] theorem Outcome.code_returned (value : BitVec width) : + Outcome.code (.returned value) = value.setWidth 258 := rfl + +@[simp] theorem Outcome.code_empty : + Outcome.code (Outcome.reverted .empty : Outcome (BitVec width)) = 1#258 <<< 256 := rfl + +@[simp] theorem Outcome.code_panic (code : BitVec 256) : + Outcome.code (Outcome.reverted (.panic code) : Outcome (BitVec width)) = + (2#258 <<< 256) ||| code.setWidth 258 := rfl + +@[simp] theorem Outcome.code_invalid : + Outcome.code (Outcome.invalid : Outcome (BitVec width)) = 3#258 <<< 256 := rfl + +@[simp] theorem Outcome.code_cond (condition : Bool) (yes no : Outcome (BitVec width)) : + Outcome.code (bif condition then yes else no) = + bif condition then Outcome.code yes else Outcome.code no := by + cases condition <;> rfl + +@[simp] theorem Outcome.code_ite (condition : Prop) [Decidable condition] + (yes no : Outcome (BitVec width)) : + Outcome.code (if condition then yes else no) = + if condition then Outcome.code yes else Outcome.code no := by + split <;> rfl + +/-- Render a concrete observation without erasing the reason execution failed. -/ +def Outcome.describe (result : Outcome (BitVec width)) : String := + match result with + | .returned value => toString value.toNat + | .reverted .empty => "revert(empty)" + | .reverted (.panic code) => s!"revert Panic({code.toNat})" + | .invalid => "invalid" + +end SolarTV diff --git a/tv/SolarTV/Reentrancy.lean b/tv/SolarTV/Reentrancy.lean new file mode 100644 index 00000000..536044d4 --- /dev/null +++ b/tv/SolarTV/Reentrancy.lean @@ -0,0 +1,220 @@ +import SolarTV.Machine + +/-! # External calls: what a reentrant callee can do to the caller's storage + +The machine semantics leaves the storage after an external call to the oracle +(`Oracle.storageAfter`), as a function of the frame's events, the call among them with the storage +it saw. Every stage holds for every oracle, so it holds for any oracle a theorem picks; but a +theorem about the contract's own specification (an invariant, a frame) cannot hold for every +oracle, since an arbitrary oracle may write anything to the contract's storage across a call. + +This module names the oracles a chain gives the contract. Other code reaches the contract's +storage only by calling the contract (no `DELEGATECALL` into it, no other writer of its account), +so across one external call the contract's storage moves only by a sequence of reentrant +transactions into the contract itself: each is a run of the same program from the storage at that +point, which commits its storage when it succeeds and keeps it when it fails, and whose own +external calls are answered the same way, one call deeper. A call that fails, or whose callee never +reenters, leaves the storage as it was. + +* `Step R σ σ'`: one reentrant run, under an oracle in `R`, takes storage `σ` to `σ'`. +* `Reach R`: any number of such runs. +* `Respects n o`: every call and creation of a frame under `o` leaves the storage at what + reentrant runs reach, each under an oracle that respects `n - 1`; at depth 0 nothing reenters. + +Two laws carry a property across a call, which is how a verifier's havoc of an external call is +justified: + +* `Respects.frame` (a reentrancy lock): when no successful run of the program changes storage + that satisfies `Locked`, a call made with `Locked` storage leaves the storage as it was. +* `Respects.preserves` (an invariant): when every successful run of the program under an oracle + of depth `n` keeps `I`, a call under an oracle of depth `n + 1` made with `I` keeps `I`. + `preserves_all` turns a run's proof, given `I` after each call it holds at, into `I` at + every depth. + +The model leaves out transient storage (a reentrant run starts with zero transient storage, and +`transientAfter` stays free), ETH balances, and the code of other accounts. -/ + +namespace SolarTV.Reentrancy + +open Machine EvmRules + +/-- A contract's storage. -/ +abbrev Storage := Word → Word + +/-- Whether a frame's end commits its state: a normal return or stop. -/ +def Halt.commits : Halt → Bool + | .stop | .ret _ => true + | .revert _ | .invalid => false + +/-- A call starts from storage `σ`: its storage pairs give each slot the value `σ` has there. -/ +def StartsAt (call : Call) (σ : Storage) : Prop := + ∀ w : Word, slotValue call.storage w.toNat = (σ w).toNat + +theorem StartsAt.initial {call : Call} {σ : Storage} (h : StartsAt call σ) : + (State.initial call).storage = σ := by + funext w + simp only [State.initial, h w, BitVec.ofNat_toNat, BitVec.setWidth_eq] + +/-- The storage a call leaves: what a committed end holds, else the storage it started from. -/ +def after (σ : Storage) (r : Halt × State) : Storage := + if Halt.commits r.1 then r.2.storage else σ + +variable (L : Layer) (p : L.Prog) + +/-- One reentrant transaction into the program, under some oracle in `R`, from storage `σ` +to storage `σ'`. -/ +def Step (R : Oracle → Prop) (σ σ' : Storage) : Prop := + ∃ o call r, R o ∧ StartsAt call σ ∧ L.Ends o p call r ∧ σ' = after σ r + +/-- Any number of reentrant transactions. -/ +inductive Reach (R : Oracle → Prop) : Storage → Storage → Prop + | refl (σ : Storage) : Reach R σ σ + | step {σ σ₁ σ₂ : Storage} : Reach R σ σ₁ → Step L p R σ₁ σ₂ → Reach R σ σ₂ + +/-- The world with an event that hands the contract's storage to outside code: a call or a +creation, with the storage it saw. -/ +def Handoff (world : List Event) (σ : Storage) : Prop := + ∃ pre, (∃ kind operands input transient, + world = pre ++ [.call kind operands input σ transient]) ∨ + (∃ operands code transient, world = pre ++ [.create operands code σ transient]) + +/-- Every hand-off under `o` leaves the storage at what reentrant runs under `R` reach. -/ +def Answers (R : Oracle → Prop) (o : Oracle) : Prop := + ∀ world σ, Handoff world σ → Reach L p R σ (o.storageAfter world) + +/-- Oracles of a chain where outside code reaches the contract's storage only through the +program, at most `n` calls deep. -/ +def Respects : Nat → Oracle → Prop + | 0 => Answers L p (fun _ => False) + | n + 1 => Answers L p (Respects n) + +variable {L p} + +theorem Reach.mono {R R' : Oracle → Prop} (sub : ∀ o, R o → R' o) {σ σ' : Storage} + (h : Reach L p R σ σ') : Reach L p R' σ σ' := by + induction h with + | refl => exact .refl _ + | step _ s ih => + obtain ⟨o, call, r, ro, start, ends, eq⟩ := s + exact .step ih ⟨o, call, r, sub o ro, start, ends, eq⟩ + +theorem Reach.of_false {σ σ' : Storage} (h : Reach L p (fun _ => False) σ σ') : σ' = σ := by + induction h with + | refl => rfl + | step _ s _ => obtain ⟨_, _, _, f, _⟩ := s; exact f.elim + +/-- A deeper bound admits every oracle of a shallower one. -/ +theorem Respects.succ : ∀ {n : Nat} {o : Oracle}, Respects L p n o → Respects L p (n + 1) o + | 0, _, h => fun w σ hw => (h w σ hw).mono (fun _ f => f.elim) + | _ + 1, _, h => fun w σ hw => (h w σ hw).mono (fun _ => Respects.succ) + +/-- A property every reentrant step keeps holds after any number of them. -/ +theorem Reach.keeps {R : Oracle → Prop} (P : Storage → Prop) + (step : ∀ σ σ', P σ → Step L p R σ σ' → P σ') {σ σ' : Storage} (h : Reach L p R σ σ') + (start : P σ) : P σ' := by + induction h with + | refl => exact start + | step _ s ih => exact step _ _ ih s + +/-- Every hand-off under an oracle of any depth reaches its storage by reentrant runs. -/ +theorem Respects.reach {n : Nat} {o : Oracle} (h : Respects L p n o) {world : List Event} + {σ : Storage} (hw : Handoff world σ) : ∃ R, Reach L p R σ (o.storageAfter world) := by + cases n with + | zero => exact ⟨_, h world σ hw⟩ + | succ n => exact ⟨_, h world σ hw⟩ + +/-- No successful run, under any oracle, changes storage that satisfies `Locked`: the entry +points that write revert while the lock is held, and the others write nothing. -/ +def LockFrame (Locked : Storage → Prop) : Prop := + ∀ o call r, Locked (State.initial call).storage → L.Ends o p call r → + Halt.commits r.1 = true → r.2.storage = (State.initial call).storage + +/-- Under a reentrancy lock, an external call leaves the storage as it was. -/ +theorem Respects.frame {Locked : Storage → Prop} (lock : LockFrame (L := L) (p := p) Locked) + {n : Nat} {o : Oracle} (h : Respects L p n o) {world : List Event} {σ : Storage} + (hw : Handoff world σ) (locked : Locked σ) : o.storageAfter world = σ := by + obtain ⟨R, reach⟩ := h.reach hw + refine reach.keeps (fun τ => τ = σ) (fun τ τ' eq s => ?_) rfl + subst eq + obtain ⟨o', call, r, _, start, ends, rfl⟩ := s + unfold after + split + · rename_i commits + rw [lock o' call r (by rw [start.initial]; exact locked) ends commits, start.initial] + · rfl + +/-- Every successful run of the program under an oracle in `R` keeps `I`. -/ +def Preserves (R : Oracle → Prop) (I : Storage → Prop) : Prop := + ∀ o call r, R o → I (State.initial call).storage → L.Ends o p call r → + Halt.commits r.1 = true → I r.2.storage + +/-- An invariant that holds at an external call holds after it, when the runs one call deeper +keep it. -/ +theorem Respects.preserves {I : Storage → Prop} {n : Nat} + (keep : Preserves (L := L) (p := p) (Respects L p n) I) {o : Oracle} + (h : Respects L p (n + 1) o) {world : List Event} {σ : Storage} (hw : Handoff world σ) + (holds : I σ) : I (o.storageAfter world) := + (h world σ hw).keeps I (fun τ τ' hτ s => by + obtain ⟨o', call, r, ro, start, ends, rfl⟩ := s + unfold after + split + · rename_i commits + exact keep o' call r ro (by rw [start.initial]; exact hτ) ends commits + · exact hτ) holds + +/-- At depth 0 every property holds after every call it holds at: nothing reenters. -/ +theorem Respects.preserves_zero {I : Storage → Prop} {o : Oracle} (h : Respects L p 0 o) + {world : List Event} {σ : Storage} (hw : Handoff world σ) (holds : I σ) : + I (o.storageAfter world) := by + rw [(h world σ hw).of_false]; exact holds + +/-- An invariant that every run keeps, given that each of the run's external calls made where +it holds leaves it holding (a verifier's check before the call and its assumption after), +holds of every run at every depth. -/ +theorem preserves_all (I : Storage → Prop) + (run : ∀ n o, (∀ world σ, Handoff world σ → I σ → I (o.storageAfter world)) → + Respects L p n o → ∀ call r, I (State.initial call).storage → L.Ends o p call r → + Halt.commits r.1 = true → I r.2.storage) : + ∀ n, Preserves (L := L) (p := p) (Respects L p n) I := by + intro n + induction n with + | zero => + exact fun o call r ro => run 0 o (fun _ _ hw hi => ro.preserves_zero hw hi) ro call r + | succ n ih => + exact fun o call r ro => run (n + 1) o (fun _ _ hw hi => ro.preserves ih hw hi) ro call r + +/-! ## The constraint is satisfiable and not trivial -/ + +/-- The oracle whose callees never reenter: after a hand-off the storage is the one handed +off. -/ +def quiet : Oracle where + env _ _ _ := 0 + result _ := 0 + storageAfter world := match world.getLast? with + | some (.call _ _ _ σ _) | some (.create _ _ σ _) => σ + | _ => fun _ => 0 + transientAfter _ _ := 0 + keccak _ := 0 + caller := 0 + +theorem quiet_handoff {world : List Event} {σ : Storage} (hw : Handoff world σ) : + quiet.storageAfter world = σ := by + obtain ⟨pre, ⟨_, _, _, _, rfl⟩ | ⟨_, _, _, rfl⟩⟩ := hw <;> simp [quiet] + +/-- No depth's constraint is vacuous: the quiet oracle respects them all. -/ +theorem quiet_respects : ∀ n, Respects L p n quiet + | 0 => fun _ _ hw => by rw [quiet_handoff hw]; exact .refl _ + | _ + 1 => fun _ _ hw => by rw [quiet_handoff hw]; exact .refl _ + +/-- The oracle that zeroes the storage after every hand-off. -/ +def wipe : Oracle := { quiet with storageAfter := fun _ _ => 0 } + +/-- Depth 0 rules out an oracle that writes the contract's storage across a call. -/ +theorem wipe_not_respects : ¬ Respects L p 0 wipe := by + intro h + have := (h [.call .call [] [] (fun _ => 1) (fun _ => 0)] (fun _ => 1) + ⟨[], .inl ⟨.call, [], [], fun _ => 0, rfl⟩⟩).of_false + have := congrFun this 0 + simp [wipe] at this + +end SolarTV.Reentrancy diff --git a/tv/SolarTV/Sem.lean b/tv/SolarTV/Sem.lean new file mode 100644 index 00000000..f3b81e42 --- /dev/null +++ b/tv/SolarTV/Sem.lean @@ -0,0 +1,64 @@ +/-! Contract-level semantics: what a call observes, and stages between languages. + +The definitions up to the marker below restate the interface of solidity-lean verbatim, so +that a stage proved here composes with its stages from Solidity to bytecode. A `Sem` runs a +program on a call and gives its observable result, or `none` when it has none (it diverges, +or the call is outside what the semantics defines). `Stage A B p q scope` says that every +result `p` gives for a call in `scope`, `q` gives too. -/ + +namespace SolarTV + +structure Call where + calldata : ByteArray + callvalue : Nat + storage : List (Nat × Nat) + +structure Observable where + success : Bool + output : List Nat + logs : List (List Nat × List Nat) + storage : Nat → Nat + +def slotValue (storage : List (Nat × Nat)) (slot : Nat) : Nat := + storage.foldl (fun acc kv => if kv.1 % 2^256 = slot % 2^256 then kv.2 % 2^256 else acc) 0 + +structure Sem where + Prog : Type + run : Prog → Call → Option Observable + +def Stage (A B : Sem) (p : A.Prog) (q : B.Prog) (scope : Call → Prop) : Prop := + ∀ call, scope call → ∀ obs, A.run p call = some obs → B.run q call = some obs + +theorem Stage.trans {A B C : Sem} {p : A.Prog} {q : B.Prog} {r : C.Prog} {scope : Call → Prop} + (first : Stage A B p q scope) (second : Stage B C q r scope) : Stage A C p r scope := + fun call inScope obs ran => second call inScope obs (first call inScope obs ran) + +/-! Everything below this marker is ours, not solidity-lean's interface. -/ + +theorem Stage.refl (A : Sem) (p : A.Prog) (scope : Call → Prop) : Stage A A p p scope := + fun _ _ _ ran => ran + +/-- A stage holds on any narrower scope. -/ +theorem Stage.mono {A B : Sem} {p : A.Prog} {q : B.Prog} {scope narrower : Call → Prop} + (stage : Stage A B p q scope) (within : ∀ call, narrower call → scope call) : + Stage A B p q narrower := + fun call inScope => stage call (within call inScope) + +/-- The frame a call runs in, which the interface leaves implicit. -/ +structure Environment where + caller : Nat + callee : Nat + frames : Nat + +/-- One frame, called by 0x2000 at 0x1000, as solidity-lean's test environment. The machine +runs at its callee but takes the caller from the oracle, so a stage proved for every oracle holds +for every caller, this one among them. -/ +def environment : Environment := ⟨0x2000, 0x1000, 1⟩ + +/-- A failed call rolls back: it logs nothing and leaves the storage it started with. Its +output is then its revert data, which each semantics defines (`Machine.revertData` here). -/ +def Sem.FailureConvention (S : Sem) : Prop := + ∀ p call obs, S.run p call = some obs → obs.success = false → + obs.logs = [] ∧ obs.storage = slotValue call.storage + +end SolarTV diff --git a/tv/SolarTV/Stages/Assembly.lean b/tv/SolarTV/Stages/Assembly.lean new file mode 100644 index 00000000..09ad9a50 --- /dev/null +++ b/tv/SolarTV/Stages/Assembly.lean @@ -0,0 +1,464 @@ +import SolarTV.Sem + +/-! The stage from assembly to bytecode, which `-Zvalidate-assembly` checks. + +The assembler solves a program of opcodes, pushes of constants and of label offsets, and label +definitions to a layout and emits bytes. `-Zvalidate-assembly` (`validate_assembly.rs`) decodes the +bytes in lockstep with the program: `Walk` is that walk, with the checker's conditions as its +constructors. Each item decodes, at the offset the walk reached, to the instruction it is at the +layout (`Item.expected`): an opcode to its byte, a constant push to a PUSH of the constant, so its +width suffices, a label push to a PUSH of the label's offset, and a label to a `JUMPDEST` at the +label's offset; and the walk ends exactly at the end of the code. Jump tables +(`indexed_jump.rs`) add two items: a packed table, a PUSH of a word of one-byte label offsets +that `BYTE` picks from, each offset below 256 so that its byte is the offset, and the entry +stubs of a stride table, each a `JUMPDEST` at the table's offset plus its index times the +stride (`Item.placed`). + +From the walk, `walk_decodes` proves that linear decoding of the bytes from offset 0 is exactly the +program's instructions at their offsets, `jump_targets` that every pushed label is the offset of a +`JUMPDEST` that decoding reaches as an instruction, and `stage` that assembly to bytecode is a +stage for any bytecode semantics that runs the code's linear decoding, against the assembly program +run at the layout the walk found. No axioms. + +An immutable's placeholder is an item of its own, a push of zeros of its width, which the +deployment code links with the immutable's value: `SolarTV.Stages.Link` shows that linear +decoding of the linked code is the walk's instructions with each placeholder pushing its value. + +Outside this model, as in the checker's limits: program data and library placeholders, which the checker checks byte for byte against the artifact's records, +and the data flow of the deployment code's copy of the runtime code. The bytecode semantics +running the linear decoding is a hypothesis: legacy EVM code runs instruction by instruction from +offset 0 and jumps only to a `JUMPDEST` that starts an instruction, which is what the decoding +lists. -/ + +namespace SolarTV.Assembly + +/-- An instruction as bytecode decodes it: an opcode, or a push of its immediate's value. -/ +inductive Instr where + | op (byte : Nat) + | push (value : Nat) + /-- An opcode that reads the byte after it as its immediate: DUPN, SWAPN or EXCHANGE + (EIP-8024). -/ + | opImm (byte imm : Nat) + deriving DecidableEq, Repr + +def PUSH0 : Nat := 0x5f +def PUSH1 : Nat := 0x60 +def PUSH32 : Nat := 0x7f +def JUMPDEST : Nat := 0x5b +def DUPN : Nat := 0xe6 +def SWAPN : Nat := 0xe7 +def EXCHANGE : Nat := 0xe8 + +/-- Whether an opcode reads the byte after it as an immediate (EIP-8024's DUPN, SWAPN and +EXCHANGE), so that decoding steps over two bytes. -/ +def hasImmediate (byte : Nat) : Bool := byte == DUPN || byte == SWAPN || byte == EXCHANGE + +/-! ### EIP-8024 immediates + +The immediates of DUPN, SWAPN and EXCHANGE as solar's assembler writes them +(`encode_stack_depth` and `encode_exchange` in `crates/evmir/src/op.rs`) and as EIP-8024 decodes +them (EthLib's `decodeSingle` and `decodePair`). A depth counts from 1 at the top: DUPN of depth +`n` pushes a copy of the `n`th word and SWAPN of depth `n` exchanges the top with the word `n` +below it, so EVM IR's `dup i` and `swap i` are depth `i + 1`. EXCHANGE exchanges the words at two +depths `n < m` below the top, with `n + m ≤ 30`: EVM IR's `exchange n m`. -/ + +/-- The immediate of DUPN or SWAPN for a depth from 17 to 235. -/ +def encodeDepth (n : Nat) : Nat := (n + 111) % 256 + +/-- The depth a DUPN or SWAPN immediate encodes, from 17 to 235; none for 91 to 127. -/ +def decodeDepth (x : Nat) : Option Nat := + if 90 < x ∧ x < 128 then none else some ((x + 145) % 256) + +/-- Whether DUPN and SWAPN reach a depth. -/ +def depthOk (n : Nat) : Bool := 17 ≤ n && n ≤ 235 + +/-- The immediate of EXCHANGE for the depths `n < m` with `n + m ≤ 30`. -/ +def encodePair (n m : Nat) : Nat := + (if m ≤ 16 then 16 * (n - 1) + (m - 1) else 16 * (29 - m) + (n - 1)) ^^^ 143 + +/-- The depths an EXCHANGE immediate encodes; none for 82 to 127. -/ +def decodePair (x : Nat) : Option (Nat × Nat) := + if 81 < x ∧ x < 128 then none + else + let k := x ^^^ 143 + if k / 16 < k % 16 then some (k / 16 + 1, k % 16 + 1) else some (k % 16 + 1, 29 - k / 16) + +/-- Whether EXCHANGE reaches a pair of depths. -/ +def pairOk (n m : Nat) : Bool := 1 ≤ n && n < m && n + m ≤ 30 + +/-- Whether the byte after an opcode with an immediate encodes an operand of it. -/ +def immediateOk (byte imm : Nat) : Bool := + if byte = EXCHANGE then (decodePair imm).isSome else (decodeDepth imm).isSome + +/-- Each immediate that decodes is the encoding of what it decodes to. -/ +def depthRound (x : Nat) : Bool := + match decodeDepth x with + | some n => depthOk n && encodeDepth n == x + | none => true + +/-- Each EXCHANGE immediate that decodes is the encoding of the pair it decodes to. -/ +def pairRound (x : Nat) : Bool := + match decodePair x with + | some (n, m) => pairOk n m && encodePair n m == x + | none => true + +set_option maxRecDepth 8000 in +theorem decodeDepth_encodeDepth_all : + ∀ n < 256, depthOk n = true → decodeDepth (encodeDepth n) = some n := by + decide + +/-- Decoding the immediate of a depth DUPN and SWAPN reach gives the depth. -/ +theorem decodeDepth_encodeDepth {n : Nat} (h : depthOk n = true) : + decodeDepth (encodeDepth n) = some n := + decodeDepth_encodeDepth_all n (by simp [depthOk] at h; omega) h + +theorem encodeDepth_lt (n : Nat) : encodeDepth n < 256 := Nat.mod_lt _ (by decide) + +set_option maxRecDepth 8000 in +theorem depthRound_all : ∀ x < 256, depthRound x = true := by decide + +/-- A byte that decodes to a depth is that depth's encoding, and DUPN and SWAPN reach it. -/ +theorem encodeDepth_decodeDepth {x n : Nat} (hx : x < 256) (h : decodeDepth x = some n) : + depthOk n = true ∧ encodeDepth n = x := by + have := depthRound_all x hx + simp only [depthRound, h, Bool.and_eq_true, beq_iff_eq] at this + exact this + +theorem decodePair_encodePair_all : + ∀ n < 32, ∀ m < 32, pairOk n m = true → + decodePair (encodePair n m) = some (n, m) ∧ encodePair n m < 256 := by + decide + +/-- Decoding the immediate of a pair EXCHANGE reaches gives the pair. -/ +theorem decodePair_encodePair {n m : Nat} (h : pairOk n m = true) : + decodePair (encodePair n m) = some (n, m) ∧ encodePair n m < 256 := + decodePair_encodePair_all n (by simp [pairOk] at h; omega) m (by simp [pairOk] at h; omega) h + +set_option maxRecDepth 8000 in +theorem pairRound_all : ∀ x < 256, pairRound x = true := by decide + +/-- A byte that decodes to a pair is that pair's encoding, and EXCHANGE reaches it. -/ +theorem encodePair_decodePair {x n m : Nat} (hx : x < 256) (h : decodePair x = some (n, m)) : + pairOk n m = true ∧ encodePair n m = x := by + have := pairRound_all x hx + simp only [pairRound, h, Bool.and_eq_true, beq_iff_eq] at this + exact this + +/-- No immediate that decodes is a PUSH opcode (PUSH0 to PUSH32) or JUMPDEST, so a scan for +jump destinations that steps over the immediate as an opcode of its own (as EIP-8024 keeps it) +stays on the same boundaries. -/ +theorem immediateOk_not_push {byte imm : Nat} (h : immediateOk byte imm = true) : + ¬(0x5b ≤ imm ∧ imm ≤ 0x7f) := by + intro ⟨h1, h2⟩ + unfold immediateOk at h + cases Nat.decEq byte EXCHANGE with + | isTrue hb => + rw [if_pos hb] at h + unfold decodePair at h + rw [if_pos ⟨by omega, by omega⟩] at h + exact Bool.false_ne_true h + | isFalse hb => + rw [if_neg hb] at h + unfold decodeDepth at h + rw [if_pos ⟨by omega, by omega⟩] at h + exact Bool.false_ne_true h + +/-- The big-endian value of `bytes`. -/ +def bigEndian (bytes : List Nat) : Nat := + bytes.foldl (fun value byte => value * 256 + byte) 0 + +/-- The instruction at `pc` of `code` and the offset after it, or `none` past the end of the +code or for a push or an opcode whose immediate runs past it, as the checker reads it. -/ +def decode (code : List Nat) (pc : Nat) : Option (Instr × Nat) := + match code[pc]? with + | none => none + | some byte => + if byte = PUSH0 then some (.push 0, pc + 1) + else if PUSH1 ≤ byte ∧ byte ≤ PUSH32 then + if pc + 1 + (byte - PUSH1 + 1) ≤ code.length then + some (.push (bigEndian ((code.drop (pc + 1)).take (byte - PUSH1 + 1))), + pc + 1 + (byte - PUSH1 + 1)) + else none + else if hasImmediate byte then + -- NOTE: EthLib reads 0 past the end of the code and halts on an immediate that encodes no + -- depth; the walk refuses both, as solar's assembler does. + match code[pc + 1]? with + | some imm => if immediateOk byte imm then some (.opImm byte imm, pc + 2) else none + | none => none + else some (.op byte, pc + 1) + +/-- Linear decoding of `code` from `pc`, each instruction at its offset, for at most `fuel` +instructions. -/ +def decodeFrom (code : List Nat) : Nat → Nat → List (Nat × Instr) + | 0, _ => [] + | fuel + 1, pc => + match decode code pc with + | some (instr, next) => (pc, instr) :: decodeFrom code fuel next + | none => [] + +/-- An instruction of the assembly program: an opcode, a push of a constant or of a label's +offset, a label's definition, or the `PUSH` placeholder of immutable `id`, zeros until a +deployment links it. -/ +inductive Item where + | op (byte : Nat) + | push (value : Nat) + | pushLabel (label : Nat) + | label (label : Nat) + | immutable (id bytes : Nat) + /-- A push of a word of one-byte label offsets, the first label's in the word's highest byte + of the push: a packed jump table, which `BYTE` picks an entry of. -/ + | pushTable (labels : List Nat) + /-- Entry `index` of a stride table whose first entry is label `table`: a `JUMPDEST` + `index` strides past the table's offset. -/ + | entry (table index stride : Nat) + /-- An opcode with its one-byte immediate: DUPN, SWAPN or EXCHANGE (EIP-8024). -/ + | opImm (byte imm : Nat) + deriving DecidableEq, Repr + +/-- The instruction an item is at a layout that puts each label at `offset`. -/ +def Item.expected (offset : Nat → Nat) : Item → Instr + | .op byte => .op byte + | .push value => .push value + | .pushLabel l => .push (offset l) + | .label _ => .op JUMPDEST + | .immutable _ _ => .push 0 + | .pushTable labels => .push (bigEndian (labels.map offset)) + | .entry _ _ _ => .op JUMPDEST + | .opImm byte imm => .opImm byte imm + +/-- Whether an item is placed where the layout says at `pc` of `code`: a label at its offset, a +packed table's every offset in one byte, so that the word's bytes are the offsets, a stride table's +entry its index of strides past the table's offset, and an immutable's placeholder a +`PUSH` of its width, `1 ≤ bytes ≤ 32`, which a deployment's linking overwrites byte for +byte: a `PUSH0` or a narrower push of zero decodes to the same push but is no placeholder. -/ +def Item.placed (code : List Nat) (offset : Nat → Nat) (pc : Nat) : Item → Bool + | .label l => offset l == pc + | .immutable _ bytes => + decide (1 ≤ bytes) && decide (bytes ≤ 32) && code[pc]? == some (PUSH1 + bytes - 1) + | .pushTable labels => labels.all (offset · < 256) + | .entry table index stride => offset table + index * stride == pc + | _ => true + +/-- The checker's walk: decoding `code` from `pc` in lockstep with `items` gives each item's +instruction at the layout `offset`, with each item placed as the layout says (`Item.placed`), +and ends at the end of the code. `stream` is the program's instructions at the offsets the walk reached. -/ +inductive Walk (code : List Nat) (offset : Nat → Nat) : + Nat → List Item → List (Nat × Instr) → Prop + | nil : Walk code offset code.length [] [] + | cons {pc next : Nat} {item : Item} {items : List Item} {stream : List (Nat × Instr)} : + decode code pc = some (item.expected offset, next) → + item.placed code offset pc = true → + Walk code offset next items stream → + Walk code offset pc (item :: items) ((pc, item.expected offset) :: stream) + +theorem decode_advances {code : List Nat} {pc next : Nat} {instr : Instr} + (h : decode code pc = some (instr, next)) : pc < next := by + unfold decode at h + split at h + · simp at h + · repeat' split at h + all_goals first + | (simp at h; done) + | (simp only [Option.some.injEq, Prod.mk.injEq] at h; obtain ⟨-, rfl⟩ := h; omega) + +/-- An instruction decodes to an opcode only from its byte, one byte on, when the byte is no +push and takes no immediate. -/ +theorem decode_op_inv {code : List Nat} {pc next byte : Nat} + (h : decode code pc = some (.op byte, next)) : + code[pc]? = some byte ∧ byte ≠ PUSH0 ∧ ¬(PUSH1 ≤ byte ∧ byte ≤ PUSH32) ∧ + hasImmediate byte = false ∧ next = pc + 1 := by + unfold decode at h + split at h + · simp at h + · rename_i b hb + repeat' split at h + all_goals simp only [Option.some.injEq, Prod.mk.injEq, reduceCtorEq, Instr.op.injEq, + false_and] at h + all_goals first + | (rename_i h0 h1 hi; obtain ⟨rfl, rfl⟩ := h; exact ⟨hb, h0, h1, by simpa using hi, rfl⟩) + | skip + all_goals simp_all + +/-- An opcode with an immediate decodes from its byte and the next, two bytes on, when the +next byte encodes an operand of it. -/ +theorem decode_opImm_inv {code : List Nat} {pc next byte imm : Nat} + (h : decode code pc = some (.opImm byte imm, next)) : + code[pc]? = some byte ∧ hasImmediate byte = true ∧ code[pc + 1]? = some imm ∧ + immediateOk byte imm = true ∧ next = pc + 2 := by + unfold decode at h + split at h + · simp at h + · rename_i b hb + repeat' split at h + all_goals simp only [Option.some.injEq, Prod.mk.injEq, reduceCtorEq, Instr.opImm.injEq, + false_and] at h + all_goals simp_all + +/-- Each item takes at least a byte. -/ +theorem walk_length {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) : + pc + items.length ≤ code.length := by + induction w with + | nil => simp + | cons decoded _ _ ih => + have := decode_advances decoded + simp only [List.length_cons] + omega + +/-- Linear decoding is the program's instructions at their offsets. -/ +theorem walk_decodes {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) : + ∀ fuel, items.length < fuel → decodeFrom code fuel pc = stream := by + induction w with + | nil => + intro fuel h + cases fuel with + | zero => simp at h + | succ fuel => + simp [decodeFrom, decode] + | cons decoded _ _ ih => + intro fuel h + cases fuel with + | zero => simp at h + | succ fuel => + simp only [List.length_cons] at h + simp only [decodeFrom, decoded] + rw [ih fuel (by omega)] + +/-- The decoded instructions are the program's items at the layout. -/ +theorem walk_instructions {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) : + stream.map Prod.snd = items.map (Item.expected offset) := by + induction w with + | nil => rfl + | cons _ _ _ ih => simp [ih] + +/-- A defined label's offset holds a `JUMPDEST` that starts an instruction. -/ +theorem walk_label {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) {label : Nat} + (defined : Item.label label ∈ items) : (offset label, Instr.op JUMPDEST) ∈ stream := by + induction w with + | nil => simp at defined + | @cons pc next item items stream _ labels _ ih => + rcases List.mem_cons.1 defined with here | later + · subst here + simp only [Item.placed, beq_iff_eq] at labels + rw [labels] + simp [Item.expected] + · exact List.mem_cons_of_mem _ (ih later) + +/-- A stride table's entry, its index of strides past the table's offset, holds a `JUMPDEST` +that starts an instruction. -/ +theorem walk_entry {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) {table index stride : Nat} + (defined : Item.entry table index stride ∈ items) : + (offset table + index * stride, Instr.op JUMPDEST) ∈ stream := by + induction w with + | nil => simp at defined + | @cons pc next item items stream _ placed _ ih => + rcases List.mem_cons.1 defined with here | later + · subst here + simp only [Item.placed, beq_iff_eq] at placed + rw [placed] + simp [Item.expected] + · exact List.mem_cons_of_mem _ (ih later) + +/-- Every label the program pushes and defines is the offset of a `JUMPDEST` that the code's +linear decoding reaches as an instruction. -/ +theorem jump_targets {code : List Nat} {offset : Nat → Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset 0 items stream) {label : Nat} + (defined : Item.label label ∈ items) : + (offset label, Instr.op JUMPDEST) ∈ decodeFrom code (code.length + 1) 0 := by + have := walk_length w + rw [walk_decodes w _ (by omega)] + exact walk_label w defined + +/-- Assembly to bytecode is a stage: the program `p`, run at the layout the walk found, and the +code, run by a bytecode semantics that runs its linear decoding, give the same result. -/ +theorem stage {A B : Sem} {p : A.Prog} {code : B.Prog} {scope : Call → Prop} + (bytes : List Nat) (items : List Item) (offset : Nat → Nat) (stream : List (Nat × Instr)) + (run : List (Nat × Instr) → Call → Option Observable) + (assembly : ∀ call, A.run p call = run stream call) + (bytecode : ∀ call, B.run code call = run (decodeFrom bytes (bytes.length + 1) 0) call) + (checked : Walk bytes offset 0 items stream) : Stage A B p code scope := by + intro call _ obs ran + have := walk_length checked + rw [bytecode, walk_decodes checked _ (by omega), ← assembly] + exact ran + +/-! A jump over a label push: `PUSH1 3; JUMP; JUMPDEST; STOP`, with label 0 at offset 3. -/ + +def example_items : List Item := [.pushLabel 0, .op 0x56, .label 0, .op 0x00] + +def example_code : List Nat := [0x60, 3, 0x56, 0x5b, 0x00] + +theorem example_walk : + Walk example_code (fun _ => 3) 0 example_items + [(0, .push 3), (2, .op 0x56), (3, .op 0x5b), (4, .op 0x00)] := + .cons (by rfl) rfl (.cons (by rfl) rfl (.cons (by rfl) rfl (.cons (by rfl) rfl .nil))) + +/-- Off by one, the label push misses the label: no walk exists, as the checker reports. -/ +theorem example_fault (stream : List (Nat × Instr)) : + ¬ Walk [0x60, 4, 0x56, 0x5b, 0x00] (fun _ => 3) 0 example_items stream := by + intro w + cases w with + | cons decoded _ _ => + simp [decode, bigEndian, Item.expected, PUSH0, PUSH1, PUSH32] at decoded + +/-! DUPN of depth 17 (`dup 16`): the immediate 0x80, two bytes on. A JUMPDEST byte or no byte +after DUPN encodes no depth, which the walk refuses. -/ + +theorem example_dupn : + Walk [0xe6, 0x80, 0x00] (fun _ => 0) 0 [.opImm DUPN (encodeDepth 17), .op 0x00] + [(0, .opImm 0xe6 0x80), (2, .op 0x00)] := + .cons (by rfl) rfl (.cons (by rfl) rfl .nil) + +theorem example_dupn_jumpdest : decode [0xe6, 0x5b] 0 = none := by decide + +theorem example_dupn_short : decode [0xe6] 0 = none := by decide + +theorem example_exchange : decodePair (encodePair 1 29) = some (1, 29) := by decide + +/-- An immutable's placeholder is a push of its width: a 32-byte placeholder walks as PUSH32 of +zeros, and a PUSH0 or PUSH1 0 in its place, which decodes to the same push of zero, has no walk. -/ +theorem example_immutable : + Walk (0x7f :: List.replicate 32 0) (fun _ => 0) 0 [.immutable 0 32] [(0, .push 0)] := + .cons (by decide) (by decide) .nil + +theorem example_immutable_push0 (stream : List (Nat × Instr)) : + ¬ Walk [0x5f] (fun _ => 0) 0 [.immutable 0 32] stream := by + intro w + cases w with + | cons _ placed _ => exact absurd placed (by decide) + +theorem example_immutable_push1 (stream : List (Nat × Instr)) : + ¬ Walk [0x60, 0x00] (fun _ => 0) 0 [.immutable 0 32] stream := by + intro w + cases w with + | cons _ placed _ => exact absurd placed (by decide) + +/-- A wrong immediate fails: DUPN with 0x81 (depth 18) where the item is depth 17's 0x80 has no +walk, though 0x81 is a valid immediate, as the checker reports. -/ +theorem example_dupn_wrong (stream : List (Nat × Instr)) : + ¬ Walk [0xe6, 0x81, 0x00] (fun _ => 0) 0 [.opImm DUPN (encodeDepth 17), .op 0x00] stream := by + intro w + cases w with + | cons decoded _ _ => + have e : decode [0xe6, 0x81, 0x00] 0 = some (.opImm 0xe6 0x81, 2) := by decide + rw [e] at decoded + simp [Item.expected, DUPN, encodeDepth] at decoded + +/-- A wrong EXCHANGE immediate fails the same way: pair (1, 3)'s byte where (1, 2)'s is due. -/ +theorem example_exchange_wrong (stream : List (Nat × Instr)) : + ¬ Walk [0xe8, encodePair 1 3, 0x00] (fun _ => 0) 0 + [.opImm EXCHANGE (encodePair 1 2), .op 0x00] stream := by + intro w + cases w with + | cons decoded _ _ => + have e : decode [0xe8, encodePair 1 3, 0x00] 0 = some (.opImm 0xe8 (encodePair 1 3), 2) := by + decide + rw [e] at decoded + simp only [Item.expected, Option.some.injEq, Prod.mk.injEq, Instr.opImm.injEq] at decoded + exact absurd decoded.1.2 (by decide) + +end SolarTV.Assembly diff --git a/tv/SolarTV/Stages/AssemblyCheck.lean b/tv/SolarTV/Stages/AssemblyCheck.lean new file mode 100644 index 00000000..58789e65 --- /dev/null +++ b/tv/SolarTV/Stages/AssemblyCheck.lean @@ -0,0 +1,74 @@ +import SolarTV.Stages.Assembly + +/-! The checker's walk as a function, which the kernel evaluates. + +`walk` runs `-Zvalidate-assembly`'s lockstep decoding (`Walk`) on concrete bytes and +items: it gives the stream of instructions the walk reaches, or `none` where an item does not +decode to its instruction at the layout, an item is not placed as the layout says, or the walk +does not end exactly at the end of the code. `walk_sound` and `walk_complete` show it is +`Walk`, so a kernel-checked `walk … = some stream` proves the walk, and `walk … = none` +refutes every walk (`no_walk`), as the checker rejects the code. -/ + +namespace SolarTV.Assembly + +/-- The checker's walk from `pc`: the stream of instructions it reaches, or `none`. -/ +def walk (code : List Nat) (offset : Nat → Nat) : Nat → List Item → Option (List (Nat × Instr)) + | pc, [] => if pc = code.length then some [] else none + | pc, item :: items => + match decode code pc with + | none => none + | some (instr, next) => + if instr = item.expected offset ∧ item.placed code offset pc = true then + match walk code offset next items with + | some rest => some ((pc, instr) :: rest) + | none => none + else none + +theorem walk_sound {code : List Nat} {offset : Nat → Nat} : + ∀ {pc : Nat} {items : List Item} {stream : List (Nat × Instr)}, + walk code offset pc items = some stream → Walk code offset pc items stream + | pc, [], stream, h => by + simp only [walk] at h + by_cases e : pc = code.length + · simp only [e, ite_true] at h + cases h + rw [e] + exact .nil + · simp only [e, ite_false] at h + cases h + | pc, item :: items, stream, h => by + simp only [walk] at h + cases hd : decode code pc with + | none => rw [hd] at h; cases h + | some r => + obtain ⟨instr, next⟩ := r + rw [hd] at h + simp only at h + by_cases ok : instr = item.expected offset ∧ item.placed code offset pc = true + · simp only [ok, and_self, ite_true] at h + cases hw : walk code offset next items with + | none => rw [hw] at h; cases h + | some rest => + rw [hw] at h + cases h + rw [ok.1] at hd + exact .cons hd ok.2 (walk_sound hw) + · simp only [ok, ite_false] at h + cases h + +theorem walk_complete {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) : + walk code offset pc items = some stream := by + induction w with + | nil => simp [walk] + | cons decoded labels _ ih => + simp [walk, decoded, labels, ih] + +/-- A walk the function refutes does not exist. -/ +theorem no_walk {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + (h : walk code offset pc items = none) (stream : List (Nat × Instr)) : + ¬ Walk code offset pc items stream := fun w => by + rw [walk_complete w] at h + cases h + +end SolarTV.Assembly diff --git a/tv/SolarTV/Stages/Entries.lean b/tv/SolarTV/Stages/Entries.lean new file mode 100644 index 00000000..57fd2bea --- /dev/null +++ b/tv/SolarTV/Stages/Entries.lean @@ -0,0 +1,93 @@ +import SolarTV.Sem + +/-! The stages of `lower-abi` and `lower-dispatch`, which `-Zvalidate-passes` checks query by +query (`validate_passes/entries.rs`). + +Before them, a contract's code is its external entries, and the ABI routes each call: to an entry +by its selector, to `receive` or `fallback`, or to an outcome of its own, such as a rejected value +or an empty revert on a miss. `Routing` is that routing and `routed` the semantics of a contract +whose entries run `body`. `lower-abi` replaces each entry's body with a wrapper that decodes its +arguments from calldata, runs the body and encodes its results; `lower-dispatch` replaces the +routing with a dispatcher, a program of whatever semantics runs the lowered MIR. + +Each query's `unsat` verdict is an obligation here: `AbiObligation` for the query of one wrapper, +that on every call the routing sends to its entry the wrapper ends as the reference over the body +does, and `DispatchObligation` for the dispatcher's query, that the dispatcher ends as the routing +over the wrappers does. They are discharged per query by the solver, or by a certificate as the +pass queries are, not proved here: each states what its query's reference encodes, over the +semantics the encoder gives MIR, and relating that to a Lean semantics of MIR is the work of the +pass validation stages, outside this file. From them `abi_stage` proves the stage of `lower-abi` over all entries, and +`entries_stage` the stage from the routed contract to its dispatcher, which `to_bytecode` +composes with the stages after it. -/ + +namespace SolarTV.Entries + +/-- How the ABI routes a call over a contract's entries `E`: to an entry, or to an outcome of the +routing itself. -/ +structure Routing (E : Type) where + route : Call → Option E + miss : Call → Option Observable + +/-- A routed contract whose entries run `body`. -/ +def Routing.run {E : Type} (r : Routing E) (body : E → Call → Option Observable) (call : Call) : + Option Observable := + match r.route call with + | some entry => body entry call + | none => r.miss call + +/-- The semantics of a contract routed by `r`: a program is the body of each entry. -/ +def routed {E : Type} (r : Routing E) : Sem := ⟨E → Call → Option Observable, r.run⟩ + +/-- What the `lower-abi` query of `entry` proves: on every call in scope that the routing sends to +the entry, its wrapper ends as its body does under the ABI's decoding and encoding, which +`body` includes. -/ +def AbiObligation {E : Type} (r : Routing E) (scope : Call → Prop) + (body wrapper : E → Call → Option Observable) (entry : E) : Prop := + ∀ call, scope call → r.route call = some entry → + ∀ obs, body entry call = some obs → wrapper entry call = some obs + +/-- What the `lower-dispatch` query proves: the dispatcher `q` ends as the routing over the +wrappers does. -/ +def DispatchObligation {E : Type} (D : Sem) (r : Routing E) (scope : Call → Prop) + (wrapper : E → Call → Option Observable) (q : D.Prog) : Prop := + ∀ call, scope call → ∀ obs, r.run wrapper call = some obs → D.run q call = some obs + +/-- The queries of every wrapper give the stage of `lower-abi`. -/ +theorem abi_stage {E : Type} {r : Routing E} {scope : Call → Prop} + {body wrapper : E → Call → Option Observable} + (each : ∀ entry, AbiObligation r scope body wrapper entry) : + Stage (routed r) (routed r) body wrapper scope := by + intro call inScope obs ran + change r.run body call = some obs at ran + change r.run wrapper call = some obs + unfold Routing.run at ran ⊢ + cases h : r.route call with + | none => rw [h] at ran; exact ran + | some entry => rw [h] at ran; exact each entry call inScope h obs ran + +theorem dispatch_stage {E : Type} {D : Sem} {r : Routing E} {scope : Call → Prop} + {wrapper : E → Call → Option Observable} {q : D.Prog} + (query : DispatchObligation D r scope wrapper q) : Stage (routed r) D wrapper q scope := + query + +/-- The stage from the routed contract to its dispatcher: `lower-abi` then `lower-dispatch`. -/ +theorem entries_stage {E : Type} {D : Sem} {r : Routing E} {scope : Call → Prop} + {body wrapper : E → Call → Option Observable} {q : D.Prog} + (abi : ∀ entry, AbiObligation r scope body wrapper entry) + (dispatch : DispatchObligation D r scope wrapper q) : Stage (routed r) D body q scope := + (abi_stage abi).trans (dispatch_stage dispatch) + +/-- From a source semantics to bytecode: a stage into the routed contract, such as the one from +SolidCore to semantic MIR, the entry lowering, a stage from the dispatcher to assembly, such as +the composed MIR, scheduling and EVM IR stages, and the assembly stage. -/ +theorem to_bytecode {E : Type} {S D A B : Sem} {r : Routing E} {scope : Call → Prop} + {src : S.Prog} {body wrapper : E → Call → Option Observable} {q : D.Prog} {p : A.Prog} + {code : B.Prog} + (front : Stage S (routed r) src body scope) + (abi : ∀ entry, AbiObligation r scope body wrapper entry) + (dispatch : DispatchObligation D r scope wrapper q) + (backend : Stage D A q p scope) (assembly : Stage A B p code scope) : + Stage S B src code scope := + ((front.trans (entries_stage abi dispatch)).trans backend).trans assembly + +end SolarTV.Entries diff --git a/tv/SolarTV/Stages/Link.lean b/tv/SolarTV/Stages/Link.lean new file mode 100644 index 00000000..4c68eea5 --- /dev/null +++ b/tv/SolarTV/Stages/Link.lean @@ -0,0 +1,376 @@ +import SolarTV.Stages.Assembly +import SolarTV.Machine + +/-! Linking immutables into the runtime bytecode. + +An immutable is fixed at deployment: the deployment code writes its value over each of its +placeholders, the zero bytes of a `PUSH` in the runtime code, as the big-endian encoding +of its low `bytes` bytes (`link`). The bytecode a stage is checked against is the code before +that, as the compiler emits it, with each placeholder an `Item.immutable` that walks as a push of +zeros. `placeholdersOf` reads the placeholders off a walk: each at the byte after its push. + +`walk_link` shows that for every value of the immutables, the linear decoding of the linked code +is the walk's stream with each placeholder pushing its value modulo `256 ^ bytes` +(`linkedStream`), and `linked_instructions` that those are the program's items with each +placeholder linked. `placed`, which the kernel evaluates, checks what that takes of the walk: +each placeholder is a `PUSH` of its width. So a proof that the walk accepts the unlinked +bytecode binds every bytecode a deployment runs: its hash is that of `link` of the code with the +placeholders the manifest lists. `Machine.immutableWord_toNat` connects the pushed value with +the word the stages read. No axioms beyond the standard three. -/ + +namespace SolarTV.Assembly + +/-- An immutable placeholder: the immutable, the offset of its bytes and their count. -/ +structure Placeholder where + id : Nat + start : Nat + bytes : Nat + deriving DecidableEq, Repr + +/-- Whether byte `i` of the code is one of the placeholder's. -/ +def Placeholder.covers (p : Placeholder) (i : Nat) : Bool := + decide (p.start ≤ i) && decide (i < p.start + p.bytes) + +/-- Byte `j` of the `n`-byte big-endian encoding of `value`. -/ +def beByte (value n j : Nat) : Nat := value / 256 ^ (n - 1 - j) % 256 + +/-- Byte `i` of the linked code, `b` before linking. -/ +def linkByte (ps : List Placeholder) (values : Nat → Nat) (i b : Nat) : Nat := + match ps.find? (·.covers i) with + | some p => beByte (values p.id) p.bytes (i - p.start) + | none => b + +/-- `code` as a deployment runs it: the bytes of each placeholder the big-endian encoding of its +immutable's value. -/ +def link (code : List Nat) (ps : List Placeholder) (values : Nat → Nat) : List Nat := + code.mapIdx (linkByte ps values) + +/-- The placeholders of a walk's immutable items, each at the byte after its push. -/ +def placeholdersOf : List (Nat × Instr) → List Item → List Placeholder + | (pc, _) :: stream, item :: items => + match item with + | .immutable id bytes => ⟨id, pc + 1, bytes⟩ :: placeholdersOf stream items + | _ => placeholdersOf stream items + | _, _ => [] + +/-- Whether each immutable item of a walk is a `PUSH` of its width, `1 ≤ bytes ≤ 32`. -/ +def placed (code : List Nat) : List (Nat × Instr) → List Item → Bool + | (pc, _) :: stream, item :: items => + match item with + | .immutable _ bytes => + decide (1 ≤ bytes) && decide (bytes ≤ 32) && code[pc]? == some (PUSH1 + bytes - 1) && + placed code stream items + | _ => placed code stream items + | _, _ => true + +/-- A walk's stream with each placeholder pushing its immutable's value. -/ +def linkedStream (values : Nat → Nat) : List (Nat × Instr) → List Item → List (Nat × Instr) + | (pc, instr) :: stream, item :: items => + match item with + | .immutable id bytes => (pc, .push (values id % 256 ^ bytes)) :: linkedStream values stream items + | _ => (pc, instr) :: linkedStream values stream items + | _, _ => [] + +/-- The instruction an item is once a deployment links it. -/ +def Item.linked (offset : Nat → Nat) (values : Nat → Nat) : Item → Instr + | .immutable id bytes => .push (values id % 256 ^ bytes) + | item => item.expected offset + +theorem bigEndian_append (xs : List Nat) (b : Nat) : + bigEndian (xs ++ [b]) = bigEndian xs * 256 + b := by + simp [bigEndian, List.foldl_append] + +/-- The big-endian bytes of a value are the value modulo the bytes' range. -/ +theorem bigEndian_beBytes (n value : Nat) : + bigEndian ((List.range n).map (beByte value n)) = value % 256 ^ n := by + induction n generalizing value with + | zero => simp [bigEndian, Nat.mod_one] + | succ n ih => + rw [List.range_succ, List.map_append, List.map_singleton, bigEndian_append] + have hpre : (List.range n).map (beByte value (n + 1)) = + (List.range n).map (beByte (value / 256) n) := by + apply List.map_congr_left + intro j hj + have hj := List.mem_range.1 hj + unfold beByte + have e : n + 1 - 1 - j = (n - 1 - j) + 1 := by omega + rw [e, Nat.pow_succ, Nat.mul_comm, ← Nat.div_div_eq_div_mul] + rw [hpre, ih] + unfold beByte + simp only [Nat.add_sub_cancel, Nat.sub_self, Nat.pow_zero, Nat.div_one] + rw [Nat.pow_succ, Nat.mul_comm (256 ^ n) 256, Nat.mod_mul] + omega + +theorem link_length (code : List Nat) (ps : List Placeholder) (values : Nat → Nat) : + (link code ps values).length = code.length := by + simp [link] + +theorem link_getElem? (code : List Nat) (ps : List Placeholder) (values : Nat → Nat) (i : Nat) : + (link code ps values)[i]? = code[i]?.map (linkByte ps values i) := by + simp [link, List.getElem?_mapIdx] + +/-- A byte no placeholder covers is the code's. -/ +theorem link_getElem?_of_uncovered {code : List Nat} {ps : List Placeholder} {values : Nat → Nat} + {i : Nat} (h : ∀ p ∈ ps, p.covers i = false) : (link code ps values)[i]? = code[i]? := by + rw [link_getElem?] + have : ps.find? (·.covers i) = none := List.find?_eq_none.2 (fun p hp => by simp [h p hp]) + cases code[i]? <;> simp [linkByte, this] + +/-- The placeholder that covers a byte, when every one that does is the same. -/ +theorem find?_covers {ps : List Placeholder} {p : Placeholder} {i : Nat} (mem : p ∈ ps) + (covers : p.covers i = true) (unique : ∀ q ∈ ps, q.covers i = true → q = p) : + ps.find? (·.covers i) = some p := by + induction ps with + | nil => simp at mem + | cons q qs ih => + by_cases hq : q.covers i = true + · have := unique q (List.mem_cons_self) hq + subst this + simp [hq] + · have hq' : q.covers i = false := by simpa using hq + simp only [List.find?_cons, hq'] + rcases List.mem_cons.1 mem with rfl | later + · exact absurd covers hq + · exact ih later (fun r hr => unique r (List.mem_cons_of_mem _ hr)) + +/-- Decoding reads only the bytes of the instruction and the code's length. -/ +theorem decode_congr {code code' : List Nat} {pc next : Nat} {instr : Instr} + (len : code'.length = code.length) + (same : ∀ i, pc ≤ i → i < next → code'[i]? = code[i]?) + (h : decode code pc = some (instr, next)) : decode code' pc = some (instr, next) := by + have adv := decode_advances h + have hpc := same pc (Nat.le_refl _) adv + unfold decode at h ⊢ + rw [hpc] + cases hc : code[pc]? with + | none => rw [hc] at h; simp at h + | some byte => + rw [hc] at h + simp only at h ⊢ + by_cases h0 : byte = PUSH0 + · simp only [h0, ↓reduceIte] at h ⊢; exact h + · simp only [h0, ↓reduceIte] at h ⊢ + by_cases hr : PUSH1 ≤ byte ∧ byte ≤ PUSH32 + · simp only [hr, and_self, ↓reduceIte] at h ⊢ + by_cases fits : pc + 1 + (byte - PUSH1 + 1) ≤ code.length + · simp only [fits, ↓reduceIte] at h + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + have take : (code'.drop (pc + 1)).take (byte - PUSH1 + 1) = + (code.drop (pc + 1)).take (byte - PUSH1 + 1) := by + apply List.ext_getElem? + intro j + simp only [List.getElem?_take, List.getElem?_drop] + split + · exact same _ (by omega) (by omega) + · rfl + simp only [len, fits, take, ↓reduceIte] + · simp [fits] at h + · simp only [hr, ↓reduceIte] at h ⊢ + by_cases hi : hasImmediate byte = true + · simp only [hi, ↓reduceIte] at h ⊢ + cases hm : code[pc + 1]? with + | none => rw [hm] at h; simp at h + | some imm => + rw [hm] at h + by_cases ok : immediateOk byte imm = true + · simp only [ok, ↓reduceIte, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + rw [same (pc + 1) (by omega) (by omega), hm] + simp [ok] + · simp [ok] at h + · simp only [Bool.not_eq_true] at hi + simp only [hi] at h ⊢ + exact h + +/-- The offsets a walk reaches are at least where it starts. -/ +theorem walk_ge {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) : + ∀ e ∈ stream, pc ≤ e.1 := by + induction w with + | nil => simp + | cons decoded _ _ ih => + have := decode_advances decoded + intro e he + rcases List.mem_cons.1 he with rfl | later + · exact Nat.le_refl _ + · have := ih e later + omega + +/-- The placeholders of a walk start after where it starts. -/ +theorem placeholdersOf_gt {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) : + ∀ p ∈ placeholdersOf stream items, pc < p.start := by + induction w with + | nil => simp [placeholdersOf] + | @cons pc next item items stream decoded _ rest ih => + have adv := decode_advances decoded + intro p hp + cases item <;> simp only [placeholdersOf] at hp + case immutable id bytes => + rcases List.mem_cons.1 hp with rfl | later + · simp + · have := ih p later + omega + all_goals + have := ih p hp + omega + +/-- A placeholder's push decodes to its width. -/ +theorem decode_placeholder {code : List Nat} {pc next bytes : Nat} + (h : decode code pc = some (.push 0, next)) (b1 : 1 ≤ bytes) (b32 : bytes ≤ 32) + (op : code[pc]? = some (PUSH1 + bytes - 1)) : + next = pc + 1 + bytes ∧ pc + 1 + bytes ≤ code.length := by + unfold decode at h + rw [op] at h + simp only [PUSH0, PUSH1, PUSH32] at h + have n0 : ¬ (96 + bytes - 1 = 95) := by omega + have r : 96 ≤ 96 + bytes - 1 ∧ 96 + bytes - 1 ≤ 127 := by omega + have e : 96 + bytes - 1 - 96 + 1 = bytes := by omega + simp only [n0, ite_false, r, and_self, ite_true, e] at h + split at h + · rename_i fits + simp only [Option.some.injEq, Prod.mk.injEq] at h + exact ⟨h.2.symm, fits⟩ + · simp at h + +/-- Linear decoding of the linked code from `pc` is the walk's stream with each placeholder +pushing its value, when each placeholder is a push of its width, every placeholder of the walk is +linked, and every placeholder linked is before `pc` or one of the walk's. -/ +theorem walk_link {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) (ps : List Placeholder) + (values : Nat → Nat) : + placed code stream items = true → + (∀ p ∈ placeholdersOf stream items, p ∈ ps) → + (∀ p ∈ ps, p.start + p.bytes ≤ pc ∨ p ∈ placeholdersOf stream items) → + ∀ fuel, items.length < fuel → + decodeFrom (link code ps values) fuel pc = linkedStream values stream items := by + induction w with + | nil => + intro _ _ _ fuel h + cases fuel with + | zero => simp at h + | succ fuel => + have : (link code ps values)[code.length]? = none := by + rw [link_getElem?]; simp + simp [decodeFrom, decode, this, linkedStream] + | @cons pc next item items stream decoded labels rest ih => + intro hplaced hmem hps fuel h + cases fuel with + | zero => simp at h + | succ fuel => + simp only [List.length_cons] at h + have adv := decode_advances decoded + have later := placeholdersOf_gt rest + cases item + case immutable id bytes => + simp only [placed, Bool.and_eq_true, decide_eq_true_eq, beq_iff_eq] at hplaced + obtain ⟨⟨⟨b1, b32⟩, op⟩, hplaced⟩ := hplaced + obtain ⟨hnext, fits⟩ := decode_placeholder decoded b1 b32 op + subst hnext + simp only [placeholdersOf] at hmem hps + have here : ∀ p ∈ ps, p.covers pc = false := by + intro p hp + rcases hps p hp with before | mine + · (simp [Placeholder.covers]; try omega) + · rcases List.mem_cons.1 mine with rfl | tail + · (simp [Placeholder.covers]; try omega) + · have := later p tail + (simp [Placeholder.covers]; try omega) + have opByte : (link code ps values)[pc]? = some (PUSH1 + bytes - 1) := by + rw [link_getElem?_of_uncovered here, op] + have imm : ((link code ps values).drop (pc + 1)).take bytes = + (List.range bytes).map (beByte (values id) bytes) := by + apply List.ext_getElem? + intro j + simp only [List.getElem?_take, List.getElem?_drop, List.getElem?_map] + split + · rename_i hj + rw [link_getElem?] + have lt : pc + 1 + j < code.length := by omega + rw [List.getElem?_eq_getElem lt] + simp only [Option.map_some] + have cov : (⟨id, pc + 1, bytes⟩ : Placeholder).covers (pc + 1 + j) = true := by + (simp [Placeholder.covers]; try omega) + have find := find?_covers (ps := ps) (i := pc + 1 + j) (p := ⟨id, pc + 1, bytes⟩) + (hmem _ List.mem_cons_self) cov (by + intro q hq c + rcases hps q hq with before | mine + · simp [Placeholder.covers] at c; omega + · rcases List.mem_cons.1 mine with e | tail + · exact e + · have := later q tail + simp [Placeholder.covers] at c; omega) + simp [linkByte, find, hj] + · rename_i hj + simp [hj] + have d : decode (link code ps values) pc = + some (.push (values id % 256 ^ bytes), pc + 1 + bytes) := by + unfold decode + rw [opByte] + simp only [PUSH0, PUSH1, PUSH32] + have n0 : ¬ (96 + bytes - 1 = 95) := by omega + have r : 96 ≤ 96 + bytes - 1 ∧ 96 + bytes - 1 ≤ 127 := by omega + have e : 96 + bytes - 1 - 96 + 1 = bytes := by omega + have fits' : pc + 1 + bytes ≤ (link code ps values).length := by + rw [link_length]; exact fits + simp only [n0, ite_false, r, and_self, ite_true, e, fits'] + rw [imm, bigEndian_beBytes] + simp only [decodeFrom, d, linkedStream] + rw [ih hplaced (fun p hp => hmem p (List.mem_cons_of_mem _ hp)) (by + intro p hp + rcases hps p hp with before | mine + · left; omega + · rcases List.mem_cons.1 mine with rfl | tail + · left; simp + · right; exact tail) fuel (by omega)] + all_goals + simp only [placed] at hplaced + simp only [placeholdersOf] at hmem hps + have uncovered : ∀ i, pc ≤ i → i < next → (link code ps values)[i]? = code[i]? := by + intro i h1 h2 + apply link_getElem?_of_uncovered + intro p hp + rcases hps p hp with before | mine + · (simp [Placeholder.covers]; try omega) + · have := later p mine + (simp [Placeholder.covers]; try omega) + have d := decode_congr (link_length code ps values) uncovered decoded + simp only [decodeFrom, d, linkedStream] + rw [ih hplaced hmem (by + intro p hp + rcases hps p hp with before | mine + · left; omega + · right; exact mine) fuel (by omega)] + +/-- Linear decoding of the code linked at the walk's placeholders is the walk's stream with each +placeholder pushing its value. -/ +theorem decodes_linked {code : List Nat} {offset : Nat → Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset 0 items stream) + (hplaced : placed code stream items = true) (values : Nat → Nat) : + decodeFrom (link code (placeholdersOf stream items) values) (code.length + 1) 0 = + linkedStream values stream items := + walk_link w _ values hplaced (fun _ hp => hp) (fun _ hp => .inr hp) _ + (by have := walk_length w; omega) + +/-- The linked stream's instructions are the program's items, each placeholder linked. -/ +theorem linked_instructions {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) (values : Nat → Nat) : + (linkedStream values stream items).map Prod.snd = items.map (Item.linked offset values) := by + induction w with + | nil => simp [linkedStream] + | @cons pc next item items stream decoded labels rest ih => + clear decoded labels rest + cases item <;> simp [linkedStream, Item.linked, ih] + +/-- A walk places each immutable item as a `PUSH` of its width (`Item.placed`), so +linking needs no check of its own. -/ +theorem walk_placed {code : List Nat} {offset : Nat → Nat} {pc : Nat} {items : List Item} + {stream : List (Nat × Instr)} (w : Walk code offset pc items stream) : + placed code stream items = true := by + induction w with + | nil => simp [placed] + | @cons pc next item items stream _ hp _ ih => + cases item <;> simp_all [placed, Item.placed] + +end SolarTV.Assembly diff --git a/tv/SolarTV/State/ByteMemory.lean b/tv/SolarTV/State/ByteMemory.lean new file mode 100644 index 00000000..4faa46ed --- /dev/null +++ b/tv/SolarTV/State/ByteMemory.lean @@ -0,0 +1,34 @@ +import SolarTV.State.Journal + +/-! Shared byte-addressed memory with zero extension, aligned active size and +overlap-safe copies. The 64 KiB bound is a prover work limit, never an EVM trap +or an assumption that permits ignoring a live byte. Gas is modeled separately. -/ + +namespace SolarTV.Execution +open EvmRules + +def memoryWords (memory : List Byte) : Nat := memory.length / 32 + +def requiredWords (memory : List Byte) (offset count : Nat) : Nat := + if count = 0 then memoryWords memory else max (memoryWords memory) ((offset + count + 31) / 32) + +def expand (memory : List Byte) (offset count : Nat) : Except String (List Byte) := + let size := 32 * requiredWords memory offset count + if size > 65536 then .error "world memory limit of 64 KiB" + else .ok (memory ++ List.replicate (size - memory.length) 0) + +def readBytes (bytes : List Byte) (offset count : Nat) : List Byte := + (List.range count).map (fun i => bytes[offset + i]?.getD 0) + +def writeBytes (memory : List Byte) (offset : Nat) (bytes : List Byte) : List Byte := + memory.mapIdx (fun i old => if offset ≤ i ∧ i < offset + bytes.length then + bytes[i - offset]?.getD 0 else old) + +def wordBytes (word : Word) : List Byte := + (List.range 32).map (fun i => (word >>> (8 * (31 - i))).setWidth 8) + +def readWord (bytes : List Byte) (offset : Nat) : Word := + (BitVec.flattenListFast (readBytes bytes offset 32)).setWidth 256 + + +end SolarTV.Execution diff --git a/tv/SolarTV/State/Calls.lean b/tv/SolarTV/State/Calls.lean new file mode 100644 index 00000000..8503c23f --- /dev/null +++ b/tv/SolarTV/State/Calls.lean @@ -0,0 +1,142 @@ +import SolarTV.State.World + +/-! Message-call entry and journal commit/rollback, shared by MIR and EVM IR. +CALL changes the storage owner and transfers value; CALLCODE changes only code; +DELEGATECALL preserves the original caller/value and storage owner; STATICCALL +forces static permission and zero value. All four keep transaction origin. + +Child execution is separate from its boundary. A successful arbitrary child is +not a semantics for CALL; EVMIR/State/Interpreter executes the real child in the +CLI's explicit-world mode. The gas forwarding helper starts after base/memory/value +charges; it does not stand in for the full CALL price or precompile pricing. + +Reference: EVMYulLean 047f630, EVM/Semantics.lean:138-218, 364-418 and 719-815. +https://eips.ethereum.org/EIPS/eip-150 -/ + +namespace SolarTV.Calls +open EvmRules + +inductive Kind where + | call | callcode | delegatecall | staticcall + deriving DecidableEq + +structure Message where + kind : Kind + destination : World.Address + value : Word + input : List World.Byte + deriving DecidableEq + +/-- Whether this opcode explicitly supplies a value operand, not CALLVALUE as +observed by the child. DELEGATECALL can inherit nonzero value in static mode. -/ +def hasValue (message : Message) : Bool := + (message.kind == .call || message.kind == .callcode) && message.value != 0 + +def childEnvironment (parent : World.Environment) (message : Message) : World.Environment := + {parent with + address := if message.kind == .call || message.kind == .staticcall then + message.destination else parent.address + codeAddress := message.destination + caller := if message.kind == .delegatecall then parent.caller else parent.address + value := if message.kind == .delegatecall then parent.value + else if message.kind == .staticcall then 0 else message.value + input := message.input + isStatic := parent.isStatic || message.kind == .staticcall + depth := parent.depth + 1} + +structure Entry where + /-- Snapshot after warming the destination, before any value transfer. -/ + checkpoint : World.State + world : World.State + environment : World.Environment + +inductive Preparation where + | enter (entry : Entry) + | rejected (world : World.State) + | exception (reason : Storage.Error) + +def prepare (world : World.State) (parent : World.Environment) (message : Message) + (fork : Fork := .cancun) : Preparation := + if message.kind == .staticcall && !fork.atLeast .byzantium then .exception .unavailable + else if parent.isStatic && message.kind == .call && message.value != 0 then .exception .staticViolation + else + let checkpoint := World.warmAccount world message.destination + if parent.depth ≥ 1024 then .rejected checkpoint + else if hasValue message && (world.accounts parent.address).balance.ult message.value then + .rejected checkpoint + else + let entered := if message.kind == .call then + World.transfer checkpoint parent.address message.destination message.value + else some checkpoint + match entered with + | none => .rejected checkpoint + | some world => + let world := if message.kind == .call && !fork.atLeast .spuriousDragon then + World.setAccount world message.destination + {(world.accounts message.destination) with present := true} + else world + .enter ⟨checkpoint, world, childEnvironment parent message⟩ + +inductive ChildResult where + | success (world : World.State) (data : List World.Byte) (remaining : Nat) + | reverted (data : List World.Byte) (remaining : Nat) + | exception + +structure Result where + world : World.State + success : Bool + returnData : List World.Byte + remaining : Nat + +/-- Revert keeps return data and unused gas but restores the journal. An +exception has empty return data and burns the complete supplied child budget. -/ +def complete (checkpoint : World.State) : ChildResult → Result + | .success world data remaining => ⟨world, true, data, remaining⟩ + | .reverted data remaining => ⟨checkpoint, false, data, remaining⟩ + | .exception => ⟨checkpoint, false, [], 0⟩ + +structure Budget where + charged : Nat + supplied : Nat + deriving DecidableEq + +def forwardGas (fork : Fork) (available requested : Nat) (value : Bool) : Option Budget := + let cap := if fork.atLeast .tangerineWhistle then available - available / 64 else available + if !fork.atLeast .tangerineWhistle && requested > available then none + else + let forwarded := min requested cap + some ⟨forwarded, forwarded + if value then 2300 else 0⟩ + +@[simp] theorem reverted_restores_journal (checkpoint : World.State) + (data : List World.Byte) (gas : Nat) : + (complete checkpoint (.reverted data gas)).world = checkpoint := rfl + +@[simp] theorem exceptional_call_burns_gas (checkpoint : World.State) : + (complete checkpoint .exception).remaining = 0 := rfl + +@[simp] theorem delegate_keeps_owner (parent : World.Environment) (to : World.Address) + (value : Word) (input : List World.Byte) : + (childEnvironment parent ⟨.delegatecall, to, value, input⟩).address = parent.address := by + simp [childEnvironment] + +@[simp] theorem delegate_keeps_caller (parent : World.Environment) (to : World.Address) + (value : Word) (input : List World.Byte) : + (childEnvironment parent ⟨.delegatecall, to, value, input⟩).caller = parent.caller := by + simp [childEnvironment] + +@[simp] theorem delegate_keeps_value (parent : World.Environment) (to : World.Address) + (value : Word) (input : List World.Byte) : + (childEnvironment parent ⟨.delegatecall, to, value, input⟩).value = parent.value := by + simp [childEnvironment] + +/-- A delegate call in a static frame keeps static permission even if its +inherited CALLVALUE is nonzero. The value is not a new transfer. -/ +theorem static_is_inherited (parent : World.Environment) (message : Message) + (permission : parent.isStatic = true) : + (childEnvironment parent message).isStatic = true := by simp [childEnvironment, permission] + +example : forwardGas .homestead 6400 6401 false = none := by decide +example : forwardGas .tangerineWhistle 6400 6401 false = some ⟨6300, 6300⟩ := by decide +example : forwardGas .cancun 6400 6401 true = some ⟨6300, 8600⟩ := by decide + +end SolarTV.Calls diff --git a/tv/SolarTV/State/Context.lean b/tv/SolarTV/State/Context.lean new file mode 100644 index 00000000..446025f5 --- /dev/null +++ b/tv/SolarTV/State/Context.lean @@ -0,0 +1,46 @@ +import SolarTV.State.Journal + +/-! Explicit transaction and block inputs, shared by direct MIR and EVM execution. +These are immutable inputs, independent of physical instruction selection. -/ + +namespace SolarTV.Execution +open EvmRules + +/-- Explicit block/transaction context, fixed throughout all nested frames. +Missing history entries and out-of-range blob indices denote zero. -/ +structure Block where + number : Word := 0 + beneficiary : Address := 0 + timestamp : Word := 1 + gasLimit : Word := 2^64 - 1 + difficulty : Word := 0 + randomness : Word := 0 + chainId : Word := 1 + baseFee : Word := 0 + blobBaseFee : Word := 1 + slot : BitVec 64 := 0 + hashes : Slots := [] + blobs : List Word := [] + + +def blockHash (context : Block) (number : Word) : Word := + if number.toNat < context.number.toNat && context.number.toNat - number.toNat ≤ 256 then + slotsRead context.hashes number + else 0 + +def environmentValue (fork : Fork) (context : Block) (opcode : Nat) (argument : Word) : Word := + match opcode with + | 0x40 => blockHash context argument + | 0x41 => context.beneficiary.setWidth 256 + | 0x42 => context.timestamp + | 0x43 => context.number + | 0x44 => if fork.atLeast .paris then context.randomness else context.difficulty + | 0x45 => context.gasLimit + | 0x46 => context.chainId + | 0x48 => context.baseFee + | 0x49 => context.blobs[argument.toNat]?.getD 0 + | 0x4a => context.blobBaseFee + | 0x4b => context.slot.setWidth 256 + | _ => 0 + +end SolarTV.Execution diff --git a/tv/SolarTV/State/Fork.lean b/tv/SolarTV/State/Fork.lean new file mode 100644 index 00000000..ec3450e8 --- /dev/null +++ b/tv/SolarTV/State/Fork.lean @@ -0,0 +1,22 @@ +/-! Fork ordering shared by state and gas semantics. The constructors match the +compiler's EvmVersion schema. Feature availability and gas are separate: an +unavailable opcode is exceptional, not an expensive version of a legal one. -/ + +namespace SolarTV + +inductive Fork where + | homestead | tangerineWhistle | spuriousDragon | byzantium + | constantinople | petersburg | istanbul | berlin | london | paris + | shanghai | cancun | prague | osaka | amsterdam + deriving DecidableEq, Repr + +def Fork.ordinal : Fork → Nat + | .homestead => 0 | .tangerineWhistle => 1 | .spuriousDragon => 2 + | .byzantium => 3 | .constantinople => 4 | .petersburg => 5 + | .istanbul => 6 | .berlin => 7 | .london => 8 | .paris => 9 + | .shanghai => 10 | .cancun => 11 | .prague => 12 | .osaka => 13 + | .amsterdam => 14 + +def Fork.atLeast (fork since : Fork) : Bool := since.ordinal ≤ fork.ordinal + +end SolarTV diff --git a/tv/SolarTV/State/Journal.lean b/tv/SolarTV/State/Journal.lean new file mode 100644 index 00000000..bb9c5526 --- /dev/null +++ b/tv/SolarTV/State/Journal.lean @@ -0,0 +1,88 @@ +import SolarTV.State.World + +/-! Shared finite journals for explicit-world MIR and EVM execution. Account and +slot updates preserve unrelated state; both evaluators use the same address-qualified +store. No instruction, backend layout, gas policy or stack convention lives here. -/ + +namespace SolarTV.Execution +open EvmRules + +abbrev Byte := BitVec 8 +abbrev Address := BitVec 160 +abbrev Slots := List (Word × Word) + +structure Account where + address : Address + nonce : Nat := 0 + balance : Word := 0 + code : List Byte := [] + storage : Slots := [] + transient : Slots := [] + created : Bool := false + destroyed : Bool := false + deriving DecidableEq + +structure Journal where + accounts : List Account + original : List Account + warmAddresses : List Address + warmSlots : List (Address × Word) + logs : List World.Log := [] + refund : Int := 0 + deriving DecidableEq + +def slotsRead (slots : Slots) (key : Word) : Word := + (slots.find? (fun entry => entry.1 == key)).map Prod.snd |>.getD 0 + +def slotsWrite (slots : Slots) (key value : Word) : Slots := + (key, value) :: slots.filter (fun entry => entry.1 != key) + +def account (world : Journal) (address : Address) : Account := + (world.accounts.find? (fun a => a.address == address)).getD {address} + +def putAccount (world : Journal) (account : Account) : Journal := + {world with accounts := account :: world.accounts.filter (fun a => a.address != account.address)} + +def warmAddress (world : Journal) (address : Address) : Journal := + {world with warmAddresses := if world.warmAddresses.contains address then world.warmAddresses + else address :: world.warmAddresses} + +def warmSlot (world : Journal) (address : Address) (key : Word) : Journal := + {world with warmSlots := if world.warmSlots.contains (address, key) then world.warmSlots + else (address, key) :: world.warmSlots} + +def transfer (world : Journal) (source destination : Address) (value : Word) : Option Journal := + let sender := account world source + if sender.balance.ult value then none + else if source = destination || value == 0 then some world + else + let world := putAccount world {sender with balance := sender.balance - value} + let to := account world destination + some (putAccount world {to with balance := to.balance + value}) + + +/-- Structural sorting keeps concrete observation proofs reducible in the kernel. +The finite fixture/evaluator bounds keep these comparison-only lists small. -/ +def orderedInsert (le : α → α → Bool) (value : α) : List α → List α + | [] => [value] + | head :: rest => if le value head then value :: head :: rest + else head :: orderedInsert le value rest + +def ordered (le : α → α → Bool) : List α → List α + | [] => [] + | head :: rest => orderedInsert le head (ordered le rest) + +def normalizedSlots (slots : Slots) : Slots := + ordered (fun a b => a.1.ule b.1) (slots.filter (fun entry => entry.2 != 0)) + +/-- Same-key overwrite is the state identity used by storage-DSE, without alias assumptions. -/ +@[simp] theorem slotsWrite_overwrite (slots : Slots) (key old value : Word) : + slotsWrite (slotsWrite slots key old) key value = slotsWrite slots key value := by + simp [slotsWrite, List.filter_filter] + +/-- Reading the cell just written returns its value independently of the initial journal. -/ +@[simp] theorem slotsRead_write (slots : Slots) (key value : Word) : + slotsRead (slotsWrite slots key value) key = value := by + simp [slotsRead, slotsWrite] + +end SolarTV.Execution diff --git a/tv/SolarTV/State/MemoryLaws.lean b/tv/SolarTV/State/MemoryLaws.lean new file mode 100644 index 00000000..162d15ef --- /dev/null +++ b/tv/SolarTV/State/MemoryLaws.lean @@ -0,0 +1,76 @@ +import SolarTV.State.ByteMemory + +/-! Kernel-proved byte-memory normalization, independent of any compiler pass. +Read-over-write rules require actual overlap/active-range proofs; they never +assume that two pointers are distinct. Pre-simplification avoids expanding an +entire symbolic heap merely to read an untouched allocation-cursor word. -/ + +namespace SolarTV.Execution +open EvmRules + +@[simp] theorem wordBytes_length (value : Word) : (wordBytes value).length = 32 := by + simp [wordBytes] + +@[simp] theorem writeBytes_length (memory bytes : List Byte) (offset : Nat) : + (writeBytes memory offset bytes).length = memory.length := by + simp [writeBytes] + +theorem readBytes_writeBytes_disjoint (memory bytes : List Byte) (destination source count : Nat) + (h : destination + bytes.length ≤ source ∨ source + count ≤ destination) : + readBytes (writeBytes memory destination bytes) source count = readBytes memory source count := by + unfold readBytes + apply List.map_congr_left + intro i hi + have hi' : i < count := List.mem_range.mp hi + have outside : ¬ (destination ≤ source + i ∧ source + i < destination + bytes.length) := by omega + simp [writeBytes, List.getElem?_mapIdx, outside] + +theorem readBytes_writeBytes_same (memory bytes : List Byte) (offset : Nat) + (h : offset + bytes.length ≤ memory.length) : + readBytes (writeBytes memory offset bytes) offset bytes.length = bytes := by + apply List.ext_getElem + · simp [readBytes] + · intro i hi hj + have hm : offset + i < memory.length := by omega + simp [readBytes, writeBytes, List.getElem?_mapIdx, List.getElem?_eq_getElem hm, + Nat.add_sub_cancel_left, List.getElem?_eq_getElem hj] <;> omega + +theorem flatten_wordBytes (word : Word) : (BitVec.flattenList (wordBytes word)).setWidth 256 = word := by + have hl : (wordBytes word).length = 32 := by simp [wordBytes] + apply BitVec.eq_of_getLsbD_eq + intro i hi + have hj : 31 - i / 8 < 32 := by omega + have hm : i % 8 < 8 := Nat.mod_lt i (by decide) + have hp : 8 * (31 - (31 - i / 8)) + i % 8 = i := by omega + have hr : (List.range 32)[31 - i / 8]? = some (31 - i / 8) := by + rw [List.getElem?_eq_getElem (by simpa using hj)] + simp + simp only [BitVec.getLsbD_setWidth, BitVec.getLsbD_flattenList, hl, hi, decide_true, Bool.true_and] + simp only [wordBytes, List.getElem?_map, hr, Option.map_some, Option.getD_some] + simp only [BitVec.getLsbD_setWidth, hm, decide_true, Bool.true_and, BitVec.getLsbD_ushiftRight, hp] + +@[simp↓] theorem readWord_writeWord (memory : List Byte) (offset : Nat) (word : Word) + (h : offset + 32 ≤ memory.length) : + readWord (writeBytes memory offset (wordBytes word)) offset = word := by + change (BitVec.flattenListFast (readBytes (writeBytes memory offset (wordBytes word)) offset (wordBytes word).length)).setWidth 256 = word + rw [readBytes_writeBytes_same memory (wordBytes word) offset (by simpa using h)] + rw [← BitVec.flattenList_eq_flattenListFast] + exact flatten_wordBytes word + +@[simp↓] theorem readWord_writeBytes_disjoint (memory bytes : List Byte) (destination source : Nat) + (h : destination + bytes.length ≤ source ∨ source + 32 ≤ destination) : + readWord (writeBytes memory destination bytes) source = readWord memory source := by + unfold readWord + rw [readBytes_writeBytes_disjoint memory bytes destination source 32 h] + +@[simp↓] theorem readWord_append_prefix (memory bytes : List Byte) (offset : Nat) + (h : offset + 32 ≤ memory.length) : readWord (memory ++ bytes) offset = readWord memory offset := by + unfold readWord + congr 2 + unfold readBytes + apply List.map_congr_left + intro i hi + have hm : offset + i < memory.length := by have := List.mem_range.mp hi; omega + simp [List.getElem?_append_left hm] + +end SolarTV.Execution diff --git a/tv/SolarTV/State/Storage.lean b/tv/SolarTV/State/Storage.lean new file mode 100644 index 00000000..b61bdf96 --- /dev/null +++ b/tv/SolarTV/State/Storage.lean @@ -0,0 +1,123 @@ +import SolarTV.State.Fork +import EvmRules.Word + +/-! Persistent and transient storage with transaction-original values, per-address +access warmth and signed refunds. Stores are total functions, so proofs quantify +over all slots rather than assuming an initially empty or finitely sized store. + +Pricing follows EIP-2200 (including its <=2300 gas sentry), EIP-2929's cold +surcharge and reset price, and EIP-3529's clear refund. Constantinople uses +EIP-1283 without the sentry; Petersburg restores the legacy rules. Refunds +are signed because an individual frame may remove a refund earned by its caller. +A failed store leaves all state to its enclosing frame's rollback rule. +https://eips.ethereum.org/EIPS/eip-2200#specification +https://eips.ethereum.org/EIPS/eip-2929#sstore-changes +https://eips.ethereum.org/EIPS/eip-3529#specification -/ + +namespace SolarTV.Storage +open EvmRules + +abbrev Address := BitVec 160 +abbrev Store := Address → Word → Word +abbrev WarmSlots := Address → Word → Bool + +def update (store : Store) (address : Address) (slot value : Word) : Store := + fun a k => if a = address ∧ k = slot then value else store a k + +def warm (slots : WarmSlots) (address : Address) (slot : Word) : WarmSlots := + fun a k => (a == address && k == slot) || slots a k + +structure State where + persistent : Store + original : Store + transient : Store + accessed : WarmSlots + refund : Int + +inductive Error where + | outOfGas | staticViolation | unavailable + deriving DecidableEq + +structure Price where + gas : Nat + refund : Int + deriving DecidableEq + +def readPrice (fork : Fork) (warm : Bool) : Nat := + if fork.atLeast .berlin then if warm then 100 else 2100 + else if fork.atLeast .istanbul then 800 + else if fork.atLeast .tangerineWhistle then 200 else 50 + +def netMetered (fork : Fork) : Bool := + fork == .constantinople || fork.atLeast .istanbul + +/-- Pricing alone does not enforce the sentry or static permission. -/ +def writePrice (fork : Fork) (warm : Bool) (original current value : Word) : Price := + let cold := if fork.atLeast .berlin && !warm then 2100 else 0 + let read := readPrice fork true + let reset := if fork.atLeast .berlin then 2900 else 5000 + let clear : Int := if fork.atLeast .london then 4800 else 15000 + if !netMetered fork then + ⟨if current == 0 && value != 0 then 20000 else 5000, + if current != 0 && value == 0 then clear else 0⟩ + else if current == value then ⟨cold + read, 0⟩ + else if original == current then + if original == 0 then ⟨cold + 20000, 0⟩ + else ⟨cold + reset, if value == 0 then clear else 0⟩ + else + let remove := if original != 0 && current == 0 then -clear else 0 + let add := if original != 0 && value == 0 then clear else 0 + let restored := if original == value then + (if original == 0 then (20000 : Int) else (reset : Int)) - (read : Int) else 0 + ⟨cold + read, remove + add + restored⟩ + +def load (fork : Fork) (state : State) (address : Address) (slot : Word) (gas : Nat) : + Except Error (Word × State × Nat) := + let charge := readPrice fork (state.accessed address slot) + if gas < charge then .error .outOfGas else + .ok (state.persistent address slot, + {state with accessed := warm state.accessed address slot}, gas - charge) + +def store (fork : Fork) (state : State) (address : Address) (slot value : Word) + (gas : Nat) (isStatic : Bool) : Except Error (State × Nat) := + if isStatic then .error .staticViolation + else if fork.atLeast .istanbul && gas ≤ 2300 then .error .outOfGas + else + let price := writePrice fork (state.accessed address slot) + (state.original address slot) (state.persistent address slot) value + if gas < price.gas then .error .outOfGas else + .ok ({state with + persistent := update state.persistent address slot value + accessed := warm state.accessed address slot + refund := state.refund + price.refund}, + gas - price.gas) + +def tload (fork : Fork) (state : State) (address : Address) (slot : Word) (gas : Nat) : + Except Error (Word × Nat) := + if !fork.atLeast .cancun then .error .unavailable + else if gas < 100 then .error .outOfGas + else .ok (state.transient address slot, gas - 100) + +/-- Transient stores have no EIP-2200 sentry and no refund. -/ +def tstore (fork : Fork) (state : State) (address : Address) (slot value : Word) + (gas : Nat) (isStatic : Bool) : Except Error (State × Nat) := + if !fork.atLeast .cancun then .error .unavailable + else if isStatic then .error .staticViolation + else if gas < 100 then .error .outOfGas + else .ok ({state with transient := update state.transient address slot value}, gas - 100) + +@[simp] theorem update_same (state : Store) (a : Address) (k value : Word) : + update state a k value a k = value := by simp [update] + +@[simp] theorem update_other (state : Store) (a b : Address) (k j value : Word) + (different : b ≠ a ∨ j ≠ k) : update state a k value b j = state b j := by + simp only [update] + rcases different with h | h <;> simp_all + +theorem overwrite (state : Store) (a : Address) (k first last : Word) : + update (update state a k first) a k last = update state a k last := by + funext b j + simp only [update] + split <;> simp_all + +end SolarTV.Storage diff --git a/tv/SolarTV/State/StorageSafety.lean b/tv/SolarTV/State/StorageSafety.lean new file mode 100644 index 00000000..11246145 --- /dev/null +++ b/tv/SolarTV/State/StorageSafety.lean @@ -0,0 +1,32 @@ +import SolarTV.State.Storage + +/-! Storage boundary proofs independent of any importer projection. The examples +pin zero/no-op stores, cold/warm pricing, dirty-slot refunds, the stipend sentry +and the distinct transient-store rule. All proofs are checked in the kernel. -/ + +namespace SolarTV.Storage + +example : writePrice .homestead false 0 0 0 = ⟨5000, 0⟩ := by decide +example : writePrice .constantinople false 0 0 0 = ⟨200, 0⟩ := by decide +example : writePrice .petersburg false 0 0 0 = ⟨5000, 0⟩ := by decide +example : writePrice .istanbul false 0 0 0 = ⟨800, 0⟩ := by decide +example : writePrice .berlin false 0 0 0 = ⟨2200, 0⟩ := by decide +example : writePrice .london false 7 7 0 = ⟨5000, 4800⟩ := by decide +example : writePrice .london true 7 0 7 = ⟨100, -2000⟩ := by decide +example : writePrice .london true 0 1 0 = ⟨100, 19900⟩ := by decide + +/-- Equal storage contents do not suffice for gas equivalence: access warmth matters. -/ +theorem cold_read_costs_more : readPrice .cancun false > readPrice .cancun true := by decide + +/-- No-op stores still fail the gas sentry, even though their price is only 100. -/ +theorem sentry_rejects (state : State) (a : Address) (k value : EvmRules.Word) : + store .cancun state a k value 2300 false = .error .outOfGas := by + simp [store, Fork.atLeast, Fork.ordinal] + +/-- A transient store at the same budget succeeds and leaves persistent storage alone. -/ +theorem transient_ignores_sentry (state : State) (a : Address) (k value : EvmRules.Word) : + tstore .cancun state a k value 100 false = + .ok ({state with transient := update state.transient a k value}, 0) := by + simp [tstore, Fork.atLeast, Fork.ordinal] + +end SolarTV.Storage diff --git a/tv/SolarTV/State/World.lean b/tv/SolarTV/State/World.lean new file mode 100644 index 00000000..642e7afe --- /dev/null +++ b/tv/SolarTV/State/World.lean @@ -0,0 +1,87 @@ +import SolarTV.State.Storage + +/-! Account state and journaled transaction effects. Storage includes the address +of its owner, so CALL and DELEGATECALL cannot accidentally share a global slot +map. Snapshots include transient storage, logs, refund and access sets; restoring +only persistent storage would be incorrect after a child reverts. + +These definitions describe state and message boundaries, not an oracle for +executing unknown code. A child result must eventually come from the instruction +semantics; it is not admitted as an unconstrained successful call by the CLI. -/ + +namespace SolarTV.World +open EvmRules + +abbrev Address := Storage.Address +abbrev Byte := BitVec 8 + +structure Account where + present : Bool + nonce : Nat + balance : Word + code : List Byte + deriving DecidableEq + +structure Log where + address : Address + topics : List Word + data : List Byte + deriving DecidableEq + +structure State where + accounts : Address → Account + storage : Storage.State + logs : List Log + accessedAccounts : Address → Bool + created : Address → Bool + destructed : Address → Bool + +structure Environment where + address : Address + codeAddress : Address + caller : Address + origin : Address + value : Word + gasPrice : Word + input : List Byte + isStatic : Bool + depth : Nat + deriving DecidableEq + +def setAccount (state : State) (address : Address) (account : Account) : State := + {state with accounts := fun a => if a = address then account else state.accounts a} + +def warmAccount (state : State) (address : Address) : State := + {state with accessedAccounts := fun a => a == address || state.accessedAccounts a} + +/-- The caller checks sufficient funds. Self-transfers do not mint or destroy funds. -/ +def transfer (state : State) (source destination : Address) (value : Word) : Option State := + if (state.accounts source).balance.ult value then none + else if source = destination then some state + else + let debited := setAccount state source + {(state.accounts source) with balance := (state.accounts source).balance - value} + let credited := {(debited.accounts destination) with + present := (debited.accounts destination).present || value != 0 + balance := (debited.accounts destination).balance + value} + some (setAccount debited destination credited) + +/-- A log is forbidden in static mode, including LOG0 with zero bytes. -/ +def emitLog (state : State) (environment : Environment) (topics : List Word) (data : List Byte) : + Except Storage.Error State := + if environment.isStatic then .error .staticViolation + else .ok {state with logs := state.logs ++ [⟨environment.address, topics, data⟩]} + +@[simp] theorem setAccount_same (state : State) (address : Address) (account : Account) : + (setAccount state address account).accounts address = account := by simp [setAccount] + +@[simp] theorem setAccount_other (state : State) (address other : Address) (account : Account) + (different : other ≠ address) : + (setAccount state address account).accounts other = state.accounts other := by + simp [setAccount, different] + +theorem transfer_to_self (state : State) (address : Address) (value : Word) + (funds : (state.accounts address).balance.ult value = false) : + transfer state address address value = some state := by simp [transfer, funds] + +end SolarTV.World diff --git a/tv/SolarTV/Termination.lean b/tv/SolarTV/Termination.lean new file mode 100644 index 00000000..3c0875ef --- /dev/null +++ b/tv/SolarTV/Termination.lean @@ -0,0 +1,734 @@ +import SolarTV.CutPointHoare + +/-! # Termination and resource certificates through cut points + +`CutPoint.ends_of_segments` proves that a machine ends from a Nat rank that every segment +between cut points lowers. This module makes that the reusable termination checker the +certified pipeline needs, in four parts. + +* **Well-founded ranks** (`ends_of_segments_wf`, `ends_of_reach`): any well-founded relation + on any type of ranks, so nested loops take lexicographic ranks (`Prod.Lex`) and recursion + takes a measure on the call stack. The ranking certificate is data (an invariant and a rank + per cut point, emitted by solar's `inferred.py` from what `solar-verify --show-inferred` + infers); nothing here trusts it: each segment must be shown to end at a cut point meeting the + invariant with a lower rank, or in a result meeting the postcondition. A segment that is stuck + or runs out of its fuel proves nothing (`SegEnds` is `False` there), so a certificate whose + rank does not fall fails by mismatch (`Negative.flat_rejected`). + +* **Compositional total contracts** (`Reaches`, `Reaches.trans`, `Reaches.of_wf`): a total + contract `Reaches step Pre Q` says every configuration meeting `Pre` runs, in finitely many + steps, to one meeting `Q` (an internal call's entry to its return to the caller) or to an end + meeting `Post`. Contracts compose, and a recursive function's contract follows from its + body's under a well-founded recursion measure (`Reaches.of_wf`): the body may use the + contract at every call whose measure is lower. + +* **Explicit step bounds** (`ends_within`, `ends_within_start`): when every segment of the + certificate has at most `K` steps, a run from a cut point of rank `r` ends within + `(r + 1) * K` steps; a bound derived from the ranking, not a chosen fuel. + +* **Resources** (`runGas`, `gas_ends`, `runGas_done_run`): a metered run charges each step + `cost x` before it takes it and fails with `oog` when the gas left is lower, as the EVM does. + When every segment of the certificate costs at most `C`, a metered run from a cut point of + rank `r` with gas at least `(r + 1) * C` never runs out of gas and ends in a result meeting + `Post` (`gas_ends`); and a metered run that ends gives the result the unmetered run gives + (`runGas_done_run`), so the resource bound is a separate theorem from the gas-insensitive + behaviour, and the premise on the gas is a number, not an assumption of success. + `Negative.oog_below` shows the bound is not vacuous: below it a metered run does run out. +-/ + +namespace SolarTV.CutPoint + +universe u v w + +variable {σ : Type u} {R : Type v} + +/-- A segment's obligation is decidable when its parts are, so a certificate on concrete +configurations is checked by evaluation. -/ +instance SegEnds.decidable {Inv : σ → Prop} {Post : R → Prop} {below : σ → Prop} + [DecidablePred Inv] [DecidablePred Post] [DecidablePred below] : + ∀ s : Seg R σ, Decidable (SegEnds Inv Post below s) + | .done r => inferInstanceAs (Decidable (Post r)) + | .cut y => inferInstanceAs (Decidable (Inv y ∧ below y)) + | .stuck => isFalse id + | .fuel => isFalse id + +/-! ## Segment lengths -/ + +section Lengths + +variable {step : Step σ R} {cut : σ → Bool} + +/-- A segment with `k` steps of fuel that reaches a cut point ran at most `k` steps to it. -/ +theorem seg_cut_le : ∀ {k : Nat} {x y : σ}, seg step cut k x = .cut y → + ∃ j, 1 ≤ j ∧ j ≤ k ∧ ∀ n, run step (n + j) x = run step n y ∧ steps step (n + j) x = steps step n y + | 0, _, _, h => by cases h + | k + 1, x, y, h => by + simp only [seg] at h + cases e : step x with + | none => rw [e] at h; cases h + | some v => + cases v with + | inl r => rw [e] at h; cases h + | inr z => + rw [e] at h + simp only at h + by_cases c : cut z = true + · simp only [c, ↓reduceIte] at h + cases h + refine ⟨1, Nat.le_refl 1, by omega, fun n => ⟨?_, ?_⟩⟩ <;> simp only [run, steps, e] + · simp only [c] at h + obtain ⟨j, pos, le, runs⟩ := seg_cut_le h + refine ⟨j + 1, by omega, by omega, fun n => ?_⟩ + rw [← Nat.add_assoc] + simp only [run, steps, e] + exact runs n + +/-- A segment with `k` steps of fuel that ends ran at most `k` steps to its result. -/ +theorem seg_done_le : ∀ {k : Nat} {x : σ} {r : R}, seg step cut k x = .done r → + ∃ j, 1 ≤ j ∧ j ≤ k ∧ ∀ n, run step (n + j) x = some r + | 0, _, _, h => by cases h + | k + 1, x, r, h => by + simp only [seg] at h + cases e : step x with + | none => rw [e] at h; cases h + | some v => + cases v with + | inl r' => + rw [e] at h + cases h + exact ⟨1, Nat.le_refl 1, by omega, fun n => by simp only [run, e]⟩ + | inr z => + rw [e] at h + simp only at h + by_cases c : cut z = true + · simp only [c, ↓reduceIte] at h; cases h + · simp only [c] at h + obtain ⟨j, pos, le, runs⟩ := seg_done_le h + refine ⟨j + 1, by omega, by omega, fun n => ?_⟩ + rw [← Nat.add_assoc] + simp only [run, e] + exact runs n + +end Lengths + +/-! ## Well-founded ranks -/ + +/-- **Total correctness through cut points under any well-founded rank**: lexicographic ranks +for nested loops, stack measures for recursion. -/ +theorem ends_of_segments_wf {step : Step σ R} {cut : σ → Bool} {Inv : σ → Prop} {Post : R → Prop} + {α : Sort w} {lt : α → α → Prop} (wf : WellFounded lt) (rank : σ → α) + (segment : ∀ x, Inv x → ∃ k, SegEnds Inv Post (fun y => lt (rank y) (rank x)) (seg step cut k x)) : + ∀ x, Inv x → ∃ n r, run step n x = some r ∧ Post r := by + intro x + induction x using (InvImage.wf rank wf).induction with + | h x ih => + intro inv + obtain ⟨k, hk⟩ := segment x inv + cases hs : seg step cut k x with + | fuel | stuck => rw [hs] at hk; exact hk.elim + | done a => + rw [hs] at hk + obtain ⟨j, _, runs⟩ := seg_done hs + exact ⟨0 + j, a, runs 0, hk⟩ + | cut y => + rw [hs] at hk + obtain ⟨iy, lt'⟩ := hk + obtain ⟨j, _, runs⟩ := seg_cut hs + obtain ⟨n, r, ran, post⟩ := ih y lt' iy + exact ⟨n + j, r, by rw [(runs n).1]; exact ran, post⟩ + +/-! ## Compositional total contracts -/ + +/-- **A total contract**: from every configuration meeting `Pre`, the machine reaches, in +finitely many steps, a configuration meeting `Q` or an end meeting `Post`. An internal call's +contract has the callee's entry as `Pre` and the caller's return configuration as `Q`. -/ +def Reaches (step : Step σ R) (Pre Q : σ → Prop) (Post : R → Prop) : Prop := + ∀ x, Pre x → (∃ n r, run step n x = some r ∧ Post r) ∨ ∃ j y, steps step j x = some (.inr y) ∧ Q y + +theorem steps_add {step : Step σ R} : ∀ (i j : Nat) (x : σ) (y : σ), + steps step i x = some (.inr y) → steps step (i + j) x = steps step j y + | 0, j, x, y, h => by simp only [steps] at h; cases h; simp + | i + 1, j, x, y, h => by + rw [Nat.add_right_comm] + simp only [steps] at h ⊢ + cases e : step x with + | none => rw [e] at h; cases h + | some v => + cases v with + | inl r => rw [e] at h; cases h + | inr z => rw [e] at h; exact steps_add i j z y h + +theorem run_add {step : Step σ R} (i n : Nat) (x y : σ) (h : steps step i x = some (.inr y)) : + run step (i + n) x = run step n y := by + rw [run_eq_steps, run_eq_steps, steps_add i n x y h] + +/-- Total contracts compose. -/ +theorem Reaches.trans {step : Step σ R} {P Q S : σ → Prop} {Post : R → Prop} + (h1 : Reaches step P Q Post) (h2 : Reaches step Q S Post) : Reaches step P S Post := by + intro x hx + rcases h1 x hx with e | ⟨i, y, hy, qy⟩ + · exact Or.inl e + rcases h2 y qy with ⟨n, r, ran, post⟩ | ⟨j, z, hz, sz⟩ + · exact Or.inl ⟨i + n, r, by rw [run_add i n x y hy]; exact ran, post⟩ + · exact Or.inr ⟨i + j, z, by rw [steps_add i j x y hy]; exact hz, sz⟩ + +/-- A total contract whose target is the end itself is termination. -/ +theorem Reaches.ends {step : Step σ R} {P : σ → Prop} {Post : R → Prop} + (h : Reaches step P (fun _ => False) Post) : ∀ x, P x → ∃ n r, run step n x = some r ∧ Post r := + fun x hx => (h x hx).resolve_right (fun ⟨_, _, _, f⟩ => f) + +/-- **Recursion**: a contract follows from its body's, when the body may use the contract at +every configuration of lower measure (the recursive calls), for a well-founded measure. -/ +theorem Reaches.of_wf {step : Step σ R} {P Q : σ → Prop} {Post : R → Prop} {α : Sort w} + {lt : α → α → Prop} (wf : WellFounded lt) (μ : σ → α) + (body : ∀ x, P x → Reaches step (fun x' => P x' ∧ lt (μ x') (μ x)) Q Post → + (∃ n r, run step n x = some r ∧ Post r) ∨ ∃ j y, steps step j x = some (.inr y) ∧ Q y) : + Reaches step P Q Post := by + intro x + induction x using (InvImage.wf μ wf).induction with + | h x ih => exact fun hx => body x hx (fun x' ⟨px', lt'⟩ => ih x' lt' px') + +/-- Total correctness from contracts: when every configuration of the invariant reaches an end +meeting `Post` or another configuration of the invariant with a lower rank (a segment, or a +segment that runs a callee through its contract), every run from the invariant ends. Unlike +`ends_of_segments_wf`, the steps to the next configuration need not stop at the first cut +point, so a caller's segment may run a whole callee. -/ +theorem ends_of_reach {step : Step σ R} {Inv : σ → Prop} {Post : R → Prop} {α : Sort w} + {lt : α → α → Prop} (wf : WellFounded lt) (rank : σ → α) + (segment : ∀ x, Inv x → (∃ n r, run step n x = some r ∧ Post r) ∨ + ∃ j y, steps step j x = some (.inr y) ∧ Inv y ∧ lt (rank y) (rank x)) : + ∀ x, Inv x → ∃ n r, run step n x = some r ∧ Post r := by + intro x + induction x using (InvImage.wf rank wf).induction with + | h x ih => + intro inv + rcases segment x inv with e | ⟨i, y, hy, iy, lt'⟩ + · exact e + obtain ⟨n, r, ran, post⟩ := ih y lt' iy + exact ⟨i + n, r, by rw [run_add i n x y hy]; exact ran, post⟩ + +/-! ## Segments to a callee's return -/ + +/-- A segment of a callee that ends as its total contract asks: in a result meeting `Post` +(a revert, say), at a cut point of its invariant with a lower rank, or at a configuration +meeting `Q` (the caller resumed). Stuck and out of fuel prove nothing. -/ +def SegReaches (Inv Q : σ → Prop) (Post : R → Prop) (below : σ → Prop) : Seg R σ → Prop + | .done r => Post r + | .cut y => (Inv y ∧ below y) ∨ Q y + | .stuck => False + | .fuel => False + +/-- A weaker invariant, target and postcondition. -/ +theorem SegReaches.mono {Inv Inv' Q Q' : σ → Prop} {Post Post' : R → Prop} {below : σ → Prop} + (hi : ∀ y, Inv y → Inv' y) (hq : ∀ y, Q y → Q' y) (hp : ∀ r, Post r → Post' r) : + ∀ {s : Seg R σ}, SegReaches Inv Q Post below s → SegReaches Inv' Q' Post' below s + | .done _, h => hp _ h + | .cut _, h => h.elim (fun ⟨a, b⟩ => Or.inl ⟨hi _ a, b⟩) (fun q => Or.inr (hq _ q)) + | .stuck, h | .fuel, h => h + +/-- **A callee's total contract from its segments**: when every segment from the invariant ends +in a result meeting `Post`, at the invariant with a lower rank, or at `Q`, every configuration of +the invariant reaches `Q` or such a result. -/ +theorem reaches_of_segments {step : Step σ R} {cut : σ → Bool} {Inv Q : σ → Prop} + {Post : R → Prop} (rank : σ → Nat) + (segment : ∀ x, Inv x → ∃ k, SegReaches Inv Q Post (fun y => rank y < rank x) (seg step cut k x)) : + Reaches step Inv Q Post := by + intro x + induction h : rank x using Nat.strongRecOn generalizing x with + | ind m ih => + intro inv + obtain ⟨k, hk⟩ := segment x inv + cases hs : seg step cut k x with + | fuel | stuck => rw [hs] at hk; exact hk.elim + | done a => + rw [hs] at hk + obtain ⟨j, _, runs⟩ := seg_done hs + exact Or.inl ⟨0 + j, a, runs 0, hk⟩ + | cut y => + rw [hs] at hk + obtain ⟨j, _, runs⟩ := seg_cut hs + have hy : steps step j x = some (.inr y) := by + have := (runs 0).2 + simpa [steps] using this + rcases hk with ⟨iy, lt⟩ | qy + · rcases ih (rank y) (h ▸ lt) y rfl iy with ⟨n, r, ran, post⟩ | ⟨i, z, hz, qz⟩ + · exact Or.inl ⟨j + n, r, by rw [run_add j n x y hy]; exact ran, post⟩ + · exact Or.inr ⟨j + i, z, by rw [steps_add j i x y hy]; exact hz, qz⟩ + · exact Or.inr ⟨j, y, hy, qy⟩ + +/-- The same from a first configuration that need not be a cut point. -/ +theorem reaches_of_start {step : Step σ R} {cut : σ → Bool} {Inv Q : σ → Prop} + {Post : R → Prop} (rank : σ → Nat) {x₀ : σ} + (start : ∃ k, SegReaches Inv Q Post (fun _ => True) (seg step cut k x₀)) + (segment : ∀ x, Inv x → ∃ k, SegReaches Inv Q Post (fun y => rank y < rank x) (seg step cut k x)) : + (∃ n r, run step n x₀ = some r ∧ Post r) ∨ ∃ j y, steps step j x₀ = some (.inr y) ∧ Q y := + Reaches.trans (P := (· = x₀)) (Q := fun y => Inv y ∨ Q y) + (fun x hx => by + subst hx + obtain ⟨k, hk⟩ := start + cases hs : seg step cut k x with + | fuel | stuck => rw [hs] at hk; exact hk.elim + | done a => + rw [hs] at hk + obtain ⟨j, _, runs⟩ := seg_done hs + exact Or.inl ⟨0 + j, a, runs 0, hk⟩ + | cut y => + rw [hs] at hk + obtain ⟨j, _, runs⟩ := seg_cut hs + have hy : steps step j x = some (.inr y) := by simpa [steps] using (runs 0).2 + exact Or.inr ⟨j, y, hy, hk.elim (fun h => Or.inl h.1) Or.inr⟩) + (fun y hy => hy.elim (reaches_of_segments rank segment y) + (fun q => Or.inr ⟨0, y, rfl, q⟩)) x₀ rfl + +/-- info: 'SolarTV.CutPoint.reaches_of_start' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms reaches_of_start + +/-! ## Explicit step bounds -/ + +/-- **A step bound from the ranking**: when every segment of the certificate takes at most `K` +steps of fuel, a run from a cut point of rank `r` ends within `(r + 1) * K` steps. -/ +theorem ends_within {step : Step σ R} {cut : σ → Bool} {Inv : σ → Prop} {Post : R → Prop} + (rank : σ → Nat) (K : Nat) + (segment : ∀ x, Inv x → SegEnds Inv Post (fun y => rank y < rank x) (seg step cut K x)) : + ∀ x, Inv x → ∃ r, run step ((rank x + 1) * K) x = some r ∧ Post r := by + intro x + induction h : rank x using Nat.strongRecOn generalizing x with + | ind m ih => + intro inv + have hk := segment x inv + cases hs : seg step cut K x with + | fuel | stuck => rw [hs] at hk; exact hk.elim + | done a => + rw [hs] at hk + obtain ⟨j, _, le, runs⟩ := seg_done_le hs + refine ⟨a, ?_, hk⟩ + have := runs ((m + 1) * K - j) + rw [show (m + 1) * K - j + j = (m + 1) * K by + have : K ≤ (m + 1) * K := Nat.le_mul_of_pos_left K (Nat.succ_pos m) + omega] at this + exact this + | cut y => + rw [hs] at hk + obtain ⟨iy, lt⟩ := hk + obtain ⟨j, _, le, runs⟩ := seg_cut_le hs + obtain ⟨r, ran, post⟩ := ih (rank y) (h ▸ lt) y rfl iy + refine ⟨r, ?_, post⟩ + have e1 := (runs ((rank y + 1) * K)).1 + rw [ran] at e1 + apply run_mono _ e1 + have : (rank y + 1) * K + K ≤ (m + 1) * K := by + rw [← Nat.succ_mul]; exact Nat.mul_le_mul_right K (by omega) + omega + +/-- The same from a first configuration that need not be a cut point, with every rank of the +invariant at most `B`: the run ends within `(B + 2) * K` steps. -/ +theorem ends_within_start {step : Step σ R} {cut : σ → Bool} {Inv : σ → Prop} {Post : R → Prop} + (rank : σ → Nat) (K B : Nat) (hB : ∀ y, Inv y → rank y ≤ B) {x₀ : σ} + (start : SegEnds Inv Post (fun _ => True) (seg step cut K x₀)) + (segment : ∀ x, Inv x → SegEnds Inv Post (fun y => rank y < rank x) (seg step cut K x)) : + ∃ r, run step ((B + 2) * K) x₀ = some r ∧ Post r := by + cases hs : seg step cut K x₀ with + | fuel | stuck => rw [hs] at start; exact start.elim + | done a => + rw [hs] at start + obtain ⟨j, _, le, runs⟩ := seg_done_le hs + refine ⟨a, ?_, start⟩ + have := runs ((B + 2) * K - j) + rw [show (B + 2) * K - j + j = (B + 2) * K by + have : K ≤ (B + 2) * K := Nat.le_mul_of_pos_left K (by omega) + omega] at this + exact this + | cut y => + rw [hs] at start + obtain ⟨j, _, le, runs⟩ := seg_cut_le hs + obtain ⟨r, ran, post⟩ := ends_within rank K segment y start.1 + refine ⟨r, ?_, post⟩ + have e1 := (runs ((rank y + 1) * K)).1 + rw [ran] at e1 + apply run_mono _ e1 + have : (rank y + 1) * K + K ≤ (B + 2) * K := by + rw [← Nat.succ_mul]; exact Nat.mul_le_mul_right K (by have := hB y start.1; omega) + omega + +/-! ## Bounds along simulations -/ + +section Sim + +universe u' v' + +variable {τ : Type u'} {R' : Type v'} + +/-- A segment that ends does not depend on fuel beyond what it took. -/ +theorem seg_fuel_mono {step : Step σ R} {cut : σ → Bool} : + ∀ {k k' : Nat} {x : σ}, k ≤ k' → seg step cut k x ≠ .fuel → seg step cut k' x = seg step cut k x + | 0, _, _, _, h => absurd rfl h + | k + 1, 0, _, le, _ => absurd le (by omega) + | k + 1, k' + 1, x, le, h => by + simp only [seg] at h ⊢ + cases e : step x with + | none => rfl + | some v => + cases v with + | inl r => rfl + | inr y => + simp only [e] at h + by_cases c : cut y = true + · simp only [c, ↓reduceIte] + · simp only [c, Bool.false_eq_true, ↓reduceIte] at h ⊢ + exact seg_fuel_mono (by omega) h + +theorem seg_eq_of_ne_fuel {step : Step σ R} {cut : σ → Bool} {k k' : Nat} {x : σ} + (h : seg step cut k x ≠ .fuel) (h' : seg step cut k' x ≠ .fuel) : + seg step cut k x = seg step cut k' x := by + rcases Nat.le_total k k' with le | le + · exact (seg_fuel_mono le h).symm + · exact seg_fuel_mono le h' + +/-- **A simulation whose target segments take at most `K'` steps**: from related +configurations, the source's segment (at some fuel) and the target's segment within `K'` steps +end alike. The certify driver's stage proofs give each target segment a literal fuel. -/ +def BoundedSim (step : Step σ R) (cut : σ → Bool) (step' : Step τ R') (cut' : τ → Bool) + (Ag : R → R' → Prop) (Rel : σ → τ → Prop) (K' : Nat) : Prop := + ∀ x x', Rel x x' → ∃ k, SegRel Ag Rel (seg step cut k x) (seg step' cut' K' x') + +/-- **A step bound on the target from a ranking certificate on the source**: segments match one +for one, so a run of the target from a configuration related to a cut point of rank `r` ends +within `(r + 1) * K'` steps, in a result that agrees with one meeting `Post`. -/ +theorem ends_within_sim {step : Step σ R} {cut : σ → Bool} {step' : Step τ R'} {cut' : τ → Bool} + {Ag : R → R' → Prop} {Rel : σ → τ → Prop} {Inv : σ → Prop} {Post : R → Prop} + (rank : σ → Nat) (K K' : Nat) + (segment : ∀ x, Inv x → SegEnds Inv Post (fun y => rank y < rank x) (seg step cut K x)) + (sim : BoundedSim step cut step' cut' Ag Rel K') : + ∀ x x', Inv x → Rel x x' → + ∃ r', run step' ((rank x + 1) * K') x' = some r' ∧ ∃ r, Ag r r' ∧ Post r := by + intro x + induction h : rank x using Nat.strongRecOn generalizing x with + | ind m ih => + intro x' inv rel + have hk := segment x inv + obtain ⟨k, hs⟩ := sim x x' rel + have hne : seg step cut K x ≠ .fuel := fun e => by rw [e] at hk; exact hk + have hne' : seg step cut k x ≠ .fuel := fun e => by rw [e] at hs; exact hs + rw [seg_eq_of_ne_fuel hne' hne] at hs + have hK : K' ≤ (m + 1) * K' := Nat.le_mul_of_pos_left K' (Nat.succ_pos m) + cases ha : seg step cut K x with + | fuel | stuck => rw [ha] at hk; exact hk.elim + | done a => + rw [ha] at hk hs + cases hb : seg step' cut' K' x' with + | done b => + rw [hb] at hs + obtain ⟨j, _, le, runs⟩ := seg_done_le hb + refine ⟨b, ?_, a, hs, hk⟩ + have := runs ((m + 1) * K' - j) + rwa [show (m + 1) * K' - j + j = (m + 1) * K' by omega] at this + | cut _ | stuck | fuel => rw [hb] at hs; exact hs.elim + | cut y => + rw [ha] at hk hs + obtain ⟨iy, lt⟩ := hk + cases hb : seg step' cut' K' x' with + | cut y' => + rw [hb] at hs + obtain ⟨j, _, le, runs⟩ := seg_cut_le hb + obtain ⟨r', ran, r, ag, post⟩ := ih (rank y) (h ▸ lt) y rfl y' iy hs + refine ⟨r', ?_, r, ag, post⟩ + have e1 := (runs ((rank y + 1) * K')).1 + rw [ran] at e1 + apply run_mono _ e1 + have : (rank y + 1) * K' + K' ≤ (m + 1) * K' := by + rw [← Nat.succ_mul]; exact Nat.mul_le_mul_right K' (by omega) + omega + | done _ | stuck | fuel => rw [hb] at hs; exact hs.elim + +/-- The same from related first configurations that need not be cut points, with every rank of +the invariant at most `B`: the target ends within `(B + 2) * K'` steps. -/ +theorem ends_within_sim_start {step : Step σ R} {cut : σ → Bool} {step' : Step τ R'} + {cut' : τ → Bool} {Ag : R → R' → Prop} {Rel : σ → τ → Prop} {Inv : σ → Prop} + {Post : R → Prop} (rank : σ → Nat) (K K' B : Nat) (hB : ∀ y, Inv y → rank y ≤ B) + {x₀ : σ} {x₀' : τ} (rel : Rel x₀ x₀') + (start : SegEnds Inv Post (fun _ => True) (seg step cut K x₀)) + (segment : ∀ x, Inv x → SegEnds Inv Post (fun y => rank y < rank x) (seg step cut K x)) + (sim : BoundedSim step cut step' cut' Ag Rel K') : + ∃ r', run step' ((B + 2) * K') x₀' = some r' ∧ ∃ r, Ag r r' ∧ Post r := by + obtain ⟨k, hs⟩ := sim x₀ x₀' rel + have hne : seg step cut K x₀ ≠ .fuel := fun e => by rw [e] at start; exact start + have hne' : seg step cut k x₀ ≠ .fuel := fun e => by rw [e] at hs; exact hs + rw [seg_eq_of_ne_fuel hne' hne] at hs + have hK : K' ≤ (B + 2) * K' := Nat.le_mul_of_pos_left K' (by omega) + cases ha : seg step cut K x₀ with + | fuel | stuck => rw [ha] at start; exact start.elim + | done a => + rw [ha] at start hs + cases hb : seg step' cut' K' x₀' with + | done b => + rw [hb] at hs + obtain ⟨j, _, le, runs⟩ := seg_done_le hb + refine ⟨b, ?_, a, hs, start⟩ + have := runs ((B + 2) * K' - j) + rwa [show (B + 2) * K' - j + j = (B + 2) * K' by omega] at this + | cut _ | stuck | fuel => rw [hb] at hs; exact hs.elim + | cut y => + rw [ha] at start hs + cases hb : seg step' cut' K' x₀' with + | cut y' => + rw [hb] at hs + obtain ⟨j, _, le, runs⟩ := seg_cut_le hb + obtain ⟨r', ran, r, ag, post⟩ := ends_within_sim rank K K' segment sim y y' start.1 hs + refine ⟨r', ?_, r, ag, post⟩ + have e1 := (runs ((rank y + 1) * K')).1 + rw [ran] at e1 + apply run_mono _ e1 + have : (rank y + 1) * K' + K' ≤ (B + 2) * K' := by + rw [← Nat.succ_mul]; exact Nat.mul_le_mul_right K' (by have := hB y start.1; omega) + omega + | done _ | stuck | fuel => rw [hb] at hs; exact hs.elim + +/-- A bounded simulation from one obligation per pair of cut points, each target segment with its +own literal fuel at most `K'` (as the certify driver's `refine ⟨k, k', ?_⟩` gives): fuel beyond a +segment's end changes nothing (`seg_fuel_mono`). -/ +theorem BoundedSim.of_each {step : Step σ R} {cut : σ → Bool} {step' : Step τ R'} + {cut' : τ → Bool} {Ag : R → R' → Prop} {rels : List (σ → τ → Prop)} {K' : Nat} + (each : ∀ P ∈ rels, ∀ x x', P x x' → ∃ k k', k' ≤ K' ∧ + SegRel Ag (fun y y' => ∃ Q ∈ rels, Q y y') (seg step cut k x) (seg step' cut' k' x')) : + BoundedSim step cut step' cut' Ag (fun x x' => ∃ P ∈ rels, P x x') K' := by + rintro x x' ⟨P, mem, holds⟩ + obtain ⟨k, k', le, h⟩ := each P mem x x' holds + have ne : seg step' cut' k' x' ≠ .fuel := fun e => by + rw [e] at h + cases ha : seg step cut k x <;> rw [ha] at h <;> exact h + exact ⟨k, by rw [seg_fuel_mono le ne]; exact h⟩ + +/-- Bounded simulations compose, segment for segment, with the last stage's bound. -/ +theorem BoundedSim.trans {υ : Type u} {R'' : Type v} {step : Step σ R} {cut : σ → Bool} + {step' : Step τ R'} {cut' : τ → Bool} {step'' : Step υ R''} {cut'' : υ → Bool} + {Ag : R → R' → Prop} {Ag' : R' → R'' → Prop} {Rel : σ → τ → Prop} {Rel' : τ → υ → Prop} + {K' K'' : Nat} + (h : BoundedSim step cut step' cut' Ag Rel K') (h' : BoundedSim step' cut' step'' cut'' Ag' Rel' K'') : + BoundedSim step cut step'' cut'' (fun a c => ∃ b, Ag a b ∧ Ag' b c) + (fun x z => ∃ y, Rel x y ∧ Rel' y z) K'' := by + rintro x z ⟨y, r1, r2⟩ + obtain ⟨k, s1⟩ := h x y r1 + obtain ⟨k', s2⟩ := h' y z r2 + have n1 : seg step' cut' K' y ≠ .fuel := fun e => by + rw [e] at s1 + cases ha : seg step cut k x <;> rw [ha] at s1 <;> exact s1 + have n2 : seg step' cut' k' y ≠ .fuel := fun e => by rw [e] at s2; exact s2 + rw [seg_eq_of_ne_fuel n2 n1] at s2 + refine ⟨k, ?_⟩ + cases ha : seg step cut k x <;> cases hb : seg step' cut' K' y <;> + cases hc : seg step'' cut'' K'' z <;> + simp only [ha, hb, hc, SegRel] at s1 s2 ⊢ + all_goals first + | exact ⟨_, s1, s2⟩ + | trivial + | exact s1.elim + | exact s2.elim + +/-- info: 'SolarTV.CutPoint.ends_within_sim_start' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms ends_within_sim_start + +end Sim + +/-! ## Resources -/ + +/-- How a metered run ends: in a result with the gas left, out of gas, or stuck. -/ +inductive Metered (R : Type v) where + | done (r : R) (left : Nat) + | oog + | stuck + deriving DecidableEq + +/-- A metered run: each step from `x` is charged `cost x` before it is taken, and the run fails +with `oog` when less gas is left, as the EVM charges an instruction before running it. The fuel +`n` only bounds the recursion; `none` when it runs out. -/ +def runGas (step : Step σ R) (cost : σ → Nat) : Nat → Nat → σ → Option (Metered R) + | 0, _, _ => none + | n + 1, g, x => + if g < cost x then some .oog else + match step x with + | some (.inl r) => some (.done r (g - cost x)) + | some (.inr y) => runGas step cost n (g - cost x) y + | none => some .stuck + +/-- What a segment costs: the charge of each step it takes. -/ +def segCost (step : Step σ R) (cut : σ → Bool) (cost : σ → Nat) : Nat → σ → Nat + | 0, _ => 0 + | k + 1, x => + cost x + match step x with + | some (.inr y) => if cut y then 0 else segCost step cut cost k y + | _ => 0 + +section Metered + +variable {step : Step σ R} {cut : σ → Bool} {cost : σ → Nat} + +/-- **The resource bound is separate from the behaviour**: a metered run that ends gives the +result the unmetered run gives with the same fuel. -/ +theorem runGas_done_run : ∀ {n g : Nat} {x : σ} {r : R} {left : Nat}, + runGas step cost n g x = some (.done r left) → run step n x = some r + | 0, _, _, _, _, h => by cases h + | n + 1, g, x, r, left, h => by + simp only [runGas] at h + split at h + · cases h + · simp only [run] + cases e : step x with + | none => rw [e] at h; cases h + | some v => + cases v with + | inl r' => rw [e] at h; cases h; rfl + | inr y => rw [e] at h; exact runGas_done_run h + +theorem segCost_cut : ∀ {k : Nat} {x y : σ} {g : Nat}, seg step cut k x = .cut y → + segCost step cut cost k x ≤ g → + ∃ j, j ≤ k ∧ ∀ n, runGas step cost (n + j) g x = runGas step cost n (g - segCost step cut cost k x) y + | 0, _, _, _, h, _ => by cases h + | k + 1, x, y, g, h, hg => by + simp only [seg] at h + simp only [segCost] at hg ⊢ + cases e : step x with + | none => rw [e] at h; cases h + | some v => + cases v with + | inl r => rw [e] at h; cases h + | inr z => + simp only [e] at h hg ⊢ + by_cases c : cut z = true + · simp only [c, ↓reduceIte] at h hg ⊢ + cases h + refine ⟨1, by omega, fun n => ?_⟩ + simp only [runGas, show ¬ g < cost x by omega, ↓reduceIte, e, Nat.add_zero] + · simp only [c, Bool.false_eq_true, ↓reduceIte] at h hg ⊢ + obtain ⟨j, le, runs⟩ := segCost_cut (g := g - cost x) h (by omega) + refine ⟨j + 1, by omega, fun n => ?_⟩ + rw [← Nat.add_assoc] + simp only [runGas, show ¬ g < cost x by omega, ↓reduceIte, e] + rw [runs n, Nat.sub_sub] + +theorem segCost_done : ∀ {k : Nat} {x : σ} {r : R} {g : Nat}, seg step cut k x = .done r → + segCost step cut cost k x ≤ g → + ∃ j, j ≤ k ∧ ∀ n, runGas step cost (n + j) g x = some (.done r (g - segCost step cut cost k x)) + | 0, _, _, _, h, _ => by cases h + | k + 1, x, r, g, h, hg => by + simp only [seg] at h + simp only [segCost] at hg ⊢ + cases e : step x with + | none => rw [e] at h; cases h + | some v => + cases v with + | inl r' => + simp only [e] at h hg ⊢ + cases h + refine ⟨1, by omega, fun n => ?_⟩ + simp only [runGas, show ¬ g < cost x by omega, ↓reduceIte, e, Nat.add_zero] + | inr z => + simp only [e] at h hg ⊢ + by_cases c : cut z = true + · simp only [c, ↓reduceIte] at h; cases h + · simp only [c, Bool.false_eq_true, ↓reduceIte] at h hg ⊢ + obtain ⟨j, le, runs⟩ := segCost_done (g := g - cost x) h (by omega) + refine ⟨j + 1, by omega, fun n => ?_⟩ + rw [← Nat.add_assoc] + simp only [runGas, show ¬ g < cost x by omega, ↓reduceIte, e] + rw [runs n, Nat.sub_sub] + +/-- **Enough gas from the ranking**: when every segment of the certificate costs at most `C`, +a metered run from a cut point of rank `r` with at least `(r + 1) * C` gas never runs out of gas: +it ends, in a result meeting `Post`. -/ +theorem gas_ends (rank : σ → Nat) (K C : Nat) {Inv : σ → Prop} {Post : R → Prop} + (segment : ∀ x, Inv x → SegEnds Inv Post (fun y => rank y < rank x) (seg step cut K x) ∧ + segCost step cut cost K x ≤ C) : + ∀ x, Inv x → ∀ g, (rank x + 1) * C ≤ g → + ∃ n r left, runGas step cost n g x = some (.done r left) ∧ Post r := by + intro x + induction h : rank x using Nat.strongRecOn generalizing x with + | ind m ih => + intro inv g hg + obtain ⟨hk, hc⟩ := segment x inv + have hCg : C ≤ g := Nat.le_trans (Nat.le_mul_of_pos_left C (Nat.succ_pos m)) hg + cases hs : seg step cut K x with + | fuel | stuck => rw [hs] at hk; exact hk.elim + | done a => + rw [hs] at hk + obtain ⟨j, _, runs⟩ := segCost_done (cost := cost) (g := g) hs (by omega) + exact ⟨0 + j, a, _, runs 0, hk⟩ + | cut y => + rw [hs] at hk + obtain ⟨iy, lt⟩ := hk + obtain ⟨j, _, runs⟩ := segCost_cut (cost := cost) (g := g) hs (by omega) + have hg' : (rank y + 1) * C ≤ g - segCost step cut cost K x := by + have : (rank y + 1) * C + C ≤ (m + 1) * C := by + rw [← Nat.succ_mul]; exact Nat.mul_le_mul_right C (by omega) + omega + obtain ⟨n, r, left, ran, post⟩ := ih (rank y) (h ▸ lt) y rfl iy _ hg' + exact ⟨n + j, r, left, by rw [runs n]; exact ran, post⟩ + +/-- Each step charged one unit: the segment's cost is at most its fuel. -/ +theorem segCost_one_le : ∀ (k : Nat) (x : σ), segCost step cut (fun _ => 1) k x ≤ k + | 0, _ => Nat.le_refl 0 + | k + 1, x => by + simp only [segCost] + split + · split + · omega + · have := segCost_one_le k ‹_›; omega + · omega + +end Metered + +/-! ## Controls -/ + +namespace Negative + +/-- A loop on `i` up to `5`, every configuration a cut point. `good` adds one per iteration; +`flat` forgets to. -/ +def good : Step Nat Nat := fun i => if i < 5 then some (.inr (i + 1)) else some (.inl i) +def flat : Step Nat Nat := fun i => if i < 5 then some (.inr i) else some (.inl i) +def everywhere : Nat → Bool := fun _ => true +def rank : Nat → Nat := fun i => 5 - i + +/-- The certificate `(i ≤ 5, 5 - i)` checks for the good loop, by evaluation. -/ +theorem good_accepted : ∀ i, i ≤ 5 → + SegEnds (fun i => i ≤ 5) (fun r => r = 5) (fun y => rank y < rank i) (seg good everywhere 1 i) := by + intro i hi + by_cases h : i < 5 + · simp only [seg, good, everywhere, rank, SegEnds, h, ↓reduceIte]; omega + · simp only [seg, good, SegEnds, h, ↓reduceIte]; omega + +theorem good_ends : ∃ r, run good ((5 + 2) * 1) 0 = some r ∧ r = 5 := + ends_within_start rank 1 5 (fun _ h => by simp only [rank]; omega) + (by decide) good_accepted + +/-- **A ranking certificate that does not fall is rejected**: for the loop that forgets its +increment, the same certificate's obligation at `i = 3` is false, and `decide` evaluates it to +`False` (a mismatch, at once). -/ +theorem flat_rejected : + ¬ SegEnds (fun i => i ≤ 5) (fun r => r = 5) (fun y => rank y < rank 3) (seg flat everywhere 1 3) := by + decide + +/-- No fuel helps: at every fuel, the flat loop's segment from `3` is not one the certificate +accepts, so no certificate with this rank checks. -/ +theorem flat_rejected_all (k : Nat) : + ¬ SegEnds (fun i => i ≤ 5) (fun r => r = 5) (fun y => rank y < rank 3) (seg flat everywhere k 3) := by + cases k with + | zero => simp [seg, SegEnds] + | succ k => simp [seg, flat, everywhere, SegEnds, rank] + +/-- **The gas bound is not vacuous**: the good loop costs `6` steps from `0`; with `5` gas it +runs out of gas, with `6` it ends. -/ +theorem oog_below : runGas good (fun _ => 1) 10 5 0 = some .oog := by decide +theorem ends_at_bound : ∃ left, runGas good (fun _ => 1) 10 6 0 = some (.done 5 left) := ⟨0, by decide⟩ + +end Negative + +/-- info: 'SolarTV.CutPoint.gas_ends' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms gas_ends + +/-- info: 'SolarTV.CutPoint.ends_within_start' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms ends_within_start + +end SolarTV.CutPoint diff --git a/tv/SolarTV/Word.lean b/tv/SolarTV/Word.lean new file mode 100644 index 00000000..e8945339 --- /dev/null +++ b/tv/SolarTV/Word.lean @@ -0,0 +1,56 @@ +import EvmRules.Word + +/-! Width-polymorphic scalar semantics shared by typed MIR and scheduled EVM IR. +Division by zero follows the EVM, shifts saturate instead of reducing modulo the +width, and exponentiation uses squaring so a word-sized exponent needs logarithmic +work. This file has no environment, heap or gas assumptions. -/ + +namespace SolarTV.Word + +def power {width : Nat} (base : BitVec width) (exponent : Nat) : BitVec width := + if _h : exponent = 0 then 1 + else + let half := power (base * base) (exponent / 2) + if exponent % 2 = 0 then half else base * half +termination_by exponent +decreasing_by exact Nat.div_lt_self (Nat.pos_of_ne_zero _h) (by decide) + +@[simp] theorem power_zero (base : BitVec width) : power base 0 = 1 := by simp [power] +@[simp] theorem power_one (base : BitVec width) : power base 1 = base := by simp [power] + +inductive Binary where + | add | sub | mul | div | sdiv | mod | smod | exp | and | or | xor + +def binary {width : Nat} : Binary → BitVec width → BitVec width → BitVec width + | .add => fun a b => a + b + | .sub => fun a b => a - b + | .mul => fun a b => a * b + | .div => fun a b => a / b + | .sdiv => fun a b => a.sdiv b + | .mod => fun a b => if b = 0 then 0 else a % b + | .smod => fun a b => if b = 0 then 0 else a.srem b + | .exp => fun a b => power a b.toNat + | .and => fun a b => a &&& b + | .or => fun a b => a ||| b + | .xor => fun a b => a ^^^ b + +inductive Unary where + | not | clz + +def unary {width : Nat} : Unary → BitVec width → BitVec width + | .not => fun a => ~~~a + | .clz => fun a => a.clz + +inductive Shift where + | shl | shr | sar + +/-- Arguments use MIR textual order: value, then shift. -/ +def shift {width : Nat} (op : Shift) (value amount : BitVec width) : BitVec width := + if amount.toNat ≥ width then + match op with | .shl | .shr => 0 | .sar => if value.msb then -1 else 0 + else match op with + | .shl => value <<< amount.toNat + | .shr => value >>> amount.toNat + | .sar => value.sshiftRight amount.toNat + +end SolarTV.Word diff --git a/tv/SolarTV/WordSafety.lean b/tv/SolarTV/WordSafety.lean new file mode 100644 index 00000000..139e6aef --- /dev/null +++ b/tv/SolarTV/WordSafety.lean @@ -0,0 +1,37 @@ +import SolarTV.Word + +/-! Correspondence of logarithmic exponentiation with the ordinary bit-vector +power. This establishes all exponents, including the full 256-bit range, without +unfolding an exponent-sized number of multiplication steps in the checker. -/ + +namespace SolarTV.Word + +private theorem square_power (base : BitVec width) (n : Nat) : + (base * base) ^ n = base ^ (n + n) := by + induction n with + | zero => simp + | succ n ih => + rw [BitVec.pow_succ, ih] + have h : n + 1 + (n + 1) = (n + n + 1) + 1 := by omega + rw [h, BitVec.pow_succ, BitVec.pow_succ] + simp [BitVec.mul_assoc] + +theorem power_eq_pow (base : BitVec width) (n : Nat) : power base n = base ^ n := by + induction n using Nat.strongRecOn generalizing base with + | ind n ih => + rw [power] + split + · rename_i h + simp [h] + · rename_i h + rw [ih (n / 2) (Nat.div_lt_self (Nat.pos_of_ne_zero h) (by decide)), square_power] + split + · rename_i even + change base ^ (n / 2 + n / 2) = base ^ n + exact congrArg (fun exponent => base ^ exponent) (by omega) + · rename_i odd + change base * base ^ (n / 2 + n / 2) = base ^ n + rw [BitVec.mul_comm, ← BitVec.pow_succ] + exact congrArg (fun exponent => base ^ exponent) (by omega) + +end SolarTV.Word diff --git a/tv/W1Proofs.lean b/tv/W1Proofs.lean new file mode 100644 index 00000000..09adfcec --- /dev/null +++ b/tv/W1Proofs.lean @@ -0,0 +1,3 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Stages +import W1Proofs.Assembly diff --git a/tv/W1Proofs/Assembly.lean b/tv/W1Proofs/Assembly.lean new file mode 100644 index 00000000..d5158a87 --- /dev/null +++ b/tv/W1Proofs/Assembly.lean @@ -0,0 +1,42 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Items +import gen.Main.Evm4 +import gen.Main.Bytecode + +/-! The final EVM IR of `Main` against its bytecode, by the assembly checker's walk: the bytecode decodes, linearly from offset 0, to exactly the program's instructions, each jumped-to block at its `JUMPDEST`. -/ + +namespace SolarTV.Milestone.W1 + +open SolarTV.Assembly SolarTV.Export.Main SolarTV.Milestone.W1 + +set_option maxRecDepth 100000 + +/-- The items of the final EVM IR. -/ +def items : List Item := (itemsOf evm4).getD [] + +theorem items_eq : itemsOf evm4 = some items := by decide + +/-- The layout: each jumped-to block at the bytecode's next `JUMPDEST`. The walk checks it. -/ +def offset (label : Nat) : Nat := if label = 1 then 0x2e else if label = 2 then 0x32 else 0 + +/-- The instructions the walk reaches, each at its offset. -/ +def stream : List (Nat × Instr) := (walk bytecode offset 0 items).getD [] + +/-- The checker's walk accepts the exported bytecode against the final EVM IR. -/ +theorem walk_eq : walk bytecode offset 0 items = some stream := by decide +kernel + +theorem checked : Walk bytecode offset 0 items stream := walk_sound walk_eq + +/-- The bytecode's linear decoding is the final EVM IR's instructions at the layout. -/ +theorem decodes : decodeFrom bytecode (bytecode.length + 1) 0 = stream := + walk_decodes checked _ (by have := walk_length checked; omega) + +/-- info: 'SolarTV.Milestone.W1.walk_eq' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms walk_eq + +/-- info: 'SolarTV.Milestone.W1.decodes' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms decodes + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Axioms.lean b/tv/W1Proofs/Axioms.lean new file mode 100644 index 00000000..a056c3aa --- /dev/null +++ b/tv/W1Proofs/Axioms.lean @@ -0,0 +1,25 @@ +import Lean + +/-! A fail-closed axiom check for generated proofs. + +`#axioms_within thm` fails unless every axiom `thm` depends on is `propext`, +`Classical.choice` or `Quot.sound`, and otherwise reports that it is within them, so that +`#guard_msgs` can pin the check where a generated proof's exact axiom set is not known in +advance (some runs need `Classical.choice`, some do not). `sorryAx`, `Lean.ofReduceBool` +(`native_decide`) and any declared axiom fail it. -/ + +namespace SolarTV.Milestone.W1 + +open Lean Elab Command in +/-- Fail unless the constant's axioms are among `propext`, `Classical.choice` and +`Quot.sound`. -/ +elab "#axioms_within " id:ident : command => do + let name ← liftCoreM <| realizeGlobalConstNoOverloadWithInfo id + let axioms ← liftCoreM <| collectAxioms name + let allowed := [``propext, ``Classical.choice, ``Quot.sound] + let bad := axioms.toList.filter (!allowed.contains ·) + unless bad.isEmpty do + throwError "'{name}' depends on axioms outside [propext, Classical.choice, Quot.sound]: {bad}" + logInfo m!"'{name}' depends on axioms within [propext, Classical.choice, Quot.sound]" + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Items.lean b/tv/W1Proofs/Items.lean new file mode 100644 index 00000000..082654a4 --- /dev/null +++ b/tv/W1Proofs/Items.lean @@ -0,0 +1,348 @@ +import SolarTV.Stages.AssemblyCheck +import SolarTV.EVMIR.Program + +/-! EVM IR programs as the assembly items the assembler solves. + +`itemsOf` spells an EVM IR program as the assembly the assembler solves: each instruction as +its opcode, a push as a push of its constant, a static jump as a push of its target's label +and the jump, a pushed label as its push, a dynamic jump as `JUMP`, and a `JUMPDEST` label +at the start of each block some pushed label targets. A +block's transfer to the block after it is spelled as `lower_terminator` in +`crates/codegen/src/backend/assembler/assembly/lower.rs` spells it: a final `jump` to the next +block is no instruction, and of a final `jumpi then; jump else` that falls through, only the +`JUMPI` to the other block stays, after an `ISZERO` when `then` is the one that follows. The +EVM IR semantics enters the next block past the end of a block, so the spelling runs the same +blocks. The last block's final `stop` is no instruction either, as `lower_terminator` leaves +it out of runtime code that nothing follows: the code ends there, which halts as STOP does. An +environment read the oracle answers (`.env`) is spelled as the opcode of the mnemonic the +exporter names it with, as solar lowers it. It is partial: an effect outside the EVM's +opcodes or with another arity than its opcode's has no item, so a program outside that scope +fails the check. Every contract's `Assembly` module (w1's and the ones +`milestone/certify.py` writes) evaluates `SolarTV.Assembly.walk` over its bytecode against +these items. + +A jump table (`jumpTable`) is spelled as `indexed_jump.rs` lowers it, in the encoding the +bytecode shows (`Spelling`), which `itemsWith` takes for each table in layout order: packed, +a word of one-byte offsets, the first target's in its high byte, that `BYTE` picks the entry the +index numbers from, after adding the zero bytes above it (`PUSH 32-n; ADD; PUSHn table; SWAP1; +BYTE; JUMP`); or a stride table, `PUSH stride; MUL; PUSH entry0; ADD; JUMP` into entry stubs +`JUMPDEST; PUSH target; JUMP` laid out after the last block, `stride` bytes apart, each named by +a label past every block's. The walk checks that each packed offset fits its byte and that each +stub sits its index of strides past the first, so that the pick lands on the entry's target. With +stubs after it, the last block's final `stop` is a `STOP` again. The other encodings, relative +to a base or packed wider than a byte (`-Zpack-wide-jump-tables`, the size objective), have no +spelling, so the check refuses them, as it does a table with no spelling given. EVM IR requires a +table's index to be in range, as every lowering of a switch checks before the jump; out of range +the EVM IR semantics halts, while the bytecode jumps wherever the pick lands. -/ + +namespace SolarTV.Milestone.W1 + +open SolarTV.Assembly + +/-- The opcode of a stack operation, or `none` for one no opcode reaches: `dup` and `swap` of the +first sixteen words are DUP1 to DUP16 and SWAP1 to SWAP16, deeper ones DUPN and SWAPN with the +depth's immediate up to depth 235, and `exchange` EXCHANGE with its pair's immediate, as solar's +assembler encodes them where the EVM version has EIP-8024's opcodes. Where it has not, the +assembler writes no such opcode and the walk finds none. -/ +def stackItem : EVM.Op → Option Item + | .add => some (.op 0x01) | .mul => some (.op 0x02) | .sub => some (.op 0x03) + | .div => some (.op 0x04) | .sdiv => some (.op 0x05) | .mod => some (.op 0x06) + | .smod => some (.op 0x07) | .addmod => some (.op 0x08) | .mulmod => some (.op 0x09) + | .exp => some (.op 0x0a) | .signextend => some (.op 0x0b) + | .lt => some (.op 0x10) | .gt => some (.op 0x11) | .slt => some (.op 0x12) + | .sgt => some (.op 0x13) | .eq => some (.op 0x14) | .iszero => some (.op 0x15) + | .and => some (.op 0x16) | .or => some (.op 0x17) | .xor => some (.op 0x18) + | .not => some (.op 0x19) | .byte => some (.op 0x1a) | .shl => some (.op 0x1b) + | .shr => some (.op 0x1c) | .sar => some (.op 0x1d) | .clz => some (.op 0x1e) + | .calldatasize => some (.op 0x36) | .returndatasize => some (.op 0x3d) + | .pop => some (.op 0x50) + | .push value => some (.push value.toNat) + | .dup index => + if index.val < 16 then some (.op (0x80 + index.val)) + else if depthOk (index.val + 1) then some (.opImm DUPN (encodeDepth (index.val + 1))) + else none + | .swap index => + if index.val < 16 then some (.op (0x90 + index.val)) + else if depthOk (index.val + 1) then some (.opImm SWAPN (encodeDepth (index.val + 1))) + else none + | .exchange first second => + if pairOk first.val second.val then some (.opImm EXCHANGE (encodePair first.val second.val)) + else none + +/-! The immediates `stackItem` writes decode back to the operation: DUPN and SWAPN to the +depth `index + 1`, EXCHANGE to its pair, each a valid immediate, so the walk's decoding of the +bytes (`decode`) reads the item and nothing else. -/ + +theorem stackItem_dup_opImm {index : Fin 256} {byte imm : Nat} + (h : stackItem (.dup index) = some (.opImm byte imm)) : + byte = DUPN ∧ decodeDepth imm = some (index.val + 1) ∧ immediateOk byte imm = true := by + simp only [stackItem] at h + split at h + · cases h + · split at h + · rename_i hd + cases h + have := decodeDepth_encodeDepth hd + exact ⟨rfl, this, by simp [immediateOk, DUPN, EXCHANGE, this]⟩ + · cases h + +theorem stackItem_swap_opImm {index : Fin 256} {byte imm : Nat} + (h : stackItem (.swap index) = some (.opImm byte imm)) : + byte = SWAPN ∧ decodeDepth imm = some (index.val + 1) ∧ immediateOk byte imm = true := by + simp only [stackItem] at h + split at h + · cases h + · split at h + · rename_i hd + cases h + have := decodeDepth_encodeDepth hd + exact ⟨rfl, this, by simp [immediateOk, SWAPN, EXCHANGE, this]⟩ + · cases h + +theorem stackItem_exchange_opImm {first second : Fin 32} {byte imm : Nat} + (h : stackItem (.exchange first second) = some (.opImm byte imm)) : + byte = EXCHANGE ∧ decodePair imm = some (first.val, second.val) ∧ + immediateOk byte imm = true := by + simp only [stackItem] at h + split at h + · rename_i hp + cases h + have := (decodePair_encodePair hp).1 + exact ⟨rfl, this, by simp [immediateOk, this]⟩ + · cases h + +/-- The bytes of an item `stackItem` writes with an immediate decode to that item, two bytes on. -/ +theorem decode_opImm_of_valid {code : List Nat} {pc byte imm : Nat} + (hb : code[pc]? = some byte) (hi : code[pc + 1]? = some imm) (hh : hasImmediate byte = true) + (ok : immediateOk byte imm = true) : decode code pc = some (.opImm byte imm, pc + 2) := by + have h0 : byte ≠ PUSH0 := by + intro e; subst e; simp [hasImmediate, PUSH0, DUPN, SWAPN, EXCHANGE] at hh + have h1 : ¬(PUSH1 ≤ byte ∧ byte ≤ PUSH32) := by + simp only [hasImmediate, Bool.or_eq_true, beq_iff_eq, DUPN, SWAPN, EXCHANGE] at hh + simp only [PUSH1, PUSH32]; omega + simp [decode, hb, hi, h0, h1, hh, ok] + +/-- The opcode of a memory instruction, or `none` for a copy or hash, which the program runs +as effects. -/ +def memoryItem : EVM.Memory.Op → Option Item + | .stack op => stackItem op + | .load => some (.op 0x51) + | .store => some (.op 0x52) + | .storeByte => some (.op 0x53) + | .size => some (.op 0x59) + | .copy | .hash => none + +/-- The opcode of an effect with its arity, or `none` for one that is no opcode. -/ +def effectItem : Machine.Effect → Nat → Option Item + | .address, 0 => some (.op 0x30) + | .caller, 0 => some (.op 0x33) + | .callvalue, 0 => some (.op 0x34) + | .calldataload, 1 => some (.op 0x35) + | .calldatasize, 0 => some (.op 0x36) + | .returndatasize, 0 => some (.op 0x3d) + | .mload, 1 => some (.op 0x51) + | .mstore, 2 => some (.op 0x52) + | .mstore8, 2 => some (.op 0x53) + | .sload, 1 => some (.op 0x54) + | .sstore, 2 => some (.op 0x55) + | .msize, 0 => some (.op 0x59) + | .tload, 1 => some (.op 0x5c) + | .tstore, 2 => some (.op 0x5d) + | .keccak256, 2 => some (.op 0x20) + | .calldatacopy, 3 => some (.op 0x37) + | .returndatacopy, 3 => some (.op 0x3e) + | .gas, 0 => some (.op 0x5a) + | .mcopy, 3 => some (.op 0x5e) + | .call .call, 7 => some (.op 0xf1) + | .call .callcode, 7 => some (.op 0xf2) + | .call .delegatecall, 6 => some (.op 0xf4) + | .call .staticcall, 6 => some (.op 0xfa) + -- NOTE: the runtime code's placeholder, a PUSH of zeros that the manifest lists, which + -- the deployment code links with the immutable (`SolarTV.Assembly.link`). + | .immutable id bytes .word, 0 => some (.immutable id bytes) + | .codecopy, 3 => some (.op 0x39) + | .create, 3 => some (.op 0xf0) + | .create2, 4 => some (.op 0xf5) + | .log n, arity => if n ≤ 4 ∧ arity = n + 2 then some (.op (0xa0 + n)) else none + -- The oracle's environment reads, by the mnemonic the exporter names each with. + | .env "balance", 1 => some (.op 0x31) + | .env "origin", 0 => some (.op 0x32) + | .env "codesize", 0 => some (.op 0x38) + | .env "gasprice", 0 => some (.op 0x3a) + | .env "extcodesize", 1 => some (.op 0x3b) + | .env "extcodehash", 1 => some (.op 0x3f) + | .env "blockhash", 1 => some (.op 0x40) + | .env "coinbase", 0 => some (.op 0x41) + | .env "timestamp", 0 => some (.op 0x42) + | .env "number", 0 => some (.op 0x43) + | .env "prevrandao", 0 => some (.op 0x44) + | .env "gaslimit", 0 => some (.op 0x45) + | .env "chainid", 0 => some (.op 0x46) + | .env "selfbalance", 0 => some (.op 0x47) + | .env "basefee", 0 => some (.op 0x48) + | .env "blobhash", 1 => some (.op 0x49) + | .env "blobbasefee", 0 => some (.op 0x4a) + | _, _ => none + +/-- The items of an instruction. -/ +def instrItems : EVM.Program.Instr → Option (List Item) + | .op op => (memoryItem op).map ([·]) + | .effect effect arity => (effectItem effect arity).map ([·]) + | .jump target => some [.pushLabel target, .op 0x56] + | .jumpi target => some [.pushLabel target, .op 0x57] + | .pushLabel target => some [.pushLabel target] + | .jumpDyn => some [.op 0x56] + | .jumpiDyn => some [.op 0x57] + -- NOTE: a jump table's items depend on its encoding, which `tableItems` spells. + | .jumpTable _ => none + | .stop => some [.op 0x00] + | .ret => some [.op 0xf3] + | .revert => some [.op 0xfd] + | .invalid => some [.op 0xfe] + +/-- How the assembler encoded a jump table, as the bytecode shows: `packed`, one-byte offsets +in a word that `BYTE` picks from, or `stride`, entry stubs whose target pushes are `width` +bytes wide. -/ +inductive Spelling where + | packed + | stride (width : Nat) + deriving DecidableEq, Repr + +def Spelling.isStride : Spelling → Bool + | .stride _ => true + | .packed => false + +/-- The jump tables' spellings not yet used, the label of the next stride table's first entry, +and the entry stubs of the stride tables so far, in layout order. -/ +structure Tables where + spellings : List Spelling + fresh : Nat + stubs : List Item + +/-- The entry stubs of a stride table from entry `index`: `JUMPDEST; PUSH target; JUMP`. -/ +def entries (table stride : Nat) : Nat → List Nat → List Item + | _, [] => [] + | index, target :: rest => + [.entry table index stride, .pushLabel target, .op 0x56] ++ entries table stride (index + 1) rest + +/-- The items of a jump table in the next spelling, as `indexed_jump::lower` writes it. -/ +def tableItems (targets : List Nat) (t : Tables) : Option (List Item × Tables) := + match t.spellings with + | [] => none + | .packed :: rest => + if 2 ≤ targets.length ∧ targets.length ≤ 32 then + -- PUSH 32-n; ADD (when n < 32); PUSHn table; SWAP1; BYTE; JUMP + some ((if targets.length < 32 then [.push (32 - targets.length), .op 0x01] else []) + ++ [.pushTable targets, .op 0x90, .op 0x1a, .op 0x56], { t with spellings := rest }) + else none + | .stride width :: rest => + if 1 ≤ width ∧ width ≤ 32 ∧ targets ≠ [] then + -- PUSH stride; MUL; PUSH entry0; ADD; JUMP + some ([.push (width + 3), .op 0x02, .pushLabel t.fresh, .op 0x01, .op 0x56], + { spellings := rest, fresh := t.fresh + 1, + stubs := t.stubs ++ entries t.fresh (width + 3) 0 targets }) + else none + +/-- The items of an instruction, a jump table in the next spelling. -/ +def instrTableItems (t : Tables) : EVM.Program.Instr → Option (List Item × Tables) + | .jumpTable targets => tableItems targets t + | instr => (instrItems instr).map (·, t) + +/-- The items of a list of instructions. -/ +def instrsItems : List EVM.Program.Instr → Option (List Item) + | [] => some [] + | instr :: rest => do + let head ← instrItems instr + let tail ← instrsItems rest + pure (head ++ tail) + +/-- The items of a block, given the block that follows it in the layout (none for the last +block) and whether the code ends after it: a final transfer to `next` falls through instead of +jumping, and a final stop where the code ends is the end of the code. -/ +def blockItems (next : Option Nat) (ends : Bool) (t : Tables) : + List EVM.Program.Instr → Option (List Item × Tables) + | [] => some ([], t) + | [.stop] => + -- the last block's stop: the code ends + if ends then some ([], t) + -- STOP + else some ([.op 0x00], t) + | [.jump target] => + -- jump next + if next = some target then some ([], t) + -- push target; JUMP + else some ([.pushLabel target, .op 0x56], t) + | [.jumpi yes, .jump no] => + -- push yes; JUMPI + if next = some no then some ([.pushLabel yes, .op 0x57], t) + -- ISZERO; push no; JUMPI + else if next = some yes then some ([.op 0x15, .pushLabel no, .op 0x57], t) + -- push yes; JUMPI; push no; JUMP + else some ([.pushLabel yes, .op 0x57, .pushLabel no, .op 0x56], t) + | instr :: rest => do + let (head, t) ← instrTableItems t instr + let (tail, t) ← blockItems next ends t rest + pure (head ++ tail, t) + +/-- The blocks' items in layout order from block `index`, each with the block after it; the code +ends after the last block when `ends`. -/ +def bodiesOf (ends : Bool) : Nat → Tables → List (List EVM.Program.Instr) → + Option (List (List Item) × Tables) + | _, t, [] => some ([], t) + | index, t, block :: rest => do + let (body, t) ← + blockItems (if rest.isEmpty then none else some (index + 1)) (ends && rest.isEmpty) t block + let (tail, t) ← bodiesOf ends (index + 1) t rest + pure (body :: tail, t) + +/-- The labels some item pushes, a packed table's each. -/ +def pushedLabels (bodies : List (List Item)) : List Nat := + bodies.flatMap fun body => body.flatMap fun + | .pushLabel label => [label] + | .pushTable labels => labels + | _ => [] + +/-- Each body from block `index` on, opening with its label when some item pushes it. -/ +def labelBodies (pushed : List Nat) : Nat → List (List Item) → List Item + | _, [] => [] + | index, body :: rest => + (if index ∈ pushed then [.label index] else []) ++ body ++ labelBodies pushed (index + 1) rest + +/-- The program as assembly items in layout order, each block some item jumps to opening with +its label, its jump tables in `spellings`, one each in layout order, and the stride tables' +entry stubs after the last block. -/ +def itemsWith (spellings : List Spelling) (p : EVM.Program.Program) : Option (List Item) := do + let (bodies, t) ← + bodiesOf (!spellings.any Spelling.isStride) 0 ⟨spellings, p.blocks.length, []⟩ p.blocks + if t.spellings.isEmpty then + pure (labelBodies (pushedLabels (bodies ++ [t.stubs])) 0 bodies ++ t.stubs) + else none + +/-- The program as assembly items, without jump tables. -/ +def itemsOf (p : EVM.Program.Program) : Option (List Item) := itemsWith [] p + +/-! Refusals: a jump table without its encoding has no items, and a packed table whose offsets do +not fit their bytes is placed nowhere, so no walk accepts code for it (`SolarTV.Assembly.no_walk`). -/ + +theorem table_unspelled : itemsOf ⟨[[.jumpTable [1, 1]], [.stop]]⟩ = none := by decide + +/-- A packed table: the bytes above its two entries added to the index, then the BYTE pick. -/ +theorem table_spelled : + itemsWith [.packed] ⟨[[.jumpTable [1, 1]], [.stop]]⟩ = + some [.push 30, .op 0x01, .pushTable [1, 1], .op 0x90, .op 0x1a, .op 0x56, .label 1] := by + decide + +/-- A stride table: its entry stubs after the last block, whose final stop is a STOP again. -/ +theorem table_stride : + itemsWith [.stride 2] ⟨[[.jumpTable [1, 1]], [.stop]]⟩ = + some [.push 5, .op 0x02, .pushLabel 2, .op 0x01, .op 0x56, .label 1, .op 0x00, + .entry 2 0 5, .pushLabel 1, .op 0x56, .entry 2 1 5, .pushLabel 1, .op 0x56] := by + decide + +/-- A table of one entry is never packed. -/ +theorem table_too_few : itemsWith [.packed] ⟨[[.jumpTable [1]], [.stop]]⟩ = none := by decide + +/-- An offset of 256 does not fit its byte. -/ +theorem table_wide (pc : Nat) : (Item.pushTable [1]).placed [] (fun _ => 256) pc = false := rfl + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Runs/Evm1.lean b/tv/W1Proofs/Runs/Evm1.lean new file mode 100644 index 00000000..9b64ad6d --- /dev/null +++ b/tv/W1Proofs/Runs/Evm1.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import gen.Main.Evm1 +import gen.Main.Sched + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.W1 + +open Machine SolarTV.Export.Main + +set_option maxHeartbeats 2000000 in +theorem evm1_run (o : Oracle) (call : Call) : + EVM.Program.run o sched call 9 = EVM.Program.run o evm1 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W1.evm1_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms evm1_run + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Runs/Evm2.lean b/tv/W1Proofs/Runs/Evm2.lean new file mode 100644 index 00000000..d14ef954 --- /dev/null +++ b/tv/W1Proofs/Runs/Evm2.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import gen.Main.Evm2 +import gen.Main.Evm1 + +/-! `share-reverts`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.W1 + +open Machine SolarTV.Export.Main + +set_option maxHeartbeats 2000000 in +theorem evm2_run (o : Oracle) (call : Call) : + EVM.Program.run o evm1 call 5 = EVM.Program.run o evm2 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W1.evm2_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms evm2_run + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Runs/Evm3.lean b/tv/W1Proofs/Runs/Evm3.lean new file mode 100644 index 00000000..d29e1b9f --- /dev/null +++ b/tv/W1Proofs/Runs/Evm3.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import gen.Main.Evm3 +import gen.Main.Evm2 + +/-! `terminal-dedup`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.W1 + +open Machine SolarTV.Export.Main + +set_option maxHeartbeats 2000000 in +theorem evm3_run (o : Oracle) (call : Call) : + EVM.Program.run o evm2 call 5 = EVM.Program.run o evm3 call 5 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W1.evm3_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms evm3_run + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Runs/Evm4.lean b/tv/W1Proofs/Runs/Evm4.lean new file mode 100644 index 00000000..dd6107c5 --- /dev/null +++ b/tv/W1Proofs/Runs/Evm4.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import gen.Main.Evm4 +import gen.Main.Evm3 + +/-! `cfg-simplify-early`: its input and output end in the same result on every call. -/ + +namespace SolarTV.Milestone.W1 + +open Machine SolarTV.Export.Main + +set_option maxHeartbeats 2000000 in +theorem evm4_run (o : Oracle) (call : Call) : + EVM.Program.run o evm3 call 5 = EVM.Program.run o evm4 call 3 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W1.evm4_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms evm4_run + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Runs/Sched.lean b/tv/W1Proofs/Runs/Sched.lean new file mode 100644 index 00000000..329a2efd --- /dev/null +++ b/tv/W1Proofs/Runs/Sched.lean @@ -0,0 +1,22 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import gen.Main.Sched +import gen.Main.Stage0 + +/-! Stack scheduling: the last lowered MIR and the scheduled EVM IR end in the same result on every call. -/ + +namespace SolarTV.Milestone.W1 + +open Machine SolarTV.Export.Main + +set_option maxHeartbeats 2000000 in +theorem sched_run (o : Oracle) (call : Call) : + MIR.Lowered.Module.run o stage0 call 9 = EVM.Program.run o sched call 9 := by + sym_exec + +/-- info: 'SolarTV.Milestone.W1.sched_run' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms sched_run + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Runs/Stage0.lean b/tv/W1Proofs/Runs/Stage0.lean new file mode 100644 index 00000000..4addfd75 --- /dev/null +++ b/tv/W1Proofs/Runs/Stage0.lean @@ -0,0 +1,21 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Tactic +import W1Proofs.Axioms +import gen.Main.Stage0 + +/-! The first lowered MIR ends on every call within 9 blocks, the number of its blocks. -/ + +namespace SolarTV.Milestone.W1 + +open Machine SolarTV.Export.Main + +set_option maxHeartbeats 2000000 in +theorem stage0_ends (o : Oracle) (call : Call) : + (MIR.Lowered.Module.run o stage0 call 9).isSome = true := by + sym_exec + +/-- info: 'SolarTV.Milestone.W1.stage0_ends' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage0_ends + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Segment.lean b/tv/W1Proofs/Segment.lean new file mode 100644 index 00000000..5c1f1b6c --- /dev/null +++ b/tv/W1Proofs/Segment.lean @@ -0,0 +1,201 @@ +import W1Proofs.Tactic +import SolarTV.CutPoint + +/-! Symbolic execution of loop-free segments between cut points. + +`sym_exec` runs two programs from their first configurations to their ends. A program that +loops has no such end within a fuel its blocks bound, so its stages are proved through cut +points instead (`SolarTV.CutPoint`): from every pair of configurations the exporter relates, +the two segments (`seg`) end alike. `sym_seg` proves one such obligation for configurations +whose words and state are variables: it evaluates both segments with the same definitional +steps as `sym_exec`, splits on the branch conditions they leave, and closes each leaf: + +- two ends, by the agreement of equal results (`agree_of_eq`) and `sym_exec`'s leaf procedures; +- two stuck segments, trivially; +- two cut points, by the relation lemma (`mk`) of a related pair: its source configuration + unifies with the leaf's, which fixes the related words, and the target configuration must + then equal the leaf's, by evaluation and the same leaf procedures. + +A segment that runs out of fuel, or ends differently from the other, leaves `False` or a +goal the procedures cannot close: the proof fails by mismatch. Nothing here proves an +invariant: the relations are the exporter's, and Lean only checks that they are preserved. -/ + +namespace SolarTV.Milestone.W1 + +open SolarTV.CutPoint Machine + +theorem agree_of_eq {a b : Halt × State} (h : a = b) : Agree a b := h ▸ Agree.refl a + +/-- One step of a segment from a configuration the code has built. Matching only a pair keeps +`dsimp` from unfolding the steps after one it cannot compute yet, as `iterate_mk` does for runs. -/ +@[defeq] theorem seg_mk {α β R : Type} (step : α × β → Option (R ⊕ (α × β))) (cut : α × β → Bool) + (k : Nat) (a : α) (b : β) : + seg step cut (k + 1) (a, b) = + match step (a, b) with + | none => .stuck + | some (.inl r) => .done r + | some (.inr y) => if cut y then .cut y else seg step cut k y := by + rw [seg] + cases step (a, b) with + | none => rfl + | some v => cases v <;> rfl + +@[defeq] theorem seg_zero {σ R : Type} (step : σ → Option (R ⊕ σ)) (cut : σ → Bool) (x : σ) : + seg step cut 0 x = .fuel := by + rw [seg] + +/-- A related pair from one relation of a list. -/ +theorem rel_mem {α β : Type} {rels : List (α → β → Prop)} {Q : α → β → Prop} {y : α} {y' : β} + (mem : Q ∈ rels) (h : Q y y') : ∃ Q ∈ rels, Q y y' := ⟨Q, mem, h⟩ + +open Lean Meta Simp in +/-- A stack position, a numeral of `Fin n`, as the number it is: a segment starts from a stack of +variables, so a `dup` or `swap` reads it at that number. -/ +dsimproc_decl finValLit (Fin.val _) := fun e => do + let_expr Fin.val n a := e | return .continue + let some n ← Nat.fromExpr? n | return .continue + let_expr OfNat.ofNat _ lit _ := a | return .continue + let some k := lit.rawNatLit? | return .continue + if n == 0 then return .continue + return .done (toExpr (k % n)) + +open Lean Meta Simp in +/-- `||` of a literal on the left, as a cut test of a known block leaves it: definitional, since +`||` matches on its left argument. A literal on the right is `seg_cut_test`'s (`Bool.or_true`, +`Bool.or_false`), by rewriting: `b || true` does not evaluate to `true` while `b` is unknown, and a +`dsimp` step claiming it leaves a term the kernel refuses. -/ +dsimproc_decl boolLit (_ || _) := fun e => do + let_expr or a b := e | return .continue + match a.constName?, b.constName? with + | some ``true, _ => return .done (mkConst ``true) + | some ``false, _ => return .done b + | _, _ => return .continue + +open Lean Meta Simp in +/-- `&&` of a literal on the left (definitional, as `boolLit`). -/ +dsimproc_decl boolAndLit (_ && _) := fun e => do + let_expr and a b := e | return .continue + match a.constName?, b.constName? with + | some ``false, _ => return .done (mkConst ``false) + | some ``true, _ => return .done b + | _, _ => return .continue + +open Lean Meta Simp in +/-- A conditional on two numerals being equal, as a MIR value lookup leaves it (`Env.set` +compares value numbers): the branch the numerals pick. Definitional, since equality of numerals +decides by evaluation, so `dsimp` keeps the decision instance and the term type-correct. -/ +dsimproc_decl iteNatLit (ite _ _ _) := fun e => do + let_expr ite _ c _ a b := e | return .continue + let_expr Eq ty x y := c | return .continue + unless ty.isConstOf ``Nat do return .continue + let some m ← Nat.fromExpr? x | return .continue + let some n ← Nat.fromExpr? y | return .continue + return .done (if m == n then a else b) + +/-- Unfold a segment's step and its cut test. -/ +syntax "seg_eval" "[" Lean.Parser.Tactic.simpLemma,* "]" : tactic +macro_rules + | `(tactic| seg_eval [$ids,*]) => `(tactic| + dsimp only [seg_mk, seg_zero, SegRel, $ids,*, finValLit, boolLit, boolAndLit, iteNatLit, Nat.reduceBEq, ↓reduceIte, Bool.false_eq_true]) + +/-- The cut test of a block a branch picks, distributed over the branch. -/ +theorem ite_beq {α : Type} [BEq α] (c : Prop) [Decidable c] (a b n : α) : + ((if c then a else b) == n) = (if c then a == n else b == n) := by + split <;> rfl + +/-- `0 < a` as a word is `a ≠ 0`: the scheduler may test a value's `ne` against zero with +`lt`, and a segment's two ends then agree only through this. -/ +theorem evm_lt_zero_left (a : EvmRules.Word) : EvmRules.Evm.lt 0 a = EvmRules.Evm.ne a 0 := by + unfold EvmRules.Evm.lt EvmRules.Evm.ne + by_cases h : a = 0 + · subst h; decide + · have hn : a.toNat ≠ 0 := fun e => h (BitVec.eq_of_toNat_eq (by simpa using e)) + have hu : (0#256).ult a = true := by + simp only [BitVec.ult, BitVec.toNat_ofNat, decide_eq_true_eq]; omega + simpa [hu] using h + +/-- The initial state rebuilt field by field, as a program that writes none of it leaves it, is +the initial state: a cut point reached before either program writes the state relates it as one +state. -/ +theorem state_initial_eta (call : Call) : + ({ memory := Mem.initial, storage := (State.initial call).storage, + transient := (State.initial call).transient, world := (State.initial call).world } : State) = + State.initial call := rfl + +/-- A test and its negation as Boolean branches (`if c then true else false` and +`if c then false else true`, as a pass may leave them) joined by `||` are `true`: folded before +any case split, where splitting on the two would leave a leaf only the excluded middle closes. -/ +theorem ite_or_ite_not (c : Prop) [Decidable c] : + ((if c then true else false) || (if c then false else true)) = true := by + by_cases h : c <;> simp [h] + +theorem ite_not_or_ite (c : Prop) [Decidable c] : + ((if c then false else true) || (if c then true else false)) = true := by + by_cases h : c <;> simp [h] + +/-- A cut test of a block a branch picks (`(if c then 15 else 14) == 1`) evaluates on both +branches, so a test that holds on neither is `false` before any case split. Splitting on it +first instead leaves leaves whose contradiction only the branch condition shows, and the case +splits multiply. -/ +macro "seg_cut_test" : tactic => `(tactic| + simp only [ite_beq, Nat.reduceBEq, BitVec.reduceEq, BitVec.reduceNe, ite_self, Bool.false_eq_true, + evm_lt_zero_left, state_initial_eta, Bool.or_true, Bool.or_false, Bool.and_true, Bool.and_false, + ↓reduceIte, Mem.load_store_of_disjoint, Mem.load_store_same, Mem.load_expand, Nat.reduceAdd, + Nat.reduceLeDiff, true_or, or_true, ite_or_ite_not, ite_not_or_ite]) + +syntax "seg_norm" "[" Lean.Parser.Tactic.simpLemma,* "]" : tactic +macro_rules + | `(tactic| seg_norm [$ids,*]) => + `(tactic| repeat (first | sym_eval | seg_eval [$ids,*] | seg_cut_test | sym_cond)) + +/-- The equation of two words, configurations or results, by evaluation and `sym_exec`'s leaf +procedures. -/ +macro "seg_word_eq" : tactic => `(tactic| ( + first + | with_reducible rfl + | ((try seg_cut_test); sym_norm; first + | with_reducible rfl + | (exfalso; bv_omega) + | (exfalso; sym_omega) + | (exfalso; sym_comm_contra) + | sym_select + | sym_agree))) + +/-- What a relation lemma asks of the target configuration: the variables only the target +names, given by unification, then its configuration and each condition. -/ +macro "seg_eq" : tactic => `(tactic| ( + repeat (apply Exists.intro) + repeat' (apply And.intro) + all_goals seg_word_eq)) + +/-- A leaf at two cut points, by one of the relation lemmas `mks` (each +`mk (words…) (state) (y') (h : y' = …) : ∃ Q ∈ rels, Q (…) y'`). -/ +syntax "seg_cut" "[" ident,* "]" : tactic +macro_rules + | `(tactic| seg_cut []) => `(tactic| fail "sym_seg: no relation relates the cut points") + | `(tactic| seg_cut [$m]) => `(tactic| (refine $m ?_; seg_eq)) + | `(tactic| seg_cut [$m, $ms,*]) => `(tactic| + first + | (refine $m ?_; seg_eq) + | seg_cut [$ms,*]) + +/-- One segment obligation, from configurations of variables: evaluate both segments, split +on the conditions they leave, and close each leaf. `unfolds` are the cut tests' definitions +and `mks` the relation lemmas. -/ +syntax "sym_seg" "[" Lean.Parser.Tactic.simpLemma,* "]" "[" ident,* "]" : tactic +set_option hygiene false in +macro_rules + | `(tactic| sym_seg [$us,*] [$ms,*]) => `(tactic| ( + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + seg_norm [$us,*] + repeat' (split_cond <;> seg_norm [$us,*]) + all_goals first + | exact True.intro + | (apply agree_of_eq; seg_eq) + | seg_cut [$ms,*] + | (exfalso; bv_omega) + | (exfalso; sym_omega) + | (exfalso; sym_comm_contra) + | fail "sym_seg: the segments end differently on this path, or the procedure cannot tell")) + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Stage.lean b/tv/W1Proofs/Stage.lean new file mode 100644 index 00000000..38c6fd5b --- /dev/null +++ b/tv/W1Proofs/Stage.lean @@ -0,0 +1,41 @@ +import SolarTV.Machine + +/-! A stage from two runs that end in the same result. + +The procedure of [Tactic.lean](Tactic.lean) proves, for concrete programs, that the first ends +at fuel `n` on every call in scope and that both programs give the same result there, at fuels +`n` and `m`. Since a layer's runs are deterministic and only gain ends with fuel, that is a +stage of their fuel-free semantics, whatever fuel the first program's result was reached at. -/ + +namespace SolarTV.Milestone.W1 + +open Machine + +/-- Every call: the w1 stages hold for any calldata, call value and storage. -/ +def anyCall : Call → Prop := fun _ => True + +theorem stage_of_runs {A B : Layer} {o : Oracle} {p : A.Prog} {q : B.Prog} + {scope : Call → Prop} (n m : Nat) + (ends : ∀ call, scope call → (A.run o p call n).isSome = true) + (same : ∀ call, scope call → A.run o p call n = B.run o q call m) : + Stage (A.sem o) (B.sem o) p q scope := by + apply stage_of_certified + intro call inScope r ran + obtain ⟨r0, h0⟩ := Option.isSome_iff_exists.mp (ends call inScope) + have e : r = r0 := A.ends_unique ran ⟨n, h0⟩ + subst e + refine ⟨r, ⟨m, ?_⟩, Agree.refl r⟩ + rw [← same call inScope] + exact h0 + +/-- The second program of such a pair ends where the first does. -/ +theorem ends_of_runs {A B : Layer} {o : Oracle} {p : A.Prog} {q : B.Prog} + {scope : Call → Prop} {n m : Nat} + (ends : ∀ call, scope call → (A.run o p call n).isSome = true) + (same : ∀ call, scope call → A.run o p call n = B.run o q call m) : + ∀ call, scope call → (B.run o q call m).isSome = true := by + intro call inScope + rw [← same call inScope] + exact ends call inScope + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Stages.lean b/tv/W1Proofs/Stages.lean new file mode 100644 index 00000000..c0e649aa --- /dev/null +++ b/tv/W1Proofs/Stages.lean @@ -0,0 +1,99 @@ +-- Generated by solar-tv/milestone/certify.py; do not edit. +import W1Proofs.Runs.Stage0 +import W1Proofs.Runs.Sched +import W1Proofs.Runs.Evm1 +import W1Proofs.Runs.Evm2 +import W1Proofs.Runs.Evm3 +import W1Proofs.Runs.Evm4 +import W1Proofs.Stage +import SolarTV.Composition + +/-! The backend stages of `Main`, each proved on every call (`anyCall`: any calldata, call value and storage) under every oracle, and chained from the first lowered MIR `stage0` to the final EVM IR `evm4`. Fuels are the programs' block counts. -/ + +namespace SolarTV.Milestone.W1 + +open Machine SolarTV.Export.Main + +/-- `stack-schedule`: stage0 to sched. -/ +theorem stage_sched (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 sched anyCall := + stage_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) 9 9 (fun call _ => stage0_ends o call) + (fun call _ => sched_run o call) + +theorem sched_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o sched call 9).isSome = true := + ends_of_runs (A := MIR.Lowered.moduleLayer) (B := EVM.Program.layer) + (o := o) (p := stage0) (q := sched) (n := 9) (m := 9) (fun call _ => stage0_ends o call) + (fun call _ => sched_run o call) + +/-- `cfg-simplify-early`: sched to evm1. -/ +theorem stage_evm1 (o : Oracle) : Stage (evmirSem o) (evmirSem o) sched evm1 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 9 5 (sched_ends o) + (fun call _ => evm1_run o call) + +theorem evm1_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm1 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := sched) (q := evm1) (n := 9) (m := 5) (sched_ends o) + (fun call _ => evm1_run o call) + +/-- `share-reverts`: evm1 to evm2. -/ +theorem stage_evm2 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm1 evm2 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm1_ends o) + (fun call _ => evm2_run o call) + +theorem evm2_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm2 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm1) (q := evm2) (n := 5) (m := 5) (evm1_ends o) + (fun call _ => evm2_run o call) + +/-- `terminal-dedup`: evm2 to evm3. -/ +theorem stage_evm3 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm2 evm3 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 5 (evm2_ends o) + (fun call _ => evm3_run o call) + +theorem evm3_ends (o : Oracle) : ∀ call, anyCall call → + (EVM.Program.run o evm3 call 5).isSome = true := + ends_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) + (o := o) (p := evm2) (q := evm3) (n := 5) (m := 5) (evm2_ends o) + (fun call _ => evm3_run o call) + +/-- `cfg-simplify-early`: evm3 to evm4. -/ +theorem stage_evm4 (o : Oracle) : Stage (evmirSem o) (evmirSem o) evm3 evm4 anyCall := + stage_of_runs (A := EVM.Program.layer) (B := EVM.Program.layer) 5 3 (evm3_ends o) + (fun call _ => evm4_run o call) + +/-- The compilation from the first lowered MIR to the final EVM IR. -/ +def compilation : Compilation := + ⟨stage0, [], sched, [evm1, evm2, evm3, evm4]⟩ + +/-- Every stage from the first lowered MIR to the final EVM IR, chained by the library's composition, on every call. -/ +theorem w1_mir_to_evmir (o : Oracle) : Stage (mirSem o) (evmirSem o) stage0 evm4 anyCall := + mir_to_evmir o anyCall compilation trivial (stage_sched o) + ⟨stage_evm1 o, stage_evm2 o, stage_evm3 o, stage_evm4 o, trivial⟩ + +/-- info: 'SolarTV.Milestone.W1.stage_sched' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_sched + +/-- info: 'SolarTV.Milestone.W1.stage_evm1' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm1 + +/-- info: 'SolarTV.Milestone.W1.stage_evm2' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm2 + +/-- info: 'SolarTV.Milestone.W1.stage_evm3' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm3 + +/-- info: 'SolarTV.Milestone.W1.stage_evm4' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms stage_evm4 + +/-- info: 'SolarTV.Milestone.W1.w1_mir_to_evmir' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms w1_mir_to_evmir + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/Tactic.lean b/tv/W1Proofs/Tactic.lean new file mode 100644 index 00000000..23fb12ae --- /dev/null +++ b/tv/W1Proofs/Tactic.lean @@ -0,0 +1,1141 @@ +import Lean +import EvmRules.Bits +import SolarTV.Machine +import SolarTV.MemorySymbolic +import SolarTV.MIR.Program +import SolarTV.EVMIR.Program + +/-! A kernel-only procedure for the stages of one loop-free contract. + +For two concrete programs, a stage holds when, on every call, the first ends at some fuel +and both end in the same result (`stage_of_runs`). `sym_exec` proves that equation, and the +first program's end, by symbolic execution over a symbolic call and oracle: + +- `dsimp` runs both programs block by block with the semantics' own equations and the + lookups below, all definitional, so the kernel checks a computed step by evaluation and + not by replaying a chain of rewrites. Calldata words, memory, the oracle and the word + operations stay opaque, so both programs build the same terms for the same values. +- A branch condition that the code cannot decide is turned into a proposition over those + terms by the `cond_*` lemmas (when the word an operation leaves is zero), and + `split_cond` case-splits on the first one left, rewriting both programs with the case. +- A leaf closes by reflexivity when both ends agree, and by `bv_omega` when its cases + contradict each other, as when the programs test one condition in different words. +- Shifts, `NOT` and the binary word operations of numerals fold to numerals, as passes respell + constants and an allocation's bounds checks compute on the constant free memory pointer, and + the tests the compiler spells an address check with (the word above the 160-bit mask, its high + bits shifted out, the word equal to its masked self) rewrite to one proposition, so that each + program's spelling meets the other's. +- A load at a constant address reads the word a store there wrote, reads past a store to + another word, and reads zero from the memory a call starts with, so that the checks that + fresh memory is zero are decided. + +Nothing here calls `bv_decide` or `native_decide`, and `decide` only runs on closed terms, +inside `dsimp`'s evaluation and in `BitVec.reduceEq` on two numerals, so the proofs rest on the +kernel and the standard axioms. A program that loops, reads a value the code does not pin, or +whose stage is false leaves a goal: the procedure fails closed. -/ + +namespace SolarTV.Milestone.W1 + +open EvmRules Machine + +/-! Branch conditions as propositions. A jump is taken on a nonzero word, so each lemma +says when the word an operation leaves is zero. -/ + +theorem cond_ne (a b : Word) : (Evm.ne a b = 0) = (a = b) := by + unfold Evm.ne + by_cases h : a = b + · simp [h] + · simp [h] + +theorem cond_eq (a b : Word) : (Evm.eq a b = 0) = ¬(b = a) := by + unfold Evm.eq + by_cases h : a = b + · simp [h] + · have h' : ¬b = a := fun e => h e.symm + simp [h, h'] + +theorem cond_sub (a b : Word) : (Evm.sub a b = 0) = (b = a) := by + unfold Evm.sub + apply propext + constructor + · intro h; bv_omega + · intro h; bv_omega + +theorem cond_lt (a b : Word) : (Evm.lt a b = 0) = ¬(a < b) := by + unfold Evm.lt + by_cases h : a < b + · simp [h, BitVec.ult_iff_lt] + · simp [h, BitVec.ult_iff_lt] + +theorem cond_gt (a b : Word) : (Evm.gt a b = 0) = ¬(b < a) := by + unfold Evm.gt + by_cases h : b < a + · simp [h, BitVec.ult_iff_lt] + · simp [h, BitVec.ult_iff_lt] + +theorem cond_iszero (a : Word) : (Evm.iszero a = 0) = ¬(a = 0) := by + unfold Evm.iszero + by_cases h : a = 0 + · simp only [h, beq_self_eq_true, Bool.cond_true, not_true_eq_false] + decide + · simp only [h, not_false_eq_true] + have : (a == 0) = false := by simpa using h + rw [this] + decide + +/-- A test compared with zero the other way round, as a fact a pass checks with `eq` reads +it (`cond_eq` puts the zero first): the same propositions as the lemmas above. -/ +theorem cond_zero_lt (a b : Word) : ((0 : Word) = Evm.lt a b) = ¬(a < b) := by + rw [← cond_lt]; exact propext ⟨Eq.symm, Eq.symm⟩ + +theorem cond_zero_gt (a b : Word) : ((0 : Word) = Evm.gt a b) = ¬(b < a) := by + rw [← cond_gt]; exact propext ⟨Eq.symm, Eq.symm⟩ + +theorem cond_zero_eq (a b : Word) : ((0 : Word) = Evm.eq a b) = ¬(b = a) := by + rw [← cond_eq]; exact propext ⟨Eq.symm, Eq.symm⟩ + +theorem cond_zero_ne (a b : Word) : ((0 : Word) = Evm.ne a b) = (a = b) := by + rw [show ((0 : Word) = Evm.ne a b) = (Evm.ne a b = 0) from propext ⟨Eq.symm, Eq.symm⟩, cond_ne] + +theorem cond_zero_iszero (a : Word) : ((0 : Word) = Evm.iszero a) = ¬(a = 0) := by + rw [← cond_iszero]; exact propext ⟨Eq.symm, Eq.symm⟩ + +/-- A disjunction of tests, as the dispatcher's guards combine them, is zero when both are. -/ +theorem cond_or (a b : Word) : (Evm.or a b = 0) = (a = 0 ∧ b = 0) := by + unfold Evm.or + exact propext BitVec.or_eq_zero_iff + +/-! An address is a word of at most 160 bits, the mask's own: masking it keeps it, so a test +that a word equals its masked self holds once a test that it fits passed. The caller is the +oracle's, any address, which fits. -/ + +theorem and_mask {x : Word} (h : ¬ (1461501637330902918203684832716283019655932542975 : Word) < x) : + Evm.and x 1461501637330902918203684832716283019655932542975 = x := by + unfold Evm.and + apply BitVec.eq_of_toNat_eq + have hm : (1461501637330902918203684832716283019655932542975 : Word).toNat = 2 ^ 160 - 1 := rfl + have hx : x.toNat ≤ 2 ^ 160 - 1 := by + rw [BitVec.lt_def, hm] at h; omega + rw [BitVec.toNat_and, hm, Nat.and_two_pow_sub_one_eq_mod] + exact Nat.mod_eq_of_lt (by omega) + +theorem mask_and {x : Word} (h : ¬ (1461501637330902918203684832716283019655932542975 : Word) < x) : + Evm.and 1461501637330902918203684832716283019655932542975 x = x := by + have := and_mask h + unfold Evm.and at this ⊢ + rw [BitVec.and_comm] + exact this + +theorem caller_le_mask (o : Oracle) : + ¬ (1461501637330902918203684832716283019655932542975 : Word) < o.caller.setWidth 256 := by + have hm : (1461501637330902918203684832716283019655932542975 : Word).toNat = 2 ^ 160 - 1 := rfl + have h := o.caller.isLt + rw [BitVec.lt_def, BitVec.toNat_setWidth, hm, Nat.mod_eq_of_lt (by omega)] + omega + +/-- An address immutable's `PUSH20` placeholder pushes 20 bytes, which fit. -/ +theorem immutable20_le_mask (o : Oracle) (id : Nat) : + ¬ (1461501637330902918203684832716283019655932542975 : Word) < immutableWord o id 20 := by + have hm : (1461501637330902918203684832716283019655932542975 : Word).toNat = 2 ^ 160 - 1 := rfl + have h := immutableWord_toNat o id 20 (by decide) (by decide) + have lt := Nat.mod_lt (immutableValue o id).toNat (by decide : 0 < 256 ^ 20) + rw [BitVec.lt_def, hm, h] + have : (256 : Nat) ^ 20 = 2 ^ 160 := by decide + omega + +/-- A width test as solar spells it, by shifting out the address bits, as the mask test. -/ +theorem shr160_eq_zero (x : Word) : + (Evm.shr 160 x = 0) = ¬ (1461501637330902918203684832716283019655932542975 : Word) < x := by + have hm : (1461501637330902918203684832716283019655932542975 : Word).toNat = 2 ^ 160 - 1 := rfl + have hs : Evm.shr 160 x = x >>> 160 := by + unfold Evm.shr + rw [show (160 : Word).ult 256 = true from rfl, Bool.cond_true, BitVec.ushiftRight_eq'] + rfl + rw [hs, BitVec.lt_def, hm] + apply propext + rw [BitVec.toNat_eq, BitVec.toNat_ushiftRight, Nat.shiftRight_eq_div_pow] + show x.toNat / 2 ^ 160 = 0 ↔ ¬2 ^ 160 - 1 < x.toNat + rw [Nat.div_eq_zero_iff] + have := x.isLt + omega + +theorem zero_eq_shr160 (x : Word) : + (0 = Evm.shr 160 x) = ¬ (1461501637330902918203684832716283019655932542975 : Word) < x := by + rw [← shr160_eq_zero] + exact propext eq_comm + +/-- The address mask as `late-word` spells it, shifting the high 96 bits out and back +(`shr(96, shl(96, x))`), as the mask: so a test on a masked word reads the same in both programs. -/ +theorem shr_shl96 (x : Word) : + Evm.shr 96 (Evm.shl 96 x) = Evm.and x 1461501637330902918203684832716283019655932542975 := by + unfold Evm.shr Evm.shl Evm.and + rw [show (96 : Word).ult 256 = true from rfl, Bool.cond_true, Bool.cond_true, + BitVec.ushiftRight_eq', BitVec.shiftLeft_eq'] + apply BitVec.eq_of_toNat_eq + have hm : (1461501637330902918203684832716283019655932542975 : Word).toNat = 2 ^ 160 - 1 := rfl + have h96 : (96 : Word).toNat = 96 := rfl + rw [BitVec.toNat_ushiftRight, BitVec.toNat_shiftLeft, BitVec.toNat_and, hm, h96, + Nat.and_two_pow_sub_one_eq_mod, Nat.shiftLeft_eq, Nat.shiftRight_eq_div_pow, + show 2 ^ 256 = 2 ^ 96 * 2 ^ 160 by rw [← Nat.pow_add], Nat.mod_mul_right_div_self, + Nat.mul_div_cancel _ (Nat.two_pow_pos 96)] + +/-! Tests the cases decide, as the words they leave, and the arithmetic a select becomes: +`if-convert` turns a branch on a test `c` between `t` and `f` into `f + c * (t - f)`. -/ + +theorem lt_of_case {a b : Word} (h : a < b) : Evm.lt a b = 1 := by + simp [Evm.lt, BitVec.ult_iff_lt, h] +theorem lt_of_not_case {a b : Word} (h : ¬(a < b)) : Evm.lt a b = 0 := by + simp [Evm.lt, BitVec.ult_iff_lt, h] +theorem gt_of_case {a b : Word} (h : b < a) : Evm.gt a b = 1 := by + simp [Evm.gt, BitVec.ult_iff_lt, h] +theorem gt_of_not_case {a b : Word} (h : ¬(b < a)) : Evm.gt a b = 0 := by + simp [Evm.gt, BitVec.ult_iff_lt, h] +theorem eq_of_case {a b : Word} (h : b = a) : Evm.eq a b = 1 := by + subst h; simp [Evm.eq] +theorem eq_of_not_case {a b : Word} (h : ¬(b = a)) : Evm.eq a b = 0 := by + unfold Evm.eq + rw [beq_eq_false_iff_ne.mpr (fun e => h e.symm)] + rfl +theorem iszero_of_case {a : Word} (h : a = 0) : Evm.iszero a = 1 := by + subst h; simp [Evm.iszero] +theorem iszero_of_not_case {a : Word} (h : ¬(a = 0)) : Evm.iszero a = 0 := by + unfold Evm.iszero + rw [beq_eq_false_iff_ne.mpr h] + rfl + +theorem mul_word_one (a : Word) : Evm.mul a 1 = a := BitVec.mul_one a +theorem mul_one_word (a : Word) : Evm.mul 1 a = a := BitVec.one_mul a +theorem mul_word_zero (a : Word) : Evm.mul a 0 = 0 := BitVec.mul_zero +theorem mul_zero_word (a : Word) : Evm.mul 0 a = 0 := BitVec.zero_mul +theorem add_sub_word (a b : Word) : Evm.add b (Evm.sub a b) = a := by + unfold Evm.add Evm.sub + bv_omega +theorem add_word_zero (a : Word) : Evm.add a 0 = a := BitVec.add_zero a +theorem add_zero_word (a : Word) : Evm.add 0 a = a := BitVec.zero_add a + +/-! Commutative operations, which a pass may write either way round: the `word*Comm` +simprocs below rewrite with them towards one order of their operands, the same for both +programs. -/ + +theorem word_add_comm (a b : Word) : Evm.add a b = Evm.add b a := BitVec.add_comm a b +theorem word_mul_comm (a b : Word) : Evm.mul a b = Evm.mul b a := BitVec.mul_comm a b +theorem word_and_comm (a b : Word) : Evm.and a b = Evm.and b a := BitVec.and_comm a b +theorem word_or_comm (a b : Word) : Evm.or a b = Evm.or b a := BitVec.or_comm a b +theorem word_xor_comm (a b : Word) : Evm.xor a b = Evm.xor b a := BitVec.xor_comm a b + +/-! Evaluation steps, each definitional. -/ + +/-- One iteration from a configuration the code has built. Matching only a pair keeps +`dsimp` from unfolding the iterations after a step it cannot compute yet. -/ +@[defeq] theorem iterate_mk {α β : Type} (step : α × β → Option ((Halt × State) ⊕ (α × β))) + (n : Nat) (a : α) (b : β) : + iterate step (n + 1) (a, b) = + match step (a, b) with + | some (.inl result) => some result + | some (.inr next) => iterate step n next + | none => none := by + rw [iterate] + cases step (a, b) with + | none => rfl + | some v => cases v <;> rfl + +@[defeq] theorem iterate_zero {σ : Type} (step : σ → Option ((Halt × State) ⊕ σ)) (x : σ) : + iterate step 0 x = none := by + rw [iterate] + + +/-! Effects, one equation each. A calldata word is read through `cd`, a variable the procedure +binds to `calldataWord call` first, so that the kernel never unfolds the 32-byte read while it +checks a step. -/ + +section effects + +variable (o : Oracle) (call : Call) (s : State) + +@[defeq] theorem apply_mload (offset : Word) : Effect.apply o call .mload [offset] s = + some (some (s.memory.load offset.toNat), { s with memory := s.memory.expand offset.toNat 32 }) := rfl +@[defeq] theorem apply_mstore (offset value : Word) : Effect.apply o call .mstore [offset, value] s = + some (none, { s with memory := s.memory.store offset.toNat value }) := rfl +@[defeq] theorem apply_mstore8 (offset value : Word) : Effect.apply o call .mstore8 [offset, value] s = + some (none, { s with memory := s.memory.storeByte offset.toNat value }) := rfl +@[defeq] theorem apply_msize : Effect.apply o call .msize [] s = some (some s.memory.msize, s) := rfl +@[defeq] theorem apply_sload (key : Word) : Effect.apply o call .sload [key] s = + some (some (s.storage key), s) := rfl +@[defeq] theorem apply_sstore (key value : Word) : Effect.apply o call .sstore [key, value] s = + some (none, { s with storage := update s.storage key value }) := rfl +@[defeq] theorem apply_tload (key : Word) : Effect.apply o call .tload [key] s = + some (some (s.transient key), s) := rfl +@[defeq] theorem apply_tstore (key value : Word) : Effect.apply o call .tstore [key, value] s = + some (none, { s with transient := update s.transient key value }) := rfl +@[defeq] theorem apply_calldatasize : Effect.apply o call .calldatasize [] s = + some (some (BitVec.ofNat 256 call.calldata.size), s) := rfl +@[defeq] theorem apply_callvalue : Effect.apply o call .callvalue [] s = + some (some (BitVec.ofNat 256 call.callvalue), s) := rfl +@[defeq] theorem apply_caller : Effect.apply o call .caller [] s = + some (some (o.caller.setWidth 256), s) := rfl +@[defeq] theorem apply_address : Effect.apply o call .address [] s = + some (some (BitVec.ofNat 256 environment.callee), s) := rfl +@[defeq] theorem apply_returndatasize : Effect.apply o call .returndatasize [] s = + some (some (o.env "returndatasize" s.world []), s) := rfl +@[defeq] theorem apply_keccak256 (offset size : Word) : + Effect.apply o call .keccak256 [offset, size] s = + let memory := s.memory.expand offset.toNat size.toNat + some (some (o.keccak (memory.read offset.toNat size.toNat)), { s with memory }) := rfl + +@[defeq] theorem apply_immutable (id bytes : Nat) (read : ImmutableRead) : + Effect.apply o call (.immutable id bytes read) [] s = + some (some (read.apply (immutableWord o id bytes)), s) := rfl +@[defeq] theorem apply_codecopy (dest offset size : Word) : + Effect.apply o call .codecopy [dest, offset, size] s = + let memory := s.memory.write dest.toNat size.toNat (fun i => codeByte o (offset.toNat + i)) + some (none, { s with memory }) := rfl +@[defeq] theorem apply_create (value offset size : Word) : + Effect.apply o call .create [value, offset, size] s = some (created o s [value] offset size) := + rfl +@[defeq] theorem apply_create2 (value offset size salt : Word) : + Effect.apply o call .create2 [value, offset, size, salt] s = + some (created o s [value, salt] offset size) := rfl +@[defeq] theorem apply_gas : Effect.apply o call .gas [] s = + let world := s.world ++ [.read "gas"] + some (some (o.env "gas" world []), { s with world }) := rfl +@[defeq] theorem apply_env (name : String) (operands : List Word) : + Effect.apply o call (.env name) operands s = some (some (o.env name s.world operands), s) := rfl +@[defeq] theorem apply_calldatacopy (dest offset size : Word) : + Effect.apply o call .calldatacopy [dest, offset, size] s = + let memory := s.memory.write dest.toNat size.toNat + (fun i => calldataByte call (offset.toNat + i)) + some (none, { s with memory }) := rfl +@[defeq] theorem apply_mcopy (dest source size : Word) : + Effect.apply o call .mcopy [dest, source, size] s = + let read := s.memory.expand source.toNat size.toNat + let memory := read.write dest.toNat size.toNat (fun i => read.bytes (source.toNat + i)) + some (none, { s with memory }) := rfl +@[defeq] theorem apply_returndatacopy (dest offset size : Word) : + Effect.apply o call .returndatacopy [dest, offset, size] s = + if (returndataSize o s.world).toNat < offset.toNat + size.toNat then none + else + let memory := s.memory.write dest.toNat size.toNat + (fun i => returndataByte o s.world (offset.toNat + i)) + some (none, { s with memory }) := rfl + +/-- The memory a call sees, after the expansion of its input and output ranges. -/ +def callMemory (s : State) (inOffset inSize outOffset outSize : Word) : Mem := + (s.memory.expand inOffset.toNat inSize.toNat).expand outOffset.toNat outSize.toNat + +/-- The world after a call, which `sym_eval` unfolds. -/ +def callWorld (s : State) (kind : CallKind) (seen : List Word) + (inOffset inSize outOffset outSize : Word) : List Event := + s.world ++ [.call kind seen + ((callMemory s inOffset inSize outOffset outSize).read inOffset.toNat inSize.toNat) + s.storage s.transient] + +@[defeq] theorem apply_call (gas address value inOffset inSize outOffset outSize : Word) : + Effect.apply o call (.call .call) [gas, address, value, inOffset, inSize, outOffset, outSize] s = + let world := callWorld s .call [gas, address, value] inOffset inSize outOffset outSize + some (some (callFlag o world), called o .call s + (callMemory s inOffset inSize outOffset outSize) outOffset outSize world) := rfl +@[defeq] theorem apply_callcode (gas address value inOffset inSize outOffset outSize : Word) : + Effect.apply o call (.call .callcode) + [gas, address, value, inOffset, inSize, outOffset, outSize] s = + let world := callWorld s .callcode [gas, address, value] inOffset inSize outOffset outSize + some (some (callFlag o world), called o .callcode s + (callMemory s inOffset inSize outOffset outSize) outOffset outSize world) := rfl +@[defeq] theorem apply_delegatecall (gas address inOffset inSize outOffset outSize : Word) : + Effect.apply o call (.call .delegatecall) [gas, address, inOffset, inSize, outOffset, outSize] s = + let world := callWorld s .delegatecall [gas, address] inOffset inSize outOffset outSize + some (some (callFlag o world), called o .delegatecall s + (callMemory s inOffset inSize outOffset outSize) outOffset outSize world) := rfl +@[defeq] theorem apply_staticcall (gas address inOffset inSize outOffset outSize : Word) : + Effect.apply o call (.call .staticcall) [gas, address, inOffset, inSize, outOffset, outSize] s = + let world := callWorld s .staticcall [gas, address] inOffset inSize outOffset outSize + some (some (callFlag o world), called o .staticcall s + (callMemory s inOffset inSize outOffset outSize) outOffset outSize world) := rfl + +/-- The state after a log, which `sym_eval` unfolds. -/ +def logged (s : State) (offset size : Word) (topics : List Word) : State := + let memory := s.memory.expand offset.toNat size.toNat + { s with memory, world := s.world ++ [.log topics (memory.read offset.toNat size.toNat)] } + +@[defeq] theorem apply_log0 (offset size : Word) : + Effect.apply o call (.log 0) [offset, size] s = some (none, logged s offset size []) := rfl +@[defeq] theorem apply_log1 (offset size t0 : Word) : + Effect.apply o call (.log 1) [offset, size, t0] s = + some (none, logged s offset size [t0]) := rfl +@[defeq] theorem apply_log2 (offset size t0 t1 : Word) : + Effect.apply o call (.log 2) [offset, size, t0, t1] s = + some (none, logged s offset size [t0, t1]) := rfl +@[defeq] theorem apply_log3 (offset size t0 t1 t2 : Word) : + Effect.apply o call (.log 3) [offset, size, t0, t1, t2] s = + some (none, logged s offset size [t0, t1, t2]) := rfl +@[defeq] theorem apply_log4 (offset size t0 t1 t2 t3 : Word) : + Effect.apply o call (.log 4) [offset, size, t0, t1, t2, t3] s = + some (none, logged s offset size [t0, t1, t2, t3]) := rfl + +/-- A calldata read as a read of `cd`. Not definitional, so `simp` rewrites with its proof. -/ +theorem apply_calldataload {cd : Word → Word} (hcd : cd = calldataWord call) (offset : Word) : + Effect.apply o call .calldataload [offset] s = some (some (cd offset), s) := by + subst hcd + rfl + +end effects + +/-! EVM IR word operations, one equation each, by `rfl`. `sym_eval` rewrites a step with these +instead of unfolding `EVM.step`, whose match over every operation it would otherwise reduce on +every step of every path. `EVM.step` itself is unchanged, and an operation without an equation +here (`exchange`, or a stack too short for its operands) leaves the step unevaluated, so the +procedure fails rather than guesses. -/ + +section steps + +variable (ctx : EVM.Context) + +@[defeq] theorem step_add (a b : Word) (rest : List Word) : + EVM.step ctx .add (a :: b :: rest) = some (Evm.add a b :: rest) := rfl +@[defeq] theorem step_mul (a b : Word) (rest : List Word) : + EVM.step ctx .mul (a :: b :: rest) = some (Evm.mul a b :: rest) := rfl +@[defeq] theorem step_and (a b : Word) (rest : List Word) : + EVM.step ctx .and (a :: b :: rest) = some (Evm.and a b :: rest) := rfl +@[defeq] theorem step_or (a b : Word) (rest : List Word) : + EVM.step ctx .or (a :: b :: rest) = some (Evm.or a b :: rest) := rfl +@[defeq] theorem step_xor (a b : Word) (rest : List Word) : + EVM.step ctx .xor (a :: b :: rest) = some (Evm.xor a b :: rest) := rfl +@[defeq] theorem step_div (a b : Word) (rest : List Word) : + EVM.step ctx .div (a :: b :: rest) = some (Evm.div a b :: rest) := rfl +@[defeq] theorem step_sdiv (a b : Word) (rest : List Word) : + EVM.step ctx .sdiv (a :: b :: rest) = some (Evm.sdiv a b :: rest) := rfl +@[defeq] theorem step_mod (a b : Word) (rest : List Word) : + EVM.step ctx .mod (a :: b :: rest) = some (Evm.mod a b :: rest) := rfl +@[defeq] theorem step_smod (a b : Word) (rest : List Word) : + EVM.step ctx .smod (a :: b :: rest) = some (Evm.smod a b :: rest) := rfl +@[defeq] theorem step_signextend (a b : Word) (rest : List Word) : + EVM.step ctx .signextend (a :: b :: rest) = some (Evm.signextend a b :: rest) := rfl +@[defeq] theorem step_byte (a b : Word) (rest : List Word) : + EVM.step ctx .byte (a :: b :: rest) = some (Evm.byte a b :: rest) := rfl +@[defeq] theorem step_shl (a b : Word) (rest : List Word) : + EVM.step ctx .shl (a :: b :: rest) = some (Evm.shl a b :: rest) := rfl +@[defeq] theorem step_shr (a b : Word) (rest : List Word) : + EVM.step ctx .shr (a :: b :: rest) = some (Evm.shr a b :: rest) := rfl +@[defeq] theorem step_sar (a b : Word) (rest : List Word) : + EVM.step ctx .sar (a :: b :: rest) = some (Evm.sar a b :: rest) := rfl +@[defeq] theorem step_lt (a b : Word) (rest : List Word) : + EVM.step ctx .lt (a :: b :: rest) = some (Evm.lt a b :: rest) := rfl +@[defeq] theorem step_gt (a b : Word) (rest : List Word) : + EVM.step ctx .gt (a :: b :: rest) = some (Evm.gt a b :: rest) := rfl +@[defeq] theorem step_slt (a b : Word) (rest : List Word) : + EVM.step ctx .slt (a :: b :: rest) = some (Evm.slt a b :: rest) := rfl +@[defeq] theorem step_sgt (a b : Word) (rest : List Word) : + EVM.step ctx .sgt (a :: b :: rest) = some (Evm.sgt a b :: rest) := rfl +@[defeq] theorem step_eq (a b : Word) (rest : List Word) : + EVM.step ctx .eq (a :: b :: rest) = some (Evm.eq a b :: rest) := rfl +@[defeq] theorem step_sub (a b : Word) (rest : List Word) : + EVM.step ctx .sub (a :: b :: rest) = some (Evm.sub a b :: rest) := rfl +@[defeq] theorem step_exp (a b : Word) (rest : List Word) : + EVM.step ctx .exp (a :: b :: rest) = some (Word.power a b.toNat :: rest) := rfl +@[defeq] theorem step_addmod (a b n : Word) (rest : List Word) : + EVM.step ctx .addmod (a :: b :: n :: rest) = some (Evm.addmod a b n :: rest) := rfl +@[defeq] theorem step_mulmod (a b n : Word) (rest : List Word) : + EVM.step ctx .mulmod (a :: b :: n :: rest) = some (Evm.mulmod a b n :: rest) := rfl +@[defeq] theorem step_not (a : Word) (rest : List Word) : + EVM.step ctx .not (a :: rest) = some (Evm.not a :: rest) := rfl +@[defeq] theorem step_clz (a : Word) (rest : List Word) : + EVM.step ctx .clz (a :: rest) = some (Evm.clz a :: rest) := rfl +@[defeq] theorem step_iszero (a : Word) (rest : List Word) : + EVM.step ctx .iszero (a :: rest) = some (Evm.iszero a :: rest) := rfl +@[defeq] theorem step_pop (a : Word) (rest : List Word) : + EVM.step ctx .pop (a :: rest) = some rest := rfl +@[defeq] theorem step_dup (index : Fin 256) (stack : List Word) : + EVM.step ctx (.dup index) stack = (stack[index.val]?).map (fun value => value :: stack) := rfl +@[defeq] theorem step_swap (index : Fin 256) (a : Word) (rest : List Word) : + EVM.step ctx (.swap index) (a :: rest) = + (rest[index.val]?).map (fun value => value :: rest.set index.val a) := rfl +@[defeq] theorem step_calldatasize (rest : List Word) : + EVM.step ctx .calldatasize rest = some (ctx.calldataSize :: rest) := rfl +@[defeq] theorem step_returndatasize (rest : List Word) : + EVM.step ctx .returndatasize rest = some (ctx.returndataSize :: rest) := rfl +@[defeq] theorem step_push (value : Word) (rest : List Word) : + EVM.step ctx (.push value) rest = some (value :: rest) := rfl + +end steps + +/-! Stack positions of `dup` and `swap` as numbers. -/ + +open Lean Meta Simp in +/-- A stack position of `dup`, `swap` or `exchange`, a `Fin` numeral of any bound, as the +number it is, so that `dup` and `swap` read the stack at a literal index. -/ +dsimproc_decl finValue (Fin.val _) := fun e => do + let_expr Fin.val _ x := e | return .continue + let some ⟨_, value⟩ ← getFinValue? x | return .continue + return .done (mkNatLit value.val) + +open Lean Meta Simp in +/-- A list spelled out as a program constant's field, unfolded to its spine; any other list is +left as it is, so that a stack is only read once its words are computed. A long list literal +elaborates to chunks bound with `have`, which unfold to the same spine. -/ +def programSpine? (xs : Expr) : MetaM (Option Expr) := do + let xs := xs.consumeMData + if xs.isAppOfArity ``List.cons 3 || xs.isAppOfArity ``List.nil 1 then return some xs + if xs.isLet then return some (← whnfD xs) + let fn := xs.getAppFn + let some name := fn.constName? | return none + unless (← getEnv).isProjectionFn name do return none + let some arg := xs.getAppArgs.back? | return none + unless arg.consumeMData.isConst || (arg.getAppFn.isConst && + (← getEnv).isConstructor arg.getAppFn.constName!) do + return none + return some (← whnfD xs) + +open Lean Meta Simp in +/-- The element at a numeral index of a list the code spells out, as `some x` or `none`. It +reduces only the spine of a program's list, so a program stays a constant in the goal and only +the block a step enters is unfolded, and never evaluates a list it does not see. -/ +dsimproc_decl listLookup ((_ : List _)[_]?) := fun e => do + let_expr GetElem?.getElem? _ _ elem _ _ xs i := e | return .continue + let some n ← Nat.fromExpr? i | return .continue + let some spine ← programSpine? xs | return .continue + let mut spine := spine + for _ in [0:n] do + let_expr List.cons _ _ tail := spine | return .continue + let some tail' ← programSpine? tail | return .continue + spine := tail' + match_expr spine with + | List.cons _ head _ => return .done (← mkAppOptM ``Option.some #[elem, head]) + | List.nil _ => return .done (← mkAppOptM ``Option.none #[elem]) + | _ => return .continue + +open Lean Meta Simp in +/-- The length of a list the code spells out, as a numeral, such as a program's block count, +which a dynamic jump past the last block compares with. -/ +dsimproc_decl listLength (List.length _) := fun e => do + let_expr List.length _ xs := e | return .continue + let some spine ← programSpine? xs | return .continue + let mut spine := spine + let mut n := 0 + repeat + match_expr spine with + | List.cons _ _ tail => + let some tail' ← programSpine? tail | return .continue + spine := tail' + n := n + 1 + | List.nil _ => break + | _ => return .continue + return .done (mkNatLit n) + +open Lean Meta Simp in +/-- The entry function of a module the code spells out. -/ +dsimproc_decl moduleEntry (SolarTV.MIR.Lowered.Module.entry _) := fun e => do + let e' ← whnfD e + if (← Nat.fromExpr? e').isSome then return .done e' else return .continue + +open Lean Meta Simp in +/-- The parameters of a function the code spells out. -/ +dsimproc_decl functionParams (SolarTV.MIR.Lowered.Function.params _) := fun e => do + let e' ← whnfD e + match_expr e' with + | List.nil _ => return .done e' + | List.cons _ _ _ => return .done e' + | _ => return .continue + +open Lean Meta Simp in +/-- An `if` whose condition the code fixes: its `Decidable` instance evaluates to `isTrue` or +`isFalse`, so the `if` is its branch by definition. Conditions on the call stay. -/ +dsimproc_decl decideIte (ite _ _ _) := fun e => do + let_expr ite _ c inst yes no := e | return .continue + if c.hasFVar || c.hasMVar then return .continue + let inst ← whnfD inst + if inst.isAppOf ``Decidable.isTrue then return .visit yes + if inst.isAppOf ``Decidable.isFalse then return .visit no + return .continue + +open Lean Meta in +/-- The value of a numeral word. -/ +def wordLit? (e : Expr) : MetaM (Option Nat) := do + match ← getBitVecValue? e with + | some ⟨256, v⟩ => return some v.toNat + | _ => return none + +open Lean Meta Simp in +/-- A shift or `NOT` of numerals as the numeral it computes, as a pass spells a constant +(`compact-pushes` pushes the address mask as `shr(96, not(0))`), so that the lemmas about +the constant apply. The kernel checks the value by evaluation. -/ +dsimproc_decl foldNot (Evm.not _) := fun e => do + let_expr Evm.not a := e | return .continue + let some x ← wordLit? a | return .continue + return .done (← mkNumeral (mkConst ``EvmRules.Word) (2 ^ 256 - 1 - x)) + +open Lean Meta Simp in +/-- See `foldNot`. -/ +dsimproc_decl foldShl (Evm.shl _ _) := fun e => do + let_expr Evm.shl s v := e | return .continue + let some s ← wordLit? s | return .continue + let some v ← wordLit? v | return .continue + return .done (← mkNumeral (mkConst ``EvmRules.Word) (if s < 256 then (v <<< s) % 2 ^ 256 else 0)) + +open Lean Meta Simp in +/-- See `foldNot`. -/ +dsimproc_decl foldShr (Evm.shr _ _) := fun e => do + let_expr Evm.shr s v := e | return .continue + let some s ← wordLit? s | return .continue + let some v ← wordLit? v | return .continue + return .done (← mkNumeral (mkConst ``EvmRules.Word) (if s < 256 then v >>> s else 0)) + +open Lean Meta Simp in +/-- A binary word operation of two numerals as the numeral it computes, as the bounds checks of +a memory allocation compute on the constant free memory pointer (the end of an allocation, its +test against the pointer's 64-bit range), so that a test the constants decide is decided. The +kernel checks the value by evaluation. -/ +def foldWord2 (op : Name) (f : Nat → Nat → Nat) (e : Expr) : SimpM DStep := do + unless e.isAppOfArity op 2 do return .continue + let some a ← wordLit? (e.getArg! 0) | return .continue + let some b ← wordLit? (e.getArg! 1) | return .continue + return .done (← mkNumeral (mkConst ``EvmRules.Word) (f a b % 2 ^ 256)) + +dsimproc_decl foldAdd (Evm.add _ _) := foldWord2 ``Evm.add (· + ·) +dsimproc_decl foldSub (Evm.sub _ _) := foldWord2 ``Evm.sub (fun a b => a + 2 ^ 256 - b) +dsimproc_decl foldMul (Evm.mul _ _) := foldWord2 ``Evm.mul (· * ·) +dsimproc_decl foldAnd (Evm.and _ _) := foldWord2 ``Evm.and (· &&& ·) +dsimproc_decl foldOr (Evm.or _ _) := foldWord2 ``Evm.or (· ||| ·) +dsimproc_decl foldXor (Evm.xor _ _) := foldWord2 ``Evm.xor (· ^^^ ·) +dsimproc_decl foldLt (Evm.lt _ _) := foldWord2 ``Evm.lt (fun a b => if a < b then 1 else 0) +dsimproc_decl foldGt (Evm.gt _ _) := foldWord2 ``Evm.gt (fun a b => if a > b then 1 else 0) +dsimproc_decl foldEq (Evm.eq _ _) := foldWord2 ``Evm.eq (fun a b => if a = b then 1 else 0) + +open Lean Elab Tactic Meta in +/-- Case-split on the first `if` of the goal whose condition is closed, as `hc`, with `hcs` its +symmetric form when it is an equation or its negation, so that either program's orientation +of a test rewrites. A positive equation is oriented to rewrite its open side into its closed +side, and a side that contains the other into the other, as a word equal to its masked self +(an ABI address check) rewrites the masked word into the word: the other way would loop. It +fails when no such condition is left, or when one is already a hypothesis, which means the +rewrite with it did not reach its `if`. -/ +elab "split_cond" : tactic => withMainContext do + let target ← instantiateMVars (← getMainTarget) + let some cond := (target.find? fun e => + e.isAppOfArity ``ite 5 && !(e.getArg! 1).hasLooseBVars && !(e.getArg! 1).hasMVar).map + (·.getArg! 1) + | throwError "split_cond: no closed condition in the goal" + for decl in ← getLCtx do + if decl.isImplementationDetail then continue + let ty ← instantiateMVars decl.type + if ty == cond || ty == mkNot cond then + throwError "split_cond: the case {cond} is a hypothesis but its condition remains" + let stx ← Term.exprToSyntax cond + let hc := mkIdent `hc + let hcs := mkIdent `hcs + let closed (e : Expr) : Bool := !e.hasFVar && !e.hasMVar + let isEq := cond.isAppOfArity ``Eq 3 + -- x = f x rewrites as f x = x, which ends. + let pos ← if isEq && (closed (cond.getArg! 1) || (cond.getArg! 1).occurs (cond.getArg! 2)) then + `(tactic| (replace $hc:ident := Eq.symm $hc; have $hcs:ident := $hc)) + else `(tactic| have $hcs:ident := $hc) + let neg ← if isEq then `(tactic| have $hcs:ident := Ne.symm $hc) + else `(tactic| have $hcs:ident := $hc) + evalTactic (← `(tactic| by_cases $hc:ident : $stx)) + let goals ← getGoals + let (yes, no, rest) ← match goals with + | yes :: no :: rest => pure (yes, no, rest) + | _ => throwError "split_cond: by_cases did not give two cases" + setGoals [yes] + evalTactic pos + let yes' ← getGoals + setGoals [no] + evalTactic neg + setGoals (yes' ++ (← getGoals) ++ rest) + +/-! Jump tables. A table's lookup at an index the code does not fix becomes a chain of tests of +the index, one per entry, which `split_cond` splits like any branch. -/ + +/-- A jump table's entry at word index `i`, from entry `k`, as a chain of tests of the index. -/ +def tableEntry (i : Word) : Nat → List Nat → Option Nat + | _, [] => none + | k, x :: xs => if i = BitVec.ofNat 256 k then some x else tableEntry i (k + 1) xs + +theorem tableEntry_eq (i : Word) : ∀ (xs : List Nat) (k : Nat), k + xs.length ≤ 2 ^ 256 → + tableEntry i k xs = if k ≤ i.toNat then xs[i.toNat - k]? else none + | [], k, _ => by simp [tableEntry] + | x :: xs, k, h => by + simp only [List.length_cons] at h + have hk : k < 2 ^ 256 := by omega + have ih := tableEntry_eq i xs (k + 1) (by omega) + unfold tableEntry + by_cases e : i = BitVec.ofNat 256 k + · have hi : i.toNat = k := by rw [e, BitVec.toNat_ofNat]; exact Nat.mod_eq_of_lt hk + rw [if_pos e, if_pos (by omega), hi, Nat.sub_self, List.getElem?_cons_zero] + · have hi : i.toNat ≠ k := fun h' => e (by + apply BitVec.eq_of_toNat_eq + rw [h', BitVec.toNat_ofNat, Nat.mod_eq_of_lt hk]) + rw [if_neg e, ih] + by_cases h1 : k + 1 ≤ i.toNat + · rw [if_pos h1, if_pos (by omega), + show i.toNat - k = (i.toNat - (k + 1)) + 1 by omega, List.getElem?_cons_succ] + · rw [if_neg h1, if_neg (by omega)] + +/-- A table lookup at a word index is the chain of tests of `tableEntry`. -/ +theorem table_lookup (xs : List Nat) (i : Word) (h : xs.length ≤ 2 ^ 256) : + xs[i.toNat]? = tableEntry i 0 xs := by + rw [tableEntry_eq i xs 0 (by omega)] + simp + +open Lean Elab Tactic Meta in +/-- Rewrite the first lookup of a jump table the code spells out at an index it does not fix, +`xs[i.toNat]?`, to the chain of tests of `tableEntry` (`table_lookup`, its side condition +decided by the kernel). It fails when there is none. -/ +elab "split_table" : tactic => withMainContext do + let target ← instantiateMVars (← getMainTarget) + let some e := target.find? fun e => + e.isAppOfArity ``GetElem?.getElem? 7 && (e.getArg! 6).isAppOfArity ``BitVec.toNat 2 && + !(e.getArg! 5).hasFVar && !(e.getArg! 5).hasMVar && !(e.getArg! 5).hasLooseBVars && + (e.getArg! 6).hasFVar && !(e.getArg! 6).hasLooseBVars && !(e.getArg! 6).hasMVar + | throwError "split_table: no table lookup at an open index in the goal" + unless ← isDefEq (← inferType (e.getArg! 5)) (← mkAppM ``List #[mkConst ``Nat]) do + throwError "split_table: the lookup is in no list of block numbers" + let xs ← Term.exprToSyntax (e.getArg! 5) + let i ← Term.exprToSyntax ((e.getArg! 6).getArg! 1) + evalTactic (← `(tactic| simp only [table_lookup $xs $i (by decide)])) + +open Lean Meta Simp in +/-- A low mask of a natural number as its remainder, `a &&& (2^k - 1)` as `a % 2^k`, for a +literal mask on either side, so that `omega` reads the masks of narrow integers. -/ +simproc_decl natMask ((_ : Nat) &&& _) := fun e => do + let_expr HAnd.hAnd _ _ _ _ a b := e | return .continue + let (x, mask, swapped) ← match ← Nat.fromExpr? b with + | some n => pure (a, n, false) + | none => + match ← Nat.fromExpr? a with + | some n => pure (b, n, true) + | none => return .continue + let k := (mask + 1).log2 + unless 2 ^ k == mask + 1 do return .continue + let rhs ← mkAppM ``HMod.hMod #[x, mkNatLit (mask + 1)] + -- x &&& 2^k - 1 = x % 2^k, with both sides' literals computed by the kernel. + let low ← mkExpectedTypeHint (mkApp2 (mkConst ``Nat.and_two_pow_sub_one_eq_mod) x (mkNatLit k)) + (← mkEq (← mkAppM ``HAnd.hAnd #[x, mkNatLit mask]) rhs) + let proof ← if swapped then mkEqTrans (← mkAppM ``Nat.and_comm #[a, b]) low else pure low + return .done { expr := rhs, proof? := some proof } + +/-! A byte of a loaded word, as passes that share one memory read between neighbouring byte +reads spell it (`byte-run-loads`): `BYTE k` of the word loaded at `a` is the byte at +`a + k`, so that `byte 0 (mload (p + 1))` and `byte 1 (mload p)` meet. -/ + +/-- A fold of bytes into a word, as `Mem.load` folds them, bit by bit: the low `8 * n` bits +are the `n` bytes, the last lowest, and the bits above them the initial word's. -/ +theorem getLsbD_foldBytes (l : List SolarTV.Memory.Byte) (acc : BitVec 256) (j : Nat) : + (l.foldl (fun (acc : BitVec 256) (b : SolarTV.Memory.Byte) => (acc <<< 8) ||| b.setWidth 256) + acc).getLsbD j = + (decide (j < 256) && if j < 8 * l.length then + (l.getD (l.length - 1 - j / 8) 0).getLsbD (j % 8) else acc.getLsbD (j - 8 * l.length)) := by + induction l generalizing acc with + | nil => + simp only [List.foldl_nil, List.length_nil, Nat.mul_zero, Nat.not_lt_zero, ite_false, + Nat.sub_zero] + by_cases h : j < 256 + · simp [h] + · simp [h, BitVec.getLsbD_of_ge acc j (by omega)] + | cons b t ih => + rw [List.foldl_cons, ih] + simp only [List.length_cons] + by_cases h256 : j < 256 + · simp only [h256, decide_true, Bool.true_and] + by_cases ht : j < 8 * t.length + · have hl : j < 8 * (t.length + 1) := by omega + have e : t.length + 1 - 1 - j / 8 = (t.length - 1 - j / 8) + 1 := by omega + simp only [ht, hl, ite_true, e, List.getD_cons_succ] + · simp only [ht, ite_false, BitVec.getLsbD_or, BitVec.getLsbD_shiftLeft, + BitVec.getLsbD_setWidth] + by_cases hl : j < 8 * (t.length + 1) + · have e : t.length + 1 - 1 - j / 8 = 0 := by omega + have hlt : j - 8 * t.length < 8 := by omega + have hm : j % 8 = j - 8 * t.length := by omega + simp only [hl, ite_true, e, List.getD_cons_zero, hm, hlt, decide_true, + Bool.not_true, Bool.and_false, Bool.false_and, Bool.false_or] + simp only [show j - 8 * t.length < 256 by omega, decide_true, Bool.true_and] + · have hnot8 : ¬ j - 8 * t.length < 8 := by omega + have e : j - 8 * t.length - 8 = j - 8 * (t.length + 1) := by omega + simp only [hl, ite_false, hnot8, decide_false, Bool.not_false, Bool.and_true, e, + show j - 8 * t.length < 256 by omega, decide_true, Bool.true_and] + rw [BitVec.getLsbD_of_ge b _ (by omega)] + simp + · simp [h256] + +/-- Byte i of a loaded word is the byte at the load's address plus i. -/ +theorem byte_load (m : Mem) (a i : Nat) (hi : i < 32) : + SolarTV.Memory.byte (m.load a) i = m.bytes (a + i) := by + apply BitVec.eq_of_getLsbD_eq + intro j hj + unfold Mem.load Mem.read SolarTV.Memory.byte + rw [BitVec.getLsbD_setWidth, BitVec.getLsbD_ushiftRight, getLsbD_foldBytes] + have e1 : (32 - 1 - (8 * (31 - i) + j) / 8) = i := by omega + have e2 : (8 * (31 - i) + j) % 8 = j := by omega + have h3 : 8 * (31 - i) + j < 256 := by omega + simp only [List.length_map, List.length_range, e1, e2, hj, h3, decide_true, Bool.true_and, + ite_true, List.getD_eq_getElem?_getD, List.getElem?_map, List.getElem?_range hi, + Option.map_some, Option.getD_some] + +/-- BYTE of a loaded word at a position below 32: the byte at that offset from the load. -/ +theorem evm_byte_load (m : Mem) (a : Nat) (k : Word) (h : k.toNat < 32) : + Evm.byte k (m.load a) = (m.bytes (a + k.toNat)).setWidth 256 := by + rw [← byte_load m a k.toNat h] + unfold Evm.byte SolarTV.Memory.byte + have hk : k.ult 32 = true := by simp [BitVec.ult, h] + have hs : (31 - k) * 8 = BitVec.ofNat 256 (8 * (31 - k.toNat)) := by + apply BitVec.eq_of_toNat_eq + have h31 : (31 : Word).toNat = 31 := rfl + have h8 : (8 : Word).toNat = 8 := rfl + simp only [BitVec.toNat_mul, BitVec.toNat_sub, BitVec.toNat_ofNat, h31, h8] + omega + have hm : (255 : Word) = BitVec.ofNat 256 (2 ^ 8 - 1) := rfl + rw [hk, Bool.cond_true, hs, hm] + apply BitVec.eq_of_getLsbD_eq + intro j hj + simp only [BitVec.getLsbD_and, BitVec.getLsbD_setWidth, BitVec.ushiftRight_eq', + BitVec.getLsbD_ushiftRight, BitVec.getLsbD_ofNat, Nat.testBit_two_pow_sub_one, + BitVec.toNat_ofNat] + have hsh : 8 * (31 - k.toNat) % 2 ^ 256 = 8 * (31 - k.toNat) := Nat.mod_eq_of_lt (by omega) + rw [hsh] + by_cases hj8 : j < 8 <;> simp [hj8, hj] + +/-! A memory expansion within one an earlier expansion already reached, as a pass that drops a +load of a word the expanded memory already covers leaves it out. -/ + +/-- Expanding memory over a range that ends within the words an expansion already made active +changes nothing. -/ +theorem expand_expand_within (m : Mem) (a s b t : Nat) (hs : s ≠ 0) + (h : (b + t + 31) / 32 ≤ (a + s + 31) / 32) (hw : (a + s + 31) / 32 < 2 ^ 251) : + (m.expand a s).expand b t = m.expand a s := by + unfold Mem.expand + simp only [hs, ite_false] + split + · rfl + · congr 1 + unfold SolarTV.Memory.grow + have hb : (b + t + 31) / 32 < 2 ^ 251 := by omega + by_cases h1 : m.words.ult (BitVec.ofNat 251 ((a + s + 31) / 32)) = true + · have h2 : (BitVec.ofNat 251 ((a + s + 31) / 32)).ult (BitVec.ofNat 251 ((b + t + 31) / 32)) + = false := by + simp only [BitVec.ult, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hw, Nat.mod_eq_of_lt hb] + exact decide_eq_false (by omega) + simp [h1, h2] + · have h1' : m.words.ult (BitVec.ofNat 251 ((a + s + 31) / 32)) = false := by simpa using h1 + have h2 : m.words.ult (BitVec.ofNat 251 ((b + t + 31) / 32)) = false := by + simp only [BitVec.ult, BitVec.toNat_ofNat, Nat.mod_eq_of_lt hw, Nat.mod_eq_of_lt hb, + decide_eq_false_iff_not, Nat.not_lt] at h1' ⊢ + omega + simp [h1', h2] + +/-- Cases that contradict each other: the words' bitwise and modular operations as +bit-vector ones, a word combined with itself or added to zero as the word it leaves, as +numbers, low masks as remainders and right shifts as quotients, then `omega`. -/ +macro "sym_omega" : tactic => `(tactic| ( + (try simp only [Evm.and, Evm.or, Evm.xor, Evm.add, Evm.sub, BitVec.xor_self, BitVec.and_self, + BitVec.or_self, BitVec.zero_add, BitVec.add_zero] at *) + -- The rewrites above may leave a false case already. + all_goals ( + (try simp -implicitDefEqProofs only [bitvec_to_nat] at *) + (try simp only [BitVec.toNat_and, toNat_shr, BitVec.toNat_ofNat, Nat.reducePow, Nat.reduceMod, + natMask] at *) + omega))) + +/-- Two words equal under the cases: with a word combined with itself or added to zero as the +word it leaves, as numbers, with low masks as remainders, right shifts as quotients and sums +under a mask as sums modulo the word size, by `omega`; else equal up to the order of the +operands of AND, OR, XOR and ADD, as the stack scheduler commutes them (`ac_rfl`). -/ +macro "sym_word" : tactic => `(tactic| ( + (try simp only [Evm.and, Evm.or, Evm.xor, Evm.add, Evm.sub, BitVec.xor_self, BitVec.and_self, + BitVec.or_self, BitVec.zero_add, BitVec.add_zero] at *) + -- A byte of a loaded word as the byte at its address, once the addresses are numerals. + (try simp (disch := decide) only [evm_byte_load, BitVec.reduceToNat, Nat.reduceAdd] at *) + -- The rewrites above may close the equation already. + all_goals first + | (apply BitVec.eq_of_toNat_eq + (try simp -implicitDefEqProofs only [bitvec_to_nat] at *) + (try simp only [BitVec.toNat_and, BitVec.toNat_add, toNat_shr, toNat_shl, BitVec.toNat_ofNat, Nat.reducePow, + Nat.reduceMod, natMask] at *) + omega) + | with_reducible ac_rfl)) + +open Lean Meta Elab Tactic in +/-- A proof that two ends are equal where they differ only in words: a parallel walk of both +terms that keeps what they share, proves each pair of differing words with `sym_word`, and +puts the proof together by congruence. -/ +partial def agree (a b : Expr) : TacticM Expr := do + -- Annotations, such as a case's, are no part of the terms. + let a := a.consumeMData + let b := b.consumeMData + if a == b then return ← mkEqRefl a + let ty ← whnfR (← inferType a) + if ty.isAppOfArity ``BitVec 1 then + let m ← mkFreshExprSyntheticOpaqueMVar (← mkEq a b) + -- Without error recovery, so that a pair it cannot prove fails rather than closes with an + -- error's `sorry`. + let rest ← Tactic.run m.mvarId! (withoutRecover (evalTactic (← `(tactic| sym_word)))) + let proof ← instantiateMVars m + unless rest.isEmpty && !proof.hasSorry do + throwError "sym_agree: cannot prove the words equal:{indentExpr a}\nand{indentExpr b}" + return proof + match a, b with + | .app f x, .app g y => + if x == y then return ← mkCongrFun (← agree f g) x + let hx ← agree x y + if f == g then return ← mkCongrArg f hx + mkCongr (← agree f g) hx + | _, _ => + if ← withReducible (isDefEq a b) then return ← mkEqRefl a + throwError "sym_agree: the ends differ beyond words:{indentExpr a}\nand{indentExpr b}" + +open Lean Meta Elab Tactic in +/-- Closes an equation of two ends that differ only in words a pass rewrote, as in an e-graph +or CSE stage, each pair proved equal from the cases. -/ +elab "sym_agree" : tactic => withMainContext do + let goal ← getMainGoal + let some (_, l, r) := (← instantiateMVars (← goal.getType)).consumeMData.eq? + | throwError "sym_agree: the goal is not an equation" + goal.assign (← agree l r) + replaceMainGoal [] + +/-- Two ends that differ in a select's arithmetic or in the order of a commutative operation's +operands, as stack scheduling may compute them: the tests the cases decide as their words, the +arithmetic on zero and one as the arm it picks, and the operands of additions, products and +bitwise operations in one order. -/ +macro "sym_select" : tactic => `(tactic| ( + (try simp (disch := first | assumption | (apply Classical.not_not.mp; assumption)) + only [lt_of_case, lt_of_not_case, gt_of_case, gt_of_not_case, eq_of_case, eq_of_not_case, + iszero_of_case, iszero_of_not_case, mul_word_one, mul_one_word, mul_word_zero, + mul_zero_word, add_sub_word, add_word_zero, add_zero_word]) + (try simp only [Evm.add, Evm.mul, Evm.and, Evm.or, Evm.xor, BitVec.add_comm, BitVec.mul_comm, + BitVec.and_comm, BitVec.or_comm, BitVec.xor_comm]) + all_goals first + | with_reducible rfl + | sym_agree)) + +/-- The proposition a hypothesis denies, for `¬ p` and `a ≠ b`. -/ +def deniedProp? (ty : Lean.Expr) : Option Lean.Expr := + if let some p := ty.not? then some p.consumeMData + else if ty.isAppOfArity ``Ne 3 then + some (Lean.mkApp3 (Lean.mkConst ``Eq ty.getAppFn.constLevels!) (ty.getArg! 0) (ty.getArg! 1) + (ty.getArg! 2)) + else none + +open Lean Meta Elab Tactic in +/-- Closes a goal whose hypotheses contradict each other as they are written: `False`, a +hypothesis `a ≠ a`, or a proposition and its negation. Unlike `contradiction`, it compares +the hypotheses' terms and never reduces them, so its cost is bounded by their size: on a path +whose ends differ, `contradiction` reduced the word terms of its hypotheses to weak head +normal form for minutes (mulx's `spell-width-tests` stage with a shift edited), so that the +procedure ran out of heartbeats rather than reporting the mismatch. -/ +elab "sym_absurd" : tactic => withMainContext do + let goal ← getMainGoal + let target ← instantiateMVars (← goal.getType) + let mut props : Array (Expr × Expr) := #[] + for decl in ← getLCtx do + if decl.isImplementationDetail then continue + props := props.push (decl.toExpr, (← instantiateMVars decl.type).consumeMData) + for (h, ty) in props do + if ty.isConstOf ``False then + goal.assign (← mkFalseElim target h) + replaceMainGoal [] + return + let some p := deniedProp? ty | continue + if let some (_, a, b) := p.eq? then + if a.consumeMData == b.consumeMData then + -- h rfl : False + goal.assign (← mkFalseElim target (mkApp h (← mkEqRefl a))) + replaceMainGoal [] + return + for (h', ty') in props do + if ty' == p then + -- absurd h' h + goal.assign (← mkAbsurd target h' h) + replaceMainGoal [] + return + throwError "sym_absurd: no two hypotheses contradict each other" + +open Lean Meta Elab Tactic in +/-- Orients the equations among the hypotheses as `split_cond` orients a positive case, so +that `simp_all` rewrites with them towards an end: an equation whose left side occurs in its +right side, or whose left side is closed and right side open, turns round, and a doubly +negated equation becomes the equation. `split_cond` leaves the case that a negated equation +fails as `¬¬(a = b)`; `simp_all` reads it as `a = b`, and for a word equal to its masked +self (`x = x &&& 255`, as `masks` tests a narrow argument) rewrote `x` into its mask +without end, so that an edited stage ran out of recursion depth rather than reporting the +mismatch. -/ +elab "sym_orient" : tactic => withMainContext do + let mut goal ← getMainGoal + for decl in ← getLCtx do + if decl.isImplementationDetail then continue + let ty := (← instantiateMVars decl.type).consumeMData + let (eq, proof) ← match ty.not? >>= fun p => p.consumeMData.not? with + -- byContradiction h : p, for h : ¬¬p + | some p => pure (p.consumeMData, mkApp2 (mkConst ``Classical.byContradiction) p decl.toExpr) + | none => pure (ty, decl.toExpr) + let some (_, a, b) := eq.eq? | continue + let closed (e : Expr) : Bool := !e.hasFVar && !e.hasMVar + let flip := (a != b && a.occurs b) || (closed a && !closed b) + if !flip && eq == ty then continue + -- h : a = b as h : b = a + let (ty', proof') ← if flip then + goal.withContext do pure (← mkEq b a, ← mkEqSymm proof) + else pure (eq, proof) + goal := (← goal.replace decl.fvarId proof' (some ty')).mvarId + replaceMainGoal [goal] + +/-- A path whose cases contradict each other once the operands of additions, products and +bitwise operations are in one order: the stack scheduler commutes them, so the two programs' +tests of one word can differ in that order alone (`mul a b` against `mul b a`). -/ +macro "sym_comm_contra" : tactic => `(tactic| ( + (try simp only [Evm.add, Evm.mul, Evm.and, Evm.or, Evm.xor, BitVec.add_comm, BitVec.mul_comm, + BitVec.and_comm, BitVec.or_comm, BitVec.xor_comm] at *) + first + | sym_absurd + | (sym_orient; simp_all; done))) + +open Lean Meta Simp in +/-- The operands of a commutative word operation `op` in one order, the structural order of +their terms, proved by `comm`. Permutation lemmas would order them the same way for both +programs too, but `simp` compares terms for them at a cost that grows with the goal (over +100 s for one call on mulx's `spell-width-tests` stage); this compares the terms as they +are. -/ +def wordCommStep (op comm : Name) (e : Expr) : SimpM Step := do + unless e.isAppOfArity op 2 do return .continue + let a := e.appFn!.appArg! + let b := e.appArg! + unless b.lt a do return .continue + -- op a b = op b a + return .visit { expr := mkApp2 (mkConst op) b a, proof? := some (mkApp2 (mkConst comm) a b) } + +simproc_decl wordAddComm (Evm.add _ _) := wordCommStep ``Evm.add ``word_add_comm +simproc_decl wordMulComm (Evm.mul _ _) := wordCommStep ``Evm.mul ``word_mul_comm +simproc_decl wordAndComm (Evm.and _ _) := wordCommStep ``Evm.and ``word_and_comm +simproc_decl wordOrComm (Evm.or _ _) := wordCommStep ``Evm.or ``word_or_comm +simproc_decl wordXorComm (Evm.xor _ _) := wordCommStep ``Evm.xor ``word_xor_comm + +open Lean Meta Simp in +/-- `not` of a literal as the literal it leaves, as `compact-pushes` spells a wide constant +(`push 255; not` for `~0xff`), so that both programs push the same word. -/ +dsimproc_decl evmNotLit (Evm.not _) := fun e => do + let_expr Evm.not a := e | return .continue + let_expr OfNat.ofNat ty lit _ := a | return .continue + let some n := lit.rawNatLit? | return .continue + return .done (← mkNumeral ty (~~~(BitVec.ofNat 256 n)).toNat) + +/-- The definitional evaluation of both layers. -/ +macro "sym_eval" : tactic => `(tactic| + dsimp only [iterate_mk, iterate_zero, listLookup, listLength, moduleEntry, functionParams, + foldNot, foldShl, foldShr, foldAdd, foldSub, foldMul, foldAnd, foldOr, foldXor, foldLt, foldGt, + foldEq, tableEntry, + MIR.Lowered.Module.run, MIR.Lowered.moduleBlock, MIR.Lowered.segment, + MIR.Lowered.splitCall, MIR.Lowered.bindResult, MIR.Lowered.bindResults, + MIR.Lowered.bindExtras, MIR.Lowered.publishResults, MIR.Lowered.publishWords, MIR.Lowered.bindPhis, + MIR.Lowered.bindParams, MIR.Lowered.execInsts, MIR.Lowered.Operand.eval, + MIR.Lowered.Env.set, MIR.Lowered.switchTarget, MIR.Lowered.halt, MIR.Lowered.evalPure, + MIR.Lowered.lowBits, MIR.Lowered.selectWord, MIR.Lowered.Function.start, + MIR.Lowered.Module.startState, List.find?_cons, List.find?_nil, Nat.reduceBEq, + EVM.Program.run, EVM.Program.block, EVM.Program.exec, EVM.Program.stepOp, + EVM.Program.output, EVM.Program.context, EVM.stepChecked, + step_add, step_mul, step_and, step_or, step_xor, step_div, step_sdiv, step_mod, step_smod, + step_signextend, step_byte, step_shl, step_shr, step_sar, step_lt, step_gt, step_slt, step_sgt, + step_eq, step_sub, step_exp, step_addmod, step_mulmod, step_not, step_clz, step_iszero, + step_pop, step_dup, step_swap, step_calldatasize, step_returndatasize, step_push, apply_mload, + apply_mstore, apply_mstore8, apply_msize, apply_sload, apply_sstore, apply_tload, + apply_tstore, apply_calldatasize, apply_callvalue, apply_caller, apply_address, + apply_returndatasize, apply_keccak256, apply_log0, apply_log1, apply_log2, apply_log3, + apply_log4, logged, apply_gas, apply_immutable, ImmutableRead.apply, apply_codecopy, apply_create, + apply_create2, created, apply_env, apply_calldatacopy, apply_mcopy, + apply_returndatacopy, apply_call, apply_callcode, apply_delegatecall, + apply_staticcall, called, returndataSize, BitVec.reduceToNat, + List.map, List.take, List.drop, List.set, List.length, List.find?, Nat.reduceBEq, + Except.map, Option.map, + Option.isSome, Nat.reduceAdd, Nat.reduceSub, Nat.reduceMul, evmNotLit, finValue]) + +set_option hygiene false in +/-- Branch conditions as propositions, decided by the cases split so far. -/ +macro "sym_cond" : tactic => `(tactic| + simp only [*, apply_calldataload _ _ _ hcd, Mem.load_expand, Mem.load_write_of_disjoint, + Mem.expand_store, Mem.load_store_same, Mem.load_store_of_disjoint, Mem.load_initial, + State.initial_memory, BitVec.reduceEq, + cond_ne, cond_eq, cond_sub, cond_lt, cond_gt, cond_iszero, cond_or, + cond_zero_lt, cond_zero_gt, cond_zero_eq, cond_zero_ne, cond_zero_iszero, + wordAddComm, wordMulComm, wordAndComm, wordOrComm, wordXorComm, and_mask, + mask_and, caller_le_mask, immutable20_le_mask, shr160_eq_zero, zero_eq_shr160, shr_shl96, + and_self, and_true, true_and, and_false, false_and, + ite_true, ite_false, + not_false_eq_true, not_true_eq_false, Classical.not_not, ↓reduceIte, Nat.reduceGT, Nat.reduceLT, + Nat.reduceEqDiff, Nat.reduceLeDiff, Nat.reduceAdd, Nat.reduceSub, Nat.lt_irrefl, + Bool.false_eq_true, gt_iff_lt, true_or, or_true]) + +/-- A range side condition by `omega` over the offsets' `toNat`s, as `sym_omega` reads +words, failing without logging so that `simp` leaves an unproved rewrite undone. -/ +macro "sym_mem_disch_core" : tactic => `(tactic| + ((try simp only [Evm.and, Evm.or, Evm.xor, Evm.add, Evm.sub, BitVec.zero_add, BitVec.add_zero] at *) + <;> (try simp -implicitDefEqProofs only [bitvec_to_nat] at *) + <;> (try simp only [BitVec.toNat_and, toNat_shr, BitVec.toNat_ofNat, Nat.reducePow, Nat.reduceMod, + natMask] at *) + <;> omega)) + +open Lean Elab Tactic in +/-- `sym_mem_disch_core` without error recovery, so a failed side condition is a plain failure. -/ +elab "sym_mem_disch" : tactic => do withoutRecover (evalTactic (← `(tactic| sym_mem_disch_core))) + +/-- Memory at computed offsets: a read or load moves past a store, byte store or copy only +when `sym_mem_disch` proves the two ranges disjoint (or the read inside the written range) from +the cases split so far, over the offsets' `toNat`s; a range read of more than a word splits +into words, so a hash of `abi.encode` output meets the stored words. Ranges it cannot place +keep the read over the write, so both programs must build the same term there. -/ +macro "sym_mem" : tactic => `(tactic| first + | simp (disch := sym_mem_disch) only [Mem.read_expand, Mem.read_store_at, + Mem.read_store_disjoint, Mem.load_store_at, Mem.load_store_disjoint, + Mem.read_storeByte_disjoint, Mem.load_storeByte_disjoint, Mem.read_write_disjoint, + Mem.load_write_of_disjoint, Mem.read_write_same, Mem.read_write_inside, + Mem.read_copy_inside, Mem.read_store_within, Mem.read_write_within, + Mem.read_of_eq_zero, Mem.read_write_at, List.append_nil, List.nil_append, List.append_assoc] + | simp only [Mem.read_split, Nat.reduceLT, Nat.reduceLeDiff, Nat.reduceSub, Nat.reduceAdd]) + +/-- Memory in a normal form: expansions outside the stores, stores to disjoint literal words in +order of their offsets, and a store overwritten at the same offset dropped. Two runs that write +the same words in another order, or one that writes a word once more with the value it holds +(`block-cse` dropping a second `mstore(32, 0)` before a second mapping hash), then agree. Every +step is an equation on `Mem`, rewriting the goal and every hypothesis, so a path whose two +programs decided the same condition in two memory forms becomes a contradiction. -/ +macro "sym_mem_order" : tactic => `(tactic| + simp (disch := decide) only [Mem.store_expand_comm, Mem.store_store_same, Mem.expand_expand, + Mem.expand_comm, Mem.expand_store, Mem.store_store_comm] at *) + +/-- Evaluate, decide conditions and move memory reads until none changes the goal. -/ +macro "sym_norm" : tactic => `(tactic| repeat (first | sym_eval | sym_cond | sym_mem)) + +/-- Two ends that differ in addresses and memory sizes alone: one program spells an address as +the sum of numerals its pass left unfolded (`(Evm.add 32 128).toNat`) where the other has the +numeral (`160`), or expands memory over a word an earlier access already made active, as when a +pass drops a load. The addresses become numerals, the redundant expansion goes, and the words +are compared. -/ +macro "sym_expand" : tactic => `(tactic| ( + simp (disch := decide) only [expand_expand_within, Evm.add, BitVec.reduceAdd, + BitVec.reduceToNat, Nat.reduceAdd] + all_goals first + | with_reducible rfl + | sym_agree)) + +set_option hygiene false in +/-- Symbolic execution to one result: evaluate, decide what the cases decide, split on the +next condition, and close each leaf by reflexivity or a contradiction between its cases. A leaf +it cannot close fails with its goal, the two ends on that path. -/ +macro "sym_exec" : tactic => `(tactic| ( + obtain ⟨cd, hcd⟩ : ∃ cd, cd = calldataWord call := ⟨_, rfl⟩ + sym_norm + repeat' ((first | split_cond | split_table) <;> sym_norm) + all_goals first + | with_reducible rfl + | (exfalso; bv_omega) + | (exfalso; sym_omega) + | (exfalso; sym_comm_contra) + | sym_select + | sym_agree + | sym_expand + | (sym_mem_order <;> first + | with_reducible rfl + | (exfalso; bv_omega) + | (exfalso; sym_omega) + | (exfalso; sym_comm_contra) + | sym_select + | sym_agree) + | fail "sym_exec: the runs end in different results on this path, or the procedure cannot tell")) + +end SolarTV.Milestone.W1 diff --git a/tv/W1Proofs/WalkAt.lean b/tv/W1Proofs/WalkAt.lean new file mode 100644 index 00000000..7c1d019a --- /dev/null +++ b/tv/W1Proofs/WalkAt.lean @@ -0,0 +1,91 @@ +import SolarTV.Stages.AssemblyCheck + +/-! The checker's walk on the code after the offset it reached, given the code's length. + +`walk` indexes the code from its start at every instruction, so the kernel's evaluation of the +walk of a bytecode of many kilobytes takes time quadratic in its length. `walkAt` reads the +next bytes of the suffix the walk reached instead, in linear time, and `walk_of_walkAt` shows it +gives the stream `walk` gives. -/ + +namespace SolarTV.Assembly + +def decodeAt (rest : List Nat) (len pc : Nat) : Option (Instr × Nat) := + match rest with + | [] => none + | byte :: tl => + if byte = PUSH0 then some (.push 0, pc + 1) + else if PUSH1 ≤ byte ∧ byte ≤ PUSH32 then + if pc + 1 + (byte - PUSH1 + 1) ≤ len then + some (.push (bigEndian (tl.take (byte - PUSH1 + 1))), pc + 1 + (byte - PUSH1 + 1)) + else none + else if hasImmediate byte then + match tl with + | imm :: _ => if immediateOk byte imm then some (.opImm byte imm, pc + 2) else none + | [] => none + else some (.op byte, pc + 1) + +theorem decodeAt_eq (code : List Nat) (pc : Nat) : + decodeAt (code.drop pc) code.length pc = decode code pc := by + unfold decodeAt decode + cases h : code.drop pc with + | nil => + have : code.length ≤ pc := List.drop_eq_nil_iff.mp h + simp [List.getElem?_eq_none this] + | cons byte tl => + have h0 : code[pc]? = some byte := by + have := congrArg (·[0]?) h + simpa [List.getElem?_drop] using this + have h1 : code.drop (pc + 1) = tl := by + rw [← List.drop_drop, h]; rfl + have h2 : code[pc + 1]? = tl[0]? := by + rw [← h1, List.getElem?_drop] + simp only [h0, h1, h2] + cases tl <;> rfl + + +def Item.placedAt (rest : List Nat) (offset : Nat → Nat) (pc : Nat) : Item → Bool + | .immutable _ bytes => + decide (1 ≤ bytes) && decide (bytes ≤ 32) && rest.head? == some (PUSH1 + bytes - 1) + | item => item.placed [] offset pc + +theorem Item.placedAt_eq (code : List Nat) (offset : Nat → Nat) (pc : Nat) (item : Item) : + item.placedAt (code.drop pc) offset pc = item.placed code offset pc := by + cases item <;> simp [Item.placedAt, Item.placed, List.head?_drop] + +def walkAt (len : Nat) (offset : Nat → Nat) : + Nat → List Nat → List Item → Option (List (Nat × Instr)) + | pc, _, [] => if pc = len then some [] else none + | pc, rest, item :: items => + match decodeAt rest len pc with + | none => none + | some (instr, next) => + if instr = item.expected offset ∧ item.placedAt rest offset pc = true then + match walkAt len offset next (rest.drop (next - pc)) items with + | some tail => some ((pc, instr) :: tail) + | none => none + else none + +theorem walkAt_eq (code : List Nat) (offset : Nat → Nat) : + ∀ (pc : Nat) (items : List Item), + walkAt code.length offset pc (code.drop pc) items = walk code offset pc items + | pc, [] => by simp [walkAt, walk] + | pc, item :: items => by + simp only [walkAt, walk, decodeAt_eq, Item.placedAt_eq] + cases hd : decode code pc with + | none => rfl + | some r => + obtain ⟨instr, next⟩ := r + have lt := decode_advances hd + have hdrop : (code.drop pc).drop (next - pc) = code.drop next := by + rw [List.drop_drop]; congr 1; omega + simp only [hdrop, walkAt_eq code offset next items] + rfl + +theorem walk_of_walkAt {code : List Nat} {len : Nat} (hl : code.length = len) + {offset : Nat → Nat} {items : List Item} {stream : List (Nat × Instr)} + (h : walkAt len offset 0 code items = some stream) : walk code offset 0 items = some stream := by + subst hl + rw [← walkAt_eq] + simpa using h + +end SolarTV.Assembly diff --git a/vendor/README.md b/vendor/README.md new file mode 100644 index 00000000..fd2b0fa6 --- /dev/null +++ b/vendor/README.md @@ -0,0 +1,21 @@ +# Vendored dependencies + +Ports of two dependencies to Lean 4.35 and Mathlib v4.35.0, which EthLib needs. +Only the modules SolidCore imports are kept. + +| Directory | Upstream | Commit | +|---|---|---| +| `evmyul/` | https://github.com/danrobinson/EVMYulLean | `b08573c65e33feb5331abe2b7c1d76be89bb8eff` | +| `evm-interaction/` | https://github.com/danrobinson/evm-interaction | `c939817c55f966dab97e1ba8df05ceca1fdfbdb2` | + +The port changes only what Lean 4.35 rejects: + +* Batteries moved `RBMap`, `RBSet` and `RBNode` from `Batteries` to `RBTree`. +* `EvmYul.toExecute` matches on the operation type and the account map together, + so the match refines the map's type. +* Two proofs in `EvmInteraction.Simulation.OpenWorld` (`extCodeHash_evm`, + `sstore_eq`) close goals that Lean 4.35's `simp` and matchers leave open. +* `evmyul`'s lakefile pins the SHA-2 and Keccak C sources it clones, and no longer + initializes the EthereumTests submodule. + +Once the upstream repositories move to Lean 4.35, require them from git again. diff --git a/vendor/evm-interaction/EvmInteraction.lean b/vendor/evm-interaction/EvmInteraction.lean new file mode 100644 index 00000000..43dd9247 --- /dev/null +++ b/vendor/evm-interaction/EvmInteraction.lean @@ -0,0 +1,15 @@ +/- +`evm-interaction`: the standalone language-of-composition package. + +Verbatim extraction of evm-compiler's `EvmCompiler.Simulation.*` framework +(the free interaction monad, `Query`/`Answer`, `OpenWorld`, `ForwardRel` and its +composition lemmas). The `EvmCompiler.Simulation.*` namespaces and declaration +names are preserved so evm-compiler's frozen theorem statements stay textually +unchanged; since 2026-07-09 evm-compiler consumes this package directly (its +local copies are deleted), so this IS the single source. Module paths live +under `EvmInteraction.*` (namespaces unchanged) so the root `EvmCompiler` lib +prefix of evm-compiler does not claim them. Depends only on the pinned EVMYulLean + Mathlib. +-/ +import EvmInteraction.Simulation.Interaction +import EvmInteraction.Simulation.OpenWorld +import EvmInteraction.Simulation.Outcome diff --git a/vendor/evm-interaction/EvmInteraction/Simulation/Interaction.lean b/vendor/evm-interaction/EvmInteraction/Simulation/Interaction.lean new file mode 100644 index 00000000..ce76cc38 --- /dev/null +++ b/vendor/evm-interaction/EvmInteraction/Simulation/Interaction.lean @@ -0,0 +1,2579 @@ +import EvmInteraction.Simulation.OpenWorld +import EvmYul.Data.Stack +import EvmYul.MachineStateOps +import EvmYul.Operations + +namespace EvmCompiler +namespace Simulation + +abbrev InteractionWord := EvmYul.UInt256 +abbrev InteractionAddress := EvmYul.AccountAddress +abbrev InteractionStack := EvmYul.Stack InteractionWord + +inductive CallKind where + | call + | callcode + | delegatecall + | staticcall + deriving DecidableEq, Repr + +namespace CallKind + +def toYulOperation : CallKind → EvmYul.Operation .Yul + | .call => .System .CALL + | .callcode => .System .CALLCODE + | .delegatecall => .System .DELEGATECALL + | .staticcall => .System .STATICCALL + +def toEVMOperation : CallKind → EvmYul.Operation .EVM + | .call => .CALL + | .callcode => .CALLCODE + | .delegatecall => .DELEGATECALL + | .staticcall => .STATICCALL + +def ofYulOperation? : EvmYul.Operation .Yul → Option CallKind + | .System .CALL => some .call + | .System .CALLCODE => some .callcode + | .System .DELEGATECALL => some .delegatecall + | .System .STATICCALL => some .staticcall + | _ => none + +def ofEVMOperation? : EvmYul.Operation .EVM → Option CallKind + | .CALL => some .call + | .CALLCODE => some .callcode + | .DELEGATECALL => some .delegatecall + | .STATICCALL => some .staticcall + | _ => none + +def inputArity : CallKind → Nat + | .call | .callcode => 7 + | .delegatecall | .staticcall => 6 + +@[simp] theorem ofYulOperation?_toYulOperation (kind : CallKind) : + ofYulOperation? kind.toYulOperation = some kind := by + cases kind <;> rfl + +@[simp] theorem ofEVMOperation?_toEVMOperation (kind : CallKind) : + ofEVMOperation? kind.toEVMOperation = some kind := by + cases kind <;> rfl + +end CallKind + +inductive CreateKind where + | create + | create2 + deriving DecidableEq, Repr + +namespace CreateKind + +def toYulOperation : CreateKind → EvmYul.Operation .Yul + | .create => .System .CREATE + | .create2 => .System .CREATE2 + +def toEVMOperation : CreateKind → EvmYul.Operation .EVM + | .create => .CREATE + | .create2 => .CREATE2 + +def ofYulOperation? : EvmYul.Operation .Yul → Option CreateKind + | .System .CREATE => some .create + | .System .CREATE2 => some .create2 + | _ => none + +def ofEVMOperation? : EvmYul.Operation .EVM → Option CreateKind + | .CREATE => some .create + | .CREATE2 => some .create2 + | _ => none + +def inputArity : CreateKind → Nat + | .create => 3 + | .create2 => 4 + +@[simp] theorem ofYulOperation?_toYulOperation (kind : CreateKind) : + ofYulOperation? kind.toYulOperation = some kind := by + cases kind <;> rfl + +@[simp] theorem ofEVMOperation?_toEVMOperation (kind : CreateKind) : + ofEVMOperation? kind.toEVMOperation = some kind := by + cases kind <;> rfl + +end CreateKind + +/-- The complete opcode family that suspends at the open-world boundary. -/ +inductive ExternalKind where + | call : CallKind → ExternalKind + | create : CreateKind → ExternalKind + deriving DecidableEq, Repr + +namespace ExternalKind + +def toYulOperation : ExternalKind → EvmYul.Operation .Yul + | .call kind => kind.toYulOperation + | .create kind => kind.toYulOperation + +def toEVMOperation : ExternalKind → EvmYul.Operation .EVM + | .call kind => kind.toEVMOperation + | .create kind => kind.toEVMOperation + +def ofYulOperation? (op : EvmYul.Operation .Yul) : Option ExternalKind := + match CallKind.ofYulOperation? op with + | some kind => some (.call kind) + | none => (CreateKind.ofYulOperation? op).map .create + +def ofEVMOperation? (op : EvmYul.Operation .EVM) : Option ExternalKind := + match CallKind.ofEVMOperation? op with + | some kind => some (.call kind) + | none => (CreateKind.ofEVMOperation? op).map .create + +@[simp] theorem ofYulOperation?_toYulOperation (kind : ExternalKind) : + ofYulOperation? kind.toYulOperation = some kind := by + cases kind with + | call kind => cases kind <;> rfl + | create kind => cases kind <;> rfl + +theorem eq_toYulOperation_of_ofYulOperation?_eq_some + {op : EvmYul.Operation .Yul} {kind : ExternalKind} + (hKind : ofYulOperation? op = some kind) : + op = kind.toYulOperation := by + cases op <;> rename_i family <;> cases family <;> + simp [ofYulOperation?, CallKind.ofYulOperation?, + CreateKind.ofYulOperation?] at hKind + all_goals subst kind <;> rfl + +@[simp] theorem ofEVMOperation?_toEVMOperation (kind : ExternalKind) : + ofEVMOperation? kind.toEVMOperation = some kind := by + cases kind with + | call kind => cases kind <;> rfl + | create kind => cases kind <;> rfl + +@[simp] theorem classifies_call : + ofEVMOperation? EvmYul.Operation.CALL = + some (.call .call) := rfl + +@[simp] theorem classifies_callcode : + ofEVMOperation? EvmYul.Operation.CALLCODE = + some (.call .callcode) := rfl + +@[simp] theorem classifies_delegatecall : + ofEVMOperation? EvmYul.Operation.DELEGATECALL = + some (.call .delegatecall) := rfl + +@[simp] theorem classifies_staticcall : + ofEVMOperation? EvmYul.Operation.STATICCALL = + some (.call .staticcall) := rfl + +@[simp] theorem classifies_create : + ofEVMOperation? EvmYul.Operation.CREATE = + some (.create .create) := rfl + +@[simp] theorem classifies_create2 : + ofEVMOperation? EvmYul.Operation.CREATE2 = + some (.create .create2) := rfl + +end ExternalKind + +structure CallRequest where + kind : CallKind + requestedGas : InteractionWord + caller : InteractionAddress + recipient : InteractionAddress + codeAddress : InteractionAddress + transferValue : InteractionWord + apparentValue : InteractionWord + calldata : ByteArray + permission : Bool + +structure CallLocal where + inputOffset : InteractionWord + inputSize : InteractionWord + outputOffset : InteractionWord + outputSize : InteractionWord + +structure CreateRequest where + kind : CreateKind + creator : InteractionAddress + value : InteractionWord + initCode : ByteArray + salt : Option InteractionWord + permission : Bool + +structure CreateLocal where + initOffset : InteractionWord + initSize : InteractionWord + +structure CallOperands where + requestedGas : InteractionWord + address : InteractionWord + valueArg : InteractionWord + inputOffset : InteractionWord + inputSize : InteractionWord + outputOffset : InteractionWord + outputSize : InteractionWord + +namespace CallOperands + +def callLocal (operands : CallOperands) : CallLocal where + inputOffset := operands.inputOffset + inputSize := operands.inputSize + outputOffset := operands.outputOffset + outputSize := operands.outputSize + +end CallOperands + +structure CreateOperands where + value : InteractionWord + initOffset : InteractionWord + initSize : InteractionWord + saltArg : InteractionWord + +namespace CreateOperands + +def createLocal (operands : CreateOperands) : CreateLocal where + initOffset := operands.initOffset + initSize := operands.initSize + +end CreateOperands + +/-- Protected caller-frame data needed to normalize an external request. -/ +structure ExternalFrame where + machine : EvmYul.MachineState + codeOwner : InteractionAddress + source : InteractionAddress + apparentCallValue : InteractionWord + permission : Bool + +namespace ExternalFrame + +def ofShared {τ : EvmYul.OperationType} + (state : EvmYul.SharedState τ) : ExternalFrame where + machine := state.toMachineState + codeOwner := state.executionEnv.codeOwner + source := state.executionEnv.source + apparentCallValue := state.executionEnv.weiValue + permission := state.executionEnv.perm + +def calldata (frame : ExternalFrame) (callLocal : CallLocal) : ByteArray := + frame.machine.memory.readWithPadding + callLocal.inputOffset.toNat callLocal.inputSize.toNat + +def initCode (frame : ExternalFrame) (createLocal : CreateLocal) : ByteArray := + frame.machine.memory.readWithPadding + createLocal.initOffset.toNat createLocal.initSize.toNat + +def callRequest (frame : ExternalFrame) + (kind : CallKind) (operands : CallOperands) : CallRequest := + let target := EvmYul.AccountAddress.ofUInt256 operands.address + let callLocal := operands.callLocal + match kind with + | .call => + { kind := kind + requestedGas := operands.requestedGas + caller := frame.codeOwner + recipient := target + codeAddress := target + transferValue := operands.valueArg + apparentValue := operands.valueArg + calldata := frame.calldata callLocal + permission := frame.permission } + | .callcode => + { kind := kind + requestedGas := operands.requestedGas + caller := frame.codeOwner + recipient := frame.codeOwner + codeAddress := target + transferValue := operands.valueArg + apparentValue := operands.valueArg + calldata := frame.calldata callLocal + permission := frame.permission } + | .delegatecall => + { kind := kind + requestedGas := operands.requestedGas + caller := frame.source + recipient := frame.codeOwner + codeAddress := target + transferValue := EvmYul.UInt256.ofNat 0 + apparentValue := frame.apparentCallValue + calldata := frame.calldata callLocal + permission := frame.permission } + | .staticcall => + { kind := kind + requestedGas := operands.requestedGas + caller := frame.codeOwner + recipient := target + codeAddress := target + transferValue := EvmYul.UInt256.ofNat 0 + apparentValue := EvmYul.UInt256.ofNat 0 + calldata := frame.calldata callLocal + permission := false } + +def createRequest (frame : ExternalFrame) + (kind : CreateKind) (operands : CreateOperands) : CreateRequest := + { kind := kind + creator := frame.codeOwner + value := operands.value + initCode := frame.initCode operands.createLocal + salt := + match kind with + | .create => none + | .create2 => some operands.saltArg + permission := frame.permission } + +end ExternalFrame + +namespace CallKind + +def canonicalOperands : CallKind → CallOperands → CallOperands + | .call, operands => operands + | .callcode, operands => operands + | .delegatecall, operands => + { operands with valueArg := EvmYul.UInt256.ofNat 0 } + | .staticcall, operands => + { operands with valueArg := EvmYul.UInt256.ofNat 0 } + +def args : CallKind → CallOperands → List InteractionWord + | .call, operands + | .callcode, operands => + [operands.requestedGas, operands.address, operands.valueArg, + operands.inputOffset, operands.inputSize, operands.outputOffset, + operands.outputSize] + | .delegatecall, operands + | .staticcall, operands => + [operands.requestedGas, operands.address, operands.inputOffset, + operands.inputSize, operands.outputOffset, operands.outputSize] + +@[simp] theorem args_length (kind : CallKind) (operands : CallOperands) : + (kind.args operands).length = kind.inputArity := by + cases kind <;> rfl + +def evmOperands? : + CallKind → InteractionStack → + Option (InteractionStack × CallOperands) + | .call, stack => + match stack.pop7 with + | some ⟨rest, gas, address, value, inputOffset, inputSize, + outputOffset, outputSize⟩ => + some + (rest, + { requestedGas := gas + address := address + valueArg := value + inputOffset := inputOffset + inputSize := inputSize + outputOffset := outputOffset + outputSize := outputSize }) + | none => none + | .callcode, stack => + match stack.pop7 with + | some ⟨rest, gas, address, value, inputOffset, inputSize, + outputOffset, outputSize⟩ => + some + (rest, + { requestedGas := gas + address := address + valueArg := value + inputOffset := inputOffset + inputSize := inputSize + outputOffset := outputOffset + outputSize := outputSize }) + | none => none + | .delegatecall, stack => + match stack.pop6 with + | some ⟨rest, gas, address, inputOffset, inputSize, + outputOffset, outputSize⟩ => + some + (rest, + { requestedGas := gas + address := address + valueArg := EvmYul.UInt256.ofNat 0 + inputOffset := inputOffset + inputSize := inputSize + outputOffset := outputOffset + outputSize := outputSize }) + | none => none + | .staticcall, stack => + match stack.pop6 with + | some ⟨rest, gas, address, inputOffset, inputSize, + outputOffset, outputSize⟩ => + some + (rest, + { requestedGas := gas + address := address + valueArg := EvmYul.UInt256.ofNat 0 + inputOffset := inputOffset + inputSize := inputSize + outputOffset := outputOffset + outputSize := outputSize }) + | none => none + +@[simp] theorem evmOperands?_args + (kind : CallKind) (operands : CallOperands) + (rest : InteractionStack) : + kind.evmOperands? (kind.args operands ++ rest) = + some (rest, kind.canonicalOperands operands) := by + cases kind <;> rfl + +/-- +Appending an opaque suffix below a complete CALL-family operand prefix leaves +the parsed operands unchanged and appends the suffix only to the remainder. +-/ +theorem evmOperands?_append_of_some + (kind : CallKind) {stack rest : InteractionStack} + {operands : CallOperands} (hidden : InteractionStack) + (hOperands : + kind.evmOperands? stack = some (rest, operands)) : + kind.evmOperands? (stack ++ hidden) = + some (rest ++ hidden, operands) := by + cases kind with + | call | callcode => + unfold evmOperands? at hOperands ⊢ + cases hPop : stack.pop7 with + | none => + simp [hPop] at hOperands + | some popped => + rcases popped with + ⟨parsedRest, gas, address, value, inputOffset, inputSize, + outputOffset, outputSize⟩ + have hAppend : + (stack ++ hidden).pop7 = + some + (parsedRest ++ hidden, gas, address, value, + inputOffset, inputSize, outputOffset, outputSize) := by + cases stack with + | nil => simp [EvmYul.Stack.pop7] at hPop + | cons a stack => + cases stack with + | nil => simp [EvmYul.Stack.pop7] at hPop + | cons b stack => + cases stack with + | nil => simp [EvmYul.Stack.pop7] at hPop + | cons c stack => + cases stack with + | nil => simp [EvmYul.Stack.pop7] at hPop + | cons d stack => + cases stack with + | nil => simp [EvmYul.Stack.pop7] at hPop + | cons e stack => + cases stack with + | nil => simp [EvmYul.Stack.pop7] at hPop + | cons f stack => + cases stack with + | nil => + simp [EvmYul.Stack.pop7] at hPop + | cons g tail => + simp [EvmYul.Stack.pop7] at hPop ⊢ + rcases hPop with + ⟨rfl, rfl, rfl, rfl, rfl, rfl, + rfl, rfl⟩ + simp + simp [hPop] at hOperands + rcases hOperands with ⟨rfl, rfl⟩ + simp [hAppend] + | delegatecall | staticcall => + unfold evmOperands? at hOperands ⊢ + cases hPop : stack.pop6 with + | none => + simp [hPop] at hOperands + | some popped => + rcases popped with + ⟨parsedRest, gas, address, inputOffset, inputSize, + outputOffset, outputSize⟩ + have hAppend : + (stack ++ hidden).pop6 = + some + (parsedRest ++ hidden, gas, address, inputOffset, + inputSize, outputOffset, outputSize) := by + cases stack with + | nil => simp [EvmYul.Stack.pop6] at hPop + | cons a stack => + cases stack with + | nil => simp [EvmYul.Stack.pop6] at hPop + | cons b stack => + cases stack with + | nil => simp [EvmYul.Stack.pop6] at hPop + | cons c stack => + cases stack with + | nil => simp [EvmYul.Stack.pop6] at hPop + | cons d stack => + cases stack with + | nil => simp [EvmYul.Stack.pop6] at hPop + | cons e stack => + cases stack with + | nil => simp [EvmYul.Stack.pop6] at hPop + | cons f tail => + simp [EvmYul.Stack.pop6] at hPop ⊢ + rcases hPop with + ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩ + simp + simp [hPop] at hOperands + rcases hOperands with ⟨rfl, rfl⟩ + simp [hAppend] + +/-- +Intrinsic static-mode legality checked by the suspended caller before an +external request is exposed. +-/ +def allowedIn (kind : CallKind) (frame : ExternalFrame) + (operands : CallOperands) : Bool := + match kind with + | .call => + frame.permission || + operands.valueArg == EvmYul.UInt256.ofNat 0 + | .callcode | .delegatecall | .staticcall => true + +end CallKind + +namespace CreateKind + +def canonicalOperands : CreateKind → CreateOperands → CreateOperands + | .create, operands => + { operands with saltArg := EvmYul.UInt256.ofNat 0 } + | .create2, operands => operands + +def args : CreateKind → CreateOperands → List InteractionWord + | .create, operands => + [operands.value, operands.initOffset, operands.initSize] + | .create2, operands => + [operands.value, operands.initOffset, operands.initSize, + operands.saltArg] + +@[simp] theorem args_length (kind : CreateKind) (operands : CreateOperands) : + (kind.args operands).length = kind.inputArity := by + cases kind <;> rfl + +def evmOperands? : + CreateKind → InteractionStack → + Option (InteractionStack × CreateOperands) + | .create, stack => + match stack.pop3 with + | some ⟨rest, value, initOffset, initSize⟩ => + some + (rest, + { value := value + initOffset := initOffset + initSize := initSize + saltArg := EvmYul.UInt256.ofNat 0 }) + | none => none + | .create2, stack => + match stack.pop4 with + | some ⟨rest, value, initOffset, initSize, salt⟩ => + some + (rest, + { value := value + initOffset := initOffset + initSize := initSize + saltArg := salt }) + | none => none + +@[simp] theorem evmOperands?_args + (kind : CreateKind) (operands : CreateOperands) + (rest : InteractionStack) : + kind.evmOperands? (kind.args operands ++ rest) = + some (rest, kind.canonicalOperands operands) := by + cases kind <;> rfl + +/-- +Appending an opaque suffix below a complete CREATE-family operand prefix +leaves the parsed operands unchanged and appends the suffix only to the +remainder. +-/ +theorem evmOperands?_append_of_some + (kind : CreateKind) {stack rest : InteractionStack} + {operands : CreateOperands} (hidden : InteractionStack) + (hOperands : + kind.evmOperands? stack = some (rest, operands)) : + kind.evmOperands? (stack ++ hidden) = + some (rest ++ hidden, operands) := by + cases kind with + | create => + unfold evmOperands? at hOperands ⊢ + cases hPop : stack.pop3 with + | none => + simp [hPop] at hOperands + | some popped => + rcases popped with + ⟨parsedRest, value, inputOffset, inputSize⟩ + have hAppend : + (stack ++ hidden).pop3 = + some + (parsedRest ++ hidden, value, inputOffset, inputSize) := by + cases stack with + | nil => simp [EvmYul.Stack.pop3] at hPop + | cons a stack => + cases stack with + | nil => simp [EvmYul.Stack.pop3] at hPop + | cons b stack => + cases stack with + | nil => simp [EvmYul.Stack.pop3] at hPop + | cons c tail => + simp [EvmYul.Stack.pop3] at hPop ⊢ + rcases hPop with ⟨rfl, rfl, rfl, rfl⟩ + simp + simp [hPop] at hOperands + rcases hOperands with ⟨rfl, rfl⟩ + simp [hAppend] + | create2 => + unfold evmOperands? at hOperands ⊢ + cases hPop : stack.pop4 with + | none => + simp [hPop] at hOperands + | some popped => + rcases popped with + ⟨parsedRest, value, inputOffset, inputSize, salt⟩ + have hAppend : + (stack ++ hidden).pop4 = + some + (parsedRest ++ hidden, value, inputOffset, inputSize, + salt) := by + cases stack with + | nil => simp [EvmYul.Stack.pop4] at hPop + | cons a stack => + cases stack with + | nil => simp [EvmYul.Stack.pop4] at hPop + | cons b stack => + cases stack with + | nil => simp [EvmYul.Stack.pop4] at hPop + | cons c stack => + cases stack with + | nil => simp [EvmYul.Stack.pop4] at hPop + | cons d tail => + simp [EvmYul.Stack.pop4] at hPop ⊢ + rcases hPop with ⟨rfl, rfl, rfl, rfl, rfl⟩ + simp + simp [hPop] at hOperands + rcases hOperands with ⟨rfl, rfl⟩ + simp [hAppend] + +end CreateKind + +inductive ResourceQuery where + | gas + | msize + deriving DecidableEq, Repr + +inductive ExternalRequest where + | call : CallRequest → ExternalRequest + | create : CreateRequest → ExternalRequest + +inductive Query where + | resource : ResourceQuery → Query + | external : OpenWorld → ExternalRequest → Query + +structure CallResponse where + success : Bool + returnData : ByteArray + postWorld : OpenWorld + returnedGas : InteractionWord + +namespace CallResponse + +def statusWord (response : CallResponse) : InteractionWord := + if response.success then + EvmYul.UInt256.ofNat 1 + else + EvmYul.UInt256.ofNat 0 + +end CallResponse + +structure CreateResponse where + address : InteractionWord + returnData : ByteArray + postWorld : OpenWorld + returnedGas : InteractionWord + +namespace CallLocal + +def finishMachine (callLocal : CallLocal) (machine : EvmYul.MachineState) + (returnData : ByteArray) : EvmYul.MachineState := + machine.finishExternalCall returnData + callLocal.inputOffset callLocal.inputSize + callLocal.outputOffset callLocal.outputSize + +end CallLocal + +namespace CreateLocal + +def finishMachine (createLocal : CreateLocal) (machine : EvmYul.MachineState) + (returnData : ByteArray) : EvmYul.MachineState := + machine.finishExternalCall returnData + createLocal.initOffset createLocal.initSize + (EvmYul.UInt256.ofNat 0) (EvmYul.UInt256.ofNat 0) + +end CreateLocal + +def Answer : Query → Type + | .resource _ => InteractionWord + | .external _ (.call _) => CallResponse + | .external _ (.create _) => CreateResponse + +/-- One canonical answer used only to select a branch of an open interaction +tree. Compiler theorems still quantify over every answer through `AllDone`. -/ +def Query.defaultAnswer : (query : Query) → Answer query + | .resource _ => EvmYul.UInt256.ofNat 0 + | .external world (.call _) => + { success := false, returnData := default, postWorld := world, + returnedGas := EvmYul.UInt256.ofNat 0 } + | .external world (.create _) => + { address := EvmYul.UInt256.ofNat 0, returnData := default, + postWorld := world, returnedGas := EvmYul.UInt256.ofNat 0 } + +universe u1 v1 u2 v2 u3 v3 w1 w2 + +/-- +The one ordered carrier for resource observations and open-world effects. +-/ +inductive Interaction (Error : Type u1) (Result : Type v1) : + Type (max u1 v1) where + | done : Except Error Result → Interaction Error Result + | request : + (query : Query) → + (Answer query → Interaction Error Result) → + Interaction Error Result + +namespace Interaction + +/-- One exact query/answer exchange along a concrete interaction branch. -/ +structure Exchange where + query : Query + answer : Answer query + +abbrev Transcript := List Exchange + +/-- A concrete ordered transcript is a prefix of an interaction tree. Unlike +`Executes`, this relation need not end at a terminal leaf. -/ +inductive Follows {Error : Type u1} {Result : Type v1} : + Interaction Error Result → Transcript → Prop where + | nil (interaction : Interaction Error Result) : Follows interaction [] + | request {query : Query} + {resume : Answer query → Interaction Error Result} + {answer : Answer query} {transcript : Transcript} : + Follows (resume answer) transcript → + Follows (.request query resume) + ({ query := query, answer := answer } :: transcript) + +def pure {Error : Type u1} {Result : Type v1} + (value : Result) : Interaction Error Result := + .done (.ok value) + +def error {Error : Type u1} {Result : Type v1} + (err : Error) : Interaction Error Result := + .done (.error err) + +def bind {Error : Type u1} {Source : Type v1} {Target : Type w1} + (result : Interaction Error Source) + (next : Source → Interaction Error Target) : + Interaction Error Target := + match result with + | .done (.ok value) => next value + | .done (.error err) => .done (.error err) + | .request query resume => + .request query fun answer => bind (resume answer) next + +def map {Error : Type u1} {Source : Type v1} {Target : Type w1} + (f : Source → Target) (result : Interaction Error Source) : + Interaction Error Target := + bind result fun value => pure (f value) + +def tryCatch {Error : Type u1} {Result : Type v1} + (result : Interaction Error Result) + (handler : Error → Interaction Error Result) : + Interaction Error Result := + match result with + | .done (.error err) => handler err + | .done (.ok value) => .done (.ok value) + | .request query resume => + .request query fun answer => tryCatch (resume answer) handler + +instance {Error : Type u1} : Monad (Interaction Error) where + pure := pure + bind := bind + map := map + +instance {Error : Type u1} : MonadExceptOf Error (Interaction Error) where + throw := error + tryCatch := tryCatch + +/-- +A property of every terminal leaf of an open interaction tree. + +Unlike a concrete execution transcript, `AllDone` quantifies over every +possible answer at every request. Pass proofs use it for branch-independent +invariants such as program-counter advancement. +-/ +inductive AllDone + {Error : Type u1} {Result : Type v1} + (property : Except Error Result → Prop) : + Interaction Error Result → Prop where + | done {outcome} : + property outcome → + AllDone property (.done outcome) + | request {query : Query} + {resume : Answer query → Interaction Error Result} : + (∀ answer, AllDone property (resume answer)) → + AllDone property (.request query resume) + +namespace AllDone + +/-- A universal terminal property in particular holds on the canonical branch. +This eliminates no open-world quantification; it merely witnesses that an +interaction tree has a terminal leaf. -/ +theorem exists_done + {Error : Type u1} {Result : Type v1} + {property : Except Error Result → Prop} + {interaction : Interaction Error Result} + (hAll : AllDone property interaction) : + ∃ outcome, property outcome := by + induction interaction with + | done outcome => + cases hAll with + | done hProperty => exact ⟨outcome, hProperty⟩ + | request query resume ih => + cases hAll with + | request hResume => + exact ih query.defaultAnswer (hResume query.defaultAnswer) + +theorem trivial + {Error : Type u1} {Result : Type v1} + (interaction : Interaction Error Result) : + AllDone (fun _ => True) interaction := by + induction interaction with + | done outcome => + exact .done True.intro + | request query resume ih => + exact .request ih + +/-- Intersect two leaf properties over the same open interaction tree. -/ +theorem inter + {Error : Type u1} {Result : Type v1} + {left right : Except Error Result → Prop} + {interaction : Interaction Error Result} + (hLeft : AllDone left interaction) + (hRight : AllDone right interaction) : + AllDone (fun outcome => left outcome ∧ right outcome) interaction := by + induction hLeft with + | done hLeftDone => + cases hRight with + | done hRightDone => exact .done ⟨hLeftDone, hRightDone⟩ + | request hLeftResume ih => + cases hRight with + | request hRightResume => + exact .request fun answer => ih answer (hRightResume answer) + +theorem mono + {Error : Type u1} {Result : Type v1} + {left right : Except Error Result → Prop} + {interaction : Interaction Error Result} + (hInteraction : AllDone left interaction) + (hProperty : ∀ outcome, left outcome → right outcome) : + AllDone right interaction := by + induction hInteraction with + | done hDone => + exact .done (hProperty _ hDone) + | request hResume ih => + exact .request ih + +theorem bind + {Error : Type u1} {Source : Type v1} {Target : Type w1} + {sourceProperty : Except Error Source → Prop} + {targetProperty : Except Error Target → Prop} + {interaction : Interaction Error Source} + {next : Source → Interaction Error Target} + (hInteraction : AllDone sourceProperty interaction) + (hError : + ∀ err, sourceProperty (.error err) → + targetProperty (.error err)) + (hNext : + ∀ value, sourceProperty (.ok value) → + AllDone targetProperty (next value)) : + AllDone targetProperty (Interaction.bind interaction next) := by + induction hInteraction with + | @done outcome hDone => + cases outcome with + | error err => + exact .done (hError err hDone) + | ok value => + exact hNext value hDone + | request hResume ih => + exact .request ih + +theorem map + {Error : Type u1} {Source : Type v1} {Target : Type w1} + {sourceProperty : Except Error Source → Prop} + {targetProperty : Except Error Target → Prop} + {interaction : Interaction Error Source} + (f : Source → Target) + (hInteraction : AllDone sourceProperty interaction) + (hError : + ∀ err, sourceProperty (.error err) → + targetProperty (.error err)) + (hValue : + ∀ value, sourceProperty (.ok value) → + targetProperty (.ok (f value))) : + AllDone targetProperty (Interaction.map f interaction) := by + exact + bind hInteraction hError fun value hSource => + .done (hValue value hSource) + +/-- +Two continuations are interchangeable when they agree at every successful +leaf reachable from the first interaction. +-/ +theorem bind_congr + {Error : Type u1} {Source : Type v1} {Target : Type w1} + {property : Except Error Source → Prop} + {interaction : Interaction Error Source} + {left right : Source → Interaction Error Target} + (hInteraction : AllDone property interaction) + (hNext : + ∀ value, property (.ok value) → + left value = right value) : + Interaction.bind interaction left = + Interaction.bind interaction right := by + induction interaction generalizing left right with + | done outcome => + cases hInteraction with + | done hDone => + cases outcome with + | error err => + rfl + | ok value => + exact hNext value hDone + | request query resume ih => + cases hInteraction with + | request hResume => + change + Interaction.request query + (fun answer => + Interaction.bind (resume answer) left) = + Interaction.request query + (fun answer => + Interaction.bind (resume answer) right) + congr + funext answer + exact ih answer (hResume answer) hNext + +/-- Invert a terminal property through a bind into its reachable continuations. -/ +theorem bind_inv + {Error : Type u1} {Source : Type v1} {Target : Type w1} + {targetProperty : Except Error Target → Prop} + {interaction : Interaction Error Source} + {next : Source → Interaction Error Target} + (hResult : AllDone targetProperty (Interaction.bind interaction next)) : + AllDone + (fun outcome => + match outcome with + | .error err => targetProperty (.error err) + | .ok value => AllDone targetProperty (next value)) + interaction := by + induction interaction with + | done outcome => + cases outcome with + | error err => + cases hResult with + | done hDone => exact .done hDone + | ok value => + exact .done hResult + | request query resume ih => + cases hResult with + | request hResume => + exact .request fun answer => ih answer (hResume answer) + +end AllDone + +/-- Every open-world terminal branch returns successfully. -/ +def Successful + {Error : Type u1} {Result : Type v1} + (interaction : Interaction Error Result) : Prop := + AllDone + (fun outcome => + match outcome with + | .error _ => False + | .ok _ => True) + interaction + +namespace Successful + +theorem bind_inv + {Error : Type u1} {Source : Type v1} {Target : Type w1} + {interaction : Interaction Error Source} + {next : Source → Interaction Error Target} + (hResult : Successful (Interaction.bind interaction next)) : + AllDone + (fun outcome => + match outcome with + | .error _ => False + | .ok value => Successful (next value)) + interaction := + AllDone.bind_inv hResult + +/-- Successful continuation execution implies that the bound prefix itself +has no failing open-world branch. -/ +theorem bind_left + {Error : Type u1} {Source : Type v1} {Target : Type w1} + {interaction : Interaction Error Source} + {next : Source → Interaction Error Target} + (hResult : Successful (Interaction.bind interaction next)) : + Successful interaction := by + apply AllDone.mono (bind_inv hResult) + intro outcome hOutcome + cases outcome with + | error _ => exact hOutcome + | ok _ => trivial + +theorem error_false + {Error : Type u1} {Result : Type v1} (err : Error) + (hResult : Successful (Interaction.error (Result := Result) err)) : + False := by + cases hResult with + | done hDone => exact hDone + +end Successful + +@[simp] theorem bind_done_ok + {Error : Type u1} {Source : Type v1} {Target : Type w1} + (value : Source) (next : Source → Interaction Error Target) : + bind (.done (.ok value)) next = next value := rfl + +@[simp] theorem bind_done_error + {Error : Type u1} {Source : Type v1} {Target : Type w1} + (err : Error) (next : Source → Interaction Error Target) : + bind (.done (.error err)) next = + (.done (.error err) : Interaction Error Target) := rfl + +theorem bind_request + {Error : Type u1} {Source : Type v1} {Target : Type w1} + (query : Query) + (resume : Answer query → Interaction Error Source) + (next : Source → Interaction Error Target) : + bind (.request query resume) next = + .request query fun answer => bind (resume answer) next := rfl + +@[simp] theorem bind_pure + {Error : Type u1} {Result : Type v1} + (result : Interaction Error Result) : + bind result pure = result := by + induction result with + | done outcome => + cases outcome <;> rfl + | request query resume ih => + simp only [bind_request] + congr + funext answer + exact ih answer + +theorem bind_assoc + {Error : Type u1} {First : Type v1} + {Second : Type w1} {Third : Type u2} + (result : Interaction Error First) + (next : First → Interaction Error Second) + (finish : Second → Interaction Error Third) : + bind (bind result next) finish = + bind result fun value => bind (next value) finish := by + induction result with + | done outcome => + cases outcome <;> rfl + | request query resume ih => + simp only [bind_request] + congr + funext answer + exact ih answer + +@[simp] theorem monad_pure_bind + {Error : Type u1} {Source Target : Type v1} + (value : Source) (next : Source → Interaction Error Target) : + (do + let source ← (pure value : Interaction Error Source) + next source) = + next value := rfl + +@[simp] theorem monad_error_bind + {Error : Type u1} {Source Target : Type v1} + (err : Error) (next : Source → Interaction Error Target) : + (do + let source ← (error err : Interaction Error Source) + next source) = + error err := rfl + +@[simp] theorem monad_bind_pure + {Error : Type u1} {Result : Type v1} + (result : Interaction Error Result) : + (do + let value ← result + pure value) = + result := by + exact bind_pure result + +/-- +A concrete branch through an open interaction tree. + +The transcript records the exact ordered query and answer at every suspension. +It is external-world behavior, not compiler-generated evidence. +-/ +inductive Executes + {Error : Type u1} {Result : Type v1} : + Interaction Error Result → + Transcript → + Except Error Result → + Prop where + | done (outcome : Except Error Result) : + Executes (.done outcome) [] outcome + | request {query : Query} + {resume : Answer query → Interaction Error Result} + (answer : Answer query) + {transcript : Transcript} + {outcome : Except Error Result} + (tail : Executes (resume answer) transcript outcome) : + Executes (.request query resume) + ({ query := query, answer := answer } :: transcript) outcome + +namespace Executes + +/-- Every terminal execution also witnesses its transcript as a prefix. -/ +theorem follows + {Error : Type u1} {Result : Type v1} + {interaction : Interaction Error Result} + {transcript : Transcript} {outcome : Except Error Result} + (hExec : Executes interaction transcript outcome) : + Follows interaction transcript := by + induction hExec with + | done outcome => exact .nil _ + | request answer tail ih => exact .request ih + +theorem bind_ok + {Error : Type u1} {Source : Type v1} {Target : Type w1} + {first : Interaction Error Source} + {next : Source → Interaction Error Target} + {firstTranscript restTranscript : Transcript} + {value : Source} {outcome : Except Error Target} + (hFirst : Executes first firstTranscript (.ok value)) + (hRest : Executes (next value) restTranscript outcome) : + Executes (bind first next) + (firstTranscript ++ restTranscript) outcome := by + generalize hOutcome : (.ok value : Except Error Source) = firstOutcome + at hFirst + induction hFirst generalizing value restTranscript outcome with + | done firstOutcome => + cases hOutcome + simpa using hRest + | request answer tail ih => + simpa [bind_request] using + Executes.request answer (ih hRest hOutcome) + +theorem bind_error + {Error : Type u1} {Source : Type v1} {Target : Type w1} + {first : Interaction Error Source} + {next : Source → Interaction Error Target} + {transcript : Transcript} {err : Error} + (hFirst : Executes first transcript (.error err)) : + Executes (bind first next) transcript (.error err) := by + generalize hOutcome : (.error err : Except Error Source) = firstOutcome + at hFirst + induction hFirst generalizing err with + | done firstOutcome => + cases hOutcome + exact Executes.done (.error err) + | request answer tail ih => + simpa [bind_request] using + Executes.request answer (ih hOutcome) + +theorem bind_cases + {Error : Type u1} {Source : Type v1} {Target : Type w1} + {first : Interaction Error Source} + {next : Source → Interaction Error Target} + {transcript : Transcript} {outcome : Except Error Target} + (hExec : Executes (bind first next) transcript outcome) : + (∃ err, + outcome = .error err ∧ + Executes first transcript (.error err)) ∨ + ∃ value firstTranscript restTranscript, + transcript = firstTranscript ++ restTranscript ∧ + Executes first firstTranscript (.ok value) ∧ + Executes (next value) restTranscript outcome := by + induction first generalizing transcript outcome with + | done firstOutcome => + cases firstOutcome with + | error err => + change Executes (.done (.error err)) transcript outcome at hExec + cases hExec + exact .inl ⟨err, rfl, Executes.done _⟩ + | ok value => + exact + .inr + ⟨value, [], transcript, by simp, Executes.done _, hExec⟩ + | request query resume ih => + change + Executes + (.request query fun answer => bind (resume answer) next) + transcript outcome at hExec + cases hExec with + | request answer tail => + rcases ih answer tail with hError | hOk + · rcases hError with ⟨err, hOutcome, hFirst⟩ + exact + .inl + ⟨err, hOutcome, Executes.request answer hFirst⟩ + · rcases hOk with + ⟨value, firstTranscript, restTranscript, + hTranscript, hFirst, hRest⟩ + exact + .inr + ⟨value, + { query := query, answer := answer } :: firstTranscript, + restTranscript, + by simp [hTranscript], + Executes.request answer hFirst, + hRest⟩ + +end Executes + +namespace Follows + +/-- Binding after an interaction cannot erase an already exposed transcript. -/ +theorem bind + {Error : Type u1} {Source : Type v1} {Target : Type w1} + {first : Interaction Error Source} + {next : Source -> Interaction Error Target} + {transcript : Transcript} + (hFollow : Follows first transcript) : + Follows (Interaction.bind first next) transcript := by + induction hFollow with + | nil interaction => exact .nil _ + | request tail ih => exact .request ih + +/-- A completed left side followed by a prefix of its continuation yields the +concatenated prefix of the monadic bind. -/ +theorem bind_ok + {Error : Type u1} {Source : Type v1} {Target : Type w1} + {first : Interaction Error Source} + {next : Source -> Interaction Error Target} + {firstTranscript restTranscript : Transcript} + {value : Source} + (hFirst : Executes first firstTranscript (.ok value)) + (hRest : Follows (next value) restTranscript) : + Follows (Interaction.bind first next) + (firstTranscript ++ restTranscript) := by + generalize hOutcome : (.ok value : Except Error Source) = firstOutcome + at hFirst + induction hFirst generalizing value restTranscript with + | done firstOutcome => + cases hOutcome + simpa using hRest + | request answer tail ih => + exact .request (ih hRest hOutcome) + +/-- Invert one followed request at its first exchange. -/ +theorem request_inv + {Error : Type u1} {Result : Type v1} + {query : Query} + {resume : Answer query -> Interaction Error Result} + {exchange : Exchange} {transcript : Transcript} + (hFollow : Follows (.request query resume) (exchange :: transcript)) : + exists answer, + exchange = { query := query, answer := answer } /\ + Follows (resume answer) transcript := by + cases hFollow with + | request tail => exact ⟨_, rfl, tail⟩ + +/-- A followed prefix can always be extended to one complete concrete branch +by selecting default answers after the prefix. -/ +theorem exists_executes_extension + {Error : Type u1} {Result : Type v1} + {interaction : Interaction Error Result} + {head : Transcript} + (hFollow : Follows interaction head) : + ∃ suffix outcome, + Executes interaction (head ++ suffix) outcome := by + induction hFollow with + | nil interaction => + induction interaction with + | done outcome => + exact ⟨[], outcome, Executes.done outcome⟩ + | request query resume ih => + obtain ⟨suffix, outcome, hExec⟩ := ih query.defaultAnswer + exact + ⟨{ query := query, answer := query.defaultAnswer } :: suffix, + outcome, Executes.request query.defaultAnswer hExec⟩ + | @request query resume answer transcript hTail ih => + obtain ⟨suffix, outcome, hExec⟩ := ih + exact ⟨suffix, outcome, by simpa using Executes.request answer hExec⟩ + +/-- Forget a suffix from an already followed transcript. -/ +theorem prefix_of_append + {Error : Type u1} {Result : Type v1} + {interaction : Interaction Error Result} + (head suffix : Transcript) + (hFollow : Follows interaction (head ++ suffix)) : + Follows interaction head := by + induction head generalizing interaction with + | nil => exact .nil interaction + | cons exchange head ih => + cases interaction with + | done outcome => cases hFollow + | request query resume => + obtain ⟨answer, hExchange, hTail⟩ := request_inv hFollow + subst exchange + exact .request (ih hTail) + +end Follows + +namespace AllDone + +/-- Select one concrete branch witnessing a universal terminal property. -/ +theorem exists_executes + {Error : Type u1} {Result : Type v1} + {property : Except Error Result -> Prop} + {interaction : Interaction Error Result} + (hAll : AllDone property interaction) : + exists transcript outcome, + Executes interaction transcript outcome /\ property outcome := by + induction hAll with + | done hProperty => + exact ⟨[], _, Executes.done _, hProperty⟩ + | @request query resume hResume ih => + obtain ⟨transcript, outcome, hExec, hProperty⟩ := + ih query.defaultAnswer + exact + ⟨{ query := query, answer := query.defaultAnswer } :: transcript, + outcome, Executes.request query.defaultAnswer hExec, hProperty⟩ + +/-- A property of every terminal leaf holds on any selected concrete branch. -/ +theorem property_of_executes + {Error : Type u1} {Result : Type v1} + {property : Except Error Result -> Prop} + {interaction : Interaction Error Result} + {transcript : Transcript} {outcome : Except Error Result} + (hAll : AllDone property interaction) + (hExec : Executes interaction transcript outcome) : + property outcome := by + induction hExec with + | done outcome => + cases hAll with + | done hProperty => exact hProperty + | @request query resume answer transcript outcome hTail ih => + cases hAll with + | request hResume => exact ih (hResume answer) + +end AllDone + +namespace Executes + +/-- Invert one concrete execution of a request at its first exchange. -/ +theorem request_inv + {Error : Type u1} {Result : Type v1} + {query : Query} + {resume : Answer query -> Interaction Error Result} + {exchange : Exchange} {transcript : Transcript} + {outcome : Except Error Result} + (hExec : + Executes (.request query resume) (exchange :: transcript) outcome) : + exists answer, + exchange = { query := query, answer := answer } /\ + Executes (resume answer) transcript outcome := by + cases hExec with + | request answer tail => + exact ⟨answer, rfl, tail⟩ + +end Executes + +inductive ExceptRel + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + (errorRel : Error₁ → Error₂ → Prop) + (resultRel : Result₁ → Result₂ → Prop) : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop where + | error {left right} : + errorRel left right → + ExceptRel errorRel resultRel (.error left) (.error right) + | ok {left right} : + resultRel left right → + ExceptRel errorRel resultRel (.ok left) (.ok right) + +/-- +Structural open-world equivalence. Related computations expose the exact same +query and remain related for every exact shared answer. +-/ +inductive Rel + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + (doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop) : + Interaction Error₁ Result₁ → + Interaction Error₂ Result₂ → Prop where + | done {left right} : + doneRel left right → + Rel doneRel (.done left) (.done right) + | request {query} {left right} : + (∀ answer, Rel doneRel (left answer) (right answer)) → + Rel doneRel (.request query left) (.request query right) + +namespace Rel + +theorem refl + {Error : Type u1} {Result : Type v1} + {doneRel : + Except Error Result → Except Error Result → Prop} + (hDone : ∀ result, doneRel result result) + (interaction : Interaction Error Result) : + Rel doneRel interaction interaction := by + induction interaction with + | done result => + exact .done (hDone result) + | request query resume ih => + exact .request ih + +theorem mono + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {doneRel₁ doneRel₂ : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + (hRel : Rel doneRel₁ left right) + (hDone : + ∀ leftDone rightDone, + doneRel₁ leftDone rightDone → + doneRel₂ leftDone rightDone) : + Rel doneRel₂ left right := by + induction hRel with + | done hResult => + exact .done (hDone _ _ hResult) + | request hResume ih => + exact .request ih + +/-- Intersect two proofs over the same open interaction tree. -/ +theorem inter + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {doneRel₁ doneRel₂ : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + (hFirst : Rel doneRel₁ left right) + (hSecond : Rel doneRel₂ left right) : + Rel (fun leftDone rightDone => + doneRel₁ leftDone rightDone ∧ doneRel₂ leftDone rightDone) + left right := by + induction hFirst with + | done hFirstDone => + cases hSecond with + | done hSecondDone => exact .done ⟨hFirstDone, hSecondDone⟩ + | request hFirstResume ih => + cases hSecond with + | request hSecondResume => + exact .request fun answer => + ih answer (hSecondResume answer) + +theorem strengthen_left + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {property : Except Error₁ Result₁ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + (hRel : Rel doneRel left right) + (hAll : AllDone property left) : + Rel (fun leftDone rightDone => + doneRel leftDone rightDone ∧ property leftDone) + left right := by + induction hRel with + | done hDone => + cases hAll with + | done hProperty => + exact .done ⟨hDone, hProperty⟩ + | request hResume ih => + cases hAll with + | request hProperty => + exact .request fun answer => + ih answer (hProperty answer) + +/-- Strengthen a relation with a target-side invariant at every terminal +leaf. -/ +theorem strengthen_right + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {property : Except Error₂ Result₂ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + (hRel : Rel doneRel left right) + (hAll : AllDone property right) : + Rel (fun leftDone rightDone => + doneRel leftDone rightDone ∧ property rightDone) + left right := by + induction hRel with + | done hDone => + cases hAll with + | done hProperty => exact .done ⟨hDone, hProperty⟩ + | request hResume ih => + cases hAll with + | request hProperty => + exact .request fun answer => ih answer (hProperty answer) + +theorem allDone_right + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {property : Except Error₂ Result₂ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + (hRel : Rel doneRel left right) + (hDone : + ∀ leftDone rightDone, + doneRel leftDone rightDone → + property rightDone) : + AllDone property right := by + induction hRel with + | done hRelated => + exact .done (hDone _ _ hRelated) + | request hResume ih => + exact .request ih + +theorem symm + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + (hRel : Rel doneRel left right) : + Rel (fun rightDone leftDone => doneRel leftDone rightDone) + right left := by + induction hRel with + | done hDone => + exact .done hDone + | request hResume ih => + exact .request ih + +theorem trans + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {Error₃ : Type u3} {Result₃ : Type v3} + {doneRel₁₂ : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {doneRel₂₃ : + Except Error₂ Result₂ → Except Error₃ Result₃ → Prop} + {left : Interaction Error₁ Result₁} + {middle : Interaction Error₂ Result₂} + {right : Interaction Error₃ Result₃} + (hLeft : Rel doneRel₁₂ left middle) + (hRight : Rel doneRel₂₃ middle right) : + Rel + (fun leftDone rightDone => + ∃ middleDone, + doneRel₁₂ leftDone middleDone ∧ + doneRel₂₃ middleDone rightDone) + left right := by + induction hLeft generalizing right with + | done hDone => + cases hRight with + | done hRightDone => + exact .done ⟨_, hDone, hRightDone⟩ + | request hResume ih => + cases hRight with + | request hRightResume => + exact .request fun answer => + ih answer (hRightResume answer) + +/-- Compose through a representation-transparent right boundary. -/ +theorem trans_eq_right + {Error1 : Type u1} {Result1 : Type v1} + {Error2 : Type u2} {Result2 : Type v2} + {doneRel : + Except Error1 Result1 -> Except Error2 Result2 -> Prop} + {left : Interaction Error1 Result1} + {middle right : Interaction Error2 Result2} + (hLeft : Rel doneRel left middle) + (hRight : Rel Eq middle right) : + Rel doneRel left right := by + apply Rel.mono (Rel.trans hLeft hRight) + intro leftDone rightDone hDone + rcases hDone with ⟨middleDone, hRelated, hEq⟩ + subst rightDone + exact hRelated + +theorem bind + {Error₁ : Type u1} {Source₁ : Type v1} {Target₁ : Type w1} + {Error₂ : Type u2} {Source₂ : Type v2} {Target₂ : Type w2} + {errorRel : Error₁ → Error₂ → Prop} + {sourceRel : Source₁ → Source₂ → Prop} + {targetRel : Target₁ → Target₂ → Prop} + {left : Interaction Error₁ Source₁} + {right : Interaction Error₂ Source₂} + {leftNext : Source₁ → Interaction Error₁ Target₁} + {rightNext : Source₂ → Interaction Error₂ Target₂} + (hResult : + Rel (ExceptRel errorRel sourceRel) left right) + (hNext : + ∀ leftValue rightValue, + sourceRel leftValue rightValue → + Rel (ExceptRel errorRel targetRel) + (leftNext leftValue) (rightNext rightValue)) : + Rel (ExceptRel errorRel targetRel) + (Interaction.bind left leftNext) + (Interaction.bind right rightNext) := by + induction hResult with + | done hDone => + cases hDone with + | error hError => + exact .done (.error hError) + | ok hValue => + exact hNext _ _ hValue + | request hResume ih => + exact .request fun answer => ih answer + +theorem bind_custom + {Error₁ : Type u1} {Source₁ : Type v1} {Target₁ : Type w1} + {Error₂ : Type u2} {Source₂ : Type v2} {Target₂ : Type w2} + {sourceDoneRel : + Except Error₁ Source₁ → Except Error₂ Source₂ → Prop} + {targetDoneRel : + Except Error₁ Target₁ → Except Error₂ Target₂ → Prop} + {left : Interaction Error₁ Source₁} + {right : Interaction Error₂ Source₂} + {leftNext : Source₁ → Interaction Error₁ Target₁} + {rightNext : Source₂ → Interaction Error₂ Target₂} + (hResult : Rel sourceDoneRel left right) + (hNext : + ∀ leftDone rightDone, + sourceDoneRel leftDone rightDone → + Rel targetDoneRel + (match leftDone with + | .error error => .done (.error error) + | .ok value => leftNext value) + (match rightDone with + | .error error => .done (.error error) + | .ok value => rightNext value)) : + Rel targetDoneRel + (Interaction.bind left leftNext) + (Interaction.bind right rightNext) := by + induction hResult with + | @done leftDone rightDone hDone => + cases leftDone <;> cases rightDone <;> + simpa [Interaction.bind] using + hNext _ _ hDone + | request hResume ih => + exact .request fun answer => ih answer + +/-- Remove a pure administrative map from the left side of a relation. -/ +theorem bind_pure_left_inv + {Error₁ : Type u1} {Source₁ : Type v1} {Target₁ : Type w1} + {Error₂ : Type u2} {Result₂ : Type v2} + {doneRel : + Except Error₁ Target₁ → Except Error₂ Result₂ → Prop} + {left : Interaction Error₁ Source₁} + {right : Interaction Error₂ Result₂} + {f : Source₁ → Target₁} + (hRel : + Rel doneRel + (Interaction.bind left + (fun value => Interaction.pure (f value))) + right) : + Rel + (fun leftDone rightDone => + match leftDone with + | .error err => doneRel (.error err) rightDone + | .ok value => doneRel (.ok (f value)) rightDone) + left right := by + induction left generalizing right with + | done outcome => + cases outcome with + | error err => + cases hRel with + | done hDone => exact .done hDone + | ok value => + cases hRel with + | done hDone => exact .done hDone + | request query resume ih => + cases hRel with + | request hResume => + exact .request fun answer => ih answer (hResume answer) + +theorem done_left + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {leftDone : Except Error₁ Result₁} + {right : Interaction Error₂ Result₂} + (hRel : Rel doneRel (.done leftDone) right) : + ∃ rightDone, + right = .done rightDone ∧ doneRel leftDone rightDone := by + cases hRel with + | done hDone => + exact ⟨_, rfl, hDone⟩ + +theorem request_left + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {query : Query} + {left : Answer query → Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + (hRel : Rel doneRel (.request query left) right) : + ∃ rightResume : Answer query → Interaction Error₂ Result₂, + right = .request query rightResume ∧ + ∀ answer, Rel doneRel (left answer) (rightResume answer) := by + cases hRel with + | request hResume => + exact ⟨_, rfl, hResume⟩ + +/-- +Reconstruct a structural open-world relation from exact preservation of every +successful concrete branch. Universal source success rules out the only missing +case: a source error leaf, for which the branch premise intentionally has no +obligation. +-/ +theorem of_successful_executes + {Error1 : Type u1} {Result1 : Type v1} + {Error2 : Type u2} {Result2 : Type v2} + {doneRel : + Except Error1 Result1 -> Except Error2 Result2 -> Prop} + {left : Interaction Error1 Result1} + {right : Interaction Error2 Result2} + (hSuccessful : Successful left) + (hExec : + forall transcript leftResult, + Executes left transcript (.ok leftResult) -> + exists rightDone, + Executes right transcript rightDone /\ + doneRel (.ok leftResult) rightDone) : + Rel doneRel left right := by + induction left generalizing right with + | done leftDone => + cases leftDone with + | error err => + exact False.elim (Successful.error_false err hSuccessful) + | ok value => + obtain ⟨rightDone, hRightExec, hDone⟩ := + hExec [] value (Executes.done (.ok value)) + cases hRightExec with + | done => exact .done hDone + | request query resume ih => + cases hSuccessful with + | request hResumeSuccessful => + cases right with + | done rightDone => + obtain + ⟨tailTranscript, leftDone, hLeftTail, hLeftSuccess⟩ := + AllDone.exists_executes + (hResumeSuccessful query.defaultAnswer) + cases leftDone with + | error err => exact False.elim hLeftSuccess + | ok value => + obtain ⟨targetDone, hTargetExec, _hDone⟩ := + hExec + ({ query := query, answer := query.defaultAnswer } :: + tailTranscript) + value + (Executes.request query.defaultAnswer hLeftTail) + cases hTargetExec + | request targetQuery targetResume => + obtain + ⟨tailTranscript, leftDone, hLeftTail, hLeftSuccess⟩ := + AllDone.exists_executes + (hResumeSuccessful query.defaultAnswer) + cases leftDone with + | error err => exact False.elim hLeftSuccess + | ok value => + obtain ⟨targetDone, hTargetExec, _hDone⟩ := + hExec + ({ query := query, answer := query.defaultAnswer } :: + tailTranscript) + value + (Executes.request query.defaultAnswer hLeftTail) + obtain ⟨targetAnswer, hExchange, _hTargetTail⟩ := + Executes.request_inv hTargetExec + have hQuery : query = targetQuery := + congrArg Exchange.query hExchange + subst targetQuery + exact .request fun answer => by + apply ih answer (hResumeSuccessful answer) + intro transcript leftResult hLeftExec + obtain ⟨rightDone, hRightExec, hDone⟩ := + hExec + ({ query := query, answer := answer } :: transcript) + leftResult + (Executes.request answer hLeftExec) + obtain ⟨rightAnswer, hHead, hRightTail⟩ := + Executes.request_inv hRightExec + cases hHead + exact ⟨rightDone, hRightTail, hDone⟩ + +/-- Reconstruct a structural open-world relation from exact preservation of +every concrete branch, including error outcomes. -/ +theorem of_executes + {Error1 : Type u1} {Result1 : Type v1} + {Error2 : Type u2} {Result2 : Type v2} + {doneRel : + Except Error1 Result1 -> Except Error2 Result2 -> Prop} + {left : Interaction Error1 Result1} + {right : Interaction Error2 Result2} + (hExec : + forall transcript leftDone, + Executes left transcript leftDone -> + exists rightDone, + Executes right transcript rightDone /\ + doneRel leftDone rightDone) : + Rel doneRel left right := by + induction left generalizing right with + | done leftDone => + obtain ⟨rightDone, hRightExec, hDone⟩ := + hExec [] leftDone (Executes.done leftDone) + cases hRightExec with + | done => exact .done hDone + | request query resume ih => + cases right with + | done rightDone => + obtain ⟨tailTranscript, leftDone, hLeftTail, _⟩ := + AllDone.exists_executes + (AllDone.trivial (resume query.defaultAnswer)) + obtain ⟨targetDone, hTargetExec, _hDone⟩ := + hExec + ({ query := query, answer := query.defaultAnswer } :: + tailTranscript) + leftDone + (Executes.request query.defaultAnswer hLeftTail) + cases hTargetExec + | request targetQuery targetResume => + obtain ⟨tailTranscript, leftDone, hLeftTail, _⟩ := + AllDone.exists_executes + (AllDone.trivial (resume query.defaultAnswer)) + obtain ⟨targetDone, hTargetExec, _hDone⟩ := + hExec + ({ query := query, answer := query.defaultAnswer } :: + tailTranscript) + leftDone + (Executes.request query.defaultAnswer hLeftTail) + obtain ⟨targetAnswer, hExchange, _hTargetTail⟩ := + Executes.request_inv hTargetExec + have hQuery : query = targetQuery := + congrArg Exchange.query hExchange + subst targetQuery + exact .request fun answer => by + apply ih answer + intro transcript leftDone hLeftExec + obtain ⟨rightDone, hRightExec, hDone⟩ := + hExec + ({ query := query, answer := answer } :: transcript) + leftDone + (Executes.request answer hLeftExec) + obtain ⟨rightAnswer, hHead, hRightTail⟩ := + Executes.request_inv hRightExec + cases hHead + exact ⟨rightDone, hRightTail, hDone⟩ + +/-- +Structural open equivalence transports every concrete external-world branch +with the exact same ordered transcript. +-/ +theorem executes + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + {transcript : Transcript} + {leftOutcome : Except Error₁ Result₁} + (hRel : Rel doneRel left right) + (hExec : Executes left transcript leftOutcome) : + ∃ rightOutcome, + Executes right transcript rightOutcome ∧ + doneRel leftOutcome rightOutcome := by + induction hExec generalizing right with + | done outcome => + cases hRel with + | done hDone => + exact ⟨_, Executes.done _, hDone⟩ + | request answer tail ih => + cases hRel with + | request hResume => + obtain ⟨rightOutcome, hRight, hDone⟩ := + ih (hResume answer) + exact + ⟨rightOutcome, Executes.request answer hRight, hDone⟩ + +end Rel + +/-- +Forward open-world refinement with an explicit source-side truncation error. + +Before truncation, the source and target expose the exact same query and all +exact shared answers remain related. A truncated source computation carries no +claim about the target suffix. This is the appropriate relation for +fuel-indexed source semantics when compiler expansion changes the amount of +target fuel needed to realize one source control step. +-/ +inductive ForwardRel + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + (truncated : Error₁ → Prop) + (doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop) : + Interaction Error₁ Result₁ → + Interaction Error₂ Result₂ → Prop where + | truncated {error : Error₁} + {right : Interaction Error₂ Result₂} : + truncated error → + ForwardRel truncated doneRel (.done (.error error)) right + | done {left : Except Error₁ Result₁} + {right : Except Error₂ Result₂} : + doneRel left right → + ForwardRel truncated doneRel (.done left) (.done right) + | request {query : Query} + {left : Answer query → Interaction Error₁ Result₁} + {right : Answer query → Interaction Error₂ Result₂} : + (∀ answer, + ForwardRel truncated doneRel (left answer) (right answer)) → + ForwardRel truncated doneRel + (.request query left) (.request query right) + +namespace ForwardRel + +/-- Execute one source branch of a forward refinement. A truncated branch +retains its exact target transcript prefix; every other branch reaches a +related target leaf. -/ +theorem executes_or_follows + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {truncated : Error₁ → Prop} + {doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + {transcript : Transcript} + {leftDone : Except Error₁ Result₁} + (hRel : ForwardRel truncated doneRel left right) + (hExec : Executes left transcript leftDone) : + (∃ error, + leftDone = .error error ∧ truncated error ∧ + Follows right transcript) ∨ + ∃ rightDone, + Executes right transcript rightDone ∧ doneRel leftDone rightDone := by + induction hExec generalizing right with + | done outcome => + cases hRel with + | truncated hTruncated => + exact .inl ⟨_, rfl, hTruncated, .nil _⟩ + | done hDone => + exact .inr ⟨_, Executes.done _, hDone⟩ + | @request query resume answer transcript outcome hTail ih => + cases hRel with + | request hResume => + rcases ih (hResume answer) with hTruncated | hDone + · rcases hTruncated with + ⟨error, hError, hTruncated, hFollow⟩ + exact .inl + ⟨error, hError, hTruncated, Follows.request hFollow⟩ + · rcases hDone with ⟨rightDone, hRight, hRelated⟩ + exact .inr + ⟨rightDone, Executes.request answer hRight, hRelated⟩ + +/-- +Reconstruct source-truncating forward refinement from concrete branches. + +A non-truncated source branch must execute to a related target outcome. A +truncated source branch only requires its exact ordered transcript to remain a +prefix of the target interaction. This is the branchwise interface needed when +the compiler gives the target more fuel than the source. +-/ +theorem of_executes_or_follows + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {truncated : Error₁ -> Prop} + {doneRel : + Except Error₁ Result₁ -> Except Error₂ Result₂ -> Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + (hBranches : + forall transcript leftDone, + Executes left transcript leftDone -> + (exists error, + leftDone = .error error /\ + truncated error /\ Follows right transcript) \/ + exists rightDone, + Executes right transcript rightDone /\ + doneRel leftDone rightDone) : + ForwardRel truncated doneRel left right := by + induction left generalizing right with + | done leftDone => + rcases hBranches [] leftDone (Executes.done leftDone) with + hTruncated | hDone + · obtain ⟨error, hError, hTruncated, _hFollow⟩ := hTruncated + subst leftDone + exact .truncated hTruncated + · obtain ⟨rightDone, hRight, hDone⟩ := hDone + cases hRight with + | done => exact .done hDone + | request query resume ih => + cases right with + | done rightDone => + obtain ⟨transcript, leftDone, hLeft, _⟩ := + AllDone.exists_executes + (AllDone.trivial (resume query.defaultAnswer)) + rcases hBranches + ({ query := query, answer := query.defaultAnswer } :: transcript) + leftDone + (Executes.request query.defaultAnswer hLeft) with + hTruncated | hDone + · obtain ⟨_error, _hError, _hTruncated, hFollow⟩ := hTruncated + cases hFollow + · obtain ⟨_rightDone, hRight, _hDone⟩ := hDone + cases hRight + | request targetQuery targetResume => + obtain ⟨transcript, leftDone, hLeft, _⟩ := + AllDone.exists_executes + (AllDone.trivial (resume query.defaultAnswer)) + have hQuery : query = targetQuery := by + rcases hBranches + ({ query := query, answer := query.defaultAnswer } :: transcript) + leftDone + (Executes.request query.defaultAnswer hLeft) with + hTruncated | hDone + · obtain ⟨_error, _hError, _hTruncated, hFollow⟩ := hTruncated + obtain ⟨_answer, hHead, _hTail⟩ := + Follows.request_inv hFollow + exact congrArg Exchange.query hHead + · obtain ⟨_rightDone, hRight, _hDone⟩ := hDone + obtain ⟨_answer, hHead, _hTail⟩ := + Executes.request_inv hRight + exact congrArg Exchange.query hHead + subst targetQuery + exact .request fun answer => by + apply ih answer + intro tailTranscript tailDone hTail + rcases hBranches + ({ query := query, answer := answer } :: tailTranscript) + tailDone + (Executes.request answer hTail) with + hTruncated | hDone + · obtain ⟨error, hError, hTruncated, hFollow⟩ := hTruncated + obtain ⟨_targetAnswer, hHead, hTargetTail⟩ := + Follows.request_inv hFollow + cases hHead + exact .inl ⟨error, hError, hTruncated, hTargetTail⟩ + · obtain ⟨rightDone, hRight, hDone⟩ := hDone + obtain ⟨_targetAnswer, hHead, hTargetTail⟩ := + Executes.request_inv hRight + cases hHead + exact .inr ⟨rightDone, hTargetTail, hDone⟩ + +/-- Strengthen every related target leaf with a universal target invariant. +Source truncation remains truncation and therefore needs no target relation. -/ +theorem strengthen_right + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {truncated : Error₁ → Prop} + {doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {property : Except Error₂ Result₂ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + (hRel : ForwardRel truncated doneRel left right) + (hAll : AllDone property right) : + ForwardRel truncated + (fun leftDone rightDone => doneRel leftDone rightDone ∧ property rightDone) + left right := by + induction hRel with + | truncated hTruncated => + exact .truncated hTruncated + | done hDone => + cases hAll with + | done hProperty => exact .done ⟨hDone, hProperty⟩ + | request hResume ih => + cases hAll with + | request hProperty => + exact .request fun answer => ih answer (hProperty answer) + +/-- Sequence a target-only continuation while leaving the completed source +result unchanged. -/ +theorem bind_right + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Source₂ : Type v2} {Target₂ : Type w2} + {truncated : Error₁ → Prop} + {sourceDoneRel : + Except Error₁ Result₁ → Except Error₂ Source₂ → Prop} + {targetDoneRel : + Except Error₁ Result₁ → Except Error₂ Target₂ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Source₂} + {rightNext : Source₂ → Interaction Error₂ Target₂} + (hRel : ForwardRel truncated sourceDoneRel left right) + (hNext : + ∀ leftDone rightDone, + sourceDoneRel leftDone rightDone → + ForwardRel truncated targetDoneRel + (.done leftDone) + (match rightDone with + | .error error => .done (.error error) + | .ok value => rightNext value)) : + ForwardRel truncated targetDoneRel left + (Interaction.bind right rightNext) := by + induction hRel with + | truncated hTruncated => + exact .truncated hTruncated + | @done leftDone rightDone hDone => + cases rightDone with + | error error => + simpa [Interaction.bind] using + hNext leftDone (.error error) hDone + | ok value => + simpa [Interaction.bind] using + hNext leftDone (.ok value) hDone + | request hResume ih => + exact .request ih + +theorem ofRel + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {truncated : Error₁ → Prop} + {doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + (hRel : Rel doneRel left right) : + ForwardRel truncated doneRel left right := by + induction hRel with + | done hDone => + exact .done hDone + | request hResume ih => + exact .request ih + +theorem mono + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {truncated : Error₁ → Prop} + {doneRel₁ doneRel₂ : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + (hRel : ForwardRel truncated doneRel₁ left right) + (hDone : + ∀ leftDone rightDone, + doneRel₁ leftDone rightDone → + doneRel₂ leftDone rightDone) : + ForwardRel truncated doneRel₂ left right := by + induction hRel with + | truncated hTruncated => + exact .truncated hTruncated + | done hRelated => + exact .done (hDone _ _ hRelated) + | request hResume ih => + exact .request ih + +/-- Remove a pure administrative map from the source side of a forward +simulation while preserving source truncation. -/ +theorem bind_pure_left_inv + {Error₁ : Type u1} {Source₁ : Type v1} {Target₁ : Type w1} + {Error₂ : Type u2} {Result₂ : Type v2} + {truncated : Error₁ → Prop} + {doneRel : + Except Error₁ Target₁ → Except Error₂ Result₂ → Prop} + {left : Interaction Error₁ Source₁} + {right : Interaction Error₂ Result₂} + {f : Source₁ → Target₁} + (hRel : + ForwardRel truncated doneRel + (Interaction.bind left + (fun value => Interaction.pure (f value))) + right) : + ForwardRel truncated + (fun leftDone rightDone => + match leftDone with + | .error err => doneRel (.error err) rightDone + | .ok value => doneRel (.ok (f value)) rightDone) + left right := by + induction left generalizing right with + | done outcome => + cases outcome with + | error error => + cases hRel with + | truncated hTruncated => exact .truncated hTruncated + | done hDone => exact .done hDone + | ok value => + cases hRel with + | done hDone => exact .done hDone + | request query resume ih => + cases hRel with + | request hResume => + exact .request fun answer => ih answer (hResume answer) + +/-- A forward simulation followed by an exact open-world relation composes +without replaying or interpreting either interaction tree. -/ +theorem trans_rel + {Error1 : Type u1} {Result1 : Type v1} + {Error2 : Type u2} {Result2 : Type v2} + {Error3 : Type u3} {Result3 : Type v3} + {truncated : Error1 → Prop} + {doneRel12 : + Except Error1 Result1 → Except Error2 Result2 → Prop} + {doneRel23 : + Except Error2 Result2 → Except Error3 Result3 → Prop} + {left : Interaction Error1 Result1} + {middle : Interaction Error2 Result2} + {right : Interaction Error3 Result3} + (hLeft : ForwardRel truncated doneRel12 left middle) + (hRight : Rel doneRel23 middle right) : + ForwardRel truncated + (fun leftDone rightDone => + ∃ middleDone, + doneRel12 leftDone middleDone ∧ + doneRel23 middleDone rightDone) + left right := by + induction hLeft generalizing right with + | truncated hTruncated => + exact .truncated hTruncated + | @done leftDone middleDone hDone => + cases hRight with + | done hRightDone => + exact .done ⟨middleDone, hDone, hRightDone⟩ + | @request query leftResume middleResume hResume ih => + cases hRight with + | request hRightResume => + exact .request fun answer => + ih answer (hRightResume answer) + +/-- +Compose two source-truncating forward refinements. The first adjacent boundary +owns the only extra fact required for composition: if its target outcome is a +truncation for the second boundary, then the original source outcome was +already a truncation. No target suffix is inspected or replayed. +-/ +theorem trans + {Error1 : Type u1} {Result1 : Type v1} + {Error2 : Type u2} {Result2 : Type v2} + {Error3 : Type u3} {Result3 : Type v3} + {truncated1 : Error1 → Prop} + {truncated2 : Error2 → Prop} + {doneRel12 : + Except Error1 Result1 → Except Error2 Result2 → Prop} + {doneRel23 : + Except Error2 Result2 → Except Error3 Result3 → Prop} + {left : Interaction Error1 Result1} + {middle : Interaction Error2 Result2} + {right : Interaction Error3 Result3} + (hLeft : ForwardRel truncated1 doneRel12 left middle) + (hRight : ForwardRel truncated2 doneRel23 middle right) + (hReflect : + ∀ leftDone middleError, + doneRel12 leftDone (.error middleError) → + truncated2 middleError → + ∃ leftError, + leftDone = .error leftError ∧ truncated1 leftError) : + ForwardRel truncated1 + (fun leftDone rightDone => + ∃ middleDone, + doneRel12 leftDone middleDone ∧ + doneRel23 middleDone rightDone) + left right := by + induction hLeft generalizing right with + | truncated hTruncated => + exact .truncated hTruncated + | @done leftDone middleDone hDone => + cases hRight with + | truncated hMiddleTruncated => + obtain ⟨leftError, hLeftDone, hLeftTruncated⟩ := + hReflect leftDone _ hDone hMiddleTruncated + subst leftDone + exact .truncated hLeftTruncated + | done hRightDone => + exact .done ⟨middleDone, hDone, hRightDone⟩ + | @request query leftResume middleResume hResume ih => + cases hRight with + | request hRightResume => + exact .request fun answer => + ih answer (hRightResume answer) + +/-- Universal source success crosses a forward simulation whenever every +related successful source leaf has a successful target leaf. -/ +theorem successful_right + {Error1 : Type u1} {Result1 : Type v1} + {Error2 : Type u2} {Result2 : Type v2} + {truncated : Error1 → Prop} + {doneRel : + Except Error1 Result1 → Except Error2 Result2 → Prop} + {left : Interaction Error1 Result1} + {right : Interaction Error2 Result2} + (hRel : ForwardRel truncated doneRel left right) + (hSuccessful : Successful left) + (hDone : ∀ leftDone rightDone, + doneRel leftDone rightDone → + (match leftDone with | .error _ => False | .ok _ => True) → + (match rightDone with | .error _ => False | .ok _ => True)) : + Successful right := by + induction hRel with + | truncated hTruncated => + cases hSuccessful with + | done hSource => exact False.elim hSource + | @done leftDone rightDone hRelated => + cases hSuccessful with + | done hSource => exact .done (hDone leftDone rightDone hRelated hSource) + | @request query leftResume rightResume hResume ih => + cases hSuccessful with + | request hSource => + exact .request fun answer => + ih answer (hSource answer) + +/-- A universally successful source cannot reach the truncation constructor, +so a forward refinement becomes a full structural open-world relation. -/ +theorem rel_of_successful + {Error1 : Type u1} {Result1 : Type v1} + {Error2 : Type u2} {Result2 : Type v2} + {truncated : Error1 -> Prop} + {doneRel : + Except Error1 Result1 -> Except Error2 Result2 -> Prop} + {left : Interaction Error1 Result1} + {right : Interaction Error2 Result2} + (hRel : ForwardRel truncated doneRel left right) + (hSuccessful : Successful left) : + Rel doneRel left right := by + induction hRel with + | truncated hTruncated => + cases hSuccessful with + | done hSource => exact False.elim hSource + | done hDone => + exact .done hDone + | request hResume ih => + cases hSuccessful with + | request hSource => + exact .request fun answer => ih answer (hSource answer) + +/-- A source-leaf invariant that excludes every truncated failure upgrades a +forward refinement to a full structural open-world relation. -/ +theorem rel_of_allDone + {Error1 : Type u1} {Result1 : Type v1} + {Error2 : Type u2} {Result2 : Type v2} + {truncated : Error1 -> Prop} + {doneRel : + Except Error1 Result1 -> Except Error2 Result2 -> Prop} + {property : Except Error1 Result1 -> Prop} + {left : Interaction Error1 Result1} + {right : Interaction Error2 Result2} + (hRel : ForwardRel truncated doneRel left right) + (hAll : AllDone property left) + (hExcludes : forall error, property (.error error) -> + Not (truncated error)) : + Rel doneRel left right := by + induction hRel with + | truncated hTruncated => + cases hAll with + | done hProperty => + exact False.elim (hExcludes _ hProperty hTruncated) + | done hDone => + exact .done hDone + | request hResume ih => + cases hAll with + | request hProperty => + exact .request fun answer => ih answer (hProperty answer) + +/-- Strengthen a forward simulation with a source-side invariant that holds at +every terminal leaf. Source truncation remains source truncation and therefore +does not require a target relation. -/ +theorem strengthen_left + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {truncated : Error₁ → Prop} + {doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {property : Except Error₁ Result₁ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + (hRel : ForwardRel truncated doneRel left right) + (hAll : AllDone property left) : + ForwardRel truncated + (fun leftDone rightDone => + doneRel leftDone rightDone ∧ property leftDone) + left right := by + induction hRel with + | truncated hTruncated => + exact .truncated hTruncated + | done hDone => + cases hAll with + | done hProperty => + exact .done ⟨hDone, hProperty⟩ + | request hResume ih => + cases hAll with + | request hProperty => + exact .request fun answer => + ih answer (hProperty answer) + +theorem bind + {Error₁ : Type u1} {Source₁ : Type v1} {Target₁ : Type w1} + {Error₂ : Type u2} {Source₂ : Type v2} {Target₂ : Type w2} + {truncated : Error₁ → Prop} + {errorRel : Error₁ → Error₂ → Prop} + {sourceRel : Source₁ → Source₂ → Prop} + {targetRel : Target₁ → Target₂ → Prop} + {left : Interaction Error₁ Source₁} + {right : Interaction Error₂ Source₂} + {leftNext : Source₁ → Interaction Error₁ Target₁} + {rightNext : Source₂ → Interaction Error₂ Target₂} + (hResult : + ForwardRel truncated (ExceptRel errorRel sourceRel) left right) + (hNext : + ∀ leftValue rightValue, + sourceRel leftValue rightValue → + ForwardRel truncated (ExceptRel errorRel targetRel) + (leftNext leftValue) (rightNext rightValue)) : + ForwardRel truncated (ExceptRel errorRel targetRel) + (Interaction.bind left leftNext) + (Interaction.bind right rightNext) := by + induction hResult with + | truncated hTruncated => + exact .truncated hTruncated + | done hDone => + cases hDone with + | error hError => + exact .done (.error hError) + | ok hValue => + exact hNext _ _ hValue + | request hResume ih => + exact .request ih + +theorem bind_custom + {Error₁ : Type u1} {Source₁ : Type v1} {Target₁ : Type w1} + {Error₂ : Type u2} {Source₂ : Type v2} {Target₂ : Type w2} + {truncated : Error₁ → Prop} + {sourceDoneRel : + Except Error₁ Source₁ → Except Error₂ Source₂ → Prop} + {targetDoneRel : + Except Error₁ Target₁ → Except Error₂ Target₂ → Prop} + {left : Interaction Error₁ Source₁} + {right : Interaction Error₂ Source₂} + {leftNext : Source₁ → Interaction Error₁ Target₁} + {rightNext : Source₂ → Interaction Error₂ Target₂} + (hResult : ForwardRel truncated sourceDoneRel left right) + (hNext : + ∀ leftDone rightDone, + sourceDoneRel leftDone rightDone → + ForwardRel truncated targetDoneRel + (match leftDone with + | .error error => .done (.error error) + | .ok value => leftNext value) + (match rightDone with + | .error error => .done (.error error) + | .ok value => rightNext value)) : + ForwardRel truncated targetDoneRel + (Interaction.bind left leftNext) + (Interaction.bind right rightNext) := by + induction hResult with + | truncated hTruncated => + exact .truncated hTruncated + | @done leftDone rightDone hDone => + cases leftDone <;> cases rightDone <;> + simpa [Interaction.bind] using + hNext _ _ hDone + | request hResume ih => + exact .request ih + +/-- +Every non-truncated concrete source execution is reproduced by the target with +the exact same ordered query/answer transcript. +-/ +theorem executes + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {truncated : Error₁ → Prop} + {doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + {transcript : Transcript} + {leftOutcome : Except Error₁ Result₁} + (hRel : ForwardRel truncated doneRel left right) + (hExec : Executes left transcript leftOutcome) + (hNotTruncated : + ∀ error, leftOutcome = .error error → ¬ truncated error) : + ∃ rightOutcome, + Executes right transcript rightOutcome ∧ + doneRel leftOutcome rightOutcome := by + induction hExec generalizing right with + | done outcome => + cases hRel with + | truncated hTruncated => + exact False.elim (hNotTruncated _ rfl hTruncated) + | done hDone => + exact ⟨_, Executes.done _, hDone⟩ + | request answer tail ih => + cases hRel with + | request hResume => + obtain ⟨rightOutcome, hRight, hDone⟩ := + ih (hResume answer) hNotTruncated + exact + ⟨rightOutcome, Executes.request answer hRight, hDone⟩ + +theorem executes_ok + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {truncated : Error₁ → Prop} + {doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + {transcript : Transcript} + {leftResult : Result₁} + (hRel : ForwardRel truncated doneRel left right) + (hExec : Executes left transcript (.ok leftResult)) : + ∃ rightOutcome, + Executes right transcript rightOutcome ∧ + doneRel (.ok leftResult) rightOutcome := by + apply executes hRel hExec + intro error hError + cases hError + +end ForwardRel + +/-- A deterministic client for the open interaction tree. -/ +abbrev Strategy := (query : Query) → Answer query + +def interpret {Error : Type u1} {Result : Type v1} + (strategy : Strategy) : + Interaction Error Result → Except Error Result + | .done result => result + | .request query resume => + interpret strategy (resume (strategy query)) + +theorem Rel.interpret + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + (strategy : Strategy) + (hRel : Rel doneRel left right) : + doneRel (interpret strategy left) (interpret strategy right) := by + induction hRel with + | done hDone => + exact hDone + | @request query left right hResume ih => + exact ih (strategy query) + +theorem ForwardRel.interpret + {Error₁ : Type u1} {Result₁ : Type v1} + {Error₂ : Type u2} {Result₂ : Type v2} + {truncated : Error₁ → Prop} + {doneRel : + Except Error₁ Result₁ → Except Error₂ Result₂ → Prop} + {left : Interaction Error₁ Result₁} + {right : Interaction Error₂ Result₂} + (strategy : Strategy) + (hRel : ForwardRel truncated doneRel left right) + (hNotTruncated : + ∀ error, interpret strategy left = .error error → + ¬ truncated error) : + doneRel (interpret strategy left) (interpret strategy right) := by + induction hRel with + | truncated hTruncated => + exact False.elim (hNotTruncated _ rfl hTruncated) + | done hDone => + exact hDone + | @request query left right hResume ih => + exact ih (strategy query) hNotTruncated + +end Interaction + +end Simulation +end EvmCompiler diff --git a/vendor/evm-interaction/EvmInteraction/Simulation/OpenWorld.lean b/vendor/evm-interaction/EvmInteraction/Simulation/OpenWorld.lean new file mode 100644 index 00000000..acdcdd36 --- /dev/null +++ b/vendor/evm-interaction/EvmInteraction/Simulation/OpenWorld.lean @@ -0,0 +1,618 @@ +import EvmYul.SharedState +import EvmYul.StateOps + +namespace EvmCompiler +namespace Simulation + +abbrev OpenWord := EvmYul.UInt256 +abbrev OpenAddress := EvmYul.AccountAddress + +/-- +The account data observable across the compiler's open external boundary. + +External code is deliberately represented only by bytes. In particular, an +external account does not carry a Yul AST or any compiler provenance. +-/ +structure OpenAccount where + nonce : OpenWord + balance : OpenWord + storage : EvmYul.Storage + transientStorage : EvmYul.Storage + codeBytes : ByteArray + deriving Inhabited + +namespace OpenAccount + +def ofAccount {τ : EvmYul.OperationType} + (account : EvmYul.Account τ) : OpenAccount where + nonce := account.nonce + balance := account.balance + storage := account.storage + transientStorage := account.tstorage + codeBytes := EvmYul.State.accountCodeImage account + +def empty (account : OpenAccount) : Bool := + account.codeBytes.isEmpty && + (decide (account.nonce = ⟨0⟩) && + decide (account.balance = ⟨0⟩)) + +def ofYul (account : EvmYul.Account .Yul) : OpenAccount where + nonce := account.nonce + balance := account.balance + storage := account.storage + transientStorage := account.tstorage + codeBytes := account.codeBytes + +def ofEVM (account : EvmYul.Account .EVM) : OpenAccount where + nonce := account.nonce + balance := account.balance + storage := account.storage + transientStorage := account.tstorage + codeBytes := account.code + +@[simp] theorem ofAccount_yul (account : EvmYul.Account .Yul) : + ofAccount account = ofYul account := rfl + +@[simp] theorem ofAccount_evm (account : EvmYul.Account .EVM) : + ofAccount account = ofEVM account := rfl + +@[simp] theorem ofAccount_default {τ : EvmYul.OperationType} : + ofAccount (default : EvmYul.Account τ) = (default : OpenAccount) := by + cases τ <;> rfl + +@[simp] theorem ofAccount_balance {τ : EvmYul.OperationType} + (account : EvmYul.Account τ) : + (ofAccount account).balance = account.balance := rfl + +@[simp] theorem ofAccount_withBalance {τ : EvmYul.OperationType} + (account : EvmYul.Account τ) (balance : OpenWord) : + ofAccount { account with balance := balance } = + { ofAccount account with balance := balance } := by + cases τ <;> rfl + +@[simp] theorem ofAccount_defaultWithBalance + {τ : EvmYul.OperationType} (balance : OpenWord) : + ofAccount ({ (default : EvmYul.Account τ) with balance := balance }) = + { (default : OpenAccount) with balance := balance } := by + cases τ <;> rfl + +theorem ofAccount_updateStorage {τ : EvmYul.OperationType} + (account : EvmYul.Account τ) (key value : EvmYul.UInt256) : + ofAccount (account.updateStorage key value) = + { ofAccount account with + storage := + if value == (default : EvmYul.UInt256) then + account.storage.erase key + else account.storage.insert key value } := by + cases τ <;> + by_cases hZero : value == (default : EvmYul.UInt256) <;> + simp [EvmYul.Account.updateStorage, hZero, ofAccount, + EvmYul.State.accountCodeImage] + +theorem ofAccount_updateTransientStorage {τ : EvmYul.OperationType} + (account : EvmYul.Account τ) (key value : EvmYul.UInt256) : + ofAccount (account.updateTransientStorage key value) = + { ofAccount account with + transientStorage := + if value == (default : EvmYul.UInt256) then + account.tstorage.erase key + else account.tstorage.insert key value } := by + cases τ <;> + by_cases hZero : value == (default : EvmYul.UInt256) <;> + simp [EvmYul.Account.updateTransientStorage, hZero, ofAccount, + EvmYul.State.accountCodeImage] + +/-- +Install code-erased account data into a legacy Yul account while retaining an +explicit compatibility AST. Canonical open semantics must not inspect that AST. +-/ +def toYul (account : OpenAccount) + (compatibilityCode : EvmYul.Yul.Ast.YulContract) : + EvmYul.Account .Yul where + nonce := account.nonce + balance := account.balance + storage := account.storage + code := compatibilityCode + codeBytes := account.codeBytes + tstorage := account.transientStorage + +def toEVM (account : OpenAccount) : EvmYul.Account .EVM where + nonce := account.nonce + balance := account.balance + storage := account.storage + code := account.codeBytes + codeBytes := account.codeBytes + tstorage := account.transientStorage + +@[simp] theorem ofYul_toYul (account : OpenAccount) + (compatibilityCode : EvmYul.Yul.Ast.YulContract) : + ofYul (account.toYul compatibilityCode) = account := by + cases account + rfl + +@[simp] theorem ofEVM_toEVM (account : OpenAccount) : + ofEVM account.toEVM = account := by + cases account + rfl + +end OpenAccount + +namespace CodeErasedState + +/-- Account emptiness observable through the open-world boundary. Unlike the +legacy Yul predicate, this inspects the executable byte image, not a retained +compatibility AST. -/ +def emptyAccount {τ : EvmYul.OperationType} + (account : EvmYul.Account τ) : Bool := + (OpenAccount.ofAccount account).empty + +def dead {τ : EvmYul.OperationType} + (accounts : EvmYul.AccountMap τ) + (address : EvmYul.AccountAddress) : Bool := + (accounts.find? address).option true emptyAccount + +/-- `EXTCODEHASH` over the code-erased account view shared by Yul and EVM. -/ +def extCodeHash {τ : EvmYul.OperationType} + (state : EvmYul.State τ) (value : EvmYul.UInt256) : + EvmYul.State τ × EvmYul.UInt256 := + let address := EvmYul.AccountAddress.ofUInt256 value + let next := state.addAccessedAccount address + if dead state.accountMap address then + (next, ⟨0⟩) + else + let result := + state.lookupAccount address |>.option ⟨0⟩ + (fun account => + .ofNat <| EvmYul.fromByteArrayBigEndian + (ffi.KEC (EvmYul.State.accountCodeImage account))) + (next, result) + +theorem extCodeHash_evm (state : EvmYul.State .EVM) (value : EvmYul.UInt256) : + extCodeHash state value = EvmYul.State.extCodeHash state value := by + have hEmpty : + (fun account : EvmYul.Account .EVM => emptyAccount account) = + EvmYul.Account.emptyAccount := by + funext account + simp [emptyAccount, EvmYul.Account.emptyAccount, + EvmYul.State.accountCodeImage, OpenAccount.empty, + OpenAccount.ofEVM] + all_goals rfl + simp [extCodeHash, dead, EvmYul.State.extCodeHash, + EvmYul.State.dead, hEmpty] + +def currentStorageValue {τ : EvmYul.OperationType} + (state : EvmYul.State τ) (owner : EvmYul.AccountAddress) + (key : EvmYul.UInt256) : EvmYul.UInt256 := + (state.accountMap.find! owner).1.storage.findD key ⟨0⟩ + +def initialStorageValue {τ : EvmYul.OperationType} + (state : EvmYul.State τ) (owner : EvmYul.AccountAddress) + (key : EvmYul.UInt256) : EvmYul.UInt256 := + (state.σ₀.find? owner).option ⟨0⟩ + (fun account => account.storage.findD key ⟨0⟩) + +def sstoreRefundBalance + (initial current new refundBalance : EvmYul.UInt256) : + EvmYul.UInt256 := + let dirtyClear : ℤ := + if initial ≠ .ofNat 0 && current = .ofNat 0 then + -GasConstants.Rsclear + else if initial ≠ .ofNat 0 && new = .ofNat 0 then + GasConstants.Rsclear + else 0 + let dirtyReset : ℤ := + if initial = new && initial = .ofNat 0 then + GasConstants.Gsset - GasConstants.Gwarmaccess + else if initial = new && initial ≠ .ofNat 0 then + GasConstants.Gsreset - GasConstants.Gwarmaccess + else 0 + let refundDelta : ℤ := + if current ≠ new && initial = current && new = .ofNat 0 then + GasConstants.Rsclear + else if current ≠ new && initial ≠ current then + dirtyClear + dirtyReset + else 0 + match refundDelta with + | .ofNat n => refundBalance + .ofNat n + | .negSucc n => refundBalance - .ofNat n - ⟨1⟩ + +theorem sstore_eq {τ : EvmYul.OperationType} + (state : EvmYul.State τ) (key value : EvmYul.UInt256) : + state.sstore key value = + let owner := state.executionEnv.codeOwner + state.lookupAccount owner |>.option state fun account => + let state' := + state.setAccount owner (account.updateStorage key value) + |>.addAccessedStorageKey (owner, key) + { state' with + substate.refundBalance := + sstoreRefundBalance + (initialStorageValue state owner key) + (currentStorageValue state owner key) + value state.substate.refundBalance } := by + unfold EvmYul.State.sstore + dsimp only + congr 1 + funext account + congr 1 + congr 1 + simp only [sstoreRefundBalance, initialStorageValue, currentStorageValue, Option.option] + congr + all_goals (cases RBTree.RBMap.find? state.σ₀ state.executionEnv.codeOwner <;> rfl) + +end CodeErasedState + +/-- +The mutable, code-erased world shared exactly by source and target semantics. + +Transaction snapshots, block history, active code, frame-local data, and gas +counters are intentionally excluded. +-/ +structure OpenWorld where + accounts : EvmYul.AddrMap OpenAccount + substate : EvmYul.Substate + createdAccounts : RBTree.RBSet OpenAddress compare + deriving Inhabited + +namespace OpenWorld + +theorem ext_of_fields + {left right : OpenWorld} + (hAccounts : left.accounts = right.accounts) + (hSubstate : left.substate = right.substate) + (hCreated : left.createdAccounts = right.createdAccounts) : + left = right := by + cases left + cases right + simp_all + +theorem find?_mapVal_const + {α β γ : Type} {cmp : α → α → Ordering} + (map : RBTree.RBMap α β cmp) (f : β → γ) (key : α) : + (map.mapVal fun _ value => f value).find? key = + (map.find? key).map f := by + rcases map with ⟨tree, hTree⟩ + change + Option.map Prod.snd + (RBTree.RBNode.find? (fun entry => cmp key entry.1) + (tree.map (RBTree.RBMap.Imp.mapSnd fun _ value => f value))) = + Option.map f + (Option.map Prod.snd + (RBTree.RBNode.find? (fun entry => cmp key entry.1) tree)) + clear hTree + induction tree with + | nil => rfl + | node color left entry right leftIH rightIH => + cases hCompare : cmp key entry.1 <;> + simp [RBTree.RBNode.map, RBTree.RBNode.find?, + RBTree.RBMap.Imp.mapSnd, hCompare, leftIH, rightIH, + Function.comp_def] + +private theorem mapSnd_setBlack + {α β γ : Type} (f : α → β → γ) + (tree : RBTree.RBNode (α × β)) : + (tree.setBlack.map (RBTree.RBMap.Imp.mapSnd f)) = + (tree.map (RBTree.RBMap.Imp.mapSnd f)).setBlack := by + cases tree <;> rfl + +private theorem mapSnd_balance1 + {α β γ : Type} (f : α → β → γ) + (left : RBTree.RBNode (α × β)) (value : α × β) + (right : RBTree.RBNode (α × β)) : + (RBTree.RBNode.balance1 left value right).map + (RBTree.RBMap.Imp.mapSnd f) = + RBTree.RBNode.balance1 + (left.map (RBTree.RBMap.Imp.mapSnd f)) + (RBTree.RBMap.Imp.mapSnd f value) + (right.map (RBTree.RBMap.Imp.mapSnd f)) := by + cases left with + | nil => rfl + | node color leftLeft leftValue leftRight => + cases color with + | black => rfl + | red => + cases leftLeft with + | nil => + cases leftRight with + | nil => rfl + | node rightColor rightLeft rightValue rightRight => + cases rightColor <;> rfl + | node leftColor farLeft pivot nearLeft => + cases leftColor with + | red => rfl + | black => + cases leftRight with + | nil => rfl + | node rightColor rightLeft rightValue rightRight => + cases rightColor <;> rfl + +private theorem mapSnd_balance2 + {α β γ : Type} (f : α → β → γ) + (left : RBTree.RBNode (α × β)) (value : α × β) + (right : RBTree.RBNode (α × β)) : + (RBTree.RBNode.balance2 left value right).map + (RBTree.RBMap.Imp.mapSnd f) = + RBTree.RBNode.balance2 + (left.map (RBTree.RBMap.Imp.mapSnd f)) + (RBTree.RBMap.Imp.mapSnd f value) + (right.map (RBTree.RBMap.Imp.mapSnd f)) := by + cases right with + | nil => rfl + | node color rightLeft rightValue rightRight => + cases color with + | black => rfl + | red => + cases rightRight with + | nil => + cases rightLeft with + | nil => rfl + | node leftColor leftLeft leftValue leftRight => + cases leftColor <;> rfl + | node rightColor nearRight pivot farRight => + cases rightColor with + | red => rfl + | black => + cases rightLeft with + | nil => rfl + | node leftColor leftLeft leftValue leftRight => + cases leftColor <;> rfl + +private theorem mapSnd_ins + {α β γ : Type} {cmp : α → α → Ordering} + (f : α → β → γ) (key : α) (value : β) + (tree : RBTree.RBNode (α × β)) : + (tree.ins (Ordering.byKey Prod.fst cmp) (key, value)).map + (RBTree.RBMap.Imp.mapSnd f) = + (tree.map (RBTree.RBMap.Imp.mapSnd f)).ins + (Ordering.byKey Prod.fst cmp) (key, f key value) := by + induction tree with + | nil => rfl + | node color left entry right leftIH rightIH => + cases color with + | red => + cases hCompare : cmp key entry.1 <;> + simp [RBTree.RBNode.ins, RBTree.RBNode.map, + RBTree.RBMap.Imp.mapSnd, Ordering.byKey, + hCompare, leftIH, rightIH] + | black => + cases hCompare : cmp key entry.1 with + | lt => + simp only [RBTree.RBNode.ins, RBTree.RBNode.map, + RBTree.RBMap.Imp.mapSnd, Ordering.byKey, hCompare] + rw [mapSnd_balance1, leftIH] + simp [RBTree.RBMap.Imp.mapSnd] + | gt => + simp only [RBTree.RBNode.ins, RBTree.RBNode.map, + RBTree.RBMap.Imp.mapSnd, Ordering.byKey, hCompare] + rw [mapSnd_balance2, rightIH] + simp [RBTree.RBMap.Imp.mapSnd] + | eq => + simp [RBTree.RBNode.ins, RBTree.RBNode.map, + RBTree.RBMap.Imp.mapSnd, Ordering.byKey, hCompare] + +private theorem mapSnd_insert + {α β γ : Type} {cmp : α → α → Ordering} + (f : α → β → γ) (key : α) (value : β) + (tree : RBTree.RBNode (α × β)) : + (tree.insert (Ordering.byKey Prod.fst cmp) (key, value)).map + (RBTree.RBMap.Imp.mapSnd f) = + (tree.map (RBTree.RBMap.Imp.mapSnd f)).insert + (Ordering.byKey Prod.fst cmp) (key, f key value) := by + unfold RBTree.RBNode.insert + have hColor : + (tree.map (RBTree.RBMap.Imp.mapSnd f)).isRed = tree.isRed := by + cases tree <;> rfl + rw [hColor] + cases tree.isRed <;> + simp [mapSnd_ins, mapSnd_setBlack] + +theorem mapVal_insert + {α β γ : Type} {cmp : α → α → Ordering} + (map : RBTree.RBMap α β cmp) (f : α → β → γ) + (key : α) (value : β) : + (map.insert key value).mapVal f = + (map.mapVal f).insert key (f key value) := by + apply Subtype.ext + exact mapSnd_insert f key value map.1 + +def selfdestructAccounts (accounts : EvmYul.AddrMap OpenAccount) + (source target : OpenAddress) (created : Bool) : + EvmYul.AddrMap OpenAccount := + match accounts.find? source with + | none => accounts + | some sourceAccount => + match accounts.find? target with + | none => + if sourceAccount.balance == (EvmYul.UInt256.ofNat 0) then + accounts + else + accounts.insert target + { (default : OpenAccount) with + balance := sourceAccount.balance } + |>.insert source + { sourceAccount with + balance := EvmYul.UInt256.ofNat 0 } + | some targetAccount => + if target ≠ source then + accounts.insert target + { targetAccount with + balance := targetAccount.balance + sourceAccount.balance } + |>.insert source + { sourceAccount with + balance := EvmYul.UInt256.ofNat 0 } + else if created then + accounts.insert target + { targetAccount with balance := EvmYul.UInt256.ofNat 0 } + |>.insert source + { sourceAccount with balance := EvmYul.UInt256.ofNat 0 } + else accounts + +private theorem mapVal_leftInverse + {α β γ : Type} {cmp : α → α → Ordering} + (f : α → β → γ) (g : α → γ → β) + (h : ∀ key value, g key (f key value) = value) + (map : RBTree.RBMap α β cmp) : + (map.mapVal f).mapVal g = map := by + apply Subtype.ext + change RBTree.RBNode.map (RBTree.RBMap.Imp.mapSnd g) + (RBTree.RBNode.map (RBTree.RBMap.Imp.mapSnd f) map.1) = map.1 + induction map.1 with + | nil => rfl + | node color left value right leftIH rightIH => + simp [RBTree.RBNode.map, leftIH, rightIH, + RBTree.RBMap.Imp.mapSnd, h] + +def ofYulState (state : EvmYul.State .Yul) : OpenWorld where + accounts := state.accountMap.mapVal fun _ account => OpenAccount.ofYul account + substate := state.substate + createdAccounts := state.createdAccounts + +def ofEVMState (state : EvmYul.State .EVM) : OpenWorld where + accounts := state.accountMap.mapVal fun _ account => OpenAccount.ofEVM account + substate := state.substate + createdAccounts := state.createdAccounts + +def ofYulShared (state : EvmYul.SharedState .Yul) : OpenWorld := + ofYulState state.toState + +def ofEVMShared (state : EvmYul.SharedState .EVM) : OpenWorld := + ofEVMState state.toState + +def installYulAccounts + (base : EvmYul.AccountMap .Yul) + (accounts : EvmYul.AddrMap OpenAccount) : + EvmYul.AccountMap .Yul := + accounts.mapVal fun address account => + let compatibilityCode := + match base.find? address with + | some existing => existing.code + | none => default + account.toYul compatibilityCode + +def installEVMAccounts + (accounts : EvmYul.AddrMap OpenAccount) : + EvmYul.AccountMap .EVM := + accounts.mapVal fun _ account => account.toEVM + +/-- +Install an open world into a legacy source state. All transaction, block, and +protected execution-frame fields are preserved from `base`. +-/ +def installYul (base : EvmYul.State .Yul) (world : OpenWorld) : + EvmYul.State .Yul := + { base with + accountMap := installYulAccounts base.accountMap world.accounts + substate := world.substate + createdAccounts := world.createdAccounts } + +/-- +Install an open world into a legacy target state. Active bytecode remains in +the protected execution environment, not in this world replacement. +-/ +def installEVM (base : EvmYul.State .EVM) (world : OpenWorld) : + EvmYul.State .EVM := + { base with + accountMap := installEVMAccounts world.accounts + substate := world.substate + createdAccounts := world.createdAccounts } + +def installYulShared + (base : EvmYul.SharedState .Yul) (world : OpenWorld) : + EvmYul.SharedState .Yul := + { base with toState := installYul base.toState world } + +def installEVMShared + (base : EvmYul.SharedState .EVM) (world : OpenWorld) : + EvmYul.SharedState .EVM := + { base with toState := installEVM base.toState world } + +@[simp] theorem ofYulState_installYul + (base : EvmYul.State .Yul) (world : OpenWorld) : + ofYulState (installYul base world) = world := by + cases world with + | mk accounts substate createdAccounts => + change OpenWorld.mk + ((accounts.mapVal fun address account => + let compatibilityCode := + match base.accountMap.find? address with + | some existing => existing.code + | none => default + account.toYul compatibilityCode).mapVal + fun _ account => OpenAccount.ofYul account) + substate createdAccounts = + OpenWorld.mk accounts substate createdAccounts + rw [mapVal_leftInverse + (fun address account => + let compatibilityCode := + match base.accountMap.find? address with + | some existing => existing.code + | none => default + account.toYul compatibilityCode) + (fun _ account => OpenAccount.ofYul account) + (by intro address account; simp) + accounts] + +@[simp] theorem ofEVMState_installEVM + (base : EvmYul.State .EVM) (world : OpenWorld) : + ofEVMState (installEVM base world) = world := by + cases world with + | mk accounts substate createdAccounts => + change OpenWorld.mk + ((accounts.mapVal fun _ account => account.toEVM).mapVal + fun _ account => OpenAccount.ofEVM account) + substate createdAccounts = + OpenWorld.mk accounts substate createdAccounts + rw [mapVal_leftInverse + (fun _ account => account.toEVM) + (fun _ account => OpenAccount.ofEVM account) + (by intro address account; simp) + accounts] + +@[simp] theorem ofYulShared_installYulShared + (base : EvmYul.SharedState .Yul) (world : OpenWorld) : + ofYulShared (installYulShared base world) = world := by + exact ofYulState_installYul base.toState world + +@[simp] theorem ofEVMShared_installEVMShared + (base : EvmYul.SharedState .EVM) (world : OpenWorld) : + ofEVMShared (installEVMShared base world) = world := by + exact ofEVMState_installEVM base.toState world + +@[simp] theorem installYul_executionEnv + (base : EvmYul.State .Yul) (world : OpenWorld) : + (installYul base world).executionEnv = base.executionEnv := rfl + +@[simp] theorem installEVM_executionEnv + (base : EvmYul.State .EVM) (world : OpenWorld) : + (installEVM base world).executionEnv = base.executionEnv := rfl + +@[simp] theorem installYul_substate + (base : EvmYul.State .Yul) (world : OpenWorld) : + (installYul base world).substate = world.substate := rfl + +@[simp] theorem installEVM_substate + (base : EvmYul.State .EVM) (world : OpenWorld) : + (installEVM base world).substate = world.substate := rfl + +@[simp] theorem installYul_createdAccounts + (base : EvmYul.State .Yul) (world : OpenWorld) : + (installYul base world).createdAccounts = world.createdAccounts := rfl + +@[simp] theorem installEVM_createdAccounts + (base : EvmYul.State .EVM) (world : OpenWorld) : + (installEVM base world).createdAccounts = world.createdAccounts := rfl + +@[simp] theorem installYulShared_machine + (base : EvmYul.SharedState .Yul) (world : OpenWorld) : + (installYulShared base world).toMachineState = + base.toMachineState := rfl + +@[simp] theorem installEVMShared_machine + (base : EvmYul.SharedState .EVM) (world : OpenWorld) : + (installEVMShared base world).toMachineState = + base.toMachineState := rfl + +end OpenWorld + +end Simulation +end EvmCompiler diff --git a/vendor/evm-interaction/EvmInteraction/Simulation/Outcome.lean b/vendor/evm-interaction/EvmInteraction/Simulation/Outcome.lean new file mode 100644 index 00000000..88feefb2 --- /dev/null +++ b/vendor/evm-interaction/EvmInteraction/Simulation/Outcome.lean @@ -0,0 +1,105 @@ +import Mathlib.Data.List.Basic + +namespace EvmCompiler +namespace Simulation + +/-! +Shared outcome-indexed simulation vocabulary. + +Compiler passes use different outcome and state types, but preservation proofs +repeat the same operation: inspect source and target modes, then select the +state relation and cleanup contract owned by that mode. `OutcomeView` separates +that common operation from each layer's concrete outcome representation, while +`OutcomeContract` keeps mode-specific policy at the pass boundary. +-/ + +structure OutcomeView (Outcome State Mode : Type) where + state : Outcome → State + mode : Outcome → Mode + +structure OutcomeContract + (SourceMode TargetMode SourceState TargetState : Type) where + relate : + SourceMode → TargetMode → SourceState → TargetState → Prop + +structure OutcomePackage (Mode : Type) (Obligation : Mode → Prop) : Prop where + sound : ∀ mode, Obligation mode + +namespace OutcomePackage + +def project {Mode : Type} {Obligation : Mode → Prop} + (package : OutcomePackage Mode Obligation) (mode : Mode) : + Obligation mode := + package.sound mode + +def map {Mode : Type} {left right : Mode → Prop} + (hMap : ∀ mode, left mode → right mode) + (package : OutcomePackage Mode left) : + OutcomePackage Mode right where + sound mode := hMap mode (package.sound mode) + +end OutcomePackage + +def OutcomeRel + {SourceOutcome TargetOutcome SourceState TargetState + SourceMode TargetMode : Type} + (sourceView : OutcomeView SourceOutcome SourceState SourceMode) + (targetView : OutcomeView TargetOutcome TargetState TargetMode) + (contract : + OutcomeContract SourceMode TargetMode SourceState TargetState) + (source : SourceOutcome) (target : TargetOutcome) : Prop := + contract.relate + (sourceView.mode source) (targetView.mode target) + (sourceView.state source) (targetView.state target) + +namespace OutcomeRel + +theorem intro + {SourceOutcome TargetOutcome SourceState TargetState + SourceMode TargetMode : Type} + {sourceView : OutcomeView SourceOutcome SourceState SourceMode} + {targetView : OutcomeView TargetOutcome TargetState TargetMode} + {contract : + OutcomeContract SourceMode TargetMode SourceState TargetState} + {source : SourceOutcome} {target : TargetOutcome} + (hRel : + contract.relate + (sourceView.mode source) (targetView.mode target) + (sourceView.state source) (targetView.state target)) : + OutcomeRel sourceView targetView contract source target := + hRel + +theorem elim + {SourceOutcome TargetOutcome SourceState TargetState + SourceMode TargetMode : Type} + {sourceView : OutcomeView SourceOutcome SourceState SourceMode} + {targetView : OutcomeView TargetOutcome TargetState TargetMode} + {contract : + OutcomeContract SourceMode TargetMode SourceState TargetState} + {source : SourceOutcome} {target : TargetOutcome} + (hRel : OutcomeRel sourceView targetView contract source target) : + contract.relate + (sourceView.mode source) (targetView.mode target) + (sourceView.state source) (targetView.state target) := + hRel + +theorem mono + {SourceOutcome TargetOutcome SourceState TargetState + SourceMode TargetMode : Type} + {sourceView : OutcomeView SourceOutcome SourceState SourceMode} + {targetView : OutcomeView TargetOutcome TargetState TargetMode} + {left right : + OutcomeContract SourceMode TargetMode SourceState TargetState} + (hMono : + ∀ sourceMode targetMode sourceState targetState, + left.relate sourceMode targetMode sourceState targetState → + right.relate sourceMode targetMode sourceState targetState) + {source : SourceOutcome} {target : TargetOutcome} + (hRel : OutcomeRel sourceView targetView left source target) : + OutcomeRel sourceView targetView right source target := + hMono _ _ _ _ hRel + +end OutcomeRel + +end Simulation +end EvmCompiler diff --git a/vendor/evm-interaction/lakefile.lean b/vendor/evm-interaction/lakefile.lean new file mode 100644 index 00000000..a2df296f --- /dev/null +++ b/vendor/evm-interaction/lakefile.lean @@ -0,0 +1,37 @@ +import Lake +open Lake DSL + +require evmyul from ".." / "evmyul" + +package «evm-interaction» { + moreLeanArgs := #[ + "-DautoImplicit=false", + "-Dlinter.all=false", + "-Dlinter.constructorNameAsVariable=false", + "-Dlinter.deprecated=false", + "-Dlinter.unnecessarySeqFocus=false", + "-Dlinter.unnecessarySimpa=false", + "-Dlinter.unreachableTactic=false", + "-Dlinter.unusedSimpArgs=false", + "-Dlinter.unusedTactic=false", + "-Dlinter.unusedVariables=false" + ] + moreServerOptions := #[ + ⟨`autoImplicit, false⟩, + ⟨`linter.all, false⟩, + ⟨`linter.constructorNameAsVariable, false⟩, + ⟨`linter.deprecated, false⟩, + ⟨`linter.unnecessarySeqFocus, false⟩, + ⟨`linter.unnecessarySimpa, false⟩, + ⟨`linter.unreachableTactic, false⟩, + ⟨`linter.unusedSimpArgs, false⟩, + ⟨`linter.unusedTactic, false⟩, + ⟨`linter.unusedVariables, false⟩ + ] +} + +@[default_target] +lean_lib «EvmInteraction» where + roots := #[`EvmInteraction] + globs := #[`EvmInteraction, `EvmInteraction.Simulation.Interaction, + `EvmInteraction.Simulation.OpenWorld, `EvmInteraction.Simulation.Outcome].map Lake.Glob.one diff --git a/vendor/evm-rules/EvmRules.lean b/vendor/evm-rules/EvmRules.lean new file mode 100644 index 00000000..89174c75 --- /dev/null +++ b/vendor/evm-rules/EvmRules.lean @@ -0,0 +1,10 @@ +import EvmRules.Word +import EvmRules.Bitblast +import EvmRules.Bits +import EvmRules.Casts +import EvmRules.Simp +import EvmRules.Reference +import EvmRules.Tactic +import EvmRules.Arith +import EvmRules.ArithTactic +import EvmRules.Lemmas diff --git a/vendor/evm-rules/EvmRules/Arith.lean b/vendor/evm-rules/EvmRules/Arith.lean new file mode 100644 index 00000000..1ea59255 --- /dev/null +++ b/vendor/evm-rules/EvmRules/Arith.lean @@ -0,0 +1,244 @@ +import EvmRules.Word + +/-! +# Word arithmetic as natural numbers + +The lemmas `evm_arith` (`ArithTactic.lean`) rewrites with. Comparison words become the +bits of decided propositions, each operation becomes a number with its wrapping, and the +readers' overflow preconditions become bounds on exact products and sums. The bounds the +tactic adds for every quotient and remainder, and the rewrites that remove wrapping and +quotients once those bounds allow it, follow. +-/ + +namespace EvmRules + +/-- The all-ones word, as the printer writes `MAX`. -/ +abbrev MAX : Word := 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff + +theorem toNat_max : MAX.toNat = 2 ^ 256 - 1 := rfl + +theorem toNat_pos {a : Word} (h : a ≠ 0) : 0 < a.toNat := by + rcases Nat.eq_zero_or_pos a.toNat with h₀ | h₀ + · exact absurd (BitVec.eq_of_toNat_eq (by simpa using h₀)) h + · exact h₀ + +/-! Comparison words are the bits of decided propositions about the numbers. -/ + +theorem lt_bits (a b : Word) : Evm.lt a b = bif decide (a.toNat < b.toNat) then 1 else 0 := by + simp [Evm.lt, BitVec.ult] + +theorem gt_bits (a b : Word) : Evm.gt a b = bif decide (b.toNat < a.toNat) then 1 else 0 := by + simp [Evm.gt, BitVec.ult] + +theorem eq_bits (a b : Word) : Evm.eq a b = bif decide (a.toNat = b.toNat) then 1 else 0 := by + simp [Evm.eq, ← BitVec.toNat_eq] + +theorem ne_bits (a b : Word) : Evm.ne a b = bif decide (a.toNat ≠ b.toNat) then 1 else 0 := by + by_cases h : a = b + · subst h + simp [Evm.ne] + · have h' : a.toNat ≠ b.toNat := fun e => h (BitVec.eq_of_toNat_eq e) + simp [Evm.ne, h, h'] + +theorem iszero_bits (a : Word) : Evm.iszero a = bif decide (a.toNat = 0) then 1 else 0 := by + by_cases h : a.toNat = 0 + · have ha : a = 0 := BitVec.eq_of_toNat_eq h + subst ha + rfl + · have hb : (a == 0) = false := by + rw [beq_eq_false_iff_ne] + exact fun e => h (by rw [e]; rfl) + rw [Evm.iszero, hb] + simp [h] + +theorem or_bits (p q : Bool) : + Evm.or (bif p then 1 else 0) (bif q then 1 else 0) = bif p || q then 1 else 0 := by + cases p <;> cases q <;> decide + +theorem bits_eq_bits (p q : Prop) [Decidable p] [Decidable q] : + (bif decide p then (1 : Word) else 0) = (bif decide q then 1 else 0) ↔ (p ↔ q) := by + by_cases hp : p <;> by_cases hq : q <;> simp [hp, hq] + +theorem bits_eq_one (p : Prop) [Decidable p] : (bif decide p then (1 : Word) else 0) = 1 ↔ p := by + by_cases hp : p <;> simp [hp] + +theorem bits_eq_zero (p : Prop) [Decidable p] : + (bif decide p then (1 : Word) else 0) = 0 ↔ ¬p := by + by_cases hp : p <;> simp [hp] + +/-! Each operation as a number, with its wrapping and EVM's zero divisor. -/ + +theorem toNat_div (a b : Word) : (Evm.div a b).toNat = a.toNat / b.toNat := + BitVec.toNat_udiv + +theorem toNat_mul (a b : Word) : (Evm.mul a b).toNat = a.toNat * b.toNat % 2 ^ 256 := + BitVec.toNat_mul .. + +theorem toNat_mod_ite (a b : Word) : + (Evm.mod a b).toNat = if b.toNat = 0 then 0 else a.toNat % b.toNat := by + by_cases h : b.toNat = 0 + · have hb : b = 0 := BitVec.eq_of_toNat_eq h + subst hb + simp [Evm.mod] + · have hb : (b == 0) = false := by + rw [beq_eq_false_iff_ne] + exact fun e => h (by rw [e]; rfl) + rw [ite_eq_right h, Evm.mod, hb, Bool.cond_false, BitVec.toNat_umod] + +theorem toNat_add_wrap (a b : Word) : (Evm.add a b).toNat = (a.toNat + b.toNat) % 2 ^ 256 := + BitVec.toNat_add .. + +theorem toNat_sub_wrap (a b : Word) : + (Evm.sub a b).toNat = (2 ^ 256 - b.toNat + a.toNat) % 2 ^ 256 := + BitVec.toNat_sub .. + +/-- `ADDMOD` as a number: the exact sum, reduced by a nonzero modulus. -/ +theorem toNat_addmod (a b n : Word) : + (Evm.addmod a b n).toNat = if n.toNat = 0 then 0 else (a.toNat + b.toNat) % n.toNat := by + have ha := a.isLt + have hb := b.isLt + have hn := n.isLt + by_cases h : n.toNat = 0 + · have : n = 0 := BitVec.eq_of_toNat_eq h + subst this + rfl + · have hz : (n == 0) = false := beq_eq_false_iff_ne.mpr fun e => h (by rw [e]; rfl) + rw [Evm.addmod, hz, Bool.cond_false] + simp only [h, ↓reduceIte] + rw [BitVec.toNat_setWidth, BitVec.toNat_umod, BitVec.toNat_add, BitVec.toNat_setWidth, + BitVec.toNat_setWidth, BitVec.toNat_setWidth] + have hr := Nat.mod_lt (a.toNat + b.toNat) (Nat.pos_of_ne_zero h) + rw [Nat.mod_eq_of_lt (by omega : a.toNat < 2 ^ 512), + Nat.mod_eq_of_lt (by omega : b.toNat < 2 ^ 512), + Nat.mod_eq_of_lt (by omega : n.toNat < 2 ^ 512), + Nat.mod_eq_of_lt (by omega : a.toNat + b.toNat < 2 ^ 512), + Nat.mod_eq_of_lt (by omega : (a.toNat + b.toNat) % n.toNat < 2 ^ 256)] + +set_option exponentiation.threshold 512 in +/-- `MULMOD` as a number: the exact product, reduced by a nonzero modulus. -/ +theorem toNat_mulmod (a b n : Word) : + (Evm.mulmod a b n).toNat = if n.toNat = 0 then 0 else a.toNat * b.toNat % n.toNat := by + have ha := a.isLt + have hb := b.isLt + have hn := n.isLt + have hab : a.toNat * b.toNat < 2 ^ 512 := + calc a.toNat * b.toNat < 2 ^ 256 * 2 ^ 256 := Nat.mul_lt_mul'' ha hb + _ = 2 ^ 512 := by rw [← Nat.pow_add] + by_cases h : n.toNat = 0 + · have : n = 0 := BitVec.eq_of_toNat_eq h + subst this + rfl + · have hz : (n == 0) = false := beq_eq_false_iff_ne.mpr fun e => h (by rw [e]; rfl) + rw [Evm.mulmod, hz, Bool.cond_false] + simp only [h, ↓reduceIte] + rw [BitVec.toNat_setWidth, BitVec.toNat_umod, BitVec.toNat_mul, BitVec.toNat_setWidth, + BitVec.toNat_setWidth, BitVec.toNat_setWidth] + have hr := Nat.mod_lt (a.toNat * b.toNat) (Nat.pos_of_ne_zero h) + rw [Nat.mod_eq_of_lt (by omega : a.toNat < 2 ^ 512), + Nat.mod_eq_of_lt (by omega : b.toNat < 2 ^ 512), + Nat.mod_eq_of_lt (by omega : n.toNat < 2 ^ 512), Nat.mod_eq_of_lt hab, + Nat.mod_eq_of_lt (by omega : a.toNat * b.toNat % n.toNat < 2 ^ 256)] + +/-! The readers' overflow preconditions as bounds on the exact product or sum. -/ + +/-- `u256_mul_fits a b`: the exact product is a word. -/ +theorem mul_fits_iff (a b : Word) : + (b ≠ 0 → a ≤ Evm.div MAX b) ↔ a.toNat * b.toNat < 2 ^ 256 := by + rw [BitVec.le_def, toNat_div, toNat_max] + constructor + · intro h + by_cases hb : b = 0 + · subst hb + simp + · have := (Nat.le_div_iff_mul_le (toNat_pos hb)).mp (h hb) + omega + · intro h hb + exact (Nat.le_div_iff_mul_le (toNat_pos hb)).mpr (by omega) + +/-- `u256_add_fits a b`: the exact sum is a word. -/ +theorem add_fits_iff (a b : Word) : a ≤ Evm.sub MAX b ↔ a.toNat + b.toNat < 2 ^ 256 := by + have hb := b.isLt + rw [BitVec.le_def, Evm.sub, BitVec.toNat_sub, toNat_max] + have : (2 ^ 256 - b.toNat + (2 ^ 256 - 1)) % 2 ^ 256 = 2 ^ 256 - 1 - b.toNat := by omega + omega + +/-- `a ≤ MAX / b`, as the readers state that the exact product is a word when `b ≠ 0` is a +separate precondition. -/ +theorem le_div_max_iff (a b : Word) : + a ≤ Evm.div MAX b ↔ a.toNat * b.toNat < 2 ^ 256 ∧ (b.toNat = 0 → a.toNat = 0) := by + rw [BitVec.le_def, toNat_div, toNat_max] + by_cases hb : b.toNat = 0 + · simp [hb] + · rw [Nat.le_div_iff_mul_le (Nat.pos_of_ne_zero hb)] + omega + +/-! Bounds that `evm_arith` adds for every quotient and remainder by a non-literal. -/ + +theorem div_le_half (a b : Nat) : 2 ≤ b → a / b ≤ a / 2 := fun h => Nat.div_le_div_left h (by decide) + +theorem lt_div_mul_add_of_pos (a b : Nat) : 0 < b → a < a / b * b + b := + fun h => Nat.lt_div_mul_add h + +theorem mod_lt_of_pos (a b : Nat) : 0 < b → a % b < b := fun h => Nat.mod_lt a h + +/-! Rewrites that remove wrapping and quotients once those bounds allow it. -/ + +theorem sub_wrap_of_le {a b n : Nat} (h : b ≤ a) (ha : a < n) : (n - b + a) % n = a - b := by + rw [show n - b + a = a - b + n by omega, Nat.add_mod_right, Nat.mod_eq_of_lt (by omega)] + +/-- Rounding down to a multiple of `y` and dividing by `y` again gives the quotient, also +when `y` is zero. -/ +theorem div_mul_div_cancel (x y : Nat) : x / y * y / y = x / y := by + by_cases h : y = 0 + · simp [h] + · rw [Nat.mul_div_cancel _ (Nat.pos_of_ne_zero h)] + +theorem lt_div_succ_iff {x c m : Nat} (hc : 0 < c) : x < m / c + 1 ↔ x * c ≤ m := by + rw [Nat.lt_succ_iff, Nat.le_div_iff_mul_le hc] + +/-- A product whose wrapped value divides back to its factor did not wrap. -/ +theorem wrapped_div_eq_iff {x c n : Nat} (hc : 0 < c) (hn : 0 < n) : + x * c % n / c = x ↔ x * c < n := by + constructor + · intro h + apply Classical.byContradiction + intro hlt + have hr : x * c % n < x * c := by + have := Nat.mod_lt (x * c) hn + omega + have := (Nat.div_lt_iff_lt_mul hc).mpr hr + omega + · intro h + rw [Nat.mod_eq_of_lt h, Nat.mul_div_cancel _ hc] + +theorem eq_wrapped_div_iff {x c n : Nat} (hc : 0 < c) (hn : 0 < n) : + x = x * c % n / c ↔ x * c < n := by + rw [eq_comm] + exact wrapped_div_eq_iff hc hn + +/-- The test of a checked product `c * x`, which divides by the variable factor. -/ +theorem checked_product_left {x c n : Nat} (hn : 0 < n) : + (x = 0 ∨ x * c % n / x = c) ↔ x * c < n := by + by_cases hx : x = 0 + · simp [hx, hn] + · simp only [hx, false_or] + rw [Nat.mul_comm] + exact wrapped_div_eq_iff (Nat.pos_of_ne_zero hx) hn + +theorem checked_product_left' {x c n : Nat} (hn : 0 < n) : + (x * c % n / x = c ∨ x = 0) ↔ x * c < n := by + rw [or_comm] + exact checked_product_left hn + +/-- A share `c / d ≤ 1` of `x` never exceeds `x`, also when `x * c` wraps: the wrapped +value is still at most `x * c ≤ x * d`. -/ +theorem not_lt_share {x c d n : Nat} (hcd : c ≤ d) : ¬x < x * c % n / d := by + rcases Nat.eq_zero_or_pos d with hd | hd + · simp [hd] + · have h₁ := Nat.mod_le (x * c) n + have h₂ := Nat.mul_le_mul_left x hcd + have h₃ : x * c % n / d ≤ x * d / d := Nat.div_le_div_right (by omega) + rw [Nat.mul_div_cancel _ hd] at h₃ + omega + +end EvmRules diff --git a/vendor/evm-rules/EvmRules/ArithTactic.lean b/vendor/evm-rules/EvmRules/ArithTactic.lean new file mode 100644 index 00000000..1fa5a06a --- /dev/null +++ b/vendor/evm-rules/EvmRules/ArithTactic.lean @@ -0,0 +1,112 @@ +import Lean.Elab.Tactic.Basic +import Lean.Meta.Tactic.Assert +import EvmRules.Arith +import EvmRules.Tactic + +/-! +# `evm_arith` + +`evm_arith` proves rules over products, quotients and remainders with symbolic operands, +which bit-blasting cannot. It works over natural numbers: + +1. It substitutes equal operands, states comparison words as decided propositions and + the readers' overflow preconditions as bounds on exact products and sums. +2. It states every word as its number, writing each operation with its wrapping + (`(a + b) % 2 ^ 256`) and EVM's zero divisor. +3. `evm_div_facts` adds the bounds of every quotient and remainder by a non-literal: + `a / b ≤ a`, `a / b * b ≤ a < a / b * b + b`, `a / b * b + a % b = a` and more. +4. Rewrites whose side conditions `omega` proves from those bounds remove the wrapping + that cannot happen and the quotients in comparisons. +5. After ordering every product the same way, `omega` closes the goal, treating the + remaining products, quotients and remainders as opaque terms. + +Each step is a proof Lean's kernel checks; nothing is trusted beyond the definitions. +-/ + +namespace EvmRules + +open Lean Meta Elab Tactic + +/-- Collects the natural-number quotients (`true`) and remainders (`false`) by a +non-literal in `e` that mention no bound variables; `omega` handles literal divisors. -/ +partial def natDivMods (e : Expr) (acc : Array (Bool × Expr × Expr)) : + Array (Bool × Expr × Expr) := + match e with + | .app .. => + let args := e.getAppArgs + let acc := args.foldl (fun acc a => natDivMods a acc) (natDivMods e.getAppFn acc) + let isDiv := e.isAppOfArity ``HDiv.hDiv 6 + if (isDiv || e.isAppOfArity ``HMod.hMod 6) && args[0]! == mkConst ``Nat + && !e.hasLooseBVars && args[5]!.nat?.isNone then + let entry := (isDiv, args[4]!, args[5]!) + if acc.contains entry then acc else acc.push entry + else acc + | .forallE _ d b _ | .lam _ d b _ => natDivMods b (natDivMods d acc) + | .mdata _ b | .proj _ _ b => natDivMods b acc + | .letE _ t v b _ => natDivMods b (natDivMods v (natDivMods t acc)) + | _ => acc + +/-- Adds the bounds of every natural-number quotient and remainder by a non-literal in +the goal and its hypotheses, so that `omega` can treat them as opaque terms. -/ +elab "evm_div_facts" : tactic => withMainContext do + let mut found := natDivMods (← instantiateMVars (← getMainTarget)) #[] + for decl in ← getLCtx do + unless decl.isImplementationDetail do + found := natDivMods (← instantiateMVars decl.type) found + for (isDiv, a, b) in found do + let lemmas := if isDiv then + #[``Nat.div_le_self, ``Nat.div_mul_le_self, ``div_le_half, ``lt_div_mul_add_of_pos] + else #[``Nat.mod_le, ``mod_lt_of_pos, ``Nat.div_add_mod'] + for lemma in lemmas do + let proof ← mkAppM lemma #[a, b] + let type ← inferType proof + liftMetaTactic fun goal => do + let goal ← goal.assert `bound type proof + let (_, goal) ← goal.intro1P + return [goal] + +end EvmRules + +/-- Proves a rule over products, quotients and remainders; see `EvmRules/ArithTactic.lean`. -/ +macro "evm_arith" : tactic => `(tactic| ( + subst_vars + try simp only [↓ EvmRules.mul_fits_iff, ↓ EvmRules.add_fits_iff, ↓ EvmRules.le_div_max_iff, + EvmRules.lt_bits, EvmRules.gt_bits, EvmRules.eq_bits, EvmRules.ne_bits, EvmRules.iszero_bits, + EvmRules.or_bits, ← Bool.decide_or, ite_true, ite_false, EvmRules.bits_eq_bits, + EvmRules.bits_eq_one, EvmRules.bits_eq_zero] at * + try simp only [BitVec.toNat_eq, BitVec.le_def, BitVec.lt_def, ne_eq, EvmRules.toNat_div, + EvmRules.toNat_mul, EvmRules.toNat_add_wrap, EvmRules.toNat_sub_wrap, + EvmRules.toNat_mod_ite, EvmRules.toNat_addmod, EvmRules.toNat_mulmod, Nat.add_zero, + Nat.zero_add, Nat.mul_one, Nat.one_mul, BitVec.ofNat_eq_ofNat, BitVec.toNat_ofNat, + Nat.reducePow, Nat.reduceMod] at * + all_goals evm_div_facts + try simp (disch := omega) only [Nat.mod_eq_of_lt, EvmRules.sub_wrap_of_le, ite_eq_left, + ite_eq_right, Nat.div_div_eq_div_mul, EvmRules.div_mul_div_cancel, Nat.div_lt_iff_lt_mul, + Nat.le_div_iff_mul_le, Nat.div_eq_zero_iff_lt, Nat.lt_div_iff_mul_lt, + Nat.div_le_iff_le_mul_add_pred, EvmRules.lt_div_succ_iff, EvmRules.wrapped_div_eq_iff, + EvmRules.eq_wrapped_div_iff, EvmRules.checked_product_left, + EvmRules.checked_product_left', EvmRules.not_lt_share, Nat.div_eq_of_lt, + Nat.mul_div_cancel, Nat.mul_div_cancel_left, not_false_eq_true, + not_true_eq_false, iff_self, false_iff, iff_false, true_iff, iff_true] at * + try simp only [Nat.mul_comm, Nat.mul_left_comm] at * + all_goals omega)) + +open Lean in +/-- Records the tactic that proved a theorem, for the verification report. -/ +elab "evm_proved_by " name:str : tactic => logInfo m!"proved by {name.getString}" + +/-- Tries `evm_arith`, `evm_decide` with a SAT limit of at most five seconds, `evm_bits`, +`evm_ring`, `evm_simp` with the same short limit, and finally `evm_decide` with a SAT limit of +`n` seconds, and records which one proved the goal. Most rules bit-blast within the short limit; +the tactics that avoid a SAT solver, and the lemmas of `Simp.lean`, run before a long search for +the shapes that bit-blasting handles poorly. The last attempt reports the counterexample of a +false rule. -/ +macro "evm_auto " n:num : tactic => do + let short := Lean.Syntax.mkNumLit (toString (min 5 n.getNat)) + `(tactic| first + | (evm_arith; evm_proved_by "evm_arith") + | (evm_decide $short; evm_proved_by "evm_decide") + | (evm_bits; evm_proved_by "evm_bits") + | (evm_ring; evm_proved_by "evm_ring") + | (evm_simp $short; evm_proved_by "evm_simp") + | (evm_decide $n; evm_proved_by "evm_decide")) diff --git a/vendor/evm-rules/EvmRules/Bitblast.lean b/vendor/evm-rules/EvmRules/Bitblast.lean new file mode 100644 index 00000000..aefaffd1 --- /dev/null +++ b/vendor/evm-rules/EvmRules/Bitblast.lean @@ -0,0 +1,42 @@ +import EvmRules.Word + +/-! +# Bit-blasting forms + +The shifts state the word-width case as the specification does. Lean's shifts by a +`BitVec` amount already saturate, so these forms are equal and need no comparison. +-/ + +namespace EvmRules.Evm + +theorem shl_eq (shift value : Word) : shl shift value = value <<< shift := by + unfold shl + by_cases h : shift.toNat < 256 + · simp [BitVec.ult, h] + · have h' : shift.ult 256 = false := by simp [BitVec.ult]; omega + rw [h', Bool.cond_false, BitVec.shiftLeft_eq', BitVec.shiftLeft_eq_zero (by omega)] + rfl + +theorem shr_eq (shift value : Word) : shr shift value = value >>> shift := by + unfold shr + by_cases h : shift.toNat < 256 + · simp [BitVec.ult, h] + · have h' : shift.ult 256 = false := by simp [BitVec.ult]; omega + rw [h', Bool.cond_false, BitVec.ushiftRight_eq', BitVec.ushiftRight_eq_zero (by omega)] + rfl + +theorem sar_eq (shift value : Word) : sar shift value = value.sshiftRight' shift := by + unfold sar + by_cases h : shift.toNat < 256 + · simp [BitVec.ult, h] + · have h' : shift.ult 256 = false := by simp [BitVec.ult]; omega + rw [h', Bool.cond_false] + apply BitVec.eq_of_getLsbD_eq + intro i hi + rw [BitVec.getLsbD_sshiftRight', ite_eq_right (by omega)] + cases hm : value.msb + · simp + · rw [Bool.cond_true, show (-1 : Word) = BitVec.allOnes 256 by decide, BitVec.getLsbD_allOnes] + simp [hi] + +end EvmRules.Evm diff --git a/vendor/evm-rules/EvmRules/Bits.lean b/vendor/evm-rules/EvmRules/Bits.lean new file mode 100644 index 00000000..3e84e1d2 --- /dev/null +++ b/vendor/evm-rules/EvmRules/Bits.lean @@ -0,0 +1,133 @@ +import EvmRules.Arith +import EvmRules.Bitblast + +/-! +# Word operations bit by bit + +Bit `i` of every word operation `evm_bits` (`Tactic.lean`) reads, as a bit of its operand at +an index computed from the shift count or byte index. Bit-blasting builds a barrel shifter for +every variable shift count and a 31-way choice for every variable `SIGNEXTEND` index, which +SAT solvers handle poorly once two of them interact. Stated bit by bit, a rule over variable +counts becomes linear arithmetic over the indices instead. +-/ + +namespace EvmRules + +theorem signExtend_low_bits (x : Word) (w : Nat) (hw : 0 < w) (i : Nat) (hi : i < 256) : + ((x.setWidth w).signExtend 256).getLsbD i = x.getLsbD (min i (w - 1)) := by + rw [BitVec.getLsbD_signExtend] + by_cases h : i < w + · simp [hi, h, Nat.min_eq_left (show i ≤ w - 1 by omega)] + · simp [hi, h, BitVec.msb_setWidth, Nat.min_eq_right (show w - 1 ≤ i by omega), hw] + +/-- `SIGNEXTEND n x` repeats bit `8n + 7` of `x` upward; every index from 31 on keeps `x`. -/ +theorem bits_signextend (n x : Word) (i : Nat) : + (Evm.signextend n x).getLsbD i = + (decide (i < 256) && x.getLsbD (min i (n.toNat * 8 + 7))) := by + by_cases hi : i < 256 + · simp only [hi, decide_true, Bool.true_and] + unfold Evm.signextend + by_cases h : n.toNat < 31 + · have hn : n = BitVec.ofNat 256 n.toNat := by simp + generalize n.toNat = k at h hn + subst hn + rcases k with _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | + _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | k + all_goals first + | omega + | simp (disch := omega) [signExtend_low_bits, -BitVec.getLsbD_eq_getElem] + · have hne : ∀ k : Word, k.toNat < 31 → (n == k) = false := by + intro k hk + simp only [beq_eq_false_iff_ne, ne_eq, BitVec.toNat_eq] + omega + simp (disch := simp) only [hne, Bool.cond_false] + rw [Nat.min_eq_left (by omega)] + · simp [hi, BitVec.getLsbD_of_ge _ _ (by omega : 256 ≤ i)] + +theorem bits_shl (s x : Word) (i : Nat) : + (Evm.shl s x).getLsbD i = + (decide (i < 256) && !decide (i < s.toNat) && x.getLsbD (i - s.toNat)) := by + rw [Evm.shl_eq, BitVec.getLsbD_shiftLeft'] + +/-- Bits shifted in from beyond the word are zero, also once the count reaches the width. -/ +theorem bits_shr (s x : Word) (i : Nat) : (Evm.shr s x).getLsbD i = x.getLsbD (s.toNat + i) := by + rw [Evm.shr_eq, BitVec.ushiftRight_eq', BitVec.getLsbD_ushiftRight] + +/-- Bits shifted in from beyond the word copy the sign bit 255. -/ +theorem bits_sar (s x : Word) (i : Nat) : + (Evm.sar s x).getLsbD i = (decide (i < 256) && x.getLsbD (min (s.toNat + i) 255)) := by + rw [Evm.sar_eq, BitVec.getLsbD_sshiftRight', BitVec.msb_eq_getLsbD_last] + by_cases hi : i < 256 + · by_cases h : s.toNat + i < 256 + · simp [hi, h, Nat.min_eq_left (show s.toNat + i ≤ 255 by omega)] + · simp [hi, h, Nat.min_eq_right (show 255 ≤ s.toNat + i by omega)] + · simp [hi, show 256 ≤ i by omega] + +/-- The low-bits mask `(1 << n) - 1`: every bit below `n`, so all of them from 256 on. -/ +theorem bits_mask (n : Word) (i : Nat) : + (Evm.sub (Evm.shl n 1) 1).getLsbD i = (decide (i < 256) && decide (i < n.toNat)) := by + rw [Evm.sub, Evm.shl_eq, BitVec.shiftLeft_eq', show (1 : Word) = 1#256 from rfl, + ← BitVec.not_neg, ← BitVec.shiftLeft_neg] + simp only [BitVec.getLsbD_not, BitVec.getLsbD_shiftLeft, BitVec.neg_one_eq_allOnes, + BitVec.getLsbD_allOnes] + by_cases hi : i < 256 <;> simp [hi] <;> omega + +theorem bits_max (i : Nat) : + (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff : Word).getLsbD i = + decide (i < 256) := by + rw [show (0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff : Word) = + BitVec.allOnes 256 from rfl, BitVec.getLsbD_allOnes] + +theorem bits_address_mask (i : Nat) : + (0xffffffffffffffffffffffffffffffffffffffff : Word).getLsbD i = decide (i < 160) := by + rw [show (0xffffffffffffffffffffffffffffffffffffffff : Word) = BitVec.ofNat 256 (2 ^ 160 - 1) + from rfl, BitVec.getLsbD_ofNat, Nat.testBit_two_pow_sub_one] + by_cases h : i < 160 <;> simp [h] <;> omega + +theorem bits_one (i : Nat) : (1 : Word).getLsbD i = decide (i = 0) := by + rw [show (1 : Word) = 1#256 from rfl, BitVec.getLsbD_one] + simp + +theorem bits_zero (i : Nat) : (0 : Word).getLsbD i = false := by + rw [show (0 : Word) = 0#256 from rfl, BitVec.getLsbD_zero] + +/-! The indices above are numbers; these state the counts the readers compute as numbers. -/ + +/-- The smaller of two words, as the e-graph selects it. -/ +theorem toNat_select_lt (a b : Word) : + (Evm.select (Evm.lt a b) a b).toNat = min a.toNat b.toNat := by + unfold Evm.select Evm.lt + by_cases h : a.toNat < b.toNat <;> simp [BitVec.ult, h] <;> omega + +/-- The larger of two words, as the e-graph selects it. -/ +theorem toNat_select_gt (a b : Word) : + (Evm.select (Evm.gt a b) a b).toNat = max a.toNat b.toNat := by + unfold Evm.select Evm.gt + by_cases h : b.toNat < a.toNat <;> simp [BitVec.ult, h] <;> omega + +theorem toNat_shr (s x : Word) : (Evm.shr s x).toNat = x.toNat / 2 ^ s.toNat := by + rw [Evm.shr_eq, BitVec.ushiftRight_eq', BitVec.toNat_ushiftRight, Nat.shiftRight_eq_div_pow] + +theorem toNat_shl (s x : Word) : (Evm.shl s x).toNat = x.toNat * 2 ^ s.toNat % 2 ^ 256 := by + rw [Evm.shl_eq, BitVec.shiftLeft_eq', BitVec.toNat_shiftLeft, Nat.shiftLeft_eq] + +theorem toNat_shl_one {k : Word} (h : k < 256) : (Evm.shl k 1).toNat = 2 ^ k.toNat := by + rw [toNat_shl, show (1 : Word).toNat = 1 from rfl, Nat.one_mul, + Nat.mod_eq_of_lt (Nat.pow_lt_pow_right (by decide) (show k.toNat < 256 from h))] + +/-- A count that is a whole number of bytes, as the readers test it. -/ +theorem and_seven_eq_zero (s : Word) : Evm.and s 7 = 0 ↔ s.toNat % 8 = 0 := by + rw [Evm.and, ← BitVec.toNat_inj, BitVec.toNat_and, show (7 : Word).toNat = 2 ^ 3 - 1 from rfl, + Nat.and_two_pow_sub_one_eq_mod] + rfl + +/-- Multiplication by the low-bits mask negates within those bits. -/ +theorem mul_low_mask {lo hi : Nat} (x : BitVec (hi + lo)) : + (x * (BitVec.allOnes lo).setWidth (hi + lo)) &&& (BitVec.allOnes lo).setWidth (hi + lo) = + (-x) &&& (BitVec.allOnes lo).setWidth (hi + lo) := by + rw [BitVec.and_setWidth_allOnes, BitVec.and_setWidth_allOnes] + congr 1 + rw [BitVec.setWidth_mul _ _ (by omega), BitVec.setWidth_neg_of_le (by omega)] + simp [← BitVec.neg_one_eq_allOnes, BitVec.mul_neg] + +end EvmRules diff --git a/vendor/evm-rules/EvmRules/Casts.lean b/vendor/evm-rules/EvmRules/Casts.lean new file mode 100644 index 00000000..5ac3631a --- /dev/null +++ b/vendor/evm-rules/EvmRules/Casts.lean @@ -0,0 +1,173 @@ +import EvmRules.Bits + +/-! +# Structural rewrites + +Identities that `evm_decide` (`Tactic.lean`) rewrites with before bit-blasting. Each replaces a +nest of variable shifts or extensions, which bit-blasting handles poorly, by one equivalent +operation, so that many rules over them hold syntactically afterwards. The reader states MIR +`sext value from to` as `(sar s (shl s value)) & ((1 << to) - 1)` with the count +`s = 256 - min(from, 256)`; the lemmas below match that form. +-/ + +namespace EvmRules + +/-- Bit `i` of the reader's `sext x n m`: the low `n` bits of `x` with the top one repeated, +cut to `m` bits; zero for a zero width. -/ +theorem bits_sext (n m x : Word) (i : Nat) : + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) x)) + (Evm.sub (Evm.shl m 1) 1)).getLsbD i = + (decide (i < 256) && decide (i < m.toNat) && decide (0 < n.toNat) && + x.getLsbD (min i (n.toNat - 1))) := by + have hs : (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)).toNat = 256 - min n.toNat 256 := by + rw [toNat_sub_wrap, toNat_select_lt, show (256 : Word).toNat = 256 from rfl] + omega + rw [Evm.and, BitVec.getLsbD_and, bits_mask, bits_sar, bits_shl, hs] + by_cases hi : i < 256 <;> by_cases hn : 0 < n.toNat <;> by_cases hm : i < m.toNat <;> + simp [hi, hn, hm] <;> grind + +/-- Nested `SIGNEXTEND`s keep the narrower extension. -/ +theorem signextend_signextend (a b x : Word) : + Evm.signextend a (Evm.signextend b x) = Evm.signextend (Evm.select (Evm.lt a b) a b) x := by + apply BitVec.eq_of_getLsbD_eq + intro i hi + simp only [bits_signextend, toNat_select_lt] + grind + +theorem select_same (c a : Word) : Evm.select c a a = a := by + unfold Evm.select + cases c == 0 <;> rfl + +/-- Extending the low `a` bits, then the low `b > a` bits of the result, extends the low `a` +bits once. -/ +theorem sext_sext (a b c x : Word) (h : a < b) : + Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt b 256) b 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt b 256) b 256)) + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt a 256) a 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt a 256) a 256)) x)) + (Evm.sub (Evm.shl b 1) 1)))) + (Evm.sub (Evm.shl c 1) 1) = + Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt a 256) a 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt a 256) a 256)) x)) + (Evm.sub (Evm.shl c 1) 1) := by + rw [BitVec.lt_def] at h + apply BitVec.eq_of_getLsbD_eq + intro i hi + simp only [bits_sext] + grind + +/-- Equality words agree when the equalities they test are equivalent. -/ +theorem eq_congr_iff {a b c d : Word} (h : a = b ↔ c = d) : Evm.eq a b = Evm.eq c d := by + unfold Evm.eq + by_cases e : c = d + · rw [beq_iff_eq.mpr (h.mpr e), beq_iff_eq.mpr e] + · rw [beq_eq_false_iff_ne.mpr (mt h.mp e), beq_eq_false_iff_ne.mpr e] + +theorem ne_congr_iff {a b c d : Word} (h : a = b ↔ c = d) : Evm.ne a b = Evm.ne c d := by + unfold Evm.ne + by_cases e : c = d + · rw [beq_iff_eq.mpr (h.mpr e), beq_iff_eq.mpr e] + · rw [beq_eq_false_iff_ne.mpr (mt h.mp e), beq_eq_false_iff_ne.mpr e] + +/-- A value of at most `n` bits is recovered from its extension to more bits. -/ +theorem sext_inj (n m x y : Word) (h₁ : 1 ≤ n) (h₂ : n < m) + (hx : Evm.and x (Evm.sub (Evm.shl n 1) 1) = x) (hy : Evm.and y (Evm.sub (Evm.shl n 1) 1) = y) : + Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) x)) + (Evm.sub (Evm.shl m 1) 1) = + Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) y)) + (Evm.sub (Evm.shl m 1) 1) ↔ x = y := by + constructor + · intro h + rw [BitVec.le_def] at h₁ + rw [BitVec.lt_def] at h₂ + rw [BitVec.eq_of_getLsbD_eq_iff] at h hx hy ⊢ + intro i hi + have e := h i hi + have ex := hx i hi + have ey := hy i hi + rw [bits_sext, bits_sext] at e + simp only [Evm.and, BitVec.getLsbD_and, bits_mask] at ex ey + simp only [show (1 : Word).toNat = 1 from rfl] at h₁ + grind + · rintro rfl + rfl + +theorem eq_sext_sext (n m x y : Word) (h₁ : 1 ≤ n) (h₂ : n < m) + (hx : Evm.and x (Evm.sub (Evm.shl n 1) 1) = x) (hy : Evm.and y (Evm.sub (Evm.shl n 1) 1) = y) : + Evm.eq + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) x)) + (Evm.sub (Evm.shl m 1) 1)) + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) y)) + (Evm.sub (Evm.shl m 1) 1)) = Evm.eq x y := + eq_congr_iff (sext_inj n m x y h₁ h₂ hx hy) + +theorem ne_sext_sext (n m x y : Word) (h₁ : 1 ≤ n) (h₂ : n < m) + (hx : Evm.and x (Evm.sub (Evm.shl n 1) 1) = x) (hy : Evm.and y (Evm.sub (Evm.shl n 1) 1) = y) : + Evm.ne + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) x)) + (Evm.sub (Evm.shl m 1) 1)) + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) y)) + (Evm.sub (Evm.shl m 1) 1)) = Evm.ne x y := + ne_congr_iff (sext_inj n m x y h₁ h₂ hx hy) + +theorem eq_sext_zero (n m x : Word) (h₁ : 1 ≤ n) (h₂ : n < m) + (hx : Evm.and x (Evm.sub (Evm.shl n 1) 1) = x) : + Evm.eq + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) x)) + (Evm.sub (Evm.shl m 1) 1)) 0 = Evm.eq x 0 := by + simpa [Evm.shl, Evm.sar, Evm.and] using + eq_sext_sext n m x 0 h₁ h₂ hx (by simp [Evm.and]) + +theorem ne_sext_zero (n m x : Word) (h₁ : 1 ≤ n) (h₂ : n < m) + (hx : Evm.and x (Evm.sub (Evm.shl n 1) 1) = x) : + Evm.ne + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) x)) + (Evm.sub (Evm.shl m 1) 1)) 0 = Evm.ne x 0 := by + simpa [Evm.shl, Evm.sar, Evm.and] using + ne_sext_sext n m x 0 h₁ h₂ hx (by simp [Evm.and]) + +/-- Unsigned division by a power of two is a right shift, also once the count reaches the +word width and the divisor is zero. -/ +theorem div_shl_one (x n : Word) : Evm.div x (Evm.shl n 1) = Evm.shr n x := by + apply BitVec.eq_of_toNat_eq + rw [toNat_div, toNat_shr] + by_cases h : n < 256 + · rw [toNat_shl_one h] + · have hn : 256 ≤ n.toNat := by + have : ¬n.toNat < 256 := h + omega + have hz : Evm.shl n 1 = 0 := by + rw [Evm.shl, show n.ult 256 = false by simp [BitVec.ult]; omega] + rfl + rw [hz, show (0 : Word).toNat = 0 from rfl, Nat.div_zero, Nat.div_eq_of_lt] + exact Nat.lt_of_lt_of_le x.isLt (Nat.pow_le_pow_right (by decide) hn) + +/-- A word of at most one is a boolean, for `evm_ring` to split on. -/ +theorem le_one_iff (c : Word) : c ≤ 1 ↔ c = 0 ∨ c = 1 := by + constructor + · intro h + bv_omega + · rintro (rfl | rfl) <;> decide + +end EvmRules diff --git a/vendor/evm-rules/EvmRules/Lemmas.lean b/vendor/evm-rules/EvmRules/Lemmas.lean new file mode 100644 index 00000000..f1675d79 --- /dev/null +++ b/vendor/evm-rules/EvmRules/Lemmas.lean @@ -0,0 +1,130 @@ +import EvmRules.Tactic + +/-! +# Lemmas for hand-written rule proofs + +Facts about the `Evm` definitions that the scripts in `proofs/` share. +-/ + +namespace EvmRules + +/-- `EXP` of the all-ones word, which is `-1`: one for even exponents, itself for odd ones. -/ +theorem max_pow (k : Nat) : MAX ^ k = if k % 2 = 0 then 1 else MAX := by + induction k with + | zero => rfl + | succ k ih => + rw [BitVec.pow_succ, ih] + by_cases h : k % 2 = 0 + · rw [ite_eq_left h, ite_eq_right (by omega)] + exact BitVec.one_mul _ + · rw [ite_eq_right h, ite_eq_left (by omega)] + decide + +/-- A left shift that the same right shift undoes kept every bit: it multiplied by a power of +two without wrapping. -/ +theorem toNat_shl_of_shr_shl {s x : Word} (h : Evm.shr s (Evm.shl s x) = x) : + (Evm.shl s x).toNat = x.toNat * 2 ^ s.toNat := by + have hd := congrArg BitVec.toNat h + rw [toNat_shr] at hd + have hdvd : 2 ^ s.toNat ∣ (Evm.shl s x).toNat := by + rw [toNat_shl] + by_cases hs : s.toNat ≤ 256 + · rw [Nat.dvd_mod_iff (Nat.pow_dvd_pow 2 hs)] + exact Nat.dvd_mul_left _ _ + · rw [Nat.mod_eq_zero_of_dvd (Nat.dvd_mul_left_of_dvd (Nat.pow_dvd_pow 2 (by omega)) _)] + exact Nat.dvd_zero _ + rw [← Nat.div_mul_cancel hdvd, hd] + +theorem shr_shl (s x : Word) : Evm.shr s (Evm.shl s x) = Evm.and x (Evm.shr s MAX) := by + apply BitVec.eq_of_getLsbD_eq + intro i hi + simp only [bits_shr, bits_shl, Evm.and, BitVec.getLsbD_and, bits_max] + grind + +/-- With its top `s` bits clear, `x` survives a left shift by `s`. -/ +theorem shr_shl_of_clear {s x : Word} (h : Evm.and (Evm.shr s MAX) x = x) : + Evm.shr s (Evm.shl s x) = x := by + rw [shr_shl, Evm.and, BitVec.and_comm] + exact h + +/-- Multiplying by an odd word is invertible modulo 2²⁵⁶. -/ +theorem mul_odd_inj {c : Word} (hc : Evm.and c 1 = 1) (x y : Word) : + Evm.mul x c = Evm.mul y c ↔ x = y := by + constructor + · intro h + have hodd : c.toNat % 2 = 1 := by + have := congrArg BitVec.toNat hc + rwa [Evm.and, BitVec.toNat_and, show (1 : Word).toNat = 1 from rfl, + Nat.and_one_is_mod] at this + have hcop : Nat.Coprime (2 ^ 256) c.toNat := by + apply Nat.Coprime.pow_left + show Nat.gcd 2 c.toNat = 1 + rw [Nat.gcd_rec, hodd] + rfl + have h' := congrArg BitVec.toNat h + rw [toNat_mul, toNat_mul] at h' + have hx := x.isLt + have hy := y.isLt + apply BitVec.eq_of_toNat_eq + rcases Nat.le_total y.toNat x.toNat with hle | hle + · have hd : 2 ^ 256 ∣ (x.toNat - y.toNat) * c.toNat := by + rw [Nat.sub_mul] + exact Nat.dvd_of_mod_eq_zero (Nat.sub_mod_eq_zero_of_mod_eq h') + have := Nat.eq_zero_of_dvd_of_lt (hcop.dvd_of_dvd_mul_right hd) (by omega) + omega + · have hd : 2 ^ 256 ∣ (y.toNat - x.toNat) * c.toNat := by + rw [Nat.sub_mul] + exact Nat.dvd_of_mod_eq_zero (Nat.sub_mod_eq_zero_of_mod_eq h'.symm) + have := Nat.eq_zero_of_dvd_of_lt (hcop.dvd_of_dvd_mul_right hd) (by omega) + omega + · rintro rfl + rfl + +/-- A power of two up to the word width divides a word's signed value exactly when it divides +its unsigned value. -/ +theorem pow_dvd_toInt_iff (x : Word) {k : Nat} (hk : k ≤ 256) : + ((2 ^ k : Nat) : Int) ∣ x.toInt ↔ x.toNat % 2 ^ k = 0 := by + have hw : ((2 ^ k : Nat) : Int) ∣ ((2 ^ 256 : Nat) : Int) := + Int.natCast_dvd_natCast.mpr (Nat.pow_dvd_pow 2 hk) + rw [← Nat.dvd_iff_mod_eq_zero, ← Int.natCast_dvd_natCast, BitVec.toInt_eq_toNat_cond] + split + · exact Iff.rfl + · constructor + · intro h + simpa using Int.dvd_add h hw + · intro h + exact Int.dvd_sub h hw + +/-- The mask below a power of two `m = 1 << k`. -/ +theorem toNat_mask_of_pow {m k : Word} (h : k < 256) (hm : m = Evm.shl k 1) : + (Evm.sub m 1).toNat = 2 ^ k.toNat - 1 := by + subst hm + have hp : 2 ^ k.toNat < 2 ^ 256 := Nat.pow_lt_pow_right (by decide) (show k.toNat < 256 from h) + have h1 : 1 ≤ 2 ^ k.toNat := Nat.one_le_two_pow + rw [Evm.sub, BitVec.toNat_sub, toNat_shl_one h, show (1 : Word).toNat = 1 from rfl] + omega + +/-- A signed remainder by a power of two below the sign bit is zero exactly when the low bits +are. -/ +theorem smod_pow_eq_zero_iff (x m k : Word) (h₁ : k < 256) (h₂ : m = Evm.shl k 1) + (h₃ : k.toNat < 255) : Evm.smod x m = 0 ↔ Evm.and x (Evm.sub m 1) = 0 := by + have hmask := toNat_mask_of_pow h₁ h₂ + subst h₂ + have hc := toNat_shl_one h₁ + have hp : 2 ^ k.toNat < 2 ^ 255 := Nat.pow_lt_pow_right (by decide) h₃ + have hcm : (Evm.shl k 1).msb = false := by + rw [BitVec.msb_eq_false_iff_two_mul_lt, hc] + omega + have hm0 : Evm.shl k 1 ≠ 0 := by + intro e + have := congrArg BitVec.toNat e + rw [hc] at this + have := Nat.one_le_two_pow (n := k.toNat) + simp_all + rw [Evm.smod, beq_eq_false_iff_ne.mpr hm0, Bool.cond_false, ← BitVec.toInt_inj, + BitVec.toInt_srem, BitVec.toInt_eq_toNat_of_msb hcm, hc, show (0 : Word).toInt = 0 from rfl, + ← Int.dvd_iff_tmod_eq_zero, pow_dvd_toInt_iff x (by omega), ← BitVec.toNat_inj, Evm.and, + BitVec.toNat_and, hmask, Nat.and_two_pow_sub_one_eq_mod] + rfl + +end EvmRules diff --git a/vendor/evm-rules/EvmRules/Reference.lean b/vendor/evm-rules/EvmRules/Reference.lean new file mode 100644 index 00000000..24abdc99 --- /dev/null +++ b/vendor/evm-rules/EvmRules/Reference.lean @@ -0,0 +1,207 @@ +import EvmRules.Bits + +/-! +# A second transcription of the EVM semantics + +The definitions of paradigmxyz/solar#1648, which transcribed the same execution specifications +independently of `Word.lean`: shifts by a natural count, zero divisors as an explicit case, +`SIGNEXTEND` as a pair of shifts, and comparisons as the `if` terms that its printer wrote. +Every theorem below proves that the definition the rules are checked against agrees with this +one on all inputs, so a transcription error would have to be made twice, in two different +forms, to go unnoticed. The proofs avoid `bv_decide` and rely on Lean's kernel alone. +-/ + +namespace EvmRules.Reference + +def shl (count value : Word) : Word := + if count < 256#256 then value <<< count.toNat else 0#256 + +def shr (count value : Word) : Word := + if count < 256#256 then value >>> count.toNat else 0#256 + +def sar (count value : Word) : Word := + if count < 256#256 then value.sshiftRight count.toNat else value.sshiftRight 256 + +def div (a b : Word) : Word := if b = 0#256 then 0#256 else a / b + +def mod (a b : Word) : Word := if b = 0#256 then 0#256 else a % b + +def sdiv (a b : Word) : Word := if b = 0#256 then 0#256 else a.sdiv b + +def smod (a b : Word) : Word := if b = 0#256 then 0#256 else a.srem b + +def addmod (a b n : Word) : Word := + if n = 0#256 then 0#256 else ((a.setWidth 512 + b.setWidth 512) % n.setWidth 512).setWidth 256 + +def mulmod (a b n : Word) : Word := + if n = 0#256 then 0#256 else ((a.setWidth 512 * b.setWidth 512) % n.setWidth 512).setWidth 256 + +def exp (a b : Word) : Word := a ^ b.toNat + +def byte (index value : Word) : Word := + if index < 32#256 then shr ((31#256 - index) * 8#256) value &&& 255#256 else 0#256 + +def signextend (index value : Word) : Word := + if index < 31#256 then sar (248#256 - index * 8#256) (shl (248#256 - index * 8#256) value) + else value + +def clz (value : Word) : Word := value.clz + +/-! The comparison and selection terms #1648's printer wrote. -/ + +def lt (a b : Word) : Word := if a < b then 1 else 0 + +def gt (a b : Word) : Word := if a > b then 1 else 0 + +def slt (a b : Word) : Word := if BitVec.slt a b = true then 1 else 0 + +def sgt (a b : Word) : Word := if BitVec.slt b a = true then 1 else 0 + +def eq (a b : Word) : Word := if a = b then 1 else 0 + +def ne (a b : Word) : Word := if a ≠ b then 1 else 0 + +def iszero (a : Word) : Word := if a = 0 then 1 else 0 + +def select (c a b : Word) : Word := if c ≠ 0 then a else b + +end EvmRules.Reference + +namespace EvmRules + +/-! Every operation agrees with the second transcription. -/ + +theorem shl_agrees (count value : Word) : Evm.shl count value = Reference.shl count value := by + rw [Evm.shl_eq, BitVec.shiftLeft_eq'] + unfold Reference.shl + split + · rfl + · rename_i h + rw [BitVec.shiftLeft_eq_zero (by simp only [BitVec.lt_def] at h; simp at h; omega)] + +theorem shr_agrees (count value : Word) : Evm.shr count value = Reference.shr count value := by + rw [Evm.shr_eq, BitVec.ushiftRight_eq'] + unfold Reference.shr + split + · rfl + · rename_i h + rw [BitVec.ushiftRight_eq_zero (by simp only [BitVec.lt_def] at h; simp at h; omega)] + +theorem sar_agrees (count value : Word) : Evm.sar count value = Reference.sar count value := by + rw [Evm.sar_eq, BitVec.sshiftRight_eq'] + unfold Reference.sar + split + · rfl + · rename_i h + have hc : 256 ≤ count.toNat := by + simp only [BitVec.lt_def] at h + simp at h + omega + exact BitVec.sshiftRight_eq_sshiftRight_of_le hc (by omega) + +theorem div_agrees (a b : Word) : Evm.div a b = Reference.div a b := by + unfold Evm.div Reference.div + split + · rename_i h + subst h + exact BitVec.udiv_zero + · rfl + +theorem mod_agrees (a b : Word) : Evm.mod a b = Reference.mod a b := by + unfold Evm.mod Reference.mod + by_cases h : b = 0 <;> simp [h] + +theorem sdiv_agrees (a b : Word) : Evm.sdiv a b = Reference.sdiv a b := by + unfold Evm.sdiv Reference.sdiv + split + · rename_i h + subst h + exact BitVec.sdiv_zero + · rfl + +theorem smod_agrees (a b : Word) : Evm.smod a b = Reference.smod a b := by + unfold Evm.smod Reference.smod + by_cases h : b = 0 <;> simp [h] + +theorem addmod_agrees (a b n : Word) : Evm.addmod a b n = Reference.addmod a b n := by + unfold Evm.addmod Reference.addmod + by_cases h : n = 0 <;> simp [h] + +theorem mulmod_agrees (a b n : Word) : Evm.mulmod a b n = Reference.mulmod a b n := by + unfold Evm.mulmod Reference.mulmod + by_cases h : n = 0 <;> simp [h] + +theorem exp_agrees (a b : Word) : Evm.exp a b = Reference.exp a b := rfl + +theorem clz_agrees (a : Word) : Evm.clz a = Reference.clz a := rfl + +theorem byte_agrees (index value : Word) : Evm.byte index value = Reference.byte index value := by + unfold Evm.byte Reference.byte + by_cases h : index.toNat < 32 + · have hc : ((31#256 - index) * 8#256).toNat < 256 := by bv_omega + rw [show index.ult 32 = true by simp [BitVec.ult, h], + ite_eq_left (show index < 32#256 from h), ← shr_agrees, Evm.shr_eq] + rfl + · rw [show index.ult 32 = false by simp [BitVec.ult]; omega, + ite_eq_right (show ¬index < 32#256 from h)] + rfl + +theorem signextend_agrees (index value : Word) : + Evm.signextend index value = Reference.signextend index value := by + unfold Reference.signextend + rw [← shl_agrees, ← sar_agrees] + apply BitVec.eq_of_getLsbD_eq + intro i hi + rw [bits_signextend] + split + · rename_i h + have hn : index.toNat < 31 := h + have hs : (248#256 - index * 8#256).toNat = 248 - index.toNat * 8 := by bv_omega + rw [bits_sar, bits_shl, hs] + have e₁ : min (248 - index.toNat * 8 + i) 255 < 256 := by omega + have e₂ : ¬min (248 - index.toNat * 8 + i) 255 < 248 - index.toNat * 8 := by omega + have e₃ : min (248 - index.toNat * 8 + i) 255 - (248 - index.toNat * 8) = + min i (index.toNat * 8 + 7) := by omega + simp only [hi, e₁, e₂, e₃, decide_true, decide_false, Bool.not_false, Bool.true_and] + · rename_i h + have hn : 31 ≤ index.toNat := by + simp only [BitVec.lt_def] at h + simp at h + omega + simp [hi, Nat.min_eq_left (show i ≤ index.toNat * 8 + 7 by omega)] + +theorem lt_agrees (a b : Word) : Evm.lt a b = Reference.lt a b := by + unfold Evm.lt Reference.lt + rw [show a.ult b = decide (a < b) by simp [BitVec.ult, BitVec.lt_def]] + by_cases h : a < b <;> simp [h] + +theorem gt_agrees (a b : Word) : Evm.gt a b = Reference.gt a b := by + unfold Evm.gt Reference.gt + rw [show b.ult a = decide (a > b) by simp [BitVec.ult, BitVec.lt_def]] + by_cases h : a > b <;> simp [h] + +theorem slt_agrees (a b : Word) : Evm.slt a b = Reference.slt a b := by + unfold Evm.slt Reference.slt + cases a.slt b <;> rfl + +theorem sgt_agrees (a b : Word) : Evm.sgt a b = Reference.sgt a b := by + unfold Evm.sgt Reference.sgt + cases b.slt a <;> rfl + +theorem eq_agrees (a b : Word) : Evm.eq a b = Reference.eq a b := by + unfold Evm.eq Reference.eq + by_cases h : a = b <;> simp [h] + +theorem ne_agrees (a b : Word) : Evm.ne a b = Reference.ne a b := by + unfold Evm.ne Reference.ne + by_cases h : a = b <;> simp [h] + +theorem iszero_agrees (a : Word) : Evm.iszero a = Reference.iszero a := by + unfold Evm.iszero Reference.iszero + by_cases h : a = 0 <;> simp [h] + +theorem select_agrees (c a b : Word) : Evm.select c a b = Reference.select c a b := by + unfold Evm.select Reference.select + by_cases h : c = 0 <;> simp [h] + +end EvmRules diff --git a/vendor/evm-rules/EvmRules/Simp.lean b/vendor/evm-rules/EvmRules/Simp.lean new file mode 100644 index 00000000..d5a3e82a --- /dev/null +++ b/vendor/evm-rules/EvmRules/Simp.lean @@ -0,0 +1,234 @@ +import EvmRules.Casts + +/-! +# Simplification lemmas + +The `@[simp]` lemmas of paradigmxyz/solar#1648, restated for the definitions in `Word.lean`. +`evm_simp` (`Tactic.lean`) rewrites the goal and every hypothesis with them before deciding +what remains: products and quotients by powers of two become shifts, nested shifts become one, +a shift distributes over bitwise operations and addition, `EXP` with a literal base or exponent +folds, and a cast recovers its input. +-/ + +namespace EvmRules + +/-- A count clamped to the word width, as the e-graph's `shift_sum` clamps each count. -/ +theorem clamp_toNat (x : Word) : + (Evm.select (Evm.lt x 256) x 256).toNat = min x.toNat 256 := by + unfold Evm.select Evm.lt + by_cases hx : x.toNat < 256 <;> simp [BitVec.ult, hx] <;> omega + +/-- The count the e-graph gives two nested shifts by `a` then `b`: each count clamped to the +word width, then their sum clamped again. As a number, it is `min (a + b) 256`. -/ +theorem shift_sum_toNat (a b : Word) : + (Evm.select + (Evm.lt (Evm.add (Evm.select (Evm.lt a 256) a 256) (Evm.select (Evm.lt b 256) b 256)) + 256) + (Evm.add (Evm.select (Evm.lt a 256) a 256) (Evm.select (Evm.lt b 256) b 256)) + 256).toNat = min (a.toNat + b.toNat) 256 := by + rw [clamp_toNat] + have h₁ := clamp_toNat a + have h₂ := clamp_toNat b + generalize Evm.select (Evm.lt a 256) a 256 = t₁ at * + generalize Evm.select (Evm.lt b 256) b 256 = t₂ at * + have hsum : (Evm.add t₁ t₂).toNat = t₁.toNat + t₂.toNat := by + rw [Evm.add, BitVec.toNat_add] + apply Nat.mod_eq_of_lt + omega + omega + +theorem one_pow (n : Nat) : (1 : Word) ^ n = 1 := by + induction n with + | zero => rfl + | succ n ih => rw [BitVec.pow_succ, ih]; rfl + +theorem two_pow (n : Nat) : (2 : Word) ^ n = BitVec.twoPow 256 n := by + induction n with + | zero => rfl + | succ n ih => + rw [BitVec.pow_succ, ih, show (2 : Word) = BitVec.twoPow 256 1 from rfl, + BitVec.twoPow_mul_twoPow_eq] + +/-! Products, quotients and remainders. -/ + +theorem mul_shl_one (x c : Word) : Evm.mul x (Evm.shl c 1) = Evm.shl c x := by + rw [Evm.mul, Evm.shl_eq, Evm.shl_eq, BitVec.shiftLeft_eq', BitVec.shiftLeft_eq', + show (1 : Word) = 1#256 from rfl, ← BitVec.twoPow_eq, BitVec.mul_twoPow_eq_shiftLeft] + +theorem shl_one_mul (x c : Word) : Evm.mul (Evm.shl c 1) x = Evm.shl c x := by + rw [Evm.mul, BitVec.mul_comm, ← Evm.mul, mul_shl_one] + +theorem div_lt (x y : Word) (h : x < y) : Evm.div x y = 0 := by + apply BitVec.eq_of_toNat_eq + rw [Evm.div, BitVec.toNat_udiv, Nat.div_eq_of_lt h] + rfl + +theorem mod_lt (x y : Word) (h : x < y) : Evm.mod x y = x := by + have hy : (y == 0) = false := by + rw [beq_eq_false_iff_ne] + intro e + subst e + exact absurd h (by simp [BitVec.lt_def]) + rw [Evm.mod, hy, Bool.cond_false, BitVec.umod_eq_of_lt h] + +theorem mod_self (x : Word) : Evm.mod x x = 0 := by + unfold Evm.mod + cases x == 0 <;> simp [BitVec.umod_self] + +theorem smod_self (x : Word) : Evm.smod x x = 0 := by + unfold Evm.smod + cases x == 0 <;> simp + +/-- A remainder by a power of two below the word width keeps the low bits. -/ +theorem mod_shl_one (x c : Word) (h : c < 256) : + Evm.mod x (Evm.shl c 1) = Evm.and x (Evm.sub (Evm.shl c 1) 1) := by + have hc : c.toNat < 256 := h + have hn := toNat_shl_one h + have hp : 2 ^ c.toNat < 2 ^ 256 := Nat.pow_lt_pow_right (by decide) hc + have hz : (Evm.shl c 1 == 0) = false := by + rw [beq_eq_false_iff_ne] + intro e + rw [e] at hn + have := Nat.two_pow_pos c.toNat + simp at hn + omega + apply BitVec.eq_of_toNat_eq + rw [Evm.mod, hz, Bool.cond_false, BitVec.toNat_umod, Evm.and, BitVec.toNat_and, Evm.sub, + BitVec.toNat_sub, hn, show (1 : Word).toNat = 1 from rfl] + have h1 := Nat.one_le_two_pow (n := c.toNat) + rw [show (2 ^ 256 - 1 + 2 ^ c.toNat) % 2 ^ 256 = 2 ^ c.toNat - 1 by omega, + Nat.and_two_pow_sub_one_eq_mod] + +/-- `CLZ` is at most 256, so it is below any larger divisor. -/ +theorem div_clz (x b : Word) (h : 256 < b) : Evm.div (Evm.clz x) b = 0 := + div_lt _ _ (Nat.lt_of_le_of_lt BitVec.clz_le h) + +theorem mod_clz (x b : Word) (h : 256 < b) : Evm.mod (Evm.clz x) b = Evm.clz x := + mod_lt _ _ (Nat.lt_of_le_of_lt BitVec.clz_le h) + +/-! `EXP` with a literal base or exponent. -/ + +theorem exp_two (c : Word) : Evm.exp 2 c = Evm.shl c 1 := by + rw [Evm.exp, two_pow, Evm.shl_eq, BitVec.shiftLeft_eq', BitVec.twoPow_eq] + rfl + +theorem exp_square (x : Word) : Evm.exp x 2 = Evm.mul x x := by + rw [Evm.exp, Evm.mul, show (2 : Word).toNat = 2 from rfl, BitVec.pow_succ, BitVec.pow_succ, + BitVec.pow_zero, BitVec.one_mul] + +theorem exp_zero (x : Word) : Evm.exp x 0 = 1 := by + rw [Evm.exp, show (0 : Word).toNat = 0 from rfl, BitVec.pow_zero] + rfl + +theorem exp_one (x : Word) : Evm.exp x 1 = x := by + rw [Evm.exp, show (1 : Word).toNat = 1 from rfl, BitVec.pow_succ, BitVec.pow_zero, + BitVec.one_mul] + +theorem one_exp (x : Word) : Evm.exp 1 x = 1 := by + rw [Evm.exp, one_pow] + +/-! Nested shifts by `a`, then `b`, are one shift by their sum clamped to the word width. -/ + +/-- The clamped sum of two shift counts. -/ +def shiftSum (a b : Word) : Word := BitVec.ofNat 256 (min 256 (a.toNat + b.toNat)) + +theorem shiftSum_toNat (a b : Word) : (shiftSum a b).toNat = min 256 (a.toNat + b.toNat) := by + rw [shiftSum, BitVec.toNat_ofNat] + apply Nat.mod_eq_of_lt + have := Nat.min_le_left 256 (a.toNat + b.toNat) + omega + +/-- The e-graph's `shift_sum` of two counts is their clamped sum. -/ +theorem shift_sum_eq (a b : Word) : + Evm.select + (Evm.lt (Evm.add (Evm.select (Evm.lt a 256) a 256) (Evm.select (Evm.lt b 256) b 256)) + 256) + (Evm.add (Evm.select (Evm.lt a 256) a 256) (Evm.select (Evm.lt b 256) b 256)) + 256 = shiftSum a b := by + apply BitVec.eq_of_toNat_eq + rw [shift_sum_toNat, shiftSum_toNat, Nat.min_comm] + +theorem shl_shl (a b x : Word) : Evm.shl a (Evm.shl b x) = Evm.shl (shiftSum a b) x := by + simp only [Evm.shl_eq, BitVec.shiftLeft_eq', shiftSum_toNat, ← BitVec.shiftLeft_add] + by_cases h : a.toNat + b.toNat < 256 + · rw [Nat.min_eq_right (by omega), Nat.add_comm] + · rw [Nat.min_eq_left (by omega), BitVec.shiftLeft_eq_zero (by omega), + BitVec.shiftLeft_eq_zero (by omega)] + +theorem shr_shr (a b x : Word) : Evm.shr a (Evm.shr b x) = Evm.shr (shiftSum a b) x := by + simp only [Evm.shr_eq, BitVec.ushiftRight_eq', shiftSum_toNat, ← BitVec.shiftRight_add] + by_cases h : a.toNat + b.toNat < 256 + · rw [Nat.min_eq_right (by omega), Nat.add_comm] + · rw [Nat.min_eq_left (by omega), BitVec.ushiftRight_eq_zero (by omega), + BitVec.ushiftRight_eq_zero (by omega)] + +theorem sar_sar (a b x : Word) : Evm.sar a (Evm.sar b x) = Evm.sar (shiftSum a b) x := by + simp only [Evm.sar_eq, BitVec.sshiftRight_eq', shiftSum_toNat, ← BitVec.sshiftRight_add] + by_cases h : a.toNat + b.toNat < 256 + · rw [Nat.min_eq_right (by omega), Nat.add_comm] + · rw [Nat.min_eq_left (by omega)] + exact BitVec.sshiftRight_eq_sshiftRight_of_le (by omega) (by omega) + +/-! A shift by one count distributes over bitwise operations and addition. -/ + +theorem and_shl (n x y : Word) : + Evm.and (Evm.shl n x) (Evm.shl n y) = Evm.shl n (Evm.and x y) := by + simp only [Evm.and, Evm.shl_eq, BitVec.shiftLeft_eq', BitVec.shiftLeft_and_distrib] + +theorem or_shl (n x y : Word) : + Evm.or (Evm.shl n x) (Evm.shl n y) = Evm.shl n (Evm.or x y) := by + simp only [Evm.or, Evm.shl_eq, BitVec.shiftLeft_eq', BitVec.shiftLeft_or_distrib] + +theorem xor_shl (n x y : Word) : + Evm.xor (Evm.shl n x) (Evm.shl n y) = Evm.shl n (Evm.xor x y) := by + simp only [Evm.xor, Evm.shl_eq, BitVec.shiftLeft_eq', BitVec.shiftLeft_xor_distrib] + +theorem add_shl (n x y : Word) : + Evm.add (Evm.shl n x) (Evm.shl n y) = Evm.shl n (Evm.add x y) := by + simp only [Evm.add, Evm.shl_eq, BitVec.shiftLeft_eq', BitVec.shiftLeft_add_distrib] + +theorem and_shr (n x y : Word) : + Evm.and (Evm.shr n x) (Evm.shr n y) = Evm.shr n (Evm.and x y) := by + simp only [Evm.and, Evm.shr_eq, BitVec.ushiftRight_eq', BitVec.ushiftRight_and_distrib] + +theorem or_shr (n x y : Word) : + Evm.or (Evm.shr n x) (Evm.shr n y) = Evm.shr n (Evm.or x y) := by + simp only [Evm.or, Evm.shr_eq, BitVec.ushiftRight_eq', BitVec.ushiftRight_or_distrib] + +theorem xor_shr (n x y : Word) : + Evm.xor (Evm.shr n x) (Evm.shr n y) = Evm.shr n (Evm.xor x y) := by + simp only [Evm.xor, Evm.shr_eq, BitVec.ushiftRight_eq', BitVec.ushiftRight_xor_distrib] + +theorem and_sar (n x y : Word) : + Evm.and (Evm.sar n x) (Evm.sar n y) = Evm.sar n (Evm.and x y) := by + simp only [Evm.and, Evm.sar_eq, BitVec.sshiftRight_eq', BitVec.sshiftRight_and_distrib] + +theorem or_sar (n x y : Word) : + Evm.or (Evm.sar n x) (Evm.sar n y) = Evm.sar n (Evm.or x y) := by + simp only [Evm.or, Evm.sar_eq, BitVec.sshiftRight_eq', BitVec.sshiftRight_or_distrib] + +theorem xor_sar (n x y : Word) : + Evm.xor (Evm.sar n x) (Evm.sar n y) = Evm.sar n (Evm.xor x y) := by + simp only [Evm.xor, Evm.sar_eq, BitVec.sshiftRight_eq', BitVec.sshiftRight_xor_distrib] + +/-! A cast recovers a value that fits its source width (`signedMask_recover` in #1648). -/ + +theorem sext_recover (n m x : Word) (h₁ : 1 ≤ n) (h₂ : n < m) + (hx : Evm.and x (Evm.sub (Evm.shl n 1) 1) = x) : + Evm.and + (Evm.and + (Evm.sar (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) + (Evm.shl (Evm.sub 256 (Evm.select (Evm.lt n 256) n 256)) x)) + (Evm.sub (Evm.shl m 1) 1)) + (Evm.sub (Evm.shl n 1) 1) = x := by + rw [BitVec.le_def] at h₁ + rw [BitVec.lt_def] at h₂ + apply BitVec.eq_of_getLsbD_eq + intro i hi + have ex := congrArg (BitVec.getLsbD · i) hx + simp only [Evm.and, BitVec.getLsbD_and, bits_mask] at ex + rw [Evm.and, BitVec.getLsbD_and, bits_sext, bits_mask] + simp only [show (1 : Word).toNat = 1 from rfl] at h₁ + grind + +end EvmRules diff --git a/vendor/evm-rules/EvmRules/Tactic.lean b/vendor/evm-rules/EvmRules/Tactic.lean new file mode 100644 index 00000000..38425997 --- /dev/null +++ b/vendor/evm-rules/EvmRules/Tactic.lean @@ -0,0 +1,101 @@ +import EvmRules.Simp + +/-! +# Automatic rule proofs + +`evm_decide` rewrites with the structural identities of `Casts.lean`, unfolds every EVM +operation into `BitVec` primitives and bit-blasts the goal with `bv_decide`, which checks the +SAT solver's LRAT certificate in Lean. An optional argument sets the SAT solver's limit in +seconds. + +Bit-blasting struggles with two shapes, which the other tactics prove without a SAT solver: + +* `evm_bits` proves an equation bit by bit with the lemmas of `Bits.lean`, turning variable + shift counts and extension widths into linear arithmetic over bit indices for `grind`. +* `evm_ring` lets `grind`'s commutative-ring normalization prove identities over products of + variables, such as distributivity, after splitting conditions that are known to be + booleans. + +`evm_simp` is the pipeline of paradigmxyz/solar#1648: it simplifies the goal and every +hypothesis with the lemmas of `Simp.lean` and `Casts.lean`, then decides what remains with +`bv_omega`, or bit-blasts it after normalizing associative and commutative operations. +-/ + +namespace EvmRules + +/-- Unfold the EVM operations in the goal and every hypothesis into `BitVec` primitives. -/ +macro "evm_unfold" : tactic => + `(tactic| ( + try simp only [Evm.add, Evm.sub, Evm.mul, Evm.div, Evm.mod, Evm.sdiv, Evm.smod, Evm.addmod, + Evm.mulmod, Evm.exp, Evm.and, Evm.or, Evm.xor, Evm.not, Evm.shl_eq, Evm.shr_eq, Evm.sar_eq, + Evm.lt, Evm.gt, Evm.slt, Evm.sgt, Evm.eq, Evm.ne, Evm.iszero, Evm.select, Evm.byte, + Evm.signextend, Evm.clz, Evm.address, Evm.balance, Evm.selfbalance] at *)) + +/-- Rewrite nested sign extensions and casts and divisions by powers of two with the +identities of `Casts.lean`, discharging their preconditions from the hypotheses. Only the side +goals substitute equal variables: the goal keeps every variable, so that a counterexample +`bv_decide` reports afterwards still assigns each of them. -/ +macro "evm_struct" : tactic => + `(tactic| ( + try simp (disch := (try subst_vars) <;> assumption) only [signextend_signextend, + select_same, sext_sext, eq_sext_sext, ne_sext_sext, eq_sext_zero, ne_sext_zero, + div_shl_one] at *)) + +/-- Rewrite structurally, unfold the EVM operations, then bit-blast whatever goal remains, +with an optional SAT limit in seconds. -/ +syntax "evm_decide" (ppSpace num)? : tactic + +macro_rules + | `(tactic| evm_decide) => `(tactic| evm_decide 10) + | `(tactic| evm_decide $timeout:num) => + `(tactic| ( + evm_struct + all_goals (evm_unfold <;> bv_decide (config := { timeout := $timeout })))) + +/-- Prove a word equation bit by bit: state the goal and every word equation among the +hypotheses as equalities of all 256 bits, write each bit of a shift, extension or mask as a bit +of its operand, and let `grind` relate the bit indices. -/ +macro "evm_bits" : tactic => + `(tactic| ( + subst_vars + try simp only [and_seven_eq_zero] at * + simp only [BitVec.eq_of_getLsbD_eq_iff, Evm.and, Evm.or, Evm.xor, Evm.not, + BitVec.getLsbD_and, BitVec.getLsbD_or, BitVec.getLsbD_xor, BitVec.getLsbD_not, bits_shl, + bits_shr, bits_sar, bits_mask, bits_signextend, bits_max, bits_address_mask, bits_one, + bits_zero, toNat_select_lt, toNat_select_gt, toNat_shr, toNat_add_wrap, toNat_sub_wrap, + toNat_mul, BitVec.lt_def, BitVec.le_def, Nat.add_sub_cancel, Nat.add_sub_cancel_left] at * + try simp only [BitVec.ofNat_eq_ofNat, BitVec.toNat_ofNat, Nat.reducePow, Nat.reduceMod] at * + grind)) + +/-- Prove a ring identity with `grind`: split boolean conditions, write left shifts as products +with powers of two and normalize both sides as commutative-ring polynomials. -/ +macro "evm_ring" : tactic => + `(tactic| ( + subst_vars + try simp only [le_one_iff] at * + try simp only [Evm.add, Evm.sub, Evm.mul, Evm.and, Evm.or, Evm.xor, Evm.not, Evm.shl_eq, + BitVec.shiftLeft_eq', BitVec.shiftLeft_eq_mul_twoPow, Evm.shr, Evm.sar, Evm.select, Evm.lt, + Evm.gt, Evm.eq, Evm.ne, Evm.iszero] at * + grind)) + +/-- Simplify with the lemmas of `Simp.lean` and `Casts.lean` everywhere, unfold the EVM +operations, then decide the rest over natural numbers with `bv_omega` or bit-blast it with +associative and commutative operations normalized, with an optional SAT limit in seconds. -/ +syntax "evm_simp" (ppSpace num)? : tactic + +macro_rules + | `(tactic| evm_simp) => `(tactic| evm_simp 10) + | `(tactic| evm_simp $timeout:num) => + `(tactic| ( + try subst_vars + try simp_all only [mul_shl_one, shl_one_mul, div_lt, mod_lt, mod_self, smod_self, + mod_shl_one, div_clz, mod_clz, exp_two, exp_square, exp_zero, exp_one, one_exp, + shift_sum_eq, shl_shl, shr_shr, sar_sar, and_shl, or_shl, xor_shl, add_shl, and_shr, + or_shr, xor_shr, and_sar, or_sar, xor_sar, sext_recover, signextend_signextend, + select_same, sext_sext, eq_sext_sext, ne_sext_sext, div_shl_one] + all_goals (evm_unfold; try simp only [shiftSum] at *) + all_goals first + | bv_omega + | bv_decide (config := { timeout := $timeout, acNf := true }))) + +end EvmRules diff --git a/vendor/evm-rules/EvmRules/Word.lean b/vendor/evm-rules/EvmRules/Word.lean new file mode 100644 index 00000000..6b096b88 --- /dev/null +++ b/vendor/evm-rules/EvmRules/Word.lean @@ -0,0 +1,141 @@ +import Std.Tactic.BVDecide + +/-! +# EVM word semantics + +The meaning of every word operation the rule checker reads, transcribed from the +[Ethereum execution specifications](https://github.com/ethereum/execution-specs/tree/master/src/ethereum/forks/cancun/vm/instructions). +Words are `BitVec 256` with wrapping arithmetic. Operands are in MIR / EVM pop order, so +shifts take the amount before the value. Rule theorems are stated over these definitions, +and the checker's regression tests evaluate them against the independent integer evaluator +in `evm_rules/expr.py`. Memory, storage, calls, gas and control flow are outside this model. +-/ + +namespace EvmRules + +/-- A 256-bit EVM word. -/ +abbrev Word := BitVec 256 + +namespace Evm + +def add (a b : Word) : Word := a + b + +def sub (a b : Word) : Word := a - b + +def mul (a b : Word) : Word := a * b + +/-- `DIV`. Lean's unsigned division already returns zero for a zero divisor. -/ +def div (a b : Word) : Word := a / b + +/-- `MOD`: zero for a zero divisor, where Lean's `%` keeps the dividend. -/ +def mod (a b : Word) : Word := bif b == 0 then 0 else a % b + +/-- `SDIV`, truncating toward zero. `BitVec.sdiv` returns zero for a zero divisor, and +`-2²⁵⁵ / -1` wraps to `-2²⁵⁵`, both as the EVM does. -/ +def sdiv (a b : Word) : Word := a.sdiv b + +/-- `SMOD`: the remainder takes the dividend's sign; zero for a zero divisor. -/ +def smod (a b : Word) : Word := bif b == 0 then 0 else a.srem b + +/-- `ADDMOD`: the sum is not reduced modulo 2²⁵⁶ before the modulus. -/ +def addmod (a b n : Word) : Word := + bif n == 0 then 0 else ((a.setWidth 512 + b.setWidth 512) % n.setWidth 512).setWidth 256 + +/-- `MULMOD`: the product is not reduced modulo 2²⁵⁶ before the modulus. -/ +def mulmod (a b n : Word) : Word := + bif n == 0 then 0 else ((a.setWidth 512 * b.setWidth 512) % n.setWidth 512).setWidth 256 + +/-- `EXP`, modulo 2²⁵⁶. -/ +def exp (a b : Word) : Word := a ^ b.toNat + +def and (a b : Word) : Word := a &&& b + +def or (a b : Word) : Word := a ||| b + +def xor (a b : Word) : Word := a ^^^ b + +def not (a : Word) : Word := ~~~a + +/-- `SHL`: zero once the shift reaches the word width. -/ +def shl (shift value : Word) : Word := bif shift.ult 256 then value <<< shift else 0 + +/-- `SHR`: zero once the shift reaches the word width. -/ +def shr (shift value : Word) : Word := bif shift.ult 256 then value >>> shift else 0 + +/-- `SAR`: every bit takes the sign once the shift reaches the word width. -/ +def sar (shift value : Word) : Word := + bif shift.ult 256 then value.sshiftRight' shift else bif value.msb then -1 else 0 + +def lt (a b : Word) : Word := bif a.ult b then 1 else 0 + +def gt (a b : Word) : Word := bif b.ult a then 1 else 0 + +def slt (a b : Word) : Word := bif a.slt b then 1 else 0 + +def sgt (a b : Word) : Word := bif b.slt a then 1 else 0 + +def eq (a b : Word) : Word := bif a == b then 1 else 0 + +/-- MIR `ne`, the word form of an inequality. -/ +def ne (a b : Word) : Word := bif a == b then 0 else 1 + +def iszero (a : Word) : Word := bif a == 0 then 1 else 0 + +/-- MIR `select`: the first arm for every nonzero condition word. -/ +def select (c a b : Word) : Word := bif c == 0 then b else a + +/-- `BYTE`: byte `i` counted from the most significant end, and zero from 32 on. -/ +def byte (i v : Word) : Word := bif i.ult 32 then (v >>> ((31 - i) * 8)) &&& 255 else 0 + +/-- `SIGNEXTEND`: extend the sign of the low `i + 1` bytes. Every index from 31 on is the +identity, however large. One case per byte keeps the definition free of variable shifts. -/ +def signextend (i v : Word) : Word := + bif i == 0 then (v.setWidth 8).signExtend 256 else + bif i == 1 then (v.setWidth 16).signExtend 256 else + bif i == 2 then (v.setWidth 24).signExtend 256 else + bif i == 3 then (v.setWidth 32).signExtend 256 else + bif i == 4 then (v.setWidth 40).signExtend 256 else + bif i == 5 then (v.setWidth 48).signExtend 256 else + bif i == 6 then (v.setWidth 56).signExtend 256 else + bif i == 7 then (v.setWidth 64).signExtend 256 else + bif i == 8 then (v.setWidth 72).signExtend 256 else + bif i == 9 then (v.setWidth 80).signExtend 256 else + bif i == 10 then (v.setWidth 88).signExtend 256 else + bif i == 11 then (v.setWidth 96).signExtend 256 else + bif i == 12 then (v.setWidth 104).signExtend 256 else + bif i == 13 then (v.setWidth 112).signExtend 256 else + bif i == 14 then (v.setWidth 120).signExtend 256 else + bif i == 15 then (v.setWidth 128).signExtend 256 else + bif i == 16 then (v.setWidth 136).signExtend 256 else + bif i == 17 then (v.setWidth 144).signExtend 256 else + bif i == 18 then (v.setWidth 152).signExtend 256 else + bif i == 19 then (v.setWidth 160).signExtend 256 else + bif i == 20 then (v.setWidth 168).signExtend 256 else + bif i == 21 then (v.setWidth 176).signExtend 256 else + bif i == 22 then (v.setWidth 184).signExtend 256 else + bif i == 23 then (v.setWidth 192).signExtend 256 else + bif i == 24 then (v.setWidth 200).signExtend 256 else + bif i == 25 then (v.setWidth 208).signExtend 256 else + bif i == 26 then (v.setWidth 216).signExtend 256 else + bif i == 27 then (v.setWidth 224).signExtend 256 else + bif i == 28 then (v.setWidth 232).signExtend 256 else + bif i == 29 then (v.setWidth 240).signExtend 256 else + bif i == 30 then (v.setWidth 248).signExtend 256 else + v + +/-- `CLZ` (EIP-7939): the number of leading zero bits, 256 for zero. -/ +def clz (v : Word) : Word := v.clz + +/-- `ADDRESS`: the executing account, zero-extended. -/ +def address (self : BitVec 160) : Word := self.setWidth 256 + +/-- `BALANCE` reads the snapshot balance of the account in the word's low 160 bits. -/ +def balance (balances : BitVec 160 → Word) (account : Word) : Word := + balances (account.setWidth 160) + +/-- `SELFBALANCE`: the snapshot balance of the executing account. -/ +def selfbalance (balances : BitVec 160 → Word) (self : BitVec 160) : Word := balances self + +end Evm + +end EvmRules diff --git a/vendor/evm-rules/README.md b/vendor/evm-rules/README.md new file mode 100644 index 00000000..85c1aa9d --- /dev/null +++ b/vendor/evm-rules/README.md @@ -0,0 +1,10 @@ +# EvmRules (vendored) + +solar's word semantics and rewrite-rule lemmas (`EvmRules`, `EvmRules.*`), which the SolarTV +library's MIR and EVM IR semantics are written in. Copied verbatim from +paradigmxyz/solar `scripts/evm-rules/lean/EvmRules.lean` and `scripts/evm-rules/lean/EvmRules/` +at main de3967800 (only the library: solar's rule checker, `Checker.lean`, and its generated rule +proofs stay in solar, which keeps its own copy for checking its ISLE rules). + +To update, copy those paths from the solar commit and update the commit above; +`scripts/check-evm-rules-vendor.sh ` reports any difference. diff --git a/vendor/evmyul/.gitignore b/vendor/evmyul/.gitignore new file mode 100644 index 00000000..057246aa --- /dev/null +++ b/vendor/evmyul/.gitignore @@ -0,0 +1,2 @@ +sha2/ +keccak256/ diff --git a/vendor/evmyul/Conform/Wheels.lean b/vendor/evmyul/Conform/Wheels.lean new file mode 100644 index 00000000..96b445db --- /dev/null +++ b/vendor/evmyul/Conform/Wheels.lean @@ -0,0 +1,112 @@ +import Lean.Data.Json +import EvmYul.UInt256 +import EvmYul.Wheels +import Batteries.Data.RBMap + +import Mathlib.Data.Multiset.Sort + +namespace Lean.Json + +def getObjValAs! + (self : Json) (α : Type) (key : String) [Inhabited α] [FromJson α] : α := + match self.getObjValAs? α key with + | .error _ => panic! s!"Expected the key {key} in the map." + | .ok pre => pre + +/-- +Turn non-existance of the key into default initialisation. + +This silences ONLY the `property not found:` error. +If the parsing of an existing value fails, we propagate the error. +-/ +def getObjValAsD (j : Json) (α : Type) [FromJson α] (k : String) (D : α) : Except String α := + match j.getObjVal? k with + | .error _ => pure D + | .ok val => fromJson? val + +/-- +`getObjValAsD! = getObjValAsD default` for inhabited types. +-/ +def getObjValAsD! (j : Json) (α : Type) [FromJson α] [Inhabited α] (k : String) : Except String α := + getObjValAsD j α k default + +def getObjVals? + (self : Json) (α β : Type) [Ord α] [FromJson α] [FromJson β] : Except String (RBTree.RBMap α β compare) := do + let keys := (← self.getObj?).toArray.map Prod.fst + let mut result : RBTree.RBMap α β compare := ∅ + for k in keys do + if let .ok key := FromJson.fromJson? (.str k) then + result := result.insert key (← self.getObjValAs? β k) + pure result + +def fromFile (path : System.FilePath) : IO Json := do + let .ok json ← Json.parse <$> IO.FS.readFile path | panic! s!"Failed to parse Json at: {path}" + pure json + +end Lean.Json + +namespace EvmYul + +namespace Conform + +end Conform + +section WithConform + +open Conform + +namespace UInt256 + +def fromBlob? (blob : Blob) : Except String UInt256 := + .ofNat <$> ((·.1) <| blob.foldr (init := (.ok 0, 0)) λ digit (acc, exp) ↦ + (do pure <| (←acc) + (16 ^ exp) * (←cToHex? digit), exp + 1)) + +def fromBlob! (blob : Blob) : UInt256 := fromBlob? blob |>.toOption.get! + +end UInt256 + +def Nat.fromBlob? (blob : Blob) : Except String ℕ := + ((·.1) <| blob.foldr (init := (.ok 0, 0)) λ digit (acc, exp) ↦ + (do pure <| (←acc) + (16 ^ exp) * (←cToHex? digit), exp + 1)) + +namespace AccountAddress + +def fromBlob? (s : Blob) : Except String AccountAddress := (Fin.ofNat _ ·.toNat) <$> UInt256.fromBlob? s + +def fromBlob! (blob : Blob) : AccountAddress := fromBlob? blob |>.toOption.get! + +end AccountAddress + +end WithConform + +namespace DebuggingAndProfiling + +section + +set_option autoImplicit true + +unsafe def report [Inhabited β] (s : String) (f : α → β) (a : α) : β := + dbg_trace s!"BEGIN: {s}" + let res := timeit s!"The function '{s}' took:" <| pure (f a) + dbg_trace s!"END: {s}" + unsafeIO res |>.toOption.get! + +def testJsonParser (α : Type) [Repr α] [Lean.FromJson α] (s : String) : String := + match Lean.FromJson.fromJson? (α := α) <| (Lean.Json.parse s).toOption.getD Lean.Json.null with + | .error e => s!"err: {e}" + | .ok ok => s!"ok: {repr ok}" + +end + +end DebuggingAndProfiling + +end EvmYul + +def computeToList! {α} + [LE α] [IsTrans α (· ≤ ·)] [Std.Antisymm (α := α) (· ≤ ·)] [Std.Total (α := α) (· ≤ ·)] + [DecidableRel (α := α) (· ≤ ·)] (m : Multiset α) : List α := + m.sort (· ≤ ·) + +def RBTree.RBMap.partition {α β : Type} {cmp : α → α → Ordering} + (t : RBTree.RBMap α β cmp) (p : α → β → Bool) : RBTree.RBMap α β cmp × RBTree.RBMap α β cmp := + (t.filter p, t.filter (λ k v ↦ not (p k v))) diff --git a/vendor/evmyul/EvmYul/Data/Stack.lean b/vendor/evmyul/EvmYul/Data/Stack.lean new file mode 100644 index 00000000..5119c13b --- /dev/null +++ b/vendor/evmyul/EvmYul/Data/Stack.lean @@ -0,0 +1,86 @@ +namespace EvmYul + +abbrev Stack (α : Type) := List α + +namespace Stack + +variable {α : Type} + +def new : Stack α := [] + +def isEmpty (s : Stack α) := List.isEmpty s + +def size (s : Stack α) : Nat := List.length s +def push (s : Stack α) (v : α) : Stack α := v :: s + +def pop : Stack α → Option (Stack α × α) + | hd :: tl => .some (tl, hd) + | [] => .none + +def pop2 : Stack α → Option (Stack α × α × α) + | hd :: hd₁ :: tl => .some (tl, hd, hd₁) + | _ => .none + +def pop3 : Stack α → Option (Stack α × α × α × α) + | hd :: hd₁ :: hd₂ :: tl => .some (tl, hd, hd₁, hd₂) + | _ => .none + +def pop4 : Stack α → Option (Stack α × α × α × α × α) + | hd :: hd₁ :: hd₂ :: hd₃ :: tl => .some (tl, hd, hd₁, hd₂, hd₃) + | _ => .none + +def pop5 : Stack α → Option (Stack α × α × α × α × α × α) + | hd :: hd₁ :: hd₂ :: hd₃ :: hd₄ :: tl => .some (tl, hd, hd₁, hd₂, hd₃, hd₄) + | _ => .none + +def pop6 : Stack α → Option (Stack α × α × α × α × α × α × α) + | hd :: hd₁ :: hd₂ :: hd₃ :: hd₄ :: hd₅ :: tl => .some (tl, hd, hd₁, hd₂, hd₃, hd₄, hd₅) + | _ => .none + +def pop7 : Stack α → Option (Stack α × α × α × α × α × α × α × α) + | hd :: hd₁ :: hd₂ :: hd₃ :: hd₄ :: hd₅ :: hd₆ :: tl => + .some (tl, hd, hd₁, hd₂, hd₃, hd₄, hd₅, hd₆) + | _ => .none + +section StackLemmas + +variable {x : α} {s : Stack α} + +@[simp] +theorem isEmpty_push_false : (s.push x).isEmpty = false := rfl + +@[simp] +theorem isEmpty_nil : Stack.isEmpty (α := α) [] := rfl + +@[simp] +theorem isEmpty_cons_false : Stack.isEmpty (α := α) (x :: s) = false := rfl + +@[simp] +theorem size_nil : Stack.size (α := α) [] = 0 := rfl + +@[simp] +theorem size_new : Stack.new.size (α := α) = 0 := rfl + +@[simp] +theorem size_cons : Stack.size (α := α) (x :: s) = Stack.size s + 1 := rfl + +theorem size_zero_iff_isEmpty_eq_true : s.size = 0 ↔ s.isEmpty = true := by + cases s <;> simp + +@[simp] +theorem size_push : (s.push x).size = s.size + 1 := rfl + +@[simp] +theorem pop_push : (s.push x).pop = some (s, x) := rfl + +end StackLemmas + +instance {α} : Inhabited (Stack α) := ⟨Stack.new⟩ +instance {α} [DecidableEq α] : DecidableEq (Stack α) := inferInstanceAs (DecidableEq (List α)) +instance {α} : EmptyCollection (Stack α) := ⟨Stack.new⟩ + +end Stack + +instance {α : Type} [ToString α] : ToString (Stack α) := inferInstanceAs (ToString (List α)) + +end EvmYul diff --git a/vendor/evmyul/EvmYul/EVM/Exception.lean b/vendor/evmyul/EvmYul/EVM/Exception.lean new file mode 100644 index 00000000..a53c8a99 --- /dev/null +++ b/vendor/evmyul/EvmYul/EVM/Exception.lean @@ -0,0 +1,153 @@ +import EvmYul.Wheels +import EvmYul.Maps.AccountMap +namespace EvmYul + +namespace EVM + +inductive ExecutionException where + | OutOfFuel + | InvalidInstruction + | OutOfGass + | BadJumpDestination + | StackOverflow + | StackUnderflow + | InvalidMemoryAccess + | StaticModeViolation +deriving BEq + +instance : Repr ExecutionException where + reprPrec s _ := + match s with + | .OutOfFuel => "OutOfFuel" + | .InvalidInstruction => "InvalidInstruction" + | .OutOfGass => "OutOfGass" + | .BadJumpDestination => "BadJumpDestination" + | .StackOverflow => "StackOverflow" + | .StackUnderflow => "StackUnderflow" + | .InvalidMemoryAccess => "InvalidMemoryAccess" + | .StaticModeViolation => "StaticModeViolation" + +inductive BlockException where + | INCORRECT_EXCESS_BLOB_GAS + | INCORRECT_BLOB_GAS_USED + | INCORRECT_BLOCK_FORMAT -- No "Cancun" test needs this + | BLOB_GAS_USED_ABOVE_LIMIT + | INVALID_WITHDRAWALS_ROOT + | IMPORT_IMPOSSIBLE_UNCLES_OVER_PARIS + | RLP_STRUCTURES_ENCODING + | IMPORT_IMPOSSIBLE_DIFFICULTY_OVER_PARIS + | RLP_INVALID_FIELD_OVERFLOW_64 + | RLP_INVALID_ADDRESS + | GASLIMIT_TOO_BIG + | INVALID_GAS_USED + | UNKNOWN_PARENT_ZERO + | EXTRA_DATA_TOO_BIG + | INVALID_BLOCK_NUMBER + | INVALID_BLOCK_TIMESTAMP_OLDER_THAN_PARENT + | INVALID_GASLIMIT + | INVALID_BASEFEE_PER_GAS + | UNKNOWN_PARENT + | INVALID_STATE_ROOT + | INVALID_LOG_BLOOM + | INVALID_TRANSACTIONS_ROOT + | INVALID_RECEIPTS_ROOT + +instance : Repr BlockException where + reprPrec s _ := + match s with + | .INCORRECT_EXCESS_BLOB_GAS => "INCORRECT_EXCESS_BLOB_GAS" + | .INCORRECT_BLOB_GAS_USED => "INCORRECT_BLOB_GAS_USED" + | .INCORRECT_BLOCK_FORMAT => "INCORRECT_BLOCK_FORMAT" + | .BLOB_GAS_USED_ABOVE_LIMIT => "BLOB_GAS_USED_ABOVE_LIMIT" + | .INVALID_WITHDRAWALS_ROOT => "INVALID_WITHDRAWALS_ROOT" + | .IMPORT_IMPOSSIBLE_UNCLES_OVER_PARIS => "IMPORT_IMPOSSIBLE_UNCLES_OVER_PARIS" + | .RLP_STRUCTURES_ENCODING => "RLP_STRUCTURES_ENCODING" + | .IMPORT_IMPOSSIBLE_DIFFICULTY_OVER_PARIS => "IMPORT_IMPOSSIBLE_DIFFICULTY_OVER_PARIS" + | .RLP_INVALID_FIELD_OVERFLOW_64 => "RLP_INVALID_FIELD_OVERFLOW_64" + | .RLP_INVALID_ADDRESS => "RLP_INVALID_ADDRESS" + | .GASLIMIT_TOO_BIG => "GASLIMIT_TOO_BIG" + | .INVALID_GAS_USED => "INVALID_GAS_USED" + | .UNKNOWN_PARENT_ZERO => "UNKNOWN_PARENT_ZERO" + | .EXTRA_DATA_TOO_BIG => "EXTRA_DATA_TOO_BIG" + | .INVALID_BLOCK_NUMBER => "INVALID_BLOCK_NUMBER" + | .INVALID_BLOCK_TIMESTAMP_OLDER_THAN_PARENT => "INVALID_BLOCK_TIMESTAMP_OLDER_THAN_PARENT" + | .INVALID_GASLIMIT => "INVALID_GASLIMIT" + | .INVALID_BASEFEE_PER_GAS => "INVALID_BASEFEE_PER_GAS" + | .UNKNOWN_PARENT => "UNKNOWN_PARENT" + | .INVALID_STATE_ROOT => "INVALID_STATE_ROOT" + | .INVALID_LOG_BLOOM => "INVALID_LOG_BLOOM" + | .INVALID_TRANSACTIONS_ROOT => "INVALID_TRANSACTIONS_ROOT" + | .INVALID_RECEIPTS_ROOT => "INVALID_RECEIPTS_ROOT" + +inductive TransactionException where + | IllFormedRLP + | INVALID_SIGNATURE_VRS + | NONCE_MISMATCH_TOO_LOW + | NONCE_MISMATCH_TOO_HIGH + | SENDER_NOT_EOA + | INSUFFICIENT_ACCOUNT_FUNDS + | PRIORITY_GREATER_THAN_MAX_FEE_PER_GAS + | TYPE_3_TX_ZERO_BLOBS + | INTRINSIC_GAS_TOO_LOW + | INSUFFICIENT_MAX_FEE_PER_BLOB_GAS + | INITCODE_SIZE_EXCEEDED + | NONCE_IS_MAX + | TYPE_3_TX_BLOB_COUNT_EXCEEDED + | GAS_ALLOWANCE_EXCEEDED + | TYPE_3_TX_MAX_BLOB_GAS_ALLOWANCE_EXCEEDED + | INSUFFICIENT_MAX_FEE_PER_GAS + | TYPE_3_TX_INVALID_BLOB_VERSIONED_HASH + | TYPE_3_TX_CONTRACT_CREATION + | GASLIMIT_PRICE_PRODUCT_OVERFLOW + | RLP_INVALID_VALUE + +/-- + TYPE_NOT_SUPPORTED - No "Cancun" test needs this +-/ +instance : Repr TransactionException where + reprPrec s _ := + match s with + | .IllFormedRLP => "IllFormedRLP" + | .INVALID_SIGNATURE_VRS => "INVALID_SIGNATURE_VRS" + | .NONCE_MISMATCH_TOO_LOW => "NONCE_MISMATCH_TOO_LOW" + | .NONCE_MISMATCH_TOO_HIGH => "NONCE_MISMATCH_TOO_HIGH" + | .SENDER_NOT_EOA => "SENDER_NOT_EOA" + | .INSUFFICIENT_ACCOUNT_FUNDS => "INSUFFICIENT_ACCOUNT_FUNDS" + | .PRIORITY_GREATER_THAN_MAX_FEE_PER_GAS => "PRIORITY_GREATER_THAN_MAX_FEE_PER_GAS" + | .TYPE_3_TX_ZERO_BLOBS => "TYPE_3_TX_ZERO_BLOBS" + | .INTRINSIC_GAS_TOO_LOW => "INTRINSIC_GAS_TOO_LOW" + | .INSUFFICIENT_MAX_FEE_PER_BLOB_GAS => "INSUFFICIENT_MAX_FEE_PER_BLOB_GAS" + | .INITCODE_SIZE_EXCEEDED => "INITCODE_SIZE_EXCEEDED" + -- | .MAX_CODE_SIZE_EXCEEDED => "MAX_CODE_SIZE_EXCEEDED" + | .NONCE_IS_MAX => "NONCE_IS_MAX" + | .TYPE_3_TX_BLOB_COUNT_EXCEEDED => "TYPE_3_TX_BLOB_COUNT_EXCEEDED" + | .GAS_ALLOWANCE_EXCEEDED => "GAS_ALLOWANCE_EXCEEDED" + | .TYPE_3_TX_MAX_BLOB_GAS_ALLOWANCE_EXCEEDED => "TYPE_3_TX_MAX_BLOB_GAS_ALLOWANCE_EXCEEDED" + | .INSUFFICIENT_MAX_FEE_PER_GAS => "INSUFFICIENT_MAX_FEE_PER_GAS" + | .TYPE_3_TX_INVALID_BLOB_VERSIONED_HASH => "TYPE_3_TX_INVALID_BLOB_VERSIONED_HASH" + | .TYPE_3_TX_CONTRACT_CREATION => "TYPE_3_TX_CONTRACT_CREATION" + | .GASLIMIT_PRICE_PRODUCT_OVERFLOW => "GASLIMIT_PRICE_PRODUCT_OVERFLOW" + | .RLP_INVALID_VALUE => "RLP_INVALID_VALUE" + +inductive Exception where + | ExecutionException : ExecutionException → Exception + | NotEncodableRLP : Exception + | TransactionException : TransactionException → Exception + | SenderRecoverError : String → Exception + | BlockException : BlockException → Exception + | MissedExpectedException : List String → Exception + +instance : Repr Exception where + reprPrec s _ := + match s with + | .ExecutionException ee => "Execution exception: " ++ repr ee + | .NotEncodableRLP => "NotEncodableRLP" + | .TransactionException e => "TransactionException." ++ repr e + | .SenderRecoverError s => "SenderRecoverError." ++ s + | .BlockException be => "BlockException." ++ repr be + | .MissedExpectedException mee => + "Missed expected exception: " ++ String.intercalate "|" mee + +end EVM + +end EvmYul diff --git a/vendor/evmyul/EvmYul/EVM/GasConstants.lean b/vendor/evmyul/EvmYul/EVM/GasConstants.lean new file mode 100644 index 00000000..272b5b40 --- /dev/null +++ b/vendor/evmyul/EvmYul/EVM/GasConstants.lean @@ -0,0 +1,47 @@ +import EvmYul.UInt256 + +namespace GasConstants + +section FeeSchedule + +def Gzero : ℕ := 0 +def Gjumpdest : ℕ := 1 +def Gbase : ℕ := 2 +def Gverylow : ℕ := 3 +def Glow : ℕ := 5 +def Gmid : ℕ := 8 +def Ghigh : ℕ := 10 +def Gwarmaccess : ℕ := 100 +def Gaccesslistaddress : ℕ := 2400 +def Gaccessliststorage : ℕ := 1900 +def Gcoldaccountaccess : ℕ := 2600 +def Gcoldsload : ℕ := 2100 +def Gsset : ℕ := 20000 +def Gsreset : ℕ := 2900 +def Rsclear : ℕ := 4800 +def Gselfdestruct : ℕ := 5000 +def Gcreate : ℕ := 32000 +def Gcodedeposit : ℕ := 200 +def Ginitcodeword : ℕ := 2 +def Gcallvalue : ℕ := 9000 +def Gcallstipend : ℕ := 2300 +def Gnewaccount : ℕ := 25000 +def Gexp : ℕ := 10 +def Gexpbyte : ℕ := 50 +def Gmemory : ℕ := 3 +def Gtxcreate : ℕ := 32000 +def Gtxdatazero : ℕ := 4 +def Gtxdatanonzero : ℕ := 16 +def Gtransaction : ℕ := 21000 +def Glog : ℕ := 375 +def Glogdata : ℕ := 8 +def Glogtopic : ℕ := 375 +def Gkeccak256 : ℕ := 30 +def Gkeccak256word : ℕ := 6 +def Gcopy : ℕ := 3 +def Gblockhash : ℕ := 20 +def HASH_OPCODE_GAS : ℕ := 3 + +end FeeSchedule + +end GasConstants diff --git a/vendor/evmyul/EvmYul/FFI/ffi.c b/vendor/evmyul/EvmYul/FFI/ffi.c new file mode 100644 index 00000000..9b9991f7 --- /dev/null +++ b/vendor/evmyul/EvmYul/FFI/ffi.c @@ -0,0 +1,161 @@ +#include +#include "lean/lean.h" +#include "sha-256.h" +#include +#include +#include "sha3.h" + +#define SHA256_OUTPUT_SIZE 32 +#define KECCAK256_OUTPUT_SIZE 32 + +// #define BLAKE2B_OUTPUT_SIZE 64 +#define BLAKE2B_COMPRESS_SIZE 8 +#define BLAKE2B_KEY_LENGTH 8 + +extern lean_obj_res sha256(b_lean_obj_arg input, size_t len) { + uint8_t hash[SHA256_OUTPUT_SIZE]; + calc_sha_256(hash, lean_sarray_cptr(input), len); + lean_obj_res res = lean_mk_empty_byte_array(lean_box(SHA256_OUTPUT_SIZE)); + for (int i = 0; i < SHA256_OUTPUT_SIZE; ++i) + lean_byte_array_push(res, hash[i]); + return res; +} + +// Implementation based on https://github.com/BLAKE2/BLAKE2/ +// with # of rounds parameterised from 12 (BLAKE2) to k < 2^32. + +uint64_t rotr64(const uint64_t w, const unsigned int c) { + return (w >> c) | (w << (64 - c)); +} + +#define G(a, b, c, d, e, f) \ + do { \ + v[a] = v[a] + v[b] + e; \ + v[d] = rotr64(v[d] ^ v[a], 32); \ + v[c] = v[c] + v[d]; \ + v[b] = rotr64(v[b] ^ v[c], 24); \ + v[a] = v[a] + v[b] + f; \ + v[d] = rotr64(v[d] ^ v[a], 16); \ + v[c] = v[c] + v[d]; \ + v[b] = rotr64(v[b] ^ v[c], 63); \ + } while(0) + +const uint64_t blake2b_IV[8] = { + 0x6A09E667F3BCC908ULL, 0xBB67AE8584CAA73BULL, + 0x3C6EF372FE94F82BULL, 0xA54FF53A5F1D36F1ULL, + 0x510E527FADE682D1ULL, 0x9B05688C2B3E6C1FULL, + 0x1F83D9ABFB41BD6BULL, 0x5BE0CD19137E2179ULL +}; + +// Do not repeat the last two rows, we'll be MOD 10, +// as we are going 12 -> k rounds. +const uint8_t blake2b_sigma[10][16] = { + {0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10, 11, 12, 13, 14, 15}, + {14, 10, 4 , 8 , 9 , 15, 13, 6 , 1 , 12, 0 , 2 , 11, 7 , 5 , 3 }, + {11, 8 , 12, 0 , 5 , 2 , 15, 13, 10, 14, 3 , 6 , 7 , 1 , 9 , 4 }, + {7 , 9 , 3 , 1 , 13, 12, 11, 14, 2 , 6 , 5 , 10, 4 , 0 , 15, 8 }, + {9 , 0 , 5 , 7 , 2 , 4 , 10, 15, 14, 1 , 11, 12, 6 , 8 , 3 , 13}, + {2 , 12, 6 , 10, 0 , 11, 8 , 3 , 4 , 13, 7 , 5 , 15, 14, 1 , 9 }, + {12, 5 , 1 , 15, 14, 13, 4 , 10, 0 , 7 , 6 , 3 , 9 , 2 , 8 , 11}, + {13, 11, 7 , 14, 12, 1 , 3 , 9 , 5 , 0 , 15, 4 , 8 , 6 , 2 , 10}, + {6 , 15, 14, 9 , 11, 3 , 0 , 8 , 12, 2 , 13, 7 , 1 , 4 , 10, 5 }, + {10, 2 , 8 , 4 , 7 , 6 , 1 , 5 , 15, 11, 9 , 14, 3 , 12, 13, 0 } +}; + +static void blake2b_compress_any( + uint32_t rounds, + uint64_t* h, + const uint64_t* const m, + const uint64_t* const t, + bool f +) { + uint64_t v[16]; + for (int i = 0; i < 8; ++i) { + v[i] = h[i]; + v[i + 8] = blake2b_IV[i]; + } + v[12] ^= t[0]; + v[13] ^= t[1]; + if (f) v[14] = ~v[14]; + + for (unsigned int i = 0U; i < rounds; ++i) { + G(0, 4, 8 , 12, m[blake2b_sigma[i % 10][0 ]], m[blake2b_sigma[i % 10][1 ]]); + G(1, 5, 9 , 13, m[blake2b_sigma[i % 10][2 ]], m[blake2b_sigma[i % 10][3 ]]); + G(2, 6, 10, 14, m[blake2b_sigma[i % 10][4 ]], m[blake2b_sigma[i % 10][5 ]]); + G(3, 7, 11, 15, m[blake2b_sigma[i % 10][6 ]], m[blake2b_sigma[i % 10][7 ]]); + G(0, 5, 10, 15, m[blake2b_sigma[i % 10][8 ]], m[blake2b_sigma[i % 10][9 ]]); + G(1, 6, 11, 12, m[blake2b_sigma[i % 10][10]], m[blake2b_sigma[i % 10][11]]); + G(2, 7, 8 , 13, m[blake2b_sigma[i % 10][12]], m[blake2b_sigma[i % 10][13]]); + G(3, 4, 9 , 14, m[blake2b_sigma[i % 10][14]], m[blake2b_sigma[i % 10][15]]); + } + + for (int i = 0; i < 8; ++i) + h[i] ^= v[i] ^ v[i + 8]; +} + +extern lean_obj_arg blake2compressb64(b_lean_obj_arg input) { + uint8_t* in = lean_sarray_cptr(input); + + // [0; 3] (4 bytes) - big endian, 4 bytes + uint32_t rounds = (in[3] << 0 * 8) | (in[2] << 1 * 8) | + (in[1] << 2 * 8) | ((uint32_t)in[0] << 3 * 8); + in += 4; + + // [4; 67] (64 bytes) - small endian, 8 bytes, 8 times + uint64_t h[8]; + for (int i = 0; i < 8; ++i) { + h[i] = ((uint64_t)in[0] << (0 * 8)) | ((uint64_t)in[1] << (1 * 8)) | + ((uint64_t)in[2] << (2 * 8)) | ((uint64_t)in[3] << (3 * 8)) | + ((uint64_t)in[4] << (4 * 8)) | ((uint64_t)in[5] << (5 * 8)) | + ((uint64_t)in[6] << (6 * 8)) | ((uint64_t)in[7] << (7 * 8)); + in += sizeof(uint64_t); + } + + // [68; 195] (128 bytes) - small endian, 8 bytes, 16 times + uint64_t m[16]; + for (int i = 0; i < 16; ++i) { + m[i] = ((uint64_t)in[0] << (0 * 8)) | ((uint64_t)in[1] << (1 * 8)) | + ((uint64_t)in[2] << (2 * 8)) | ((uint64_t)in[3] << (3 * 8)) | + ((uint64_t)in[4] << (4 * 8)) | ((uint64_t)in[5] << (5 * 8)) | + ((uint64_t)in[6] << (6 * 8)) | ((uint64_t)in[7] << (7 * 8)); + in += sizeof(uint64_t); + } + + // [196; 211] (16 bytes) - small endian, 8 bytes, 2 times + uint64_t t[2]; + for (int i = 0; i < 2; ++i) { + t[i] = ((uint64_t)in[0] << (0 * 8)) | ((uint64_t)in[1] << (1 * 8)) | + ((uint64_t)in[2] << (2 * 8)) | ((uint64_t)in[3] << (3 * 8)) | + ((uint64_t)in[4] << (4 * 8)) | ((uint64_t)in[5] << (5 * 8)) | + ((uint64_t)in[6] << (6 * 8)) | ((uint64_t)in[7] << (7 * 8)); + in += sizeof(uint64_t); + } + + // [212; 212] (1 bytes) - 0 is false, 1 is true + bool f = *in; + + blake2b_compress_any(rounds, h, m, t, f); + + lean_obj_res res = lean_mk_empty_byte_array(lean_box(BLAKE2B_COMPRESS_SIZE * sizeof(uint64_t))); + + for (int i = 0; i < BLAKE2B_COMPRESS_SIZE * sizeof(uint64_t); ++i) + lean_byte_array_push(res, *(((uint8_t*)h) + i)); + + return res; +} + +extern lean_obj_arg memset_zero(size_t n) { + lean_object* res = lean_alloc_sarray(1, n, n); + uint8_t* it = lean_sarray_cptr(res); + memset(it, 0, n); + return res; +} + +extern lean_obj_arg keccak256(b_lean_obj_arg input, size_t inBytes) { + uint8_t hash[KECCAK256_OUTPUT_SIZE]; + sha3_HashBuffer(256, SHA3_FLAGS_KECCAK, lean_sarray_cptr(input), inBytes, hash, KECCAK256_OUTPUT_SIZE); + lean_obj_res res = lean_mk_empty_byte_array(lean_box(KECCAK256_OUTPUT_SIZE)); + for (int i = 0; i < KECCAK256_OUTPUT_SIZE; ++i) + lean_byte_array_push(res, hash[i]); + return res; +} diff --git a/vendor/evmyul/EvmYul/FFI/ffi.lean b/vendor/evmyul/EvmYul/FFI/ffi.lean new file mode 100644 index 00000000..6b58b01f --- /dev/null +++ b/vendor/evmyul/EvmYul/FFI/ffi.lean @@ -0,0 +1,94 @@ +import Init.Data.Array.Lemmas +import EvmYul.SpongeHash.Keccak256 + +namespace ffi + +@[extern "sha256"] +opaque sha256 (input : @& ByteArray) (len : USize) : ByteArray + +def SHA256 (d : ByteArray) : Except String ByteArray := + pure <| sha256 d d.size.toUSize + +@[extern "blake2compressb64"] +opaque BLAKE2Compress (input : @& ByteArray) : ByteArray + +def BLAKE2 (d : ByteArray) : Except String ByteArray := do + if d.size != 213 then throw "error" + if d[212]! ∉ [0, 1].map Nat.toUInt8 then throw "error" + return BLAKE2Compress d + +@[extern "memset_zero"] +def ByteArray.zeroes (n : USize) : ByteArray := + ⟨Array.replicate n.toNat 0⟩ + +@[simp] theorem ByteArray.size_zeroes (n : USize) : + (ByteArray.zeroes n).size = n.toNat := by + change (Array.replicate n.toNat 0).size = n.toNat + simp + +@[simp] theorem ByteArray.getElem_zeroes + (n : USize) (index : Nat) + (hIndex : index < (ByteArray.zeroes n).size) : + (ByteArray.zeroes n)[index] = 0 := by + rw [ByteArray.size_zeroes] at hIndex + change + (Array.replicate n.toNat 0)[index]'(by simpa using hIndex) = 0 + simp + +@[simp] theorem ByteArray.data_getD_zeroes + (n : USize) (index : Nat) : + (ByteArray.zeroes n).data.getD index 0 = 0 := by + simp [ByteArray.zeroes, Array.getD] + +@[simp] theorem ByteArray.data_getElem?_zeroes + (n : USize) (index : Nat) : + (ByteArray.zeroes n).data[index]? = + if index < n.toNat then some 0 else none := by + simp [ByteArray.zeroes, Array.getElem?_replicate] + +private theorem ByteArray.toList_loop + (bytes : ByteArray) (index : Nat) (acc : List UInt8) : + ByteArray.toList.loop bytes index acc = + acc.reverse ++ bytes.data.toList.drop index := by + fun_induction ByteArray.toList.loop bytes index acc with + | case1 index acc hIndex ih => + rw [ih] + simp only [List.reverse_cons, List.singleton_append, + List.append_assoc] + have hDataIndex : index < bytes.data.toList.length := by + simpa [ByteArray.size_data] using hIndex + rw [List.drop_eq_getElem_cons hDataIndex] + congr 2 + unfold ByteArray.get! + cases bytes with + | mk data => + exact getElem!_pos data index (by simpa using hDataIndex) + | case2 index acc hIndex => + have hData : bytes.data.toList.length ≤ index := by + simpa [ByteArray.size_data, Nat.not_lt] using hIndex + simp [List.drop_eq_nil_iff.mpr hData] + +@[simp] theorem ByteArray.toList_eq_data_toList + (bytes : ByteArray) : + bytes.toList = bytes.data.toList := by + unfold ByteArray.toList + simpa using ByteArray.toList_loop bytes 0 [] + +/-- Keccak-256 of the first `len` bytes of `input`. + +No longer `opaque`: the logical meaning is the pure sponge implementation in +`EvmYul.SpongeHash.Keccak256`, so `KEC` is provable-about; the `@[extern]` +attribute keeps compiled execution on the native `keccak256` symbol +(byte-parity with the pure body is asserted by downstream witnesses). -/ +@[extern "keccak256"] +def keccak256 (input : @& ByteArray) (len : USize) : ByteArray := + EvmYul.SpongeHash.Keccak256.keccak256 + (ByteArray.mk (input.data.extract 0 len.toNat)) + +def KECCAK256 (d : ByteArray) : Except String ByteArray := + pure <| keccak256 d d.size.toUSize + +def KEC (data : ByteArray) : ByteArray := + ffi.KECCAK256 data |>.toOption.getD .empty + +end ffi diff --git a/vendor/evmyul/EvmYul/MachineState.lean b/vendor/evmyul/EvmYul/MachineState.lean new file mode 100644 index 00000000..fdc90dc2 --- /dev/null +++ b/vendor/evmyul/EvmYul/MachineState.lean @@ -0,0 +1,40 @@ +import Batteries + +import EvmYul.Maps.ByteMap +import EvmYul.UInt256 +import Batteries.Data.HashMap + +namespace EvmYul + +open Batteries + +instance : DecidableEq ByteArray + | a, b => match decEq a.data b.data with + | isTrue h₁ => isTrue <| congrArg ByteArray.mk h₁ + | isFalse h₂ => isFalse <| λ h ↦ by cases h; exact (h₂ rfl) + +/-- +The partial shared `MachineState` `μ`. Section 9.4.1. +- `gasAvailable` `g` +- `memory` `m` +- `activeWords` `i` - # active words. +- `returnData` `o` - Data from the previous call from the current environment. +-/ +structure MachineState where + gasAvailable : UInt256 + activeWords : UInt256 + memory : ByteArray + returnData : ByteArray + H_return : ByteArray + deriving Inhabited + +-- inductive WordSize := | Standard | Single + +-- def WordSize.toNat (this : WordSize) : ℕ := +-- match this with +-- | WordSize.Standard => 32 +-- | WordSize.Single => 1 + +-- instance : Coe WordSize Nat := ⟨WordSize.toNat⟩ + +end EvmYul diff --git a/vendor/evmyul/EvmYul/MachineStateOps.lean b/vendor/evmyul/EvmYul/MachineStateOps.lean new file mode 100644 index 00000000..396f59e4 --- /dev/null +++ b/vendor/evmyul/EvmYul/MachineStateOps.lean @@ -0,0 +1,156 @@ +import Batteries.Data.RBMap + +import EvmYul.MachineState + +import EvmYul.SpongeHash.Keccak256 + +namespace EvmYul + +def writeBytes + (source : ByteArray) + (sourceAddr : ℕ) + (self : MachineState) + (destAddr len : ℕ) + : MachineState := + { self with + memory := source.write sourceAddr self.memory destAddr len + } + +namespace MachineState + +open RBTree (RBMap) + +-- Appendix H, (320) +def M (s f l : ℕ) : ℕ := + match l with + | 0 => s + | l => + -- ⌈ (f + l) ÷ 32 ⌉ + -- The addition is not subject to s²⁵⁶ division (at least that's what MSTORE suggests) + max s ((f + l + 31) / 32) + +def x : ByteArray := "hello".toUTF8 +def y : ByteArray := "kokusho".toUTF8 + +def writeWord (self : MachineState) (addr val : UInt256) : MachineState := + let numOctets := 32 + let source : ByteArray := val.toByteArray + writeBytes source 0 self addr.toNat numOctets + +def lookupMemory (self : MachineState) (addr : UInt256) : UInt256 := + if addr.toNat ≥ self.memory.size ∨ addr ≥ self.activeWords * ⟨32⟩ then ⟨0⟩ else + let bytes := self.memory.readWithPadding addr.toNat 32 + let val := fromByteArrayBigEndian bytes + .ofNat val + +def msize (self : MachineState) : UInt256 := + self.activeWords * ⟨32⟩ + +def mload (self : MachineState) (spos : UInt256) : UInt256 × MachineState := + let val := self.lookupMemory spos + let self := + { self with + activeWords := .ofNat (MachineState.M self.activeWords.toNat spos.toNat 32) + } + (val, self) + +def mstore (self : MachineState) (spos sval : UInt256) : MachineState := + let self := self.writeWord spos sval + { self with + activeWords := .ofNat (MachineState.M self.activeWords.toNat spos.toNat 32) + } + +def mstore8 (self : MachineState) (spos sval : UInt256) : MachineState := + let self := writeBytes ⟨#[UInt8.ofNat sval.toNat]⟩ 0 self spos.toNat 1 + { self with + activeWords := .ofNat (MachineState.M self.activeWords.toNat spos.toNat 1) + } + +def mcopy (self : MachineState) (writeStart readStart s : UInt256) : MachineState := + let self := writeBytes self.memory readStart.toNat self writeStart.toNat s.toNat + { self with + activeWords := + .ofNat (MachineState.M self.activeWords.toNat (max writeStart.toNat readStart.toNat) s.toNat) + } + +def gas (self : MachineState) : UInt256 := + self.gasAvailable + +section ReturnData + +def freshExternalCall (gas : UInt256) : MachineState := + { (default : MachineState) with gasAvailable := gas } + +def setReturnData (self : MachineState) (r : ByteArray) : MachineState := + { self with returnData := r } + +def setHReturn (self : MachineState) (r : ByteArray) : MachineState := + { self with H_return := r } + +def returndatasize (self : MachineState) : UInt256 := + .ofNat self.returnData.size + +def returndataat (self : MachineState) (pos : UInt256) : UInt8 := + self.returnData.data.getD pos.toNat 0 + +def returndatacopy (self : MachineState) (mstart rstart size : UInt256) : MachineState := + let self := writeBytes self.returnData rstart.toNat self mstart.toNat size.toNat + { self with + activeWords := + .ofNat (MachineState.M self.activeWords.toNat mstart.toNat size.toNat) + } + +def finishExternalCall + (self : MachineState) (returnData : ByteArray) + (inOffset inSize outOffset outSize : UInt256) : MachineState := + let copyLen := min outSize.toNat returnData.size + let self := writeBytes returnData 0 self outOffset.toNat copyLen + { self with + activeWords := + .ofNat <| + MachineState.M + (MachineState.M self.activeWords.toNat inOffset.toNat inSize.toNat) + outOffset.toNat outSize.toNat + returnData := returnData + H_return := ByteArray.empty + } + + +def evmReturn (self : MachineState) (mstart s : UInt256) : MachineState := + { self with + H_return := self.memory.readWithPadding mstart.toNat s.toNat + activeWords := + .ofNat <| MachineState.M self.activeWords.toNat mstart.toNat s.toNat + } + +def evmRevert (self : MachineState) (mstart s : UInt256) : MachineState := + let self := self.evmReturn mstart s + { self with + activeWords := + .ofNat <| MachineState.M self.activeWords.toNat mstart.toNat s.toNat + } + +end ReturnData + +def keccak256 (self : MachineState) (mstart s : UInt256) : UInt256 × MachineState := + let bytes := self.memory.readWithPadding mstart.toNat s.toNat + let kec := ffi.KEC bytes + let newMachineState := + { self with activeWords := .ofNat (M self.activeWords.toNat mstart.toNat s.toNat) } + (.ofNat (fromByteArrayBigEndian kec), newMachineState) + +section Gas + +def mkNewWithGas (gas : ℕ) : MachineState := + let init : MachineState := default + { init with gasAvailable := .ofNat gas } + +end Gas + +section Storage + +end Storage + +end MachineState + +end EvmYul diff --git a/vendor/evmyul/EvmYul/Maps/AccountMap.lean b/vendor/evmyul/EvmYul/Maps/AccountMap.lean new file mode 100644 index 00000000..cfa9f1b4 --- /dev/null +++ b/vendor/evmyul/EvmYul/Maps/AccountMap.lean @@ -0,0 +1,133 @@ +/- +We need a more unified approach to maps. + +This file shouldn't exist; but it does for now. +`Finmap`s have terrible computational behaviour, one needs some ordering lemmas to make them compute. + +In `Conform`, we use `Lean.RBMap`, although we would ideally use `RBTree.RBMap`, but the `Lean.Json` +uses `Lean.RBMap`, which means that we would need an additional cast to `RBTree.RBMap`. + +Furthermore, replacing everything with either of the `RBMaps` would then reintroduce this mess, +but with ordering lemmas needed for some `Decidable` instances. + +When time allows, I suggest we replace everything with `RBTree.RBMap` and prove the reasoning lemmas we need. +This way, we get decent performance AND the ability to conveniently reason about the structure +a'la `Finmap`. + +TODO - All of this is very ugly. +-/ + +import Batteries.Data.RBMap + +import EvmYul.Wheels + +import EvmYul.Maps.StorageMap + +import EvmYul.State.Account +import EvmYul.State.AccountOps + +namespace EvmYul + +section RemoveLater + +abbrev AddrMap (α : Type) [Inhabited α] := RBTree.RBMap AccountAddress α compare +abbrev AccountMap (τ : OperationType) := AddrMap (Account τ) +abbrev PersistentAccountMap (τ : OperationType) := AddrMap (PersistentAccountState τ) +def AccountMap.toPersistentAccountMap (τ : OperationType) (a : AccountMap τ) : PersistentAccountMap τ := + a.mapVal (λ _ acc ↦ acc.toPersistentAccountState) + +def AccountMap.increaseBalance (τ : OperationType) (σ : AccountMap τ) (addr : AccountAddress) (amount : UInt256) + : AccountMap τ +:= + match σ.find? addr with + | none => σ.insert addr {(default : Account τ) with balance := amount} + | some acc => σ.insert addr {acc with balance := acc.balance + amount} + +/-- + Returns `none` in the case of an overflow below zero. +-/ +def AccountMap.decreaseBalance (τ : OperationType) (σ : AccountMap τ) (addr : AccountAddress) (amount : UInt256) + : Option (AccountMap τ) +:= + match σ.find? addr with + | none => .none + | some acc => + if acc.balance < amount then .none else .some (σ.insert addr {acc with balance := acc.balance - amount}) + +/-- + Returns `none` in the case of an overflow below zero. +-/ +def AccountMap.transferBalance (τ : OperationType) (σ : AccountMap τ) (from_addr to_addr : AccountAddress) (amount : UInt256) + : Option (AccountMap τ) +:= + match (σ.decreaseBalance τ from_addr amount) with + | .none => .none + | .some σ' => σ'.increaseBalance τ to_addr amount + +def AccountMap.delegatedCodeTarget? (σ : AccountMap .EVM) (t : AccountAddress) : + Option AccountAddress := + match PrecompiledContract.ofAddress? t with + | some _ => none + | none => + match σ.find? t with + | none => none + | some account => account.eip7702DelegationTarget? + +def AccountMap.delegatedToExecute (σ : AccountMap .EVM) (t : AccountAddress) : + ToExecute .EVM := + match σ.delegatedCodeTarget? t with + | none => + match σ.find? t with + | none => ToExecute.Code default + | some account => ToExecute.Code account.code + | some target => + if (PrecompiledContract.ofAddress? target).isSome then + ToExecute.Code default + else + match σ.find? target with + | none => ToExecute.Code default + | some account => ToExecute.Code account.code + +def toExecute (τ : OperationType) (σ : AccountMap τ) (t : AccountAddress) : ToExecute τ := + match PrecompiledContract.ofAddress? t with + | some precompiled => ToExecute.Precompiled precompiled + | none => + match τ, σ with + | .EVM, σ => + AccountMap.delegatedToExecute σ t + | .Yul, σ => + match σ.find? t with + | none => ToExecute.Code default + | some tDirect => ToExecute.Code tDirect.code + +def L_S (σ : PersistentAccountMap .EVM) : Array (ByteArray × ByteArray) := + σ.foldl + (λ arr (addr : AccountAddress) acc ↦ + arr.push (p addr acc) + ) + .empty + where + p (addr : AccountAddress) (acc : PersistentAccountState .EVM) : ByteArray × ByteArray := + (ffi.KEC addr.toByteArray, rlp acc) + rlp (acc : PersistentAccountState .EVM) := + Option.get! <| + RLP <| + .𝕃 + [ .𝔹 (BE acc.nonce.toNat) + , .𝔹 (BE acc.balance.toNat) + , .𝔹 <| (computeTrieRoot acc.storage).getD .empty + , .𝔹 acc.codeHash.toByteArray + ] + +def stateTrieRoot (σ : PersistentAccountMap .EVM) : Option ByteArray := + let a := Array.map toBlobPair (L_S σ) + (ByteArray.ofBlob (blobComputeTrieRoot a)).toOption + where + toBlobPair entry : String × String := + let b₁ := EvmYul.toHex entry.1 + let b₂ := EvmYul.toHex entry.2 + (b₁, b₂) + +end RemoveLater + +end EvmYul diff --git a/vendor/evmyul/EvmYul/Maps/ByteMap.lean b/vendor/evmyul/EvmYul/Maps/ByteMap.lean new file mode 100644 index 00000000..a1ece1f2 --- /dev/null +++ b/vendor/evmyul/EvmYul/Maps/ByteMap.lean @@ -0,0 +1,32 @@ +/- +We need a more unified approach to maps. + +This file shouldn't exist; but it does for now. +`Finmap`s have terrible computational behaviour, one needs some ordering lemmas to make them compute. + +In `Conform`, we use `Lean.RBMap`, although we would ideally use `RBTree.RBMap`, but the `Lean.Json` +uses `Lean.RBMap`, which means that we would need an additional cast to `RBTree.RBMap`. + +Furthermore, replacing everything with either of the `RBMaps` would then reintroduce this mess, +but with ordering lemmas needed for some `Decidable` instances. + +When time allows, I suggest we replace everything with `RBTree.RBMap` and prove the reasoning lemmas we need. +This way, we get decent performance AND the ability to conveniently reason about the structure +a'la `Finmap`. + +TODO - All of this is very ugly. +-/ + +import Batteries.Data.RBMap + +import EvmYul.Wheels + +namespace EvmYul + +section RemoveLater + +abbrev ByteMap := RBTree.RBMap UInt256 UInt8 compare + +end RemoveLater + +end EvmYul diff --git a/vendor/evmyul/EvmYul/Maps/StorageMap.lean b/vendor/evmyul/EvmYul/Maps/StorageMap.lean new file mode 100644 index 00000000..d3c4cc14 --- /dev/null +++ b/vendor/evmyul/EvmYul/Maps/StorageMap.lean @@ -0,0 +1,53 @@ +/- +We need a more unified approach to maps. + +This file shouldn't exist; but it does for now. +`Finmap`s have terrible computational behaviour, one needs some ordering lemmas to make them compute. + +In `Conform`, we use `Lean.RBMap`, although we would ideally use `RBTree.RBMap`, but the `Lean.Json` +uses `Lean.RBMap`, which means that we would need an additional cast to `RBTree.RBMap`. + +Furthermore, replacing everything with either of the `RBMaps` would then reintroduce this mess, +but with ordering lemmas needed for some `Decidable` instances. + +When time allows, I suggest we replace everything with `RBTree.RBMap` and prove the reasoning lemmas we need. +This way, we get decent performance AND the ability to conveniently reason about the structure +a'la `Finmap`. + +TODO - All of this is very ugly. +-/ + +import Batteries.Data.RBMap +import Mathlib.Data.Multiset.Sort + +import EvmYul.Wheels +import EvmYul.State.TrieRoot +import EvmYul.SpongeHash.Keccak256 + +import EvmYul.FFI.ffi + +namespace EvmYul + +section RemoveLater + +abbrev Storage : Type := RBTree.RBMap UInt256 UInt256 compare + +def Storage.toFinmap (self : Storage) : Finmap (λ _ : UInt256 ↦ UInt256) := + self.foldl (init := ∅) λ acc k v ↦ acc.insert (UInt256.ofNat k.1) v + +def Storage.toEvmYulStorage (self : Storage) : EvmYul.Storage := + self.foldl (init := ∅) λ acc k v ↦ acc.insert (UInt256.ofNat k.1) v + +def toBlobs (pair : UInt256 × UInt256) : Option (String × String) := do + let kec := ffi.KEC pair.1.toByteArray + let rlp ← RLP (.𝔹 (BE pair.2.toNat)) + pure (EvmYul.toHex kec, EvmYul.toHex rlp) + +def computeTrieRoot (storage : Storage) : Option ByteArray := + match Array.mapM toBlobs storage.1.toArray with + | none => .none + | some pairs => (ByteArray.ofBlob (blobComputeTrieRoot pairs)).toOption + +end RemoveLater + +end EvmYul diff --git a/vendor/evmyul/EvmYul/Operations.lean b/vendor/evmyul/EvmYul/Operations.lean new file mode 100644 index 00000000..0d02cac5 --- /dev/null +++ b/vendor/evmyul/EvmYul/Operations.lean @@ -0,0 +1,813 @@ +import EvmYul.UInt256 +import EvmYul.MachineState + +import Mathlib.Data.Finmap + +namespace EvmYul + +set_option autoImplicit true + +inductive OperationType where + | Yul + | EVM + deriving DecidableEq, Repr + +namespace Operation + +section Operation + +/-- + Stop and Arithmetic Operations +-/ +inductive SAOp (τ : OperationType) : Type where + /-- + Stop: halts program execution + δ: 0 ; α : 0 + -/ + | protected STOP : SAOp τ + /-- + ADD: adds two stack values. + δ: 2 ; α : 1 + -/ + | protected ADD : SAOp τ + /-- + MUL: multiplies two stack values. + δ: 2 ; α : 1 + -/ + | protected MUL : SAOp τ + /-- + SUB: subtracts two stack values. + δ: 2 ; α : 1 + -/ + | protected SUB : SAOp τ + /-- + DIV: divides two stack values. + δ: 2 ; α: 1 + -/ + | protected DIV : SAOp τ + /-- + SDIV: signed integer division + δ: 2 ; α: 1 + -/ + | protected SDIV : SAOp τ + /-- + MOD: Modulo remainder operation + δ: 2 ; α: 1 + -/ + | protected MOD : SAOp τ + /-- + SMOD: signed integer remainder + δ: 2 ; α: 1 + -/ + | protected SMOD : SAOp τ + /-- + ADDMOD: addition modulo operation + δ: 3 ; α: 1 + -/ + | protected ADDMOD : SAOp τ + /-- + MULMOD: multiplication modulo operation + δ: 3 ; α: 1 + -/ + | protected MULMOD : SAOp τ + /-- + EXP: Exponential operation + δ:2 ; α: 1 + -/ + | protected EXP : SAOp τ + /-- + SIGNEXTEND: Extend length of two's complement signed integer + δ: 2 ; α: 1 + -/ + | protected SIGNEXTEND : SAOp τ + deriving DecidableEq, Repr + +/-- + Comparison & Bitwise Logic Operations +-/ +inductive CBLOp (τ : OperationType) : Type where + /-- + LT: less than comparison + δ: 2 ; α: 1 + -/ + | protected LT : CBLOp τ + /-- + GT: greater than comparison + δ: 2 ; α: 1 + -/ + | protected GT : CBLOp τ + /-- + SLT: signed less-than comparison + δ:2 ; α: 1 + -/ + | protected SLT : CBLOp τ + /-- + SGT: signed greater-than comparison + δ: 2 ; α: 1 + -/ + | protected SGT : CBLOp τ + /-- + EQ: equality test + δ:2 ; α : 1 + -/ + | protected EQ : CBLOp τ + /-- + ISZERO: simple not operation + δ: 1 ; α : 1 + -/ + | protected ISZERO : CBLOp τ + /-- + AND: bitwise and + δ:2 ; α: 1 + -/ + | protected AND : CBLOp τ + /-- + OR: bitwise or + δ: 2 ; α: 1 + -/ + | protected OR : CBLOp τ + /-- + XOR: bitwise xor + δ: 2 ; α: 1 + -/ + | protected XOR : CBLOp τ + /-- + NOT: bitwise not + δ:1 ; α: 1 + -/ + | protected NOT : CBLOp τ + /-- + BYTE: retrieve single byte from a word + δ:2 ; α:1 + -/ + | protected BYTE : CBLOp τ + /-- + SHL: shift left operation + δ:2 ; α: 1 + -/ + | protected SHL : CBLOp τ + /-- + SHR: logical shift right operation + δ:2 ; α:1 + -/ + | protected SHR : CBLOp τ + /-- + SAR: arithmetical shift right operation + δ:2 ; α:1 + -/ + | protected SAR : CBLOp τ + /-- + CLZ: count leading zero bits in a 256-bit word + δ:1 ; α:1 + -/ + | protected CLZ : CBLOp τ + deriving DecidableEq, Repr + +/-- + Keccak operation. +-/ +inductive KOp : OperationType → Type where + /-- + KECCAK256: compute KECCAK256 hash + δ:2 ; α: 1 + -/ + | protected KECCAK256 : KOp τ + deriving DecidableEq, Repr + +/-- + Environment Information. +-/ +inductive EOp : OperationType → Type where + /-- + ADDRESS: get the address of current executing account + δ:0 ; α: 1 + -/ + | protected ADDRESS : EOp τ + /-- + BALANCE: get the balance of an input account + δ:1 ; α: 1 + -/ + | protected BALANCE : EOp τ + /-- + ORIGIN: get execution origination address + δ:0 ; α: 1 + -/ + | protected ORIGIN : EOp τ + /-- + CALLER: returns the caller address + δ: 0 ; α: 1 + -/ + | protected CALLER : EOp τ + /-- + CALLVALUE: get deposited value by the instruction / transaction + responsible for this execution. + δ: 0 ; α: 1 + -/ + | protected CALLVALUE : EOp τ + /-- + CALLDATALOAD: get input data of current environment + δ: 1 ; α: 1 + -/ + | protected CALLDATALOAD : EOp τ + /-- + CALLDATASIZE: get size of input data in current environment + δ: 0 ; α: 1 + -/ + | protected CALLDATASIZE : EOp τ + /-- + CALLDATACOPY: copy input data from environment to memory + δ: 3 ; α: 0 + -/ + | protected CALLDATACOPY : EOp τ + /-- + CODESIZE: get the size of code running in current environment + δ:0 ; α: 1 + -/ + | protected GASPRICE : EOp τ + /-- + CODECOPY: Copy code running in current environment to memory + δ: 3 ; α: 0 + -/ + | protected CODESIZE : EOp τ + /-- + GASPRICE: Gas price in current execution environment + δ: 0 ; α: 1 + -/ + | protected CODECOPY : EOp τ + /-- + EXTCODESIZE: get the size of an account's code + δ:1 ; α: 1 + -/ + | protected EXTCODESIZE : EOp τ + /-- + EXTCODECOPY: copy an account's code to memory + δ: 4 ; α: 0 + -/ + | protected EXTCODECOPY : EOp τ + /-- + RETURNDATASIZE: get the size of output data from the previous call + from the current environment. + δ: 0 ; α: 1 + -/ + | protected RETURNDATASIZE : EOp τ + /-- + RETURNDATACOPY: copy output data from previous call to memory + δ: 3 ; α: 0 + -/ + | protected RETURNDATACOPY : EOp τ + /-- + EXTCODEHASH: get hash of an account's code + δ: 1 ; α: 1 + -/ + | protected EXTCODEHASH : EOp τ + deriving DecidableEq, Repr + +/-- + Block Information. +-/ +inductive BOp : OperationType → Type where + /-- + BLOCKHASH: get the hash of one of the 256 most recent blocks + δ:1 ; α: 1 + -/ + | protected BLOCKHASH : BOp τ + /-- + COINBASE: get current's block beneficiary address + δ: 0 ; α: 1 + -/ + | protected COINBASE : BOp τ + /-- + TIMESTAMP: get current block's timestamp + δ: 0 ; α: 1 + -/ + | protected TIMESTAMP : BOp τ + /-- + NUMBER: get current block's number + δ: 0 ; α: 1 + -/ + | protected NUMBER : BOp τ + | protected PREVRANDAO : BOp τ + /-- + GASLIMIT: get the gas limit for the current block + δ: 0 ; α: 1 + -/ + | protected GASLIMIT : BOp τ + /-- + CHAINID: returns the chainid, β + δ: 0 ; α: 1 + -/ + | protected CHAINID : BOp τ + /-- + SELFBALANCE: get the balance of the current executing account + δ: 0 ; α: 1 + -/ + | protected SELFBALANCE : BOp τ + | protected BASEFEE : BOp τ + | protected BLOBHASH : BOp τ + | protected BLOBBASEFEE : BOp τ + deriving DecidableEq, Repr + +/-- + Stack, Memory, Storage and Flow Operations +-/ +inductive SMSFOp : OperationType → Type where + /-- + POP: remove an item from the stack + δ: 1 ; α: 0 + -/ + | protected POP : SMSFOp τ + /-- + MLOAD: load word from memory + δ: 1 ; α: 1 + -/ + | protected MLOAD : SMSFOp τ + /-- + MSTORE: save word in memory + δ: 2 ; α: 0 + -/ + | protected MSTORE : SMSFOp τ + /-- + SLOAD: load word from storage + δ: 1 ; α: 1 + -/ + | protected SLOAD : SMSFOp τ + /-- + SSTORE: Save word to storage + δ:2 ; α: 0 + -/ + | protected SSTORE : SMSFOp τ + /-- + MSTORE8: save byte in memory + δ: 2 ; α: 0 + -/ + | protected MSTORE8 : SMSFOp τ + /-- + JUMP: modify program counter + δ:1 ; α: 0 + -/ + | protected JUMP : SMSFOp .EVM + /-- + JUMPI: conditionally modify program counter + δ: 2 ; α: 0 + -/ + | protected JUMPI : SMSFOp .EVM + /-- + PC: get program counter before increment + δ: 0 ; α: 1 + -/ + | protected PC : SMSFOp .EVM + /-- + MSIZE: get the size of active memory in bytes + δ: 0 ; α: 1 + -/ + | protected MSIZE : SMSFOp τ + /-- + GAS: get the amount of available gas + δ: 0 ; α: 1 + -/ + | protected GAS : SMSFOp τ + /-- + JUMPDEST: mark a valid destination for jumps + δ: 0 ; α: 0 + -/ + | protected JUMPDEST : SMSFOp .EVM + /-- + EIP-1153 + https://eips.ethereum.org/EIPS/eip-1153 + TLOAD: load word from transient memory + δ: 1 ; α: 1 + -/ + | protected TLOAD : SMSFOp τ + /-- + EIP-1153 + https://eips.ethereum.org/EIPS/eip-1153 + TSTORE: Save word to transient memory + δ: 2 ; α: 0 + -/ + | protected TSTORE : SMSFOp τ + /-- + EIPS-5656 + MCOPY: copy memory areas + δ: 3 ; α: 0 + -/ + | protected MCOPY : SMSFOp τ deriving DecidableEq, Repr + +/-- + Push operations. + + PUSH0 : pushes `0` to stack. + δ: 0 ; α: 1 + + PUSHn : pushes n bytes to stack. + δ: 0 ; α: 1 +-/ +inductive POp : Type where + | protected PUSH0 : POp + | protected PUSH1 : POp + | protected PUSH2 : POp + | protected PUSH3 : POp + | protected PUSH4 : POp + | protected PUSH5 : POp + | protected PUSH6 : POp + | protected PUSH7 : POp + | protected PUSH8 : POp + | protected PUSH9 : POp + | protected PUSH10 : POp + | protected PUSH11 : POp + | protected PUSH12 : POp + | protected PUSH13 : POp + | protected PUSH14 : POp + | protected PUSH15 : POp + | protected PUSH16 : POp + | protected PUSH17 : POp + | protected PUSH18 : POp + | protected PUSH19 : POp + | protected PUSH20 : POp + | protected PUSH21 : POp + | protected PUSH22 : POp + | protected PUSH23 : POp + | protected PUSH24 : POp + | protected PUSH25 : POp + | protected PUSH26 : POp + | protected PUSH27 : POp + | protected PUSH28 : POp + | protected PUSH29 : POp + | protected PUSH30 : POp + | protected PUSH31 : POp + | protected PUSH32 : POp + deriving DecidableEq, Repr + +/-- + Duplicate Operations. + + DUPn: duplicates the nth item on the stack. + δ: n ; α: n + 1 +-/ +inductive DOp : Type where + | protected DUP1 + | protected DUP2 + | protected DUP3 + | protected DUP4 + | protected DUP5 + | protected DUP6 + | protected DUP7 + | protected DUP8 + | protected DUP9 + | protected DUP10 + | protected DUP11 + | protected DUP12 + | protected DUP13 + | protected DUP14 + | protected DUP15 + | protected DUP16 + deriving DecidableEq, Repr + +/-- + Exchange Operations. + + SWAPn: swaps the 1st and nth element of the stack. + δ: n + 1 ; α: n + 1 + +-/ +inductive ExOp : Type where + | protected SWAP1 : ExOp + | protected SWAP2 : ExOp + | protected SWAP3 : ExOp + | protected SWAP4 : ExOp + | protected SWAP5 : ExOp + | protected SWAP6 : ExOp + | protected SWAP7 : ExOp + | protected SWAP8 : ExOp + | protected SWAP9 : ExOp + | protected SWAP10 : ExOp + | protected SWAP11 : ExOp + | protected SWAP12 : ExOp + | protected SWAP13 : ExOp + | protected SWAP14 : ExOp + | protected SWAP15 : ExOp + | protected SWAP16 : ExOp + deriving DecidableEq, Repr + +/-- + Logging Operations. + + LOGn: append log record with n topics. + δ: n + 2 ; α : 0 +-/ +inductive LOp : OperationType → Type where + | protected LOG0 : LOp τ + | protected LOG1 : LOp τ + | protected LOG2 : LOp τ + | protected LOG3 : LOp τ + | protected LOG4 : LOp τ + deriving DecidableEq, Repr + +/-- + System Operations. +-/ +inductive SOp : OperationType → Type where + /-- + CREATE: create a new account with associated code + δ: 3 ; α: 1 + -/ + | protected CREATE : SOp τ + /-- + CALL: message call into an account + δ: 7 ; α: 1 + -/ + | protected CALL : SOp τ + /-- + CALLCODE: message call into this account with an alternative account's code + δ: 7 ; α: 1 + -/ + | protected CALLCODE : SOp τ + /-- + RETURN: Halt execution returning output data + δ: 2 ; α: 0 + -/ + | protected RETURN : SOp τ + /-- + DELEGATECALL: message call into this account with an alternative account's code + but persisting the current values for sender and value + δ: 6 ; α: 1 + -/ + | protected DELEGATECALL : SOp τ + /-- + CREATE2: create a new account with associated code + δ: 4 ; α: 1 + -/ + | protected CREATE2 : SOp τ + /-- + STATICCALL: static message call into an account + δ: 6 ; α: 1 + -/ + | protected STATICCALL : SOp τ + /-- + REVERT: halt execution reverting state changes but returning data and remaining gas + δ: 2 ; α: 0 + -/ + | protected REVERT : SOp τ + /-- + INVALID: invalid opcode + δ: ∅ ; α: ∅ + -/ + | protected INVALID : SOp τ + /-- + SELFDESTRUCT: halt and send entire balance to target. + Deprecated; see EIP-6780 + δ: 1 ; α: 0 + -/ + | protected SELFDESTRUCT : SOp τ + deriving DecidableEq, Repr + +end Operation + +end Operation + +open Operation + +inductive Operation : OperationType → Type where + | protected StopArith : SAOp τ → Operation τ + | protected CompBit : CBLOp τ → Operation τ + | protected Keccak : KOp τ → Operation τ + | protected Env : EOp τ → Operation τ + | protected Block : BOp τ → Operation τ + | protected StackMemFlow : SMSFOp τ → Operation τ + | protected Push : POp → Operation .EVM + | protected Dup : DOp → Operation .EVM + | protected Exchange : ExOp → Operation .EVM + | protected Log : LOp τ → Operation τ + | protected System : SOp τ → Operation τ + deriving DecidableEq, Repr +namespace Operation + +@[match_pattern] +abbrev STOP {τ : OperationType} : Operation τ := .StopArith .STOP +abbrev ADD {τ : OperationType} : Operation τ := .StopArith .ADD +abbrev MUL {τ : OperationType} : Operation τ := .StopArith .MUL +abbrev SUB {τ : OperationType} : Operation τ := .StopArith .SUB +abbrev DIV {τ : OperationType} : Operation τ := .StopArith .DIV +abbrev SDIV {τ : OperationType} : Operation τ := .StopArith .SDIV +abbrev MOD {τ : OperationType} : Operation τ := .StopArith .MOD +abbrev SMOD {τ : OperationType} : Operation τ := .StopArith .SMOD +abbrev ADDMOD {τ : OperationType} : Operation τ := .StopArith .ADDMOD +abbrev MULMOD {τ : OperationType} : Operation τ := .StopArith .MULMOD +abbrev EXP {τ : OperationType} : Operation τ := .StopArith .EXP +abbrev SIGNEXTEND {τ : OperationType} : Operation τ := .StopArith .SIGNEXTEND + +abbrev LT {τ : OperationType} : Operation τ := .CompBit .LT +abbrev GT {τ : OperationType} : Operation τ := .CompBit .GT +abbrev SLT {τ : OperationType} : Operation τ := .CompBit .SLT +abbrev SGT {τ : OperationType} : Operation τ := .CompBit .SGT +abbrev EQ {τ : OperationType} : Operation τ := .CompBit .EQ +abbrev ISZERO {τ : OperationType} : Operation τ := .CompBit .ISZERO +abbrev AND {τ : OperationType} : Operation τ := .CompBit .AND +abbrev OR {τ : OperationType} : Operation τ := .CompBit .OR +abbrev XOR {τ : OperationType} : Operation τ := .CompBit .XOR +abbrev NOT {τ : OperationType} : Operation τ := .CompBit .NOT +abbrev BYTE {τ : OperationType} : Operation τ := .CompBit .BYTE +abbrev SHL {τ : OperationType} : Operation τ := .CompBit .SHL +abbrev SHR {τ : OperationType} : Operation τ := .CompBit .SHR +abbrev SAR {τ : OperationType} : Operation τ := .CompBit .SAR +abbrev CLZ {τ : OperationType} : Operation τ := .CompBit .CLZ + +abbrev KECCAK256 {τ : OperationType} : Operation τ := .Keccak .KECCAK256 + +abbrev ADDRESS {τ : OperationType} : Operation τ := .Env .ADDRESS +abbrev BALANCE {τ : OperationType} : Operation τ := .Env .BALANCE +abbrev ORIGIN {τ : OperationType} : Operation τ := .Env .ORIGIN +abbrev CALLER {τ : OperationType} : Operation τ := .Env .CALLER +abbrev CALLVALUE {τ : OperationType} : Operation τ := .Env .CALLVALUE +abbrev CALLDATALOAD {τ : OperationType} : Operation τ := .Env .CALLDATALOAD +abbrev CALLDATASIZE {τ : OperationType} : Operation τ := .Env .CALLDATASIZE +abbrev CALLDATACOPY {τ : OperationType} : Operation τ := .Env .CALLDATACOPY +abbrev CODESIZE {τ : OperationType} : Operation τ := .Env .CODESIZE +abbrev GASPRICE {τ : OperationType} : Operation τ := .Env .GASPRICE +abbrev CODECOPY {τ : OperationType} : Operation τ := .Env .CODECOPY +abbrev EXTCODECOPY {τ : OperationType} : Operation τ := .Env .EXTCODECOPY +abbrev EXTCODESIZE {τ : OperationType} : Operation τ := .Env .EXTCODESIZE +abbrev RETURNDATASIZE {τ : OperationType} : Operation τ := .Env .RETURNDATASIZE +abbrev RETURNDATACOPY {τ : OperationType} : Operation τ := .Env .RETURNDATACOPY +abbrev EXTCODEHASH {τ : OperationType} : Operation τ := .Env .EXTCODEHASH + +abbrev BLOCKHASH {τ : OperationType} : Operation τ := .Block .BLOCKHASH +abbrev COINBASE {τ : OperationType} : Operation τ := .Block .COINBASE +abbrev TIMESTAMP {τ : OperationType} : Operation τ := .Block .TIMESTAMP +abbrev NUMBER {τ : OperationType} : Operation τ := .Block .NUMBER +abbrev PREVRANDAO {τ : OperationType} : Operation τ := .Block .PREVRANDAO +abbrev GASLIMIT {τ : OperationType} : Operation τ := .Block .GASLIMIT +abbrev CHAINID {τ : OperationType} : Operation τ := .Block .CHAINID +abbrev SELFBALANCE {τ : OperationType} : Operation τ := .Block .SELFBALANCE +abbrev BASEFEE {τ : OperationType} : Operation τ := .Block .BASEFEE +abbrev BLOBHASH {τ : OperationType} : Operation τ := .Block .BLOBHASH +abbrev BLOBBASEFEE {τ : OperationType} : Operation τ := .Block .BLOBBASEFEE + +abbrev POP {τ : OperationType} : Operation τ := .StackMemFlow .POP +abbrev MLOAD {τ : OperationType} : Operation τ := .StackMemFlow .MLOAD +abbrev MSTORE {τ : OperationType} : Operation τ := .StackMemFlow .MSTORE +abbrev SLOAD {τ : OperationType} : Operation τ := .StackMemFlow .SLOAD +abbrev SSTORE {τ : OperationType} : Operation τ := .StackMemFlow .SSTORE +abbrev MSTORE8 {τ : OperationType} : Operation τ := .StackMemFlow .MSTORE8 +abbrev JUMP : Operation .EVM := .StackMemFlow .JUMP +abbrev JUMPI : Operation .EVM := .StackMemFlow .JUMPI +abbrev PC : Operation .EVM := .StackMemFlow .PC +abbrev MSIZE {τ : OperationType} : Operation τ := .StackMemFlow .MSIZE +abbrev GAS {τ : OperationType} : Operation τ := .StackMemFlow .GAS +abbrev JUMPDEST : Operation .EVM := .StackMemFlow .JUMPDEST +abbrev TLOAD {τ : OperationType} : Operation τ := .StackMemFlow .TLOAD +abbrev TSTORE {τ : OperationType} : Operation τ := .StackMemFlow .TSTORE +abbrev MCOPY {τ : OperationType} : Operation τ := .StackMemFlow .MCOPY + +abbrev PUSH0 : Operation .EVM := .Push .PUSH0 +abbrev PUSH1 : Operation .EVM := .Push .PUSH1 +abbrev PUSH2 : Operation .EVM := .Push .PUSH2 +abbrev PUSH3 : Operation .EVM := .Push .PUSH3 +abbrev PUSH4 : Operation .EVM := .Push .PUSH4 +abbrev PUSH5 : Operation .EVM := .Push .PUSH5 +abbrev PUSH6 : Operation .EVM := .Push .PUSH6 +abbrev PUSH7 : Operation .EVM := .Push .PUSH7 +abbrev PUSH8 : Operation .EVM := .Push .PUSH8 +abbrev PUSH9 : Operation .EVM := .Push .PUSH9 +abbrev PUSH10 : Operation .EVM := .Push .PUSH10 +abbrev PUSH11 : Operation .EVM := .Push .PUSH11 +abbrev PUSH12 : Operation .EVM := .Push .PUSH12 +abbrev PUSH13 : Operation .EVM := .Push .PUSH13 +abbrev PUSH14 : Operation .EVM := .Push .PUSH14 +abbrev PUSH15 : Operation .EVM := .Push .PUSH15 +abbrev PUSH16 : Operation .EVM := .Push .PUSH16 +abbrev PUSH17 : Operation .EVM := .Push .PUSH17 +abbrev PUSH18 : Operation .EVM := .Push .PUSH18 +abbrev PUSH19 : Operation .EVM := .Push .PUSH19 +abbrev PUSH20 : Operation .EVM := .Push .PUSH20 +abbrev PUSH21 : Operation .EVM := .Push .PUSH21 +abbrev PUSH22 : Operation .EVM := .Push .PUSH22 +abbrev PUSH23 : Operation .EVM := .Push .PUSH23 +abbrev PUSH24 : Operation .EVM := .Push .PUSH24 +abbrev PUSH25 : Operation .EVM := .Push .PUSH25 +abbrev PUSH26 : Operation .EVM := .Push .PUSH26 +abbrev PUSH27 : Operation .EVM := .Push .PUSH27 +abbrev PUSH28 : Operation .EVM := .Push .PUSH28 +abbrev PUSH29 : Operation .EVM := .Push .PUSH29 +abbrev PUSH30 : Operation .EVM := .Push .PUSH30 +abbrev PUSH31 : Operation .EVM := .Push .PUSH31 +abbrev PUSH32 : Operation .EVM := .Push .PUSH32 + +abbrev DUP1 : Operation .EVM := .Dup .DUP1 +abbrev DUP2 : Operation .EVM := .Dup .DUP2 +abbrev DUP3 : Operation .EVM := .Dup .DUP3 +abbrev DUP4 : Operation .EVM := .Dup .DUP4 +abbrev DUP5 : Operation .EVM := .Dup .DUP5 +abbrev DUP6 : Operation .EVM := .Dup .DUP6 +abbrev DUP7 : Operation .EVM := .Dup .DUP7 +abbrev DUP8 : Operation .EVM := .Dup .DUP8 +abbrev DUP9 : Operation .EVM := .Dup .DUP9 +abbrev DUP10 : Operation .EVM := .Dup .DUP10 +abbrev DUP11 : Operation .EVM := .Dup .DUP11 +abbrev DUP12 : Operation .EVM := .Dup .DUP12 +abbrev DUP13 : Operation .EVM := .Dup .DUP13 +abbrev DUP14 : Operation .EVM := .Dup .DUP14 +abbrev DUP15 : Operation .EVM := .Dup .DUP15 +abbrev DUP16 : Operation .EVM := .Dup .DUP16 + +abbrev SWAP1 : Operation .EVM := .Exchange .SWAP1 +abbrev SWAP2 : Operation .EVM := .Exchange .SWAP2 +abbrev SWAP3 : Operation .EVM := .Exchange .SWAP3 +abbrev SWAP4 : Operation .EVM := .Exchange .SWAP4 +abbrev SWAP5 : Operation .EVM := .Exchange .SWAP5 +abbrev SWAP6 : Operation .EVM := .Exchange .SWAP6 +abbrev SWAP7 : Operation .EVM := .Exchange .SWAP7 +abbrev SWAP8 : Operation .EVM := .Exchange .SWAP8 +abbrev SWAP9 : Operation .EVM := .Exchange .SWAP9 +abbrev SWAP10 : Operation .EVM := .Exchange .SWAP10 +abbrev SWAP11 : Operation .EVM := .Exchange .SWAP11 +abbrev SWAP12 : Operation .EVM := .Exchange .SWAP12 +abbrev SWAP13 : Operation .EVM := .Exchange .SWAP13 +abbrev SWAP14 : Operation .EVM := .Exchange .SWAP14 +abbrev SWAP15 : Operation .EVM := .Exchange .SWAP15 +abbrev SWAP16 : Operation .EVM := .Exchange .SWAP16 + +abbrev LOG0 {τ : OperationType} : Operation τ := .Log .LOG0 +abbrev LOG1 {τ : OperationType} : Operation τ := .Log .LOG1 +abbrev LOG2 {τ : OperationType} : Operation τ := .Log .LOG2 +abbrev LOG3 {τ : OperationType} : Operation τ := .Log .LOG3 +abbrev LOG4 {τ : OperationType} : Operation τ := .Log .LOG4 + +abbrev CREATE {τ : OperationType} : Operation τ := .System .CREATE +abbrev CALL {τ : OperationType} : Operation τ := .System .CALL +abbrev CALLCODE {τ : OperationType} : Operation τ := .System .CALLCODE +abbrev RETURN {τ : OperationType} : Operation τ := .System .RETURN +abbrev DELEGATECALL {τ : OperationType} : Operation τ := .System .DELEGATECALL +abbrev CREATE2 {τ : OperationType} : Operation τ := .System .CREATE2 +abbrev STATICCALL {τ : OperationType} : Operation τ := .System .STATICCALL +abbrev REVERT {τ : OperationType} : Operation τ := .System .REVERT +abbrev INVALID {τ : OperationType} : Operation τ := .System .INVALID +abbrev SELFDESTRUCT {τ : OperationType} : Operation τ := .System .SELFDESTRUCT + +def isPush {τ : OperationType} : Operation τ → Bool + | .Push _ => true + | _ => false + +def isJump {τ : OperationType} : Operation τ → Bool + | .JUMP => true + | .JUMPI => true + | _ => false + +def isPC {τ : OperationType} : Operation τ → Bool + | .PC => true + | _ => false + +def isJumpdest {τ : OperationType} : Operation τ → Bool + | .JUMPDEST => true + | _ => false + +def isDup {τ : OperationType} : Operation τ → Bool + | .Dup _ => true + | _ => false + +def isSwap {τ : OperationType} : Operation τ → Bool + | .Exchange _ => true + | _ => false + +def isCreate {τ : OperationType} : Operation τ → Bool + | .CREATE => true + | .CREATE2 => true + | _ => false + +def isCall {τ : OperationType} : Operation τ → Bool + | .CALL => true + | .CALLCODE => true + | .DELEGATECALL => true + | .STATICCALL => true + | _ => false + + +end Operation + +open EvmYul.UInt256 + +def exp (a b : UInt256) : UInt256 := + a ^ b + +abbrev fromBool := Bool.toUInt256 + +def lt (a b : UInt256) := + fromBool (a < b) + +def gt (a b : UInt256) := + fromBool (a > b) + +-- def slt (a b : UInt256) := +-- fromBool (EvmYul.UInt256.slt a b) + +-- def sgt (a b : UInt256) := +-- fromBool (EvmYul.UInt256.sgt a b) + +def eq (a b : UInt256) := + fromBool (a = b) + +def isZero (a : UInt256) := + fromBool (eq0 a) + +end EvmYul + +open EvmYul diff --git a/vendor/evmyul/EvmYul/PerformIO.lean b/vendor/evmyul/EvmYul/PerformIO.lean new file mode 100644 index 00000000..fa681d92 --- /dev/null +++ b/vendor/evmyul/EvmYul/PerformIO.lean @@ -0,0 +1,7 @@ +unsafe def unsafePerformIO {τ} [Inhabited τ] (io : IO τ) : τ := + match unsafeIO io with + | Except.ok a => a + | Except.error e => panic! s!"unsafePerformIO was a not great idea after all: {e}" + +@[implemented_by unsafePerformIO] +def totallySafePerformIO {τ} [Inhabited τ] (io : IO τ) : τ := Inhabited.default diff --git a/vendor/evmyul/EvmYul/Pretty.lean b/vendor/evmyul/EvmYul/Pretty.lean new file mode 100644 index 00000000..abdb4733 --- /dev/null +++ b/vendor/evmyul/EvmYul/Pretty.lean @@ -0,0 +1,44 @@ +/- +Human-eyeball friendly version of various data used throughout the project. +Mostly used for debugging, possibly for reporting. + +The function for pretty printing is always `.pretty (self : Datatype) : String` +modulo parametricity. +-/ + +import EvmYul.Operations + +import Conform.Wheels + +namespace EvmYul + +/-- +Strip the existing `repr` a'la: +- EvmYul.Operation.Push (EvmYul.Operation.POp.PUSH1) → PUSH1 + +This breaks the moment that `Repr` changes its behaviour; it is fine for the time being. +-/ +def Operation.pretty {τ} (self : Operation τ) : String := + let reprStr := ToString.toString <| repr self + let lastComponent := reprStr.splitOn "." |>.getLast! + (lastComponent.take lastComponent.length.pred).toString + +/-- +`Finmap`s are not very computation-friendly and so the API is ever so slightly meh; +do feel encouraged to sorry out the order properties and just point it to an instance of `LE`. + +TODO(not critical) - Unify all the maps used throught the formalisation one day. +-/ +def Finmap.pretty {α β : Type} [ToString α] [ToString β] + [LE ((_ : α) × β)] + [IsTrans ((_ : α) × β) fun x x_1 => x ≤ x_1] + [Std.Antisymm (α := ((_ : α) × β)) fun x x_1 => x ≤ x_1] + [Std.Total (α := ((_ : α) × β)) fun x x_1 => x ≤ x_1] + [DecidableRel fun (x : ((_ : α) × β)) x_1 => x ≤ x_1] + (self : Finmap (λ _ : α ↦ β)) : String := Id.run do + let mut result : String := "" + for ⟨k, v⟩ in computeToList! self.entries do + result := result.append s!"{k} → {v}\n" + return result + +end EvmYul diff --git a/vendor/evmyul/EvmYul/SharedState.lean b/vendor/evmyul/EvmYul/SharedState.lean new file mode 100644 index 00000000..bacb4174 --- /dev/null +++ b/vendor/evmyul/EvmYul/SharedState.lean @@ -0,0 +1,9 @@ +import EvmYul.State +import EvmYul.MachineState + +namespace EvmYul + +structure SharedState (τ : OperationType) extends EvmYul.State τ, EvmYul.MachineState + deriving Inhabited + +end EvmYul diff --git a/vendor/evmyul/EvmYul/SpongeHash/Keccak256.lean b/vendor/evmyul/EvmYul/SpongeHash/Keccak256.lean new file mode 100644 index 00000000..d05a1e64 --- /dev/null +++ b/vendor/evmyul/EvmYul/SpongeHash/Keccak256.lean @@ -0,0 +1,214 @@ +/- +Pure, total Keccak-256 (restored). + +This is the equational implementation this file's stub always promised: a +plain Lean sponge over `Nat` lanes, no `partial`, no FFI. The compiled/native +path may still use the `keccak256` C symbol via `EvmYul.ffi` — whose `def` +body is THIS function, so the logical meaning is pure and provable while +execution stays fast. + +Provenance: verbatim port of the implementation maintained (corpus-validated +against solc/Forge fixtures and byte-parity-checked against the native +`keccak256` symbol) in the solidity-lean project, itself a relocation of the +former upstream implementation of this module. +-/ + +namespace EvmYul +namespace SpongeHash +namespace Keccak256 + +abbrev Byte := Nat + +def word64 : Nat := 18446744073709551616 +def mask64 : Nat := 18446744073709551615 + +def u64 (n : Nat) : Nat := + n % word64 + +def bxor (a b : Nat) : Nat := + u64 (Nat.xor (u64 a) (u64 b)) + +def band (a b : Nat) : Nat := + u64 (Nat.land (u64 a) (u64 b)) + +def bnot (a : Nat) : Nat := + mask64 - u64 a + +def rotl64 (x r : Nat) : Nat := + let x := u64 x + if r % 64 == 0 then + x + else + u64 (((x * (2 ^ (r % 64))) % word64) + (x / (2 ^ (64 - r % 64)))) + +def getD (xs : List Nat) (i : Nat) : Nat := + xs.getD i 0 + +def setD : List Nat -> Nat -> Nat -> List Nat + | [], _, _ => [] + | _ :: xs, 0, value => value :: xs + | x :: xs, i + 1, value => x :: setD xs i value + +def laneIndex (x y : Nat) : Nat := + (x % 5) + 5 * (y % 5) + +def lane (st : List Nat) (x y : Nat) : Nat := + getD st (laneIndex x y) + +def xorList : List Nat -> Nat + | [] => 0 + | x :: xs => bxor x (xorList xs) + +def columnXor (st : List Nat) (x : Nat) : Nat := + xorList ((List.range 5).map fun y => lane st x y) + +def rhoOffset (x y : Nat) : Nat := + match x % 5, y % 5 with + | 0, 0 => 0 | 0, 1 => 36 | 0, 2 => 3 | 0, 3 => 41 | 0, _ => 18 + | 1, 0 => 1 | 1, 1 => 44 | 1, 2 => 10 | 1, 3 => 45 | 1, _ => 2 + | 2, 0 => 62 | 2, 1 => 6 | 2, 2 => 43 | 2, 3 => 15 | 2, _ => 61 + | 3, 0 => 28 | 3, 1 => 55 | 3, 2 => 25 | 3, 3 => 21 | 3, _ => 56 + | _, 0 => 27 | _, 1 => 20 | _, 2 => 39 | _, 3 => 8 | _, _ => 14 + +def roundConstants : List Nat := + [0x0000000000000001, 0x0000000000008082, + 0x800000000000808A, 0x8000000080008000, + 0x000000000000808B, 0x0000000080000001, + 0x8000000080008081, 0x8000000000008009, + 0x000000000000008A, 0x0000000000000088, + 0x0000000080008009, 0x000000008000000A, + 0x000000008000808B, 0x800000000000008B, + 0x8000000000008089, 0x8000000000008003, + 0x8000000000008002, 0x8000000000000080, + 0x000000000000800A, 0x800000008000000A, + 0x8000000080008081, 0x8000000000008080, + 0x0000000080000001, 0x8000000080008008] + +def theta (st : List Nat) : List Nat := + let c := (List.range 5).map fun x => columnXor st x + let d := (List.range 5).map fun x => + bxor (getD c ((x + 4) % 5)) (rotl64 (getD c ((x + 1) % 5)) 1) + (List.range 25).map fun i => + bxor (getD st i) (getD d (i % 5)) + +def rhoPiSet (a : List Nat) (x y : Nat) (b : List Nat) : List Nat := + let dest := y + 5 * ((2 * x + 3 * y) % 5) + setD b dest (rotl64 (lane a x y) (rhoOffset x y)) + +def rhoPi (st : List Nat) : List Nat := + Id.run do + let mut b := List.replicate 25 0 + for y in List.range 5 do + for x in List.range 5 do + b := rhoPiSet st x y b + pure b + +def chi (b : List Nat) : List Nat := + (List.range 25).map fun i => + let x := i % 5 + let y := i / 5 + bxor (lane b x y) (band (bnot (lane b (x + 1) y)) (lane b (x + 2) y)) + +def iota (st : List Nat) (rc : Nat) : List Nat := + setD st 0 (bxor (getD st 0) rc) + +def round (st : List Nat) (rc : Nat) : List Nat := + iota (chi (rhoPi (theta st))) rc + +def permute : List Nat -> List Nat -> List Nat + | st, [] => st + | st, rc :: rest => permute (round st rc) rest + +def keccakF1600 (st : List Nat) : List Nat := + permute st roundConstants + +def byteShift (i : Nat) : Nat := + 2 ^ (8 * (i % 8)) + +def absorbByte (st : List Nat) (i byte : Nat) : List Nat := + let li := i / 8 + let value := bxor (getD st li) ((byte % 256) * byteShift i) + setD st li value + +def absorbBlockFrom : List Nat -> Nat -> List Byte -> List Nat + | st, _, [] => st + | st, i, byte :: bytes => + absorbBlockFrom (absorbByte st i byte) (i + 1) bytes + +def absorbBlock (st : List Nat) (block : List Byte) : List Nat := + keccakF1600 (absorbBlockFrom st 0 block) + +def rateBytes : Nat := 136 + +def padKeccak (msg : List Byte) : List Byte := + let rem := msg.length % rateBytes + let padLen := rateBytes - rem + if padLen == 1 then + msg ++ [0x81] + else + msg ++ [0x01] ++ List.replicate (padLen - 2) 0 ++ [0x80] + +def chunksOfWithFuel : Nat -> Nat -> List Byte -> List (List Byte) + | 0, _, _ => [] + | _, _, [] => [] + | fuel + 1, n, bytes => + bytes.take n :: chunksOfWithFuel fuel n (bytes.drop n) + +def chunksOf (n : Nat) (bytes : List Byte) : List (List Byte) := + if n == 0 then + [] + else + chunksOfWithFuel (bytes.length + 1) n bytes + +def absorbBlocks : List Nat -> List (List Byte) -> List Nat + | st, [] => st + | st, block :: blocks => absorbBlocks (absorbBlock st block) blocks + +def laneByte (lane : Nat) (i : Nat) : Byte := + (lane / (2 ^ (8 * i))) % 256 + +def laneBytesLE (lane : Nat) : List Byte := + (List.range 8).map fun i => laneByte lane i + +def squeezeBytes (st : List Nat) : List Byte := + ((List.range 25).flatMap fun i => laneBytesLE (getD st i)).take 32 + +def bytesOfString (s : String) : List Byte := + s.toUTF8.toList.map UInt8.toNat + +def keccak256Bytes (bytes : List Byte) : List Byte := + squeezeBytes + (absorbBlocks (List.replicate 25 0) + (chunksOf rateBytes (padKeccak bytes))) + +def keccak256String (s : String) : List Byte := + keccak256Bytes (bytesOfString s) + +def wordFromBytesBE : List Byte -> Nat + | [] => 0 + | byte :: bytes => + (byte % 256) * (2 ^ (8 * bytes.length)) + wordFromBytesBE bytes + +def selector4 (signature : String) : Nat := + wordFromBytesBE ((keccak256String signature).take 4) + +def digestWord (signature : String) : Nat := + wordFromBytesBE (keccak256String signature) + +def transferSelectorExample : Bool := + selector4 "transfer(address,uint256)" == 0xa9059cbb + +def balanceOfSelectorExample : Bool := + selector4 "balanceOf(address)" == 0x70a08231 + +def setSelectorExample : Bool := + selector4 "set(uint256)" == 0x60fe47b1 + + +/-- ByteArray convenience wrapper: hash the whole array. -/ +def keccak256 (input : ByteArray) : ByteArray := + ByteArray.mk (Array.mk ((keccak256Bytes (input.toList.map UInt8.toNat)).map UInt8.ofNat)) + +end Keccak256 +end SpongeHash +end EvmYul diff --git a/vendor/evmyul/EvmYul/State.lean b/vendor/evmyul/EvmYul/State.lean new file mode 100644 index 00000000..8e812491 --- /dev/null +++ b/vendor/evmyul/EvmYul/State.lean @@ -0,0 +1,41 @@ +import Batteries.Data.RBMap +import Mathlib.Data.Finset.Basic + +import EvmYul.State.ExecutionEnv +import EvmYul.State.Substate +import EvmYul.State.Account +import EvmYul.State.Block +import EvmYul.State.Substate +import EvmYul.State.Transaction + +import EvmYul.Maps.AccountMap + +import EvmYul.UInt256 +import EvmYul.Wheels + +namespace EvmYul + +/-- +The `State`. Section 9.3. + +- `accountMap` `σ` +- `substate` `A` +- `executionEnv` `I` +- `totalGasUsedInBlock` `Υᵍ` +-/ +structure State (τ : OperationType) where + accountMap : AccountMap τ + σ₀ : AccountMap .EVM + totalGasUsedInBlock : ℕ + transactionReceipts : Array TransactionReceipt + substate : Substate + executionEnv : ExecutionEnv τ + blocks : ProcessedBlocks + genesisBlockHeader : BlockHeader + createdAccounts : RBTree.RBSet AccountAddress compare +deriving Inhabited + +def State.blockHashes {τ} (self : State τ) : Array UInt256 := + self.blocks.map ProcessedBlock.hash + +end EvmYul diff --git a/vendor/evmyul/EvmYul/State/Account.lean b/vendor/evmyul/EvmYul/State/Account.lean new file mode 100644 index 00000000..0b4a1e0a --- /dev/null +++ b/vendor/evmyul/EvmYul/State/Account.lean @@ -0,0 +1,127 @@ +import EvmYul.Maps.StorageMap +import EvmYul.SpongeHash.Keccak256 + +import EvmYul.UInt256 +import EvmYul.Wheels + +import EvmYul.Yul.Ast + +namespace EvmYul + +inductive PrecompiledContract where + | ecrec + | sha256 + | rip160 + | identity + | expmod + | bnAdd + | bnMul + | snarkv + | blake2F + | pointEval + deriving DecidableEq, Inhabited, Repr + +namespace PrecompiledContract + +def address : PrecompiledContract → AccountAddress + | .ecrec => 1 + | .sha256 => 2 + | .rip160 => 3 + | .identity => 4 + | .expmod => 5 + | .bnAdd => 6 + | .bnMul => 7 + | .snarkv => 8 + | .blake2F => 9 + | .pointEval => 10 + +def all : List PrecompiledContract := + [ .ecrec + , .sha256 + , .rip160 + , .identity + , .expmod + , .bnAdd + , .bnMul + , .snarkv + , .blake2F + , .pointEval + ] + +def ofAddress? (addr : AccountAddress) : Option PrecompiledContract := + match addr.val with + | 1 => some .ecrec + | 2 => some .sha256 + | 3 => some .rip160 + | 4 => some .identity + | 5 => some .expmod + | 6 => some .bnAdd + | 7 => some .bnMul + | 8 => some .snarkv + | 9 => some .blake2F + | 10 => some .pointEval + | _ => none + +end PrecompiledContract + +/-- + Precompiled contract addresses. + (142) `π ≡ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}` +-/ +def π : RBTree.RBSet AccountAddress compare := + RBTree.RBSet.ofList (PrecompiledContract.all.map PrecompiledContract.address) compare + +inductive ToExecute (τ : OperationType) where + | Code (code : Yul.Ast.contractCode τ) + | Precompiled (precompiled : PrecompiledContract) + +structure PersistentAccountState (τ : OperationType) where + nonce : UInt256 + balance : UInt256 + storage : Storage + code : (Yul.Ast.contractCode τ) + codeBytes : ByteArray := default + deriving BEq, Inhabited, Repr + +/-- +The `Account` data. Section 4.1. + +Suppose `a` is some address. + +- `nonce` -- σ[a]ₙ. +- `balance` -- σ[a]_b. + +In the yellow paper it is supposed to be a 256-bit hash of the root node of +a Merkle Tree. KEVM implemets it as just an key/value map. +- `storage` -- σ[a]_s. +- `tstorage` -- Transiont storage; added in EIP-1153 +- `codeHash` -- σ[a]_c. + +For now, we assume no global map `GM` with which `GM[code_hash] ≡ code`. +- `code` +- `codeBytes` -- source-side byte image used by Yul code-image operations + when this account is entered by a call frame. +-/ +structure Account (τ : OperationType) extends PersistentAccountState τ where + tstorage : Storage +deriving BEq, Inhabited + +def PersistentAccountState.codeHash (self : PersistentAccountState .EVM) : UInt256 := + .ofNat <| fromByteArrayBigEndian (ffi.KEC self.code) + +def Account.codeHash (self : (Account .EVM)) : UInt256 := + self.toPersistentAccountState.codeHash + +def eip7702DelegationTargetOfCode? (code : ByteArray) : Option AccountAddress := + if code.size == 23 + && code.get? 0 == some 0xef + && code.get? 1 == some 0x01 + && code.get? 2 == some 0x00 then + some <| .ofNat <| fromByteArrayBigEndian (code.readWithoutPadding 3 20) + else + none + +def Account.eip7702DelegationTarget? (self : Account .EVM) : Option AccountAddress := + eip7702DelegationTargetOfCode? self.code + +end EvmYul diff --git a/vendor/evmyul/EvmYul/State/AccountOps.lean b/vendor/evmyul/EvmYul/State/AccountOps.lean new file mode 100644 index 00000000..931a5f8f --- /dev/null +++ b/vendor/evmyul/EvmYul/State/AccountOps.lean @@ -0,0 +1,49 @@ +import EvmYul.State.Account + +import EvmYul.Maps.StorageMap + +import EvmYul.Pretty + +namespace EvmYul + +namespace Account + +def lookupStorage {τ} (self : Account τ) (k : UInt256) : UInt256 := + self.storage.findD k ⟨0⟩ + +def updateStorage {τ} (self : Account τ) (k v : UInt256) : Account τ := + if v == default then + { self with storage := self.storage.erase k } + else + { self with storage := self.storage.insert k v } + +def lookupTransientStorage {τ} (self : Account τ) (k : UInt256) : UInt256 := + self.tstorage.findD k ⟨0⟩ + +def updateTransientStorage {τ} (self : Account τ) (k v : UInt256) : Account τ := + if v == default then + { self with tstorage := self.tstorage.erase k } + else + { self with tstorage := self.tstorage.insert k v } + +/-- +EMPTY(σ, a). Section 4.1., equation 14. +-/ +def emptyAccount {τ} (self : Account τ) : Bool := + match τ with + | .EVM => self.code.isEmpty ∧ self.nonce = ⟨0⟩ ∧ self.balance = ⟨0⟩ + | .Yul => self.code == default ∧ self.nonce = ⟨0⟩ ∧ self.balance = ⟨0⟩ + +def addBalance {τ} (self : Account τ) (balance : UInt256) : Option (Account τ) := + let overflow : Bool := self.balance + balance < self.balance + if overflow then .none + else .some { self with balance := self.balance + balance } + +def subBalance {τ} (self : Account τ) (balance : UInt256) : Option (Account τ) := + let underflow : Bool := self.balance < balance + if underflow then .none + else .some { self with balance := self.balance - balance } + +end Account + +end EvmYul diff --git a/vendor/evmyul/EvmYul/State/Block.lean b/vendor/evmyul/EvmYul/State/Block.lean new file mode 100644 index 00000000..d7db205f --- /dev/null +++ b/vendor/evmyul/EvmYul/State/Block.lean @@ -0,0 +1,357 @@ +import Mathlib.Data.Finset.Basic + +import EvmYul.State.BlockHeader +import EvmYul.State.Transaction +import EvmYul.State.Withdrawal + +namespace EvmYul + +instance : Repr (Finset BlockHeader) := ⟨λ _ _ ↦ "Dummy Repr for ommers. TODO - change this :)."⟩ + +structure Transactions where + trieRoot : ByteArray + array : Array Transaction +deriving BEq, Inhabited, Repr + +structure Withdrawals where + trieRoot : ByteArray + array : Array Withdrawal +deriving BEq, Inhabited, Repr + +structure RawBlock where + rlp : ByteArray + exception : List String +deriving BEq, Inhabited, Repr + +abbrev RawBlocks := Array RawBlock + +structure DeserializedBlock where + hash : UInt256 + blockHeader : BlockHeader + transactions : Transactions + withdrawals : Withdrawals + exception : List String +deriving BEq, Inhabited, Repr + +abbrev DeserializedBlocks := Array DeserializedBlock + +structure ProcessedBlock where + hash : UInt256 + blockHeader : BlockHeader + σ : AccountMap .EVM +deriving Inhabited + +abbrev ProcessedBlocks := Array ProcessedBlock + +def validateUInt256 + (b : ByteArray) + (e : EVM.Exception) + : Except EVM.Exception UInt256 +:= do + let b := fromByteArrayBigEndian b + if b ≥ UInt256.size then throw e + pure (.ofNat b) + +def validateUInt64 + (b : ByteArray) + (e : EVM.Exception) + : Except EVM.Exception UInt64 +:= do + let b := fromByteArrayBigEndian b + if b ≥ UInt64.size then throw e + pure (.ofNat b) + +def validateAccountAddress + (a : ByteArray) + (e : EVM.Exception) + : Except EVM.Exception AccountAddress +:= do + if a.size ≠ 20 then throw e + pure (.ofNat (fromByteArrayBigEndian a)) + +def deserializeBlock + (rlp : ByteArray) + : Except EVM.Exception (UInt256 × BlockHeader × Transactions × Withdrawals) +:= do + let (hash, header, transactionTrieRoot, ts, withdrawalTrieRoot, ws) ← + Option.toExceptWith (.BlockException .RLP_STRUCTURES_ENCODING) do + let .inr [headerRLP, transactionsRLP, _, withdrawalsRLP] ← oneStepRLP rlp | none + let hash : UInt256 := .ofNat <| fromByteArrayBigEndian <| ffi.KEC headerRLP + let header ← deserializeRLP headerRLP + let (.inr transactions) ← oneStepRLP transactionsRLP | none + let getTrieSnd (t : ByteArray) : Option ByteArray := do + match ← oneStepRLP t with + | .inl typePlusPayload => typePlusPayload + | .inr _ => t + let transactionTrieRoot ← + Transaction.computeTrieRoot (← transactions.toArray.mapM getTrieSnd) + let ts ← transactions.mapM deserializeRLP + let (.inr withdrawals) ← oneStepRLP withdrawalsRLP | none + let withdrawalTrieRoot ← Withdrawal.computeTrieRoot withdrawals.toArray + let ws ← withdrawals.mapM deserializeRLP + pure (hash, header, transactionTrieRoot, ts, withdrawalTrieRoot, ws) + let header ← parseHeader header + let transactions ← parseTransactions (.𝕃 ts) + let withdrawals ← parseWithdrawals (.𝕃 ws) + pure (hash, header, ⟨transactionTrieRoot, Array.mk transactions⟩, ⟨withdrawalTrieRoot, Array.mk withdrawals⟩) + where + parseWithdrawal : 𝕋 → Except EVM.Exception Withdrawal + | .𝕃 [.𝔹 globalIndex, .𝔹 validatorIndex, .𝔹 recipient, .𝔹 amount] => do + pure <| + .mk + (← validateUInt64 globalIndex (.BlockException .RLP_INVALID_FIELD_OVERFLOW_64)) + (← validateUInt64 validatorIndex (.BlockException .RLP_INVALID_FIELD_OVERFLOW_64)) + (← validateAccountAddress recipient (.BlockException .RLP_INVALID_ADDRESS)) + (← validateUInt64 amount (.BlockException .RLP_INVALID_FIELD_OVERFLOW_64)) + | _ => + dbg_trace "RLP error: parseWithdrawal" + throw <| .BlockException .RLP_STRUCTURES_ENCODING + parseWithdrawals : 𝕋 → Except EVM.Exception (List Withdrawal) + | .𝕃 withdrawals => withdrawals.mapM parseWithdrawal + | .𝔹 ⟨#[]⟩ => pure [] + | _ => + dbg_trace "RLP error: parseWithdrawals" + throw <| .BlockException .RLP_STRUCTURES_ENCODING + + parseStorageKey : 𝕋 → Except EVM.Exception UInt256 + | .𝔹 key => pure <| .ofNat <| fromByteArrayBigEndian key + | _ => + dbg_trace "RLP error: parseStorageKey" + throw <| .BlockException .RLP_STRUCTURES_ENCODING + parseAccessListEntry : 𝕋 → Except EVM.Exception (AccountAddress × Array UInt256) + | .𝕃 [.𝔹 accountAddress, .𝕃 storageKeys] => do + let storageKeys ← storageKeys.mapM parseStorageKey + let accountAddress : AccountAddress := .ofNat <| fromByteArrayBigEndian accountAddress + pure (accountAddress, Array.mk storageKeys) + | _ => + dbg_trace "RLP error: parseAccessListEntry" + throw <| .BlockException .RLP_STRUCTURES_ENCODING + + parseBlobVersionHash : 𝕋 → Except EVM.Exception ByteArray + | .𝔹 hash => pure hash + | _ => + dbg_trace "RLP error: parseBlobVersionHash" + throw <| .BlockException .RLP_STRUCTURES_ENCODING + parseTransaction : 𝕋 → Except EVM.Exception Transaction + | .𝔹 typePlusPayload => -- Transaction type > 0 + match deserializeRLP (typePlusPayload.extract 1 typePlusPayload.size) with + | some -- Type 3 transactions + (.𝕃 + [ .𝔹 chainId + , .𝔹 nonce + , .𝔹 maxPriorityFeePerGas + , .𝔹 maxFeePerGas + , .𝔹 gasLimit + , .𝔹 recipient + , .𝔹 value + , .𝔹 p + , .𝕃 accessList + , .𝔹 maxFeePerBlobGas + , .𝕃 blobVersionedHashes + , .𝔹 y + , .𝔹 r + , .𝔹 s + ] + ) => do + let recipient : Option AccountAddress:= + if recipient.isEmpty then none + else some <| .ofNat <| fromByteArrayBigEndian recipient + let accessList ← accessList.mapM parseAccessListEntry + + let base : Transaction.Base := + .mk + (.ofNat <| fromByteArrayBigEndian nonce) + (.ofNat <| fromByteArrayBigEndian gasLimit) + recipient + (← validateUInt256 value (.TransactionException .RLP_INVALID_VALUE)) + r + s + p + let withAccessList : Transaction.WithAccessList := + .mk + (.ofNat <| fromByteArrayBigEndian chainId) + accessList + (.ofNat <| fromByteArrayBigEndian y) + let maxPriorityFeePerGas := + .ofNat <| fromByteArrayBigEndian maxPriorityFeePerGas + let maxFeePerGas := .ofNat <| fromByteArrayBigEndian maxFeePerGas + let maxFeePerBlobGas := + .ofNat <| fromByteArrayBigEndian maxFeePerBlobGas + let blobVersionedHashes ← + blobVersionedHashes.mapM parseBlobVersionHash + let dynamicFeeTransaction : DynamicFeeTransaction := + .mk base withAccessList maxFeePerGas maxPriorityFeePerGas + pure <| .blob <| + BlobTransaction.mk + dynamicFeeTransaction + maxFeePerBlobGas + blobVersionedHashes + | some -- Type 2 transactions + (.𝕃 + [ .𝔹 chainId + , .𝔹 nonce + , .𝔹 maxPriorityFeePerGas + , .𝔹 maxFeePerGas + , .𝔹 gasLimit + , .𝔹 recipient + , .𝔹 value + , .𝔹 p + , .𝕃 accessList + , .𝔹 y + , .𝔹 r + , .𝔹 s + ] + ) => do + let recipient : Option AccountAddress:= + if recipient.isEmpty then none + else some <| .ofNat <| fromByteArrayBigEndian recipient + let accessList ← accessList.mapM parseAccessListEntry + + let base : Transaction.Base := + .mk + (.ofNat <| fromByteArrayBigEndian nonce) + (.ofNat <| fromByteArrayBigEndian gasLimit) + recipient + (← validateUInt256 value (.TransactionException .RLP_INVALID_VALUE)) + r + s + p + let withAccessList : Transaction.WithAccessList := + .mk + (.ofNat <| fromByteArrayBigEndian chainId) + accessList + (.ofNat <| fromByteArrayBigEndian y) + let maxPriorityFeePerGas := + .ofNat <| fromByteArrayBigEndian maxPriorityFeePerGas + let maxFeePerGas := + .ofNat <| fromByteArrayBigEndian maxFeePerGas + pure <| .dynamic <| + DynamicFeeTransaction.mk + base + withAccessList + maxFeePerGas maxPriorityFeePerGas + | some -- Type 1 transactions + (.𝕃 + [ .𝔹 chainId + , .𝔹 nonce + , .𝔹 gasPrice + , .𝔹 gasLimit + , .𝔹 recipient + , .𝔹 value + , .𝔹 p + , .𝕃 accessList + , .𝔹 y + , .𝔹 r + , .𝔹 s + ] + ) => do + let recipient : Option AccountAddress:= + if recipient.isEmpty then none + else some <| .ofNat <| fromByteArrayBigEndian recipient + let accessList ← accessList.mapM parseAccessListEntry + + let base : Transaction.Base := + .mk + (.ofNat <| fromByteArrayBigEndian nonce) + (.ofNat <| fromByteArrayBigEndian gasLimit) + recipient + (← validateUInt256 value (.TransactionException .RLP_INVALID_VALUE)) + r + s + p + let withAccessList : Transaction.WithAccessList := + .mk + (.ofNat <| fromByteArrayBigEndian chainId) + accessList + (.ofNat <| fromByteArrayBigEndian y) + let gasPrice := .ofNat <| fromByteArrayBigEndian gasPrice + pure <| .access <| AccessListTransaction.mk base withAccessList ⟨gasPrice⟩ + | _ => + dbg_trace "RLP error: deserializeRLP could not parse non-legacy transaction" + throw <| .BlockException .RLP_STRUCTURES_ENCODING + | .𝕃 + [ .𝔹 nonce + , .𝔹 gasPrice + , .𝔹 gasLimit + , .𝔹 recipient + , .𝔹 value + , .𝔹 p + , .𝔹 w + , .𝔹 r + , .𝔹 s + ] => do + let recipient : Option AccountAddress:= + if recipient.isEmpty then none + else some <| .ofNat <| fromByteArrayBigEndian recipient + + let base : Transaction.Base := + Transaction.Base.mk + (.ofNat <| fromByteArrayBigEndian nonce) + (.ofNat <| fromByteArrayBigEndian gasLimit) + recipient + (← validateUInt256 value (.TransactionException .RLP_INVALID_VALUE)) + r + s + p + let gasPrice := .ofNat <| fromByteArrayBigEndian gasPrice + let w := .ofNat <| fromByteArrayBigEndian w + pure <| .legacy <| LegacyTransaction.mk base ⟨gasPrice⟩ w + | _ => + dbg_trace "RLP error: parseTransaction" + throw <| .BlockException .RLP_STRUCTURES_ENCODING + parseTransactions : 𝕋 → Except EVM.Exception (List Transaction) + | .𝕃 transactions => transactions.mapM parseTransaction + | .𝔹 ⟨#[]⟩ => pure [] + | _ => + dbg_trace "RLP error: parseTransactions" + throw <| .BlockException .RLP_STRUCTURES_ENCODING + parseHeader : 𝕋 → Except EVM.Exception BlockHeader + | .𝕃 + [ .𝔹 parentHash + , .𝔹 uncleHash + , .𝔹 coinbase + , .𝔹 stateRoot + , .𝔹 transactionsTrie + , .𝔹 receiptTrie + , .𝔹 bloom + , .𝔹 difficulty + , .𝔹 number + , .𝔹 gasLimit + , .𝔹 gasUsed + , .𝔹 timestamp + , .𝔹 extraData + , .𝔹 mixHash + , .𝔹 nonce + , .𝔹 baseFeePerGas + , .𝔹 withdrawalsRoot + , .𝔹 blobGasUsed + , .𝔹 excessBlobGas + , .𝔹 parentBeaconBlockRoot + ] + => pure <| + BlockHeader.mk + (.ofNat <| fromByteArrayBigEndian parentHash) + (.ofNat <| fromByteArrayBigEndian uncleHash) + (.ofNat <| fromByteArrayBigEndian coinbase) + (.ofNat <| fromByteArrayBigEndian stateRoot) + transactionsTrie + receiptTrie + bloom + (fromByteArrayBigEndian difficulty) + (fromByteArrayBigEndian number) + (fromByteArrayBigEndian gasLimit) + (fromByteArrayBigEndian gasUsed) + (fromByteArrayBigEndian timestamp) + extraData + (.ofNat <| fromByteArrayBigEndian nonce) + (.ofNat <| fromByteArrayBigEndian mixHash) + (fromByteArrayBigEndian baseFeePerGas) + parentBeaconBlockRoot + withdrawalsRoot + (.ofNat <| fromByteArrayBigEndian blobGasUsed) + (.ofNat <| fromByteArrayBigEndian excessBlobGas) + | _ => + dbg_trace "Block header has wrong RLP structure" + throw <| .BlockException .RLP_STRUCTURES_ENCODING + +end EvmYul diff --git a/vendor/evmyul/EvmYul/State/BlockHeader.lean b/vendor/evmyul/EvmYul/State/BlockHeader.lean new file mode 100644 index 00000000..e986857e --- /dev/null +++ b/vendor/evmyul/EvmYul/State/BlockHeader.lean @@ -0,0 +1,107 @@ +import EvmYul.UInt256 +import EvmYul.Wheels + +namespace EvmYul + +/-- +`BlockHeader`. `H_`. Section 4.3. + +`parentHash` `p` +`ommersHash` `o` +`beneficiary` `c` +`stateRoot` `r` +`transRoot` `t` +`receiptRoot` `e` +`logsBloom` `b` +`difficulty` `d` [deprecated] +`number` `i` +`gasLimit` `l` +`gasUsed` `g` +`timestamp` `s` +`extraData` `x` +`chainId` `n` +`nonce` `n` [deprecated] +`baseFeePerGas` `f` +`withdrawalsRoot` (EIP-4895) +`parentBeaconBlockRoot` (EIP-4877) +-/ +structure BlockHeader where + parentHash : UInt256 + ommersHash : UInt256 + beneficiary : AccountAddress + stateRoot : UInt256 + transRoot : ByteArray + receiptRoot : ByteArray + logsBloom : ByteArray + -- Officially deprecated, but checked in `wrongDifficulty_Cancun` + difficulty : ℕ + number : ℕ + gasLimit : ℕ + gasUsed : ℕ + timestamp : ℕ + extraData : ByteArray + nonce : UInt64 + prevRandao : UInt256 + baseFeePerGas : ℕ + parentBeaconBlockRoot : ByteArray + withdrawalsRoot : ByteArray + blobGasUsed : UInt64 + excessBlobGas : UInt64 +deriving DecidableEq, Inhabited, Repr, BEq + +def prettyDifference (h₁ h₂ : BlockHeader) : String := Id.run do + let mut result := "" + if h₁.parentHash != h₂.parentHash then result := result ++ "different parentHash\n" + if h₁.ommersHash != h₂.ommersHash then result := result ++ "different ommersHash\n" + if h₁.beneficiary != h₂.beneficiary then result := result ++ "different beneficiary\n" + if h₁.stateRoot != h₂.stateRoot then result := result ++ "different stateRoot\n" + if h₁.transRoot != h₂.transRoot then result := result ++ "different transRoot\n" + if h₁.receiptRoot != h₂.receiptRoot then result := result ++ "different receiptRoot\n" + if h₁.logsBloom != h₂.logsBloom then result := result ++ "different logsBloom\n" + if h₁.difficulty != h₂.difficulty then result := result ++ "different difficulty\n" + if h₁.number != h₂.number then result := result ++ "different number\n" + if h₁.gasLimit != h₂.gasLimit then result := result ++ "different gasLimit\n" + if h₁.gasUsed != h₂.gasUsed then result := result ++ "different gasUsed\n" + if h₁.timestamp != h₂.timestamp then result := result ++ "different timestamp\n" + if h₁.extraData != h₂.extraData then result := result ++ "different extraData\n" + if h₁.nonce != h₂.nonce then result := result ++ "different nonce\n" + if h₁.prevRandao != h₂.prevRandao then result := result ++ "different prevRandao\n" + if h₁.baseFeePerGas != h₂.baseFeePerGas then result := result ++ "different baseFeePerGas\n" + if h₁.parentBeaconBlockRoot != h₂.parentBeaconBlockRoot then result := result ++ "different parentBeaconBlockRoot\n" + if h₁.withdrawalsRoot != h₂.withdrawalsRoot then result := result ++ "different withdrawalsRoot\n" + if h₁.blobGasUsed != h₂.blobGasUsed then result := result ++ "different blobGasUsed\n" + if h₁.excessBlobGas != h₂.excessBlobGas then result := result ++ "different excessBlobGas\n" + + result + +def TARGET_BLOB_GAS_PER_BLOCK := 393216 + +def calcExcessBlobGas (parent : BlockHeader) : Option UInt64 := do + if parent.excessBlobGas.toNat + parent.blobGasUsed.toNat < TARGET_BLOB_GAS_PER_BLOCK then + pure ⟨0⟩ + else + pure <| .ofNat <| parent.excessBlobGas.toNat + parent.blobGasUsed.toNat - TARGET_BLOB_GAS_PER_BLOCK + +-- See https://eips.ethereum.org/EIPS/eip-4844#gas-accounting +partial def fakeExponential0 (i output factor numerator denominator : ℕ) : (numeratorAccum : ℕ) → ℕ + | 0 => + output / denominator + | numeratorAccum => + let output := output + numeratorAccum + let numeratorAccum := (numeratorAccum * numerator) / (denominator * i) + let i := i + 1 + fakeExponential0 i output factor numerator denominator numeratorAccum + +def fakeExponential (factor numerator denominator : ℕ) : ℕ := + fakeExponential0 1 0 factor numerator denominator (factor * denominator) + +def MIN_BASE_FEE_PER_BLOB_GAS := 1 +def BLOB_BASE_FEE_UPDATE_FRACTION := 3338477 + +def BlockHeader.getBlobGasprice (h : BlockHeader) : ℕ := + fakeExponential + MIN_BASE_FEE_PER_BLOB_GAS + h.excessBlobGas.toNat + BLOB_BASE_FEE_UPDATE_FRACTION + +end EvmYul diff --git a/vendor/evmyul/EvmYul/State/ExecutionEnv.lean b/vendor/evmyul/EvmYul/State/ExecutionEnv.lean new file mode 100644 index 00000000..cf5b08af --- /dev/null +++ b/vendor/evmyul/EvmYul/State/ExecutionEnv.lean @@ -0,0 +1,49 @@ +import EvmYul.Wheels +import EvmYul.UInt256 +import EvmYul.State.BlockHeader +import EvmYul.Yul.Ast + +namespace EvmYul + +/-- +The execution envorinment `I` `ExecutionEnv`. Section 9.3. +- `codeOwner` `Iₐ` +- `sender` `Iₒ` +- `source` `Iₛ` +- `weiValue` `Iᵥ` +- `calldata` `I_d` +- `code` `I_b` +- `gasPrice` `Iₚ` +- `header` `I_H` +- `depth` `Iₑ` +- `perm` `I_w` +-/ +structure ExecutionEnv (τ : OperationType) where + codeOwner : AccountAddress + sender : AccountAddress + source : AccountAddress + weiValue : UInt256 + calldata : ByteArray + code : (Yul.Ast.contractCode τ) + gasPrice : ℕ + header : BlockHeader + depth : ℕ + perm : Bool + blobVersionedHashes : List ByteArray + codeBytes : ByteArray := default + deriving BEq, Inhabited, Repr + +def prevRandao {τ} (e : ExecutionEnv τ) : UInt256 := + e.header.prevRandao + +def basefee {τ} (e : ExecutionEnv τ) : UInt256 := + .ofNat e.header.baseFeePerGas + +def ExecutionEnv.getBlobGasprice {τ} (e : ExecutionEnv τ) : UInt256 := + .ofNat e.header.getBlobGasprice + +def blobhash {τ} (e : ExecutionEnv τ) (i : UInt256) : UInt256 := + e.blobVersionedHashes[i.toNat]?.option ⟨0⟩ + (.ofNat ∘ fromByteArrayBigEndian) + +end EvmYul diff --git a/vendor/evmyul/EvmYul/State/Substate.lean b/vendor/evmyul/EvmYul/State/Substate.lean new file mode 100644 index 00000000..52e66fd2 --- /dev/null +++ b/vendor/evmyul/EvmYul/State/Substate.lean @@ -0,0 +1,87 @@ +import Batteries.Data.RBMap +import EvmYul.UInt256 +import EvmYul.Wheels +import EvmYul.State.Account + +namespace EvmYul + +/-- +Not important for reasoning about Substate, this is currently done to get some nice performance properties +of the `RBTree.RBMap`. + +TODO - to reason about the model, we will be better off with `Finset` or some such - +without the requirement of ordering. + +The current goal is to make sure that the model is executable and conformance-testable +before we make it easy to reason about. +-/ +def Substate.storageKeysCmp (sk₁ sk₂ : AccountAddress × UInt256) : Ordering := + lexOrd.compare sk₁ sk₂ + +structure LogEntry where + address : AccountAddress + topics : Array UInt256 + data : ByteArray +deriving BEq, Inhabited, Repr + +def LogEntry.to𝕋 : LogEntry → 𝕋 + | ⟨address, topics, data⟩ => + .𝕃 + [ .𝔹 address.toByteArray + , .𝕃 <| topics.toList.map (.𝔹 ∘ UInt256.toByteArray) + , .𝔹 data + ] + +abbrev LogSeries := Array LogEntry + +def LogSeries.to𝕋 (logSeries : LogSeries) : 𝕋 := + .𝕃 (logSeries.toList.map LogEntry.to𝕋) + +/-- +The `Substate` `A`. Section 6.1. +- `selfDestructSet` `Aₛ` +- `touchedAccounts` `Aₜ` +- `refundBalance` `Aᵣ` +- `accessedAccounts` `Aₐ` +- `accessedStorageKey` `Aₖ` +- `logSeries` `Aₗ` +-/ +structure Substate where + selfDestructSet : RBTree.RBSet AccountAddress compare + touchedAccounts : RBTree.RBSet AccountAddress compare + refundBalance : UInt256 + accessedAccounts : RBTree.RBSet AccountAddress compare + accessedStorageKeys : RBTree.RBSet (AccountAddress × UInt256) Substate.storageKeysCmp + logSeries : LogSeries + deriving BEq, Inhabited, Repr + +/-- + (63) `A0 ≡ (∅, (), ∅, 0, π, ∅)` +-/ +def A0 : Substate := { (default : Substate) with accessedAccounts := π } + +-- See the Bloom filter function M +def bloomFilter (a : Array ByteArray) : ByteArray := + let zeroes : ByteArray := ffi.ByteArray.zeroes 256 + a.foldl set3Bits zeroes + where + setBit (bytes256 : ByteArray) (bitIndex : ℕ) : ByteArray := + let byteIndex := 255 - bitIndex / 8 + let mask : UInt8 := .ofNat <| 1 <<< (bitIndex % 8) + let newByte := bytes256[byteIndex]! ||| mask + bytes256.set! byteIndex newByte + bitIndices (x : ByteArray) : List ℕ := + let kec := ffi.KEC x + let lowOrder11Bits := λ b ↦ b &&& (1<<<11 - 1) + [ kec.readWithPadding 0 2 + , kec.readWithPadding 2 2 + , kec.readWithPadding 4 2 + ].map (lowOrder11Bits ∘ fromByteArrayBigEndian) + set3Bits acc b := bitIndices b |>.foldl setBit acc + +def Substate.joinLogs (substate : Substate) : Array ByteArray := + Array.flatten <| + substate.logSeries.map + λ ⟨a, as, _⟩ ↦ (as.map UInt256.toByteArray).push a.toByteArray + +end EvmYul diff --git a/vendor/evmyul/EvmYul/State/SubstateOps.lean b/vendor/evmyul/EvmYul/State/SubstateOps.lean new file mode 100644 index 00000000..f7bb37d2 --- /dev/null +++ b/vendor/evmyul/EvmYul/State/SubstateOps.lean @@ -0,0 +1,15 @@ +import EvmYul.State.Substate + +namespace EvmYul + +namespace Substate + +def addAccessedAccount (self : Substate) (addr : AccountAddress) : Substate := + { self with accessedAccounts := self.accessedAccounts.insert addr } + +def addAccessedStorageKey (self : Substate) (sk : AccountAddress × UInt256) : Substate := + { self with accessedStorageKeys := self.accessedStorageKeys.insert sk } + +end Substate + +end EvmYul diff --git a/vendor/evmyul/EvmYul/State/Transaction.lean b/vendor/evmyul/EvmYul/State/Transaction.lean new file mode 100644 index 00000000..510022c1 --- /dev/null +++ b/vendor/evmyul/EvmYul/State/Transaction.lean @@ -0,0 +1,183 @@ +import Mathlib.Data.List.AList + +import EvmYul.UInt256 +import EvmYul.Wheels +import EvmYul.State.TrieRoot +import Conform.Wheels +import EvmYul.State.Substate + +namespace EvmYul + +open RBTree (RBMap RBSet) + +-- "All transaction types specify a number of common fields:" +/-- +`BaseTransaction`. Section 4.3. + +- `nonce` `n` +- `gasLimit` `g` +- `recipinet` `t` +- `value` `v` +- `r` `r` +- `s` `s` +- `data` `d/i` +-/ +structure Transaction.Base where + nonce : UInt256 + gasLimit : UInt256 + recipient : Option AccountAddress + value : UInt256 + r : ByteArray + s : ByteArray + data : ByteArray +deriving BEq, Repr + +-- "EIP-2930 (type 1) and EIP-1559 (type 2) transactions also have:"" +/-- +`AccessList`. EIP-2930. +- `chainId` `c` +- `accessList` `A` +- `yParity` `y` +-/ +structure Transaction.WithAccessList where + chainId : UInt256 + accessList : List (AccountAddress × Array UInt256) + yParity : UInt256 +deriving BEq, Repr + +-- "type 0 and type 1 transactions specify gas price as a single value:" +/-- +`WithGasPrice`. Section 4.3. +- `gasPrice` `p` +-/ +structure Transaction.WithGasPrice where + gasPrice : UInt256 +deriving BEq, Repr + +-- Legacy transactions do not have an `accessList`, while `chainId` and `yParity` for legacy transactions are combined into a single value: +/-- +Type 0: `LegacyTransaction`. Section 4.3. +- `nonce` `n` +- `gasLimit` `g` +- `recipinet` `t` +- `value` `v` +- `r` `r` +- `s` `s` +- `data` `d/i` +- `gasPrice` `p` +- `w` `w` +-/ +structure LegacyTransaction extends Transaction.Base, Transaction.WithGasPrice where + w: UInt256 +deriving BEq, Repr + +/-- Type 1: `AccessListTransaction` +- `nonce` `n` +- `gasLimit` `g` +- `recipinet` `t` +- `value` `v` +- `r` `r` +- `s` `s` +- `data` `d/i` +- `chainId` `c` +- `accessList` `A` +- `yParity` `y` +- `gasPrice` `p` +-/ +structure AccessListTransaction + extends Transaction.Base, Transaction.WithAccessList, Transaction.WithGasPrice +deriving BEq, Repr + +/-- +Type 2: `DynamicFeeTransaction` +- `nonce` `n` +- `gasLimit` `g` +- `recipinet` `t` +- `value` `v` +- `r` `r` +- `s` `s` +- `data` `d/i` +- `chainId` `c` +- `accessList` `A` +- `yParity` `y` +- `maxFeePerGas` `m` +- `maxPriorityFeePerGas` `f` +-/ +structure DynamicFeeTransaction extends Transaction.Base, Transaction.WithAccessList where + maxFeePerGas : UInt256 + maxPriorityFeePerGas : UInt256 +deriving BEq, Repr + +structure BlobTransaction extends DynamicFeeTransaction where + maxFeePerBlobGas : UInt256 + blobVersionedHashes : List ByteArray +deriving BEq, Repr + +inductive Transaction where + | legacy : LegacyTransaction → Transaction + | access : AccessListTransaction → Transaction + | dynamic : DynamicFeeTransaction → Transaction + | blob : BlobTransaction → Transaction +deriving BEq, Repr + +def Transaction.base : Transaction → Transaction.Base + | legacy t => t.toBase + | access t => t.toBase + | dynamic t => t.toBase + | blob t => t.toBase + +def Transaction.getAccessList : Transaction → List (AccountAddress × Array UInt256) + | legacy _ => [] + | access t => t.accessList + | dynamic t => t.accessList + | blob t => t.accessList + +def Transaction.type : Transaction → UInt8 + | .legacy _ => 0 + | .access _ => 1 + | .dynamic _ => 2 + | .blob _ => 3 + +def Transaction.toBlobs (t : ℕ × ByteArray) : Option (String × String) := do + let rlpᵢ ← RLP (.𝔹 (BE t.1)) + let rlp := t.2 + pure (EvmYul.toHex rlpᵢ, EvmYul.toHex rlp) + +def Transaction.computeTrieRoot (ts : Array ByteArray) : Option ByteArray := do + match Array.mapM Transaction.toBlobs ((Array.range ts.size).zip ts) with + | none => .none + | some ws => (ByteArray.ofBlob (blobComputeTrieRoot ws)).toOption + +structure TransactionReceipt where + type : UInt8 /- R_x -/ + statusCode : Bool /- R_z -/ + cumulativeGasUsedInBlock : ℕ /- R_u -/ + bloomFilter : ByteArray /- R_b -/ + logSeries : LogSeries /- R_l -/ +deriving BEq, Inhabited, Repr + +def L_R : TransactionReceipt → 𝕋 + | ⟨_, statusCode, cumulativeGasUsedInBlock, bloomFilter, logSeries⟩ => + .𝕃 + [ if statusCode then .𝔹 (BE 1) else .𝔹 (BE 0) + , .𝔹 (BE cumulativeGasUsedInBlock) + , .𝔹 bloomFilter + , logSeries.to𝕋 + ] + +def TransactionReceipt.toBlobs (w : ℕ × ByteArray) : Option (String × String) := do + let rlpᵢ ← RLP (.𝔹 (BE w.1)) + let rlp ← w.2 + pure (EvmYul.toHex rlpᵢ, EvmYul.toHex rlp) + +-- EIP-4895 +def TransactionReceipt.computeTrieRoot (ws : Array ByteArray) : Option ByteArray := do + match Array.mapM TransactionReceipt.toBlobs ((Array.range ws.size).zip ws) with + | none => .none + | some ws => (ByteArray.ofBlob (blobComputeTrieRoot ws)).toOption + +def TransactionReceipt.toTrieValue (r : TransactionReceipt) : ByteArray := + let rlp := Option.get! ∘ RLP ∘ L_R <| r + if r.type = 0 then rlp else ⟨#[r.type]⟩ ++ rlp + +end EvmYul diff --git a/vendor/evmyul/EvmYul/State/TrieRoot.lean b/vendor/evmyul/EvmYul/State/TrieRoot.lean new file mode 100644 index 00000000..2a83c1cd --- /dev/null +++ b/vendor/evmyul/EvmYul/State/TrieRoot.lean @@ -0,0 +1,34 @@ +import EvmYul.PerformIO +import EvmYul.Wheels + +def blobComputeTrieRoot (ws : Array (String × String)) : String := + -- dbg_trace s!"called blobComputeTrieRoot with an array of size {ws.size}" + -- dbg_trace s!"called blobComputeTrieRoot with data {ws[0]!.2.length}" + + totallySafePerformIO do + /- + Yes, this makes testing in parallel technically nondeterministic, but it is also the + fastest to implement. + + This 'using a file trick' to get around big command line arguments should probably go + at some point. + -/ + let entropy ← IO.getRandomBytes 3 + let entropy' ← IO.monoNanosNow + let inputFile := s!"EvmYul/EllipticCurvesPy/trieInput_{entropy}{entropy'}.txt" + IO.FS.withFile inputFile .write λ h ↦ + forM ws.toList λ s ↦ do + h.putStrLn s.1 + h.putStrLn s.2 + let result ← IO.Process.run (pythonCommandOfInput inputFile ws) + IO.FS.removeFile inputFile + pure result + where + pythonCommandOfInput (inputFile : String) (ws : Array (String × String)) : IO.Process.SpawnArgs := { + cmd := "python3", + args := + #["EvmYul/EllipticCurvesPy/trie_root.py"] + ++ #[inputFile] + ++ #[ws.size.repr] + -- ++ (ws.map (λ (i, w) ↦ #[i, w])).join + } diff --git a/vendor/evmyul/EvmYul/State/Withdrawal.lean b/vendor/evmyul/EvmYul/State/Withdrawal.lean new file mode 100644 index 00000000..3a4b157b --- /dev/null +++ b/vendor/evmyul/EvmYul/State/Withdrawal.lean @@ -0,0 +1,65 @@ +-- Requires the following python packages: pycryptodome + +import EvmYul.Wheels +import EvmYul.PerformIO +import EvmYul.Maps.AccountMap +import Conform.Wheels +import EvmYul.EVM.Exception + +import EvmYul.State.TrieRoot + +open EvmYul ByteArray + +/-- +EIP-4895: Beacon chain push withdrawals as operations. +- `index` - starting from `0` +- `validator_index` +- `address` - a recipient for the withdrawn ether +- `amount` - a nonzero amount of ether given in Gwei +-/ +structure Withdrawal where + index : UInt64 + validatorIndex : UInt64 + address : AccountAddress + amount : UInt64 +deriving Repr, BEq + +namespace Withdrawal + +def to𝕋 : Withdrawal → 𝕋 + | {index, validatorIndex, address, amount} => + .𝕃 + [ .𝔹 (BE index.toFin.val) + , .𝔹 (BE validatorIndex.toFin.val) + , .𝔹 (address.toByteArray) + , .𝔹 (BE amount.toFin.val) + ] + +end Withdrawal + +def Withdrawal.toBlobs (w : ℕ × ByteArray) : Option (String × String) := do + let rlpᵢ ← RLP (.𝔹 (BE w.1)) + let rlp ← w.2 + pure (EvmYul.toHex rlpᵢ, EvmYul.toHex rlp) + +-- EIP-4895 +def Withdrawal.computeTrieRoot (ws : Array ByteArray) : Option ByteArray := do + match Array.mapM Withdrawal.toBlobs ((Array.range ws.size).zip ws) with + | none => .none + | some ws => (ByteArray.ofBlob (blobComputeTrieRoot ws)).toOption + +def applyWithdrawals + (σ : AccountMap .EVM) + (ws : Array Withdrawal) + : + AccountMap .EVM +:= + ws.foldl applyWithdrawal σ + where + applyWithdrawal (σ : AccountMap .EVM) (w : Withdrawal) : AccountMap .EVM := + if w.amount <= 0 then σ else + match σ.find? w.address with + | none => + σ.insert w.address {(default : Account .EVM) with balance := .ofNat <| w.amount.toFin.val * 10^9} + | some ac => + σ.insert w.address {ac with balance := .ofNat <| ac.balance.toNat + w.amount.toFin.val * 10^9} diff --git a/vendor/evmyul/EvmYul/StateOps.lean b/vendor/evmyul/EvmYul/StateOps.lean new file mode 100644 index 00000000..7b81c29b --- /dev/null +++ b/vendor/evmyul/EvmYul/StateOps.lean @@ -0,0 +1,189 @@ +import EvmYul.State.SubstateOps +import EvmYul.State.AccountOps + +import EvmYul.Maps.AccountMap + +import EvmYul.State +import EvmYul.Wheels +import EvmYul.EVM.GasConstants + +namespace EvmYul + +namespace State + +def addAccessedAccount {τ} (self : State τ) (addr : AccountAddress) : State τ := + { self with substate := self.substate.addAccessedAccount addr } + +def addAccessedStorageKey {τ} (self : State τ) (sk : AccountAddress × UInt256) : State τ := + { self with substate := self.substate.addAccessedStorageKey sk } + +/-- +DEAD(σ, a). Section 4.1., equation 15. +-/ +def dead {τ} (σ : AccountMap τ) (addr : AccountAddress) : Bool := + σ.find? addr |>.option True Account.emptyAccount + +def accountExists {τ} (self : State τ) (addr : AccountAddress) : Bool := self.accountMap.find? addr |>.isSome + +def lookupAccount {τ} (self : State τ) (addr : AccountAddress) : Option (Account τ) := + self.accountMap.find? addr + +def updateAccount {τ} (addr : AccountAddress) (act : Account τ) (self : State τ) : State τ := + { self with accountMap := self.accountMap.insert addr act } + +def setAccount {τ} (self : State τ) (addr : AccountAddress) (acc : Account τ) : State τ := + { self with accountMap := self.accountMap.insert addr acc } + +def setSelfAccount {τ} (self : State τ) (acc : Account τ := default) : State τ := + self.setAccount self.executionEnv.codeOwner acc + +def updateAccount! {τ} (self : State τ) (addr : AccountAddress) (f : Account τ → Account τ) : State τ := + let acc! := self.lookupAccount addr |>.getD default + self.setAccount addr (f acc!) + +def updateSelfAccount! {τ} (self : State τ) : (Account τ → Account τ) → State τ := + self.updateAccount! self.executionEnv.codeOwner + +def balance {τ} (self : State τ) (k : UInt256) : State τ × UInt256 := + let addr := AccountAddress.ofUInt256 k + (self.addAccessedAccount addr, self.accountMap.find? addr |>.elim ⟨0⟩ (·.balance)) + +def accountCodeImage {τ} (account : Account τ) : ByteArray := + match τ with + | .EVM => account.code + | .Yul => account.codeBytes + +def initialiseAccount (addr : AccountAddress) (self : State .EVM) : State .EVM := + if self.accountExists addr then self else self.updateAccount addr default + +def calldataload {τ} (self : State τ) (v : UInt256) : UInt256 := + uInt256OfByteArray <| self.executionEnv.calldata.readBytes v.toNat 32 + +def setNonce! {τ} (self : State τ) (addr : AccountAddress) (nonce : UInt256) : State τ := + self.updateAccount! addr (λ acc ↦ { acc with nonce := nonce }) + +def setSelfNonce! {τ} (self : State τ) (nonce : UInt256) : State τ := + self.setNonce! self.executionEnv.codeOwner nonce + +def selfStorage! {τ} (self : State τ) : Storage := + self.lookupAccount self.executionEnv.codeOwner |>.getD default |>.storage + +section CodeCopy + +def extCodeSize {τ} (self : State τ) (a : UInt256) : State τ × UInt256 := + let addr := AccountAddress.ofUInt256 a + let s := + self.lookupAccount addr |>.option ⟨0⟩ + (.ofNat ∘ ByteArray.size ∘ accountCodeImage) + (self.addAccessedAccount addr, s) + +def extCodeHash {τ} (self : State τ) (v : UInt256) : State τ × UInt256 := + let addr := AccountAddress.ofUInt256 v + let newState := self.addAccessedAccount addr + if dead self.accountMap addr then (newState, ⟨0⟩) else + let r := + self.lookupAccount (AccountAddress.ofUInt256 v) |>.option ⟨0⟩ + (fun account => + .ofNat <| fromByteArrayBigEndian (ffi.KEC (accountCodeImage account))) + (newState, r) + +end CodeCopy + +section Blocks + +def blockHash {τ} (self : State τ) (blockNumber : UInt256) : UInt256 := + let v := self.executionEnv.header.number + if v ≤ blockNumber.toNat || blockNumber.toNat + 256 < v then ⟨0⟩ + else + let hashes := self.blockHashes + hashes.getD blockNumber.toNat ⟨0⟩ + +def coinBase {τ} (self : State τ) : AccountAddress := + self.executionEnv.header.beneficiary + +def timeStamp {τ} (self : State τ) : UInt256 := + .ofNat self.executionEnv.header.timestamp + +def number {τ} (self : State τ) : UInt256 := + .ofNat self.executionEnv.header.number + +def difficulty {τ} (self : State τ) : UInt256 := + .ofNat self.executionEnv.header.difficulty + +def gasLimit {τ} (self : State τ) : UInt256 := + .ofNat self.executionEnv.header.gasLimit + +def chainId {τ} (_ : State τ) : UInt256 := .ofNat EvmYul.chainId + +def selfbalance {τ} (self : State τ) : UInt256 := + RBTree.RBMap.find? self.accountMap self.executionEnv.codeOwner |>.elim ⟨0⟩ (·.balance) + +def setCode (self : State .EVM) (code : ByteArray) : State .EVM := + { self with executionEnv.code := code } + +end Blocks + +section Storage + +def setStorage! {τ} (self : State τ) (addr : AccountAddress) (strg : Storage) : State τ := + self.updateAccount! addr (λ acc ↦ { acc with storage := strg }) + +def setSelfStorage! {τ} (self : State τ) : Storage → State τ := + self.setStorage! self.executionEnv.codeOwner + +def sload {τ} (self : State τ) (spos : UInt256) : State τ × UInt256 := + let Iₐ := self.executionEnv.codeOwner + let v := self.lookupAccount Iₐ |>.option ⟨0⟩ (Account.lookupStorage (k := spos)) + let state' := self.addAccessedStorageKey (Iₐ, spos) + (state', v) + +def sstore {τ} (self : State τ) (spos sval : UInt256) : State τ := + let Iₐ := self.executionEnv.codeOwner + let { storage := σ_Iₐ, .. } := self.accountMap.find! Iₐ + let v₀ := + match self.σ₀.find? Iₐ with + | none => ⟨0⟩ + | some acc => acc.storage.findD spos ⟨0⟩ + let v := σ_Iₐ.findD spos ⟨0⟩ + let v' := sval + + let r_dirtyclear : ℤ := + if v₀ ≠ .ofNat 0 && v = .ofNat 0 then - GasConstants.Rsclear else + if v₀ ≠ .ofNat 0 && v' = .ofNat 0 then GasConstants.Rsclear else + 0 + + let r_dirtyreset : ℤ := + if v₀ = v' && v₀ = .ofNat 0 then GasConstants.Gsset - GasConstants.Gwarmaccess else + if v₀ = v' && v₀ ≠ .ofNat 0 then GasConstants.Gsreset - GasConstants.Gwarmaccess else + 0 + + let ΔAᵣ : ℤ := + if v ≠ v' && v₀ = v && v' = .ofNat 0 then GasConstants.Rsclear else + if v ≠ v' && v₀ ≠ v then r_dirtyclear + r_dirtyreset else + 0 + + let newAᵣ : UInt256 := + match ΔAᵣ with + | .ofNat n => self.substate.refundBalance + .ofNat n + | .negSucc n => self.substate.refundBalance - .ofNat n - ⟨1⟩ + self.lookupAccount Iₐ |>.option self λ acc ↦ + let self' := + self.setAccount Iₐ (acc.updateStorage spos sval) + |>.addAccessedStorageKey (Iₐ, spos) + { self' with substate.refundBalance := newAᵣ } + +def tload {τ} (self : State τ) (spos : UInt256) : State τ × UInt256 := + let Iₐ := self.executionEnv.codeOwner + let v := self.lookupAccount Iₐ |>.option ⟨0⟩ (Account.lookupTransientStorage (k := spos)) + (self, v) + +def tstore {τ} (self : State τ) (spos sval : UInt256) : State τ := + let Iₐ := self.executionEnv.codeOwner + self.lookupAccount Iₐ |>.option self λ acc ↦ + self.updateAccount Iₐ (acc.updateTransientStorage spos sval) + +end Storage + +end State + +end EvmYul diff --git a/vendor/evmyul/EvmYul/UInt256.lean b/vendor/evmyul/EvmYul/UInt256.lean new file mode 100644 index 00000000..35a3560c --- /dev/null +++ b/vendor/evmyul/EvmYul/UInt256.lean @@ -0,0 +1,532 @@ +import Init.Data.Nat.Div +import Mathlib.Data.Nat.Basic +import Mathlib.Data.Fin.Basic +import Mathlib.Data.Vector.Basic +import Mathlib.Algebra.Group.Defs +import Mathlib.Algebra.GroupWithZero.Defs +import Mathlib.Algebra.Ring.Basic +import Mathlib.Algebra.Order.Floor.Defs +import Mathlib.Algebra.Order.Floor.Ring +import Mathlib.Algebra.Order.Floor.Semiring +import Mathlib.Data.ZMod.Defs +import Mathlib.Tactic.Ring + +namespace EvmYul + +/-- The size of type `UInt256`, that is, `2^256`. -/ +def UInt256.size : ℕ := + 115792089237316195423570985008687907853269984665640564039457584007913129639936 + +instance : NeZero UInt256.size where + out := (by unfold UInt256.size; simp) + +structure UInt256 where + val : Fin UInt256.size + deriving BEq, Ord + +instance : ToString UInt256 where + toString a := toString a.val + +namespace UInt256 + +def ofNat (n : ℕ) : UInt256 := Id.run do + ⟨Fin.ofNat _ n⟩ + +def toNat (u : UInt256) : ℕ := u.val.val + +instance : Repr UInt256 where + reprPrec n _ := repr n.toNat + +instance {n : ℕ} : OfNat (Fin UInt256.size) n := ⟨Fin.ofNat _ n⟩ +instance : Inhabited UInt256 := ⟨ofNat 0⟩ + +end UInt256 + +end EvmYul + +section CastUtils + +open EvmYul UInt256 + +abbrev Nat.toUInt256 : ℕ → UInt256 := ofNat +abbrev UInt8.toUInt256 (a : UInt8) : UInt256 := + ⟨a.toNat, Nat.lt_trans a.toFin.2 (by decide)⟩ +def Bool.toUInt256 (b : Bool) : UInt256 := + if b then UInt256.ofNat 1 else UInt256.ofNat 0 + +@[simp] +lemma Bool.toUInt256_true : true.toUInt256 = UInt256.ofNat 1 := rfl + +@[simp] +lemma Bool.toUInt256_false : false.toUInt256 = UInt256.ofNat 0 := rfl + +end CastUtils + +namespace EvmYul + +namespace UInt256 + +def add (a b : UInt256) : UInt256 := ⟨a.val + b.val⟩ +def sub (a b : UInt256) : UInt256 := ⟨a.val - b.val⟩ +def mul (a b : UInt256) : UInt256 := ⟨a.val * b.val⟩ +def div (a b : UInt256) : UInt256 := ⟨a.val / b.val⟩ +def mod (a b : UInt256) : UInt256 := if b.val == 0 then ⟨0⟩ else ⟨a.val % b.val⟩ +def modn (a : UInt256) (n : ℕ) : UInt256 := ⟨Fin.modn a.val n⟩ +def land (a b : UInt256) : UInt256 := ⟨Fin.land a.val b.val⟩ +def lor (a b : UInt256) : UInt256 := ⟨Fin.lor a.val b.val⟩ +def xor (a b : UInt256) : UInt256 := ⟨Fin.xor a.val b.val⟩ +def shiftLeft (a b : UInt256) : UInt256 := + if b.val >= 256 then ⟨0⟩ else ⟨a.val <<< b.val⟩ +def shiftRight (a b : UInt256) : UInt256 := + if b.val >= 256 then ⟨0⟩ else ⟨a.val >>> b.val⟩ +-- def lt (a b : UInt256) : Prop := a.1 < b.1 +-- def le (a b : UInt256) : Prop := a.1 ≤ b.1 +def log2 (a : UInt256) : UInt256 := ⟨Fin.log2 a.val⟩ + +instance : Add UInt256 := ⟨UInt256.add⟩ +instance : Sub UInt256 := ⟨UInt256.sub⟩ +instance : Mul UInt256 := ⟨UInt256.mul⟩ +instance : Div UInt256 := ⟨UInt256.div⟩ +instance : Mod UInt256 := ⟨UInt256.mod⟩ +instance : HMod UInt256 ℕ UInt256 := ⟨UInt256.modn⟩ + +instance : LT UInt256 where + lt a b := LT.lt a.val b.val + +instance : LE UInt256 where + le a b := LE.le a.val b.val + +instance : Preorder UInt256 where + le_refl := by intro; apply Nat.le_refl + le_trans := by intro _ _ _ h₁ h₂ ; apply Nat.le_trans h₁ h₂ + lt := fun a b => a ≤ b ∧ ¬b ≤ a + lt_iff_le_not_ge := by intros; rfl + +def complement (a : UInt256) : UInt256 := ⟨0 - (a.val + 1)⟩ + +def lnot (a : UInt256) : UInt256 := ofNat (UInt256.size - 1) - a + +def abs (a : UInt256) : UInt256 := + if 2 ^ 255 <= a.toNat + then ⟨a.val * (-1)⟩ + else a + +def fromSigned (a : UInt256) : ℤ := + if a.toNat < 2^255 then a.val else - (Nat.xor (UInt256.size - 1) a.val) - 1 + +def toSigned (i : ℤ) : UInt256 := + match i with + | .ofNat n => ofNat n + | .negSucc n => ofNat (UInt256.size - 1 - n) + +instance : Complement UInt256 := ⟨EvmYul.UInt256.complement⟩ + +private def powAux (a : UInt256) (c : UInt256) : ℕ → UInt256 + | 0 => a + | n@(k + 1) => if n % 2 == 1 + then powAux (a * c) (c * c) (n / 2) + else powAux a (c * c) (n / 2) + +def pow (b : UInt256) (n : UInt256) := powAux ⟨1⟩ b n.1 + +instance : HPow UInt256 UInt256 UInt256 := ⟨pow⟩ +instance : AndOp UInt256 := ⟨UInt256.land⟩ +instance : OrOp UInt256 := ⟨UInt256.lor⟩ +instance : HXor UInt256 UInt256 UInt256 := ⟨UInt256.xor⟩ +instance : ShiftLeft UInt256 := ⟨UInt256.shiftLeft⟩ +instance : ShiftRight UInt256 := ⟨UInt256.shiftRight⟩ + +instance : DecidableEq UInt256 := λ a b ↦ + match decEq a.val b.val with + | isTrue h => isTrue (congrArg UInt256.mk h) + | isFalse h => by + have neq : ¬ a = b := by + intro eq + have eq' : a.val = b.val := congrArg UInt256.val eq + contradiction + exact isFalse neq + +def decLt (a b : UInt256) : Decidable (a < b) := + match a, b with + | n, m => inferInstanceAs (Decidable (n < m)) + +def decLe (a b : UInt256) : Decidable (a ≤ b) := + match a, b with + | n, m => inferInstanceAs (Decidable (n <= m)) + +instance (a b : UInt256) : Decidable (a < b) := decLt _ _ +instance (a b : UInt256) : Decidable (a ≤ b) := UInt256.decLe a b +instance : Max UInt256 := maxOfLe +instance : Min UInt256 := minOfLe + +def eq0 (a : UInt256) : Bool := a == ⟨0⟩ + +def byteAt (a b : UInt256) : UInt256 := + if a > ⟨31⟩ then ⟨0⟩ else + b >>> (UInt256.ofNat ((31 - a.toNat) * 8)) &&& ⟨0xFF⟩ + +def sgn (a : UInt256) : ℤ := + if 2 ^ 255 <= a.toNat then + -1 + else + if eq0 a then 0 else 1 + +def bigUInt : UInt256 := ofNat 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff + +def sdiv (a b : UInt256) : UInt256 := + if 2 ^ 255 <= a.toNat then + if 2 ^ 255 <= b.toNat then + abs a / abs b + else ⟨(abs a / b).val * -1⟩ + else + if 2 ^ 255 <= b.toNat then + ⟨(a / abs b).val * -1⟩ + else a / b + +def smod (a b : UInt256) : UInt256 := + if b.toNat == 0 then ⟨0⟩ + else + toSigned <| sgn a * (abs a % abs b).toNat + +def sltBool (a b : UInt256) : Bool := + if a.toNat ≥ 2 ^ 255 then + if b.toNat ≥ 2 ^ 255 then + a < b + else true + else + if b.toNat ≥ 2 ^ 255 then false + else a < b + +def sgtBool (a b : UInt256) : Bool := + if a.toNat ≥ 2 ^ 255 then + if b.toNat ≥ 2 ^ 255 then + a > b + else false + else + if b.toNat ≥ 2 ^ 255 then true + else a > b + +abbrev fromBool := Bool.toUInt256 + +def slt (a b : UInt256) := + fromBool (sltBool a b) + +def sgt (a b : UInt256) := + fromBool (sgtBool a b) + +def sar (a b : UInt256) : UInt256 := + if sltBool b ⟨0⟩ + then UInt256.complement (UInt256.complement b >>> a) + else b >>> a + +private partial def dbg_toHex (n : Nat) : String := + if n < 16 + then hexDigitRepr n + else (dbg_toHex (n / 16)) ++ hexDigitRepr (n % 16) + +def signextend (a b : UInt256) : UInt256 := + if a.toNat ≤ 31 then + let test_bit := a * ⟨8⟩ + ⟨7⟩ + let sign_bit := ⟨1⟩ <<< test_bit + if b &&& sign_bit ≠ ⟨0⟩ then + b ||| (UInt256.size.toUInt256 - sign_bit) + else b &&& (sign_bit - ⟨1⟩) + else b + +def addMod (a b c : UInt256) : UInt256 := + -- "All intermediate calculations of this operation are **not** subject to the 2^256 modulo." + if eq0 c then ⟨0⟩ else + ofNat <| Nat.mod (a.val + b.val) c.toNat + +def mulMod (a b c : UInt256) : UInt256 := + -- "All intermediate calculations of this operation are **not** subject to the 2^256 modulo." + if eq0 c then ⟨0⟩ else + ofNat <| Nat.mod (a.val * b.val) c.toNat + +def exp (a b : UInt256) : UInt256 := pow a b + +def lt (a b : UInt256) := fromBool (a < b) + +def gt (a b : UInt256) := fromBool (a > b) + +def eq (a b : UInt256) := fromBool (a = b) + +def isZero (a : UInt256) := + fromBool (eq0 a) + +def clz (a : UInt256) : UInt256 := + if a == ⟨0⟩ then + ⟨256⟩ + else + .ofNat (255 - (UInt256.log2 a).toNat) + +end UInt256 + +-- | Convert from a list of little-endian bytes to a natural number. +def fromBytes' : List UInt8 → ℕ +| [] => 0 +| b :: bs => b.toFin.val + 2^8 * fromBytes' bs + +def fromBytesBigEndian : List UInt8 → ℕ := fromBytes' ∘ List.reverse +def fromByteArrayBigEndian (b : ByteArray) : ℕ := fromBytesBigEndian b.toList + +variable {bs : List UInt8} + {n : ℕ} + +-- | A bound for the natural number value of a list of bytes. +private lemma fromBytes'_le : fromBytes' bs < 2^(8 * bs.length) := by + induction bs with + | nil => unfold fromBytes'; simp + | cons b bs ih => + unfold fromBytes' + have h := b.toFin.isLt + simp only [List.length_cons, Nat.mul_succ, Nat.add_comm, Nat.pow_add] + have _ := + Nat.add_le_of_le_sub + (Nat.one_le_pow _ _ (by decide)) + (Nat.le_sub_one_of_lt ih) + linarith + +-- | The natural number value of a length 32 list of bytes is < 2^256. +private lemma fromBytes'_UInt256_le (h : bs.length = 32) : fromBytes' bs < 2^256 := by + have h' := @fromBytes'_le bs + rw [h] at h' + exact h' + +-- | Convert a natural number into a list of bytes. +private def toBytes' : ℕ → List UInt8 + | 0 => [] + | n@(.succ n') => + let byte : UInt8 := ⟨Nat.mod n UInt8.size, Nat.mod_lt _ (by linarith)⟩ + have : n / UInt8.size < n' + 1 := by + rename_i h + rw [h] + apply Nat.div_lt_self <;> simp + byte :: toBytes' (n / UInt8.size) + +def toBytesBigEndian : ℕ → List UInt8 := List.reverse ∘ toBytes' + +-- | If n < 2⁸ᵏ, then (toBytes' n).length ≤ k. +private lemma toBytes'_le {k : ℕ} (h : n < 2 ^ (8 * k)) : (toBytes' n).length ≤ k := by + induction k generalizing n with + | zero => + simp at h + rw [h] + simp [toBytes'] + | succ e ih => + match n with + | .zero => simp [toBytes'] + | .succ n => + unfold toBytes' + simp + apply ih (Nat.div_lt_of_lt_mul _) + rw [Nat.mul_succ, Nat.pow_add] at h + linarith + +-- | If n < 2²⁵⁶, then (toBytes' n).length ≤ 32. +private lemma toBytes'_UInt256_le (h : n < UInt256.size) : (toBytes' n).length ≤ 32 := toBytes'_le h + +-- | Zero-pad a list of bytes up to some length, adding the zeroes on the right. +private def zeroPadBytes (n : ℕ) (bs : List UInt8) : List UInt8 := + bs ++ (List.replicate (n - bs.length)) 0 + +-- | The length of a `zeroPadBytes` call is its first argument. +lemma zeroPadBytes_len (h : bs.length ≤ n) : (zeroPadBytes n bs).length = n := by + unfold zeroPadBytes + aesop + +-- | Appending a bunch of zeroes to a little-endian list of bytes doesn't change its value. +@[simp] +private lemma extend_bytes_zero : fromBytes' (bs ++ List.replicate n 0) = fromBytes' bs := by + induction bs with + | nil => + simp [fromBytes'] + induction n with + | zero => simp [List.replicate, fromBytes'] + | succ _ ih => simp [List.replicate, fromBytes']; norm_cast + | cons _ _ ih => simp [fromBytes', ih] + +-- | The ℕ value of a little-endian list of bytes is invariant under right zero-padding up to length 32. +@[simp] +private lemma fromBytes'_zeroPadBytes_32_eq : fromBytes' (zeroPadBytes 32 bs) = fromBytes' bs := extend_bytes_zero + +-- | Casting a natural number to a list of bytes and back is the identity. +@[simp] +private lemma fromBytes'_toBytes' {x : ℕ} : fromBytes' (toBytes' x) = x := by + match x with + | .zero => simp [toBytes', fromBytes'] + | .succ n => + unfold toBytes' fromBytes' + simp + have := Nat.div_lt_self (Nat.zero_lt_succ n) (by decide : 1 < UInt8.size) + rw [fromBytes'_toBytes'] + simp [UInt8.size, add_comm] + apply Nat.div_add_mod + +theorem fromBytesBigEndian_zeroPad_toBytesBigEndian + (value padding : Nat) : + fromBytesBigEndian + (List.replicate padding 0 ++ toBytesBigEndian value) = + value := by + unfold fromBytesBigEndian toBytesBigEndian + simp only [Function.comp_apply] + rw [List.reverse_append, List.reverse_replicate, + List.reverse_reverse] + rw [extend_bytes_zero] + exact fromBytes'_toBytes' + +private lemma fromBytes'_cons_mod (b : UInt8) (bs : List UInt8) : + fromBytes' (b :: bs) % UInt8.size = b.toFin.val := by + unfold fromBytes' + rw [show 2 ^ 8 = UInt8.size by native_decide] + rw [Nat.add_mul_mod_self_left] + exact Nat.mod_eq_of_lt b.toFin.isLt + +private lemma fromBytes'_cons_div (b : UInt8) (bs : List UInt8) : + fromBytes' (b :: bs) / UInt8.size = fromBytes' bs := by + unfold fromBytes' + rw [show 2 ^ 8 = UInt8.size by native_decide] + rw [Nat.add_mul_div_left _ _ (by decide : 0 < UInt8.size)] + rw [Nat.div_eq_of_lt b.toFin.isLt] + rw [zero_add] + cases bs <;> rfl + +private lemma fromBytes'_eq_of_length_eq + {xs ys : List UInt8} {n : ℕ} + (hxs : xs.length = n) (hys : ys.length = n) + (hEq : fromBytes' xs = fromBytes' ys) : + xs = ys := by + induction n generalizing xs ys with + | zero => + cases xs <;> cases ys <;> simp at hxs hys ⊢ + | succ n ih => + cases xs with + | nil => simp at hxs + | cons x xs => + cases ys with + | nil => simp at hys + | cons y ys => + simp at hxs hys + have hHeadNat : x.toFin.val = y.toFin.val := by + have hMod := congrArg (fun value => value % UInt8.size) hEq + simpa [fromBytes'_cons_mod] using hMod + have hHead : x = y := + UInt8.eq_of_toFin_eq (Fin.ext hHeadNat) + subst y + have hTailEq : fromBytes' xs = fromBytes' ys := by + have hDiv := congrArg (fun value => value / UInt8.size) hEq + simpa [fromBytes'_cons_div] using hDiv + have hTail : xs = ys := ih hxs hys hTailEq + subst ys + rfl + +theorem zeroPadBytes_toBytes'_fromBytes'_eq_of_length_eq_32 + {bs : List UInt8} (hLen : bs.length = 32) : + zeroPadBytes 32 (toBytes' (fromBytes' bs)) = bs := by + apply fromBytes'_eq_of_length_eq + · exact zeroPadBytes_len (toBytes'_UInt256_le (by + unfold UInt256.size + exact fromBytes'_UInt256_le hLen)) + · exact hLen + · rw [fromBytes'_zeroPadBytes_32_eq] + exact fromBytes'_toBytes' + +theorem toBytesBigEndian_length_le_of_UInt256 (value : UInt256) : + (toBytesBigEndian value.toNat).length ≤ 32 := by + unfold toBytesBigEndian + simp [UInt256.toNat] + exact toBytes'_UInt256_le value.val.isLt + +theorem zeroPadBytes_toBytesBigEndian_fromBytesBigEndian_eq_of_length_eq_32 + {bs : List UInt8} (hLen : bs.length = 32) : + List.replicate (32 - (toBytesBigEndian (fromBytesBigEndian bs)).length) + 0 ++ toBytesBigEndian (fromBytesBigEndian bs) = + bs := by + have hLittle := + zeroPadBytes_toBytes'_fromBytes'_eq_of_length_eq_32 + (bs := bs.reverse) (by simpa [List.length_reverse] using hLen) + have hRev := congrArg List.reverse hLittle + simpa [toBytesBigEndian, fromBytesBigEndian, zeroPadBytes, + List.reverse_append, List.length_reverse] using hRev + +def fromBytes! (bs : List UInt8) : ℕ := fromBytes' (bs.take 32) + +private lemma fromBytes_was_good_all_year_long + (h : bs.length ≤ 32) : fromBytes' bs < 2^256 := by + have h' := @fromBytes'_le bs + rw [pow_mul] at h' + refine lt_of_lt_of_le (b := (2 ^ 8) ^ List.length bs) h' ?lenBs + case lenBs => rw [←pow_mul]; exact pow_le_pow_right₀ (by decide) (by linarith) + +@[simp] +lemma fromBytes_wasnt_naughty : fromBytes! bs < 2^256 := fromBytes_was_good_all_year_long (by simp) + +theorem fromBytesBigEndian_lt_UInt256_size_of_length_le_32 + {bs : List UInt8} (hLen : bs.length ≤ 32) : + fromBytesBigEndian bs < UInt256.size := by + unfold fromBytesBigEndian UInt256.size + exact fromBytes_was_good_all_year_long + (bs := bs.reverse) (by simpa [List.length_reverse] using hLen) + +theorem UInt256.toNat_ofNat_of_lt {n : Nat} (hLt : n < UInt256.size) : + (UInt256.ofNat n).toNat = n := by + unfold UInt256.ofNat UInt256.toNat + change (Fin.ofNat UInt256.size n).val = n + rw [Fin.val_ofNat] + exact Nat.mod_eq_of_lt hLt + +@[simp] theorem UInt256.ofNat_toNat (value : UInt256) : + UInt256.ofNat value.toNat = value := by + cases value with + | mk val => + unfold UInt256.ofNat UInt256.toNat + simp + rfl + +theorem UInt256.toNat_ofNat_fromBytesBigEndian_of_length_le_32 + {bs : List UInt8} (hLen : bs.length ≤ 32) : + (UInt256.ofNat (fromBytesBigEndian bs)).toNat = + fromBytesBigEndian bs := + UInt256.toNat_ofNat_of_lt + (fromBytesBigEndian_lt_UInt256_size_of_length_le_32 hLen) + +theorem zeroPadBytes_toBytesBigEndian_ofNat_fromBytesBigEndian_eq_of_length_eq_32 + {bs : List UInt8} (hLen : bs.length = 32) : + List.replicate + (32 - + (toBytesBigEndian + (UInt256.ofNat (fromBytesBigEndian bs)).toNat).length) + 0 ++ + toBytesBigEndian + (UInt256.ofNat (fromBytesBigEndian bs)).toNat = + bs := by + rw [UInt256.toNat_ofNat_fromBytesBigEndian_of_length_le_32 + (by omega : bs.length ≤ 32)] + exact zeroPadBytes_toBytesBigEndian_fromBytesBigEndian_eq_of_length_eq_32 + hLen + +-- Convenience function for spooning into UInt256. +-- Given that I 'accept' UInt8, might as well live with UInt256. +def fromBytes_if_you_really_must? (bs : List UInt8) : UInt256 := + ⟨fromBytes! bs, fromBytes_wasnt_naughty⟩ + +def toBytes! (n : UInt256) : List UInt8 := zeroPadBytes 32 (toBytes' n.1) + +def uInt256OfByteArray (arr : ByteArray) : UInt256 := + .ofNat <| fromBytes' arr.data.toList.reverse + +end EvmYul + +section HicSuntDracones + +def ByteArray.copySlice' (src : ByteArray) (srcOff : Nat) (dest : ByteArray) (destOff len : Nat) (exact : Bool := true) : ByteArray := + if false -- srcOff < 2^64 && destOff < 2^64 && len < 2^64 + then src.copySlice srcOff dest destOff len exact -- NB only when `srcOff`, `destOff` and `len` are sufficiently small + else let srcData := src.data + let destData := dest.data + let sourceChunk := srcData.extract srcOff (srcOff + len) + let destBegin := destData.extract 0 destOff + let destEnd := destData.extract (destOff + len) destData.size + ⟨destBegin ++ sourceChunk ++ destEnd⟩ + +end HicSuntDracones diff --git a/vendor/evmyul/EvmYul/Wheels.lean b/vendor/evmyul/EvmYul/Wheels.lean new file mode 100644 index 00000000..2a1a4758 --- /dev/null +++ b/vendor/evmyul/EvmYul/Wheels.lean @@ -0,0 +1,413 @@ +import EvmYul.UInt256 +import Mathlib.Data.Finmap +import EvmYul.FFI.ffi + +-- (195) +def BE : ℕ → ByteArray := List.toByteArray ∘ EvmYul.toBytesBigEndian + +namespace EvmYul + +def chainId : ℕ := 1 + +def UInt256.toByteArray (val : UInt256) : ByteArray := + let b := BE val.toNat + ffi.ByteArray.zeroes ⟨32 - b.size⟩ ++ b + +@[simp] theorem UInt256.size_toByteArray (value : UInt256) : + value.toByteArray.size = 32 := by + have hLen := + toBytesBigEndian_length_le_of_UInt256 value + unfold UInt256.toByteArray BE + simp only [Function.comp_apply, ByteArray.size_append, + ffi.ByteArray.size_zeroes, List.size_toByteArray] + change + ((32 : BitVec System.Platform.numBits) - + (toBytesBigEndian value.toNat).length).toNat + + (toBytesBigEndian value.toNat).length = + 32 + have hPow : 32 < 2 ^ System.Platform.numBits := by + rcases System.Platform.numBits_eq with h | h <;> simp [h] + have h32 : + (32 : BitVec System.Platform.numBits).toNat = 32 := by + rcases System.Platform.numBits_eq with h | h <;> simp [h] + have hValue : + ((toBytesBigEndian value.toNat).length : + BitVec System.Platform.numBits).toNat = + (toBytesBigEndian value.toNat).length := by + rcases System.Platform.numBits_eq with h | h + · rw [h, BitVec.natCast_eq_ofNat, BitVec.toNat_ofNat, + Nat.mod_eq_of_lt] + omega + · rw [h, BitVec.natCast_eq_ofNat, BitVec.toNat_ofNat, + Nat.mod_eq_of_lt] + omega + rw [BitVec.toNat_sub_of_le] + · rw [h32, hValue] + omega + · rw [BitVec.le_def, h32, hValue] + exact hLen + +@[simp] theorem UInt256.fromByteArrayBigEndian_toByteArray + (value : UInt256) : + EvmYul.fromByteArrayBigEndian value.toByteArray = value.toNat := by + unfold UInt256.toByteArray EvmYul.fromByteArrayBigEndian BE + rw [ffi.ByteArray.toList_eq_data_toList] + simp [ffi.ByteArray.zeroes] + exact + EvmYul.fromBytesBigEndian_zeroPad_toBytesBigEndian + value.toNat _ + +abbrev Literal := UInt256 + +-- 2^160 https://www.wolframalpha.com/input?i=2%5E160 +def AccountAddress.size : Nat := 1461501637330902918203684832716283019655932542976 + +instance : NeZero AccountAddress.size where + out := (by unfold AccountAddress.size; simp) + +abbrev AccountAddress : Type := Fin AccountAddress.size + +instance : Ord AccountAddress where + compare a₁ a₂ := compare a₁.val a₂.val + +instance : Inhabited AccountAddress := ⟨Fin.ofNat _ 0⟩ + +namespace AccountAddress + +def ofNat (n : ℕ) : AccountAddress := Fin.ofNat _ n +def ofUInt256 (v : UInt256) : AccountAddress := Fin.ofNat _ (v.val % AccountAddress.size) +instance {n : Nat} : OfNat AccountAddress n := ⟨Fin.ofNat _ n⟩ + +def toByteArray (a : AccountAddress) : ByteArray := + let b := BE a + ffi.ByteArray.zeroes ⟨20 - b.size⟩ ++ b + +end AccountAddress + +def hexOfByte (byte : UInt8) : String := + hexDigitRepr (byte.toNat >>> 4 &&& 0b00001111) ++ + hexDigitRepr (byte.toNat &&& 0b00001111) + +def toHex (bytes : ByteArray) : String := + bytes.foldl (init := "") λ acc byte ↦ acc ++ hexOfByte byte + +instance : Repr ByteArray where + reprPrec s _ := toHex s + +def Identifier := String +instance : ToString Identifier := inferInstanceAs (ToString String) +instance : Inhabited Identifier := inferInstanceAs (Inhabited String) +instance : DecidableEq Identifier := inferInstanceAs (DecidableEq String) +instance : Repr Identifier := inferInstanceAs (Repr String) + +namespace NaryNotation + +scoped syntax "!nary[" ident "^" num "]" : term + +open Lean in +scoped macro_rules + | `(!nary[ $idn:ident ^ $nat:num ]) => + let rec go (n : ℕ) : MacroM Term := + match n with + | 0 => `($idn) + | n + 1 => do `($idn → $(←go n)) + go nat.getNat + +end NaryNotation + +namespace Primop + +section + +open NaryNotation + +def Nullary := !nary[UInt256 ^ 0] +def Unary := !nary[UInt256 ^ 1] +def Binary := !nary[UInt256 ^ 2] +def Ternary := !nary[UInt256 ^ 3] +def Quaternary := !nary[UInt256 ^ 4] + +end + +end Primop + +end EvmYul + +/-- +TODO(rework later to a sane version) +-/ +instance : DecidableEq ByteArray := by + rintro ⟨a⟩ ⟨b⟩ + rw [ByteArray.mk.injEq] + apply decEq + +def Option.option {α β : Type} (dflt : β) (f : α -> β) : Option α → β + | .none => dflt + | .some x => f x + +def Option.toExceptWith {α β : Type} (dflt : β) (x : Option α) : Except β α := + x.option (.error dflt) Except.ok + +def ByteArray.get? (self : ByteArray) (n : Nat) : Option UInt8 := + if h : n < self.size + then self.get n h + else .none + +partial def Nat.toHex (n : Nat) : String := + if n < 16 + then hexDigitRepr n + else (toHex (n / 16)) ++ hexDigitRepr (n % 16) + +def hexOfByte (byte : UInt8) : String := + hexDigitRepr (byte.toNat >>> 4 &&& 0b00001111) ++ + hexDigitRepr (byte.toNat &&& 0b00001111) + +def toHex (bytes : ByteArray) : String := + bytes.foldl (init := "") λ acc byte ↦ acc ++ hexOfByte byte + +/-- Add `0`s to make the hex representation valid for `ByteArray.ofBlob` -/ +def padLeft (n : ℕ) (s : String) := + let l := s.length + if l < n then String.replicate (n - l) '0' ++ s else s + +/-- +TODO - Well this is ever so slightly unfortunate. +It appears to be the case that some (all?) definitions that have C++ implementations +use 64bit-width integers to hold numeric arguments. + +When this assumption is broken, e.g. `n : Nat := 2^64`, the Lean (4.9.0) gives +inernal out of memory error. + +This implementation works around the issue at the price of using a slower implementation +in case either of the arguments is too big. +-/ +def ByteArray.extract' (a : ByteArray) (b e : Nat) : ByteArray := + -- TODO: Shouldn't (`e` - `b`) be < `2^64` instead of `e` since eventually `a.copySlice b empty 0 (e - b)` is called? + if b < 2^64 && e < 2^64 + then a.extract b e -- NB only when `b` and `e` are sufficiently small + else ⟨⟨a.toList.drop b |>.take (e - b)⟩⟩ + +def HexPrefix := "0x" + +def TargetSchedule := "Cancun" + +def isHexDigitChar (c : Char) : Bool := + '0' <= c && c <= '9' || 'a' <= c.toLower && c.toLower <= 'f' + +def cToHex? (c : Char) : Except String Nat := + if '0' ≤ c ∧ c ≤ '9' + then .ok <| c.toString.toNat! + else if 'a' ≤ c.toLower ∧ c.toLower ≤ 'f' + then let Δ := c.toLower.toNat - 'a'.toNat + .ok <| 10 + Δ + else .error s!"Not a hex digit: {c}" + +def ofHex? : List Char → Except String UInt8 + | [] => pure 0 + | [msb, lsb] => do pure ∘ UInt8.ofNat <| (← cToHex? msb) * 16 + (← cToHex? lsb) + | _ => throw "Need two hex digits for every byte." + +def Blob := String + +instance : Inhabited Blob := inferInstanceAs (Inhabited String) + +def Blob.toString : Blob → String := λ blob ↦ blob + +instance : ToString Blob := ⟨Blob.toString⟩ + +def getBlob? (s : String) : Except String Blob := + if isHex s then + let rest := s.drop HexPrefix.length + if rest.any (not ∘ isHexDigitChar) + then .error "Blobs must consist of valid hex digits." + else .ok rest.toString.toLower + else .error "Input does not begin with 0x." + where + isHex (s : String) := s.startsWith HexPrefix + +def getBlob! (s : String) : Blob := getBlob? s |>.toOption.get! + +def ByteArray.ofBlob (self : Blob) : Except String ByteArray := do + let chunks ← self.toList.toChunks 2 |>.mapM ofHex? + pure ⟨chunks.toArray⟩ + +def ByteArray.readBytes (source : ByteArray) (start size : ℕ) : ByteArray := + let read := + if start < 2^64 && size < 2^64 then + source.copySlice start empty 0 size + else + ⟨⟨source.toList.drop start |>.take size⟩⟩ + read ++ ffi.ByteArray.zeroes ⟨size - read.size⟩ + +def ByteArray.readWithoutPadding (source : ByteArray) (addr len : ℕ) : ByteArray := + if addr ≥ source.size then .empty else + let len := min len source.size + source.extract addr (addr + len) + +private def inf := 2^66 + +def ByteArray.readWithPadding (source : ByteArray) (addr len : ℕ) : ByteArray := + if len ≥ 2^64 then + panic! s!"ByteArray.readWithPadding: can not handle byte arrays of length {len}" + else + let read := source.readWithoutPadding addr len + read ++ ffi.ByteArray.zeroes ⟨len - read.size⟩ + +inductive 𝕋 where + | 𝔹 : ByteArray → 𝕋 + | 𝕃 : (List 𝕋) → 𝕋 + deriving Repr, BEq + + +def lengthRLP (rlp : ByteArray) : Option ℕ := + let len := rlp.size + if len = 0 then + none + else + let rlp₀ := rlp.get! 0 + if rlp₀ ≤ 0x7f then + some 1 + else + let strLen := rlp₀.toNat - 0x80 + if rlp₀ ≤ 0xb7 ∧ len > strLen then + some (1 + strLen) + else + let lenOfStrLen := rlp₀.toNat - 0xb7 + if rlp₀ ≤ 0xbf ∧ len > lenOfStrLen + strLen then + let strLen := + EvmYul.fromByteArrayBigEndian + (rlp.readWithoutPadding 1 lenOfStrLen) + some (1 + lenOfStrLen + strLen) + else + let listLen := rlp₀.toNat - 0xc0 + if rlp₀ ≤ 0xf7 ∧ len > listLen then do + some (1 + listLen) + else + let lenOfListLen := rlp₀.toNat - 0xf7 + let listLen := + EvmYul.fromByteArrayBigEndian + (rlp.readWithoutPadding 1 lenOfListLen) + if len > lenOfListLen + listLen then do + some (1 + lenOfListLen + listLen) + else + none + +partial def separateListRLP (rlp : ByteArray) : Option (List ByteArray) := do + if rlp.isEmpty then pure [] + else + let headLen ← lengthRLP rlp + let head := rlp.readWithoutPadding 0 headLen + let tail ← separateListRLP (rlp.readWithoutPadding headLen rlp.size) + pure <| head :: tail + +def oneStepRLP (rlp : ByteArray) : Option (Sum ByteArray (List ByteArray)) := + let len := rlp.size + if len = 0 then + none + else + let rlp₀ := rlp.get! 0 + if rlp₀ ≤ 0x7f then + let data := .inl ⟨#[rlp₀]⟩ + some data + else + let strLen := rlp₀.toNat - 0x80 + if rlp₀ ≤ 0xb7 ∧ len > strLen then + let data := .inl (rlp.readWithoutPadding 1 strLen) + some data + else + let lenOfStrLen := rlp₀.toNat - 0xb7 + if rlp₀ ≤ 0xbf ∧ len > lenOfStrLen + strLen then + let strLen := + EvmYul.fromByteArrayBigEndian + (rlp.readWithoutPadding 1 lenOfStrLen) + let data := .inl (rlp.readWithoutPadding (1 + lenOfStrLen) strLen) + some data + else + let listLen := rlp₀.toNat - 0xc0 + if rlp₀ ≤ 0xf7 ∧ len > listLen then do + let list ← separateListRLP (rlp.readWithoutPadding 1 listLen) + some <| .inr list + else + let lenOfListLen := rlp₀.toNat - 0xf7 + let listLen := + EvmYul.fromByteArrayBigEndian + (rlp.readWithoutPadding 1 lenOfListLen) + if len > lenOfListLen + listLen then do + let list ← separateListRLP (rlp.readWithoutPadding (1 + lenOfListLen) listLen) + some <| .inr list + else + none + +partial def deserializeRLP (rlp : ByteArray) : Option 𝕋 := do + match ← oneStepRLP rlp with + | .inl byteArray => + some (.𝔹 byteArray) + | .inr list => + let l ← list.mapM deserializeRLP + some (.𝕃 l) + +private def R_b (x : ByteArray) : Option ByteArray := + if x.size = 1 ∧ x.get! 0 < 128 then some x + else + if x.size < 56 then some <| [⟨128 + x.size⟩].toByteArray ++ x + else + if x.size < 2^64 then + let be := BE x.size + some <| [⟨183 + be.size⟩].toByteArray ++ be ++ x + else none + +mutual + +private def s (l : List 𝕋) : Option ByteArray := + match l with + | [] => some .empty + | t :: ts => + match RLP t, s ts with + | none , _ => none + | _ , none => none + | some rlpₗ, some rlpᵣ => rlpₗ ++ rlpᵣ + +def R_l (l : List 𝕋) : Option ByteArray := + match s l with + | none => none + | some s_x => + if s_x.size < 56 then + some <| [⟨192 + s_x.size⟩].toByteArray ++ s_x + else + if s_x.size < 2^64 then + let be := BE s_x.size + some <| [⟨247 + be.size⟩].toByteArray ++ be ++ s_x + else none + +def RLP (t : 𝕋) : Option ByteArray := + match t with + | .𝔹 ba => R_b ba + | .𝕃 l => R_l l + +end + +def myByteArray : ByteArray := ⟨#[1, 2, 3]⟩ + +def ByteArray.write + (source : ByteArray) + (sourceAddr : ℕ) + (dest : ByteArray) + (destAddr len : ℕ) + : ByteArray +:= + if len = 0 then dest else + if sourceAddr ≥ source.size then + let len := min len (dest.size - destAddr) + let destAddr := min destAddr dest.size + (ffi.ByteArray.zeroes ⟨len⟩).copySlice 0 dest destAddr len + else + let practicalLen := min len (source.size - sourceAddr) + let endPaddingAddr := min dest.size (destAddr + len) + let sourcePaddingLength : ℕ := endPaddingAddr - (destAddr + practicalLen) + let sourcePadding := ffi.ByteArray.zeroes ⟨sourcePaddingLength⟩ + let destPaddingLength : ℕ := destAddr - dest.size + let destPadding := ffi.ByteArray.zeroes ⟨destPaddingLength⟩ + (source ++ sourcePadding).copySlice sourceAddr + (dest ++ destPadding) + destAddr + (practicalLen + sourcePaddingLength) diff --git a/vendor/evmyul/EvmYul/Yul/Ast.lean b/vendor/evmyul/EvmYul/Yul/Ast.lean new file mode 100644 index 00000000..99be310a --- /dev/null +++ b/vendor/evmyul/EvmYul/Yul/Ast.lean @@ -0,0 +1,113 @@ +/- Yul specification: +https://docs.soliditylang.org/en/v0.8.9/yul.html +-/ + +import EvmYul.UInt256 +import EvmYul.Operations +import EvmYul.Wheels + +namespace EvmYul + +namespace Yul + +namespace Ast + +open EvmYul UInt256 + +abbrev Literal := UInt256 +-- def Identifier := String + +instance : ToString Identifier := inferInstanceAs (ToString String) + +instance : Inhabited Identifier := ⟨""⟩ +instance : DecidableEq Identifier := String.decEq + +abbrev PrimOp := Operation .Yul + +def stringOfPrimOp : PrimOp → String := toString ∘ repr + +instance : ToString PrimOp := ⟨stringOfPrimOp⟩ + +-- https://docs.soliditylang.org/en/latest/yul.html#informal-description-of-yul + +abbrev YulFunctionName := String + +mutual + inductive FunctionDefinition where + | Def : List Identifier → List Identifier → List Stmt → FunctionDefinition + deriving BEq, Inhabited + + inductive Expr where + | Call : (PrimOp ⊕ YulFunctionName) → List Expr → Expr + | Var : Identifier → Expr + | Lit : Literal → Expr + + -- | The loop constructor 'Stmt.For' has no initialiser because of + -- https://docs.soliditylang.org/en/latest/internals/optimizer.html#forloopinitrewriter + inductive Stmt where + | Block : List Stmt → Stmt + | Let : List Identifier → Option Expr → Stmt + | Assign : List Identifier → Expr → Stmt + | ExprStmtCall : Expr → Stmt + | Switch : Expr → List (Literal × List Stmt) → List Stmt → Stmt + | For : Expr → List Stmt → List Stmt → Stmt + | If : Expr → List Stmt → Stmt + | Continue : Stmt + | Break : Stmt + | Leave : Stmt + deriving BEq, Inhabited, Repr +end + +structure YulContract where + dispatcher : Yul.Ast.Stmt + functions : Finmap (fun (_ : YulFunctionName) ↦ Yul.Ast.FunctionDefinition) + deriving Inhabited + +instance : Repr YulContract where + reprPrec _ _ := "YulContract" -- TODO: implement an actual `reprPrec` for YulContract + +instance : BEq YulContract where + beq a b := + a.dispatcher == b.dispatcher + && (a.functions.keys == b.functions.keys && + a.functions.all (λ k _ => a.functions.lookup k == b.functions.lookup k)) + +abbrev contractCode (τ : OperationType) := + match τ with + | OperationType.EVM => ByteArray + | OperationType.Yul => YulContract + +instance {τ} : BEq (contractCode τ) where + beq a b := match τ with + | .EVM => a == b + | .Yul => a == b + +instance {τ} : Inhabited (contractCode τ) where + default := match τ with + | .EVM => default + | .Yul => default + +instance {τ} : Repr (contractCode τ) where + reprPrec a _ := match τ with + | .EVM => reprPrec a 0 + | .Yul => reprPrec a 0 + + +namespace FunctionDefinition + +def params : FunctionDefinition → List Identifier + | Def params _ _ => params + +def rets : FunctionDefinition → List Identifier + | Def _ rets _ => rets + +def body : FunctionDefinition → List Stmt + | Def _ _ body => body + +end FunctionDefinition + +end Ast + +end Yul + +end EvmYul diff --git a/vendor/evmyul/lakefile.lean b/vendor/evmyul/lakefile.lean new file mode 100644 index 00000000..2faae7df --- /dev/null +++ b/vendor/evmyul/lakefile.lean @@ -0,0 +1,73 @@ +import Lake +open Lake DSL System + +require "leanprover-community" / "mathlib" @ git "v4.35.0" + +package «evmyul» { + moreLeanArgs := #["-DautoImplicit=false"] + moreServerOptions := #[⟨`autoImplicit, false⟩] +} + +def cloneWithCache (pkg : NPackage __name__) (dirname url rev : String) : FetchM (Job GitRepo) := do + let repoDir : GitRepo := ⟨pkg.dir / dirname⟩ + if !(← repoDir.dir.pathExists) then + dbg_trace s!"Cloning: {url}" + GitRepo.clone url repoDir + repoDir.checkoutDetach rev + return pure repoDir + +target cloneSha2 pkg : GitRepo := + cloneWithCache pkg "sha2" "https://github.com/amosnier/sha-2.git" + "565f65009bdd98267361b17d50cddd7c9beb3e6c" + +target cloneKeccak256 pkg : GitRepo := + cloneWithCache pkg "keccak256" "https://github.com/brainhub/SHA3IUF.git" + "fc8504750a5c2174a1874094dd05e6a0d8797753" + +def hash256CDir (hash256repo : GitRepo) : FilePath := + hash256repo.dir + +abbrev compiler := "cc" + +target ffi.o pkg : FilePath := do + let sha2 ← (←cloneSha2.fetch).await + let keccak256 ← (←cloneKeccak256.fetch).await + let oFile := pkg.buildDir / "ffi.o" + let srcJob ← inputTextFile <| pkg.dir / "EvmYul" / "FFI" / "ffi.c" + let weakArgs := #[ + "-I", (← getLeanIncludeDir).toString, + "-I", sha2.dir.toString, + "-I", keccak256.dir.toString + ] + buildO oFile srcJob weakArgs #["-fPIC"] compiler getLeanTrace + +def buildFFILib (pkg : Package) (repo : GitRepo) (fileName : String) : FetchM (Job FilePath) := do + let srcJob ← inputTextFile $ repo.dir / fileName |>.addExtension "c" + let oFile := pkg.buildDir / fileName |>.addExtension "o" + let includeArgs := #["-I", repo.dir.toString] + let weakArgs := includeArgs + buildO oFile srcJob weakArgs #["-fPIC"] compiler getLeanTrace + +def buildSha256Obj (pkg : Package) (fileName : String) := do + buildFFILib pkg (← (←cloneSha2.fetch).await).1 fileName + +def buildKeccak256Obj (pkg : Package) (fileName : String) := do + buildFFILib pkg (← (←cloneKeccak256.fetch).await).1 fileName + +extern_lib libleanffi pkg := do + -- In the static lib we include: + -- the `sha-256` library itself + let sha256O ← buildSha256Obj pkg "sha-256" + let keccak256 ← buildKeccak256Obj pkg "sha3" + -- our own `ffi.c` + let ffiO ← ffi.o.fetch + + let name := nameToStaticLib "leanffi" + buildStaticLib (pkg.staticLibDir / name) #[sha256O, keccak256, ffiO] + +lean_lib «Conform» where + roots := #[`Conform.Wheels] + +@[default_target] +lean_lib «EvmYul» where + globs := #[.submodules `EvmYul] diff --git a/vendor/evmyul/license.txt b/vendor/evmyul/license.txt new file mode 100644 index 00000000..8d70572c --- /dev/null +++ b/vendor/evmyul/license.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 Demerzel Solutions Limited (t/a Nethermind) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License.